code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# CS224N Assignment 1: Exploring Word Vectors (25 Points) Welcome to CS224n! Before you start, make sure you read the README.txt in the same directory as this notebook. ``` source activate myenv # All Import Statements Defined Here # Note: Do not add to this list. # All the dependencies you need, can be installed by running . # ---------------- import sys assert sys.version_info[0]==3 assert sys.version_info[1] >= 5 from gensim.models import KeyedVectors from gensim.test.utils import datapath import pprint import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [10, 5] import nltk nltk.download('reuters') from nltk.corpus import reuters import numpy as np import random import scipy as sp from sklearn.decomposition import TruncatedSVD from sklearn.decomposition import PCA START_TOKEN = '<START>' END_TOKEN = '<END>' np.random.seed(0) random.seed(0) # ---------------- ``` ## Please Write Your SUNet ID Here: ## Word Vectors Word Vectors are often used as a fundamental component for downstream NLP tasks, e.g. question answering, text generation, translation, etc., so it is important to build some intuitions as to their strengths and weaknesses. Here, you will explore two types of word vectors: those derived from *co-occurrence matrices*, and those derived via *word2vec*. **Assignment Notes:** Please make sure to save the notebook as you go along. Submission Instructions are located at the bottom of the notebook. **Note on Terminology:** The terms "word vectors" and "word embeddings" are often used interchangeably. The term "embedding" refers to the fact that we are encoding aspects of a word's meaning in a lower dimensional space. As [Wikipedia](https://en.wikipedia.org/wiki/Word_embedding) states, "*conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension*". ## Part 1: Count-Based Word Vectors (10 points) Most word vector models start from the following idea: *You shall know a word by the company it keeps ([Firth, J. R. 1957:11](https://en.wikipedia.org/wiki/John_Rupert_Firth))* Many word vector implementations are driven by the idea that similar words, i.e., (near) synonyms, will be used in similar contexts. As a result, similar words will often be spoken or written along with a shared subset of words, i.e., contexts. By examining these contexts, we can try to develop embeddings for our words. With this intuition in mind, many "old school" approaches to constructing word vectors relied on word counts. Here we elaborate upon one of those strategies, *co-occurrence matrices* (for more information, see [here](http://web.stanford.edu/class/cs124/lec/vectorsemantics.video.pdf) or [here](https://medium.com/data-science-group-iitr/word-embedding-2d05d270b285)). ### Co-Occurrence A co-occurrence matrix counts how often things co-occur in some environment. Given some word $w_i$ occurring in the document, we consider the *context window* surrounding $w_i$. Supposing our fixed window size is $n$, then this is the $n$ preceding and $n$ subsequent words in that document, i.e. words $w_{i-n} \dots w_{i-1}$ and $w_{i+1} \dots w_{i+n}$. We build a *co-occurrence matrix* $M$, which is a symmetric word-by-word matrix in which $M_{ij}$ is the number of times $w_j$ appears inside $w_i$'s window. **Example: Co-Occurrence with Fixed Window of n=1**: Document 1: "all that glitters is not gold" Document 2: "all is well that ends well" | * | START | all | that | glitters | is | not | gold | well | ends | END | |----------|-------|-----|------|----------|------|------|-------|------|------|-----| | START | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | all | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | | that | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | | glitters | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | | is | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | | not | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | | gold | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | | well | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | | ends | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | | END | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | **Note:** In NLP, we often add START and END tokens to represent the beginning and end of sentences, paragraphs or documents. In thise case we imagine START and END tokens encapsulating each document, e.g., "START All that glitters is not gold END", and include these tokens in our co-occurrence counts. The rows (or columns) of this matrix provide one type of word vectors (those based on word-word co-occurrence), but the vectors will be large in general (linear in the number of distinct words in a corpus). Thus, our next step is to run *dimensionality reduction*. In particular, we will run *SVD (Singular Value Decomposition)*, which is a kind of generalized *PCA (Principal Components Analysis)* to select the top $k$ principal components. Here's a visualization of dimensionality reduction with SVD. In this picture our co-occurrence matrix is $A$ with $n$ rows corresponding to $n$ words. We obtain a full matrix decomposition, with the singular values ordered in the diagonal $S$ matrix, and our new, shorter length-$k$ word vectors in $U_k$. ![Picture of an SVD](imgs/svd.png "SVD") This reduced-dimensionality co-occurrence representation preserves semantic relationships between words, e.g. *doctor* and *hospital* will be closer than *doctor* and *dog*. **Notes:** If you can barely remember what an eigenvalue is, here's [a slow, friendly introduction to SVD](https://davetang.org/file/Singular_Value_Decomposition_Tutorial.pdf). If you want to learn more thoroughly about PCA or SVD, feel free to check out lectures [7](https://web.stanford.edu/class/cs168/l/l7.pdf), [8](http://theory.stanford.edu/~tim/s15/l/l8.pdf), and [9](https://web.stanford.edu/class/cs168/l/l9.pdf) of CS168. These course notes provide a great high-level treatment of these general purpose algorithms. Though, for the purpose of this class, you only need to know how to extract the k-dimensional embeddings by utilizing pre-programmed implementations of these algorithms from the numpy, scipy, or sklearn python packages. In practice, it is challenging to apply full SVD to large corpora because of the memory needed to perform PCA or SVD. However, if you only want the top $k$ vector components for relatively small $k$ — known as *[Truncated SVD](https://en.wikipedia.org/wiki/Singular_value_decomposition#Truncated_SVD)* — then there are reasonably scalable techniques to compute those iteratively. ### Plotting Co-Occurrence Word Embeddings Here, we will be using the Reuters (business and financial news) corpus. If you haven't run the import cell at the top of this page, please run it now (click it and press SHIFT-RETURN). The corpus consists of 10,788 news documents totaling 1.3 million words. These documents span 90 categories and are split into train and test. For more details, please see https://www.nltk.org/book/ch02.html. We provide a `read_corpus` function below that pulls out only articles from the "crude" (i.e. news articles about oil, gas, etc.) category. The function also adds START and END tokens to each of the documents, and lowercases words. You do **not** have perform any other kind of pre-processing. ``` def read_corpus(category="crude"): """ Read files from the specified Reuter's category. Params: category (string): category name Return: list of lists, with words from each of the processed files """ files = reuters.fileids(category) return [[START_TOKEN] + [w.lower() for w in list(reuters.words(f))] + [END_TOKEN] for f in files] ``` Let's have a look what these documents are like…. ``` reuters_corpus = read_corpus() pprint.pprint(reuters_corpus[:3], compact=True, width=100) ``` ### Question 1.1: Implement `distinct_words` [code] (2 points) Write a method to work out the distinct words (word types) that occur in the corpus. You can do this with `for` loops, but it's more efficient to do it with Python list comprehensions. In particular, [this](https://coderwall.com/p/rcmaea/flatten-a-list-of-lists-in-one-line-in-python) may be useful to flatten a list of lists. If you're not familiar with Python list comprehensions in general, here's [more information](https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html). You may find it useful to use [Python sets](https://www.w3schools.com/python/python_sets.asp) to remove duplicate words. ``` def distinct_words(corpus): """ Determine a list of distinct words for the corpus. Params: corpus (list of list of strings): corpus of documents Return: corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function) num_corpus_words (integer): number of distinct words across the corpus """ corpus_words = [] num_corpus_words = -1 # ------------------ # Write your implementation here. # ------------------ return corpus_words, num_corpus_words # --------------------- # Run this sanity check # Note that this not an exhaustive check for correctness. # --------------------- # Define toy corpus test_corpus = ["START All that glitters isn't gold END".split(" "), "START All's well that ends well END".split(" ")] test_corpus_words, num_corpus_words = distinct_words(test_corpus) # Correct answers ans_test_corpus_words = sorted(list(set(["START", "All", "ends", "that", "gold", "All's", "glitters", "isn't", "well", "END"]))) ans_num_corpus_words = len(ans_test_corpus_words) # Test correct number of words assert(num_corpus_words == ans_num_corpus_words), "Incorrect number of distinct words. Correct: {}. Yours: {}".format(ans_num_corpus_words, num_corpus_words) # Test correct words assert (test_corpus_words == ans_test_corpus_words), "Incorrect corpus_words.\nCorrect: {}\nYours: {}".format(str(ans_test_corpus_words), str(test_corpus_words)) # Print Success print ("-" * 80) print("Passed All Tests!") print ("-" * 80) ``` ### Question 1.2: Implement `compute_co_occurrence_matrix` [code] (3 points) Write a method that constructs a co-occurrence matrix for a certain window-size $n$ (with a default of 4), considering words $n$ before and $n$ after the word in the center of the window. Here, we start to use `numpy (np)` to represent vectors, matrices, and tensors. If you're not familiar with NumPy, there's a NumPy tutorial in the second half of this cs231n [Python NumPy tutorial](http://cs231n.github.io/python-numpy-tutorial/). ``` def compute_co_occurrence_matrix(corpus, window_size=4): """ Compute co-occurrence matrix for the given corpus and window_size (default of 4). Note: Each word in a document should be at the center of a window. Words near edges will have a smaller number of co-occurring words. For example, if we take the document "START All that glitters is not gold END" with window size of 4, "All" will co-occur with "START", "that", "glitters", "is", and "not". Params: corpus (list of list of strings): corpus of documents window_size (int): size of context window Return: M (numpy matrix of shape (number of corpus words, number of corpus words)): Co-occurence matrix of word counts. The ordering of the words in the rows/columns should be the same as the ordering of the words given by the distinct_words function. word2Ind (dict): dictionary that maps word to index (i.e. row/column number) for matrix M. """ words, num_words = distinct_words(corpus) M = None word2Ind = {} # ------------------ # Write your implementation here. # ------------------ return M, word2Ind # --------------------- # Run this sanity check # Note that this is not an exhaustive check for correctness. # --------------------- # Define toy corpus and get student's co-occurrence matrix test_corpus = ["START All that glitters isn't gold END".split(" "), "START All's well that ends well END".split(" ")] M_test, word2Ind_test = compute_co_occurrence_matrix(test_corpus, window_size=1) # Correct M and word2Ind M_test_ans = np.array( [[0., 0., 0., 1., 0., 0., 0., 0., 1., 0.,], [0., 0., 0., 1., 0., 0., 0., 0., 0., 1.,], [0., 0., 0., 0., 0., 0., 1., 0., 0., 1.,], [1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,], [0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,], [0., 0., 0., 0., 0., 0., 0., 1., 1., 0.,], [0., 0., 1., 0., 0., 0., 0., 1., 0., 0.,], [0., 0., 0., 0., 0., 1., 1., 0., 0., 0.,], [1., 0., 0., 0., 1., 1., 0., 0., 0., 1.,], [0., 1., 1., 0., 1., 0., 0., 0., 1., 0.,]] ) word2Ind_ans = {'All': 0, "All's": 1, 'END': 2, 'START': 3, 'ends': 4, 'glitters': 5, 'gold': 6, "isn't": 7, 'that': 8, 'well': 9} # Test correct word2Ind assert (word2Ind_ans == word2Ind_test), "Your word2Ind is incorrect:\nCorrect: {}\nYours: {}".format(word2Ind_ans, word2Ind_test) # Test correct M shape assert (M_test.shape == M_test_ans.shape), "M matrix has incorrect shape.\nCorrect: {}\nYours: {}".format(M_test.shape, M_test_ans.shape) # Test correct M values for w1 in word2Ind_ans.keys(): idx1 = word2Ind_ans[w1] for w2 in word2Ind_ans.keys(): idx2 = word2Ind_ans[w2] student = M_test[idx1, idx2] correct = M_test_ans[idx1, idx2] if student != correct: print("Correct M:") print(M_test_ans) print("Your M: ") print(M_test) raise AssertionError("Incorrect count at index ({}, {})=({}, {}) in matrix M. Yours has {} but should have {}.".format(idx1, idx2, w1, w2, student, correct)) # Print Success print ("-" * 80) print("Passed All Tests!") print ("-" * 80) ``` ### Question 1.3: Implement `reduce_to_k_dim` [code] (1 point) Construct a method that performs dimensionality reduction on the matrix to produce k-dimensional embeddings. Use SVD to take the top k components and produce a new matrix of k-dimensional embeddings. **Note:** All of numpy, scipy, and scikit-learn (`sklearn`) provide *some* implementation of SVD, but only scipy and sklearn provide an implementation of Truncated SVD, and only sklearn provides an efficient randomized algorithm for calculating large-scale Truncated SVD. So please use [sklearn.decomposition.TruncatedSVD](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html). ``` def reduce_to_k_dim(M, k=2): """ Reduce a co-occurence count matrix of dimensionality (num_corpus_words, num_corpus_words) to a matrix of dimensionality (num_corpus_words, k) using the following SVD function from Scikit-Learn: - http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html Params: M (numpy matrix of shape (number of corpus words, number of corpus words)): co-occurence matrix of word counts k (int): embedding size of each word after dimension reduction Return: M_reduced (numpy matrix of shape (number of corpus words, k)): matrix of k-dimensioal word embeddings. In terms of the SVD from math class, this actually returns U * S """ n_iters = 10 # Use this parameter in your call to `TruncatedSVD` M_reduced = None print("Running Truncated SVD over %i words..." % (M.shape[0])) # ------------------ # Write your implementation here. # ------------------ print("Done.") return M_reduced # --------------------- # Run this sanity check # Note that this not an exhaustive check for correctness # In fact we only check that your M_reduced has the right dimensions. # --------------------- # Define toy corpus and run student code test_corpus = ["START All that glitters isn't gold END".split(" "), "START All's well that ends well END".split(" ")] M_test, word2Ind_test = compute_co_occurrence_matrix(test_corpus, window_size=1) M_test_reduced = reduce_to_k_dim(M_test, k=2) # Test proper dimensions assert (M_test_reduced.shape[0] == 10), "M_reduced has {} rows; should have {}".format(M_test_reduced.shape[0], 10) assert (M_test_reduced.shape[1] == 2), "M_reduced has {} columns; should have {}".format(M_test_reduced.shape[1], 2) # Print Success print ("-" * 80) print("Passed All Tests!") print ("-" * 80) ``` ### Question 1.4: Implement `plot_embeddings` [code] (1 point) Here you will write a function to plot a set of 2D vectors in 2D space. For graphs, we will use Matplotlib (`plt`). For this example, you may find it useful to adapt [this code](https://www.pythonmembers.club/2018/05/08/matplotlib-scatter-plot-annotate-set-text-at-label-each-point/). In the future, a good way to make a plot is to look at [the Matplotlib gallery](https://matplotlib.org/gallery/index.html), find a plot that looks somewhat like what you want, and adapt the code they give. ``` def plot_embeddings(M_reduced, word2Ind, words): """ Plot in a scatterplot the embeddings of the words specified in the list "words". NOTE: do not plot all the words listed in M_reduced / word2Ind. Include a label next to each point. Params: M_reduced (numpy matrix of shape (number of unique words in the corpus , k)): matrix of k-dimensioal word embeddings word2Ind (dict): dictionary that maps word to indices for matrix M words (list of strings): words whose embeddings we want to visualize """ # ------------------ # Write your implementation here. # ------------------ # --------------------- # Run this sanity check # Note that this not an exhaustive check for correctness. # The plot produced should look like the "test solution plot" depicted below. # --------------------- print ("-" * 80) print ("Outputted Plot:") M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]]) word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4} words = ['test1', 'test2', 'test3', 'test4', 'test5'] plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words) print ("-" * 80) ``` <font color=red>**Test Plot Solution**</font> <br> <img src="imgs/test_plot.png" width=40% style="float: left;"> </img> ### Question 1.5: Co-Occurrence Plot Analysis [written] (3 points) Now we will put together all the parts you have written! We will compute the co-occurrence matrix with fixed window of 4, over the Reuters "crude" corpus. Then we will use TruncatedSVD to compute 2-dimensional embeddings of each word. TruncatedSVD returns U\*S, so we normalize the returned vectors, so that all the vectors will appear around the unit circle (therefore closeness is directional closeness). **Note**: The line of code below that does the normalizing uses the NumPy concept of *broadcasting*. If you don't know about broadcasting, check out [Computation on Arrays: Broadcasting by Jake VanderPlas](https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html). Run the below cell to produce the plot. It'll probably take a few seconds to run. What clusters together in 2-dimensional embedding space? What doesn't cluster together that you might think should have? **Note:** "bpd" stands for "barrels per day" and is a commonly used abbreviation in crude oil topic articles. ``` # ----------------------------- # Run This Cell to Produce Your Plot # ------------------------------ reuters_corpus = read_corpus() M_co_occurrence, word2Ind_co_occurrence = compute_co_occurrence_matrix(reuters_corpus) M_reduced_co_occurrence = reduce_to_k_dim(M_co_occurrence, k=2) # Rescale (normalize) the rows to make them each of unit-length M_lengths = np.linalg.norm(M_reduced_co_occurrence, axis=1) M_normalized = M_reduced_co_occurrence / M_lengths[:, np.newaxis] # broadcasting words = ['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela'] plot_embeddings(M_normalized, word2Ind_co_occurrence, words) ``` #### <font color="red">Write your answer here.</font> ## Part 2: Prediction-Based Word Vectors (15 points) As discussed in class, more recently prediction-based word vectors have come into fashion, e.g. word2vec. Here, we shall explore the embeddings produced by word2vec. Please revisit the class notes and lecture slides for more details on the word2vec algorithm. If you're feeling adventurous, challenge yourself and try reading the [original paper](https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf). Then run the following cells to load the word2vec vectors into memory. **Note**: This might take several minutes. ``` def load_word2vec(): """ Load Word2Vec Vectors Return: wv_from_bin: All 3 million embeddings, each lengh 300 """ import gensim.downloader as api wv_from_bin = api.load("word2vec-google-news-300") vocab = list(wv_from_bin.vocab.keys()) print("Loaded vocab size %i" % len(vocab)) return wv_from_bin # ----------------------------------- # Run Cell to Load Word Vectors # Note: This may take several minutes # ----------------------------------- wv_from_bin = load_word2vec() ``` **Note: If you are receiving out of memory issues on your local machine, try closing other applications to free more memory on your device. You may want to try restarting your machine so that you can free up extra memory. Then immediately run the jupyter notebook and see if you can load the word vectors properly. If you still have problems with loading the embeddings onto your local machine after this, please follow the Piazza instructions, as how to run remotely on Stanford Farmshare machines.** ### Reducing dimensionality of Word2Vec Word Embeddings Let's directly compare the word2vec embeddings to those of the co-occurrence matrix. Run the following cells to: 1. Put the 3 million word2vec vectors into a matrix M 2. Run reduce_to_k_dim (your Truncated SVD function) to reduce the vectors from 300-dimensional to 2-dimensional. ``` def get_matrix_of_vectors(wv_from_bin, required_words=['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']): """ Put the word2vec vectors into a matrix M. Param: wv_from_bin: KeyedVectors object; the 3 million word2vec vectors loaded from file Return: M: numpy matrix shape (num words, 300) containing the vectors word2Ind: dictionary mapping each word to its row number in M """ import random words = list(wv_from_bin.vocab.keys()) print("Shuffling words ...") random.shuffle(words) words = words[:10000] print("Putting %i words into word2Ind and matrix M..." % len(words)) word2Ind = {} M = [] curInd = 0 for w in words: try: M.append(wv_from_bin.word_vec(w)) word2Ind[w] = curInd curInd += 1 except KeyError: continue for w in required_words: try: M.append(wv_from_bin.word_vec(w)) word2Ind[w] = curInd curInd += 1 except KeyError: continue M = np.stack(M) print("Done.") return M, word2Ind # ----------------------------------------------------------------- # Run Cell to Reduce 300-Dimensinal Word Embeddings to k Dimensions # Note: This may take several minutes # ----------------------------------------------------------------- M, word2Ind = get_matrix_of_vectors(wv_from_bin) M_reduced = reduce_to_k_dim(M, k=2) ``` ### Question 2.1: Word2Vec Plot Analysis [written] (4 points) Run the cell below to plot the 2D word2vec embeddings for `['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela']`. What clusters together in 2-dimensional embedding space? What doesn't cluster together that you might think should have? How is the plot different from the one generated earlier from the co-occurrence matrix? ``` words = ['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'venezuela'] plot_embeddings(M_reduced, word2Ind, words) ``` #### <font color="red">Write your answer here.</font> ### Cosine Similarity Now that we have word vectors, we need a way to quantify the similarity between individual words, according to these vectors. One such metric is cosine-similarity. We will be using this to find words that are "close" and "far" from one another. We can think of n-dimensional vectors as points in n-dimensional space. If we take this perspective L1 and L2 Distances help quantify the amount of space "we must travel" to get between these two points. Another approach is to examine the angle between two vectors. From trigonometry we know that: <img src="imgs/inner_product.png" width=20% style="float: center;"></img> Instead of computing the actual angle, we can leave the similarity in terms of $similarity = cos(\Theta)$. Formally the [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) $s$ between two vectors $p$ and $q$ is defined as: $$s = \frac{p \cdot q}{||p|| ||q||}, \textrm{ where } s \in [-1, 1] $$ ### Question 2.2: Polysemous Words (2 points) [code + written] Find a [polysemous](https://en.wikipedia.org/wiki/Polysemy) word (for example, "leaves" or "scoop") such that the top-10 most similar words (according to cosine similarity) contains related words from *both* meanings. For example, "leaves" has both "vanishes" and "stalks" in the top 10, and "scoop" has both "handed_waffle_cone" and "lowdown". You will probably need to try several polysemous words before you find one. Please state the polysemous word you discover and the multiple meanings that occur in the top 10. Why do you think many of the polysemous words you tried didn't work? **Note**: You should use the `wv_from_bin.most_similar(word)` function to get the top 10 similar words. This function ranks all other words in the vocabulary with respect to their cosine similarity to the given word. For further assistance please check the __[GenSim documentation](https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.FastTextKeyedVectors.most_similar)__. ``` # ------------------ # Write your polysemous word exploration code here. wv_from_bin.most_similar("") # ------------------ ``` #### <font color="red">Write your answer here.</font> ### Question 2.3: Synonyms & Antonyms (2 points) [code + written] When considering Cosine Similarity, it's often more convenient to think of Cosine Distance, which is simply 1 - Cosine Similarity. Find three words (w1,w2,w3) where w1 and w2 are synonyms and w1 and w3 are antonyms, but Cosine Distance(w1,w3) < Cosine Distance(w1,w2). For example, w1="happy" is closer to w3="sad" than to w2="cheerful". Once you have found your example, please give a possible explanation for why this counter-intuitive result may have happened. You should use the the `wv_from_bin.distance(w1, w2)` function here in order to compute the cosine distance between two words. Please see the __[GenSim documentation](https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.FastTextKeyedVectors.distance)__ for further assistance. ``` # ------------------ # Write your synonym & antonym exploration code here. w1 = "" w2 = "" w3 = "" w1_w2_dist = wv_from_bin.distance(w1, w2) w1_w3_dist = wv_from_bin.distance(w1, w3) print("Synonyms {}, {} have cosine distance: {}".format(w1, w2, w1_w2_dist)) print("Antonyms {}, {} have cosine distance: {}".format(w1, w3, w1_w3_dist)) # ------------------ ``` #### <font color="red">Write your answer here.</font> ### Solving Analogies with Word Vectors Word2Vec vectors have been shown to *sometimes* exhibit the ability to solve analogies. As an example, for the analogy "man : king :: woman : x", what is x? In the cell below, we show you how to use word vectors to find x. The `most_similar` function finds words that are most similar to the words in the `positive` list and most dissimilar from the words in the `negative` list. The answer to the analogy will be the word ranked most similar (largest numerical value). **Note:** Further Documentation on the `most_similar` function can be found within the __[GenSim documentation](https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.FastTextKeyedVectors.most_similar)__. ``` # Run this cell to answer the analogy -- man : king :: woman : x pprint.pprint(wv_from_bin.most_similar(positive=['woman', 'king'], negative=['man'])) ``` ### Question 2.4: Finding Analogies [code + written] (2 Points) Find an example of analogy that holds according to these vectors (i.e. the intended word is ranked top). In your solution please state the full analogy in the form x:y :: a:b. If you believe the analogy is complicated, explain why the analogy holds in one or two sentences. **Note**: You may have to try many analogies to find one that works! ``` # ------------------ # Write your analogy exploration code here. pprint.pprint(wv_from_bin.most_similar(positive=[], negative=[])) # ------------------ ``` #### <font color="red">Write your answer here.</font> ### Question 2.5: Incorrect Analogy [code + written] (1 point) Find an example of analogy that does *not* hold according to these vectors. In your solution, state the intended analogy in the form x:y :: a:b, and state the (incorrect) value of b according to the word vectors. ``` # ------------------ # Write your incorrect analogy exploration code here. pprint.pprint(wv_from_bin.most_similar(positive=[], negative=[])) # ------------------ ``` #### <font color="red">Write your answer here.</font> ### Question 2.6: Guided Analysis of Bias in Word Vectors [written] (1 point) It's important to be cognizant of the biases (gender, race, sexual orientation etc.) implicit to our word embeddings. Run the cell below, to examine (a) which terms are most similar to "woman" and "boss" and most dissimilar to "man", and (b) which terms are most similar to "man" and "boss" and most dissimilar to "woman". What do you find in the top 10? ``` # Run this cell # Here `positive` indicates the list of words to be similar to and `negative` indicates the list of words to be # most dissimilar from. pprint.pprint(wv_from_bin.most_similar(positive=['woman', 'boss'], negative=['man'])) print() pprint.pprint(wv_from_bin.most_similar(positive=['man', 'boss'], negative=['woman'])) ``` #### <font color="red">Write your answer here.</font> ### Question 2.7: Independent Analysis of Bias in Word Vectors [code + written] (2 points) Use the `most_similar` function to find another case where some bias is exhibited by the vectors. Please briefly explain the example of bias that you discover. ``` # ------------------ # Write your bias exploration code here. pprint.pprint(wv_from_bin.most_similar(positive=[], negative=[])) print() pprint.pprint(wv_from_bin.most_similar(positive=[,], negative=[])) # ------------------ ``` #### <font color="red">Write your answer here.</font> ### Question 2.8: Thinking About Bias [written] (1 point) What might be the cause of these biases in the word vectors? #### <font color="red">Write your answer here.</font> # <font color="blue"> Submission Instructions</font> 1. Click the Save button at the top of the Jupyter Notebook. 2. Please make sure to have entered your SUNET ID above. 3. Select Cell -> All Output -> Clear. This will clear all the outputs from all cells (but will keep the content of ll cells). 4. Select Cell -> Run All. This will run all the cells in order, and will take several minutes. 5. Once you've rerun everything, select File -> Download as -> PDF via LaTeX 6. Look at the PDF file and make sure all your solutions are there, displayed correctly. The PDF is the only thing your graders will see! 7. Submit your PDF on Gradescope.
github_jupyter
## Creating the Dataset ``` import numpy as np np.random.seed(42) x = np.random.rand(100, 1) y = 1 + 2 * x + .1 * np.random.randn(100, 1) # Shuffles the indices idx = np.arange(100) np.random.shuffle(idx) # Uses first 80 random indices for train train_idx = idx[:80] # Uses the remaining indices for validation val_idx = idx[80:] # Generates train and validation sets x_train, y_train = x[train_idx], y[train_idx] x_val, y_val = x[val_idx], y[val_idx] print(x_train.shape) ``` ### Formatting the Dataset for Pytorch ``` import torch import torch.optim as optim import torch.nn as nn device = 'cuda' if torch.cuda.is_available() else 'cpu' x_train_tensor = torch.from_numpy(x_train).float().to(device) y_train_tensor = torch.from_numpy(y_train).float().to(device) from model import LayerLinearRegression # Now we can create a model and send it at once to the device model = LayerLinearRegression().to(device) # We can also inspect its parameters using its state_dict print(model.state_dict()) lr = 1e-1 n_epochs = 1000 loss_fn = nn.MSELoss(reduction='mean') optimizer = optim.SGD(model.parameters(), lr=lr) for epoch in range(n_epochs): # What is this?!? model.train() # No more manual prediction! # yhat = a + b * x_tensor yhat = model(x_train_tensor) loss = loss_fn(y_train_tensor, yhat) loss.backward() optimizer.step() optimizer.zero_grad() print(model.state_dict()) # Testing the prediction a = np.array([1.5]) y = model(torch.as_tensor(a,dtype=torch.float32,device=device)) print(y) ``` ### Saving the Model ``` torch.save(model.state_dict(),'model.pth') import os import sagemaker import tarfile print(os.getcwd()) # files = [f for f in os.listdir('.') if os.path.isfile(f)] # for f in files: # print(f) def make_tarfile(output_filename, source_dir): with tarfile.open(output_filename, "w:gz") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) os.makedirs('export',exist_ok=True) os.makedirs('export/code',exist_ok=True) os.system('cp model.py export/code/') os.system('cp generate.py export/code/inference.py') os.system('cp model.pth export/') os.system('cp requirements.txt export/code/') os.chdir('export') os.system('tar -czvf ../model.tar.gz .') # make_tarfile('../model.tar.gz','./') os.chdir('../') s3_path_to_data = sagemaker.Session().upload_data(bucket='pahts-test-bucket', path=os.path.join(os.getcwd(),'model.tar.gz'), key_prefix='linear_model_key') # s3_path_to_data = sagemaker.Session().upload_data(bucket='pahts-test-bucket', # path=os.path.join(os.getcwd(),'model.py'), # key_prefix='linear_model_key') # s3_path_to_data = sagemaker.Session().upload_data(bucket='pahts-test-bucket', # path=os.path.join(os.getcwd(),'generate.py'), # key_prefix='linear_model_key') # print(s3_path_to_data) ``` ### Exporting the model as an endpoint ``` from sagemaker.pytorch import PyTorch from sagemaker.predictor import JSONSerializer, JSONDeserializer, Predictor class JSONPredictor(Predictor): def __init__(self, endpoint_name, sagemaker_session): super(JSONPredictor, self).__init__(endpoint_name, sagemaker_session, JSONSerializer, JSONDeserializer) import sagemaker from sagemaker.pytorch import PyTorchModel sagemaker_session = sagemaker.Session() role = sagemaker.get_execution_role() bucket = sagemaker_session.default_bucket() print(bucket) pytorch_model = PyTorchModel(model_data='s3://pahts-test-bucket/linear_model_key/model.tar.gz', role=role, entry_point='inference.py', framework_version='1.5.0', py_version='py3', source_dir='', predictor_cls=JSONPredictor) # Deploy model, https://aws.amazon.com/sagemaker/pricing/ predictor = pytorch_model.deploy(instance_type='ml.t2.medium',initial_instance_count=1) #Cheapest ``` ## Evaluate and Test ``` print('Evaluating') input = {'xvalue':2} input_json = json.dumps(input) # response = predictor.predict(input_json, initial_args={'ContentType': 'application/json'}) response = predictor.predict(input) print(response) import requests url = 'https://runtime.sagemaker.us-east-2.amazonaws.com/endpoints/pytorch-inference-2021-02-19-22-17-20-522/invocations' myobj = {'xvalue': 2} x = requests.post(url, data = myobj) print(x.text) ```
github_jupyter
# Annulus distribution In this notebook we create an annulus distribution, which has the following density, $$p(x|r_0, \sigma) \propto \text{exp}(-\frac{(|x|-r_0)^2}{2\sigma^2}),$$ where $\beta > 0$ and $|x|$ is the Euclidean norm of the d-dimensional $x$. This distribution was created due to its similarity in geometry to the distribution of a high-dimensional normal (albeit in lower dimensions), for its use in testing MCMC algorithms. Plotting a two-dimensional version of this function with $r0=10$ and $\sigma=1$. ``` import pints import pints.toy import numpy as np import matplotlib.pyplot as plt # Create log pdf (default is 2-dimensional with r0=10 and sigma=1) log_pdf = pints.toy.AnnulusLogPDF() # Contour plot of pdf num_points = 100 x = np.linspace(-15, 15, num_points) y = np.linspace(-15, 15, num_points) X, Y = np.meshgrid(x, y) Z = np.zeros(X.shape) Z = np.exp([[log_pdf([i, j]) for i in x] for j in y]) plt.contour(X, Y, Z) plt.xlabel('x') plt.ylabel('y') plt.show() ``` ## Generate independent samples from this distribution and plot them ``` samples = log_pdf.sample(100) num_points = 100 x = np.linspace(-15, 15, num_points) y = np.linspace(-15, 15, num_points) X, Y = np.meshgrid(x, y) Z = np.zeros(X.shape) Z = np.exp([[log_pdf([i, j]) for i in x] for j in y]) plt.contour(X, Y, Z) plt.scatter(samples[:, 0], samples[:, 1]) plt.xlabel('x') plt.ylabel('y') plt.show() ``` Use adaptive covariance MCMC to sample from this (un-normalised) pdf. ``` # Create an adaptive covariance MCMC routine x0 = np.random.uniform([2, 2], [8, 8], size=(4, 2)) mcmc = pints.MCMCController(log_pdf, 4, x0, method=pints.AdaptiveCovarianceMCMC) # Set maximum number of iterations mcmc.set_max_iterations(4000) # Disable logging mcmc.set_log_to_screen(False) # Number of chains num_chains = 4 # Run! print('Running...') chains = mcmc.run() print('Done!') # Discard warm-up chains = [chain[1000:] for chain in chains] ``` Scatter plot of the samples. Adaptive covariance MCMC seems to do ok at sampling from this distribution. ``` stacked = np.vstack(chains) plt.contour(X, Y, Z, colors='k', alpha=0.5) plt.scatter(stacked[:,0], stacked[:,1], marker='.', alpha=0.2) plt.xlim(-15, 15) plt.ylim(-15, 15) plt.xlabel('x') plt.ylabel('y') plt.show() ``` Try Hamiltonian Monte Carlo on same problem. ``` # Create an adaptive covariance MCMC routine x0 = np.random.uniform([2, 2], [8, 8], size=(4, 2)) sigma0 = [2, 2] mcmc = pints.MCMCController(log_pdf, 4, x0, method=pints.HamiltonianMCMC, sigma0=sigma0) # Set maximum number of iterations mcmc.set_max_iterations(400) # Disable logging # mcmc.set_log_to_screen(False) # Number of chains num_chains = 4 # Run! print('Running...') chains = mcmc.run() print('Done!') # Discard warm-up chains = [chain[200:] for chain in chains] ``` A single chain of HMC moves much more naturally around the annulus. ``` plt.contour(X, Y, Z, colors='k', alpha=0.5) plt.plot(chains[0][:, 0], chains[0][:, 1]) plt.xlim(-15, 15) plt.ylim(-15, 15) plt.xlabel('x') plt.ylabel('y') plt.show() ``` ## 3-dimensional annulus Now creating a 3 dimensional annulus with $r0=20$ and $\sigma=0.5$, then using Adaptive covariance MCMC to sample from it. ``` log_pdf = pints.toy.AnnulusLogPDF(dimensions=3, r0=20, sigma=0.5) # Create an adaptive covariance MCMC routine x0 = np.zeros(log_pdf.n_parameters()) + np.random.normal(0, 1, size=(4, log_pdf.n_parameters())) mcmc = pints.MCMCController(log_pdf, 4, x0, method=pints.AdaptiveCovarianceMCMC) # Set maximum number of iterations mcmc.set_max_iterations(4000) # Disable logging mcmc.set_log_to_screen(False) # Number of chains num_chains = 4 # Run! print('Running...') chains = mcmc.run() print('Done!') # Discard warm-up chains = [chain[1000:] for chain in chains] stacked = np.vstack(chains) ``` Samples are near to surface of sphere of radius 20. ``` from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca(projection='3d') ax.plot(stacked[:, 0], stacked[:, 1], stacked[:, 2], '.', alpha=0.1) ax.legend() plt.show() ``` We can see that the mean of the samples is a long way from the true value (0, 0, 0) ``` a_mean = np.mean(stacked, axis=0) print("True mean = " + str(log_pdf.mean())) print("Sample mean = " + str(a_mean)) ``` ## 10-dimensional annulus Now creating a 10 dimensional annulus with $r0=15$ and $\sigma=2$, then using Adaptive covariance MCMC to sample from it. ``` log_pdf = pints.toy.AnnulusLogPDF(dimensions=10, r0=15, sigma=2) # Create an adaptive covariance MCMC routine x0 = np.zeros(log_pdf.n_parameters()) + np.random.normal(0, 1, size=(4, log_pdf.n_parameters())) mcmc = pints.MCMCController(log_pdf, 4, x0, method=pints.AdaptiveCovarianceMCMC) # Set maximum number of iterations mcmc.set_max_iterations(8000) # Disable logging mcmc.set_log_to_screen(False) # Number of chains num_chains = 4 # Run! print('Running...') chains = mcmc.run() print('Done!') # Discard warm-up chains = [chain[1000:] for chain in chains] ``` Compare the theoretical mean and variance of the normed distance from the origin with the sample-based estimates. Does ok! ``` chain = np.vstack(chains) d = list(map(lambda x: np.linalg.norm(x), chain)) a_mean = np.mean(d) a_var = np.var(d) print("True normed mean = " + str(log_pdf.mean_normed())) print("Sample normed mean = " + str(a_mean)) print("True normed var = " + str(log_pdf.var_normed())) print("Sample normed var = " + str(a_var)) ``` Less good at recapitulating the actual mean. ``` a_mean = np.mean(chain, axis=0) print("True mean = " + str(log_pdf.mean())) print("Sample mean = " + str(a_mean)) ```
github_jupyter
``` import pandas as pd import numpy as np from scipy import stats from datetime import date from sqlalchemy import create_engine from config import db_password # load in tensile data tensile_df = pd.read_csv("../Resources/Raw Data/tensile_data.csv") tensile_df # rename columns tensile_df = tensile_df.rename(columns={ "Date Code": "date_code", "Nominal Thickness": "thickness", "Oven \nNumber": "oven_id", "Date Removed from Oven": "remove_date", "Pre Cure \nTensile":"amb_tensile_pre_cure", "Pre Cure Elongation": "amb_elongation_pre_cure", "Post Cure Tensile": "amb_tensile_post_cure", "Post Cure Elongation": "amb_elongation_post_cure", "Start \nTensile": "hot_tensile_start", "Start \nElongation": "hot_elongation_start", "Start Scrap Footage": "start_scrap", "End \nTensile": "hot_tensile_end", "End \nElongation": "hot_elongation_end", "End Scrap Footage": "end_scrap", "Comments": "comments", "Class": "class"}) tensile_df tensile_df['oven_id'].value_counts() # drop columns that don't matter; start and end scrap footage, comments, class tensile_df = tensile_df.drop(columns=["comments","class","start_scrap","end_scrap"]) tensile_df.head() # remove T from thickness, convert to numeric value tensile_df['thickness'] = tensile_df.thickness.str.extract('(\d+)').astype(float) tensile_df.head() # check data set datatypes tensile_df.dtypes #convert to numeric tensile_df['oven_id']=pd.to_numeric(tensile_df['oven_id'], errors='coerce') # convert remove_date to datetime tensile_df['remove_date']=pd.to_datetime(tensile_df['remove_date']) #convert ambient tensile pre cure to float tensile_df['amb_tensile_pre_cure']=pd.to_numeric(tensile_df['amb_tensile_pre_cure'],errors='coerce') #convert ambient elongation pre cure to float tensile_df['amb_elongation_pre_cure']=pd.to_numeric(tensile_df['amb_elongation_pre_cure'],errors='coerce') #convert ambient tensile prost cure to float tensile_df['amb_tensile_post_cure']=pd.to_numeric(tensile_df['amb_tensile_post_cure'],errors='coerce') #convert ambient elongation post cure to float tensile_df['amb_elongation_post_cure']=pd.to_numeric(tensile_df['amb_elongation_post_cure'],errors='coerce') #convert ambient tensile pre cure to float tensile_df['hot_tensile_start']=pd.to_numeric(tensile_df['hot_tensile_start'],errors='coerce') tensile_df.dtypes tensile_df.isna().sum() # drop olumns with high number of nulls remaining tensile_df=tensile_df.drop(columns=['oven_id','remove_date']) #Keep only clean data tensile_df=tensile_df.dropna() tensile_df # establish norms tensile_df.describe() # function that removes outliers from each specified column df = dataframe, cols = list of column names def remove_outliers(df,cols): #iterate through each column for col in df.columns: # check if column requires outlier scrubbing if col in cols: #print for debug #print(f"Processing ",col) #get quartile values q1 = df[col].quantile(0.25) q3 = df[col].quantile(0.75) iqr = q3-q1 #get upper/lower bounds upper = q3+1.5*iqr lower = q1-1.5*iqr #filter df to keep only values which are below the upper bound, above the lower bound df=df.loc[(df[col]<upper)&(df[col]<upper)] # return filtered df return df # remove outliers from temp_tensile cols = tensile_df.loc[:, (tensile_df.columns !='thickness')&(tensile_df.columns !='date_code')].columns #clean tensile dataframe equal to original without outliers clean_tensile_df = remove_outliers(tensile_df, cols) clean_tensile_df # produce binary pass/fail based on ASTM specs clean_tensile_df['amb_elongation_result']=np.where(clean_tensile_df['amb_elongation_post_cure']>250,1,0) clean_tensile_df['amb_tensile_result']=np.where(clean_tensile_df['amb_tensile_post_cure']>24,1,0) clean_tensile_df['hot_tensile_result']= np.where(np.logical_and(np.logical_and(clean_tensile_df['hot_tensile_start']>6,clean_tensile_df['hot_tensile_start']<16),np.logical_and(clean_tensile_df['hot_tensile_end']>6,clean_tensile_df['hot_tensile_end']<16)),1,0) clean_tensile_df['hot_elongation_result']=np.where(np.logical_and(clean_tensile_df['hot_elongation_start']>100,clean_tensile_df['hot_elongation_end']>100),1,0) clean_tensile_df['overall_result']=clean_tensile_df['amb_elongation_result']*clean_tensile_df['amb_tensile_result']*clean_tensile_df['hot_elongation_result']*clean_tensile_df['hot_tensile_result'] clean_tensile_df # get final tensile data showing only X vals (thickness, ambient tensile/elongation pre cure) and Y vals (results 0/1 for fail/pass) final_tensile_df = clean_tensile_df.drop(columns=['amb_elongation_post_cure', 'amb_tensile_post_cure', 'hot_tensile_start', 'hot_elongation_start', 'hot_tensile_end', 'hot_elongation_end']) final_tensile_df.head() #save as csv final_tensile_df.to_csv('../Resources/Clean Data/final_tensile.csv', index=False) # connect to PostrgreSQL db_string = f"postgresql://postgres:{db_password}@127.0.0.1:5432/polypropylene_analysis_db" engine = create_engine(db_string) final_tensile_df.to_sql(name='tensile_data', con=engine, if_exists='replace') ```
github_jupyter
``` %pylab inline #%matplotlib qt from __future__ import division # use so 1/2 = 0.5, etc. import sk_dsp_comm.sigsys as ss import sk_dsp_comm.iir_design_helper as iir_d import sk_dsp_comm.pyaudio_helper as pah import scipy.signal as signal import time import sys import imp # for module development and reload() from IPython.display import Audio, display from IPython.display import Image, SVG pylab.rcParams['savefig.dpi'] = 100 # default 72 #pylab.rcParams['figure.figsize'] = (6.0, 4.0) # default (6,4) #%config InlineBackend.figure_formats=['png'] # default for inline viewing %config InlineBackend.figure_formats=['svg'] # SVG inline viewing #%config InlineBackend.figure_formats=['pdf'] # render pdf figs for LaTeX #Image('filename.png',width='80%') ``` # Static/Simulation-Based Audio Processing ## Notch Filters to Remove Interference Within `sigsys` there are some handy functions for designing single section notch filters and then cascading them. First set up a scenario with tone interference present in speech. ``` fs,s = ss.from_wav('OSR_us_000_0030_8k.wav') soi = s[10000:40000] n = arange(len(soi)) snoi = 0.4*cos(2*pi*1000/fs*n) + 0.5*cos(2*pi*1500/fs*n) r = soi + snoi psd(r,2**10,8000); title(r'Two Interfering Tones'); ``` Look at the waveform and then listen to it. ``` # First save r to a wave file for static playback ss.to_wav('speech_tone.wav',8000,r/2) Audio('speech_tone.wav') ``` Design a cascade of notch filters: ``` plot(r[6000:10000]) title(r'The Interference is Overwhelming') bn1, an1 = ss.fir_iir_notch(1000,8000) bn2, an2 = ss.fir_iir_notch(1500,8000,.98) # tighten the bandwidth of the 12k notch bn, an = ss.cascade_filters(bn1,an1,bn2,an2) iir_d.freqz_resp_list([bn],[an],'dB',8000) grid(); ``` Now apply the filter to the composite signal:: ``` z = signal.lfilter(bn,an,r) specgram(z,512,8000); # First save z to a wave file for static playback ss.to_wav('speech_tone_notch.wav',8000,z) Audio('speech_tone_notch.wav') ``` ## Adaptive Interference Removal (Placeholder, but start from `ss.lms_ic`) ```python def lms_ic(r,M,mu,delta=1): """ Least mean square (LMS) interference canceller adaptive filter. A complete LMS adaptive filter simulation function for the case of interference cancellation. Used in the digital filtering case study. Parameters ---------- M : FIR Filter length (order M-1) delta : Delay used to generate the reference signal mu : LMS step-size delta : decorrelation delay between input and FIR filter input Returns ------- n : ndarray Index vector r : ndarray noisy (with interference) input signal r_hat : ndarray filtered output (NB_hat[n]) e : ndarray error sequence (WB_hat[n]) ao : ndarray final value of weight vector F : ndarray frequency response axis vector Ao : ndarray frequency response of filter Examples ---------- >>> # import a speech signal >>> fs,s = from_wav('OSR_us_000_0030_8k.wav') >>> # add interference at 1kHz and 1.5 kHz and >>> # truncate to 5 seconds >>> r = soi_snoi_gen(s,10,5*8000,[1000, 1500]) >>> # simulate with a 64 tap FIR and mu = 0.005 >>> n,r,r_hat,e,ao,F,Ao = lms_ic(r,64,0.005) """ ``` # Audio Special Effects Consider *flanging*, which is a combination of a direct signal path and a time varying delay path. In `digitalcom` there is a function for creating a time-varying delay, $\beta[n]$, that works well for communication systems impairments, but is useful here as well. Understand that a time varying delay is compressing and expanding the time axis just like the Doppler effect. In music this causes the pitch to wobble, but at slow rates introduces a whooshing effect, made popular in rock music many years ago. ``` Image('images/Flanging_Block.png',width='80%') ``` The time varying delay in flanging takes the form: $$ \beta[n] = D_p \big(1+\cos(2\pi f_0/f_s)\big) $$ where here $D_p = 50$ and $f_0 \simeq 1$ Hz or less. Import some sound files and set up the time varying delay. ``` import sk_dsp_comm.digitalcom as dc # for time delay Audio('c_major.wav') fs,s12 = ss.from_wav('Music_Test.wav') fs # Processing is slow because the time axis interpolation is subsample-based # Using a 3rd-order Lagrange interpolator fs,s1 = ss.from_wav('c_major.wav') #fs,s12 = ss.from_wav('Music_Test.wav') #s1 = (s12[:,0] + s12[:,0])/2 n = arange(len(s1)) f0 = 1 Dp = 50 D = Dp*(1 + cos(2*pi*f0/fs*n)) x = dc.time_delay(s1,D + 2, 2*Dp+4) x_wav = x # for PyAudio playback # Flanged versions of c_major.wav and Music_Test.wav #ss.to_wav('flanger_audio_c_major.wav',44100,x_wav) ss.to_wav('flanger_audio_Music_Test.wav',44100,x_wav) ``` #### Playback using PyAudio (one channel only) ``` pah.available_devices() # define callback # Here we configure the callback to play back a wav file def callback(in_data, frame_count, time_info, status): # Ignore in_data when generating output only #*********************************************** global x # Note wav is scaled to [-1,1] so need to rescale to int16 y = 32767*x.get_samples(frame_count) # Save data for later analysis # accumulate a new frame of samples DSP_IO.DSP_capture_add_samples(y) #*********************************************** # Convert from float back to int16 y = y.astype(int16) return y.tobytes(), pah.pyaudio.paContinue x = pah.loop_audio(x_wav) DSP_IO = pah.DSP_io_stream(callback,0,1,fs=44100,Tcapture=2) DSP_IO.stream(20) # may need to change time ```
github_jupyter
# Predicting Student Admissions with Neural Networks In this notebook, we predict student admissions to graduate school at UCLA based on three pieces of data: - GRE Scores (Test) - GPA Scores (Grades) - Class rank (1-4) The dataset originally came from here: http://www.ats.ucla.edu/ ## Loading the data To load the data and format it nicely, we will use two very useful packages called Pandas and Numpy. You can read on the documentation here: - https://pandas.pydata.org/pandas-docs/stable/ - https://docs.scipy.org/ ``` # Importing pandas and numpy import pandas as pd import numpy as np # Reading the csv file into a pandas DataFrame data = pd.read_csv('student_data.csv') # Printing out the first 10 rows of our data data[:10] ``` ## Plotting the data First let's make a plot of our data to see how it looks. In order to have a 2D plot, let's ingore the rank. ``` # Importing matplotlib import matplotlib.pyplot as plt # Function to help us plot def plot_points(data): X = np.array(data[["gre","gpa"]]) y = np.array(data["admit"]) admitted = X[np.argwhere(y==1)] rejected = X[np.argwhere(y==0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s = 25, color = 'red', edgecolor = 'k') plt.scatter([s[0][0] for s in admitted], [s[0][1] for s in admitted], s = 25, color = 'cyan', edgecolor = 'k') plt.xlabel('Test (GRE)') plt.ylabel('Grades (GPA)') # Plotting the points plot_points(data) plt.show() ``` Roughly, it looks like the students with high scores in the grades and test passed, while the ones with low scores didn't, but the data is not as nicely separable as we hoped it would. Maybe it would help to take the rank into account? Let's make 4 plots, each one for each rank. ``` # Separating the ranks data_rank1 = data[data["rank"]==1] data_rank2 = data[data["rank"]==2] data_rank3 = data[data["rank"]==3] data_rank4 = data[data["rank"]==4] # Plotting the graphs plot_points(data_rank1) plt.title("Rank 1") plt.show() plot_points(data_rank2) plt.title("Rank 2") plt.show() plot_points(data_rank3) plt.title("Rank 3") plt.show() plot_points(data_rank4) plt.title("Rank 4") plt.show() ``` This looks more promising, as it seems that the lower the rank, the higher the acceptance rate. Let's use the rank as one of our inputs. In order to do this, we should one-hot encode it. ## TODO: One-hot encoding the rank Use the `get_dummies` function in numpy in order to one-hot encode the data. ``` # TODO: Make dummy variables for rank one_hot_data = pd.concat([data, pd.get_dummies(data['rank'], prefix='rank')], axis=1) # TODO: Drop the previous rank column #one_hot_data.drop('rank', axis=1) del(one_hot_data["rank"]) # Print the first 10 rows of our data one_hot_data[:10] ``` ## TODO: Scaling the data The next step is to scale the data. We notice that the range for grades is 1.0-4.0, whereas the range for test scores is roughly 200-800, which is much larger. This means our data is skewed, and that makes it hard for a neural network to handle. Let's fit our two features into a range of 0-1, by dividing the grades by 4.0, and the test score by 800. ``` # Making a copy of our data processed_data = one_hot_data[:] # TODO: Scale the columns # Printing the first 10 rows of our procesed data processed_data[:10] ``` ## Splitting the data into Training and Testing In order to test our algorithm, we'll split the data into a Training and a Testing set. The size of the testing set will be 10% of the total data. ``` sample = np.random.choice(processed_data.index, size=int(len(processed_data)*0.9), replace=False) train_data, test_data = processed_data.iloc[sample], processed_data.drop(sample) print("Number of training samples is", len(train_data)) print("Number of testing samples is", len(test_data)) print(train_data[:10]) print(test_data[:10]) ``` ## Splitting the data into features and targets (labels) Now, as a final step before the training, we'll split the data into features (X) and targets (y). ``` features = train_data.drop('admit', axis=1) targets = train_data['admit'] features_test = test_data.drop('admit', axis=1) targets_test = test_data['admit'] print(features[:10]) print(targets[:10]) ``` ## Training the 2-layer Neural Network The following function trains the 2-layer neural network. First, we'll write some helper functions. ``` # Activation (sigmoid) function def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_prime(x): return sigmoid(x) * (1-sigmoid(x)) def error_formula(y, output): return - y*np.log(output) - (1 - y) * np.log(1-output) ``` # TODO: Backpropagate the error Now it's your turn to shine. Write the error term. Remember that this is given by the equation $$ -(y-\hat{y}) \sigma'(x) $$ ``` # TODO: Write the error term formula def error_term_formula(y, output): pass # Neural Network hyperparameters epochs = 1000 learnrate = 0.5 # Training function def train_nn(features, targets, epochs, learnrate): # Use to same seed to make debugging easier np.random.seed(42) n_records, n_features = features.shape last_loss = None # Initialize weights weights = np.random.normal(scale=1 / n_features**.5, size=n_features) for e in range(epochs): del_w = np.zeros(weights.shape) for x, y in zip(features.values, targets): # Loop through all records, x is the input, y is the target # Activation of the output unit # Notice we multiply the inputs and the weights here # rather than storing h as a separate variable output = sigmoid(np.dot(x, weights)) # The error, the target minus the network output error = error_formula(y, output) # The error term # Notice we calulate f'(h) here instead of defining a separate # sigmoid_prime function. This just makes it faster because we # can re-use the result of the sigmoid function stored in # the output variable error_term = error_term_formula(y, output) # The gradient descent step, the error times the gradient times the inputs del_w += error_term * x # Update the weights here. The learning rate times the # change in weights, divided by the number of records to average weights += learnrate * del_w / n_records # Printing out the mean square error on the training set if e % (epochs / 10) == 0: out = sigmoid(np.dot(features, weights)) loss = np.mean((out - targets) ** 2) print("Epoch:", e) if last_loss and last_loss < loss: print("Train loss: ", loss, " WARNING - Loss Increasing") else: print("Train loss: ", loss) last_loss = loss print("=========") print("Finished training!") return weights weights = train_nn(features, targets, epochs, learnrate) ``` ## Calculating the Accuracy on the Test Data ``` # Calculate accuracy on test data tes_out = sigmoid(np.dot(features_test, weights)) predictions = tes_out > 0.5 accuracy = np.mean(predictions == targets_test) print("Prediction accuracy: {:.3f}".format(accuracy)) ```
github_jupyter
<a href="https://colab.research.google.com/github/skimotv/SkimoTextSummarizer/blob/master/Multiple_Summarizer_Tests.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !pip install -U git+https://github.com/huggingface/transformers.git import torch from transformers import AutoTokenizer, AutoModelWithLMHead # Use a model from https://huggingface.co/models?filter=summarization&sort=modified models = ["sshleifer/distilbart-cnn-12-3", "sshleifer/distilbart-cnn-12-6", "sshleifer/distilbart-cnn-6-6", "sshleifer/distilbart-xsum-1-1", "sshleifer/distilbart-xsum-12-1", "sshleifer/distilbart-xsum-12-3", "sshleifer/distilbart-xsum-12-6", "sshleifer/distilbart-xsum-6-6", "sshleifer/distilbart-xsum-9-6", "google/pegasus-billsum" ] tokenizer = AutoTokenizer.from_pretrained(models[9]) model = AutoModelWithLMHead.from_pretrained(models[9]) text = "Four overnight camps in Maine successfully identified and isolated three Covid-19 positive people with no symptoms, preventing transmission to more than 1,000 other campers and staff this summer, says a new report published by the Centers for Disease Control and Prevention.For many kids, summer camp looked and felt a little different this year. There were daily temperatures checks, more time spent outside and plenty of face masks. Dr. Laura Blaisdell of the Maine Medical Center Research Institute and colleagues said the extra effort paid off.They detailed where these camps went right in a report examining 642 children and 380 staff members who attended the four camps in Maine for well over a month between June and August. Camp attendees traveled from across the United States and six international locations: Bermuda, Canada, Mexico, South Africa, Spain and the United Kingdom. They quarantined for up to 14 days before arriving at camp and three of the sites asked campers to submit Covid-19 test results before attending. This was an important step in preventing introduction of the virus in a setting with many young adults who could be asymptomatic or presymptomatic, Blaisdell and colleagues wrote in the CDC's weekly report.Camp attendees were separated into groups when they first arrived and had to wear face coverings when interacting with people outside of their groups. The camps kept surfaces clean and groups physically distant. They staggered bathroom use and dining times. They also screened campers daily for fever and coronavirus symptoms. Most attendees were tested again for Covid-19 a few days after arriving at camp. That's when a symptomless camper and two staff members tested positive, according to the report. They were rapidly isolated until they recovered, and their contacts were quarantined for 14 days. (CNN)Four overnight camps in Maine successfully identified and isolated three Covid-19 positive people with no symptoms, preventing transmission to more than 1,000 other campers and staff this summer, says a new report published by the Centers for Disease Control and Prevention.For many kids, summer camp looked and felt a little different this year. There were daily temperatures checks, more time spent outside and plenty of face masks. Dr. Laura Blaisdell of the Maine Medical Center Research Institute and colleagues said the extra effort paid off.They detailed where these camps went right in a report examining 642 children and 380 staff members who attended the four camps in Maine for well over a month between June and August.A Georgia sleepaway camp&#39;s coronavirus outbreak is a warning for what could happen when schools reopen, CDC saysA Georgia sleepaway camp's coronavirus outbreak is a warning for what could happen when schools reopen, CDC saysCamp attendees traveled from across the United States and six international locations: Bermuda, Canada, Mexico, South Africa, Spain and the United Kingdom. They quarantined for up to 14 days before arriving at camp and three of the sites asked campers to submit Covid-19 test results before attending.Content by CNN UnderscoredHow to sell your old tech before it loses its value.CNN Underscored partnered with Decluttr to create this content. When you make a purchase, CNN receives revenue.This was an important step in preventing introduction of the virus in a setting with many young adults who could be asymptomatic or presymptomatic, Blaisdell and colleagues wrote in the CDC's weekly report.Camp attendees were separated into groups when they first arrived and had to wear face coverings when interacting with people outside of their groups. The camps kept surfaces clean and groups physically distant. They staggered bathroom use and dining times. They also screened campers daily for fever and coronavirus symptoms.Covid-19 child cases in the US have increased by 21% since early August, new data showsCovid-19 child cases in the US have increased by 21% since early August, new data showsMost attendees were tested again for Covid-19 a few days after arriving at camp. That's when a symptomless camper and two staff members tested positive, according to the report. They were rapidly isolated until they recovered, and their contacts were quarantined for 14 days.None of the contacts tested positive for Covid-19, according to the CDC report.The report noted that it wasn't one particular precaution that helped prevent the spread of coronavirus in these camps, but rather a multilayered strategy that was carefully executed." print(len(text)) def summarize(text): inputs = tokenizer.encode(text, add_special_tokens=False, return_tensors="pt") outputs = model.generate(inputs, max_length=250, do_sample=True, top_p=0.95, top_k=60) generated = tokenizer.decode(outputs[0]) return generated sum = summarize(text) print(sum) print(sum) print(len(sum)) ```
github_jupyter
# SPIE 2020 - Testing Residual Learning in BSD300 dataset with Poisson noise ## Importing libraries ``` from typing import List, Dict, Tuple from copy import deepcopy import os import cv2 import keras import numpy as np import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf from glob import glob from tqdm import tqdm from keras import Sequential, layers, activations from keras.models import Model, load_model from skimage.metrics import peak_signal_noise_ratio as psnr, structural_similarity as ssim from skimage.util import random_noise from images.image import * from utils import * ``` ## Loading BSD300 Dataset and adding Poisson noise ``` y_train = [] x_train = [] for file in tqdm(glob(os.path.join('dataset/bsd300/train/*.jpg'))): img = cv2.imread(file, cv2.IMREAD_GRAYSCALE) patches = crop_image(img, height=50, width=50, stride=20) for i in range(patches.shape[0]): y_train.append(patches[i]) x_train.append(np.random.poisson(lam=patches[i], size=None)) y_test = [] x_test = [] for file in tqdm(glob(os.path.join('dataset/bsd300/test/*.jpg'))): img = cv2.imread(file, cv2.IMREAD_GRAYSCALE) patches = crop_image(img, height=50, width=50, stride=20) for i in range(patches.shape[0]): y_test.append(patches[i]) x_test.append(np.random.poisson(lam=patches[i], size=None)) y_train = np.array(y_train) x_train = np.array(x_train) y_test = np.array(y_test) x_test = np.array(x_test) x_train.shape x_test.shape mostrar_lado_a_lado(imagens=[x_train[1500, :,:], y_train[1500,:,:]], titulos=['Ruidoso', 'Original']) mostrar_lado_a_lado(imagens=[x_test[3010, :,:], y_test[3010,:,:]], titulos=['Ruidoso', 'Original']) ``` ## Normalizing datasets between [0;1] ``` x_train = cv2.normalize(x_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F) y_train = cv2.normalize(y_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F) x_test = cv2.normalize(x_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F) y_test = cv2.normalize(y_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F) ``` ## Adding color dimension ``` x_train = adiciona_a_dimensao_das_cores(x_train) y_train = adiciona_a_dimensao_das_cores(y_train) x_test = adiciona_a_dimensao_das_cores(x_test) y_test = adiciona_a_dimensao_das_cores(y_test) x_train.shape x_test.shape ``` # Building model with Residual Learning ``` model_with_subtract = build_dncnn_model(nb_layers=10, with_subtract=True) # model_with_subtract.summary() ``` ## Hyper-parameters ``` BATCH_SIZE = 128 LEARNING_RATE = 0.001 EPOCHS = 60 model_with_subtract.compile(optimizer=keras.optimizers.Adam(LEARNING_RATE), loss='mse') ``` ## Saving model checkpoint ``` checkpoint = keras.callbacks.ModelCheckpoint('checkpoints/dncnn-10l-with-rl-bsd300.hdf5', verbose=1, save_best_only=True, save_weights_only=False, period=1) ``` # Training the model ``` history = model_with_subtract.fit( x_train, y_train, validation_data=(x_test, y_test), batch_size=BATCH_SIZE, shuffle=True, epochs=EPOCHS, verbose=1, callbacks=[checkpoint] ) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.legend(['loss', 'val. loss']) ``` # Building the model without RL ``` model_without_subtract = build_dncnn_model(nb_layers=10, with_subtract=False) model_without_subtract.compile(optimizer=keras.optimizers.Adam(LEARNING_RATE), loss='mse') checkpoint = keras.callbacks.ModelCheckpoint('checkpoints/dncnn-10l-without-rl-bsd300.hdf5', verbose=1, save_best_only=True, save_weights_only=False, period=1) hist_without_subtract = model_without_subtract.fit( x_train, y_train, validation_data=(x_test, y_test), batch_size=BATCH_SIZE, shuffle=True, epochs=EPOCHS, verbose=1, callbacks=[checkpoint] ) plt.plot(hist_without_subtract.history['loss']) plt.plot(hist_without_subtract.history['val_loss']) plt.legend(['loss', 'val. loss']) ``` # Testing the models ``` model_with_subtract.load_weights('checkpoints/dncnn-10l-with-rl-bsd300.hdf5') model_without_subtract.load_weights('checkpoints/dncnn-10l-without-rl-bsd300.hdf5') ``` ## Denoising in test projections ``` predicted_with_subtract = model_with_subtract.predict(x_test, verbose=2) predicted_with_subtract.shape predicted_without_subtract = model_without_subtract.predict(x_test, verbose=2) predicted_without_subtract.shape ``` ## Visual comparison ``` mostrar_lado_a_lado(imagens=[y_test[100,:,:,0], x_test[100,:,:,0], predicted_with_subtract[100,:,:,0], predicted_without_subtract[100,:,:,0]], titulos=['Original', 'Ruidoso', 'DnCNN', 'DnCNN without RL']) y_test[100].shape from denoising.measures import PSNR, SSIM pnsr_img = PSNR(y_test[100].reshape(1,50,50,1), predicted_with_subtract[100].reshape(1,50,50,1)) ssim_img = SSIM(y_test[100].reshape(1,50,50,1), predicted_with_subtract[100].reshape(1,50,50,1)) print('PSNR médio: %.2f dB e SSIM médio %.2f.' % (np.array(pnsr_img).mean(), np.array(ssim_img).mean())) pnsr_img = PSNR(y_test[100].reshape(1,50,50,1), predicted_without_subtract[100].reshape(1,50,50,1)) ssim_img = SSIM(y_test[100].reshape(1,50,50,1), predicted_without_subtract[100].reshape(1,50,50,1)) print('PSNR médio: %.2f dB e SSIM médio %.2f.' % (np.array(pnsr_img).mean(), np.array(ssim_img).mean())) mostrar_lado_a_lado(imagens=[y_test[500,:,:,0], x_test[500,:,:,0], predicted_with_subtract[500,:,:,0], predicted_without_subtract[500,:,:,0]], titulos=['Original', 'Ruidoso', 'DnCNN', 'DnCNN without RL']) ``` ## Compairing PSNR and SSIM of projections filtered by the network ``` psnr = PSNR(y_test, x_test) ssim = SSIM(y_test, x_test) print('PSNR médio: %.2f dB e SSIM médio %.2f.' % (np.array(psnr).mean(), np.array(ssim).mean())) psnr_pred = PSNR(y_test, predicted_with_subtract) ssim_pred = SSIM(y_test, predicted_with_subtract) print('PSNR médio: %.2f dB e SSIM médio %.2f.' % (np.array(psnr_pred).mean(), np.array(ssim_pred).mean())) psnr_pred_without_subtract = PSNR(y_test, predicted_without_subtract) ssim_pred_without_subtract = SSIM(y_test, predicted_without_subtract) print('PSNR médio: %.2f dB e SSIM médio %.2f.' % (np.array(psnr_pred_without_subtract).mean(), np.array(ssim_pred_without_subtract).mean())) ``` ## PSNR with RL: 25.87 dB ## PSNR without RL: 28.82 dB ## SSIM with RL: 0.90 ## SSIM without RL: 0.89 # Saving data ``` np.save('results/spie2020/teste-rl/poisson/predicted_with_rl.npy', predicted_with_subtract) np.save('results/spie2020/teste-rl/poisson/predicted_without_rl.npy', predicted_without_subtract) np.save('results/spie2020/teste-rl/poisson/psnr_with_rl.npy', np.array(psnr_pred)) np.save('results/spie2020/teste-rl/poisson/ssim_with_rl.npy', np.array(ssim_pred)) np.save('results/spie2020/teste-rl/poisson/psnr_without_rl.npy', np.array(psnr_pred_without_subtract)) np.save('results/spie2020/teste-rl/poisson/ssim_without_rl.npy', np.array(ssim_pred_without_subtract)) ```
github_jupyter
``` import numpy as np import astropy.units as u from astropy.time import Time from astropy.table import Table from sbpy.data import Ephem, Phys from sbpy.activity import (Haser, LTE, NonLTE, photo_timescale, einstein_coeff, intensity_conversion, beta_factor, total_number, from_Haser) import matplotlib.pyplot as plt import matplotlib import astropy.constants as con ``` Calculating Column Density using the NonLTE iterative code `from_pyradex` ======================================= _____________________________________________________________________________________________ `sbpy.activity` offers an implementation of `pyradex` which is a python wrapper for the NonLTE, iterative fortran code called RADEX. Radex is described in [van der Tak et al. 2013](https://ui.adsabs.harvard.edu/abs/2007A%26A...468..627V/abstract). This model takes in an initial guess for the column density and compares the data iteratively against RADEX results, finding the best fit column density for the data. More information about the installation and setup of `pyradex` can be found here [here](https://github.com/keflavich/pyradex), as well as more information about the parameters needed for the [RADEX](https://personal.sron.nl/~vdtak/radex/index.shtml) code. `from_pyradex` returns the best fitting column density based on the data provided which can then be used with the Haser model shown in the previous example. RADEX requires information on collider densities in order to determine collision rates. The collider densities are required to be given in the form of a dictionary. For comets, we expect H2O to be our main collisional partner but RADEX does not contain information on collisional rates for H2O. Therefore, the default value for collider densities in sbpy is a scaled version of the H2 collisional rate to account for H2O. This scaling is prominent in a lot of literature, such as [Walker et al. 2014](https://ui.adsabs.harvard.edu/abs/2014ApJ...790...96W/abstract), [de Val Borro et al. 2017](https://ui.adsabs.harvard.edu/abs/2018MNRAS.474.1099D/abstract), and [Schoier et al. 2004](https://ui.adsabs.harvard.edu/abs/2005A%26A...432..369S/abstract). In the case of this module we have chosen to follow the Walker et al. scaling for deriving H2O-H2O collision rates from H2-H2O coefficients. Within this scaling, we apply the square root of the ratio of reduced masses: $$s = (\frac{m_{H2O}}{m_{H2}})^{0.5}$$ Where `s` is the scale to multiply the collisional density of H2 against in order to obtain H2O-H2O collision rates. For the implementation of this code, the user can either define their chosen first guess for column density, or they can calculate it from their data or JPLSpec data `cdensity_Bockelee`. The literature used for this example is the same as in [this notebook](LTE_prodrate_Haser), [Wierzchos et al. 2018](https://ui.adsabs.harvard.edu/abs/2018AJ....156...34W/abstract): **Important notes:** `pyradex` requires a fortran compiler to be installed in your system. The recommendation is gfortran, which can be installed using [Homebrew](https://brewformulas.org/Gfortran), or any other similar service. Warnings of a missing file and RunTime error are normal from pyradex, if the user wants to find out more about them, see the [`pyradex` docs](https://github.com/keflavich/pyradex). The file error comes from the fact that `sbpy` uses, like pyradex, `astroquery.Lamda` for the molecular data files instead of searching them locally (despite the Fortran code still forcing the search for a local molecular data file). In the future, a function will be added to `sbpy` in which a user may build their own molecular data files from JPLSpec information. For now, LAMDA catalog is the primary source of the molecular data file for the implementation of RADEX. ``` co = Table.read(('data/CO.csv'), format="ascii.csv") error = np.array([0.2, 0.4, 0.4, 0.4, 0.4]) * 10.**28 # +/- error from literature Q_error = np.array(co['Q']) + np.array(error) # upper error limit Q_error = np.log10(np.array(Q_error)) - np.array(co['log(Q)']) co['Q_error'] = Q_error print("Table:\n{}\nColumn Names:\n{}".format(co, co.columns)) ``` Model parameters needed, all values are taken directly from the literature. In this example the molecule identifier will be inputted as a regular expression. Regular expressions for mol_tag can be used but the user must be careful not to provide an ambiguous regular expression. One good thing to remember is that anything between symbols '^' and '\\$' will be matched exactly, therefore you can avoid an ambiguity error by writing your molecule name as such: '^name\\$'. A perfect example of this is with the molecule in this example 'CO', simply writing mol_tag = 'CO' will produce an ambiguity error because it will match CO, CO2, etc. therefore, it is necessary to restrict our molecule name regex to '^CO\\$' as presented below. ``` transition_freq = (230.538 * u.GHz).to('MHz') aper = 10 * u.m # aperture mol_tag = '^CO$' # regex molecule identifier temp_estimate = 25. * u.K vgas = 0.5 * u.km / u.s target = 'C/2016 R2' b = 0.74 # intrinsic antenna value ``` Obtaining molecular data from the JPL Molecular Spectroscopy Catalog using `sbpy.data.phys`. See documentation for a detailed breakdown of the resulting object and the values stored in the object. ``` mol_data = Phys.from_jplspec(temp_estimate, transition_freq, mol_tag) # molecular data from JPLSpec intl = intensity_conversion(mol_data) # calculate line intensity mol_data.apply([intl.value] * intl.unit, name='Integrated line intensity at desired temp') # store value ``` Obtaining the Einstein Coefficient. In this example, we will obtain our Einstein Coefficient from LAMDA catalog and append it to our molecular data Phys object. In [this notebook](LTE_prodrate_without_photolysis.ipynb) we have been calculating it through sbpy/JPLSpec. It is possible that your transition frequency values may not exactly match the LAMDA catalog to the 4th significant figure, especially if you're using JPLSpec. Therefore, we recommend when using this method that you match your transition frequency with the LAMDA value over the JPLSpec value, since `from_jplspec` is designed to pick the closest transition frequency within a range of 1 GHz, whereas LAMDA will expect the exact value found in their catalog. ``` from astroquery.lamda import Lamda mol_name = 'CO' # LAMDA molecule name lam_search = Lamda.query(mol=mol_name.lower()) # LAMDA Query lam_result = lam_search[1] # outputs CO table lam_found = lam_result[lam_result['Frequency'] == transition_freq.to('GHz').value] # parse results at frequency au_cat = lam_found['EinsteinA'] # get Einstein Coefficient au_cat = au_cat.data[0] # get value of coefficient au = au_cat / u.s # define the unit mol_data.apply([au.value] * au.unit, name='eincoeff') # store einstein coefficient ``` Initialize the `sbpy.activity.Haser` model in order to perform our production rate calculations. `Q_estimate` first guess for the production rate was obtained running `from_Drahus` for the same data set before doing this example ``` Q_estimate = 3.594*10**(28) / u.s parent = photo_timescale('CO') * vgas # parent photodissociation rate coma = Haser(Q_estimate, vgas, parent) # initializing the model with an estimate ``` Run the `from_pyradex` iterative code on the data to find best fit column densities, and then calculate total number based on telescope geometry. Use Haser model for the calculation of production rates. You can give a column density first guess either using `sbpy.data.LTE` `cdensity_Bockelee` function, or user-defined into the data class. In this example, we'll use `cdensity_Bockelee` Since our data file contains 6 different data points of observation times and integrated flux, we can calculate production rates for all of these 6 data points using a python for loop. **IMPORTANT: Because we are using a for loop, and some of the values that should be appended to the `mol_data` phys object are calculated within the loop itself, we must initialize our columns within the phys object BEFORE performing the loop. This is because you cannot iteratively redefine the same column of data within a phys object, but you CAN change the value of an already defined column as many times as you want. Since our `beta`, `cdensity` and `total_number` values vary with every iteration, and since our production rate needs these values within the loop, we must simply change the value of our already defined columns for beta, column density, and total number everytime we iterate. Keep in mind when you initialize the column you must initialize it with the correct units and correct type (float, int, str). If you get an error saying there are duplicate columns, it is most likely due to what has been mentioned in this note, and you will have to reinitialize your mol_data object before trying to enter more data in** ``` nonlte = NonLTE() q_found_pyradex = [] lte = LTE() for i in range(0, 5): time = Time(co['Time'][i], format='iso') integrated_flux = co['T_B'][i] * u.K * u.km / u.s ephemobj = Ephem.from_horizons(target, epochs=time.jd) beta = beta_factor(mol_data, ephemobj) mol_data['beta'] = beta cdensity_bockelee = lte.cdensity_Bockelee(integrated_flux, mol_data) # col density first guess mol_data['cdensity'] = cdensity_bockelee cdensity = nonlte.from_pyradex(integrated_flux, mol_data) mol_data['cdensity'] = cdensity tnum = total_number(mol_data, aper, b) # total number of molecules in aperture mol_data['total_number'] = tnum Q = from_Haser(coma, mol_data, aper=aper) # production rate from Haser model q_found_pyradex.append(np.log10(Q.value)[0]) q_pred_co = list(co['log(Q)']) print("The Resulting Production Rates for CO in {} using Haser model are:\n {}".format(target, np.round(q_found_pyradex,3))) print("Residuals:\n{}".format(np.round((np.array(q_pred_co)) - (np.array(q_found_pyradex)),3))) print("Literature errors:\n{}".format(np.round(co['Q_error'],3))) time_co = list(co['Time']) time_co = matplotlib.dates.datestr2num(time_co) plt.plot_date(time_co, q_pred_co, 'o', color='slateblue', label='Wierzchos & Womack 2018') plt.plot_date(time_co, q_found_pyradex, 'o', color='hotpink', label='sbpy results') plt.xlabel('Time') plt.ylabel('Log (Q)') plt.legend(loc='best', fontsize='x-small') plt.title('Q vs Time Plot for CO in {}'.format(target)) plt.show() ``` It is clear that the implementation of pyradex gives better results than the example in [this notebook](LTE_prodrate_Haser.ipynb) in comparison to the literature, and it is done entirely within `sbpy` functionalities, offering the user a rigorous way to calculate column densities, and from those, production rates using the Haser model within `sbpy`. Even so, `sbpy` allows for flexibility in terms of data entry. Hardly traceable inconsistencies like are common in cometary studies, since a lot depends on the molecular catalogs that the data is obtained from, or what calculations are used. This is exactly why sbpy offers flexibility in all its functions through the use of `sbpy.data` classes, which allow the user to define their preferrred parameters if they do not happen to be satisfied with the catalog functionalities and derivations of parameters that sbpy offers. Yet we recommend the use of as many sbpy functionalities as possible in order to maintain consistency in your calculations, which may prove to be important when conversations about comet classification arise. Helpful Links ======= ___________________________________________ Relevant Notebooks ----------------- - [How to calculate LTE production rates without photolysis effects](LTE_prodrate_without_photolysis.ipynb) - [How to calculate LTE production rates with Haser model](LTE_prodrate_Haser.ipynb) - [How to use Phys data class and `from_jplspec`](../data/Phys.ipynb) - [What is `astroquery.jplspec`](../data/jplspec.ipynb) Relevant Links ------------- - [LAMDA Queries with astroquery](https://astroquery.readthedocs.io/en/latest/lamda/lamda.html) - [JPLSpec Queries with astroquery](https://astroquery.readthedocs.io/en/latest/jplspec/jplspec.html) - [sbpy Activity Haser Class](https://sbpy.readthedocs.io/en/latest/api/sbpy.activity.Haser.html#sbpy.activity.Haser) - [sbpy Ephem data class](https://sbpy.readthedocs.io/en/latest/sbpy/data/index.html#how-to-use-ephem) - [sbpy Phys data class](https://sbpy.readthedocs.io/en/latest/sbpy/data/index.html#how-to-use-phys) - [sbpy data class alternative field names](https://sbpy.readthedocs.io/en/latest/sbpy/data/fieldnames.html#list-of-alternative-field-names) - [pyradex source code](https://github.com/keflavich/pyradex) - [RADEX fortran source code](https://personal.sron.nl/~vdtak/radex/) - [RADEX homepage](https://personal.sron.nl/~vdtak/radex/index.shtml) - [sbpy citation (please cite our work)](http://joss.theoj.org/papers/10.21105/joss.01426)
github_jupyter
# Variablen Variablen werden benutzt, um Daten zu speichern und wieder abzurufen. Im Laufe eines Programmablaufs kann eine Variable verschiedene Werte annehmen und wieder ausgelesen werden. Dabei kann mit Werten von Variablen gerechnet werden, als wären es die Zahlen, die ihnen zuletzt zugewiesen wurden. ## Definition und Zuweisungen Wir weisen zwei Variablen jeweils eine Zahl zu und werten dann diese beiden Variablen sowie ihre Summe und ihr Produkt aus: ``` a := 19 b := 23 println(a) println(b) println(a+b) println(a*b) ``` **Anmerkung:** Ein Ausdruck wie ```println(a)``` sorgt dafür, dass der Wert von ```a``` auf eine eigene Zeile ausgegeben wird. Lässt man oben die ```println(...)```-Teile weg, werden zwar alle Ausdrücke ausgewertet, aber nur die letzte Zeile wird ausgegeben. ### Typangabe bei der Definition Bei der Definition einer Variablen muss klar sein, welchen *Datentyp* (oder kurz *Typ*) die Variable hat. Es gibt verschiedene Datentypen wie z.B. `int` für ganze Zahlen oder `string` für Zeichenfolgen. Die Angabe bei der Definition ist wichtig, weil davon abhängt, wie viel Speicher für die Variable gebraucht wird. Im obigen Beispiel definieren und initialisieren wir Variablen z.B. mit dem Ausdruck `a:=19`. Mit diesem Ausdruck legen wir zwei Dinge auf einmal fest: 1. `a` soll eine neue Variable sein. 2. Der Wert von `a` soll am Anfang 23 sein. Aus dem Anfangswert bestimmt der Compiler den Typ von `a`, in diesem Fall `int`. Damit kann er Speicher reservieren und die Variable initialisieren. In der Regel werden wir Variablen auf diese Weise definieren. Manchmal ist es jedoch nützlich oder notwendig, den Typ einer Variablen explizit anzugeben. Die folgende Anweisung definiert eine Variable bom Typ `int`, ohne diese explizit zu initialisieren: ``` var a int ``` ## Rechnen mit Variablen Das Zuweisen und Auslesen von Werten in Variablen alleine ist noch nicht sehr nützlich. Im obigen Beispiel haben wir schon die Summe und das Produkt zweier Variablen ausgegeben. Genau so kann man an Variablen auch direkt ein Rechenergebnis zuweisen. ``` a = 19 + 23 a b = a + 15 b c := 3 d := c + b * a d ``` **Anmerkung:** Man beachte, dass oben für Zuweisungen zu ```a``` und ```b``` nur das Gleichheitszeichen (```=```) verwendet wird, für ```c``` und ```d``` aber der Ausdruck "```:=```". Auch hier sieht man, dass man die erste Verwendung (*Definition*) einer Variablen von allen weiteren Verwendungen unterscheiden muss. ### Ein komplexeres Beispiel: Addieren der Zahlen von 1 bis n Wir wollen die Summe der Zahlen von 1 bis zu einer gegebenen Zahl n addieren. Also z.B. für $n = 6$ die Summe $1+2+3+4+5+6$ berechnen. Für ein festes $n$ kann man natürlich einfach genau diese Summe hinschreiben. Will man flexibel bleiben, sollte man sich zuerst überlegen, wie man die Aufgabe schrittweise angehen kann. Ein Mensch berechnet solch eine Summe im Kopf, indem er Zwischenergebnisse berechnet und sich merkt. Dies machen wir auch beim Programmieren, indem wir Variablen benutzen: ``` sum := 0 sum = sum + 1 sum = sum + 2 sum = sum + 3 sum = sum + 4 sum = sum + 5 sum = sum + 6 sum ``` **Anmerkung:** An diesem Beispiel sieht man u.A., dass auf beiden Seiten einer Zuweisung auch die gleiche Variable vorkommen darf. Solche Zuweisungen liest man nicht wie mathematische Gleichungen (also Aussagen über einen Zusammenhang), sondern als Anweisungen: "Der neue Wert der Variable ```sum``` soll ihr alter Wert plus 3 sein".
github_jupyter
## Evolution of the French Five-Act Comedy in Verse Here, we re-run the notebook to get rounded summary statistics from a previous analysis. ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns from scipy.stats import shapiro # set the boundaries as we determined based on our analysis of a 10% sample def determine_period(row): if row <= 1650: period = 1 elif row >= 1651 and row <= 1695: period = 2 elif row >= 1696 and row <= 1795: period = 3 else: period = 4 return period def run_tests(test, feature): """ The function allows us to run a statistical test of our choice on the adjacent periods. Params: test - a test of our choice, e.g., mannwhitneyu. feature - str, name of the feature we want to test on. Returns: no retun, prints the result of each test """ result_one = test(period_one[feature], period_two[feature]) print('Period one and two:', '\n', feature, result_one) result_two = test(period_two[feature], period_three[feature]) print('Period two and three:', '\n', feature, result_two) result_three = test(period_three[feature], period_four[feature]) print('Period three and four:', '\n', feature, result_three) def summary(feature): mean = feature.mean() std = feature.std() median = feature.median() return mean, std, median def make_plot(feature, title): mean, std, median = summary(feature) plt.figure(figsize=(10, 7)) plt.title(title, fontsize=17) sns.distplot(feature, kde=False) mean_line = plt.axvline(mean, color='black', linestyle='solid', linewidth=2); M1 = 'Mean'; median_line = plt.axvline(median, color='green',linestyle='dashdot', linewidth=2); M2='Median' std_line = plt.axvline(mean + std, color='black', linestyle='dashed', linewidth=2); M3 = 'Standard deviation'; plt.axvline(mean - std, color='black', linestyle='dashed', linewidth=2) plt.legend([mean_line, median_line, std_line], [M1, M2, M3]) plt.show() # read the data data = pd.read_csv('../French_Comedies/Data/French_Comedies_Data.csv') data.shape # read the sample data sample_df = pd.read_csv('../French_Comedies/Data/French_Comedies_Data_Sample.csv') # exclude the comedies used for the sample analysis not_sample = data[~data['index'].isin(sample_df['index'])].copy() not_sample.shape not_sample.columns # include only five act comedies and only the comedies that are not translations/adaptations original_comedies = not_sample[(not_sample['num_acts'] ==5)& (not_sample['translation/adaptation/contrastive'] == 0)].copy() original_comedies.head() original_comedies.shape # sort by date sorted_comedies = original_comedies.sort_values(by='date') # create time periods based on our hypothesized periodization sorted_comedies['period'] = sorted_comedies['date'].apply(determine_period) # rename column names for clarity sorted_comedies = sorted_comedies.rename(columns={'num_scenes_iarkho': 'mobility_coefficient', 'percentage_non_duologues': 'percentage_non_dialogues', 'percentage_above_two_speakers': 'percentage_polylogues'}) # define the features we want to analyze features = ['num_present_characters', 'mobility_coefficient', 'sigma_iarkho', 'percentage_monologues', 'percentage_non_dialogues', 'percentage_polylogues'] ``` ## Updated Periodization: Three Periods - Period one: from 1629 to 1695 - Period two: from 1696 to 1795 - Period three: from 1796 to 1849 ``` # update the boundaries as we determined based on our hypothesis testing def determine_period(row): if row <= 1695: period = 1 elif row >= 1696 and row <= 1795: period = 2 else: period = 3 return period # update our periodization accordingly sorted_comedies['period'] = sorted_comedies['date'].apply(determine_period) ``` Descriptive Statistics for Each Period ### Number of Dramatic Characters ``` sorted_comedies.groupby('period').describe().loc[:, 'num_present_characters'][['mean', 'std', '50%','min', 'max']].round(2) ``` ### Mobility Coefficient ``` sorted_comedies.groupby('period').describe().loc[:, 'mobility_coefficient'][['mean', 'std', '50%','min', 'max']].round(2) ``` ### Standard Range of the Number of Speaking Characters (Sigma) ``` sorted_comedies.groupby('period').describe().loc[:, 'sigma_iarkho'][['mean', 'std', '50%','min', 'max']].round(2) ``` ### The Percentage of Non-Dialogues ``` sorted_comedies.groupby('period').describe().loc[:, 'percentage_non_dialogues'][['mean', 'std', '50%','min', 'max']].round(2) ``` ### The Percentage of Polylogues ``` sorted_comedies.groupby('period').describe().loc[:, 'percentage_polylogues'][['mean', 'std', '50%','min', 'max']].round(2) ``` ### The Percentage of Monologues ``` sorted_comedies.groupby('period').describe().loc[:, 'percentage_monologues'][['mean', 'std', '50%','min', 'max']].round(2) ```
github_jupyter
# E-CEO Challenge #3 Evaluation ### Weights Define the weight of each wavelength ``` w_412 = 0.56 w_443 = 0.73 w_490 = 0.71 w_510 = 0.36 w_560 = 0.01 ``` ### Run Provide the run information: * run id * run metalink containing the 3 by 3 kernel extractions * participant ``` run_id = '0000006-150701000046181-oozie-oozi-W' run_meta = 'http://sb-10-16-10-55.dev.terradue.int:50075/streamFile/ciop/run/participant-e/0000006-150701000046181-oozie-oozi-W/results.metalink?' participant = 'participant-e' ``` ### Define all imports in a single cell ``` import glob import pandas as pd from scipy.stats.stats import pearsonr import numpy import math ``` ### Manage run results Download the results and aggregate them in a single Pandas dataframe ``` !curl $run_meta | aria2c -d $participant -M - path = participant # use your path allFiles = glob.glob(path + "/*.txt") frame = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) list_.append(df) frame = pd.concat(list_) ``` Number of points extracted from MERIS level 2 products ``` len(frame.index) ``` ### Calculate Pearson For all three sites, AAOT, BOUSSOLE and MOBY, calculate the Pearson factor for each band. > Note AAOT does not have measurements for band @510 #### AAOT site ``` insitu_path = './insitu/AAOT.csv' insitu = pd.read_csv(insitu_path) frame_full = pd.DataFrame.merge(frame.query('Name == "AAOT"'), insitu, how='inner', on = ['Date', 'ORBIT']) frame_xxx= frame_full[['Rrs_413_mean', 'rho_wn_IS_412']].dropna() r_aaot_412 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @412") frame_xxx= frame_full[['Rrs_443_mean', 'rho_wn_IS_443']].dropna() r_aaot_443 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @443") frame_xxx= frame_full[['Rrs_490_mean', 'rho_wn_IS_490']].dropna() r_aaot_490 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @490") r_aaot_510 = 0 print("0 observations for band @510") frame_xxx= frame_full[['Rrs_510_mean', 'rho_wn_IS_560']].dropna() r_aaot_560 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @560") insitu_path = './insitu/BOUSS.csv' insitu = pd.read_csv(insitu_path) frame_full = pd.DataFrame.merge(frame.query('Name == "BOUS"'), insitu, how='inner', on = ['Date', 'ORBIT']) frame_xxx= frame_full[['Rrs_413_mean', 'rho_wn_IS_412']].dropna() r_bous_412 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @412") frame_xxx= frame_full[['Rrs_443_mean', 'rho_wn_IS_443']].dropna() r_bous_443 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @443") frame_xxx= frame_full[['Rrs_490_mean', 'rho_wn_IS_490']].dropna() r_bous_490 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @490") frame_xxx= frame_full[['Rrs_510_mean', 'rho_wn_IS_510']].dropna() r_bous_510 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @510") frame_xxx= frame_full[['Rrs_560_mean', 'rho_wn_IS_560']].dropna() r_bous_560 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @560") insitu_path = './insitu/MOBY.csv' insitu = pd.read_csv(insitu_path) frame_full = pd.DataFrame.merge(frame.query('Name == "MOBY"'), insitu, how='inner', on = ['Date', 'ORBIT']) frame_xxx= frame_full[['Rrs_413_mean', 'rho_wn_IS_412']].dropna() r_moby_412 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @12") frame_xxx= frame_full[['Rrs_443_mean', 'rho_wn_IS_443']].dropna() r_moby_443 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @443") frame_xxx= frame_full[['Rrs_490_mean', 'rho_wn_IS_490']].dropna() r_moby_490 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @490") frame_xxx= frame_full[['Rrs_510_mean', 'rho_wn_IS_510']].dropna() r_moby_510 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @510") frame_xxx= frame_full[['Rrs_560_mean', 'rho_wn_IS_560']].dropna() r_moby_560 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(len(frame_xxx.index)) + " observations for band @560") [r_aaot_412, r_aaot_443, r_aaot_490, r_aaot_510, r_aaot_560] [r_bous_412, r_bous_443, r_bous_490, r_bous_510, r_bous_560] [r_moby_412, r_moby_443, r_moby_490, r_moby_510, r_moby_560] r_final = (numpy.mean([r_bous_412, r_moby_412, r_aaot_412]) * w_412 \ + numpy.mean([r_bous_443, r_moby_443, r_aaot_443]) * w_443 \ + numpy.mean([r_bous_490, r_moby_490, r_aaot_490]) * w_490 \ + numpy.mean([r_bous_510, r_moby_510, r_aaot_510]) * w_510 \ + numpy.mean([r_bous_560, r_moby_560, r_aaot_560]) * w_560) \ / (w_412 + w_443 + w_490 + w_510 + w_560) r_final ```
github_jupyter
## Import packages You'll first need to install either the ```spaCY``` medium or large model! ->> terminal ```cd cds-language source ./lang101/bin/activate python -m spacy download en_core_web_md deactivate``` ``` # preprocessing import os import pandas as pd from tqdm import tqdm # nlp import spacy nlp = spacy.load("en_core_web_md") # gensim from gensim.models import Word2Vec import gensim.downloader ``` ## Using pretrained vectors in ```spaCy``` ``` doc = nlp("denmark") print(len(doc.vector)) doc.vector[0:50] ``` __Comparing individual words__ ``` banana = nlp("banana") apple = nlp("apple") scotland = nlp("scotland") denmark = nlp("denmark") ``` __Inspect word similarities__ ``` banana.similarity(apple) banana.similarity(scotland) denmark.similarity(scotland) ``` __Document similarities__ ``` doc1 = nlp("I like bananas") doc2 = nlp("I like apples") doc3 = nlp("I come from Scotland") doc4 = nlp("I live in Denmark") doc1.similarity(doc3) doc3.similarity(doc4) ``` ## Working with ```gensim``` __Download pretrained models__ ``` list(gensim.downloader.info()['models'].keys()) ``` __Download a pretrained model__ ``` pretrained_vectors = gensim.downloader.load('glove-wiki-gigaword-100') ``` __Inspect vector for specific word__ ``` pretrained_vectors['denmark'] ``` __Find most similar words to target__ ``` pretrained_vectors.most_similar('denmark') ``` __Compare specific words__ ``` pretrained_vectors.similarity('denmark', 'scotland') pretrained_vectors.similarity('denmark', 'sweden') ``` __Vector algebra__ *Man* is to *woman* as *cat* is to ... ``` pretrained_vectors.most_similar(positive=['woman', 'dog'], negative=['man'], topn=1) pretrained_vectors.most_similar(positive=['walk', 'swim'], negative=['walked'], topn=1) pretrained_vectors.most_similar(positive=['berlin', 'denmark'], negative=['germany'], topn=1) ``` __Odd one out!__ ``` pretrained_vectors.doesnt_match(["france", "germany", "dog", "japan"]) ``` ## Train your own models __Load data with pandas__ ``` filename = os.path.join("..", "data", "labelled_data", "fake_or_real_news.csv") data = pd.read_csv(filename) data.head() ``` __Tokenize with ```spaCy```__ ``` sentences = [] for post in tqdm(data["text"]): # create a temporary list tmp_list = [] # create spaCy doc object doc = nlp(post.lower()) # loop over for token in doc: tmp_list.append(token.text) # append tmp_list to sentences sentences.append(tmp_list) ``` __Train model with ```gensim```__ ``` model = Word2Vec(sentences=sentences, # input data size=50, # embedding size window=5, # context window sg=1, # cbow or skip-gram (cbow=0, sg=1) negative=5, # number of negative samples min_count=3, # remove rare words workers=6) # number of CPU processes ``` __Inspect most similar word__ ``` model.wv.most_similar('faith', topn=10) ``` __Compare words__ ``` model.wv.similarity('jesus', 'god') ```
github_jupyter
# 深度循环神经网络 :label:`sec_deep_rnn` 到目前为止,我们只讨论了具有一个单向隐藏层的循环神经网络。 其中,隐变量和观测值与具体的函数形式的交互方式是相当随意的。 只要交互类型建模具有足够的灵活性,这就不是一个大问题。 然而,对于一个单层来说,这可能具有相当的挑战性。 之前在线性模型中,我们通过添加更多的层来解决这个问题。 而在循环神经网络中,我们首先需要确定如何添加更多的层, 以及在哪里添加额外的非线性,因此这个问题有点棘手。 事实上,我们可以将多层循环神经网络堆叠在一起, 通过对几个简单层的组合,产生了一个灵活的机制。 特别是,数据可能与不同层的堆叠有关。 例如,我们可能希望保持有关金融市场状况 (熊市或牛市)的宏观数据可用, 而微观数据只记录较短期的时间动态。 :numref:`fig_deep_rnn`描述了一个具有$L$个隐藏层的深度循环神经网络, 每个隐状态都连续地传递到当前层的下一个时间步和下一层的当前时间步。 ![深度循环神经网络结构](../img/deep-rnn.svg) :label:`fig_deep_rnn` ## 函数依赖关系 我们可以将深度架构中的函数依赖关系形式化, 这个架构是由 :numref:`fig_deep_rnn`中描述了$L$个隐藏层构成。 后续的讨论主要集中在经典的循环神经网络模型上, 但是这些讨论也适应于其他序列模型。 假设在时间步$t$有一个小批量的输入数据 $\mathbf{X}_t \in \mathbb{R}^{n \times d}$ (样本数:$n$,每个样本中的输入数:$d$)。 同时,将$l^\mathrm{th}$隐藏层($l=1,\ldots,L$) 的隐状态设为$\mathbf{H}_t^{(l)} \in \mathbb{R}^{n \times h}$ (隐藏单元数:$h$), 输出层变量设为$\mathbf{O}_t \in \mathbb{R}^{n \times q}$ (输出数:$q$)。 设置$\mathbf{H}_t^{(0)} = \mathbf{X}_t$, 第$l$个隐藏层的隐状态使用激活函数$\phi_l$,则: $$\mathbf{H}_t^{(l)} = \phi_l(\mathbf{H}_t^{(l-1)} \mathbf{W}_{xh}^{(l)} + \mathbf{H}_{t-1}^{(l)} \mathbf{W}_{hh}^{(l)} + \mathbf{b}_h^{(l)}),$$ :eqlabel:`eq_deep_rnn_H` 其中,权重$\mathbf{W}_{xh}^{(l)} \in \mathbb{R}^{h \times h}$, $\mathbf{W}_{hh}^{(l)} \in \mathbb{R}^{h \times h}$和 偏置$\mathbf{b}_h^{(l)} \in \mathbb{R}^{1 \times h}$ 都是第$l$个隐藏层的模型参数。 最后,输出层的计算仅基于第$l$个隐藏层最终的隐状态: $$\mathbf{O}_t = \mathbf{H}_t^{(L)} \mathbf{W}_{hq} + \mathbf{b}_q,$$ 其中,权重$\mathbf{W}_{hq} \in \mathbb{R}^{h \times q}$和偏置$\mathbf{b}_q \in \mathbb{R}^{1 \times q}$都是输出层的模型参数。 与多层感知机一样,隐藏层数目$L$和隐藏单元数目$h$都是超参数。 也就是说,它们可以由我们调整的。 另外,用门控循环单元或长短期记忆网络的隐状态 来代替 :eqref:`eq_deep_rnn_H`中的隐状态进行计算, 可以很容易地得到深度门控循环神经网络或深度长短期记忆神经网络。 ## 简洁实现 实现多层循环神经网络所需的许多逻辑细节在高级API中都是现成的。 简单起见,我们仅示范使用此类内置函数的实现方式。 以长短期记忆网络模型为例, 该代码与之前在 :numref:`sec_lstm`中使用的代码非常相似, 实际上唯一的区别是我们指定了层的数量, 而不是使用单一层这个默认值。 像往常一样,我们从加载数据集开始。 ``` from mxnet import npx from mxnet.gluon import rnn from d2l import mxnet as d2l npx.set_np() batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) ``` 像选择超参数这类架构决策也跟 :numref:`sec_lstm`中的决策非常相似。 因为我们有不同的词元,所以输入和输出都选择相同数量,即`vocab_size`。 隐藏单元的数量仍然是$256$。 唯一的区别是,我们现在(**通过`num_layers`的值来设定隐藏层数**)。 ``` vocab_size, num_hiddens, num_layers = len(vocab), 256, 2 device = d2l.try_gpu() lstm_layer = rnn.LSTM(num_hiddens, num_layers) model = d2l.RNNModel(lstm_layer, len(vocab)) ``` ## [**训练**]与预测 由于使用了长短期记忆网络模型来实例化两个层,因此训练速度被大大降低了。 ``` num_epochs, lr = 500, 2 d2l.train_ch8(model, train_iter, vocab, lr, num_epochs, device) ``` ## 小结 * 在深度循环神经网络中,隐状态的信息被传递到当前层的下一时间步和下一层的当前时间步。 * 有许多不同风格的深度循环神经网络, 如长短期记忆网络、门控循环单元、或经典循环神经网络。 这些模型在深度学习框架的高级API中都有涵盖。 * 总体而言,深度循环神经网络需要大量的调参(如学习率和修剪) 来确保合适的收敛,模型的初始化也需要谨慎。 ## 练习 1. 基于我们在 :numref:`sec_rnn_scratch`中讨论的单层实现, 尝试从零开始实现两层循环神经网络。 1. 在本节训练模型中,比较使用门控循环单元替换长短期记忆网络后模型的精确度和训练速度。 1. 如果增加训练数据,你能够将困惑度降到多低? 1. 在为文本建模时,是否可以将不同作者的源数据合并?有何优劣呢? [Discussions](https://discuss.d2l.ai/t/2771)
github_jupyter
## Product Sentiment Data Data (public domain): https://data.world/crowdflower/brands-and-product-emotions Notebook code based on IMDB notebook from bert-sklearn/other_examples ``` import numpy as np import pandas as pd import os import sys import csv import re from sklearn import metrics from sklearn.metrics import classification_report from sklearn.utils import shuffle from ftfy import fix_text from bert_sklearn import BertClassifier from bert_sklearn import load_model print(os.getcwd()) DATAFILE = "./data/judge-cleaned-up.csv" # Prep Data def cleanup(txt): return fix_text(txt) converters = {'tweet_text': cleanup} raw_data = pd.read_csv(DATAFILE, converters=converters, encoding='unicode_escape') raw_data.head(10) ## Transform columns ## ONLY RUN THIS CELL ONCE!!! # Add columns to make the labels usable by the model # tweet_text => text # Positive / No emotion / Negative => 1, 0, -1 # Product: Apple stuff, Google stuff, NaN => Apple, Google, '' def clean_text(txt): return txt raw_data.insert(1, "text", np.vectorize(clean_text)(raw_data['tweet_text'])) def create_labels(sentiment): if sentiment.startswith('Positive'): return 1 if sentiment.startswith('Negative'): return -1 return 0 raw_data.insert(3, 'label', np.vectorize(create_labels)(raw_data['is_there_an_emotion_directed_at_a_brand_or_product'])) def get_company(product): if pd.isnull(product): return '' if 'iPad' in product or 'iPhone' in product or 'Apple' in product: return 'Apple' if 'Google' in product or 'Android' in product: return 'Google' return '' raw_data.insert(2, 'company', np.vectorize(get_company)(raw_data['emotion_in_tweet_is_directed_at'])) raw_data.head(10) # Last Data Preparation Step # Clean up characters and pull out columns of interest def clean(text): text = re.sub(r'<.*?>', '', text) text = re.sub(r"\"", "", text) return text data = raw_data.filter(['text', 'company', 'label'], axis=1) data['text'] = data['text'].transform(clean) # Split into training and test data msk = np.random.rand(len(data)) < 0.8 train = data[msk] test = data[~msk] print('Training data size: ' + str(train.shape)) print('Test data size: ' + str(test.shape)) train[:1].values ``` As you can see, each review is much longer than a sentence or two. The Google AI BERT models were trained on sequences of max length 512. Lets look at the performance for max_seq_length equal to 128, 256, and 512. ### max_seq_length = 128 ``` ## Set up data for the classifier train = train.sample(800) test = test.sample(500) print("Train data size: %d "%(len(train))) print("Test data size: %d "%(len(test))) X_train = train['text'] y_train = train['label'] X_test = test['text'] y_test = test['label'] ## Create the model model = BertClassifier(bert_model='bert-base-uncased', label_list=[-1,0,1]) model.max_seq_length = 128 model.learning_rate = 2e-05 model.epochs = 4 print(model) %%time ## Train the model using our data (this could take a while) model.fit(X_train, y_train) accy = model.score(X_test, y_test) %%time ## Test out the model with our own invented examples! examples = [ 'This Android product is not very good', 'I could not get that iPhone to work, so I sent it back. I''m really upset!', 'Another great product from the folks at Google! We really liked it a lot', 'My iPad is essential - of course I would buy another one!',' 'When in the course of human events it becomes necessary to dissolve those ties...', 'We the people, in order to form a more perfect union, establish justice, insure domestic tranquility, ...' ] print(model.predict_proba(examples)) model.save('models/model1_128_bb_uncased.mdl') ``` ### max_seq_length = 256 ``` %%time ## Don't use this one - it will take a very long time! model = BertClassifier(bert_model='bert-base-uncased', label_list=[-1,0,1]) model.max_seq_length = 256 model.train_batch_size = 32 model.learning_rate = 2e-05 model.epochs = 4 print(model) model.fit(X_train, y_train) accy = model.score(X_test, y_test) ``` ### max_seq_length = 512 ``` %%time ## Don't use this one - it will take the longest of all! model = BertClassifier(bert_model='bert-base-uncased', label_list=[-1,0,1]) model.max_seq_length = 512 # max_seq_length=512 will use a lot more GPU mem, so I am turning down batch size # and adding gradient accumulation steps model.train_batch_size = 16 model_gradient_accumulation_steps = 4 model.learning_rate = 2e-05 model.epochs = 4 print(model) model.fit(X_train, y_train) accy = model.score(X_test, y_test) ```
github_jupyter
``` from google.colab import drive drive.mount('/content/gdrive') import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import math ``` # Getting Data ``` data=pd.read_csv("/content/gdrive/MyDrive/kag_risk_factors_cervical_cancer.csv",dtype='object') data.head() ``` # Checking if there is any null value ``` data.isnull().sum() #Dropping unnecessary data data=data.drop(['STDs: Time since first diagnosis'], axis = 1) #replacing "?" with nan data = data.replace('?', np.nan) data = data.drop_duplicates() data = data.apply(pd.to_numeric, errors='coerce') data.head(13) data.isnull().sum() # for continuous variable data['Number of sexual partners'] = data['Number of sexual partners'].fillna(data['Number of sexual partners'].median()) data['First sexual intercourse'] = data['First sexual intercourse'].fillna(data['First sexual intercourse'].median()) data['Num of pregnancies'] = data['Num of pregnancies'].fillna(data['Num of pregnancies'].median()) data['Smokes'] = data['Smokes'].fillna(1) data['Smokes (years)'] = data['Smokes (years)'].fillna(data['Smokes (years)'].median()) data['Smokes (packs/year)'] = data['Smokes (packs/year)'].fillna(data['Smokes (packs/year)'].median()) data['Hormonal Contraceptives'] = data['Hormonal Contraceptives'].fillna(1) data['Hormonal Contraceptives (years)'] = data['Hormonal Contraceptives (years)'].fillna(data['Hormonal Contraceptives (years)'].median()) data['IUD'] = data['IUD'].fillna(0) # Under suggestion data['IUD (years)'] = data['IUD (years)'].fillna(0) #Under suggestion data['STDs'] = data['STDs'].fillna(1) data['STDs (number)'] = data['STDs (number)'].fillna(data['STDs (number)'].median()) data['STDs:condylomatosis'] = data['STDs:condylomatosis'].fillna(data['STDs:condylomatosis'].median()) data['STDs:cervical condylomatosis'] = data['STDs:cervical condylomatosis'].fillna(data['STDs:cervical condylomatosis'].median()) data['STDs:vaginal condylomatosis'] = data['STDs:vaginal condylomatosis'].fillna(data['STDs:vaginal condylomatosis'].median()) data['STDs:vulvo-perineal condylomatosis'] = data['STDs:vulvo-perineal condylomatosis'].fillna(data['STDs:vulvo-perineal condylomatosis'].median()) data['STDs:syphilis'] = data['STDs:syphilis'].fillna(data['STDs:syphilis'].median()) data['STDs:pelvic inflammatory disease'] = data['STDs:pelvic inflammatory disease'].fillna(data['STDs:pelvic inflammatory disease'].median()) data['STDs:genital herpes'] = data['STDs:genital herpes'].fillna(data['STDs:genital herpes'].median()) data['STDs:molluscum contagiosum'] = data['STDs:molluscum contagiosum'].fillna(data['STDs:molluscum contagiosum'].median()) data['STDs:AIDS'] = data['STDs:AIDS'].fillna(data['STDs:AIDS'].median()) data['STDs:HIV'] = data['STDs:HIV'].fillna(data['STDs:HIV'].median()) data['STDs:Hepatitis B'] = data['STDs:Hepatitis B'].fillna(data['STDs:Hepatitis B'].median()) data['STDs:HPV'] = data['STDs:HPV'].fillna(data['STDs:HPV'].median()) #for categorical data data = pd.get_dummies(data=data, columns=['Smokes','Hormonal Contraceptives','IUD','STDs', 'Dx:Cancer','Dx:CIN','Dx:HPV','Dx','Hinselmann','Citology','Schiller']) data.isnull().sum() ``` # Data Exploration ``` data.columns # 0 means not cancer affected and 1 means cancer affected cell data['Biopsy'].value_counts() data['Number of sexual partners'].value_counts() # Biopsy vs no. of sexual partners #categorical to categorical fig, (ax1,ax2) = plt.subplots(2, 1, figsize = (15, 8)) sns.countplot(x = 'Number of sexual partners', data = data, ax=ax1) sns.barplot(x = 'Number of sexual partners', y = 'Biopsy', data = data, ax=ax2) #continuous to categorical facet = sns.FacetGrid(data, hue='Biopsy',aspect=4) facet.map(sns.kdeplot,'Number of sexual partners',shade= True) facet.set(xlim=(0, data['Number of sexual partners'].max())) facet.add_legend() # Biopsy vs no. of sexual partners #categorical to categorical fig, (ax1,ax2) = plt.subplots(2, 1, figsize = (15, 8)) sns.countplot(x = 'Number of sexual partners', data = data, ax=ax1) sns.barplot(x = 'Number of sexual partners', y = 'Biopsy', data = data, ax=ax2) #continuous to categorical facet = sns.FacetGrid(data, hue='Biopsy',aspect=4) facet.map(sns.kdeplot,'Number of sexual partners',shade= True) facet.set(xlim=(0, data['Number of sexual partners'].max())) facet.add_legend() # biopsy vs no. of pregnancies sns.factorplot('Num of pregnancies','Biopsy',data = data, size=5, aspect=3) #continuous to categorical facet = sns.FacetGrid(data, hue='Biopsy', aspect=4) facet.map(sns.kdeplot,'Num of pregnancies', shade= True) facet.set(xlim=(0, data['Num of pregnancies'].max())) facet.add_legend() # list the heatmap of top correlation corr = data.corr() # number of variables for heatmap k = 15 cols = corr.nlargest(k, 'Biopsy')['Biopsy'].index cm = np.corrcoef(data[cols].values.T) plt.figure(figsize=(12, 10)) sns.set(font_scale=1.25) sns.heatmap(cm, cbar = True, annot = True, square = True, annot_kws = {'size': 10}, yticklabels = cols.values, xticklabels = cols.values) plt.show() data.describe() data.info() data.describe() data.head(75) x = data.iloc[:,:46] y = data.iloc[:,45] print(x.shape) print(y.shape) # with the following function we can select highly correlated features # it will remove the first feature that is correlated with anything other feature def correlation(dataset, threshold): col_corr = set() # Set of all the names of correlated columns corr_matrix = dataset.corr() for i in range(len(corr_matrix.columns)): for j in range(i): if abs(corr_matrix.iloc[i, j]) > threshold: # we are interested in absolute coeff value colname = corr_matrix.columns[i] # getting the name of column col_corr.add(colname) return col_corr corr_features = correlation(data, 0.7) len(set(corr_features)) corr_features # Selected features y = np.array(data['Biopsy']) x = data.drop(['Age','Number of sexual partners','First sexual intercourse','Num of pregnancies', 'Smokes (years)','Smokes_0.0','Hormonal Contraceptives (years)','IUD (years)','STDs (number)', 'STDs:cervical condylomatosis','STDs:vaginal condylomatosis','STDs:syphilis','STDs:pelvic inflammatory disease', 'STDs:genital herpes','STDs:molluscum contagiosum','STDs:AIDS','STDs:HIV','STDs:Hepatitis B','STDs:HPV', 'STDs: Time since last diagnosis','Smokes_0.0','Hormonal Contraceptives_0.0', 'STDs_0.0','Dx:Cancer_0','Dx:CIN_0','Dx_0','Hinselmann_0','Citology_0'], axis = 1 ).iloc[:] ``` # Traning & Test Dataset ``` # splitting the dataset into training and test set from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.4, random_state = 45) print(x_train.shape) print(y_train.shape) print(x_test.shape) print(y_test.shape) # MinMaxScaling from sklearn.preprocessing import MinMaxScaler # creating a minmax scaler mm = MinMaxScaler() # feeding the independent data into the scaler x_train = mm.fit_transform(x_train) x_test = mm.fit_transform(x_test) ``` # Applying machine learning algorithms # Logistic Regression ``` from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report # creating the model lr_clf = LogisticRegression() # feeding the training data into the model lr_clf.fit(x_train, y_train) # predicting the test set results y_pred = model.predict(x_test) # Calculating the accuracies print("Training accuracy :", model.score(x_train, y_train)) print("Testing accuracy :", model.score(x_test, y_test)) # classification report print(classification_report(y_test, y_pred)) # confusion matrix print(confusion_matrix(y_test, y_pred)) ``` # Logistic Regression using Hyperparameter Tuning ``` from sklearn.model_selection import GridSearchCV params = {"C": np.logspace(-4, 4, 20), "solver": ["liblinear"]} lr_clf = LogisticRegression() lr_cv = GridSearchCV(lr_clf, params, scoring="accuracy", n_jobs=-1, verbose=1, cv=5, iid=True) lr_cv.fit(x_train, y_train) best_params = lr_cv.best_params_ print(f"Best parameters: {best_params}") lr_clf = LogisticRegression(**best_params) lr_clf.fit(x_train, y_train) # predicting the test set results y_pred =lr_clf.predict(x_test) # Calculating the accuracies print("Training accuracy :", lr_clf.score(x_train, y_train)) print("Testing accuracy :", lr_clf.score(x_test, y_test)) # classification report print(classification_report(y_test, y_pred)) # confusion matrix print(confusion_matrix(y_test, y_pred)) import pickle file='cervical_tuned_LR.pkl' with open(file,'wb') as f: pickle.dump(lr_clf,f) ``` # Support Vector Classifier ``` from sklearn.svm import SVC # creating the model svm_clf = SVC() # feeding the training data into the model svm_clf.fit(x_train, y_train) # predicting the test set results y_pred = svm_clf.predict(x_test) # Calculating the accuracies print("Training accuracy :", svm_clf.score(x_train, y_train)) print("Testing accuracy :", svm_clf.score(x_test, y_test)) # classification report print(classification_report(y_test, y_pred)) # confusion matrix print(confusion_matrix(y_test, y_pred)) import pickle file='cervical_tuned_SVC.pkl' with open(file,'wb') as f: pickle.dump(svm_clf,f) ``` # Random Forest Classifier ``` from sklearn.ensemble import RandomForestClassifier # creating the model rf_clf = RandomForestClassifier() # feeding the training data into the model rf_clf.fit(x_train, y_train) # predicting the test set results y_pred = rf_clf.predict(x_test) # Calculating the accuracies print("Training accuracy :", rf_clf.score(x_train, y_train)) print("Testing accuracy :", rf_clf.score(x_test, y_test)) # classification report print(classification_report(y_test, y_pred)) # confusion matrix print(confusion_matrix(y_test, y_pred)) import pickle file='cervical_tuned_RF.pkl' with open(file,'wb') as f: pickle.dump(rf_clf,f) ``` # AdaBoost Classifier ``` from sklearn.ensemble import AdaBoostClassifier # creating the model adb_clf = AdaBoostClassifier() # feeding the training data into the model adb_clf.fit(x_train, y_train) # predicting the test set results y_pred = adb_clf.predict(x_test) # Calculating the accuracies print("Training accuracy :", adb_clf.score(x_train, y_train)) print("Testing accuracy :", adb_clf.score(x_test, y_test)) # classification report print(classification_report(y_test, y_pred)) # confusion matrix print(confusion_matrix(y_test, y_pred)) import pickle file='cervical_tuned_ADB.pkl' with open(file,'wb') as f: pickle.dump(adb_clf,f) test_score = accuracy_score(y_test, lr_clf.predict(x_test)) * 100 train_score = accuracy_score(y_train, lr_clf.predict(x_train)) * 100 results_df = pd.DataFrame(data=[["Logistic Regression", train_score, test_score]], columns=['Model', 'Training Accuracy %', 'Testing Accuracy %']) test_score = accuracy_score(y_test, svm_clf.predict(x_test)) * 100 train_score = accuracy_score(y_train, svm_clf.predict(x_train)) * 100 df=pd.DataFrame(data=[["Support Vector Classifier", train_score, test_score]], columns=['Model', 'Training Accuracy %', 'Testing Accuracy %']) results_df = results_df.append(df, ignore_index=True) test_score = accuracy_score(y_test, rf_clf.predict(x_test)) * 100 train_score = accuracy_score(y_train, rf_clf.predict(x_train)) * 100 df=pd.DataFrame(data=[["Random Forest Classifier", train_score, test_score]], columns=['Model', 'Training Accuracy %', 'Testing Accuracy %']) results_df = results_df.append(df, ignore_index=True) test_score = accuracy_score(y_test, adb_clf.predict(x_test)) * 100 train_score = accuracy_score(y_train, adb_clf.predict(x_train)) * 100 df=pd.DataFrame(data=[["AdaBoost Classifier", train_score, test_score]], columns=['Model', 'Training Accuracy %', 'Testing Accuracy %']) results_df = results_df.append(df, ignore_index=True) results_df ```
github_jupyter
# 命令式和符号式混合编程 本书到目前为止一直都在使用命令式编程,它使用编程语句改变程序状态。考虑下面这段简单的命令式程序。 ``` def add(a, b): return a + b def fancy_func(a, b, c, d): e = add(a, b) f = add(c, d) g = add(e, f) return g fancy_func(1, 2, 3, 4) ``` 和我们预期的一样,在运行语句`e = add(a, b)`时,Python会做加法运算并将结果存储在变量`e`中,从而令程序的状态发生改变。类似地,后面的两条语句`f = add(c, d)`和`g = add(e, f)`会依次做加法运算并存储变量。 虽然使用命令式编程很方便,但它的运行可能很慢。一方面,即使`fancy_func`函数中的`add`是被重复调用的函数,Python也会逐一执行这3条函数调用语句。另一方面,我们需要保存变量`e`和`f`的值直到`fancy_func`中所有语句执行结束。这是因为在执行`e = add(a, b)`和`f = add(c, d)`这2条语句之后我们并不知道变量`e`和`f`是否会被程序的其他部分使用。 与命令式编程不同,符号式编程通常在计算流程完全定义好后才被执行。多个深度学习框架,如Theano和TensorFlow,都使用了符号式编程。通常,符号式编程的程序需要下面3个步骤: 1. 定义计算流程; 2. 把计算流程编译成可执行的程序; 3. 给定输入,调用编译好的程序执行。 下面我们用符号式编程重新实现本节开头给出的命令式编程代码。 ``` def add_str(): return ''' def add(a, b): return a + b ''' def fancy_func_str(): return ''' def fancy_func(a, b, c, d): e = add(a, b) f = add(c, d) g = add(e, f) return g ''' def evoke_str(): return add_str() + fancy_func_str() + ''' print(fancy_func(1, 2, 3, 4)) ''' prog = evoke_str() print(prog) y = compile(prog, '', 'exec') exec(y) ``` 以上定义的3个函数都仅以字符串的形式返回计算流程。最后,我们通过`compile`函数编译完整的计算流程并运行。由于在编译时系统能够完整地获取整个程序,因此有更多空间优化计算。例如,编译的时候可以将程序改写成`print((1 + 2) + (3 + 4))`,甚至直接改写成`print(10)`。这样不仅减少了函数调用,还节省了内存。 对比这两种编程方式,我们可以看到以下两点。 * 命令式编程更方便。当我们在Python里使用命令式编程时,大部分代码编写起来都很直观。同时,命令式编程更容易调试。这是因为我们可以很方便地获取并打印所有的中间变量值,或者使用Python的调试工具。 * 符号式编程更高效并更容易移植。一方面,在编译的时候系统容易做更多优化;另一方面,符号式编程可以将程序变成一个与Python无关的格式,从而可以使程序在非Python环境下运行,以避开Python解释器的性能问题。 ## 混合式编程取两者之长 大部分深度学习框架在命令式编程和符号式编程之间二选一。例如,Theano和受其启发的后来者TensorFlow使用了符号式编程,Chainer和它的追随者PyTorch使用了命令式编程。开发人员在设计Gluon时思考了这个问题:有没有可能既得到命令式编程的好处,又享受符号式编程的优势?开发者们认为,用户应该用纯命令式编程进行开发和调试;当需要产品级别的计算性能和部署时,用户可以将大部分命令式程序转换成符号式程序来运行。Gluon通过提供混合式编程的方式做到了这一点。 在混合式编程中,我们可以通过使用`HybridBlock`类或者`HybridSequential`类构建模型。默认情况下,它们和`Block`类或者`Sequential`类一样依据命令式编程的方式执行。当我们调用`hybridize`函数后,Gluon会转换成依据符号式编程的方式执行。事实上,绝大多数模型都可以接受这样的混合式编程的执行方式。 本节将通过实验展示混合式编程的魅力。 ## 使用`HybridSequential`类构造模型 我们之前学习了如何使用`Sequential`类来串联多个层。为了使用混合式编程,下面我们将`Sequential`类替换成`HybridSequential`类。 ``` from mxnet import nd, sym from mxnet.gluon import nn import time def get_net(): net = nn.HybridSequential() # 这里创建HybridSequential实例 net.add(nn.Dense(256, activation='relu'), nn.Dense(128, activation='relu'), nn.Dense(2)) net.initialize() return net x = nd.random.normal(shape=(1, 512)) net = get_net() net(x) ``` 我们可以通过调用`hybridize`函数来编译和优化`HybridSequential`实例中串联的层的计算。模型的计算结果不变。 ``` net.hybridize() net(x) ``` 需要注意的是,只有继承`HybridBlock`类的层才会被优化计算。例如,`HybridSequential`类和Gluon提供的`Dense`类都是`HybridBlock`类的子类,它们都会被优化计算。如果一个层只是继承自`Block`类而不是`HybridBlock`类,那么它将不会被优化。 ### 计算性能 下面通过比较调用`hybridize`函数前后的计算时间来展示符号式编程的性能提升。这里我们对1000次`net`模型计算计时。在`net`调用`hybridize`函数前后,它分别依据命令式编程和符号式编程做模型计算。 ``` def benchmark(net, x): start = time.time() for i in range(1000): _ = net(x) nd.waitall() # 等待所有计算完成方便计时 return time.time() - start net = get_net() print('before hybridizing: %.4f sec' % (benchmark(net, x))) net.hybridize() print('after hybridizing: %.4f sec' % (benchmark(net, x))) ``` 由上述结果可见,在一个`HybridSequential`实例调用`hybridize`函数后,它可以通过符号式编程提升计算性能。 ### 获取符号式程序 在模型`net`根据输入计算模型输出后,例如`benchmark`函数中的`net(x)`,我们就可以通过`export`函数将符号式程序和模型参数保存到硬盘。 ``` net.export('my_mlp') ``` 此时生成的.json和.params文件分别为符号式程序和模型参数。它们可以被Python或MXNet支持的其他前端语言读取,如C++、R、Scala、Perl和其他语言。这样,我们就可以很方便地使用其他前端语言或在其他设备上部署训练好的模型。同时,由于部署时使用的是符号式程序,计算性能往往比命令式程序的性能更好。 在MXNet中,符号式程序指的是基于`Symbol`类型的程序。我们知道,当给`net`提供`NDArray`类型的输入`x`后,`net(x)`会根据`x`直接计算模型输出并返回结果。对于调用过`hybridize`函数后的模型,我们还可以给它输入一个`Symbol`类型的变量,`net(x)`会返回`Symbol`类型的结果。 ``` x = sym.var('data') net(x) ``` ## 使用`HybridBlock`类构造模型 和`Sequential`类与`Block`类之间的关系一样,`HybridSequential`类是`HybridBlock`类的子类。与`Block`实例需要实现`forward`函数不太一样的是,对于`HybridBlock`实例,我们需要实现`hybrid_forward`函数。 前面我们展示了调用`hybridize`函数后的模型可以获得更好的计算性能和可移植性。此外,调用`hybridize`函数后的模型会影响灵活性。为了解释这一点,我们先使用`HybridBlock`类构造模型。 ``` class HybridNet(nn.HybridBlock): def __init__(self, **kwargs): super(HybridNet, self).__init__(**kwargs) self.hidden = nn.Dense(10) self.output = nn.Dense(2) def hybrid_forward(self, F, x): print('F: ', F) print('x: ', x) x = F.relu(self.hidden(x)) print('hidden: ', x) return self.output(x) ``` 在继承`HybridBlock`类时,我们需要在`hybrid_forward`函数中添加额外的输入`F`。我们知道,MXNet既有基于命令式编程的`NDArray`类,又有基于符号式编程的`Symbol`类。由于这两个类的函数基本一致,MXNet会根据输入来决定`F`使用`NDArray`或`Symbol`。 下面创建了一个`HybridBlock`实例。可以看到在默认情况下`F`使用`NDArray`。而且,我们打印出了输入`x`和使用ReLU激活函数的隐藏层的输出。 ``` net = HybridNet() net.initialize() x = nd.random.normal(shape=(1, 4)) net(x) ``` 再运行一次前向计算会得到同样的结果。 ``` net(x) ``` 接下来看看调用`hybridize`函数后会发生什么。 ``` net.hybridize() net(x) ``` 可以看到,`F`变成了`Symbol`。而且,虽然输入数据还是`NDArray`,但在`hybrid_forward`函数里,相同输入和中间输出全部变成了`Symbol`类型。 再运行一次前向计算看看。 ``` net(x) ``` 可以看到`hybrid_forward`函数里定义的3条打印语句都没有打印任何东西。这是因为上一次在调用`hybridize`函数后运行`net(x)`的时候,符号式程序已经得到。之后再运行`net(x)`的时候MXNet将不再访问Python代码,而是直接在C++后端执行符号式程序。这也是调用`hybridize`函数后模型计算性能会提升的一个原因。但它可能的问题在于,我们损失了写程序的灵活性。在上面这个例子中,如果我们希望使用那3条打印语句调试代码,执行符号式程序时会跳过它们无法打印。此外,对于少数像`asnumpy`这样的`Symbol`所不支持的函数,以及像`a += b`和`a[:] = a + b`(需改写为`a = a + b`)这样的原地(in-place)操作,我们无法在`hybrid_forward`函数中使用并在调用`hybridize`函数后进行前向计算。 ## 小结 * 命令式编程和符号式编程各有优劣。MXNet通过混合式编程取二者之长。 * 通过`HybridSequential`类和`HybridBlock`类构建的模型可以调用`hybridize`函数将命令式程序转成符号式程序。建议大家使用这种方法获得计算性能的提升。 ## 练习 * 在本节`HybridNet`类的`hybrid_forward`函数中第一行添加`x.asnumpy()`,运行本节的全部代码,观察并分析报错的位置和错误类型。 * 如果在`hybrid_forward`函数中加入Python的`if`和`for`语句会怎么样? * 回顾前面几章中你感兴趣的模型,改用`HybridBlock`类或`HybridSequential`类实现。 ## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/1665) ![](../img/qr_hybridize.svg)
github_jupyter
# Proof of concept of Imviz requirements using glupyter/bqplot We start off by silencing warnings that can happen when loading data as well as deprecation warnings, for clarity: ``` import warnings warnings.simplefilter('ignore') ``` We also need this to display Matplotlib in the notebook later. ``` %matplotlib inline from astropy.utils.data import download_file acs_47tuc_1 = download_file('https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HST/product/jbqf03gjq_flc.fits', cache=True) acs_47tuc_2 = download_file('https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HST/product/jbqf03h1q_flc.fits', cache=True) ``` We start off by looking at some of the basic features: ``` import matplotlib.pyplot as plt from glue.plugins.wcs_autolinking.wcs_autolinking import wcs_autolink, WCSLink from jdaviz import Imviz imviz = Imviz() imviz.load_data(acs_47tuc_1, data_label='acs_47tuc_1') imviz.load_data(acs_47tuc_2, data_label='acs_47tuc_2') viewer = imviz.app.get_viewer('viewer-1') # Manually link the data. We can remove this when Imviz auto-linking issue is resolved. # This is necessary for blink to function properly. wcs_links = wcs_autolink(viewer.session.data_collection) for link in wcs_links: exists = False for existing_link in viewer.session.data_collection.external_links: if isinstance(existing_link, WCSLink): if (link.data1 is existing_link.data1 and link.data2 is existing_link.data2): exists = True break # Add only those links that don't already exist if not exists: viewer.session.data_collection.add_link(link) # Because linking happens after load, the image display is broken a little. # So, please do this manually **after** running this cell. # # 1. Uncheck both data from Data menu. # 2. Re-check both data from Data menu. imviz.app ``` Panning and zooming is possible by showing the viewer toolbar and clicking on the '+'-shaped icon, then dragging around in the image and using scrolling to zoom in and out. To change the stretch and colormap, show the **Layer** options accessible through the last icon in the viewer toolbar. We can also change these programmatically, for example the stretch: ``` viewer.state.layers[0].stretch = 'sqrt' ``` the colormap: ``` viewer.state.layers[0].cmap = plt.cm.viridis ``` the limits via the percentile option: ``` viewer.state.layers[0].percentile = 95 ``` or the limits directly: ``` viewer.state.layers[0].v_min = 0 viewer.state.layers[0].v_max = 1000 ``` Note also that in the above example there are mouse-over coordinates visible by default. It possible to make selections/regions in images and export these to astropy regions. Click on the viewer toolbar then click on the circular selection tool, and drag and click to select an interesting region on the sky. We can then export this region with: ``` regions = imviz.app.get_subsets_from_viewer('viewer-1') regions ``` Since the region is an astropy region, we can e.g. convert it to a mask: ``` mask = regions['Subset 1'].to_mask(mode='subpixels') data = imviz.app.get_data_from_viewer('viewer-1', 'acs_47tuc_1[SCI,1]') plt.imshow(mask.to_image(data.shape), origin='lower') ``` You can also programmatically control the viewer. ``` # Center the image on given pixel position. imviz.center_on((1173, 1013)) # X, Y (0-indexed) # Move the image with the given pixel offsets. imviz.offset_to(500, -100) # dX, dY # Center the image on given sky coordinates. from astropy.coordinates import SkyCoord sky = SkyCoord('00h24m07.33s -71d52m50.71s') imviz.center_on(sky) # Move the image with the given sky offsets. from astropy import units as u imviz.offset_to(0.5 * u.arcsec, -1.5 * u.arcsec, skycoord_offset=True) ```
github_jupyter
# Before we begin * Github (Github Education) * Bitbucket * Kaggle # Introduction In this week, we want to implement an Ant Colony Optimization Algorithm to solve Travelling Sales Man problem. ``` import random import math import operator import matplotlib.pyplot as plt ``` # Content * Travelling Sales Man Problem * Helper Functions * Cost & Pheromone Graph * Designing Ants * Designing ACO * Running # Travelling Sales Man Problem(TSP) The travelling salesman problem (TSP) asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?" It is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science. ![TSP Sample](figs/tsp.png) # Helper Functions \begin{align} Distance = \sqrt{ (y_2 - y_1)^2 + (x_2 - x_1)^2} \end{align} ``` def distance(city1: dict, city2: dict): return math.sqrt((city1['x'] - city2['x']) ** 2 + (city1['y'] - city2['y']) ** 2) def plot(points, path: list): x = [] y = [] for point in points: x.append(point[0]) y.append(point[1]) y = list(map(operator.sub, [max(y) for i in range(len(points))], y)) # for better visualization plt.plot(x, y, 'co') for k in range(1, len(path)): i = path[k - 1] # index of first city j = path[k] # index of next city plt.arrow(x[i], y[i], x[j] - x[i], y[j] - y[i], color='r', length_includes_head=True) plt.xlim(0, max(x) * 1.1) plt.ylim(0, max(y) * 1.1) plt.show() ``` # Prerequisites ### ACO Algorihtm ![ACO Algorithm](figs/aco_algorithm.PNG) ### Strategy ![Q Updating](figs/strategy.PNG) With $Q \in [0,1]$ ### Rho \begin{align} T_{ij}(t) \leftarrow rho * T_{ij}(t) \end{align} With $rho \in [0,1]$ ### Transition Probability ![Transition Probability](figs/transition_prob.PNG) With $\alpha, \beta \in [0,1]$ # Cost & Pheromone Graph The graph is a data structure that has the matrices that we needed to evaluate transition probability: ``` class Graph(object): def __init__(self, cost_matrix: list, rank: int): """ :param cost_matrix: :param rank: rank of the cost matrix """ self.matrix = cost_matrix self.rank = rank # noinspection PyUnusedLocal self.pheromone = [[1 / (rank * rank) for j in range(rank)] for i in range(rank)] ``` # Designing Ants ``` class Ant(object): def __init__(self, aco, graph: Graph): self.colony = aco self.graph = graph self.total_cost = 0.0 self.path = [] # path self.pheromone_delta = [] # the local increase of pheromone self.allowed = [i for i in range(graph.rank)] # nodes which are allowed for the next selection self.eta = [[0 if i == j else 1 / graph.matrix[i][j] for j in range(graph.rank)] \ for i in range(graph.rank)] # heuristic information for calculating start = random.randint(0, graph.rank - 1) # start from any node self.path.append(start) self.current = start self.allowed.remove(start) def select_next(self): denominator = 0 for i in self.allowed: denominator += self.graph.pheromone[self.current][i] ** self.colony.alpha \ * self.eta[self.current][i] ** self.colony.beta # noinspection PyUnusedLocal probabilities = [0 for i in range(self.graph.rank)] # probabilities for moving to a node in the next step for i in range(self.graph.rank): try: self.allowed.index(i) # test if allowed list contains i probabilities[i] = self.graph.pheromone[self.current][i] ** self.colony.alpha * \ self.eta[self.current][i] ** self.colony.beta / denominator except ValueError: pass # do nothing # select next node by probability roulette selected = 0 rand = random.random() for i, probability in enumerate(probabilities): rand -= probability if rand <= 0: selected = i break self.allowed.remove(selected) self.path.append(selected) self.total_cost += self.graph.matrix[self.current][selected] self.current = selected # noinspection PyUnusedLocal def update_pheromone_delta(self): self.pheromone_delta = [[0 for j in range(self.graph.rank)] for i in range(self.graph.rank)] for k in range(1, len(self.path)): i = self.path[k - 1] j = self.path[k] if self.colony.update_strategy == 1: # ant-quality system self.pheromone_delta[i][j] = self.colony.Q elif self.colony.update_strategy == 2: # ant-density system # noinspection PyTypeChecker self.pheromone_delta[i][j] = self.colony.Q / self.graph.matrix[i][j] else: # ant-cycle system self.pheromone_delta[i][j] = self.colony.Q / self.total_cost ``` # Designing ACO ``` class ACO(object): def __init__(self, ant_count: int, generations: int, alpha: float, beta: float, rho: float, q: int, strategy: int): """ :param ant_count: :param generations: :param alpha: relative importance of pheromone :param beta: relative importance of heuristic information :param rho: pheromone residual coefficient :param q: pheromone intensity :param strategy: pheromone update strategy. 0 - ant-cycle, 1 - ant-quality, 2 - ant-density """ self.Q = q self.rho = rho # Evapuration Rate self.beta = beta self.alpha = alpha self.ant_count = ant_count self.generations = generations self.update_strategy = strategy def _update_pheromone(self, graph: Graph, ants: list): for i, row in enumerate(graph.pheromone): for j, col in enumerate(row): graph.pheromone[i][j] *= self.rho # Evapuration for ant in ants: graph.pheromone[i][j] += ant.pheromone_delta[i][j] def solve(self, graph: Graph): """ :param graph: """ best_cost = float('inf') best_solution = [] for gen in range(self.generations): # noinspection PyUnusedLocal ants = [Ant(self, graph) for i in range(self.ant_count)] for ant in ants: for i in range(graph.rank - 1): ant.select_next() ant.total_cost += graph.matrix[ant.path[-1]][ant.path[0]] if ant.total_cost < best_cost: best_cost = ant.total_cost best_solution = [] + ant.path # update pheromone ant.update_pheromone_delta() self._update_pheromone(graph, ants) print('generation #{}, best cost: {}, path: {}'.format(gen, best_cost, best_solution)) return best_solution, best_cost ``` # Running ``` def main(): # Loading Data from files cities = [] points = [] with open('./data/chn31.txt') as f: for line in f.readlines(): city = line.split(' ') cities.append(dict(index=int(city[0]), x=int(city[1]), y=int(city[2]))) points.append((int(city[1]), int(city[2]))) # Calculating Cost matrix => distance between city i and j cost_matrix = [] rank = len(cities) for i in range(rank): row = [] for j in range(rank): row.append(distance(cities[i], cities[j])) cost_matrix.append(row) # Instaniate ACO, and Run aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2) graph = Graph(cost_matrix, rank) path, cost = aco.solve(graph) print('cost: {}, path: {}'.format(cost, path)) # Ploting the best cycle found plot(points, path) if __name__ == '__main__': main() ```
github_jupyter
``` import pandas as pd import nltk from nltk.tokenize import word_tokenize import tkinter as tk import requests # pprint is used to format the JSON response from pprint import pprint import os import pandas as pd import numpy as np subscription_key = "cd0cf9855b244aa28c017742ed7a904c" endpoint = "https://cpftext.cognitiveservices.azure.com/" sentiment_url = endpoint + "/text/analytics/v2.1/sentiment" language_api_url = endpoint + "/text/analytics/v2.1/languages" keyphrase_url = endpoint + "/text/analytics/v2.1/keyphrases" nltk.download('punkt') columns = ['keywords', 'urgency'] rows = [] training_data = pd.DataFrame(rows, columns=columns) training_data = pd.read_csv("cpf_processed.csv") from sklearn.feature_extraction.text import CountVectorizer u1_docs = [row['keywords'] for index,row in training_data.iterrows() if row['urgency'] == 1] vec_u1 = CountVectorizer() X_u1 = vec_u1.fit_transform(u1_docs) tdm_u1 = pd.DataFrame(X_u1.toarray(), columns=vec_u1.get_feature_names()) u2_docs = [row['keywords'] for index,row in training_data.iterrows() if row['urgency'] == 2] vec_u2 = CountVectorizer() X_u2 = vec_u2.fit_transform(u2_docs) tdm_u2 = pd.DataFrame(X_u2.toarray(), columns=vec_u2.get_feature_names()) u3_docs = [row['keywords'] for index,row in training_data.iterrows() if row['urgency'] == 3] vec_u3 = CountVectorizer() X_u3 = vec_u3.fit_transform(u3_docs) tdm_u3 = pd.DataFrame(X_u3.toarray(), columns=vec_u3.get_feature_names()) u4_docs = [row['keywords'] for index,row in training_data.iterrows() if row['urgency'] == 4] vec_u4 = CountVectorizer() X_u4 = vec_u4.fit_transform(u4_docs) tdm_u4 = pd.DataFrame(X_u4.toarray(), columns=vec_u4.get_feature_names()) u5_docs = [row['keywords'] for index,row in training_data.iterrows() if row['urgency'] == 5] vec_u5 = CountVectorizer() X_u5 = vec_u5.fit_transform(u5_docs) tdm_u5 = pd.DataFrame(X_u5.toarray(), columns=vec_u5.get_feature_names()) ## word_list_u1 = vec_u1.get_feature_names(); count_list_u1 = X_u1.toarray().sum(axis=0) freq_u1 = dict(zip(word_list_u1,count_list_u1)) word_list_u2 = vec_u2.get_feature_names(); count_list_u2 = X_u2.toarray().sum(axis=0) freq_u2 = dict(zip(word_list_u2,count_list_u2)) word_list_u3 = vec_u3.get_feature_names(); count_list_u3 = X_u3.toarray().sum(axis=0) freq_u3 = dict(zip(word_list_u3,count_list_u3)) word_list_u4 = vec_u4.get_feature_names(); count_list_u4 = X_u4.toarray().sum(axis=0) freq_u4 = dict(zip(word_list_u4,count_list_u4)) word_list_u5 = vec_u5.get_feature_names(); count_list_u5 = X_u5.toarray().sum(axis=0) freq_u5 = dict(zip(word_list_u5,count_list_u5)) ## prob_u1 = [] for word, count in zip(word_list_u1, count_list_u1): prob_u1.append(count/sum(freq_u1.values())) dict(zip(word_list_u1, prob_u1)) prob_u2 = [] for word, count in zip(word_list_u2, count_list_u2): prob_u2.append(count/sum(freq_u2.values())) dict(zip(word_list_u2, prob_u2)) prob_u3 = [] for word, count in zip(word_list_u3, count_list_u3): prob_u3.append(count/sum(freq_u3.values())) dict(zip(word_list_u3, prob_u3)) prob_u4 = [] for word, count in zip(word_list_u4, count_list_u4): prob_u4.append(count/sum(freq_u4.values())) dict(zip(word_list_u4, prob_u4)) prob_u5 = [] for word, count in zip(word_list_u5, count_list_u5): prob_u5.append(count/sum(freq_u5.values())) dict(zip(word_list_u5, prob_u5)) ## from sklearn.feature_extraction.text import CountVectorizer docs = [row['keywords'] for index,row in training_data.iterrows()] vec = CountVectorizer() X = vec.fit_transform(docs) total_features = len(vec.get_feature_names()) total_cnts_features_u1 = count_list_u1.sum(axis=0) total_cnts_features_u2 = count_list_u2.sum(axis=0) total_cnts_features_u3 = count_list_u3.sum(axis=0) total_cnts_features_u4 = count_list_u4.sum(axis=0) total_cnts_features_u5 = count_list_u4.sum(axis=0) def predict_urgency(sentence): new_word_list = word_tokenize(sentence) prob_u1_with_ls = [] for word in new_word_list: if word in freq_u1.keys(): count = freq_u1[word] else: count = 0 prob_u1_with_ls.append((count + 1)/(total_cnts_features_u1 + total_features)) u1_dict = dict(zip(new_word_list,prob_u1_with_ls)) u1_prob = training_data.groupby('urgency').count()['keywords'][1] for keyword in new_word_list: u1_prob = u1_prob * u1_dict[keyword] prob_u2_with_ls = [] for word in new_word_list: if word in freq_u2.keys(): count = freq_u2[word] else: count = 0 prob_u2_with_ls.append((count + 1)/(total_cnts_features_u2 + total_features)) u2_dict = dict(zip(new_word_list,prob_u2_with_ls)) u2_prob = training_data.groupby('urgency').count()['keywords'][2] for keyword in new_word_list: u2_prob = u2_prob * u2_dict[keyword] prob_u3_with_ls = [] for word in new_word_list: if word in freq_u3.keys(): count = freq_u3[word] else: count = 0 prob_u3_with_ls.append((count + 1)/(total_cnts_features_u3 + total_features)) u3_dict = dict(zip(new_word_list,prob_u3_with_ls)) u3_prob = training_data.groupby('urgency').count()['keywords'][3] for keyword in new_word_list: u3_prob = u3_prob * u3_dict[keyword] prob_u4_with_ls = [] for word in new_word_list: if word in freq_u4.keys(): count = freq_u4[word] else: count = 0 prob_u4_with_ls.append((count + 1)/(total_cnts_features_u4 + total_features)) u4_dict = dict(zip(new_word_list,prob_u4_with_ls)) u4_prob = training_data.groupby('urgency').count()['keywords'][4] for keyword in new_word_list: u4_prob = u4_prob * u4_dict[keyword] max_prob = max(u1_prob, u2_prob, u3_prob, u4_prob) if max_prob == u1_prob: return 1 elif max_prob == u2_prob: return 2 elif max_prob == u3_prob: return 3 elif max_prob == u4_prob: return 4 root= tk.Tk() canvas1 = tk.Canvas(root, width = 200, height = 150) canvas1.pack() entry1 = tk.Entry (root) canvas1.create_window(100, 50, window=entry1) title = tk.Label(root, text= "Enter ticket sentence to\n get urgency level!") canvas1.create_window(100, 20, window=title) def call_urgency_predictor (): x1 = entry1.get() keys = extract_keywords(x1) print("Keywords: " + keys) sentiment = extract_sentiment(x1) print("Sentiment: " + str(sentiment)) urgency_level = predict_urgency(keys) print("Original urgency: " + str(urgency_level)) # Sentiment is between 0 and 1, higher score means more positive sentiment. So, higher score means less urgent urgency_level_final = round(urgency_level + ((1 - sentiment) * 5)) print("Urgency with sentiment: " + str(urgency_level_final)) label1 = tk.Label(root, text= "Urgency Level: " + str(urgency_level_final)) canvas1.create_window(100, 120, window=label1) def enter_button(event): call_urgency_predictor() def extract_keywords(sentence): documents = {"documents": [ {"id": "1", "language": "en", "text": sentence}]} headers = {"Ocp-Apim-Subscription-Key": subscription_key} response = requests.post(keyphrase_url, headers=headers, json=documents) key_phrases = response.json() s = "" for j in range(len(response.json()['documents'][0]['keyPhrases'])): s = s + " " + response.json()['documents'][0]['keyPhrases'][j] if s == "": s = "NoKeywordsFound" return s def extract_sentiment(sentence): documents = {"documents": [ {"id": "1", "language": "en", "text": sentence}]} headers = {"Ocp-Apim-Subscription-Key": subscription_key} response = requests.post(sentiment_url, headers=headers, json=documents) key_phrases = response.json() return response.json()['documents'][0]['score'] button1 = tk.Button(text='Get urgency level', command=call_urgency_predictor) root.bind('<Return>', enter_button) canvas1.create_window(100, 80, window=button1) root.mainloop() ```
github_jupyter
<a href="https://colab.research.google.com/github/BlaiseMarvin/FaceRecognitionPaymentSystem/blob/main/TrainingFacenetConfusionMatrix1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## RE-TRAINING THE FACENET MODEL USING BLACK-FACES ``` from google.colab import drive drive.mount('/content/drive') ``` ## The Arcface loss class ``` import math as m import numpy as np from tqdm import tqdm import math import os import tensorflow as tf import tensorflow.keras from tensorflow.keras.models import * from tensorflow.keras.models import load_model from tensorflow.keras.layers import * from tensorflow.keras.layers import Dense, Flatten, Dropout, Input from tensorflow.keras.optimizers import Adam, RMSprop from tensorflow.keras.metrics import categorical_crossentropy from tensorflow.keras.preprocessing import image from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import Layer from tensorflow.keras.applications.densenet import DenseNet121 from tensorflow.keras.callbacks import * from tensorflow.keras import backend as K from tensorflow.keras import regularizers from tensorflow.keras.metrics import categorical_accuracy from tensorflow.keras import layers from tensorflow.keras import Model from sklearn.metrics import confusion_matrix from sklearn.metrics import plot_confusion_matrix import matplotlib.pyplot as plt # Original paper: https://arxiv.org/pdf/1801.07698.pdf # Original implementation: https://github.com/deepinsight/insightface # Adapted from tensorflow implementation: https://github.com/luckycallor/InsightFace-tensorflow class ArcFace(Layer): '''Custom Keras layer implementing ArcFace including: 1. Generation of embeddings 2. Loss function 3. Accuracy function ''' def __init__(self, output_dim, class_num, margin=0.5, scale=64., **kwargs): self.output_dim = output_dim self.class_num = class_num self.margin = margin self.s = scale self.cos_m = tf.math.cos(margin) self.sin_m = tf.math.sin(margin) self.mm = self.sin_m * margin self.threshold = tf.math.cos(tf.constant(m.pi) - margin) super(ArcFace, self).__init__(**kwargs) def build(self, input_shape): # Create a trainable weight variable for this layer. self.kernel = self.add_weight(name='kernel', shape=(input_shape[1], self.class_num), initializer='glorot_normal', trainable=True) super(ArcFace, self).build(input_shape) # Be sure to call this at the end def call(self, x): embeddings = tf.nn.l2_normalize(x, axis=1, name='normed_embeddings') weights = tf.nn.l2_normalize(self.kernel, axis=0, name='normed_weights') cos_t = tf.matmul(embeddings, weights, name='cos_t') return cos_t def get_logits(self, labels, y_pred): cos_t = y_pred cos_t2 = tf.square(cos_t, name='cos_2') sin_t2 = tf.subtract(1., cos_t2, name='sin_2') sin_t = tf.sqrt(sin_t2, name='sin_t') cos_mt = self.s * tf.subtract(tf.multiply(cos_t, self.cos_m), tf.multiply(sin_t, self.sin_m), name='cos_mt') cond_v = cos_t - self.threshold cond = tf.cast(tf.nn.relu(cond_v, name='if_else'), dtype=tf.bool) keep_val = self.s*(cos_t - self.mm) cos_mt_temp = tf.where(cond, cos_mt, keep_val) mask = tf.one_hot(labels, depth=self.class_num, name='one_hot_mask') inv_mask = tf.subtract(1., mask, name='inverse_mask') s_cos_t = tf.multiply(self.s, cos_t, name='scalar_cos_t') output = tf.add(tf.multiply(s_cos_t, inv_mask), tf.multiply(cos_mt_temp, mask), name='arcface_logits') return output def loss(self, y_true, y_pred): labels = K.argmax(y_true, axis=-1) logits = self.get_logits(labels, y_pred) loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) return loss def accuracy(self, y_true, y_pred): labels = K.argmax(y_true, axis=-1) logits = self.get_logits(labels, y_pred) accuracy = categorical_accuracy(y_true=labels, y_pred=logits) return accuracy def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) import os from os import listdir path="/content/drive/MyDrive/Dataset/Training/" count=0 for f in listdir(path): count=0 for nome in listdir(path+f): count+=1 print("Name: ",f,"count: ",count) import os from os import listdir path="/content/drive/MyDrive/Dataset/Validation/" count=0 for f in listdir(path): count=0 for nome in listdir(path+f): count+=1 print("Name: ",f,"count: ",count) ``` #### Setting up the Image Data Generator API ``` #Import shutil first, this package deletes ipnb_checkpoints files that create a ghost class import shutil #The next step is to delete every ipynb_checkpoints file created by colab #shutil.rmtree("/tmp/training/.ipynb_checkpoints") #be careful with shutil.rmtree() because it deletes every tree in that path. In other words, do not make mistakes. #shutil.rmtree("/tmp/testing/.ipynb_checkpoints") #specify both the training and validation directories TRAINING_DIR="/content/drive/MyDrive/Dataset/Training/" VALIDATION_DIR="/content/drive/MyDrive/Dataset/Validation/" #Initialize Image Data Generator objects, and rescale the image training_datagen=ImageDataGenerator(rescale=1/255) validation_datagen=ImageDataGenerator(rescale=1/255) #Create the image generators that create the create the classes for all images uploaded training_generator=training_datagen.flow_from_directory(TRAINING_DIR,class_mode='categorical',target_size=(160,160), shuffle=False) validation_generator=validation_datagen.flow_from_directory(VALIDATION_DIR,class_mode='categorical',target_size=(160,160), shuffle=False, batch_size=1) #Load the facenet model architecture #model=load_model('/tmp/facenet/facenet_keras.h5') ``` ## Loading the facenet Model architecture ``` model=load_model('/content/drive/MyDrive/facenet_keras (1).hdf5') #A summary of the model architecture model.summary() print("Number of layers in the base model: ", len(model.layers)) local_weights_file='/content/drive/MyDrive/weightss/facenet_keras_weights.hdf5' model.load_weights(local_weights_file) for layer in model.layers: layer.trainable=False #Specify the last layer from the architecture, that you actually want last_layer=model.get_layer('Bottleneck') last_output=last_layer.output model.summary() #Code from arcface repo #customizable arcface layer af_layer = ArcFace(output_dim=128, class_num=128, margin=0.5, scale=64.) arcface_output = af_layer(last_output) x=layers.Flatten()(arcface_output) #print(arcface_output) x = Dropout(rate=0.3)(x) x=layers.Dense(1024,activation='relu')(arcface_output) x=layers.Dense(512,activation='relu')(x) x = Dropout(rate=0.5)(x) x=layers.Dense(128,activation='relu')(x) x=layers.Dense(46,activation='softmax')(arcface_output) model=Model(model.input,x) model.compile(optimizer=RMSprop(learning_rate=0.0001),loss='categorical_crossentropy',metrics=['accuracy',tf.keras.metrics.AUC(multi_label = True), tf.keras.metrics.Recall(),tf.keras.metrics.Precision()]) #training for 100 epochs history=model.fit(training_generator,validation_data=validation_generator,epochs=500,verbose=2) ``` ### Lets visualize the output of the training phase ## 413 from 426 ``` auc=history.history['auc_1'] val_auc=history.history['val_auc_1'] acc=history.history['accuracy'] val_acc=history.history['val_accuracy'] loss=history.history['loss'] val_loss=history.history['val_loss'] recall=history.history['recall_1'] val_recall=history.history['val_recall_1'] precision=history.history['precision_1'] val_precision=history.history['val_precision_1'] epochs=range(len(acc)) plt.plot(epochs,loss,'bo',label="Training Loss") plt.plot(epochs,val_loss,'r',label="Validation Loss") plt.legend() plt.show() plt.plot(epochs,auc,'bo',label="Training AUC") plt.plot(epochs,val_auc,'r',label="Validation AUC") plt.legend() plt.figure() plt.plot(epochs,acc,'bo',label="Training Accuracy") plt.plot(epochs,val_acc,'r',label="Validation Accuracy") plt.legend() plt.show() plt.plot(epochs,recall,'bo',label="Training Recall") plt.plot(epochs,val_recall,'r',label="Validation Recall") plt.legend() plt.show() plt.plot(epochs,precision,'bo',label="Training Precision") plt.plot(epochs,val_precision,'r',label="Validation Precision") plt.legend() plt.show() from sklearn.metrics import classification_report, confusion_matrix from sklearn.metrics import plot_confusion_matrix filenames = validation_generator.filenames nb_samples = len(filenames) predict = model.predict_generator(validation_generator,steps = nb_samples) y_pred = np.argmax(predict, axis=1) print('Confusion Matrix') print(confusion_matrix(validation_generator.classes, y_pred)) target_names=list(training_generator.class_indices.keys()) print(classification_report(validation_generator.classes, y_pred, target_names=target_names)) !pip install scikit-plot import scikitplot as skplt plt.figure(figsize=(20, 20)) fig, ax = plt.subplots(figsize=(20, 20)) skplt.metrics.plot_confusion_matrix(validation_generator.classes, y_pred, normalize=True,ax=ax) plt.figure(figsize=(20, 20)) plt.show() title='Normalized confusion matrix' disp = plot_confusion_matrix(model, X_test, y_test, display_labels=target_names, cmap=plt.cm.Blues, normalize=normalize) disp.ax_.set_title(title) print(title) print(disp.confusion_matrix) plt.show() model.summary() model2=Model(model.input,model.layers[-3].output) model2.summary() import tensorflow.compat.v1 as tf tf.disable_v2_behavior() sess=tf.Session() from tensorflow.python.framework import graph_io frozen = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, ["name_of_the_output_node"]) graph_io.write_graph(frozen, '/tmp/session-frozens', 'inference_graph.pb', as_text=False) import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from keras import backend as K from keras.models import Sequential, Model sess=tf.Session() K.set_learning_phase(0) # Set the learning phase to 0 model = model2 config = model2.get_config() #weights = model2.get_weights() #model = Sequential.from_config(config) output_node = model2.output.name.split(':')[0] # We need this in the next step graph_file = "kerasFacenet.pb" ckpt_file = "kerasFacenet.ckpt" saver = tf.train.Saver(sharded=True) tf.train.write_graph(sess.graph_def, '', graph_file) #saver.save(sess, ckpt_file) from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 tf.saved_model.save(model2, "/tmp/saved-models") # Convert Keras model to ConcreteFunction full_model = tf.function(lambda x: model2(x)) full_model = full_model.get_concrete_function( tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype)) # Get frozen ConcreteFunction frozen_func = convert_variables_to_constants_v2(full_model) frozen_func.graph.as_graph_def() layers = [op.name for op in frozen_func.graph.get_operations()] #print("-" * 50) #print("Frozen model layers: ") for layer in layers: print(layer) #print("-" * 50) #print("Frozen model inputs: ") #print(frozen_func.inputs) #print("Frozen model outputs: ") #print(frozen_func.outputs) # Save frozen graph from frozen ConcreteFunction to hard drive tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir="/tmp/saved-model", name="facenet-Original-LastLayer.pb", as_text=False) ```
github_jupyter
``` %pylab inline ``` # Drawing random numbers in Python ## 1. Drawing using the rectangular distribution The prerequisite for drawing from a probability distribution is the ability to draw randomly from the rectangular or uniform distribution on $(0,1)$. For any other distribution, draws can be generated by 1) draw $\xi$ randomly from the uniform distribution 2) evaluate the inverse cumulative distribution function $G^{-1}(x)$ at $\xi$ ### Implementation in Python Uniform numbers in Python are drawn by ``` python import numpy as np xi = np.random.rand(size) ``` Standard normally distributed values ```python xi = np.random.randn(size) ``` #### Example ```python import numpy as np np.random.randn(100) np.random.rand(100,10) ``` Probability distributions are implemented in _scipy_ with inverse cumulative distributions being implemented as **ppf** for the individual probability distributions: ``` python import scipy.stats as stats # normal distribution stats.norm.ppf(q, loc = 0, scale = 1) # gamma distribution stats.gamma.ppf(q, a, loc = 0, scale = 1) # t-distribution stats.t.ppf(q, dof, loc = 0, scale = 1) # poisson distribution stats.poisson.ppf(q, mu, loc = 0) ``` ### Exercise 1.1 Using the rectangular distribution, draw 1000 random numbers from - normal distribution with mean $mu=0.2$ and standard deviation $\sigma=0.1$ - gamma distribution with shape parameter $a=2.5$ and scale parameter $s=0.2$ - t-distribution with 5 degrees of freedom, located around $3.5$ and with scale $s=0.8$ Plot a histogram for each outcome. ``` from numpy.random import rand import scipy.stats as stats ``` ## 2. Drawing using the built-in generator functions The **scipy.stats** package provides over 90 different probability distributions, each with its own random number generating function. The basic usage is 1) Import the **scipy.stats** package ``` python import scipy.stats as stats ``` 2) Call the **rvs** function of the sought probalitity distribution with size as keyword argument ``` python xi = stats.norm.rvs(size=1000) xi = stats.gamma.rvs(a, size=1000) xi = stats.t.rvs(dof, size=1000) ``` The optional keyword parameters for each distribution correspond to those of the call for the inverse cumulative distribution function. ### Exercise 1.2 Repeat the random number generation from Exercise 1.1, but now use the built-in **rvs** function for each example. ### Curvilinear trapezoidal distribution To sample from CTrap(a, b, d), make two draws $r_1$ and $r_2$ independently from the standard rectangular distribution $R(0, 1)$ and form $$ a_s = (a − d) + 2dr_1 \qquad b_s = (a+b)-a_s , $$ and $$ \xi = a_s + (b_s − a_s)r_2 . $$ In this way $a_s$ is a draw from the rectangular distribution with limits $a \pm d$. $b_s$ is then formed to ensure that the midpoint of $a_s$ and $b_s$ is the prescribed value $x = (a + b)/2$. ### Task A certificate states that a voltage X lies in the interval 10.0 V ± 0.1 V. No other information is available concerning X, except that it is believed that the magnitude of the interval endpoints is the result of rounding correctly some numerical value. On this basis, that numerical value lies between 0.05 V and 0.15 V, since the numerical value of every point in the interval (0.05, 0.15) rounded to one significant decimal digit is 0.1. The location of the interval can therefore be regarded as fixed, whereas its width is inexact. The best estimate of X is x = 10.0 V. Based on a = 9.9 V, b = 10.1 V and d = 0.05 V, sample from the PDF and calculate the best estimate and the associated uncertainty. ``` a = 9.9 b = 10.1 d = 0.05 ```
github_jupyter
``` import numpy as np import pandas as pd import seaborn as sns %matplotlib notebook import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') ``` import data and drop NAs, calculate metascore/10 and rating*10 ``` imdb = pd.read_csv("C:\\Users\\Adam\\Google Drive\\School\\ComputerScience\\intro to data science\\rotten_needles\\data\\datasets\\movies_dataset.csv") #imdb = imdb.dropna() imdb = imdb.assign(rating10=(imdb['rating']*10)) imdb = imdb.assign(metascore10=(imdb['metascore']/10)) ``` create movie profit score column ``` imdb = imdb.assign(score1=100*(imdb.gross_income-imdb.budget)/imdb.budget) imdb = imdb.assign(score2=(imdb['gross_income']-imdb['budget'])) # best score measure imdb = imdb.assign(score3=np.log(imdb['gross_income'])/np.log(imdb['budget'])) # imdb[['score2', 'name','rating','metascore']].sort_values('score2',ascending=0) ``` # Figure shows scatter of gross income against meta score and imdb rating ``` plt.figure() imdb_temp = imdb imdb_temp['scaled_gross_income'] = np.log(imdb['gross_income']) # / 1000000 sns.regplot(x = imdb['rating']*10, y = 'scaled_gross_income', data = imdb_temp, color = 'yellow') sns.regplot(x = imdb['metascore'], y = 'scaled_gross_income', data = imdb_temp, color = 'Green') sns.plt.title("Gross Income against MetaScore \ IMDB Rating - Scatter") sns.plt.xlabel("IMDB Rating, Metascore") sns.plt.ylabel("Log of Gross Income") # legend_patches = matplotlib.patches.Patch(color='green', label='label') # Plot the legend sns.plt.legend(['IMDB Ratings', 'Metascore']) # imdb.isnull().sum() ``` # Figure shows distribution of Movie Ratings ``` plt.figure() sns.countplot(x = 'rating', data = imdb) plt.xticks(rotation=60) sns.plt.title("Distribution of Movie Ratings") sns.plt.xlabel("Movie Rating") sns.plt.ylabel("Count of Ratings") ``` # Distribution of ratings by Genres ``` temp = pd.DataFrame( data = { 'type': [i for i in range(1,11) for genre in imdb.columns if 'genre' in genre], 'votes': [imdb[imdb[genre] == 1]['rating_freq.1'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.2'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.3'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.4'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.5'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.6'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.7'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.8'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.9'].mean() for genre in imdb.columns if 'genre' in genre] + [imdb[imdb[genre] == 1]['rating_freq.10'].mean() for genre in imdb.columns if 'genre' in genre] }, index= [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre]*10 ) plt.figure() sns.barplot(x = temp.index , y = 'votes',hue = 'type', data = temp) plt.xticks(rotation=45, ha='right') sns.plt.title("Distribution of Ratings by Genres") sns.plt.xlabel("Genres") sns.plt.ylabel("Number of Votes") ``` scattering stuff ``` # plt.figure() # plt.ylim([0,10]) # plt.xlim([0,10]) # sns.regplot(x ='avg_rating_per_demo.aged_under_18', y = 'avg_rating_per_demo.aged_45+', data = imdb, color = 'red') # plt.figure() # plt.ylim([0,10]) # plt.xlim([0,10]) # sns.regplot(x ='avg_rating_per_demo.aged_18-29', y = 'avg_rating_per_demo.aged_45+', data = imdb, color = 'green') # imdb.plot(kind='scatter', x='rating', y='avg_rating_per_demo.us_users'); ``` # Figure shows high correlation between opening weekend incomes and Total weekend ``` plt.figure() sns.regplot(x = 'opening_weekend_income', y = 'gross_income', data=imdb, color='seagreen') sns.plt.title("Opening weeked Incomes vs Total Incomes") sns.plt.xlabel("Opening Weekend") sns.plt.ylabel("Total") ``` correlations ``` # imdb[['metascore','critic_review_count','rating','rating_count','gross_income','rating_freq.3','rating_freq.4','rating_freq.5','rating_freq.6', # 'rating_freq.7','rating_freq.8','rating_freq.9','score2']].corr() # imdb[['avg_rating_per_demo.males','avg_rating_per_demo.females']].corr() ``` # figure shows how different age groups tend to vote the same, the diagonal shows the rating distribution of each age group ``` from pandas.tools.plotting import scatter_matrix temp = imdb[['avg_rating_per_demo.aged_under_18','avg_rating_per_demo.aged_18-29', 'avg_rating_per_demo.aged_30-44','avg_rating_per_demo.aged_45+']] temp.columns = ['-18','18-29','30-44','45+'] scatter_matrix(temp, alpha=0.2,figsize=(6,6)) plt.suptitle('Rating Scatter over Different Age Groups') ``` # figure shows that above 400K voters, the average rating is allways greater than 7 - people tend to rate when they like a movie ``` plt.figure() sns.regplot(x = 'rating_count', y = 'rating', data=imdb, color='seagreen') sns.plt.title("IMDB Rating vs Number of Votes") sns.plt.xlabel("Number of Votes") sns.plt.ylabel("IMDB Rating") ``` # figure shows the difference of males and females number of votes over different genres ``` temp = pd.DataFrame( data={ 'sex': ['Male' for genre in imdb.columns if 'genre' in genre] + ['Female' for genre in imdb.columns if 'genre' in genre], 'score': [ imdb[imdb[genre] == 1]['votes_per_demo.males'].mean() for genre in imdb.columns if 'genre' in genre ] + [ imdb[imdb[genre] == 1]['votes_per_demo.females'].mean() for genre in imdb.columns if 'genre' in genre ] }, index= [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre] + [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre] ) plt.figure() sns.barplot(x = temp.index , y = 'score',hue = 'sex', data = temp) plt.xticks(rotation=45, ha='right') sns.plt.title("Number of Votes, Difference between Male and Female") sns.plt.xlabel("Genres") sns.plt.ylabel("Number of Votes") ``` # figure shows the similarity of males and females average scores over different genres - women are more mefargenot! ``` temp1 = pd.DataFrame( data={ 'sex': ['Male' for genre in imdb.columns if 'genre' in genre] + ['Female' for genre in imdb.columns if 'genre' in genre], 'score': [ imdb[imdb[genre] == 1]['avg_rating_per_demo.males'].mean() for genre in imdb.columns if 'genre' in genre ] + [ imdb[imdb[genre] == 1]['avg_rating_per_demo.females'].mean() for genre in imdb.columns if 'genre' in genre ] }, index= [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre] + [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre] ) plt.figure() sns.barplot(x = temp1.index , y = 'score',hue = 'sex', data = temp1) plt.xticks(rotation=45, ha='right') sns.plt.title("Average Ratings, Difference between Male and Female") sns.plt.xlabel("Genres") sns.plt.ylabel("Average Rating") # plt.figure() # plt.ylim([0,10]) # plt.xlim([0,10]) # sns.regplot(x ='avg_rating_per_demo.males', y = 'avg_rating_per_demo.females', data = imdb, color = 'red') ``` # figure shows retrun on investment (gross income divided by budget) ``` temp2 = pd.DataFrame( data={ 'score': [ imdb[imdb[genre] == 1]['score1'].mean() for genre in imdb.columns if 'genre' in genre ] }, index= [genre[genre.rfind('.')+1:] for genre in imdb.columns if 'genre' in genre] ) plt.figure() sns.barplot(x = temp2.index , y = 'score', data = temp2) plt.xticks(rotation=45, ha='right') sns.plt.title("Return on Investment by Genre") sns.plt.xlabel("Genres") sns.plt.ylabel("Roi %") ```
github_jupyter
<a href="https://colab.research.google.com/github/NLP-END3/Session3/blob/main/Session3_Pytorch101_ver3a.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %load_ext tensorboard ``` ## 1. Problem Statement Write a neural network that can: 1. take 2 inputs: - an image from the MNIST dataset (say 5), and - a random number between 0 and 9, (say 7) 2. and gives two outputs: - the "number" that was represented by the MNIST image (predict 5), and - the "sum" of this number with the random number and the input image to the network (predict 5 + 7 = 12) 3. you can mix fully connected layers and convolution layers 4. you can use one-hot encoding to represent the random number input as well as the "summed" output. a. Random number (7) can be represented as 0 0 0 0 0 0 0 1 0 0 b. Sum (13) can be represented as: 1. 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 c. 0b1101 (remember that 4 digits in binary can at max represent 15, so we may need to go for 5 digits. i.e. 10010 ## 2. Importing required libraries & Checking GPU ``` import argparse import torch import torch.nn as nn import torch.optim as optim import torchvision import torch.nn.functional as F from torchvision import datasets, transforms from torch.autograd import Variable import matplotlib.pyplot as plt from torch.optim.lr_scheduler import StepLR print(torch.cuda.is_available()) # Checks if GPU is available print(torch.cuda.get_device_name(0)) # Name of GPU print(torch.cuda.device_count()) from torch.utils.tensorboard import SummaryWriter # default `log_dir` is "runs" - we'll be more specific here writer = SummaryWriter('runs/mnist_experiment_1') ``` ## 3. Importing MNIST dataset from pytorch ``` transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) mnist_train = datasets.MNIST('../data',train=True,download=True) # Train dataset mnist_test = datasets.MNIST('./data',train=False,download=True) # Test dataset ``` ## 3. Plotting few samples of the downloaded data ``` figure = plt.figure(figsize=(8, 8)) cols, rows = 10, 10 for i in range(1, cols * rows + 1): sample_idx = torch.randint(len(mnist_train), size=(1,)).item() img, label = mnist_train[sample_idx] figure.add_subplot(rows, cols, i) plt.title(label) plt.axis("off") plt.imshow(img, cmap="gray") figure.tight_layout() plt.show() #dir(mnist_train) ``` ## 4. Checking the size of the image, label and image information ``` print(f'Number of examples in training dataset :{len(mnist_train)}') print(f'Shape of the training dataset - images : {mnist_train.data.shape}') print(f'Labels in the training dataset : {mnist_train.targets}') ``` ## 5. Defining Custom Dataset Class ``` from torch.utils.data import Dataset from random import randrange # Dataset is there to be able to interact with DataLoader class MyDataset(Dataset): def __init__(self, inpDataset, transform): self.inpDataset = inpDataset self.transform = transform def __getitem__(self, index): randomNumber = randrange(10) sample_image, label = self.inpDataset[index] if self.transform: sample_image = self.transform(sample_image) sample = (sample_image,F.one_hot(torch.tensor(randomNumber),num_classes=10), label,label+randomNumber) return sample def __len__(self): return len(self.inpDataset) myData_train = MyDataset(mnist_train,transform) myData_test = MyDataset(mnist_test,transform) image,randomNumber, label1, label2 = next(iter(myData_train)) image.shape,randomNumber, label1, label2 ``` ## 6. Creating DataLoader ``` use_cuda = torch.cuda.is_available() device = torch.device("cuda") if use_cuda else torch.device("cpu") train_kwargs = {'batch_size': 1000} test_kwargs = {'batch_size': 1000} if use_cuda: cuda_kwargs = {'num_workers': 1, 'pin_memory': True, 'shuffle': True} train_kwargs.update(cuda_kwargs) test_kwargs.update(cuda_kwargs) train_loader = torch.utils.data.DataLoader(myData_train,**train_kwargs) test_loader = torch.utils.data.DataLoader(myData_test, **test_kwargs) # train_loader = torch.utils.data.DataLoader(mnist_train,**train_kwargs) # test_loader = torch.utils.data.DataLoader(mnist_test, **test_kwargs) # helper function to show an image # (used in the `plot_classes_preds` function below) def matplotlib_imshow(img, one_channel=False): if one_channel: img = img.mean(dim=0) img = img / 2 + 0.5 # unnormalize npimg = img.numpy() if one_channel: plt.imshow(npimg, cmap="Greys") else: plt.imshow(np.transpose(npimg, (1, 2, 0))) # get some random training images dataiter = iter(train_loader) images, randomNumber, labels, sum = dataiter.next() # create grid of images img_grid = torchvision.utils.make_grid(images[0:100,]) # show images matplotlib_imshow(img_grid, one_channel=True) # write to tensorboard writer.add_image('mnist_images', img_grid) %tensorboard --logdir=runs ``` ## 7. Defining Network ``` class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9226, 128) self.fc2 = nn.Linear(128, 10) self.fc3 = nn.Linear(128, 20) def forward(self, x,y): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = torch.cat((x, y), 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x1 = self.fc2(x) x2 = self.fc3(x) output1 = F.log_softmax(x1, dim=1) output2 = F.log_softmax(x2, dim=1) return output1, output2 model = Net().to(device) model ``` ## 8. Training Network ``` def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data,randomNumber,target,target1) in enumerate(train_loader): data,randomNumber,target,target1 = data.to(device), randomNumber.to(device), target.to(device), target1.to(device) optimizer.zero_grad() output, output1 = model(data,randomNumber) loss = F.nll_loss(output, target) + F.nll_loss(output1, target1) * 2 loss.backward() optimizer.step() log_interval = 10 if batch_idx % log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) writer.add_scalar('training loss', loss / log_interval, epoch * len(train_loader) + batch_idx) def test(model, device, test_loader,epoch): model.eval() test_loss = 0 correct = 0 correct1 = 0 with torch.no_grad(): for data,randomNumber,target,target1 in test_loader: data,randomNumber,target,target1 = data.to(device), randomNumber.to(device), target.to(device), target1.to(device) output, output1 = model(data,randomNumber) test_loss += F.nll_loss(output, target, reduction='sum').item() + F.nll_loss(output1, target1, reduction='sum').item() * 2 # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability pred1 = output1.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() correct1 += pred1.eq(target1.view_as(pred1)).sum().item() test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Image Accuracy: {}/{} ({:.0f}%), Sum Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset), correct1, len(test_loader.dataset), 100. * correct1 / len(test_loader.dataset))) writer.add_scalar('test loss', test_loss, epoch) optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9) epochs = 20 # scheduler = StepLR(optimizer, step_size=1, gamma=0.7) for epoch in range(1, epochs + 1): train(model, device, train_loader, optimizer, epoch) test(model, device, test_loader, epoch) # scheduler.step() ```
github_jupyter
<a href="https://colab.research.google.com/github/mishagrol/Seminar_Sobol/blob/master/Seminar_Soil_Sensitivity.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Introduction to Digital agro ## Crop simulation models ____ ### Mikhail Gasanov E-mail: Mikhail.Gasanov[a]skoltech.ru tg:@misha_grol <img src="http://drive.google.com/uc?export=view&id=1Pm5Zysv5PxYcTAQDuPe0LNz_zbE0msEW"> ## Clone utils and files from GitHub ``` # !git clone https://github.com/mishagrol/Seminar_Sobol.git # !cp -r ./Seminar_Sobol/* . ``` # How to start with PCSE/WOFOST model _____ ### Documentation: [PCSE](https://pcse.readthedocs.io/) <img style="float: right;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOIAAAAjCAYAAACJpNbGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABR0RVh0Q3JlYXRpb24gVGltZQAzLzcvMTNND4u/AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAACMFJREFUeJztnD1y20gWgD+6nJtzAsPhRqKL3AwqwQdYDpXDZfoEppNNTaWbmD7BUEXmI3EPMFCR2YI1UDQpdAPqBNzgvRZA/BGUZEnk9FeFIgj0z2ugX7/XP+jGer2mLv/8b6d+4Efgf/8KG0+Zn8XyXLx+bgEslqegcfzxSY3Irrx6bgEsFssBWsRGowGufwHAYtq7u+H6fUCOxTTWax4wBAbr+SRqNDKesOv3gN/133sW0yh927j1mucIaFWINl7PJ+OcvMcfW8Bol3iN44+mLIOsTCp3UJFfAETr+WRQcG8EOJpunEnTyDlYzycbeWr5xxq3jOF6PglK8ix9buv5xCsrAzBkMV1l5OwD/aJ4BXzV3+8F9z4gz/hTSbz8cxc84FuNvDc4VIsYA7+qohmGwAnycA194G22YqUYlZxv4vpN4AuwBv4oON5m8k3TVLnK4sYFcRyN86dWvCwnlCvFCeUVvwX8CkSZZ5eWs5mLJWE/VZThBMgpfirPk5J4f1SU4QsQ6LNP4+j9OkSUKdRiGlD87CWe3PcyR5PFdAhc1cz/joOziMoIeVF95GX1EGVY6bWhvsAeZQrm+kON80PDneD6PRbTi4LQpmJfsZieFaR1qXlXURh3y2BaBPyG63sspv0t6e+CKJTrf2YxHe8Qr6z8AXBdGbMoHgCTshgr4AiItfxljenPJGv5roCi+rGVw1TExTTWl99ThRsglfYHUnF7SMv+Bhjn4idxbhFLGiAu6gjXD3LuUBF5VzWi3CoAfMP1kxe7mNYZMT5DLFgf13eAXi3ZtvMOsUb3V3J5/mmqy+/66RbnTC1LFdfIu/kd8Qx2bTQeg2GBTPfiUF1TgHNE0QaIq/JDX9RKr/WBy/V8EhfEHWncWMO2EKV8S7UypYnYdE2r+o8gyj5MHXVYsZh+JnG7A+3LPQxR5g9II/UJ148ockmrybqm2+Qapo6gppwB8J7EM6jqaz8u0lhfkXgB58BKPam6rvEdh2kRARbTMa7/HXEfVqnW8hxxWwE+5+JJRTYd9CM90gxw/XFuMKMo/yTNDzUkLnbr6rCYnuH6N8igQ3CvNPJproDPuH6MKMd4Z5kMUjnrh98tn1if72/Ie729Vzq708L0YV3/HGmgB4iHsjOProhhd1lrEr4zaz/FvM4lolTnqWum/6jKmeuDmFb1jHylNg96hPQbhcU0wPVBXESvQI4W5aNshsK4jeOPhSOcOaThMVb48dhU8m2UlR+29ZHzrqyhLL0EaTROteGt67EYIsT6F1HXC/ikcvS00dl51PRwLaIwQtzCxGWRFnRMkT8v/SyAy8I+iliHJtDUsHHq7imipE42GtJanxdcB6mgQcm9MmKNs1m5F9MI13+n+cXZSEpAeV8mQgZqNkmU/HsuT7kf4PrGhXcK0h1SXv7iPKsJKCrDYvoV17+meMqhiDFlll7GEb4U3iseAf+k7mqksmU9qUoaj73E7TEtol3iZnks7Moai8WylUN3TS0WANbzyYv2rqxFtFheANYi7iGNRoPOrO2QGTQIu8vhU8vSmbWNDAHQD7vLYWfWbgFx2F3ee3FBZ9ZuIgMpTWAQdpeRXm9pPoPOrD3UMCtkQM4BRmF3ubG6ZZdxkOfCWsT9pU96CuX56KfOjeIFVC8Ar8NI0xuyOQJsVkWl8xzptQGPNY/6xFiLuL+0gIu0FVTrNESmbK7C7tLrzNpmPW0EeGF32UyFN19UnCAT4ZHGWWnYqDNrB4jViZBK/kbD9sLuMiBZSD8AVp1Z+0LD/NmZta+BIzOS3pm1xwBhd9kvkeEGUbQeqSmIdHhkXnGs5fIQRUxPV1x0Zm2zMuoq7C69rU/yBWAt4v7iAd86s/ZaDweZP+wBvwBOZ9b2SCrrmPzk+AWizA09j1QxMK4gZumcWKUWMvkdA56mfxN2l7GmHWk6V2F32Qi7yxaIsmnYHvkJ9zEQqAwBotQXwK2m0c+EN/Kk8zPTZiOkIWrp/xNTnpeOtYh7iFauN+k5W+0vXab6UsbyecAw229SxWiG3aVZ7NBCKrGHuneazy2iyBeIuxkjk9UDE1bzOtJ4IzbdwysNN0D6dnf9Rk3/iKSBWOnhUbASSWW+DbvLWM+HKreZ3O/r77gza5u842w6LxFrEfcTj+Jv3mK4q7Co63hE+fI6E94hUaT0cry+XushSuvoNZO2CdsCrlXJHDYVMUIUJso2BmhfL+wuV6rMvVR6AXnS1428XupaE7Hwnrqkg4cMGD0lr3NfpVegrUw1m2sN0+crNirEX1uTqiPbPoyI/QSKKmqA9I9aer+fcR2zxIj7GiMV+EYVIkZc3r5eH2rYI+0vnpBYIE/vGwUCdYM7s3agbqXJu58VIOwug86sfd2ZtSPNKwi7S9PHy4UnscCmXKuUZQRdsqbPwCHp2754pKYnW0akcZBO/x2df29XnvA//6iV8T3TSluBmOQlR+v5JNvaHixlDZRalRZifbZaAg3vIIrkmP6YVu6owI1M9x2r0vVIFCBGXNLS96Ph45IGY2ey6e1DY20UMaLGItUXoIhVvCv5tvDg2MWLqYNaoKBKWe6Z7gBR8OwAzZOyD4poBmtidlwt/gIxw/QHz0+oWKIoj19fRz8p3YOjoV8195F5l31ltZ5PfnluISyW+/IK6SPstRIiH/FaLHvLa2R+6F6f978AVsD7v0vf0HK4vNK9VfbVojSBceP4o/PcglgsD8GMmjaRbRCc1PEQIrbv45nlIfleIrs778XkrcWSZXMcXPZyqbvfxy7ckuyqHJPslJzH9c3We2ZRbx1O/07ziJbDI1FE2Qwp4n4DNzHJhkZF16+3bnwrCmi40U2eWoj7KZvobn7+YtKO1vPJVyyWPSZrER1kNU0TqfienpvlaWZR7oX+3tba6lxcX7MK3tNfo2RlpNc8tthsIFbAKYtpsA+TtRbLNp5/H4/EFXX0MOfbOGUxvbCKaDkEnl8Rq0jc1ayFjhFFjKwiWg6B/wNk+JCXXNBIXQAAAABJRU5ErkJggg=="> ``` %matplotlib inline import sys, os import pcse import pandas as pd import matplotlib import yaml matplotlib.style.use("ggplot") import matplotlib.pyplot as plt print("This notebook was built with:") print("python version: %s " % sys.version) print("PCSE version: %s" % pcse.__version__) import warnings warnings.filterwarnings("ignore") wofostPP = pcse.start_wofost(mode="wlp") ``` You have just successfully initialized a PCSE/WOFOST object in the Python interpreter, which is in its initial state and waiting to do some simulation. We can now advance the model state for example with 1 day: ``` wofostPP.run() ``` Advancing the crop simulation with only 1 day, is often not so useful so the number of days to simulate can be specified as well: ``` wofostPP.run(days=10) ``` ## Getting information about state and rate variables Retrieving information about the calculated model states or rates can be done with the `get_variable()` method on a PCSE object. For example, to retrieve the leaf area index value in the current model state you can do: ### Leaf Area Index <img src="http://drive.google.com/uc?export=view&id=14nRP6TBQJLnIQ9Tv_HEvpvIvCe9gnXOO"> ``` # Leaf Area Index at this date print(wofostPP.day) print('LAI', wofostPP.get_variable('LAI')) ``` The `get_variable()` method can retrieve any state or rate variable that is defined somewhere in the model. Finally, we can finish the crop season by letting it run until the model terminates because the crop reaches maturity or the harvest date: ``` wofostPP.run_till_terminate() ``` ## Retrieving and displaying WOFOST output We can retrieve the results of the simulation at each time step using `get_output()`. In python terms this returns a list of dictionaries, one dictionary for each time step of the the simulation results. Each dictionary contains the key:value pairs of the state or rate variables that were stored at that time step. ``` output = wofostPP.get_output() ``` The most convenient way to handle the output from WOFOST is to used the `pandas` module to convert it into a dataframe. Pandas DataFrames can be converted to a variety of formats including excel, CSV or database tables. ``` df_crop = pd.DataFrame(output).set_index('day') summary_output = wofostPP.get_summary_output() msg = "Reached maturity at {DOM} with total biomass {TAGP:.1f} kg/ha, " \ "a yield of {TWSO:.1f} kg/ha with a maximum LAI of {LAIMAX:.2f}." for crop_cycle in summary_output: print(msg.format(**crop_cycle)) fig, (axis1, axis2) = plt.subplots(nrows=1, ncols=2, figsize=(16,8)) df_crop.LAI.plot(ax=axis1, label="LAI", color='k') df_crop.TAGP.plot(ax=axis2, label="Total biomass") df_crop.TWSO.plot(ax=axis2, label="Yield") axis1.set_title("Leaf Area Index") axis2.set_title("Crop biomass") fig.autofmt_xdate() r = fig.legend() ``` # Running PCSE/WOFOST with custom input data This Jupyter notebook will show you how to read inputs from files for running PCSE/WOFOST. thanks to **Allard de Wit** **Prerequisites for running this notebook** Several packages need to be installed for running PCSE/WOFOST: 1. `PCSE` and its dependencies. See the [PCSE user guide](http://pcse.readthedocs.io/en/stable/installing.html) for more information; 2. The `pandas` module for processing and storing WOFOST output; 3. The `matplotlib` module for generating charts <img style="float: right;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOIAAAAjCAYAAACJpNbGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABR0RVh0Q3JlYXRpb24gVGltZQAzLzcvMTNND4u/AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAACMFJREFUeJztnD1y20gWgD+6nJtzAsPhRqKL3AwqwQdYDpXDZfoEppNNTaWbmD7BUEXmI3EPMFCR2YI1UDQpdAPqBNzgvRZA/BGUZEnk9FeFIgj0z2ugX7/XP+jGer2mLv/8b6d+4Efgf/8KG0+Zn8XyXLx+bgEslqegcfzxSY3Irrx6bgEsFssBWsRGowGufwHAYtq7u+H6fUCOxTTWax4wBAbr+SRqNDKesOv3gN/133sW0yh927j1mucIaFWINl7PJ+OcvMcfW8Bol3iN44+mLIOsTCp3UJFfAETr+WRQcG8EOJpunEnTyDlYzycbeWr5xxq3jOF6PglK8ix9buv5xCsrAzBkMV1l5OwD/aJ4BXzV3+8F9z4gz/hTSbz8cxc84FuNvDc4VIsYA7+qohmGwAnycA194G22YqUYlZxv4vpN4AuwBv4oON5m8k3TVLnK4sYFcRyN86dWvCwnlCvFCeUVvwX8CkSZZ5eWs5mLJWE/VZThBMgpfirPk5J4f1SU4QsQ6LNP4+j9OkSUKdRiGlD87CWe3PcyR5PFdAhc1cz/joOziMoIeVF95GX1EGVY6bWhvsAeZQrm+kON80PDneD6PRbTi4LQpmJfsZieFaR1qXlXURh3y2BaBPyG63sspv0t6e+CKJTrf2YxHe8Qr6z8AXBdGbMoHgCTshgr4AiItfxljenPJGv5roCi+rGVw1TExTTWl99ThRsglfYHUnF7SMv+Bhjn4idxbhFLGiAu6gjXD3LuUBF5VzWi3CoAfMP1kxe7mNYZMT5DLFgf13eAXi3ZtvMOsUb3V3J5/mmqy+/66RbnTC1LFdfIu/kd8Qx2bTQeg2GBTPfiUF1TgHNE0QaIq/JDX9RKr/WBy/V8EhfEHWncWMO2EKV8S7UypYnYdE2r+o8gyj5MHXVYsZh+JnG7A+3LPQxR5g9II/UJ148ockmrybqm2+Qapo6gppwB8J7EM6jqaz8u0lhfkXgB58BKPam6rvEdh2kRARbTMa7/HXEfVqnW8hxxWwE+5+JJRTYd9CM90gxw/XFuMKMo/yTNDzUkLnbr6rCYnuH6N8igQ3CvNPJproDPuH6MKMd4Z5kMUjnrh98tn1if72/Ie729Vzq708L0YV3/HGmgB4iHsjOProhhd1lrEr4zaz/FvM4lolTnqWum/6jKmeuDmFb1jHylNg96hPQbhcU0wPVBXESvQI4W5aNshsK4jeOPhSOcOaThMVb48dhU8m2UlR+29ZHzrqyhLL0EaTROteGt67EYIsT6F1HXC/ikcvS00dl51PRwLaIwQtzCxGWRFnRMkT8v/SyAy8I+iliHJtDUsHHq7imipE42GtJanxdcB6mgQcm9MmKNs1m5F9MI13+n+cXZSEpAeV8mQgZqNkmU/HsuT7kf4PrGhXcK0h1SXv7iPKsJKCrDYvoV17+meMqhiDFlll7GEb4U3iseAf+k7mqksmU9qUoaj73E7TEtol3iZnks7Moai8WylUN3TS0WANbzyYv2rqxFtFheANYi7iGNRoPOrO2QGTQIu8vhU8vSmbWNDAHQD7vLYWfWbgFx2F3ee3FBZ9ZuIgMpTWAQdpeRXm9pPoPOrD3UMCtkQM4BRmF3ubG6ZZdxkOfCWsT9pU96CuX56KfOjeIFVC8Ar8NI0xuyOQJsVkWl8xzptQGPNY/6xFiLuL+0gIu0FVTrNESmbK7C7tLrzNpmPW0EeGF32UyFN19UnCAT4ZHGWWnYqDNrB4jViZBK/kbD9sLuMiBZSD8AVp1Z+0LD/NmZta+BIzOS3pm1xwBhd9kvkeEGUbQeqSmIdHhkXnGs5fIQRUxPV1x0Zm2zMuoq7C69rU/yBWAt4v7iAd86s/ZaDweZP+wBvwBOZ9b2SCrrmPzk+AWizA09j1QxMK4gZumcWKUWMvkdA56mfxN2l7GmHWk6V2F32Qi7yxaIsmnYHvkJ9zEQqAwBotQXwK2m0c+EN/Kk8zPTZiOkIWrp/xNTnpeOtYh7iFauN+k5W+0vXab6UsbyecAw229SxWiG3aVZ7NBCKrGHuneazy2iyBeIuxkjk9UDE1bzOtJ4IzbdwysNN0D6dnf9Rk3/iKSBWOnhUbASSWW+DbvLWM+HKreZ3O/r77gza5u842w6LxFrEfcTj+Jv3mK4q7Co63hE+fI6E94hUaT0cry+XushSuvoNZO2CdsCrlXJHDYVMUIUJso2BmhfL+wuV6rMvVR6AXnS1428XupaE7Hwnrqkg4cMGD0lr3NfpVegrUw1m2sN0+crNirEX1uTqiPbPoyI/QSKKmqA9I9aer+fcR2zxIj7GiMV+EYVIkZc3r5eH2rYI+0vnpBYIE/vGwUCdYM7s3agbqXJu58VIOwug86sfd2ZtSPNKwi7S9PHy4UnscCmXKuUZQRdsqbPwCHp2754pKYnW0akcZBO/x2df29XnvA//6iV8T3TSluBmOQlR+v5JNvaHixlDZRalRZifbZaAg3vIIrkmP6YVu6owI1M9x2r0vVIFCBGXNLS96Ph45IGY2ey6e1DY20UMaLGItUXoIhVvCv5tvDg2MWLqYNaoKBKWe6Z7gBR8OwAzZOyD4poBmtidlwt/gIxw/QHz0+oWKIoj19fRz8p3YOjoV8195F5l31ltZ5PfnluISyW+/IK6SPstRIiH/FaLHvLa2R+6F6f978AVsD7v0vf0HK4vNK9VfbVojSBceP4o/PcglgsD8GMmjaRbRCc1PEQIrbv45nlIfleIrs778XkrcWSZXMcXPZyqbvfxy7ckuyqHJPslJzH9c3We2ZRbx1O/07ziJbDI1FE2Qwp4n4DNzHJhkZF16+3bnwrCmi40U2eWoj7KZvobn7+YtKO1vPJVyyWPSZrER1kNU0TqfienpvlaWZR7oX+3tba6lxcX7MK3tNfo2RlpNc8tthsIFbAKYtpsA+TtRbLNp5/H4/EFXX0MOfbOGUxvbCKaDkEnl8Rq0jc1ayFjhFFjKwiWg6B/wNk+JCXXNBIXQAAAABJRU5ErkJggg=="> ## Reading model parameters ### Crop parameters ``` data_dir = 'data/' from pcse.fileinput import CABOFileReader cropfile = os.path.join(data_dir, 'crop', 'SUG0601.crop') cropdata = CABOFileReader(cropfile) #potato from pcse.fileinput import CABOFileReader cropfile_potato = os.path.join(data_dir, 'crop', 'POT701.CAB') cropdata_potato = CABOFileReader(cropfile_potato) # Number of parameters for our crop len(cropdata_potato) ``` ### Soil parameters The soildata dictionary provides the parameter name/value pairs related to the soil type and soil physical properties. The number of parameters is variable depending on the soil water balance type that is used for the simulation. For this example, we will use the water balance for freely draining soils and use the soil file for medium fine sand: `ec3.soil`. This file is also taken from the soil files in the [WOFOST Control Centre](http://www.wageningenur.nl/wofost). ``` soilfile = os.path.join(data_dir, 'soil', 'ec3.soil') soildata = CABOFileReader(soilfile) print(soildata) ``` ### Site parameters The site parameters provide ancillary parameters that are not related to the crop or the soil. Examples are the initial conditions of the water balance such as the initial soil moisture content (WAV) and the initial and maximum surface storage (SSI, SSMAX). Also the atmospheric $CO_{2}$ concentration is a typical site parameter. For the moment, we can define these parameters directly on the Python commandline as a simple python dictionary. However, it is more convenient to use the `WOFOST71SiteDataProvider` that documents the site parameters and provides sensible defaults: ``` from pcse.util import WOFOST71SiteDataProvider sitedata = WOFOST71SiteDataProvider(WAV=100, CO2=360) print(sitedata) ``` ### Packaging all parameters Finally, we need to pack the different sets of parameters into one variable using the `ParameterProvider`. This is needed because PCSE expects one variable that contains all parameter values. Using this approach has the additional advantage that parameter value can be easily overridden in case of running multiple simulations with slightly different parameter values: ``` from pcse.base import ParameterProvider parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata) ``` ## Agromanagement The agromanagement inputs provide the start date of the agricultural campaign, the start_date/start_type of the crop simulation, the end_date/end_type of the crop simulation and the maximum duration of the crop simulation. The latter is included to avoid unrealistically long simulations for example as a results of a too high temperature sum requirement. The agromanagement inputs are defined with a special syntax called [YAML](http://yaml.org/) which allows to easily create more complex structures which is needed for defining the agromanagement. The agromanagement file for sugar beet in Wageningen `sugarbeet_calendar.agro` can be read with the `YAMLAgroManagementReader`: ``` from pcse.fileinput import YAMLAgroManagementReader #crop rotation for Moscow region agromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar_Moscow_short.agro') #agromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar.agro') agromanagement = YAMLAgroManagementReader(agromanagement_file) print(agromanagement) ``` We can create a crop rotation in the model ``` K_kg = 60 P_kg = 60 N_kg = 120 year=2017 yaml_agro = f""" - {year}-05-01: CropCalendar: crop_name: 'sugar-beet' variety_name: 'sugar-beet-601' crop_start_date: {year}-05-20 crop_start_type: sowing crop_end_date: crop_end_type: maturity max_duration: 250 TimedEvents: - event_signal: apply_npk name: Timed N/P/K application table comment: All fertilizer amounts in kg/ha events_table: - {year}-06-22: {{N_amount : {N_kg}, P_amount: {P_kg}, K_amount: {K_kg}}} StateEvents: null """ agromanagement = yaml.safe_load(yaml_agro) print(yaml_agro) #crop_end_date: {year_date_1}-11-15 ``` ## Daily weather observations Daily weather variables are needed for running the simulation. There are several data providers in PCSE for reading weather data, see the section on [weather data providers](http://pcse.readthedocs.io/en/stable/reference_guide.html#weather-data-providers) to get an overview. For this example we will use weather data from an excel file which provides daily weather data for Wageningen for the period 2004 to 2008. We will read the data from the file using the ExcelWeatherDataProvider: ### NASA Weather Data Provider from NASA [DataBase](https://power.larc.nasa.gov/) ``` #NASA Weather system #Sometimes it does not work (server), upload excel file from pcse.db import NASAPowerWeatherDataProvider weather = NASAPowerWeatherDataProvider(51, 5, force_update=True) print(weather) ``` ### Problems with missing days (~1-5 %) ``` def weather_loader(latitude, longitude): path = './data/meteo/' #API request to NASA database weather = NASAPowerWeatherDataProvider(latitude, longitude, force_update=True) # Print done if downloaded print('____DONE_____','latitude',latitude, 'longitude',longitude,'____') # export pcse.weather format to pandas df df_weather = pd.DataFrame(weather.export()) #print('initial number of days:', len(df_weather)) #create full range of dates r = pd.date_range(start=df_weather.DAY.min(), end=df_weather.DAY.max()) #extend range of dates full_range_weather = df_weather.set_index('DAY').reindex(r).rename_axis('DAY').reset_index() missing_days = (full_range_weather.isna()).sum().sum() print('num_of_missing_days', missing_days) #fill weather with fill forward method in pandas filled_weather = full_range_weather.fillna(method='ffill', axis=0) #save as csv file filled_weather=filled_weather[['DAY', 'IRRAD', 'TMIN', 'TMAX', 'VAP', 'WIND', 'RAIN']] filled_weather['SNOWDEPTH'] = 'NaN' filled_weather[['IRRAD']] = filled_weather[['IRRAD']]/1000. filled_weather[['VAP']] = filled_weather[['VAP']]/10. filled_weather.DAY=filled_weather.DAY.dt.strftime('%Y%m%d') text = open(path+"pattern.csv", "r") text = ''.join([i for i in text]).replace("1111", str(weather.longitude)) text = ''.join([i for i in text]).replace("2222", str(weather.latitude)) text = ''.join([i for i in text]).replace("3333", str(weather.elevation)) text = ''.join([i for i in text]).replace("4444", str(weather.angstA)) text = ''.join([i for i in text]).replace("5555", str(weather.angstB)) x = open(path+f'NASA_weather_latitude_{latitude}_longitude_{longitude}.csv',"w") x.writelines(text) x.close() path_to_save_csv_file = path+f'NASA_weather_latitude_{latitude}_longitude_{longitude}.csv' filled_weather.to_csv(path_to_save_csv_file, mode='a', header=False, index=False) #add info to weather database and save it to csv #LOAD WEATHER as csv file weather = pcse.fileinput.CSVWeatherDataProvider(path_to_save_csv_file) return weather weather = weather_loader(55,55) df_weather = pd.DataFrame(weather.export()) fig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16,4)) df_weather.set_index('DAY')['ET0'][-365:].plot(ax=ax1, label='ET0') df_weather.set_index('DAY')['TMAX'][-365:].plot(ax=ax2, label='T MAX') ax1.set_title('ET 0') ax2.set_title('T°C Max') ``` ## Importing, initializing and running a PCSE model Internally, PCSE uses a simulation engine to run a crop simulation. This engine takes a configuration file that specifies the components for the crop, the soil and the agromanagement that need to be used for the simulation. So any PCSE model can be started by importing the engine and initializing it with a given configuration file and the corresponding parameters, weather data and agromanagement. However, as many users of PCSE only need a particular configuration (for example the WOFOST model for potential production), preconfigured Engines are provided in `pcse.models`. For the sugarbeet example we will import the WOFOST model for water-limited simulation under freely draining soil conditions: ``` from pcse.models import Wofost71_WLP_FD wofsim = Wofost71_WLP_FD(parameters, weather, agromanagement) wofsim.run_till_terminate() df_results = pd.DataFrame(wofsim.get_output()) df_results = df_results.set_index("day") df_results.tail() ``` We can then run the simulation and retrieve the time series of daily simulation output using the get_output() method on the WOFOST object. Finally, we convert the simulation results to a pandas dataframe: ``` summary_output = wofsim.get_summary_output() wofsim.get_summary_output() msg = "Reached maturity at {DOM} with total biomass {TAGP} kg/ha "\ "and a yield of {TWSO} kg/ha." print(msg.format(**summary_output[0])) ``` # Sensitivity analysis of models ___ <img src="http://drive.google.com/uc?export=view&id=1uijz-Bm9Mxwv8eI6CL8QsumiP7ISqnFo"> <img src="http://drive.google.com/uc?export=view&id=1dPvni3r4B3FqMFKugxtT8GfH1_W1jNNR"> ``` # !pip install SALib ``` ## Sobol’ Sequences versus Random numbers and regular grid <img src="http://drive.google.com/uc?export=view&id=1ezjA8aa50P08EUybwdDyo8JKCP7lU7zw"> ``` from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np ``` __Docs [SALib](https://salib.readthedocs.io/en/latest/#)__ In this example, we will perform a Sobol’ sensitivity analysis of the _Ishigami_ function, shown below. The _Ishigami_ function is commonly used to test uncertainty and sensitivity analysis methods because it exhibits strong nonlinearity and nonmonotonicity. $f(x)=\sin \left(x_{1}\right)+ \text{a}\, \operatorname{sin}^{2}\left(x_{2}\right)+ \text{b}\, x_{3}^{4} \sin \left(x_{1}\right)$ ``` problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-np.pi, np.pi]]*3 } # Generate samples param_values = saltelli.sample(problem, 10, calc_second_order=True) param_values.shape ``` Here, `param_values` is a NumPy matrix. If we run `param_values.shape`, we see that the matrix is **8000 by 3**. The Saltelli sampler generated 8000 samples. The Saltelli sampler generates $N∗(2D+2)$ samples, where in this example $N$ is 1000 (the argument we supplied) and $D$ is 3 (the number of model inputs). The keyword argument `calc_second_order=False` will exclude second-order indices, resulting in a smaller sample matrix with $N∗(D+2)$ rows instead. ``` # Run model (example) Y = Ishigami.evaluate(param_values) # Perform analysis Si = sobol.analyze(problem, Y, print_to_console=True) # Returns a dictionary with keys 'S1', 'S1_conf', 'ST', and 'ST_conf' # (first and total-order indices with bootstrap confidence intervals) T_Si, first_Si, (idx, second_Si) = sobol.Si_to_pandas_dict(Si) ``` Consider the model output as \begin{eqnarray*} Y=f(X)=f\left(X_{1}, \ldots, X_{p}\right), \end{eqnarray*} where $f$ in our case part of agro-model simulator, $X$ are $p$ varied input parameters and $Y$ is the predicted output. Following the techniques by Sobol we represent the multi-variate random function $f$ using Hoeffding decomposition: \begin{equation} f(X_1,\dots,X_p) = f_0 + \sum_i^p f_i + \sum_i^p\sum_{j>i}^p f_{ij} + \dots + f_{1\dots p}, \end{equation} where $f_0$ is a constant term, $f_i = f_i(X_i)$ denotes main effects, $f_{ij} = f_{ij}(X_i, X_j)$ and others describe higher-order interactions. These terms can be written as \begin{equation*} \begin{split} f_0 &= E(Y),\\ f_i &= E_{X_{\sim i}}(Y | X_i) - E(Y),\\ f_{ij} &= E_{X_{\sim ij}}(Y | X_i, X_j) - f_i - f_j - f_0,\\ \dots \end{split} \end{equation*} where $E$ is mathematical expectation and $X_{\sim i}$ denotes all parameters except $i^\text{th}$. Under the assumption that the input parameters are independent, total variance $V(Y)$ of the crop yield can be decomposed as follows: \begin{equation*} V(Y) = \sum_i^p V_i + \sum_i^p\sum_{j>i}^p V_{ij} + \dots + V_{12\dots p}, \end{equation*} where partial variances are \begin{equation*} \begin{split} V_i &= V[f_i(X_i)] = V_{X_i}\left[E_{X_{\sim i}}(Y | X_i)\right],\\ V_{ij} &= V[f_{ij}(X_i,X_j)] = V_{X_iX_j}\left[E_{X_{\sim ij}}(Y | X_i, X_j)\right] - V_i - V_j,\\ \dots \end{split} \end{equation*} ## Sobol index (first order, second order, total index) This way, sensitivity indices (SI) can be introduced as \begin{equation} \Large S_i = \frac{V_i}{V(Y)},~S_{ij} = \frac{V_{ij}}{V(Y)},~\dots \end{equation} In order to incorporate all of the interactions for a particular parameter, one can compute the total effect index: \begin{equation} S_{T_i} = \frac{E_{X_{\sim i}}\left[V_{X_i}(Y|X_{\sim i})\right]}{V(Y)} = 1 - \frac{V_{X_{\sim i}}\left[E_{X_i}(Y | X_{\sim i})\right]}{V(Y)} \end{equation} From this assumption we can conclude: \begin{equation} \Large 0 \leq S_i \leq S_{T_i} \leq 1 \end{equation} More - * [Wiki](https://en.wikipedia.org/wiki/Sobol_sequence) * [Habr](https://habr.com/ru/post/440892/) * Feature selection [Skoltech ML 2020](https://github.com/adasegroup/ML2020_lectures/blob/master/lecture9/Lecture_9_Model_Feature_Selection_Sensitivity.pdf) # Sensitivity analysis of WOFOST model <img src="http://drive.google.com/uc?export=view&id=1OPZ0xIFpc8Ku3wtt6XffKy2QKLashDWP"> ## Install modules ``` from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np import pandas as pd ``` ## Parameters ``` NPK = { 'num_vars':3, 'names':['N_kg', 'P_kg', 'K_kg'], 'bounds':[[30., 60.], [60., 90.], [100., 130.]] } Soil_parameters = { 'num_vars':5, 'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'], 'bounds':[[0.7, 1.3], [0.1, 0.5], [0.2, 0.6], [0.04, 0.08], [22.5, 27.5]]} ``` ## Generate input parameters ``` param_values = saltelli.sample(Soil_parameters, 10) ``` $n = N \times (D \times 2 +2)$ ``` param_values.shape ``` ## Loop for yield prediction ``` from pcse.fileinput import YAMLAgroManagementReader agromanagement_file = os.path.join(data_dir, 'agro', './sugarbeet_calendar.agro') agromanagement = YAMLAgroManagementReader(agromanagement_file) #print(agromanagement) Soil_parameters = { 'num_vars':5, 'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'], 'bounds':[[0.7, 1.3], [0.1, 0.5], [0.2, 0.6], [0.04, 0.08], [22.5, 27.5]]} param_values = saltelli.sample(Soil_parameters, N=10, calc_second_order=True) ``` Soil parameters in [PCSE model](https://pcse.readthedocs.io/en/stable/code.html?highlight=K0#pcse.soil.WaterbalanceFD) ``` def sensitivity_soil(soil_parameters): SMV, SMFCF, SM0, CRAIRC, K0 = soil_parameters soildata['SMV'] = SMV soildata['SMFCF'] = SMFCF soildata['SM0'] = SM0 soildata['CRAIRC'] = CRAIRC soildata['K0'] = K0 parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata) wofsim = Wofost71_WLP_FD(parameters, wdp, agromanagement) wofsim.run_till_terminate() #df_results = pd.DataFrame(wofsim.get_output()) #df_results = df_results.set_index("day") #df_results.tail() summary_output = wofsim.get_summary_output() yield_list.append(summary_output[0]['TWSO']) %%time yield_list = [] param_values = saltelli.sample(Soil_parameters, 10, calc_second_order=True) for step in range(len(param_values)): sensitivity_soil(param_values[step]) print(param_values[step]) np_yield = np.array(yield_list) Si = sobol.analyze(Soil_parameters, np_yield, print_to_console=False) Si_dict = dict(Si) Si_df = pd.DataFrame() Si_df = Si_df.append(pd.Series(Si_dict['S1']), ignore_index=True) Si_df = Si_df.append(pd.Series(Si_dict['ST']), ignore_index=True) Si_df = Si_df.append(pd.Series(Si_dict['S1_conf']), ignore_index=True) Si_df = Si_df.append(pd.Series(Si_dict['ST_conf']), ignore_index=True) Si_df = Si_df.T Si_df.columns = ['Si', 'ST', 'Si_conf', 'ST_conf'] Si_df.rename(index={0:'SMV',1:'SMFCF', 2:'SM0', 3:'CRAIRC', 4:'K0'}, inplace=True) Si_df ``` Is it ok? \begin{equation} \Large 0 \leq S_i \leq S_{T_i} \leq 1 \end{equation} ### For 5 years ``` def sensitivity_weather(year): K_kg = 60 P_kg = 60 N_kg = 120 year_date=year print(year) print(year_date) yaml_agro = f""" - {year_date}-06-01: CropCalendar: crop_name: 'sugar-beet' variety_name: 'sugar-beet-601' crop_start_date: {year_date}-06-02 crop_start_type: emergence crop_end_date: {year_date}-10-15 crop_end_type: harvest max_duration: 300 TimedEvents: - event_signal: apply_npk name: Timed N/P/K application table comment: All fertilizer amounts in kg/ha events_table: - {year_date}-06-22: {{N_amount : {N_kg}, P_amount: {P_kg}, K_amount: {K_kg}}} StateEvents: null """ agromanagement = yaml.safe_load(yaml_agro) parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata) wofsim = Wofost71_WLP_FD(parameters, moscow_weather, agromanagement) wofsim.run_till_terminate() summary_output = wofsim.get_summary_output() yield_list_weather.append(summary_output[0]['TWSO']) ``` ## Visualizing simulation results Finally, we can generate some figures of WOFOST variables such as the development (DVS), total biomass (TAGP), leaf area index (LAI) and root-zone soil moisture (SM) using the MatPlotLib plotting package: ``` fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,10)) for var, ax in zip(["DVS", "TWSO", "LAI", "SM"], axes.flatten()): ax.plot_date(df_results.index, df_results[var], 'b-') ax.set_title(var) fig.autofmt_xdate() ``` # Visualization for sensitivity analysis Plots by [Water programming group](https://waterprogramming.wordpress.com/2019/08/27/a-python-implementation-of-grouped-radial-convergence-plots-to-visualize-sobol-sensitivity-analysis-results/) How to repeat: [Repo of SampleVIS](https://github.com/charlesrouge/SampleVis) ``` import numpy as np from SALib.analyze import sobol from SALib.sample import saltelli from fishery import fish_game import matplotlib.pyplot as plt import itertools import math ``` ### Why number of samples is important? ``` # Set up dictionary with system parameters problem = { 'num_vars': 6, 'names': ['a', 'b', 'c','h', 'K','m'], 'bounds': [[ 0.002, 2], [0.005, 1], [0.2, 1], [0.001, 1], [100, 5000], [0.1, 1.5]] } # Array with n's to use nsamples = np.arange(50, 500, 50) # Arrays to store the index estimates S1_estimates = np.zeros([problem['num_vars'],len(nsamples)]) ST_estimates = np.zeros([problem['num_vars'],len(nsamples)]) # Loop through all n values, create sample, evaluate model and estimate S1 & ST for i in range(len(nsamples)): print('n= '+ str(nsamples[i])) # Generate samples sampleset = saltelli.sample(problem, nsamples[i],calc_second_order=False) # Run model for all samples output = [fish_game(*sampleset[j,:]) for j in range(len(sampleset))] # Perform analysis results = sobol.analyze(problem, np.asarray(output), calc_second_order=False,print_to_console=False) # Store estimates ST_estimates[:,i]=results['ST'] S1_estimates[:,i]=results['S1'] np.save('ST_estimates.npy', ST_estimates) np.save('S1_estimates.npy', S1_estimates) S1_estimates = np.load('S1_estimates.npy') ST_estimates = np.load('ST_estimates.npy') # Generate figure showing evolution of indices fig = plt.figure(figsize=(18,9)) ax1 = fig.add_subplot(1,2,1) handles = [] for j in range(problem['num_vars']): handles += ax1.plot(nsamples, S1_estimates[j,:], linewidth=5) ax1.set_title('Evolution of S1 index estimates', fontsize=20) ax1.set_ylabel('S1', fontsize=18) ax1.set_xlabel('Number of samples (n)', fontsize=18) ax1.tick_params(axis='both', which='major', labelsize=14) ax2 = fig.add_subplot(1,2,2) for j in range(problem['num_vars']): ax2.plot(nsamples, ST_estimates[j,:], linewidth=5) ax2.set_title('Evolution of ST index estimates', fontsize=20) ax2.set_ylabel('ST', fontsize=18) ax2.tick_params(axis='both', which='major', labelsize=14) ax2.set_xlabel('Number of samples (n)', fontsize=18) fig.legend(handles, problem['names'], loc = 'right', fontsize=11) plt.show() #plt.savefig('indexevolution.png') # Calculate parameter rankings S1_ranks = np.zeros_like(S1_estimates) ST_ranks = np.zeros_like(ST_estimates) for i in range(len(nsamples)): orderS1 = np.argsort(S1_estimates[:,i]) orderST = np.argsort(ST_estimates[:,i]) S1_ranks[:,i] = orderS1.argsort() ST_ranks[:,i] = orderST.argsort() # Generate figure showing evolution of ranks fig = plt.figure(figsize=(18,9)) ax1 = fig.add_subplot(1,2,1) handles = [] for j in range(problem['num_vars']): handles += ax1.plot(nsamples, S1_ranks[j,:], linewidth=3) ax1.set_title('Parameter ranking based on S1', fontsize=20) ax1.set_ylabel('S1', fontsize=18) ax1.set_xlabel('Number of samples (n)', fontsize=18) ax1.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1)) ax1.tick_params(axis='both', which='major', labelsize=14) ax2 = fig.add_subplot(1,2,2) for j in range(problem['num_vars']): ax2.plot(nsamples, ST_ranks[j,:], linewidth=3) ax2.set_title('Parameter ranking based on ST', fontsize=20) ax2.set_ylabel('ST', fontsize=18) ax2.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1)) ax2.tick_params(axis='both', which='major', labelsize=14) ax2.set_xlabel('Number of samples (n)', fontsize=18) fig.legend(handles, problem['names'], loc = 'right', fontsize=14) #plt.show() #plt.savefig('rankingevolution.png') ``` ## Radial plot for SA ``` import numpy as np import itertools import matplotlib.pyplot as plt import seaborn as sns import math from numpy import genfromtxt import matplotlib.patches as mpatches import matplotlib.pyplot as plt sns.set_style('whitegrid', {'axes_linewidth': 0, 'axes.edgecolor': 'white'}) ``` ## Plot function ``` def is_significant(value, confidence_interval, threshold="conf"): if threshold == "conf": return value - abs(confidence_interval) > 0 else: return value - abs(float(threshold)) > 0 def grouped_radial(SAresults, parameters, radSc=2.0, scaling=1, widthSc=0.5, STthick=1, varNameMult=1.3, colors=None, groups=None, gpNameMult=1.5, threshold="conf"): # Derived from https://github.com/calvinwhealton/SensitivityAnalysisPlots fig, ax = plt.subplots(1, 1) color_map = {} # initialize parameters and colors if groups is None: if colors is None: colors = ["k"] for i, parameter in enumerate(parameters): color_map[parameter] = colors[i % len(colors)] else: if colors is None: colors = sns.color_palette("deep", max(3, len(groups))) for i, key in enumerate(groups.keys()): #parameters.extend(groups[key]) for parameter in groups[key]: color_map[parameter] = colors[i % len(colors)] n = len(parameters) angles = radSc*math.pi*np.arange(0, n)/n x = radSc*np.cos(angles) y = radSc*np.sin(angles) # plot second-order indices for i, j in itertools.combinations(range(n), 2): #key1 = parameters[i] #key2 = parameters[j] if is_significant(SAresults["S2"][i][j], SAresults["S2_conf"][i][j], threshold): angle = math.atan((y[j]-y[i])/(x[j]-x[i])) if y[j]-y[i] < 0: angle += math.pi line_hw = scaling*(max(0, SAresults["S2"][i][j])**widthSc)/2 coords = np.empty((4, 2)) coords[0, 0] = x[i] - line_hw*math.sin(angle) coords[1, 0] = x[i] + line_hw*math.sin(angle) coords[2, 0] = x[j] + line_hw*math.sin(angle) coords[3, 0] = x[j] - line_hw*math.sin(angle) coords[0, 1] = y[i] + line_hw*math.cos(angle) coords[1, 1] = y[i] - line_hw*math.cos(angle) coords[2, 1] = y[j] - line_hw*math.cos(angle) coords[3, 1] = y[j] + line_hw*math.cos(angle) ax.add_artist(plt.Polygon(coords, color="0.75")) # plot total order indices for i, key in enumerate(parameters): if is_significant(SAresults["ST"][i], SAresults["ST_conf"][i], threshold): ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults["ST"][i]**widthSc)/2, color='w')) ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults["ST"][i]**widthSc)/2, lw=STthick, color='0.4', fill=False)) # plot first-order indices for i, key in enumerate(parameters): if is_significant(SAresults["S1"][i], SAresults["S1_conf"][i], threshold): ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults["S1"][i]**widthSc)/2, color='0.4')) # add labels for i, key in enumerate(parameters): ax.text(varNameMult*x[i], varNameMult*y[i], key, ha='center', va='center', rotation=angles[i]*360/(2*math.pi) - 90, color=color_map[key]) if groups is not None: for i, group in enumerate(groups.keys()): print(group) group_angle = np.mean([angles[j] for j in range(n) if parameters[j] in groups[group]]) ax.text(gpNameMult*radSc*math.cos(group_angle), gpNameMult*radSc*math.sin(group_angle), group, ha='center', va='center', rotation=group_angle*360/(2*math.pi) - 90, color=colors[i % len(colors)]) ax.set_facecolor('white') ax.set_xticks([]) ax.set_yticks([]) # ax. plt.axis('equal') plt.axis([-2*radSc, 2*radSc, -2*radSc, 2*radSc]) #plt.show() return fig ``` ## Range of soil parameters ``` problem = { 'num_vars':6, 'names':['SOC', 'Sand', 'Clay', 'pH', 'CN', 'BD'], 'bounds':[[2.58, 6.20], [0.01, 0.30], [0.01, 0.30], [4.6, 6.9], [10.9, 12.4], [900, 1350]] } #names for csv files list_of_csv=['soybean-000-2015.csv', 'sugar-beet-2011.csv', 'sugar-beet-2017.csv', 'spring-barley-2012.csv', 'sugar-beet-2014.csv'] list_of_names=['soybean-000-2015', 'sugar-beat-2011', 'sugar-beat-2017', 'spring-barley-2012', 'sugar-beat-2014'] list_of_totals=['total_SI_'+x for x in list_of_names] list_of_first=['fisrt_SI_'+x for x in list_of_names] list_of_second=['second_SI_'+x for x in list_of_names] list_of_SI=['SI_'+x for x in list_of_names] for j, i in enumerate(list_of_csv): all_data_csv = genfromtxt('./'+str(i), delimiter=',') output = all_data_csv[:,2] print(i) list_of_SI[j] = sobol.analyze(problem, output, calc_second_order=True, conf_level=0.95, print_to_console=False) groups={"Soil physics" : ["Sand", "Clay", "BD"], "Soil chemistry" : ["pH", "SOC", "CN"]} fig = grouped_radial(list_of_SI[4], ['BD', 'Sand', 'Clay', 'pH', 'CN', 'SOC'], groups=groups, threshold=0.001) red_patch = mpatches.Patch(color='red', label='The red data') plt.title(list_of_names[4], loc='left') plt.show() ``` ## Homework __[Tasks](https://skoltech-my.sharepoint.com/:w:/g/personal/mikhail_gasanov_skoltech_ru/EeTPQxbrzVdPqnSENKYyoTUBay1RDYgMMW3GO3qFT2ge5g?e=4hk45V)__ Usefull __SA and UQ__ 1) [Rhodium project](https://github.com/Project-Platypus/Rhodium.git) 2) [SALib](https://github.com/SALib/SALib) __Model__ 3) [PCSE](https://pcse.readthedocs.io/en/stable/index.html) 4) How to install PCSE at local machine `conda env create -f` [py3_pcse.yml](https://github.com/mishagrol/Seminar_Sobol/blob/master/py3_pcse.yml) Аny questions - Telegram - `@misha_grol` Part 1 – Crop Yield Prediction (PCSE, MONICA) You can use the seminars’ colab: “https://colab.research.google.com/drive/1j4AHD8KkTRThPuNsQzQFWYSJtptQ6bUA” 1) Assess the yield of one of the crops for the Moscow region over several years (potatoes, sugar beets for 2-3 years) Crop - (https://github.com/mishagrol/Seminar_Sobol/tree/master/data/crop) Soil - (https://github.com/mishagrol/Seminar_Sobol/tree/master/data/soil) Weather - NASAdataprovider in PCSE (https://pcse.readthedocs.io/en/stable/code.html?highlight=NASA#pcse.db.NASAPowerWeatherDataProvider) Agromanagement - (https://github.com/mishagrol/Seminar_Sobol/blob/master/data/agro/sugarbeet_calendar_Moscow_short.agro) Part 2 – Sensitivity Analysis (SALib) 1) Perform sensitivity analysis of one of the model blocks (crop, soil, agromanagement *) with SALib. You can choose one of the methods that you consider necessary (Sobol, FAST, ...). Generate samples – In report provide the size of the resulting matrix and the sample size (N) Conduct parameter sensitivity analysis - In report provide S1 and ST indices. 2) Generate plots (Hist, Radial convergence plot, etc.) *3) Estimate the required number of simulations to obtain reliable values of the sensitivity indices. Try to estimate the sample size at the confidence interval of the sensitivity indices. * Please note that working with discrete data can cause certain difficulties. #Agro Hack https://agro-code.ru/ ### bonus __Morris method__ Generate a sample using the Method of Morris Three variants of Morris' sampling for elementary effects is supported: - Vanilla Morris - Optimised trajectories when ``optimal_trajectories=True`` (using Campolongo's enhancements from 2007 and optionally Ruano's enhancement from 2012; ``local_optimization=True``) - Groups with optimised trajectories when ``optimal_trajectories=True`` and the problem definition specifies groups (note that ``local_optimization`` must be ``False``) At present, optimised trajectories is implemented using either a brute-force approach, which can be very slow, especially if you require more than four trajectories, or a local method based which is much faster. Both methods now implement working with groups of factors. Note that the number of factors makes little difference, but the ratio between number of optimal trajectories and the sample size results in an exponentially increasing number of scores that must be computed to find the optimal combination of trajectories. We suggest going no higher than 4 from a pool of 100 samples with the brute force approach. With local_optimization = True (which is default), it is possible to go higher than the previously suggested 4 from 100. ``` import sys from SALib.analyze import morris from SALib.sample.morris import sample from SALib.test_functions import Sobol_G from SALib.util import read_param_file from SALib.plotting.morris import horizontal_bar_plot, covariance_plot, \ sample_histograms import matplotlib.pyplot as plt #sys.path.append('../..') # Read the parameter range file and generate samples #problem = read_param_file('/Users/mikhailgasanov/Documents/GIT/SALib/src/SALib/test_functions/params/Sobol_G.txt') # or define manually without a parameter file: problem = { 'num_vars': 8, 'names': ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8'], 'groups': None, 'bounds': [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0], [0.0, 1.0]] } # Files with a 4th column for "group name" will be detected automatically, e.g. # param_file = '../../src/SALib/test_functions/params/Ishigami_groups.txt' # Generate samples param_values = sample(problem, N=1000, num_levels=4, optimal_trajectories=None) # To use optimized trajectories (brute force method), # give an integer value for optimal_trajectories # Run the "model" -- this will happen offline for external models Y = Sobol_G.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = morris.analyze(problem, param_values, Y, conf_level=0.95, print_to_console=True, num_levels=4, num_resamples=100) # Returns a dictionary with keys 'mu', 'mu_star', 'sigma', and 'mu_star_conf' # e.g. Si['mu_star'] contains the mu* value for each parameter, in the # same order as the parameter file fig, (ax1, ax2) = plt.subplots(1, 2) horizontal_bar_plot(ax1, Si, {}, sortby='mu_star', unit=r"tCO$_2$/year") covariance_plot(ax2, Si, {}, unit=r"tCO$_2$/year") fig2 = plt.figure() sample_histograms(fig2, param_values, problem, {'color': 'y'}) plt.show() ```
github_jupyter
# Assignment 1: Bandits and Exploration/Exploitation Welcome to Assignment 1. This notebook will: - Help you create your first bandit algorithm - Help you understand the effect of epsilon on exploration and learn about the exploration/exploitation tradeoff - Introduce you to some of the reinforcement learning software we are going to use for this specialization This class uses RL-Glue to implement most of our experiments. It was originally designed by Adam White, Brian Tanner, and Rich Sutton. This library will give you a solid framework to understand how reinforcement learning experiments work and how to run your own. If it feels a little confusing at first, don't worry - we are going to walk you through it slowly and introduce you to more and more parts as you progress through the specialization. We are assuming that you have used a Jupyter notebook before. But if not, it is quite simple. Simply press the run button, or shift+enter to run each of the cells. The places in the code that you need to fill in will be clearly marked for you. ## Section 0: Preliminaries ``` # Import necessary libraries %matplotlib inline import numpy as np import matplotlib.pyplot as plt from rl_glue import RLGlue import main_agent import ten_arm_env import test_env from tqdm import tqdm import time ``` In the above cell, we import the libraries we need for this assignment. We use numpy throughout the course and occasionally provide hints for which methods to use in numpy. Other than that we mostly use vanilla python and the occasional other library, such as matplotlib for making plots. You might have noticed that we import ten_arm_env. This is the __10-armed Testbed__ introduced in [section 2.3](http://www.incompleteideas.net/book/RLbook2018.pdf) of the textbook. We use this throughout this notebook to test our bandit agents. It has 10 arms, which are the actions the agent can take. Pulling an arm generates a stochastic reward from a Gaussian distribution with unit-variance. For each action, the expected value of that action is randomly sampled from a normal distribution, at the start of each run. If you are unfamiliar with the 10-armed Testbed please review it in the textbook before continuing. __DO NOT IMPORT OTHER LIBRARIES as this will break the autograder.__ __DO NOT SET A RANDOM SEED as this will break the autograder.__ ## Section 1: Greedy Agent We want to create an agent that will find the action with the highest expected reward. One way an agent could operate is to always choose the action with the highest value based on the agent’s current estimates. This is called a greedy agent as it greedily chooses the action that it thinks has the highest value. Let's look at what happens in this case. First we are going to implement the argmax function, which takes in a list of action values and returns an action with the highest value. Why are we implementing our own instead of using the argmax function that numpy uses? Numpy's argmax function returns the first instance of the highest value. We do not want that to happen as it biases the agent to choose a specific action in the case of ties. Instead we want to break ties between the highest values randomly. So we are going to implement our own argmax function. You may want to look at [np.random.choice](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html) to randomly select from a list of values. ``` # [Graded] def argmax(q_values): """ Takes in a list of q_values and returns the index of the item with the highest value. Breaks ties randomly. returns: int - the index of the highest value in q_values """ top = float("-inf") ties = [] for i in range(len(q_values)): # if a value in q_values is greater than the highest value, then update top and reset ties to zero # if a value is equal to top value, then add the index to ties (hint: do this no matter what) # Note: You do not have to follow this exact solution. You can choose to do your own implementation. ### START CODE HERE ### if q_values[i] > top: top, ties = q_values[i], [i] elif q_values[i] == top: ties.append(i) ### END CODE HERE ### # return a random selection from ties. (hint: look at np.random.choice) ### START CODE HERE ### ind = np.random.choice(ties) ### END CODE HERE ### return ind # change this # Test argmax implentation test_array = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0] assert argmax(test_array) == 8, "Check your argmax implementation returns the index of the largest value" test_array = [1, 0, 0, 1] total = 0 for i in range(100): total += argmax(test_array) np.save("argmax_test", total) assert total > 0, "Make sure your argmax implementation randomly choooses among the largest values. Make sure you are not setting a random seed (do not use np.random.seed)" assert total != 300, "Make sure your argmax implementation randomly choooses among the largest values." ``` Now we introduce the first part of an RL-Glue agent that you will implement. Here we are going to create a GreedyAgent and implement the agent_step method. This method gets called each time the agent takes a step. The method has to return the action selected by the agent. This method also ensures the agent’s estimates are updated based on the signals it gets from the environment. Fill in the code below to implement a greedy agent. ``` # Greedy agent here [Graded] class GreedyAgent(main_agent.Agent): def agent_step(self, reward, observation): """ Takes one step for the agent. It takes in a reward and observation and returns the action the agent chooses at that time step. Arguments: reward -- float, the reward the agent received from the environment after taking the last action. observation -- float, the observed state the agent is in. Do not worry about this for this assignment as you will not use it until future lessons. Returns: current_action -- int, the action chosen by the agent at the current time step. """ ### Useful Class Variables ### # self.q_values : An array with the agent’s value estimates for each action. # self.arm_count : An array with a count of the number of times each arm has been pulled. # self.last_action : The action that the agent took on the previous time step. ####################### # Update action values. Hint: Look at the algorithm in section 2.4 of the textbook. # Increment the counter in self.arm_count for the action from the previous time step # Update the step size using self.arm_count # Update self.q_values for the action from the previous time step # (~3-5 lines) ### START CODE HERE ### self.arm_count[self.last_action] += 1 self.q_values[self.last_action] += (reward - self.q_values[self.last_action]) / self.arm_count[self.last_action] ### END CODE HERE ### # current action = ? # Use the argmax function you created above # (~2 lines) ### START CODE HERE ### current_action = argmax(self.q_values) ### END CODE HERE ### self.last_action = current_action return current_action # Do not modify this cell # Test for Greedy Agent Code greedy_agent = GreedyAgent() greedy_agent.q_values = [0, 0, 1.0, 0, 0] greedy_agent.arm_count = [0, 1, 0, 0, 0] greedy_agent.last_action = 1 action = greedy_agent.agent_step(1, 0) print(greedy_agent.q_values) np.save("greedy_test", greedy_agent.q_values) print("Output:") print(greedy_agent.q_values) print("Expected Output:") print([0, 0.5, 1.0, 0, 0]) assert action == 2, "Check that you are using argmax to choose the action with the highest value." assert greedy_agent.q_values == [0, 0.5, 1.0, 0, 0], "Check that you are updating q_values correctly." ``` Let's visualize the result. Here we run an experiment using RL-Glue to test our agent. For now, we will set up the experiment code; in future lessons, we will walk you through running experiments so that you can create your own. ``` # Plot Greedy Result num_runs = 200 # The number of times we run the experiment num_steps = 1000 # The number of steps each experiment is run for env = ten_arm_env.Environment # We the environment to use agent = GreedyAgent # We choose what agent we want to use agent_info = {"num_actions": 10} # Pass the agent the information it needs; # here it just needs the number of actions (number of arms). env_info = {} # Pass the environment the information it needs; in this case, it is nothing. all_averages = [] for i in tqdm(range(num_runs)): # tqdm is what creates the progress bar below once the code is run rl_glue = RLGlue(env, agent) # Creates a new RLGlue experiment with the env and agent we chose above rl_glue.rl_init(agent_info, env_info) # Pass RLGlue what it needs to initialize the agent and environment rl_glue.rl_start() # Start the experiment scores = [0] averages = [] for i in range(num_steps): reward, _, action, _ = rl_glue.rl_step() # The environment and agent take a step and return # the reward, and action taken. scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) all_averages.append(averages) plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') plt.plot([1.55 for _ in range(num_steps)], linestyle="--") plt.plot(np.mean(all_averages, axis=0)) plt.legend(["Best Possible", "Greedy"]) plt.title("Average Reward of Greedy Agent") plt.xlabel("Steps") plt.ylabel("Average reward") plt.show() greedy_scores = np.mean(all_averages, axis=0) np.save("greedy_scores", greedy_scores) ``` How did our agent do? Is it possible for it to do better? ## Section 2: Epsilon-Greedy Agent We learned about [another way for an agent to operate](https://www.coursera.org/learn/fundamentals-of-reinforcement-learning/lecture/tHDck/what-is-the-trade-off), where it does not always take the greedy action. Instead, sometimes it takes an exploratory action. It does this so that it can find out what the best action really is. If we always choose what we think is the current best action is, we may miss out on taking the true best action, because we haven't explored enough times to find that best action. Implement an epsilon-greedy agent below. Hint: we are implementing the algorithm from [section 2.4](http://www.incompleteideas.net/book/RLbook2018.pdf#page=52) of the textbook. You may want to use your greedy code from above and look at [np.random.random](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.html), as well as [np.random.randint](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html), to help you select random actions. ``` # Epsilon Greedy Agent here [Graded] class EpsilonGreedyAgent(main_agent.Agent): def agent_step(self, reward, observation): """ Takes one step for the agent. It takes in a reward and observation and returns the action the agent chooses at that time step. Arguments: reward -- float, the reward the agent received from the environment after taking the last action. observation -- float, the observed state the agent is in. Do not worry about this for this assignment as you will not use it until future lessons. Returns: current_action -- int, the action chosen by the agent at the current time step. """ ### Useful Class Variables ### # self.q_values : An array with the agent’s value estimates for each action. # self.arm_count : An array with a count of the number of times each arm has been pulled. # self.last_action : The action that the agent took on the previous time step. # self.epsilon : The probability an epsilon greedy agent will explore (ranges between 0 and 1) ####################### # Update action-values - this should be the same update as your greedy agent above # (~3-5 lines) ### START CODE HERE ### self.arm_count[self.last_action] += 1 self.q_values[self.last_action] += (reward - self.q_values[self.last_action]) / self.arm_count[self.last_action] ### END CODE HERE ### # Choose action using epsilon greedy # Randomly choose a number between 0 and 1 and see if it is less than self.epsilon # (Hint: look at np.random.random()). If it is, set current_action to a random action. # Otherwise choose current_action greedily as you did above. # (~4 lines) ### START CODE HERE ### if np.random.random() < self.epsilon: current_action = np.random.randint(len(self.q_values)) else: current_action = argmax(self.q_values) ### END CODE HERE ### self.last_action = current_action return current_action # Do not modify this cell # Test Code for Epsilon Greedy Agent e_greedy_agent = EpsilonGreedyAgent() e_greedy_agent.q_values = [0, 0, 1.0, 0, 0] e_greedy_agent.arm_count = [0, 1, 0, 0, 0] e_greedy_agent.num_actions = 5 e_greedy_agent.last_action = 1 e_greedy_agent.epsilon = 0.5 action = e_greedy_agent.agent_step(1, 0) print("Output:") print(e_greedy_agent.q_values) print("Expected Output:") print([0, 0.5, 1.0, 0, 0]) # assert action == 2, "Check that you are using argmax to choose the action with the highest value." assert e_greedy_agent.q_values == [0, 0.5, 1.0, 0, 0], "Check that you are updating q_values correctly." ``` Now that we have our epsilon greedy agent created. Let's compare it against the greedy agent with epsilon of 0.1. ``` # Plot Epsilon greedy results and greedy results num_runs = 200 num_steps = 1000 epsilon = 0.1 agent = EpsilonGreedyAgent env = ten_arm_env.Environment agent_info = {"num_actions": 10, "epsilon": epsilon} env_info = {} all_averages = [] for i in tqdm(range(num_runs)): rl_glue = RLGlue(env, agent) rl_glue.rl_init(agent_info, env_info) rl_glue.rl_start() scores = [0] averages = [] for i in range(num_steps): reward, _, action, _ = rl_glue.rl_step() # The environment and agent take a step and return # the reward, and action taken. scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) all_averages.append(averages) plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') plt.plot([1.55 for _ in range(num_steps)], linestyle="--") plt.plot(greedy_scores) plt.title("Average Reward of Greedy Agent vs. Epsilon-Greedy Agent") plt.plot(np.mean(all_averages, axis=0)) plt.legend(("Best Possible", "Greedy", "Epsilon Greedy: Epsilon = 0.1")) plt.xlabel("Steps") plt.ylabel("Average reward") plt.show() np.save("e-greedy", all_averages) ``` Notice how much better the epsilon-greedy agent did. Because we occasionally choose a random action we were able to find a better long term policy. By acting greedily before our value estimates are accurate, we risk settling on a suboptimal action. ## 1.2 Averaging Multiple Runs Did you notice that we averaged over 2000 runs? Why did we do that? To get some insight, let's look at the results of two individual runs by the same agent. ``` # Plot runs of e-greedy agent agent = EpsilonGreedyAgent agent_info = {"num_actions": 10, "epsilon": 0.1} env_info = {} all_averages = [] plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') num_steps = 1000 for run in (0, 1): np.random.seed(run) # Here we set the seed so that we can compare two different runs averages = [] rl_glue = RLGlue(env, agent) rl_glue.rl_init(agent_info, env_info) rl_glue.rl_start() scores = [0] for i in range(num_steps): reward, state, action, is_terminal = rl_glue.rl_step() scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) # all_averages.append(averages) plt.plot(averages) # plt.plot(greedy_scores) plt.title("Comparing two runs of the same agent") plt.xlabel("Steps") plt.ylabel("Average reward") # plt.plot(np.mean(all_averages, axis=0)) # plt.legend(("Greedy", "Epsilon: 0.1")) plt.show() ``` Notice how the two runs were different? But, if this is the exact same algorithm, why does it behave differently in these two runs? The answer is that it is due to randomness in the environment and in the agent. Depending on what action the agent randomly starts with, or when it randomly chooses to explore, it can change the results of the runs. And even if the agent chooses the same action, the reward from the environment is randomly sampled from a Gaussian. The agent could get lucky, and see larger rewards for the best action early on and so settle on the best action faster. Or, it could get unlucky and see smaller rewards for best action early on and so take longer to recognize that it is in fact the best action. To be more concrete, let’s look at how many times an exploratory action is taken, for different seeds. ``` print("Random Seed 1") np.random.seed(1) for _ in range(15): if np.random.random() < 0.1: print("Exploratory Action") print() print() print("Random Seed 2") np.random.seed(2) for _ in range(15): if np.random.random() < 0.1: print("Exploratory Action") ``` With the first seed, we take an exploratory action three times out of 15, but with the second, we only take an exploratory action once. This can significantly affect the performance of our agent because the amount of exploration has changed significantly. To compare algorithms, we therefore report performance averaged across many runs. We do this to ensure that we are not simply reporting a result that is due to stochasticity, as explained [in the lectures](https://www.coursera.org/learn/fundamentals-of-reinforcement-learning/lecture/PtVBs/sequential-decision-making-with-evaluative-feedback). Rather, we want statistically significant outcomes. We will not use statistical significance tests in this course. Instead, because we have access to simulators for our experiments, we use the simpler strategy of running for a large number of runs and ensuring that the confidence intervals do not overlap. ## Section 3: Comparing values of epsilon Can we do better than an epsilon of 0.1? Let's try several different values for epsilon and see how they perform. We try different settings of key performance parameters to understand how the agent might perform under different conditions. Below we run an experiment where we sweep over different values for epsilon: ``` # Experiment code for epsilon-greedy with different values of epsilon epsilons = [0.0, 0.01, 0.1, 0.4] plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') plt.plot([1.55 for _ in range(num_steps)], linestyle="--") n_q_values = [] n_averages = [] n_best_actions = [] num_runs = 200 for epsilon in epsilons: all_averages = [] for run in tqdm(range(num_runs)): agent = EpsilonGreedyAgent agent_info = {"num_actions": 10, "epsilon": epsilon} env_info = {"random_seed": run} rl_glue = RLGlue(env, agent) rl_glue.rl_init(agent_info, env_info) rl_glue.rl_start() best_arm = np.argmax(rl_glue.environment.arms) scores = [0] averages = [] best_action_chosen = [] for i in range(num_steps): reward, state, action, is_terminal = rl_glue.rl_step() scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) if action == best_arm: best_action_chosen.append(1) else: best_action_chosen.append(0) if epsilon == 0.1 and run == 0: n_q_values.append(np.copy(rl_glue.agent.q_values)) if epsilon == 0.1: n_averages.append(averages) n_best_actions.append(best_action_chosen) all_averages.append(averages) plt.plot(np.mean(all_averages, axis=0)) plt.legend(["Best Possible"] + epsilons) plt.xlabel("Steps") plt.ylabel("Average reward") plt.show() ``` Why did 0.1 perform better than 0.01? If exploration helps why did 0.4 perform worse that 0.0 (the greedy agent)? Think about these and how you would answer these questions. They are questions in the practice quiz. If you still have questions about it, retake the practice quiz. ## Section 4: The Effect of Step Size In Section 1 of this assignment, we decayed the step size over time based on action-selection counts. The step-size was 1/N(A), where N(A) is the number of times action A was selected. This is the same as computing a sample average. We could also set the step size to be a constant value, such as 0.1. What would be the effect of doing that? And is it better to use a constant or the sample average method? To investigate this question, let’s start by creating a new agent that has a constant step size. This will be nearly identical to the agent created above. You will use the same code to select the epsilon-greedy action. You will change the update to have a constant step size instead of using the 1/N(A) update. ``` # Constant Step Size Agent Here [Graded] # Greedy agent here class EpsilonGreedyAgentConstantStepsize(main_agent.Agent): def agent_step(self, reward, observation): """ Takes one step for the agent. It takes in a reward and observation and returns the action the agent chooses at that time step. Arguments: reward -- float, the reward the agent received from the environment after taking the last action. observation -- float, the observed state the agent is in. Do not worry about this for this assignment as you will not use it until future lessons. Returns: current_action -- int, the action chosen by the agent at the current time step. """ ### Useful Class Variables ### # self.q_values : An array with the agent’s value estimates for each action. # self.arm_count : An array with a count of the number of times each arm has been pulled. # self.last_action : The action that the agent took on the previous time step. # self.step_size : A float which is the current step size for the agent. # self.epsilon : The probability an epsilon greedy agent will explore (ranges between 0 and 1) ####################### # Update q_values for action taken at previous time step # using self.step_size intead of using self.arm_count # (~1-2 lines) ### START CODE HERE ### self.arm_count[self.last_action] += 1 self.q_values[self.last_action] += self.step_size * (reward - self.q_values[self.last_action]) ### END CODE HERE ### # Choose action using epsilon greedy. This is the same as you implemented above. # (~4 lines) ### START CODE HERE ### if np.random.random() < self.epsilon: current_action = np.random.randint(len(self.q_values)) else: current_action = argmax(self.q_values) ### END CODE HERE ### self.last_action = current_action return current_action # Do not modify this cell # Test Code for Epsilon Greedy with Different Constant Stepsizes for step_size in [0.01, 0.1, 0.5, 1.0]: e_greedy_agent = EpsilonGreedyAgentConstantStepsize() e_greedy_agent.q_values = [0, 0, 1.0, 0, 0] # e_greedy_agent.arm_count = [0, 1, 0, 0, 0] e_greedy_agent.num_actions = 5 e_greedy_agent.last_action = 1 e_greedy_agent.epsilon = 0.0 e_greedy_agent.step_size = step_size action = e_greedy_agent.agent_step(1, 0) print("Output for step size: {}".format(step_size)) print(e_greedy_agent.q_values) print("Expected Output:") print([0, step_size, 1.0, 0, 0]) assert e_greedy_agent.q_values == [0, step_size, 1.0, 0, 0], "Check that you are updating q_values correctly using the stepsize." # Experiment code for different step sizes [graded] step_sizes = [0.01, 0.1, 0.5, 1.0] epsilon = 0.1 num_steps = 1000 num_runs = 200 fig, ax = plt.subplots(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') q_values = {step_size: [] for step_size in step_sizes} true_values = {step_size: None for step_size in step_sizes} best_actions = {step_size: [] for step_size in step_sizes} for step_size in step_sizes: all_averages = [] for run in tqdm(range(num_runs)): agent = EpsilonGreedyAgentConstantStepsize agent_info = {"num_actions": 10, "epsilon": epsilon, "step_size": step_size, "initial_value": 0.0} env_info = {"random_seed": run} rl_glue = RLGlue(env, agent) rl_glue.rl_init(agent_info, env_info) rl_glue.rl_start() best_arm = np.argmax(rl_glue.environment.arms) scores = [0] averages = [] if run == 0: true_values[step_size] = np.copy(rl_glue.environment.arms) best_action_chosen = [] for i in range(num_steps): reward, state, action, is_terminal = rl_glue.rl_step() scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) if action == best_arm: best_action_chosen.append(1) else: best_action_chosen.append(0) if run == 0: q_values[step_size].append(np.copy(rl_glue.agent.q_values)) best_actions[step_size].append(best_action_chosen) ax.plot(np.mean(best_actions[step_size], axis=0)) if step_size == 0.01: np.save("step_size", best_actions[step_size]) ax.plot(np.mean(n_best_actions, axis=0)) fig.legend(step_sizes + ["1/N(A)"]) plt.title("% Best Action Taken") plt.xlabel("Steps") plt.ylabel("% Best Action Taken") vals = ax.get_yticks() ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals]) plt.show() ``` Notice first that we are now plotting the amount of time that the best action is taken rather than the average reward. To better understand the performance of an agent, it can be useful to measure specific behaviors, beyond just how much reward is accumulated. This measure indicates how close the agent’s behaviour is to optimal. It seems as though 1/N(A) performed better than the others, in that it reaches a solution where it takes the best action most frequently. Now why might this be? Why did a step size of 0.5 start out better but end up performing worse? Why did a step size of 0.01 perform so poorly? Let's dig into this further below. Let’s plot how well each agent tracks the true value, where each agent has a different step size method. You do not have to enter any code here, just follow along. ``` # Plot various step sizes and estimates largest = 0 num_steps = 1000 for step_size in step_sizes: plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') largest = np.argmax(true_values[step_size]) plt.plot([true_values[step_size][largest] for _ in range(num_steps)], linestyle="--") plt.title("Step Size: {}".format(step_size)) plt.plot(np.array(q_values[step_size])[:, largest]) plt.legend(["True Expected Value", "Estimated Value"]) plt.xlabel("Steps") plt.ylabel("Value") plt.show() plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') plt.title("Step Size: 1/N(A)") plt.plot([true_values[step_size][largest] for _ in range(num_steps)], linestyle="--") plt.plot(np.array(n_q_values)[:, largest]) plt.legend(["True Expected Value", "Estimated Value"]) plt.xlabel("Steps") plt.ylabel("Value") plt.show() ``` These plots help clarify the performance differences between the different step sizes. A step size of 0.01 makes such small updates that the agent’s value estimate of the best action does not get close to the actual value. Step sizes of 0.5 and 1.0 both get close to the true value quickly, but are very susceptible to stochasticity in the rewards. The updates overcorrect too much towards recent rewards, and so oscillate around the true value. This means that on many steps, the action that pulls the best arm may seem worse than it actually is. A step size of 0.1 updates fairly quickly to the true value, and does not oscillate as widely around the true values as 0.5 and 1.0. This is one of the reasons that 0.1 performs quite well. Finally we see why 1/N(A) performed well. Early on while the step size is still reasonably high it moves quickly to the true expected value, but as it gets pulled more its step size is reduced which makes it less susceptible to the stochasticity of the rewards. Does this mean that 1/N(A) is always the best? When might it not be? One possible setting where it might not be as effective is in non-stationary problems. You learned about non-stationarity in the lessons. Non-stationarity means that the environment may change over time. This could manifest itself as continual change over time of the environment, or a sudden change in the environment. Let's look at how a sudden change in the reward distributions affects a step size like 1/N(A). This time we will run the environment for 2000 steps, and after 1000 steps we will randomly change the expected value of all of the arms. We compare two agents, both using epsilon-greedy with epsilon = 0.1. One uses a constant step size of 0.1, the other a step size of 1/N(A) that reduces over time. ``` epsilon = 0.1 num_steps = 2000 num_runs = 200 step_size = 0.1 plt.figure(figsize=(15, 5), dpi= 80, facecolor='w', edgecolor='k') plt.plot([1.55 for _ in range(num_steps)], linestyle="--") for agent in [EpsilonGreedyAgent, EpsilonGreedyAgentConstantStepsize]: all_averages = [] for run in tqdm(range(num_runs)): agent_info = {"num_actions": 10, "epsilon": epsilon, "step_size": step_size} env_info = {"random_seed": run} rl_glue = RLGlue(env, agent) rl_glue.rl_init(agent_info, env_info) rl_glue.rl_start() scores = [0] averages = [] for i in range(num_steps): reward, state, action, is_terminal = rl_glue.rl_step() scores.append(scores[-1] + reward) averages.append(scores[-1] / (i + 1)) if i == 1000: rl_glue.environment.arms = np.random.randn(10) all_averages.append(averages) plt.plot(np.mean(all_averages, axis=0)) plt.legend(["Best Possible", "1/N(A)", "0.1"]) plt.xlabel("Steps") plt.ylabel("Average reward") plt.show() ``` Now the agent with a step size of 1/N(A) performed better at the start but then performed worse when the environment changed! What happened? Think about what the step size would be after 1000 steps. Let's say the best action gets chosen 500 times. That means the step size for that action is 1/500 or 0.002. At each step when we update the value of the action and the value is going to move only 0.002 * the error. That is a very tiny adjustment and it will take a long time for it to get to the true value. The agent with step size 0.1, however, will always update in 1/10th of the direction of the error. This means that on average it will take ten steps for it to update its value to the sample mean. These are the types of tradeoffs we have to think about in reinforcement learning. A larger step size moves us more quickly toward the true value, but can make our estimated values oscillate around the expected value. A step size that reduces over time can converge to close to the expected value, without oscillating. On the other hand, such a decaying stepsize is not able to adapt to changes in the environment. Nonstationarity---and the related concept of partial observability---is a common feature of reinforcement learning problems and when learning online. ## Section 5: Conclusion Great work! You have: - Implemented your first agent - Learned about the effect of epsilon, an exploration parameter, on the performance of an agent - Learned about the effect of step size on the performance of the agent - Learned about a good experiment practice of averaging across multiple runs
github_jupyter
<a href="https://colab.research.google.com/github/connorpheraty/DS-Unit-1-Sprint-1-Dealing-With-Data/blob/master/Connor_Heraty_LS_DS_113_Basic_Data_Visualizations.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Lambda School Data Science - Basic Data Visualizations A picture is worth a thousand words. So, without any further ado: ## Lecture Example ``` # https://matplotlib.org/gallery/lines_bars_and_markers/barh.html#sphx-glr-gallery-lines-bars-and-markers-barh-py import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) plt.rcdefaults() fig, ax = plt.subplots() # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) ax.barh(y_pos, performance,xerr = error, align='center', color='green', ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(people) ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Performance') ax.set_title('How fast do you want to go today?') plt.show() ``` The above is fairly clear. It's a lot less clear as a piechart. ``` # Adapted to piechart # https://matplotlib.org/gallery/pie_and_polar_charts/pie_features.html#sphx-glr-gallery-pie-and-polar-charts-pie-features-py import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) plt.rcdefaults() fig, ax = plt.subplots() # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) ax.pie(performance, labels=people) ax.set_title('How fast do you want to go today?') plt.show() ``` What about continuous data? Scatterplot is a natural fit, and higher dimensions can be represented by size, color, or other visual aspects of the points. ``` # https://matplotlib.org/gallery/lines_bars_and_markers/scatter_demo2.html#sphx-glr-gallery-lines-bars-and-markers-scatter-demo2-py import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook # Load a numpy record array from yahoo csv data with fields date, open, close, # volume, adj_close from the mpl-data/example directory. The record array # stores the date as an np.datetime64 with a day unit ('D') in the date column. with cbook.get_sample_data('goog.npz') as datafile: price_data = np.load(datafile)['price_data'].view(np.recarray) price_data = price_data[-250:] # get the most recent 250 trading days delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1] # Marker size in units of points^2 volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2 close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2] fig, ax = plt.subplots() ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5) ax.set_xlabel(r'$\Delta_i$', fontsize=15) ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=15) ax.set_title('Volume and percent change') ax.grid(True) fig.tight_layout() plt.show() ``` An alternative way to represent higher dimensional data is with 3D scatterplots - but these are pretty hard to look at. Specifically, if it's not interactive (you can't drag it and move it around), your eye may not be able to distinguish which spatial dimension is separating two specific points. ``` # https://matplotlib.org/gallery/mplot3d/scatter3d.html#sphx-glr-gallery-mplot3d-scatter3d-py # This import registers the 3D projection, but is otherwise unused. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) def randrange(n, vmin, vmax): ''' Helper function to make an array of random numbers having shape (n, ) with each number distributed Uniform(vmin, vmax). ''' return (vmax - vmin)*np.random.rand(n) + vmin fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 # For each set of style and range settings, plot n random points in the box # defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh]. for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]: xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, zlow, zhigh) ax.scatter(xs, ys, zs, c=c, marker=m) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() ``` Live lecture - let's pick some plots and try them! - https://matplotlib.org/gallery - the foundational Python plotting library - https://seaborn.pydata.org/examples/index.html - opinionated, built on matplotlib so less configurable but arguably more usable/pretty (or easy to make pretty) - http://ggplot.yhathq.com/ - based on R's ggplot2 (the "Grammar of Graphics", a consistent and widely used foundation of plotting, particularly by academics) - https://bokeh.pydata.org/en/latest/ - interactive plots - write in Python, build and serve in HTML and JavaScript - https://plot.ly/ - similar to Bokeh but with a commercial service (though the software itself is still open source) - https://altair-viz.github.io/ - declarative visual graphics - a little different than the matplotlib/seaborn paradigm (based on the Vega Visualization Grammar) - https://python.libhunt.com/seaborn-alternatives - even more! ``` from google.colab import files uploaded = files.upload() import pandas as pd df_wine = pd.read_csv('winemag-data_first150k.csv') new_df_wine = df_wine[['country', 'designation', 'points','price','province','region_1', 'variety','winery']].dropna() new_df_wine.info() new_df_wine.isnull().sum() new_df_wine.head() new_df_wine['price'].describe() import matplotlib.pyplot as plt import seaborn as sns # 1 Histogram # Seaborn histogram shows distribution of scores for various wines ax = sns.distplot(new_df_wine['points'],color='crimson') ax.set(xlabel='Wine Quality Score', title='Distribution of Wine Scores'); import numpy as np # Plot the scatter plot above comparing price to score plt.scatter(x=new_df_wine["points"], y=new_df_wine["price"], color='crimson'); plt.xlabel('Quality') plt.ylabel('Price of Wine') plt.title('Does more Expensive Wine Taste Better?', size=15) # The problem with this graph appears to be outliers in the price range. # Removing all wines over $1000 would make a more readable graph sns.jointplot(x=new_df_wine["points"], y=new_df_wine["price"], kind="hex", color="k"); sns.set(style='whitegrid') # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 6)) # Draw a violinplot with a narrower bandwidth than the default sns.violinplot(x=new_df_wine["points"], y=new_df_wine["price"], palette="Set3", bw=.2, cut=1, linewidth=1); # This plot is limited in its utility because the prices cluster near the bottom. # I will now create a line of best fit from my scatter plot above to see how much increases in price correlate with increases in quality for our wine sample. from numpy import * from scipy.interpolate import * reg_df = new_df_wine x = reg_df['points'].values y = reg_df['price'].values plot_line = polyfit(x,y,1) print(plot_line) plt.scatter(x=new_df_wine["points"], y=new_df_wine["price"], color='crimson'); plt.xlabel('Quality') plt.ylabel('Price of Wine') plt.title('Does more Expensive Wine Taste Better?', size=15) plt.plot(x,polyval(plot_line,x),color='black',ls='--'); # The answer is that it does! But not nearly as much as one would think. You may want to think twice before purchasing that $100 bottle of wine! plt.xkcd() fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.bar([-0.125, 1.0-0.125], [0, 100], 0.25) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.set_xticks([0, 1]) ax.set_xlim([-0.5, 1.5]) ax.set_ylim([0, 110]) ax.set_xticklabels(['Sober', 'After Wine']) plt.yticks([]) plt.title("Impulse to eat McDonalds") plt.show(); ``` ## Assignment - draw some plots! In the following section you should draw at least *3* plots, using the data you loaded yesterday - the first should be with matplotlib. The other two can be with any Python tool of your choice - Seaborn in particular is suggested to try. It is OK to start with code from a gallery/example or whatever documentation you find, but try to get it working with your own data. After you make the plots, write a summary (around a paragraph) for each plot, interpreting and describing it and what insight it gives you into the data. This summary should be written for an "interested but non-technical" audience - that is usually the sort of audience data scientists communicate with. Try to *explain* what's going on without making it scary. Stretch goals: - Interactive plots! (from the above tools, either Bokeh or plot.ly) - 3D plots that are intuitive/informative (and probably also interactive) - Share your plot! Take a screenshot and drop it in the cohort channel or elsewhere in Slack - Deploy! If it's interactive, you can put it out there (plot.ly will host your plot for you, and Bokeh will make an HTML file) - Work on your local Python setup - so far we've just used Colab, but [Anaconda](https://www.anaconda.com/download/) is a local environment for Python that lets you do everything you can in Colab and more
github_jupyter
``` import numpy as np import pandas as pd from sklearn.preprocessing import LabelBinarizer import matplotlib.colors as colors import matplotlib.cbook as cbook from IPython.display import display import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from eis.EISDataIO import eis_dataframe_from_csv from os import path import logging # loading training data # if you are on a windows machine un-comment the following line to get the path to training data # here = !echo %cd% # if you are on a mac/ unix machine un-comment the following line to get the path to training data here = !pwd train_data_path = path.join(path.dirname(here[0]), "train_data.csv") eis_data = eis_dataframe_from_csv(train_data_path) def complex_parts(cmp: pd.Series) -> tuple[pd.Series, pd.Series]: real_part= cmp.apply(np.real) imag_part= cmp.apply(np.imag) return (real_part, imag_part) eis_data["Z_real"], eis_data["Z_imag"] = complex_parts(eis_data.Z) display(eis_data) def drange(cmp: pd.Series) -> tuple[pd.Series, pd.Series]: min_= cmp.apply(np.min) max_= cmp.apply(np.max) return (min_, max_) eis_data["freq_min"], eis_data["freq_max"] = drange(eis_data.freq) eis_data["Z_real_min"], eis_data["Z_real_max"] = drange(eis_data.Z_real) eis_data["Z_imag_min"], eis_data["Z_imag_max"] = drange(eis_data.Z_imag) display(eis_data) def minmaxer(cmp: pd.Series, min_, max_) -> pd.Series: minmaxed = (cmp-min_)/(max_-min_) return minmaxed Z_real_min = eis_data["Z_real_min"].min() Z_real_max = eis_data["Z_real_max"].max() Z_imag_min = eis_data["Z_imag_min"].min() Z_imag_max = eis_data["Z_imag_max"].max() eis_data["Z_real_minmaxed"] = minmaxer(eis_data.Z_real,Z_real_min,Z_real_max) eis_data["Z_imag_minmaxed"] = minmaxer(eis_data.Z_imag,Z_imag_min,Z_imag_max) display(eis_data) from typing import List def input_prepro(cmp: pd.DataFrame, cols: List) -> tuple[pd.Series, pd.Series]: res_col = [] mask_col = [] n_cols = len(cols) for idx, r in cmp.iterrows(): len_data=len(r[cols[0]]) res = np.zeros([83,n_cols]) mask = np.zeros([83,1]) mask[0:len_data]=1 for i, c in enumerate(cols): res[0:len_data,i]=r[c] res_col.append(res) mask_col.append(mask) return (pd.Series(res_col), pd.Series(mask_col)) eis_data["input_data"],eis_data["input_mask"] = input_prepro(eis_data, ["freq", "Z_real", "Z_imag"]) # display(eis_data) display(eis_data["input_data"].to_numpy()) # Utility for our sequence model. def get_sequence_model(max_seq_len: int,N_features: int,N_classes: int ): #Max sequence lenght: 83, Number of features: 3 eis_features_input = keras.Input((max_seq_len, N_features)) mask_input = keras.Input((max_seq_len,), dtype="bool") x = keras.layers.LSTM(16, return_sequences=True)( eis_features_input, mask=mask_input ) x = keras.layers.LSTM(8)(x) x = keras.layers.Dropout(0.4)(x) x = keras.layers.Dense(8, activation="relu")(x) # Number of posible classes at the output output = keras.layers.Dense(N_classes, activation="softmax")(x) rnn_model = keras.Model([eis_features_input, mask_input], output) rnn_model.compile( loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"] ) return rnn_model mymodel = get_sequence_model(83, 3, 9) myohe = LabelBinarizer() a = myohe.fit_transform(eis_data["Circuit"]) h = mymodel.fit( x=( np.asarray(eis_data["input_data"]).astype('float32'), np.asarray(eis_data["input_mask"]).astype('float32') ), y=myohe.fit_transform(eis_data["Circuit"]).astype('float32'), batch_size=2, epochs=2, verbose=2 ) np.random.randn(len(eis_data["Circuit"]), 83, 3).astype('float32').shape np.random.randint(low=0, high=2, size=(len(eis_data["Circuit"]), 83, 1)).astype('float32').shape myohe.fit_transform(eis_data["Circuit"]).astype('float32').shape h = mymodel.fit( x=( np.random.randn(len(eis_data["Circuit"]), 83, 3).astype('float32'), np.random.randint(low=0, high=2, size=(len(eis_data["Circuit"]), 83, 1)).astype('float32') ), y=myohe.fit_transform(eis_data["Circuit"]).astype('float32'), batch_size=18, epochs=2, verbose=2 ) ```
github_jupyter
# Classifying Images with a NN and DNN Model ## Introduction In this notebook, you learn how to build a neural network to classify the tf-flowers dataset using a Deep Neural Network Model. ## Learning Objectives * Define Helper Functions. * Train and evaluate a Neural Network (NN) model. * Train and evaluate a Deep Neural Network model. Each learning objective will correspond to a __#TODO__ in the student lab notebook -- try to complete this notebook first and then review the [solution notebook](../solutions/classifying_images_with_a_nn_and_dnn_model.ipynb). ``` # Import and print the installed version of TensorFlow import tensorflow as tf print(tf.version.VERSION) ``` ## Defining Helper Functions #### Reading and Preprocessing image data ``` # Helper functions def training_plot(metrics, history): f, ax = plt.subplots(1, len(metrics), figsize=(5*len(metrics), 5)) for idx, metric in enumerate(metrics): ax[idx].plot(history.history[metric], ls='dashed') ax[idx].set_xlabel("Epochs") ax[idx].set_ylabel(metric) ax[idx].plot(history.history['val_' + metric]); ax[idx].legend([metric, 'val_' + metric]) # Call model.predict() on a few images in the evaluation dataset def plot_predictions(filename): f, ax = plt.subplots(3, 5, figsize=(25,15)) dataset = (tf.data.TextLineDataset(filename). map(decode_csv)) for idx, (img, label) in enumerate(dataset.take(15)): ax[idx//5, idx%5].imshow((img.numpy())); batch_image = tf.reshape(img, [1, IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS]) batch_pred = model.predict(batch_image) pred = batch_pred[0] label = CLASS_NAMES[label.numpy()] pred_label_index = tf.math.argmax(pred).numpy() pred_label = CLASS_NAMES[pred_label_index] prob = pred[pred_label_index] ax[idx//5, idx%5].set_title('{}: {} ({:.4f})'.format(label, pred_label, prob)) def show_trained_weights(model): # CLASS_NAMES is ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips'] LAYER = 1 # Layer 0 flattens the image, layer=1 is the first dense layer WEIGHT_TYPE = 0 # 0 for weight, 1 for bias f, ax = plt.subplots(1, 5, figsize=(15,15)) for flower in range(len(CLASS_NAMES)): weights = model.layers[LAYER].get_weights()[WEIGHT_TYPE][:, flower] min_wt = tf.math.reduce_min(weights).numpy() max_wt = tf.math.reduce_max(weights).numpy() flower_name = CLASS_NAMES[flower] print("Scaling weights for {} in {} to {}".format( flower_name, min_wt, max_wt)) weights = (weights - min_wt)/(max_wt - min_wt) ax[flower].imshow(weights.reshape(IMG_HEIGHT, IMG_WIDTH, 3)); ax[flower].set_title(flower_name); # The import statement combines two operations; it searches for the named module, then it binds the results of that search import matplotlib.pylab as plt import numpy as np import tensorflow as tf IMG_HEIGHT = 224 IMG_WIDTH = 224 IMG_CHANNELS = 3 def read_and_decode(filename, reshape_dims): # Read the file img = # TODO 1 -- Your code here # Convert the compressed string to a 3D uint8 tensor. img = tf.image.decode_jpeg(img, channels=IMG_CHANNELS) # Use `convert_image_dtype` to convert to floats in the [0,1] range. img = tf.image.convert_image_dtype(img, tf.float32) # Resize the image to the desired size. return tf.image.resize(img, reshape_dims) CLASS_NAMES = [item.numpy().decode("utf-8") for item in tf.strings.regex_replace( tf.io.gfile.glob("gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/*"), "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/", "")] CLASS_NAMES = [item for item in CLASS_NAMES if item.find(".") == -1] print("These are the available classes:", CLASS_NAMES) # the label is the index into CLASS_NAMES array def decode_csv(csv_row): record_defaults = ["path", "flower"] filename, label_string = tf.io.decode_csv(csv_row, record_defaults) img = read_and_decode(filename, [IMG_HEIGHT, IMG_WIDTH]) label = tf.argmax(tf.math.equal(CLASS_NAMES, label_string)) return img, label ``` ## Train and evaluate a Neural Network (NN) model One way to get a more complex method is to interpose one or more Dense layers in between the input and output. The model now has three layers. A layer with trainable weights such as the one recently added, that is neither the input nor the output, is called a hidden layer. In Keras, you introduce the activation function with tf.keras.activations. The Rectified Linear Unit (ReLU) is the most commonly used activation function for hidden layers – other commonly used activation functions include sigmoid, tanh, and elu. ``` import tensorflow as tf import numpy as np import matplotlib.pylab as plt fig, ax = plt.subplots(1, 3, figsize=(10,5)) x = np.arange(-10.0, 10.0, 0.1) y = tf.keras.activations.sigmoid(x) ax[0].plot(x, y); ax[0].set_title("sigmoid") y = tf.keras.activations.relu(x) ax[1].plot(x, y); ax[1].set_title("relu") y = tf.keras.activations.elu(x) ax[2].plot(x, y); ax[2].set_title("elu"); model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(IMG_WIDTH, IMG_HEIGHT, 3)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(len(CLASS_NAMES), activation='softmax') ]) model.summary() tf.keras.utils.plot_model(model, show_shapes=True, show_layer_names=False) model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)), tf.keras.layers.Dense(len(CLASS_NAMES), activation='softmax') ]) model.summary() BATCH_SIZE = 32 train_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/train_set.csv"). map(decode_csv)).batch(BATCH_SIZE) eval_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/eval_set.csv"). map(decode_csv)).batch(BATCH_SIZE) # NN with one hidden layer model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)), tf.keras.layers.Dense(128, activation=tf.keras.activations.relu), tf.keras.layers.Dense(len(CLASS_NAMES), activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy']) history = # TODO 2 -- Your code here training_plot(['loss', 'accuracy'], history) ``` ## Training the neural network Training the neural network is similar to training the linear model. Compile the model passing in the optimizer, the loss, and the metrics. Then, call model.fit() passing in the datasets. ``` # parameterize to the values in the previous cell def train_and_evaluate(batch_size = 32, lrate = 0.001, # default in Adam constructor l1 = 0, l2 = 0, num_hidden = 128): regularizer = tf.keras.regularizers.l1_l2(l1, l2) train_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/train_set.csv"). map(decode_csv)).batch(batch_size) eval_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/eval_set.csv"). map(decode_csv)).batch(32) # this doesn't matter # NN with one hidden layers model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)), tf.keras.layers.Dense(num_hidden, kernel_regularizer=regularizer, activation=tf.keras.activations.relu), tf.keras.layers.Dense(len(CLASS_NAMES), kernel_regularizer=regularizer, activation='softmax') ]) model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lrate), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy']) history = model.fit(train_dataset, validation_data=eval_dataset, epochs=10) training_plot(['loss', 'accuracy'], history) return model ``` First, train your model by using 128 hidden layers. ``` model = train_and_evaluate(batch_size=32, lrate=0.0001, l1=0, l2=0, num_hidden=128) ``` You would normally expect that adding layers to a model will improve the ability of the model to fit the training data, and thus lower the loss. Notice that it is not always the case though. ``` model = train_and_evaluate(batch_size=32, lrate=0.0001, l1=0, l2=0, num_hidden=256) ``` ## Train and evaluate a Deep Neural Network model Now train a DNN. You need to parameterize the number of layers, and the number of nodes in each layer. ``` # parameterize to the values in the previous cell def train_and_evaluate(batch_size = 32, lrate = 0.0001, l1 = 0, l2 = 0.001, num_hidden = [64, 16]): regularizer = tf.keras.regularizers.l1_l2(l1, l2) train_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/train_set.csv"). map(decode_csv)).batch(batch_size) eval_dataset = (tf.data.TextLineDataset( "gs://practical-ml-vision-book/flowers_5_jpeg/flower_photos/eval_set.csv"). map(decode_csv)).batch(32) # this doesn't matter # NN with multiple hidden layers layers = [tf.keras.layers.Flatten( input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), name='input_pixels')] layers = layers + [ tf.keras.layers.Dense(nodes, kernel_regularizer=regularizer, activation=tf.keras.activations.relu, name='hidden_dense_{}'.format(hno)) for hno, nodes in enumerate(num_hidden) ] layers = layers + [ tf.keras.layers.Dense(len(CLASS_NAMES), kernel_regularizer=regularizer, activation='softmax', name='flower_prob') ] model = tf.keras.Sequential(layers, name='flower_classification') model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lrate), loss=tf.keras.losses.SparseCategoricalCrossentropy( from_logits=False), metrics=['accuracy']) print(model.summary()) history = model.fit(train_dataset, validation_data=eval_dataset, epochs=10) training_plot(['loss', 'accuracy'], history) return model model = # TODO 3 -- Your code here ``` Congrats! You've completed the lab!
github_jupyter
# Adau1761_0 IP This notebook serves as a quick demonstration of the audio codec being used in the **PYNQ-Z2 board**. A new IP has been introduced to make use of the codec. Before starting with this notebook please ensure you have the following: * Added the new audio.py file in the board * Added the new pl.py file in the board * Also, a new libsaudio.so is to be added ## How the new IP looks like? This is a screenshot of the addition done to the exsisting base overlay. Instead of the original audio IP block the new one looks like this <p align="center"> <img src ="./sources/IP.JPG" width="100%" height="100%"/> </p> As we can see : * The **adau1761_0** IP is where the main AXI interactions take place. It also conists of a serializer, to serialize the audio going to the headphone jack, and a deserializer, to decode the sound coming from the MIC. * The **axi_dma_0** IP is responsible for streaming audio data to the adau1761_0 through the _Slave AXI-Stream_ Interface of adau1761_0 * Thw **segement_stream_0** is responsible for controlling the _Master AXI_Stream_ Interface of adau1761_0 # Wavgen This is a seprate python function to generate a sine wave and save it as a _.wav_ file. The function description is as follows: ``` audio_write("name_of_the_file.wav", sampling rate, time period, frequency of sine wave) ``` ( Make sure to keep this jupyter nb in the same place where the wavegen.py file is) ``` from wavgen import audio_write audio_write("./output/samples.wav",100,5,44) ``` The waveform being generated: ``` %matplotlib inline import wave import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.fftpack import fft wav_path = "./output/samples.wav" with wave.open(wav_path, 'r') as wav_file: raw_frames = wav_file.readframes(-1) num_frames = wav_file.getnframes() num_channels = wav_file.getnchannels() sample_rate = wav_file.getframerate() sample_width = wav_file.getsampwidth() temp_buffer = np.empty((num_frames, num_channels, 4), dtype=np.uint8) raw_bytes = np.frombuffer(raw_frames, dtype=np.uint8) temp_buffer[:, :, :sample_width] = raw_bytes.reshape(-1, num_channels, sample_width) temp_buffer[:, :, sample_width:] = \ (temp_buffer[:, :, sample_width-1:sample_width] >> 7) * 255 frames = temp_buffer.view('<i4').reshape(temp_buffer.shape[:-1]) for channel_index in range(num_channels): plt.figure(num=None, figsize=(15, 3)) plt.title('Audio in Time Domain (Channel {})'.format(channel_index)) plt.xlabel('Time in s') plt.ylabel('Amplitude') time_axis = np.arange(0, num_frames/sample_rate, 1/sample_rate) plt.plot(time_axis, frames[:, channel_index]) plt.show() ``` # Initialization ### Create a new audio object ``` from audio import * base=Overlay("./sources/AXIS_audio.bit") Audiobj=base.adau1761_0 ``` ## Bypass audio Users can select either `LINE_IN`, or `HP+MIC` as the input port. In the following example, we choose `LINE_IN`. To choose `MIC`: ```python pAudio.select_microphone() ``` or choose `LINE_IN`: ```python pAudio.select_line_in() ``` ``` Audiobj.select_microphone() ``` ## Load and play Load a sample and play the loaded sample. ``` Audiobj.load("./sources/sine.wav") ``` ## Play function ## Stream Copy the list genrated from the audio file (the load() function generates this) into an array. ``` buf = Audiobj.buffer ``` Create a continous allocated memory numpy array ``` import pynq.lib.dma from pynq import Xlnk xlnk = Xlnk() dma_send = base.axi_dma_0 cma_ar = xlnk.cma_array(buf.shape, buf.dtype) cma_ar[:] = buf ``` The `playinit()` initializes the various audio codec registers. The numpy array which we declared above is passed onto the **DMA** send channel. ``` async def play_audio(): Audiobj.playinit() dma_send.sendchannel.transfer(cma_ar) await dma_send.sendchannel.wait_async() ``` ## Monitoring the CPU Usage To see how CPU usages is impacted by the audio stream we create another task that prints out the current CPU utilisation every 3 seconds. ``` import psutil import asyncio @asyncio.coroutine def print_cpu_usage(): # Calculate the CPU utilisation by the amount of idle time # each CPU has had in three second intervals last_idle = [c.idle for c in psutil.cpu_times(percpu=True)] while True: yield from asyncio.sleep(3) next_idle = [c.idle for c in psutil.cpu_times(percpu=True)] usage = [(1-(c2-c1)/3) * 100 for c1,c2 in zip(last_idle, next_idle)] print("CPU Usage: {0:3.2f}%, {1:3.2f}%".format(*usage)) last_idle = next_idle audio_task = asyncio.ensure_future(play_audio()) cpu_task = asyncio.ensure_future(print_cpu_usage()) asyncio.get_event_loop().run_until_complete(audio_task) ``` The `playend()` mutes the various audio codec registers which were being used. ``` Audiobj.playend() ``` ### Slave The play() function of the AXI-Slave is not configured properly. Please note. ``` Audiobj.play() ``` ## Record function Records a 5-second sample and is stored in a continous memory allocated array : ### Stream Enter the time for which the recording will take place: ``` seconds = 5 ``` Create a continous allocated memory numpy array ``` import numpy as np import pynq.lib.dma from pynq import Xlnk xlnk = Xlnk() dma_send = base.axi_dma_0 cma_ar = xlnk.cma_array(shape = seconds * 2 * 48000, dtype = "uint32") ``` The segement_stream is responsible for managing the AXI-Stream transactions between the `MIC` (Master AXI Stream) of the audio codec and the PS (Slave Stream). ``` base.segment_stream_0.write(0, seconds * 2 * 48000) ``` After this we have to send the audio array to the DMA ``` Audiobj.recordinit(seconds) dma_send.recvchannel.transfer(cma_ar) dma_send.recvchannel.wait() ``` And then to play it, we will use the DMA again to play from the array: ``` Audiobj.playinit() dma_send.sendchannel.transfer(cma_ar) dma_send.sendchannel.wait() Audiobj.playend() ``` ### Slave This here again is the recording function, but uses the **AXI-Slave** instead of the **AXI-Stream**. ``` Audiobj.record(seconds=5) Audiobj.play() ```
github_jupyter
# Cloud and sea tile classifier It has been identified that ESRGAN in both pretrain PSNR mode and GAN mode struggles with super-resoluting satellite image tiles completely covered by either sea surface or opaque clouds. In addition, both areas of interest, the harbors of Toulon and La Spezia, has lots of sea surface (approaching 50%). Left without intervention around 50% of tiles will only consist of sea and opaque clouds. It is assumed that this leads to an unwanted imbalance in what we want the model to be optimized to perform on. There are several ways to mitigate this imbalance. One way would be to manually draw a sea surface polygon in a GIS software and undersample tiles extracted from within this polygon. A downside of this approach is that interesting features (ships) within the sea surface polygon would also be undersampled. Another approach would be to train a cloud and sea tile classifier to detect the the unwanted tiles and discard all or a significant proportion of these tiles before training. This approach has the benefit of addressing the problem head on. The main downside of the approach is that it might be time-consuming to label tiles. However it is hypothesized that relatively little training data is needed to train a modern neural net classifier on such a *simple* classification task. ``` import pickle import geopandas import pandas as pd import pathlib import datetime import rasterio import rasterio.plot import tensorflow as tf from modules.tile_generator import * from modules.helpers import * from modules.image_utils import * from modules.tile_input_pipeline import * from modules.cloudsea_classifier import * # Check GPUs:", gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: for gpu in gpus: # Prevent TensorFlow from allocating all memory of all GPUs: tf.config.experimental.set_memory_growth(gpu, True) logical_gpus = tf.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: print(e) tf.sysconfig.get_build_info() # Toggles whether to actually do the generation on this run # Be careful with setting these to True if tiles are already labelled! # New tiles will overwrite old tiles and labels are trash GENERATE_NEW_TILES = False CONVERT_TO_PNG = False CREATE_LABEL_CSV = False with open('metadata_df.pickle', 'rb') as file: meta = pickle.load(file) # Path to location where individual satellite images are located DATA_PATH = 'data/toulon-laspezia/' DATA_PATH_TILES = 'data/toulon-laspezia-cloud-sea-classifier/' SENSORS = ['WV02', 'GE01', 'WV03_VNIR'] AREAS = ['La_Spezia', 'Toulon'] meta = meta.loc[meta['sensorVehicle'].isin(SENSORS)] meta = meta.loc[meta['area_name'].isin(AREAS)] N_IMAGES = len(meta.index) #96x96, 128x128, 196x196, 384x384 -- All tiles are squares TILE_SIZES = [96, 128, 196, 384] # number of tiles to generate at each tile size N_TILES = {96: 500, 128: 1000, 196: 500, 384: 500} N_TILES_TOTAL = sum(N_TILES.values()) print(N_IMAGES) print(N_TILES) print(N_TILES_TOTAL) TRAIN_TILE_SIZE = 224 PAN_OR_MS_OR_BOTH = 'pan' if PAN_OR_MS_OR_BOTH == 'pan': TRAIN_TILE_BANDS = 1 elif PAN_OR_MS_OR_BOTH == 'ms': TRAIN_TILE_BANDS = 4 elif PAN_OR_MS_OR_BOTH == 'both': TRAIN_TILE_BANDS = 5 RESIZE_METHOD = 'bilinear' BATCH_SIZE = 16 VAL_SPLIT = 0.3 ``` ## Allocate n_tiles to every image (weighted by size of image) ``` if GENERATE_NEW_TILES: meta = allocate_tiles(meta, by_partition=False, n_tiles_total=N_TILES[96], new_column_name='n_tiles_96') meta = allocate_tiles(meta, by_partition=False, n_tiles_total=N_TILES[128], new_column_name='n_tiles_128') meta = allocate_tiles(meta, by_partition=False, n_tiles_total=N_TILES[196], new_column_name='n_tiles_196') meta = allocate_tiles(meta, by_partition=False, n_tiles_total=N_TILES[384], new_column_name='n_tiles_384') meta ``` ## Generate tiles to disk ``` if GENERATE_NEW_TILES: meta['n_tiles'] = 0 for tile_size in TILE_SIZES: pathlib.Path(DATA_PATH_TILES).joinpath(str(tile_size)).mkdir() tile_size_ms = int(tile_size/4) meta['n_tiles'] = meta[str('n_tiles_'+str(tile_size))] generate_all_tiles(meta, save_dir = str(DATA_PATH_TILES+'/'+str(tile_size)), ms_height_width=(tile_size_ms,tile_size_ms), sr_factor=4, cloud_sea_removal=False) ``` ## Flatten the directory structure after generation Lots of foor loops in order to do one change at a time. ``` if GENERATE_NEW_TILES: # Remove train/val/test directories for tilesize_dir in pathlib.Path(DATA_PATH_TILES).iterdir(): for partition_dir in tilesize_dir.iterdir(): for image_dir in partition_dir.iterdir(): dest = tilesize_dir.joinpath(image_dir.stem) source = image_dir source.rename(dest) partition_dir.rmdir() # Add tile size to filenames for tilesize_dir in pathlib.Path(DATA_PATH_TILES).iterdir(): for image_dir in tilesize_dir.iterdir(): for ms_pan_dir in image_dir.iterdir(): for tile in ms_pan_dir.iterdir(): new_tile_name = str(tilesize_dir.stem+'-'+tile.name) new_path = ms_pan_dir.joinpath(new_tile_name) tile.rename(new_path) # Completely flatten file structure, remove tile size directories for tilesize_dir in pathlib.Path(DATA_PATH_TILES).iterdir(): for image_dir in tilesize_dir.iterdir(): for ms_pan_dir in image_dir.iterdir(): for tile in ms_pan_dir.iterdir(): new_dir = pathlib.Path(DATA_PATH_TILES).joinpath(image_dir.stem, ms_pan_dir.name) new_dir.mkdir(parents=True, exist_ok=True) new_path = new_dir.joinpath(tile.name) tile.rename(new_path) ms_pan_dir.rmdir() image_dir.rmdir() tilesize_dir.rmdir() # Add image_int_uid to filenames and flatten structure completely for image_dir in pathlib.Path(DATA_PATH_TILES).iterdir(): if image_dir.stem == 'ms' or image_dir.stem == 'pan': continue for ms_pan_dir in image_dir.iterdir(): for tile in ms_pan_dir.iterdir(): int_uid = get_int_uid(meta, image_dir.stem) new_tile_name = str(str(int_uid).zfill(2)+'-'+tile.name) new_dir = pathlib.Path(DATA_PATH_TILES).joinpath(ms_pan_dir.stem) new_dir.mkdir(parents=True, exist_ok=True) new_path = new_dir.joinpath(new_tile_name) tile.rename(new_path) ms_pan_dir.rmdir() image_dir.rmdir() # List all tif files tif_paths = [file for file in pathlib.Path(DATA_PATH_TILES).glob('**/*.tif')] tif_paths_ms = tif_paths[:2500] tif_paths_pan = tif_paths[2500:] # Divide by 2 because each tile consists of 1 MS + 1 PAN print('Number of tiles generated and present in flat file structure:', str(int(len(tif_paths)/2))) ``` # Convert to png While the input to the actual cloud/sea classifier is tif files it is practical to also convert the image tiles to png. This makes labelling easier. ``` if CONVERT_TO_PNG: for tif_path in tif_paths: ms_or_pan = tif_path.parent.stem # sensor type is needed for conversion of ms to rgb png:: int_uid = int(tif_path.stem[:2]) string_uid = get_string_uid(meta, int_uid) sensor = get_sensor(meta, string_uid) # saves png to disk geotiff_to_png(tif_path, ms_or_pan=ms_or_pan, scale=True, stretch_img=True, sensor=sensor) # List all png files png_paths = [file for file in pathlib.Path(DATA_PATH_TILES).glob('**/*.png')] # Divide by 2 because each tile consists of 1 MS + 1 PAN print('Number of tiles generated and present in flat file structure:', str(int(len(png_paths)/2))) ``` # Create label csv file Labels are `None` before manual labelling ``` if CREATE_LABEL_CSV: label_df = pd.DataFrame([tif_path.stem for tif_path in tif_paths[:N_TILES_TOTAL]], columns=['tile_uid']) label_df['cloud-sea'] = None label_df.to_csv(pathlib.Path(DATA_PATH_TILES).joinpath('labels-to-be.csv'), index=False) ``` # Labelling *... 4 tedious labelling hours later...* # Loading the labeled csv Our `load_and_populate_label_df` function also extracts `sensor`, `tile_size` and `img_uid` from the `tile_uid` column. This is used later when preparing data for training. ``` label_df = load_and_populate_label_df(DATA_PATH_TILES + '/labels.csv', meta) label_df ``` ## Preprocessing of images and labels Images in have different resolution. Classifier model architecture `EfficientNet` requires fixed image sizes as input so images are resized to `TRAIN_TILE_SIZE_PAN = 224`. [Native EfficientNet image sizes](https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/) Note that `EfficientNet` has rescaling and normalizing layers as their first layers so such preprocessing is not required in advance. In fact it seems like such preprocessing hurts performance of the model. We can therefore keep image tiles with `dtype=uint16`. ``` X, y = prepare_for_training(label_df, tif_paths_pan, tif_paths_ms, pan_or_ms_or_both=PAN_OR_MS_OR_BOTH, pan_tile_size=TRAIN_TILE_SIZE, ms_tile_size=TRAIN_TILE_SIZE, resize_method=RESIZE_METHOD) ``` ## Model ``` model = build_model(augment=True, input_shape=(TRAIN_TILE_SIZE, TRAIN_TILE_SIZE, TRAIN_TILE_BANDS)) model.summary() pretrain_model_name = str('cloud-sea-classifier-effnetb0-pan-augm') log_dir = pathlib.Path(str('logs/cloud-sea-classifier/fit/' + pretrain_model_name + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))) tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=10, write_graph=False, write_images=False, update_freq='epoch') checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filepath = str('models/cloud-sea-classifier/' + pretrain_model_name + '-{epoch:02d}-{val_loss:.6f}.h5'), monitor = "val_acc", save_best_only = False, save_weights_only = True, ) EPOCHS = 100 model.fit(X, y, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=VAL_SPLIT, initial_epoch=0, callbacks=[checkpoint_callback, tensorboard_callback]) ``` # Hyperparameter tuning ``` RESIZE_METHODS = ['bilinear', 'nearest', 'bicubic'] PAN_MS_BOTH = ['pan', 'ms', 'both'] LEARNING_RATES = [0.001, 0.0005, 0.0001] EPOCHS = 200 for resize_method in RESIZE_METHODS: for pan_ms_both in PAN_MS_BOTH: if pan_ms_both == 'pan': train_tile_bands = 1 elif pan_ms_both == 'ms': train_tile_bands = 4 elif pan_ms_both == 'both': train_tile_bands = 5 for learning_rate in LEARNING_RATES: X, y = prepare_for_training(label_df, tif_paths_pan, tif_paths_ms, pan_or_ms_or_both=pan_ms_both, pan_tile_size=TRAIN_TILE_SIZE, ms_tile_size=TRAIN_TILE_SIZE, resize_method=resize_method) model = build_model(augment=True, input_shape=(TRAIN_TILE_SIZE, TRAIN_TILE_SIZE, train_tile_bands), learning_rate=learning_rate) pretrain_model_name = str('cloudsea-effb0-augm-' + resize_method + '-' + pan_ms_both + '-' + str(learning_rate) + '-') log_dir = pathlib.Path(str('logs/cloud-sea-classifier/fit/' + pretrain_model_name + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))) tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=10, write_graph=False, write_images=False, update_freq='epoch') checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filepath = str('models/cloud-sea-classifier/' + pretrain_model_name + '-{epoch:02d}-{val_loss:.6f}.h5'), monitor = "val_acc", save_best_only = False, save_weights_only = True, ) model.fit(X, y, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=VAL_SPLIT, initial_epoch=0, callbacks=[checkpoint_callback, tensorboard_callback]) for ```
github_jupyter
<!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> *This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).* *The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!* <!--NAVIGATION--> < [IPython Magic Commands](01.03-Magic-Commands.ipynb) | [Contents](Index.ipynb) | [IPython and Shell Commands](01.05-IPython-And-Shell-Commands.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.04-Input-Output-History.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a> # Input and Output History Previously we saw that the IPython shell allows you to access previous commands with the up and down arrow keys, or equivalently the Ctrl-p/Ctrl-n shortcuts. Additionally, in both the shell and the notebook, IPython exposes several ways to obtain the output of previous commands, as well as string versions of the commands themselves. We'll explore those here. ## IPython's ``In`` and ``Out`` Objects By now I imagine you're quite familiar with the ``In [1]:``/``Out[1]:`` style prompts used by IPython. But it turns out that these are not just pretty decoration: they give a clue as to how you can access previous inputs and outputs in your current session. Imagine you start a session that looks like this: ```ipython In [1]: import math In [2]: math.sin(2) Out[2]: 0.9092974268256817 In [3]: math.cos(2) Out[3]: -0.4161468365471424 ``` We've imported the built-in ``math`` package, then computed the sine and the cosine of the number 2. These inputs and outputs are displayed in the shell with ``In``/``Out`` labels, but there's more–IPython actually creates some Python variables called ``In`` and ``Out`` that are automatically updated to reflect this history: ```ipython In [4]: print(In) ['', 'import math', 'math.sin(2)', 'math.cos(2)', 'print(In)'] In [5]: Out Out[5]: {2: 0.9092974268256817, 3: -0.4161468365471424} ``` The ``In`` object is a list, which keeps track of the commands in order (the first item in the list is a place-holder so that ``In[1]`` can refer to the first command): ```ipython In [6]: print(In[1]) import math ``` The ``Out`` object is not a list but a dictionary mapping input numbers to their outputs (if any): ```ipython In [7]: print(Out[2]) 0.9092974268256817 ``` Note that not all operations have outputs: for example, ``import`` statements and ``print`` statements don't affect the output. The latter may be surprising, but makes sense if you consider that ``print`` is a function that returns ``None``; for brevity, any command that returns ``None`` is not added to ``Out``. Where this can be useful is if you want to interact with past results. For example, let's check the sum of ``sin(2) ** 2`` and ``cos(2) ** 2`` using the previously-computed results: ```ipython In [8]: Out[2] ** 2 + Out[3] ** 2 Out[8]: 1.0 ``` The result is ``1.0`` as we'd expect from the well-known trigonometric identity. In this case, using these previous results probably is not necessary, but it can become very handy if you execute a very expensive computation and want to reuse the result! ## Underscore Shortcuts and Previous Outputs The standard Python shell contains just one simple shortcut for accessing previous output; the variable ``_`` (i.e., a single underscore) is kept updated with the previous output; this works in IPython as well: ```ipython In [9]: print(_) 1.0 ``` But IPython takes this a bit further—you can use a double underscore to access the second-to-last output, and a triple underscore to access the third-to-last output (skipping any commands with no output): ```ipython In [10]: print(__) -0.4161468365471424 In [11]: print(___) 0.9092974268256817 ``` IPython stops there: more than three underscores starts to get a bit hard to count, and at that point it's easier to refer to the output by line number. There is one more shortcut we should mention, however–a shorthand for ``Out[X]`` is ``_X`` (i.e., a single underscore followed by the line number): ```ipython In [12]: Out[2] Out[12]: 0.9092974268256817 In [13]: _2 Out[13]: 0.9092974268256817 ``` ## Suppressing Output Sometimes you might wish to suppress the output of a statement (this is perhaps most common with the plotting commands that we'll explore in [Introduction to Matplotlib](04.00-Introduction-To-Matplotlib.ipynb)). Or maybe the command you're executing produces a result that you'd prefer not like to store in your output history, perhaps so that it can be deallocated when other references are removed. The easiest way to suppress the output of a command is to add a semicolon to the end of the line: ```ipython In [14]: math.sin(2) + math.cos(2); ``` Note that the result is computed silently, and the output is neither displayed on the screen or stored in the ``Out`` dictionary: ```ipython In [15]: 14 in Out Out[15]: False ``` ## Related Magic Commands For accessing a batch of previous inputs at once, the ``%history`` magic command is very helpful. Here is how you can print the first four inputs: ```ipython In [16]: %history -n 1-4 1: import math 2: math.sin(2) 3: math.cos(2) 4: print(In) ``` As usual, you can type ``%history?`` for more information and a description of options available. Other similar magic commands are ``%rerun`` (which will re-execute some portion of the command history) and ``%save`` (which saves some set of the command history to a file). For more information, I suggest exploring these using the ``?`` help functionality discussed in [Help and Documentation in IPython](01.01-Help-And-Documentation.ipynb). <!--NAVIGATION--> < [IPython Magic Commands](01.03-Magic-Commands.ipynb) | [Contents](Index.ipynb) | [IPython and Shell Commands](01.05-IPython-And-Shell-Commands.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.04-Input-Output-History.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a>
github_jupyter
# Credit Card Fraud Detection Throughout the financial sector, machine learning algorithms are being developed to detect fraudulent transactions. In this project, that is exactly what we are going to be doing as well. Using a dataset of of nearly 28,500 credit card transactions and multiple unsupervised anomaly detection algorithms, we are going to identify transactions with a high probability of being credit card fraud. In this project, we will build and deploy the following two machine learning algorithms: * Local Outlier Factor (LOF) * Isolation Forest Algorithm ``` import sys import numpy import pandas import matplotlib import seaborn import scipy # import the necessary packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ``` ### 2. The Data Set ``` # Load the dataset from the csv file using pandas data = pd.read_csv('creditcard.csv') # Start exploring the dataset print(data.columns) # Print the shape of the data data = data.sample(frac=0.1, random_state = 1) print(data.shape) print(data.describe()) # V1 - V28 are the results of a PCA Dimensionality reduction to protect user identities and sensitive features # Plot histograms of each parameter data.hist(figsize = (20, 20)) plt.show() # Determine number of fraud cases in dataset Fraud = data[data['Class'] == 1] Valid = data[data['Class'] == 0] outlier_fraction = len(Fraud)/float(len(Valid)) print(outlier_fraction) print('Fraud Cases: {}'.format(len(data[data['Class'] == 1]))) print('Valid Transactions: {}'.format(len(data[data['Class'] == 0]))) # Correlation matrix corrmat = data.corr() fig = plt.figure(figsize = (12, 9)) sns.heatmap(corrmat, vmax = .8, square = True) plt.show() # Get all the columns from the dataFrame columns = data.columns.tolist() # Filter the columns to remove data we do not want columns = [c for c in columns if c not in ["Class"]] # Store the variable we'll be predicting on target = "Class" X = data[columns] Y = data[target] # Print shapes print(X.shape) print(Y.shape) ``` ## 3. Unsupervised Outlier Detection Now that we have processed our data, we can begin deploying our machine learning algorithms. We will use the following techniques: **Local Outlier Factor (LOF)** The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly score depends on how isolated the object is with respect to the surrounding neighborhood. **Isolation Forest Algorithm** The IsolationForest ‘isolates’ observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of the selected feature. Since recursive partitioning can be represented by a tree structure, the number of splittings required to isolate a sample is equivalent to the path length from the root node to the terminating node. This path length, averaged over a forest of such random trees, is a measure of normality and our decision function. Random partitioning produces noticeably shorter paths for anomalies. Hence, when a forest of random trees collectively produce shorter path lengths for particular samples, they are highly likely to be anomalies. ``` from sklearn.metrics import classification_report, accuracy_score from sklearn.ensemble import IsolationForest from sklearn.neighbors import LocalOutlierFactor # define random states state = 1 # define outlier detection tools to be compared classifiers = { "Isolation Forest": IsolationForest(max_samples=len(X), contamination=outlier_fraction, random_state=state), "Local Outlier Factor": LocalOutlierFactor( n_neighbors=20, contamination=outlier_fraction)} # Fit the model plt.figure(figsize=(9, 7)) n_outliers = len(Fraud) for i, (clf_name, clf) in enumerate(classifiers.items()): # fit the data and tag outliers if clf_name == "Local Outlier Factor": y_pred = clf.fit_predict(X) scores_pred = clf.negative_outlier_factor_ else: clf.fit(X) scores_pred = clf.decision_function(X) y_pred = clf.predict(X) # Reshape the prediction values to 0 for valid, 1 for fraud. y_pred[y_pred == 1] = 0 y_pred[y_pred == -1] = 1 n_errors = (y_pred != Y).sum() # Run classification metrics print('{}: {}'.format(clf_name, n_errors)) print(accuracy_score(Y, y_pred)) print(classification_report(Y, y_pred)) ```
github_jupyter
# Which U.S. Airport Has the Longest Flight Delays? #### A visualization for flight delay patterns in major US airports by Chen Chen ``` import pandas as pd import numpy as np import bqplot import ipywidgets url = 'https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/datasets/csv/airlines/airlines.csv?raw=true' airlines = pd.read_csv(url) airlines airlines['Minutes Delayed.Total'] = airlines['Minutes Delayed.Total'].astype('float') # Check for any null values airlines.isnull().sum() code = np.array(airlines['Code']) year = np.array(airlines['Year']) delay_min = np.array(airlines['Minutes Delayed.Total']) month = np.array(airlines['Month']) df1 = pd.DataFrame({'Code':code, 'Year':year, 'Minutes Delayed.Total':delay_min}) df2 = pd.DataFrame({'Month':month, 'Minutes Delayed.Total':delay_min}) table1 = pd.pivot_table(df1, values=['Minutes Delayed.Total'], index=['Year'], columns = ['Code'], aggfunc=np.mean, fill_value=0) table2 = pd.pivot_table(df2, values=['Minutes Delayed.Total'], index=['Month'], aggfunc=np.sum, fill_value=0) airport_code = table1.columns.levels[1].to_list() ####### GRID HEAT MAP ####### # scales col_sc = bqplot.ColorScale(scheme='RdPu') x_sc = bqplot.OrdinalScale() y_sc = bqplot.OrdinalScale() # axis col_ax = bqplot.ColorAxis(scale=col_sc, orientation='vertical', side='right') x_ax = bqplot.Axis(scale=x_sc, label='Airport.Code', tick_rotate=45) y_ax = bqplot.Axis(scale=y_sc, orientation='vertical', label='Year') # marks heat_map = bqplot.GridHeatMap(color=table1.values, row=table1.index, column=airport_code, scales={'color':col_sc,'row':y_sc, 'column':x_sc}, interactions={'click':'select'}, selected_style={'fill':'blue'}) fig = bqplot.Figure(marks=[heat_map], axes=[col_ax,x_ax, y_ax]) fig myLabel = ipywidgets.Label() ####### BAR PLOT ####### # scales x_scb = bqplot.LinearScale() y_scb = bqplot.LinearScale() # axis x_axb = bqplot.Axis(label='Month', scale=x_scb) y_axb = bqplot.Axis(label='Total Minutes Delayed', scale=y_scb, orientation='vertical') footage, footage_edges = np.histogram(table2.index.values, weights=table2['Minutes Delayed.Total'].values, bins=10) footage_centers = (footage_edges[:-1] + footage_edges[1:])/2 footage_hist = bqplot.Bars(x=footage_centers, y=footage, scales={'x':x_scb, 'y':y_scb},padding=0.03) fig_bars = bqplot.Figure(marks=[footage_hist],axes=[x_axb, y_axb]) fig_bars def on_selection(change): i,j = change['owner'].selected[0] v = table1.values[i,j] c = table1.columns.levels[1][j] myLabel.value = 'Airport: ' + str(c) + '; Mean of Total Minutes Delayed: ' + str(v) mask = (airlines['Year'] == table1.index[i]) & \ (airlines['Code'] == table1.columns.levels[1][j]) airlines_subset = airlines[mask] grouped = airlines_subset.groupby("Month")["Minutes Delayed.Total"].sum() months = grouped.index minutes = grouped.values footage_hist.x = months footage_hist.y = minutes heat_map.observe(on_selection,'selected') figures = ipywidgets.HBox([fig,fig_bars]) fig.layout.min_width='800px' fig_bars.layout.min_width='400px' dashboard = ipywidgets.VBox([myLabel,figures]) dashboard ``` The code above are modified based on my previous code for homework 6 and Week 7's in class notebook (https://uiuc-ischool-dataviz.github.io/is445_spring2022/nbv.html?notebook_name=%2Fis445_spring2022%2Fweek07%2FinClass_week07.ipynb). The dataset was obtained from the github page of CORGIS Dataset Project (https://github.com/RealTimeWeb/datasets/blob/master/datasets/csv/airlines/airlines.csv) and detailed explanations regarding the data could be retrieved from the webpage of CORGIS Dataset Project (https://think.cs.vt.edu/corgis/csv/airlines/). This dashboard is trying to explore the length of flight delays happened in each major US airport between June 2003 and January 2016. On the left hand side, the Grid Heat Map illustrates the monthly average minutes of flight delays at each airport within every single year and the darker the cell is, the longer the average delays are for that specific airport at such year. For example, we can tell from the plot that ATL(Hartsfield-Jackson Atlanta International Airport) and ORD(Chicago O'Hare International) are the top two airports that had experienced long delays during the 13 years because of the relatively darker cells they have. On the right hand side, the bar plot shows the details of total minutes delayed within each month of a given year and airport. By simply clicking the cell of intended year and airport in the Grid Heat Map, the audience can have a clear understanding about the patterns of monthly flight delays throughout the given year for such airport via the linked bar plot. In this way, the dashboard might help tourists who would be visiting those airports to learn about the potential length of flight delays and plan their schedules accordingly to avoid problems in advance. The first contextual visualization shown right below is based on the Airline On-Time Statistics and Delay Causes provided by Bureau of Transportation Statistics (https://www.transtats.bts.gov/OT_Delay/ot_delaycause1.asp?6B2r=FE&20=E). It visualizes data about the causes of delays in US domestic flights operated by major air carriers at ORD(Chicago O'Hare International) between June 2003 and January 2016. The reason why I choose ORD here is because from the dashboard above, we can tell that it is the airport that had experienced the longest delays. Since the central interactive visualization is mainly focusing on the detailed length of delays in minutes, this complementary graph could help us dig into the reasons behind flight delays and understand the length of delays in a new perspective. From the visualization below, we can see that the top 1 reason for flight delays at ORD is due to the National Aviation System Delay (11.3%). ![ORD%20Delays-3.png](attachment:ORD%20Delays-3.png) The second contextual visualization is also from the Bureau of Transportation Statistics (https://www.transtats.bts.gov/OT_Delay/ot_delaycause1.asp?6B2r=I&20=E) and it is kind of a continuation for the first contextual visualization. From the graph above, we realize that National Aviation System Delay is the biggest reason for flight delays in ORD between June 2003 to January 2016 and this time we are going to continue breaking down the causes of National Aviation System Delay. According to the definition from Bureau of Transportation Statistics (https://www.bts.gov/topics/airlines-and-airports/understanding-reporting-causes-flight-delays-and-cancellations), National Aviation System Delay refers to a broad range of circumstances led to delays, such as non-extreme weather conditions and heavy air traffic volume. Based on the visualization below, weather accounts for the highest proportion of such delays, i.e. 77.49%. If we go back to the main dashboard, we can see that the longer delays at ORD tend to happen during winter months and that are probably due to the heavy snow storms which usually occur in Midwest's winter. ![NAS-2.png](attachment:NAS-2.png)
github_jupyter
# Residual Networks Welcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](https://arxiv.org/pdf/1512.03385.pdf), allow you to train much deeper networks than were previously practically feasible. **In this assignment, you will:** - Implement the basic building blocks of ResNets. - Put together these building blocks to implement and train a state-of-the-art neural network for image classification. ## <font color='darkblue'>Updates</font> #### If you were working on the notebook before this update... * The current notebook is version "2a". * You can find your original work saved in the notebook with the previous version name ("v2") * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. #### List of updates * For testing on an image, replaced `preprocess_input(x)` with `x=x/255.0` to normalize the input image in the same way that the model's training data was normalized. * Refers to "shallower" layers as those layers closer to the input, and "deeper" layers as those closer to the output (Using "shallower" layers instead of "lower" or "earlier"). * Added/updated instructions. This assignment will be done in Keras. Before jumping into the problem, let's run the cell below to load the required packages. ``` import numpy as np from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras.applications.imagenet_utils import preprocess_input import pydot from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from keras.utils import plot_model from resnets_utils import * from keras.initializers import glorot_uniform import scipy.misc from matplotlib.pyplot import imshow %matplotlib inline import keras.backend as K K.set_image_data_format('channels_last') K.set_learning_phase(1) ``` ## 1 - The problem of very deep neural networks Last week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers. * The main benefit of a very deep network is that it can represent very complex functions. It can also learn features at many different levels of abstraction, from edges (at the shallower layers, closer to the input) to very complex features (at the deeper layers, closer to the output). * However, using a deeper network doesn't always help. A huge barrier to training them is vanishing gradients: very deep networks often have a gradient signal that goes to zero quickly, thus making gradient descent prohibitively slow. * More specifically, during gradient descent, as you backprop from the final layer back to the first layer, you are multiplying by the weight matrix on each step, and thus the gradient can decrease exponentially quickly to zero (or, in rare cases, grow exponentially quickly and "explode" to take very large values). * During training, you might therefore see the magnitude (or norm) of the gradient for the shallower layers decrease to zero very rapidly as training proceeds: <img src="images/vanishing_grad_kiank.png" style="width:450px;height:220px;"> <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Vanishing gradient** <br> The speed of learning decreases very rapidly for the shallower layers as the network trains </center></caption> You are now going to solve this problem by building a Residual Network! ## 2 - Building a Residual Network In ResNets, a "shortcut" or a "skip connection" allows the model to skip layers: <img src="images/skip_connection_kiank.png" style="width:650px;height:200px;"> <caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : A ResNet block showing a **skip-connection** <br> </center></caption> The image on the left shows the "main path" through the network. The image on the right adds a shortcut to the main path. By stacking these ResNet blocks on top of each other, you can form a very deep network. We also saw in lecture that having ResNet blocks with the shortcut also makes it very easy for one of the blocks to learn an identity function. This means that you can stack on additional ResNet blocks with little risk of harming training set performance. (There is also some evidence that the ease of learning an identity function accounts for ResNets' remarkable performance even more so than skip connections helping with vanishing gradients). Two main types of blocks are used in a ResNet, depending mainly on whether the input/output dimensions are same or different. You are going to implement both of them: the "identity block" and the "convolutional block." ### 2.1 - The identity block The identity block is the standard block used in ResNets, and corresponds to the case where the input activation (say $a^{[l]}$) has the same dimension as the output activation (say $a^{[l+2]}$). To flesh out the different steps of what happens in a ResNet's identity block, here is an alternative diagram showing the individual steps: <img src="images/idblock2_kiank.png" style="width:650px;height:150px;"> <caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Identity block.** Skip connection "skips over" 2 layers. </center></caption> The upper path is the "shortcut path." The lower path is the "main path." In this diagram, we have also made explicit the CONV2D and ReLU steps in each layer. To speed up training we have also added a BatchNorm step. Don't worry about this being complicated to implement--you'll see that BatchNorm is just one line of code in Keras! In this exercise, you'll actually implement a slightly more powerful version of this identity block, in which the skip connection "skips over" 3 hidden layers rather than 2 layers. It looks like this: <img src="images/idblock3_kiank.png" style="width:650px;height:150px;"> <caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Identity block.** Skip connection "skips over" 3 layers.</center></caption> Here are the individual steps. First component of main path: - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2a'`. Use 0 as the seed for the random initialization. - The first BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2a'`. - Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path: - The second CONV2D has $F_2$ filters of shape $(f,f)$ and a stride of (1,1). Its padding is "same" and its name should be `conv_name_base + '2b'`. Use 0 as the seed for the random initialization. - The second BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2b'`. - Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path: - The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and its name should be `conv_name_base + '2c'`. Use 0 as the seed for the random initialization. - The third BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2c'`. - Note that there is **no** ReLU activation function in this component. Final step: - The `X_shortcut` and the output from the 3rd layer `X` are added together. - **Hint**: The syntax will look something like `Add()([var1,var2])` - Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the ResNet identity block. We have implemented the first component of the main path. Please read this carefully to make sure you understand what it is doing. You should implement the rest. - To implement the Conv2D step: [Conv2D](https://keras.io/layers/convolutional/#conv2d) - To implement BatchNorm: [BatchNormalization](https://faroit.github.io/keras-docs/1.2.2/layers/normalization/) (axis: Integer, the axis that should be normalized (typically the 'channels' axis)) - For the activation, use: `Activation('relu')(X)` - To add the value passed forward by the shortcut: [Add](https://keras.io/layers/merge/#add) ``` # GRADED FUNCTION: identity_block def identity_block(X, f, filters, stage, block): """ Implementation of the identity block as defined in Figure 4 Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage -- integer, used to name the layers, depending on their position in the network block -- string/character, used to name the layers, depending on their position in the network Returns: X -- output of the identity block, tensor of shape (n_H, n_W, n_C) """ # defining name basis conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Retrieve Filters F1, F2, F3 = filters # Save the input value. You'll need this later to add back to the main path. X_shortcut = X # First component of main path X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X) X = Activation('relu')(X) ### START CODE HERE ### # Second component of main path (≈3 lines) X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X) X = Activation('relu')(X) # Third component of main path (≈2 lines) X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X) # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines) X = Add()([X, X_shortcut]) X = Activation('relu')(X) ### END CODE HERE ### return X tf.reset_default_graph() with tf.Session() as test: np.random.seed(1) A_prev = tf.placeholder("float", [3, 4, 4, 6]) X = np.random.randn(3, 4, 4, 6) A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a') test.run(tf.global_variables_initializer()) out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0}) print("out = " + str(out[0][1][1][0])) ``` **Expected Output**: <table> <tr> <td> **out** </td> <td> [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003] </td> </tr> </table> ## 2.2 - The convolutional block The ResNet "convolutional block" is the second block type. You can use this type of block when the input and output dimensions don't match up. The difference with the identity block is that there is a CONV2D layer in the shortcut path: <img src="images/convblock_kiank.png" style="width:650px;height:150px;"> <caption><center> <u> <font color='purple'> **Figure 4** </u><font color='purple'> : **Convolutional block** </center></caption> * The CONV2D layer in the shortcut path is used to resize the input $x$ to a different dimension, so that the dimensions match up in the final addition needed to add the shortcut value back to the main path. (This plays a similar role as the matrix $W_s$ discussed in lecture.) * For example, to reduce the activation dimensions's height and width by a factor of 2, you can use a 1x1 convolution with a stride of 2. * The CONV2D layer on the shortcut path does not use any non-linear activation function. Its main role is to just apply a (learned) linear function that reduces the dimension of the input, so that the dimensions match up for the later addition step. The details of the convolutional block are as follows. First component of main path: - The first CONV2D has $F_1$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '2a'`. Use 0 as the `glorot_uniform` seed. - The first BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2a'`. - Then apply the ReLU activation function. This has no name and no hyperparameters. Second component of main path: - The second CONV2D has $F_2$ filters of shape (f,f) and a stride of (1,1). Its padding is "same" and it's name should be `conv_name_base + '2b'`. Use 0 as the `glorot_uniform` seed. - The second BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2b'`. - Then apply the ReLU activation function. This has no name and no hyperparameters. Third component of main path: - The third CONV2D has $F_3$ filters of shape (1,1) and a stride of (1,1). Its padding is "valid" and it's name should be `conv_name_base + '2c'`. Use 0 as the `glorot_uniform` seed. - The third BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '2c'`. Note that there is no ReLU activation function in this component. Shortcut path: - The CONV2D has $F_3$ filters of shape (1,1) and a stride of (s,s). Its padding is "valid" and its name should be `conv_name_base + '1'`. Use 0 as the `glorot_uniform` seed. - The BatchNorm is normalizing the 'channels' axis. Its name should be `bn_name_base + '1'`. Final step: - The shortcut and the main path values are added together. - Then apply the ReLU activation function. This has no name and no hyperparameters. **Exercise**: Implement the convolutional block. We have implemented the first component of the main path; you should implement the rest. As before, always use 0 as the seed for the random initialization, to ensure consistency with our grader. - [Conv2D](https://keras.io/layers/convolutional/#conv2d) - [BatchNormalization](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis)) - For the activation, use: `Activation('relu')(X)` - [Add](https://keras.io/layers/merge/#add) ``` # GRADED FUNCTION: convolutional_block def convolutional_block(X, f, filters, stage, block, s = 2): """ Implementation of the convolutional block as defined in Figure 4 Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage -- integer, used to name the layers, depending on their position in the network block -- string/character, used to name the layers, depending on their position in the network s -- Integer, specifying the stride to be used Returns: X -- output of the convolutional block, tensor of shape (n_H, n_W, n_C) """ # defining name basis conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' # Retrieve Filters F1, F2, F3 = filters # Save the input value X_shortcut = X ##### MAIN PATH ##### # First component of main path X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X) X = Activation('relu')(X) ### START CODE HERE ### # Second component of main path (≈3 lines) X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X) X = Activation('relu')(X) # Third component of main path (≈2 lines) X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=glorot_uniform(seed=0))(X) X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X) ##### SHORTCUT PATH #### (≈2 lines) X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1', kernel_initializer=glorot_uniform(seed=0))(X_shortcut) X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut) # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines) X = Add()([X, X_shortcut]) X = Activation('relu')(X) ### END CODE HERE ### return X tf.reset_default_graph() with tf.Session() as test: np.random.seed(1) A_prev = tf.placeholder("float", [3, 4, 4, 6]) X = np.random.randn(3, 4, 4, 6) A = convolutional_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a') test.run(tf.global_variables_initializer()) out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0}) print("out = " + str(out[0][1][1][0])) ``` **Expected Output**: <table> <tr> <td> **out** </td> <td> [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603] </td> </tr> </table> ## 3 - Building your first ResNet model (50 layers) You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the architecture of this neural network. "ID BLOCK" in the diagram stands for "Identity block," and "ID BLOCK x3" means you should stack 3 identity blocks together. <img src="images/resnet_kiank.png" style="width:850px;height:150px;"> <caption><center> <u> <font color='purple'> **Figure 5** </u><font color='purple'> : **ResNet-50 model** </center></caption> The details of this ResNet-50 model are: - Zero-padding pads the input with a pad of (3,3) - Stage 1: - The 2D Convolution has 64 filters of shape (7,7) and uses a stride of (2,2). Its name is "conv1". - BatchNorm is applied to the 'channels' axis of the input. - MaxPooling uses a (3,3) window and a (2,2) stride. - Stage 2: - The convolutional block uses three sets of filters of size [64,64,256], "f" is 3, "s" is 1 and the block is "a". - The 2 identity blocks use three sets of filters of size [64,64,256], "f" is 3 and the blocks are "b" and "c". - Stage 3: - The convolutional block uses three sets of filters of size [128,128,512], "f" is 3, "s" is 2 and the block is "a". - The 3 identity blocks use three sets of filters of size [128,128,512], "f" is 3 and the blocks are "b", "c" and "d". - Stage 4: - The convolutional block uses three sets of filters of size [256, 256, 1024], "f" is 3, "s" is 2 and the block is "a". - The 5 identity blocks use three sets of filters of size [256, 256, 1024], "f" is 3 and the blocks are "b", "c", "d", "e" and "f". - Stage 5: - The convolutional block uses three sets of filters of size [512, 512, 2048], "f" is 3, "s" is 2 and the block is "a". - The 2 identity blocks use three sets of filters of size [512, 512, 2048], "f" is 3 and the blocks are "b" and "c". - The 2D Average Pooling uses a window of shape (2,2) and its name is "avg_pool". - The 'flatten' layer doesn't have any hyperparameters or name. - The Fully Connected (Dense) layer reduces its input to the number of classes using a softmax activation. Its name should be `'fc' + str(classes)`. **Exercise**: Implement the ResNet with 50 layers described in the figure above. We have implemented Stages 1 and 2. Please implement the rest. (The syntax for implementing Stages 3-5 should be quite similar to that of Stage 2.) Make sure you follow the naming convention in the text above. You'll need to use this function: - Average pooling [see reference](https://keras.io/layers/pooling/#averagepooling2d) Here are some other functions we used in the code below: - Conv2D: [See reference](https://keras.io/layers/convolutional/#conv2d) - BatchNorm: [See reference](https://keras.io/layers/normalization/#batchnormalization) (axis: Integer, the axis that should be normalized (typically the features axis)) - Zero padding: [See reference](https://keras.io/layers/convolutional/#zeropadding2d) - Max pooling: [See reference](https://keras.io/layers/pooling/#maxpooling2d) - Fully connected layer: [See reference](https://keras.io/layers/core/#dense) - Addition: [See reference](https://keras.io/layers/merge/#add) ``` # GRADED FUNCTION: ResNet50 def ResNet50(input_shape = (64, 64, 3), classes = 6): """ Implementation of the popular ResNet50 the following architecture: CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3 -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL -> TOPLAYER Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras """ # Define the input as a tensor with shape input_shape X_input = Input(input_shape) # Zero-Padding X = ZeroPadding2D((3, 3))(X_input) # Stage 1 X = Conv2D(64, (7, 7), strides = (2, 2), name = 'conv1', kernel_initializer = glorot_uniform(seed=0))(X) X = BatchNormalization(axis = 3, name = 'bn_conv1')(X) X = Activation('relu')(X) X = MaxPooling2D((3, 3), strides=(2, 2))(X) # Stage 2 X = convolutional_block(X, f = 3, filters = [64, 64, 256], stage = 2, block='a', s = 1) X = identity_block(X, 3, [64, 64, 256], stage=2, block='b') X = identity_block(X, 3, [64, 64, 256], stage=2, block='c') ### START CODE HERE ### # Stage 3 (≈4 lines) X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2) X = identity_block(X, 3, [128, 128, 512], stage=3, block='b') X = identity_block(X, 3, [128, 128, 512], stage=3, block='c') X = identity_block(X, 3, [128, 128, 512], stage=3, block='d') # Stage 4 (≈6 lines) X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2) X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b') X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c') X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d') X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e') X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f') # Stage 5 (≈3 lines) X = X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2) X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b') X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c') # AVGPOOL (≈1 line). Use "X = AveragePooling2D(...)(X)" X = AveragePooling2D(pool_size=(2, 2), padding='same')(X) ### END CODE HERE ### # output layer X = Flatten()(X) X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer = glorot_uniform(seed=0))(X) # Create model model = Model(inputs = X_input, outputs = X, name='ResNet50') return model ``` Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below. ``` model = ResNet50(input_shape = (64, 64, 3), classes = 6) ``` As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model. ``` model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ``` The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. <img src="images/signs_data_kiank.png" style="width:450px;height:250px;"> <caption><center> <u> <font color='purple'> **Figure 6** </u><font color='purple'> : **SIGNS dataset** </center></caption> ``` X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() # Normalize image vectors X_train = X_train_orig/255. X_test = X_test_orig/255. # Convert training and test labels to one hot matrices Y_train = convert_to_one_hot(Y_train_orig, 6).T Y_test = convert_to_one_hot(Y_test_orig, 6).T print ("number of training examples = " + str(X_train.shape[0])) print ("number of test examples = " + str(X_test.shape[0])) print ("X_train shape: " + str(X_train.shape)) print ("Y_train shape: " + str(Y_train.shape)) print ("X_test shape: " + str(X_test.shape)) print ("Y_test shape: " + str(Y_test.shape)) ``` Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. ``` model.fit(X_train, Y_train, epochs = 2, batch_size = 32) ``` **Expected Output**: <table> <tr> <td> ** Epoch 1/2** </td> <td> loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. </td> </tr> <tr> <td> ** Epoch 2/2** </td> <td> loss: between 1 and 5, acc: between 0.2 and 0.5, you should see your loss decreasing and the accuracy increasing. </td> </tr> </table> Let's see how this model (trained on only two epochs) performs on the test set. ``` preds = model.evaluate(X_test, Y_test) print ("Loss = " + str(preds[0])) print ("Test Accuracy = " + str(preds[1])) ``` **Expected Output**: <table> <tr> <td> **Test Accuracy** </td> <td> between 0.16 and 0.25 </td> </tr> </table> For the purpose of this assignment, we've asked you to train the model for just two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check correctness, the online grader will run your code only for a small number of epochs as well. After you have finished this official (graded) part of this assignment, you can also optionally train the ResNet for more iterations, if you want. We get a lot better performance when we train for ~20 epochs, but this will take more than an hour when training on a CPU. Using a GPU, we've trained our own ResNet50 model's weights on the SIGNS dataset. You can load and run our trained model on the test set in the cells below. It may take ≈1min to load the model. ``` model = load_model('ResNet50.h5') preds = model.evaluate(X_test, Y_test) print ("Loss = " + str(preds[0])) print ("Test Accuracy = " + str(preds[1])) ``` ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy. Congratulations on finishing this assignment! You've now implemented a state-of-the-art image classification system! ## 4 - Test on your own image (Optional/Ungraded) If you wish, you can also take a picture of your own hand and see the output of the model. To do this: 1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub. 2. Add your image to this Jupyter Notebook's directory, in the "images" folder 3. Write your image's name in the following code 4. Run the code and check if the algorithm is right! ``` img_path = 'images/my_image.jpg' img = image.load_img(img_path, target_size=(64, 64)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = x/255.0 print('Input image shape:', x.shape) my_image = scipy.misc.imread(img_path) imshow(my_image) print("class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = ") print(model.predict(x)) ``` You can also print a summary of your model by running the following code. ``` model.summary() ``` Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png". ``` plot_model(model, to_file='model.png') SVG(model_to_dot(model).create(prog='dot', format='svg')) ``` ## What you should remember - Very deep "plain" networks don't work in practice because they are hard to train due to vanishing gradients. - The skip-connections help to address the Vanishing Gradient problem. They also make it easy for a ResNet block to learn an identity function. - There are two main types of blocks: The identity block and the convolutional block. - Very deep Residual Networks are built by stacking these blocks together. ### References This notebook presents the ResNet algorithm due to He et al. (2015). The implementation here also took significant inspiration and follows the structure given in the GitHub repository of Francois Chollet: - Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun - [Deep Residual Learning for Image Recognition (2015)](https://arxiv.org/abs/1512.03385) - Francois Chollet's GitHub repository: https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
github_jupyter
<a href="https://colab.research.google.com/github/butchland/fastai_nb_explorations/blob/master/CollectRealFingersData.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Data Exploration notebooks for Fingers datasets ### Run using a CPU Runtime (no GPU needed) ## Environment setup ``` !curl https://course.fast.ai/setup/colab | bash !pip install fastai2 --upgrade !pip install fastcore --upgrade !pip install nbdev --upgrade from google.colab import drive drive.mount('/content/drive') from fastai2.vision.all import * escdrive = lambda x : x.as_posix().replace(' ','\ ') gdrive = Path('/content/drive/My Drive/fastai_v4') config = Config() data_path = config.d['data_path'] archive_path = config.d['archive_path'] model_path = config.d['model_path'] (data_path, archive_path,model_path) ``` ## Collect Realworld Pics as Test Data ``` from IPython.display import display, Javascript from google.colab.output import eval_js from base64 import b64decode def take_photo(filename='photo.jpg', quality=0.8): js = Javascript(''' async function takePhoto(quality) { const div = document.createElement('div'); const capture = document.createElement('button'); capture.textContent = 'Capture'; div.appendChild(capture); const video = document.createElement('video'); video.style.display = 'block'; const stream = await navigator.mediaDevices.getUserMedia({video: true}); document.body.appendChild(div); div.appendChild(video); video.srcObject = stream; await video.play(); // Resize the output to fit the video element. google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true); // Wait for Capture to be clicked. await new Promise((resolve) => capture.onclick = resolve); const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); stream.getVideoTracks()[0].stop(); div.remove(); return canvas.toDataURL('image/jpeg', quality); } ''') display(js) data = eval_js('takePhoto({})'.format(quality)) binary = b64decode(data.split(',')[1]) with open(filename, 'wb') as f: f.write(binary) return filename from IPython.display import Image try: filename = take_photo() print('Saved to {}'.format(filename)) # Show the image which was just taken. display(Image(filename)) except Exception as err: # Errors will be thrown if the user does not have a webcam or if they do not # grant the page permission to access it. print(str(err)) !mv photo.jpg test1_1R.jpg !mkdir -p data/fingers/testset/orig !mv *.jpg data/fingers/testset/orig dataset = 'testset' path = Path(data_path)/'fingers' ``` ## Backup realworld testset to GDrive ``` !tar -czf {(Path(data_path)/(dataset + '.tgz')).as_posix()} -C {Path(data_path).as_posix()} {path.as_posix()} !cp data/testset.tgz {escdrive(gdrive/'data'/'fingers_testset.tgz')} ```
github_jupyter
# Deep Learning & Art: Neural Style Transfer In 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! ## <font color='darkblue'>Updates</font> #### 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. ``` 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 ``` ## 1 - Problem Statement Neural 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). <img src="images/louvre_generated.png" style="width:750px;height:200px;"> Let's see how you can do this. ## 2 - Transfer Learning Neural 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. ``` pp = pprint.PrettyPrinter(indent=4) model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") pp.pprint(model) ``` * 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 layer To 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: ```python model["input"].assign(image) ``` This assigns the image as an input to the model. #### Activate a layer After 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: ```python sess.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 cost In 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. ``` content_image = scipy.misc.imread("images/louvre.jpg") imshow(content_image); ``` 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}$. <img src="images/NST_LOSS.png" style="width:800px;height:400px;"> **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. ``` tf.reshape() # 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=[-1, n_C]) a_G_unrolled = tf.reshape(a_G, shape=[-1, n_C]) # compute the cost with tensorflow (≈1 line) J_content = 1/(4 * n_H * n_W * n_C) * tf.reduce_sum((a_C - a_G)**2) ### 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())) ``` **Expected Output**: <table> <tr> <td> **J_content** </td> <td> 6.76559 </td> </tr> </table> #### 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 cost For our running example, we will use the following style image: ``` style_image = scipy.misc.imread("images/monet_800600.jpg") imshow(style_image); ``` 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: <img src="images/NST_GM.png" style="width:900px;height:300px;"> $$\mathbf{G}_{gram} = \mathbf{A}_{unrolled} \mathbf{A}_{unrolled}^T$$ #### $G_{(gram)i,j}$: correlation The 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). ``` # 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, A, transpose_b=True) ### 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())) ``` **Expected Output**: <table> <tr> <td> **GA** </td> <td> [[ 6.42230511 -4.42912197 -2.09668207] <br> [ -4.42912197 19.46583748 19.56387138] <br> [ -2.09668207 19.56387138 20.6864624 ]] </td> </tr> </table> ### 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. ``` # 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.transpose(tf.reshape(a_S, shape=[-1, n_C])) a_G = tf.transpose(tf.reshape(a_G, shape=[-1, n_C])) # 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 = 1/(2*n_C*n_H*n_W)**2 * tf.reduce_sum((GS-GG)**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())) ``` **Expected Output**: <table> <tr> <td> **J_style_layer** </td> <td> 9.19028 </td> </tr> </table> ### 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$) ``` STYLE_LAYERS = [ ('conv1_1', 0.2), ('conv2_1', 0.2), ('conv3_1', 0.2), ('conv4_1', 0.2), ('conv5_1', 0.2)] ``` 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. ``` 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 ``` **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. ``` # 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)) ``` **Expected Output**: <table> <tr> <td> **J** </td> <td> 35.34667875478276 </td> </tr> </table> ## 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 Session 2. Load the content image 3. Load the style image 4. Randomly initialize the image to be generated 5. Load the VGG19 model 7. 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 rate 8. 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 Sessions You'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. ``` # Reset the graph tf.reset_default_graph() # Start interactive session sess = tf.InteractiveSession() ``` #### Content image Let's load, reshape, and normalize our "content" image (the Louvre museum picture): ``` content_image = scipy.misc.imread("images/louvre_small.jpg") content_image = reshape_and_normalize_image(content_image) ``` #### Style image Let's load, reshape and normalize our "style" image (Claude Monet's painting): ``` style_image = scipy.misc.imread("images/monet.jpg") style_image = reshape_and_normalize_image(style_image) ``` #### Generated image correlated with content image Now, 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. ``` generated_image = generate_noise_image(content_image) imshow(generated_image[0]); ``` #### Load pre-trained VGG19 model Next, as explained in part (2), let's load the VGG19 model. ``` model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") ``` #### Content Cost To 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. ``` # 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) ``` #### Style cost ``` # 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) ``` ### 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`. ``` ### START CODE HERE ### (1 line) J = total_cost(J_content, J_style, alpha=10, beta=40) ### END CODE HERE ### ``` ### 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) ``` # define optimizer (1 line) optimizer = tf.train.AdamOptimizer(2.0) # define train_step (1 line) train_step = optimizer.minimize(J) ``` ### 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: ```Python sess.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: ```python model["input"].assign(image) ``` ``` 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) 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 ``` 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. ``` model_nn(sess, generated_image) ``` **Expected Output**: <table> <tr> <td> **Iteration 0 : ** </td> <td> total cost = 5.05035e+09 <br> content cost = 7877.67 <br> style cost = 1.26257e+08 </td> </tr> </table> You're done! After running this, in the upper bar of the notebook click on "File" and then "Open". Go to the "/output" directory to see all the saved images. Open "generated_image" to see the generated image! :) You should see something the image presented below on the right: <img src="images/louvre_generated.png" style="width:800px;height:300px;"> We didn't want you to wait too long to see an initial result, and so had set the hyperparameters accordingly. To get the best looking results, running the optimization algorithm longer (and perhaps with a smaller learning rate) might work better. After completing and submitting this assignment, we encourage you to come back and play more with this notebook, and see if you can generate even better looking images. Here are few other examples: - The beautiful ruins of the ancient city of Persepolis (Iran) with the style of Van Gogh (The Starry Night) <img src="images/perspolis_vangogh.png" style="width:750px;height:300px;"> - The tomb of Cyrus the great in Pasargadae with the style of a Ceramic Kashi from Ispahan. <img src="images/pasargad_kashi.png" style="width:750px;height:300px;"> - A scientific study of a turbulent fluid with the style of a abstract blue fluid painting. <img src="images/circle_abstract.png" style="width:750px;height:300px;"> ## 5 - Test with your own image (Optional/Ungraded) Finally, you can also rerun the algorithm on your own images! To do so, go back to part 4 and change the content image and style image with your own pictures. In detail, here's what you should do: 1. Click on "File -> Open" in the upper tab of the notebook 2. Go to "/images" and upload your images (requirement: (WIDTH = 300, HEIGHT = 225)), rename them "my_content.png" and "my_style.png" for example. 3. Change the code in part (3.4) from : ```python content_image = scipy.misc.imread("images/louvre.jpg") style_image = scipy.misc.imread("images/claude-monet.jpg") ``` to: ```python content_image = scipy.misc.imread("images/my_content.jpg") style_image = scipy.misc.imread("images/my_style.jpg") ``` 4. Rerun the cells (you may need to restart the Kernel in the upper tab of the notebook). You can share your generated images with us on social media with the hashtag #deeplearniNgAI or by direct tagging! You can also tune your hyperparameters: - Which layers are responsible for representing the style? STYLE_LAYERS - How many iterations do you want to run the algorithm? num_iterations - What is the relative weighting between content and style? alpha/beta ## 6 - Conclusion Great job on completing this assignment! You are now able to use Neural Style Transfer to generate artistic images. This is also your first time building a model in which the optimization algorithm updates the pixel values rather than the neural network's parameters. Deep learning has many different types of models and this is only one of them! ## What you should remember - Neural Style Transfer is an algorithm that given a content image C and a style image S can generate an artistic image - It uses representations (hidden layer activations) based on a pretrained ConvNet. - The content cost function is computed using one hidden layer's activations. - The style cost function for one layer is computed using the Gram matrix of that layer's activations. The overall style cost function is obtained using several hidden layers. - Optimizing the total cost function results in synthesizing new images. # Congratulations on finishing the course! This was the final programming exercise of this course. Congratulations--you've finished all the programming exercises of this course on Convolutional Networks! We hope to also see you in Course 5, on Sequence models! ### References: The Neural Style Transfer algorithm was due to Gatys et al. (2015). Harish Narayanan and Github user "log0" also have highly readable write-ups from which we drew inspiration. The pre-trained network used in this implementation is a VGG network, which is due to Simonyan and Zisserman (2015). Pre-trained weights were from the work of the MathConvNet team. - Leon A. Gatys, Alexander S. Ecker, Matthias Bethge, (2015). [A Neural Algorithm of Artistic Style](https://arxiv.org/abs/1508.06576) - Harish Narayanan, [Convolutional neural networks for artistic style transfer.](https://harishnarayanan.org/writing/artistic-style-transfer/) - Log0, [TensorFlow Implementation of "A Neural Algorithm of Artistic Style".](http://www.chioka.in/tensorflow-implementation-neural-algorithm-of-artistic-style) - Karen Simonyan and Andrew Zisserman (2015). [Very deep convolutional networks for large-scale image recognition](https://arxiv.org/pdf/1409.1556.pdf) - [MatConvNet.](http://www.vlfeat.org/matconvnet/pretrained/)
github_jupyter
# Terms metadata in Dataverse installations and effect of multiple-license update ## Goals of this notebook This notebook explores the "Terms" metadata of datasets in 56 known Dataverse installations as of August 2021. This snapshot may be used to learn more about the effects of the "multiple-license" update as it makes its way to the Dataverse software (https://github.com/IQSS/dataverse/pull/7920) and is applied to Dataverse installations. The "multiple-license" update will change how depositors enter "Terms" metadata (that is, metadata about how the data should or must be used). A goal of this update is to encourage the use and machine-readable application of standard licenses to datasets in Dataverse installations. This should make it easier for other people and systems to determine how the data can and can't be used. Additionally, with this update, if a dataset's Terms metadata includes values in any of the fields in the software's "Terms of Use" panel, such as Confidentiality Declaration and Special Permissions, the software will consider those terms to be "Custom Terms," even when a CC0 waiver (or a CCBY license in some forked Dataverse installations) was also applied. For more information about the update, see the Multiple License Consensus Proposal ([Google Doc](https://docs.google.com/document/d/10htygglMdlABYWqtcZpqd8sHOwIe6sLL_UJtTv8NEKw)) and the following GitHub issues and pull request: - https://github.com/IQSS/dataverse/issues/7742 - https://github.com/IQSS/dataverse/issues/7440 - https://github.com/IQSS/dataverse/pull/7920 So the two questions this notebook seeks to answer are: - How much of the dataset metadata published by each Dataverse installation includes any Terms metadata? This snapshot could be the first of ongoing efforts to track how Terms metadata in Dataverse installations change over time and particularly after each installation applies this and similar updates, as a way to measure the success of these changes and justify them. - When installations apply this update, which ones have published datasets with CC0 waivers (or, for some forked installations, CCBY licenses) plus any of the eight "Terms of Use" fields filled? The software will consider these datasets to have "Custom Terms". And how many of these datasets has each installation published? The community might use these numbers to get a sense of the scale of the change from this update, and the numbers might encourage each installation to look into the effects of this change. For example, a closer look at the metadata could reveal how the things that depositors enter into the "Custom Terms" fields do or do not conflict with the chosen CC waivers or licenses. ## Methods The Terms metadata published by 56 Dataverse installations is recorded in the terms_metadata.tab file. That tabular file was created by: - Downloading all zip files in the dataset at https://doi.org/10.7910/DVN/DCDKZQ. That dataset contains the JSON metadata files collected between August 4 and August 7, 2021 using a Python script. The methods for getting this metadata are described in the dataset's metadata. - Using another Python script to extract the JSON metadata files in each Zip file into a directory. - Parsing the terms metadata of every JSON metadata file in that directory into a single CSV file using the [parse_terms_metadata.py](https://github.com/jggautier/dataverse-scripts/blob/main/get-dataverse-metadata/parse_metadata_fields/parse_terms_metadata.py) script in the GitHub repository at https://github.com/jggautier/dataverse-scripts. - Parsing the value of each JSON files' "publisher" key, which indicates the installation that published the metadata in each JSON file, into a single CSV file using the [parse_basic_metadata.py](https://github.com/jggautier/dataverse_scripts/blob/main/get-dataverse-metadata/parse_metadata_fields/parse_basic_metadata.py) script in the GitHub repository at https://github.com/jggautier/dataverse-scripts. - Joining both CSV files into a single CSV file that contains the persistent URLs, dataset version IDs, installation names ("publishers"), and Terms metadata for every published dataset version, and converting that CSV file into a .tab file (so that it's easier to make this notebook accessible using the Dataverse software's [binder integration](https://guides.dataverse.org/en/5.7/admin/integrations.html?highlight=integrations#binder). This notebook uses the pandas and numpy Python packages to filter, reshape, and provide simple analysis of the data in the terms_metadata.tab file in order to help answer the two questions. ## Exploration ``` # Import Python packages from functools import reduce import numpy as np import pandas as pd ``` ### Importing and preparing the data ``` # Import data as a dataframe allVersions = pd.read_csv('terms_metadata.tab', sep='\t', na_filter = False, parse_dates=['datasetPublicationDate', 'versionCreateTime']) allVersions.head(5) print('Number of dataset versions: %s' % (len(allVersions))) print('Number of unique datasets: %s' % (len(allVersions.persistentUrl.unique()))) ``` **About dataset versioning and Terms metadata** While we know from experience that some datasets published in Dataverse installations contain versions where each version needs different Terms metadata, such as a dataset where each version represents a wave of the same longitudinal research study and data re-users should consider each dataset version's license, let's assume that for a large majority of datasets, the Terms metadata of their latest versions have replaced the metadata of their previous versions. For example, if a dataset has two published versions, the first version has no CC0 waiver, and the second version has a CC0 waiver, the CC0 waiver in the latest version is what should apply to the dataset (and one could argue that previous version should have been deaccessioned). Since dataset versioning in the Dataverse software is designed more as a way to record improvements to a dataset over time, as opposed to a way to publish disparate but connected datasets (such as waves in a longitudinal study), we'll assume that this is how most people use dataset versioning when publishing datasets in Dataverse installations. Additionally, the Dataverse software favors the latest published version of each dataset, tending to expose the metadata in the latest published version more than it exposes the metadata of previously published versions (such as through indexing and search result displays, metadata distributing, and how dataset PIDs direct users to the latest published version). So let's get and consider the Terms metadata for only the latest version of each dataset. ``` # Get only metadata for the latest versions of each dataset latestversion = (allVersions .iloc[allVersions .groupby('persistentUrl')['datasetVersionId'] .agg(pd.Series.idxmax)] .sort_values(by=['publisher'], inplace=False, ascending=True) .reset_index(drop=True, inplace=False)) ``` Let's prepare the rest of the data so it's easier to work with. ``` # Replace any blank values with NaN, making it easier to count and sort later latestversion = latestversion.replace(r'^\s*$', np.nan, regex=True) # Dartmouth's installation exports JSON dataset metadata files with "Root" in the "publisher" key. Replace "Root" with "Dartmouth" latestversion['publisher'] = latestversion['publisher'].replace(['Root'],'Dartmouth') ``` There shouldn't be too many unique values entered in the license fields, so let's see what's there. ``` # Let's see what's been entered in the license fields latestversion.license.unique() ``` From earlier experiences working with this metadata, I know that both the string "NONE" and null values (NaN) have been used to indicate that there's nothing in the license field. Let's replace all 'NONE' strings with NaN. ``` latestversion = latestversion.replace('NONE', np.nan) latestversion.head(5) ``` Finally, lets remove the datasetVersionId column and reorder the remaining columns so that the columns with basic info about each dataset are together and are followed by columns with the Terms metadata. ``` # Remove versionID column and reorder remaining columns latestversion = latestversion[[ 'publisher', 'persistentUrl', 'majorVersionNumber', 'minorVersionNumber', 'versionCreateTime', 'license', 'termsOfUse', 'confidentialityDeclaration', 'specialPermissions', 'restrictions', 'citationRequirements', 'depositorRequirements', 'conditions', 'disclaimer' ]] print('Number of datasets: %s' % (len(latestversion))) print('Number of installations: %s' % (len(latestversion.publisher.unique()))) ``` ### Question 1: How many datasets published by each Dataverse installation include any information about how the data can be used? We'll be exploring the Terms metadata of 155,719 datasets in 56 Dataverse installations. First let's get the counts of published datasets in each installation. Then we can compare those counts to the counts of published datasets that have any kind of Terms metadata. ``` countDatasetsByInstallation = latestversion.value_counts(subset=['publisher']).to_frame('count of datasets') countDatasetsByInstallation.head(5) ``` How many of those datasets have metadata with any Terms metadata? Let's take a look at a few rows from the latestversion dataframe to see how we might query it. ``` latestversion.head(5) # Create dataframe containing only datasets with something in their license fields or any Terms of Use fields datasetsWithAnyTerms = (latestversion .query('license.notnull() or termsOfUse.notnull() or confidentialityDeclaration.notnull() or specialPermissions.notnull() or restrictions.notnull() or citationRequirements.notnull() or depositorRequirements.notnull() or conditions.notnull() or disclaimer.notnull()') .reset_index(drop = True, inplace = False) ) ``` How many of those datasets are in each installation? ``` countDatasetsWithTermsByInstallation = datasetsWithAnyTerms.value_counts(subset=['publisher']).to_frame('count of datasets with any Terms') countDatasetsWithTermsByInstallation.head(5) # Combine the two dataframes so we can compare the count of datasets with any Terms to the count of all datasets dataframes = [ countDatasetsByInstallation, countDatasetsWithTermsByInstallation, ] countDatasetsWithAndWithoutTermsByInstallation = reduce(lambda left, right: left.join(right, how='outer'), dataframes) # Format the dataframe to replace NA values with 0 and cast the counts as integers countDatasetsWithAndWithoutTermsByInstallation = (countDatasetsWithAndWithoutTermsByInstallation .fillna(0) .astype('int32') ) # Add a column showing the percentage of datasets with any Terms countDatasetsWithAndWithoutTermsByInstallation['percent of datasets with any Terms'] = countDatasetsWithAndWithoutTermsByInstallation['count of datasets with any Terms'] / countDatasetsWithAndWithoutTermsByInstallation['count of datasets'] countDatasetsWithAndWithoutTermsByInstallation.head(5) ``` I think it might be helpful for some installations to see which datasets have no Terms metadata, so lets query for that and export the results to a CSV file. ``` datasetsWithNoTerms = (latestversion .query('(license == "NONE" or license.isnull()) and (termsOfUse.isnull() and confidentialityDeclaration.isnull() and specialPermissions.isnull() and restrictions.isnull() and citationRequirements.isnull() and depositorRequirements.isnull() and conditions.isnull() and disclaimer.isnull())') .reset_index(drop = True, inplace = False) ) print('Number of datasets with no Terms metadata: %s' % (len(datasetsWithNoTerms))) # Export dataframe to a CSV file datasetsWithNoTerms.to_csv('datasetsWithNoTerms.csv', index=False) ``` ### Question 2: When installations apply the changes in the "multiple license" software update, how many datasets will have "Custom Terms"? And how many of these datasets has each installation published? Again, the community might use these numbers to get a sense of the scale of the change from this update, and the numbers might encourage each installation to look into the effects of this change. For example, a closer look at the metadata could reveal how the things that depositors enter into the "Custom Terms" fields do or do not conflict with the chosen CC waivers or licenses. ``` # Create a new dataframe containing the datasets that have a value in the licenses field (that is, their license field is not null) plus one or more values in the Terms of Use fields datasetsWithCustomTerms = (latestversion .query('(license.notnull()) and (confidentialityDeclaration.notnull() or specialPermissions.notnull() or restrictions.notnull() or citationRequirements.notnull() or depositorRequirements.notnull() or conditions.notnull() or disclaimer.notnull())') .reset_index(drop = True, inplace = False) ) print('Number of datasets with something in the license field plus something in one or more Terms of Use fields: %s' % (len(datasetsWithCustomTerms))) datasetsWithCustomTerms.head(5) ``` How many of these datasets are in each Dataverse installation? ``` countDatasetsWithCustomTermsByInstallation = datasetsWithCustomTerms.value_counts(subset=['publisher']).to_frame('count of datasets with "Custom Terms"') countDatasetsWithCustomTermsByInstallation.head(5) ``` Finally, let's join this dataframe to the dataframe showing all datasets in each installation. ``` dataframes = [ countDatasetsByInstallation, countDatasetsWithCustomTermsByInstallation] countDatasetsWithAndWithoutCustomTermsByInstallation = reduce(lambda left, right: left.join(right, how='outer'), dataframes) # Format allCountsByInstallation dataframe to replace NA values with 0, cast values as integers and sort by greatest number of datasets with "Custom Terms" countDatasetsWithAndWithoutCustomTermsByInstallation = (countDatasetsWithAndWithoutCustomTermsByInstallation .fillna(0) .astype('int32') .sort_values([ 'count of datasets with "Custom Terms"', 'count of datasets'], ascending=False) ) # Add a column showing the percentage of datasets with any Terms countDatasetsWithAndWithoutCustomTermsByInstallation['percentage of datasets with "Custom Terms"'] = countDatasetsWithAndWithoutCustomTermsByInstallation['count of datasets with "Custom Terms"'] / countDatasetsWithAndWithoutCustomTermsByInstallation['count of datasets'] countDatasetsWithAndWithoutCustomTermsByInstallation.head(5) ``` Finally, it might also be helpful for some installations to see which datasets will be considered to have "Custom Terms", so lets export that dataframe to a CSV file. ``` # Export dataframe to a CSV file datasetsWithCustomTerms.to_csv('datasetsWithCustomTerms.csv', index=False) ```
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import os import editdistance import pickle import time from keras.optimizers import SGD, Adam from keras.callbacks import ModelCheckpoint from crnn_model import CRNN from crnn_data import InputGenerator from crnn_utils import decode from ssd_training import Logger, ModelSnapshot ``` ### Data ``` from data_icdar2015fst import GTUtility gt_util_train = GTUtility('data/ICDAR2013/') gt_util_test = GTUtility('data/ICDAR2013/', test=True) gt_util = GTUtility.merge(gt_util_train, gt_util_test) #print(gt_util) from data_synthtext import GTUtility #gt_util = GTUtility('data/SynthText/', polygon=True) file_name = 'gt_util_synthtext_seglink.pkl' #pickle.dump(gt_util, open(file_name,'wb')) with open(file_name, 'rb') as f: gt_util = pickle.load(f) gt_util_train, gt_util_val = GTUtility.split(gt_util, split=0.8) #print(gt_util) ``` ### Model ``` from crnn_utils import alphabet87 as alphabet input_width = 256 input_height = 32 batch_size = 128 input_shape = (input_width, input_height, 1) model, model_pred = CRNN(input_shape, len(alphabet), gru=False) experiment = 'crnn_lstm_synthtext' #model, model_pred = CRNN(input_shape, len(alphabet), gru=True) #experiment = 'crnn_gru_synthtext' max_string_len = model_pred.output_shape[1] gen_train = InputGenerator(gt_util_train, batch_size, alphabet, input_shape[:2], grayscale=True, max_string_len=max_string_len) gen_val = InputGenerator(gt_util_val, batch_size, alphabet, input_shape[:2], grayscale=True, max_string_len=max_string_len) ``` ### Training ``` checkdir = './checkpoints/' + time.strftime('%Y%m%d%H%M') + '_' + experiment if not os.path.exists(checkdir): os.makedirs(checkdir) with open(checkdir+'/source.py','wb') as f: source = ''.join(['# In[%i]\n%s\n\n' % (i, In[i]) for i in range(len(In))]) f.write(source.encode()) optimizer = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5) #optimizer = Adam(lr=0.02, epsilon=0.001, clipnorm=1.) # dummy loss, loss is computed in lambda layer model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=optimizer) #model.summary() model.fit_generator(generator=gen_train.generate(), # batch_size here? steps_per_epoch=gt_util_train.num_objects // batch_size, epochs=100, validation_data=gen_val.generate(), # batch_size here? validation_steps=gt_util_val.num_objects // batch_size, callbacks=[ #ModelCheckpoint(checkdir+'/weights.{epoch:03d}.h5', verbose=1, save_weights_only=True), ModelSnapshot(checkdir, 10000), Logger(checkdir) ], initial_epoch=0) ``` ### Predict ``` g = gen_val.generate() d = next(g) res = model_pred.predict(d[0]['image_input']) mean_ed = 0 mean_ed_norm = 0 #for i in range(len(res)): for i in range(10): # best path, real ocr applications use beam search with dictionary and language model chars = [alphabet[c] for c in np.argmax(res[i], axis=1)] gt_str = d[0]['source_str'][i] res_str = decode(chars) ed = editdistance.eval(gt_str, res_str) #ed = levenshtein(gt_str, res_str) ed_norm = ed / len(gt_str) mean_ed += ed mean_ed_norm += ed_norm # display image img = d[0]['image_input'][i][:,:,0].T plt.figure(figsize=[30,0.5]) plt.imshow(img, cmap='gray') ax = plt.gca() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() print('%-20s %-20s %s %0.2f' % (gt_str, res_str, ''.join(chars), ed_norm)) mean_ed /= len(res) mean_ed_norm /= len(res) print('\nmean editdistance: %0.3f\nmean normalized editdistance: %0.3f' % (mean_ed, mean_ed_norm)) ``` ### Test ``` model.load_weights('./checkpoints/201806162129_crnn_lstm_synthtext/weights.300000.h5') #model.load_weights('./checkpoints/201806190711_crnn_gru_synthtext/weights.300000.h5') g = gen_val.generate() n = 100000 #n = batch_size mean_ed = 0 mean_ed_norm = 0 mean_character_recogniton_rate = 0 sum_ed = 0 char_count = 0 correct_word_count = 0 word_recognition_rate = 0 j = 0 while j < n: d = next(g) res = model_pred.predict(d[0]['image_input']) for i in range(len(res)): if not j < n: break j += 1 # best path, real ocr applications use beam search with dictionary and language model chars = [alphabet[c] for c in np.argmax(res[i], axis=1)] gt_str = d[0]['source_str'][i] res_str = decode(chars) ed = editdistance.eval(gt_str, res_str) #ed = levenshtein(gt_str, res_str) ed_norm = ed / len(gt_str) mean_ed += ed mean_ed_norm += ed_norm sum_ed += ed char_count += len(gt_str) if ed == 0.: correct_word_count += 1 #print('%20s %20s %f' %(gt_str, res_str, ed)) mean_ed /= j mean_ed_norm /= j character_recogniton_rate = (char_count-sum_ed) / char_count word_recognition_rate = correct_word_count / j print() print('mean editdistance %0.3f' % (mean_ed)) print('mean normalized editdistance %0.3f' % (mean_ed_norm)) print('character recogniton rate %0.3f' % (character_recogniton_rate)) print('word recognition rate %0.3f' % (word_recognition_rate)) %%timeit res = model_pred.predict(d[0]['image_input'][1,None], batch_size=1) for i in range(len(res)): chars = [alphabet[c] for c in np.argmax(res[i], axis=1)] res_str = decode(chars) %%timeit res = model_pred.predict(d[0]['image_input'][:16], batch_size=16) for i in range(len(res)): chars = [alphabet[c] for c in np.argmax(res[i], axis=1)] res_str = decode(chars) ``` ### Example plots ``` g = gen_val.generate() d = next(g) res = model_pred.predict(d[0]['image_input']) mean_ed = 0 mean_ed_norm = 0 font = {'family': 'monospace', 'color': 'black', 'weight': 'normal', 'size': 12, } plot_name = 'crnn_sythtext' #for i in range(len(res)): for i in range(10): # best path, real ocr applications use beam search with dictionary and language model chars = [alphabet[c] for c in np.argmax(res[i], axis=1)] gt_str = d[0]['source_str'][i] res_str = decode(chars) ed = editdistance.eval(gt_str, res_str) #ed = levenshtein(gt_str, res_str) ed_norm = ed / len(gt_str) mean_ed += ed mean_ed_norm += ed_norm # display image img = d[0]['image_input'][i][:,:,0].T plt.figure(figsize=[10,1.03]) plt.imshow(img, cmap='gray', interpolation=None) ax = plt.gca() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.text(0, 45, '%s' % (''.join(chars)), fontdict=font) plt.text(0, 60, 'GT: %-24s RT: %-24s %0.2f' % (gt_str, res_str, ed_norm), fontdict=font) #file_name = 'plots/%s_recogniton_%03d.pgf' % (plot_name, i) file_name = 'plots/%s_recogniton_%03d.png' % (plot_name, i) #plt.savefig(file_name, bbox_inches='tight', dpi=300) #print(file_name) plt.show() #print('%-20s %-20s %s %0.2f' % (gt_str, res_str, ''.join(chars), ed_norm)) mean_ed /= len(res) mean_ed_norm /= len(res) print('\nmean editdistance: %0.3f\nmean normalized editdistance: %0.3f' % (mean_ed, mean_ed_norm)) from ssd_utils import calc_memory_usage, count_parameters crnn_lstm = CRNN((input_width, input_height, 1), len(alphabet), prediction_only=True, gru=False) crnn_gru = CRNN((input_width, input_height, 1), len(alphabet), prediction_only=True, gru=True) calc_memory_usage(crnn_lstm) count_parameters(crnn_lstm) calc_memory_usage(crnn_gru) count_parameters(crnn_gru) ```
github_jupyter
## The tutorial teaches how to deal with the imbalanced dataset: Two techniques we could use here are: * SMOTE * Near miss ``` # Importing the libraries: import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, confusion_matrix, recall_score from imblearn.over_sampling import SMOTE from imblearn.under_sampling import NearMiss ## importing the dataset: bank = pd.read_csv("bank-full.csv", sep = ";", na_values = "unknown") ## checking the first 3 rows and all the columns print(bank.head()) ## print(bank.shape) print(bank.columns) ## mapping the qualitative element in the columns to qualitatives ones: bank["default"] = bank["default"].map({"no":0,"yes":1}) bank["housing"] = bank["housing"].map({"no":0,"yes":1}) bank["loan"] = bank["loan"].map({"no":0,"yes":1}) bank["y"] = bank["y"].map({"no":0,"yes":1}) bank.education = bank.education.map({"primary": 0, "secondary":1, "tertiary":2}) # converting the may month to number: bank.month = pd.to_datetime(bank.month, format = "%b").dt.month ## checking for the number of NAN values columns wise: bank.isnull().sum() ## above we saw that "poutcome" and "contact" bank.drop(["poutcome", "contact"], axis = 1, inplace = True) ## getting rid of the rows where the NAN values are existing: bank.dropna(inplace = True) ## getting dummy values for multiple columns bank = pd.get_dummies(bank, drop_first = True) bank.y.value_counts() X = bank.drop("y", axis = 1) y = bank.y bank = pd.get_dummies(bank, drop_first = True) ## Checking the values of column "Y", this is our target variable: bank.y.value_counts() ## Separating the features and Target variable: X = bank.drop("y", axis = 1) y = bank.y ## Runing the model: X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1, stratify=y) y_train.value_counts() lr = LogisticRegression() lr.fit(X_train, y_train) ## predicting on the basis of model. y_pred = lr.predict(X_test) # creating the confusion matrix for better understanding confusion_matrix(y_test, y_pred) print("The accuracy score is",accuracy_score(y_test, y_pred)) print("Recall is",recall_score(y_test, y_pred)) ## So now let us balanced the imbalanced data: # train, test and split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1, stratify=y) # fitting the SMOTE smt = SMOTE() X_train, y_train = smt.fit_sample(X_train, y_train) np.bincount(y_train) # Again reruning the logistic regression lr = LogisticRegression() lr.fit(X_train, y_train) # prediction on the basis of SMOTE y_pred = lr.predict(X_test) # Confusion matrix confusion_matrix(y_test, y_pred) accuracy_score(y_test, y_pred) recall_score(y_test, y_pred) # Confusion matrix confusion_matrix(y_test, y_pred) print(accuracy_score(y_test, y_pred)) print("Recall has improve manifold",recall_score(y_test, y_pred)) ## using another technique of NEAR miss to get the imbalanced data as balanced: X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1, stratify=y) nr = NearMiss() X_train, y_train = nr.fit_sample(X_train, y_train) np.bincount(y_train) lr = LogisticRegression() lr.fit(X_train, y_train) y_pred = lr.predict(X_test) # result of the confusion matrix: confusion_matrix(y_test, y_pred) print("Accuracy score is",accuracy_score(y_test, y_pred)) print("Recall value",recall_score(y_test, y_pred)) ```
github_jupyter
``` import random import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt import esda import libpysal.weights as weights from esda.moran import Moran from shapely.geometry import Point, MultiPoint, LineString, Polygon, shape import json import pylab import libpysal import numpy as np from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics import f1_score from pyclustering.cluster.cure import cure from pyclustering.cluster.kmeans import kmeans from pyclustering.cluster.center_initializer import kmeans_plusplus_initializer from sklearn import preprocessing def permutation(lst): if len(lst) == 0: return [] if len(lst) == 1: return [lst] l = [] for i in range(len(lst)): m = lst[i] remLst = lst[:i] + lst[i+1:] for p in permutation(remLst): l.append([m] + p) return l def get_f1_score(df, permut): def match_clus(x, permut): if x == 0: return int(permut[0]) elif x == 1: return int(permut[1]) else: return x df["group_match"] = df["group"].apply(lambda x: match_clus(x, permut)) return df, f1_score(df.group_match.values, df.clus_group_gt.values, average='macro') def get_max_f1_score(df): max_f1 = 0 max_p = [] for p in permutation([3,4]): df, f1 = get_f1_score(df, p) if max_f1 < f1: max_f1 = f1 max_p = p print("f1_score ", max_f1, max_p) def cal_joint_statistic(nyc_data, w_voronoi): matched_connects = 0 all_neighbors_connects = 0 for obj_id, neighbors in w_voronoi.neighbors.items(): obj_clus = nyc_data.iat[obj_id, -1] for nei in neighbors: nei_clus = nyc_data.iat[nei, -1] all_neighbors_connects += 1 if obj_clus == nei_clus: matched_connects += 1 return matched_connects / all_neighbors_connects ``` # Processing NYC Check-in Data ``` nyc_check_in = gpd.read_file('data/nyc_checkin.shp') nyc_check_in.head(1) nyc_check_in.groupby("venueCateg").count().sort_values("venueId").tail(1) venueCateg_list = ["Office", "Home (private)"] venueId_list = pd.DataFrame(nyc_check_in.venueId.unique()).sample(frac=0.5).values.squeeze() nyc_check_sticc = nyc_check_in[(nyc_check_in.venueCateg.isin(venueCateg_list))&(nyc_check_in.venueId.isin(venueId_list))] print(nyc_check_sticc.shape) nyc_check_sticc.head(1) def return_week(x): if x == "Mon": return 1 elif x == "Tue": return 2 elif x == "Wed": return 3 elif x == "Thu": return 4 elif x == "Fri": return 5 elif x == "Sat": return 6 elif x == "Sun": return 7 def return_category(x): if x == "Gym": return 1 elif x == "Coffee Shop": return 2 elif x == "Office": return 3 elif x == "Home (private)": return 4 elif x == "Subway": return 5 nyc_check_sticc["week_attr"] = nyc_check_sticc["week"].apply(lambda x: return_week(x)) nyc_check_sticc["category"] = nyc_check_sticc["venueCateg"].apply(lambda x: return_category(x)) nyc_check_sticc = nyc_check_sticc.reset_index().drop("index", axis=1) nyc_check_sticc.head(1) kd = libpysal.cg.KDTree(np.array(nyc_check_sticc[["latitude", "longitude"]].values)) wnn = libpysal.weights.KNN(kd, 3) nearest_pt = pd.DataFrame().from_dict(wnn.neighbors, orient="index") for i in range(nearest_pt.shape[1]): nearest_pt = nearest_pt.rename({i:f"n_pt_{i}"}, axis=1) nearest_pt.head(1) nyc_check_sticc = nyc_check_sticc.join(nearest_pt) nyc_check_sticc.head(1) nyc_check_sticc[["week_attr", "hour", "n_pt_0", "n_pt_1", "n_pt_2"]].to_csv(r'nyc_checkin.txt', header=None, index=True, sep=',') w_voronoi = weights.Voronoi.from_dataframe(nyc_check_sticc) ``` # STICC ``` !python STICC_main.py --fname=nyc_checkin.txt --oname=result_nyc_checkin.txt --attr_idx_start=1 \ --attr_idx_end=2 --spatial_idx_start=3 --spatial_idx_end=5 \ --spatial_radius 4 --number_of_clusters 2 --lambda_parameter 10e-2 --beta 5 --maxIters 20 group = pd.read_table('result_nyc_checkin.txt', names=["group"]) result_nyc_check_sticc = nyc_check_sticc.join(group) result_nyc_check_sticc = result_nyc_check_sticc.rename({"category": "clus_group_gt"}, axis=1) print("Adjusted rand score", adjusted_rand_score(result_nyc_check_sticc["group"].values, result_nyc_check_sticc.clus_group_gt.values)) sp_contiguity = cal_joint_statistic(result_nyc_check_sticc, w_voronoi) print("Spatial contiguity: ", sp_contiguity) get_max_f1_score(result_nyc_check_sticc) ``` # Other methods ``` def get_pycluster_result(ground_truth, cluster_method): data = ground_truth[["week_attr", "hour"]].values # For K-Means data = ground_truth[["week_attr", "hour", "latitude", "longitude"]].values # For Sp K-Means if cluster_method == kmeans: initial_centers = kmeans_plusplus_initializer(data.tolist(), 2).initialize() instance = cluster_method(data.tolist(), initial_centers) elif cluster_method == cure: print("cure") instance = cure(data, 2) else: instance = cluster_method(data.tolist(), 2) instance.process() clusters = instance.get_clusters() clusters_result = [] for i, clus in enumerate(clusters): for data in clus: clusters_result.append([data, i]) clusters_result_df = pd.DataFrame(clusters_result, columns=["pt", "group"]).sort_values("pt").set_index("pt") return clusters_result_df ``` # K-Means ``` group = get_pycluster_result(nyc_check_sticc, kmeans) result_nyc_check_sticc = nyc_check_sticc.join(group) result_nyc_check_sticc = result_nyc_check_sticc.rename({"category": "clus_group_gt"}, axis=1) print("Adjusted rand score", adjusted_rand_score(result_nyc_check_sticc["group"].values, result_nyc_check_sticc.clus_group_gt.values)) sp_contiguity = cal_joint_statistic(result_nyc_check_sticc, w_voronoi) print("Spatial contiguity: ", sp_contiguity) get_max_f1_score(result_nyc_check_sticc) ``` # Sp K-Means ``` group = get_pycluster_result(nyc_check_sticc, kmeans) result_nyc_check_sticc = nyc_check_sticc.join(group) result_nyc_check_sticc = result_nyc_check_sticc.rename({"category": "clus_group_gt"}, axis=1) print("Adjusted rand score", adjusted_rand_score(result_nyc_check_sticc["group"].values, result_nyc_check_sticc.clus_group_gt.values)) sp_contiguity = cal_joint_statistic(result_nyc_check_sticc, w_voronoi) print("Spatial contiguity: ", sp_contiguity) get_max_f1_score(result_nyc_check_sticc) nyc_check_sticc.head(1) ``` # CURE ``` group = get_pycluster_result(nyc_check_sticc, cure) result_nyc_check_sticc = nyc_check_sticc.join(group) result_nyc_check_sticc = result_nyc_check_sticc.rename({"category": "clus_group_gt"}, axis=1) print("Adjusted rand score", adjusted_rand_score(result_nyc_check_sticc["group"].values, result_nyc_check_sticc.clus_group_gt.values)) sp_contiguity = cal_joint_statistic(result_nyc_check_sticc, w_voronoi) print("Spatial contiguity: ", sp_contiguity) get_max_f1_score(result_nyc_check_sticc) ``` # GMM ``` from sklearn.mixture import GaussianMixture gmm_data = nyc_check_sticc.copy() gmm_data.head(1) X = gmm_data[['hour', 'week_attr']].values gm = GaussianMixture(n_components=2).fit(X) gmm = pd.DataFrame(gm.predict(X), columns=["group"]) gmm.head(1) result_nyc_check_sticc = nyc_check_sticc.join(gmm) result_nyc_check_sticc = result_nyc_check_sticc.rename({"category": "clus_group_gt"}, axis=1) print("Adjusted rand score", adjusted_rand_score(result_nyc_check_sticc["group"].values, result_nyc_check_sticc.clus_group_gt.values)) sp_contiguity = cal_joint_statistic(result_nyc_check_sticc, w_voronoi) print("Spatial contiguity: ", sp_contiguity) get_max_f1_score(result_nyc_check_sticc) ```
github_jupyter
# Training of the model for Thumb Classification The goal of this notebook is to train a classification model that can detect thumb up and thumb down in video stream This notebook has been run on Google Colab to take advantage of the GPU. ``` import numpy as np import os import shutil from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix import tensorflow as tf import keras from keras.preprocessing.image import ImageDataGenerator from keras import backend as K from keras.applications.vgg16 import VGG16 from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg from keras.layers import Dense, Dropout, Flatten from keras.models import Model from keras import optimizers from keras.models import load_model import seaborn as sns ``` Define the three classification category ``` NB_CLASSES = 3 THUMB_UP = '01' THUMB_DOWN = '02' OTHER = '03' PATH_TO_ZIP = '/content/DSTI_Python_Labs/assets/data_train' ZIP_FILE = 'thumbv3.zip' IMAGES_RAW = 'images_raw_thumb' IMAGES_SPLITED = 'images_keras_thumb' MODEL_FILE = 'model_thumb_v24112020.h5' SAVE_FOLDER = 'save_model_thumb' ``` ## Get the training data from the github repository ``` !git clone https://github.com/EricKiennemann/DSTI_Python_Labs.git cd $PATH_TO_ZIP !mkdir $IMAGES_RAW ``` **Unzip the file training data file locally locally** ``` import zipfile with zipfile.ZipFile(ZIP_FILE, 'r') as zip_ref: zip_ref.extractall(IMAGES_RAW) !ls $IMAGES_RAW ``` ## Prepare the files for the processing Split the files into three datasets (folders) : * "train" for training * "valid" for validation * "test" for test ``` def TrainValidTestFruit(category): # Path to the directory where the original dataset was uncompressed original_dataset_dir = IMAGES_RAW # Directory where the three datasets will be stored base_dir = IMAGES_SPLITED os.mkdir(base_dir) # Directory for the training splits train_dir = os.path.join(base_dir, 'train') os.mkdir(train_dir) # Directory for the validation splits valid_dir = os.path.join(base_dir, 'valid') os.mkdir(valid_dir) # Directory for the test splits test_dir = os.path.join(base_dir, 'test') os.mkdir(test_dir) for cat in category: # Directories for training categories train_category_dir = os.path.join(train_dir, cat) os.mkdir(train_category_dir) # Directories for validation categories valid_category_dir = os.path.join(valid_dir, cat) os.mkdir(valid_category_dir) # Directories for test categories test_category_dir = os.path.join(test_dir, cat) os.mkdir(test_category_dir) data_folder = os.path.join(original_dataset_dir, cat) jpgfiles = os.listdir(data_folder) nb_images = len(jpgfiles) train_ratio = 0.75 # 75% of files for training validation_ratio = 0.15 # 15% of files for validation test_ratio = 0.10 # 10% of files for test dataX = np.arange(nb_images) # train is now 75% of the entire data set x_train, x_test = train_test_split(dataX, test_size=1 - train_ratio) # test is now 10% of the initial data set # validation is now 15% of the initial data set x_valid, x_test = train_test_split(x_test, test_size=test_ratio/(test_ratio + validation_ratio)) # Copy the train files fnames = [jpgfiles[i] for i in x_train] for fname in fnames: src = os.path.join(original_dataset_dir, cat, fname) dst = os.path.join(train_category_dir, fname) shutil.copyfile(src, dst) # Copy the validation files fnames = [jpgfiles[i] for i in x_valid] for fname in fnames: src = os.path.join(original_dataset_dir, cat, fname) dst = os.path.join(valid_category_dir, fname) shutil.copyfile(src, dst) # Copy the test files fnames = [jpgfiles[i] for i in x_test] for fname in fnames: src = os.path.join(original_dataset_dir, cat, fname) dst = os.path.join(test_category_dir, fname) shutil.copyfile(src, dst) # Sanity Check to ensure that Training, Validation and Test Folders have the expected number of images print('Number of Images in Training Directory is {} for category {}'.format(len(os.listdir(train_category_dir)),cat)) print('Number of Images in Validation Directory is {} for category {}'.format(len(os.listdir(valid_category_dir)),cat)) print('Number of Images in Test Directory is {} for category {}'.format(len(os.listdir(test_category_dir)),cat)) # Run the creation of the three datasets on our three labels TrainValidTestFruit([THUMB_UP,THUMB_DOWN,OTHER]) ``` The dataset is quit well balanced between 'thumb up' 517 images and 'thumb down' 593 images for training ## Building the Neural Network We'll be using VGG16 model and the corresponding preprocessing function for the input images. ``` # include_top=false => we only take the convolutional part not the classification part. # The image standard size is (224,224) base_model = VGG16(include_top=False, weights='imagenet', input_shape = (224,224,3)) base_model.summary() ``` Note that we have downloaded only a convolution part of the neural network. Let's add some dense layers on top of it. I choose a sigmoid activation in order to be able to dect more easelly when there is "nothing" in the screen. If the probability for both 'thumb up' and 'thumb down' are low it is likely that there is no thumb on the screen ``` flatten = Flatten()(base_model.output) dropout_1 = Dropout(0.25)(flatten) fc_1 = Dense(128)(dropout_1) dropout_2 = Dropout(0.5)(fc_1) predictions = Dense(NB_CLASSES, activation="sigmoid", name='predictions')(dropout_2) model = Model(base_model.input, predictions) ``` **The final model structure** ``` model.summary() ``` **Chosing the optimizer parameters and compiling the model** Categorical crossentropy is choosen for this multi label classification problem ``` loss = 'categorical_crossentropy' learning_rate = 0.001 optimizer = optimizers.SGD ## optimizers.SGD metrics = ['accuracy'] model.compile(loss=loss, optimizer=optimizer(learning_rate), metrics=metrics) ``` ## Data preparation We will do data augmentation in order to have more data for the training. We apply : * rotation * width shift * height shift ``` train_dir = os.path.join(IMAGES_SPLITED, "train") val_dir = os.path.join(IMAGES_SPLITED, "valid") test_dir = os.path.join(IMAGES_SPLITED, "test") # we'll resize images in correspondance to network input size image_size = (224,224) # apply some data augmentation # train_datagen = ImageDataGenerator(rotation_range=15, width_shift_range=0.2, height_shift_range=0.2, fill_mode='nearest', preprocessing_function=preprocess_input_vgg ) validation_datagen = ImageDataGenerator(preprocessing_function=preprocess_input_vgg) # for validation we don't need to augment train_batchsize = 40 val_batchsize = 40 # this function takes images from folders and feeds to Imagedatagenerator train_generator = train_datagen.flow_from_directory( train_dir, target_size=image_size, batch_size=train_batchsize, class_mode='categorical') validation_generator = validation_datagen.flow_from_directory( val_dir, target_size=image_size, batch_size=val_batchsize, class_mode='categorical', shuffle=False) ``` **The data generation is only applied to the train dataset** We do have 1370 images for training (without data augmentation) and 273 images for validation ## Model training Starting with a number of epoch equal to 100 ``` epochs = 60 nb_train_steps = train_generator.samples // train_generator.batch_size nb_val_steps = validation_generator.samples // validation_generator.batch_size history = model.fit_generator( train_generator, steps_per_epoch=nb_train_steps, epochs=epochs, validation_data=validation_generator, validation_steps=nb_val_steps, verbose=1, #0 ) ``` **The accuracy for training and validation dataset are good** ``` print('training acc.:',history.history['accuracy'][-1]) print('val acc.:', (history.history['val_accuracy'])[-1]) import matplotlib.pyplot as plt %matplotlib inline def plot_history(history): plt.figure(figsize=(12,6)) plt.subplot(1,2,1) plt.xlabel('Epoch') plt.ylabel('Accuracy %') plt.plot(history.epoch, np.array(history.history['accuracy']), label='Train Accuracy') plt.plot(history.epoch, np.array(history.history['val_accuracy']), label = 'Val Accuracy') plt.legend() plt.title('Accuracy for train and validation') plt.ylim([0, 1.1]) plt.subplot(1,2,2) plt.xlabel('Epoch') plt.ylabel('loss') plt.plot(history.epoch, np.array(history.history['loss']), label='Train Loss') plt.plot(history.epoch, np.array(history.history['val_loss']), label = 'Validation Loss') plt.legend() plt.title('Loss for train and validation') plt.show() plot_history(history) ``` ## Saving model The model is saved to be used in the back end part of the web application ``` os.makedirs(SAVE_FOLDER, exist_ok=True) model_path = os.path.join(SAVE_FOLDER, MODEL_FILE) model.save(model_path) ``` ## Final test on the test Dataset ``` model = load_model(model_path) ``` Apply the same preprocessing on the images as for validation dataset ``` test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input_vgg) ``` Realize the prediction ``` test_generator = test_datagen.flow_from_directory( test_dir, target_size=image_size, shuffle = False, class_mode='categorical', batch_size=1) filenames = test_generator.filenames nb_samples = len(filenames) predict = model.predict(test_generator,steps=nb_samples) ``` The prediction has been done for 185 images **See the result of the prediction** ``` def show_classification_confusion_matrix(y_valid,y_fit,list_classes): print(classification_report(y_valid, y_fit, target_names = list_classes)) mat = confusion_matrix(y_valid, y_fit) sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=list_classes, yticklabels=list_classes) plt.xlabel('true label') plt.ylabel('predicted label') # choose the higher probability as the best prediction y_pred = np.argmax(predict, axis=1) classes = ["{:02d}".format(i) for i in range(1, 4)] show_classification_confusion_matrix(test_generator.classes,y_pred,classes) ``` **All the images has been correctly predicted** **The model is kept and will be use for the web application** ## Store the model file on a google account ``` from google.colab import drive drive.mount('/content/gdrive') %cp $model_path ../../../gdrive/'My Drive' ```
github_jupyter
# Neuromorphic Computing Course ## 0. Example Code ### Download the program and move it up one directory. ``` # Delete everything in the content (current) directory on google colab !rm -rf /content/* || echo rm -rf /content/* failed # Clone git repo, change the branch and move it up by one level in the folder hierarchy !git clone https://gitlab.socsci.ru.nl/snnsimulator/simsnn.git !mv ./simsnn ./simsnnn !mv ./simsnnn/* ./ !rm -rf simsnnn || echo rm -rf simsnnn failed ``` ### Creating a programmed neuron. ``` from simsnn.core.networks import Network from simsnn.core.simulators import Simulator # Create the network and the simulator object net = Network() sim = Simulator(net) # Create a programmed neuron, that spikes on times 1 and 3, # does not repeat it's programming and has the ID "pn". programmed_neuron = net.createInputTrain(train=[0,1,0,1], loop=False, ID="pn") # Add all neurons to the raster sim.raster.addTarget(programmed_neuron) # Add all neurons to the multimeter sim.multimeter.addTarget(programmed_neuron) # Run the simulation for 10 rounds, enable the plotting of the raster, # the multimeter and the network structure. sim.run(steps=10, plotting=True) ``` Do you understand what is going on? ### Connecting two neurons with a synapse. ``` from simsnn.core.networks import Network from simsnn.core.simulators import Simulator net = Network() sim = Simulator(net) programmed_neuron = net.createInputTrain(train=[0,1,0,1], loop=False, ID="pn") # Create a LIF neuron, with a membrane voltage threshold of 1, # a post spike reset value of 0 and no voltage decay (m=1). lif_neuron = net.createLIF(ID="ln", thr=1, V_reset=0, m=1) # Create a Synapse, between the programmed neuron and the LIF neuron, # with a voltage weight of 1 and a delay of 1. net.createSynapse(pre=programmed_neuron, post=lif_neuron, ID="pn-ln", w=1, d=1) sim.raster.addTarget([programmed_neuron, lif_neuron]) sim.multimeter.addTarget([programmed_neuron, lif_neuron]) sim.run(steps=10, plotting=True) ``` Note how the LIF neuron does not ever seem to get any voltage. This is just an artifact of the timing of the voltage measurement. The voltages are measured at the end of every discrete timestep. When a LIF neuron spikes, its voltage will be reset to the V_reset value, which is 0 in this case. ### Creating an endlessly spiking neuron ``` from simsnn.core.networks import Network from simsnn.core.simulators import Simulator net = Network() sim = Simulator(net) # Create a neuron that has threshold of 4, a post spike reset value of 0, # no voltage decay and a constant input current of 1 lif_neuron = net.createLIF(ID="ln", thr=4, V_reset=0, m=1, I_e=1) sim.raster.addTarget([lif_neuron]) sim.multimeter.addTarget([lif_neuron]) sim.run(steps=10, plotting=True) ```
github_jupyter
``` import sys import os os.getcwd() os.chdir("/App") import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from alns.Problem import Problem import alns.TVRPAlgorithms as tvrp from alns.ALNS import ALNS from alns.criteria import HillClimbing, SimulatedAnnealing, RecordToRecordTravel, ThresholdAcceptance plt.rcParams["figure.figsize"]=10,10 ``` # Parallel Urgency Assignment using average travel time for cluster workload estimation ``` p = Problem("examples/Datasets/Data_1.csv", "examples/Datasets/Matrix_1.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Data_2.csv", "examples/Datasets/Matrix_2.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Data_3.csv", "examples/Datasets/Matrix_3.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Data_4.csv", "examples/Datasets/Matrix_4.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) ``` # Parallel Urgency Assignment using median travel time for cluster workload estimation ``` p = Problem("examples/Datasets/Data_1.csv", "examples/Datasets/Matrix_1.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Data_2.csv", "examples/Datasets/Matrix_2.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Data_3.csv", "examples/Datasets/Matrix_3.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) p = Problem("examples/Datasets/Datasets/Data_4.csv", "examples/Datasets/Datasets/Matrix_4.json") Graph, solution = tvrp.parallelUrgencyAssignment(p, True) print("Percent custs in holding after clustering", len(solution.unassignedRequests)/len(solution.problem.demand)) tvrp.buildSolutionParallelStyle(solution) print("Total objective: ", solution.objective()) avgCalculatedObjectives = [3039.70658, 2490.04619, 9133.95555, 1400.7912900000001] medianCalculatedObjectives = [1093.59721, 1328.25573, 5506.022669999999, 564.8194799999999] x = [1,2,3,4] ax = plt.figure().gca() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.set_title("objective values of the initial route construction: avg. vs median clustering") ax.set_xlabel("instance number") ax.set_ylabel("objective value") plt.plot(x, avgCalculatedObjectives, label="avg") plt.plot(x, medianCalculatedObjectives, label="median") plt.legend(loc="upper left") plt.show() avgCalculatedCustInHolding = [0.3333333333333333, 0.26666666666666666, 0.7916666666666666, 0.4] medianCalculatedCustInHolding = [0.0, 0.0, 0.375, 0.1] Ì x = [1,2,3,4] ax = plt.figure().gca() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.set_title("% of custs in holding after clustering: avg. vs median travel time approximation") ax.set_xlabel("instance number") ax.set_ylabel("% in holding") plt.plot(x, avgCalculatedCustInHolding, label="avg") plt.plot(x, medianCalculatedCustInHolding, label="median") plt.legend(loc="upper left") plt.show() ``` # Conclusions With a great variance in travel times due to the nature of the routing environment the estimated average travetime is too high, such that even nearby customers can not be assigned anymore even though (as tested many times running the alns algorithm) can be included in a solution easily. The median performs better both in percent of customers assigned and in the resulting ojective function of the initially constructed route.
github_jupyter
# Week2 ## Signals and Systems $x(n_1,n_2)$, $-\infty < n_1 , n_2 < \infty$, $n_1,n_2=0,\pm 1, \pm 2$ Orientation axes: $n_1$ is horizontal, $n_2$ is vertical coordinate. $n_1$ goes from $0$ to $N-1$. $m_1$ goes from $0$ to $M-1$. In case of RGB images, we have: $$ X(n_1*,n_2*) = \begin{bmatrix} X_R(n_1*,n_2*) \\[0.3em] X_G(n_1*,n_2*) \\[0.3em] X_B(n_1*,n_2*) \end{bmatrix} $$ Discrete Unit Impulse is: $$ \delta (n_1,n_2) = \begin{cases} 1 & \quad \text{for } n_1=n_2=0 \\ 0 & \quad \text{ otherwise}\\ \end{cases} $$ therefore: $$ \delta (n_1-n_1',n_2-n_2') = \begin{cases} 1 & \quad \text{for } n_1-n_1'=n_2-n_2'=0 \\ 0 & \quad \text{ otherwise}\\ \end{cases} $$ Also, there are Separable Signals (also means independent) if: $$ g(n_1,n_2)=f_1(n_1) \cdot f_2(n_2) $$ Discrete impulse signal is separable. Another definition is Discrete Unit Step: $$ u (n_1,n_2) = \begin{cases} 1 & \quad \text{for } n_1 \geq 0, n_2 \geq 0 \\ 0 & \quad \text{ otherwise}\\ \end{cases} $$ Also $u$ is separable. In fact $u(n_1,n_2)=u(n_1) \cdot u(n_2) $ ## Complex Exponential Signals Very important in DSP. $x(n_1,n_2)=e^{j\omega_1n_1} \cdot e^{j\omega_2n_2} $ . 1. They are Eigen-functions of LSI systems (a system that is linearly and spatial invariant: complex exponential goes through the LSI system). Therefore at the output we could have $Ae^{j\omega_1n_1+j\omega_2n_2}e^{j\Phi}$ 2. They are the building blocks of any signal. $$ x(n_1,n_2)=e^{j\omega_1n_1} \cdot e^{j\omega_2n_2}=\cos(\omega_1n_1+\omega_2n_2)+j \sin(\omega_1n_1+\omega_2n_2) $$ The module is 1: $$ |e^{j\omega_1n_1}| = |e^{j\omega_2n_2}| = 1 $$ They are also periodic signals: $$ e^{j(\omega_1+2\pi)n_1} e^{j(\omega_2+2\pi)n_2} = e^{j\omega_1n_1} e^{j\omega_2n_2} $$ What describes holds for 1d and multidimensional systems. To analyse the periodicity of the signal with respect to $n_1$ and $n_2$, then $N_1$ and $N_2$ have to be: $$ \omega_1N_1=2\pi k_1 , N_1 = k_1 \frac{2\pi }{\omega_1} $$ and $$ \omega_2N_2=2\pi k_2 , N_2 = k_2 \frac{2\pi }{\omega_2} $$ with $k$ and $N$ integers. In summary, unlike the continuous time complex exponentials, which are always periodic in time or spatial domain (not in frequency), the discrete time complex exponential are always periodic in the frequency domain but may or may not be periodic in the time or spatial domain. 1D Discrete cosine goes like $$ cos(\omega n) $$ ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(17,5)) omega = [0.0001, 1./8*np.pi, 1./4*np.pi, 1./2*np.pi, np.pi, 3./2.*np.pi, 7./4.*np.pi, 15./8.*np.pi, 2*np.pi] num_steps = 16 x = np.linspace(0, 2*np.pi, num_steps) for index, alpha in enumerate(omega): ax=plt.subplot(1, 9, index+1) markerline, stemlines, baseline = plt.stem(x, np.cos(alpha*x*(num_steps-1)/(2*np.pi)), '--') plt.setp(stemlines, 'color', 'b') plt.setp(baseline, 'color', 'k') plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) plt.title('$\omega$='+str(round(alpha,2))+', N='+str(round(2*np.pi/alpha,2))) plt.ylim([-2,2]) ``` The 2D Discrete cosine goes like: $$ cos(\omega_1 n_1 + \omega_2 n_2 ) $$ Also, to remember: $$ cos(\pi n_1) = (-1)^{n_1} $$ ``` import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(10,10)) omega1 = [0.0001, 1./8*np.pi, 1./4*np.pi, 1./2*np.pi, np.pi] omega2 = [0.0001, 1./8*np.pi, 1./4*np.pi, 1./2*np.pi, np.pi] num_steps = 8 x = np.linspace(0, 2*np.pi, num_steps) y = np.linspace(0, 2*np.pi, num_steps) X, Y = np.meshgrid(x, y) i=0 for index1, alpha1 in enumerate(omega1): for index2, alpha2 in enumerate(omega2): i+=1 ax=plt.subplot(5, 5, i) grid = np.cos((alpha1*X+alpha2*Y)*(num_steps-1)/(2*np.pi)) ax.imshow(grid, cmap=plt.cm.gray, interpolation='nearest', vmin=-1, vmax=1) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) plt.title('$\omega_1$='+str(round(alpha1,2))+', $\omega_2$='+str(round(alpha2,2))) ``` ## LSI Systems (Linear Shift-Invariant) $x(n_1,n_2) \rightarrow T[ \cdot ] \rightarrow y(n_1,n_2)=T[x(n_1,n_2)]$ This is a system, which can have indipendent properties as stability, With/out Memory, Causality, $\textbf{Linearity},\textbf{Spatial Invariance}$. $T$ can be an average, median, ... filter. If: $$ T[\alpha_1 x_1 (n_1,n_2)+\alpha_2 x_2 (n_1,n_2)] = \alpha_1 T[x_1 (n_1,n_2)]+\alpha_2 T[x_2 (n_1,n_2)] $$ Then $T[\cdot]$ is linear and have for example: $\alpha_2=0 \rightarrow T[\alpha_1 x_1 (n_1,n_2)]=\alpha_1 T [x_1 (n_1,n_2)]$ and $\alpha_1=-\alpha_2 \rightarrow T[0]=0$ An example of a non-linear system is finding the negative of an image: $$ y(n_1,n_2) = T[x(n_1,n_2)] = 255-x(n_1,n_2) $$ If I shift the input and find the shift in the output, then the system is Spatially Invariant: $$ T[x(n_1-k_1,n_2-k_2)]=y(n_1-k_1,n_2-k_2) $$ Finding the negative of an image is Spatially Invariant (or Spatially Varying). LSI are Systems that have both fore-mentioned properties. $$ \delta(n_1,n_2) \rightarrow LSI \rightarrow h(n_1,n_2)=\texttt{impulse respone} $$ and $$ x(n_1,n_2) \rightarrow h(n_1,n_2) \rightarrow y(n_1,n_2)=x(n_1,n_2) ** h(n_1,n_2) $$ The $**$ is 2D Discrete Convolution: $$ y(n_1,n_2)=x(n_1,n_2)**h(n_1,n_2) = \sum^{\infty}_{k_1=-\infty} \sum^{\infty}_{k_2=-\infty} x(k_1,k_2) \cdot h(n_1-k_1,n_2-k_2) $$ Convolution is commutative. ## 2D convolution This is one of the most important operations in signal processing. LSI are uniquely defined by their 2d input. The output is the convolution of the input with the impulse response of the system. The impulse response might have to be identified. $$ x(n_1,n_2) = \sum^{\infty}_{k_1=-\infty} \sum^{\infty}_{k_2=-\infty} x(k_1,k_2) \delta(n_1-k_1,n_2-k_2) $$ $$ y(n_1,n_2) = T\left[ x(n_1,n_2)\right] = T \left[ \sum^{\infty}_{k_1=-\infty} \sum^{\infty}_{k_2=-\infty} x(k_1,k_2) \delta(n_1-k_1,n_2-k_2) \right] $$ with x(k_1,k_2) that acts as a weight, a costant. If I'm working with a linear and spatially invariant system: $$ y(n_1,n_2) = \sum^{\infty}_{k_1=-\infty} \sum^{\infty}_{k_2=-\infty} x(k_1,k_2) \cdot h(n_1-k_1,n_2-k_2)=x(n_1,n_2)**h(n_1,n_2) $$ Convolution is made of Reflection, Shift and Summing. ``` # x(n1,n2) x1 = [0, 1, 2, 0, 1, 2] x2 = [0, 0, 0, 1, 1, 1] x3 = [1, 2, 3, 4, 5, 6] # h(n1,n2) h1 = [0, 1, 0, 1] h2 = [0, 0, 1, 1] h3 = [1, 1, 1, 1] # x(n1,n2)**h(n1,n2) y1 = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] y2 = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] y3 = [1, 3, 5, 3, 5, 12, 16, 9, 4, 9, 11, 6] from scipy import signal import numpy as np yy = signal.convolve2d(np.reshape(x3,(2,3)), np.reshape(h3,(2,2)), mode='same') plt.figure(figsize=(10,4)) ax=plt.subplot(1, 4, 1) ax.scatter(x1,x2, c='b',s=[x*50 for x in x3] ) plt.setp(ax.get_xticklabels(), visible=False); plt.setp(ax.get_yticklabels(), visible=False) plt.xlabel('$n_1$'); plt.ylabel('$n_2$') plt.xlim([-1,4]); plt.ylim([-1,3]); plt.title('$x(n_1,n_2)$') ax=plt.subplot(1, 4, 2) ax.scatter(h1,h2, c='r',s=[x*50 for x in h3] ) plt.setp(ax.get_xticklabels(), visible=False); plt.setp(ax.get_yticklabels(), visible=False) plt.xlabel('$n_1$'); plt.ylabel('$n_2$') plt.xlim([-1,4]); plt.ylim([-1,3]); plt.title('$h(n_1,n_2)$') ax=plt.subplot(1, 4, 3) ax.scatter(y1,y2, c='k',s=[x*50 for x in y3] ) plt.setp(ax.get_xticklabels(), visible=False); plt.setp(ax.get_yticklabels(), visible=False) plt.xlabel('$n_1$'); plt.ylabel('$n_2$') plt.xlim([-1,4]); plt.ylim([-1,3]); plt.title('$x(n_1,n_2)**h(n_1,n_2)$') ax=plt.subplot(1, 4, 4) ax.scatter(x1,x2, c='grey',s=[x*50 for x in yy] ) plt.setp(ax.get_xticklabels(), visible=False); plt.setp(ax.get_yticklabels(), visible=False) plt.xlabel('$n_1$'); plt.ylabel('$n_2$') plt.xlim([-1,4]); plt.ylim([-1,3]); plt.title("scipy.signal.convolve2d") ``` ## Filtering in the Spatial Domain We are studying $\bf{Boundary Effects}$. We could get for example zero-padding, symmetric, circular filter. Also, we can apply $\bf{Spatial Filtering}$, like LPF (Low pass filter) which generates a blurry image.. or HPF (High pass filter), which accentuates the edges of the image. LPF is also used for $\bf{Noise Reduction}$. Median Filtering helps a lot for Noise Reduction noise.
github_jupyter
# RadarCOVID-Report ## Data Extraction ``` import datetime import json import logging import os import shutil import tempfile import textwrap import uuid import matplotlib.pyplot as plt import matplotlib.ticker import numpy as np import pandas as pd import pycountry import retry import seaborn as sns %matplotlib inline current_working_directory = os.environ.get("PWD") if current_working_directory: os.chdir(current_working_directory) sns.set() matplotlib.rcParams["figure.figsize"] = (15, 6) extraction_datetime = datetime.datetime.utcnow() extraction_date = extraction_datetime.strftime("%Y-%m-%d") extraction_previous_datetime = extraction_datetime - datetime.timedelta(days=1) extraction_previous_date = extraction_previous_datetime.strftime("%Y-%m-%d") extraction_date_with_hour = datetime.datetime.utcnow().strftime("%Y-%m-%d@%H") current_hour = datetime.datetime.utcnow().hour are_today_results_partial = current_hour != 23 ``` ### Constants ``` from Modules.ExposureNotification import exposure_notification_io spain_region_country_code = "ES" germany_region_country_code = "DE" default_backend_identifier = spain_region_country_code backend_generation_days = 7 * 2 daily_summary_days = 7 * 4 * 3 daily_plot_days = 7 * 4 tek_dumps_load_limit = daily_summary_days + 1 ``` ### Parameters ``` environment_backend_identifier = os.environ.get("RADARCOVID_REPORT__BACKEND_IDENTIFIER") if environment_backend_identifier: report_backend_identifier = environment_backend_identifier else: report_backend_identifier = default_backend_identifier report_backend_identifier environment_enable_multi_backend_download = \ os.environ.get("RADARCOVID_REPORT__ENABLE_MULTI_BACKEND_DOWNLOAD") if environment_enable_multi_backend_download: report_backend_identifiers = None else: report_backend_identifiers = [report_backend_identifier] report_backend_identifiers environment_invalid_shared_diagnoses_dates = \ os.environ.get("RADARCOVID_REPORT__INVALID_SHARED_DIAGNOSES_DATES") if environment_invalid_shared_diagnoses_dates: invalid_shared_diagnoses_dates = environment_invalid_shared_diagnoses_dates.split(",") else: invalid_shared_diagnoses_dates = [] invalid_shared_diagnoses_dates ``` ### COVID-19 Cases ``` report_backend_client = \ exposure_notification_io.get_backend_client_with_identifier( backend_identifier=report_backend_identifier) @retry.retry(tries=10, delay=10, backoff=1.1, jitter=(0, 10)) def download_cases_dataframe(): return pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv") confirmed_df_ = download_cases_dataframe() confirmed_df_.iloc[0] confirmed_df = confirmed_df_.copy() confirmed_df = confirmed_df[["date", "new_cases", "iso_code"]] confirmed_df.rename( columns={ "date": "sample_date", "iso_code": "country_code", }, inplace=True) def convert_iso_alpha_3_to_alpha_2(x): try: return pycountry.countries.get(alpha_3=x).alpha_2 except Exception as e: logging.info(f"Error converting country ISO Alpha 3 code '{x}': {repr(e)}") return None confirmed_df["country_code"] = confirmed_df.country_code.apply(convert_iso_alpha_3_to_alpha_2) confirmed_df.dropna(inplace=True) confirmed_df["sample_date"] = pd.to_datetime(confirmed_df.sample_date, dayfirst=True) confirmed_df["sample_date"] = confirmed_df.sample_date.dt.strftime("%Y-%m-%d") confirmed_df.sort_values("sample_date", inplace=True) confirmed_df.tail() confirmed_days = pd.date_range( start=confirmed_df.iloc[0].sample_date, end=extraction_datetime) confirmed_days_df = pd.DataFrame(data=confirmed_days, columns=["sample_date"]) confirmed_days_df["sample_date_string"] = \ confirmed_days_df.sample_date.dt.strftime("%Y-%m-%d") confirmed_days_df.tail() def sort_source_regions_for_display(source_regions: list) -> list: if report_backend_identifier in source_regions: source_regions = [report_backend_identifier] + \ list(sorted(set(source_regions).difference([report_backend_identifier]))) else: source_regions = list(sorted(source_regions)) return source_regions report_source_regions = report_backend_client.source_regions_for_date( date=extraction_datetime.date()) report_source_regions = sort_source_regions_for_display( source_regions=report_source_regions) report_source_regions def get_cases_dataframe(source_regions_for_date_function, columns_suffix=None): source_regions_at_date_df = confirmed_days_df.copy() source_regions_at_date_df["source_regions_at_date"] = \ source_regions_at_date_df.sample_date.apply( lambda x: source_regions_for_date_function(date=x)) source_regions_at_date_df.sort_values("sample_date", inplace=True) source_regions_at_date_df["_source_regions_group"] = source_regions_at_date_df. \ source_regions_at_date.apply(lambda x: ",".join(sort_source_regions_for_display(x))) source_regions_at_date_df.tail() #%% source_regions_for_summary_df_ = \ source_regions_at_date_df[["sample_date", "_source_regions_group"]].copy() source_regions_for_summary_df_.rename(columns={"_source_regions_group": "source_regions"}, inplace=True) source_regions_for_summary_df_.tail() #%% confirmed_output_columns = ["sample_date", "new_cases", "covid_cases"] confirmed_output_df = pd.DataFrame(columns=confirmed_output_columns) for source_regions_group, source_regions_group_series in \ source_regions_at_date_df.groupby("_source_regions_group"): source_regions_set = set(source_regions_group.split(",")) confirmed_source_regions_set_df = \ confirmed_df[confirmed_df.country_code.isin(source_regions_set)].copy() confirmed_source_regions_group_df = \ confirmed_source_regions_set_df.groupby("sample_date").new_cases.sum() \ .reset_index().sort_values("sample_date") confirmed_source_regions_group_df = \ confirmed_source_regions_group_df.merge( confirmed_days_df[["sample_date_string"]].rename( columns={"sample_date_string": "sample_date"}), how="right") confirmed_source_regions_group_df["new_cases"] = \ confirmed_source_regions_group_df["new_cases"].clip(lower=0) confirmed_source_regions_group_df["covid_cases"] = \ confirmed_source_regions_group_df.new_cases.rolling(7, min_periods=0).mean().round() confirmed_source_regions_group_df = \ confirmed_source_regions_group_df[confirmed_output_columns] confirmed_source_regions_group_df = confirmed_source_regions_group_df.replace(0, np.nan) confirmed_source_regions_group_df.fillna(method="ffill", inplace=True) confirmed_source_regions_group_df = \ confirmed_source_regions_group_df[ confirmed_source_regions_group_df.sample_date.isin( source_regions_group_series.sample_date_string)] confirmed_output_df = confirmed_output_df.append(confirmed_source_regions_group_df) result_df = confirmed_output_df.copy() result_df.tail() #%% result_df.rename(columns={"sample_date": "sample_date_string"}, inplace=True) result_df = confirmed_days_df[["sample_date_string"]].merge(result_df, how="left") result_df.sort_values("sample_date_string", inplace=True) result_df.fillna(method="ffill", inplace=True) result_df.tail() #%% result_df[["new_cases", "covid_cases"]].plot() if columns_suffix: result_df.rename( columns={ "new_cases": "new_cases_" + columns_suffix, "covid_cases": "covid_cases_" + columns_suffix}, inplace=True) return result_df, source_regions_for_summary_df_ confirmed_eu_df, source_regions_for_summary_df = get_cases_dataframe( report_backend_client.source_regions_for_date) confirmed_es_df, _ = get_cases_dataframe( lambda date: [spain_region_country_code], columns_suffix=spain_region_country_code.lower()) ``` ### Extract API TEKs ``` raw_zip_path_prefix = "Data/TEKs/Raw/" base_backend_identifiers = [report_backend_identifier] multi_backend_exposure_keys_df = \ exposure_notification_io.download_exposure_keys_from_backends( backend_identifiers=report_backend_identifiers, generation_days=backend_generation_days, fail_on_error_backend_identifiers=base_backend_identifiers, save_raw_zip_path_prefix=raw_zip_path_prefix) multi_backend_exposure_keys_df["region"] = multi_backend_exposure_keys_df["backend_identifier"] multi_backend_exposure_keys_df.rename( columns={ "generation_datetime": "sample_datetime", "generation_date_string": "sample_date_string", }, inplace=True) multi_backend_exposure_keys_df.head() early_teks_df = multi_backend_exposure_keys_df[ multi_backend_exposure_keys_df.rolling_period < 144].copy() early_teks_df["rolling_period_in_hours"] = early_teks_df.rolling_period / 6 early_teks_df[early_teks_df.sample_date_string != extraction_date] \ .rolling_period_in_hours.hist(bins=list(range(24))) early_teks_df[early_teks_df.sample_date_string == extraction_date] \ .rolling_period_in_hours.hist(bins=list(range(24))) multi_backend_exposure_keys_df = multi_backend_exposure_keys_df[[ "sample_date_string", "region", "key_data"]] multi_backend_exposure_keys_df.head() active_regions = \ multi_backend_exposure_keys_df.groupby("region").key_data.nunique().sort_values().index.unique().tolist() active_regions multi_backend_summary_df = multi_backend_exposure_keys_df.groupby( ["sample_date_string", "region"]).key_data.nunique().reset_index() \ .pivot(index="sample_date_string", columns="region") \ .sort_index(ascending=False) multi_backend_summary_df.rename( columns={"key_data": "shared_teks_by_generation_date"}, inplace=True) multi_backend_summary_df.rename_axis("sample_date", inplace=True) multi_backend_summary_df = multi_backend_summary_df.fillna(0).astype(int) multi_backend_summary_df = multi_backend_summary_df.head(backend_generation_days) multi_backend_summary_df.head() def compute_keys_cross_sharing(x): teks_x = x.key_data_x.item() common_teks = set(teks_x).intersection(x.key_data_y.item()) common_teks_fraction = len(common_teks) / len(teks_x) return pd.Series(dict( common_teks=common_teks, common_teks_fraction=common_teks_fraction, )) multi_backend_exposure_keys_by_region_df = \ multi_backend_exposure_keys_df.groupby("region").key_data.unique().reset_index() multi_backend_exposure_keys_by_region_df["_merge"] = True multi_backend_exposure_keys_by_region_combination_df = \ multi_backend_exposure_keys_by_region_df.merge( multi_backend_exposure_keys_by_region_df, on="_merge") multi_backend_exposure_keys_by_region_combination_df.drop( columns=["_merge"], inplace=True) if multi_backend_exposure_keys_by_region_combination_df.region_x.nunique() > 1: multi_backend_exposure_keys_by_region_combination_df = \ multi_backend_exposure_keys_by_region_combination_df[ multi_backend_exposure_keys_by_region_combination_df.region_x != multi_backend_exposure_keys_by_region_combination_df.region_y] multi_backend_exposure_keys_cross_sharing_df = \ multi_backend_exposure_keys_by_region_combination_df \ .groupby(["region_x", "region_y"]) \ .apply(compute_keys_cross_sharing) \ .reset_index() multi_backend_cross_sharing_summary_df = \ multi_backend_exposure_keys_cross_sharing_df.pivot_table( values=["common_teks_fraction"], columns="region_x", index="region_y", aggfunc=lambda x: x.item()) multi_backend_cross_sharing_summary_df multi_backend_without_active_region_exposure_keys_df = \ multi_backend_exposure_keys_df[multi_backend_exposure_keys_df.region != report_backend_identifier] multi_backend_without_active_region = \ multi_backend_without_active_region_exposure_keys_df.groupby("region").key_data.nunique().sort_values().index.unique().tolist() multi_backend_without_active_region exposure_keys_summary_df = multi_backend_exposure_keys_df[ multi_backend_exposure_keys_df.region == report_backend_identifier] exposure_keys_summary_df.drop(columns=["region"], inplace=True) exposure_keys_summary_df = \ exposure_keys_summary_df.groupby(["sample_date_string"]).key_data.nunique().to_frame() exposure_keys_summary_df = \ exposure_keys_summary_df.reset_index().set_index("sample_date_string") exposure_keys_summary_df.sort_index(ascending=False, inplace=True) exposure_keys_summary_df.rename(columns={"key_data": "shared_teks_by_generation_date"}, inplace=True) exposure_keys_summary_df.head() ``` ### Dump API TEKs ``` tek_list_df = multi_backend_exposure_keys_df[ ["sample_date_string", "region", "key_data"]].copy() tek_list_df["key_data"] = tek_list_df["key_data"].apply(str) tek_list_df.rename(columns={ "sample_date_string": "sample_date", "key_data": "tek_list"}, inplace=True) tek_list_df = tek_list_df.groupby( ["sample_date", "region"]).tek_list.unique().reset_index() tek_list_df["extraction_date"] = extraction_date tek_list_df["extraction_date_with_hour"] = extraction_date_with_hour tek_list_path_prefix = "Data/TEKs/" tek_list_current_path = tek_list_path_prefix + f"/Current/RadarCOVID-TEKs.json" tek_list_daily_path = tek_list_path_prefix + f"Daily/RadarCOVID-TEKs-{extraction_date}.json" tek_list_hourly_path = tek_list_path_prefix + f"Hourly/RadarCOVID-TEKs-{extraction_date_with_hour}.json" for path in [tek_list_current_path, tek_list_daily_path, tek_list_hourly_path]: os.makedirs(os.path.dirname(path), exist_ok=True) tek_list_base_df = tek_list_df[tek_list_df.region == report_backend_identifier] tek_list_base_df.drop(columns=["extraction_date", "extraction_date_with_hour"]).to_json( tek_list_current_path, lines=True, orient="records") tek_list_base_df.drop(columns=["extraction_date_with_hour"]).to_json( tek_list_daily_path, lines=True, orient="records") tek_list_base_df.to_json( tek_list_hourly_path, lines=True, orient="records") tek_list_base_df.head() ``` ### Load TEK Dumps ``` import glob def load_extracted_teks(mode, region=None, limit=None) -> pd.DataFrame: extracted_teks_df = pd.DataFrame(columns=["region"]) file_paths = list(reversed(sorted(glob.glob(tek_list_path_prefix + mode + "/RadarCOVID-TEKs-*.json")))) if limit: file_paths = file_paths[:limit] for file_path in file_paths: logging.info(f"Loading TEKs from '{file_path}'...") iteration_extracted_teks_df = pd.read_json(file_path, lines=True) extracted_teks_df = extracted_teks_df.append( iteration_extracted_teks_df, sort=False) extracted_teks_df["region"] = \ extracted_teks_df.region.fillna(spain_region_country_code).copy() if region: extracted_teks_df = \ extracted_teks_df[extracted_teks_df.region == region] return extracted_teks_df daily_extracted_teks_df = load_extracted_teks( mode="Daily", region=report_backend_identifier, limit=tek_dumps_load_limit) daily_extracted_teks_df.head() exposure_keys_summary_df_ = daily_extracted_teks_df \ .sort_values("extraction_date", ascending=False) \ .groupby("sample_date").tek_list.first() \ .to_frame() exposure_keys_summary_df_.index.name = "sample_date_string" exposure_keys_summary_df_["tek_list"] = \ exposure_keys_summary_df_.tek_list.apply(len) exposure_keys_summary_df_ = exposure_keys_summary_df_ \ .rename(columns={"tek_list": "shared_teks_by_generation_date"}) \ .sort_index(ascending=False) exposure_keys_summary_df = exposure_keys_summary_df_ exposure_keys_summary_df.head() ``` ### Daily New TEKs ``` tek_list_df = daily_extracted_teks_df.groupby("extraction_date").tek_list.apply( lambda x: set(sum(x, []))).reset_index() tek_list_df = tek_list_df.set_index("extraction_date").sort_index(ascending=True) tek_list_df.head() def compute_teks_by_generation_and_upload_date(date): day_new_teks_set_df = tek_list_df.copy().diff() try: day_new_teks_set = day_new_teks_set_df[ day_new_teks_set_df.index == date].tek_list.item() except ValueError: day_new_teks_set = None if pd.isna(day_new_teks_set): day_new_teks_set = set() day_new_teks_df = daily_extracted_teks_df[ daily_extracted_teks_df.extraction_date == date].copy() day_new_teks_df["shared_teks"] = \ day_new_teks_df.tek_list.apply(lambda x: set(x).intersection(day_new_teks_set)) day_new_teks_df["shared_teks"] = \ day_new_teks_df.shared_teks.apply(len) day_new_teks_df["upload_date"] = date day_new_teks_df.rename(columns={"sample_date": "generation_date"}, inplace=True) day_new_teks_df = day_new_teks_df[ ["upload_date", "generation_date", "shared_teks"]] day_new_teks_df["generation_to_upload_days"] = \ (pd.to_datetime(day_new_teks_df.upload_date) - pd.to_datetime(day_new_teks_df.generation_date)).dt.days day_new_teks_df = day_new_teks_df[day_new_teks_df.shared_teks > 0] return day_new_teks_df shared_teks_generation_to_upload_df = pd.DataFrame() for upload_date in daily_extracted_teks_df.extraction_date.unique(): shared_teks_generation_to_upload_df = \ shared_teks_generation_to_upload_df.append( compute_teks_by_generation_and_upload_date(date=upload_date)) shared_teks_generation_to_upload_df \ .sort_values(["upload_date", "generation_date"], ascending=False, inplace=True) shared_teks_generation_to_upload_df.tail() today_new_teks_df = \ shared_teks_generation_to_upload_df[ shared_teks_generation_to_upload_df.upload_date == extraction_date].copy() today_new_teks_df.tail() if not today_new_teks_df.empty: today_new_teks_df.set_index("generation_to_upload_days") \ .sort_index().shared_teks.plot.bar() generation_to_upload_period_pivot_df = \ shared_teks_generation_to_upload_df[ ["upload_date", "generation_to_upload_days", "shared_teks"]] \ .pivot(index="upload_date", columns="generation_to_upload_days") \ .sort_index(ascending=False).fillna(0).astype(int) \ .droplevel(level=0, axis=1) generation_to_upload_period_pivot_df.head() new_tek_df = tek_list_df.diff().tek_list.apply( lambda x: len(x) if not pd.isna(x) else None).to_frame().reset_index() new_tek_df.rename(columns={ "tek_list": "shared_teks_by_upload_date", "extraction_date": "sample_date_string",}, inplace=True) new_tek_df.tail() shared_teks_uploaded_on_generation_date_df = shared_teks_generation_to_upload_df[ shared_teks_generation_to_upload_df.generation_to_upload_days == 0] \ [["upload_date", "shared_teks"]].rename( columns={ "upload_date": "sample_date_string", "shared_teks": "shared_teks_uploaded_on_generation_date", }) shared_teks_uploaded_on_generation_date_df.head() estimated_shared_diagnoses_df = shared_teks_generation_to_upload_df \ .groupby(["upload_date"]).shared_teks.max().reset_index() \ .sort_values(["upload_date"], ascending=False) \ .rename(columns={ "upload_date": "sample_date_string", "shared_teks": "shared_diagnoses", }) invalid_shared_diagnoses_dates_mask = \ estimated_shared_diagnoses_df.sample_date_string.isin(invalid_shared_diagnoses_dates) estimated_shared_diagnoses_df[invalid_shared_diagnoses_dates_mask] = 0 estimated_shared_diagnoses_df.head() ``` ### Hourly New TEKs ``` hourly_extracted_teks_df = load_extracted_teks( mode="Hourly", region=report_backend_identifier, limit=25) hourly_extracted_teks_df.head() hourly_new_tek_count_df = hourly_extracted_teks_df \ .groupby("extraction_date_with_hour").tek_list. \ apply(lambda x: set(sum(x, []))).reset_index().copy() hourly_new_tek_count_df = hourly_new_tek_count_df.set_index("extraction_date_with_hour") \ .sort_index(ascending=True) hourly_new_tek_count_df["new_tek_list"] = hourly_new_tek_count_df.tek_list.diff() hourly_new_tek_count_df["new_tek_count"] = hourly_new_tek_count_df.new_tek_list.apply( lambda x: len(x) if not pd.isna(x) else 0) hourly_new_tek_count_df.rename(columns={ "new_tek_count": "shared_teks_by_upload_date"}, inplace=True) hourly_new_tek_count_df = hourly_new_tek_count_df.reset_index()[[ "extraction_date_with_hour", "shared_teks_by_upload_date"]] hourly_new_tek_count_df.head() hourly_summary_df = hourly_new_tek_count_df.copy() hourly_summary_df.set_index("extraction_date_with_hour", inplace=True) hourly_summary_df = hourly_summary_df.fillna(0).astype(int).reset_index() hourly_summary_df["datetime_utc"] = pd.to_datetime( hourly_summary_df.extraction_date_with_hour, format="%Y-%m-%d@%H") hourly_summary_df.set_index("datetime_utc", inplace=True) hourly_summary_df = hourly_summary_df.tail(-1) hourly_summary_df.head() ``` ### Official Statistics ``` import requests import pandas.io.json official_stats_response = requests.get("https://radarcovid.covid19.gob.es/kpi/statistics/basics") official_stats_response.raise_for_status() official_stats_df_ = pandas.io.json.json_normalize(official_stats_response.json()) official_stats_df = official_stats_df_.copy() official_stats_df["date"] = pd.to_datetime(official_stats_df["date"], dayfirst=True) official_stats_df.head() official_stats_column_map = { "date": "sample_date", "applicationsDownloads.totalAcummulated": "app_downloads_es_accumulated", "communicatedContagions.totalAcummulated": "shared_diagnoses_es_accumulated", } accumulated_suffix = "_accumulated" accumulated_values_columns = \ list(filter(lambda x: x.endswith(accumulated_suffix), official_stats_column_map.values())) interpolated_values_columns = \ list(map(lambda x: x[:-len(accumulated_suffix)], accumulated_values_columns)) official_stats_df = \ official_stats_df[official_stats_column_map.keys()] \ .rename(columns=official_stats_column_map) official_stats_df["extraction_date"] = extraction_date official_stats_df.head() official_stats_path = "Data/Statistics/Current/RadarCOVID-Statistics.json" previous_official_stats_df = pd.read_json(official_stats_path, orient="records", lines=True) previous_official_stats_df["sample_date"] = pd.to_datetime(previous_official_stats_df["sample_date"], dayfirst=True) official_stats_df = official_stats_df.append(previous_official_stats_df) official_stats_df.head() official_stats_df = official_stats_df[~(official_stats_df.shared_diagnoses_es_accumulated == 0)] official_stats_df.sort_values("extraction_date", ascending=False, inplace=True) official_stats_df.drop_duplicates(subset=["sample_date"], keep="first", inplace=True) official_stats_df.head() official_stats_stored_df = official_stats_df.copy() official_stats_stored_df["sample_date"] = official_stats_stored_df.sample_date.dt.strftime("%Y-%m-%d") official_stats_stored_df.to_json(official_stats_path, orient="records", lines=True) official_stats_df.drop(columns=["extraction_date"], inplace=True) official_stats_df = confirmed_days_df.merge(official_stats_df, how="left") official_stats_df.sort_values("sample_date", ascending=False, inplace=True) official_stats_df.head() official_stats_df[accumulated_values_columns] = \ official_stats_df[accumulated_values_columns] \ .astype(float).interpolate(limit_area="inside") official_stats_df[interpolated_values_columns] = \ official_stats_df[accumulated_values_columns].diff(periods=-1) official_stats_df.drop(columns="sample_date", inplace=True) official_stats_df.head() ``` ### Data Merge ``` result_summary_df = exposure_keys_summary_df.merge( new_tek_df, on=["sample_date_string"], how="outer") result_summary_df.head() result_summary_df = result_summary_df.merge( shared_teks_uploaded_on_generation_date_df, on=["sample_date_string"], how="outer") result_summary_df.head() result_summary_df = result_summary_df.merge( estimated_shared_diagnoses_df, on=["sample_date_string"], how="outer") result_summary_df.head() result_summary_df = result_summary_df.merge( official_stats_df, on=["sample_date_string"], how="outer") result_summary_df.head() result_summary_df = confirmed_eu_df.tail(daily_summary_days).merge( result_summary_df, on=["sample_date_string"], how="left") result_summary_df.head() result_summary_df = confirmed_es_df.tail(daily_summary_days).merge( result_summary_df, on=["sample_date_string"], how="left") result_summary_df.head() result_summary_df["sample_date"] = pd.to_datetime(result_summary_df.sample_date_string) result_summary_df = result_summary_df.merge(source_regions_for_summary_df, how="left") result_summary_df.set_index(["sample_date", "source_regions"], inplace=True) result_summary_df.drop(columns=["sample_date_string"], inplace=True) result_summary_df.sort_index(ascending=False, inplace=True) result_summary_df.head() with pd.option_context("mode.use_inf_as_na", True): result_summary_df = result_summary_df.fillna(0).astype(int) result_summary_df["teks_per_shared_diagnosis"] = \ (result_summary_df.shared_teks_by_upload_date / result_summary_df.shared_diagnoses).fillna(0) result_summary_df["shared_diagnoses_per_covid_case"] = \ (result_summary_df.shared_diagnoses / result_summary_df.covid_cases).fillna(0) result_summary_df["shared_diagnoses_per_covid_case_es"] = \ (result_summary_df.shared_diagnoses_es / result_summary_df.covid_cases_es).fillna(0) result_summary_df.head(daily_plot_days) def compute_aggregated_results_summary(days) -> pd.DataFrame: aggregated_result_summary_df = result_summary_df.copy() aggregated_result_summary_df["covid_cases_for_ratio"] = \ aggregated_result_summary_df.covid_cases.mask( aggregated_result_summary_df.shared_diagnoses == 0, 0) aggregated_result_summary_df["covid_cases_for_ratio_es"] = \ aggregated_result_summary_df.covid_cases_es.mask( aggregated_result_summary_df.shared_diagnoses_es == 0, 0) aggregated_result_summary_df = aggregated_result_summary_df \ .sort_index(ascending=True).fillna(0).rolling(days).agg({ "covid_cases": "sum", "covid_cases_es": "sum", "covid_cases_for_ratio": "sum", "covid_cases_for_ratio_es": "sum", "shared_teks_by_generation_date": "sum", "shared_teks_by_upload_date": "sum", "shared_diagnoses": "sum", "shared_diagnoses_es": "sum", }).sort_index(ascending=False) with pd.option_context("mode.use_inf_as_na", True): aggregated_result_summary_df = aggregated_result_summary_df.fillna(0).astype(int) aggregated_result_summary_df["teks_per_shared_diagnosis"] = \ (aggregated_result_summary_df.shared_teks_by_upload_date / aggregated_result_summary_df.covid_cases_for_ratio).fillna(0) aggregated_result_summary_df["shared_diagnoses_per_covid_case"] = \ (aggregated_result_summary_df.shared_diagnoses / aggregated_result_summary_df.covid_cases_for_ratio).fillna(0) aggregated_result_summary_df["shared_diagnoses_per_covid_case_es"] = \ (aggregated_result_summary_df.shared_diagnoses_es / aggregated_result_summary_df.covid_cases_for_ratio_es).fillna(0) return aggregated_result_summary_df aggregated_result_with_7_days_window_summary_df = compute_aggregated_results_summary(days=7) aggregated_result_with_7_days_window_summary_df.head() last_7_days_summary = aggregated_result_with_7_days_window_summary_df.to_dict(orient="records")[1] last_7_days_summary aggregated_result_with_14_days_window_summary_df = compute_aggregated_results_summary(days=13) last_14_days_summary = aggregated_result_with_14_days_window_summary_df.to_dict(orient="records")[1] last_14_days_summary ``` ## Report Results ``` display_column_name_mapping = { "sample_date": "Sample\u00A0Date\u00A0(UTC)", "source_regions": "Source Countries", "datetime_utc": "Timestamp (UTC)", "upload_date": "Upload Date (UTC)", "generation_to_upload_days": "Generation to Upload Period in Days", "region": "Backend", "region_x": "Backend\u00A0(A)", "region_y": "Backend\u00A0(B)", "common_teks": "Common TEKs Shared Between Backends", "common_teks_fraction": "Fraction of TEKs in Backend (A) Available in Backend (B)", "covid_cases": "COVID-19 Cases (Source Countries)", "shared_teks_by_generation_date": "Shared TEKs by Generation Date (Source Countries)", "shared_teks_by_upload_date": "Shared TEKs by Upload Date (Source Countries)", "shared_teks_uploaded_on_generation_date": "Shared TEKs Uploaded on Generation Date (Source Countries)", "shared_diagnoses": "Shared Diagnoses (Source Countries – Estimation)", "teks_per_shared_diagnosis": "TEKs Uploaded per Shared Diagnosis (Source Countries)", "shared_diagnoses_per_covid_case": "Usage Ratio (Source Countries)", "covid_cases_es": "COVID-19 Cases (Spain)", "app_downloads_es": "App Downloads (Spain – Official)", "shared_diagnoses_es": "Shared Diagnoses (Spain – Official)", "shared_diagnoses_per_covid_case_es": "Usage Ratio (Spain)", } summary_columns = [ "covid_cases", "shared_teks_by_generation_date", "shared_teks_by_upload_date", "shared_teks_uploaded_on_generation_date", "shared_diagnoses", "teks_per_shared_diagnosis", "shared_diagnoses_per_covid_case", "covid_cases_es", "app_downloads_es", "shared_diagnoses_es", "shared_diagnoses_per_covid_case_es", ] summary_percentage_columns= [ "shared_diagnoses_per_covid_case_es", "shared_diagnoses_per_covid_case", ] ``` ### Daily Summary Table ``` result_summary_df_ = result_summary_df.copy() result_summary_df = result_summary_df[summary_columns] result_summary_with_display_names_df = result_summary_df \ .rename_axis(index=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) result_summary_with_display_names_df ``` ### Daily Summary Plots ``` result_plot_summary_df = result_summary_df.head(daily_plot_days)[summary_columns] \ .droplevel(level=["source_regions"]) \ .rename_axis(index=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) summary_ax_list = result_plot_summary_df.sort_index(ascending=True).plot.bar( title=f"Daily Summary", rot=45, subplots=True, figsize=(15, 30), legend=False) ax_ = summary_ax_list[0] ax_.get_figure().tight_layout() ax_.get_figure().subplots_adjust(top=0.95) _ = ax_.set_xticklabels(sorted(result_plot_summary_df.index.strftime("%Y-%m-%d").tolist())) for percentage_column in summary_percentage_columns: percentage_column_index = summary_columns.index(percentage_column) summary_ax_list[percentage_column_index].yaxis \ .set_major_formatter(matplotlib.ticker.PercentFormatter(1.0)) ``` ### Daily Generation to Upload Period Table ``` display_generation_to_upload_period_pivot_df = \ generation_to_upload_period_pivot_df \ .head(backend_generation_days) display_generation_to_upload_period_pivot_df \ .head(backend_generation_days) \ .rename_axis(columns=display_column_name_mapping) \ .rename_axis(index=display_column_name_mapping) fig, generation_to_upload_period_pivot_table_ax = plt.subplots( figsize=(12, 1 + 0.6 * len(display_generation_to_upload_period_pivot_df))) generation_to_upload_period_pivot_table_ax.set_title( "Shared TEKs Generation to Upload Period Table") sns.heatmap( data=display_generation_to_upload_period_pivot_df .rename_axis(columns=display_column_name_mapping) .rename_axis(index=display_column_name_mapping), fmt=".0f", annot=True, ax=generation_to_upload_period_pivot_table_ax) generation_to_upload_period_pivot_table_ax.get_figure().tight_layout() ``` ### Hourly Summary Plots ``` hourly_summary_ax_list = hourly_summary_df \ .rename_axis(index=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) \ .plot.bar( title=f"Last 24h Summary", rot=45, subplots=True, legend=False) ax_ = hourly_summary_ax_list[-1] ax_.get_figure().tight_layout() ax_.get_figure().subplots_adjust(top=0.9) _ = ax_.set_xticklabels(sorted(hourly_summary_df.index.strftime("%Y-%m-%d@%H").tolist())) ``` ### Publish Results ``` github_repository = os.environ.get("GITHUB_REPOSITORY") if github_repository is None: github_repository = "pvieito/Radar-STATS" github_project_base_url = "https://github.com/" + github_repository display_formatters = { display_column_name_mapping["teks_per_shared_diagnosis"]: lambda x: f"{x:.2f}" if x != 0 else "", display_column_name_mapping["shared_diagnoses_per_covid_case"]: lambda x: f"{x:.2%}" if x != 0 else "", display_column_name_mapping["shared_diagnoses_per_covid_case_es"]: lambda x: f"{x:.2%}" if x != 0 else "", } general_columns = \ list(filter(lambda x: x not in display_formatters, display_column_name_mapping.values())) general_formatter = lambda x: f"{x}" if x != 0 else "" display_formatters.update(dict(map(lambda x: (x, general_formatter), general_columns))) daily_summary_table_html = result_summary_with_display_names_df \ .head(daily_plot_days) \ .rename_axis(index=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) \ .to_html(formatters=display_formatters) multi_backend_summary_table_html = multi_backend_summary_df \ .head(daily_plot_days) \ .rename_axis(columns=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) \ .rename_axis(index=display_column_name_mapping) \ .to_html(formatters=display_formatters) def format_multi_backend_cross_sharing_fraction(x): if pd.isna(x): return "-" elif round(x * 100, 1) == 0: return "" else: return f"{x:.1%}" multi_backend_cross_sharing_summary_table_html = multi_backend_cross_sharing_summary_df \ .rename_axis(columns=display_column_name_mapping) \ .rename(columns=display_column_name_mapping) \ .rename_axis(index=display_column_name_mapping) \ .to_html( classes="table-center", formatters=display_formatters, float_format=format_multi_backend_cross_sharing_fraction) multi_backend_cross_sharing_summary_table_html = \ multi_backend_cross_sharing_summary_table_html \ .replace("<tr>","<tr style=\"text-align: center;\">") extraction_date_result_summary_df = \ result_summary_df[result_summary_df.index.get_level_values("sample_date") == extraction_date] extraction_date_result_hourly_summary_df = \ hourly_summary_df[hourly_summary_df.extraction_date_with_hour == extraction_date_with_hour] covid_cases = \ extraction_date_result_summary_df.covid_cases.item() shared_teks_by_generation_date = \ extraction_date_result_summary_df.shared_teks_by_generation_date.item() shared_teks_by_upload_date = \ extraction_date_result_summary_df.shared_teks_by_upload_date.item() shared_diagnoses = \ extraction_date_result_summary_df.shared_diagnoses.item() teks_per_shared_diagnosis = \ extraction_date_result_summary_df.teks_per_shared_diagnosis.item() shared_diagnoses_per_covid_case = \ extraction_date_result_summary_df.shared_diagnoses_per_covid_case.item() shared_teks_by_upload_date_last_hour = \ extraction_date_result_hourly_summary_df.shared_teks_by_upload_date.sum().astype(int) display_source_regions = ", ".join(report_source_regions) if len(report_source_regions) == 1: display_brief_source_regions = report_source_regions[0] else: display_brief_source_regions = f"{len(report_source_regions)} 🇪🇺" def get_temporary_image_path() -> str: return os.path.join(tempfile.gettempdir(), str(uuid.uuid4()) + ".png") def save_temporary_plot_image(ax): if isinstance(ax, np.ndarray): ax = ax[0] media_path = get_temporary_image_path() ax.get_figure().savefig(media_path) return media_path def save_temporary_dataframe_image(df): import dataframe_image as dfi df = df.copy() df_styler = df.style.format(display_formatters) media_path = get_temporary_image_path() dfi.export(df_styler, media_path) return media_path summary_plots_image_path = save_temporary_plot_image( ax=summary_ax_list) summary_table_image_path = save_temporary_dataframe_image( df=result_summary_with_display_names_df) hourly_summary_plots_image_path = save_temporary_plot_image( ax=hourly_summary_ax_list) multi_backend_summary_table_image_path = save_temporary_dataframe_image( df=multi_backend_summary_df) generation_to_upload_period_pivot_table_image_path = save_temporary_plot_image( ax=generation_to_upload_period_pivot_table_ax) ``` ### Save Results ``` report_resources_path_prefix = "Data/Resources/Current/RadarCOVID-Report-" result_summary_df.to_csv( report_resources_path_prefix + "Summary-Table.csv") result_summary_df.to_html( report_resources_path_prefix + "Summary-Table.html") hourly_summary_df.to_csv( report_resources_path_prefix + "Hourly-Summary-Table.csv") multi_backend_summary_df.to_csv( report_resources_path_prefix + "Multi-Backend-Summary-Table.csv") multi_backend_cross_sharing_summary_df.to_csv( report_resources_path_prefix + "Multi-Backend-Cross-Sharing-Summary-Table.csv") generation_to_upload_period_pivot_df.to_csv( report_resources_path_prefix + "Generation-Upload-Period-Table.csv") _ = shutil.copyfile( summary_plots_image_path, report_resources_path_prefix + "Summary-Plots.png") _ = shutil.copyfile( summary_table_image_path, report_resources_path_prefix + "Summary-Table.png") _ = shutil.copyfile( hourly_summary_plots_image_path, report_resources_path_prefix + "Hourly-Summary-Plots.png") _ = shutil.copyfile( multi_backend_summary_table_image_path, report_resources_path_prefix + "Multi-Backend-Summary-Table.png") _ = shutil.copyfile( generation_to_upload_period_pivot_table_image_path, report_resources_path_prefix + "Generation-Upload-Period-Table.png") ``` ### Publish Results as JSON ``` def generate_summary_api_results(df: pd.DataFrame) -> list: api_df = df.reset_index().copy() api_df["sample_date_string"] = \ api_df["sample_date"].dt.strftime("%Y-%m-%d") api_df["source_regions"] = \ api_df["source_regions"].apply(lambda x: x.split(",")) return api_df.to_dict(orient="records") summary_api_results = \ generate_summary_api_results(df=result_summary_df) today_summary_api_results = \ generate_summary_api_results(df=extraction_date_result_summary_df)[0] summary_results = dict( backend_identifier=report_backend_identifier, source_regions=report_source_regions, extraction_datetime=extraction_datetime, extraction_date=extraction_date, extraction_date_with_hour=extraction_date_with_hour, last_hour=dict( shared_teks_by_upload_date=shared_teks_by_upload_date_last_hour, shared_diagnoses=0, ), today=today_summary_api_results, last_7_days=last_7_days_summary, last_14_days=last_14_days_summary, daily_results=summary_api_results) summary_results = \ json.loads(pd.Series([summary_results]).to_json(orient="records"))[0] with open(report_resources_path_prefix + "Summary-Results.json", "w") as f: json.dump(summary_results, f, indent=4) ``` ### Publish on README ``` with open("Data/Templates/README.md", "r") as f: readme_contents = f.read() readme_contents = readme_contents.format( extraction_date_with_hour=extraction_date_with_hour, github_project_base_url=github_project_base_url, daily_summary_table_html=daily_summary_table_html, multi_backend_summary_table_html=multi_backend_summary_table_html, multi_backend_cross_sharing_summary_table_html=multi_backend_cross_sharing_summary_table_html, display_source_regions=display_source_regions) with open("README.md", "w") as f: f.write(readme_contents) ``` ### Publish on Twitter ``` enable_share_to_twitter = os.environ.get("RADARCOVID_REPORT__ENABLE_PUBLISH_ON_TWITTER") github_event_name = os.environ.get("GITHUB_EVENT_NAME") if enable_share_to_twitter and github_event_name == "schedule" and \ (shared_teks_by_upload_date_last_hour or not are_today_results_partial): import tweepy twitter_api_auth_keys = os.environ["RADARCOVID_REPORT__TWITTER_API_AUTH_KEYS"] twitter_api_auth_keys = twitter_api_auth_keys.split(":") auth = tweepy.OAuthHandler(twitter_api_auth_keys[0], twitter_api_auth_keys[1]) auth.set_access_token(twitter_api_auth_keys[2], twitter_api_auth_keys[3]) api = tweepy.API(auth) summary_plots_media = api.media_upload(summary_plots_image_path) summary_table_media = api.media_upload(summary_table_image_path) generation_to_upload_period_pivot_table_image_media = api.media_upload(generation_to_upload_period_pivot_table_image_path) media_ids = [ summary_plots_media.media_id, summary_table_media.media_id, generation_to_upload_period_pivot_table_image_media.media_id, ] if are_today_results_partial: today_addendum = " (Partial)" else: today_addendum = "" def format_shared_diagnoses_per_covid_case(value) -> str: if value == 0: return "–" return f"≤{value:.2%}" display_shared_diagnoses_per_covid_case = \ format_shared_diagnoses_per_covid_case(value=shared_diagnoses_per_covid_case) display_last_14_days_shared_diagnoses_per_covid_case = \ format_shared_diagnoses_per_covid_case(value=last_14_days_summary["shared_diagnoses_per_covid_case"]) display_last_14_days_shared_diagnoses_per_covid_case_es = \ format_shared_diagnoses_per_covid_case(value=last_14_days_summary["shared_diagnoses_per_covid_case_es"]) status = textwrap.dedent(f""" #RadarCOVID – {extraction_date_with_hour} Today{today_addendum}: - Uploaded TEKs: {shared_teks_by_upload_date:.0f} ({shared_teks_by_upload_date_last_hour:+d} last hour) - Shared Diagnoses: ≤{shared_diagnoses:.0f} - Usage Ratio: {display_shared_diagnoses_per_covid_case} Last 14 Days: - Usage Ratio (Estimation): {display_last_14_days_shared_diagnoses_per_covid_case} - Usage Ratio (Official): {display_last_14_days_shared_diagnoses_per_covid_case_es} Info: {github_project_base_url}#documentation """) status = status.encode(encoding="utf-8") api.update_status(status=status, media_ids=media_ids) ```
github_jupyter
# In-Class Coding Lab: Lists The goals of this lab are to help you understand: - List indexing and slicing - List methods such as insert, append, find, delete - How to iterate over lists with loops ## Python Lists work like Real-Life Lists In real life, we make lists all the time. To-Do lists. Shopping lists. Reading lists. These lists are collections of items, for example here's my shopping list: ``` Milk, Eggs, Bread, Beer ``` There are 4 items in this list. Likewise, we can make a similar list in Python, and count the number of items in the list using the `len()` function: ``` shopping_list = [ 'Milk', 'Eggs', 'Bread', 'Beer'] item_count = len(shopping_list) print("List: %s has %d items" % (shopping_list, item_count)) ``` ## Enumerating Your List Items In real-life, we *enumerate* lists all the time. We go through the items on our list one at a time and make a decision, for example: "Did I add that to my shopping cart yet?" In Python we go through items in our lists with the `for` loop. We use `for` because the number of items in pre-determined and thus a **definite** loop is the appropriate choice. Here's an example: ``` for item in shopping_list: print("I need to buy some %s " % (item)) ``` ## Now You Try It! Write code in the space below to print each stock on its own line. ``` stocks = [ 'IBM', 'AAPL', 'GOOG', 'MSFT', 'TWTR', 'FB'] ItemCount = len(stocks) print("List: %s has %d items" % (stocks, ItemCount)) ``` ## Indexing Lists Sometimes we refer to our items by their place in the list. For example "Milk is the first item on the list" or "Beer is the last item on the list." We can also do this in Python, and it is called *indexing* the list. **IMPORTANT** The first item in a Python lists starts at index **0**. ``` print("The first item in the list is:", shopping_list[0]) print("The last item in the list is:", shopping_list[3]) print("This is also the last item in the list:", shopping_list[-1]) print("This is the second to last item in the list:", shopping_list[-2]) ``` ## For Loop with Index You can also loop through your Python list using an index. In this case we use the `range()` function to determine how many times we should loop: ``` for i in range(len(shopping_list)): print("I need to buy some %s " % (shopping_list[i])) ``` ## Now You Try It! Write code to print the 2nd and 4th stocks in the list variable `stocks`. For example: `AAPL MSFT` ``` print("The second stock in the list is:", stocks[1]) print("The fourth stock in the list is:", stocks[3]) ``` ## Lists are Mutable Unlike strings, lists are mutable. This means we can change a value in the list. For example, I want `'Craft Beer'` not just `'Beer'`: ``` print(shopping_list) shopping_list[-1] = 'Craft Beer' print(shopping_list) ``` ## List Methods In your readings and class lecture, you encountered some list methods. These allow us to maniupulate the list by adding or removing items. ``` print("Shopping List: %s" %(shopping_list)) print("Adding 'Cheese' to the end of the list...") shopping_list.append('Cheese') #add to end of list print("Shopping List: %s" %(shopping_list)) print("Adding 'Cereal' to position 0 in the list...") shopping_list.insert(0,'Cereal') # add to the beginning of the list (position 0) print("Shopping List: %s" %(shopping_list)) print("Removing 'Cheese' from the list...") shopping_list.remove('Cheese') # remove 'Cheese' from the list print("Shopping List: %s" %(shopping_list)) print("Removing item from position 0 in the list...") del shopping_list[0] # remove item at position 0 print("Shopping List: %s" %(shopping_list)) ``` ## Now You Try It! Write a program to remove the following stocks: `IBM` and `TWTR` Then add this stock to the end `NFLX` and this stock to the beginning `TSLA` Print your list when you are done. It should look like this: `['TSLA', 'AAPL', 'GOOG', 'MSFT', 'FB', 'NFLX']` ``` print("Stock List: %s" %(stocks)) print("Removing 'IBM' from the list...") stocks.remove("IBM") print("Stock List: %s" %(stocks)) print("Removing 'TWTR' from the list...") stocks.remove("TWTR") print("Stock List: %s" %(stocks)) print("Adding 'NFLX' to position 5 in the list...") stocks.insert(5,'NFLX') print("Stock List: %s" %(stocks)) print("Adding 'TSLA' to position 0 in the list...") stocks.insert(0,'TSLA') print("Stock List: %s" %(stocks)) ``` ## Sorting Since Lists are mutable. You can use the `sort()` method to re-arrange the items in the list alphabetically (or numerically if it's a list of numbers) ``` print("Before Sort:", shopping_list) shopping_list.sort() print("After Sort:", shopping_list) ``` # Putting it all together Winning Lotto numbers. When the lotto numbers are drawn, they are in any order, when they are presented they're allways sorted. Let's write a program to input 5 numbers then output them sorted ``` 1. for i in range(5) 2. input a number 3. append the number you input to the lotto_numbers list 4. sort the lotto_numbers list 5. print the lotto_numbers list like this: 'today's winning numbers are [1, 5, 17, 34, 56]' ``` ``` lotto_numbers = [] for i in range(5): number = int(input("Number: ")) lotto_numbers.append(number) lotto_numbers.sort() print("Today's winning numbers are:", lotto_numbers) ```
github_jupyter
# Classifying cancer from 32 parameters Data is taken from https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29 We simply read all the data, drop the patient ID and place the label into an array of it's own. ``` import csv import numpy with open('data_Cancer.csv') as input_file: text_data = [row for row in csv.reader(input_file, delimiter=',')] for line in text_data: _ = line.pop(0) #We remove the ID - no need for it known_labels = ','.join([line.pop(0) for line in text_data]) raw_data = numpy.array(text_data).astype(numpy.float) data = raw_data / numpy.max(raw_data, axis = 0) ``` Now we can write a generic clustering mechanism, similar to the small previous example. ``` def all_dist(observation, data): return numpy.sqrt((data[:, 0] - observation[0])**2 + (data[:, 1] - observation[1])**2) def cluster(data, k): samples, _= data.shape centroids = numpy.array([data[numpy.random.randint(samples), :,] for _ in range(k)]) done = False while not done: distances = numpy.empty((k,samples)) for d in range(k): distances[d, :] = all_dist(centroids[d], data) winners = numpy.argmin(distances, axis = 0) clusters = [data[winners == i, :] for i in range(k)] prev_centroids = centroids centroids = numpy.array([numpy.average(c, axis = 0) for c in clusters]) if numpy.sum(prev_centroids-centroids) == 0: done=True return winners ``` Now we can find the clusters, since we have only two categories its rather fast. We cannot know if category 0 is malign or benign, but have to assume that the smaller category is malign. We thus change the labels to that assumption. Then we can easily compare the classifications of each patient and check who well we did. ``` clusters = cluster(data, 2) a, b = numpy.bincount(clusters) labels = known_labels+'' if a<b: labels = labels.replace('M','0') labels = labels.replace('B','1') else: labels = labels.replace('M','1') labels = labels.replace('B','0') compare = (numpy.equal(clusters, numpy.array(labels.split(',')).astype(numpy.int))) print(numpy.bincount(compare),'(Wrong, Right)') ``` Run it a few times and realize that success differ extremely. Several approaches can be tried to remedy this. Try and simply remove one or more dimensions to see if they are merely in the way (really: do a PCA but QaD tests are ok as well). Try and change the distance metric for individual dimensions, so rather than simply include or not at in the first appraoch, we can tune the importance of a parameter. ``` def cluster(data, k, centroids = []): samples, _= data.shape if centroids == []: centroids = numpy.array([data[numpy.random.randint(samples), :,] for _ in range(k)]) done = False while not done: distances = numpy.empty((k,samples)) for d in range(k): distances[d, :] = all_dist(centroids[d], data) winners = numpy.argmin(distances, axis = 0) clusters = [data[winners == i, :] for i in range(k)] prev_centroids = centroids clusters = [c for c in clusters if len(c)>0] k = len(clusters) centroids = numpy.array([numpy.average(c, axis = 0) for c in clusters]) if len(prev_centroids) == len(centroids): if numpy.sum(prev_centroids-centroids) == 0: done=True return winners, centroids target_k = 2 n_centroids = 25 centroids = [] while n_centroids > target_k: clusters, centroids = cluster(data, n_centroids, centroids) if ( n_centroids > target_k ) and ( len(centroids) == n_centroids ): centroid_dist = numpy.sum(numpy.sqrt((centroids[:, numpy.newaxis, :]-centroids)**2), axis =2) centroid_dist[centroid_dist==0] = 1000.0 centroids = list(centroids) minpos = numpy.argmin(centroid_dist) point0, point1 = centroids.pop(minpos//n_centroids), centroids.pop((minpos%n_centroids)-1) #-1 because we pop centroids.append((point0 + point1)/2) n_centroids -= 1 else: n_centroids = len(centroids) clusters, centroids = cluster(data, n_centroids, centroids) #We have the number of required centroids now a, b = numpy.bincount(clusters) labels = known_labels+'' if a<b: labels = labels.replace('M','0') labels = labels.replace('B','1') else: labels = labels.replace('M','1') labels = labels.replace('B','0') compare = (numpy.equal(clusters, numpy.array(labels.split(',')).astype(numpy.int))) print(numpy.bincount(compare),'(Wrong, Right)') ``` *** Note to self - try with many more clusters, and after convergence, fuse the two clusters that are closest to one and repeat training. Repeat until the desired number of clusters are found. Fusing: simple mean, weighted mean or most discriminating (one furthest away from other centroids) ***
github_jupyter
## Loading an HCA matrix into scanpy This vignette illustrates requesting an expression matrix from the HCA matrix service and loading it into scanpy. First, install and import some dependencies: ``` import sys !{sys.executable} -m pip install python-igraph loompy louvain pandas requests scanpy import json, os, requests, scanpy.api as sc, shutil, time, zipfile, warnings ``` Now, we're going to make some requests to describe what fields and values we can filter on when we're selecting our matrix. ``` MATRIX_URL = "https://matrix.data.humancellatlas.org/v1" resp = requests.get(MATRIX_URL + "/filters") print(resp.text) ``` That's the list of metadata fields we can filter on when requesting the matrix. We can describe any of them with further API calls. When we request categorical data, we see the number of cells associated with each category. For numeric, we see the range of value. ``` resp = requests.get(MATRIX_URL + "/filters/project.project_core.project_short_name") print(resp.text) resp = requests.get(MATRIX_URL + "/filters/genes_detected") print(resp.text) resp = requests.get(MATRIX_URL + "/filters/analysis_protocol.protocol_core.protocol_id") print(resp.text) ``` If we want to request a matrix based on these metadata values, we can add them to the `filter` in the body of a POST request to the matrix service: ``` resp = requests.post( MATRIX_URL + "/matrix", json={"filter": {"op": "and", "value": [ {"op": "=", "value": "Single cell transcriptome analysis of human pancreas", "field": "project.project_core.project_short_name"}, {"op": ">=", "value": 300, "field": "genes_detected"} ] }}) print(resp.text) ``` That call responds right away and tells us that the matrix is being prepared. We can use the `request_id` to wait until the matrix is done. ``` while True: status_resp = requests.get( MATRIX_URL + "/matrix/" + resp.json()["request_id"]) if status_resp.json()["status"] == "Complete": break print(status_resp.json()["status"], "Waiting...") time.sleep(30) print(status_resp.text) ``` Now, that the matrix is ready, we can download it. The file we download is a zip archive that contains a readme and a loom-formatted matrix. Loom is the default matrix format, but others can be specified in the matrix request. ``` matrix_response = requests.get(status_resp.json()["matrix_url"], stream=True) matrix_zip_filename = os.path.basename(status_resp.json()["matrix_url"]) with open(matrix_zip_filename, 'wb') as matrix_zip_file: shutil.copyfileobj(matrix_response.raw, matrix_zip_file) ``` ## HCA Matrix Service Loom Output The loom-formatted output from the matrix service is a zip archive that contains two files: | Filename | Description | |------------------------------------|-------------------------------| | `loom_readme.md` | This readme | | `<file_name>.loom` | Loom file with requested data | The Loom format is documented more fully, along with code samples, [here](https://linnarssonlab.org/loompy/index.html). Per Loom [conventions](https://linnarssonlab.org/loompy/conventions/index.html), columns in the loom-formatted expression matrix represent cells, and rows represent genes. The column and row attributes follow Loom conventions where applicable as well: `CellID` uniquely identifies a cell, `Gene` is a gene name, and `Accession` is an ensembl gene id. Descriptions of the remaining metadata fields are available at the [HCA Data Browser](https://prod.data.humancellatlas.org/metadata). And finally, we can use the `read_loom` method from scanpy, to load the matrix and peforms some analyses. Note that we specify `var_names="Accession"` so we get unique gene names. ``` matrix_loom_filename = matrix_zip_filename.rstrip(".zip") adata = sc.read_loom(matrix_loom_filename, var_names="Accession") adata.shape ``` We can perform some standard scanpy tasks, like nearest-neighbor calculation and clustering. ``` ?sc.pp.neighbors ?sc.pp.pca sc.pp.normalize_per_cell(adata) sc.pp.neighbors(adata) sc.tl.umap(adata) sc.pl.umap(adata, color="project.project_core.project_short_name", legend_loc="lower center", legend_fontsize=6) sc.tl.louvain(adata, resolution=0.2) sc.pl.umap(adata, color=["louvain"]) with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) # catch a repetitive louvain warning sc.tl.rank_genes_groups(adata, 'louvain') sc.pl.rank_genes_groups(adata, n_genes=16, fontsize=12, gene_symbols="Gene") ```
github_jupyter
# Demo: How to scrape multiple things from multiple pages This example uses the website [Box Office Mojo](https://www.boxofficemojo.com/). The goal is to scrape info about the five top-grossing movies for each year, for 10 years. I want the title and rank of the movie, and also, how much money it grossed at the box office. In the end I will put the scraped data into a CSV file. This is a small-scale project to demonstrate how a larger-scale project using various other websites (instead of Box Office Mojo) might be accomplished. This demo uses: * Python 3 * Jupyter Notebook * [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) * [Requests](https://requests.kennethreitz.org/en/master/) ``` # load the Python libraries from bs4 import BeautifulSoup import requests # begin to explore ONE page - load the page and capture all of its HTML in a variable named `soup` url = 'https://www.boxofficemojo.com/yearly/chart/?yr=2019' html = requests.get(url) soup = BeautifulSoup(html.text, 'html.parser') ``` Before you can start trying to get the data you want, you will *explore* the HTML of the selected web page, using Chrome Developer Tools. **Step 1:** Right-click on the exact line or element you wish to capture (scrape). A menu pops up. Select **Inspect.** The Elements inspection pane will open. If this is on the side (instead of at bottom, as shown), you can move it by clicking the kebab menu icon in the upper right corner, beside the X. **Step 2:** Examine the HTML elements that hold the data you want to scrape. You'll use these element names to scrape the contents. If you don't know much about HTML, [this brief guide](http://bit.ly/mm-htmltags) will help. The **circled area** in the HTML shows us that the data we want is contained in a `table` element. HTML tables have rows &mdash; in `tr` elements. The rows contain cells &mdash; in `td` elements. The start of a row, and some cells, can be seen in the **boxed area** above. There are various ways to scrape HTML tables other than what is demonstrated here. Our goal here is to demonstrate a scraping method that can work for more than just tables. ``` # I discover the data I want is in an HTML table with no class or ID # I capture all the tables on the page like this - in a Python list named tables - tables = soup.find_all( 'table' ) # then I print the number of how many tables are in that list print(len(tables)) ``` I had to test a few numbers before I got the correct `tables[]` and `rows[]` numbers you see below. I have deleted those testing cells from this notebook. It's important for beginners to understand that scraping requires a lot of trial-and-error work. It would be cumbersome to keep that work in the notebook, so it is gone. However, you will need to *do* that work before you discover how to get the data you desire from a page. The number in square brackets &mdash; `[6]` &mdash; is the result of my trial-and-error testing. I just kept changing the number in `tables[ ]` and printing until I found the right table. ``` # I capture all the rows in that table like this - in a Python list named rows - rows = tables[6].find_all('tr') # Here is some of the testing needed to find the correct data row print(len(rows)) print(rows[2]) ``` Above: There are 106 rows in my list, named `rows`. I can see on the page that the top row contains column headings, which I do not want to scrape. Some more (deleted) testing showed me that `rows[0]` and `rows[1]` contained data I do not want. Therefore I printed `rows[2]` to have a look at its contents. The contents are a lot of HTML elements all mashed together. Can you see the `td` that contains the first movie title? ``` # check to see whether I can get the first movie title in the first row cells = rows[2].find_all('td') title = cells[1].text print(title) ``` When using Python lists, we access items in a list by their index, which is the number you see inside square brackets. `cells[1].text` is the text inside the *second* item in the list named `cells`. The first item in any list has the index `0`. To access only the cells in the first row of data, I made a new list, named `cells`. My next test is to determine whether I can cleanly get the contents I want from the first five rows in this table. I use a Python for-loop to do this. Using `range(2, 7)` will bring me the rows with the *indexes* 2 through 6 (7 is the endpoint in the range). ``` # get top 5 movies on this page - I know the first row is [2] for i in range(2, 7): cells = rows[i].find_all('td') title = cells[1].text print(title) ``` My test was successful! ``` # I would like to get the total gross number also for i in range(2, 7): cells = rows[i].find_all('td') gross = cells[3].text print(gross) ``` Testing each individual thing you want is easier to debug than trying to get all the things in one big chunk of code. ``` # next I want to get rank (1-5), title and gross all on one line for i in range(2, 7): cells = rows[i].find_all('td') print(cells[0].text, cells[1].text, cells[3].text) # I want to do this for 10 years, ending with 2019 # first create a list of the years I want years = [] start = 2019 for i in range(0, 10): years.append(start - i) print(years) ``` Sure, I could have *typed* out that list, named `years`, by hand, but a for-loop created the list for me. It's nice to use `range()` to do things like this. **Feel free to try other years!** Box Office Mojo charts go back to 1980, so you could start your list (previous cell) with 1989. ``` # create a base url so I can open each year's page base_url = 'https://www.boxofficemojo.com/yearly/chart/?yr=' # test it # print(base_url + years[0]) -- ERROR # years[0] is an integer, so I must convert it to a string, with str() print( base_url + str(years[0]) ) ``` I am working toward making a loop that will open each web page I want (one for each year) and scrape from that page the top five movies and their gross earnings. To do this, I will combine the `base_url` text with the year. That will give me 10 URLs, one for each year. Now that my testing process is (mosty) done, I can attempt to make the complete set of instructions to scrape all 10 pages &mdash; ``` # collect all necessary pieces from above to make a loop that gets top 5 movies # for each of the 10 years for year in years: url = base_url + str(year) html = requests.get(url) soup = BeautifulSoup(html.text, 'html.parser') tables = soup.find_all( 'table' ) rows = tables[6].find_all('tr') for i in range(2, 7): cells = rows[i].find_all('td') print(cells[0].text, cells[1].text, cells[3].text) ``` It worked! However, looking at this, I realize that each line needs to include the year as well. I also realize I should clean the gross so it is a pure integer. That is a common data-cleaning task, but I will do a test before I add it to my code. [How `strip()` works](https://docs.python.org/3/library/stdtypes.html#str.strip) [How `replace()` works](https://docs.python.org/3/library/stdtypes.html#str.replace) ``` # test making a pure integer from the gross - using .strip() and .replace() chained together - num = '$293,004,164' print(num.strip('$').replace(',', '')) ``` Now I make another attempt at the complete set of instructions to scrape all 10 pages. This time I am also going to write the year into the line. Instead of using all 10 years (because this is just a test), I create a tiny array with just two years in it. ``` miniyears = [2017, 2014] for year in miniyears: url = base_url + str(year) html = requests.get(url) soup = BeautifulSoup(html.text, 'html.parser') tables = soup.find_all( 'table' ) rows = tables[6].find_all('tr') for i in range(2, 7): cells = rows[i].find_all('td') gross = cells[3].text.strip('$').replace(',', '') print(year, cells[0].text, cells[1].text, gross) ``` Now I am confident this code will work with all 10 years. But before I run it with `years`, I want to be sure to save the data in a new CSV file. This uses some standard Python code that always works fine, so I do not bother to test it. I just add it in. This will be my final cell in the notebook. After it runs, I will have a new file named `movies.csv` in the same folder as this notebook, and it will contain a header row and 50 rows of movie data. ``` # to save data into a csv, we must import - import csv # open a new file for writing - csvfile = open("movies.csv", 'w', newline='', encoding='utf-8') # make a new variable, c, for Python's CSV writer object - c = csv.writer(csvfile) # write custom header row to csv c.writerow( ['year', 'rank', 'title', 'gross'] ) # modified code that was already tested, from above for year in years: url = base_url + str(year) html = requests.get(url) soup = BeautifulSoup(html.text, 'html.parser') tables = soup.find_all( 'table' ) rows = tables[6].find_all('tr') for i in range(2, 7): cells = rows[i].find_all('td') gross = cells[3].text.strip('$').replace(',', '') # print(year, cells[0].text, cells[1].text, gross) # instead of printing, I need to make a list and write that list to the CSV as one row c.writerow( [year, cells[0].text, cells[1].text, gross] ) # close the csv file and save it csvfile.close() ``` The result is a CSV file, named `movies.csv`, that has 51 rows: the header row plus 5 movies for each year from 2010 through 2019. It has four columns: year, rank, title, and gross. Note that **only the final cell above** is needed to create this CSV, by scraping 10 separate web pages. Everything *above* the final cell above is just instruction, demonstration. It is intended to show the problem-solving you need to go through to get to a desired scraping result.
github_jupyter
``` %load_ext autoreload %autoreload 1 import time import pandas as pd import numpy as np import random as rn from tqdm import tqdm import os import sys sys.path.append("../utils/") %aimport utils from keras import backend as K from keras.models import Sequential, Model from keras.layers import Dense from imblearn.over_sampling import RandomOverSampler from imblearn.under_sampling import RandomUnderSampler from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from tensorflow import set_random_seed import seaborn as sns import matplotlib.pyplot as plt # reproducibility seed = 42 os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) set_random_seed(seed) rn.seed(seed) # maximum number of cores n_cores = 10 K.set_session(K.tf.Session(config=K.tf.ConfigProto( intra_op_parallelism_threads=n_cores, inter_op_parallelism_threads=n_cores ))) TUMOR = 0 NORMAL = 1 now = time.strftime('%Y%m%d_%H%M') description = "LUNG_1vsALL_NN_NN" folder = now + "_" + description output_folder = os.path.join("./results/", folder) output_folder writer = pd.ExcelWriter(os.path.join(output_folder, "results.xlsx"), engine='xlsxwriter') ``` ## Data ``` def get_filtered_features(X): #return np.arange(10) return X.std(0).argsort()[::-1][:5000] def preprocess(X): scaler = MinMaxScaler() return utils.pre_process(X, get_filtered_features, scaler) colormap = { TUMOR: 'red', NORMAL: 'blue' } def plot_PCA(X, y): pca = PCA(n_components=2) X_t = pca.fit_transform(X) colors = list(map(lambda x: colormap[x], y)) plt.figure(figsize=(10, 10)) sns.regplot(x=X_t[:, 0], y=X_t[:, 1], fit_reg=False, scatter_kws={'color': colors, 's': 50}) return pca ``` ## Procedure ``` cancer_name = "THCA" X_c, y_c = utils.get_cancer_data(cancer_name) # sampler = RandomUnderSampler() # X_c, y_c = sampler.fit_sample(X_c, y_c) print("Cancer: {}".format(cancer_name)) print("\t#samples: {}".format(X_c.shape[0])) print("\t#genes: {}".format(X_c.shape[1])) print("\t#TUMORS: {}\t#NORMAL: {}".format(y_c[y_c == TUMOR].shape[0], y_c[y_c == NORMAL].shape[0])) plt.figure(figsize=(10, 10)) pca = plot_PCA(X_c, y_c) plt.show() pca.explained_variance_ratio_ others = list(set(utils.all_tumor_names) - {'BLCA'}) # others = ['OV', 'BRCA'] # print(", ".join(others)) X_others = np.empty((0, X_c.shape[1]), dtype=int) y_others = np.empty(0, dtype=int) for o in others: print(o) X_o, y_o = utils.get_cancer_data(o) X_others = np.append(X_others, X_o, axis=0) y_others = np.append(y_others, y_o) print("Cancer: {}".format(others)) print("\t#samples: {}".format(X_others.shape[0])) print("\t#genes: {}".format(X_others.shape[1])) print("\t#TUMORS: {}\t#NORMAL: {}".format(y_others[y_others == TUMOR].shape[0], y_others[y_others == NORMAL].shape[0])) plt.figure(figsize=(10, 10)) plot_PCA(X_others, y_others) plt.show() ``` ### Tumor alone ``` def tumor_alone_model(input_size): """ A super-simple NN for the single tumor classification """ model = Sequential() model.add(Dense(100, input_shape=(input_size,), activation='relu')) model.add(Dense(20, activation='relu')) model.add(Dense(1, activation="sigmoid")) return model cvscores_c, histories_c = utils.cross_validation(X=X_c, y=y_c, preprocess=preprocess, seed=seed, n_randomizations=5, create_model=tumor_alone_model, get_measures=utils.get_measures) cvscores_c.mean().to_frame().T.drop(["split", 'random_set'], axis=1) utils.report(cvscores_c, writer=writer, sheet_name="{}_alone".format(cancer_name)) ``` ### Others alone ``` def others_alone_model(input_size): h1 = 500 h2 = 200 h3 = 100 h4 = 50 out = 1 model = Sequential() model.add(Dense(h1, input_shape=(input_size, ), activation="relu")) model.add(Dense(h2, activation="relu")) model.add(Dense(h3, activation="relu")) model.add(Dense(h4, activation="relu")) model.add(Dense(out, activation="sigmoid")) return model cvscores_others, histories_others = utils.cross_validation(X=X_others, y=y_others, preprocess=preprocess, seed=seed, create_model=others_alone_model, get_measures=utils.get_measures) cvscores_others.mean().to_frame().T.drop("split", axis=1) utils.report(cvscores_others, writer=writer, sheet_name="{}_others".format(cancer_name)) ``` ### Transfer learning ``` def create_other_network(input_size): h1 = 500 h2 = 200 h3 = 100 h4 = 50 out = 1 model = Sequential() model.add(Dense(h1, input_shape=(input_size, ), activation="relu", name='h1')) model.add(Dense(h2, activation="relu", name='h2')) model.add(Dense(h3, activation="relu", name='h3')) model.add(Dense(h4, activation="relu", name='h4')) model.add(Dense(out, activation="sigmoid", name='out')) encoder = Model(inputs=model.input, outputs=model.get_layer("h3").output) return model, encoder def create_additional_network(input_size): h1 = 50 h2 = 10 out = 1 model = Sequential() model.add(Dense(h1, input_shape=(input_size, ), activation="relu", name='h1')) model.add(Dense(h2, activation="relu", name='h2')) model.add(Dense(out, activation="sigmoid", name='out')) return model def tl_data_merging(X, y, train, test, preprocess, validation_split, seed, X_other, y_other): # print(X.shape, y.shape) # print(X_other.shape, y.shape) # print("Splitting of X_c") # Splitting the single tumor dataset X_train, y_train = X[train], y[train] X_test, y_test = X[test], y[test] # get the validation set in a stratified fashion from the training set X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=validation_split, random_state=seed, stratify=y_train) # Merge the single cancer training set with the other set X_train_merged = np.append(X_train, X_other, axis=0) y_train_merged = np.append(y_train, y_other) # preprocess merged training set and get features and scaler X_train_merged, scaler, sel_features = preprocess(X_train_merged) # transform testing set X_test = scaler.fit_transform(X_test[:, sel_features]) # transform validation set X_val = scaler.fit_transform(X_val[:, sel_features]) # print(X_train_merged.shape, y_train_merged.shape) # print(X_val.shape, y_val.shape) # print(X_test.shape, y_test.shape) return X_train_merged, X_val, X_test, y_train_merged, y_val, y_test def transfer_learning(X, y, train, test, preprocess, validation_split, seed, X_other, y_other): # print(X.shape, y.shape) # print(X_other.shape, y.shape) # print("Splitting of X_c") # Splitting the single tumor dataset X_train, y_train = X[train], y[train] X_test, y_test = X[test], y[test] # get the validation set in a stratified fashion from the training set X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=validation_split, random_state=seed, stratify=y_train) # print("Scaling of X_c") # preprocess training set and get features and scaler X_train, scaler, sel_features = preprocess(X_train) # transform testing set X_test = scaler.fit_transform(X_test[:, sel_features]) # transform validation set X_val = scaler.fit_transform(X_val[:, sel_features]) # print("Scaling and selection on X_other") # for the other set we use a brand new scaler but the same features other_scaler = MinMaxScaler() X_other = other_scaler.fit_transform(X_other[:, sel_features]) # splitting other set in training and validation (no test...useless) X_other_train, X_other_val, \ y_other_train, y_other_val = train_test_split(X_other, y_other, test_size=validation_split, random_state=seed, stratify=y_other) # print("Fitting the OTHER model") # create and fit the OTHER model other_model, encoder = create_other_network(input_size=X_other_train.shape[1]) other_model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy']) other_model.fit(X_other_train, y_other_train, epochs=100, batch_size=60, verbose=0, validation_data=(X_other_val, y_other_val), callbacks=[utils.get_early_stopping_condition()]) # print("Encoding X_c") # embedding of data X_train_code = encoder.predict(X_train) X_val_code = encoder.predict(X_val) X_test_code = encoder.predict(X_test) # print(X_train_code.shape) # print(X_val_code.shape) # print(X_test_code.shape) return X_train_code, X_val_code, X_test_code, y_train, y_val, y_test cvscores_tl, histories_tl = utils.cross_validation(X=X_c, y=y_c, preprocess=preprocess, seed=seed, n_randomizations=5, create_model=create_additional_network, get_measures=utils.get_measures, data_preparation=transfer_learning, X_other=X_others, y_other=y_others) cvscores_tl.mean().to_frame().T.drop(["split", 'random_set'], axis=1) cvscores_c.mean().to_frame().T.drop(["split", 'random_set'], axis=1) utils.report(cvscores_tl, writer=writer, sheet_name="{}_TL".format(cancer_name)) os.makedirs(output_folder, exist_ok=True) writer.save() cvscores_tl.mean() - cvscores_c.mean() ```
github_jupyter
Tutorial on computational modeling and statistical model fitting part of the *IBL Computational Neuroscience Course* organized by the [International Brain Laboratory](https://www.internationalbrainlab.com/) (April 2020). **Lecturer:** [Luigi Acerbi](http://luigiacerbi.com/). **Instructions:** - To run the tutorial, you will need a standard scientific Python 3.x installation with Jupyter notebook (such as [Anaconda](https://www.anaconda.com/distribution/)). - You will also need the `CMA-ES` optimization algorithm (see [here](https://github.com/CMA-ES/pycma)). You can install CMA-ES from the command line with `pip install cma`. - For any question, please email the course instructor at luigi.acerbi@internationalbrainlab.org. **Initial setup and loading the data:** ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd import scipy as sp from scipy.stats import norm import cma ``` During this tutorial, we are going to use data from the [International Brain Laboratory](https://www.internationalbrainlab.com/) publicly released behavioral mouse dataset, from exemplar mouse `KS014`. See [this preprint](https://www.biorxiv.org/content/10.1101/2020.01.17.909838v2) for more information about the task and datasets. These data can also be inspected via the IBL DataJoint public interface [here](https://data.internationalbrainlab.org/mouse/18a54f60-534b-4ed5-8bda-b434079b8ab8). For convenience, the data of all behavioral sessions from examplar mouse `KS014` have been already downloaded in the `data` folder and slightly preprocessed into two `.csv` files, one for the training sessions (`KS014_train.csv`) and one with the *biased* sessions (`KS014_biased.csv`). We begin our tutorial by examining the training sessions. ``` df = pd.read_csv('./data/KS014_train.csv') # Load .csv file into a pandas DataFrame df['signed_contrast'] = df['contrast']*df['position'] # We define a new column for "signed contrasts" df.drop(columns='stim_probability_left', inplace=True) # Stimulus probability has no meaning for training sessions print('Total # of trials: ' + str(len(df['trial_num']))) print('Sessions: ' + str(np.unique(df['session_num']))) df.head() ``` **Inspecting the data:** The first thing to do with any dataset is to get familiar with it by running simple visualizations. Just plot stuff! For example, as a starter we plot data from individual sessions using a *scatterplot* format (perhaps not the best). What can we see from here? ``` def scatterplot_psychometric_data(df,session_num=None,ax=None): """Plot psychometric data (optionally, of a chosen training session) as a scatter plot.""" if session_num == None: trial_mask = np.ones(len(df['session_num']), dtype=bool) # Select all trials else: trial_mask = df['session_num'] == session_num # Indexes of trials of the chosen session Ntrials = np.sum(trial_mask) # Number of chosen trials # Count "left" and "right" responses for each signed contrast level left_resp = df[(df['response_choice'] == -1) & trial_mask].groupby(['signed_contrast']).count()['trial_num'] right_resp = df[(df['response_choice'] == 1) & trial_mask].groupby(['signed_contrast']).count()['trial_num'] if ax == None: ax=fig.add_axes([0,0,1,1]) ax.scatter(left_resp.index,np.zeros(len(left_resp.index)), s=left_resp*10); ax.scatter(right_resp.index,np.ones(len(right_resp.index)), s=right_resp*10); ax.set_xlabel('Signed contrast (%)') ax.set_ylabel('Rightward response') if session_num == None: ax.set_title('Psychometric data (# trials = ' + str(Ntrials) + ')') else: ax.set_title('Psychometric data (session ' + str(session_num) + ', # trials = ' + str(Ntrials) + ')') return ax # Plot 2nd session fig = plt.figure(figsize=(9,4)) scatterplot_psychometric_data(df,2) plt.show() # Plot 15th session (last training session) fig = plt.figure(figsize=(9,4)) scatterplot_psychometric_data(df,15) plt.show() ``` We plot the same data again, this time with a different type of plot which may be more informative. ``` def plot_psychometric_data(df,session_num=None,ax=None): """Plot psychometric data (optionally, of a chosen training session) as a scatter plot.""" if session_num == None: trial_mask = np.ones(len(df['session_num']), dtype=bool) # Select all trials else: trial_mask = df['session_num'] == session_num # Indexes of trials of the chosen session Ntrials = np.sum(trial_mask) # Number of chosen trials # Count "left" and "right" responses for each signed contrast level left_resp = df[(df['response_choice'] == -1) & trial_mask].groupby(['signed_contrast']).count()['trial_num'] right_resp = df[(df['response_choice'] == 1) & trial_mask].groupby(['signed_contrast']).count()['trial_num'] frac_resp = right_resp / (left_resp + right_resp) err_bar = np.sqrt(frac_resp*(1-frac_resp)/(left_resp + right_resp)) # Why this formula for error bars? if ax == None: ax=fig.add_axes([0,0,1,1]) ax.errorbar(x=left_resp.index,y=frac_resp,yerr=err_bar,label='data'); ax.set_xlabel('Signed contrast (%)') ax.set_ylabel('Rightward response') if session_num == None: ax.set_title('Psychometric data (# trials = ' + str(Ntrials) + ')') else: ax.set_title('Psychometric data (session ' + str(session_num) + ', # trials = ' + str(Ntrials) + ')') plt.xlim((-105,105)) plt.ylim((0,1)) return ax fig = plt.figure(figsize=(9,4)) plot_psychometric_data(df,2) plt.show() fig = plt.figure(figsize=(9,4)) plot_psychometric_data(df,15) plt.show() ``` **The psychometric function model:** We define now the `basic` psychometric function (descriptive) model and a plotting function. ``` def psychofun(theta,stim): """Psychometric function based on normal CDF and lapses""" mu = theta[0] # bias sigma = theta[1] # slope/noise lapse = theta[2] # lapse rate if len(theta) == 4: # lapse bias lapse_bias = theta[3]; else: lapse_bias = 0.5 # if theta has only three elements, assume symmetric lapses p_right = norm.cdf(stim,loc=mu,scale=sigma) # Probability of responding "rightwards", without lapses p_right = lapse*lapse_bias + (1-lapse)*p_right # Adding lapses return p_right def psychofun_plot(theta,ax): """Plot psychometric function""" stim = np.linspace(-100,100,201) # Create stimulus grid for plotting p_right = psychofun(theta,stim) # Compute psychometric function values ax.plot(stim,p_right,label='model') ax.legend() return ``` Now try plotting the psychometric function for different values of the parameters (use both the symmetric and asymmetric psychometric function). Try and match the data from one of the sessions. ``` theta0 = (0,50,0.2,0.5) # Arbitrary parameter values - try different ones session_num = 15 fig = plt.figure(figsize=(9,4)) ax = plot_psychometric_data(df,session_num) psychofun_plot(theta0,ax) plt.show() ``` We now define the log likelihood function of the psychometric function model for a given dataset and model parameter vector, $\log p(\text{data}|\mathbf{\theta})$. ``` def psychofun_loglike(theta,df): """Log-likelihood for psychometric function model""" s_vec = df['signed_contrast'] # Stimulus values r_vec = df['response_choice'] # Responses p_right = psychofun(theta,s_vec) # Compute summed log likelihood for all rightwards and leftwards responses loglike = np.sum(np.log(p_right[r_vec == 1])) + np.sum(np.log(1 - p_right[r_vec == -1])) return loglike ``` Now try to get the best fit for this session, as we did before, but by finding better and better values of the log-likelihood. ``` session_num = 14 # Let's use a different session theta0 = (0,25,0.1,0.5) ll = psychofun_loglike(theta0,df[df['session_num'] == session_num]) print('Log-likelihood value: ' + "{:.3f}".format(ll)) fig = plt.figure(figsize=(9,4)) ax = plot_psychometric_data(df,session_num) psychofun_plot(theta0,ax) plt.show() ``` **Maximum-likelihood estimation:** In this section, we are going to estimate model parameters (aka fit our models) by maximizing the log-likelihood. By convention in optimization, we are going to *minimize* the negative log-likelihood. Before running the optimization, we define the *hard* lower and upper bounds for the parameters. If the optimization algorithm supports constrained (bound) optimization, it will never go outside the hard bounds. We also define informally the *plausible* bounds as the range of parameters that we would expect to see. We are going to use the plausible range to initialize the problem later. ``` # Define hard parameter bounds lb = np.array([-100,0.5,0,0]) ub = np.array([100,200,1,1]) bounds = [lb,ub] # Define plausible range plb = np.array([-25,5,0.05,0.2]) pub = np.array([25,25,0.40,0.8]) # Pick session data session_num = 14 df_session = df[df['session_num'] == session_num] # Define objective function: negative log-likelihood opt_fun = lambda theta_: -psychofun_loglike(theta_,df_session) ``` We are now going to run a *black-box* optimization algorithm called CMA-ES. For now we are going to run the optimization only once, but in general you should *always* run the optimization from multiple distinct starting points. ``` # Generate random starting point for the optimization inside the plausible box theta0 = np.random.uniform(low=plb,high=pub) # Initialize CMA-ES algorithm opts = cma.CMAOptions() opts.set("bounds",bounds) opts.set("tolfun",1e-5) # Run optimization res = cma.fmin(opt_fun, theta0, 0.5, opts) print('') print('Returned parameter vector: ' + str(res[0])) print('Negative log-likelihood at solution: ' + str(res[1])) fig = plt.figure(figsize=(9,4)) ax = plot_psychometric_data(df_session,session_num) psychofun_plot(res[0],ax) plt.show() ``` **Model comparison:** We consider now a slightly more advanced model which includes time dependency by having the response in the current trial being influenced by the response in the previous trial. We adopt a simple model, `repeatlast`, in which the observer has a fixed chance of repeating the previous choice. ``` def psychofun_repeatlast_loglike(theta,df): """Log-likelihood for last-choice dependent psychometric function model""" s_vec = np.array(df['signed_contrast']) # Stimulus values r_vec = np.array(df['response_choice']) # Responses p_last = theta[0] # Probability of responding as last choice theta_psy = theta[1:] # Standard psychometric function parameters p_right = psychofun(theta_psy,s_vec) # Starting from the 2nd trial, probability of responding equal to the last trial p_right[1:] = p_last*(r_vec[0:-1] == 1) + (1-p_last)*p_right[1:] # Compute summed log likelihood for all rightwards and leftwards responses loglike = np.sum(np.log(p_right[r_vec == 1])) + np.sum(np.log(1 - p_right[r_vec == -1])) return loglike lb = np.array([0,-100,1,0,0]) ub = np.array([1,100,100,1,1]) bounds = [lb,ub] plb = np.array([0.05,-25,5,0.05,0.2]) pub = np.array([0.2,25,25,0.45,0.8]) df_session = df[df['session_num'] == session_num] # df_session = df[(df['session_num'] == session_num) & (df['trial_num'] > 300)] opt_fun = lambda theta_: -psychofun_repeatlast_loglike(theta_,df_session) theta0 = np.random.uniform(low=plb,high=pub) opts = cma.CMAOptions() opts.set("bounds",bounds) opts.set("tolfun",1e-5) res_repeatlast = cma.fmin(opt_fun, theta0, 0.5, opts) print('') print('Returned parameter vector: ' + str(res_repeatlast[0])) print('Negative log-likelihood at solution: ' + str(res_repeatlast[1])) fig = plt.figure(figsize=(9,4)) ax = plot_psychometric_data(df_session,session_num) #psychofun_plot(res[0],ax) plt.show() ``` We now calculate a few model simple comparison metrics, such as AIC and BIC, for the `basic` and `repeatlast` models. ``` Nmodels = 2 nll = np.zeros(Nmodels) nparams = np.zeros(Nmodels) results = [res,res_repeatlast] # Store all optimization output in a vector for i in range(0,len(results)): nll[i] = results[i][1] # The optimization algorithm received the *negative* log-likelihood nparams[i] = len(results[i][0]) ntrials = len(df['signed_contrast']) aic = 2*nll + 2*nparams bic = 2*nll + nparams*np.log(ntrials) print('Model comparison results (for all metrics, lower is better)\n') print('Negative log-likelihoods: ' + str(nll)) print('AIC: ' + str(aic)) print('BIC: ' + str(bic)) ``` **[Advanced] Optional model:** We consider next a more advanced model which includes explicit time dependency (the trials are not all the same), also known as *non-stationarity*. Note that this function is not coded very efficiently and runs quite slowly due to the `for` loop - it could be improved with vectorization. ``` def psychofun_timevarying_loglike(theta,df): """Log-likelihood for time-varying psychometric function model""" s_vec = np.array(df['signed_contrast']) # Stimulus values r_vec = np.array(df['response_choice']) # Responses Ntrials = len(s_vec) mu_vec = np.linspace(theta[0],theta[4],Ntrials) sigma_vec = np.linspace(theta[1],theta[5],Ntrials) lapse_vec = np.linspace(theta[2],theta[6],Ntrials) lapsebias_vec = np.linspace(theta[3],theta[7],Ntrials) p_right = np.zeros(Ntrials) for t in range(0,Ntrials): p_right[t] = psychofun([mu_vec[t],sigma_vec[t],lapse_vec[t],lapsebias_vec[t]],s_vec[t]) # Compute summed log likelihood for all rightwards and leftwards responses loglike = np.sum(np.log(p_right[r_vec == 1])) + np.sum(np.log(1 - p_right[r_vec == -1])) return loglike theta0 = (0,20,0.1,0.5,1,20,0.1,0.5) ll = psychofun_timevarying_loglike(theta0,df[df['session_num'] == session_num]) lb = np.array([-100,1,0,0,-100,1,0,0]) ub = np.array([100,100,1,1,100,100,1,1]) bounds = [lb,ub] plb = np.array([-25,5,0.05,0.2,-25,5,0.05,0.2]) pub = np.array([25,25,0.45,0.8,25,25,0.45,0.8]) session_num = 14 df_session = df[df['session_num'] == session_num] # df_session = df[(df['session_num'] == session_num) & (df['trial_num'] > 300)] opt_fun = lambda theta_: -psychofun_timevarying_loglike(theta_,df_session) theta0 = np.random.uniform(low=plb,high=pub) opts = cma.CMAOptions() opts.set("bounds",bounds) opts.set("tolfun",1e-5) res_time = cma.fmin(opt_fun, theta0, 0.5, opts) print('') print('Returned parameter vector: ' + str(res_time[0])) print('Negative log-likelihood at solution: ' + str(res_time[1])) fig = plt.figure(figsize=(9,4)) ax = plot_psychometric_data(df_session,session_num) #psychofun_plot(res[0],ax) plt.show() ```
github_jupyter
``` # bem: triangulation and fmm/bem electrostatics tools # # Copyright (C) 2011-2012 Robert Jordens <jordens@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ``` # `bem` 3D electrostatics example ``` import sys import logging, os from time import time import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') sys.path.append('../../../electrode/') from bem import Electrodes, Sphere, Mesh, Grid, Configuration, Result from bem.formats import stl # base file name for outputs and inputs is the script name try: # works only if we are a script prefix = os.path.splitext(__file__)[0] except NameError: # fallback for notebooks prefix = "SimpleTrap" # scale to natural units (ion height) scale = 40e-6 use_stl = True if not use_stl: # load electrode faces from loops ele = Electrodes.from_trap(open("%s.ele" % prefix), scale) # initial triangulation, area 20, quiet mesh = Mesh.from_electrodes(ele) mesh.triangulate(opts="qa10Q") else: # load electrode faces from colored stl s = stl.read_stl(open("%s.stl" % prefix, "rb")) mesh = Mesh.from_mesh(stl.stl_to_mesh(*s, scale=scale/1e-6, rename={9495: "DC1", 17962: "DC3", 18994: "DC5", 18869: "DC2", 20943: "RF", 18129: "DC4"})) def run_job(args): job, grid, prefix = args # refine twice adaptively with increasing number of triangles, min # angle 25deg job.adapt_mesh(triangles=4e2, opts="q25Q") job.adapt_mesh(triangles=1e3, opts="q25Q") # solve for charges job.solve_singularities(num_mom=4, num_lev=3) # get potentials and fields result = job.simulate(grid, field=job.name=="RF", num_lev=1) result.to_vtk(prefix) print("finished job %s" % job.name) return job.collect_charges() # set .1 max area within 3 mesh.areas_from_constraints(Sphere(center=np.array([0, 0, 1.]), radius=2, inside=.2, outside=10.)) # retriangulate quality and quiet with areas mesh.triangulate(opts="qQ", new=False) # save base mesh to vtk mesh.to_vtk(prefix) # grid to evalute potential and fields at n, s = 2*10, .1 grid = Grid(center=(0, 0, 1.5), step=(s, s, s), shape=(n, n, n)) # generate electrode potential configurations to simulate # use regexps to match electrode names jobs = list(Configuration.select(mesh, "DC.*", "RF")) # run the different electrodes on the parallel pool #pmap = Pool().map # parallel map pmap = map # serial map t0 = time() list(pmap(run_job, ((job, grid, prefix) for job in jobs))) # In python 3, convert map(...) to list(map(...)) print("Computing time: %f s"%(time()-t0)) # isocontour plot of the RF pseudopotential radially result = Result.from_vtk(prefix, "RF") p = result.pseudo_potential x = grid.to_mgrid()[:, p.shape[0]//2] # In python 3, use // p = p[p.shape[0]//2] fig, ax = plt.subplots() ax.set_aspect("equal") ax.contour(x[1], x[2], p, levels=np.linspace(0, 2e-2, 20), cmap=plt.cm.Reds) fig, ax = plt.subplots(subplot_kw=dict(aspect="equal")) mesh.plot(ax) # explore it in fancy 3D # fire up a mayavi2 window showing base mesh, charges on final mesh # and isosurfaces of the pseudopotential Result.view(prefix, "RF") # need to start the full eventloop for the window. # close it to return control to the notebook from pyface.api import GUI GUI().start_event_loop() from electrode import System, GridElectrode # load the electrostatics results into a electrode.System() s = System() for name in "DC1 DC2 DC3 DC4 DC5 RF".split(): r = Result.from_vtk(prefix, name) e = GridElectrode.from_result(r) e.name = name s.append(e) import scipy.constants as ct l = 40e-6 # length scale o = 100e6*2*np.pi # rf frequency m = 25*ct.atomic_mass # ion mass q = 1*ct.elementary_charge # ion charge rf_scale = s.rf_scale(m,q,l,o) s["RF"].rf = 25. # peak rf voltage method = 'Newton-CG' x0 = s.minimum((0, 0, 1.),method=method) for _ in s.analyze_static(x0, m=m, l=l, o=o, min_method=method): print(_) n = 30 #xyz = np.mgrid[-.1:.1:1j*n, -.1:.1:1j*n, 1.12:2] #xyz = np.mgrid[0:1, -.02:.02:1j*n, .5:1.5:1j*n] xyz = grid.to_mgrid() p = s.potential(xyz.reshape(3, -1).T, 0).reshape(xyz[0].shape) v = np.linspace(0, 2e-2, 21) fig, ax = plt.subplots() ax.set_aspect("equal") ax.contour(xyz[1, 10, :, :], xyz[2, 10, :, :], p[10, :, :], v, cmap=plt.cm.Reds_r) ```
github_jupyter
# Running cell2location on NanostringWTA data In this notebook we we map fetal brain cell types to regions of interest (ROIs) profiled with the NanostringWTA technology, using a version of our cell2location method recommended for probe based spatial transcriptomics data. This notebook should be read after looking at the main cell2location notebooks. Load the required modules and configure theano settings: ``` import sys,os import pickle import anndata import pandas as pd import numpy as np import matplotlib.pyplot as plt import scanpy as sc from IPython.display import Image data_type = 'float32' os.environ["THEANO_FLAGS"] = 'device=cuda,floatX=' + data_type + ',force_device=True' + ',dnn.enabled=False' import cell2location # Download data: os.mkdir('./data') os.system('cd ./data && wget https://cell2location.cog.sanger.ac.uk/nanostringWTA/nanostringWTA_fetailBrain_AnnData_smallestExample.p') os.system('cd ./data && wget https://cell2location.cog.sanger.ac.uk/nanostringWTA/polioudakis2019_meanExpressionProfiles.csv') ``` Load a data: ``` adata_wta = pickle.load(open("data/nanostringWTA_fetailBrain_AnnData_smallestExample.p", "rb" )) ``` In this NanostringWTA run we profiled 288 regions of interest (ROIs) spanning the full depth of the cortex and at both 19pcw and 14pcw. An example is shown in the image below, together with the cell types we expect in each region: ``` Image(filename='../images/GeometricROIs.PNG') ``` Here we load an existing matrix of average gene expression profiles for each cell type expected in our nanostringWTA data (taken from the single-cell RNAseq study Polioudakis et al., Neuron, 2019): ``` meanExpression_sc = pd.read_csv("data/polioudakis2019_meanExpressionProfiles.csv", index_col=0) ``` We need seperate gene probes and negative probes and if available we can also supply nuclei counts. We initialize all of those here: ``` counts_negativeProbes = np.asarray(adata_wta[:,np.array(adata_wta.var_names =='NegProbe-WTX').squeeze()].X) counts_nuclei = np.asarray(adata_wta.obs['nuclei']).reshape(len(adata_wta.obs['nuclei']),1) adata_wta = adata_wta[:,np.array(adata_wta.var_names != 'NegProbe-WTX').squeeze()] ``` As you can see the nuclei counts and negative probes need to be numpy arrays, but the gene probe counts are supplied as an AnnData object. ``` adata_wta.raw = adata_wta ``` Run cell2location: Explanations of the arguments are as follows: <br> 'model_name = cell2location.models.LocationModelWTA' > Here we tell cell2location to use the NanostringWTA model, rather than the standard model. <br> 'use_raw': False > extract the data from adata_wta.X and not from adata_wta.raw.X <br> 'Y_data': counts_negativeProbes > we supply the negative probe information here <br> 'cell_number_prior' and 'cell_number_var_prior': we supply information about nuclei counts here <br> ``` cell2location.run_c2l.run_cell2location(meanExpression_sc, adata_wta, model_name=cell2location.models.LocationModelWTA, train_args={'use_raw': False}, model_kwargs={ "Y_data" : counts_negativeProbes, "cell_number_prior" : {'cells_per_spot': counts_nuclei, 'factors_per_spot': 6, 'combs_per_spot': 3}, "cell_number_var_prior" : {'cells_mean_var_ratio': 1, 'factors_mean_var_ratio': 1, 'combs_mean_var_ratio': 1}}) ``` An anndata object that has the cell2location results included is saved and can be used for further analysis, as in standard cell2location: ``` adata_c2l = sc.read_h5ad('resultsLocationModelWTA_1experiments_16clusters_288locations_15124genes/sp.h5ad') adata_c2l.obs.loc[:,['mean_spot_factors' in c for c in adata_c2l.obs.columns]] ``` We can also plot the same QC metrics as in standard cell2location: ``` from IPython.display import Image Image(filename='resultsLocationModelWTA_1experiments_16clusters_288locations_15124genes/plots/training_history_without_first_20perc.png', width=400) Image(filename='resultsLocationModelWTA_1experiments_16clusters_288locations_15124genes/plots/data_vs_posterior_mean.png', width=400) Image(filename='resultsLocationModelWTA_1experiments_16clusters_288locations_15124genes/plots/evaluate_stability.png', width=400) ``` Finally we have this method to plot cell type abundance in 1D across our coordinate of interest (cortical depth): It makes most sense to plot a subset, for example on one 19pcw slide at one position: ``` colourCode = {'SPN': 'salmon', 'End': 'darkcyan', 'ExDp1': 'deepskyblue', 'ExDp2': 'blue', 'ExM': 'gold', 'ExM-U': 'yellow', 'ExN': 'darkorange', 'InCGE': 'darkgrey', 'InMGE': 'dimgray', 'IP': 'darkviolet', 'Mic': 'indianred', 'OPC': 'lightcoral', 'oRG': 'red', 'Per': 'darkgreen', 'PgG2M': 'rebeccapurple', 'PgS': 'violet', 'vRG': 'lightgreen'} subset_19pcw = [adata_c2l.obs['slide'].iloc[i] == '00MU' and adata_c2l.obs['Radial_position'].iloc[i] == 2 for i in range(len(adata_c2l.obs['Radial_position']))] cell2location.plt.plot_absolute_abundances_1D(adata_c2l, subset = subset_19pcw, saving = False, scaling = 0.15, power = 1, pws = [0,0,100,500,1000,3000,6000], figureSize = (12,8), dimName = 'VCDepth', xlab = 'Cortical Depth', colourCode = colourCode) ``` You can also plot density rather than total numbers: ``` cell2location.plt.plot_density_1D(adata_c2l, subset = subset_19pcw, saving = False, scaling = 0.05, power = 1, pws = [0,0,100,500,1000,3000,6000,10000], figureSize = (12,8), dimName = 'VCDepth', areaName = 'roi_dimension', xlab = 'Cortical Depth', colourCode = colourCode) ```
github_jupyter
``` # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the read-only "../input/" directory # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory import os for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) # You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session from sklearn.preprocessing import LabelEncoder ``` # **Reading Input** ``` path = '/kaggle/input/osic-pulmonary-fibrosis-progression/' train = pd.read_csv(path + 'train.csv') test = pd.read_csv(path + 'test.csv') sub = pd.read_csv(path + 'sample_submission.csv') train.head() print(train.shape) print(test.shape) print(sub.shape) ``` # Preparing Categorical Variables ``` encoder = LabelEncoder() cat_features = ['Sex', 'SmokingStatus'] encoded = train[cat_features].apply(encoder.fit_transform) X = train[['Percent', 'Weeks', 'Age']].join(encoded) X.head() Y = train['FVC'] Y.head() ``` # Linear Regression Model ``` from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.2, random_state=0) model = LinearRegression() model.fit(X_train, Y_train) print(model.intercept_) print(model.coef_) y_pred = model.predict(X_val) ``` # Making Predicitons ``` sub.head() test.head() sub[['Patient', 'Weeks']] = sub.Patient_Week.str.split("_", expand=True) sub.head() encoded = test[cat_features].apply(encoder.fit_transform) test.head() test2 = test[['Patient', 'Percent', 'Age']].join(encoded) test2.head() sub = sub.drop('FVC', 1) sub = sub.drop('Confidence', 1) # test.drop('Weeks', 1) sub = pd.merge(sub, test2, on='Patient', how='left') sub.head(100) X2 = sub[['Percent', 'Weeks', 'Age', 'Sex', 'SmokingStatus']] sub['FVC'] = model.predict(X2) sub.head() sub['FVC_Group'] = sub.groupby(['Weeks','SmokingStatus','Sex','Age'])['FVC'].transform('mean') sub['Confidence'] = 100 * sub['FVC'] / sub['FVC_Group'] sub.head(100) submission = sub[['Patient_Week', 'FVC', 'Confidence']] submission['FVC'] = submission['FVC'].astype(int) submission['Confidence'] = submission['Confidence'].astype(int) submission.head() submission.to_csv("/kaggle/working/submission.csv", index=False) ```
github_jupyter
``` # hide %load_ext autoreload from nbdev import * # default_exp annotate ``` # Annotate > Tools to support creating and process annotation for samples of Newspaper Navigator data using Label Studio ``` # hide from nbdev.showdoc import * # export from nnanno.core import * # export from tqdm.notebook import trange, tqdm from toolz.itertoolz import count import pandas as pd from pandas import json_normalize import simplejson as json import requests import re from datetime import datetime from glob import glob from pathlib import Path # export import nnanno from typing import Union, Optional, Type ``` ## Annotating Newspaper Navigator data Once you have created a sample of Newspaper Navigator data using `sample`, you might want to annotate it somehow. These annotations may function as the input for a machine learning model or could be used directly to explore images in the newspaper navigator data. The `Examples` section in the documentation shows how annotations can generate training data for machine learning tasks. ## Setup annotation task The bulk of annotation work is outsourced to label studio, which provides a flexible annotations system that supports annotations for various data types, including images and text. This module does a few steps to help process annotations produced through label studio. This module is essentially some suggestions on how you can get label-studio setup with data from Newspaper Navigator. First, we'll create a small sample of images we want to annotate using `sample`. If you have already done this step, you can skip this. ``` # export from nnanno.sample import * sampler = nnSampler() df = sampler.create_sample( 50, "photos", start_year=1910, end_year=1920, year_sample=False ) ``` There are a few ways in which we can use label studio to annotate. For example, we could download images from our sample using `sample.download_sample`. However, if we have a large sample of images, we might want to do some annotating before downloading all of these images locally. Label-studio supports annotating from a URL. We can use this combined with IIIF to annotate images without downloading them all first since IIIF is a flexible interface for getting images. IIIF also gives us flexibility in annotating at a smaller resolution/size before downloading higher-res images. ## Create label studio annotation tasks Label-studio supports a load of different ways of setting up 'tasks'. In this context, a 'task' is an image to be annotated. One way of setting up a task is to import a `JSON` file that includes tasks. To do this, we take an existing sample DataFrame and add column `image`, which contains a IIIF URL. ``` # export def create_label_studio_json( sample: Union[pd.DataFrame, Type[nnSampler]], fname: Union[str, Path, None] = None, original: bool = True, pct: Optional[int] = None, size: Optional[tuple] = None, preserve_asp_ratio: bool = True, ): """create a json file which can be used to upload tasks to label studio""" if fname and Path(fname).exists(): raise FileExistsError(f"{fname} already exists") if fname is None: today = datetime.today() time_stamp = today.strftime("%Y_%d_%m_%H_%M") fname = f"{time_stamp}_tasks.json" if type(sample) == nnanno.sample.nnSampler: try: sample = sample.sample.copy() except AttributeError as e: print(f"{sample} doesn't have a sample associated with it") else: sample = sample.copy() sample["image"] = sample.apply( lambda x: iiif_df_apply( x, original=original, pct=pct, size=size, preserve_asp_ratio=preserve_asp_ratio, ), axis=1, ) label_studio_json = sample.apply(lambda x: x.to_dict(), axis=1).to_list() with open(fname, "w") as f: json.dump(label_studio_json, f, ignore_nan=True) ``` We can pass in either a dataframe or `nnSampler` to `create_label_studio_json`. This is a simple function that will create a `JSON` file that can create 'tasks' in labels studio. In this example, we pass in size parameters. This is used to generate a IIIF URL that will request this size. ``` create_label_studio_json(df, "tasks.json", size=(500, 500)) # hide Path("tasks.json").unlink() ``` This creates a `JSON` file we can use to load tasks into label-studio. ### Importing tasks into label studio To avoid this documentation becoming out of date, I haven't included screenshots etc. However, you can currently (January 2021) create tasks in label studio via the GUI or by passing in tasks through the CLI. For example, to load the tasks and create a template for annotating classifications ```bash label-studio init project_name --template=image_classification --input-path=tasks.json ``` You can then start label-studio and complete the rest of the setup via the GUI. ```bash label-studio start ./project_name ``` ## Setting up labeling For a proper introduction to configuring your labels, consult the label studio [documentation](https://labelstud.io/guide/). One way in which you can setup labels is to use a template as shown above. This template setups an image classification task. There are other [templates](https://labelstud.io/templates/) for different tasks. These templates consist of `XML` templates that define your labels. These templates allow you to define how you want to label your images and share these definitions with others. For example ```xml <View> <Choices name="choice" toName="image" showInLine="true" choice="multiple"> <Choice value="human"/> <Choice value="animal"/> <Choice value="human-structure"/> <Choice value="landscape"/> </Choices> <Image name="image" value="$image"/> </View> ``` You can change many other options in Label-studio. It also includes features such as adding a machine learning backend to support annotations. ### Notes on labelling using IIIF images There are a few things to consider and be aware of when loading images via IIIF in label studio. #### Missing images Occasionally when you are doing your annotations in label studio for IIIF URLs, you will get a missing image error. This is probably because for some reason the IIIF URL has been generated incorrectly for that image, or that image doesn't exist via IIIF. If this happens, you can 'skip' this image in the annotation interface. #### Setting a comfortable size for viewing You can take advantage of the flexibility of IIIF by requesting images to be a specific size when you create the tasks. This also helps speed up the process of loading each image since we often request a smaller sized image to fit it in on a smallish screen comfortably. #### Annotating vs training image size, resolution etc. IF you are annotating labels or classifications, you may decide to annotate at a smaller size or quality and work with a higher quality image when you come to training a model. If you are doing any annotations of pixels or regions of the image, you will want to be careful to make sure these aren't lost if moving between different sizes of the image. ### Exporting and loading annotations from label studio Label studio supports a broad range of annotation tasks which may require particular export formats i.e. COCO or VOC for object detection. Since the processing of these outputs is tasks specific this module only contains functionality to deal with image classification and labeling tasks since these were the tasks covered in the Programming Historian lessons for which this code was originally written. ### Exporting and processing CSV Once you have finished annotating all your images or got too bored of annotating, you can export in various formats, including JSON and CSV. A CSV export is often sufficient for simple tasks and has the additional benefit of having a lower barrier to entry than JSON for people who aren't coders. We'll now process the annotations we generated above and labeled using label studio ``` # export def process_labels(x): try: x = "|".join(eval(x)["choices"]) except: NameError return x # exports def load_annotations_csv(csv: Union[str, Path], kind="classification"): if kind == "classification": df = pd.read_csv(csv, converters={"box": eval}) df["label"] = df["choice"] return df if kind == "label": df = pd.read_csv(csv, converters={"box": eval}) df["label"] = df["choice"].apply(process_labels) return df ``` As you can see above, this code doesn't do much to process the annotations into a DataFrame. The main things to note are the `kind` parameter. The CSV export for labelling tasks includes a column that contains a JSON with the labels. In this case, we use a pandas converter and `eval` and grab the choices, which returns a list of labels. If we look at the columns from the annotation DataFrame we'll see that label studio kept the original metadata. We now have a new column `label` that contains our annotations. We also have a column `choice` containing the original column format from the label studio export, which will be different from the `label` column when processing labelling annotations. ``` annotation_df = load_annotations_csv("test_iiif_anno/label_studio_export.csv") annotation_df.columns # hide assert "choice" in annotation_df.columns ``` We can now do the usual Pandas things to start exploring our annotations further. For example we can see how many of each label option we have ``` annotation_df["choice"].value_counts() ``` ### Downloading the images associated with annotations Once we have some annotations done, we'll often want to get the original images to work locally. This is particularly important if we are planning to train a machine learning model with these images. Although it is possible to train a model using the images from IIIF, since we'll usually be grabbing these images multiple times for each epoch, this isn't particularly efficient and isn't very friendly to the IIIF endpoint. We can use the `sampler.download_sample` method to download our sample; we just pass in our annotation DataFrame a folder we want to download images to and an optional name to save our 'log' of the download. We can also pass in different parameters to request different size etc. of the image. See the `download_sample` docs for more details. ``` sampler.download_sample( "test_iiif_anno/test_dl", df=annotation_df, original=True, json_name="test_dl" ) # hide # test we have a very similar number of images downloaded and in our annotation dataframe # allow for some images to be missing images = list(Path("test_iiif_anno/test_dl").rglob("*.jpg")) test_close(len(images), len(annotation_df), eps=1) ``` ### Moving between local annotation and the cloud ☁ Although 'storage is cheap', it isn't free. One helpful feature of the IIIF annotations workflow is that it allows you to annotate 'locally,' i.e. on a personal computer and then quickly move the information required to download all the images into the cloud without having to pass the images themselves around. This is particularly useful if you will use a service like Google Colab to train a computer vision model, i.e. you don't have the resources to rent GPUs. In the context of working with limited bandwidth, it might also be relatively time-consuming to download a large set of images. However, it might be feasible to get around this by annotating using the IIIF images and then using a service like google Colab when you want to grab the actual images files. Since Colab is running in the cloud with a big internet tube, this should be much more doable even if your internet is limited. Once you have download your images you may want to check if any images weren't able to download. You can do this using the `check_download_df_match` function. ``` # export def check_download_df_match(dl_folder: Union[Path, str], df: pd.DataFrame) -> str: im_count = count( f for f in Path(dl_folder).iterdir() if f.suffix in image_extensions ) if type(df) == pd.core.frame.DataFrame: if len(df) == im_count: print( f"Length of DataFrame {len(df)} and number of images in {dl_folder} {im_count} match", "\U0001F600", ) if len(df) != im_count: print( f"Length of DataFrame {len(df)} and number of images in {dl_folder} {im_count} do not match", "\U0001F615", ) ``` This will let you know if you have a different number of downloaded images compared to the number of rows in the DataFrame. ``` check_download_df_match("test_iiif_anno/test_dl", annotation_df) ``` ## Working with the annotations This will really depend on the framework or library you want to use. In fastai the process is simple since our data matches one of the fastai 'factory' methods for loading data. ### Loading with fastai ``` # slow from fastai.vision.all import * # slow df = pd.read_json("test_iiif_anno/test_dl/test_dl.json") # slow dls = ImageDataLoaders.from_df( df, path="test_iiif_anno/test_dl", fn_col="download_image_path", label_col="choice", item_tfms=Resize(64), bs=4, ) # slow dls.show_batch() # hide [f.unlink() for f in Path("test_iiif_anno/test_dl").iterdir()] Path("test_iiif_anno/test_dl").rmdir() ``` ## Process completions directly Label studio stores annotations as json files so we can work with these directly without using the exports from label studio. This code below shows how to do this but the above approach is likely to be more reliable. ``` # export def load_df(json_file: Union[str, Path]): with open(json_file) as f: data = json.load(f) df = json_normalize(data, record_path=["completions"], meta=["data"]) # df['result'] = df['result'].apply(lambda x: return_choice(x[0]) if len([x][0]) ==1 else x) df["result"] = df["result"].apply( lambda x: x[0]["value"]["choices"] if len([x][0]) == 1 else x ) return df # export def load_completions(path: Union[str, Path]): filenames = glob(f"{path}/completions/*.json") dataframes = [load_df(f) for f in filenames] return pd.concat(dataframes) # slow df = load_completions("../ph/ads/ad_annotations/") df.head(1) # slow # df = load_completions('../ph/photos/multi_label/') # df.head(1) # exporti def _df_to_csv(df, out_fn): df[["data", "result"]].to_csv( out_fn, header=[ "file", "label", ], index=False, ) # exporti def _df_to_json(df, out_fn): df[["data", "value.choices"]].to_json(out_fn) # exporti def _df_to_pkl(df, out_fn): df.to_pickle(out_fn) # exporti def get_og_filepath(x): """ Transforms a filepaths from processed ImageStudio format back to the Orginal Newspaper Navigator filepath format """ b, m, e = re.split("(_data_)", x) m = m.replace("_", "/") e = re.split("(\d{3}_\d{1}_\d{2}.jpg)", e) return b + m + e[0].replace("_", "/") + e[1] # export def anno_sample_merge( sample_df: pd.DataFrame, annotation_df: pd.DataFrame ) -> pd.DataFrame: """anno_sample_merge merges a DataFrame containing a sample from Newspaper Navigator and a DataFrame containing annotations Parameters ---------- sample_df : pd.DataFrame A Pandas DataFrame which holds a sample from Newspaper Navigator Generated by `sample.nnSample()` annotation_df : pd.DataFrame A pandas DataFrame containing annotations loaded via the `annotate.nnAnnotations` class Returns ------- pd.DataFrame A new DataFrame which merges the two input DataFrames """ sample_df, annotation_df = sample_df.copy(), annotation_df.copy() annotation_df["id"] = annotation_df["data"].map(lambda x: get_og_filepath(x)) return sample_df.merge(annotation_df, left_on="filepath", right_on="id") sample_df = pd.read_csv("../ph/ads/sample.csv", index_col=0) # export class nnAnnotations: def __init__(self, df): self.annotation_df = df self.labels = df["result"].unique() self.label_counts = df["result"].value_counts() def __repr__(self): return f"{self.__class__.__name__}" f" #annotations:{len(self.annotation_df)}" @classmethod def from_completions(cls, path, kind, drop_dupes=True, sample_df=None): df = load_completions(path) df = df.reset_index(drop=True) # add index df["data"] = df["data"].map(lambda x: x["image"]) df["data"] = df["data"].map(lambda x: x.split("?")[0]) df["data"] = df["data"].apply(lambda x: Path(x).name) if any( df["data"].str.contains("-") ): # removes labelstudio hash from data loaded via web interface df["data"] = df["data"].str.split("-", expand=True)[1] if drop_dupes: df = df.drop_duplicates(subset="data", keep="last") if kind == "classification": empty_rows = df[df["result"].apply(lambda x: len(x) == 0)].index df = df.drop(empty_rows) df["result"] = df["result"].map(lambda x: x[0]) if kind == "label": df["result"] = df["result"].map( lambda x: "|".join(map(str, x)) if len(x) >= 1 else x ) df["result"] = df["result"].map(lambda x: "" if len(x) == 0 else x) return cls(df) def merge_sample(self, sample_df): self.merged_df = anno_sample_merge(sample_df, self.annotation_df) def export_merged(self, out_fn): self.merged_df.to_csv(out_fn) def export_annotations(self, out_fn): df = self.annotation_df if not Path(out_fn).exists(): Path(out_fn).touch() suffix = Path(out_fn).suffix if suffix == ".csv": _df_to_csv(df, out_fn) if suffix == ".json": _df_to_json(df, out_fn) if suffix == ".pkl": _df_to_pkl(df, out_fn) show_doc(nnAnnotations) show_doc(nnAnnotations.from_completions) annotations = nnAnnotations.from_completions( "../ph/ads/ad_annotations/", "classification" ) annotations annotations.labels annotations.label_counts show_doc(nnAnnotations.merge_sample) annotations.merge_sample(sample_df) annotations.merged_df.head(2) show_doc(nnAnnotations.export_merged) annotations.export_merged("testmerge.csv") show_doc(nnAnnotations.from_completions) # hide Path("testmerge.csv").unlink() annotations = nnAnnotations.from_completions( "../ph/ads/ad_annotations/", "classification" ) annotations.annotation_df.head(2) from nbdev.export import notebook2script notebook2script() ```
github_jupyter
``` #!/usr/bin/env python3 import math import cv2 as cv import numpy as np import tkinter as tk #import time #time.sleep(10) # Verificação da resolução da tela root = tk.Tk() screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() cap = cv.VideoCapture(0) while True: ret, frame = cap.read() # ajuste da imagem da câmera ao tamanho da tela - com a proporção mantida # opção 1: mantendo a altura final igual à altura da tela r = screen_height/frame.shape[1] # razão de conversão = (altura/largura) dim = (int(frame.shape[1]*r), screen_height) # a ALTURA final é fixa. resized = cv.resize(frame, dim, interpolation = cv.INTER_AREA) # aqui, é definida a imagem em seu novo tamanho. # opção 2: mantendo a largura final igual à largura da tela #r = screen_width/frame.shape[0] # razão de conversão = (altura/largura) #larg = 0.75 # proporção da largura que você quer usar #dim = (int(screen_width*larg), int(frame.shape[0]*r*larg)) # a LARGURA final é fixa. #resized = cv.resize(frame, dim, interpolation = cv.INTER_AREA) # aqui, é definida a imagem em seu novo tamanho. # Círculo canvas = np.zeros((resized.shape[0], resized.shape[1], 50), dtype = "uint8") (centerX, centerY) = (canvas.shape[1] // 2, canvas.shape[0] // 2) black = (0, 0, 0) espessura_da_borda = canvas.shape[1]*math.sqrt(2)/2 - resized.shape[1]/2 novo_raio = (canvas.shape[1] // 2) + espessura_da_borda/2 # novo raio = raio antigo + (espessura da borda)/2 cv.circle(resized, (centerX, centerY), math.ceil(novo_raio), black, math.ceil(espessura_da_borda)) # Zoom Digital #cropping = image[start y: end y, start x: end x] (sintaxe) zoom = 1 if zoom != 0: resized = resized[int((math.fabs(zoom-1))*resized.shape[1]/(2*zoom)):int((zoom+1)*resized.shape[1]/(2*zoom)), int((math.fabs(zoom-1))*resized.shape[0]/(2*zoom)):int((zoom+1)*resized.shape[0]/(2*zoom))] #cropping # observação: mapear os valores em mV da saída do potenciômetro de zoom pra eles começarem em 1. // (e pegar os valores positivos dele) # a imagem deve ser ajustada novamente ao tamanho da tela após o cropping: r = screen_height/resized.shape[1] # razão de conversão = (altura/largura) dim = (int(resized.shape[1]*r), screen_height) # a ALTURA final é fixa. resized = cv.resize(resized, dim, interpolation = cv.INTER_AREA) # aqui, é definida a imagem em seu novo tamanho. cv.imshow("Frame", resized) if cv.waitKey(1) & 0xFF == ord('q'): break ```
github_jupyter
``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] get_available_gpus() with np.load("notMNIST.npz") as data : Data, Target = data ["images"], data["labels"] posClass = 2 negClass = 9 dataIndx = (Target==posClass) + (Target==negClass) Data = Data[dataIndx]/255. Target = Target[dataIndx].reshape(-1, 1) Target[Target==posClass] = 1 Target[Target==negClass] = 0 np.random.seed(521) randIndx = np.arange(len(Data)) np.random.shuffle(randIndx) Data, Target = Data[randIndx], Target[randIndx] trainData, trainTarget = Data[:3500], Target[:3500] validData, validTarget = Data[3500:3600], Target[3500:3600] testData, testTarget = Data[3600:], Target[3600:] learning_rate = 0.005 n_epochs = 20000 batch_size = 500 n_dim = 28*28 def grab_batches(trainData, trainTarget, batch_size): batch_indices = np.random.permutation(range(3500)).reshape(-1, batch_size) X_batches = trainData.reshape(-1, n_dim)[batch_indices] y_batches = trainTarget[batch_indices] batches = zip(X_batches, y_batches) return batches X = tf.placeholder(tf.float32,[None,n_dim]) Y = tf.placeholder(tf.float32,[None,1]) W = tf.Variable(tf.ones([n_dim,1])) weight_decay = tf.placeholder(tf.float32) y_ = tf.matmul(X, W) loss = tf.reduce_mean(tf.squared_difference(y_, Y)) regularizer = tf.nn.l2_loss(W) loss = tf.reduce_mean(loss + weight_decay * regularizer) prediction = tf.cast(tf.round(tf.sigmoid(y_)), tf.int8) equality = tf.equal(prediction, tf.cast(Y, tf.int8)) accuracy = tf.reduce_mean(tf.cast(equality, tf.float32)) training_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) init = tf.global_variables_initializer() weight_decays = [0.0, 0.001, 0.1, 1] valid_accuracies = [] train_accuracies = [] test_accuracies = [] with tf.Session() as sess: for wd in weight_decays: sess.run(init) print("Weight Decay: {} \n".format(wd)) for epoch in range(1,n_epochs+1): batches = grab_batches(trainData, trainTarget, batch_size) for X_batch, y_batch in batches: sess.run(training_step, feed_dict={X: X_batch, Y: y_batch, weight_decay: wd}) if epoch % 500 == 0: feed_dict ={X: trainData.reshape(-1,n_dim), Y: trainTarget, weight_decay: wd} train_loss, train_accuracy = sess.run([loss, accuracy], feed_dict) print("Epoch: {}, Loss: {}, Accuracy: {}".format(epoch, train_loss, train_accuracy)) train_accuracies.append(train_accuracy) valid_accuracy = sess.run(accuracy, feed_dict = {X: validData.reshape(-1,n_dim), Y: validTarget}) valid_accuracies.append(valid_accuracy) test_accuracy = sess.run(accuracy, feed_dict = {X: testData.reshape(-1,n_dim), Y: testTarget}) test_accuracies.append(test_accuracy) valid_accuracies train_accuracies test_accuracies ``` ## Comparison SGD with Normal Equation ``` def normal_equation(): W = tf.matmul(tf.inverse(tf.matmul(tf.transpose(trainData), trainData)), tf.matmul(trainData, trainTarget)) return W def train(): with tf.Session() as sess: sess.run(init) for epoch in range(1,n_epochs+1): batches = grab_batches(trainData, trainTarget, batch_size) for X_batch, y_batch in batches: sess.run(training_step, feed_dict={X: X_batch, Y: y_batch, weight_decay: 0.0}) import timeit timeit.timeit('normal_equation(trainData, trainTarget)') timeit.timeit('train(trainData, trainTarget, n_epochs=2000)') ```
github_jupyter
# Scikits DAE solver In this notebook, we show some examples of solving a DAE model using the Scikits DAE solver, which interfaces with the [SUNDIALS](https://computation.llnl.gov/projects/sundials) library via the [scikits-odes](https://scikits-odes.readthedocs.io/en/latest/) Python interface ``` # Setup import pybamm import tests import numpy as np import os import matplotlib.pyplot as plt from pprint import pprint os.chdir(pybamm.__path__[0]+'/..') # Create solver dae_solver = pybamm.ScikitsDaeSolver() ``` ## Integrating DAEs In the simplest case, the `integrate` method of the DAE solver needs to be passed a function that returns residuals given `(t,y,ydot)`, initial conditions `y0`, and a time `t_eval` at which to return the solution: ``` def exponential_decay_dae(t, y, ydot): return [-y[0] - ydot[0], 2 * y[0] - y[1]] # Solve y0 = np.array([1, 2]) t_eval = np.linspace(0, 5, 20) solution = dae_solver.integrate(exponential_decay_dae, y0, t_eval) # Plot t_fine = np.linspace(0,t_eval[-1],1000) def plot(t_sol, y_sol): fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4)) ax1.plot(t_fine, np.exp(-t_fine), t_sol, y_sol[0], "o") ax1.set_xlabel("t") ax1.legend(["exp(-t)", "y_sol[0]"], loc="best") ax2.plot(t_fine, 2*np.exp(-t_fine), t_sol, y_sol[1], "o") ax2.set_xlabel("t") ax2.legend(["2*exp(-t)", "y_sol[1]"], loc="best") plt.tight_layout() plt.show() plot(solution.t, solution.y) ``` We can also provide the mass matrix and Jacobian (both must be provided together) ``` def jacobian(t, y): return np.array([[-1.0, 0.0], [2, -1]]) mass_matrix = np.array([[1, 0], [0, 0]]) solution = dae_solver.integrate(exponential_decay_dae, y0, t_eval, jacobian=jacobian, mass_matrix=mass_matrix) plot(solution.t, solution.y) ``` Finally, we can specify events at which the solver should terminate ``` def y1_equal_0pt2(t, y): return y[1] - 0.2 # Solve solution = dae_solver.integrate(exponential_decay_dae, y0, t_eval, events=[y1_equal_0pt2]) # Plot fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4)) ax1.plot(t_fine, np.exp(-t_fine), solution.t, solution.y[0], "o") ax1.set_xlabel("t") ax1.legend(["exp(-t)", "y_sol[0]"], loc="best") ax2.plot(t_fine, 2*np.exp(-t_fine), solution.t, solution.y[1], "o", t_fine, 0.2 * np.ones_like(t_fine), "k") ax2.set_xlabel("t") ax2.legend(["2*exp(-t)", "y_sol[1]", "y=0.2"], loc="best") plt.tight_layout() plt.show() ``` ## Finding consistent initial conditions The solver will fail if initial conditions that are inconsistent with the algebraic equations are provided. ``` y0_bad = np.array([1, 3]) print("algebraic residual at (0, y0_bad, [0]) is {}".format(exponential_decay_dae(0, y0_bad, [0])[1])) try: solution = dae_solver.integrate(exponential_decay_dae, y0_bad, t_eval) except pybamm.SolverError as e: print(e) ``` However, we can use `calculate_consistent_initial_conditions` to obtain consistent initial conditions, starting from a guess of bad initial conditions, using a simple root-finding algorithm. ``` def exponential_decay_dae_rhs(t, y): return np.array([exponential_decay_dae(t, y, [0])[0]]) def exponential_decay_dae_algebraic(t, y): return np.array([exponential_decay_dae(t, y, [0])[1]]) y0_fixed = dae_solver.calculate_consistent_initial_conditions( exponential_decay_dae_rhs, exponential_decay_dae_algebraic, y0_bad ) print("y0_fixed = {}\n".format(y0_fixed)) print("algebraic residual at (0, y0_fixed, [0]) is {}".format(exponential_decay_dae(0, y0_fixed, [0])[1])) solution = dae_solver.integrate(exponential_decay_dae, y0_fixed, t_eval) plot(solution.t, solution.y) ``` ## Solving a model The `solve` method is common to all DAE solvers. It takes a model, which contains all of the above information (residuals function, initial conditions and optionally jacobian, mass matrix, events), and a time to evaluate `t_eval`, and calls `integrate` to solve this model. ``` # Create model model = pybamm.BaseModel() u = pybamm.Variable("u") v = pybamm.Variable("v") model.rhs = {u: -v} # du/dt = -v model.algebraic = {v: 2 * u - v} # 2*v = u model.initial_conditions = {u: 1, v: 1} # bad initial conditions, solver fixes model.events['v=0.2'] = v - 0.2 model.variables = {"u": u, "v": v} # Discretise using default discretisation disc = pybamm.Discretisation() disc.process_model(model) # Solve ################################# t_eval = np.linspace(0, 2, 30) solution = dae_solver.solve(model, t_eval) ######################################### # Post-process, so that u and v can be called at any time t (using interpolation) t_sol, y_sol = solution.t, solution.y u = pybamm.ProcessedVariable(model.variables["u"], t_sol, y_sol) v = pybamm.ProcessedVariable(model.variables["v"], t_sol, y_sol) # Plot t_fine = np.linspace(0,t_eval[-1],1000) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4)) ax1.plot(t_fine, np.exp(-2 * t_fine), t_sol, u(t_sol), "o") ax1.set_xlabel("t") ax1.legend(["exp(-2*t)", "u"], loc="best") ax2.plot(t_fine, 2 * np.exp(-2 * t_fine), t_sol, v(t_sol), "o", t_fine, 0.2 * np.ones_like(t_fine), "k") ax2.set_xlabel("t") ax2.legend(["2*exp(-2*t)", "v", "v = 0.2"], loc="best") plt.tight_layout() plt.show() ``` Note that the discretisation or solver will have created the mass matrix and jacobian algorithmically, using the expression tree, so we do not need to calculate and input these manually.
github_jupyter
# This notebook plots metrics throughout training (Supplementary Fig. 3) ``` import os import numpy as np from six.moves import cPickle import matplotlib.pyplot as plt %matplotlib inline from tensorflow import keras import helper from tfomics import utils, explain, metrics num_trials = 10 model_names = ['cnn-deep', 'cnn-2', 'cnn-50'] activations = ['relu', 'exponential', 'sigmoid', 'tanh', 'softplus', 'linear', 'elu', 'shift_scale_relu', 'shift_scale_tanh', 'shift_scale_sigmoid', 'exp_relu'] # save path results_path = utils.make_directory('../../results', 'task1') # load dataset data_path = '../../data/synthetic_dataset.h5' data = helper.load_data(data_path) x_train, y_train, x_valid, y_valid, x_test, y_test = data # pickle results file_path = os.path.join(results_path, "task1_history.pickle") with open(file_path, 'rb') as f: results = cPickle.load(f) num_rows = 5 index = 0 ylabel = 'Training loss' yticks = [0.1, 0.2, 0.3, 0.4, 0.5] ylim = [0.1,.5] fig = plt.figure(figsize=(9,10)) activation = 'relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,1); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.title('CNN-deep', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) plt.xlim([0,100]) ax.set_xticklabels([]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,2) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-2', fontsize=12) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,3); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-50', fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Relu', fontsize=12) activation = 'exponential' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,4); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,5) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,6); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Exponential', fontsize=12) activation = 'shift_scale_relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,7); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,8) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,9); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Sigmoid', fontsize=12) activation = 'shift_scale_sigmoid' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,10); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,11) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,12); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Relu', fontsize=12) activation = 'shift_scale_tanh' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,13); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.xlabel('Epoch', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,14) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,15); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Tanh', fontsize=12); outfile = os.path.join(results_path, 'training_loss.pdf') fig.savefig(outfile, format='pdf', dpi=200, bbox_inches='tight') num_rows = 5 index = 3 ylabel = 'Validation loss' yticks = [0.1, 0.2, 0.3, 0.4, 0.5] ylim = [0.1,.5] fig = plt.figure(figsize=(9,10)) activation = 'relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,1); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.title('CNN-deep', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,2) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-2', fontsize=12) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,3); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-50', fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Relu', fontsize=12) activation = 'exponential' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,4); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,5) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,6); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Exponential', fontsize=12) activation = 'shift_scale_relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,7); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,8) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,9); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Sigmoid', fontsize=12) activation = 'shift_scale_sigmoid' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,10); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,11) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,12); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Relu', fontsize=12) activation = 'shift_scale_tanh' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,13); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.xlabel('Epoch', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,14) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,15); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Tanh', fontsize=12); outfile = os.path.join(results_path, 'validation_loss.pdf') fig.savefig(outfile, format='pdf', dpi=200, bbox_inches='tight') num_rows = 5 index = 5 ylabel = 'AUPR' yticks = [0.2, 0.4, 0.6, 0.8, 1.0] ylim = [0.1,1] fig = plt.figure(figsize=(9,10)) activation = 'relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,1); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.title('CNN-deep', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,2) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-2', fontsize=12) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,3); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.title('CNN-50', fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Relu', fontsize=12) activation = 'exponential' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,4); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,5) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,6); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Exponential', fontsize=12) activation = 'shift_scale_relu' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,7); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,8) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,9); for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Sigmoid', fontsize=12) activation = 'shift_scale_sigmoid' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,10); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) ax.set_xticklabels([]) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,11) for i in range(10): ax.plot(np.array(history[i])[index,:]); ax.set_xticklabels([]) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,12); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax.set_xticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Relu', fontsize=12) activation = 'shift_scale_tanh' history = results['cnn-deep'][activation] ax = plt.subplot(num_rows,3,13); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.ylabel(ylabel, fontsize=12) plt.xlabel('Epoch', fontsize=12) plt.yticks(yticks, fontsize=12) plt.ylim(ylim) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) history = results['cnn-2'][activation] ax = plt.subplot(num_rows,3,14) for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) history = results['cnn-50'][activation] ax = plt.subplot(num_rows,3,15); for i in range(10): ax.plot(np.array(history[i])[index,:]); plt.xlabel('Epoch', fontsize=12) plt.xticks([0, 25, 50, 75, 100], fontsize=12) plt.xlim([0,100]) plt.ylim(ylim) ax.set_yticklabels([]) ax2 = ax.twinx() ax2.set_yticks([]) ax2.set_ylabel('Modified-Tanh', fontsize=12); outfile = os.path.join(results_path, 'aupr.pdf') fig.savefig(outfile, format='pdf', dpi=200, bbox_inches='tight') ```
github_jupyter
#Three texts has been saved in a folder named "Novels": ``` ls directory = "Novels" ``` #Processing text files in Novels: ``` import glob, re, os, collections docs = {} for file in glob.glob(directory + "/*.txt"): with open(file, encoding="ISO-8859-1") as f: text = f.read(); tokens = re.findall(r'\b\w[\w-]*\b', text.lower()) count = len(tokens) relativefreqs = {} localfreqs = collections.Counter(tokens) for word, wordcount in localfreqs.items(): if word.isalpha(): relativefreqs[word] = wordcount/count docs[os.path.basename(file)] = relativefreqs print("Files processed: " + str(len(docs))) ``` #Data frame: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(docs) df.head(20) df.describe() ``` #summed relative frequency: ``` df['Sum'] = df.sum(axis=1) df.sort_values("Sum", ascending=False, inplace=True) df[:20] len(df) ``` # Saving the table of frequencies into a CSV file: ``` FileName = "FrequenciesResultsShort.csv" df.to_csv(FileName) ls *.csv import sys print(sys.version) import sys; print('{0[0]}.{0[1]}'.format(sys.version_info)) %%bash head fileIwanttosee.txt import pip import sys,os,os.path sys.path.append(os.path.expanduser('~/code/eol_hsrl_python')) os.environ['HSRL_INSTRUMENT']='gvhsrl' os.environ['HSRL_CONFIG']=os.path.expanduser('~/hsrl_config') # I installed MSYS head -n3 FrequenciesResultsShort !head %head %alias head powershell -command "& {Get-Content %s -Head 3}" %head FrequenciesResultsShort.csv # it seems that windows doesnt operate Unix commands! # I really have no idea why it doesnt recognize"!head"? # I tried to define Python path into the list of Environment Variables, still didnt work # It has something related to the System Path, but couldnt sove it. ``` #Fliping the data frame: ``` df2 = df.transpose() df2.head(20) df3 = df2.drop(['Sum']) df3.head(18) ``` #Saving the fliped data frame into a csv file: ``` FileName = "FrequenciesResultsShortFlip.csv" df3.to_csv(FileName, na_rep=0) ``` #Texts without sum row: ``` df3 = df2.drop(['Sum']) df3.head(18) import numpy as np import matplotlib.pyplot as plt %matplotlib inline word2Plot = "society" plt.figure(figsize=(3, 3)) df3[[word2Plot]].plot() plt.title('Histogram of ' + word2Plot) plt.show() import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline ls Frequencies*.csv ``` #How to read a csv file: ``` df = pd.read_csv('FrequenciesResultsShortFlip.csv' , encoding="utf-8") df.rename(columns={'Unnamed: 0': 'Text'}, inplace=True) df.head(10) #I needed to change 'utf-8' codec to "latin1": df = pd.read_csv('FrequenciesResultsShortFlip.csv' , encoding="latin1") df.rename(columns={'Unnamed: 0': 'Text'}, inplace=True) df.head(10) # same thing is happening here for the "head"! # "df" is not changed, so from now on these codes seem to be useless! df.info() df.describe() print(list(df.columns.values)) len(list(df.columns.values)) df[['system','question','process']].plot() plt.title('Histogram') #KeyError: "['society' 'mass' 'festival'] not in index" which makes sense due to the prior error indexed_df = df.set_index(['Text']) my_plot = indexed_df[['society','question','process']].plot(kind='bar') howManyComps = 4 listOfWords = ['intelligence','possible','support','information','declassify','customer','consent'] from sklearn.decomposition import PCA df2 = df.ix[1:,listOfWords] pca = PCA(n_components=howManyComps) pca.fit(df2) X = pca.transform(df2) print("Done") print(pca.explained_variance_ratio_) type(pca.explained_variance_ratio_) ```
github_jupyter
# Robustness evaluation: non-yearly data ### Rodrigo Leo --- **Frequency (this fitting)**: monthly. ## Data preparation ``` # Import requiered libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import shapiro, kstest, anderson # Prefix for saved plots: px = 'freq_m' # 'pub_quality' is a flag variable: # - If true, automatically exports all plots to PDF at 200 dpi. # - If false, all plots are displayed inline at 70 dpi. pub_quality = False if pub_quality: plt.rcParams['figure.dpi']= 200 else: plt.rcParams['figure.dpi']= 70 # Preferred style for the plotting engine plt.style.use('seaborn-talk') # Set a random seed np.random.seed(0) # Load data data = pd.read_csv(f'databases/aggregated_m.csv') data.head() data['year'] = data['Unnamed: 0'] data['sp500'] = (data['sp500_price'] - data['sp500_price'].shift(1)) / data['sp500_price'].shift(1) data['tbill'] = data['tbill'] / 100 # Name of the risky asset return column: r_name = 'sp500' # Name of the riskfree asset return column: rf_name = 'tbill' # Calculate inflation rate data['inflation'] = (data['price'] - data['price'].shift(1)) / data['price'].shift(1) # Calculate real returns on both assets data['r'] = (1 + data[r_name]) / (1 + data['inflation']) data['rf'] = (1 + data[rf_name])**(1/12) / (1 + data['inflation']) # The risk premium is the difference beetween the return of the risky asset and the riskfree one data['risk_premium'] = data['r'] - data['rf'] # Get data limits x1 = min(data['year']) x2 = max(data['year']) data.head() # Investmment period length (in years) t_list = [1, 3, 5, 10] # We will store the modified data in a dictionary called tdata tdata = {t: None for t in t_list} for t in t_list: years = list(data['year']) periods = [] consumption = [] r_returns = [] rf_returns = [] # Loop through the original data to form periods of length t for i in range(0, len(years) - t, t): # 'year_1' and 'year_2' are the starting and ending points of the period year_1 = years[i] year_2 = years[i + t - 1] periods.append((year_1, year_2)) # 'sample' is the data from the current period sample = data.query('year >= ' + str(year_1) + ' & year <= ' + str(year_2)) # Aggregate the consumption and return data consumption.append(sample['rpc_consumption'].sum()) r_returns.append(sample['r'].product()) rf_returns.append(sample['rf'].product()) # Finally store the aggregated data in a tempral dataframe callen data_period data_period = pd.DataFrame({ 'year': [period[1] for period in periods], 'consumption': consumption, 'r': r_returns, 'rf': rf_returns }) # Gross growth rate of per capita consumption and its logarithm data_period['delta_consumption_gross'] = data_period['consumption'] / data_period['consumption'].shift(1) data_period['log_delta_consumption_gross'] = np.log(data_period['delta_consumption_gross']) # Net growth rate of per capita consumption data_period['delta_consumption_net'] = data_period['delta_consumption_gross'] - 1 # Long term (gross) risky return data_period['r2'] = data_period['r'] * data_period['r'].shift(1) # Set 'year' as index data_period = data_period.set_index('year') # And save tdata[t] = data_period # Check if it worked tdata[10].head() # Get the sample size for every t: print('t\t', 'sample size') for t in t_list: print(str(t) + '\t', len(tdata[t])) ``` ## Exploratory data analysis ``` # Set the index of the original data data = data.set_index('year') # Statistical summary of the returns over the whole series data[['r', 'rf']].apply(lambda x: (x-1)*100).describe() # Plot of real consumption per capita and inflation rate fig = plt.figure() plt.subplot(2, 1, 1) plt.plot(data['rpc_consumption']) axes = plt.gca() axes.set_xlim([x1, x2]) plt.ylabel('Consumo per cápita (USD)') plt.subplot(2, 1, 2) plt.bar(data.index, data['inflation']*100) plt.axhline(0, color='black', linestyle='-') axes = plt.gca() axes.set_xlim([x1, x2]) plt.ylabel('Inflación media anual (%)') plt.xlabel('Año') axes = plt.gca() fig.align_ylabels() if pub_quality: fig.savefig(f'figures/{px}_fig_consumo_inflacion.pdf', bbox_inches='tight') # The normality test results will be stored in a dictionary called 'normality_tests' normality_tests = {t: None for t in t_list} quants = {t: None for t in t_list} quantiles = np.linspace(0,1,100) for t in t_list: # Mean and standard deviation for the reference sample m = tdata[t]['log_delta_consumption_gross'].mean() s = tdata[t]['log_delta_consumption_gross'].std() # Test (data) sample test_sample = tdata[t]['log_delta_consumption_gross'].copy().dropna() normal_sample = pd.Series(np.random.normal(m, s, 1000)) test_quantiles = test_sample.quantile(quantiles) normal_quantiles = normal_sample.quantile(quantiles) # Run some built-in normality tests normality_tests[t] = shapiro(test_sample), kstest(test_sample, 'norm', args=(m ,s)), anderson(test_sample, dist='norm') # Plot limits lim_inf = m - 2.5 * s lim_sup = m + 2.5 * s # Straight line straight = np.linspace(lim_inf, lim_sup, 10) quants[t] = { 'test_quantiles': test_quantiles, 'normal_quantiles': normal_quantiles, 'straight': straight, 'lim_inf': lim_inf, 'lim_sup': lim_sup } t2axes = { 1: [0, 0], 3: [0, 1], 5: [1, 0], 10: [1, 1] } # QQ plots fig, axes = plt.subplots(nrows=2, ncols=2) fig.add_subplot(111, frame_on=False) for t in t_list: axes[t2axes[t][0], t2axes[t][1]].plot(quants[t]['straight'], quants[t]['straight'], color='orange') axes[t2axes[t][0], t2axes[t][1]].scatter(quants[t]['normal_quantiles'], quants[t]['test_quantiles'], s=40) axes[t2axes[t][0], t2axes[t][1]].set_xlim([quants[t]['lim_inf'], quants[t]['lim_sup']]) axes[t2axes[t][0], t2axes[t][1]].set_title('$T$ = ' + str(t)) axes[t2axes[t][0], t2axes[t][1]].set_aspect(0.7) plt.tick_params(labelcolor="none", bottom=False, left=False) plt.xlabel('Cuantiles teóricos (distribución normal)') plt.ylabel('Cuantiles observados') fig.tight_layout() if pub_quality: fig.savefig(f'figures/{px}_fig_qqplots.pdf', bbox_inches='tight') normality_results = pd.DataFrame({ 'T': t_list, 'Shapiro-Wilks': [round(normality_tests[t][0].pvalue, 4) for t in t_list], 'Kolmogorov-Smirnov': [round(normality_tests[t][1].pvalue, 4) for t in t_list] }) normality_results = normality_results.set_index('T') normality_results # Asset returns plot fig = plt.figure() plt.plot((data['r']-1)*100) plt.plot((data['rf']-1)*100, linestyle='dashed') plt.axhline(0, color='black', linestyle='-') plt.legend(labels = ['Activo riesgoso', 'Activo libre de riesgo']) plt.xlabel('Año') plt.ylabel('Retorno neto anual real (%)') axes = plt.gca() axes.set_xlim([x1, x2]) if pub_quality: fig.savefig(f'figures/{px}_fig_retornos.pdf', bbox_inches='tight') # Risk premium plot fig = plt.figure() plt.bar(data.query('risk_premium > 0').index, data.query('risk_premium > 0')['risk_premium']*100) plt.bar(data.query('risk_premium < 0').index, data.query('risk_premium < 0')['risk_premium']*100) plt.axhline(0, color='black', linestyle='-', linewidth=1.5) plt.xlabel('Año') plt.ylabel('Premio al riesgo anual real (%)') axes = plt.gca() axes.set_xlim([x1, x2]) if pub_quality: fig.savefig(f'figures/{px}_fig_premio_al_riesgo.pdf', bbox_inches='tight') # Plot of real returns and risk premium fig = plt.figure() plt.subplot(2, 1, 1) plt.plot((data['r']-1)*100) plt.plot((data['rf']-1)*100, linestyle='dashed') plt.axhline(0, color='black', linestyle='-') axes = plt.gca() axes.set_xlim([x1, x2]) plt.ylabel('Retorno anual (%)') plt.legend(labels = ['Activo riesgoso', 'Activo libre de riesgo']) plt.subplot(2, 1, 2) plt.bar(data.query('risk_premium > 0').index, data.query('risk_premium > 0')['risk_premium']*100) plt.bar(data.query('risk_premium < 0').index, data.query('risk_premium < 0')['risk_premium']*100) plt.axhline(0, color='black', linestyle='-', linewidth=1.5) axes = plt.gca() axes.set_xlim([x1, x2]) plt.ylabel('Premio al riesgo anual (%)') plt.xlabel('Año') axes = plt.gca() fig.align_ylabels() if pub_quality: fig.savefig(f'figures/{px}_fig_retornos_premio.pdf', bbox_inches='tight') ``` ## Model fitting ``` # Subjective discount factors (beta) betas = [0.1, 0.5, 0.90, 0.95, 1.0] # Maximum value of the relative risk aversion coefficient (gamma) gamma_max = 150 # Subjective probabilities of not experiencing a consumption shock (pi_2) pis = [0.2, 0.4, 0.6, 0.8, 1.0] # Generate the sample space for gamma points = 1000 gammas = np.linspace(0, gamma_max, points) # The fitting results will be stored in a dictionary called 'treport' treport = {t: None for t in t_list} for t in t_list: # Mean returns r = tdata[t]['r'].mean() rf = tdata[t]['rf'].mean() # Standard deviations sr = tdata[t]['r'].std() sr2 = tdata[t]['r2'].std() # Mean and standard deviation of the rate of growth of consumption mc = tdata[t]['delta_consumption_gross'].mean() - 1 sc = tdata[t]['delta_consumption_gross'].std() # The estimation of the return of the risky asset is stored in the dictioonary 'report' # Each key corresponds to a value of the beta parameter report = {beta: None for beta in betas} # Estimation of the return of the risky asset for beta in betas: # For each value of beta, the estimation is stored in a temporary dataframe called 'results' results = pd.DataFrame({'gamma': gammas}) # Loop over the values of the pi parameter for pi in pis: # For each value of pi, the estimation is stored in 'result' result = [] for gamma in gammas: # Calculate the first and second central moments of the delta discount factor md1 = beta * np.exp(- gamma * mc + gamma ** 2 * sc ** 2 / 2) md2 = beta ** 2 * np.exp(- 2 * gamma * mc + gamma ** 2 * sc ** 2) sd1 = np.sqrt(beta ** 2 * np.exp(- 2 * gamma * mc + gamma ** 2 * sc ** 2) * (np.exp(gamma ** 2 * sc ** 2) - 1)) sd2 = np.sqrt(beta ** 4 * np.exp(- 4 * gamma * mc + 2 * gamma ** 2 * sc ** 2) * (np.exp(2 * gamma ** 2 * sc ** 2) - 1)) # Auxiliary factor c c = (pi - 1) * sd1 * sr - pi ** 2 * sd2 * sr2 - md1 * rf - pi * md2 * rf ** 2 # Estimator r_estimation = (- md1 + np.sqrt(md1 ** 2 - 4 * pi * md2 * c)) / (2 * pi * md2) # The estimator is annualized for an easier interpretation r_estimation = r_estimation ** (1 / t) # Store result.append((r_estimation - 1) * 100) # Store results[str(pi)] = result # Store report[beta] = results # Store treport[t] = report # Take a look treport[1][0.95].head() # Line markers for each probability (this is just styling stuff) markers = { 0.2: '$A$', 0.4: '$B$', 0.6: '$C$', 0.8: '$D$', 1.0: '$E$' } # Override markers markers = {pi: None for pi in pis} # Labels for each probability labels = ['$\pi_2 = $' + str(pi) for pi in pis] # Plotting function def graph(T, beta): fig = plt.figure() for pi in pis: plt.plot(gammas, treport[t][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(700,2000), markerfacecolor='black') plt.axhline((data['r'].mean() ** 12 - 1) * 100, color='black', linestyle='dashed') plt.axhline((data['rf'].mean() - 1) * 100, color='black', linestyle='dotted') plt.xlabel('Coeficiente de aversión relativa al riesgo') plt.ylabel('Retorno neto anualizado (%)') plt.legend(labels = labels + ['Activo riesgoso (media)', 'Activo sin riesgo (media)'], bbox_to_anchor=(0.5, -0.37), loc='lower center', ncol=3) plt.grid(linestyle="-", linewidth=0.5) axes = plt.gca() axes.set_xlim([0, 140]) axes.set_ylim([-1, 9]) plt.title('$T$ = ' + str(t)) plt.axvspan(0, 10, alpha=0.1, color='black') if pub_quality: fig.savefig(f'figures/{px}_fig_resultados_beta_' + str(int(100 * beta)) + '_t_' + str(t) + '.pdf', bbox_inches='tight') # Plot the results for the given value of beta beta = 0.95 for t in t_list: graph(t, beta) # A more compact plot plt.gcf().clear() fig, axes = plt.subplots(nrows=2, ncols=2) fig.add_subplot(111, frame_on=False) beta = 0.95 for pi in pis: axes[0, 0].plot(gammas, treport[1][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[0, 1].plot(gammas, treport[3][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 1].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 0].plot(gammas, treport[5][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 1].plot(gammas, treport[10][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 1].axvspan(0, 10, alpha=0.04, color='gray') for i in range(0, 2): for j in range(0, 2): axes[i, j].axhline((data['r'].mean() ** 12 - 1) * 100, color='black', linestyle='dashed') axes[i, j].axhline((data['rf'].mean() - 1) * 100, color='black', linestyle='dotted') axes[0, 0].set_title('$T$ = 1') axes[0, 1].set_title('$T$ = 3') axes[1, 0].set_title('$T$ = 5') axes[1, 1].set_title('$T$ = 10') plt.setp(axes, xlim=(0, 30), ylim=(-1, 9)) plt.tick_params(labelcolor="none", bottom=False, left=False) plt.xlabel('Coeficiente de aversión relativa al riesgo') plt.ylabel('Retorno neto anualizado (%)') fig.legend(labels = labels + ['Activo riesgoso (media)', 'Activo sin riesgo (media)'], bbox_to_anchor=(0.55, -0.01), loc='lower center', ncol=3) fig.tight_layout() fig.subplots_adjust(bottom=0.25) if pub_quality: fig.savefig(f'figures/{px}_fig_resultados_comparativo_beta_' + str(int(100 * beta)) + '.pdf', bbox_inches='tight') str(int(100 * beta))# A more compact plot fig, axes = plt.subplots(nrows=2, ncols=2) fig.add_subplot(111, frame_on=False) beta = 0.5 for pi in pis: axes[0, 0].plot(gammas, treport[1][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[0, 1].plot(gammas, treport[3][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 1].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 0].plot(gammas, treport[5][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 1].plot(gammas, treport[10][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 1].axvspan(0, 10, alpha=0.04, color='gray') for i in range(0, 2): for j in range(0, 2): axes[i, j].axhline((data['r'].mean() ** 12 - 1) * 100, color='black', linestyle='dashed') axes[i, j].axhline((data['rf'].mean() - 1) * 100, color='black', linestyle='dotted') #axes[i, j].grid(linestyle="-", linewidth=0.5) axes[0, 0].set_title('$T$ = 1') axes[0, 1].set_title('$T$ = 3') axes[1, 0].set_title('$T$ = 5') axes[1, 1].set_title('$T$ = 10') plt.setp(axes, xlim=(0,60), ylim=(-1, 9)) plt.tick_params(labelcolor="none", bottom=False, left=False) plt.xlabel('Coeficiente de aversión relativa al riesgo') plt.ylabel('Retorno neto anualizado (%)') fig.legend(labels = labels + ['Activo riesgoso (media)', 'Activo sin riesgo (media)'], bbox_to_anchor=(0.55, -0.01), loc='lower center', ncol=3) fig.tight_layout() fig.subplots_adjust(bottom=0.25) if pub_quality: fig.savefig(f'figures/{px}_fig_resultados_comparativo_beta_' + str(int(100 * beta)) + '.pdf', bbox_inches='tight') # A more compact plot fig, axes = plt.subplots(nrows=2, ncols=2) fig.add_subplot(111, frame_on=False) beta = 0.1 for pi in pis: axes[0, 0].plot(gammas, treport[1][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[0, 1].plot(gammas, treport[3][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[0, 1].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 0].plot(gammas, treport[5][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 0].axvspan(0, 10, alpha=0.04, color='gray') for pi in pis: axes[1, 1].plot(gammas, treport[10][beta][str(pi)], marker=markers[pi], markersize=9, markevery=(110,2000), markerfacecolor='black') axes[1, 1].axvspan(0, 10, alpha=0.04, color='gray') for i in range(0, 2): for j in range(0, 2): axes[i, j].axhline((tdata[t]['r'].mean() ** 12 - 1) * 100, color='black', linestyle='dashed') axes[i, j].axhline((tdata[t]['rf'].mean() - 1) * 100, color='black', linestyle='dotted') #axes[i, j].grid(linestyle="-", linewidth=0.5) axes[0, 0].set_title('$T$ = 1') axes[0, 1].set_title('$T$ = 3') axes[1, 0].set_title('$T$ = 5') axes[1, 1].set_title('$T$ = 10') plt.setp(axes, xlim=(0,60), ylim=(-1, 9)) plt.tick_params(labelcolor="none", bottom=False, left=False) plt.xlabel('Coeficiente de aversión relativa al riesgo') plt.ylabel('Retorno neto anualizado (%)') fig.legend(labels = labels + ['Activo riesgoso (media)', 'Activo sin riesgo (media)'], bbox_to_anchor=(0.55, -0.01), loc='lower center', ncol=3) fig.tight_layout() fig.subplots_adjust(bottom=0.25) if pub_quality: fig.savefig(f'figures/{px}_fig_resultados_comparativo_beta_' + str(int(100 * beta)) + '.pdf', bbox_inches='tight') ```
github_jupyter
### **Icesat-2 data read out.** ``` import os os.chdir('..') import h5py import cartopy.crs as ccrs from notebooks import config from utils.imgShow import imgShow import matplotlib.pyplot as plt from utils.geotif_io import readTiff from utils.transform_xy import coor2coor import numpy as np ### read in and write out ## atl03 # !h5ls data/icesat2/download_atl03/processed_ATL03_20200101005343_00810606_004_01.h5 # !python utils/readout03.py data/icesat2/download_atl03/data_202012/*ATL03*.h5 -o data/icesat2/processed_atl03/data_202012 -n 4 ## atl06 # !h5ls data/icesat2/download_atl06/processed_ATL06_20200105004522_01420606_004_01.h5 # !python utils/readout06.py data/icesat2/download_atl06/data_202001/*ATL06*.h5 -o data/icesat2/processed_atl06/data_202001 -n 4 #### atl03 ## ascending # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot1_A*.h5 -o data/icesat2/processed_atl03/atl03_spot1_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot2_A*.h5 -o data/icesat2/processed_atl03/atl03_spot2_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot3_A*.h5 -o data/icesat2/processed_atl03/atl03_spot3_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot4_A*.h5 -o data/icesat2/processed_atl03/atl03_spot4_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot5_A*.h5 -o data/icesat2/processed_atl03/atl03_spot5_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot6_A*.h5 -o data/icesat2/processed_atl03/atl03_spot6_A.h5 # ### descending # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot1_D*.h5 -o data/icesat2/processed_atl03/atl03_spot1_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot2_D*.h5 -o data/icesat2/processed_atl03/atl03_spot2_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot3_D*.h5 -o data/icesat2/processed_atl03/atl03_spot3_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot4_D*.h5 -o data/icesat2/processed_atl03/atl03_spot4_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot5_D*.h5 -o data/icesat2/processed_atl03/atl03_spot5_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl03/*ATL03*_spot6_D*.h5 -o data/icesat2/processed_atl03/atl03_spot6_D.h5 #### atl06 ## merge data into specific spot ## ascending # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot1_A*.h5 -o data/icesat2/processed_atl06/atl06_spot1_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot2_A*.h5 -o data/icesat2/processed_atl06/atl06_spot2_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot3_A*.h5 -o data/icesat2/processed_atl06/atl06_spot3_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot4_A*.h5 -o data/icesat2/processed_atl06/atl06_spot4_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot5_A*.h5 -o data/icesat2/processed_atl06/atl06_spot5_A.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot6_A*.h5 -o data/icesat2/processed_atl06/atl06_spot6_A.h5 # ### descending # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot1_D*.h5 -o data/icesat2/processed_atl06/atl06_spot1_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot2_D*.h5 -o data/icesat2/processed_atl06/atl06_spot2_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot3_D*.h5 -o data/icesat2/processed_atl06/atl06_spot3_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot4_D*.h5 -o data/icesat2/processed_atl06/atl06_spot4_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot5_D*.h5 -o data/icesat2/processed_atl06/atl06_spot5_D.h5 # !python utils/merge_files.py data/icesat2/processed_atl06/*ATL06*_spot6_D*.h5 -o data/icesat2/processed_atl06/atl06_spot6_D.h5 ## merge all ascending/descending data # ## Ascending # !python utils/merge_files.py data/icesat2/processed_atl06/atl06_spot?_A.h5 -o data/icesat2/processed_atl06/atl06_A.h5 # ## Descending # !python utils/merge_files.py data/icesat2/processed_atl06/atl06_spot?_D.h5 -o data/icesat2/processed_atl06/atl06_D.h5 ## merge all data into one ## atl03 # !python utils/merge_files.py data/icesat2/processed_atl03/data_202012/*ATL03*_spot*.h5 -o data/icesat2/processed_atl03/data_202012/atl03_202012.h5 ## atl06 # !python utils/merge_files.py data/icesat2/processed_atl06/atl06_2020*.h5 -o data/icesat2/processed_atl06/atl06_2020.h5 ``` ### data subseting ``` # !python utils/subset_file.py data/icesat2/processed_atl03/atl03_2020??.h5 -m data/rgi/rgi60_1305_StudyArea/mask_based_dem.tif ```
github_jupyter
# Artificial Intelligence Nanodegree ## Voice User Interfaces ## Project: Speech Recognition with Neural Networks --- In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully! > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. >**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode. The rubric contains _optional_ "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook. --- ## Introduction In this notebook, you will build a deep neural network that functions as part of an end-to-end automatic speech recognition (ASR) pipeline! Your completed pipeline will accept raw audio as input and return a predicted transcription of the spoken language. The full pipeline is summarized in the figure below. <img src="images/pipeline.png"> - **STEP 1** is a pre-processing step that converts raw audio to one of two feature representations that are commonly used for ASR. - **STEP 2** is an acoustic model which accepts audio features as input and returns a probability distribution over all potential transcriptions. After learning about the basic types of neural networks that are often used for acoustic modeling, you will engage in your own investigations, to design your own acoustic model! - **STEP 3** in the pipeline takes the output from the acoustic model and returns a predicted transcription. Feel free to use the links below to navigate the notebook: - [The Data](#thedata) - [**STEP 1**](#step1): Acoustic Features for Speech Recognition - [**STEP 2**](#step2): Deep Neural Networks for Acoustic Modeling - [Model 0](#model0): RNN - [Model 1](#model1): RNN + TimeDistributed Dense - [Model 2](#model2): CNN + RNN + TimeDistributed Dense - [Model 3](#model3): Deeper RNN + TimeDistributed Dense - [Model 4](#model4): Bidirectional RNN + TimeDistributed Dense - [Models 5+](#model5) - [Compare the Models](#compare) - [Final Model](#final) - [**STEP 3**](#step3): Obtain Predictions <a id='thedata'></a> ## The Data We begin by investigating the dataset that will be used to train and evaluate your pipeline. [LibriSpeech](http://www.danielpovey.com/files/2015_icassp_librispeech.pdf) is a large corpus of English-read speech, designed for training and evaluating models for ASR. The dataset contains 1000 hours of speech derived from audiobooks. We will work with a small subset in this project, since larger-scale data would take a long while to train. However, after completing this project, if you are interested in exploring further, you are encouraged to work with more of the data that is provided [online](http://www.openslr.org/12/). In the code cells below, you will use the `vis_train_features` module to visualize a training example. The supplied argument `index=0` tells the module to extract the first example in the training set. (You are welcome to change `index=0` to point to a different training example, if you like, but please **DO NOT** amend any other code in the cell.) The returned variables are: - `vis_text` - transcribed text (label) for the training example. - `vis_raw_audio` - raw audio waveform for the training example. - `vis_mfcc_feature` - mel-frequency cepstral coefficients (MFCCs) for the training example. - `vis_spectrogram_feature` - spectrogram for the training example. - `vis_audio_path` - the file path to the training example. ``` from data_generator import vis_train_features # extract label and audio features for a single training example vis_text, vis_raw_audio, vis_mfcc_feature, vis_spectrogram_feature, vis_audio_path = vis_train_features() ``` The following code cell visualizes the audio waveform for your chosen example, along with the corresponding transcript. You also have the option to play the audio in the notebook! ``` from IPython.display import Markdown, display from data_generator import vis_train_features, plot_raw_audio from IPython.display import Audio %matplotlib inline # plot audio signal plot_raw_audio(vis_raw_audio) # print length of audio signal display(Markdown('**Shape of Audio Signal** : ' + str(vis_raw_audio.shape))) # print transcript corresponding to audio clip display(Markdown('**Transcript** : ' + str(vis_text))) # play the audio file Audio(vis_audio_path) ``` <a id='step1'></a> ## STEP 1: Acoustic Features for Speech Recognition For this project, you won't use the raw audio waveform as input to your model. Instead, we provide code that first performs a pre-processing step to convert the raw audio to a feature representation that has historically proven successful for ASR models. Your acoustic model will accept the feature representation as input. In this project, you will explore two possible feature representations. _After completing the project_, if you'd like to read more about deep learning architectures that can accept raw audio input, you are encouraged to explore this [research paper](https://pdfs.semanticscholar.org/a566/cd4a8623d661a4931814d9dffc72ecbf63c4.pdf). ### Spectrograms The first option for an audio feature representation is the [spectrogram](https://www.youtube.com/watch?v=_FatxGN3vAM). In order to complete this project, you will **not** need to dig deeply into the details of how a spectrogram is calculated; but, if you are curious, the code for calculating the spectrogram was borrowed from [this repository](https://github.com/baidu-research/ba-dls-deepspeech). The implementation appears in the `utils.py` file in your repository. The code that we give you returns the spectrogram as a 2D tensor, where the first (_vertical_) dimension indexes time, and the second (_horizontal_) dimension indexes frequency. To speed the convergence of your algorithm, we have also normalized the spectrogram. (You can see this quickly in the visualization below by noting that the mean value hovers around zero, and most entries in the tensor assume values close to zero.) ``` from data_generator import plot_spectrogram_feature # plot normalized spectrogram plot_spectrogram_feature(vis_spectrogram_feature) # print shape of spectrogram display(Markdown('**Shape of Spectrogram** : ' + str(vis_spectrogram_feature.shape))) ``` ### Mel-Frequency Cepstral Coefficients (MFCCs) The second option for an audio feature representation is [MFCCs](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum). You do **not** need to dig deeply into the details of how MFCCs are calculated, but if you would like more information, you are welcome to peruse the [documentation](https://github.com/jameslyons/python_speech_features) of the `python_speech_features` Python package. Just as with the spectrogram features, the MFCCs are normalized in the supplied code. The main idea behind MFCC features is the same as spectrogram features: at each time window, the MFCC feature yields a feature vector that characterizes the sound within the window. Note that the MFCC feature is much lower-dimensional than the spectrogram feature, which could help an acoustic model to avoid overfitting to the training dataset. ``` from data_generator import plot_mfcc_feature # plot normalized MFCC plot_mfcc_feature(vis_mfcc_feature) # print shape of MFCC display(Markdown('**Shape of MFCC** : ' + str(vis_mfcc_feature.shape))) ``` When you construct your pipeline, you will be able to choose to use either spectrogram or MFCC features. If you would like to see different implementations that make use of MFCCs and/or spectrograms, please check out the links below: - This [repository](https://github.com/baidu-research/ba-dls-deepspeech) uses spectrograms. - This [repository](https://github.com/mozilla/DeepSpeech) uses MFCCs. - This [repository](https://github.com/buriburisuri/speech-to-text-wavenet) also uses MFCCs. - This [repository](https://github.com/pannous/tensorflow-speech-recognition/blob/master/speech_data.py) experiments with raw audio, spectrograms, and MFCCs as features. <a id='step2'></a> ## STEP 2: Deep Neural Networks for Acoustic Modeling In this section, you will experiment with various neural network architectures for acoustic modeling. You will begin by training five relatively simple architectures. **Model 0** is provided for you. You will write code to implement **Models 1**, **2**, **3**, and **4**. If you would like to experiment further, you are welcome to create and train more models under the **Models 5+** heading. All models will be specified in the `sample_models.py` file. After importing the `sample_models` module, you will train your architectures in the notebook. After experimenting with the five simple architectures, you will have the opportunity to compare their performance. Based on your findings, you will construct a deeper architecture that is designed to outperform all of the shallow models. For your convenience, we have designed the notebook so that each model can be specified and trained on separate occasions. That is, say you decide to take a break from the notebook after training **Model 1**. Then, you need not re-execute all prior code cells in the notebook before training **Model 2**. You need only re-execute the code cell below, that is marked with **`RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK`**, before transitioning to the code cells corresponding to **Model 2**. ``` ##################################################################### # RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK # ##################################################################### # allocate 50% of GPU memory (if you like, feel free to change this) from keras.backend.tensorflow_backend import set_session import tensorflow as tf config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.5 set_session(tf.Session(config=config)) # watch for any changes in the sample_models module, and reload it automatically %load_ext autoreload %autoreload 2 # import NN architectures for speech recognition from sample_models import * # import function for training acoustic model from train_utils import train_model ``` <a id='model0'></a> ### Model 0: RNN Given their effectiveness in modeling sequential data, the first acoustic model you will use is an RNN. As shown in the figure below, the RNN we supply to you will take the time sequence of audio features as input. <img src="images/simple_rnn.png" width="50%"> At each time step, the speaker pronounces one of 28 possible characters, including each of the 26 letters in the English alphabet, along with a space character (" "), and an apostrophe ('). The output of the RNN at each time step is a vector of probabilities with 29 entries, where the $i$-th entry encodes the probability that the $i$-th character is spoken in the time sequence. (The extra 29th character is an empty "character" used to pad training examples within batches containing uneven lengths.) If you would like to peek under the hood at how characters are mapped to indices in the probability vector, look at the `char_map.py` file in the repository. The figure below shows an equivalent, rolled depiction of the RNN that shows the output layer in greater detail. <img src="images/simple_rnn_unrolled.png" width="60%"> The model has already been specified for you in Keras. To import it, you need only run the code cell below. ``` model_0 = simple_rnn_model(input_dim=161) # change to 13 if you would like to use MFCC features ``` As explored in the lesson, you will train the acoustic model with the [CTC loss](http://www.cs.toronto.edu/~graves/icml_2006.pdf) criterion. Custom loss functions take a bit of hacking in Keras, and so we have implemented the CTC loss function for you, so that you can focus on trying out as many deep learning architectures as possible :). If you'd like to peek at the implementation details, look at the `add_ctc_loss` function within the `train_utils.py` file in the repository. To train your architecture, you will use the `train_model` function within the `train_utils` module; it has already been imported in one of the above code cells. The `train_model` function takes three **required** arguments: - `input_to_softmax` - a Keras model instance. - `pickle_path` - the name of the pickle file where the loss history will be saved. - `save_model_path` - the name of the HDF5 file where the model will be saved. If we have already supplied values for `input_to_softmax`, `pickle_path`, and `save_model_path`, please **DO NOT** modify these values. There are several **optional** arguments that allow you to have more control over the training process. You are welcome to, but not required to, supply your own values for these arguments. - `minibatch_size` - the size of the minibatches that are generated while training the model (default: `20`). - `spectrogram` - Boolean value dictating whether spectrogram (`True`) or MFCC (`False`) features are used for training (default: `True`). - `mfcc_dim` - the size of the feature dimension to use when generating MFCC features (default: `13`). - `optimizer` - the Keras optimizer used to train the model (default: `SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)`). - `epochs` - the number of epochs to use to train the model (default: `20`). If you choose to modify this parameter, make sure that it is *at least* 20. - `verbose` - controls the verbosity of the training output in the `model.fit_generator` method (default: `1`). - `sort_by_duration` - Boolean value dictating whether the training and validation sets are sorted by (increasing) duration before the start of the first epoch (default: `False`). The `train_model` function defaults to using spectrogram features; if you choose to use these features, note that the acoustic model in `simple_rnn_model` should have `input_dim=161`. Otherwise, if you choose to use MFCC features, the acoustic model should have `input_dim=13`. We have chosen to use `GRU` units in the supplied RNN. If you would like to experiment with `LSTM` or `SimpleRNN` cells, feel free to do so here. If you change the `GRU` units to `SimpleRNN` cells in `simple_rnn_model`, you may notice that the loss quickly becomes undefined (`nan`) - you are strongly encouraged to check this for yourself! This is due to the [exploding gradients problem](http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/). We have already implemented [gradient clipping](https://arxiv.org/pdf/1211.5063.pdf) in your optimizer to help you avoid this issue. __IMPORTANT NOTE:__ If you notice that your gradient has exploded in any of the models below, feel free to explore more with gradient clipping (the `clipnorm` argument in your optimizer) or swap out any `SimpleRNN` cells for `LSTM` or `GRU` cells. You can also try restarting the kernel to restart the training process. ``` train_model(input_to_softmax=model_0, pickle_path='model_0.pickle', save_model_path='model_0.h5', spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='model1'></a> ### (IMPLEMENTATION) Model 1: RNN + TimeDistributed Dense Read about the [TimeDistributed](https://keras.io/layers/wrappers/) wrapper and the [BatchNormalization](https://keras.io/layers/normalization/) layer in the Keras documentation. For your next architecture, you will add [batch normalization](https://arxiv.org/pdf/1510.01378.pdf) to the recurrent layer to reduce training times. The `TimeDistributed` layer will be used to find more complex patterns in the dataset. The unrolled snapshot of the architecture is depicted below. <img src="images/rnn_model.png" width="60%"> The next figure shows an equivalent, rolled depiction of the RNN that shows the (`TimeDistrbuted`) dense and output layers in greater detail. <img src="images/rnn_model_unrolled.png" width="60%"> Use your research to complete the `rnn_model` function within the `sample_models.py` file. The function should specify an architecture that satisfies the following requirements: - The first layer of the neural network should be an RNN (`SimpleRNN`, `LSTM`, or `GRU`) that takes the time sequence of audio features as input. We have added `GRU` units for you, but feel free to change `GRU` to `SimpleRNN` or `LSTM`, if you like! - Whereas the architecture in `simple_rnn_model` treated the RNN output as the final layer of the model, you will use the output of your RNN as a hidden layer. Use `TimeDistributed` to apply a `Dense` layer to each of the time steps in the RNN output. Ensure that each `Dense` layer has `output_dim` units. Use the code cell below to load your model into the `model_1` variable. Use a value for `input_dim` that matches your chosen audio features, and feel free to change the values for `units` and `activation` to tweak the behavior of your recurrent layer. ``` model_1 = rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200, activation='relu') ``` Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_1.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_1.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ``` train_model(input_to_softmax=model_1, pickle_path='model_1.pickle', save_model_path='model_1.h5', spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='model2'></a> ### (IMPLEMENTATION) Model 2: CNN + RNN + TimeDistributed Dense The architecture in `cnn_rnn_model` adds an additional level of complexity, by introducing a [1D convolution layer](https://keras.io/layers/convolutional/#conv1d). <img src="images/cnn_rnn_model.png" width="100%"> This layer incorporates many arguments that can be (optionally) tuned when calling the `cnn_rnn_model` module. We provide sample starting parameters, which you might find useful if you choose to use spectrogram audio features. If you instead want to use MFCC features, these arguments will have to be tuned. Note that the current architecture only supports values of `'same'` or `'valid'` for the `conv_border_mode` argument. When tuning the parameters, be careful not to choose settings that make the convolutional layer overly small. If the temporal length of the CNN layer is shorter than the length of the transcribed text label, your code will throw an error. Before running the code cell below, you must modify the `cnn_rnn_model` function in `sample_models.py`. Please add batch normalization to the recurrent layer, and provide the same `TimeDistributed` layer as before. ``` model_2 = cnn_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=2, conv_border_mode='valid', units=200) ``` Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_2.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_2.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ``` from keras.optimizers import SGD train_model(input_to_softmax=model_2, pickle_path='model_2.pickle', save_model_path='model_2.h5', # add clipvalue=0.5 from https://discussions.udacity.com/t/model-2-cnn-rnn-timedistributed-dense-gets-nan/478646/3 optimizer=SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5, clipvalue=0.5), spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='model3'></a> ### (IMPLEMENTATION) Model 3: Deeper RNN + TimeDistributed Dense Review the code in `rnn_model`, which makes use of a single recurrent layer. Now, specify an architecture in `deep_rnn_model` that utilizes a variable number `recur_layers` of recurrent layers. The figure below shows the architecture that should be returned if `recur_layers=2`. In the figure, the output sequence of the first recurrent layer is used as input for the next recurrent layer. <img src="images/deep_rnn_model.png" width="80%"> Feel free to change the supplied values of `units` to whatever you think performs best. You can change the value of `recur_layers`, as long as your final value is greater than 1. (As a quick check that you have implemented the additional functionality in `deep_rnn_model` correctly, make sure that the architecture that you specify here is identical to `rnn_model` if `recur_layers=1`.) ``` model_3 = deep_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200, recur_layers=2) ``` Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_3.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_3.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ``` train_model(input_to_softmax=model_3, pickle_path='model_3.pickle', save_model_path='model_3.h5', spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='model4'></a> ### (IMPLEMENTATION) Model 4: Bidirectional RNN + TimeDistributed Dense Read about the [Bidirectional](https://keras.io/layers/wrappers/) wrapper in the Keras documentation. For your next architecture, you will specify an architecture that uses a single bidirectional RNN layer, before a (`TimeDistributed`) dense layer. The added value of a bidirectional RNN is described well in [this paper](http://www.cs.toronto.edu/~hinton/absps/DRNN_speech.pdf). > One shortcoming of conventional RNNs is that they are only able to make use of previous context. In speech recognition, where whole utterances are transcribed at once, there is no reason not to exploit future context as well. Bidirectional RNNs (BRNNs) do this by processing the data in both directions with two separate hidden layers which are then fed forwards to the same output layer. <img src="images/bidirectional_rnn_model.png" width="80%"> Before running the code cell below, you must complete the `bidirectional_rnn_model` function in `sample_models.py`. Feel free to use `SimpleRNN`, `LSTM`, or `GRU` units. When specifying the `Bidirectional` wrapper, use `merge_mode='concat'`. ``` model_4 = bidirectional_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features units=200) ``` Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_4.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_4.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ``` train_model(input_to_softmax=model_4, pickle_path='model_4.pickle', save_model_path='model_4.h5', spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='model5'></a> ### (OPTIONAL IMPLEMENTATION) Models 5+ If you would like to try out more architectures than the ones above, please use the code cell below. Please continue to follow the same convention for saving the models; for the $i$-th sample model, please save the loss at **`model_i.pickle`** and saving the trained model at **`model_i.h5`**. ``` ## (Optional) TODO: Try out some more models! ### Feel free to use as many code cells as needed. # model_5 : # cnn and bidirectional rnn can get good prediction since combine that be model_5 model_5 = bidirectional_deep_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=2, conv_border_mode='valid', units=200, recur_layers=2) # the train result is pretty good but validate result is bad, it obvious is overfitting when epoch 5 or 6. train_model(input_to_softmax=model_5, pickle_path='model_5.pickle', save_model_path='model_5.h5', spectrogram=True) # change to False if you would like to use MFCC features recurrent_dropout = 0.3 dropout = 0.3 cnn_layers = 2 recur_layers = 2 dilation_rate = 3 # model_6 : # use recurrent_dropout only and set the value is 0.3 model_6 = bidirectional_deep_rnn_dropout_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=2, conv_border_mode='valid', units=200, recurrent_dropout=recurrent_dropout, recur_layers=2) # it also overfitting when epoch 7 or 8. train_model(input_to_softmax=model_6, pickle_path='model_6.pickle', save_model_path='model_6.h5', spectrogram=True) # change to False if you would like to use MFCC features recurrent_dropout = 0.3 dropout = 0.3 # use 0.3 be values of recurrent_dropout and dropout model_7 = bidirectional_deep_rnn_dropout_model2(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=2, conv_border_mode='valid', units=200, recurrent_dropout=recurrent_dropout, dropout=dropout, recur_layers=2) train_model(input_to_softmax=model_7, pickle_path='model_7.pickle', save_model_path='model_7.h5', spectrogram=True) # change to False if you would like to use MFCC features recurrent_dropout = 0.3 dropout = 0.3 recur_layers = 2 dilation_rate = 3 model_8 = causal_cnn_bidirectional_deep_rnn_dropout_model( input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='causal', units=200, dilation_rate=dilation_rate, recurrent_dropout=recurrent_dropout, dropout=dropout, recur_layers=recur_layers) train_model(input_to_softmax=model_8, pickle_path='model_8.pickle', save_model_path='model_8.h5', spectrogram=True) # change to False if you would like to use MFCC features ``` <a id='compare'></a> ### Compare the Models Execute the code cell below to evaluate the performance of the drafted deep learning models. The training and validation loss are plotted for each model. ``` from glob import glob import numpy as np import _pickle as pickle import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set_style(style='white') # obtain the paths for the saved model history all_pickles = sorted(glob("results/*.pickle")) # remove model_0 because it is different with others all_pickles = ['results/model_0.pickle', 'results/model_1.pickle', 'results/model_2.pickle', 'results/model_3.pickle', 'results/model_4.pickle', 'results/model_5.pickle', 'results/model_6.pickle', 'results/model_7.pickle', 'results/model_8.pickle'] # print(all_pickles) # extract the name of each model model_names = [item[8:-7] for item in all_pickles] # extract the loss history for each model valid_loss = [pickle.load( open( i, "rb" ) )['val_loss'] for i in all_pickles] train_loss = [pickle.load( open( i, "rb" ) )['loss'] for i in all_pickles] # save the number of epochs used to train each model num_epochs = [len(valid_loss[i]) for i in range(len(valid_loss))] fig = plt.figure(figsize=(16,5)) # plot the training loss vs. epoch for each model ax1 = fig.add_subplot(121) for i in range(len(all_pickles)): ax1.plot(np.linspace(1, num_epochs[i], num_epochs[i]), train_loss[i], label=model_names[i]) # clean up the plot ax1.legend() ax1.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Training Loss') # plot the validation loss vs. epoch for each model ax2 = fig.add_subplot(122) for i in range(len(all_pickles)): ax2.plot(np.linspace(1, num_epochs[i], num_epochs[i]), valid_loss[i], label=model_names[i]) # clean up the plot ax2.legend() ax2.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Validation Loss') plt.show() all_pickles = ['results/model_1.pickle', 'results/model_2.pickle', 'results/model_3.pickle', 'results/model_4.pickle', 'results/model_5.pickle', 'results/model_6.pickle', 'results/model_7.pickle', 'results/model_8.pickle'] # print(all_pickles) # extract the name of each model model_names = [item[8:-7] for item in all_pickles] # extract the loss history for each model valid_loss = [pickle.load( open( i, "rb" ) )['val_loss'] for i in all_pickles] train_loss = [pickle.load( open( i, "rb" ) )['loss'] for i in all_pickles] # save the number of epochs used to train each model num_epochs = [len(valid_loss[i]) for i in range(len(valid_loss))] fig = plt.figure(figsize=(16,5)) # plot the training loss vs. epoch for each model ax1 = fig.add_subplot(121) for i in range(len(all_pickles)): ax1.plot(np.linspace(1, num_epochs[i], num_epochs[i]), train_loss[i], label=model_names[i]) # clean up the plot ax1.legend() ax1.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Training Loss') # plot the validation loss vs. epoch for each model ax2 = fig.add_subplot(122) for i in range(len(all_pickles)): ax2.plot(np.linspace(1, num_epochs[i], num_epochs[i]), valid_loss[i], label=model_names[i]) # clean up the plot ax2.legend() ax2.set_xlim([1, max(num_epochs)]) plt.xlabel('Epoch') plt.ylabel('Validation Loss') plt.show() ``` __Question 1:__ Use the plot above to analyze the performance of each of the attempted architectures. Which performs best? Provide an explanation regarding why you think some models perform better than others. __Answer:__ 1. Model 0: RNN --> Epoch 20: 214s - loss: 751.0739 - val_loss: 729.9091 * The performance is bad, the model is too simple can't fulfill the dataset. 2. Model 1: RNN + TimeDistributed Dense --> Epoch 20: 222s - loss: 109.6430 - val_loss: 135.0520 * The perormance is good, and the gap between loss and val_loss is not too big.It add a BatchNormalization and TimeDistributed base on simple_rnn_model. 3. Model 2: CNN + RNN + TimeDistributed Dense --> Epoch 20: 57s - loss: 85.0991 - val_loss: 133.3752 * The performance is good and quick, but the gap between loss and val_loss is a little big.It use CNN + RNN also have BatchNormalization and TimeDistributed.It got NaN loss when training, until I modify parametrs of SGD as bellow. optimizer=SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5, clipvalue=0.5), 4. Model 3: Deeper RNN + TimeDistributed Dense --> Epoch 20: 379s - loss: 97.7273 - val_loss: 128.5798 * Then performance is good but it spend almost 6 minutes each epoch. But at least the result is good. I set 2 RNN layers in the model. 5. Model 4: Bidirectional RNN + TimeDistributed Dense --> Epoch 20: 361s - loss: 106.7681 - val_loss: 138.9251 * Then performance is good but it spend almost 6 minutes each epoch. But at least the result is good. The model have one bidirectional RNN but the parameters and time of epoch are similar as two layers RNN. 6. Model 5: CNN + Deeper Bidirectional RNN + TimeDistributed Dense --> Epoch 20: 349s - loss: 30.6069 - val_loss: 169.0728 * Base on above models, CNN, TimeDistributed Dense, Deeper RNN, and Bidirectional RNN can get good performance. This model combines all of that and should get bestest result. The train loss is the bestest but val_loss increase to another direction when epoch 5 or 6. It is overfitting. 7. Model 6: CNN + Deeper Bidirectional RNN + TimeDistributed Dense + Recurrent Dropout --> Epoch 20: 337s - loss: 48.1893 - val_loss: 146.8864 * I set 0.3 on Recurrent Dropout in each RNN, but it still overfitting when epoch 7 or 8. 8. Model 7: CNN + Deeper Bidirectional RNN + TimeDistributed Dense + Recurrent Dropout&Dropout --> Epoch 20: 344s - loss: 107.0704 - val_loss: 111.1476 * The performance is good and no obvious overfitting. I just set 0.3 on Recurrent Dropout and Dropout in each RNN. 9. Model 8: Dilated CNN + Deeper Bidirectional RNN + TimeDistributed Dense + Recurrent Dropout --> Epoch 20: 700s - loss: 115.5528 - val_loss: 115.3043 * The performance is good and no obvious overfitting, but no obvoius benefit compare to CNN. I use Dilated CNN instead CNN and others are base on Model 7. <a id='final'></a> ### (IMPLEMENTATION) Final Model Now that you've tried out many sample models, use what you've learned to draft your own architecture! While your final acoustic model should not be identical to any of the architectures explored above, you are welcome to merely combine the explored layers above into a deeper architecture. It is **NOT** necessary to include new layer types that were not explored in the notebook. However, if you would like some ideas for even more layer types, check out these ideas for some additional, optional extensions to your model: - If you notice your model is overfitting to the training dataset, consider adding **dropout**! To add dropout to [recurrent layers](https://faroit.github.io/keras-docs/1.0.2/layers/recurrent/), pay special attention to the `dropout_W` and `dropout_U` arguments. This [paper](http://arxiv.org/abs/1512.05287) may also provide some interesting theoretical background. - If you choose to include a convolutional layer in your model, you may get better results by working with **dilated convolutions**. If you choose to use dilated convolutions, make sure that you are able to accurately calculate the length of the acoustic model's output in the `model.output_length` lambda function. You can read more about dilated convolutions in Google's [WaveNet paper](https://arxiv.org/abs/1609.03499). For an example of a speech-to-text system that makes use of dilated convolutions, check out this GitHub [repository](https://github.com/buriburisuri/speech-to-text-wavenet). You can work with dilated convolutions [in Keras](https://keras.io/layers/convolutional/) by paying special attention to the `padding` argument when you specify a convolutional layer. - If your model makes use of convolutional layers, why not also experiment with adding **max pooling**? Check out [this paper](https://arxiv.org/pdf/1701.02720.pdf) for example architecture that makes use of max pooling in an acoustic model. - So far, you have experimented with a single bidirectional RNN layer. Consider stacking the bidirectional layers, to produce a [deep bidirectional RNN](https://www.cs.toronto.edu/~graves/asru_2013.pdf)! All models that you specify in this repository should have `output_length` defined as an attribute. This attribute is a lambda function that maps the (temporal) length of the input acoustic features to the (temporal) length of the output softmax layer. This function is used in the computation of CTC loss; to see this, look at the `add_ctc_loss` function in `train_utils.py`. To see where the `output_length` attribute is defined for the models in the code, take a look at the `sample_models.py` file. You will notice this line of code within most models: ``` model.output_length = lambda x: x ``` The acoustic model that incorporates a convolutional layer (`cnn_rnn_model`) has a line that is a bit different: ``` model.output_length = lambda x: cnn_output_length( x, kernel_size, conv_border_mode, conv_stride) ``` In the case of models that use purely recurrent layers, the lambda function is the identity function, as the recurrent layers do not modify the (temporal) length of their input tensors. However, convolutional layers are more complicated and require a specialized function (`cnn_output_length` in `sample_models.py`) to determine the temporal length of their output. You will have to add the `output_length` attribute to your final model before running the code cell below. Feel free to use the `cnn_output_length` function, if it suits your model. ``` # specify the model cnn_dropout = 0.2 recurrent_dropout = 0.3 dropout = 0.3 cnn_layers = 2 recur_layers = 2 dilation_rate = 3 model_end = final_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='causal', units=200, dilation_rate=dilation_rate, cnn_dropout=cnn_dropout, recurrent_dropout=recurrent_dropout, dropout=dropout, recur_layers=recur_layers) # model_end = bidirectional_deep_rnn_dropout_model(input_dim=161, # change to 13 if you would like to use MFCC features # filters=200, # kernel_size=11, # conv_stride=2, # conv_border_mode='valid', # units=200, # recurrent_dropout=recurrent_dropout, # recur_layers=2) # model_end = final_model(input_dim=161, # change to 13 if you would like to use MFCC features # filters=200, # kernel_size=11, # conv_stride=2, # conv_border_mode='valid', # units=200, # recur_layers=2) # model_end = final_model(input_dim=161, # change to 13 if you would like to use MFCC features # filters=200, # kernel_size=11, # conv_stride=2, # conv_border_mode='valid', # units=200, # cnn_layers=cnn_layers, # recur_layers=recur_layers, # recurrent_dropout=recurrent_dropout, dropout=dropout, # dilation_rate=dilation_rate) ``` Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_end.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_end.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required. ``` train_model(input_to_softmax=model_end, pickle_path='model_end.pickle', save_model_path='model_end.h5', epochs=35, spectrogram=True) # change to False if you would like to use MFCC features ``` __Question 2:__ Describe your final model architecture and your reasoning at each step. __Answer:__ My final model is base on model 8, because it didn't occured overfitting and have good protential if run more epochs. I list all layers as bellow: 1. Dilate CNN to filter features from voice input and Dilate can reduce overfitting slightly observe from result of Model 8. 2. BatchNormalization + Dropout(0.2) for reducing overfitting. 3. Deep Bidirectional + GRU to find time serial patterns and I use two layers of that. Each RNN append a BatchNormalization. 4. I use a TimeDistributed layer to restore to serial data. 5. Finnaly is a softmax layer to predict output of 29 types. 6. I use 35 epochs to traing because it has protential to continue training when I run 20 epochs. The model is more complex and more toleration of overfitting, but it also need more time and epochs to train. Even on AWS GPU environment it spend 7 hours. I can't imagine it spend how long to train when I run a real case training! Finally after 7 hours, the loss is 96.5344, val_loss is 104.2914. It is a little overfitting but not too much. But in prediction are not good enough to use in real world. Maybe to use bigger dataset can train to better result, but the spend time is too big for my credit of aws. <a id='step3'></a> ## STEP 3: Obtain Predictions We have written a function for you to decode the predictions of your acoustic model. To use the function, please execute the code cell below. ``` import numpy as np from data_generator import AudioGenerator from keras import backend as K from utils import int_sequence_to_text from IPython.display import Audio def get_predictions(index, partition, input_to_softmax, model_path): """ Print a model's decoded predictions Params: index (int): The example you would like to visualize partition (str): One of 'train' or 'validation' input_to_softmax (Model): The acoustic model model_path (str): Path to saved acoustic model's weights """ # load the train and test data data_gen = AudioGenerator() data_gen.load_train_data() data_gen.load_validation_data() # obtain the true transcription and the audio features if partition == 'validation': transcr = data_gen.valid_texts[index] audio_path = data_gen.valid_audio_paths[index] data_point = data_gen.normalize(data_gen.featurize(audio_path)) elif partition == 'train': transcr = data_gen.train_texts[index] audio_path = data_gen.train_audio_paths[index] data_point = data_gen.normalize(data_gen.featurize(audio_path)) else: raise Exception('Invalid partition! Must be "train" or "validation"') # obtain and decode the acoustic model's predictions input_to_softmax.load_weights(model_path) prediction = input_to_softmax.predict(np.expand_dims(data_point, axis=0)) output_length = [input_to_softmax.output_length(data_point.shape[0])] pred_ints = (K.eval(K.ctc_decode( prediction, output_length)[0][0])+1).flatten().tolist() # play the audio file, and display the true and predicted transcriptions print('-'*80) Audio(audio_path) print('True transcription:\n' + '\n' + transcr) print('-'*80) print('Predicted transcription:\n' + '\n' + ''.join(int_sequence_to_text(pred_ints))) print('-'*80) def create_end_model(): input_to_softmax = final_model(input_dim=161, # change to 13 if you would like to use MFCC features filters=200, kernel_size=11, conv_stride=1, conv_border_mode='causal', units=200, dilation_rate=dilation_rate, cnn_dropout=cnn_dropout, recurrent_dropout=recurrent_dropout, dropout=dropout, recur_layers=recur_layers) return input_to_softmax ``` Use the code cell below to obtain the transcription predicted by your final model for the first example in the training dataset. ``` get_predictions(index=0, partition='train', input_to_softmax=create_end_model(), model_path='results/model_end.h5') ``` Use the next code cell to visualize the model's prediction for the first example in the validation dataset. ``` get_predictions(index=0, partition='validation', input_to_softmax=create_end_model(), model_path='results/model_end.h5') ``` One standard way to improve the results of the decoder is to incorporate a language model. We won't pursue this in the notebook, but you are welcome to do so as an _optional extension_. If you are interested in creating models that provide improved transcriptions, you are encouraged to download [more data](http://www.openslr.org/12/) and train bigger, deeper models. But beware - the model will likely take a long while to train. For instance, training this [state-of-the-art](https://arxiv.org/pdf/1512.02595v1.pdf) model would take 3-6 weeks on a single GPU!
github_jupyter
## Binary Search ``` def binary_search(n, li, x): s = 0 e = n-1 while s<=e: mid = (s+e)//2 if li[mid] == x: return mid elif li[mid] < x: s = mid + 1 continue elif li[mid] > x: e = mid - 1 continue if x not in li: return -1 n = int(input()) li = [int(x) for x in input().split()] x = int(input()) found_index = binary_search(n, li, x) print(found_index) ``` ## Bubble Sort ``` n = int(input()) li = [int(x) for x in input().split()] for round in range(n): for i in range(round, n): for j in range(i+1, n): if li[j] < li[i]: li[i], li[j] = li[j], li[i] #print(round, i, j) break for ele in li: print(ele, end = " ") ``` ## Insertion Sort ``` n = int(input()) li = [int(x) for x in input().split()] for i in range(1, n): j = i-1 temp = li[i] while li[j]>temp and j>=0: li[j+1] = li[j] j = j - 1 li[j+1] = temp for ele in li: print(ele, end = " ") ``` ``` n = int(input()) li = [int(x) for x in input().split()] m = int(input()) li2 = [int(x) for x in input().split()] li_main = [] i = 0 j = 0 while (i<n) and (j<m): #print(li[i], li2[j]) if li[i]<li2[j]: #print(li[i]) li_main.append(li[i]) i = i + 1 continue elif li[i]>li2[j]: #print(li2[j]) li_main.append(li2[j]) j = j + 1 continue else: #print(li[i]) #print(li2[j]) li_main.append(li[i]) li_main.append(li2[j]) i = i + 1 j = j + 1 while i <n: li_main.append(li[i]) i = i + 1 while j <m: li_main.append(li2[j]) j = j + 1 for ele in li_main: print(ele, end = " ") ``` ``` n = int(input()) li = [int(x) for x in input().split()] li2 = [] for i in range(n): if li[i] != 0: li2.append(li[i]) while i<=n: li2.append(0) i = i + 1 length1 = len(li) length2 = len(li2) s = length1 - length2 x = 0 while x<s: li2.append(0) x = x + 1 for ele in li2: print(ele, end = " ") ``` ``` def Rotate(arr, d): # MOST SIMPLEST ONE LINER CODE arr[d:], arr[:d] = arr[:d], arr[d:] # 1ST (CORRECT) APPROACH CODE # for k in range(1, d+1): # temp = arr[0] # for i in range(1, n): # arr[i-1] = arr[i] # arr[n-1] = temp #2ND (CORRECT) APPROACH CODE # arr_temp = [] # for i in range(d): # arr_temp.append(arr[i]) # for j in range(d, n): # arr[j-d] = arr[j] # r = n-d # for k in range(d): # arr[r] = arr_temp[k] # r = r+1 #3RD (CORRECT) APPROACH CODE #leng = len(arr) #arr = arr[::-1] #arr = arr[leng-d-1:0:-1] #arr[:] = arr[::-1] #print(arr) #[item for i in range(0,leng,leng//2) for item in arr[i:i+leng//2][::-1]] # Main n=int(input()) arr=list(int(i) for i in input().strip().split(' ')) d=int(input()) Rotate(arr, d) print(*arr) ``` ``` n = int(input()) li = [int(x) for x in input().split()] temp = max(li) while temp in li: li.remove(temp) new_temp = max(li) xor = 0 for ele in li: xor = xor^ele if n > 0 and xor !=0: print(new_temp) else: print(-2147483648) ``` ``` n = int(input()) li = [int(x) for x in input().split()] val = False for i in range(n): if i<n-1: if li[i]>li[i+1]: print(i+1) val = False break elif li[i]<li[i+1]: val = True elif i == n-1: if li[i-1]>li[i]: print(i) break elif li[i-1] < li[i]: pass if val == True: print("0") ```
github_jupyter
# Getting Financial Data - Pandas Datareader ### Introduction: This time you will get data from a website. ### Step 1. Import the necessary libraries ``` import pandas as pd import requests ``` ### Step 2. Create your time range (start and end variables). The start date should be 01/01/2015 and the end should today (whatever your today is). ``` from datetime import datetime start_date = 1/1/2015 hoy = datetime.today().strftime('%Y/%m/%d') ``` ### Step 3. Get an API key for one of the APIs that are supported by Pandas Datareader, preferably for import pandas_datareader. If you do not have an API key for any of the supported APIs, it is easiest to get one for [AlphaVantage](https://www.alphavantage.co/support/#api-key). (Note that the API key is shown directly after the signup. You do *not* receive it via e-mail.) (For a full list of the APIs that are supported by Pandas Datareader, [see here](https://pydata.github.io/pandas-datareader/readers/index.html). As the APIs are provided by third parties, this list may change.) ``` apy_key = 'ODCME5YNUVQBFUMF' url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=ODCME5YNUVQBFUMF' r = requests.get(url) r r.json() pd.DataFrame(r.json()['Time Series (5min)']) time_series = pd.DataFrame(r.json()['Time Series (5min)']).transpose() time_series ``` ### Step 4. Use Pandas Datarader to read the daily time series for the Apple stock (ticker symbol AAPL) between 01/01/2015 and today, assign it to df_apple and print it. ``` import pandas_datareader url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AAPL&apikey=ODCME5YNUVQBFUMF' q = requests.get(url) q q.json() pd.DataFrame(q.json()['Time Series (Daily)']) aapl = pd.DataFrame(q.json()['Time Series (Daily)']).transpose() aapl (aapl[''] > start_date) & (aapl[''] <= hoy) # Quería coger la columna de fechas y seleccionar desde 01/01/2015 hasta hoy. # Pero no se entrar en el indice aapl.iloc[3:2] ``` ### Step 5. Add a new column "stock" to the dataframe and add the ticker symbol ### Step 6. Repeat the two previous steps for a few other stocks, always creating a new dataframe: Tesla, IBM and Microsoft. (Ticker symbols TSLA, IBM and MSFT.) ### Step 7. Combine the four separate dataFrames into one combined dataFrame df that holds the information for all four stocks ### Step 8. Shift the stock column into the index (making it a multi-level index consisting of the ticker symbol and the date). ### Step 7. Create a dataFrame called vol, with the volume values. ### Step 8. Aggregate the data of volume to weekly. Hint: Be careful to not sum data from the same week of 2015 and other years. ### Step 9. Find all the volume traded in the year of 2015
github_jupyter
# Batch processing with Argo Worfklows In this notebook we will dive into how you can run batch processing with Argo Workflows and Seldon Core. Dependencies: * Seldon core installed as per the docs with an ingress * Minio running in your cluster to use as local (s3) object storage * Argo Workfklows installed in cluster (and argo CLI for commands) ### Setup #### Install Seldon Core Use the notebook to [set-up Seldon Core with Ambassador or Istio Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html). Note: If running with KIND you need to make sure do follow [these steps](https://github.com/argoproj/argo/issues/2376#issuecomment-595593237) as workaround to the `/.../docker.sock` known issue. #### Set up Minio in your cluster Use the notebook to [set-up Minio in your cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/minio_setup.html). #### Copy the Minio Secret to namespace We need to re-use the minio secret for the batch job, so this can be done by just copying the minio secret created in the `minio-system` The command below just copies the secred with the name "minio" from the minio-system namespace to the default namespace. ``` !kubectl get secret minio -n minio-system -o json | jq '{apiVersion,data,kind,metadata,type} | .metadata |= {"annotations", "name"}' | kubectl apply -n default -f - ``` #### Install Argo Workflows You can follow the instructions from the official [Argo Workflows Documentation](https://github.com/argoproj/argo#quickstart). You also need to make sure that argo has permissions to create seldon deployments - for this you can create a role: ``` %%writefile role.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: workflow rules: - apiGroups: - "" resources: - pods verbs: - "*" - apiGroups: - "apps" resources: - deployments verbs: - "*" - apiGroups: - "" resources: - pods/log verbs: - "*" - apiGroups: - machinelearning.seldon.io resources: - "*" verbs: - "*" !!kubectl apply -f role.yaml ``` A service account: ``` !kubectl create serviceaccount workflow ``` And a binding ``` !kubectl create rolebinding workflow --role=workflow --serviceaccount=default:workflow ``` ### Create some input for our model We will create a file that will contain the inputs that will be sent to our model ``` mkdir -p assets/ with open("assets/input-data.txt", "w") as f: for i in range(10000): f.write('[[1, 2, 3, 4]]\n') ``` #### Check the contents of the file ``` !wc -l assets/input-data.txt !head assets/input-data.txt ``` #### Upload the file to our minio ``` !mc mb minio-seldon/data !mc cp assets/input-data.txt minio-seldon/data/ ``` #### Create Argo Workflow In order to create our argo workflow we have made it simple so you can leverage the power of the helm charts. Before we dive into the contents of the full helm chart, let's first give it a try with some of the settings. We will run a batch job that will set up a Seldon Deployment with 10 replicas and 100 batch client workers to send requests. ``` !helm template seldon-batch-workflow helm-charts/seldon-batch-workflow/ \ --set workflow.name=seldon-batch-process \ --set seldonDeployment.name=sklearn \ --set seldonDeployment.replicas=10 \ --set seldonDeployment.serverWorkers=1 \ --set seldonDeployment.serverThreads=10 \ --set batchWorker.workers=100 \ --set batchWorker.payloadType=ndarray \ --set batchWorker.dataType=data \ | argo submit --serviceaccount workflow - !argo list !argo get seldon-batch-process !argo logs -w seldon-batch-process || argo logs seldon-batch-process # The 2nd command is for argo 2.8+ ``` ### Check output in object store We can now visualise the output that we obtained in the object store. First we can check that the file is present: ``` import json wf_arr = !argo get seldon-batch-process -o json wf = json.loads("".join(wf_arr)) WF_ID = wf["metadata"]["uid"] print(f"Workflow ID is {WF_ID}") !mc ls minio-seldon/data/output-data-"$WF_ID".txt ``` Now we can output the contents of the file created using the `mc head` command. ``` !mc cp minio-seldon/data/output-data-"$WF_ID".txt assets/output-data.txt !head assets/output-data.txt !argo delete seldon-batch-process ```
github_jupyter
# Host Label Validation and Exploration After plotting every feature's density distribution by relevance, the top 10 that are “most wrong” in either part of the value range were manually checked (i.e. videos often repeated across articles, yet labeled as "relevant"). This way, some mislabeled data could be identified and corrected. This was done iteratively until the top 10 "most wrong" labels in any value range were determined to be correctly labeled. ``` import pandas as pd import psycopg2 %load_ext autoreload %autoreload 2 # Load the dataset from the database # TODO this is not DRY yet # TODO don't use "most wrong" terminology conn = psycopg2.connect(database="gdelt_social_video", user="postgres") c = conn.cursor() # Just work with youtube for now platform = "youtube" samples = pd.read_sql_query('''SELECT h.*, lh.twitter_relevant, lh.facebook_relevant, lh.youtube_relevant FROM hosts h RIGHT JOIN labeled_hosts lh ON h.hostname=lh.hostname WHERE lh.%s_relevant <> -1''' % platform,con=conn) samples = samples[["hostname", "article_count", "%s_video_sum" % platform, "%s_video_sum_distinct" % platform, "%s_video_count" % platform, "%s_relevant" % platform]] # Compute the remaining interesting features # Average number of videos per article, including articles without videos samples["%s_video_average" % platform] = samples["%s_video_sum" % platform] / samples["article_count"] # Average distinct videos per article samples["%s_video_average_distinct" % platform] = samples["%s_video_sum_distinct" % platform] / samples["article_count"] # Total videos to distinct videos samples["%s_video_distinct_to_sum" % platform] = samples["%s_video_sum_distinct" % platform] / samples["%s_video_sum" % platform] # Percentage of articles with videos samples["%s_video_percentage" % platform] = samples["%s_video_count" % platform] / samples["article_count"] samples.head() # Print 10 hosts that are "most wrong" samples[samples["youtube_relevant"] != 1].sort_values("youtube_video_count", ascending=True).head(10) # Manually look at the articles from a host articles = pd.read_sql_query("SELECT DISTINCT website_url FROM found_videos WHERE hostname='www.premiumtimesng.com' AND platform='youtube'",con=conn) for row in articles.iterrows(): print(row[1][0]) ``` Mislabled examples were manually change in the database. **The hosts dataset is now considered clean**
github_jupyter
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/thrash-lab/sparse-growth-curve/blob/main/2_one_file_multiple_growth_curves_analysis.ipynb) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) for the code. [![License: CC BY-NC 4.0](https://img.shields.io/badge/License-CC%20BY--NC%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by-nc/4.0/) for other contents. #### **Authors**: Chuankai Cheng and J. Cameron Thrash(*) Department of Biological Sciences, University of Southern California, Los Angeles, CA, USA #### (*) Correspondence: J. Cameron Thrash - University of Southern California - 3616 Trousdale Pkwy, AHF 209 - Los Angeles, CA 90089, USA - thrash@usc.edu ``` !wget https://raw.githubusercontent.com/thrash-lab/sparse-growth-curve/main/Growth_curve_data_example/LSUCC0096_all_salinity.xlsx \ -O LSUCC0096_all_salinity.xlsx #What is your file name? # The input file has to be a '.xlsx' file input_file='./LSUCC0096_all_salinity.xlsx' input_file_name=input_file.split('.xlsx')[0] import pandas as pd #pandas for reading tables import numpy as np from matplotlib import pyplot as plt from matplotlib import cm colormap=cm.tab10 import os from datetime import datetime from random import random #statistical analysis from sklearn.tree import DecisionTreeRegressor from sklearn.linear_model import LinearRegression,RANSACRegressor from scipy import stats from scipy.interpolate import interp1d ``` # All the functions that are needed ``` def myLinearRegression_CB(x, y, x_fit, one_order=10): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ #print('\nFitting data:') #print('x = ', x) #print('y = ', y) corr=np.corrcoef(x,y)[0][1] #print('|corr|=', np.abs(corr)) if (((np.abs(corr)<0.80) or (len(y)<4)) and ((np.abs(corr)<0.90) or (len(y)<3)) and ((np.max(y)-np.min(y))<np.log2(one_order))): comp_y=np.median(y)*np.ones(len(y)) pre_y=np.median(y)*np.ones(len(x_fit)) doubling_rate=1e-6 else: #Robust linear model estimation using RANSAC X=x.reshape(-1,1) if len(y)>4: try: reg = RANSACRegressor() reg.fit(X, y) doubling_rate=reg.estimator_.coef_[0] inlier_mask = reg.inlier_mask_ outlier_mask = np.logical_not(inlier_mask) except ValueError: #print('RANSAC could not find a valid consensus set.\n', # 'Running regular linear regression.') reg = LinearRegression() reg.fit(X,y) doubling_rate=reg.coef_[0] else: reg = LinearRegression() reg.fit(X,y) doubling_rate=reg.coef_[0] pre_y=reg.predict(x_fit.reshape(-1,1)) comp_y=reg.predict(X) sigma=np.sqrt( np.sum( (comp_y-y)**2 / (len(x)-1)) ) T_95 = stats.t.ppf(0.95, len(x)-1) G=np.sqrt( 1/len(x) + (x_fit-np.mean(x))**2 / sum((x-np.mean(x))**2) ) ci=sigma*T_95*G #sigma**2/np.sum() return (doubling_rate, pre_y, ci) def preprocessing_growth_curve(time, cell_density): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ t=np.array(time) X=np.array(cell_density) #for i in range(len(time)-3): # t=np.r_[t,np.median(time[[i,i+1,i+2]])] # X=np.r_[X, np.median(cell_density[[i,i+1, i+2]])] X=X[np.argsort(t)] t=t[np.argsort(t)] #You might get multiple cell counts for the same sample at one time. #Here, I merge the cell densities by their mean: #using the function "np.unique" #I get rid of the duplicated time points t1=np.unique(t) X1=[] for tt in t1: temporary_cell_densities=X[t==tt] #Getting the mean cell density at a time point X1.append(np.median(temporary_cell_densities)) X1=np.array(X1) return t1, X1 def phase_seperations(t, X, max_depth=1): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ gamma=np.diff(np.log2(X))/np.diff(t) gamma=np.r_[gamma, gamma, gamma] #gamma=np.r_[gamma[0], gamma] t_gamma=np.r_[t[0:-1], np.array([(t[i]+t[i+1])/2 for i in range(len(t)-1)]), t[1::]] gamma_2=np.diff(np.log2(X)[::2])/np.diff(t[::2]) gamma_2=np.r_[gamma_2, gamma_2, gamma_2] t_gamma_2=np.r_[t[::2][0:-1], [(t[::2][i]+t[::2][i+1])/2 for i in range(len(t[::2])-1)], t[::2][1::]] gamma_3=np.diff(np.log2(X)[::3])/np.diff(t[::3]) gamma_3=np.r_[gamma_3, gamma_3, gamma_3] t_gamma_3=np.r_[t[::3][0:-1], [(t[::3][i]+t[::3][i+1])/2 for i in range(len(t[::3])-1)], t[::3][1::]] all_t_gamma=np.r_[t_gamma,t_gamma_2, t_gamma_3] all_gamma=np.r_[gamma, gamma_2, gamma_3] all_gamma=all_gamma[np.argsort(all_t_gamma)] all_t_gamma=np.sort(all_t_gamma) all_gamma=np.array([np.median(all_gamma[[i,i+1,i+2,i+3, i+4,i+5,i+6,i+7,i+8]]) for i in range(len(all_t_gamma)-9)]) all_t_gamma=np.array([np.median(all_t_gamma[[i,i+1,i+2,i+3, i+4,i+5,i+6,i+7,i+8]]) for i in range(len(all_t_gamma)-9)]) sel_t_gamma=np.unique(all_t_gamma) sel_gamma=[] for stg in sel_t_gamma: sel_gamma.append( np.mean(all_gamma[all_t_gamma==stg])) sel_gamma=np.array(sel_gamma) # By default, max_depth = 1 # Because for a standard growth curve (no diauxic shift) without death phase, # there would only be two states: # 1. Not growing (lag phase and stationary), growth rate is close to 0; # 2. Growing exponentially at an almost constant rate. regr_1 = DecisionTreeRegressor(max_depth=max_depth) regr_1.fit(all_t_gamma.reshape(-1, 1), all_gamma) t_fit = np.arange(0.0, t[-1], 0.01)[:, np.newaxis] gamma_fit = regr_1.predict(t_fit) #We find the state transition point gamma_fit_diff=np.diff(gamma_fit) inflection_points=t_fit[1::][gamma_fit_diff!=0] all_starting_time=np.r_[[0],inflection_points.reshape(1,-1)[0], t_fit[-1]] return all_starting_time def phases_exponential_fit(phases_points, t, X, one_order): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ all_starting_time=phases_points all_doubling_rates=[] all_fit_time=[] all_fit_cell_density=[] all_fit_conf_band=[] print('All phases points', all_starting_time) t_1 = np.arange(0.0, t[-1], 0.01)[:, np.newaxis] for i in range(len(all_starting_time)-1): start_t=all_starting_time[i] end_t=all_starting_time[i+1] #print('Time period: ', start_t, 'hours ---', end_t, 'hours') # Chooseing the time period: sel_bool=(t>=start_t-1) & (t<=end_t+1) #if np.sum(sel_bool)<3: # if np.where(sel_bool)[0][0]!=0 and np.where(sel_bool)[0][-1]!=len(sel_bool)-1: # sel_bool[np.where(sel_bool)[0][0]-1]=True # sel_bool[np.where(sel_bool)[0][-1]+1]=True # elif np.where(sel_bool)[0][0]!=0: # sel_bool[np.where(sel_bool)[0][0]-1]=True # elif np.where(sel_bool)[0][-1]!=len(sel_bool)-1: # sel_bool[np.where(sel_bool)[0][-1]+1]=True if np.sum(sel_bool)>=2: sel_t=t[sel_bool] sel_X=X[sel_bool] #print(sel_t, sel_X) fit_bool=(t_1>=start_t-1) & (t_1<=end_t+1) sel_t_1=t_1[fit_bool] (dr, pre_X_1, ci)=myLinearRegression_CB( sel_t, np.log2(sel_X), sel_t_1) all_doubling_rates.append(dr) all_fit_time.append(sel_t_1) all_fit_cell_density.append(2**pre_X_1) all_fit_conf_band.append(2**ci) print('Doubling rate:', dr, 'doubling/hour') print('\n') else: print('No data point in this time period, not fitting.') return (all_doubling_rates, all_fit_time, all_fit_cell_density, all_fit_conf_band) def growth_death_rate_decision(all_fit_cell_density, all_fit_time, all_doubling_rates): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ #all_starting_time=phases_points all_acrossing_orders=[] for i in range(len(all_fit_cell_density)): start_t=all_fit_time[i][0] end_t=all_fit_time[i][-1] print('\nTime period: ', start_t, 'hours ---', end_t, 'hours') afc = all_fit_cell_density[i] acrossing_orders=np.log10(afc[-1])-np.log10(afc[0]) all_acrossing_orders.append(acrossing_orders) print('Doubling rate:', all_doubling_rates[i], 'doubling/hour') print('Number of orders acrossing:', acrossing_orders) selected_doubling_rate=0 selected_fit_time=0 selected_fit_cell_density=all_fit_cell_density[0][0] selected_doubling_rate_d=0 selected_fit_time_d=all_fit_time[-1][-1] selected_fit_cell_density_d=all_fit_cell_density[-1][-1] #Growth phase: if max(all_acrossing_orders)>0: selected_i=np.argmax(all_acrossing_orders) selected_doubling_rate=all_doubling_rates[selected_i] selected_fit_time=all_fit_time[selected_i] selected_fit_cell_density=all_fit_cell_density[selected_i] #Death phase: if min(all_acrossing_orders)<0: selected_i_d=np.argmin(all_acrossing_orders) selected_doubling_rate_d=all_doubling_rates[selected_i_d] selected_fit_time_d=all_fit_time[selected_i_d] selected_fit_cell_density_d=all_fit_cell_density[selected_i_d] return (selected_doubling_rate, selected_fit_time, selected_fit_cell_density, selected_doubling_rate_d, selected_fit_time_d, selected_fit_cell_density_d) def fit_growth_curve(time, cell_density, one_order=10, decision_tree_depth=1): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ t1,X1=preprocessing_growth_curve(time, cell_density) phases_points=phase_seperations(t1, X1, max_depth=decision_tree_depth) print(phases_points) (all_doubling_rates, all_fit_time, all_fit_cell_density, all_fit_conf_band)=phases_exponential_fit(phases_points, t1, X1, one_order) (selected_doubling_rate, selected_fit_time, selected_fit_cell_density, selected_doubling_rate_d, selected_fit_time_d, selected_fit_cell_density_d)=growth_death_rate_decision( all_fit_cell_density, all_fit_time, all_doubling_rates) return (all_fit_time, all_fit_cell_density, all_fit_conf_band, selected_doubling_rate, selected_fit_time, selected_fit_cell_density, selected_doubling_rate_d, selected_fit_time_d, selected_fit_cell_density_d) ``` # Importing the file ``` # datetime object containing current date and time now = datetime.now() #print("now =", now) dt_string = now.strftime("%Y-%m-%d-%H_%M_%S") print('Creating a time stamp:') print("YYYY-MM-DD-hh_mm_ss =", dt_string) output_folder=input_file.split('.xlsx')[0]+'/' print('I received your input data from: '+input_file) print('The output will be stored in the folder called: '+output_folder+'\n.\n.\n.') if os.path.exists(output_folder)==False: os.mkdir(output_folder) #Read the data df=pd.read_excel( input_file, sheet_name='Data').fillna(method='ffill') df.columns=df.columns.str.strip() file_data_frame=df[['Strain', 'Replicate', 'Cell density', 'Time', 'Condition']] file_data_units=pd.read_excel(input_file, sheet_name='Units', index_col=0).fillna(' ') print('Here is how the growth curves data looks like:') print(file_data_frame) print('\n.\n.\n.') print('Here are the units for the columns:') print(file_data_units) print('\n.\n.\n.') condition_unit=file_data_units.loc['Condition'].values[0] time_unit=str(file_data_units.loc['Time'].values[0]) cell_density_unit=str(file_data_units.loc['Cell density'].values[0]) ``` # Fit the data and get growth/death rates. ``` output_data_indices=file_data_frame.groupby( ['Strain','Replicate','Condition'] ).size().reset_index().rename(columns={0:'count'} )[['Strain','Replicate','Condition']] strains_conditions=output_data_indices.groupby(['Strain','Condition'] ).size().reset_index()[['Strain','Condition']] output_data_indices['Growth: Doubling rate']=0 output_data_indices['Death: Doubling rate']=0 output_data_indices=output_data_indices.astype(object) output_data_indices=output_data_indices.sort_values(by=['Strain','Condition']) strains=np.unique(strains_conditions['Strain']) row_num=len(strains) col_num=np.int(np.ceil(len(strains_conditions)/len(strains))) %matplotlib inline plt.figure(figsize=(col_num*2+1, row_num*2+1)) plot_j=1 previous_condition=output_data_indices['Condition'].values[0] plt.subplot(row_num, col_num, plot_j) color_i=0 plt.title(str(output_data_indices['Strain'].values[0])+'\n' +str(output_data_indices['Condition'].values[0])+' ' +condition_unit) plt.ylabel(cell_density_unit) plt.xlabel(time_unit) for i in output_data_indices.index: target_gr_index=output_data_indices.loc[i] target_growth_curve_df = file_data_frame[ (file_data_frame['Strain']==target_gr_index['Strain'])& (file_data_frame['Condition']==target_gr_index['Condition']) & (file_data_frame['Replicate']==target_gr_index['Replicate'])] #print('\n\nStrain:', target_gr_index['Strain'], # '\t Condition:',str(target_gr_index['Condition'])+' '+condition_unit, # '\t Replicate:',str(target_gr_index['Replicate'])) time=target_growth_curve_df.loc[:,'Time'].values cell_density=target_growth_curve_df.loc[:,'Cell density'].values #print('time=', time) #print('cell density=', 'cell_density') if target_gr_index['Condition']!=previous_condition: plt.yscale('log') plt.ylim(10**np.floor(np.log10(np.min(file_data_frame['Cell density']))-1), 10**np.ceil(np.log10(np.max(file_data_frame['Cell density']))+1)) plt.legend() #plt.xlim(np.floor(np.min(file_data_frame['Time'])), # np.ceil(np.max(file_data_frame['Time']))) color_i=0 plot_j+=1 plt.subplot(row_num, col_num, plot_j) plt.title(str(target_gr_index['Strain'])+'\n' +str(target_gr_index['Condition'])+' ' +condition_unit) plt.ylabel(cell_density_unit) plt.xlabel(time_unit) if len(cell_density)>4: (all_fit_time, all_fit_cell_density, all_fit_conf_band, selected_doubling_rate, selected_fit_time, selected_fit_cell_density, selected_doubling_rate_d, selected_fit_time_d, selected_fit_cell_density_d)=fit_growth_curve( time, cell_density, one_order=2, decision_tree_depth=1) output_data_indices.loc[i,'Growth: Doubling rate']=selected_doubling_rate output_data_indices.loc[i,'Death: Doubling rate']=selected_doubling_rate_d for k in range(len(all_fit_time)): #plt.plot(all_fit_time[i], all_fit_cell_density[i], 'k--') #plt.fill_between(all_fit_time[k], # all_fit_cell_density[k]*(all_fit_conf_band[k]), # all_fit_cell_density[k]/(all_fit_conf_band[k]), # color=colormap(color_i), alpha=0.1) plt.plot(selected_fit_time, selected_fit_cell_density, '-', color=colormap(color_i), linewidth=2) plt.plot(selected_fit_time_d, selected_fit_cell_density_d, '--', color=colormap(color_i), linewidth=1) elif len(cell_density)>2: x=time y=np.log2(cell_density) x_fit = np.arange(0.0, x[-1], 0.01)[:, np.newaxis] (doubling_rate, pre_y, ci) = myLinearRegression_CB(x, y, x_fit, one_order=10) #plt.fill_between(x_fit, # pre_y*ci, # pre_y/ci, # color=colormap(color_i), alpha=0.1) if doubling_rate>0: output_data_indices.loc[i,'Growth: Doubling rate']=doubling_rate plt.plot(x_fit, pre_y, '-', color=colormap(color_i), linewidth=2) else: output_data_indices.loc[i,'Death: Doubling rate']=doubling_rate plt.plot(x_fit, pre_y, '--', color=colormap(color_i), linewidth=1) elif len(cell_density)==2: x=time y=np.log2(cell_density) doubling_rate=(y[1]-y[0])/(x[1]-x[0]) output_data_indices.loc[i,'Growth: Doubling rate']=doubling_rate if doubling_rate>0: output_data_indices.loc[i,'Growth: Doubling rate']=doubling_rate plt.plot(x, y, '-', color=colormap(color_i), linewidth=2) else: output_data_indices.loc[i,'Death: Doubling rate']=doubling_rate plt.plot(x, y, '--', color=colormap(color_i), linewidth=1) plt.plot(time, cell_density,'o',alpha=0.3, color=colormap(color_i), label=output_data_indices.loc[i]['Replicate']) color_i+=1 previous_condition=output_data_indices.loc[i]['Condition'] plt.yscale('log') plt.ylim(10**np.floor(np.log10(np.min(file_data_frame['Cell density']))-1), 10**np.ceil(np.log10(np.max(file_data_frame['Cell density']))+1)) #plt.xlim(np.floor(np.min(file_data_frame['Time'])), # np.ceil(np.max(file_data_frame['Time']))) plt.legend() plt.tight_layout() output_file_string=output_folder+'1_Data_fit_visualization_'+dt_string+'.pdf' plt.savefig(output_file_string) print('output file saved:'+output_file_string) plt.show() file_data_frame[(file_data_frame['Condition']==41.5) & (file_data_frame['Replicate']==2)]['Cell density'].values ``` # Plotting growth rates according to different parameters ``` !pip install XlsxWriter import xlsxwriter growth_rates_output_df=output_data_indices growth_rates_output_df[ 'Growth: Specific rate' ]=growth_rates_output_df[ 'Growth: Doubling rate' ]*np.log(2) growth_rates_output_df[ 'Death: Specific rate' ]=growth_rates_output_df[ 'Death: Doubling rate' ]*np.log(2) growth_rates_output_units=file_data_units for c in growth_rates_output_df.columns: if 'Specific' in c: growth_rates_output_units.loc[c, 'Unit']='1/'+time_unit elif 'Doubling' in c: growth_rates_output_units.loc[c, 'Unit']='doubling/'+time_unit else: growth_rates_output_units.loc[c, 'Unit']=' ' #growth_rates_output_df['Condition']=growth_rates_output_df['Condition'].astype(str)+' degree C' #conditions_unique=np.sort(np.unique(growth_rates_output_df['Condition'])) #condition_dict=dict(zip(conditions_unique, range(len(conditions_unique)))) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter(output_folder+'Growth_rates_table_'+dt_string+'.xlsx', engine='xlsxwriter') # Write each dataframe to a different worksheet. growth_rates_output_df.to_excel(writer, sheet_name='Growth rates') growth_rates_output_units.to_excel(writer, sheet_name='Unit') file_data_frame.to_excel(writer, sheet_name='Data') # Close the Pandas Excel writer and output the Excel file. writer.save() %matplotlib inline fig, ax = plt.subplots(constrained_layout=True, figsize=(8,4)) ri=0 all_targets=np.unique(growth_rates_output_df['Strain'].values) all_scatter_x=[] all_scatter_y=[] all_scatter_c=[] for ri in range(len(all_targets)): target=all_targets[ri] plot_box_df=growth_rates_output_df[growth_rates_output_df['Strain']==target] jittering_array=[] for k in range(len(plot_box_df)): jittering_array.append(ri+0.2*(random()-0.5)) all_scatter_x=np.r_[all_scatter_x, jittering_array] all_scatter_y=np.r_[all_scatter_y, plot_box_df['Growth: Specific rate'].values] all_scatter_c=np.r_[all_scatter_c, plot_box_df['Condition'].values] bp = ax.boxplot(plot_box_df['Growth: Specific rate'], positions=[ri]) #ax.set_xticklabels(all_targets) #for element in ['boxes', 'whiskers', 'means', 'medians', 'caps']: # plt.setp(bp[element], color=colormap(ri)) ax.plot(range(len(all_targets)), np.zeros(len(all_targets)), 'k--', alpha=0.5) ax.set_xticklabels(all_targets) #xticks=np.array(ax.get_xticklabels(), dtype=object) #for ri in range(len(xticks)): # xticks[ri].set_color(colormap(ri)) try: all_scatter_c=all_scatter_c.astype(float) sc = ax.scatter(all_scatter_x, all_scatter_y, c=all_scatter_c, alpha=0.8, cmap='coolwarm') cbar=fig.colorbar(sc) except: print('Conditions are not numerical values.') conditions_unique=np.sort(np.unique(growth_rates_output_df['Condition'])) condition_dict=dict(zip(conditions_unique, range(len(conditions_unique)))) c_index=np.array([condition_dict[all_scatter_c[i]] for i in range(len(all_scatter_c))]) sc = ax.scatter(all_scatter_x, all_scatter_y, c=c_index, alpha=0.8, cmap='jet') cbar=fig.colorbar(sc) cbar.ax.set_yticklabels(conditions_unique) cbar.ax.set_ylabel(condition_unit) secax = ax.secondary_yaxis('right', functions=(lambda x: x / np.log(2), lambda x: x * np.log(2))) ax.set_ylabel('Specific growth rate (1/'+time_unit+')') secax.set_ylabel('Doubling rate (doubling/'+time_unit+')') output_file_string=output_folder+'2_Strain_growth_boxplot_'+dt_string+'.pdf' plt.savefig(output_file_string) print('output file saved:'+output_file_string) plt.show() # For testing use #growth_rates_output_df[ # 'Condition str']=growth_rates_output_df[ # 'Condition'].astype(str)+' degree C' layer_1='Strain' #layer_2='Condition str' layer_2='Condition' all_targets=np.unique(growth_rates_output_df[layer_1].values) numerical_flag=True %matplotlib inline fig, ax = plt.subplots(constrained_layout=True, figsize=(8,4)) shapes=['o', '^', 's', '>', 'D', 'd', '<'] try: growth_rates_output_df[ layer_2]=growth_rates_output_df[ layer_2].astype(float) for ri in range(len(all_targets)): target=all_targets[ri] plot_df=growth_rates_output_df[growth_rates_output_df[layer_1]==target] strain_df=plot_df[[layer_2, 'Growth: Specific rate']].astype(float) mean_GR_df=strain_df.groupby(layer_2).mean() min_GR_df=strain_df.groupby(layer_2).min() max_GR_df=strain_df.groupby(layer_2).max() layer_2_values=strain_df[layer_2].values fit_layer_2=np.arange(np.min(layer_2_values), np.max(layer_2_values), 0.01) f = interp1d(mean_GR_df.index, mean_GR_df['Growth: Specific rate'], kind='quadratic') f_min = interp1d(mean_GR_df.index, min_GR_df['Growth: Specific rate'], kind='quadratic') f_max = interp1d(mean_GR_df.index, max_GR_df['Growth: Specific rate'], kind='quadratic') ax.fill_between(fit_layer_2, f_min(fit_layer_2),f_max(fit_layer_2), color=colormap(ri), alpha=0.1) ax.plot(fit_layer_2, f(fit_layer_2), '-',linewidth=2, color=colormap(ri)) ax.plot(strain_df[layer_2], strain_df['Growth: Specific rate'], shapes[ri], alpha=0.5, label=target) except: print(layer_2+' is not numerical') growth_rates_output_df[ layer_2]=growth_rates_output_df[ layer_2].astype(str) numerical_flag=False layer_1_array=np.unique(growth_rates_output_df[layer_1].values) layer_1_dict=dict(zip(layer_1_array, range(len(layer_1_array)))) layer_2_array=np.unique(growth_rates_output_df[layer_2].values) layer_2_dict=dict(zip(layer_2_array, range(len(layer_2_array)))) growth_rates_output_df[layer_1+' index']=[layer_1_dict[s] for s in growth_rates_output_df[layer_1]] growth_rates_output_df[layer_2+' index']=[layer_2_dict[s] for s in growth_rates_output_df[layer_2]] growth_rates_output_df['Visualization X' ]=growth_rates_output_df[layer_2+' index' ]*10+5/len(layer_1_array)*growth_rates_output_df[layer_1+' index'] growth_rates_output_df['Visualization X jittering' ]=[random()-0.5 for i in range(len(growth_rates_output_df.index))] for j in range(len(layer_1_array)): s=layer_1_array[j] plot_df=growth_rates_output_df[growth_rates_output_df[layer_1]==s] for c in layer_2_array: plot_box_df=plot_df[plot_df[layer_2]==c] bp = ax.boxplot(plot_box_df['Growth: Specific rate'], positions=[plot_box_df['Visualization X'].values[0]], widths=10/len(layer_1_array)) for element in ['boxes', 'whiskers', 'means', 'medians', 'caps']: plt.setp(bp[element], color=colormap(j)) ax.scatter(plot_df['Visualization X']+ 2/len(layer_1_array)*plot_df['Visualization X jittering'], plot_df['Growth: Specific rate'],s=50, label=s, alpha=0.5, marker=shapes[j%len(shapes)]) ax.set_xticks(np.unique(plot_df['Visualization X'].values)) ax.set_xticklabels(layer_2_array, rotation=90) secax = ax.secondary_yaxis('right', functions=(lambda x: x / np.log(2), lambda x: x * np.log(2))) secax.set_ylabel('Doubling rate (doubling/'+time_unit+')') ax.set_ylabel('Specific growth rate (1/'+time_unit+')') ax.set_xlabel(condition_unit) #if numerical_flag==True: plt.legend() output_file_string=output_folder+'3_Condition_growth_plot_'+dt_string+'.pdf' plt.savefig(output_file_string) plt.show() ``` # Zip the output folder ``` !zip -r $input_file_name'.zip' $input_file_name ```
github_jupyter
# Transformer Network Application: Named-Entity Recognition Welcome to Week 4's first ungraded lab. In this notebook you'll explore one application of the transformer architecture that you built in the previous assignment. **After this assignment you'll be able to**: * Use tokenizers and pre-trained models from the HuggingFace Library. * Fine-tune a pre-trained transformer model for Named-Entity Recognition ## Table of Contents - [Packages](#0) - [1 - Named-Entity Recogniton to Process Resumes](#1) - [1.1 - Data Cleaning](#1-1) - [1.2 - Padding and Generating Tags](#1-2) - [1.3 - Tokenize and Align Labels with 🤗 Library](#1-3) - [Exercise 1 - tokenize_and_align_labels](#ex-1) - [1.4 - Optimization](#1-4) <a name='0'></a> ## Packages Run the following cell to load the packages you'll need. ``` import pandas as pd import tensorflow as tf import json import random import logging import re ``` <a name='1'></a> ## 1 - Named-Entity Recogniton to Process Resumes When faced with a large amount of unstructured text data, named-entity recognition (NER) can help you detect and classify important information in your dataset. For instance, in the running example "Jane vists Africa in September", NER would help you detect "Jane", "Africa", and "September" as named-entities and classify them as person, location, and time. * You will use a variation of the Transformer model you built in the last assignment to process a large dataset of resumes. * You will find and classify relavent information such as the companies the applicant worked at, skills, type of degree, etc. <a name='1-1'></a> ### 1.1 - Dataset Cleaning In this assignment you will optimize a Transformer model on a dataset of resumes. Take a look at how the data you will be working with are structured. ``` df_data = pd.read_json("ner.json", lines=True) df_data = df_data.drop(['extras'], axis=1) df_data['content'] = df_data['content'].str.replace("\n", " ") df_data.head() df_data.iloc[0]['annotation'] def mergeIntervals(intervals): sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0]) merged = [] for higher in sorted_by_lower_bound: if not merged: merged.append(higher) else: lower = merged[-1] if higher[0] <= lower[1]: if lower[2] is higher[2]: upper_bound = max(lower[1], higher[1]) merged[-1] = (lower[0], upper_bound, lower[2]) else: if lower[1] > higher[1]: merged[-1] = lower else: merged[-1] = (lower[0], higher[1], higher[2]) else: merged.append(higher) return merged def get_entities(df): entities = [] for i in range(len(df)): entity = [] for annot in df['annotation'][i]: try: ent = annot['label'][0] start = annot['points'][0]['start'] end = annot['points'][0]['end'] + 1 entity.append((start, end, ent)) except: pass entity = mergeIntervals(entity) entities.append(entity) return entities df_data['entities'] = get_entities(df_data) df_data.head() def convert_dataturks_to_spacy(dataturks_JSON_FilePath): try: training_data = [] lines=[] with open(dataturks_JSON_FilePath, 'r') as f: lines = f.readlines() for line in lines: data = json.loads(line) text = data['content'].replace("\n", " ") entities = [] data_annotations = data['annotation'] if data_annotations is not None: for annotation in data_annotations: #only a single point in text annotation. point = annotation['points'][0] labels = annotation['label'] # handle both list of labels or a single label. if not isinstance(labels, list): labels = [labels] for label in labels: point_start = point['start'] point_end = point['end'] point_text = point['text'] lstrip_diff = len(point_text) - len(point_text.lstrip()) rstrip_diff = len(point_text) - len(point_text.rstrip()) if lstrip_diff != 0: point_start = point_start + lstrip_diff if rstrip_diff != 0: point_end = point_end - rstrip_diff entities.append((point_start, point_end + 1 , label)) training_data.append((text, {"entities" : entities})) return training_data except Exception as e: logging.exception("Unable to process " + dataturks_JSON_FilePath + "\n" + "error = " + str(e)) return None def trim_entity_spans(data: list) -> list: """Removes leading and trailing white spaces from entity spans. Args: data (list): The data to be cleaned in spaCy JSON format. Returns: list: The cleaned data. """ invalid_span_tokens = re.compile(r'\s') cleaned_data = [] for text, annotations in data: entities = annotations['entities'] valid_entities = [] for start, end, label in entities: valid_start = start valid_end = end while valid_start < len(text) and invalid_span_tokens.match( text[valid_start]): valid_start += 1 while valid_end > 1 and invalid_span_tokens.match( text[valid_end - 1]): valid_end -= 1 valid_entities.append([valid_start, valid_end, label]) cleaned_data.append([text, {'entities': valid_entities}]) return cleaned_data data = trim_entity_spans(convert_dataturks_to_spacy("ner.json")) from tqdm.notebook import tqdm def clean_dataset(data): cleanedDF = pd.DataFrame(columns=["setences_cleaned"]) sum1 = 0 for i in tqdm(range(len(data))): start = 0 emptyList = ["Empty"] * len(data[i][0].split()) numberOfWords = 0 lenOfString = len(data[i][0]) strData = data[i][0] strDictData = data[i][1] lastIndexOfSpace = strData.rfind(' ') for i in range(lenOfString): if (strData[i]==" " and strData[i+1]!=" "): for k,v in strDictData.items(): for j in range(len(v)): entList = v[len(v)-j-1] if (start>=int(entList[0]) and i<=int(entList[1])): emptyList[numberOfWords] = entList[2] break else: continue start = i + 1 numberOfWords += 1 if (i == lastIndexOfSpace): for j in range(len(v)): entList = v[len(v)-j-1] if (lastIndexOfSpace>=int(entList[0]) and lenOfString<=int(entList[1])): emptyList[numberOfWords] = entList[2] numberOfWords += 1 cleanedDF = cleanedDF.append(pd.Series([emptyList], index=cleanedDF.columns ), ignore_index=True ) sum1 = sum1 + numberOfWords return cleanedDF cleanedDF = clean_dataset(data) ``` Take a look at your cleaned dataset and the categories the named-entities are matched to, or 'tags'. ``` cleanedDF.head() ``` <a name='1-2'></a> ### 1.2 - Padding and Generating Tags Now, it is time to generate a list of unique tags you will match the named-entities to. ``` unique_tags = set(cleanedDF['setences_cleaned'].explode().unique())#pd.unique(cleanedDF['setences_cleaned'])#set(tag for doc in cleanedDF['setences_cleaned'].values.tolist() for tag in doc) tag2id = {tag: id for id, tag in enumerate(unique_tags)} id2tag = {id: tag for tag, id in tag2id.items()} unique_tags ``` Next, you will create an array of tags from your cleaned dataset. Oftentimes your input sequence will exceed the maximum length of a sequence your network can process. In this case, your sequence will be cut off, and you need to append zeroes onto the end of the shortened sequences using this [Keras padding API](https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/sequence/pad_sequences). ``` from tensorflow.keras.preprocessing.sequence import pad_sequences MAX_LEN = 512 labels = cleanedDF['setences_cleaned'].values.tolist() tags = pad_sequences([[tag2id.get(l) for l in lab] for lab in labels], maxlen=MAX_LEN, value=tag2id["Empty"], padding="post", dtype="long", truncating="post") tags ``` <a name='1-3'></a> ### 1.3 - Tokenize and Align Labels with 🤗 Library Before feeding the texts to a Transformer model, you will need to tokenize your input using a [🤗 Transformer tokenizer](https://huggingface.co/transformers/main_classes/tokenizer.html). It is crucial that the tokenizer you use must match the Transformer model type you are using! In this exercise, you will use the 🤗 [DistilBERT fast tokenizer](https://huggingface.co/transformers/model_doc/distilbert.html), which standardizes the length of your sequence to 512 and pads with zeros. Notice this matches the maximu length you used when creating tags. ``` from transformers import DistilBertTokenizerFast #, TFDistilBertModel tokenizer = DistilBertTokenizerFast.from_pretrained('tokenizer/') ``` Transformer models are often trained by tokenizers that split words into subwords. For instance, the word 'Africa' might get split into multiple subtokens. This can create some misalignment between the list of tags for the dataset and the list of labels generated by the tokenizer, since the tokenizer can split one word into several, or add special tokens. Before processing, it is important that you align the lists of tags and the list of labels generated by the selected tokenizer with a `tokenize_and_align_labels()` function. <a name='ex-1'></a> ### Exercise 1 - tokenize_and_align_labels Implement `tokenize_and_align_labels()`. The function should perform the following: * The tokenizer cuts sequences that exceed the maximum size allowed by your model with the parameter `truncation=True` * Aligns the list of tags and labels with the tokenizer `word_ids` method returns a list that maps the subtokens to the original word in the sentence and special tokens to `None`. * Set the labels of all the special tokens (`None`) to -100 to prevent them from affecting the loss function. * Label of the first subtoken of a word and set the label for the following subtokens to -100. ``` label_all_tokens = True def tokenize_and_align_labels(tokenizer, examples, tags): tokenized_inputs = tokenizer(examples, truncation=True, is_split_into_words=False, padding='max_length', max_length=512) labels = [] for i, label in enumerate(tags): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: # Special tokens have a word id that is None. We set the label to -100 so they are automatically # ignored in the loss function. if word_idx is None: label_ids.append(-100) # We set the label for the first token of each word. elif word_idx != previous_word_idx: label_ids.append(label[word_idx]) # For the other tokens in a word, we set the label to either the current label or -100, depending on # the label_all_tokens flag. else: label_ids.append(label[word_idx] if label_all_tokens else -100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs ``` Now that you have tokenized inputs, you can create train and test datasets! ``` test = tokenize_and_align_labels(tokenizer, df_data['content'].values.tolist(), tags) train_dataset = tf.data.Dataset.from_tensor_slices(( test['input_ids'], test['labels'] )) test['labels'][0] ``` <a name='1-4'></a> ### 1.4 - Optimization Fantastic! Now you can finally feed your data into into a pretrained 🤗 model. You will optimize a DistilBERT model, which matches the tokenizer you used to preprocess your data. Try playing around with the different hyperparamters to improve your results! ``` from transformers import TFDistilBertForTokenClassification model = TFDistilBertForTokenClassification.from_pretrained('model/', num_labels=len(unique_tags)) optimizer = tf.keras.optimizers.Adam(learning_rate=1e-5) model.compile(optimizer=optimizer, loss=model.compute_loss, metrics=['accuracy']) # can also use any keras loss fn model.fit(train_dataset.shuffle(1000).batch(16), epochs=3, batch_size=16) ``` ### Congratulations! #### Here's what you should remember - Named-entity recognition (NER) detects and classifies named-entities, and can help process resumes, customer reviews, browsing histories, etc. - You must preprocess text data with the corresponding tokenizer to the pretrained model before feeding your input into your Transformer model
github_jupyter
# Annotated Graph Transformer ## Prelim ``` import torch import dgl from torch import nn import torch.nn.functional as F from dgl import function as fn import numpy as np import seaborn as sns from matplotlib import pylab as plt from dgl import ops as Fops ``` ## Background ### Feed-Forward Networks with DGL ## Standard Mult-Head Attention using Torch ``` # say we have our three linear embeddings of query, key, and value # it is assumed the dimensions between key and value are equivalent q = torch.randn(10, 4, 30) k = torch.randn(10, 3, 30) v = torch.randn(10, 3, 30) # Attention is generally applied with QK^TV, often with scaling and softmax applied, # as in softmax(scaling * QK^T)V print(torch.matmul(torch.matmul(q, k.transpose(-2, -1)), v).shape) # to do multihead attention, we split the tensor across multiple heads # we first calculate some dimensions batch_size = q.size(0) d_model = q.size(-1) heads = 5 d_k = d_model // heads # else we need to change our embeddings a bit assert d_model % heads == 0 # then we split d_model across multiple heads q_view = q.view(batch_size, -1, heads, d_k) # we then swap the head to the non-matrix (i.e. batch) dimensions using transpose q_view = q_view.transpose(1, 2) # NOTE: it must be done in this was as not to juggle the values # resulting in (batch_size, h, i, d_k) # our aim is to sum across d_k during matrix multiplication, so that (b, h, i, d_k) * (b, h, d_k, j) -> (b, h, i, j) # final matmul with the value results in (b, h, i, j) * (b, h, j, d_k) -> (b, h, j, d_k) q_view = q.view(batch_size, -1, heads, d_k).transpose(1, 2) k_view = k.view(batch_size, -1, heads, d_k).transpose(1, 2) v_view = v.view(batch_size, -1, heads, d_k).transpose(1, 2) z = torch.matmul(q_view, k_view.transpose(-2, -1)) print(z.shape) # the attention as a specific head (e.g. batch=0, head=1) can be found using: print(z[0, 1]) # out final values with attenion applied a = torch.matmul(z, v_view) # which returns us to the original shape a.view(batch_size, -1, heads * d_k).shape import dgl import dgl.function as fn # contains all the built-in optimized message passing and reduce functions. import networkx as nx %matplotlib inline def init_g(d_k): g = dgl.graph(([0, 0, 2, 3], [1, 2, 4, 4])) n = g.number_of_nodes() g.ndata['k'] = torch.randn(n, d_k) g.ndata['q'] = torch.randn(n, d_k) g.ndata['v'] = torch.randn(n, d_k) return g g = init_g(12) nxg = nx.DiGraph(g.to_networkx()) print(g) nx.draw(nxg) ``` ## Utils ``` # plotting utils def to_nxg(g: dgl.DGLGraph) -> nx.DiGraph: nxg = nx.DiGraph(g.to_networkx()) return nxg def plot_graph(g: dgl.DGLGraph, ax=None, prog='neato', **kwargs): nxg = to_nxg(g) pos = nx.nx_agraph.pygraphviz_layout(nxg, prog=prog) nx.draw(nxg, pos=pos, ax=ax, **kwargs) return ax, pos, nxg def attn_to_sparse(g: dgl.DGLGraph, attn: torch.Tensor): n = g.number_of_nodes() i = torch.stack(g.edges()) v = attn x = torch.sparse_coo_tensor(i, v.flatten(), (n, n)) return x def plot_attn(g: dgl.DGLGraph, attn: torch.Tensor, ax=None): x = attn_to_sparse(g, attn) sns.heatmap(x.to_dense().numpy(), ax=ax) def plot_graph_and_attn(g: dgl.DGLGraph, attn: torch.Tensor): fig, axes = plt.subplots(1, 2, figsize=(8, 3)) axes[0].set_title("Graph") axes[1].set_title("Attention") plot_graph(g, ax=axes[0], width=attn.flatten().numpy()) plot_attn(g, attn, ax=axes[1]) ``` ## Attention layer of Graph Transformer The **attention** layer, each node in module learns to assign weights on its incoming edges. For node pair $(i,j)$ with node $x_i,x_j \in \mathbb{R}^n$, the score of connection is as follows: $$ q_j = W_q \cdot x_j \\ k_i = W_k \cdot x_i \\ v_i = W_v \cdot x_i \\ \text{score} = q_j k_i^\top $$ $W_q, W_k, W_v \in \mathbb{R}^{n \times d_k}$ map the representations of x to "query", "key", and "value" space repsectively. These values are three different linear projections of the data. For the "query" case ($W_j$), these are linear projections of source nodes for edges. For "key" and "value", were are linear projections of the destination nodes. The dot product between query source nodes and key destination nodes computes the score of the given connection. $$ \text{Attention}(Q, K, V) = \text{Softmax}\Bigg(\frac{QK^\top}{\sqrt{d_k}}\Bigg)V $$ ### Attention: Using Torch ``` def attention(g): attention_arrs = [] score_arrs = [] q = g.ndata['q'] d_k = q.size(-1) scale = d_k**0.5 n = g.number_of_nodes() for i in range(n): idx = torch.where(g.edges()[1] == i)[0] src = g.edges()[0][idx] dst = g.edges()[1][idx] src = torch.tensor(list(set(src.tolist())), dtype=torch.long) dst = torch.tensor(list(set(dst.tolist())), dtype=torch.long) # dst q = g.ndata['q'][dst] #src k = g.ndata['k'][src] v = g.ndata['v'][src] _z = torch.matmul(q, k.transpose(-2, -1)) score = F.softmax(_z / scale) out = torch.matmul(score, v) if out.size(0) == 0: out = torch.zeros_like(g.ndata['q'][:1]) attention_arrs.append(out) score_arrs.append(score) attention = torch.cat(attention_arrs) score = torch.cat([s.T for s in score_arrs if s.size(0)], 0) return attention, score g = init_g(3) out, attn = attention(g) print(attn) plot_graph_and_attn(g, attn) ``` ### Attention: With standard message passing Now we will walk through the forward propogation using dgl. First, lets create a simple test graph and attach some data to the nodes. Note, however, we cannot appropriately apply edge softmax. ``` # example: applying basic matmul qk^T in dgl # initialize graph g = init_g(3) print(g.edges()) # lets run attention on edges (2, 4), (3, 4) i = torch.tensor([0, 1]) src = g.edges()[0][i] dst = g.edges()[1][i] # we only look at unique edges src = torch.tensor(list(set(src.tolist()))) dst = torch.tensor(list(set(dst.tolist()))) print(src, dst) # filter the data k = g.ndata['k'][src] v = g.ndata['v'][src] q = g.ndata['q'][dst] # apply matmul in non-graph version # for mxn, expect a mxm matrix _z = torch.matmul(q, k.transpose(-2, -1)) print(_z) # dgl version with g.local_scope(): g.apply_edges(fn.v_mul_u('q', 'k', '_z')) print('\nEdge Messages: a \'n_edge x d_model\'') print(g.edata['_z']) print(g.edata['_z'].sum(1)) # typical message passing would take the messages on each edge # and for every node, sum incoming message. For attention, # we just want to sum across d_k. We may want to optimize # this by creating a corresponding kernel to combine this operation. # We therefore create a new user defined function. print("\nNote this is different from the typical message passing paradigm, which sums incoming edges.") with g.local_scope(): g.update_all(fn.v_mul_u('q', 'k', '_z'), fn.sum('_z', 'score')) print(g.ndata['score']) # `v_dot_u` will perform these same operations concisely print("\nHowever, the most concise was is to use the `v_dot_u` operator, followed by sum as this fuses the kernels") with g.local_scope(): g.apply_edges(fn.v_dot_u('q', 'k', '_z')) print(g.edata['_z']) ``` ### Attention: Using Generalized Sampled Dense-Dense Matrix Multiplication (GSDDMM) We can perform this operation using the provided GSDDMM (Generalized Sampled Dense-Dense Matrix Multiplication) operations, which is much more memory efficient that materializing the tensors using standard send and receive. Between the message-passing API and GSpMM/GSDMM, both API are the same efficiency. Note that the above procedure is very inefficient. Firstly, we create a new tensor for every node, secondly, we are materializing new tensors at every step of the computation, and lastly, we perform a concatenation to obtain the final attention tensor. To optimize this procedure, lets use **dgl**. ``` def attention_dgl_gsddmm(g): q = g.ndata['q'] k = g.ndata['k'] v = g.ndata['v'] d_k = q.size(-1) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / d_k**0.5) out = Fops.u_mul_e_sum(g, v, score) return out, score g = init_g(3) out0, attn0 = attention(g) out1, attn1 = attention_dgl_gsddmm(g) assert torch.allclose(out0, out1) assert torch.allclose(attn0, attn1) plot_graph_and_attn(g, attn1) g = init_g(3) q = g.ndata['q'] k = g.ndata['k'] v = g.ndata['v'] d_k = q.size(-1) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / d_k**0.5) print(score.shape) out = Fops.u_mul_e_sum(g, v, score) fig, axes = plt.subplots(1, 6, figsize=(6*4, 3)) axes[0].set_title('query') axes[1].set_title('key') axes[2].set_title('value') axes[3].set_title('q dot k') axes[4].set_title('score') axes[5].set_title('out') sns.heatmap(q, ax=axes[0]) sns.heatmap(k, ax=axes[1]) sns.heatmap(v, ax=axes[2]) sns.heatmap(Fops.v_dot_u(g, q, k), ax=axes[3]) sns.heatmap(score, ax=axes[4]) sns.heatmap(out, ax=axes[5]) plt.show() plot_graph_and_attn(g, score) ``` **Attention with half-complete graph** ``` def init_complete_g(n_nodes, d_k, half=False): edges = torch.combinations(torch.arange(n_nodes), with_replacement=False).T edges = edges[:, :] g = dgl.graph((edges[0], edges[1])) if not half: g.add_edges(edges[1], edges[0]) n = g.number_of_nodes() x = torch.randn(3, n, d_k) * 2. g.ndata['k'] = x[0] g.ndata['q'] = x[1] g.ndata['v'] = x[2] return g g = init_complete_g(10, 7, half=True) out, attn = attention_dgl_gsddmm(g) plot_graph_and_attn(g, attn) ``` ## Multi-Head Attention layer of Graph Transformer ### Multi-head attention using Torch ``` from torch import nn def torch_multihead_attention(q, k, v, h): d_model = k.size(-1) d_k = d_model // h nbatches = q.size(0) assert d_model % h == 0 assert len(q.shape) == 3 assert q.size(0) == k.size(0) assert q.size(0) == v.size(0) assert k.shape == v.shape def create_head(x): return x.view(nbatches, -1, h, d_k).transpose(1, 2) q = create_head(q) k = create_head(k) v = create_head(v) attn = F.softmax(torch.matmul(q, k.transpose(-2, -1)) * d_k**-0.5) out = torch.matmul(attn, v).transpose(1, 2).contiguous().view(nbatches, -1, d_model) return out, attn d_model = 12 q = torch.randn(1, 13, d_model) k = torch.randn(1, 7, d_model) v = torch.randn(1, 7, d_model) out, attn = torch_multihead_attention(q, k, v, 4) fig, axes = plt.subplots(2, 2, figsize=(7, 5)) for i in range(attn.size(1)): ax = axes.flatten()[i] sns.heatmap(attn[0, i], ax=ax) plt.show() print(out.shape) sns.heatmap(out[0]) ``` ### Multi-head attention: Using DGL/GSDDMM ``` q = torch.randn(10, 12) k = torch.randn(9, 12) v = k g = dgl.graph(([0, 0, 1, 2], [1, 1, 3, 3])) q = torch.randn(g.number_of_nodes(), 12) k = torch.randn(g.number_of_nodes(), 12) def head(x): return x.view(x.size(0), -1, 4, 3).transpose(1, 2) def multihead_attention_dgl_gsddmm(g, h): d_model = g.ndata['q'].size(-1) def head(x): return x.view(x.size(0), -1, h, d_model // h).transpose(1, 2) q = head(g.ndata['q']) k = head(g.ndata['k']) v = head(g.ndata['v']) d_k = q.size(-1) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / d_k**0.5) out = Fops.u_mul_e_sum(g, v, score) out = out.transpose(1, 2).view(g.number_of_nodes(), d_model) score = score.view(score.size(0), h, -1) return out, score g = init_complete_g(10, 12, half=True) out, attn = attention_dgl_gsddmm(g) print(out.shape) print(attn.shape) mh_out, mh_attn = multihead_attention_dgl_gsddmm(g, 4) print(mh_out.shape) print(mh_attn.shape) fig, axes = plt.subplots(2, 2, figsize=(7, 5)) for i in range(mh_attn.size(1)): ax = axes.flatten()[i] _attn = attn_to_sparse(g, mh_attn[:, i]).to_dense().numpy() sns.heatmap(_attn, ax=ax) ``` ## Graph Transformer Modules We can quickly implement the initial embedding of the MultiHeadAttention. Right now, we are leaving out the more complicated forward propogation. We will walk through that implementation next. ### Multi-Head Graph Attention ``` from copy import deepcopy import matplotlib as mpl from matplotlib import cm def clones(net, N): return [deepcopy(net) for _ in range(N)] def rand_g(n_nodes, n_edges): g = dgl.graph(([], [])) g.add_nodes(n_nodes) edges = torch.randint(0, n_nodes, (2, n_edges)) g.add_edges(*edges) return g class MultiHeadAttention(nn.Module): def __init__(self, dim_model, h): super().__init__() assert dim_model % h == 0 self.h = h self.dim_model = dim_model self.d_k = dim_model // h self.linears = clones(nn.Linear(dim_model, dim_model), 4) self.attn = None def _view_head(self, x): return x.view(x.size(0), -1, self.h, self.d_k).transpose(1, 2) def forward(self, g, query, key, value): q = self._view_head(self.linears[0](query)) k = self._view_head(self.linears[1](key)) v = self._view_head(self.linears[2](value)) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / self.d_k**0.5) out = Fops.u_mul_e_sum(g, v, score) out = out.transpose(1, 2).view(g.number_of_nodes(), self.h * self.d_k) score = score.view(score.size(0), self.h, -1) self.attn = score out = self.linears[3](out) return out def plot_multihead_attention(g, attn, cmap='binary', node_color='k', node_size=30, prog='neato', scale_width=2., min_width=0.3): fig, axes = plt.subplots(2, 4, figsize=(14, 5)) for i in range(attn.size(1)): ax = axes.flatten()[i] ax.set_title("Head {}".format(i)) a = attn[:, i].detach().flatten() _attn = attn_to_sparse(g, a).to_dense().numpy() sns.heatmap(_attn, ax=ax, linewidths=0, cmap=cmap) norm = mpl.colors.Normalize(vmin=0,vmax=1.) edge_colors = cm.get_cmap(cmap)(norm(a)) edges = g.edges() edgelist = [(edges[0][i].item(), edges[1][i].item()) for i in range(g.number_of_edges())] ax, pos, nxg = plot_graph(g, prog=prog, width=a*scale_width + min_width, edge_color=edge_colors, edgelist=edgelist, ax=axes.flatten()[i+4], node_size=node_size, node_color=node_color) # nx.draw_networkx_labels(g, ax=ax, pos=pos, labels={v: v for v in list(range(g.number_of_nodes()))}) def run_multiheadattn_sanity_check(): model = MultiHeadAttention(12, 4) # sanify check g = rand_g(20, 100) x = torch.randn(g.number_of_nodes(), 12) out = model(g, x, x, x) attn = model.attn plot_multihead_attention(g, attn, prog='neato') plt.show() g = init_complete_g(20, 12, half=True) x = torch.randn(g.number_of_nodes(), 12) out = model(g, x, x, x) attn = model.attn plot_multihead_attention(g, attn, prog='neato') plt.show() run_multiheadattn_sanity_check() ``` > So why does the half-complete look like a gradient? Attention is relative to all the incoming nodes. If a node only has one incoming edge (as in the upper left corner), the attention is 1.0. Since we defined a half-complete graph, edges represented in the lower-right corner will have more incoming edges. Thus, those will have less average attention given we randomly initialized input data. ### Position-wise Feed Forward ``` class PositionwiseFeedForward(nn.Module): "Implements FFN equation." def __init__(self, d_model, d_ff, dropout=0.1): super(PositionwiseFeedForward, self).__init__() self.w_1 = nn.Linear(d_model, d_ff) self.w_2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) self.act = nn.ReLU() def forward(self, x): return self.w_2(self.dropout(self.act(self.w_1(x)))) def run_ff_sanity_check(x = torch.randn(10, 12)): m = PositionwiseFeedForward(12, 24) return m(x) run_ff_sanity_check() ``` ### Add and Norm Connection $$ \text{AddNorm}(x) = \text{LayerNorm} \Big( x + \text{Dropout}\big( \text{Layer}(x) \big) \Big) $$ ``` from abc import ABC, abstractmethod from torch import nn from typing import * import torch class SizedModule(ABC) : @abstractmethod def get_size(self) -> int: ... class AddNorm(nn.Module): def __init__(self, size: Optional[int] = None, dropout: float = 0.1, layer: Optional[SizedModule] = None): super().__init__() if size is None and layer is None: return ValueError("Either size or layer must be provided") self.size = size or layer.get_size() self.layer = layer self.norm = nn.LayerNorm(self.size) self.dropout = nn.Dropout(dropout) def forward(self, x, args=None, kwargs=None, layer: Optional[SizedModule] = None): kwargs = kwargs or dict() if args is None: args = (x,) layer = layer or self.layer return self.norm(x + self.dropout(layer(*args, **kwargs))) def run_addnorm_sanity_check(x = torch.randn(10, 12)): return AddNorm(size=12, layer=nn.Linear(12, 12))(x) run_addnorm_sanity_check() ``` ### Embeddings ``` import math class Embeddings(nn.Module): def __init__(self, d_model, vocab): super(Embeddings, self).__init__() self.lut = nn.Embedding(vocab, d_model) self.d_model = d_model def forward(self, x): return self.lut(x) * math.sqrt(self.d_model) def run_embed_sanity_check(): lorem = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """.split() vocab = set(lorem) n_words = len(vocab) vocab_idx = torch.arange(n_words) embed = Embeddings(12, n_words) return embed(vocab_idx) run_embed_sanity_check().shape ``` ### Encoder ``` class EncoderLayer(nn.Module): def __init__(self, size: int, n_heads: int, d_ff: int, dropout=0.1): super().__init__() self.attn = MultiHeadAttention(dim_model=size, h=n_heads) self.layers = nn.ModuleList([ AddNorm(size=size, layer=self.attn, dropout=dropout), AddNorm(size=size, layer=PositionwiseFeedForward(d_model=size, d_ff=d_ff, dropout=dropout)) ]) def forward(self, g, x): x = self.layers[0](x, args=(g, x, x, x)) x = self.layers[1](x) return x class Encoder(nn.Module): def __init__(self, layer: EncoderLayer, N: int): super().__init__() self.N = N self.layers = nn.ModuleList(clones(layer, N)) def forward(self, g, x): for l in self.layers: x = l(g, x) return x def run_encoder_layer_sanity_check(): model = EncoderLayer(12, 4, 32) g = rand_g(20, 40) x = torch.randn(g.number_of_nodes(), 12) return model(g, x) def run_encoder_sanity_check(): model = Encoder(EncoderLayer(12, 4, 32), 4) g = rand_g(20, 40) x = torch.randn(g.number_of_nodes(), 12) return model(g, x) run_encoder_layer_sanity_check() run_encoder_sanity_check().shape ``` ### Decoder ``` class DecoderLayer(nn.Module): def __init__(self, size: int, n_heads: int, d_ff: int, dropout=0.1): super().__init__() self.self_attn = MultiHeadAttention(dim_model=size, h=n_heads) self.src_attn = MultiHeadAttention(dim_model=size, h=n_heads) self.layers = nn.ModuleList([ AddNorm(size=size, layer=self.self_attn, dropout=dropout), AddNorm(size=size, layer=self.src_attn, dropout=dropout), AddNorm(size=size, layer=PositionwiseFeedForward(d_model=size, d_ff=d_ff, dropout=dropout)) ]) def forward(self, g, x, m): x = self.layers[0](x, args=(g, x, x, x)) x = self.layers[1](x, args=(g,), kwargs=dict(query=x, key=m, value=m)) x = self.layers[2](x) return x class Decoder(nn.Module): def __init__(self, layer: DecoderLayer, N: int): super().__init__() self.N = N self.layers = nn.ModuleList(clones(layer, N)) def forward(self, g, x, m): for l in self.layers: x = l(g, x, m) return x def run_decoder_layer_sanity_check(): model = DecoderLayer(12, 4, 32) g = rand_g(20, 40) x = torch.randn(g.number_of_nodes(), 12) m = torch.randn(g.number_of_nodes(), 12) return model(g, x, m) def run_decoder_sanity_check(): model = Decoder(DecoderLayer(12, 4, 32), 4) g = rand_g(20, 40) x = torch.randn(g.number_of_nodes(), 12) m = torch.randn(g.number_of_nodes(), 12) return model(g, x, m) run_decoder_layer_sanity_check() run_decoder_sanity_check().shape ``` ### Positional Encoding $$ PE_{(pos,2i)} = \sin \big( pos / 10000^{2i / d_{\text{model}}} \big) \\ PE_{(pos,2i+1)} = \cos \big( pos / 10000^{2i / d_{\text{model}}} \big) $$ ``` max_len = 500 d_model = 12 pe = torch.zeros(max_len, d_model) pos = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) / d_model * -math.log(10000.0)) pe[:, 0::2] = torch.sin(pos * div_term) pe[:, 1::2] = torch.cos(pos * div_term) plt.figure(figsize=(5, 2)) plt.plot(pe.numpy()[:100, 4:7]); class PositionalEncoding(nn.Module): "Implement the PE function." def __init__(self, d_model, dropout, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) # Compute the positional encodings once in log space. pe = torch.zeros(max_len, d_model, requires_grad=False) pos = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) / d_model * -math.log(10000.0)) pe[:, 0::2] = torch.sin(pos * div_term) pe[:, 1::2] = torch.cos(pos * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): with torch.no_grad(): pe = self.pe[:, :x.size(1)] x = x + pe return self.dropout(x) plt.figure(figsize=(12, 2)) pe = PositionalEncoding(20, 0) y = pe.forward(torch.zeros(1, 100, 20)) plt.plot(np.arange(100), y[0, :, 4:8].data.numpy()) plt.legend(["dim %d"%p for p in [4,5,6,7]]) ``` ### Generator ``` class Generator(nn.Module): "Define standard linear + softmax generation step." def __init__(self, d_model, vocab): super(Generator, self).__init__() self.proj = nn.Linear(d_model, vocab) def forward(self, x): return F.log_softmax(self.proj(x), dim=-1) ``` ### EncoderDecoder #### Walkthrough For the language translation task, we will have a set of source language texts and target language texts. Here, we will map tokens within a sentence to node in a graph.The source language sentences can be intepreted as a complete graph, with node_ids corresponding to source vocabulary ids and nodes ordered by the sentence (for positional embedding). Correspondingly, for the target graph, we will have a half-complete graph. In the original paper, the authors used a mask to prevent the decoder from looking at future tokens (i.e. *cheating*). Here, that is implicit in the graph, provided we construct the graph in the correct way. > Notice that there is no cross-segment connections here. Each graph is its own entity. This is a topic for further improvement in Transformer literature. The vanilla Transformer has a fixed *attention span**, in that attention only considers the current sentence or segment. No information can flow between fixed length segments. This is known as *context segmentation*. The Transoformer-XL model [Dai et. al. 2019](https://arxiv.org/abs/1901.02860) tries to solve this by reusing hidden states between segments and using a new positional encoding that is suitable for reused states. The graph structure makes it possible that we can create sparse attention graphs and unique attention architectures. Here, it is fairly straightforward, but the graph NN allows us to go beyond simple masking (as in **Attention is All You Need**) and explore new structures. > Its possible the positional embeddings are no longer necessary IF we were to add another different type of edge to the graph and propogate that information. I do not test this idea here however. This may have relevance to longer attentions spans seen in Transformer-XL ``` # walkthrough of language graph creation import networkx as nx import dgl import torch import itertools def to_tuple(x): return tuple(x) def torch_product(a, b): return torch.stack([torch.stack(x) for x in itertools.product(torch.arange(a), torch.arange(b))]) def iter_node_types(g): visited = set() for x in g.canonical_etypes: n1, e, n2 = x for n in (n1, n2): if n not in visited: yield n visited.add(n) def create_fake_language_graph(src_size=7, dst_size=5): dst_edges = torch.combinations(torch.arange(dst_size)).T src_edges = torch.combinations(torch.arange(src_size), with_replacement=True).T src_edges = torch.cat([src_edges, torch.flip(src_edges, dims=(0,))], dim=1) g = dgl.heterograph({ ('src', 'src', 'src'): tuple(src_edges), ('dst', 'dst', 'dst'): tuple(dst_edges), ('src', 'cross', 'dst'): tuple(torch_product(src_size, dst_size).T) }) return g def hetrograph_to_nxg(g): nxg = nx.DiGraph() for y, ntype in enumerate(iter_node_types(g)): for n in g.nodes(ntype=ntype): node = ntype + '_' + str(n.item()) data = {'id': n, 'ntype': ntype, 'pos': (n.item(), y)} nxg.add_node(node, **data) for src, etype, dst in g.canonical_etypes: edges = torch.stack(g.edges(etype=etype)) for n1, n2 in edges.T: n1 = src + '_' + str(n1.item()) n2 = dst + '_' + str(n2.item()) nxg.add_edge(n1, n2, etype=etype) return nxg def add_alpha(rgb, alpha): colors = [] for _rgb in rgb: if len(_rgb) == 3: _rgb = _rgb + (alpha,) colors.append(_rgb) elif len(_rgb) == 4: _rgb = tuple(list(_rgb)[:-1]) + (alpha,) colors.append(_rgb) else: raise ValueError return colors def draw_nxg_with_pos(G, connectionstyle="arc3,rad=0.1", width=0.1, node_size=100., linewidths=1, node_fill_alpha=0.3, ax=None): scale = 200. pos = {n: (d['pos'][0]*scale, d['pos'][1]*2*scale) for n, d in G.nodes(data=True)} node_colors = [] for n, ndata in G.nodes(data=True): if ndata['ntype'] == 'src': node_color = (0.5, 0, 0) elif ndata['ntype'] == 'dst': node_color = (0, 0.5, 0.5) else: node_color = (0.5, 0.5, 0.5) node_colors.append(node_color) # nx.draw_networkx_nodes(G, pos) nx.draw( G, pos, connectionstyle="arc3,rad=0.2", width=width, node_color=add_alpha(node_colors,node_fill_alpha), node_size=node_size, linewidths=linewidths, edgecolors=node_colors, ax=ax ) # Create fake language graph g = create_fake_language_graph(6, 4) nxg = hetrograph_to_nxg(g) # plot the graph plt.tight_layout() fig = plt.figure() ax = fig.gca() ax.set_title("Language Graph for Translation") ax.text(-50, 175*2, 'Encoder', horizontalalignment='right', fontsize='large') ax.text(-50, 0, 'Decoder', horizontalalignment='right', fontsize='large') ax.text(-50, 100*2, 'Cross\nlanguage\nedges', horizontalalignment='right', verticalalignment='center', fontsize='small') nxg.add_node('out', ntype='out', pos=(4, 0)) ax.text(800, -100, 'next token', horizontalalignment='center', fontsize='small') ax.text(0, -100, '<start>', horizontalalignment='center', fontsize='small') draw_nxg_with_pos(nxg, node_size=200., node_fill_alpha=0.5, width=0.75, ax=ax) plt.show(); fig, axes = plt.subplots(1, 4, figsize=(8, 2)) for i, (a, b) in enumerate([(4, 3), (5, 4), (3, 6), (7, 3)]): g = create_fake_language_graph(a, b) nxg = hetrograph_to_nxg(g) ax=axes.flatten()[i] ax.set_title('segment {}'.format(i), fontsize='small') draw_nxg_with_pos(nxg, node_size=100., node_fill_alpha=0.5, width=0.75, ax=ax) fig.suptitle("Batch of Segments", fontsize=16, verticalalignment='bottom'); ``` #### How does training work? During training, our dataset will likely derive from several translated texts. We will segment the texts (see *context segmentation* problem above for issues associated with this) into *source* and *target* segments, typically at the sentence level. Say for a given sentence pair, we have a source sentence of length $l_{src}$ composed of tokens $s_0 \dots s_{l_{src}}$ and target tokens $t_0 \dots t_{l_{target}}$. To train, we will provide source tokens $s_0 \dots s_{l_{src}}$ and target tokens $t_0 \dots t_{l_{target} - 1}$ (target tokens minus the last token. The goal of the translator will be to predict the last token $t_{l_{target}}$. For the decoder, the first token for all segments is a special `<start>` token. If you've read the "Attention Is All You Need" paper, this is what is meant in the first figure by the output "shifted by one". #### How does inference work? For inference (here, also call the translation task), we will be provided with the source sentence and the goal is to generate the target sentence. To start, we initialize the decode with a special `<start>`. We retrieve a new segment as an output `<start> TOKEN_0`. We feed that output back in to produce `<start> TOKEN_0 TOKEN_1` and we contiue this process (called *autoregressive*) until we get an `<end>` token, designating that the translation is complete. #### The EncoderDecoder Module ``` class EncoderDecoder(nn.Module): def __init__(self, embedding, positional_embedding, encoder, decoder, generator): super().__init__() self.embedding = embedding self.encoder = encoder self.decoder = decoder self.pos_embed = positional_embedding self.generator = generator d_model = 12 h = 4 d_ff = 32 vocab_size = 100 n_encode = 4 n_decode = 4 max_len = 5000 dropout = 0.1 EncoderDecoder( encoder=Encoder(EncoderLayer(d_model, h, d_ff, dropout=dropout), n_encode), decoder=Decoder(DecoderLayer(d_model, h, d_ff, dropout=dropout), n_decode), embedding=Embeddings(d_model, vocab_size), positional_embedding=PositionalEncoding(d_model, dropout=dropout, max_len=max_len), generator=Generator(d_model, vocab_size) ); ``` ## Training Improvements ### Noam Opt (Learning Rate Schedule) ### Label Smoothing # Deep Link Prediction Let us consider how to use attention to perform link prediction. Lets consider the case where we are trying to predict the linkage between a set of categorical 'objects'. One way to do this is to learn an embedding $e$ such that $e_i e_j^{T}$ is the probability of there being a link between object $i$ and $j$. The mathematical operation give us a single number, which we can use to make the linkage prediction. For training, the objective would be to learn the embeddings (perhaps with a dense layer), such that we make the correct predictions. For evaluation, we would take a look at new links and evaluate. ``` objects = ['object1', 'object2'] vocab = set(objects) obj_to_idx = {o: i for i, o in enumerate(vocab)} embedding = nn.Embedding(10, 16) x = torch.tensor([obj_to_idx[o] for o in objects]) i, j = embedding(x) torch.matmul(i.unsqueeze(0), j.unsqueeze(1)).view(-1) ``` Taking a look at how attention works, we can utilize the `q` and `k` vectors to perform this operation. Lets review how attention works below. As you can see, the `v_dot_u` operation performs the correct mathematical operation. We multiply the results with a `v` vector. Basically, here, we take the src and dst tensors and multiply them and add the data to the edges. We then multiply the edges to dst nodes' `v` vector. In essense, the `q`, `k`, and `edges` determines how we adjust the `v` tensor. Hence be learning the right `q` and `k` tenosr, we can learn the degree to which two nodes along an edge should interact. One way to utilize this is to use a complete graph and intepret `q` and `k` as embeddings that determines the degree of interaction. We can use `v` to propogate information through our complete graph. For nodes that are not supposed to interact, the embeddings should be such that the dot product between q and k is low; conversely for interacting nodes, qk should be high. ``` g = init_g(3) q = g.ndata['q'] k = g.ndata['k'] v = g.ndata['v'] d_k = q.size(-1) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / d_k**0.5) print(score.shape) out = Fops.u_mul_e_sum(g, v, score) fig, axes = plt.subplots(1, 6, figsize=(6*4, 3)) axes[0].set_title('query') axes[1].set_title('key') axes[2].set_title('value') axes[3].set_title('q dot k') axes[4].set_title('score') axes[5].set_title('out') sns.heatmap(q, ax=axes[0]) sns.heatmap(k, ax=axes[1]) sns.heatmap(v, ax=axes[2]) sns.heatmap(Fops.v_dot_u(g, q, k), ax=axes[3]) sns.heatmap(score, ax=axes[4]) sns.heatmap(out, ax=axes[5]) plt.show() plot_graph_and_attn(g, score) ``` ### Causal Inference Lets learn the following rules: $$ a \rightarrow b \\ b \rightarrow c $$ ``` events = 'abcdefg' def get_complete_edges(g): """List complete edges of a dgl graph""" def leading_zero(x): yield torch.zeros_like(x[0]) yield from x x = torch.cumsum(g.batch_num_nodes(), 0) all_edges = [] for a, b in zip(leading_zero(x), x): edges = torch.combinations(torch.arange(a, b)) all_edges.append(edges) return torch.cat(all_edges, 0).T def add_complete_edges(g): n1 = g.number_of_nodes() edges = get_complete_edges(g) g.add_edges(edges[0], edges[1]) g.add_edges(edges[1], edges[0]) n2 = g.number_of_nodes() assert n1 == n2 return g def random_state(n=4): state = ''.join(np.random.choice(list(events), n)) nxg = nx.DiGraph() for n in state: nxg.add_node(n, x=events.index(n), y=0) return nxg def rule1(g): if 'a' in g: for n, ndata in g.nodes(data=True): if n == 'b': ndata['y'] = 1 def rule2(g): if 'b' in g: for n, ndata in g.nodes(data=True): if n == 'c': ndata['y'] = 1 def rule3(g): if 'd' in g: for n, ndata in g.nodes(data=True): if n == 'c': ndata['y'] = 1 def rule4(g): if 'e' in g and 'f' in g: for n, ndata in g.nodes(data=True): if n == 'g': ndata['y'] = 1 def apply_rules(g): for rule in [rule1, rule2, rule3]: rule(g) return g def create_dgl_data(n=4): nxg = random_state(n) apply_rules(nxg) g = dgl.from_networkx(nxg, node_attrs=['x', 'y']) add_complete_edges(g) return g def create_batch(n, n_nodes=4): graphs = [create_dgl_data(n_nodes) for _ in range(n)] return dgl.batch(graphs) create_batch(100) class MultiHeadAttention(nn.Module): def __init__(self, dim_model, h): super().__init__() assert dim_model % h == 0 self.h = h self.dim_model = dim_model self.d_k = dim_model // h self.linears = clones(nn.Linear(dim_model, dim_model), 4) self.attn = None def _view_head(self, x): return x.view(x.size(0), -1, self.h, self.d_k).transpose(1, 2) def forward(self, g, query, key, value): q = self._view_head(self.linears[0](query)) k = self._view_head(self.linears[1](key)) v = self._view_head(self.linears[2](value)) score = Fops.edge_softmax(g, Fops.v_dot_u(g, q, k) / self.d_k**0.5) # score = Fops.v_dot_u(g, q, k) / self.d_k**0.5 # score = F.leaky_relu(Fops.v_dot_u(g, q, k) / self.d_k**0.5) out = Fops.u_mul_e_sum(g, v, score) out = out.transpose(1, 2).view(g.number_of_nodes(), self.h * self.d_k) score = score.view(score.size(0), self.h, -1) self.attn = score out = self.linears[3](out) return out class Network(nn.Module): def __init__(self, d_model, h=16, n_heads=4, dropout=0.2): super().__init__() self.src_embedding = nn.Sequential( nn.Embedding(d_model, h), nn.Linear(h, h), nn.LeakyReLU(), nn.Linear(h, h), nn.LeakyReLU() ) self.dst_embedding = nn.Sequential( nn.Embedding(d_model, h), nn.Linear(h, h), nn.LeakyReLU(), nn.Linear(h, h), nn.LeakyReLU() ) self.encode = nn.Sequential( nn.Linear(h*2, h), nn.LeakyReLU(), nn.Linear(h, h), nn.LeakyReLU(), ) self.attn = AddNorm(h, layer=MultiHeadAttention(h, n_heads), dropout=dropout) self.core = nn.Sequential( nn.Linear(h, h), nn.LeakyReLU(), ) self.decode = nn.Sequential( nn.Linear(h, h), nn.LeakyReLU(), nn.Linear(h, 1) ) def forward(self, g, n_loops=5): with g.local_scope(): g.ndata['a'] = self.src_embedding(g.ndata['x'].long()) g.ndata['b'] = self.dst_embedding(g.ndata['x'].long()) h = torch.cat([g.ndata['a'], g.ndata['b']], 1) g.ndata['h'] = self.encode(h) for i in range(n_loops): g.ndata['h'] = self.attn(g.ndata['h'], args=(g, g.ndata['a'], g.ndata['b'], g.ndata['h'])) g.ndata['h'] = self.core(g.ndata['h']) out = self.decode(g.ndata['h']) return out net = Network(10) batch = create_batch(3) net(batch) net = Network(10, h=128, n_heads=1) batch_size = 32 n_epochs = 300 optim = torch.optim.AdamW(net.parameters(), lr=1e-3) lossfn = nn.MSELoss() losses = [] for epoch in tqdm(range(n_epochs)): batch = create_batch(batch_size) y = net(batch) y_hat = batch.ndata['y'].unsqueeze(1).float() assert y.shape == y_hat.shape loss = lossfn(y, y_hat) optim.zero_grad() loss.backward() optim.step() losses.append(loss.detach().item()) if epoch % 10 == 0: display.clear_output(wait=True) plt.plot(losses) plt.show() state = events nxg = nx.DiGraph() for n in state: nxg.add_node(n, x=events.index(n), y=0) apply_rules(nxg) g = dgl.from_networkx(nxg, node_attrs=['x', 'y']) add_complete_edges(g) y = net(g) print(y.flatten()) print(g.ndata['y']) print(g.ndata['x']) attn = net.attn.layer.attn plot_multihead_attention(g, attn) ``` # Causal Inference Engine Lets consider how to use attention to perform causal inference. Lets try to learn, for example, the 'A causes B'. To learn $A \rightarrow B$. Lets create a graph with two nodes and one edge. We maintain node attributes 'target' or $y$ and say that if $y_A = 1$ then $y_B = 1$. Else, if there are no other causes of B, $y_B = 0$. First lets generate random data to try out our inference. Note that our ability to infer that 'A causes B' depends on the rarity of certain events. If $y_A = 1$ is a super rare event, then our ability to infer that relationship is limited. ### Simple Example ``` import random from matplotlib import cm # networkx graph nxg = nx.DiGraph() # create the main events nxg.add_node('A') nxg.add_node('B') nxg.add_edge('A', 'B') # add other events for i in range(10): other_node = random.choice('CDEFGHIJKLMNOPQRSTUV') nxg.add_node(other_node) # default values for all events for n, ndata in nxg.nodes(data=True): ndata['y'] = torch.randint(0, 2, (1,)) # apply the main cause if nxg.nodes['A']['y'][0].item() == 1: nxg.nodes['B']['y'] = torch.ones(1,) cmap = cm.get_cmap('viridis', 2) ncolors = cmap([ndata['y'] for _, ndata in nxg.nodes(data=True)]) nx.draw(nxg, node_color=ncolors) ``` Lets convert the networkx graph into a dgl tensor graph. ``` def one_hot(x: torch.Tensor, num_classes: int, device=None, dtype=torch.long): to_shape = None if len(x.shape) > 1: to_shape = tuple(x.shape) + (num_classes,) x = x.flatten() b = torch.zeros(x.shape[0], num_classes, device=device, dtype=dtype) b[torch.arange(x.shape[0], device=device), x.to(device)] = 1 if to_shape: b = b.view(to_shape) return b # perform node encoding all_nodes = list(set(nxg.nodes())) all_nodes.sort() for n, ndata in nxg.nodes(data=True): ndata['x'] = torch.tensor([all_nodes.index(n)]) g = dgl.from_networkx(nxg, node_attrs=['x', 'y']) import numpy as np def get_complete_edges(g): """List complete edges of a dgl graph""" def leading_zero(x): yield torch.zeros_like(x[0]) yield from x x = torch.cumsum(g.batch_num_nodes(), 0) all_edges = [] for a, b in zip(leading_zero(x), x): edges = torch.combinations(torch.arange(a, b)) all_edges.append(edges) return torch.cat(all_edges, 0).T def add_complete_edges(g): n1 = g.number_of_nodes() edges = get_complete_edges(g) g.add_edges(edges[0], edges[1]) g.add_edges(edges[1], edges[0]) n2 = g.number_of_nodes() assert n1 == n2 return g events = 'ABCDEF' state = ''.join(np.random.choice(list(events), 3)) nxg = nx.DiGraph() for n in state: ndata = {'x': torch.tensor([events.index(n)]), 'y': torch.tensor([0.])} if n == 'B' and 'A' in state: ndata['y'] = torch.tensor([1.]) nxg.add_node(n, **ndata) g = dgl.from_networkx(nxg, node_attrs=['x', 'y']) add_complete_edges(g) def create_data(n, n_other=3): events = 'ABCDEF' graphs = [] for i in range(n): nxg = nx.DiGraph() state = ''.join(np.random.choice(list(events), n_other)) for n in state: ndata = {'x': torch.tensor([events.index(n)]), 'y': torch.tensor([0.])} if n == 'B' and 'A' in state: ndata['y'] = torch.tensor([1.]) nxg.add_node(n, **ndata) g = dgl.from_networkx(nxg, node_attrs=['x', 'y']) add_complete_edges(g) graphs.append(g) return dgl.batch(graphs) create_data(10) from torch import nn from tqdm.auto import tqdm from IPython import display class MyModule(nn.Module): def __init__(self): super().__init__() self.embedding = nn.Embedding(26, 16) # self.encode = nn.Sequential( # nn.Linear(16, 16), # nn.ReLU() # ) self.mhattn = AddNorm(16, layer=MultiHeadAttention(16, 4), dropout=0.) self.core = nn.Sequential( nn.Linear(16, 16), nn.ReLU() ) self.decode = nn.Sequential( nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 1) ) def forward(self, g): x = self.embedding(g.ndata['x'].long().flatten()) # x = self.encode(x) g.ndata['h'] = x for i in range(1): h = g.ndata['h'] # h = self.core(h) h = self.mhattn(h, args=(g, h, h, h)) g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h')) x = self.decode(g.ndata['h']) return x mod = MyModule() optim = torch.optim.AdamW(mod.parameters()) lossfn = nn.MSELoss() batch = create_data(32) losses = [] eval_losses = [] for i in tqdm(range(500)): mod.train() batch = create_data(32, 4) mod(batch) y = mod(batch) y_hat = batch.ndata['y'] assert y_hat.shape == y.shape loss = lossfn(y, y_hat) losses.append(loss.detach().item()) optim.zero_grad() loss.backward() optim.step() if i % 10 == 0: # with torch.no_grad(): # mod.eval() # eval_batch = dgl.batch(create_data(32, 3)) # y_hat = eval_batch.ndata['y'][:2] # y = mod(eval_batch)[:2] # assert y_hat.shape == y.shape # eval_loss = lossfn(y, y_hat) # eval_losses.append(eval_loss.detach().item()) display.clear_output(wait=True) plt.plot(losses) plt.show() # # x = embedding(batch.ndata['x'].long()) # sns.heatmap(mhattn(batch, x, x, x).detach()) eval_batch = create_data(1, 10) print(eval_batch.ndata['x']) y = mod(eval_batch) attn = mod.mhattn.layer.attn plot_multihead_attention(eval_batch, attn) g = create_data(3, 4) print(g.ndata['y']) mod(g) from torch import distributions as dist mod = nn.Linear(10, 2) x = torch.randn(1, 10) y = mod(x) y_hat = x[:, 1] def distribution(logits: torch.Tensor) -> dist.Normal: size = logits.shape[1] if not size % 2 == 0: raise RuntimeError( "Shape of logits dim=1 must be even. This function assumes logits are split evenly " "between `mean` and `log(std)` values." ) n_actions = int(size / 2) mean = logits[..., :n_actions] log_std = logits[..., n_actions:] std = log_std.exp() normal = dist.Normal(mean, std) return normal optim = torch.optim.AdamW(mod.parameters()) distribution(y).rsample() ``` #### Training ``` from torch import nn from tqdm.auto import tqdm from IPython import display graphs = create_data(1, n_other=3) batch = dgl.batch(graphs) embedding = nn.Embedding(26, 16) print('num_graphs: {}'.format(len(batch.batch_num_nodes()))) print('num_nodes: {}'.format(batch.number_of_nodes())) print('number of edges: {}'.format(batch.number_of_edges())) print('embedding size: {}'.format(embedding(batch.ndata['x'].long()).shape)) mhattn = MultiHeadAttention(16, 1) class MyModule(nn.Module): def __init__(self): super().__init__() self.embedding = nn.Embedding(26, 16) self.encode = nn.Sequential( nn.Linear(16, 16), nn.ReLU() ) self.mhattn = AddNorm(16, layer=MultiHeadAttention(16, 4), dropout=0.) self.core = nn.Sequential( nn.Linear(16, 16), nn.ReLU() ) self.decode = nn.Sequential( nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 1) ) def forward(self, g): x = self.embedding(g.ndata['x'].long().flatten()) x = self.encode(x) g.ndata['h'] = x for i in range(3): h = g.ndata['h'] h = self.core(h) h = self.mhattn(h, args=(g, h, x, x)) g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h')) x = self.decode(g.ndata['h']) return x mod = MyModule() optim = torch.optim.AdamW(mod.parameters()) lossfn = nn.MSELoss() losses = [] eval_losses = [] for i in tqdm(range(500)): mod.train() batch = dgl.batch(create_data(32, 3)) y = mod(batch) y_hat = batch.ndata['y'] assert y_hat.shape == y.shape loss = lossfn(y, y_hat) losses.append(loss.detach().item()) optim.zero_grad() loss.backward() optim.step() if i % 10 == 0: with torch.no_grad(): mod.eval() eval_batch = dgl.batch(create_data(32, 3)) y_hat = eval_batch.ndata['y'][:2] y = mod(eval_batch)[:2] assert y_hat.shape == y.shape eval_loss = lossfn(y, y_hat) eval_losses.append(eval_loss.detach().item()) display.clear_output(wait=True) plt.plot(losses) plt.show() plt.plot(eval_losses) plt.show() # x = embedding(batch.ndata['x'].long()) # sns.heatmap(mhattn(batch, x, x, x).detach()) create_data(3).ndata from torch import nn from tqdm.auto import tqdm from IPython import display graphs = create_data(1, n_other=3) batch = dgl.batch(graphs) embedding = nn.Embedding(26, 16) print('num_graphs: {}'.format(len(batch.batch_num_nodes()))) print('num_nodes: {}'.format(batch.number_of_nodes())) print('number of edges: {}'.format(batch.number_of_edges())) print('embedding size: {}'.format(embedding(batch.ndata['x'].long()).shape)) mhattn = MultiHeadAttention(16, 1) class MyModule(nn.Module): def __init__(self): super().__init__() self.embedding = nn.Embedding(26, 16) self.encode = nn.Sequential( nn.Linear(16, 16), nn.ReLU() ) self.mhattn = AddNorm(16, layer=MultiHeadAttention(16, 4), dropout=0.) self.core = nn.Sequential( nn.Linear(16, 16), nn.ReLU() ) self.decode = nn.Sequential( nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 2) ) def forward(self, g): x = self.embedding(g.ndata['x'].long().flatten()) x = self.encode(x) g.ndata['h'] = x for i in range(3): h = g.ndata['h'] h = self.core(h) h = self.mhattn(h, args=(g, h, x, x)) g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h')) x = self.decode(g.ndata['h']) return x def distribution(logits: torch.Tensor) -> dist.Normal: size = logits.shape[1] if not size % 2 == 0: raise RuntimeError( "Shape of logits dim=1 must be even. This function assumes logits are split evenly " "between `mean` and `log(std)` values." ) n_actions = int(size / 2) mean = logits[..., :n_actions] log_std = logits[..., n_actions:] std = log_std.exp() normal = dist.Normal(mean, std) return normal mod = MyModule() batch = dgl.batch(create_data(10, 3)) logits = mod(batch) print(logits.shape) d = distribution(logits) d.rsample() optim = torch.optim.AdamW(mod.parameters()) lossfn = nn.MSELoss() losses = [] eval_losses = [] for i in tqdm(range(500)): mod.train() batch = dgl.batch(create_data(32, 3)) logits = mod(batch) d = distribution(logits) y = d.rsample() y_hat = batch.ndata['y'] assert y_hat.shape == y.shape loss = lossfn(y, y_hat) losses.append(loss.detach().item()) optim.zero_grad() loss.backward() optim.step() if i % 10 == 0: with torch.no_grad(): mod.eval() batch = dgl.batch(create_data(32, 3)) logits = mod(batch) d = distribution(logits) y = d.rsample() y_hat = batch.ndata['y'] assert y_hat.shape == y.shape eval_loss = lossfn(y[:2], y_hat[:2]) eval_losses.append(eval_loss.detach().item()) display.clear_output(wait=True) plt.plot(losses) plt.show() plt.plot(eval_losses) plt.show() g = nx.DiGraph() g.add_node(0, x=5) g.add_node(1, x=4) g.add_edge(0, 1) g = dgl.from_networkx(g, node_attrs=['x']) mod(create_data(1, 3)[0]) def get_complete_edges(g): """List complete edges of a dgl graph""" def leading_zero(x): yield torch.zeros_like(x[0]) yield from x all_edges = [] for _a, _b in zip(leading_zero(x), x): edges = torch.combinations(torch.arange(_a, _b)) all_edges.append(edges) return torch.cat(all_edges, 0).T def add_complete_edges(g): edges = get_complete_edges(g) g.add_edges(edges[0], edges[1]) return g add_complete_edges(g) x = torch.cumsum(batch.batch_num_nodes(), 0) def leading_zero(x): yield torch.zeros_like(x[0]) yield from x def complete_edge for _a, _b in zip(leading_zero(x), x): edges = torch.combinations(torch.arange(_a, _b)) # print(edges) # from tqdm.auto import tqdm # from IPython import display # class Module(nn.Module): # def __init__(self, d_model, h, hidden, dropout): # super().__init__() # mod = AddNorm(size=hidden, layer=MultiHeadAttention(hidden, h), dropout=dropout) # self.layers = nn.ModuleList(clones(mod, 2)) # self.decode = nn.Sequential( # nn.Linear(hidden, hidden), # nn.ReLU(), # nn.Linear(hidden, 1), # nn.Sigmoid() # ) # def forward(self, g, x): # x = self.encode(x) # # for i in range(2): # # for layer in self.layers[:1]: # # x = layer(x, args=(g, x, x, x)) # return self.decode(x) import itertools def nx_iter_roots(g: nx.DiGraph) -> Generator[Hashable, None, None]: for n in g.nodes(): if not list(g.predecessors(n)): yield n def nx_iter_leaves(g: nx.DiGraph) -> Generator[Hashable, None, None]: for n in g.nodes(): if not list(g.successors(n)): yield n def _default_g(g: nx.DiGraph, global_key: str = None): for _, data in g.nodes(data=True): data["features"] = np.zeros((1,)) data["target"] = np.zeros((1,)) for _, _, data in g.edges(data=True): data["features"] = np.zeros((1,)) data["target"] = np.zeros((1,)) # g.set_global({"features": np.zeros((1,)), "target": np.zeros((1,))}, global_key) return g def boolean_network(data_size): data = [] nxgs = [] for _ in range(data_size): n_size = np.random.randint(2, 20) tree = nx.random_tree(n_size) # randomize node directions g = nx.DiGraph() for n1, n2, edata in tree.edges(data=True): i = np.random.randint(2) if i % 2 == 0: g.add_edge(n1, n2) else: g.add_edge(n2, n1) _default_g(g) for n in nx_iter_roots(g): ndata = g.nodes[n] ndata["target"] = np.array([1.0]) # embed the identity of the graph structure into the node itself for n, ndata in g.nodes(data=True): ndata['identity'] = np.zeros((2, 20)) ndata['identity'][0][n] = 1. for p in g.predecessors(n): ndata['identity'][1][p] = 1 ndata['identity'] = ndata['identity'].flatten() for _, _, edata in g.edges(data=True): edata['true_edge'] = 1 for n in nx.topological_sort(g): ndata = g.nodes[n] if "target" not in ndata: incoming = [] for p in g.predecessors(n): pdata = g.nodes[p] incoming.append(pdata["target"]) incoming = np.concatenate(incoming) i = incoming.max() if i == 1: o = np.array([0.0]) else: o = np.array([1.0]) ndata["target"] = o for n1, n2 in itertools.combinations(list(g.nodes), 2): g.add_edge(n1, n2) edata = g.get_edge_data(n1, n2) if not edata: edata['true_edge'] = 0 data.append(dgl.from_networkx(g, node_attrs=['features', 'target', 'identity'], edge_attrs=['true_edge'])) nxgs.append(g) # input_data.append(GraphData.from_networkx(g, feature_key="features")) # output_data.append(GraphData.from_networkx(g, feature_key="target")) return data, nxgs boolean_network(3)[0][0].ndata nx.DiGraph().edge g.edges() from tqdm.auto import tqdm from IPython import display class Module(nn.Module): def __init__(self, d_model, h, hidden, dropout): super().__init__() self.encode = nn.Sequential( nn.Linear(d_model, hidden), nn.ReLU() ) mod = AddNorm(size=hidden, layer=MultiHeadAttention(hidden, h), dropout=dropout) self.layers = nn.ModuleList(clones(mod, 2)) self.decode = nn.Sequential( nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, 1), nn.Sigmoid() ) def forward(self, g, x): x = self.encode(x) # for i in range(2): # for layer in self.layers[:1]: # x = layer(x, args=(g, x, x, x)) return self.decode(x) mod = Module(d_model, 4, 32, 0.2) data, _ = boolean_network(300) lossfn = torch.nn.BCELoss() optim = torch.optim.AdamW(mod.parameters(), lr=1e-3) losses = [] mod.train() for epoch in tqdm(range(100)): for g in data: y = mod(g, g.ndata['identity'].float()) y_hat = g.ndata['target'].float() loss = lossfn(y, y_hat) losses.append(loss) optim.zero_grad() loss.backward() optim.step() display.clear_output(wait=True) plt.plot(losses) plt.show() data, _ = boolean_network(1) g = data[0] g.ndata['identity'] = g.ndata['identity'].float() edges = torch.stack(g.edges())[:, g.edata['true_edge'].bool()] nxg = nx.DiGraph() nxg.add_edges_from(edges.T.numpy()) nx.draw(nxg) plt.show() y = mod(g, g.ndata['identity']) y_hat = g.ndata['target'] sns.heatmap(torch.stack((y, y_hat)).squeeze(-1).detach().numpy()) ``` ### Crosstalk orthogonality matrix We can evaluate all nodes to discover the orthogonality matrix. ``` nxg = nx.DiGraph() for i, j in list(itertools.product(list(range(20)), repeat=2)): src = torch.zeros(20) dst = torch.zeros(20) nxg.add_edge(i, j) src[i] = 1 dst[j] = 1 nxg.add_node(i, identity=torch.cat([src, dst])) nxg.add_node(j, identity=torch.cat([dst, src])) g = dgl.from_networkx(nxg, node_attrs=['identity']) mod.eval() y = mod(g, g.ndata['identity']) attn = mod.layers[0].layer.attn plot_multihead_attention(g, attn, prog='neato') data, _ = boolean_network(1) g = data[0] g.ndata['identity'] = g.ndata['identity'].float() y = mod(g, g.ndata['identity']) attn = mod.layers[0].layer.attn plot_multihead_attention(g, attn, prog='neato') plt.show() edges = torch.stack(g.edges())[:, g.edata['true_edge'].bool()] x = torch.zeros(g.number_of_nodes(), g.number_of_nodes()) x[edges[0], edges[1]] = 1 sns.heatmap(x, cmap='binary') plt.show() nxg = nx.DiGraph() for i, j in list(itertools.product(list(range(20)), repeat=2)): src = torch.zeros(20) dst = torch.zeros(20) nxg.add_edge(i, j) src[i] = 1 dst[j] = 1 nxg.add_node(i, identity=torch.cat([src, dst])) nxg.add_node(j, identity=torch.cat([dst, src])) g = dgl.from_networkx(nxg, node_attrs=['identity']) y = mod(g, g.ndata['identity']) attn = mod.layers[0].layer.attn plot_multihead_attention(g, attn, prog='neato') list(itertools.product(list(range(3)), repeat=2)) edges = torch.stack(g.edges())[:, g.edata['true_edge'].bool()] nxg = nx.DiGraph() nxg.add_edges_from(edges.T.numpy()) nx.draw(nxg) ```
github_jupyter
The tutorials use PyTorch. You will need to load the following dependencies. ``` # This specific version of torchvision is needed to download the mnist set !pip install torchvision==0.9.1 torch==1.8.0 import random import PIL import imageio import matplotlib.pyplot as plt import numpy as np import skimage.transform import torch import torch.nn as nn import torch.utils.data import torchvision from torchvision import datasets, transforms from IPython import display ``` The code below may be helpful in visualizing PyTorch tensors as images. ``` %matplotlib inline def show(img): """Show PyTorch tensor img as an image in matplotlib.""" npimg = img.cpu().detach().numpy() plt.imshow(np.transpose(npimg, (1, 2, 0)), interpolation='nearest') plt.grid(False) plt.gca().axis('off') def display_thumb(img): display.display(transforms.Resize(128)(img)) device = 'cuda' if torch.cuda.is_available() else 'cpu' ``` ## First tutorial: In the first tutorial, we are going to train a logistic regressor on the MNIST dataset of handwritten digits. Next, we will turn this logistic regressor into a non-linear convolutional network. The following code will load the MNIST dataset. Run it and inspect some of the images and their labels to confirm they are correct. ``` # Load the training and test dataset. mnist_train = datasets.MNIST('/tmp/mnist', train=True, download=True) mnist_test = datasets.MNIST('/tmp/mnist', train=False, download=True) # Show a random image and the corresponding target. img, target = mnist_train[0] print('Label of image:', mnist_train.classes[target]) img ``` Next, we create a PyTorch dataloader for the MNIST dataset. ``` # This ensures the MNIST dataset produces PyTorch tensors. mnist_train.transform = transforms.ToTensor() mnist_test.transform = transforms.ToTensor() # Size of the batches the data loader will produce. batch_size = 64 # This creates the dataloaders. train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False) ``` Next, implement a logistic regression model in PyTorch. Note that a logistic regressor uses a linear transformation of the input. ``` class LogisticRegression(nn.Module): """Linear logistic regression model.""" def __init__(self, input_size, num_classes): super().__init__() ########################################################################### # TODO: Instantiate the layer here. # ########################################################################### def forward(self, x): ########################################################################### # TODO: Apply the layer to the input. # ########################################################################### ``` We will use the following generic training loop for a PyTorch model. ``` def train(model, criterion, data_loader, optimizer, num_epochs): """Simple training loop for a PyTorch model.""" # Make sure model is in training mode. model.train() # Move model to the device. model.to(device) # Exponential moving average of the loss. ema_loss = None # Loop over epochs. for epoch in range(num_epochs): # Loop over data. for batch_idx, (data, target) in enumerate(data_loader): data = data.to(device) target = target.to(device) # Forward pass. output = model(data) loss = criterion(output, target) # Backward pass. optimizer.zero_grad() loss.backward() optimizer.step() # NOTE: It is important to call .item() on the loss before summing. if ema_loss is None: ema_loss = loss.item() else: ema_loss += (loss.item() - ema_loss) * 0.01 # Print out progress. if batch_idx % 500 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(data_loader.dataset), 100. * batch_idx / len(data_loader), ema_loss), ) ``` **Question:** For the model you are currently using, is there any difference between using the model in `train` mode or using it in `eval` mode? Create an SGD optimizer and us it to train the logistic regressor on the MNIST training data for a few epochs. What loss function do you need to use? ``` # Create model, criterion, and optimizer. model = LogisticRegression(28 * 28, 10) ########################################################################### # TODO: Create criterion and optimize here. # ########################################################################### criterion = None optimizer = None # Train the model. If everything is correct, the loss should go below 0.45. train(model, criterion, train_loader, optimizer, num_epochs=5) ``` Visualize the weights of the trained model. What do you see? Why? ``` assert model.linear.weight.shape == (10, 28 * 28) show(torchvision.utils.make_grid( model.linear.weight.view(10, 1, 28, 28), normalize=True, nrow=5, )) ``` Use the following function to measure the test accuracy of your trained model. ``` def test(model, data_loader): """Measures the accuracy of a model on a data set.""" # Make sure the model is in evaluation mode. model.eval() correct = 0 # We do not need to maintain intermediate activations while testing. with torch.no_grad(): # Loop over test data. for data, target in data_loader: # Forward pass. output = model(data.to(device)) # Get the label corresponding to the highest predicted probability. pred = output.argmax(dim=1, keepdim=True) # Count number of correct predictions. correct += pred.cpu().eq(target.view_as(pred)).sum().item() # Print test accuracy. print('Accuracy: {}/{} ({:.0f}%)\n'.format( correct, len(data_loader.dataset), 100. * correct / len(data_loader.dataset)), ) # Accuracy should be around 90%. test(model, test_loader) ``` **Question:** To have the logistic regressor output probabilities, they need to be processed through a softmax layer. Implement a softmax layer yourself. What numerical issues may arise in this layer? How can you solve them? Use the testing code to confirm you implemented it correctly. ``` def bad_softmax(logits): """Computes softmax in a naive manner.""" probs = logits.exp() probs /= probs.sum(-1, keepdim=True) return probs def good_softmax(logits): """Computes softmax in a numerically safe manner.""" ########################################################################### # TODO: Implement a more stable way to compute softmax # ########################################################################### return probs # Test the new softmax layer. logits = torch.rand((1, 20)) + 100 print(bad_softmax(logits).sum(), good_softmax(logits).sum()) # by definition, the correct value is 1 ``` Because of numerical issues like the one you just experiences, PyTorch code typically uses a `LogSoftmax` layer. **Question [optional]:** PyTorch automatically computes the backpropagation gradient of a module for you. However, it can be instructive to derive and implement your own backward function. Try and implement the backward function for your softmax module and confirm that it is correct. ## Convolutions and images The spatial dimensions of the ouput image (width and height) depend on the spatial dimensions of the input image, kernel_size, padding, and striding. In order to build efficient convolutional networks, it's important to understand what the sizes are after after each convolutional layer. In this exersise you will derive the dependency between input and output image sizes. For the sake of simplicity we assume that the input tensor is _square_, i.e., width = height = image_size. We will use the nn.Conv2d layer here. We have not yet discussed what a convolutional layer is yet, but if you set the first two parameters (input channels and output channels) to 1, then this defines a basic convolution. If your code is correct, you should see 'OK'. ``` def compute_conv_output_size(image_size, kernel_size, padding, stride): ########################################################################### # Add code that computes the size of the image after a conv layer. # ########################################################################### return output_size # Compare the size of the output of nn.Conv2d with compute_convnet_output_size. for image_size in range(5, 21, 1): # Shape: batch x channels x height x width. input_tensor = torch.zeros((1, 1, image_size, image_size)) for kernel_size in 2, 3, 5, 7: for padding in 0, 5: for stride in 1, 2, 3, 4: if kernel_size >= image_size: continue output_tensor = nn.Conv2d(1, 1, kernel_size, stride, padding)(input_tensor) output_size = output_tensor.size(2) predicted_output_size = compute_conv_output_size( image_size, kernel_size, padding, stride) assert output_size == predicted_output_size, ( f'ERROR: the real size is {output_size},' f' but got {predicted_output_size}.' f'\nimage_size={image_size}' f' kernel_size={kernel_size}' f' padding={padding}' f' stride={stride}' ) print('OK') ``` You can now use the function you just implemented to compute the size of the output of a convolution. ``` compute_conv_output_size(1, 1, 1, 1) ``` **Question [optional]:** Implement your own convolution operator **without** using any of PyTorch's (or numpy's) pre-defined convolutional functions. ``` def conv_naive(x, w, b, conv_param): """ A naive Python implementation of a convolution. The input consists of an image tensor with height H and width W. We convolve each input with a filter F, where the filter has height HH and width WW. Input: - x: Input data of shape (H, W) - w: Filter weights of shape (HH, WW) - b: Bias for filter - conv_param: A dictionary with the following keys: - 'stride': The number of pixels between adjacent receptive fields in the horizontal and vertical directions. - 'pad': The number of pixels that will be used to zero-pad the input. During padding, 'pad' zeros should be placed symmetrically (i.e equally on both sides) along the height and width axes of the input. Be careful not to modfiy the original input x directly. Returns an array. - out: Output data, of shape (H', W') where H' and W' are given by H' = 1 + (H + 2 * pad - HH) / stride W' = 1 + (W + 2 * pad - WW) / stride """ out = None H, W = x.shape filter_height, filter_width = w.shape stride, pad = conv_param['stride'], conv_param['pad'] # Check dimensions. assert (W + 2 * pad - filter_width) % stride == 0, 'width does not work' assert (H + 2 * pad - filter_height) % stride == 0, 'height does not work' ########################################################################### # TODO: Implement the convolutional forward pass. # # Hint: you can use the function torch.nn.functional.pad for padding. # ########################################################################### ``` You can test your implementation by running the following: ``` # Make convolution module. w_shape = (4, 4) w = torch.linspace(-0.2, 0.3, steps=torch.prod(torch.tensor(w_shape))).reshape(w_shape) b = torch.linspace(-0.1, 0.2, steps=1) # Compute output of module and compare against reference values. x_shape = (4, 4) x = torch.linspace(-0.1, 0.5, steps=torch.prod(torch.tensor(x_shape))).reshape(x_shape) out = conv_naive(x, w, b, {'stride': 2, 'pad': 1}) correct_out = torch.tensor([[0.156, 0.162], [0.036, -0.054]]) # Compare your output to ours; difference should be around e-8 print('Testing conv_forward_naive') rel_error = ((out - correct_out) / (out + correct_out + 1e-6)).mean() print('difference: ', rel_error) if abs(rel_error) < 1e-6: print('Nice work! Your implementation of a convolution layer works correctly.') else: print('Something is wrong. The output was expected to be {} but it was {}'.format(correct_out, out)) ``` **Aside: Image processing via convolutions:** As fun way to gain a better understanding of the type of operation that convolutional layers can perform, we will set up an input containing two images and manually set up filters that perform common image processing operations (grayscale conversion and edge detection). The convolution forward pass will apply these operations to each of the input images. We can then visualize the results as a sanity check. ``` # Load image of a kitten and a puppy. kitten_uri = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Persian_Cat_%28kitten%29.jpg/256px-Persian_Cat_%28kitten%29.jpg" puppy_uri = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Golde33443.jpg/256px-Golde33443.jpg" kitten, puppy = imageio.imread(kitten_uri), imageio.imread(puppy_uri) img_size = 200 # Make this smaller if it runs too slow x = np.zeros((2, 3, img_size, img_size)) x[0, :, :, :] = skimage.transform.resize(puppy, (img_size, img_size)).transpose((2, 0, 1)) x[1, :, :, :] = skimage.transform.resize(kitten, (img_size, img_size)).transpose((2, 0, 1)) x = torch.FloatTensor(x) # Set up a convolutional weights holding 2 filters, each 3x3 w = torch.zeros((2, 3, 3, 3), dtype=torch.float) # The first filter converts the image to grayscale. # Set up the red, green, and blue channels of the filter. w[0, 0, :, :] = torch.tensor([[0, 0, 0], [0, 0.3, 0], [0, 0, 0]]) w[0, 1, :, :] = torch.tensor([[0, 0, 0], [0, 0.6, 0], [0, 0, 0]]) w[0, 2, :, :] = torch.tensor([[0, 0, 0], [0, 0.1, 0], [0, 0, 0]]) # Second filter detects horizontal edges in the blue channel. w[1, 2, :, :] = torch.tensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) # Vector of biases. We don't need any bias for the grayscale # filter, but for the edge detection filter we want to add 128 # to each output so that nothing is negative. b = torch.tensor([0, 128], dtype=torch.float) # Compute the result of convolving each input in x with each filter in w, # offsetting by b, and storing the results in out. out = nn.functional.conv2d(x, w, b, stride=1, padding=1).numpy() def imshow_noax(img, normalize=True): """Tiny helper to show images as uint8 and remove axis labels.""" if normalize: img_max, img_min = np.max(img), np.min(img) img = 255.0 * (img - img_min) / (img_max - img_min) plt.imshow(img.astype('uint8')) plt.gca().axis('off') # Show the original images and the results of the conv operation plt.subplot(2, 3, 1) imshow_noax(puppy, normalize=False) plt.title('Original image') plt.subplot(2, 3, 2) imshow_noax(out[0, 0]) plt.title('Grayscale') plt.subplot(2, 3, 3) imshow_noax(out[0, 1]) plt.title('Edges') plt.subplot(2, 3, 4) imshow_noax(kitten, normalize=False) plt.subplot(2, 3, 5) imshow_noax(out[1, 0]) plt.subplot(2, 3, 6) imshow_noax(out[1, 1]) plt.show() ```
github_jupyter
``` from torchvision import transforms import torchvision TRANSFORM_IMG = transforms.Compose([ transforms.Resize(128), #transforms.CenterCrop(256), transforms.ToTensor(), #transforms.ToPILImage(mode='RGB'), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) TRAIN_DATA_PATH = '/home/jovyan/github/models/research/gan/imgDataset/procesed/' train_data = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM_IMG) import torch as th import torchvision as tv import pro_gan_pytorch.PRO_GAN as pg from torchvision import transforms import torchvision TRAIN_DATA_PATH = '/home/jovyan/github/models/images/' # select the device to be used for training device = th.device("cuda" if th.cuda.is_available() else "cpu") def setup_data(download=False): """ setup the CIFAR-10 dataset for training the CNN :param batch_size: batch_size for sgd :param num_workers: num_readers for data reading :param download: Boolean for whether to download the data :return: classes, trainloader, testloader => training and testing data loaders """ # data setup: TRANSFORM_IMG = transforms.Compose([ #transforms.Resize(128), #transforms.CenterCrop(256), transforms.ToTensor(), #transforms.ToPILImage(mode='RGB'), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) trainset = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM_IMG) testset = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM_IMG) classes = trainset.classes return classes, trainset, testset if __name__ == '__main__': # some parameters: depth = 4 # hyper-parameters per depth (resolution) num_epochs = [10, 20, 20, 20] fade_ins = [50, 50, 50, 50] batch_sizes = [32, 32, 32, 32] latent_size = 128 # get the data. Ignore the test data and their classes _, dataset, _ = setup_data(download=True) # ====================================================================== # This line creates the PRO-GAN # ====================================================================== pro_gan = pg.ConditionalProGAN(num_classes=len(dataset.classes), depth=depth, latent_size=latent_size, device=device) # ====================================================================== # ====================================================================== # This line trains the PRO-GAN # ====================================================================== pro_gan.train( dataset=dataset, epochs=num_epochs, fade_in_percentage=fade_ins, batch_sizes=batch_sizes, num_workers=8 ) # ====================================================================== ```
github_jupyter
<a href="https://colab.research.google.com/github/madhavjk/Hotel_Booking_Prediction/blob/main/ML_hotel_booking_Prediction_deploy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from google.colab import drive drive.mount('/content/drive') df=pd.read_csv('/content/drive/MyDrive/Project 1:Hotel Booking/hotel_bookings.csv') df.head() df.shape df.isna().sum() # Replace missing values: # agent: If no agency is given, booking was most likely made without one. # company: If none given, it was most likely private. # rest schould be self-explanatory. def data_clean(df): df.fillna(0,inplace=True) print(df.isnull().sum()) data_clean(df) list=['children','adults','babies'] for i in list: print('{} has unique values as {}'.format(i,df[i].unique())) ### seems to have some dirtiness in data as Adults,babies & children cant be zero at a same time df.shape len(df[df['adults']==0]) filter=(df['children']==0) & (df['adults']==0) & (df['babies']==0) df[filter] ### Visualise Entire Dataframe where adult,children & babies are 0 pd.set_option('display.max_columns',32) filter=(df['children']==0) & (df['adults']==0) & (df['babies']==0) df[filter] data=df[~filter] data.shape data.head() ``` ## Where do the guests come from?Lets perform Spatial Analysis ``` country_wise_data=data[data['is_canceled']==0]['country'].value_counts().reset_index() country_wise_data.columns=['country','No of guests'] country_wise_data import folium from folium.plugins import HeatMap basemap=folium.Map() country_wise_data.dtypes import plotly.express as px # show on map map_guest = px.choropleth(country_wise_data, locations=country_wise_data['country'], color=country_wise_data['No of guests'], hover_name=country_wise_data['country'], title="Home country of guests") map_guest.show() ``` #### People from all over the world are staying in these two hotels. Most guests are from Portugal and other countries in Europe ``` ``` ## How much do guests pay for a room per night? ``` data.head() ``` #### Both hotels have different room types and different meal arrangements. Seasonal factors are also important. So the prices vary a lot. Since no currency information is given, but Portugal is part of the European Monetary Union, I assume that all prices are in EUR. ``` data2=data[data['is_canceled']==0] # boxplot: plt.figure(figsize=(12, 8)) sns.boxplot(x="reserved_room_type", y="adr", hue="hotel", data=data2) plt.title("Price of room types per night and person", fontsize=16) plt.xlabel("Room type", fontsize=16) plt.ylabel("Price [EUR]", fontsize=16) plt.legend(loc="upper right") plt.ylim(0, 600) plt.show() ``` #### This figure shows the average price per room, depending on its type and the standard deviation. Note that due to data anonymization rooms with the same type letter may not necessarily be the same across hotels. ``` ``` ## How does the price per night vary over the year? ``` data_resort = data[(data["hotel"] == "Resort Hotel") & (data["is_canceled"] == 0)] data_city = data[(data["hotel"] == "City Hotel") & (data["is_canceled"] == 0)] data_resort.head() resort_hotel=data_resort.groupby(['arrival_date_month'])['adr'].mean().reset_index() resort_hotel city_hotel=data_city.groupby(['arrival_date_month'])['adr'].mean().reset_index() city_hotel final=resort_hotel.merge(city_hotel,on='arrival_date_month') final.columns=['month','price_for_resort','price_for_city_hotel'] final ``` #### now we will observe over here is month column is not in order, & if we will visualise we will get improper conclusion #### so very first we have to provide right hierarchy to the month column ``` !pip install sort-dataframeby-monthorweek ## Dependency package needs to be installed ! pip install sorted-months-weekdays import sort_dataframeby_monthorweek as sd def sort_data(df,colname): return sd.Sort_Dataframeby_Month(df,colname) final=sort_data(final,'month') final px.line(final, x='month', y='price_for_resort', title='Room price per night over the Months') px.line(final, x='month', y='price_for_city_hotel', title='Room price per night over the Months') ``` ### Conclusion-->> This clearly shows that the prices in the Resort hotel are much higher during the summer (no surprise here)., The price of the city hotel varies less and is most expensive during spring and autumn. ``` ``` ## Which are the most busy month or in which months Guests are high? ``` data_resort.head() rush_resort=data_resort['arrival_date_month'].value_counts().reset_index() rush_resort.columns=['month','no of guests'] rush_resort rush_city=data_city['arrival_date_month'].value_counts().reset_index() rush_city.columns=['month','no of guests'] rush_city final_rush=rush_resort.merge(rush_city,on='month') final_rush.columns=['month','no of guests in resort','no of guest in city hotel'] final_rush final_rush=sort_data(final_rush,'month') final_rush final_rush.dtypes final_rush.columns px.line(data_frame=final_rush, x='month', y='no of guest in city hotel', title='Total no of guests per Months') px.line(data_frame=final_rush, x='month', y='no of guests in resort', title='Total no of guests per Months') ``` ### Conclusion The City hotel has more guests during spring and autumn, when the prices are also highest. In July and August there are less visitors, although prices are lower. Guest numbers for the Resort hotel go down slighty from June to September, which is also when the prices are highest. Both hotels have the fewest guests during the winter. ``` ``` ## How long do people stay at the hotels? ``` filter=data['is_canceled']==0 clean_data=data[filter] clean_data.head() clean_data["total_nights"] = clean_data["stays_in_weekend_nights"] + clean_data["stays_in_week_nights"] clean_data.head() stay=clean_data.groupby(['total_nights','hotel']).agg('count').reset_index() stay=stay.iloc[:,0:3] stay.head() stay=stay.rename(columns={'is_canceled':'Number of stays'}) stay.head() plt.figure(figsize=(20, 8)) sns.barplot(x = "total_nights", y = "Number of stays" , hue="hotel", hue_order = ["City Hotel", "Resort Hotel"], data=stay) ``` ### Select important Features using Co-relation ``` data.head() co_relation=data.corr() co_relation co_relation=data.corr()["is_canceled"] co_relation co_relation.abs().sort_values(ascending=False) co_relation.abs().sort_values(ascending=False)[1:] data.columns ``` From this list it is apparent that lead_time, total_of_special_requests, required_car_parking_spaces, booking_changes and previous_cancellations are the 5 most important numerical features. However, to predict whether or not a booking will be canceled, the number of booking changes is a possible source of leakage, because this information can change over time. I will also not include days_in_waiting_list,booking changes and arrival_date_year. The most important feature to exclude is the "reservation_status": ``` data.groupby("is_canceled")["reservation_status"].value_counts() list_not=['days_in_waiting_list','arrival_date_year'] num_features=[col for col in data.columns if data[col].dtype!='O' and col not in list_not] num_features cat_not=['arrival_date_year', 'assigned_room_type', 'booking_changes', 'reservation_status', 'country','days_in_waiting_list'] cat_features=[col for col in data.columns if data[col].dtype=='O' and col not in cat_not] cat_features data_cat=data[cat_features] data_cat.head() import warnings from warnings import filterwarnings filterwarnings("ignore") data_cat['reservation_status_date']=pd.to_datetime(data_cat['reservation_status_date']) data_cat['year']=data_cat['reservation_status_date'].dt.year data_cat['month']=data_cat['reservation_status_date'].dt.month data_cat['day']=data_cat['reservation_status_date'].dt.day data_cat.head() data_cat.drop('reservation_status_date',axis=1,inplace=True) data_cat['cancellation']=data['is_canceled'] data_cat.columns ``` ### Feature Encoding ### Perform Mean Encoding Technique ``` cols=data_cat.columns[0:8] cols for col in cols: print(data_cat.groupby([col])['cancellation'].mean()) print('\n') for col in cols: print(data_cat.groupby([col])['cancellation'].mean().to_dict()) print('\n') df=data_cat.copy() for col in cols: dict=data_cat.groupby([col])['cancellation'].mean().to_dict() data_cat[col]=data_cat[col].map(dict) data_cat.head(20) dataframe=pd.concat([data_cat,data[num_features]],axis=1) dataframe.head() dataframe.drop(['cancellation'],axis=1,inplace=True) dataframe.shape ``` ### Handle Outliers ``` sns.distplot(dataframe['lead_time']) import numpy as np def handle_outlier(col): dataframe[col]=np.log1p(dataframe[col]) handle_outlier('lead_time') sns.distplot(dataframe['lead_time'].dropna()) sns.distplot(dataframe['adr']) handle_outlier('adr') sns.distplot(dataframe['adr'].dropna()) dataframe.isnull().sum() dataframe.dropna(inplace=True) ## separate dependent & independent features y=dataframe['is_canceled'] x=dataframe.drop('is_canceled',axis=1) ``` ### Feature Importance ``` from sklearn.linear_model import Lasso from sklearn.feature_selection import SelectFromModel # select a suitable alpha (equivalent of penalty). # The bigger the alpha the less features that will be selected. feature_sel_model = SelectFromModel(Lasso(alpha=0.005, random_state=0)) # remember to set the seed, the random state in this function feature_sel_model.fit(x,y) feature_sel_model.get_support() cols=x.columns # let's print the number of total and selected features # this is how we can make a list of the selected features selected_feat = cols[(feature_sel_model.get_support())] # let's print some stats print('total features: {}'.format((x.shape[1]))) print('selected features: {}'.format(len(selected_feat))) selected_feat x=x[selected_feat] ``` ### splitting dataset & model Building ``` from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.75,random_state=0) from sklearn.linear_model import LogisticRegression logreg=LogisticRegression() logreg.fit(x_train,y_train) y_pred=logreg.predict(x_test) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test,y_pred) cm from sklearn.metrics import accuracy_score score=accuracy_score(y_test,y_pred) score ``` ### Cross validate your model ``` from sklearn.model_selection import cross_val_score score=cross_val_score(logreg,x,y,cv=10) score score.mean() ``` ### Play with multiple Algos ``` #fit naive bayes from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier ### classifier models models = [] models.append(('LogisticRegression', LogisticRegression())) models.append(('Naive Bayes',GaussianNB())) models.append(('RandomForest', RandomForestClassifier())) models.append(('Decision Tree', DecisionTreeClassifier())) models.append(('KNN', KNeighborsClassifier(n_neighbors = 5))) import pickle for name, model in models: print(name) model.fit(x_train, y_train) # Make predictions. predictions = model.predict(x_test) # Compute the error. from sklearn.metrics import confusion_matrix print(confusion_matrix(predictions, y_test)) from sklearn.metrics import accuracy_score print(accuracy_score(predictions,y_test)) print('\n') RF = RandomForestClassifier() RF.fit(x_train,y_train) # Save the Modle to file in the current working directory Pkl_Filename = "Pickle_RF_Model.pkl" with open(Pkl_Filename, 'wb') as file: pickle.dump(RF, file) ```
github_jupyter
## 1. Obtain and review raw data <p>One day, my old running friend and I were chatting about our running styles, training habits, and achievements, when I suddenly realized that I could take an in-depth analytical look at my training. I have been using a popular GPS fitness tracker called <a href="https://runkeeper.com/">Runkeeper</a> for years and decided it was time to analyze my running data to see how I was doing.</p> <p>Since 2012, I've been using the Runkeeper app, and it's great. One key feature: its excellent data export. Anyone who has a smartphone can download the app and analyze their data like we will in this notebook.</p> <p><img src="https://assets.datacamp.com/production/project_727/img/runner_in_blue.jpg" alt="Runner in blue" title="Explore world, explore your data!"></p> <p>After logging your run, the first step is to export the data from Runkeeper (which I've done already). Then import the data and start exploring to find potential problems. After that, create data cleaning strategies to fix the issues. Finally, analyze and visualize the clean time-series data.</p> <p>I exported seven years worth of my training data, from 2012 through 2018. The data is a CSV file where each row is a single training activity. Let's load and inspect it.</p> ``` # Import pandas import pandas as pd # Define file containing dataset # runkeeper_file = 'datasets/cardioActivities.csv' #For jupyter notebook runkeeper_file = '/content/cardioActivities.csv' #For google colabratory # Create DataFrame with parse_dates and index_col parameters df_activities = pd.read_csv(runkeeper_file, parse_dates=['Date'], index_col='Date') # First look at exported data: select sample of 3 random rows display(df_activities.sample(3)) # # Print DataFrame summary print(df_activities.info()) df_activities.describe() ``` ## 2. Data preprocessing <p>Lucky for us, the column names Runkeeper provides are informative, and we don't need to rename any columns.</p> <p>But, we do notice missing values using the <code>info()</code> method. What are the reasons for these missing values? It depends. Some heart rate information is missing because I didn't always use a cardio sensor. In the case of the <code>Notes</code> column, it is an optional field that I sometimes left blank. Also, I only used the <code>Route Name</code> column once, and never used the <code>Friend's Tagged</code> column.</p> <p>We'll fill in missing values in the heart rate column to avoid misleading results later, but right now, our first data preprocessing steps will be to:</p> <ul> <li>Remove columns not useful for our analysis.</li> <li>Replace the "Other" activity type to "Unicycling" because that was always the "Other" activity.</li> <li>Count missing values.</li> </ul> ``` # Define list of columns to be deleted cols_to_drop = ['Friend\'s Tagged', 'Route Name', 'GPX File', 'Activity Id', 'Calories Burned', 'Notes'] # Delete unnecessary columns df_activities = df_activities.drop(columns=cols_to_drop) # Count types of training activities display(df_activities['Type'].value_counts()) # Rename 'Other' type to 'Unicycling' df_activities['Type'] = df_activities['Type'].str.replace('Other', 'Unicycling') # # Count missing values for each column print(df_activities.isnull().sum()) ``` ## 3. Dealing with missing values <p>As we can see from the last output, there are 214 missing entries for my average heart rate.</p> <p>We can't go back in time to get those data, but we can fill in the missing values with an average value. This process is called <em>mean imputation</em>. When imputing the mean to fill in missing data, we need to consider that the average heart rate varies for different activities (e.g., walking vs. running). We'll filter the DataFrames by activity type (<code>Type</code>) and calculate each activity's mean heart rate, then fill in the missing values with those means.</p> ``` # Calculate sample means for heart rate for each training activity type avg_hr_run = df_activities[df_activities['Type'] == 'Running']['Average Heart Rate (bpm)'].mean() avg_hr_cycle = df_activities[df_activities['Type'] == 'Cycling']['Average Heart Rate (bpm)'].mean() # Split whole DataFrame into several, specific for different activities df_run = df_activities[df_activities['Type'] == 'Running'].copy() df_walk = df_activities[df_activities['Type'] == 'Walking'].copy() df_cycle = df_activities[df_activities['Type'] == 'Cycling'].copy() # Filling missing values with counted means df_walk['Average Heart Rate (bpm)'].fillna(110, inplace=True) df_run['Average Heart Rate (bpm)'].fillna(int(avg_hr_run), inplace=True) df_cycle['Average Heart Rate (bpm)'].fillna(int(avg_hr_cycle), inplace=True) # Count missing values for each column in running data print(df_run.isnull().sum()) ``` ## 4. Plot running data <p>Now we can create our first plot! As we found earlier, most of the activities in my data were running (459 of them to be exact). There are only 29, 18, and two instances for cycling, walking, and unicycling, respectively. So for now, let's focus on plotting the different running metrics.</p> <p>An excellent first visualization is a figure with four subplots, one for each running metric (each numerical column). Each subplot will have a different y-axis, which is explained in each legend. The x-axis, <code>Date</code>, is shared among all subplots.</p> ``` %matplotlib inline # Import matplotlib, set style and ignore warning import matplotlib.pyplot as plt %matplotlib inline import warnings plt.style.use('ggplot') warnings.filterwarnings( action='ignore', module='matplotlib.figure', category=UserWarning, message=('This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.') ) # Prepare data subsetting period from 2013 till 2018 runs_subset_2013_2018 = df_run # Create, plot and customize in one step runs_subset_2013_2018.plot(subplots=True, sharex=False, figsize=(12,16), linestyle='none', marker='o', markersize=3, ) # Show plot plt.show() ``` ## 5. Running statistics <p>No doubt, running helps people stay mentally and physically healthy and productive at any age. And it is great fun! When runners talk to each other about their hobby, we not only discuss our results, but we also discuss different training strategies. </p> <p>You'll know you're with a group of runners if you commonly hear questions like:</p> <ul> <li>What is your average distance?</li> <li>How fast do you run?</li> <li>Do you measure your heart rate?</li> <li>How often do you train?</li> </ul> <p>Let's find the answers to these questions in my data. If you look back at plots in Task 4, you can see the answer to, <em>Do you measure your heart rate?</em> Before 2015: no. To look at the averages, let's only use the data from 2015 through 2018.</p> <p>In pandas, the <code>resample()</code> method is similar to the <code>groupby()</code> method - with <code>resample()</code> you group by a specific time span. We'll use <code>resample()</code> to group the time series data by a sampling period and apply several methods to each sampling period. In our case, we'll resample annually and weekly.</p> ``` # Prepare running data for the last 4 years runs_subset_2015_2018 = df_run.iloc[:303] # Calculate annual statistics print('How my average run looks in last 4 years:') display(runs_subset_2015_2018.resample('A').mean()) # Calculate weekly statistics print('Weekly averages of last 4 years:') display(runs_subset_2015_2018.resample('W').mean().mean()) # Mean weekly counts weekly_counts_average = runs_subset_2015_2018['Distance (km)'].resample('A').mean().count() print('How many trainings per week I had on average:', weekly_counts_average) ``` ## 6. Visualization with averages <p>Let's plot the long term averages of my distance run and my heart rate with their raw data to visually compare the averages to each training session. Again, we'll use the data from 2015 through 2018.</p> <p>In this task, we will use <code>matplotlib</code> functionality for plot creation and customization.</p> ``` # Prepare data runs_subset_2015_2018 = df_run['2018':'2015'] runs_distance = runs_subset_2015_2018['Distance (km)'] runs_hr = runs_subset_2015_2018['Average Heart Rate (bpm)'] # Create plot fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(12,8)) # Plot and customize first subplot runs_hr.plot(ax=ax1, color='gray') ax1.set(ylabel='Distance (km)', title='Historical data with averages') ax1.axhline(runs_distance.mean(), color='blue', linewidth=1, linestyle='-.') # Plot and customize second subplot runs_hr.plot(ax=ax2, color='gray') ax2.set(xlabel='Date', ylabel='Average Heart Rate (bpm)') ax2.axhline(runs_hr.mean(), color='blue', linewidth=1, linestyle='-.') # Show plot plt.show() ``` ## 7. Did I reach my goals? <p>To motivate myself to run regularly, I set a target goal of running 1000 km per year. Let's visualize my annual running distance (km) from 2013 through 2018 to see if I reached my goal each year. Only stars in the green region indicate success.</p> ``` # Prepare data df_run_dist_annual = df_run['Distance (km)'].resample('A').sum() # Create plot fig = plt.figure(figsize=(8,5)) # Plot and customize ax = df_run_dist_annual.plot(marker='*', markersize=14, linewidth=0, color='blue') ax.set(ylim=[0, 1210], xlim=['2012','2019'], ylabel='Distance (km)', xlabel='Years', title='Annual totals for distance') ax.axhspan(1000, 1210, color='green', alpha=0.4) ax.axhspan(800, 1000, color='yellow', alpha=0.3) ax.axhspan(0, 800, color='red', alpha=0.2) # Show plot plt.show() ``` ## 8. Am I progressing? <p>Let's dive a little deeper into the data to answer a tricky question: am I progressing in terms of my running skills? </p> <p>To answer this question, we'll decompose my weekly distance run and visually compare it to the raw data. A red trend line will represent the weekly distance run.</p> <p>We are going to use <code>statsmodels</code> library to decompose the weekly trend.</p> ``` # Import required library import statsmodels.api as sm # Prepare data df_run_dist_wkly = df_run['Distance (km)'].bfill() decomposed = sm.tsa.seasonal_decompose(df_run_dist_wkly, extrapolate_trend=1, freq=52) # Create plot fig = plt.figure(figsize=(12,5)) # Plot and customize ax = decomposed.trend.plot(label='Trend', linewidth=2) ax = decomposed.observed.plot(label='Observed', linewidth=0.5) ax.legend() ax.set_title('Running distance trend') # Show plot plt.show() ``` ## 9. Training intensity <p>Heart rate is a popular metric used to measure training intensity. Depending on age and fitness level, heart rates are grouped into different zones that people can target depending on training goals. A target heart rate during moderate-intensity activities is about 50-70% of maximum heart rate, while during vigorous physical activity it’s about 70-85% of maximum.</p> <p>We'll create a distribution plot of my heart rate data by training intensity. It will be a visual presentation for the number of activities from predefined training zones. </p> ``` # Prepare data hr_zones = [100, 125, 133, 142, 151, 173] zone_names = ['Easy', 'Moderate', 'Hard', 'Very hard', 'Maximal'] zone_colors = ['green', 'yellow', 'orange', 'tomato', 'red'] df_run_hr_all = df_run['2018':'2015']['Average Heart Rate (bpm)'] # Create plot fig, ax = plt.subplots(figsize=(8,5)) # Plot and customize n, bins, patches = ax.hist(df_run_hr_all, bins=hr_zones, alpha=0.5) for i in range(0, len(patches)): patches[i].set_facecolor(zone_colors[i]) ax.set(title='Distribution of HR', ylabel='Number of runs') ax.xaxis.set(ticks=hr_zones) ax.set_xticklabels(labels='zone_names', rotation=-30, ha='left') # Show plot plt.show() ``` ## 10. Detailed summary report <p>With all this data cleaning, analysis, and visualization, let's create detailed summary tables of my training. </p> <p>To do this, we'll create two tables. The first table will be a summary of the distance (km) and climb (m) variables for each training activity. The second table will list the summary statistics for the average speed (km/hr), climb (m), and distance (km) variables for each training activity.</p> ``` # Concatenating three DataFrames frames = [df_walk, df_cycle] df_run_walk_cycle = df_run.append(frames, sort=False) dist_climb_cols, speed_col = ['Distance (km)', 'Climb (m)'], ['Average Speed (km/h)'] # Calculating total distance and climb in each type of activities df_totals = df_run_walk_cycle.groupby('Type').sum() print('Totals for different training types:') display(df_totals) # Calculating summary statistics for each type of activities df_summary = df_run_walk_cycle.groupby('Type')[dist_climb_cols + speed_col].describe() # Combine totals with summary for i in dist_climb_cols: df_summary[i, 'total'] = df_totals[i] print('Summary statistics for different training types:') print(df_summary.stack()) ``` ## 11. Fun facts <p>To wrap up, let’s pick some fun facts out of the summary tables and solve the last exercise.</p> <p>These data (my running history) represent 6 years, 2 months and 21 days. And I remember how many running shoes I went through–7.</p> <pre><code>FUN FACTS - Average distance: 11.38 km - Longest distance: 38.32 km - Highest climb: 982 m - Total climb: 57,278 m - Total number of km run: 5,224 km - Total runs: 459 - Number of running shoes gone through: 7 pairs </code></pre> <p>The story of Forrest Gump is well known–the man, who for no particular reason decided to go for a "little run." His epic run duration was 3 years, 2 months and 14 days (1169 days). In the picture you can see Forrest’s route of 24,700 km. </p> <pre><code>FORREST RUN FACTS - Average distance: 21.13 km - Total number of km run: 24,700 km - Total runs: 1169 - Number of running shoes gone through: ... </code></pre> <p>Assuming Forest and I go through running shoes at the same rate, figure out how many pairs of shoes Forrest needed for his run.</p> <p><img src="https://assets.datacamp.com/production/project_727/img/Forrest_Gump_running_route.png" alt="Forrest's route" title="Little run of Forrest Gump"></p> ``` # Count average shoes per lifetime (as km per pair) using our fun facts average_shoes_lifetime = 5224/7 # Count number of shoes for Forrest's run distance shoes_for_forrest_run = 24700//average_shoes_lifetime print('Forrest Gump would need {} pairs of shoes!'.format(shoes_for_forrest_run)) ```
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W2D1_BayesianStatistics/W2D1_Tutorial2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Neuromatch Academy: Week 2, Day 1, Tutorial 1 # Causal inference with mixture of Gaussians **Tutorial Lecturer:** *Konrad Kording* **Tutorial Content Creator:** *Vincent Valton* ##Tutorial Objective ``` #@title Video: Intro from IPython.display import YouTubeVideo video = YouTubeVideo(id='ium-eaJz9yo', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video ``` --- ### Tutorial objectives In this notebook we'll look at creating mixtures of Gaussian distributions by applying a mixing weight to the distributions. Mathematically, we can control how the Gaussians are mixed by summing them and using a mixing parameter $\alpha$ (comprised between zero and one): \begin{eqnarray} \text{Mixture} = \left[ \alpha \times \mathcal{N_1}(\mu_{1},\sigma_{1}) \right] + \left[ \left( 1 - \alpha \right) \times \mathcal{N_2}(\mu_{2},\sigma_{2}) \right] \end{eqnarray} where $\mathcal{N_{1}}$ and $\mathcal{N_{2}}$ are the first and second Gaussian distributions used for the mixture. Steps: 1. Implement a mixture of Gaussian prior 2. Given Bayes rule, a mixture of Gaussian prior and a Gaussian likelihood, calculate the posterior distribution 3. Create a Mixture of Gaussian prior matrix that repeats the prior over multiple rows of the matrix 4. Create a Likelihood matrix with a different likelihood mean for each row of the likelihood matrix. 5. Create a Posterior matrix that is the result (on each row of the posterior matrix), the combination of the prior and likelihood matrices (row-wise). 6. Create a binary decision matrix that reports the most likely action for each of the row-posteriors of the posterior matrix. So lets start implementing these steps, one by one. --- ##Setup Please execute the cells below to initialize the notebook environment. ``` # imports import time # import time import numpy as np # import numpy import scipy as sp # import scipy import math # import basic math functions import random # import basic random number generator functions import matplotlib.pyplot as plt # import matplotlib from IPython import display #@title Figure Settings fig_w, fig_h = (8, 6) plt.rcParams.update({'figure.figsize': (fig_w, fig_h)}) plt.style.use('ggplot') %matplotlib inline %config InlineBackend.figure_format = 'retina' #@title Helper functions def my_gaussian(x_points, mu, sigma): """ DO NOT EDIT THIS FUNCTION !!! Returns un-normalized Gaussian estimated at points `x_points`, with parameters `mu` and `sigma` Args: x_points (numpy array of floats) - points at which the gaussian is evaluated mu (scalar) - mean of the Gaussian sigma (scalar) - standard deviation of the gaussian Returns: (numpy array of floats): un-normalized Gaussian (i.e. without constant) evaluated at `x` """ return np.exp(-(x_points-mu)**2/(2*sigma**2)) def plot_my_composed_prior(x, gaussian1, gaussian2, combined): """ DO NOT EDIT THIS FUNCTION !!! Plots a prior made of a mixture of gaussians Args: x (numpy array of floats): points at which the likelihood has been evaluated gaussian1 (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x` gaussian2 (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x` posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x` Returns: Nothing """ plt.plot(x, gaussian1, '--b', LineWidth=2, label='Gaussian 1') plt.plot(x, gaussian2, '-.b', LineWidth=2, label='Gaussian 2') plt.plot(x, combined, '-r', LineWidth=2, label='Gaussian Mixture') plt.legend() plt.ylabel('Probability') plt.xlabel('Orientation (Degrees)') def my_dynamic_plot(x, prior, likelihood, posterior_pointwise): """ DO NOT EDIT THIS FUNCTION !!! Plots the prior, likelihood and posterior distributions and update the figure Args: x (numpy array of floats): points at which the likelihood has been evaluated auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x` visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x` posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x` Returns: Nothing """ plt.clf() plt.plot(x, prior, '-r', LineWidth=2, label='Prior') plt.plot(x, likelihood, '-b', LineWidth=2, label='Likelihood') plt.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior') plt.ylabel('Probability') plt.xlabel('Orientation (Degrees)') plt.legend() display.clear_output(wait=True) display.display(plt.gcf()) time.sleep(0.2) def plot_mymatrix(x, matrix, xlabel, ylabel, title): """ DO NOT EDIT THIS FUNCTION !!! Plots a matrix Args : x (numpy array of floats): values where matrix is evaluated matrix (numpy array of floats) xlabel (string) : label of x-axis ylabel (string) : label of y-axis title (string) : title of plot Returns: None """ plt.figure(figsize=(fig_w*1.2, fig_h)) plt.pcolor(matrix, edgecolors='w', linewidths=1) plt.colorbar() plt.xticks(np.arange(x.shape[0]), x) plt.title(title) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.show() ``` --- ## a. Implement a mixture of Gaussians We now want to create a mixture of Gaussian probability density functions (PDFs), that we'll use as a prior in subsequent exercises. We provide you with ready-to-use plotting functions, and a code skeleton to plot the resulting PDF. **Suggestions** * Using the equation for the un-normalised Gaussian `my_gaussian`: * Generate a Gaussian with mean 0 and standard deviation 0.5 * Generate another Gaussian with mean 0 and standard deviation 10 * Combine the two Gaussians to make a new prior by mixing the two Gaussians with mixing parameter $\alpha$ = 0.05. Make it such that the peakier Gaussian has 95% of the weight (don't forget to normalize afterwards) * Using the function `plot_my_composed_prior` provided, plot the resulting mixture of gaussian * Play with the means and variance of the two Gaussians and observe the resulting distribution to get an intuition of how the parameters affect the mixture. **Helper function(s)** ``` help(plot_my_composed_prior) ``` ###Exercise 1 ``` x = np.arange(-10, 11, 0.1) prior_mean = 0. prior_sigma1 = .5 prior_sigma2 = 3. alpha = 0.05 ############################################################################### ## Insert your code here to: ## Create a Gaussian prior made of two Gaussians ## Both with mean 0 and standard deviation 0.5 and 3 respectively ## Make the combined prior (made of the two Gaussians) by weighing it ## using a mixing parameter alpha = 0.05 such that the peakier Gaussian has ## weight 0.95 ## Plot the two Gaussian and the resulting mixture using the function `plot_my_composed_prior` ############################################################################### ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_03d850de.py) *Example output:* <img alt='Solution hint' align='left' width=613 height=477 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_03d850de_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_1.jpg"/> --- ## b. Bayes with mixture of Gaussians ``` #@title Video: Bayes with mixture of Gaussians video = YouTubeVideo(id='SYTaSvW_rpE', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video ``` We now want compute the posterior using *Bayes rule*, having the mixture of Gaussian as a prior, and a Gaussian likelihood. Using the provided plotting function `my_dynamic_plot`, we'll see how the 'fat-tails' of the Gaussian mixture affects the linearity of the posterior mode as a function of the stimulus position. **Suggestions** Using the Gaussian mixture from exercise 1 as a prior: * Allow the mean of the Gaussian likelihood to vary from -8 to 8 in steps of 0.2 degree, keeping $\sigma$ of the visual stimuli to 1. * In a loop, calculate the posterior for each visual stimulus, and call the `my_dynamic_plot` function to plot it. * Calculate the mode of the posterior and plot it against the visual stimulus mean. What do you observe? **Helper function(s)** ``` help(my_dynamic_plot) ``` ###Exercise 2 ``` x = np.arange(-10, 11, 0.1) visual_mean = np.arange(-8, 9, 0.2) visual_sigma = 1. ############################################################################### ## Insert your code here to: ## Use the Gaussian mixture of Exercise 1 as your prior ## Create a Gaussian Likelihood with sigma = 1, and mean varying from -8 to 9 in increments of 0.2 Degrees ## Calculate the posterior by multiplying (pointwise) the 'auditory' and 'visual' gaussians ## (Hint: Do not forget to normalise the gaussians before plotting them) ## plot the distributions using the function `my_dynamic_plot` ## plot the posterior mode as a function of visual's mean ############################################################################### ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_9b5af403.py) *Example output:* <img alt='Solution hint' align='left' width=559 height=849 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_9b5af403_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_2.jpg"/> --- ## c. Creating a prior matrix We now want to create a prior matrix using the mixture of gaussians prior created in exercise 1. We do this because it will help us visualize graphically what is being represented and computed at each step of the inference process (this will be particularly useful in later exercises). **Suggestions** Using the prior you defined in Exercise 1 and the range `x=[-10,10]` present in your code : * The first row of your prior matrix will be your prior defined in Ex1. * Now repeat that row prior 20 times to make a matrix of 20 row-priors. * Plot the matrix using the function `plot_mymatrix()` already pre-written in your script - `plot_mymatrix()` has row 0 at the bottom, and row 20 at the top **Helper function** ``` help(plot_mymatrix) ``` ###Exercise 3 ``` x = np.arange(-10, 11, 1) ############################################################################## ## Insert your code here to: ## Create a Gaussian prior made of two Gaussian ## Both with mu = 0 and sigma 0.5 and 3 respectively ## Make the combined prior (made of the two Gaussians) by weighing it ## using a mixing parameter alpha = 0.05 such that the peakier Gaussian has ## weight 30% ## This mixture will make up the first row of your matrix ## Now repeat this row-prior 20 times, to make up a Prior matrix of 20 identical row-priors (use the `np.tile()` function) ## Plot the Prior Matrix using the function `plt.pcolor` and the code snippet provided below ############################################################################### # Uncomment once the task (steps above) is complete # plot_mymatrix(x, prior_matrix, 'Orientation (Degree)', 'Repetitions', 'Prior Matrix') ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_d9bf9f48.py) *Example output:* <img alt='Solution hint' align='left' width=581 height=412 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_d9bf9f48_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_3.jpg"/> --- ## d. Creating a likelihood matrix We now want to create a likelihood matrix that is made up of a Gaussian on each row of the matrix. Each row represents a different trial, with a different stimulus offset (i.e. a different likelihood mean). **Suggestions** Using the equation for the un-normalised Gaussian `my_gaussian`: * Allow the mean of the Gaussian likelihood to vary in 21 steps spaced linearly between from -8 to 8 degree, keeping $\sigma$ of the visual stimuli to 1. * Each likelihood with a different mean will make up a different row-likelihood of your matrix, such that you end up with a likelihood matrix made up of 20 row-Gaussians with different means * Plot the matrix using the function `plot_mymatrix()` already pre-written and commented-out in your script - `plot_mymatrix()` has row 0 at the bottom, and row 20 at the top ###Exercise 4 ``` visual_mean = np.linspace(-8, 8, x.shape[0]-1) visual_sigma = 2 likelihood_matrix = np.zeros_like(prior_matrix) ############################################################################### ## Insert your code here to: ## Create a Gaussian Likelihood with sigma = 1, and mean varying from -8 to 9 in 21 equally spaced steps (use `np.linspace()` function) ## Each of the Gaussian Likelihood with a different mean will make up a different 'trial' and hence a different row of your matrix ## Fill in your matrix with the 20 different Gaussian likelihoods (i.e. 20 trials) ## Plot the Likelihood Matrix using the function `plt.pcolor` and the code snippet provided below ############################################################################### # Uncomment once the task (steps above) is complete # plot_mymatrix(x, likelihood_matrix, 'Orientation (Degree)', 'Repetitions', 'Likelihood Matrix') ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_e4291715.py) *Example output:* <img alt='Solution hint' align='left' width=598 height=412 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_e4291715_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_4.jpg"/> --- ## e. Creating a posterior matrix We now want to create the Posterior matrix. To do so, we will compute the posterior using *Bayes rule* for each trial (i.e. row wise). That is, each row of the posterior matrix will be the posterior resulting from the multiplication of the prior and likelihood of the equivalent row. Mathematically: \begin{eqnarray} Posterior\left[i, :\right] \propto Likelihood\left[i, :\right] \odot Prior\left[i, :\right] \end{eqnarray} where $\odot$ represent the [Hadamard Product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)) (i.e. the element_wise multiplication) of the Prior and Likelihood row vectors `i` from the matrix. **Suggestions** * For each row (trial) of the Prior and Likelihood matrix, calculate posterior and fill in the Posterior matrix, such that each row of the Posterior matrix represents the posterior for a different trial. * Plot the matrix using the function `plot_mymatrix` already pre-written and commented-out in your script - `plot_mymatrix()` has row 0 at the bottom, and row 20 at the top ###Exercise 5 ``` posterior_matrix = np.zeros_like(likelihood_matrix) ############################################################################### ## Insert your code here to: ## For each row of the Prior & Likelihood Matrices, calculate the resulting posterior ## Fill the Posterior Matrix with the row_posterior ## Plot the Posterior Matrix using the function `plt.pcolor` and the code snippet provided below ############################################################################### # Uncomment once the task (steps above) is complete #plot_mymatrix(x, posterior_matrix, 'Orientation (Degree)', 'Repetitions', 'Posterior Matrix') ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_4e129f5a.py) *Example output:* <img alt='Solution hint' align='left' width=581 height=412 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_4e129f5a_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_5.jpg"/> --- ## f. Creating a binary decision matrix The subjects are asked to report one location rather than the whole posterior distribution. To do so, we're going to synthesize the posterior distribution to a point estimate (its mode), the point at which the posterior distribution is largest. In this exercise, we now want to create a binary decision matrix. To do so, we will scan the posterior matrix (i.e. row_wise), and set the matrix cell to 1 at the mode (peak) of the row posterior. This, effectively encodes the *decision* that a participant may make on a given trial (i.e. row). In this case, the modelled decision rule is to take the mode of the posterior on each trial (that is, our model makes the assumption that a participant would 'respond' with the mode of their posterior). **Suggestions** * Create a matrix of the same size as the Posterior matrix and fill it with zeros (Hint: use `np.zeros_like()`). * For each row (trial) of the Posterior matrix, calculate the mode of the posterior, and set the corresponding cell of the Binary Decision Matrix to 1. (e.g. if the mode of the posterior is at position 0, then set the cell with x_column == 0 to 1). * Plot the matrix using the function `plot_mymatrix()` already pre-written and commented-out in your script - `plot_mymatrix()` has row 0 at the bottom, and row 20 at the top ###Exercise 6 ``` binary_decision_matrix = np.zeros_like(posterior_matrix) ############################################################################### ## Insert your code here to: ## Create a matrix of the same size as the Posterior matrix and fill it with zeros (Hint: use np.zeros_like()) ## For each row of the Posterior Matrix, calculate the mode of the posterior, and set the corresponding cell of the Binary Decision Matrix to 1. ## Plot the Binary Decision Matrix using the function `plt.pcolor` and the code snippet provided below ############################################################################### # Uncomment once the task (steps above) is complete # plot_mymatrix(x, binary_decision_matrix, 'Orientation (Degree)', 'Repetitions', 'Binary Decision Matrix') ``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial2_Solution_e8c610f7.py) *Example output:* <img alt='Solution hint' align='left' width=581 height=412 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W2D1_BayesianStatistics/static/W2D1_Tutorial2_Solution_e8c610f7_0.png> <img src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/static/sample_output.png"/> <img width="450px" src="https://github.com/NeuromatchAcademy/course-content/raw/master/tutorials/Bayes/Expected_outputs/Student_BayesDay_Tutorial_2_fig_6.jpg"/> ``` #@title Video: Outro video = YouTubeVideo(id='YIFGXOsi0_A', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video ```
github_jupyter
## Compute a Monte Carlo integral for any specified function. ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import math ``` Riofa-Gean Fernandez ID: 1396498 ``` N = 500 # Number of points a = 0 #x-axis min to replace b = 1.75 #x-axis max to replace def f(x): return np.cos(x) #function to replace x = np.arange(a,b,0.01) #(start, stop, step interval) y = f(x) #function d = max(y) #y-axis maximum c = min(y) #y-axis minimum #compute the number of random points x_rand = a + (b - a)*np.random.random(N) y_rand = np.random.random(N)*d ind_below = np.where(y_rand < f(x_rand)) #points below the function ind_above = np.where(y_rand >= f(x_rand)) #points above the function #plot the function pts_below = plt.scatter(x_rand[ind_below], y_rand[ind_below], label = "Points below function", color = "green") pts_above = plt.scatter(x_rand[ind_above], y_rand[ind_above], label = "Points above function", color = "blue") plt.plot(x, y, label = "Function", color = "red") plt.legend(loc = 'lower center', ncol = 2) int_answer_1 = len(ind_below[0])/(N)*((b-a)*(d-c)) #first integral estimate (By R. Fernandez and S. Yuen) #print the answer print ("Number of points above the function:", len(ind_above[0])) print ("Number of points below the function:", len(ind_below[0])) print ("Fraction of points below the function:", int_answer_1) #By S. Yuen ``` Sierra Yuen ID: 1495259 ``` N = 10000 #number of points a2 = 0 #x-axis minimum b2 = 1.75 #x-axis maximum def f(x): return np.cos(x) #function to replace x = np.arange(a2,b2,0.01) #(start,stop,step interval) y = f(x) #function d2 = max(y) #y-axis maximum c2 = min(y) #y-axis minimum #compute the number of random points x_rand = a2 + (b2 - a2)*np.random.random(N) y_rand = np.random.random(N)*d2 ind_below = np.where(y_rand < f(x_rand)) #points below the function ind_above = np.where(y_rand >= f(x_rand)) #points above the function #plot the function pts_below = plt.scatter(x_rand[ind_below], y_rand[ind_below], label = "Dots below function", color = "green") pts_above = plt.scatter(x_rand[ind_above], y_rand[ind_above], label = "Dots above function", color = "blue") plt.plot(x, y, label = "Function", color = "red") plt.legend(loc = 'lower center', ncol = 2) int_answer_2 = len(ind_below[0])/(N)*((b2-a2)*(d2-c2)) #second integral estimate (By R. Fernandez and S. Yuen) #print the answer print ("Number of points above the function:", len(ind_above[0])) print ("Number of points below the function:", len(ind_below[0])) print ("Fraction of points below the function:", int_answer_2) #specify a tolerance for the integration tolerance = int_answer_2 - int_answer_1 #print the tolerance print(tolerance) ```
github_jupyter
# Training Neural Networks The network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten digits to class probabilities. The power of neural networks is that we can train them to approximate this function, and basically any function given enough data and compute time. <img src="assets/function_approx.png" width=500px> At first the network is naive, it doesn't know the function mapping the inputs to the outputs. We train the network by showing it examples of real data, then adjusting the network parameters such that it approximates this function. To find these parameters, we need to know how poorly the network is predicting the real outputs. For this we calculate a **loss function** (also called the cost), a measure of our prediction error. For example, the mean squared loss is often used in regression and binary classification problems $$ \large \ell = \frac{1}{2n}\sum_i^n{\left(y_i - \hat{y}_i\right)^2} $$ where $n$ is the number of training examples, $y_i$ are the true labels, and $\hat{y}_i$ are the predicted labels. By minimizing this loss with respect to the network parameters, we can find configurations where the loss is at a minimum and the network is able to predict the correct labels with high accuracy. We find this minimum using a process called **gradient descent**. The gradient is the slope of the loss function and points in the direction of fastest change. To get to the minimum in the least amount of time, we then want to follow the gradient (downwards). You can think of this like descending a mountain by following the steepest slope to the base. <img src='assets/gradient_descent.png' width=350px> ## Backpropagation For single layer networks, gradient descent is straightforward to implement. However, it's more complicated for deeper, multilayer neural networks like the one we've built. Complicated enough that it took about 30 years before researchers figured out how to train multilayer networks. Training multilayer networks is done through **backpropagation** which is really just an application of the chain rule from calculus. It's easiest to understand if we convert a two layer network into a graph representation. <img src='assets/backprop_diagram.png' width=550px> In the forward pass through the network, our data and operations go from bottom to top here. We pass the input $x$ through a linear transformation $L_1$ with weights $W_1$ and biases $b_1$. The output then goes through the sigmoid operation $S$ and another linear transformation $L_2$. Finally we calculate the loss $\ell$. We use the loss as a measure of how bad the network's predictions are. The goal then is to adjust the weights and biases to minimize the loss. To train the weights with gradient descent, we propagate the gradient of the loss backwards through the network. Each operation has some gradient between the inputs and outputs. As we send the gradients backwards, we multiply the incoming gradient with the gradient for the operation. Mathematically, this is really just calculating the gradient of the loss with respect to the weights using the chain rule. $$ \large \frac{\partial \ell}{\partial W_1} = \frac{\partial L_1}{\partial W_1} \frac{\partial S}{\partial L_1} \frac{\partial L_2}{\partial S} \frac{\partial \ell}{\partial L_2} $$ **Note:** I'm glossing over a few details here that require some knowledge of vector calculus, but they aren't necessary to understand what's going on. We update our weights using this gradient with some learning rate $\alpha$. $$ \large W^\prime_1 = W_1 - \alpha \frac{\partial \ell}{\partial W_1} $$ The learning rate $\alpha$ is set such that the weight update steps are small enough that the iterative method settles in a minimum. ## Losses in PyTorch Let's start by seeing how we calculate the loss with PyTorch. Through the `nn` module, PyTorch provides losses such as the cross-entropy loss (`nn.CrossEntropyLoss`). You'll usually see the loss assigned to `criterion`. As noted in the last part, with a classification problem such as MNIST, we're using the softmax function to predict class probabilities. With a softmax output, you want to use cross-entropy as the loss. To actually calculate the loss, you first define the criterion then pass in the output of your network and the correct labels. Something really important to note here. Looking at [the documentation for `nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss), > This criterion combines `nn.LogSoftmax()` and `nn.NLLLoss()` in one single class. > > The input is expected to contain scores for each class. This means we need to pass in the raw output of our network into the loss, not the output of the softmax function. This raw output is usually called the *logits* or *scores*. We use the logits because softmax gives you probabilities which will often be very close to zero or one but floating-point numbers can't accurately represent values near zero or one ([read more here](https://docs.python.org/3/tutorial/floatingpoint.html)). It's usually best to avoid doing calculations with probabilities, typically we use log-probabilities. ``` import torch from torch import nn import torch.nn.functional as F from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) # Download and load the training data trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) ``` ### Note If you haven't seen `nn.Sequential` yet, please finish the end of the Part 2 notebook. ``` # Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10)) # Define the loss criterion = nn.CrossEntropyLoss() # Get our data images, labels = next(iter(trainloader)) # Flatten images images = images.view(images.shape[0], -1) # Forward pass, get our logits logits = model(images) # Calculate the loss with the logits and the labels loss = criterion(logits, labels) print(loss) ``` In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, you want to use the negative log likelihood loss, `nn.NLLLoss` ([documentation](https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss)). >**Exercise:** Build a model that returns the log-softmax as the output and calculate the loss using the negative log likelihood loss. Note that for `nn.LogSoftmax` and `F.log_softmax` you'll need to set the `dim` keyword argument appropriately. `dim=0` calculates softmax across the rows, so each column sums to 1, while `dim=1` calculates across the columns so each row sums to 1. Think about what you want the output to be and choose `dim` appropriately. ``` # TODO: Build a feed-forward network model = nn.Sequential(nn.Linear(784,128), nn.ReLU(), nn.Linear(128,64), nn.ReLU(), nn.Linear(64,10), nn.LogSoftmax(dim=1)) # TODO: Define the loss criterion = nn.NLLLoss() ### Run this to check your work # Get our data images, labels = next(iter(trainloader)) # Flatten images images = images.view(images.shape[0], -1) # Forward pass, get our logits logits = model(images) # Calculate the loss with the logits and the labels loss = criterion(logits, labels) print(loss) ``` ## Autograd Now that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operations performed on tensors, then going backwards through those operations, calculating gradients along the way. To make sure PyTorch keeps track of operations on a tensor and calculates the gradients, you need to set `requires_grad = True` on a tensor. You can do this at creation with the `requires_grad` keyword, or at any time with `x.requires_grad_(True)`. You can turn off gradients for a block of code with the `torch.no_grad()` content: ```python x = torch.zeros(1, requires_grad=True) >>> with torch.no_grad(): ... y = x * 2 >>> y.requires_grad False ``` Also, you can turn on or off gradients altogether with `torch.set_grad_enabled(True|False)`. The gradients are computed with respect to some variable `z` with `z.backward()`. This does a backward pass through the operations that created `z`. ``` x = torch.randn(2,2, requires_grad=True) print(x) y = x**2 print(y) ``` Below we can see the operation that created `y`, a power operation `PowBackward0`. ``` ## grad_fn shows the function that generated this variable print(y.grad_fn) ``` The autgrad module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean. ``` z = y.mean() print(z) ``` You can check the gradients for `x` and `y` but they are empty currently. ``` print(x.grad) ``` To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x` $$ \frac{\partial z}{\partial x} = \frac{\partial}{\partial x}\left[\frac{1}{n}\sum_i^n x_i^2\right] = \frac{x}{2} $$ ``` z.backward() print(x.grad) print(x/2) ``` These gradients calculations are particularly useful for neural networks. For training we need the gradients of the cost with respect to the weights. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the gradients we can make a gradient descent step. ## Loss and Autograd together When we create a network with PyTorch, all of the parameters are initialized with `requires_grad = True`. This means that when we calculate the loss and call `loss.backward()`, the gradients for the parameters are calculated. These gradients are used to update the weights with gradient descent. Below you can see an example of calculating the gradients using a backwards pass. ``` # Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() images, labels = next(iter(trainloader)) images = images.view(images.shape[0], -1) logits = model(images) loss = criterion(logits, labels) print('Before backward pass: \n', model[0].weight.grad) loss.backward() print('After backward pass: \n', model[0].weight.grad) ``` ## Training the network! There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to define an optimizer below. ``` from torch import optim # Optimizers require the parameters to optimize and a learning rate optimizer = optim.SGD(model.parameters(), lr=0.01) ``` Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch: * Make a forward pass through the network * Use the network output to calculate the loss * Perform a backward pass through the network with `loss.backward()` to calculate the gradients * Take a step with the optimizer to update the weights Below I'll go through one training step and print out the weights and gradients so you can see how it changes. Note that I have a line of code `optimizer.zero_grad()`. When you do multiple backwards passes with the same parameters, the gradients are accumulated. This means that you need to zero the gradients on each training pass or you'll retain gradients from previous training batches. ``` print('Initial weights - ', model[0].weight) images, labels = next(iter(trainloader)) images.resize_(64, 784) # Clear the gradients, do this because gradients are accumulated optimizer.zero_grad() # Forward pass, then backward pass, then update weights output = model(images) loss = criterion(output, labels) loss.backward() print('Gradient -', model[0].weight.grad) # Take an update step and few the new weights optimizer.step() print('Updated weights - ', model[0].weight) ``` ### Training for real Now we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the loss, do a backwards pass, and update the weights. >**Exercise:** Implement the training pass for our network. If you implemented it correctly, you should see the training loss drop with each epoch. ``` ## Your solution here model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.003) epochs = 5 for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten MNIST images into a 784 long vector images = images.view(images.shape[0], -1) # TODO: Training pass optimizer.zero_grad() logits = model(images) loss = criterion(logits,labels) loss.backward() optimizer.step() running_loss += loss.item() else: print(f"Training loss: {running_loss/len(trainloader)}") ``` With the network trained, we can check out it's predictions. ``` %matplotlib inline import helper images, labels = next(iter(trainloader)) img = images[0].view(1, 784) # Turn off gradients to speed up this part with torch.no_grad(): logps = model(img) # Output of the network are log-probabilities, need to take exponential for probabilities ps = torch.exp(logps) helper.view_classify(img.view(1, 28, 28), ps) ``` Now our network is brilliant. It can accurately predict the digits in our images. Next up you'll write the code for training a neural network on a more complex dataset.
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from statsmodels.tsa.stattools import acf, pacf ``` # Time Series ## Live Demos ``` air_quality = pd.read_csv("data/AirQualityUCI.csv", sep = ";") air_quality.head() air_quality.shape air_quality = air_quality.drop(["Unnamed: 15", "Unnamed: 16"], axis = 1) air_quality.shape air_quality = air_quality.drop(range(9357, len(air_quality))) air_quality.dtypes for column in ["CO(GT)", "C6H6(GT)", "T", "RH", "AH"]: air_quality[column] = air_quality[column].str.replace(",", ".").astype("float") air_quality.dtypes air_quality.Date air_quality.Time time_formatted = air_quality.Time.str.replace(".", ":") air_quality["DateTime"] = pd.to_datetime(air_quality.Date + " " + time_formatted) air_quality = air_quality.drop(["Date", "Time"], axis = 1) air_quality.dtypes air_quality.DateTime.nunique() == len(air_quality) air_quality.DateTime.is_unique air_quality = air_quality.set_index("DateTime") air_quality.index plt.figure(figsize = (10, 8)) plt.scatter(air_quality.index, air_quality["CO(GT)"], s = 1) plt.xlabel("Time") plt.ylabel("CO Concentration") plt.show() air_quality_valid = air_quality[air_quality["CO(GT)"] >= 0] air_quality_valid = air_quality_valid.sort_index() plt.figure(figsize = (10, 8)) plt.plot(air_quality_valid.index, air_quality_valid["CO(GT)"]) plt.xlabel("Time") plt.ylabel("CO Concentration") plt.show() def plot_evolution(data, column_name = "CO(GT)", ylabel = "CO Concentration"): plt.figure(figsize = (10, 8)) plt.plot(data.index, data[column_name]) plt.xlabel("Time") plt.ylabel(ylabel) plt.show() air_quality_jul2014 = air_quality_valid.loc["2004/07/01":"2004/08/01"] air_quality_jul2014 plot_evolution(air_quality_jul2014) plot_evolution(air_quality_jul2014.interpolate("time")) air_quality_valid = air_quality_valid.interpolate("time") air_quality_valid.describe().T exogenous_data_train, exogenous_data_test, exogenous_CO_train, exogenous_CO_test = train_test_split( air_quality_valid.drop("CO(GT)", axis = 1), air_quality_valid["CO(GT)"], train_size = 0.8) fully_exogenous_model = LinearRegression() fully_exogenous_model.fit(exogenous_data_train, exogenous_CO_train) def show_results(estimator, data_train, data_test, target_train, target_test): print("Train score: {}".format(estimator.score(data_train, target_train))) print("Test score: {}".format(estimator.score(data_test, target_test))) show_results(fully_exogenous_model, exogenous_data_train, exogenous_data_test, exogenous_CO_train, exogenous_CO_test) test_predictions = fully_exogenous_model.predict(exogenous_data_test) def make_residual_plot(observed, estimated): plt.figure(figsize = (8, 5)) plt.scatter(observed, observed - estimated, s = 3) plt.xlabel("Observed") plt.ylabel("Observed - Estimated") plt.show() make_residual_plot(exogenous_CO_test, test_predictions) (exogenous_CO_test - test_predictions).mean() (exogenous_CO_test - test_predictions).std() air_quality_valid.corr() air_quality_valid[["CO(GT)"]] air_quality_valid[["CO(GT)"]].diff() air_quality_autoreg = air_quality_valid[["CO(GT)"]].copy() for lag in range(1, 6): air_quality_autoreg["CO_lag{}".format(lag)] = air_quality_autoreg["CO(GT)"].shift(lag) air_quality_autoreg = air_quality_autoreg.dropna() air_quality_autoreg ar_train, ar_test, ar_CO_train, ar_CO_test = train_test_split( air_quality_autoreg.drop("CO(GT)", axis = 1), air_quality_autoreg["CO(GT)"], train_size = 0.8) linear_autoregression = LinearRegression() linear_autoregression.fit(ar_train, ar_CO_train) show_results(linear_autoregression, ar_train, ar_test, ar_CO_train, ar_CO_test) make_residual_plot(ar_CO_test, linear_autoregression.predict(ar_test)) air_quality_autoreg = air_quality_valid[["CO(GT)"]].copy() for lag in range(1, 41): air_quality_autoreg["CO_lag{}".format(lag)] = air_quality_autoreg["CO(GT)"].shift(lag) air_quality_autoreg = air_quality_autoreg.dropna() air_quality_autoreg ar_train, ar_test, ar_CO_train, ar_CO_test = train_test_split( air_quality_autoreg.drop("CO(GT)", axis = 1), air_quality_autoreg["CO(GT)"], train_size = 0.8) linear_autoregression = LinearRegression() linear_autoregression.fit(ar_train, ar_CO_train) show_results(linear_autoregression, ar_train, ar_test, ar_CO_train, ar_CO_test) make_residual_plot(ar_CO_test, linear_autoregression.predict(ar_test)) (air_quality_valid["CO(GT)"]).corr(air_quality_valid["CO(GT)"].shift(1)) # autocorrelation (air_quality_valid["CO(GT)"]).corr(air_quality_valid["CO(GT)"].shift(2)) # autocorrelation acf_results = acf(air_quality_valid["CO(GT)"], nlags = 200, fft = True) plt.figure(figsize = (16, 5)) plt.scatter(range(len(acf_results)), acf_results) plt.axhline(0.2, c = "red") plt.axhline(-0.2, c = "red") plt.xlabel("Lag") plt.ylabel("ACF") plt.show() pacf_results = pacf(air_quality_valid["CO(GT)"], nlags = 200) plt.figure(figsize = (16, 5)) plt.scatter(range(len(pacf_results)), pacf_results) plt.axhline(0.2, c = "red") plt.axhline(-0.2, c = "red") plt.xlabel("Lag") plt.ylabel("PACF") plt.show() air_quality.columns air_quality_autoreg_exogenous = air_quality_valid.copy() for variable in ["CO(GT)", "PT08.S1(CO)", "NMHC(GT)", "C6H6(GT)", "T", "RH", "AH"]: for lag in [1, 2, 3, 4]: air_quality_autoreg_exogenous["{}_lag{}".format(variable, lag)] = air_quality_valid[variable].shift(lag) for difference in [1]: air_quality_autoreg_exogenous["{}_diff{}".format(variable, difference)] = air_quality_valid[variable].diff(difference) air_quality_autoreg_exogenous = air_quality_autoreg_exogenous.dropna() air_quality_autoreg_exogenous ar_train, ar_test, ar_CO_train, ar_CO_test = train_test_split( air_quality_autoreg_exogenous.drop("CO(GT)", axis = 1), air_quality_autoreg_exogenous["CO(GT)"], train_size = 0.8) linear_autoregression_exogenous = LinearRegression() linear_autoregression_exogenous.fit(ar_train, ar_CO_train) show_results(linear_autoregression_exogenous, ar_train, ar_test, ar_CO_train, ar_CO_test) air_quality_valid[:-1000] fremont = pd.read_csv("data/Fremont_Bridge_Bicycle_Counter.csv") fremont.Date = pd.to_datetime(fremont.Date) fremont.head() fremont.shape fremont.dtypes plt.plot(fremont.Date, fremont["Fremont Bridge Total"]) plt.show() fremont = fremont.set_index("Date") plt.plot(fremont["2015/08/01":"2015/08/16"].index, fremont["2015/08/01":"2015/08/16"]["Fremont Bridge Total"]) ```
github_jupyter
<a href="https://colab.research.google.com/github/Shellyga/Adversarial-Domain-Adaptation-with-Keras/blob/master/Binary_Final_Version_Adversarial_Domain_Adaptation_with_Keras.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Model ``` pip install keras_vggface import random import numpy as np from keras.models import Model,clone_model from keras.applications.resnet50 import ResNet50 from keras.layers import Input, Conv2D, MaxPool2D, Flatten, Dense,Reshape from keras.layers import BatchNormalization, Activation, Dropout from keras_vggface.vggface import VGGFace def build_embedding(param): inp = Input(shape= param["inp_dims"]) network = eval('VGGFace') base = network(weights = 'vggface', include_top = False) # base = network(weights = 'imagenet', include_top = False) feat = base(inp) return Model(inp,feat) # print(feat.shape) # flat = Flatten()(feat) # return flat # def build_embedding(param,inp): # model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), weights='vggface', pooling='avg') # feat = model.get_layer('avg_pool').output # # return feat # # print(feat.shape) # flat = Flatten()(feat) # # flat = Reshape((-1,))(feat) # # flat = Flatten()(embedding) # # print(flat.shape) # return flat def build_classifier(param, embedding): # embedding = Input(embedding.shape) # embedding = Input( (None, 100352) ) # embedding = Input( embedding.output) # embedding = Reshape((-1,))(embedding) flat = Flatten()(embedding.output) dense1 = Dense(400, name = 'class_dense1')(flat) bn1 = BatchNormalization(name = 'class_bn1')(dense1) act1 = Activation('relu', name = 'class_act1')(bn1) drop2 = Dropout(param["drop_classifier"], name = 'class_drop1')(act1) dense2 = Dense(100, name = 'class_dense2')(drop2) bn2 = BatchNormalization(name = 'class_bn2')(dense2) act2 = Activation('relu', name = 'class_act2')(bn2) drop2 = Dropout(param["drop_classifier"], name = 'class_drop2')(act2) densel = Dense(param["number_of_classe"], name = 'class_dense_last')(drop2) # densel = Dense(param["source_label"].shape[1], name = 'class_dense_last')(drop2) bnl = BatchNormalization(name = 'class_bn_last')(densel) actl = Activation('softmax', name = 'class_act_last')(bnl) return Model(inputs=(embedding.input), outputs=(actl)) def build_discriminator(param, embedding_shape): # embedding = Input(embedding.shape) # embedding = Input( (None, 100352) ) embedding = Input( embedding_shape ) # embedding = Reshape((-1,))(embedding) flat = Flatten()(embedding) dense1 = Dense(400, name = 'dis_dense1')(flat) bn1 = BatchNormalization(name='dis_bn1')(dense1) act1 = Activation('relu', name = 'dis_act1')(bn1) drop1 = Dropout(param["drop_discriminator"], name = 'dis_drop1')(act1) dense2 = Dense(100, name = 'dis_dense2')(drop1) bn2 = BatchNormalization(name='dis_bn2')(dense2) act2 = Activation('relu', name = 'dis_act2')(bn2) drop2 = Dropout(param["drop_discriminator"], name = 'dis_drop2')(act2) densel = Dense(1, name = 'dis_dense_last')(drop2) bnl = BatchNormalization(name = 'dis_bn_last')(densel) actl = Activation('sigmoid', name = 'dis_act_last')(bnl) return Model(input=embedding, outputs=actl) # def build_combined_classifier(inp, classifier): # comb_model = Model(inputs = inp, outputs = [classifier]) # return comb_model # def build_combined_discriminator(inp, discriminator): # comb_model = Model(inputs = inp, outputs = [discriminator]) # return comb_model # def build_combined_model(inp, comb): # comb_model = Model(inputs = inp, outputs = comb) # return comb_model ``` # Optimizer ``` import numpy as np from keras.optimizers import Adam def opt_classifier(param): return Adam(lr=param["lr_classifier"], beta_1=param["b1_classifier"], beta_2=param["b2_classifier"]) def opt_discriminator(param): return Adam(lr=param["lr_discriminator"], beta_1=param["b1_discriminator"], beta_2=param["b2_discriminator"]) def opt_combined(param): return Adam(lr=param["lr_combined"], beta_1=param["b1_combined"], beta_2=param["b2_combined"]) ``` # Data ``` from google.colab import drive drive.mount('/content/drive') SEED = 7 import os import sys import argparse import random import numpy as np # import tensorflow.python.keras as tf from tensorflow.compat.v1 import set_random_seed # import tensorflow.python.keras as tf from sklearn.model_selection import train_test_split from sklearn import metrics from plotnine import * import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from math import ceil from sklearn.utils import shuffle as skshuffle from imutils import paths from sklearn.preprocessing import LabelEncoder os.environ['PYTHONHASHSEED']=str(SEED) np.random.seed(SEED) set_random_seed(SEED) random.seed(SEED) from PIL import Image from keras.utils import to_categorical from keras.layers import Input from keras.optimizers import Adam from keras.utils import multi_gpu_model from sklearn.metrics import accuracy_score import pickle from keras.preprocessing import image def pil_loader(path): # print(path) # Return the RGB variant of input image with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB') def one_hot_encoding(param): lb = LabelEncoder() source_labels,target_labels = lb.fit_transform( param["source_label"]),lb.fit_transform( param["target_label"]) param["number_of_classe"] = len(lb.classes_) source_labels,target_labels = to_categorical(source_labels),to_categorical(target_labels) f = open('/content/drive/My Drive/pro_data/‏final_result_B/labels',"wb") f.write(pickle.dumps(lb)) f.close() return source_labels,target_labels def data_loader(filepath, inp_dims): img = [] label = [] detector = dlib.get_frontal_face_detector() predictor = "drive/My Drive/pro_data/shape_predictor_5_face_landmarks.dat" imagePaths = sorted(list(paths.list_images(filepath))) # print(imagePaths) # loop over the input images for imagePath in imagePaths: # extract the class label from the image path and update the # labels list l = imagePath.split(os.path.sep)[-2] label.append(l) # i = pil_loader(imagePath) i = image.load_img(imagePath) # keras.preprocessing.image.img_to_array(image) i = i.resize((inp_dims[0], inp_dims[1]), Image.ANTIALIAS) frame_1 = align_and_crop(detector, np.array(i), predictor)[0] frame_1 = cv2.resize(frame_1,(inp_dims[0], inp_dims[1])) img.append(frame_1) img = np.array(img) label = np.array(label) return img, label def batch_generator(data, batch_size): #Generate batches of data. all_examples_indices = len(data[0]) while True: mini_batch_indices = np.random.choice(all_examples_indices, size = batch_size, replace = False) tbr = [k[mini_batch_indices] for k in data] yield tbr def _plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Greens): from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score, recall_score, roc_auc_score, accuracy_score, roc_curve, auc, confusion_matrix import itertools """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title, fontsize = 14) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="black") plt.ylabel('True Class', fontsize = 14) plt.xlabel('Predicted Class', fontsize = 14) plt.tick_params(axis='both', which='major', labelsize=14) plt.tight_layout() ``` # Crop ``` import dlib import os import sys import cv2 import glob def align_and_crop(detector, im_to_align, predictor_path): ''' simply aligns the photo (using the detector to identify the eyes) and crops the face. :param im_to_align: an address of an image ''' # a shape predictor to find face landmarks so we can precisely localize # the face sp = dlib.shape_predictor(predictor_path) # Ask the detector to find the bounding boxes of each face. The 1 in the # second argument indicates that we should upsample the image 1 time. try: dets = detector(im_to_align, 1) except RuntimeError: return -1 num_faces = len(dets) if num_faces == 0: return im_to_align, False # Find the 5 face landmarks we need to do the alignment. faces = dlib.full_object_detections() for detection in dets: faces.append(sp(im_to_align, detection)) # get a single chip (aligned and cropped) image = dlib.get_face_chip(im_to_align, faces[0]) # cv2.imshow("f", image) show image for testing return image, True ``` # Augment ``` from imgaug import augmenters as iaa from imgaug import seed def aug_training_set_loader(images,labels,inp_dims): NUM_COPIES = ceil(1000/len(images)) images = np.array(images) images=augment(inp_dims[0], inp_dims[1], images, NUM_COPIES) aug_labels =[] for x in labels: for i in range(NUM_COPIES+1): # NUM_COPIES+1-> numbers of augmentations + 1 original aug_labels.append(x) images, labels = skshuffle(images, aug_labels) images = np.array(images) # images = np.array(images, dtype="float") / 255.0 labels = np.array(labels) return images, labels def augment(width, height, data, NUM_COPIES): """ preform augmentetion on the list of photos named 'data' :param width: width of a single photo :param height: height of a single photo :param data: a list of photos to augment :param NUM_COPIES: number of copies produced from the image :return: a list of photos that consists from the original photos and their augmentations """ augmented_data = [] sometimes = lambda aug: iaa.Sometimes(0.5, aug) seq = iaa.Sequential([ sometimes(iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.75, 2.0))), sometimes(iaa.Fliplr()), # horizontal flips sometimes(iaa.AddElementwise((-50, 50))), sometimes(iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0.0, 2.0)))), sometimes(iaa.ContrastNormalization((0.8, 1.2))), sometimes(iaa.Multiply((0.8, 1.2), per_channel=0.2)), sometimes(iaa.Affine( scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, shear=(-8, 8) )), sometimes(iaa.Superpixels(p_replace=0.1, n_segments=150)) ], random_order=True) # apply augmenters in random order for img in data: copies = augment_image(width, height, img, seq, NUM_COPIES) copies.append(img.reshape(width, height, 3)) for cpy in copies: augmented_data.append(cpy) return augmented_data def augment_image(width, height, image, seq, NUM_COPIES): """ augments a single image :param width: width of the image :param height: height of the image :param image: a matrix representing a rgb image :param seq: the augmantation sequence preformed :param NUM_COPIES: number of copies produced from the image :return: a list of all images made from 'image' not including the original """ seed (1) copies = [] image = image.reshape(width, height, 3) for i in range(NUM_COPIES): copies.append(seq.augment_image(image)) return copies ``` # Only Classifier ``` def train_classifier(param,models): inp = Input(shape = ([224, 224, 3])) # embedding = build_embedding_vgg(param,inp) # classifier = build_classifier_vgg(param, embedding) models["combined_classifier"].compile(optimizer = opt_classifier(param), loss = 'categorical_crossentropy', metrics = ['accuracy']) Xs_train, ys_train = param["Xs_train"], param["ys_train"] Xs_test , ys_test = param["Xs_test"], param["ys_test"] S_batches = batch_generator([Xs_train, ys_train], param["batch_size"]) # T_batches = batch_generator([Xt_train, np.zeros(shape = (len(Xt_train),))], param["batch_size"]) param["target_accuracy"] = 0 optim = {} optim["iter"] = 0 optim["acc"] = "" # optim["labels"] = np.array(Xt.shape[0],) gap_last_snap = 0 acc_source=[] acc_target=[] acc_domain_source=[] acc_domain_target=[] for i in range(param["num_iterations_classifier"]): Xsb, ysb = next(S_batches) # Xtb, ytb = next(T_batches) stats1 = models["combined_classifier"].train_on_batch(Xsb, [ysb]) if ((i + 1) % param["test_interval"] == 0): ys_pred = models["combined_classifier"].predict(Xs_train) # yt_pred = models["combined_classifier"].predict(Xt_train) source_accuracy = accuracy_score(ys_train.argmax(1), ys_pred.argmax(1)) # target_accuracy = accuracy_score(yt_train.argmax(1), yt_pred.argmax(1)) acc_source.append(source_accuracy) # acc_target.append(target_accuracy) log_str = "iter: {:05d}: \nLABEL CLASSIFICATION: source_accuracy: {:.5f}"\ .format(i, source_accuracy*100) print(log_str) models["combined_classifier"].save('/content/drive/My Drive/pro_data/‏final_result_B/source_classifier.h5') print("Source matrix: ",metrics.confusion_matrix(ys_train.argmax(1), ys_pred.argmax(1))) ys_test_pred = models["combined_classifier"].predict(Xs_test) source_accuracy_test = accuracy_score(ys_test.argmax(1), ys_test_pred.argmax(1)) print("source accuracy test",source_accuracy_test) cm_s = metrics.confusion_matrix(ys_test.argmax(1), ys_test_pred.argmax(1)) print("Source matrix: ",cm_s) labels_path = '/content/drive/My Drive/pro_data/‏final_result_B/labels' lb = pickle.loads(open(labels_path, "rb").read()) classes = lb.classes_ _plot_confusion_matrix(cm_s, classes,title='Classifier Source Confusion matrix') N = np.arange(0,len(acc_source)) plt.style.use("ggplot") plt.figure() plt.plot(N, np.array(acc_source), label="Source accuracy") plt.title("Training Accuracy of Source Classifier ") plt.xlabel("Number of imtervals") plt.ylabel("Accuracy") plt.legend() plt.savefig('/content/drive/My Drive/pro_data/‏final_result_B/classifier.png') plt.show() ``` # Train target discriminator ``` models = {} from keras.applications.vgg16 import preprocess_input def train(param): inp = Input(shape = (param["inp_dims"])) models["embedding_s"] = build_embedding(param) # Build the classifier models['combined_classifier'] = build_classifier(param, models["embedding_s"]) train_classifier(param,models) embedding_t = clone_model( models["embedding_s"]) # Build and compile the discriminator discriminator_s = build_discriminator(param, models["embedding_s"].output_shape[1:]) discriminator_t = build_discriminator(param, embedding_t.output_shape[1:]) models["combined_discriminator_s"] = Model(inputs=( models["embedding_s"].input), outputs=(discriminator_s( models["embedding_s"].output))) models["combined_discriminator_t"] = Model(inputs=(embedding_t.input), outputs=(discriminator_t(embedding_t.output))) models["combined_discriminator_t"].compile(optimizer = opt_discriminator(param), loss = 'binary_crossentropy', metrics = ['accuracy']) # If you set this flag after compilation - then it will not affect your model at all. # models["embedding_s"].trainable = False for layer in param["source_encoder"].layers: layer.trainable = False models["combined_discriminator_s"].compile(optimizer = opt_discriminator(param), loss = 'binary_crossentropy', metrics = ['accuracy']) models["combined_discriminator_s"].summary() models["combined_discriminator_t"].summary() Xt, Xt_test, yt, yt_test = param["Xt_train"], param["Xt_test"], param["yt_train"], param["yt_test"] Xs, Xs_test, ys, ys_test = param["Xs_train"], param["Xs_test"], param["ys_train"], param["ys_test"] Xs, ys = aug_training_set_loader(Xs, ys, param["inp_dims"]) Xt, yt = aug_training_set_loader(Xt, yt, param["inp_dims"]) # Source domain is represented by label 0 and Target by 1 S_batches = batch_generator([Xs, ys], param["batch_size"]) T_batches = batch_generator([Xt, np.zeros(shape = (len(Xt),))], param["batch_size"]) param["target_accuracy"] = 0 optim = {} optim["iter"] = 0 optim["acc"] = "" optim["labels"] = np.array(Xt.shape[0],) gap_last_snap = 0 acc_domain_source=[] acc_domain_target=[] loss_discriminator = [] t_domain_label = np.ones(( param["batch_size"], 1)) s_domain_label = np.zeros(( param["batch_size"], 1)) for i in range(param["num_iterations_discriminator"]): Xsb, ysb = next(S_batches) Xtb, ytb = next(T_batches) t_domain_label = np.zeros(Xsb.shape[0]) s_domain_label = np.ones(Xtb.shape[0]) X_adv = np.concatenate([Xsb, Xtb]) y_class = np.concatenate([ysb, np.zeros_like(ysb)]) acc_d_s , d_loss_s = models["combined_discriminator_s"].train_on_batch(Xsb, s_domain_label) acc_d_t , d_loss_t = models["combined_discriminator_t"].train_on_batch(Xtb, t_domain_label) acc = acc_d_s + acc_d_t / 2 loss = d_loss_s + d_loss_t if ((i + 1) % param["test_interval"] == 0): acc_domain_source.append(acc_d_s) acc_domain_target.append(acc_d_t) loss_discriminator.append(loss) log_str = "iter: {:05d}: DOMAIN DISCRIMINATION: source_domain_accuracy: {:.5f}, target_domain_accuracy: {:.5f} \n"\ .format(i, acc_d_s*100, acc_d_t*100) print(log_str) discriminator_t.save_weights('/content/drive/My Drive/pro_data/‏final_result_B/disc_target_10000_iter.hdf5') N = np.arange(0,len(acc_domain_source)) plt.style.use("ggplot") plt.figure() plt.plot(N, np.array(acc_domain_source), label="Domain Source accuracy") plt.plot(N, np.array(acc_domain_target), label="Domain Target accuracy") plt.title("Domain Accuracy of Source and Target ") plt.xlabel("Number of intervals") plt.ylabel("Accuracy") plt.legend() plt.savefig('/content/drive/My Drive/pro_data/‏final_result_B/discriminator_graph.png') plt.show() plt.style.use("ggplot") plt.figure() # plt.plot(N, np.array(loss_classifier_source), label="Combined Model ACC / Loss") plt.plot(N, np.array(loss_discriminator), label="Discriminator Acc / loss") plt.title("Discriminator Loss - Average of Source and Target ") plt.xlabel("Number of intervals") plt.ylabel("Acc/ Loss") plt.legend() plt.savefig('/content/drive/My Drive/pro_data/‏final_result_B/train_on_batch_graph.png') plt.show() models["combined_discriminator_s"].summary() models["combined_discriminator_t"].summary() ``` # Main ``` import argparse if __name__ == "__main__": # Read parameter values from the console parser = argparse.ArgumentParser(description = 'Domain Adaptation') parser.add_argument('--number_of_gpus', type = int, nargs = '?', default = '1', help = "Number of gpus to run") parser.add_argument('--network_name', type = str, default = 'ResNet50', help = "Name of the feature extractor network") parser.add_argument('--dataset_name', type = str, default = 'Office', help = "Name of the source dataset") parser.add_argument('--dropout_classifier', type = float, default = 0.25, help = "Dropout ratio for classifier") parser.add_argument('--dropout_discriminator', type = float, default = 0.25, help = "Dropout ratio for discriminator") parser.add_argument('--source_path', type = str, default = 'amazon_10_list.txt', help = "Path to source dataset") parser.add_argument('--target_path', type = str, default = 'webcam_10_list.txt', help = "Path to target dataset") parser.add_argument('--lr_classifier', type = float, default = 0.0001, help = "Learning rate for classifier model") parser.add_argument('--b1_classifier', type = float, default = 0.9, help = "Exponential decay rate of first moment \ for classifier model optimizer") parser.add_argument('--b2_classifier', type = float, default = 0.999, help = "Exponential decay rate of second moment \ for classifier model optimizer") parser.add_argument('--lr_discriminator', type = float, default = 0.00001, help = "Learning rate for discriminator model") parser.add_argument('--b1_discriminator', type = float, default = 0.9, help = "Exponential decay rate of first moment \ for discriminator model optimizer") parser.add_argument('--b2_discriminator', type = float, default = 0.999, help = "Exponential decay rate of second moment \ for discriminator model optimizer") parser.add_argument('--lr_combined', type = float, default = 0.00001, help = "Learning rate for combined model") parser.add_argument('--b1_combined', type = float, default = 0.9, help = "Exponential decay rate of first moment \ for combined model optimizer") parser.add_argument('--b2_combined', type = float, default = 0.999, help = "Exponential decay rate of second moment \ for combined model optimizer") parser.add_argument('--classifier_loss_weight', type = float, default = 1, help = "Classifier loss weight") parser.add_argument('--discriminator_loss_weight', type = float, default = 4, help = "Discriminator loss weight") parser.add_argument('--batch_size', type = int, default = 32, help = "Batch size for training") parser.add_argument('--test_interval', type = int, default = 3, help = "Gap between two successive test phases") parser.add_argument('--num_iterations', type = int, default = 120, help = "Number of iterations") parser.add_argument('--snapshot_interval', type = int, default = 500, help = "Minimum gap between saving outputs") parser.add_argument('--output_dir', type = str, default = 'Models', help = "Directory for saving outputs") # args = parser.parse_args() # Set GPU device # os.environ["CUDA_VISIBLE_DEVICES"] = str(list(np.arange(args.number_of_gpus))).strip('[]') # Initialize parameters param = {} models = {} param["number_of_gpus"] = 1 # param["network_name"] = 'ResNet50' param["network_name"] = 'VGGFace' param["inp_dims"] = [224, 224, 3] param["num_iterations_classifier"] = 2000 param["num_iterations_discriminator"] = 5000 # param["num_iterations"] = 500 param["lr_classifier"] = 0.0001 param["b1_classifier"] = 0.9 param["b2_classifier"] = 0.999 param["lr_discriminator"] = 0.00001 param["b1_discriminator"] = 0.9 param["b2_discriminator"] = 0.999 param["lr_combined"] = 0.00001 param["b1_combined"] = 0.9 param["b2_combined"] = 0.999 # param["batch_size"] = int(32) param["batch_size"] = int(32/2) param["class_loss_weight"] = 1 param["dis_loss_weight"] = 4 param["drop_classifier"] = 0.25 param["drop_discriminator"] = 0.25 param["test_interval"] = 100 # param["source_path"] = 'drive/My Drive/final_proj_dataset/data_file_shelly.txt' # param["target_path"] = 'drive/My Drive/final_proj_dataset/data_file_yerus.txt' param["source_path"] = '/content/drive/My Drive/pro_data/source' param["target_path"] = '/content/drive/My Drive/pro_data/target' param["snapshot_interval"] = 500 # param["snapshot_interval"] = 5 param["output_path"] = '/content/drive/My Drive/pro_data/‏final_result_B' param["number_of_classe"] = 0 # # Create directory for saving models and log files if not os.path.exists(param["output_path"]): os.mkdir(param["output_path"]) # print("[INFO] loading images...") # # Load source and target data # param["source_data"], param["source_label"] = data_loader(param["source_path"], param["inp_dims"]) # param["target_data"], param["target_label"] = data_loader(param["target_path"], param["inp_dims"]) # # param["source_data"], param["source_label"],param["target_data"], param["target_label"] = load_data(param["source_path"],param["target_path"]) # # Encode labels into one-hot format # param["source_label"], param["target_label"] = one_hot_encoding(param) print("[INFO] loading images...") # Load source and target data param["source_data"], param["source_label"] = data_loader(param["source_path"], param["inp_dims"]) print("source images loaded") print("number of images in source domain", param["source_data"].shape[0]) param["target_data"], param["target_label"] = data_loader(param["target_path"], param["inp_dims"]) print("target images loaded") print("number of images in target domain", param["target_data"].shape[0]) # Encode labels into one-hot format print("[INFO] Encode labels into one-hot format") param["source_label"], param["target_label"] = one_hot_encoding(param) param["Xt_train"], param["Xt_test"], param["yt_train"], param["yt_test"] = train_test_split(param["target_data"], param["target_label"], test_size=0.2, random_state=42) param["Xs_train"], param["Xs_test"], param["ys_train"], param["ys_test"] = train_test_split(param["source_data"], param["source_label"], test_size=0.2, random_state=42) print('Xt_train ',param["Xt_train"].shape[0] ) print('Xt_test ',param["Xt_test"].shape[0]) print('Xs_train', param["Xs_train"].shape[0] ) print('Xs_test', param["Xs_test"].shape[0]) # Train data print("[INFO] training network...") train(param) # param["combined_classifier"].save('drive/My Drive/pro_data/result_vgg_notBmix/_source_model_less_layers.h5') ``` # Target Classifier ``` from keras.models import load_model path_source_classifier = '/content/drive/My Drive/pro_data/‏final_result_B/source_classifier.h5' model = load_model(path_source_classifier) path_target_discriminator = '/content/drive/My Drive/pro_data/‏final_result_B/disc_target_10000_iter.hdf5' model.load_weights(path_target_discriminator, by_name=True) # model.compile(optimizer = opt_classifier(param), loss = 'categorical_crossentropy', metrics = ['accuracy']) test_xt,test_yt = param["Xt_test"], param["yt_test"] yt_pred = model.predict(test_xt) target_accuracy_test = accuracy_score(test_yt.argmax(1), yt_pred.argmax(1)) cm_t = metrics.confusion_matrix(test_yt.argmax(1), yt_pred.argmax(1)) print("target accuracy test",target_accuracy_test) print("target Classifier matrix: ",cm_t) test_xs,test_ys = param["Xs_test"], param["ys_test"] ys_pred = model.predict(test_xs) source_accuracy_test = accuracy_score(test_ys.argmax(1), ys_pred.argmax(1)) cm_s = metrics.confusion_matrix(test_ys.argmax(1), ys_pred.argmax(1)) print("source accuracy test",source_accuracy_test) print("source Classifier matrix: ",cm_s) labels_path = '/content/drive/My Drive/pro_data/‏final_result_B/labels' lb = pickle.loads(open(labels_path, "rb").read()) classes = lb.classes_ _plot_confusion_matrix(cm_s, classes,title='Source Confusion matrix') _plot_confusion_matrix(cm_t, classes,title='Targrt Confusion matrix') ``` # Sanity Check ``` from keras.models import load_model path_source_classifier = '/content/drive/My Drive/pro_data/‏final_result_B/source_classifier.h5' source_model = load_model(path_source_classifier) test_xt,test_yt = param["Xt_test"], param["yt_test"] yt_pred = source_model.predict(test_xt) target_accuracy_test = accuracy_score(test_yt.argmax(1), yt_pred.argmax(1)) cm_t_sanity = metrics.confusion_matrix(test_yt.argmax(1), yt_pred.argmax(1)) print("target accuracy test",target_accuracy_test) print("target Classifier matrix: ",cm_t) _plot_confusion_matrix(cm_t_sanity, classes,title='Target Confusion matrix with Source Classifier') ```
github_jupyter
``` import pandas as pd import numpy as np import os import matplotlib.pylab as plt import seaborn as sns np.random.seed(500) types_names = {90:'Ia', 67: '91bg', 52:'Iax', 42:'II', 62:'Ibc', 95: 'SLSN', 15:'TDE', 64:'KN', 88:'AGN', 92:'RRL', 65:'M-dwarf', 16:'EB',53:'Mira', 6:'MicroL', 991:'MicroLB', 992:'ILOT', 993:'CART', 994:'PISN',995:'MLString'} SNANA_types = {90:11, 62:{1:3, 2:13}, 42:{1:2, 2:12, 3:14}, 67:41, 52:43, 64:51, 95:60, 994:61, 992:62, 993:63, 15:64, 88:70, 92:80, 65:81, 16:83, 53:84, 991:90, 6:{1:91, 2:93}} SNANA_names = {11: 'Ia', 3:'Ibc', 13: 'Ibc', 2:'II', 12:'II', 14:'II', 41: '91bg', 43:'Iax', 51:'KN', 60:'SLSN', 61:'PISN', 62:'ILOT', 63:'CART', 64:'TDE', 70:'AGN', 80:'RRL', 81:'M-dwarf', 83:'EB', 84:'Mira', 90:'MicroLB', 91:'MicroL', 93:'MicroL'} fname = '/media/RESSPECT/data/PLAsTiCC/PLAsTiCC_zenodo/plasticc_test_metadata.csv' test_metadata = pd.read_csv(fname) ddf_flag = test_metadata['ddf_bool'].values == 1 ids_ddf = test_metadata['object_id'].values[ddf_flag] ids_wfd = test_metadata['object_id'].values[~ddf_flag] ``` # Check how are the Ias in DDF in comparison with WFD ``` fnames_Ia = os.listdir('Ia/results/') fnames_Ia.remove('master_fitres.fitres') fnames_Ia.remove('salt3') fnames_Ia.remove('.ipynb_checkpoints') salt2_wfd = [] for name in fnames_Ia: fitres_temp = pd.read_csv('Ia/results/' + name, delim_whitespace=True, comment='#') salt2_wfd.append(fitres_temp) salt2_Ia_wfd = pd.concat(salt2_wfd, ignore_index=True) salt2_Ia_ddf = pd.read_csv('Ia/results/master_fitres.fitres', comment='#', delim_whitespace=True) salt2_Ia_ddf['x1 - SIM_x1'] = salt2_Ia_ddf['x1'] - salt2_Ia_ddf['SIM_x1'] salt2_Ia_ddf['c - SIM_c'] = salt2_Ia_ddf['c'] - salt2_Ia_ddf['SIM_c'] salt2_Ia_ddf['x0 - SIM_x0'] = salt2_Ia_ddf['x0'] - salt2_Ia_ddf['SIM_x0'] salt2_Ia_ddf['mB - SIM_mB'] = salt2_Ia_ddf['mB'] - salt2_Ia_ddf['SIM_mB'] salt2_Ia_wfd['x1 - SIM_x1'] = salt2_Ia_wfd['x1'] - salt2_Ia_wfd['SIM_x1'] salt2_Ia_wfd['c - SIM_c'] = salt2_Ia_wfd['c'] - salt2_Ia_wfd['SIM_c'] salt2_Ia_wfd['mB - SIM_mB'] = salt2_Ia_wfd['mB'] - salt2_Ia_wfd['SIM_mB'] salt2_Ia_wfd['x0 - SIM_x0'] = salt2_Ia_wfd['x0'] - salt2_Ia_wfd['SIM_x0'] plt.figure(figsize=(24,10)) ax1 = plt.subplot(2,3,1) sns.distplot(salt2_Ia_ddf['x1'], label='DDF', ax=ax1) sns.distplot(salt2_Ia_wfd['x1'], label='WFD', ax=ax1) plt.legend() ax2 = plt.subplot(2,3,2) sns.distplot(salt2_Ia_ddf['c'], label='DDF', ax=ax2) sns.distplot(salt2_Ia_wfd['c'], label='WFD', ax=ax2) plt.legend() ax3 = plt.subplot(2,3,3) sns.distplot(salt2_Ia_ddf['mB'], label='DDF', ax=ax3) sns.distplot(salt2_Ia_wfd['mB'], label='WFD', ax=ax3) plt.legend() ax4 = plt.subplot(2,3,4) sns.distplot(salt2_Ia_ddf['x1 - SIM_x1'], label='DDF', ax=ax4) sns.distplot(salt2_Ia_wfd['x1 - SIM_x1'], label='WFD', ax=ax4) plt.legend() ax5 = plt.subplot(2,3,5) sns.distplot(salt2_Ia_ddf['c - SIM_c'], label='DDF', ax=ax5) sns.distplot(salt2_Ia_wfd['c - SIM_c'], label='WFD', ax=ax5) plt.legend() ax6 = plt.subplot(2,3,6) sns.distplot(salt2_Ia_ddf['mB - SIM_mB'], label='DDF', ax=ax6) sns.distplot(salt2_Ia_wfd['mB - SIM_mB'], label='WFD', ax=ax6) plt.legend() #plt.savefig('plots/SALT2_params_DDF_WFD.png') ``` ## Create perfect sample WFD ``` nobjs = 3000 for j in range(1, 6): perfect_sample = salt2_Ia_wfd.sample(n=nobjs, replace=False) perfect_sample['zHD'] = perfect_sample['SIM_ZCMB'] perfect_sample.fillna(value=-99, inplace=True) perfect_sample.to_csv('WFD' + str(j) + '/perfect' + str(nobjs) + '.csv', index=False) perfect_sample.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples' + str(j) + '/perfect' + str(nobjs) + '.csv', index=False) del perfect_sample ``` # Calculate populations - WFD ``` types_names = {90: 'Ia', 67: '91bg', 52:'Iax', 42:'II', 62:'Ibc', 95: 'SLSN', 15:'TDE', 64:'KN', 88:'AGN', 92:'RRL', 65:'M-dwarf', 16:'EB',53:'Mira', 6:'MicroL', 991:'MicroLB', 992:'ILOT', 993:'CART', 994:'PISN',995:'MLString'} SNANA_names = {11: 'Ia', 3:'Ibc', 13: 'Ibc', 2:'II', 12:'II', 14:'II', 41: '91bg', 43:'Iax', 51:'KN', 60:'SLSN', 61:'PISN', 62:'ILOT', 63:'CART', 64:'TDE', 70:'AGN', 80:'RRL', 81:'M-dwarf', 83:'EB', 84:'Mira', 90:'MicroLB', 91:'MicroL', 93:'MicroL'} groups, freq = np.unique(test_metadata[~ddf_flag]['true_target'].values, return_counts=True) tot_wfd = sum(~ddf_flag) print('Type \t\t Total number \t %') for i in range(len(groups)): if types_names[groups[i]] in ['M-dwarf', 'MicroLB']: print(i, ' --- ', types_names[groups[i]], '\t', freq[i], '\t\t', round(100*freq[i]/tot_wfd, 3)) else: print(i, ' -- ', types_names[groups[i]], '\t\t', freq[i], '\t\t', round(100*freq[i]/tot_wfd, 3)) ``` # Populations for a sample with 3000 SNIa ``` data_all_wfd2 = pd.read_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples/all_WFD.csv', index_col=False) ``` # Random ``` for j in range(1, 6): d1 = data_all_wfd2.sample(n=3000, replace=False) d1.to_csv('WFD' + str(j) + '/perfect' + str(nobjs) + '.csv', index=False) print(d1.iloc[0]) d1.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples' + str(j) + '/random' + str(nobjs) + '.csv', index=False) del d1 nIa = freq[11] nIa_sample = 3000 fitres_types, fitres_freq = np.unique(data_all_wfd2['SIM_TYPE_INDEX'].values, return_counts=True) mock = [] for i in range(len(groups)): n_objs = int(nIa_sample * freq[i]/nIa) print(n_objs, ' --- ', types_names[groups[i]], ' --- ', SNANA_types[groups[i]]) if n_objs > 0: if isinstance(SNANA_types[groups[i]], int) and SNANA_types[groups[i]] in fitres_types: print('***', types_names[groups[i]], ' --- ', n_objs) snana_type = SNANA_types[groups[i]] flag = data_all_wfd2['SIM_TYPE_INDEX'].values == snana_type data_partial = data_all_wfd2[flag] data_partial2 = data_partial.sample(n=n_objs, replace=False) mock.append(data_partial2) elif isinstance(SNANA_types[groups[i]], dict) and len(SNANA_types[groups[i]]) == 3: print('***', types_names[groups[i]], ' --- ', n_objs) f1 = np.logical_or(data_all_wfd2['SIM_TYPE_INDEX'].values == 2, data_all_wfd2['SIM_TYPE_INDEX'].values == 12) f2 = np.logical_or(data_all_wfd2['SIM_TYPE_INDEX'].values == 14, f1) data_partial = data_all_wfd2[f2] data_partial2 = data_partial.sample(n=n_objs, replace=False) mock.append(data_partial2) elif isinstance(SNANA_types[groups[i]], dict) and len(SNANA_types[groups[i]]) == 2: print('***', types_names[groups[i]], ' --- ', n_objs) flag = np.logical_or(data_all_wfd2['SIM_TYPE_INDEX'].values == 3, data_all_wfd2['SIM_TYPE_INDEX'].values == 13) data_partial = data_all_wfd2[flag] data_partial2 = data_partial.sample(n=n_objs, replace=False) mock.append(data_partial2) mock2 = pd.concat(mock, ignore_index=True) mock2.fillna(value=-99, inplace=True) mock2['zHD'] = mock2['SIM_ZCMB'] def classification_metrics(cont): """Classification metrics for a sample of 3k SNIa. Parameters ---------- cont: float \in [0, 1] Percentage of contamination. Returns ------- accuracy: float efficiency: float purity: float figure of merit (W=1): float figure of merit (W=3): float """ totIa = 3000 ntotal = 5588 acc = (ntotal - (2* totIa * cont))/5588 eff = (totIa - totIa * cont)/3000 f1 = ((totIa - 3000 * cont)/3000) * (1 - cont) f3 = ((1 - cont) * totIa)/(((1-cont) * totIa) + 3 * ((cont) * totIa)) return acc, eff, 1 - cont, f1, f3 classification_metrics(0.02) ``` # Single contaminant ``` c1 = [[72, 'II'], [75, 'Iax'], [75, 'II'], [90, 'Iax'], [90, 'Ibc'], [90, 'II'], [95, 'AGN'], [95, '91bg'], [95, 'Iax'], [95, 'Ibc'], [95, 'II'], [98, 'AGN'], [98, '91bg'], [98, 'Iax'], [98, 'Ibc'], [98, 'II'], [99.6, 'TDE'], [99.7, 'CART'], [99, 'AGN'], [99, 'SLSN'], [99, '91bg'], [99, 'Iax'], [99, 'Ibc'], [99, 'II']] k = 5 for i in range(len(c1)): fname_salt2 = os.listdir(c1[i][1] + '/results/') if '.ipynb_checkpoints' in fname_salt2: fname_salt2.remove('.ipynb_checkpoints') fname_salt2.remove('salt3') fname_salt2.remove('master_fitres.fitres') nobjs = round(0.01* (100 - c1[i][0]) * 3000) print('nobjs = ', nobjs) salt2_wfd = [] for name in fname_salt2: try: fitres_temp = pd.read_csv(c1[i][1] + '/results/' + name, delim_whitespace=True, comment='#') salt2_wfd.append(fitres_temp) except: pass salt2_wfd = pd.concat(salt2_wfd, ignore_index=True) types, counts = np.unique(salt2_wfd['SIM_TYPE_INDEX'].values, return_counts=True) print('salt2_wfd.shape = ', salt2_wfd.shape) print('types = ', types) print('counts = ', counts) salt2_sample = salt2_wfd.sample(n=nobjs, replace=False) fnames_Ia = os.listdir('Ia/results/') fnames_Ia.remove('master_fitres.fitres') fnames_Ia.remove('salt3') fnames_Ia.remove('.ipynb_checkpoints') salt2_wfd = [] for name in fnames_Ia: fitres_temp = pd.read_csv('Ia/results/' + name, delim_whitespace=True, comment='#') salt2_wfd.append(fitres_temp) salt2_Ia_wfd = pd.concat(salt2_wfd, ignore_index=True) types, counts = np.unique(salt2_Ia_wfd['SIM_TYPE_INDEX'].values, return_counts=True) print('types = ', types) print('counts = ', counts) salt2_Ia_sample = salt2_Ia_wfd.sample(n=3000-nobjs, replace=False) final_sample = pd.concat([salt2_Ia_sample, salt2_sample], ignore_index=True) final_sample['zHD'] = final_sample['SIM_ZCMB'] final_sample.fillna(value=-99, inplace=True) print('final_sample.shape = ', final_sample.shape) if c1[i][1] in ['AGN', 'TDE', 'SLSN', 'CART', '91bg']: cont = c1[i][1] elif c1[i][1] == '91bg': cont = 'SNIa-91bg' else: cont = 'SN' + c1[i][1] fname = 'WFD' + str(k) + '/' + str(c1[i][0]) + 'SNIa' + str(round(100 - c1[i][0], 1)) + cont + '.csv' fname2 = '/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples' + str(k) + '/' + str(c1[i][0]) + \ 'SNIa' + str(round(100 - c1[i][0], 1)) + cont + '.csv' print('fname = ', fname) print('fname2= ', fname2) final_sample.to_csv(fname, index=False) final_sample.to_csv(fname2, index=False) del final_sample del cont ``` # DDF ## Perfect ``` k = 5 np.random.seed(k) salt2_Ia_ddf = pd.read_csv('Ia/results/master_fitres.fitres', comment='#', delim_whitespace=True) types, counts = np.unique(salt2_Ia_ddf['SIM_TYPE_INDEX'].values, return_counts=True) zflag = salt2_Ia_ddf['SIM_ZCMB'].values <= 1 data = salt2_Ia_ddf[zflag] print(types) print(counts) nobjs = 3000 final_sample = data.sample(n=nobjs, replace=False) final_sample['zHD'] = final_sample['SIM_ZCMB'] final_sample.fillna(value=-99, inplace=True) final_sample.to_csv('DDF' + str(k)+ '/perfect' + str(nobjs) + '.csv') final_sample.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples' + str(k) + \ '/perfect' + str(nobjs) + '.csv') c2 = [[72, 'II'], [75, 'II'],[86, 'Iax'], [90, 'Iax'], [90, 'II'], [91, 'Iax'], [92,'Ibc'], [95, 'Iax'], [95, 'Ibc'], [95,'II'], [98, 'Iax'], [98, 'Ibc'], [98, 'II'], [99.1,'CART'], [99.8, '91bg'], [99.9, 'AGN'], [99.9, 'SLSN'], [99, 'Iax'], [99, 'Ibc'], [99, 'II']] k = 1 np.random.seed(k) for i in range(len(c2)): if c2[i][1] not in ['AGN', 'SLSN', 'CART', '91bg']: cont = 'SN' + c2[i][1] elif c2[i][1] == '91bg': cont = 'SNIa-91bg' else: cont = c2[i][1] salt2_ddf = pd.read_csv(c2[i][1] + '/results/master_fitres.fitres', comment='#', delim_whitespace=True) types, counts = np.unique(salt2_ddf['SIM_TYPE_INDEX'].values, return_counts=True) print(types) print(counts) nobjs = round(0.01* (100 - c2[i][0]) * 3000) print(nobjs) salt2_ddf_sample = salt2_ddf.sample(n=nobjs, replace=False) salt2_Ia_ddf = pd.read_csv('Ia/results/master_fitres.fitres', comment='#', delim_whitespace=True) types, counts = np.unique(salt2_Ia_ddf['SIM_TYPE_INDEX'].values, return_counts=True) salt2_Ia_sample = salt2_Ia_ddf.sample(n=3000-nobjs, replace=False) final_sample = pd.concat([salt2_Ia_sample, salt2_ddf_sample], ignore_index=True) final_sample['zHD'] = final_sample['SIM_ZCMB'] final_sample.fillna(value=-99, inplace=True) fname2 = 'DDF' + str(k) + '/' + str(c2[i][0]) + 'SNIa' + str(round(100 - c2[i][0], 1)) + cont + '.csv' print(fname2) final_sample.to_csv(fname2, index=False) fname3 = '/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples' + str(k) + '/' + \ str(c2[i][0]) + 'SNIa' + str(round(100 - c2[i][0], 1)) + cont + '.csv' ddd = pd.read_csv('DDF1/86SNIa14SNIax.csv', index_col=False) sum(ddd['SIM_TYPE_INDEX'].values == 11)/3000 ``` # Make list with all DDF surviving SALT2 ``` import os import pandas as pd import numpy as np fnames = os.listdir('.') fnames.remove('make_samples.ipynb') fnames.remove('summary.ipynb') fnames.remove('.ipynb_checkpoints') fnames.remove('WFD') fnames.remove('DDF') fnames.remove('DDF_Alex') fnames.remove('plots') fnames.remove('WFD_Alex') all_fitres = [] for name in fnames: try: data = pd.read_csv(name + '/results/master_fitres.fitres', comment='#', delim_whitespace=True) data.fillna(value=-99, inplace=True) data['zHD'] = data['SIM_ZCMB'] all_fitres.append(data) except: pass all_fitres = pd.concat(all_fitres, ignore_index=True) all_fitres.fillna(value=-99, inplace=True) types = np.array([SNANA_names[item] for item in all_fitres['SIM_TYPE_INDEX'].values]) all_fitres['types_names'] = types all_fitres2 = {} all_fitres2['id'] = all_fitres['CID'].values all_fitres2['redshift'] = all_fitres['SIM_ZCMB'].values all_fitres2['type'] = [SNANA_names[item] for item in all_fitres['SIM_TYPE_INDEX'].values] all_fitres2['code'] = all_fitres['SIM_TYPE_INDEX'].values all_fitres2['orig_sample'] = ['test' for i in range(all_fitres.shape[0])] all_fitres2['querayble'] = [True for i in range(all_fitres.shape[0])] all_fitres3 = pd.DataFrame(all_fitres2) all_fitres.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples/all_DDF.csv', index=False) all_fitres all_fitres = pd.read_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples/all_DDF.csv', index_col=False) for i in range(1,6): np.random.seed(i) d1 = all_fitres.sample(n=3000, replace=False) d1.to_csv('DDF' + str(i) + '/random3000.csv', index=False) d1.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples' + str(i) + '/random3000.csv', index=False) del d1 ``` # Make list with all WFD surviving SALT2 ``` fnames = os.listdir('.') fnames.remove('make_samples.ipynb') fnames.remove('summary.ipynb') fnames.remove('.ipynb_checkpoints') fnames.remove('WFD') fnames.remove('DDF') fnames.remove('DDF_Alex') fnames.remove('WFD_Alex') fnames.remove('plots') all_wfd = [] data_all_wfd = [] for name in fnames: flist = os.listdir(name + '/results/') flist.remove('master_fitres.fitres') flist.remove('salt3') for elem in flist: try: data = pd.read_csv(name + '/results/' + elem, comment='#', delim_whitespace=True) data['zHD'] = data['SIM_ZCMB'] data.fillna(value=-99, inplace=True) data_all_wfd.append(data) dtemp = {} dtemp['id'] = data['CID'].values dtemp['redshift'] = data['SIM_ZCMB'].values dtemp['type'] = [SNANA_names[i] for i in data['SIM_TYPE_INDEX'].values] dtemp['code'] = data['SIM_TYPE_INDEX'].values dtemp['orig_sample'] = ['test' for i in range(data.shape[0])] dtemp['queryable'] = [True for i in range(data.shape[0])] dtemp = pd.DataFrame(dtemp) all_wfd.append(dtemp) except: pass all_fitres_wfd = pd.concat(all_wfd, ignore_index=True) data_all_wfd2 = pd.concat(data_all_wfd, ignore_index=True) data_all_wfd2.fillna(value=-99, inplace=True) data_all_wfd2.append(data) types_wfd = np.array([SNANA_names[item] for item in data_all_wfd2['SIM_TYPE_INDEX'].values]) data_all_wfd2['types_names'] = types_wfd data_all_wfd2.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples/all_WFD.csv', index=False) all_fitres_wfd.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/samples/all_objs_survived_SALT2_WFD.csv', index=False) all_fitres_wfd = pd.read_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples/all_WFD.csv', index_col=False) for i in range(1,6): np.random.seed(i) d1 = all_fitres_wfd.sample(n=3000, replace=False) d1.to_csv('WFD' + str(i) + '/random3000.csv', index=False) d1.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples' + str(i) + '/random.csv', index=False) del d1 types = [SNANA_names[item] for item in all_fitres_wfd['SIM_TYPE_INDEX'].values] all_fitres_wfd['types_names'] = types all_fitres_wfd = all_fitres_wfd.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples/all_WFD.csv', index=False) ``` # plots ``` import matplotlib.pylab as plt import seaborn as sns types = np.array([SNANA_names[item] for item in all_fitres['SIM_TYPE_INDEX'].values]) sntype, freq = np.unique(types, return_counts=True) plt.pie(freq, labels=sntype, autopct='%1.1f%%', shadow=True, startangle=140) plt.axis('equal') plt.show() types_wfd = np.array([SNANA_names[item] for item in data_all_wfd2['SIM_TYPE_INDEX'].values]) sntype, freq = np.unique(types_wfd, return_counts=True) plt.pie(freq, labels=sntype, autopct='%1.1f%%', shadow=True, startangle=140) plt.axis('equal') plt.show() ``` # Kyle results - DDF ``` fname_ddf = '/media/kara/resspect_metric/workspace/kyle_boone_ddf.csv' kyle_ddf = pd.read_csv(fname_ddf, names=['object_id','6','15','16','42','52','53','62','64','65','67','88', '90','92','95'], skiprows=1) class_final = [] for i in range(kyle_ddf.shape[0]): indx = np.argsort(kyle_ddf.iloc[i].values[1:])[-1] code = int(kyle_ddf.keys()[indx + 1]) class_final.append(types_names[code]) class_final = np.array(class_final) flag_class_Ia = class_final == 'Ia' kyle_ddf_Ia = kyle_ddf[flag_class_Ia] k = 5 np.random.seed(k) kyle_ddf_sample = kyle_ddf_Ia.sample(n=3000, replace=False) fitres_ddf_flag = np.array([item in kyle_ddf_sample['object_id'].values for item in all_fitres['CID'].values]) sum(fitres_ddf_flag) kyle_fitres_ddf = all_fitres[fitres_ddf_flag] ids, freq = np.unique(kyle_fitres_ddf['CID'].values, return_counts=True) sum(freq > 1 ) kyle_fitres_ddf.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/ddf/emille_samples' + str(k) + '/fiducial3000.csv', index=False) kyle_fitres_ddf.to_csv('/media/emille/git/COIN/RESSPECT_work/PLAsTiCC/metrics_paper/resspect_metric/SALT2_fit/DDF' + str(k) + '/fiducial3000.csv', index=False) sum(kyle_fitres_ddf['SIM_TYPE_INDEX'].values == 11) ``` # Kyle results - WFD ``` np.random.seed(750) fname_wfd = '/media/kara/resspect_metric/workspace/kyle_boone_wfd.csv' kyle_wfd = pd.read_csv(fname_wfd, names=['object_id','6','15','16','42','52','53','62','64','65','67','88', '90','92','95'], skiprows=1) class_final = [] for i in range(kyle_wfd.shape[0]): indx = np.argsort(kyle_wfd.iloc[i].values[1:])[-1] code = int(kyle_wfd.keys()[indx + 1]) class_final.append(types_names[code]) class_final = np.array(class_final) flag_class_Ia = class_final == 'Ia' kyle_wfd_Ia = kyle_wfd[flag_class_Ia] kyle_wfd_sample = kyle_wfd_Ia.sample(n=3000, replace=False) fitres_wfd_flag = np.array([item in kyle_wfd_sample['object_id'].values for item in data_all_wfd2['CID'].values]) sum(fitres_wfd_flag) kyle_fitres_wfd = data_all_wfd2[fitres_wfd_flag] kyle_fitres_wfd2 = kyle_fitres_wfd.drop_duplicates(subset=['CID'], keep='first') ids, freq = np.unique(kyle_fitres_wfd2['CID'].values, return_counts=True) sum(freq > 1 ) k = 5 kyle_fitres_wfd2.to_csv('/media/RESSPECT/data/PLAsTiCC/for_metrics/wfd/emille_samples' + str(k) + '/fiducial3000.csv', index=False) kyle_fitres_wfd2.to_csv('/media/emille/git/COIN/RESSPECT_work/PLAsTiCC/metrics_paper/resspect_metric/SALT2_fit/WFD' + str(k) + '/fiducial3000.csv', index=False) sum(kyle_fitres_wfd2['SIM_TYPE_INDEX'].values == 11)/3000 ```
github_jupyter
# Collaboration and Competition --- You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started! ### 1. Start the Environment Run the next code cell to install a few packages. This line will take a few minutes to run! ``` !pip -q install ./python from unityagents import UnityEnvironment import numpy as np env = UnityEnvironment(file_name="/data/Tennis_Linux_NoVis/Tennis") ``` The environment is already saved in the Workspace and can be accessed at the file path provided below. ``` from unityagents import UnityEnvironment import numpy as np env = UnityEnvironment(file_name="/data/Tennis_Linux_NoVis/Tennis") ``` Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. ``` # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] ``` ### 2. Examine the State and Action Spaces Run the code cell below to print some information about the environment. ``` # reset the environment env_info = env.reset(train_mode=True)[brain_name] # number of agents num_agents = len(env_info.agents) print('Number of agents:', num_agents) # size of each action action_size = brain.vector_action_space_size print('Size of each action:', action_size) # examine the state space states = env_info.vector_observations state_size = states.shape[1] print('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size)) print('The state for the first agent looks like:', states[0]) ``` ### 3. Take Random Actions in the Environment In the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment. Note that **in this coding environment, you will not be able to watch the agents while they are training**, and you should set `train_mode=True` to restart the environment. ``` for i in range(5): # play game for 5 episodes env_info = env.reset(train_mode=False)[brain_name] # reset the environment states = env_info.vector_observations # get the current state (for each agent) scores = np.zeros(num_agents) # initialize the score (for each agent) while True: actions = np.random.randn(num_agents, action_size) # select an action (for each agent) actions = np.clip(actions, -1, 1) # all actions between -1 and 1 env_info = env.step(actions)[brain_name] # send all actions to tne environment next_states = env_info.vector_observations # get next state (for each agent) rewards = env_info.rewards # get reward (for each agent) dones = env_info.local_done # see if episode finished scores += env_info.rewards # update the score (for each agent) states = next_states # roll over states to next time step if np.any(dones): # exit loop if episode finished break print('Total score (averaged over agents) this episode: {}'.format(np.mean(scores))) ``` When finished, you can close the environment. ``` env.close() ``` ### 4. It's Your Turn! Now it's your turn to train your own agent to solve the environment! A few **important notes**: - When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following: ```python env_info = env.reset(train_mode=True)[brain_name] ``` - To structure your work, you're welcome to work directly in this Jupyter notebook, or you might like to start over with a new file! You can see the list of files in the workspace by clicking on **_Jupyter_** in the top left corner of the notebook. - In this coding environment, you will not be able to watch the agents while they are training. However, **_after training the agents_**, you can download the saved model weights to watch the agents on your own machine!
github_jupyter
## PmodOLED Example ## Contents * [Introduction](#Introduction) * [Setup the board and PmodOLED](#Setup-the-board-and-PmodOLED,-and-load-the-overlay) * [Write to the PmodOLED](#Write-to-the-PmodOLED) * [Draw some patterns](#Draw-some-patterns) * [Create a new Python function](#Create-a-new-Python-function) * [Putting it all together](#Putting-it-all-together) ---- ## Introduction This demonstration shows how to use the [PmodOLED](https://reference.digilentinc.com/reference/pmod/pmodoled/start) using the PYNQ-Z1 or PYNQ-Z2 board. ---- ## Setup the board and PmodOLED, and load the overlay ### Connect the PmodOLED to the board. In this example the ***PmodOLED*** should be connected to ***PMODA.*** Download the base overlay ``` from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") ``` Create an oled instance ``` from pynq.lib.pmod import Pmod_OLED # Connect to PMODA pmod_oled = Pmod_OLED(base.PMODA) ``` ## Write to the PmodOLED ``` pmod_oled.clear() pmod_oled.write(' Welcome\n to\n PYNQ!') ``` #### You should now see the text output on the OLED. Try another message: ``` pmod_oled.clear() pmod_oled.write('Python and Zynq\nProductivity & performance') ``` Clear the display when finished. ``` pmod_oled.clear() ``` System information can be captured and stored in Python variables, and written to the peripheral. ``` hostname = !hostname #Get primary IP address ip_addr = !hostname -I | cut -f1 -d' ' #Get CPU architecture cpu = !cat /proc/cpuinfo | grep "model name" | head -n 1 | cut -f3 -d' ' pmod_oled.write(hostname[0] + "\nIP:" + ip_addr[0] + '\nCPU: ' + cpu[0]) pmod_oled.clear() ``` ---- ## Draw some patterns The PmodOLED includes some built in functions running in C code on the IOP. For drawing lines and rectangles, the `draw_line()` `draw_rectangle()` functions are provided. The OLED display area is 32 pixels x 128 pixels. ### Draw a line A line can be drawn by specifying two co-ordinates: pmod_oled.draw_line(x1, y1, x2,y2) You can execute the next cell, or change the co-ordinates and execute the cell below to draw another line. `pmod_oled.clear()` should be called to clear the display if you do not want lines drawn on top of previous lines. If the bitstream is reloaded the display will also be cleared. ``` pmod_oled.draw_line(0,0,128,32) pmod_oled.draw_line(0,32,128,0) pmod_oled.clear() pmod_oled.draw_line(64,0,64,32) ``` Clear the display when finished. ``` pmod_oled.clear() ``` ### Draw a rectangle You can draw a rectangle in a similar way by specifying two co-ordinates: pmod_oled.draw_line(x1, y1, x2,y2). This will draw a rectangle using the two points as opposite corners ``` pmod_oled.draw_rect(60,5,80,25) pmod_oled.draw_rect(105,0,120,28) ``` Clear the display when finished. ``` pmod_oled.clear() ``` ---- ## Create a new Python function More functions could be implemented in the C code running on the IOP to generate other patterns. The existing functions can also be extended in Python to add more functionality. The following cell defines a function to draw circles on the PmodOLED. ``` import math # Draw a circle # Screen resolution is 128x32 def draw_circle(cx,cy, r): for i in range (0, 360): x = cx + r * math.cos(i*math.pi/180) if x > 127: x = 127 if x < 0: x = 0 y = cy + r * math.sin(i*math.pi/180) if y > 31: y = 31 if y < 0: y = 0 pmod_oled.draw_line(int(x),int(y),int(x+1),int(y)) ``` ### Draw the circle You can draw a circle by using the function which has just been created, and by specify a co-ordinate and the radius. ``` pmod_oled.clear() draw_circle(64,16,15) ``` Remember the display is 128x32 pixels. If the circle exceeds the display area it will be clipped. ``` pmod_oled.clear() draw_circle(64,32,15) ``` Additional functionality can be added easily in Python, but note that functions in Python will be slower than using the C functions running directly on the IOP. (In this case, the circle co-ordinates are calculated in Python, and the IOP draw_line() is called 360 times which is much slower than simply drawing a single line using the draw_line() function.) ---- ## Putting it all together Draw some patterns ``` pmod_oled.clear() pmod_oled.draw_line(0,0,128,32) pmod_oled.draw_rect(60,5,80,25) pmod_oled.draw_rect(105,0,120,28) draw_circle(16,16,16) pmod_oled.clear() for i in range (0,9): draw_circle(16,16,i*2) for i in range (0,6): draw_circle(48,16,1+i*3) for i in range (0,5): draw_circle(80,16,i*4) for i in range (0,4): draw_circle(111,16,1+i*5) ```
github_jupyter
``` import scipy.stats as stats import numpy as np import pandas as pd import warnings warnings.filterwarnings('ignore') %matplotlib inline ``` # Q 1.1 We will use the following formula to calculate the coefficient of CRIM. \begin{equation*} \beta = r * \frac{SD_x} {SD_Y}\end{equation*} \begin{equation*}\text {where r = Correlation of X (CRIM) and Y (PRICE) &} \end{equation*} \begin{equation*}SD_x \text{= Standard deviation of X}\end{equation*} \begin{equation*}SD_y \text{= Standard deviation of Y}\end{equation*} From table 1.1 we can find SDx = 8.60154511 & SDy = 9.197 From table 1.2 we can find r = -.388 Using the above we can find: ``` sd_crim = 8.60154511 sd_price = 9.197 r = -.388 B1 = r * sd_price / sd_crim print("B1 {}, implies as crime rate increases by 1 unit, unit price reduces by {} units".format(B1, abs(B1))) ``` # Q 1.2 The range of coefficients is given by: \begin{equation*} \beta \pm \text{t-crit *} SE_{beta}\end{equation*} where t-critical is the critical value of T for significance alpha ``` n = 506 seb1 = 0.044 tcrit = abs(stats.t.ppf(0.025, df = 505)) print("T-critical at alpha {} and df {} is {}".format(0.5, 505, tcrit)) print("Min B1 {}".format(B1 + tcrit * seb1)) print("Max B1 {}".format(B1 - tcrit * seb1)) print("Price will reduce between 32K to 50K with 95% CI, hence his assumption that it reduces by at least 30K is correct") ``` # Q 1.3 Regression is valid for only the observed ranges. The min value of Crime rate = .0068 > 0. Hence it is incorrect to draw any conclusion about the predicted values of Y for Crim==0 as that value is unobserved. We cannot claim the value will be 24.03 # Q 1.4 Here Y predicted can be calculated from the regression equation: 24.033 - 0.414 * 1 (Value of CRIM) For large values of n the range of Y-predicted is given by: The range of coefficients is given by: \begin{equation*} \hat Y \pm \text{t-crit *} SE_{Y}\end{equation*} where t-critical is the critical value of T for significance alpha. ``` se = 8.484 #seb1 * sd_crim * (n - 1) ** 0.5 #print(se) yhat = 24.033 - 0.414 * 1 yhat_max = (yhat + tcrit * se) print("Max Value of Price for CRIM ==1 is {}".format(yhat_max)) ``` # Q 1.5 Here Y predicted (mean value of regression) can be calculated from the regression equation: 24.033 - 6.346 * 1 (Value of SEZ) t-critical is computed as: \begin{equation*} t = \frac {(t_o - t_{mean})} {SE_{estimate}} \end{equation*} ``` yhat = 22.094 + 6.346 print("Mean Regression value {}".format(yhat)) t = (40 - yhat) / 9.064 print("t-crit at alpha 0.05 is {}".format(t)) print("Y-pred follows a normal distribution. Probability of Price being at least 40 lac is {} percent".format(round((1 - sp.stats.norm.cdf(t))* 100, 2))) ``` # Q 1.6 - a From the residual plot we can see that the spread of standardised errors are higher for lower values of standardised prediction compared to higher values. Hence the variance of the residuals are not equal and it demonstrates heteroscedasticity # Q 1.6 - b 1. It is a right skewed distribution 2. The left tail has less proportion of data than that of a normal distribution 3. Between 40-80 % range the distribution has much less proportion of data compared to a normal distribution From observing the P-P plot we conclude there is considerable difference between this distribution and normal distribution. # Q 1.6 - c Based on the above we can conclude that this regression equation may not be functionally correct. # Q 1.7 The increase in R-squared when a new variable is added to a model is the given by the **Square of the Semi-Partial (PART) Correlation**. - From Table 1.7: R-squared @ Step 2 = 0.542 - From Table 1.8: PART Correlation for adding RES = -.153 ``` print("R-squared in Step 3 is {}".format(0.542 + (-.153) ** 2)) ``` # Q 1.8 ==> better representation It reduces as there is correlation among RM and CRIM. Part of what was explained by RM in model 1 is now being explained by CRIM in model 2 hence the coefficient value reduces. ==Put in the equations and Graphs in possible # Q 1.9 ==> look again We will use the model in step - 6 for answering this question. - Since the variables are not standardised we cannot use the magnitude of the coefficients as a measure of impact on dependent variable (Price) - We will use the notion of the Standardised Coefficients to measure how much 1 SD change in the variable X (Predictor) changes Y (dependant) - From Tables 1.1 and 1.8 we can easily obtain the Standardised Coefficients for the regression variable and model for all variables except for RM as the SD of RM is not provided in table 1.1 and the Standardised coefficient of RM is not provided in table 1.8. Standardised Coefficient is calculated using: \begin{equation*} \beta_{STANDARDISED} = \hat\beta * \frac {S_X} {S_Y} \end{equation*} where \begin{equation*} \text{Standard Deviation X} = S_X \end{equation*} & \begin{equation*} \text{Standard Deviation Y} = S_Y \end{equation*} - To calculate the variance of RM we will use the Model 1 and Model 2 from table 1.8. In Model1 the coefficient of RM is 9.102 - In Model 2 the coefficient reduces to 8.391 on adding CRIM. This shows there is correlation among CRIM and RM which reduces the coefficient of RM in model 2. We can use the following equation to calculate SD of RM: \begin{equation*} \alpha_{RM_{Model1}} = \beta_{RM_{Model2}} + \frac{\beta_{CRIM_{Model2}} * Cor(RM, CRIM)} {Var(RM)} \end{equation*} - SD is square root of variance - From tabel 1.2 Cor(RM, CRIM) = -.219, Hence SD of RM = 2.13 - We can now use the SD of RM to calculate the standarddised coefficient for RM - From the below table we can see that **RM** has the highest impact on PRICE. ``` #print(((8.391 * .388) / (9.102 - 8.391))**0.5) data = pd.DataFrame({"_": ["INTERCEPT","RM","CRIM","RES","SEZ","Highway", "AGE"]}) data["Coefficients"] = [-8.993, 7.182, -.194, -.318, 4.499, -1.154, -.077] data["Standardized Coefficients"] = ['', 7.182 * 2.13 / 9.197, -.194 * 8.60154511 / 9.197, -.238, .0124, .208, -.077 * 28.1489 / 9.197] data ``` # Q 2.1 1. The model explains 42.25% of variation in box office collection. 2. There are outliers in the model. 3. The residuals do not follow a normal distribution. 4. The model cannot be used since R-square is low. 5. Box office collection increases as the budget increases. 1, 2, 3 are right ==> color / highlight # Q 2.2 Here Budget (X) can never be = 0, as it may not be possible to produce a movie without money and X = 0 is unobserved i.e. X = 0 falls outside the domain of the observed values of the variable X. The relationship between the variables can change as we move outside the observed region. We cannot predict for a point that is outside the range of observed values using the regression model. The Model explains the relationship between Y and X within the range of observed values only. Hence Mr Chellapa's observation is incorrect # Q 2.3 == check again? Since the variable is insignificant at alpha = 0.05, hence the coefficient may not be different from zero. There is is no statistical validity that the collection of movie released in Releasing_Time Normal_Season is different from Releasing_Time Holiday_Season (which is factored in the intercept / constant). Since we do not have the data hence we cannot rerun the model. We will assume that the co-efficient is 0 and it's removal does not have any effect on the overall equation (other significant variables). Hence the difference is **Zero**. ``` y = 2.685 + .147 #print("With beta = .147 y = {}".format(y)) #print("With beta = 0 y = {}".format(2.685)) ``` # Q 2.4 == check again? The beta for Release Normal Time is being considered as 0 as it is statistically insignificant at alpha. Hence it will be factored in the Intercept term. Releasing_Time Long_Weekend is statistically significant and the coefficient = 1.247. ``` Bmax = 1.247 + 1.964 *.588 print("Max B can be {}".format(Bmax)) Bmin = 1.247 - 1.964 *.588 print("Min B can be {}".format(Bmin)) print("Movies released in Long Wekends may earn upto 2.4 lac more than movies released in normal season.") print("Mr. Chellapa's statement is statistically incorrect.") ``` # Q 2.5 The increase in R-squared when a new variable is added to a model is the given by the **Square of the Semi-Partial (PART) Correlation**. - From Table 2.5 : R-squared @ Step 5 = 0.810 ** 2 = .6561 - From Table 2.6: PART Correlation for adding Director_CAT C = -.104 ``` print("R-squared in Step 3 is {}".format(0.6561 + (-.104) ** 2)) ``` # Q2.6 ==> Need to relook at this( can we do some hypothesis tests) - Budget_35_Cr is the highest impact on the performance of the movie. - Recommendation is to use high enough budget to hire Category A Production House, Category C Director and Music Director and produce a Comedy movie. # Q 2.7 - We cannot say that the variables have no relationship to Y (BOX Office Collection) - We can conclude that in presence of the other variables the variables in Model 2 are not explaining additional information about Y >> Formulate more nicely (charts and graphs are needed - Venn Diagram) ``` # Import the library import matplotlib.pyplot as plt from matplotlib_venn import venn3 x =10 # Make the diagram venn3(subsets = (x, 10, 10, 10, 10,10, 10)) plt.show() ``` # Q 2.8 We are making the assumption that the variable Youtube views imply views of the actual movie and not the trailers before movie release dates. The following explanation will not be valid in that case. Also, we are assuming that revenue collected from advertisements during Youtube views do not fall under the Box Office Collection. Youtube_Views = Will not contribute anything meaningful functionally to the Box Office collection as the movie has been created and released in theaters and all possible collection is completed. The main essence of the prediction here is to understand before making a movie, what all factors may lead to better revenue collection for a movie # Q 3.1 ### Table 3.1 - **Observations** (N) = 543 - **Standard Error** - \begin{equation*} SE = \sqrt {\frac{ \sum_{k=1}^N {(Y_k - \hat{Y_k})^2}} {N - 2}} \end{equation*} \begin{equation*} (Y_k - \hat{Y_k})^2 = \epsilon_k^2 = \text{Residual SS (SSE)} = \text{17104.06 (Table 3.2)}\end{equation*} - **R-Squared** = 1 - SSE / SST - SSE = 17104.06 (Table 3.2) - SST = 36481.89 (Table 3.2) - **Adjuated R-Squared** = 1 - (SSE / N-k-1) / (SST/N-1) - N = 543 - K = 3 - **Multiple R** = \begin{equation*} \sqrt R_{Squared}\end{equation*} ``` x = ["Multiple R", "R Square", "Adjusted R Squared", "Standard Error", "Observations"] data = pd.DataFrame({"Regression Statistics": x}) data["_"] = [(1 - 17104.06/36481.89) ** 0.5,1 - 17104.06/36481.89, 1 - (17104.06/(543 - 3 -1))/(36481.89/542),((17104.06)/541) ** 0.5,543] data ``` ### Table 3.2 - **DF Calculation** - DF for Regression (K) = Number of variables = 3 - DF for Residual = N - K - 1 = 539 - **SS Calculation** - Residual SS (SSE) = 17104.06 (given) - Total SS (TSS)= 36481.89 (given) - Regression SS (SSR) = TSS - SSE = 19377.83 - **MS Calculation** - MSR (Regression) = SSR / DF for SSR (=3) - MSE (Error) = SSE / DF for SSE (= 539) - **F Claculation** - F = MSR / MSE ``` x = ["Regression", "Residual", "Total"] ss = [36481.89 - 17104.06, 17104.06,36481.89] df = [3, 539,542] ms = [19377.83 / 2, 17104 / 539, ''] f = [(19377.83 / 2) / (17104 / 539),'',''] sf = [1 - sp.stats.f.cdf(305, 3, 539),'',''] data = pd.DataFrame({"_": x}) data["DF"] = df data["SS"] = ss data["MS"] = ms data["F"] = f data["SignificanceF"] = sf data ``` ### Table 3.3 - Coefficients - MLR T-Test - \begin{equation*} t_i = \frac {\beta_i - 0} {Se(\beta_i)}\end{equation*} where i denotes the different variables (here i = 3) ``` data = pd.DataFrame({"_":["Intercept", "Margin", "Gender", "College"]}) data["Coefficeints"] = [38.59235, 5.32e-05, 1.551306, -1.47506] data["Standard Error"] = [0.937225, 2.18e-06, 0.777806, 0.586995] data["t Stat"] = [(38.59235 / 0.937225),5.32e-05 / 2.18e-06, 1.551306/0.777806, -1.47506/ 0.586995] data["P-Value"] = ['','','',''] data["Lower 95%"] = [36.75129, 4.89E-05, 0.023404, -2.62814] data["Upper 95%"] = [40.4334106,5.7463E-05,3.07920835,-0.3219783] data ``` # Q 3.2 From the table above we see that for all the variables the t-value > 1.964. hence all the variables are significant. # Q 3.3 F-distribution with DF = 3, 539 at significance = 95% is 2.621. Hence the model is significant. ``` 1 - sp.stats.f.cdf(2.621, 3, 539) sp.stats.f.ppf(0.95, 3, 539) ``` # Q 3.4 The increase in R-squared when a new variable is added to a model is the given by the **Square of the Semi-Partial (PART) Correlation**. - R-squared for Model 2 = 0.52567 (R1) - R-squared for Model 3 = 0.531163 (R2) Part Correlation of College & % Votes = \begin{equation*}\sqrt{R_2 - R_1} \end{equation*} ``` print("Increase in R-Squared due to adding College = {}".format(0.531163 - 0.52567)) print("Part Correlation of College & % Votes = {}".format((0.531163 - 0.52567)**0.5)) ``` # Q 3.5 We will conduct Partial F-test between models to test for significance of each model. We make the assumption that the variables added are significant at each step (model) at alpha 0.05 \begin{equation*}F_{PARTIAL} = \frac{\frac{R_{FULL}^2 - R_{PARTIAL}^2} {k - r}} {\frac{1 - R_{FULL}^2} {N - k - 1}}\end{equation*} where k = variables in full model, r = variables in reduced model, N = Total number of records ``` def f_partial(rf, rp, n, k, r): return ((rf **2 - rp ** 2)/(k-r))/((1 - rf ** 2)/ (n - k - 1)) print("Model 3 Partial F {}".format(f_partial(0.531163, 0.52567, 543, 3, 2))) print("Model 3 Critical F at Df = (1, 539) {}".format(1 - sp.stats.f.cdf(4.36, 1, 539))) print("Model 4 Partial F {}".format(f_partial(0.56051, 0.531163, 543, 4, 3))) print("Model 4 Critical F at Df = (1, 539) {}".format(1 - sp.stats.f.cdf(25.13, 1, 539))) print("Model 5 Partial F {}".format(f_partial(0.581339, 0.56051, 543, 5, 4))) print("Model 5 Critical F at Df = (1, 539) {}".format(1 - sp.stats.f.cdf(19.29, 1, 539))) print("\nHence we can see that all the models are significant. The number of features (5) are not very high, hence we conclude it's justified to add the additional variables") ``` # Q 3.6 - Equations used for computing Standardized coefficients are provided in Q1.9 - Since the variables are not standardised we cannot use the magnitude of the coefficients as a measure of impact on dependent variable (Vote %) - We will use the notion of the Standardised Coefficients to measure how much 1 SD change in the variable X (Predictor) changes Y (dependant) - From the below table we can see that **MARGIN** has the highest impact on Vote %. 1 SD change in Margin changes .75 SD in Vote % ``` data = pd.DataFrame({"_": ["INTERCEPT","MARGIN","Gender","College","UP","AP"]}) data["Coefficients"] = [38.56993, 5.58E-05, 1.498308, -1.53774, -3.71439, 5.715821] data["Standard deviation"] = ['', 111365.7, 0.311494, 0.412796, 0.354761, 0.209766] data["Standardized Coefficients"] = ['', 5.58E-05 * 111365.7 / 8.204253, 1.498308 * 0.311494 / 8.204253, -1.53774 * 0.412796 / 8.204253, -3.71439 * 0.354761 / 8.204253, 5.715821 * 0.209766 / 8.204253] data ``` # Q 4.1 ``` positives = 353+692 negatives = 751+204 N = positives + negatives print("Total Positives: {} :: Total Negatives: {} :: Total Records: {}".format(positives, negatives, N)) pi1 = positives / N pi2 = negatives / N print("P(Y=1) = positives / N = {} :: P(Y=0) = negatives /N = {}".format(pi1, pi2)) _2LL0 = -2* (negatives * np.log(pi2) + positives * np.log(pi1)) print("-2LL0 = {}".format(_2LL0)) ``` - -2LLo is called the "Null Deviance" of a model. It is -2 Log Likelihood of a model which had no predictor variables. Hence we obtain the probabilities of positive and negative in the dataset using the frequencies for such model. - After adding "Premium" 2LL reduces to 2629.318 (Table 4.2). Hence reduction is equal to (-2LLo -(-2LLm)): ``` print(2768.537 - 2629.318) ``` # Q 4.2 ``` print("True Positive :Actually Positive and Predicted Positive = {}".format(692)) print("False Positive :Actually Negative and Predicted Positive = {}".format(204)) print("Precision = True Positive / (True Positive + False Positive) = {}".format(692.0 / (692 + 204))) ``` # Q 4.3 exp(B) = change in odds ratio. The odds ratio can be interpreted as the multiplicative adjustment to the odds of the outcome, given a **unit** change in the independent variable. In this case the unit of measurement for Premium (1 INR) which is very small compared to the actual Premium (1000s INR), hence a unit change does not lead to a meaningful change in odds ratio, subsequently the odds ratio will be very close to one. # Q 4.4 ``` print("The model predicts 751 + 353 = {} customers have a probability less than 0.5 of paying premium".format( 751+353)) print("The will call 1104 customers through Call Center") ``` # Q 4.5 Total points we are getting is 1960. total = tp + fp + fn + tn sensitivity = tp/ (tp + fn) specificity = tn / (tn + fp) recall = sensitivity precision = tp / (tp + fp) ``` tp = 60.0 fp = 20.0 fn = 51*20 tn = 43 * 20 total = tp + fp + fn + tn print(total) sensitivity = tp/ (tp + fn) specificity = tn / (tn + fp) recall = sensitivity precision = tp / (tp + fp) print("Precision {} :: \nRecall {} :: \nsensitivity {} :: \nspecificity {} ::".format(precision, recall, sensitivity, specificity)) ``` # Q 4.6 Probability can be calculated using the following formula: \begin{equation*} P(Y=1) = \frac{\exp^z} {1 + \exp^z} \end{equation*} \begin{equation*} \text{where z} = \beta_0 + \beta_1 * Salaried + \beta_2 * HouseWife +\beta_3 * others\end{equation*} However in this case the variable Housewife is not a significant variable. Hence using this equation to calculate probability for the variable house wife may not be appropriate. However we will procced to compute the probability using the equation, using the coefficient in the equation and also using the coefficient as 0 (B is not significantly different from 0 for insignificant variables) ``` print("Probability of House wife paying the Premium is (beta ==22.061): {}".format(np.exp(-.858 + 22.061) / (1 + np.exp(-.858 + 22.061)))) print("Probability of House wife paying the Premium is (beta = 0): {}".format(np.exp(-.858 + 0) / (1 + np.exp(-.858 + 0)))) print("Since Beta is insignificant Beta == 0, hence .298 is the probability for housewife paying renewal") ``` # Q 4.7 The Constant / Intercept measures for people with the following occupations **Professionals, Business and Agriculture** and they have a lower probability of renewal payment # Q 4.8 Probability can be calculated using the following formula: \begin{equation*} P(Y=1) = \frac{\exp^z} {1 + \exp^z} \end{equation*} \begin{equation*} \text{where z} = constant + \beta_1 * Policy Term\end{equation*} SSC Education, Agriculturist Profession & Marital Status Single will be factored in the term constant of the given equation. ``` print("Probability : {}".format(np.exp(3.105 + 60 * -0.026)/ (1 + np.exp(3.105 + 60 * -0.026)))) ``` # Q 4.9 The coefficients tell about the relationship between the independent variables and the dependent variable, where the dependent variable is on the logit scale. These estimates tell the amount of increase in the predicted log odds that would be predicted by a 1 unit increase in the predictor, holding all other predictors constant. **Recommendations** : - Married People has higher possibility of renewals (log odds ratio increases) - As payment term increases it leads to slightly reduced log odds of renewals - Professionals, Business men have much higher chance of defaulting on log odds of renewals - Being a graduate does increase the chance of log odds of renewals - Annual / Half yearly / Quarterly policy renewal schemes see reduced log odds of renewals - Model Change - Premuim : Variable scale should be changed for better understanding of Premium's contribution to affinity to renew policy (may be reduce unit to 1000s) - Strategy: - For new customers target Married people and graduates - For existing customers send more reminders (via Call centers / messgaes etc) to Business men, Professionals for renewal - For people paying premiums in yearly / quarterly / halfyearly terms, send reminders to them before renewal dates - For people with long payment terms keep sending them payment reminders as the tenure of their engagement increases # Q 4.10 Gain is calculated as: \begin{equation*} gain = \frac {\text{cumulative number of positive obs upto decile i}} {\text {Total number of positive observations}} \end{equation*} Lift is calculated as: \begin{equation*} lift = \frac {\text{cumulative number of positive obs upto decile i}} {\text {Total number of positive observations upto decile i from random model}} \end{equation*} ``` data = pd.DataFrame({'Decile': [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1]}) data['posunits'] = [31, 0, 0, 0, 3, 5, 5, 4, 2, 1] data['negunits'] = [0, 0, 0, 0, 0, 5, 11, 17, 12, 2] data['posCountunits'] = data['posunits'] * 20 data['negCountunits'] = data['negunits'] * 20 avgPerDec = np.sum(data['posCountunits']) / 10 data['avgCountunits'] = avgPerDec data['cumPosCountunits'] = data['posCountunits'].cumsum() data['cumAvgCountunits'] = data['avgCountunits'].cumsum() data['lift'] = data['cumPosCountunits'] / data['cumAvgCountunits'] data['gain'] = data['cumPosCountunits'] / data['posCountunits'].sum() data['avgLift'] = 1 #print(df) #### Plots plt.figure(figsize=(15, 5)) plt.subplot(1,2,1) plt.plot(data.avgLift, 'r-', label='Average Model Performance') plt.plot(data.lift, 'g-', label='Predict Model Performance') plt.title('Cumulative Lift Chart') plt.xlabel('Deciles') plt.ylabel('Normalised Model') plt.legend() plt.xlim(0, 10) plt.subplot(1,2,2) plt.plot(data.Decile, 'r-', label='Average Model Performance') plt.plot(data.gain, 'g-', label='Predict Model Performance') plt.title('Cumulative Gain Chart') plt.xlabel('Deciles') plt.ylabel('Gain') plt.legend() plt.xlim(0, 10) data ``` **Observaions** - From gain we see that the model captures 76% positives by the fifth decile - From Lift we see for the 1st decile model captures 6 times more positives than an ordinary model, 3 times for second decile, 2 times for 3rd decile, 1.5 times for 4th decile and 1.27 times for the 5th decile
github_jupyter
# Understanding linked list in Python ``` # define nodes class node(object): def __init__(self, x): self.value = x self.next = None # "next" is a pointer that connects this node with pther nodes # define a sequential linked list class seq_list(object): def __init__(self): self._head = None # linked list must have a head # an ultility that adds a new value from the head def add(self, x): node_new = node(x) # if no node exist if self._head is None: self._head = node_new # if at lead one node exist else: # temporally store the old head node and its downstream nodes temp = self._head # assign the new node as the head node self._head = node_new # assign the old head node as the next node self._head.next = temp def append(self, x): node_new = node(x) # if no node exist if self._head is None: self._head = node_new # if at least one node exist else: # duplicate a pointer from head (so the head node will not be changed) pointer_work = self._head # move to the tail of the list while pointer_work.next is not None: pointer_work = pointer_work.next pointer_work.next = node_new ``` # Create a linked list ``` list_test = seq_list() for i in range(10): list_test.add(i) list_test._head.value ``` # Advanced linked list operations ### Revert the list ``` def revert(list_head): ''' ''' if list_head is None: return list_head if list_head.next is None: return list_head pointer_work = list_head pointer_reverse = None temp = None while pointer_work is not None: temp = pointer_work.next pointer_work.next = pointer_reverse pointer_reverse = pointer_work pointer_work = temp return pointer_reverse head_reverse = revert(list_test._head) head_reverse.value ``` ### Return the last k-th node of a list ``` def index_from_tail(list_head, ind): ''' ''' if list_head is None: return list_head if list_head.next is None: return list_head assert ind >= 0, 'Input index "{}" should be non-negative'.format(ind) ind = int(ind) pointer_work = list_head pointer_tail = list_head i = 0 # shifts from work to tail while (pointer_tail.next is not None) and (i < ind): pointer_tail = pointer_tail.next i += 1 if i < ind: print("Warning: Input index is larger than the length of the linked list. The first node is returned") return list_head while pointer_tail.next is not None: pointer_work = pointer_work.next pointer_tail = pointer_tail.next return pointer_work node_ind = index_from_tail(list_test._head, 10) ``` ### Delete duplicated nodes ``` def unique(list_head): ''' ''' if list_head is None: return list_head if list_head.next is None: return list_head pointer_anchor = list_head while pointer_anchor is not None: #print(pointer_anchor.value) # identifier: node connections changed flag_change = False # two walkers start from the current anchor pointer_walk_step0 = pointer_anchor pointer_walk_step1 = pointer_anchor.next # anchor value val_anchor = pointer_anchor.value while pointer_walk_step1 is not None: # current walker value val_walk = pointer_walk_step1.value # found dups if val_anchor == val_walk: # delete dups pointer_walk_step0.next = pointer_walk_step1.next # move the two walkers pointer_walk_step0 = pointer_walk_step0.next pointer_walk_step1 = pointer_walk_step1.next # node connections changed after deleting dups flag_change = True else: # move the two walkers pointer_walk_step0 = pointer_walk_step0.next pointer_walk_step1 = pointer_walk_step1.next # if node connections not changed --> this anchor value is unique # --> move to the next anchor if not flag_change: pointer_anchor = pointer_anchor.next return list_head list_test = seq_list() list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(2) list_test.append(2) list_test.append(20) list_test.append(2) list_test.append(1) list_test.append(1) list_test.append(1) list_test.append(2) head_unique = unique(list_test._head) head_unique.next.next.next.value ``` ### delete nodes that a given value ``` def remove(list_head, x): ''' ''' if list_head is None: return list_head # upstream pointer pointer_upstream = None # output pointer (new list head) pointer_work = list_head # loop while not the last node while pointer_work is not None: # current node value val_work = pointer_work.value #print(val_work) # if it matches to the target if val_work == x: # if it is the 1st node if pointer_upstream is None: # delete temp = pointer_work.next pointer_work.next = None pointer_work = temp # also update the list head to the first valid position list_head = temp # if it is not the 1st node else: # delete pointer_upstream.next = pointer_work.next pointer_work = pointer_work.next else: # pointers move to the next node pointer_upstream = pointer_work pointer_work = pointer_work.next return list_head list_test = seq_list() list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(2) list_test.append(2) list_test.append(2) list_test.append(20) list_test.append(1) list_test.append(1) list_test.append(1) list_test.append(2) head_remove = remove(list_test._head, 20) ``` ### delete all the duplicated nodes ``` def unique_purge(list_head): ''' ''' if list_head is None: return list_head if list_head.next is None: return list_head pointer_anchor = list_head while pointer_anchor.next is not None: # pointer walk pointer_walk = pointer_anchor.next #anchor value val_anchor = pointer_anchor.value # identifier flag_change = False while pointer_walk is not None: val_walk = pointer_walk.value if val_walk == val_anchor: # found dups, remove all list_head = remove(list_head, val_walk) # ========== # # reset all the pointers if list_head is None: return list_head if list_head.next is None: return list_head pointer_anchor = list_head pointer_walk = list_head.next val_anchor = pointer_anchor.value #val_walk = pointer_walk.value # ========== # # the list is modified flag_change = True else: pointer_walk = pointer_walk.next if not flag_change: pointer_anchor = pointer_anchor.next return list_head list_test = seq_list() list_test.append(19) list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(0) list_test.append(2) list_test.append(2) list_test.append(2) list_test.append(20) list_test.append(1) list_test.append(1) list_test.append(1) list_test.append(2) list_test.append(21) head_purge = unique_purge(list_test._head) head_purge.next.next.value ``` ### Merge two ascending lists ``` def merge_ascending(list_head1, list_head2): ''' ''' if list_head1 is None: return list_head2 if list_head2 is None: return list_head1 node_init = node(-9999) head_new = node_init pointer1 = list_head1 #.next pointer2 = list_head2 #.next while (pointer1 is not None) and (pointer2 is not None): temp_val1 = pointer1.value temp_val2 = pointer2.value # list1 value is lower, collect it if temp_val1 <= temp_val2: head_new.next = pointer1 head_new = head_new.next pointer1 = pointer1.next # list2 value is lower otherwise else: head_new.next = pointer2 head_new = head_new.next pointer2 = pointer2.next # list2 runs out, list1 remains if pointer1 is not None: head_new.next = pointer1 # list1 runs out else: head_new.next = pointer2 return node_init.next list_test1 = seq_list() list_test1.append(1) list_test1.append(3) list_test1.append(5) list_test1.append(7) list_test1.append(9) list_test1.append(11) list_test2 = seq_list() list_test2.append(0) list_test2.append(2) list_test2.append(4) list_test2.append(6) list_test2.append(8) list_test2.append(10) list_test2.append(12) head_merge = merge_ascending(list_test1._head, list_test2._head) ``` ### Copy a list ``` def copy_list(list_head): ''' ''' if list_head is None: return list_head head_new = node(-9999) pointer = head_new while list_head is not None: temp_val = list_head.value pointer.next = node(temp_val) pointer = pointer.next list_head = list_head.next return head_new.next list_test = seq_list() list_test.append(1) list_test.append(3) copy_head = copy_list(list_test._head) copy_head.next.value ```
github_jupyter
# A Brief Intro to pydeck pydeck is made for visualizing data points in 2D or 3D maps. Specifically, it handles - rendering large (>1M points) data sets, like LIDAR point clouds or GPS pings - large-scale updates to data points, like plotting points with motion - making beautiful maps Under the hood, it's powered by the [deck.gl](https://github.com/uber/deck.gl/) JavaScript framework. pydeck is strongest when used in tandem with [Pandas](https://pandas.pydata.org/) but doesn't have to be. Please note that **these demo notebooks are best when executed cell-by-cell**, so ideally clone this repo. ``` import pydeck as pdk ``` # There are three steps for most pydeck visualizations We'll walk through pydeck using a visualization of vehicle accident data in the United Kingdom. ## 1. Choose your data Here, we'll use the history of accident data throughout the United Kingdom. This data set presents the location of every latitude and longitude of car accidents in the UK in 2014 ([source](https://data.gov.uk/dataset/053a6529-6c8c-42ac-ae1e-455b2708e535/road-traffic-accidents)). ``` import pandas as pd UK_ACCIDENTS_DATA = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv' pd.read_csv(UK_ACCIDENTS_DATA).head() ``` ## 2. Configure the visualization: Choose your layer(s) and viewport pydeck's **`Layer`** object takes two positional and many keyword arguments: - First, a string specifying the layer type, with our example below using `'HexagonLayer'` - Next, a data URL–below you'll see the `UK_ACCIDENTS_DATA` that we set above, but we could alternately pass a data frame or list of dictionaries - Finally, keywords representing that layer's attributes–in our example, this would include `elevation_scale`, `elevation_range`, `extruded`, `coverage`. ```python layer = pdk.Layer( 'HexagonLayer', UK_ACCIDENTS_DATA, elevation_scale=50, elevation_range=[0, 3000], extruded=True, coverage=1) ``` There is of course an entire catalog of layers which you're welcome to check out within the [deck.gl documentation](https://deck.gl/#/documentation/deckgl-api-reference/layers/overview). ### Configure your viewport We also have to specifiy a **`ViewState`** object. The **`ViewState`** object specifies a camera angle relative to the map data. If you don't want to manually specify it, the function **`pydeck.data_utils.autocompute_viewport`** can take your data and automatically zoom to it. pydeck also provides some controls, most of which should be familiar from map applications throughout the web. By default, you can hold out and drag to rotate the map. ``` layer = pdk.Layer( 'HexagonLayer', UK_ACCIDENTS_DATA, elevation_scale=50, elevation_range=[0, 3000], extruded=True, coverage=1) # Set the viewport location view_state = pdk.ViewState( longitude=-1.415, latitude=52.2323, zoom=6, min_zoom=5, max_zoom=15, pitch=40.5, bearing=-27.396) # Combined all of it and render a viewport r = pdk.Deck(layers=[layer], initial_view_state=view_state) r.show() ``` ## Render an update to the visualization Execute the cell below and look at the map in the cell above–you'll notice a seamless rendered update on the map ``` layer.elevation_range = [0, 5000] r.update() ``` ## Support updates over time We can combine any Python function with our work here, of course. Execute the cell below to update our map above over time. ``` import time for i in range(0, 10000, 1000): layer.elevation_range = [0, i] r.update() time.sleep(0.1) ```
github_jupyter
<img src="https://github.com/pmservice/ai-openscale-tutorials/raw/master/notebooks/images/banner.png" align="left" alt="banner"> This notebook should be run in a Watson Studio project, using Default Python 3.7.x runtime environment. If you are viewing this in Watson Studio and do not see Python 3.7.x in the upper right corner of your screen, please update the runtime now. ## Prerequisites To run this notebook, you must provide the following information. - IBMid and IBM Cloud instance - two (2) instances of IBM Watson Machine Learning - instance of IBM Watson OpenScale ## Provision services and configure credentials If you have not already, provision an instance of IBM Watson OpenScale and two instances of IBM Watson Machine Learning using the Cloud catalog. Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. NOTE: You can also get OpenScale API_KEY using IBM CLOUD CLI. How to install IBM Cloud (bluemix) console: [Instructions](https://console.bluemix.net/docs/cli/reference/ibmcloud/download_cli.html#install_use) **Connection to WML** Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide platform api_key and instance location. You can use IBM Cloud CLI to retrieve platform API Key and instance location. API Key can be generated in the following way: ``` ibmcloud login ibmcloud iam api-key-create API_KEY_NAME In result, get the value of api_key from the output. ``` Location of your WML instance can be retrieved in the following way: ``` ibmcloud login --apikey API_KEY -a https://cloud.ibm.com ibmcloud resource service-instances ibmcloud resource service-instance WML_INSTANCE_NAME ibmcloud resource service-instance COS_INSTANCE_NAME ``` In result, get the value of location from the output. In the output, you can also get: - **name of the service instance CRN (ID) and Name (name)** that can be used in next steps. Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below. ``` ##################################################################################### # Paste your IBM Cloud API key, WML CRN in the following field and then run this cell. ###################################################################################### CLOUD_API_KEY = "***" WML_INSTANCE_NAME="***" WML_CRN="***" COS_API_KEY_ID = "***" COS_RESOURCE_CRN = "***" # eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003abfb5d29761c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::" COS_ENDPOINT = "***" # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints BUCKET_NAME = "***" #example: "credit-risk-training-data" training_data_file_name="german_credit_data_biased_training.csv" WML_CREDENTIALS = { "url": "https://us-south.ml.cloud.ibm.com", "apikey": CLOUD_API_KEY } DB_CREDENTIALS=None #DB_CREDENTIALS= {"hostname":"","username":"","password":"","database":"","port":"","ssl":True,"sslmode":"","certificate_base64":""} KEEP_MY_INTERNAL_POSTGRES = True IAM_URL="https://iam.ng.bluemix.net/oidc/token" ``` ## Package installation The following opensource packages must be installed into this notebook instance so that they are available to use during processing. ``` !pip install pyspark==2.4.0 --no-cache | tail -n 1 !rm -rf /home/spark/shared/user-libs/python3.7* !pip install --upgrade pandas==1.2.3 --no-cache | tail -n 1 !pip install --upgrade requests==2.23 --no-cache | tail -n 1 !pip install --upgrade numpy==1.20.3 --user --no-cache | tail -n 1 !pip install SciPy --no-cache | tail -n 1 !pip install lime --no-cache | tail -n 1 !pip install --upgrade ibm-watson-machine-learning --user | tail -n 1 !pip install --upgrade ibm-watson-openscale --no-cache | tail -n 1 import json import requests import base64 from requests.auth import HTTPBasicAuth import time ``` ## Load the training data from Github So you don't have to manually generate training data, we've provided a sample and placed it in a publicly available Github repo. ``` !rm german_credit_data_biased_training.csv !wget https://raw.githubusercontent.com/IBM/watson-openscale-samples/main/IBM%20Cloud/WML/assets/data/credit_risk/german_credit_data_biased_training.csv import pandas as pd pd_data = pd.read_csv("german_credit_data_biased_training.csv", sep=",", header=0) import ibm_boto3 from ibm_botocore.client import Config, ClientError cos_client = ibm_boto3.resource("s3", ibm_api_key_id=COS_API_KEY_ID, ibm_service_instance_id=COS_RESOURCE_CRN, ibm_auth_endpoint="https://iam.bluemix.net/oidc/token", config=Config(signature_version="oauth"), endpoint_url=COS_ENDPOINT ) with open(training_data_file_name, "rb") as file_data: cos_client.Object(BUCKET_NAME, training_data_file_name).upload_fileobj( Fileobj=file_data ) ``` ## Deploy the Spark Credit Risk Model to Watson Machine Learning The following cell deploys the Spark version of the German Credit Risk Model to the specified Machine Learning instance in the specified deployment space. You'll notice that this version of the German Credit Risk model has an auc-roc score around 71%. ``` from ibm_watson_machine_learning import APIClient wml_client = APIClient(WML_CREDENTIALS) wml_client.version wml_client.spaces.list(limit=10) space_name ="pre-prod-space" spaces = wml_client.spaces.get_details()['resources'] preprod_space_id = None for space in spaces: if space['entity']['name'] == space_name: preprod_space_id = space["metadata"]["id"] if preprod_space_id is None: preprod_space_id = wml_client.spaces.store( meta_props={wml_client.spaces.ConfigurationMetaNames.NAME: space_name, wml_client.spaces.ConfigurationMetaNames.STORAGE: {"resource_crn":COS_RESOURCE_CRN}, wml_client.spaces.ConfigurationMetaNames.COMPUTE: {"name": WML_INSTANCE_NAME, "crn": WML_CRN}})["metadata"]["id"] wml_client.set.default_space(preprod_space_id) print(preprod_space_id) def deploy_credit_risk_spark_model(wml_credentials, model_name, deployment_name,space_id): import numpy numpy.version.version import pandas as pd import json from pyspark import SparkContext, SQLContext from pyspark.ml import Pipeline from pyspark.ml.classification import RandomForestClassifier,GBTClassifier from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml.feature import StringIndexer, VectorAssembler, IndexToString from pyspark.sql.types import StructType, DoubleType, StringType, ArrayType from pyspark.sql import SparkSession from pyspark import SparkFiles spark = SparkSession.builder.getOrCreate() pd_data = pd.read_csv("german_credit_data_biased_training.csv", sep=",", header=0) spark_df = spark.read.csv(path="german_credit_data_biased_training.csv", sep=",", header=True, inferSchema=True) spark_df.head() (train_data, test_data) = spark_df.randomSplit([0.9, 0.1], 24) print("Number of records for training: " + str(train_data.count())) print("Number of records for evaluation: " + str(test_data.count())) si_CheckingStatus = StringIndexer(inputCol='CheckingStatus', outputCol='CheckingStatus_IX') si_CreditHistory = StringIndexer(inputCol='CreditHistory', outputCol='CreditHistory_IX') si_LoanPurpose = StringIndexer(inputCol='LoanPurpose', outputCol='LoanPurpose_IX') si_ExistingSavings = StringIndexer(inputCol='ExistingSavings', outputCol='ExistingSavings_IX') si_EmploymentDuration = StringIndexer(inputCol='EmploymentDuration', outputCol='EmploymentDuration_IX') si_Sex = StringIndexer(inputCol='Sex', outputCol='Sex_IX') si_OthersOnLoan = StringIndexer(inputCol='OthersOnLoan', outputCol='OthersOnLoan_IX') si_OwnsProperty = StringIndexer(inputCol='OwnsProperty', outputCol='OwnsProperty_IX') si_InstallmentPlans = StringIndexer(inputCol='InstallmentPlans', outputCol='InstallmentPlans_IX') si_Housing = StringIndexer(inputCol='Housing', outputCol='Housing_IX') si_Job = StringIndexer(inputCol='Job', outputCol='Job_IX') si_Telephone = StringIndexer(inputCol='Telephone', outputCol='Telephone_IX') si_ForeignWorker = StringIndexer(inputCol='ForeignWorker', outputCol='ForeignWorker_IX') si_Label = StringIndexer(inputCol="Risk", outputCol="label").fit(spark_df) label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=si_Label.labels) va_features = VectorAssembler( inputCols=["CheckingStatus_IX", "CreditHistory_IX", "LoanPurpose_IX", "ExistingSavings_IX", "EmploymentDuration_IX", "Sex_IX", "OthersOnLoan_IX", "OwnsProperty_IX", "InstallmentPlans_IX", "Housing_IX", "Job_IX", "Telephone_IX", "ForeignWorker_IX", "LoanDuration", "LoanAmount", "InstallmentPercent", "CurrentResidenceDuration", "LoanDuration", "Age", "ExistingCreditsCount", "Dependents"], outputCol="features") classifier=GBTClassifier(featuresCol="features") pipeline = Pipeline( stages=[si_CheckingStatus, si_CreditHistory, si_EmploymentDuration, si_ExistingSavings, si_ForeignWorker, si_Housing, si_InstallmentPlans, si_Job, si_LoanPurpose, si_OthersOnLoan, si_OwnsProperty, si_Sex, si_Telephone, si_Label, va_features, classifier, label_converter]) model = pipeline.fit(train_data) predictions = model.transform(test_data) evaluator = BinaryClassificationEvaluator(rawPredictionCol="prediction") auc = evaluator.evaluate(predictions) print("Accuracy = %g" % auc) from ibm_watson_machine_learning import APIClient wml_client = APIClient(WML_CREDENTIALS) wml_client.version wml_client.set.default_space(space_id) # Remove existing model and deployment MODEL_NAME=model_name DEPLOYMENT_NAME=deployment_name deployments_list = wml_client.deployments.get_details() for deployment in deployments_list["resources"]: model_id = deployment["entity"]["asset"]["id"] deployment_id = deployment["metadata"]["id"] if deployment["metadata"]["name"] == DEPLOYMENT_NAME: print("Deleting deployment id", deployment_id) wml_client.deployments.delete(deployment_id) print("Deleting model id", model_id) wml_client.repository.delete(model_id) wml_client.repository.list_models() training_data_reference = [ { "id": "credit risk", "type": "s3", "connection": { "access_key_id": COS_API_KEY_ID, "endpoint_url": COS_ENDPOINT, "resource_instance_id":COS_RESOURCE_CRN }, "location": { "bucket": BUCKET_NAME, "path": training_data_file_name, } } ] # Save Model software_spec_uid = wml_client.software_specifications.get_id_by_name("spark-mllib_2.4") print("Software Specification ID: {}".format(software_spec_uid)) model_props = { wml_client._models.ConfigurationMetaNames.NAME:"{}".format(MODEL_NAME), #wml_client._models.ConfigurationMetaNames.SPACE_UID: space_id, wml_client._models.ConfigurationMetaNames.TYPE: "mllib_2.4", wml_client._models.ConfigurationMetaNames.SOFTWARE_SPEC_UID: software_spec_uid, wml_client._models.ConfigurationMetaNames.TRAINING_DATA_REFERENCES: training_data_reference, wml_client._models.ConfigurationMetaNames.LABEL_FIELD: "Risk", } print("Storing model ...") published_model_details = wml_client.repository.store_model( model=model, meta_props=model_props, training_data=train_data, pipeline=pipeline) model_uid = wml_client.repository.get_model_uid(published_model_details) print("Done") print("Model ID: {}".format(model_uid)) # Deploy model deployment_details = wml_client.deployments.create( model_uid, meta_props={ wml_client.deployments.ConfigurationMetaNames.NAME: "{}".format(DEPLOYMENT_NAME), wml_client.deployments.ConfigurationMetaNames.ONLINE: {} } ) scoring_url = wml_client.deployments.get_scoring_href(deployment_details) deployment_uid=wml_client.deployments.get_uid(deployment_details) print("Scoring URL:" + scoring_url) print("Model id: {}".format(model_uid)) print("Deployment id: {}".format(deployment_uid)) fields = ["CheckingStatus","LoanDuration","CreditHistory","LoanPurpose","LoanAmount","ExistingSavings","EmploymentDuration","InstallmentPercent","Sex","OthersOnLoan","CurrentResidenceDuration","OwnsProperty","Age","InstallmentPlans","Housing","ExistingCreditsCount","Job","Dependents","Telephone","ForeignWorker"] values = [ ["no_checking",13,"credits_paid_to_date","car_new",1343,"100_to_500","1_to_4",2,"female","none",3,"savings_insurance",46,"none","own",2,"skilled",1,"none","yes"], ["no_checking",24,"prior_payments_delayed","furniture",4567,"500_to_1000","1_to_4",4,"male","none",4,"savings_insurance",36,"none","free",2,"management_self-employed",1,"none","yes"], ["0_to_200",26,"all_credits_paid_back","car_new",863,"less_100","less_1",2,"female","co-applicant",2,"real_estate",38,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",14,"no_credits","car_new",2368,"less_100","1_to_4",3,"female","none",3,"real_estate",29,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",4,"no_credits","car_new",250,"less_100","unemployed",2,"female","none",3,"real_estate",23,"none","rent",1,"management_self-employed",1,"none","yes"], ["no_checking",17,"credits_paid_to_date","car_new",832,"100_to_500","1_to_4",2,"male","none",2,"real_estate",42,"none","own",1,"skilled",1,"none","yes"], ["no_checking",33,"outstanding_credit","appliances",5696,"unknown","greater_7",4,"male","co-applicant",4,"unknown",54,"none","free",2,"skilled",1,"yes","yes"], ["0_to_200",13,"prior_payments_delayed","retraining",1375,"100_to_500","4_to_7",3,"male","none",3,"real_estate",37,"none","own",2,"management_self-employed",1,"none","yes"] ] scoring_payload = {"input_data": [{"fields": fields, "values": values}]} #print(scoring_payload) scoring_response = wml_client.deployments.score(deployment_uid, scoring_payload) print(scoring_response) return model_uid, deployment_uid, scoring_url ``` ## Deploy the Scikit-Learn Credit Risk Model to Watson Machine Learning The following cell deploys the Scikit-learn version of the German Credit Risk Model to the specified Machine Learning instance in the specified deployment space. This version of the German Credit Risk model has an auc-roc score around 85% and will be called the "Challenger." ``` def deploy_credit_risk_scikit_model(wml_credentials, model_name, deployment_name,space_id): import pandas as pd import json import sys import numpy import sklearn import sklearn.ensemble numpy.set_printoptions(threshold=sys.maxsize) from sklearn.utils.multiclass import type_of_target from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OrdinalEncoder from sklearn.compose import ColumnTransformer from sklearn.model_selection import cross_validate from sklearn.metrics import get_scorer from sklearn.model_selection import cross_validate from sklearn.metrics import classification_report data_df=pd.read_csv ("german_credit_data_biased_training.csv") data_df.head() target_label_name = "Risk" feature_cols= data_df.drop(columns=[target_label_name]) label= data_df[target_label_name] # Set model evaluation properties optimization_metric = 'roc_auc' random_state = 33 cv_num_folds = 3 holdout_fraction = 0.1 if type_of_target(label.values) in ['multiclass', 'binary']: X_train, X_holdout, y_train, y_holdout = train_test_split(feature_cols, label, test_size=holdout_fraction, random_state=random_state, stratify=label.values) else: X_train, X_holdout, y_train, y_holdout = train_test_split(feature_cols, label, test_size=holdout_fraction, random_state=random_state) # Data preprocessing transformer generation numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) categorical_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='most_frequent')), ('OrdinalEncoder', OrdinalEncoder(categories='auto',dtype=numpy.float64 ))]) numeric_features = feature_cols.select_dtypes(include=['int64', 'float64']).columns categorical_features = feature_cols.select_dtypes(include=['object']).columns preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features)]) # Initiate model and create pipeline model=sklearn.ensemble.GradientBoostingClassifier() gbt_pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', model)]) model_gbt=gbt_pipeline.fit(X_train, y_train) y_pred = model_gbt.predict(X_holdout) # Evaluate model performance on test data and Cross validation scorer = get_scorer(optimization_metric) scorer(model_gbt,X_holdout, y_holdout) # Cross validation -3 folds cv_results = cross_validate(model_gbt,X_train,y_train, scoring={optimization_metric:scorer}) numpy.mean(cv_results['test_' + optimization_metric]) print(classification_report(y_pred, y_holdout)) # Initiate WML from ibm_watson_machine_learning import APIClient wml_client = APIClient(WML_CREDENTIALS) wml_client.version wml_client.set.default_space(space_id) # Remove existing model and deployment MODEL_NAME=model_name DEPLOYMENT_NAME=deployment_name deployments_list = wml_client.deployments.get_details() for deployment in deployments_list["resources"]: model_id = deployment["entity"]["asset"]["id"] deployment_id = deployment["metadata"]["id"] if deployment["metadata"]["name"] == DEPLOYMENT_NAME: print("Deleting deployment id", deployment_id) wml_client.deployments.delete(deployment_id) print("Deleting model id", model_id) wml_client.repository.delete(model_id) wml_client.repository.list_models() # Store Model #Note if there is specification related exception or specification ID is None then use "default_py3.8" instead of "default_py3.7_opence" software_spec_uid = wml_client.software_specifications.get_id_by_name("default_py3.7_opence") print("Software Specification ID: {}".format(software_spec_uid)) training_data_reference = [ { "id": "credit risk", "type": "s3", "connection": { "access_key_id": COS_API_KEY_ID, "endpoint_url": COS_ENDPOINT, "resource_instance_id":COS_RESOURCE_CRN }, "location": { "bucket": BUCKET_NAME, "path": training_data_file_name, } } ] model_props = { wml_client._models.ConfigurationMetaNames.NAME:"{}".format(MODEL_NAME), #wml_client._models.ConfigurationMetaNames.SPACE_UID: space_id, wml_client._models.ConfigurationMetaNames.TYPE: "scikit-learn_0.23", wml_client._models.ConfigurationMetaNames.SOFTWARE_SPEC_UID: software_spec_uid, wml_client._models.ConfigurationMetaNames.TRAINING_DATA_REFERENCES: training_data_reference, wml_client._models.ConfigurationMetaNames.LABEL_FIELD: "Risk", } print("Storing model ...") published_model_details = wml_client.repository.store_model(model=model_gbt, meta_props=model_props, training_data=feature_cols, training_target=label) model_uid = wml_client.repository.get_model_uid(published_model_details) print("Done") print("Model ID: {}".format(model_uid)) # Deploy model print("Deploying model...") deployment_details = wml_client.deployments.create( model_uid, meta_props={ wml_client.deployments.ConfigurationMetaNames.NAME: "{}".format(DEPLOYMENT_NAME), wml_client.deployments.ConfigurationMetaNames.ONLINE: {} } ) scoring_url = wml_client.deployments.get_scoring_href(deployment_details) deployment_uid=wml_client.deployments.get_uid(deployment_details) print("Scoring URL:" + scoring_url) print("Model id: {}".format(model_uid)) print("Deployment id: {}".format(deployment_uid)) # Sample scoring fields = ["CheckingStatus","LoanDuration","CreditHistory","LoanPurpose","LoanAmount","ExistingSavings","EmploymentDuration","InstallmentPercent","Sex","OthersOnLoan","CurrentResidenceDuration","OwnsProperty","Age","InstallmentPlans","Housing","ExistingCreditsCount","Job","Dependents","Telephone","ForeignWorker"] values = [ ["no_checking",13,"credits_paid_to_date","car_new",1343,"100_to_500","1_to_4",2,"female","none",3,"savings_insurance",46,"none","own",2,"skilled",1,"none","yes"], ["no_checking",24,"prior_payments_delayed","furniture",4567,"500_to_1000","1_to_4",4,"male","none",4,"savings_insurance",36,"none","free",2,"management_self-employed",1,"none","yes"], ["0_to_200",26,"all_credits_paid_back","car_new",863,"less_100","less_1",2,"female","co-applicant",2,"real_estate",38,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",14,"no_credits","car_new",2368,"less_100","1_to_4",3,"female","none",3,"real_estate",29,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",4,"no_credits","car_new",250,"less_100","unemployed",2,"female","none",3,"real_estate",23,"none","rent",1,"management_self-employed",1,"none","yes"], ["no_checking",17,"credits_paid_to_date","car_new",832,"100_to_500","1_to_4",2,"male","none",2,"real_estate",42,"none","own",1,"skilled",1,"none","yes"], ["no_checking",33,"outstanding_credit","appliances",5696,"unknown","greater_7",4,"male","co-applicant",4,"unknown",54,"none","free",2,"skilled",1,"yes","yes"], ["0_to_200",13,"prior_payments_delayed","retraining",1375,"100_to_500","4_to_7",3,"male","none",3,"real_estate",37,"none","own",2,"management_self-employed",1,"none","yes"] ] payload_scoring = {"input_data": [{"fields": fields, "values": values}]} #print(payload_scoring) scoring_response = wml_client.deployments.score(deployment_uid, payload_scoring) print(scoring_response) return model_uid, deployment_uid, scoring_url ``` # Deploy the models The following cells will deploy both the PreProd and Challenger models into the WML instance that is designated as Pre-Production. ``` PRE_PROD_MODEL_NAME="German Credit Risk Model - PreProd" PRE_PROD_DEPLOYMENT_NAME="German Credit Risk Model - PreProd" PRE_PROD_CHALLENGER_MODEL_NAME="German Credit Risk Model - Challenger" PRE_PROD_CHALLENGER_DEPLOYMENT_NAME="German Credit Risk Model - Challenger" pre_prod_model_uid, pre_prod_deployment_uid, pre_prod_scoring_url = deploy_credit_risk_spark_model(WML_CREDENTIALS, PRE_PROD_MODEL_NAME, PRE_PROD_DEPLOYMENT_NAME,preprod_space_id) challenger_model_uid, challenger_deployment_uid, challenger_scoring_url = deploy_credit_risk_scikit_model(WML_CREDENTIALS, PRE_PROD_CHALLENGER_MODEL_NAME, PRE_PROD_CHALLENGER_DEPLOYMENT_NAME,preprod_space_id) ``` # Configure OpenScale The notebook will now import the necessary libraries and set up a Python OpenScale client. ``` from ibm_cloud_sdk_core.authenticators import IAMAuthenticator,BearerTokenAuthenticator from ibm_watson_openscale import * from ibm_watson_openscale.supporting_classes.enums import * from ibm_watson_openscale.supporting_classes import * authenticator = IAMAuthenticator(apikey=CLOUD_API_KEY) #authenticator = BearerTokenAuthenticator(bearer_token=IAM_TOKEN) ## uncomment if using IAM token wos_client = APIClient(authenticator=authenticator) wos_client.version ``` ## Create schema and datamart ### Set up datamart Watson OpenScale uses a database to store payload logs and calculated metrics. If database credentials were not supplied above, the notebook will use the free, internal lite database. If database credentials were supplied, the datamart will be created there unless there is an existing datamart and the KEEP_MY_INTERNAL_POSTGRES variable is set to True. If an OpenScale datamart exists in Db2 or PostgreSQL, the existing datamart will be used and no data will be overwritten. Prior instances of the German Credit model will be removed from OpenScale monitoring. ``` data_marts = wos_client.data_marts.list().result.data_marts if len(data_marts) == 0: if DB_CREDENTIALS is not None: if SCHEMA_NAME is None: print("Please specify the SCHEMA_NAME and rerun the cell") print('Setting up external datamart') added_data_mart_result = wos_client.data_marts.add( background_mode=False, name="WOS Data Mart", description="Data Mart created by WOS tutorial notebook", database_configuration=DatabaseConfigurationRequest( database_type=DatabaseType.POSTGRESQL, credentials=PrimaryStorageCredentialsLong( hostname=DB_CREDENTIALS['hostname'], username=DB_CREDENTIALS['username'], password=DB_CREDENTIALS['password'], db=DB_CREDENTIALS['database'], port=DB_CREDENTIALS['port'], ssl=True, sslmode=DB_CREDENTIALS['sslmode'], certificate_base64=DB_CREDENTIALS['certificate_base64'] ), location=LocationSchemaName( schema_name= SCHEMA_NAME ) ) ).result else: print('Setting up internal datamart') added_data_mart_result = wos_client.data_marts.add( background_mode=False, name="WOS Data Mart", description="Data Mart created by WOS tutorial notebook", internal_database = True).result data_mart_id = added_data_mart_result.metadata.id else: data_mart_id=data_marts[0].metadata.id print('Using existing datamart {}'.format(data_mart_id)) ``` ## Bind WML machine learning instance as Pre-Prod Watson OpenScale needs to be bound to the Watson Machine Learning instance to capture payload data into and out of the model. If a binding with name "WML Pre-Prod" already exists, this code will delete that binding a create a new one. ``` SERVICE_PROVIDER_NAME = "Watson Machine Learning pre-prod openpage" SERVICE_PROVIDER_DESCRIPTION = "Added by tutorial WOS notebook." service_providers = wos_client.service_providers.list().result.service_providers for service_provider in service_providers: service_instance_name = service_provider.entity.name if service_instance_name == SERVICE_PROVIDER_NAME: service_provider_id = service_provider.metadata.id wos_client.service_providers.delete(service_provider_id) print("Deleted existing service_provider for WML instance: {}".format(service_provider_id)) added_service_provider_result = wos_client.service_providers.add( name=SERVICE_PROVIDER_NAME, description=SERVICE_PROVIDER_DESCRIPTION, service_type=ServiceTypes.WATSON_MACHINE_LEARNING, deployment_space_id = preprod_space_id, # use pre-prod space ID operational_space_id = "pre_production", credentials=WMLCredentialsCloud( apikey=CLOUD_API_KEY, ## use `apikey=IAM_TOKEN` if using IAM_TOKEN to initiate client url=WML_CREDENTIALS["url"], instance_id=None ), background_mode=False ).result service_provider_id = added_service_provider_result.metadata.id service_provider_id asset_deployment_details = wos_client.service_providers.list_assets(data_mart_id=data_mart_id, service_provider_id=service_provider_id, deployment_space_id = preprod_space_id).result['resources'][1] asset_deployment_details model_asset_details_from_deployment=wos_client.service_providers.get_deployment_asset(data_mart_id=data_mart_id,service_provider_id=service_provider_id,deployment_id=pre_prod_deployment_uid,deployment_space_id=preprod_space_id) model_asset_details_from_deployment ``` ## Generate an IAM token The following is a function that will generate an IAM access token used to interact with the Watson OpenScale APIs ``` def generate_access_token(): headers={} headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Accept"] = "application/json" auth = HTTPBasicAuth("bx", "bx") data = { "grant_type": "urn:ibm:params:oauth:grant-type:apikey", "apikey": CLOUD_API_KEY } response = requests.post(IAM_URL, data=data, headers=headers, auth=auth) json_data = response.json() iam_access_token = json_data['access_token'] return iam_access_token ``` ## Subscriptions ### Remove existing PreProd and Challenger credit risk subscriptions This code removes previous subscriptions with name `German Credit Risk Model - PreProd` and `German Credit Risk Model - Challenger` to refresh the monitors with the new model and new data. ``` subscriptions = wos_client.subscriptions.list().result.subscriptions for subscription in subscriptions: sub_model_name = subscription.entity.asset.name if sub_model_name == PRE_PROD_MODEL_NAME or sub_model_name == PRE_PROD_CHALLENGER_MODEL_NAME : wos_client.subscriptions.delete(subscription.metadata.id) print('Deleted existing subscription for model', subscription.entity.asset.asset_id) from ibm_watson_openscale.base_classes.watson_open_scale_v2 import ScoringEndpointRequest pre_prod_subscription_details = wos_client.subscriptions.add( data_mart_id=data_mart_id, service_provider_id=service_provider_id, asset=Asset( asset_id=model_asset_details_from_deployment["entity"]["asset"]["asset_id"], name=model_asset_details_from_deployment["entity"]["asset"]["name"], url=model_asset_details_from_deployment["entity"]["asset"]["url"], asset_type=AssetTypes.MODEL, input_data_type=InputDataType.STRUCTURED, problem_type=ProblemType.BINARY_CLASSIFICATION ), deployment=AssetDeploymentRequest( deployment_id=asset_deployment_details['metadata']['guid'], name=asset_deployment_details['entity']['name'], deployment_type= DeploymentTypes.ONLINE, url=asset_deployment_details['metadata']['url'], scoring_endpoint=ScoringEndpointRequest(url=pre_prod_scoring_url) # score model without shadow deployment ), asset_properties=AssetPropertiesRequest( label_column='Risk', probability_fields=['probability'], prediction_field='predictedLabel', feature_fields = ["CheckingStatus","LoanDuration","CreditHistory","LoanPurpose","LoanAmount","ExistingSavings","EmploymentDuration","InstallmentPercent","Sex","OthersOnLoan","CurrentResidenceDuration","OwnsProperty","Age","InstallmentPlans","Housing","ExistingCreditsCount","Job","Dependents","Telephone","ForeignWorker"], categorical_fields = ["CheckingStatus","CreditHistory","LoanPurpose","ExistingSavings","EmploymentDuration","Sex","OthersOnLoan","OwnsProperty","InstallmentPlans","Housing","Job","Telephone","ForeignWorker"], training_data_reference=TrainingDataReference(type='cos', location=COSTrainingDataReferenceLocation(bucket = BUCKET_NAME, file_name = training_data_file_name), connection=COSTrainingDataReferenceConnection.from_dict({ "resource_instance_id": COS_RESOURCE_CRN, "url": COS_ENDPOINT, "api_key": COS_API_KEY_ID, "iam_url": IAM_URL})), training_data_schema=SparkStruct.from_dict(model_asset_details_from_deployment["entity"]["asset_properties"]["training_data_schema"]) ) ).result pre_prod_subscription_id = pre_prod_subscription_details.metadata.id pre_prod_subscription_id ``` ## Subscribe challenger model ``` challenger_asset_deployment_details = wos_client.service_providers.list_assets(data_mart_id=data_mart_id, service_provider_id=service_provider_id, deployment_space_id = preprod_space_id).result['resources'][0] challenger_asset_deployment_details challenger_model_asset_details_from_deployment=wos_client.service_providers.get_deployment_asset(data_mart_id=data_mart_id,service_provider_id=service_provider_id,deployment_id=challenger_deployment_uid,deployment_space_id=preprod_space_id) challenger_model_asset_details_from_deployment challenger_subscription_details = wos_client.subscriptions.add( data_mart_id=data_mart_id, service_provider_id=service_provider_id, asset=Asset( asset_id=challenger_model_asset_details_from_deployment["entity"]["asset"]["asset_id"], name=challenger_model_asset_details_from_deployment["entity"]["asset"]["name"], url=challenger_model_asset_details_from_deployment["entity"]["asset"]["url"], asset_type=AssetTypes.MODEL, input_data_type=InputDataType.STRUCTURED, problem_type=ProblemType.BINARY_CLASSIFICATION ), deployment=AssetDeploymentRequest( deployment_id=challenger_asset_deployment_details['metadata']['guid'], name=challenger_asset_deployment_details['entity']['name'], deployment_type= DeploymentTypes.ONLINE, url=asset_deployment_details['metadata']['url'], scoring_endpoint=ScoringEndpointRequest(url=challenger_scoring_url) # score model without shadow deployment ), asset_properties=AssetPropertiesRequest( label_column='Risk', probability_fields=['probability'], prediction_field='prediction', feature_fields = ["CheckingStatus","LoanDuration","CreditHistory","LoanPurpose","LoanAmount","ExistingSavings","EmploymentDuration","InstallmentPercent","Sex","OthersOnLoan","CurrentResidenceDuration","OwnsProperty","Age","InstallmentPlans","Housing","ExistingCreditsCount","Job","Dependents","Telephone","ForeignWorker"], categorical_fields = ["CheckingStatus","CreditHistory","LoanPurpose","ExistingSavings","EmploymentDuration","Sex","OthersOnLoan","OwnsProperty","InstallmentPlans","Housing","Job","Telephone","ForeignWorker"], training_data_reference=TrainingDataReference(type='cos', location=COSTrainingDataReferenceLocation(bucket = BUCKET_NAME, file_name = training_data_file_name), connection=COSTrainingDataReferenceConnection.from_dict({ "resource_instance_id": COS_RESOURCE_CRN, "url": COS_ENDPOINT, "api_key": COS_API_KEY_ID, "iam_url": IAM_URL})), training_data_schema=SparkStruct.from_dict(challenger_model_asset_details_from_deployment["entity"]["asset_properties"]["training_data_schema"]) ) ).result challenger_subscription_id = challenger_subscription_details.metadata.id challenger_subscription_id ``` ### Score the model so we can configure monitors Now that the WML service has been bound and the subscription has been created, we need to send a request to the model before we configure OpenScale. This allows OpenScale to create a payload log in the datamart with the correct schema, so it can capture data coming into and out of the model. First, the code gets the model deployment's endpoint URL, and then sends a few records for predictions. ``` fields = ["CheckingStatus","LoanDuration","CreditHistory","LoanPurpose","LoanAmount","ExistingSavings","EmploymentDuration","InstallmentPercent","Sex","OthersOnLoan","CurrentResidenceDuration","OwnsProperty","Age","InstallmentPlans","Housing","ExistingCreditsCount","Job","Dependents","Telephone","ForeignWorker"] values = [ ["no_checking",13,"credits_paid_to_date","car_new",1343,"100_to_500","1_to_4",2,"female","none",3,"savings_insurance",46,"none","own",2,"skilled",1,"none","yes"], ["no_checking",24,"prior_payments_delayed","furniture",4567,"500_to_1000","1_to_4",4,"male","none",4,"savings_insurance",36,"none","free",2,"management_self-employed",1,"none","yes"], ["0_to_200",26,"all_credits_paid_back","car_new",863,"less_100","less_1",2,"female","co-applicant",2,"real_estate",38,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",14,"no_credits","car_new",2368,"less_100","1_to_4",3,"female","none",3,"real_estate",29,"none","own",1,"skilled",1,"none","yes"], ["0_to_200",4,"no_credits","car_new",250,"less_100","unemployed",2,"female","none",3,"real_estate",23,"none","rent",1,"management_self-employed",1,"none","yes"], ["no_checking",17,"credits_paid_to_date","car_new",832,"100_to_500","1_to_4",2,"male","none",2,"real_estate",42,"none","own",1,"skilled",1,"none","yes"], ["no_checking",33,"outstanding_credit","appliances",5696,"unknown","greater_7",4,"male","co-applicant",4,"unknown",54,"none","free",2,"skilled",1,"yes","yes"], ["0_to_200",13,"prior_payments_delayed","retraining",1375,"100_to_500","4_to_7",3,"male","none",3,"real_estate",37,"none","own",2,"management_self-employed",1,"none","yes"] ] payload_scoring = {"input_data": [{"fields": fields, "values": values}]} import time time.sleep(5) preprod_payload_data_set_id = None preprod_payload_data_set_id = wos_client.data_sets.list(type=DataSetTypes.PAYLOAD_LOGGING, target_target_id=pre_prod_subscription_id, target_target_type=TargetTypes.SUBSCRIPTION).result.data_sets[0].metadata.id if preprod_payload_data_set_id is None: print("Payload data set not found. Please check subscription status.") else: print("Payload data set id: ", preprod_payload_data_set_id) scoring_response = wml_client.deployments.score(pre_prod_deployment_uid, payload_scoring) print("Single record scoring result:", "\n fields:", scoring_response["predictions"][0]["fields"], "\n values: ", scoring_response["predictions"][0]["values"][0]) import uuid from ibm_watson_openscale.supporting_classes.payload_record import PayloadRecord time.sleep(5) pl_records_count = wos_client.data_sets.get_records_count(preprod_payload_data_set_id) print("Number of records in the payload logging table: {}".format(pl_records_count)) if pl_records_count == 0: print("Payload logging did not happen, performing explicit payload logging.") wos_client.data_sets.store_records(data_set_id=preprod_payload_data_set_id, request_body=[PayloadRecord( scoring_id=str(uuid.uuid4()), request=payload_scoring, response=scoring_response, response_time=460 )]) time.sleep(5) pl_records_count = wos_client.data_sets.get_records_count(preprod_payload_data_set_id) print("Number of records in the payload logging table: {}".format(pl_records_count)) import time time.sleep(5) challenger_payload_data_set_id = None challenger_payload_data_set_id = wos_client.data_sets.list(type=DataSetTypes.PAYLOAD_LOGGING, target_target_id=challenger_subscription_id, target_target_type=TargetTypes.SUBSCRIPTION).result.data_sets[0].metadata.id if challenger_payload_data_set_id is None: print("Payload data set not found. Please check subscription status.") else: print("Payload data set id: ", challenger_payload_data_set_id) scoring_response = wml_client.deployments.score(challenger_deployment_uid, payload_scoring) print("Single record scoring result:", "\n fields:", scoring_response["predictions"][0]["fields"], "\n values: ", scoring_response["predictions"][0]["values"][0]) import uuid from ibm_watson_openscale.supporting_classes.payload_record import PayloadRecord time.sleep(5) pl_records_count = wos_client.data_sets.get_records_count(challenger_payload_data_set_id) print("Number of records in the payload logging table: {}".format(pl_records_count)) if pl_records_count == 0: print("Payload logging did not happen, performing explicit payload logging.") wos_client.data_sets.store_records(data_set_id=challenger_payload_data_set_id, request_body=[PayloadRecord( scoring_id=str(uuid.uuid4()), request=payload_scoring, response=scoring_response, response_time=460 )]) time.sleep(5) pl_records_count = wos_client.data_sets.get_records_count(challenger_payload_data_set_id) print("Number of records in the payload logging table: {}".format(pl_records_count)) ``` # Quality monitoring ## Enable quality monitoring The code below waits ten seconds to allow the payload logging table to be set up before it begins enabling monitors. First, it turns on the quality (accuracy) monitor and sets an alert threshold of 80%. OpenScale will show an alert on the dashboard if the model accuracy measurement (area under the curve, in the case of a binary classifier) falls below this threshold. The second paramater supplied, min_records, specifies the minimum number of feedback records OpenScale needs before it calculates a new measurement. The quality monitor runs hourly, but the accuracy reading in the dashboard will not change until an additional 50 feedback records have been added, via the user interface, the Python client, or the supplied feedback endpoint. ``` import time time.sleep(10) target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=pre_prod_subscription_id ) parameters = { "min_feedback_data_size": 50 } quality_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.QUALITY.ID, target=target, parameters=parameters ).result preprod_quality_monitor_instance_id = quality_monitor_details.metadata.id preprod_quality_monitor_instance_id import time time.sleep(10) target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=challenger_subscription_id ) parameters = { "min_feedback_data_size": 50 } quality_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.QUALITY.ID, target=target, parameters=parameters ).result challenger_quality_monitor_instance_id = quality_monitor_details.metadata.id challenger_quality_monitor_instance_id ``` # Fairness, drift monitoring and explanations ## Fairness configuration The code below configures fairness monitoring for our model. It turns on monitoring for two features, Sex and Age. In each case, we must specify: Which model feature to monitor One or more majority groups, which are values of that feature that we expect to receive a higher percentage of favorable outcomes One or more minority groups, which are values of that feature that we expect to receive a higher percentage of unfavorable outcomes The threshold at which we would like OpenScale to display an alert if the fairness measurement falls below (in this case, 80%) Additionally, we must specify which outcomes from the model are favourable outcomes, and which are unfavourable. We must also provide the number of records OpenScale will use to calculate the fairness score. In this case, OpenScale's fairness monitor will run hourly, but will not calculate a new fairness rating until at least 100 records have been added. Finally, to calculate fairness, OpenScale must perform some calculations on the training data, so we provide the dataframe containing the data. ``` target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=pre_prod_subscription_id ) parameters = { "features": [ {"feature": "Sex", "majority": ['male'], "minority": ['female'], "threshold": 0.95 }, {"feature": "Age", "majority": [[26, 75]], "minority": [[18, 25]], "threshold": 0.95 } ], "favourable_class": ["No Risk"], "unfavourable_class": ["Risk"], "min_records": 100 } fairness_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.FAIRNESS.ID, target=target, parameters=parameters).result preprod_fairness_monitor_instance_id =fairness_monitor_details.metadata.id preprod_fairness_monitor_instance_id target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=challenger_subscription_id ) parameters = { "features": [ {"feature": "Sex", "majority": ['male'], "minority": ['female'], "threshold": 0.95 }, {"feature": "Age", "majority": [[26, 75]], "minority": [[18, 25]], "threshold": 0.95 } ], "favourable_class": ["No Risk"], "unfavourable_class": ["Risk"], "min_records": 100 } fairness_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.FAIRNESS.ID, target=target, parameters=parameters).result challenger_fairness_monitor_instance_id =fairness_monitor_details.metadata.id challenger_fairness_monitor_instance_id ``` ## Drift configuration Enable the drift configuration for both the subscription created with a threshold of 10% and minimal sample as 100 records. ``` target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=pre_prod_subscription_id ) parameters = { "min_samples": 100, "drift_threshold": 0.1, "train_drift_model": True, "enable_model_drift": False, "enable_data_drift": True } drift_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.DRIFT.ID, target=target, parameters=parameters ).result preprod_drift_monitor_instance_id = drift_monitor_details.metadata.id preprod_drift_monitor_instance_id target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=challenger_subscription_id ) parameters = { "min_samples": 100, "drift_threshold": 0.1, "train_drift_model": True, "enable_model_drift": False, "enable_data_drift": True } drift_monitor_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.DRIFT.ID, target=target, parameters=parameters ).result challenger_preprod_drift_monitor_instance_id = drift_monitor_details.metadata.id challenger_preprod_drift_monitor_instance_id ``` ## Configure Explainability Finally, we provide OpenScale with the training data to enable and configure the explainability features. ``` target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=pre_prod_subscription_id ) parameters = { "enabled": True } explainability_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.EXPLAINABILITY.ID, target=target, parameters=parameters ).result preprod_explainability_monitor_id = explainability_details.metadata.id preprod_explainability_monitor_id target = Target( target_type=TargetTypes.SUBSCRIPTION, target_id=challenger_subscription_id ) parameters = { "enabled": True } explainability_details = wos_client.monitor_instances.create( data_mart_id=data_mart_id, background_mode=False, monitor_definition_id=wos_client.monitor_definitions.MONITORS.EXPLAINABILITY.ID, target=target, parameters=parameters ).result challenger_explainability_monitor_id = explainability_details.metadata.id challenger_explainability_monitor_id ``` ## Enable model risk management (MRM) We enable the MRM configuration for both the subscriptions ``` WOS_GUID='***'# use openscale instance GUID here headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) payload = { "data_mart_id": WOS_GUID, "monitor_definition_id": "mrm", "target": { "target_id": pre_prod_subscription_id, "target_type": "subscription" }, "parameters": { }, "managed_by": "user" } MONITOR_INSTANCES_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances".format(WOS_GUID) response = requests.post(MONITOR_INSTANCES_URL, json=payload, headers=headers) json_data = response.json() print(json_data) if "metadata" in json_data and "id" in json_data["metadata"]: pre_prod_mrm_instance_id = json_data["metadata"]["id"] headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) payload = { "data_mart_id": WOS_GUID, "monitor_definition_id": "mrm", "target": { "target_id": challenger_subscription_id, "target_type": "subscription" }, "parameters": { }, "managed_by": "user" } MONITOR_INSTANCES_URL ="https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances".format(WOS_GUID) response = requests.post(MONITOR_INSTANCES_URL, json=payload, headers=headers) json_data = response.json() print(json_data) if "metadata" in json_data and "id" in json_data["metadata"]: challenger_mrm_instance_id = json_data["metadata"]["id"] ``` ## Create test data sets from the training data ``` test_data_1 = pd_data[1:201] test_data_1.to_csv("german_credit_risk_test_data_1.csv", encoding="utf-8", index=False) test_data_2 = pd_data[201:401] test_data_2.to_csv("german_credit_risk_test_data_2.csv", encoding="utf-8", index=False) test_data_3 = pd_data[401:601] test_data_3.to_csv("german_credit_risk_test_data_3.csv", encoding="utf-8", index=False) test_data_4 = pd_data[601:801] test_data_4.to_csv("german_credit_risk_test_data_4.csv", encoding="utf-8", index=False) ``` ## Function to upload, evaluate and check the status of the evaluation This function will upload the test data CSV and trigger the risk evaluation. It will iterate and check the status of the evaluation until its finished with a finite wait duration ``` def upload_and_evaluate(file_name, mrm_instance_id): print("Running upload and evaluate for {}".format(file_name)) import json import time from datetime import datetime status = None monitoring_run_id = None GET_UPLOAD_AND_EVALUATION_STATUS_RETRIES = 32 GET_UPLOAD_AND_EVALUATION_STATUS_INTERVAL = 10 if file_name is not None: headers = {} headers["Content-Type"] = "text/csv" headers["Authorization"] = "Bearer {}".format(generate_access_token()) POST_EVALUATIONS_URL ="https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitoring_services/mrm/monitor_instances/{1}/risk_evaluations?test_data_set_name={2}".format(WOS_GUID, mrm_instance_id, file_name) with open(file_name) as file: f = file.read() b = bytearray(f, 'utf-8') response = requests.post(POST_EVALUATIONS_URL, data=bytes(b), headers=headers) if response.ok is False: print("Upload and evalaute for {0} failed with {1}: {2}".format(file_name, response.status_code, response.reason)) return headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) GET_EVALUATIONS_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitoring_services/mrm/monitor_instances/{1}/risk_evaluations".format(WOS_GUID, mrm_instance_id) for i in range(GET_UPLOAD_AND_EVALUATION_STATUS_RETRIES): response = requests.get(GET_EVALUATIONS_URL, headers=headers) if response.ok is False: print("Getting status of upload and evalaute for {0} failed with {1}: {2}".format(file_name, response.status_code, response.reason)) return response = json.loads(response.text) if "metadata" in response and "id" in response["metadata"]: monitoring_run_id = response["metadata"]["id"] if "entity" in response and "status" in response["entity"]: status = response["entity"]["status"]["state"] if status is not None: print(datetime.utcnow().strftime('%H:%M:%S'), status.lower()) if status.lower() in ["finished", "completed"]: break elif "error"in status.lower(): print(response) break time.sleep(GET_UPLOAD_AND_EVALUATION_STATUS_INTERVAL) return status, monitoring_run_id ``` ## Perform Risk Evaluations We now start performing evaluations of smaller data sets against both the PreProd and Challenger subscriptions ``` upload_and_evaluate("german_credit_risk_test_data_1.csv", pre_prod_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_2.csv", pre_prod_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_3.csv", pre_prod_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_4.csv", pre_prod_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_1.csv", challenger_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_2.csv", challenger_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_3.csv", challenger_mrm_instance_id) upload_and_evaluate("german_credit_risk_test_data_4.csv", challenger_mrm_instance_id) ``` ## Explore the Model Risk Management UI Here is a quick recap of what we have done so far. 1. We've deployed two Credit Risk Model to a WML instance that is designated as Pre-Production 2. We've created subscriptions of these two model deployments in OpenScale 3. Configured all monitors supported by OpenScale for these subscriptions 4. We've performed a few risk evaluations against both these susbscription with the same set of test data Now, please explore the Model Risk Management UI to visualize the results, compare the performance of models, download the evaluation report as PDF. For more information, refer to the Beta Guide section "Work in Watson OpenScale." Link to OpenScale : https://aiopenscale.cloud.ibm.com/aiopenscale/insights?mrm=true # Promote pre-production model to production After you have reviewed the evaluation results of the PreProd Vs Challenger and if you make the decision to promote the PreProd model to Production, the first thing you need to do is to deploy the model into a WML instance that is designated as Production instance ## Deploy model to production WML instance ``` PROD_MODEL_NAME="German Credit Risk Model - Prod" PROD_DEPLOYMENT_NAME="German Credit Risk Model - Prod" space_name ="prod-space" spaces = wml_client.spaces.get_details()['resources'] prod_space_id = None for space in spaces: if space['entity']['name'] == space_name: prod_space_id = space["metadata"]["id"] if prod_space_id is None: prod_space_id = wml_client.spaces.store( meta_props={wml_client.spaces.ConfigurationMetaNames.NAME: space_name, wml_client.spaces.ConfigurationMetaNames.STORAGE: {"resource_crn":COS_CRN}, wml_client.spaces.ConfigurationMetaNames.COMPUTE: {"name": WML_INSTANCE_NAME, "crn": WML_CRN}})["metadata"]["id"] wml_client.set.default_space(prod_space_id) print(prod_space_id) prod_model_uid, prod_deployment_uid, prod_scoring_url = deploy_credit_risk_spark_model(WML_CREDENTIALS, PROD_MODEL_NAME, PROD_DEPLOYMENT_NAME,prod_space_id) ``` ## Bind WML machine learning instance as Prod Watson OpenScale needs to be bound to the Watson Machine Learning instance to capture payload data into and out of the model. If a binding with name "WML Prod" already exists, this code will delete that binding a create a new one. ``` SERVICE_PROVIDER_NAME = "Watson Machine Learning prod openpage" SERVICE_PROVIDER_DESCRIPTION = "Added by tutorial WOS notebook." service_providers = wos_client.service_providers.list().result.service_providers for service_provider in service_providers: service_instance_name = service_provider.entity.name if service_instance_name == SERVICE_PROVIDER_NAME: service_provider_id = service_provider.metadata.id wos_client.service_providers.delete(service_provider_id) print("Deleted existing service_provider for WML instance: {}".format(service_provider_id)) added_service_provider_result = wos_client.service_providers.add( name=SERVICE_PROVIDER_NAME, description=SERVICE_PROVIDER_DESCRIPTION, service_type=ServiceTypes.WATSON_MACHINE_LEARNING, deployment_space_id = prod_space_id, # use prod space ID operational_space_id = "production", credentials=WMLCredentialsCloud( apikey=CLOUD_API_KEY, ## use `apikey=IAM_TOKEN` if using IAM_TOKEN to initiate client url=WML_CREDENTIALS["url"], instance_id=None ), background_mode=False ).result service_provider_id = added_service_provider_result.metadata.id service_provider_id asset_deployment_details = wos_client.service_providers.list_assets(data_mart_id=data_mart_id, service_provider_id=service_provider_id, deployment_space_id = prod_space_id).result['resources'][0] asset_deployment_details ``` # Import configuration settings from pre-prod model With MRM we provide a important feature that lets you copy the configuration settings of your pre-production subscription to the production subscription. To try this out 1. Navigate to Model Monitors view in Insights dashboard of OpenScale 2. Click on the Add to dashboard 3. Select the production model deployment from WML production machine learning provider and click on Configure 4. In Selections saved dialog, click on Configure monitors 5. Click on Import settings 6. In the Import configuration settings dialog, choose the `German Credit Risk Model - PreProd` as the subscription from which you want to import the settings and click Configure 7. In the Replace existing settings? dialog, click on Import All the configuration settings are now copied into the production subscription <b>Note: The next set of cells should be executed only after finishing the import settings from the OpenScale dashboard</b> ## Score the production model so that we can trigger monitors Now that the production subscription is configured by copying the configuration, there would be schedules created for each of the monitors to run on a scheduled basis. Quality, Fairness and Mrm will run hourly. Drift will run once in three hours. For this demo purpose, we will trigger the monitors on-demand so that we can see the model summary dashboard without having to wait the entire hour. To do that lets first push some records in the Payload Logging table. ``` df = pd_data.sample(n=400) df = df.drop(['Risk'], axis=1) fields = df.columns.tolist() values = df.values.tolist() payload_scoring = {"input_data": [{"fields": fields, "values": values}]} scoring_response = wml_client.deployments.score(prod_deployment_uid, payload_scoring) print("Single record scoring result:", "\n fields:", scoring_response["predictions"][0]["fields"], "\n values: ", scoring_response["predictions"][0]["values"][0]) wos_client.subscriptions.show() prod_subscription = wos_client.subscriptions.get('5949851d-8746-4bfa-b3f0-9a27c4cef98b').result.to_dict() prod_subscription_id=prod_subscription['metadata']['id'] import time time.sleep(5) prod_payload_data_set_id = None prod_payload_data_set_id = wos_client.data_sets.list(type=DataSetTypes.PAYLOAD_LOGGING, target_target_id=prod_subscription_id, target_target_type=TargetTypes.SUBSCRIPTION).result.data_sets[0].metadata.id if prod_payload_data_set_id is None: print("Payload data set not found. Please check subscription status.") else: print("Payload data set id: ", prod_payload_data_set_id) ``` ## Fetch all monitor instances ``` headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) MONITOR_INSTANCES_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances?target.target_id={1}&target.target_type=subscription".format(WOS_GUID, prod_subscription_id) print(MONITOR_INSTANCES_URL) response = requests.get(MONITOR_INSTANCES_URL, headers=headers) monitor_instances = response.json()["monitor_instances"] drift_monitor_instance_id = None quality_monitor_instance_id = None fairness_monitor_instance_id= None mrm_monitor_instance_id = None if monitor_instances is not None: for monitor_instance in monitor_instances: if "entity" in monitor_instance and "monitor_definition_id" in monitor_instance["entity"]: monitor_name = monitor_instance["entity"]["monitor_definition_id"] if "metadata" in monitor_instance and "id" in monitor_instance["metadata"]: id = monitor_instance["metadata"]["id"] if monitor_name == "drift": drift_monitor_instance_id = id elif monitor_name == "fairness": fairness_monitor_instance_id = id elif monitor_name == "quality": quality_monitor_instance_id = id elif monitor_name == "mrm": mrm_monitor_instance_id = id print("Quality monitor instance id - {0}".format(quality_monitor_instance_id)) print("Fairness monitor instance id - {0}".format(fairness_monitor_instance_id)) print("Drift monitor instance id - {0}".format(drift_monitor_instance_id)) print("MRM monitor instance id - {0}".format(mrm_monitor_instance_id)) ``` ## Function to get the monitoring run details ``` def get_monitoring_run_details(monitor_instance_id, monitoring_run_id): headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) MONITORING_RUNS_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances/{1}/runs/{2}".format(WOS_GUID, monitor_instance_id, monitoring_run_id) response = requests.get(MONITORING_RUNS_URL, headers=headers, verify=False) return response.json() ``` ## Run on-demand Quality ``` headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) if quality_monitor_instance_id is not None: MONITOR_RUN_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances/{1}/runs".format(WOS_GUID, quality_monitor_instance_id) payload = { "triggered_by": "user" } print("Triggering Quality computation with {}".format(MONITOR_RUN_URL)) response = requests.post(MONITOR_RUN_URL, json=payload, headers=headers, verify=False) json_data = response.json() print() print(json_data) print() if "metadata" in json_data and "id" in json_data["metadata"]: quality_monitoring_run_id = json_data["metadata"]["id"] print("Done triggering Quality computation") from datetime import datetime quality_run_status = None while quality_run_status != 'finished': monitoring_run_details = get_monitoring_run_details(quality_monitor_instance_id, quality_monitoring_run_id) quality_run_status = monitoring_run_details["entity"]["status"]["state"] if quality_run_status == "error": print(monitoring_run_details) break if quality_run_status != 'finished': print(datetime.utcnow().strftime('%H:%M:%S'), quality_run_status) time.sleep(10) print(quality_run_status) ``` ## Run on-demand Drift ``` headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) if drift_monitor_instance_id is not None: MONITOR_RUN_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances/{1}/runs".format(WOS_GUID, drift_monitor_instance_id) payload = { "triggered_by": "user" } print("Triggering Drift computation with {}".format(MONITOR_RUN_URL)) response = requests.post(MONITOR_RUN_URL, json=payload, headers=headers, verify=False) json_data = response.json() print() print(json_data) print() if "metadata" in json_data and "id" in json_data["metadata"]: drift_monitoring_run_id = json_data["metadata"]["id"] print("Done triggering Drift computation") from datetime import datetime drift_run_status = None while drift_run_status != 'finished': monitoring_run_details = get_monitoring_run_details(drift_monitor_instance_id, drift_monitoring_run_id) drift_run_status = monitoring_run_details["entity"]["status"]["state"] if drift_run_status == "error": print(monitoring_run_details) break if drift_run_status != 'finished': print(datetime.utcnow().strftime('%H:%M:%S'), drift_run_status) time.sleep(10) print(drift_run_status) ``` ## Run on-demand Fairness ``` headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) if fairness_monitor_instance_id is not None: MONITOR_RUN_URL = "https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances/{1}/runs".format(WOS_GUID, fairness_monitor_instance_id) payload = { "triggered_by": "user" } print("Triggering fairness computation with {}".format(MONITOR_RUN_URL)) response = requests.post(MONITOR_RUN_URL, json=payload, headers=headers, verify=False) json_data = response.json() print() print(json_data) print() if "metadata" in json_data and "id" in json_data["metadata"]: fairness_monitor_run_id = json_data["metadata"]["id"] print("Done triggering fairness computation") from datetime import datetime fairness_run_status = None while fairness_run_status != 'finished': monitoring_run_details = get_monitoring_run_details(fairness_monitor_instance_id, fairness_monitor_run_id) fairness_run_status = monitoring_run_details["entity"]["status"]["state"] if fairness_run_status == "error": print(monitoring_run_details) break if fairness_run_status != 'finished': print(datetime.utcnow().strftime('%H:%M:%S'), fairness_run_status) time.sleep(10) print(fairness_run_status) ``` ## Run on-demand MRM ``` headers = {} headers["Content-Type"] = "application/json" headers["Authorization"] = "Bearer {}".format(generate_access_token()) if mrm_monitor_instance_id is not None: MONITOR_RUN_URL ="https://api.aiopenscale.cloud.ibm.com/openscale/{0}/v2/monitor_instances/{1}/runs".format(WOS_GUID, mrm_monitor_instance_id) payload = { "triggered_by": "user" } print("Triggering MRM computation with {}".format(MONITOR_RUN_URL)) response = requests.post(MONITOR_RUN_URL, json=payload, headers=headers, verify=False) json_data = response.json() print() print(json_data) print() if "metadata" in json_data and "id" in json_data["metadata"]: mrm_monitoring_run_id = json_data["metadata"]["id"] print("Done triggering MRM computation") from datetime import datetime mrm_run_status = None while mrm_run_status != 'finished': monitoring_run_details = get_monitoring_run_details(mrm_monitor_instance_id, mrm_monitoring_run_id) mrm_run_status = monitoring_run_details["entity"]["status"]["state"] if mrm_run_status == "error": print(monitoring_run_details) break if mrm_run_status != 'finished': print(datetime.utcnow().strftime('%H:%M:%S'), mrm_run_status) time.sleep(10) print(mrm_run_status) ``` ## Refresh the model summary of the production subscription in the OpenScale dashboard This brings us to the end of this demo exercise. Thank you for trying it out.
github_jupyter
## Libraries ``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg from collections import deque import skimage.measure import numpy as np import gym from gym import wrappers from torch.autograd import Variable import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim ``` ## Preprocessing ``` def preprocess(rgb_tensor): ''' Transforms 3D RGB numpy tensor: crop, convert to 2D grayscale, downsample, and convert to PyTorch tensor. ''' crop = rgb_tensor[30:194,:,:] grayscale = np.dot(crop[...,:3], [0.2989, 0.5870, 0.1140]) ## using Matlab's formula downsample = skimage.measure.block_reduce(grayscale, (2,2), np.max) return downsample ``` ## Agent Select Action ``` class Action: '''Returns an action value which is an int in range [0,3]''' def __init__(self): self.time_ = 0 def update_time(self): self.time_ += 1 def action(self): if self.time_ == 0: self.action_ = 1 ## start game by firing ball else: # take agent-based action every 4 time steps; else push action forward w/out agent computing if self.time_%4 == 0: if np.random.binomial(n=1, p=eg.epsilon_, size=1): self.action_ = env.action_space.sample() ## take random action else: self.action_ = cnn(Variable(torch.Tensor(initial_seq).unsqueeze(0).unsqueeze(0))).data.max(1)[1][0] ## take optimal action according to NN return self.action_ ``` ## Experience Replay ``` class ExperienceReplay: dq_ = deque(maxlen=500) def __init__(self, C): self.capacity_ = C def add_experience(self, experience_tuple): '''add new experience to experience replay''' self.dq_.append(experience_tuple) def sample(self, capacity=32): '''sample from experience replay''' nb_items = len(self.dq_) if nb_items > capacity: idx = np.random.choice( nb_items, size=capacity, replace=False) else: idx = np.random.choice( nb_items, size=nb_items, replace=False) return [self.dq_[i] for i in idx] ``` ## Epsilon Generator ``` class EpsilonGenerator(): def __init__(self, start, stop, steps): self.epsilon_ = start self.stop_ = stop self.steps_ = steps self.step_size_ = (self.epsilon_ - stop) / (self.steps_) self.count_ = 1 def epsilon_update(self): '''generate next epsilon value''' if (self.epsilon_ >= self.stop_ and self.count_ < self.steps_): self.count_ += 1 self.epsilon_ -= self.step_size_ else: self.epsilon_ = self.stop_ self.count_ += 1 ``` ## CNN Architecture ``` class CNN(nn.Module): def __init__(self,): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 16, 8, 4) ## Conv2d(nChannels, filters, kernel, stride) self.conv2 = nn.Conv2d(16, 32, 4, 4) self.fc1 = nn.Linear(32 * 4 * 4, 256) self.fc2 = nn.Linear(256, 4) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = x.view(-1, 32 * 4 * 4) ## reshape x = F.relu(self.fc1(x)) x = self.fc2(x) return x ``` ## Create Dataset ``` class Dataset: def __init__(self): self.replay_size_ = None self.data_ = None self.target_ = None def get_data(self): self.replay_size_ = len(minibatch) # create tensor of initial observations self.data_ = Variable(torch.Tensor([minibatch[i][0] for i in range(self.replay_size_)]).unsqueeze(1)) # create tensor of corresponding target variable values target_list = [] for i in range(self.replay_size_): observed = Variable(torch.Tensor(minibatch[i][3])) if minibatch[i][4] == 'terminal': target_list.append(minibatch[i][2]) else: target_list.append(minibatch[i][2] + discount * cnn(observed.unsqueeze(0).unsqueeze(0)).data.max(1)[1][0]) self.target_ = Variable(torch.Tensor(target_list)) ``` ## Training ``` num_games = 2 ## number of games to play time_steps = 500 ## max number of time steps per game record = 0 view = 1 # Atari emulator env = gym.make('Breakout-v0') # whether to record training if record: env = wrappers.Monitor(env, directory='/Users/davidziganto/Data_Science/PyTorch/OpenAI_vids/breakout-experiment-1', video_callable=None, ## takes video when episode number is perfect cube force=True) # instantiate key classes cnn = CNN() er = ExperienceReplay(C=100) eg = EpsilonGenerator(start=1, stop=0.1, steps=1000) agent = Action() dataset = Dataset() # setup variables discount = 0.9 learning_rate = 0.01 # CNN setup criterion = nn.MSELoss() optimizer = optim.RMSprop(cnn.parameters(), lr=learning_rate, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False) # play game for episode in range(num_games): ## start/reset environment + store observation initial_seq = preprocess(env.reset()) for t in range(time_steps): ## show game in real-time if view: env.render() # take action (0=do nothing; 1=fire ball; 2=move right; 3=move left) action = agent.action() agent.update_time() # update epsilon for epsilon-greedy implementation eg.epsilon_update() # get feedback from emulator observation, reward, done, info = env.step(action) # preprocess new observation post action final_seq = preprocess(observation) # stop if no more moves, else continue and update if done: er.add_experience((initial_seq, action, reward, final_seq, 'terminal')) break else: er.add_experience((initial_seq, action, reward, final_seq, 'nonterminal')) # get mini-batch sample from experience replay (fyi - randomizes index) minibatch = er.sample() # get data for updating policy network dataset.get_data() # Update CNN optimizer.zero_grad() ## zero the parameter gradients outputs = cnn(dataset.data_).max(1)[0] ## feedforward pass loss = criterion(outputs, dataset.target_) ## calculate loss loss.backward() ## backpropagation optimizer.step() ## update network weights # set new observation as initial observation initial_seq = final_seq env.close() ``` # To Do... 1) normalize pixel values (preprocessing) 2) add loss function to show learning over time 3) add GPU functionality ## Stats for 1000 games taking random actions ``` env = gym.make('Breakout-v0') rewards = [] steps = [] for game in range(1000): myreward = 0 # reset game env.reset() for t in range(1000): # show in real-time #env.render() # take a random action if t == 0: action = 1 else: action = env.action_space.sample() # get feedback observation, reward, done, info = env.step(action) myreward += reward # end game when out of balls if done: rewards.append(myreward) steps.append(t) stats = zip(steps, rewards) env.close() break max(rewards) import seaborn as sns sns.distplot(rewards); ``` #### Save Model ``` torch.save(cnn.state_dict(), '/Users/davidziganto/Data_Science/PyTorch/DL_models/DL_RL_Atari_breakout_500e_10000t') ``` #### Load Model ``` #cnn = CNN() #cnn.load_state_dict(torch.load('/Users/davidziganto/Data_Science/PyTorch/DL_models/DL_RL_Atari_breakout')) ``` # EXAMPLE ### Get Frames ``` frames = [] rewards = [] nb_frames = 500 env = gym.make('Breakout-v0') env.reset() for t in range(nb_frames): env.render() action = env.action_space.sample() # take a random action observation, reward, done, info = env.step(action) frames.append(preprocess(observation)) if t%4 == 3 or done: frameTensor = np.stack(frames) minibatch = Variable(torch.Tensor(frameTensor)) ## convert to torch Variable data type print('t:', t, '\n', minibatch) frames = [] if done: break ``` ### Show Preprocessed Data Frames ``` for frame in frames: plt.imshow(frame, cmap = plt.get_cmap('gray')) plt.show() ``` ### Frame Dimensions ``` frame.shape ```
github_jupyter
``` # ignore this cell, this is just a helper cell to provide the magic %highlight_file %run ../highlighter.py ``` ## Inventory The Inventory is arguably the most important piece of nornir. Let's see how it works. To begin with the [inventory](../api/nornir/core/inventory.html#module-nornir.core.inventory) is comprised of [hosts](../api/nornir/core/inventory.html#nornir.core.inventory.Hosts), [groups](../api/nornir/core/inventory.html#nornir.core.inventory.Groups) and [defaults](../api/nornir/core/inventory.html#nornir.core.inventory.Defaults). In this tutorial we are using the [SimpleInventory](../api/nornir/plugins/inventory/simple.html#nornir.plugins.inventory.simple.SimpleInventory) plugin. This inventory plugin stores all the relevant data in three files. Let’s start by checking them: ``` # hosts file %highlight_file inventory/hosts.yaml ``` The hosts file is basically a map where the outermost key is the name of the host and then a `Host` object. You can see the schema of the object by executing: ``` from nornir.core.inventory import Host import json print(json.dumps(Host.schema(), indent=4)) ``` The `groups_file` follows the same rules as the `hosts_file`. ``` # groups file %highlight_file inventory/groups.yaml ``` Finally, the defaults file has the same schema as the `Host` we described before but without outer keys to denote individual elements. We will see how the data in the groups and defaults file is used later on in this tutorial. ``` # defaults file %highlight_file inventory/defaults.yaml ``` ### Accessing the inventory You can access the [inventory](../api/nornir/core/inventory.html#module-nornir.core.inventory) with the `inventory` attribute: ``` from nornir import InitNornir nr = InitNornir(config_file="config.yaml") print(nr.inventory.hosts) ``` The inventory has two dict-like attributes `hosts` and `groups` that you can use to access the hosts and groups respectively: ``` nr.inventory.hosts nr.inventory.groups nr.inventory.hosts["leaf01.bma"] ``` Hosts and groups are also dict-like objects: ``` host = nr.inventory.hosts["leaf01.bma"] host.keys() host["site"] ``` ### Inheritance model Let's see how the inheritance models works by example. Let's start by looking again at the groups file: ``` # groups file %highlight_file inventory/groups.yaml ``` The host `leaf01.bma` belongs to the group `bma` which in turn belongs to the groups `eu` and `global`. The host `spine00.cmh` belongs to the group `cmh` which doesn't belong to any other group. Data resolution works by iterating recursively over all the parent groups and trying to see if that parent group (or any of it's parents) contains the data. For instance: ``` leaf01_bma = nr.inventory.hosts["leaf01.bma"] leaf01_bma["domain"] # comes from the group `global` leaf01_bma["asn"] # comes from group `eu` ``` Values in `defaults` will be returned if neither the host nor the parents have a specific value for it. ``` leaf01_cmh = nr.inventory.hosts["leaf01.cmh"] leaf01_cmh["domain"] # comes from defaults ``` If nornir can't resolve the data you should get a KeyError as usual: ``` try: leaf01_cmh["non_existent"] except KeyError as e: print(f"Couldn't find key: {e}") ``` You can also try to access data without recursive resolution by using the `data` attribute. For example, if we try to access `leaf01_cmh.data["domain"]` we should get an error as the host itself doesn't have that data: ``` try: leaf01_cmh.data["domain"] except KeyError as e: print(f"Couldn't find key: {e}") ``` ### Filtering the inventory So far we have seen that `nr.inventory.hosts` and `nr.inventory.groups` are dict-like objects that we can use to iterate over all the hosts and groups or to access any particular one directly. Now we are going to see how we can do some fancy filtering that will enable us to operate on groups of hosts based on their properties. The simpler way of filtering hosts is by `<key, value>` pairs. For instance: ``` nr.filter(site="cmh").inventory.hosts.keys() ``` You can also filter using multiple `<key, value>` pairs: ``` nr.filter(site="cmh", role="spine").inventory.hosts.keys() ``` Filter is cumulative: ``` nr.filter(site="cmh").filter(role="spine").inventory.hosts.keys() ``` Or: ``` cmh = nr.filter(site="cmh") cmh.filter(role="spine").inventory.hosts.keys() cmh.filter(role="leaf").inventory.hosts.keys() ``` You can also grab the children of a group: ``` nr.inventory.children_of_group("eu") ``` #### Advanced filtering Sometimes you need more fancy filtering. For those cases you have two options: 1. Use a filter function. 2. Use a filter object. ##### Filter functions The ``filter_func`` parameter let's you run your own code to filter the hosts. The function signature is as simple as ``my_func(host)`` where host is an object of type [Host](../api/nornir/core/inventory.html#nornir.core.inventory.Host) and it has to return either ``True`` or ``False`` to indicate if you want to host or not. ``` def has_long_name(host): return len(host.name) == 11 nr.filter(filter_func=has_long_name).inventory.hosts.keys() # Or a lambda function nr.filter(filter_func=lambda h: len(h.name) == 9).inventory.hosts.keys() ``` ##### Filter Object You can also use a filter objects to incrementally create a complex query objects. Let's see how it works by example: ``` # first you need to import the F object from nornir.core.filter import F # hosts in group cmh cmh = nr.filter(F(groups__contains="cmh")) print(cmh.inventory.hosts.keys()) # devices running either linux or eos linux_or_eos = nr.filter(F(platform="linux") | F(platform="eos")) print(linux_or_eos.inventory.hosts.keys()) # spines in cmh cmh_and_spine = nr.filter(F(groups__contains="cmh") & F(role="spine")) print(cmh_and_spine.inventory.hosts.keys()) # cmh devices that are not spines cmh_and_not_spine = nr.filter(F(groups__contains="cmh") & ~F(role="spine")) print(cmh_and_not_spine.inventory.hosts.keys()) ``` You can also access nested data and even check if dicts/lists/strings contains elements. Again, let's see by example: ``` nested_string_asd = nr.filter(F(nested_data__a_string__contains="asd")) print(nested_string_asd.inventory.hosts.keys()) a_dict_element_equals = nr.filter(F(nested_data__a_dict__c=3)) print(a_dict_element_equals.inventory.hosts.keys()) a_list_contains = nr.filter(F(nested_data__a_list__contains=2)) print(a_list_contains.inventory.hosts.keys()) ``` You can basically access any nested data by separating the elements in the path with two underscores `__`. Then you can use `__contains` to check if an element exists or if a string has a particular substring.
github_jupyter
# Tutorial 4: Scattering calculations with Tully's models ``` import sys import cmath import math import os import time import h5py import matplotlib.pyplot as plt # plots import numpy as np #from matplotlib.mlab import griddata %matplotlib inline if sys.platform=="cygwin": from cyglibra_core import * elif sys.platform=="linux" or sys.platform=="linux2": from liblibra_core import * from libra_py import units import libra_py.models.Tully as Tully from libra_py import tsh from libra_py import tsh_stat from libra_py import data_conv from libra_py import data_savers from libra_py import dynamics_plotting #from libra_py import dynamics_exact import util.libutil as comn import libra_py.dynamics.exact.compute as compute import libra_py.dynamics.exact.save as save import libra_py.dynamics.exact.plot as plot plt.rc('axes', titlesize=24) # fontsize of the axes title plt.rc('axes', labelsize=20) # fontsize of the x and y labels plt.rc('legend', fontsize=20) # legend fontsize plt.rc('xtick', labelsize=16) # fontsize of the tick labels plt.rc('ytick', labelsize=16) # fontsize of the tick labels plt.rc('figure.subplot', left=0.2) plt.rc('figure.subplot', right=0.95) plt.rc('figure.subplot', bottom=0.13) plt.rc('figure.subplot', top=0.88) colors = {} colors.update({"11": "#8b1a0e"}) # red colors.update({"12": "#FF4500"}) # orangered colors.update({"13": "#B22222"}) # firebrick colors.update({"14": "#DC143C"}) # crimson colors.update({"21": "#5e9c36"}) # green colors.update({"22": "#006400"}) # darkgreen colors.update({"23": "#228B22"}) # forestgreen colors.update({"24": "#808000"}) # olive colors.update({"31": "#8A2BE2"}) # blueviolet colors.update({"32": "#00008B"}) # darkblue colors.update({"41": "#2F4F4F"}) # darkslategray clrs_index = ["11", "21", "31", "41", "12", "22", "32", "13","23", "14", "24"] ``` ## 1. Define the model & plot the PES ``` def compute_model(q, params, full_id): model = params["model"] res = None if model==1: res = Tully.Tully1(q, params) elif model==2: res = Tully.Tully2(q, params) elif model==3: res = Tully.Tully3(q, params) return res def potential(q, params): """ Thin wrapper of the model Hamiltonians that can be used in the fully-quantum calculations """ # Diabatic properties obj = compute_model(q, params, Py2Cpp_int([0,0])) # Adiabatic properties nadi = len(params["E_n"]) ndof = 1 ham = nHamiltonian(nadi, nadi, ndof) # ndia, nadi, nnucl ham.init_all(2) ham.compute_diabatic(compute_model, q, params) ham.compute_adiabatic(1); obj.ham_adi = ham.get_ham_adi() obj.dc1_adi = CMATRIXList() for n in range(ndof): x = ham.get_dc1_adi(n) for i in range(nadi): for j in range(nadi): if i!=j: #pass if math.fabs(x.get(i,j).real)>1e+10: x.set(i,j, 0.0+0.0j) x.set(j,i, 0.0+0.0j) obj.dc1_adi.append( x ) return obj param_sets = [ {"model":1, "E_n":[0.0, 0.0], "nstates":2 }, {"model":2, "E_n":[0.0, 0.0], "nstates":2 }, {"model":3, "E_n":[0.0, 0.0], "nstates":2 } ] plot_params = {"colors": colors, "clrs_index": clrs_index, "xlim":[-15, 15], "ylim":[-0.015, 0.015 ]} dynamics_plotting.plot_surfaces(compute_model, [ param_sets[0] ], [0,1], -15.0, 15.0, 0.05, plot_params) ``` ## 2. Run the calculations ``` model_params = dict(param_sets[0]) properties_to_save = [ "timestep", "time", "Ekin_dia", "Ekin_adi", "Epot_dia", "Epot_adi", "Etot_dia", "Etot_adi", "norm_dia", "norm_adi", "pop_dia", "pop_adi", "q_dia", "q_adi", "q2_dia", "q2_adi", "p_dia", "p_adi", "p2_dia", "p2_adi", "denmat_dia", "denmat_adi", "custom_pops", "PSI_dia", "PSI_adi", "reciPSI_dia", "reciPSI_adi" ] params = { "nsteps":200, "dt":10.0, "progress_frequency":0.1, "rmin":[-35.0], "rmax":[35.0], "dx":[0.1], "nstates":2, "x0":[-10.0], "p0":[20.0], "istate":[1,0], "masses":[2000.0], "k":[0.001], "integrator":"SOFT", "prefix":"Tut4-1", "hdf5_output_level":3, "compression_level":[0,0,0], "use_compression":0, "mem_output_level":3, "txt_output_level":0, "properties_to_save": properties_to_save, "custom_pops":[ [0, [-40], [-5]], [0, [-5], [5]], [0, [5], [40]], [1, [-40], [-5]], [1, [-5], [5]], [1, [5], [40]] ] } params1 = dict(params) params1.update({ "prefix":"Tut4-1" }) res = compute.run_relaxation( params1, potential, model_params ) ``` ## 3. Plot the results ``` with h5py.File("Tut4-1/data.hdf", 'r') as f: t = list(f["time/data"][:]) print(t) #print(list(f["boxed_pops/0/data"][:, 0, 0])) print(list(f["custom_pops/data"][:, 0, 0, 0])) print(list(f["pop_adi/data"][:, 0, 0])) plot_params = {"prefix":"Tut4-1", "filename":"mem_data.hdf", "hdf5_output_level":2, "which_dofs":[0], "which_adi_states":[0, 1], "which_dia_states":[0, 1], "properties_to_save": [ "timestep", "time", "Ekin_dia", "Ekin_adi", "Epot_dia", "Epot_adi", "Etot_dia", "Etot_adi", "norm_dia", "norm_adi", "pop_dia", "pop_adi", "q_dia", "q_adi", "q2_dia", "q2_adi", "p_dia", "p_adi", "p2_dia", "p2_adi", "denmat_dia", "denmat_adi", "custom_pops", "PSI_dia", "PSI_adi", "reciPSI_dia", "reciPSI_adi" ] } plot.plot_hdf5(plot_params) def plot_custom_pops(plot_params): """ This function is meant to plot the results stored in the hdf files generated by the exact dynamics runs Args: prefix ( string ): the name of the directory containing the input HDF5 file This directory will also be used to output the generated picture files [ default : "out"] filename ( string ): name of the HDF5 file to read [ default: "data.hdf"] output_level ( int ): the level of info contained in the HDF5 file [ default : 3] which_adi_states ( list of ints ) : indices of the adiabatic states to print [ default: [0] ] which_dia_states ( list of ints ) : indices of the diabatic states to print [ default: [0] ] colors ( dictionary ): the definition of the colors to use clrs_index ( list of strings ) : defines the mapping of the colors on integers and vice versa """ plt.rc('axes', titlesize=24) # fontsize of the axes title plt.rc('axes', labelsize=20) # fontsize of the x and y labels plt.rc('legend', fontsize=20) # legend fontsize plt.rc('xtick', labelsize=16) # fontsize of the tick labels plt.rc('ytick', labelsize=16) # fontsize of the tick labels plt.rc('figure.subplot', left=0.2) plt.rc('figure.subplot', right=0.95) plt.rc('figure.subplot', bottom=0.13) plt.rc('figure.subplot', top=0.88) colors = {} colors.update({"11": "#8b1a0e"}) # red colors.update({"12": "#FF4500"}) # orangered colors.update({"13": "#B22222"}) # firebrick colors.update({"14": "#DC143C"}) # crimson colors.update({"21": "#5e9c36"}) # green colors.update({"22": "#006400"}) # darkgreen colors.update({"23": "#228B22"}) # forestgreen colors.update({"24": "#808000"}) # olive colors.update({"31": "#8A2BE2"}) # blueviolet colors.update({"32": "#00008B"}) # darkblue colors.update({"41": "#2F4F4F"}) # darkslategray clrs_index = ["11", "21", "31", "41", "12", "22", "32", "13","23", "14", "24"] # Parameters and dimensions critical_params = [ ] default_params = { "prefix":"out", "filename":"data.hdf", "hdf5_output_level":2, "colors":colors, "clrs_index":clrs_index, "figs":[] } comn.check_input(plot_params, default_params, critical_params) filename = plot_params["filename"] prefix = plot_params["prefix"] hdf5_output_level = plot_params["hdf5_output_level"] colors = plot_params["colors"] clrs_index = plot_params["clrs_index"] figs = plot_params["figs"] out_prefix = prefix with h5py.File(F"{prefix}/{filename}", 'r') as f: t = None if "time" in properties_to_save: t = list(f["time/data"][:]) #=============== Populations ====================== if t != None: nfigs = len(figs) for ifig in range(nfigs): plt.figure(ifig, figsize=(12, 12)) # dpi=300, frameon=False) plt.subplot(1, 1, 1) #plt.ylim(0, 1) plt.title(F'{figs[ifig][0]}' ) plt.xlabel('Time, a.u.') plt.ylabel('Population') nlines = len(figs[ifig]) for i in range(1, nlines): line_label = figs[ifig][i][0] pop_type = figs[ifig][i][1] istate = figs[ifig][i][2] line_color_index = figs[ifig][i][3] clr = colors[clrs_index[ line_color_index ]] Pi = list(f["custom_pops/data"][:, pop_type, istate, 0]) plt.plot(t, Pi, label=F'{line_label}', linewidth=10, color = clr) plt.legend() plt.savefig(F"{prefix}/Custom_pops_{i-1}.png", dpi=300) plt.savefig(F"{prefix}/Custom_pops_{i-1}.pdf", dpi=300) plt.show() plt.close() _plot_params = { "prefix":"Tut4-1", "filename":"mem_data.hdf", "hdf5_output_level":2, "colors":colors, "clrs_index":clrs_index, "figs":[ [ "Diabatic pops", ["reflection on the lower state", 0, 0, 0], ["unreacted on the lower state", 1, 0, 1], ["transmission on the lower state", 2, 0, 2] ], [ "Diabatic pops", ["reflection on the upper state", 0, 1, 0], ["unreacted on the upper state", 1, 1, 1], ["transmission on the upper state", 2, 1, 2] ], [ "Adiabatic pops", ["reflection on the lower state", 3, 0, 0], ["unreacted on the lower state", 4, 0, 1], ["transmission on the lower state", 5, 0, 2] ], [ "Adiabatic pops", ["reflection on the upper state", 3, 1, 0], ["unreacted on the upper state", 4, 1, 1], ["transmission on the upper state", 5, 1, 2] ] ] } plot_custom_pops(_plot_params) ``` ## Scattering probabilities Now, lets repeat the calculations many times, with different initial momenta and save all the results in different folders ``` prefix = "Tut4-2" model_params = dict(param_sets[0]) properties_to_save = [ "timestep", "time", "Ekin_dia", "Ekin_adi", "Epot_dia", "Epot_adi", "Etot_dia", "Etot_adi", "norm_dia", "norm_adi", "pop_dia", "pop_adi", "q_dia", "q_adi", "q2_dia", "q2_adi", "p_dia", "p_adi", "p2_dia", "p2_adi", "denmat_dia", "denmat_adi", "custom_pops", "PSI_dia", "PSI_adi", "reciPSI_dia", "reciPSI_adi" ] params = { "nsteps":200, "dt":10.0, "progress_frequency":0.1, "rmin":[-35.0], "rmax":[35.0], "dx":[0.1], "nstates":2, "x0":[-10.0], "p0":[20.0], "istate":[1,0], "masses":[2000.0], "k":[0.001], "integrator":"SOFT", "prefix":"Tut4-2", "hdf5_output_level":0, "compression_level":[0,0,0], "use_compression":0, "mem_output_level":3, "txt_output_level":0, "properties_to_save": properties_to_save, "custom_pops":[ [0, [-40], [-5]], [0, [-5], [5]], [0, [5], [40]], [1, [-40], [-5]], [1, [-5], [5]], [1, [5], [40]] ] } if not os.path.isdir(prefix): os.mkdir(prefix) P0 = [5.0, 6.0, 7.0, 8.0, 10.0, 12.0, 13.0, 15.0, 18.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0] ninit = len(P0) for i in range(ninit): print(F"=============== initial momentum {P0[i]} ============") if not os.path.isdir(F"{prefix}/{i}"): os.mkdir(F"{prefix}/{i}") params1 = dict(params) params1.update({"prefix": F"{prefix}/{i}", "p0":[P0[i] ], "nsteps":int(200 * (200.0/P0[i])) }) compute.run_relaxation( params1, potential, model_params ) P0 = [ 5.0, 6.0, 7.0, 8.0, 10.0, 12.0, 13.0, 15.0, 18.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0] ninit = len(P0) plt.figure(1, figsize=(48, 12)) # dpi=300, frameon=False) plt.subplot(1, 3, 1) plt.title("Unreacted pop") plt.xlabel('Time, a.u.') plt.ylabel('Population') for i in [7]: #range(ninit): nclrs = len(clrs_index) clr = colors[clrs_index[ i % nclrs]] with h5py.File(F"Tut4-2/{i}/mem_data.hdf", 'r') as f: t = list(f["time/data"][:]) p0 = list(f["custom_pops/data"][:, 4, 0, 0]) # adiabatic not reacted, on state 0 p1 = list(f["custom_pops/data"][:, 4, 1, 0]) # adiabatic not reacted, on state 1 p_unreact = [] sz = len(p0) for j in range(sz): p_unreact.append(p0[j] + p1[j]) #print(F" === init cond = {i} ===") #print(p) plt.plot(t, p_unreact, label=F'{i}', linewidth=10, color = clr) plt.legend() plt.subplot(1, 3, 2) plt.title("Reflected pop") plt.xlabel('Time, a.u.') plt.ylabel('Population') for i in [7]: #range(ninit): nclrs = len(clrs_index) clr = colors[clrs_index[ i % nclrs]] with h5py.File(F"Tut4-2/{i}/mem_data.hdf", 'r') as f: t = list(f["time/data"][:]) p0 = list(f["custom_pops/data"][:, 3, 0, 0]) # adiabatic not reacted, on state 0 p1 = list(f["custom_pops/data"][:, 3, 1, 0]) # adiabatic not reacted, on state 1 p_refl = [] sz = len(p0) for j in range(sz): p_refl.append(p0[j] + p1[j]) #print(F" === init cond = {i} ===") #print(p) plt.plot(t, p_refl, label=F'{i}', linewidth=10, color = clr) plt.legend() ```
github_jupyter
``` import numpy as np import pandas as pd from sklearn.metrics import roc_auc_score import tensorflow as tf from sklearn.feature_extraction.text import CountVectorizer from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D from sklearn.model_selection import train_test_split from keras.utils.np_utils import to_categorical import re from livelossplot import PlotLossesKeras import sys, os, re, csv, codecs, numpy as np, pandas as pd from keras.layers import GRU from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation from keras.layers import Bidirectional, GlobalMaxPool1D from keras.models import Model from keras import initializers, regularizers, constraints, optimizers, layers from keras.layers import Input, Dense,multiply from keras.layers.core import * from keras.layers.recurrent import LSTM from keras.models import * import attention_utils data = pd.read_csv('Sentiment.csv.zip') data = data[['text','sentiment']] data = data[data.sentiment != "Neutral"] data['text'] = data['text'].apply(lambda x: x.lower()) data['text'] = data['text'].apply((lambda x: re.sub('[^a-zA-z0-9\s]','',x))) print('pozitive size', data[ data['sentiment'] == 'Positive'].size) print('negative size', data[ data['sentiment'] == 'Negative'].size) for idx,row in data.iterrows(): row[0] = row[0].replace('rt',' ') max_features = 2000 tokenizer = Tokenizer(num_words=max_features, split=' ') tokenizer.fit_on_texts(data['text'].values) X = tokenizer.texts_to_sequences(data['text'].values) X = pad_sequences(X) def as_keras_metric(method): import functools from keras import backend as K import tensorflow as tf @functools.wraps(method) def wrapper(self, args, **kwargs): """ Wrapper for turning tensorflow metrics into keras metrics """ value, update_op = method(self, args, **kwargs) K.get_session().run(tf.local_variables_initializer()) with tf.control_dependencies([update_op]): value = tf.identity(value) return value return wrapper auc_roc = as_keras_metric(tf.metrics.auc) recall = as_keras_metric(tf.metrics.recall) embed_dim = 128 lstm_out = 196 model = Sequential() model.add(Embedding(max_features, embed_dim,input_length = X.shape[1])) model.add(SpatialDropout1D(0.5)) model.add(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(2,activation='softmax')) model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy', auc_roc]) print(model.summary()) Y = pd.get_dummies(data['sentiment']).values X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 42) print(X_train.shape,Y_train.shape) print(X_test.shape,Y_test.shape) callbacks = [ PlotLossesKeras()] batch_size = 128 model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs = 10, batch_size=batch_size, callbacks = callbacks) scores = model.evaluate(X_test, Y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) # Bidirectional LSTM embed_dim = 128 lstm_out = 196 model = Sequential() model.add(Embedding(max_features, embed_dim,input_length = X.shape[1])) model.add(SpatialDropout1D(0.5)) model.add(Bidirectional(LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2))) model.add(Dense(2,activation='softmax')) model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy', auc_roc]) batch_size = 64 model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs = 10, batch_size=128, callbacks = callbacks) scores = model.evaluate(X_test, Y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) # Bidirectional LSTM embed_dim = 128 lstm_out = 196 model = Sequential() model.add(Embedding(max_features, embed_dim,input_length = X.shape[1])) model.add(SpatialDropout1D(0.4)) model.add(Bidirectional(GRU(lstm_out, dropout=0.2, recurrent_dropout=0.2))) model.add(Dense(2,activation='softmax')) model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy', auc_roc]) batch_size = 64 model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs = 10, batch_size=128, callbacks = callbacks) scores = model.evaluate(X_test, Y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) X.shape[1] MAX_SEQUENCE_LENGTH = X.shape[1] embedding_layer = Embedding(max_features, embed_dim, input_length = X.shape[1]) lstm_layer = LSTM(lstm_out, dropout=0.2, recurrent_dropout=0.2,return_sequences=True) comment_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') embedded_sequences= embedding_layer(comment_input) x = lstm_layer(embedded_sequences) x = Dropout(0.2)(x) merged = Attention(MAX_SEQUENCE_LENGTH)(x) merged = Dense(2, activation='relu')(merged) merged = Dropout(0.4)(merged) #merged = BatchNormalization()(merged) preds = Dense(2, activation='sigmoid')(merged) model = Model(inputs=[comment_input], \ outputs=preds) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy', auc_roc]) print(model.summary()) model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs = 10, batch_size=64, callbacks = callbacks) scores = model.evaluate(X_test, Y_test, verbose=1) print('Test loss:', scores[0]) print('Test accuracy:', scores[1]) class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): """ Keras Layer that implements an Attention mechanism for temporal data. Supports Masking. Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756] # Input shape 3D tensor with shape: `(samples, steps, features)`. # Output shape 2D tensor with shape: `(samples, features)`. :param kwargs: Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True. The dimensions are inferred based on the output shape of the RNN. Example: model.add(LSTM(64, return_sequences=True)) model.add(Attention()) """ self.supports_masking = True #self.init = initializations.get('glorot_uniform') self.init = initializers.get('glorot_uniform') self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer) self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint) self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): # do not pass the mask to the next layers return None def call(self, x, mask=None): # eij = K.dot(x, self.W) TF backend doesn't support it # features_dim = self.W.shape[0] # step_dim = x._keras_shape[1] features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) # apply mask after the exp. will be re-normalized next if mask is not None: # Cast the mask to floatX to avoid float64 upcasting in theano a *= K.cast(mask, K.floatx()) # in some cases especially in the early stages of training the sum may be almost zero a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a #print weigthted_input.shape return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): #return input_shape[0], input_shape[-1] return input_shape[0], self.features_dim ```
github_jupyter
# Natural Language Processing In this homework, you will apply the TFIDF technique to text classification as well as use word2vec model to generate the dense word embedding for other NLP tasks. ## Text Classification The 20 Newsgroups data set is a collection of approximately 20,000 newsgroup documents, partitioned (nearly) evenly across 20 different newsgroups. To the best of my knowledge, it was originally collected by Ken Lang, probably for his Newsweeder: Learning to filter netnews paper, though he does not explicitly mention this collection. The 20 newsgroups collection has become a popular data set for experiments in text applications of machine learning techniques, such as text classification and text clustering. In this lab, we will experiment different feature extraction on the 20 newgroups dataset, including the count vector and TF-IDF vector. Also, we will apply the Naive Bayes classifier to this dataset and report the prediciton accuracy. ### Load the explore the 20newsgroup data 20 news group data is part of the sklearn library. We can directly load the data using the following command. ``` # load the traning data and test data import numpy as np from sklearn.datasets import fetch_20newsgroups twenty_train = fetch_20newsgroups(subset='train', shuffle=False) twenty_test = fetch_20newsgroups(subset='test', shuffle=False) # print total number of categories print("Number of training data:" + str(len(twenty_train.data))) print("Number of categories:" + str(len(twenty_train.target_names))) # print the first text and its category print(twenty_train.data[0]) print(twenty_train.target[0]) # You can check the target variable by printing all the categories twenty_train.target_names ``` ### Build a Naive Bayes Model Your task is to build practice an ML model to classify the newsgroup data into different categories. You will try both raw count and TF-IDF for feature extraction and then followed by a Naive Bayes classifier. Note that you can connect the feature generation and model training steps into one by using the [pipeline API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) in sklearn. Try to use Grid Search to find the best hyper parameter from the following settings (feel free to explore other options as well): * Differnet ngram range * Weather or not to remove the stop words * Weather or not to apply IDF After building the best model from the training set, we apply that model to make predictions on the test data and report its accuracy. ``` # TODO ``` --------- ## Word Embedding with word2vec Word embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. In this assessment, we will experiment with [word2vec](https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf) model from package [gensim](https://radimrehurek.com/gensim/) and generate word embeddings from a review dataset. You can then explore those word embeddings and see if they make sense semantically. ``` import gzip import logging import warnings from gensim.models import Word2Vec warnings.simplefilter(action='ignore', category=FutureWarning) logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) ``` ### Load the review data ``` import gensim def read_input(input_file): """This method reads the input file which is in gzip format""" print("reading file {0}...this may take a while".format(input_file)) with gzip.open(input_file, 'rb') as f: for i, line in enumerate(f): if (i % 10000 == 0): print("read {0} reviews".format(i)) # do some pre-processing and return list of words for each review b text yield gensim.utils.simple_preprocess(line) documents = list(read_input('reviews_data.txt.gz')) logging.info("Done reading data file") ``` ### Train the word2vec model The word2vec algorithms include skip-gram and CBOW models, using either hierarchical softmax or negative sampling introduced in Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality. A word2vec tutorial can be found [here](https://rare-technologies.com/word2vec-tutorial/). ``` # TODO build vocabulary and train model model = None ``` ### Find similar words for a given word Once the model is built, you can find interesting patterns in the model. For example, can you find the 5 most similar words to word `polite` ``` # TODO: look up top 5 words similar to 'polite' using most_similar function # Feel free to try other words and see if it makes sense. ``` ### Compare the word embedding by comparing their similarities We can also find similarity betwen two words in the embedding space. Can you find the similarities between word `great` and `good`/`horrible`, and also `dirty` and `clean`/`smelly`. Feel free to play around with the word embedding you just learnt and see if they make sense. ``` # TODO: find similarities between two words using similarity function ```
github_jupyter
# Training fine flow prediction Assuming source image $I_s$ and target image $I_t$ are already coarsely aligned, this notebook will try to predict a fine flow $F_{s\rightarrow t}$ between them. TODO describe objective functions used in this project ``` %load_ext autoreload %autoreload 2 ``` We assume you already have a zipped dataset in `data` folder. ``` %cd workspace !ln -s ../data/MegaDepth_cleansed.zip MegaDepth_cleansed.zip ``` If you are working in Google Colab, you might find this cell useful. It performs 0. Sanity check if you are using Google Colab 1. Mount Google Drive. 2. Assume you have a folder `RANSAC-Flow` that is equivalent to this repository, which contains `data` folder. 3. Copy the dataset to `/tmp` ``` # 0. try: import google.colab IN_COLAB = True except ModuleNotFoundError: IN_COLAB = False finally: if not IN_COLAB: raise RuntimeError('not running on Google Colab') # 1. from google.colab import drive drive.mount('/content/drive') # 2. %cd /content/drive/MyDrive/RANSAC-Flow # 3. !rsync -ah --progress data/MegaDepth_cleansed.zip /tmp !ln -s /tmp/MegaDepth_cleansed.zip MegaDepth_cleansed.zip ``` Import packages that we will use throughout this notebook. ``` from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.loggers import TensorBoardLogger ``` We enable logging here to make debug easier. ``` import logging logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(name)s :: %(levelname)s :: %(message)s", handlers=[logging.StreamHandler()], ) # fine tune submodules log level logging.getLogger("ransacflow").setLevel(logging.WARNING) logging.getLogger('ransacflow.data').setLevel(logging.WARNING) ``` ## Prepare dataset We already pack some datasets used in the original paper as `LightningDataModule`. We will import it here. ``` from ransacflow.data import MegaDepthDataModule mega_depth = MegaDepthDataModule( "MegaDepth_cleansed.zip", train_image_size=224, train_batch_size=2, val_image_size=480, ) #TODO add some sanity check for the dataset here, previews # TODO setup environments for the following training sessions, how? # FIXME is it possible to share the Trainer object across all 3 stages ``` ## Stage 1 Only train the **reconstruction loss**. It is based on the idea that source image $I_s$ warped with the predicted flow $F_{s\rightarrow t}$ should align well with the target image $I_t$. In the original work, they use the structural similarity (SSIM) as the perception model. $$ L_{\text{recon}}\left(I_s, I_t\right) = \sum_{(x,y)\in I_t} M_t^{\text{cycle}}(x,y) \left( 1 - \text{SSIM}\left\lbrace I_s(x^\prime, y^\prime), I_t(x,y) \right\rbrace \right) $$ FIXME wtf is M_t doing here? ``` # DEBUG somehow dataset needs to reload everythime for correct coords from ransacflow.data import MegaDepthDataModule mega_depth = MegaDepthDataModule( "MegaDepth_cleansed.zip", train_image_size=224, train_batch_size=4, val_image_size=480, num_workers=8 ) ## parameter names log_dir = "MegaDepth_logs" ## from ransacflow.train import RANSACFlowModelStage1 ransac_flow = RANSACFlowModelStage1( alpha=0, beta=0, gamma=0, kernel_size=7, ssim_window_size=11, lr=2e-4, ) # FIXME unify TB logging location and experiment name trainer = Trainer( gpus=-1, fast_dev_run=False, max_epochs=200, val_check_interval=0.25, logger=TensorBoardLogger(log_dir, name="stage1"), callbacks=[EarlyStopping(monitor="val_loss", min_delta=0.01, patience=3)], ) trainer.fit(ransac_flow, mega_depth) ``` All following command line interface are copied from the original implementation, temporarily. ``` --nEpochs 200 --lr 2e-4 --kernelSize 7 --imgSize 224 --batchSize 16 --lambda-match 0.0, alpha --mu-cycle 0.0, beta --grad 0.0, gamma --trainMode flow --margin 88 ``` ## Stage 2 Train jointly the **reconstruction loss** and **cycle consistency of the flow**. Asides from the reconstruction loss mentioned in previous stage, we start to enforce cycle consistency of the flow by $$ L_{\text{cycle}} = \sum_{(x,y) \in I_t} M_t^{\text{circle}} (x,y) \left\lVert \left(x^\prime, y^\prime \right), \bm{F}_{t\rightarrow s}(x,y) \right\rVert_2 $$ FIXME what happened with (x^\prime, y^\prime), F_{t->s}? Are they multiplied? ``` from ransacflow.train import RANSACFlowModelStage2 ransac_flow = RANSACFlowModelStage2(alpha=0, beta=1, gamma=0, kernel_size=7, lr=2e-4) # FIXME unify TB logging location and experiment name trainer = Trainer( max_epochs=50, logger=TensorBoardLogger("tb_logs", name="RANSAC-Flow_stage2"), callbacks=[EarlyStoppping(monitor="val_loss", min_delta=0.01, patience=3)], ) trainer.fit(ransac_flow, MegaDepthDataModule) --nEpochs 50 --lr 2e-4 --kernelSize 7 --imgSize 224 --batchSize 16 --lambda-match 0.0, alpha --mu-cycle 1.0, beta --grad 0.0, gamma --trainMode flow --margin 88 ``` ## Stage 3 Train all three losses together: **reconstruction loss**, **cycle consistency of the flow**, and **matchability loss**. Matchability mask can be seen as pixel-wise weights for the reconstruction and cycle consistency loss. These losses encourage th matchability to be zero. To counteract this effect, the matchability loss encourages the matchability mask to be close to one. FIXME equation for matchability FIXME still doesn't understand what matchability actually implies, what is the difference between this and cycle loss? ``` from ransacflow.train import RANSACFlowModelStage3 ransac_flow = RANSACFlowModelStage3(alpha=0.01, beta=1, gamma=0, kernel_size=7, lr=2e-4) # FIXME unify TB logging location and experiment name trainer = Trainer( max_epochs=50, logger=TensorBoardLogger("tb_logs", name="RANSAC-Flow_stage3"), callbacks=[EarlyStoppping(monitor="val_loss", min_delta=0.01, patience=3)], ) trainer.fit(ransac_flow, MegaDepthDataModule) --nEpochs 50 --lr 2e-4 --kernelSize 7 --imgSize 224 --batchSize 16 --lambda-match 0.01, alpha --mu-cycle 1.0, beta --grad 0.0, gamma --trainMode flow+match --margin 88 ``` ## Stage 4.1 This additional stage fine tune on SOMETHING MAGICAL, so the output image introduce less distortions. TODO need to update description from the original paper ## Stage 4.2 This additional stage uses perceptual loss, TODO add description about why and how to use perceptual loss
github_jupyter
# Gaussian Code Exercise Read through the code below and fill out the TODOs. You'll find a cell at the end of the Jupyter notebook containing unit tests. After you've run the code cell with the Gaussian class, you can run the final cell to check that your code functions as expected. This exercise includes a file called 'numbers.txt', which you can see if you click on the 'Jupyter' icon at the top of the workspace and then go into the folder titled 3.OOP_code_gaussian_class. The 'numbers.txt' file is read in by the read_data_file() method. There is also a solution in the 3.OOP_code_gaussian_class folder in a file called answer.py. ``` import math import matplotlib.pyplot as plt class Gaussian(): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu = 0, sigma = 1): self.mean = mu self.stdev = sigma self.data = [] def calculate_mean(self): """Method to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ #TODO: Calculate the mean of the data set. Remember that the data set is stored in self.data # Change the value of the mean attribute to be the mean of the data set # Return the mean of the data set avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean pass def calculate_stdev(self, sample=True): """Method to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ # TODO: # Calculate the standard deviation of the data set # # The sample variable determines if the data set contains a sample or a population # If sample = True, this means the data is a sample. # Keep the value of sample in mind for calculating the standard deviation # # Make sure to update self.stdev and return the standard deviation as well if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.mean sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma/n) self.stdev = sigma return self.stdev pass def read_data_file(self, file_name, sample=True): """Method to read in data from a txt file. The txt file should have one number (float) per line. The numbers are stored in the data attribute. After reading in the file, the mean and standard deviation are calculated Args: file_name (string): name of a file to read from Returns: None """ # This code opens a data file and appends the data to a list called data_list with open(file_name) as file: data_list = [] line = file.readline() while line: data_list.append(int(line)) line = file.readline() file.close() # TODO: # Update the self.data attribute with the data_list # Update self.mean with the mean of the data_list. # You can use the calculate_mean() method with self.calculate_mean() # Update self.stdev with the standard deviation of the data_list. Use the # calculate_stdev() method. self.data = data_list self.mean = self.calculate_mean() self.stdev = self.calculate_stdev(sample) def plot_histogram(self): """Method to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ # TODO: Plot a histogram of the data_list using the matplotlib package. # Be sure to label the x and y axes and also give the chart a title plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ # TODO: Calculate the probability density function of the Gaussian distribution # at the value x. You'll need to use self.stdev and self.mean to do the calculation return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) pass def plot_histogram_pdf(self, n_spaces = 50): """Method to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ #TODO: Nothing to do for this method. Try it out and see how it works. mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y # Unit tests to check your solution import unittest class TestGaussianClass(unittest.TestCase): def setUp(self): self.gaussian = Gaussian(25, 2) def test_initialization(self): self.assertEqual(self.gaussian.mean, 25, 'incorrect mean') self.assertEqual(self.gaussian.stdev, 2, 'incorrect standard deviation') def test_pdf(self): self.assertEqual(round(self.gaussian.pdf(25), 5), 0.19947,\ 'pdf function does not give expected result') def test_meancalculation(self): self.gaussian.read_data_file('numbers.txt', True) self.assertEqual(self.gaussian.calculate_mean(),\ sum(self.gaussian.data) / float(len(self.gaussian.data)), 'calculated mean not as expected') def test_stdevcalculation(self): self.gaussian.read_data_file('numbers.txt', True) self.assertEqual(round(self.gaussian.stdev, 2), 92.87, 'sample standard deviation incorrect') self.gaussian.read_data_file('numbers.txt', False) self.assertEqual(round(self.gaussian.stdev, 2), 88.55, 'population standard deviation incorrect') tests = TestGaussianClass() tests_loaded = unittest.TestLoader().loadTestsFromModule(tests) unittest.TextTestRunner().run(tests_loaded) ```
github_jupyter
``` # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Author(s): Kevin P. Murphy (murphyk@gmail.com) and Mahmoud Soliman (mjs@aucegypt.edu) ``` <a href="https://opensource.org/licenses/MIT" target="_parent"><img src="https://img.shields.io/github/license/probml/pyprobml"/></a> <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/figures/chapter14_neural_networks_for_images_figures.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Figure 14.1:<a name='14.1'></a> <a name='imageTemplates'></a> We can classify a digit by looking for certain discriminative features (image templates) occuring in the correct (relative) locations. From Figure 5.1 of <a href='#kerasBook'>[Cho17]</a> . Used with kind permission of Francois Chollet. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.1.png") ``` ## Figure 14.2:<a name='14.2'></a> <a name='tab:convTable'></a> Discrete convolution of $\mathbf x =[1,2,3,4]$ with $\mathbf w =[5,6,7]$ to yield $\mathbf z =[5,16,34,52,45,28]$. We see that this operation consists of ``flipping'' $\mathbf w $ and then ``dragging'' it over $\mathbf x $, multiplying elementwise, and adding up the results. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts ``` ## Figure 14.3:<a name='14.3'></a> <a name='conv1d'></a> 1d cross correlation. Adapted from Figure 13.10.1 of <a href='#dive'>[Zha+20]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.3.png") ``` ## Figure 14.4:<a name='14.4'></a> <a name='diveConv2d'></a> Illustration of 2d cross correlation. To reproduce this figure, click the open in colab button: <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/conv2d_torch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.4.png") ``` ## Figure 14.5:<a name='14.5'></a> <a name='cholletConv2d'></a> Convolving a 2d image (left) with a $3 \times 3$ filter (middle) produces a 2d response map (right). The bright spots of the response map correspond to locations in the image which contain diagonal lines sloping down and to the right. From Figure 5.3 of <a href='#kerasBook'>[Cho17]</a> . Used with kind permission of Francois Chollet. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.5.png") ``` ## Figure 14.6:<a name='14.6'></a> <a name='CNN2d'></a> Illustration of padding and strides in 2d convolution. (a) We apply ``same convolution'' to a $5 \times 7$ input (with zero padding) using a $3 \times 3$ filter to create a $5 \times 7$ output. (b) Now we use a stride of 2, so the output has size $3 \times 4$. Adapted from Figures 14.3--14.4 of <a href='#Geron2019'>[Aur19]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.6_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.6_B.png") ``` ## Figure 14.7:<a name='14.7'></a> <a name='convMultiChannel'></a> Illustration of 2d convolution applied to an input with 2 channels. To reproduce this figure, click the open in colab button: <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/conv2d_torch.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.7.png") ``` ## Figure 14.8:<a name='14.8'></a> <a name='CNNhypercolumn'></a> Illustration of a CNN with 2 convolutional layers. The input has 3 color channels. The feature maps at internal layers have multiple channels. The cylinders correspond to hypercolumns, which are feature vectors at a certain location. Adapted from Figure 14.6 of <a href='#Geron2019'>[Aur19]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.8.png") ``` ## Figure 14.9:<a name='14.9'></a> <a name='maxPool'></a> Illustration of maxpooling with a 2x2 filter and a stride of 1. Adapted from Figure 6.5.1 of <a href='#dive'>[Zha+20]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.9.png") ``` ## Figure 14.10:<a name='14.10'></a> <a name='cnnIntro'></a> A simple CNN for classifying images. Adapted from https://blog.floydhub.com/building-your-first-convnet/ . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.10.png") ``` ## Figure 14.11:<a name='14.11'></a> <a name='groupNorm'></a> Illustration of different activation normalization methods for a CNN. Each subplot shows a feature map tensor, with N as the batch axis, C as the channel axis, and (H, W) as the spatial axes. The pixels in blue are normalized by the same mean and variance, computed by aggregating the values of these pixels. Left to right: batch norm, layer norm, instance norm, and group norm (with 2 groups of 3 channels). From Figure 2 of <a href='#Wu2018GN'>[YK18]</a> . Used with kind permission of Kaiming He. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.11.png") ``` ## Figure 14.12:<a name='14.12'></a> <a name='lenet'></a> LeNet5, a convolutional neural net for classifying handwritten digits. From Figure 6.6.1 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.12.png") ``` ## Figure 14.13:<a name='14.13'></a> <a name='alexnet'></a> (a) LeNet5. We assume the input has size $1 \times 28 \times 28$, as is the case for MNIST. From Figure 6.6.2 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. (b) AlexNet. We assume the input has size $3 \times 224 \times 224$, as is the case for (cropped and rescaled) images from ImageNet. From Figure 7.1.2 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.13_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.13_B.png") ``` ## Figure 14.14:<a name='14.14'></a> <a name='cnnMnist'></a> Results of applying a CNN to some MNIST images (cherry picked to include some errors). Red is incorrect, blue is correct. (a) After 1 epoch of training. (b) After 2 epochs. To reproduce this figure, click the open in colab button: <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/cnn_mnist_tf.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.14_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.14_B.png") ``` ## Figure 14.15:<a name='14.15'></a> <a name='inception'></a> Inception module. The $1 \times 1$ convolutional layers reduce the number of channels, keeping the spatial dimensions the same. The parallel pathways through convolutions of different sizes allows the model to learn which filter size to use for each layer. The final depth concatenation block combines the outputs of all the different pathways (which all have the same spatial size). From Figure 7.4.1 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.15.png") ``` ## Figure 14.16:<a name='14.16'></a> <a name='googlenet'></a> GoogLeNet (slightly simplified from the original). Input is on the left. From Figure 7.4.2 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.16.png") ``` ## Figure 14.17:<a name='14.17'></a> <a name='resnetBlock'></a> A residual block for a CNN. Left: standard version. Right: version with 1x1 convolution, to allow a change in the number of channels between the input to the block and the output. From Figure 7.6.3 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.17.png") ``` ## Figure 14.18:<a name='14.18'></a> <a name='resnet18'></a> The ResNet-18 architecture. Each dotted module is a residual block shown in \cref fig:resnetBlock . From Figure 7.6.4 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.18.png") ``` ## Figure 14.19:<a name='14.19'></a> <a name='densenet'></a> (a) Left: a residual block adds the output to the input. Right: a densenet block concatenates the output with the input. (b) Illustration of a densenet. From Figures 7.7.1--7.7.2 of <a href='#dive'>[Zha+20]</a> . Used with kind permission of Aston Zhang. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.19_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.19_B.png") ``` ## Figure 14.20:<a name='14.20'></a> <a name='anchorBoxes'></a> (a) Illustration of face detection, a special case of object detection. (Photo of author and his wife Margaret, taken at Filoli in California in Feburary, 2018. Image processed by Jonathan Huang using SSD face model.) (b) Illustration of anchor boxes. Adapted from \citep [Sec 12.5] dive . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.20_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.20_B.png") ``` ## Figure 14.21:<a name='14.21'></a> <a name='maskRCNN'></a> (a) Illustration of keypoint detection for body, hands and face using the OpenPose system. From Figure 8 of <a href='#openPose'>[Zhe+18]</a> . Used with kind permission of Yaser Sheikh. (b) Illustration of object detection and instance segmentation using Mask R-CNN. From https://github.com/matterport/Mask_RCNN . Used with kind permission of Waleed Abdulla. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.21_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.21_B.png") ``` ## Figure 14.22:<a name='14.22'></a> <a name='semanticSeg'></a> Illustration of an \bf encoder-decoder (aka \bf U-net ) CNN for semantic segmentation The encoder uses convolution (which downsamples), and the decoder uses transposed convolution (which upsamples). From Figure 1 of <a href='#segnet'>[VAR17]</a> . Used with kind permission of Alex Kendall. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.22.png") ``` ## Figure 14.23:<a name='14.23'></a> <a name='densePrediction'></a> Illustration of a multi-task dense prediction problem. From Based on Figure 1 of <a href='#Eigen2015'>[DR15]</a> . Used with kind permission of Rob Fergus. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.23.png") ``` ## Figure 14.24:<a name='14.24'></a> <a name='dilatedConv'></a> Dilated convolution with a 3x3 filter using rate 1, 2 and 3. From Figure 1 of <a href='#Cui2019cnn'>[Xim+19]</a> . Used with kind permission of Ximin Cui. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.24.png") ``` ## Figure 14.25:<a name='14.25'></a> <a name='transposedConv'></a> Transposed convolution with a filter of size $3 \times 3$ and stride of 2 to map a $2 \times 3$ input to a $5 \times 7$ output. Adapted from Figure 14.27 of <a href='#Geron2019'>[Aur19]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.25.png") ``` ## Figure 14.26:<a name='14.26'></a> <a name='goose'></a> Images that maximize the probability of ImageNet classes ``goose'' and ``ostrich'' under a simple Gaussian prior. From http://yosinski.com/deepvis . Used with kind permission of Jeff Clune. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.26.png") ``` ## Figure 14.27:<a name='14.27'></a> <a name='TVnorm'></a> Illustration of total variation norm. (a) Input image: a green sea turtle (Used with kind permission of Wikimedia author P. Lindgren). (b) Horizontal deltas. (c) Vertical deltas. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.27_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.27_B.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.27_C.png") ``` ## Figure 14.28:<a name='14.28'></a> <a name='deepdreamClassvis'></a> Images that maximize the probability of certain ImageNet classes under a TV prior. From https://research.googleblog.com/2015/06/inceptionism-going-deeper-into-neural.html . Used with kind permission of Alexander Mordvintsev. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.28.png") ``` ## Figure 14.29:<a name='14.29'></a> <a name='cnn-vis'></a> We visualize ``optimal stimuli'' for neurons in layers Conv 1, 3, 5 and fc8 in the AlexNet architecture, trained on the ImageNet dataset. For Conv5, we also show retrieved real images (under the column ``data driven'') that produce similar activations. Based on the method in <a href='#Mahendran16ijcv'>[MV16]</a> . Used with kind permission of Donglai Wei. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.29.png") ``` ## Figure 14.30:<a name='14.30'></a> <a name='deepdream'></a> Illustration of DeepDream. The CNN is an Inception classifier trained on ImageNet. (a) Starting image of an Aurelia aurita (also called moon jelly). (b) Image generated after 10 iterations. (c) Image generated after 50 iterations. From https://en.wikipedia.org/wiki/DeepDream . Used with kind permission of Wikipedia author Martin Thoma. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.30_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.30_B.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.30_C.png") ``` ## Figure 14.31:<a name='14.31'></a> <a name='styleTransfer'></a> Example output from a neural style transfer system (a) Content image: a green sea turtle (Used with kind permission of Wikimedia author P. Lindgren). (b) Style image: a painting by Wassily Kandinsky called ``Composition 7''. (c) Output of neural style generation. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.31_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.31_B.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.31_C.png") ``` ## Figure 14.32:<a name='14.32'></a> <a name='neuralStyleD2L'></a> Illustration of how neural style transfer works. Adapted from Figure 12.12.2 of <a href='#dive'>[Zha+20]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.32.png") ``` ## Figure 14.33:<a name='14.33'></a> <a name='featureMaps3Images'></a> Schematic representation of 3 kinds of feature maps for 3 different input images. Adapted from Figure 5.16 of <a href='#Foster2019'>[Dav19]</a> . ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.33.png") ``` ## Figure 14.34:<a name='14.34'></a> <a name='adversarialImage'></a> Example of an adversarial attack on an image classifier. Left column: original image which is correctly classified. Middle column: small amount of structured noise which is added to the input (magnitude of noise is magnified by $10 \times $). Right column: new image, which is confidently misclassified as a ``gibbon'', even though it looks just like the original ``panda'' image. Here $\epsilon =0.007$ From Figure 1 of <a href='#Goodfellow2015adversarial'>[IJC15]</a> . Used with kind permission of Ian Goodfellow. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.34.png") ``` ## Figure 14.35:<a name='14.35'></a> <a name='breakConvEvolved'></a> Images that look like random noise but which cause the CNN to confidently predict a specific class. From Figure 1 of <a href='#Nguyen2015'>[AJJ15]</a> . Used with kind permission of Jeff Clune. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.35.png") ``` ## Figure 14.36:<a name='14.36'></a> <a name='breakConvEvolvedStructured'></a> Synthetic images that cause the CNN to confidently predict a specific class. From Figure 1 of <a href='#Nguyen2015'>[AJJ15]</a> . Used with kind permission of Jeff Clune. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.36.png") ``` ## Figure 14.37:<a name='14.37'></a> <a name='image_spam'></a> An adversarially modified image to evade spam detectors. The image is constructed from scratch, and does not involve applying a small perturbation to any given image. This is an illustrative example of how large the space of possible adversarial inputs $\Delta $ can be when the attacker has full control over the input. From <a href='#biggio2011survey'>[Bat+11]</a> . Used with kind permission of Battista Biggio. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.37.png") ``` ## Figure 14.38:<a name='14.38'></a> <a name='adversarialBugs'></a> Illustration of robust vs non-robust features for separating two classes, represented by Gaussian blobs. The green line is the decision boundary induced by empirical risk minimization (ERM). The red line is the decision boundary induced by robust training --- it ignores the vertical feature $x_2$, which is less robust than the horizontal feature $x_1$. From Figure 14 of <a href='#Ilyas2019'>[And+19]</a> . Used with kind permission of Andrew Ilyas. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.38.png") ``` ## Figure 14.39:<a name='14.39'></a> <a name='adversarialGaussianNoise'></a> Effect of Gaussian noise of increasing magnitude on an image classifier. (The model is a ResNet-50 CNN (\cref sec:resnet ) trained on ImageNet with added Gaussian noise of magnitude $\sigma =0.6$.) From Figure 23 of <a href='#Ford2019'>[Nic+19]</a> . Used with kind permission of Justin Gilmer. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.39.png") ``` ## Figure 14.40:<a name='14.40'></a> <a name='adversarialGeometry'></a> (a) When the input dimension $n$ is large and the decision boundary is locally linear, even a small error rate in random noise will imply the existence of small adversarial perturbations. Here, $d(\mathbf x _0, E)$ denotes the distance from a clean input $\mathbf x _0$ to an adversarial example (A) while the distance from $\mathbf x _0$ to a random sample $N(0; \sigma ^2 I$ (B) will be approximately $\sigma \sqrt n $. As $n \rightarrow \infty $ the ratio of $d(x_0, A)$ to $d(\mathbf x _0, B)$ goes to 0. (b) A 2d slice of the InceptionV3 decision boundary through three points: a clean image (black), an adversarial example (red), and an error in random noise (blue). The adversarial example and the error in noise lie in the same region of the error set which is misclassified as ``miniature poodle'', which closely resembles a halfspace as in Figure (a). Used with kind permission of Justin Gilmer. ``` #@title Setup { display-mode: "form" } %%time # If you run this for the first time it would take ~25/30 seconds !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null !pip3 install nbimporter -qqq %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.40_A.png") pmlt.show_image("/pyprobml/book1/figures/images/Figure_14.40_B.png") ``` ## References: <a name='Nguyen2015'>[AJJ15]</a> N. Anh, Y. Jason and C. Jeff. "Deep Neural Networks are Easily Fooled: High ConfidencePredictions for Unrecognizable Images". (2015). <a name='Ilyas2019'>[And+19]</a> I. Andrew, S. Shibani, T. D. Logan, T. Brandon and M. Aleksander. "Adversarial Examples Are Not Bugs, They Are Features". abs/1905.02175 (2019). arXiv: 1905.02175 <a name='Geron2019'>[Aur19]</a> G. Aur'elien "Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques for BuildingIntelligent Systems (2nd edition)". (2019). <a name='biggio2011survey'>[Bat+11]</a> B. Battista, F. Giorgio, P. Ignazio and R. Fabio. "A survey and experimental evaluation of image spam filtering techniques". In: Pattern recognition letters (2011). <a name='kerasBook'>[Cho17]</a> F. Chollet "Deep learning with Python". (2017). <a name='Eigen2015'>[DR15]</a> E. David and F. Rob. "Predicting Depth, Surface Normals and Semantic Labels with aCommon Multi-Scale Convolutional Architecture". (2015). <a name='Foster2019'>[Dav19]</a> F. David "Generative Deep Learning: Teaching Machines to Paint, WriteCompose, and Play". (2019). <a name='Goodfellow2015adversarial'>[IJC15]</a> G. IanJ, S. Jonathon and S. Christian. "Explaining and Harnessing Adversarial Examples". (2015). <a name='Mahendran16ijcv'>[MV16]</a> M. MahendranA and V. VedaldiA. "Visualizing Deep Convolutional Neural Networks Using Natural Pre-images". In: ijcv (2016). <a name='Ford2019'>[Nic+19]</a> F. Nic, G. Justin, C. Nicolas and C. CubukDogus. "Adversarial Examples Are a Natural Consequence of Test Errorin Noise". abs/1901.10513 (2019). arXiv: 1901.10513 <a name='segnet'>[VAR17]</a> B. Vijay, K. Alex and C. Roberto. "SegNet: A Deep Convolutional Encoder-Decoder Architecture forImage Segmentation". In: pami (2017). <a name='Cui2019cnn'>[Xim+19]</a> C. Ximin, Z. Ke, G. Lianru, Z. Bing, Y. Dong and R. Jinchang. "Multiscale Spatial-Spectral Convolutional Network withImage-Based Framework for Hyperspectral Imagery Classification". In: Remote Sensing (2019). <a name='Wu2018GN'>[YK18]</a> W. Yuxin and H. Kaiming. "Group Normalization". (2018). <a name='dive'>[Zha+20]</a> A. Zhang, Z. Lipton, M. Li and A. Smola. "Dive into deep learning". (2020). <a name='openPose'>[Zhe+18]</a> C. Zhe, H. Gines, S. Tomas, W. WeiShih-En and S. Yaser. "OpenPose: Realtime Multi-Person 2D Pose Estimationusing Part Affinity Fields". abs/1812.08008 (2018). arXiv: 1812.08008
github_jupyter
# Model-Based RL In this exercise you will implement a policy and model network which work in tandem to solve the CartPole reinforcement learning problem. What is a model and why would we want to use one? In this case, a model is going to be a neural network that attempts to learn the dynamics of the real environment. For example, in the CartPole we would like a model to be able to predict the next position of the Cart given the previous position and an action. By learning an accurate model, we can train our agent using the model rather than requiring to use the real environment every time. While this may seem less useful when the real environment is itself a simulation, like in our CartPole task, it can have huge advantages when attempting to learn policies for acting in the physical world. How are we going to accomplish this in Tensorflow? We are going to be using a neural network that will learn the transition dynamics between a previous observation and action, and the expected new observation, reward, and done state. Our training procedure will involve switching between training our model using the real environment, and training our agent’s policy using the model environment. By using this approach we will be able to learn a policy that allows our agent to solve the CartPole task without actually ever training the policy on the real environment! ### Loading libraries and starting CartPole environment ``` from __future__ import print_function import numpy as np try: import cPickle as pickle except: import pickle import tensorflow as tf %matplotlib inline import matplotlib.pyplot as plt import math import sys if sys.version_info.major > 2: xrange = range del sys import gym env = gym.make('CartPole-v0') ``` ### Setting Hyper-parameters ``` # hyperparameters H = 8 # number of hidden layer neurons learning_rate = 1e-2 gamma = 0.99 # discount factor for reward decay_rate = 0.99 # decay factor for RMSProp leaky sum of grad^2 resume = False # resume from previous checkpoint? model_bs = 3 # Batch size when learning from model real_bs = 3 # Batch size when learning from real environment # model initialization D = 4 # input dimensionality ``` ### Policy Network ``` tf.reset_default_graph() observations = tf.placeholder(tf.float32, [None,4] , name="input_x") W1 = tf.get_variable("W1", shape=[4, H], initializer=tf.contrib.layers.xavier_initializer()) layer1 = tf.nn.relu(tf.matmul(observations,W1)) W2 = tf.get_variable("W2", shape=[H, 1], initializer=tf.contrib.layers.xavier_initializer()) score = tf.matmul(layer1,W2) probability = tf.nn.sigmoid(score) tvars = tf.trainable_variables() input_y = tf.placeholder(tf.float32,[None,1], name="input_y") advantages = tf.placeholder(tf.float32,name="reward_signal") adam = tf.train.AdamOptimizer(learning_rate=learning_rate) W1Grad = tf.placeholder(tf.float32,name="batch_grad1") W2Grad = tf.placeholder(tf.float32,name="batch_grad2") batchGrad = [W1Grad,W2Grad] ################################################################################ # TODO: Implement the loss function. # # This sends the weights in the direction of making actions that gave good # # advantage (reward overtime) more likely, and actions that didn't less likely.# ################################################################################ loglik = tf.log(input_y*(input_y - probability) + (1 - input_y)*(input_y + probability)) loss = -tf.reduce_mean(loglik * advantages) ################################################################################ # END OF YOUR CODE # ################################################################################ newGrads = tf.gradients(loss,tvars) updateGrads = adam.apply_gradients(zip(batchGrad,tvars)) ``` ### Model Network Here we implement a multi-layer neural network that predicts the next observation, reward, and done state from a current state and action. ``` mH = 256 # model layer size input_data = tf.placeholder(tf.float32, [None, 5]) with tf.variable_scope('rnnlm'): softmax_w = tf.get_variable("softmax_w", [mH, 50]) softmax_b = tf.get_variable("softmax_b", [50]) previous_state = tf.placeholder(tf.float32, [None,5] , name="previous_state") W1M = tf.get_variable("W1M", shape=[5, mH], initializer=tf.contrib.layers.xavier_initializer()) B1M = tf.Variable(tf.zeros([mH]),name="B1M") layer1M = tf.nn.relu(tf.matmul(previous_state,W1M) + B1M) W2M = tf.get_variable("W2M", shape=[mH, mH], initializer=tf.contrib.layers.xavier_initializer()) B2M = tf.Variable(tf.zeros([mH]),name="B2M") layer2M = tf.nn.relu(tf.matmul(layer1M,W2M) + B2M) wO = tf.get_variable("wO", shape=[mH, 4], initializer=tf.contrib.layers.xavier_initializer()) wR = tf.get_variable("wR", shape=[mH, 1], initializer=tf.contrib.layers.xavier_initializer()) wD = tf.get_variable("wD", shape=[mH, 1], initializer=tf.contrib.layers.xavier_initializer()) bO = tf.Variable(tf.zeros([4]),name="bO") bR = tf.Variable(tf.zeros([1]),name="bR") bD = tf.Variable(tf.ones([1]),name="bD") predicted_observation = tf.matmul(layer2M,wO,name="predicted_observation") + bO predicted_reward = tf.matmul(layer2M,wR,name="predicted_reward") + bR predicted_done = tf.sigmoid(tf.matmul(layer2M,wD,name="predicted_done") + bD) true_observation = tf.placeholder(tf.float32,[None,4],name="true_observation") true_reward = tf.placeholder(tf.float32,[None,1],name="true_reward") true_done = tf.placeholder(tf.float32,[None,1],name="true_done") predicted_state = tf.concat([predicted_observation,predicted_reward,predicted_done],1) observation_loss = tf.square(true_observation - predicted_observation) reward_loss = tf.square(true_reward - predicted_reward) done_loss = tf.multiply(predicted_done, true_done) + tf.multiply(1-predicted_done, 1-true_done) done_loss = -tf.log(done_loss) model_loss = tf.reduce_mean(observation_loss + done_loss + reward_loss) modelAdam = tf.train.AdamOptimizer(learning_rate=learning_rate) updateModel = modelAdam.minimize(model_loss) ``` ### Helper-functions ``` def resetGradBuffer(gradBuffer): for ix,grad in enumerate(gradBuffer): gradBuffer[ix] = grad * 0 return gradBuffer def discount_rewards(r): ################################################################################ # TODO: Implement the discounted rewards function # # Return discounted rewards weighed by gamma. Each reward will be replaced # # with a weight reward that involves itself and all the other rewards occuring # # after it. The later the reward after it happens, the less effect it has on # # the current rewards's discounted reward # # Hint: [r0, r1, r2, ..., r_N] will look someting like: # # [(r0 + r1*gamma^1 + ... r_N*gamma^N), (r1 + r2*gamma^1 + ...), ...] # ################################################################################ rnew = np.copy(r) for i in range(1, len(rnew)): rnew[:len(r)-i] += gamma**i * r[i:] return rnew ################################################################################ # END OF YOUR CODE # ################################################################################ # This function uses our model to produce a new state when given a previous state and action def stepModel(sess, xs, action): toFeed = np.reshape(np.hstack([xs[-1][0],np.array(action)]),[1,5]) myPredict = sess.run([predicted_state],feed_dict={previous_state: toFeed}) reward = myPredict[0][:,4] observation = myPredict[0][:,0:4] observation[:,0] = np.clip(observation[:,0],-2.4,2.4) observation[:,2] = np.clip(observation[:,2],-0.4,0.4) doneP = np.clip(myPredict[0][:,5],0,1) if doneP > 0.1 or len(xs)>= 300: done = True else: done = False return observation, reward, done ``` ## Training the Policy and Model ``` xs,drs,ys,ds = [],[],[],[] running_reward = None reward_sum = 0 episode_number = 1 real_episodes = 1 init = tf.global_variables_initializer() batch_size = real_bs drawFromModel = False # When set to True, will use model for observations trainTheModel = True # Whether to train the model trainThePolicy = False # Whether to train the policy switch_point = 1 # Launch the graph with tf.Session() as sess: rendering = False sess.run(init) observation = env.reset() x = observation gradBuffer = sess.run(tvars) gradBuffer = resetGradBuffer(gradBuffer) while episode_number <= 5000: # Start displaying environment once performance is acceptably high. if (reward_sum/batch_size > 150 and drawFromModel == False) or rendering == True : # env.render() rendering = True x = np.reshape(observation,[1,4]) tfprob = sess.run(probability,feed_dict={observations: x}) action = 1 if np.random.uniform() < tfprob else 0 # record various intermediates (needed later for backprop) xs.append(x) y = 1 if action == 0 else 0 ys.append(y) # step the model or real environment and get new measurements if drawFromModel == False: observation, reward, done, info = env.step(action) else: observation, reward, done = stepModel(sess,xs,action) reward_sum += reward ds.append(done*1) drs.append(reward) # record reward (has to be done after we call step() to get reward for previous action) if done: if drawFromModel == False: real_episodes += 1 episode_number += 1 # stack together all inputs, hidden states, action gradients, and rewards for this episode epx = np.vstack(xs) epy = np.vstack(ys) epr = np.vstack(drs) epd = np.vstack(ds) xs,drs,ys,ds = [],[],[],[] # reset array memory if trainTheModel == True: ################################################################################ # TODO: Run the model network and compute predicted_state # # Output: 'pState' # ################################################################################ feed_dict = { previous_state: np.hstack([epx[:-1], np.array([1-y for y in epy][:-1])]), true_observation: epx[1:], true_reward: epr[1:], true_done: epd[1:] } tState = np.hstack([epx[1:], epr[1:], epd[1:]]) pState, _ = sess.run([predicted_state, updateModel], feed_dict=feed_dict) ################################################################################ # END OF YOUR CODE # ################################################################################ if trainThePolicy == True: ################################################################################ # TODO: Run the policy network and compute newGrads # # Output: 'tGrad' # ################################################################################ # compute the discounted reward backwards through time discounted_epr = discount_rewards(epr) # size the rewards to be unit normal (helps control the gradient estimator variance) discounted_epr -= np.mean(discounted_epr) discounted_epr //= np.std(discounted_epr) tGrad = sess.run(newGrads, feed_dict={observations: epx, input_y: epy, advantages: discounted_epr}) ################################################################################ # END OF YOUR CODE # ################################################################################ # If gradients becom too large, end training process if np.sum(tGrad[0] == tGrad[0]) == 0: break for ix,grad in enumerate(tGrad): gradBuffer[ix] += grad if switch_point + batch_size == episode_number: switch_point = episode_number if trainThePolicy == True: ################################################################################ # TODO: # # (1) Run the policy network and update gradients # # (2) Reset gradBuffer to 0 # ################################################################################ sess.run(updateGrads, feed_dict={W1Grad: gradBuffer[0], W2Grad: gradBuffer[1]}) ################################################################################ # END OF YOUR CODE # ################################################################################ running_reward = reward_sum if running_reward is None else running_reward * 0.99 + reward_sum * 0.01 if drawFromModel == False: print('World Perf: Episode %f. Reward %f. action: %f. mean reward %f.' % (real_episodes,reward_sum/real_bs,action, running_reward/real_bs)) if reward_sum/batch_size >= 200: break reward_sum = 0 # Once the model has been trained on 100 episodes if episode_number > 100: ################################################################################ # TODO: Alternating between training the policy from the model and training # # the model from the real environment. # ################################################################################ drawFromModel = not drawFromModel trainTheModel = not trainTheModel trainThePolicy = not trainThePolicy ################################################################################ # END OF YOUR CODE # ################################################################################ if drawFromModel == True: observation = np.random.uniform(-0.1,0.1,[4]) # Generate reasonable starting point batch_size = model_bs else: observation = env.reset() batch_size = real_bs print(real_episodes) ``` ### Checking model representation Here we can examine how well the model is able to approximate the true environment after training. The green line indicates the real environment, and the blue indicates model predictions. ``` plt.figure(figsize=(8, 12)) for i in range(6): plt.subplot(6, 2, 2*i + 1) plt.plot(pState[:,i]) # draw the model predictions plt.subplot(6,2,2*i+1) ################################################################################ # TODO: draw the real environment for comparison # ################################################################################ plt.plot(tState[:,i]) ################################################################################ # END OF YOUR CODE # ################################################################################ plt.tight_layout() ```
github_jupyter
<a href="https://colab.research.google.com/github/B31521/OOP-1-2/blob/main/OOP_Concepts_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Classes with multiple objects ``` class Birds: def __init__(self,bird_name): self.bird_name=bird_name def flying_birds(self): print(f"{self.bird_name} flies above the sky") def non_flying_birds(self): print(f"{self.bird_name} is the national bird of the Philippines") vulture=Birds("Griffon Vulture") crane=Birds("Common Crane") emu=Birds("Emu") vulture.flying_birds() crane.flying_birds() emu.non_flying_birds() ``` Encapsulation ``` class foo: def __init__(self,a,b): self.__a=a self.__b=b def add(self): return self.__a + self.__b #Private Attributes number=foo(3,4) number.add() number.a=7 #7, 4 7+4=11 number.add() ``` Encapsulation with Private Attributes ``` class Counter: def __init__(self): self.__current=0 def increment(self): self.__current +=1 def value(self): return self.__current def reset(self): self.__current=0 num=Counter() num.increment() #counter=counter+1 num.increment() num.increment() num.counter=1 num.value() ``` Inheritance ``` class Person: def __init__(self,firstname,surname): self.firstname=firstname self.surname=surname def printname(self): print(self.firstname,self.surname) person=Person("Ana","Santos") person.printname() class Teacher(Person): pass person2=Teacher("Maria","Sayo") person2.printname() class Student(Teacher): pass person3=Student("Billy","Pulido") person3.printname() ``` Polymorphism ``` class RegularPolygon: def __init__(self,side): self.side=side class Square(RegularPolygon): def area(self): return self.side*self.side class EquilateralTriangle(Square): def area(self): return self.side*self.side*0.433 object=Square(4) print(object.area()) object2=EquilateralTriangle(3) print(object2.area()) ``` Application 1 1. Create a Python program that displays the name of three students (Students 1,Student 2, and Student 3) and their term grades. 2. Create a class name Person and attributes - std1, std2, std3, pre, mid, fin 3. Compute the average of each term grade using Grade() method. 4. Information about student's grades must be hidden from others ``` class data: def __init__(self,name,prelim,midterm,final): self.name = name self.prelim = prelim self.midterm = midterm self.final = final def printname(self): print(self.name) class std1(data): def average(self): return ((self.prelim + self.midterm + self.final)/3) name_input1 = str(input("Name: ")) prelims_input1 = float(input("Prelims:")) midterms_input1 = float(input("Midterm:")) finals_input1 = float(input("Finals:")) student1 = std1(name_input1, prelims_input1, midterms_input1, finals_input1) print("\n") student1.printname() print("Average:" , round(student1.average(),2), "\n") class std2(data): def average(self): return ((self.prelim + self.midterm + self.final)/3) name_input2 = str(input("Name: ")) prelims_input2 = float(input("Prelims:")) midterms_input2 = float(input("Midterm:")) finals_input2 = float(input("Finals:")) student2 = std2(name_input2, prelims_input2, midterms_input2, finals_input2) print("\n") student2.printname() print("Average:" , round(student2.average(),2), "\n") class std3(data): def average(self): return ((self.prelim + self.midterm + self.final)/3) name_input3 = str(input("Name: ")) prelims_input3 = float(input("Prelims:")) midterms_input3 = float(input("Midterm:")) finals_input3 = float(input("Finals:")) student3 = std3(name_input3, prelims_input3, midterms_input3, finals_input3) print("\n") student3.printname() print("Average:" , round(student3.average(),2), "\n") ```
github_jupyter
<a href="https://colab.research.google.com/github/forest1988/colaboratory/blob/main/prophetnet_seq2seqtrainer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import torch torch.__version__ !git clone https://github.com/huggingface/transformers.git #git clone https://github.com/forest1988/transformers.git %cd transformers/ !pip install -e . %cd /content/transformers/examples/seq2seq/ # to avoid the "ModuleNotFoundError" import sys print(sys.path) sys.path.append('/content/transformers/src') print(sys.path) # If "ModuleNotFoundError" occurs in this cell, please re-run the runtime. # (The first time Colab runtime runs, it seems the sys.path is not correctly updated when we use `pip install -e .`) import transformers transformers.__version__ ``` ## dataset ``` !wget https://cdn-datasets.huggingface.co/summarization/xsum.tar.gz !tar -xzvf xsum.tar.gz # !export XSUM_DIR=${PWD}/xsum # %env XSUM_DIR=${PWD}/xsum import os os.environ['XSUM_DIR']=os.path.join(os.getcwd(), 'xsum') !echo $XSUM_DIR !ls $XSUM_DIR ``` ### Run BART-base ``` %%capture !pip install gitpython !pip install rouge_score !pip install sacrebleu !python finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --predict_with_generate \ --n_train 20 \ --n_val 10 \ --model_name_or_path facebook/bart-base \ --data_dir $XSUM_DIR \ --output_dir bart-base-tmp \ --overwrite_output_dir !nvidia-smi ``` ## Run with ProphetNet (Error occurs) ``` from transformers import ProphetNetTokenizer, ProphetNetForConditionalGeneration #, ProphetNetForCausalLM # --- commeented out to avoid CUDA memory error --- # tokenizer = ProphetNetTokenizer.from_pretrained('microsoft/prophetnet-large-uncased') # model = ProphetNetForConditionalGeneration.from_pretrained('microsoft/prophetnet-large-uncased') # input_ids = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt").input_ids # Batch size 1 # decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1 # outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids, return_dict=True) # logits_next_token = outputs.logits # logits to predict next token as usual # logits_ngram_next_tokens = outputs.logits_ngram # logits to predict 2nd, 3rd, ... next tokens # test how tokeinzer.decoder works # print(tokenizer.decode(input_ids[0])) # print(tokenizer.decode(input_ids[0], skip_special_tokens=True)) # show the style of the output # print(type(outputs)) # outputs.keys() # outputs.logits.shape, outputs.logits_ngram.shape # out_generate = model.generate(input_ids, num_beams=4, max_length=20, early_stopping=True) # out_generate.shape, out_generate[0] # tokenizer.decode(out_generate.shape[0], skip_special_tokens=True) # --- NotImplementedError occurs here --- !python finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --predict_with_generate \ --n_train 100 \ --n_val 10 \ --model_name_or_path microsoft/prophetnet-large-uncased \ --data_dir $XSUM_DIR \ --output_dir tmp \ --overwrite_output_dir ``` ### Refer to T5Tokenizer ``` python @add_start_docstrings(PREPARE_SEQ2SEQ_BATCH_DOCSTRING) def prepare_seq2seq_batch( self, src_texts: List[str], tgt_texts: Optional[List[str]] = None, max_length: Optional[int] = None, max_target_length: Optional[int] = None, padding: str = "longest", return_tensors: str = None, truncation: bool = True, **kwargs, ) -> BatchEncoding: if max_length is None: max_length = self.max_len model_inputs = self( src_texts, add_special_tokens=True, return_tensors=return_tensors, max_length=max_length, padding=padding, truncation=truncation, **kwargs, ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: max_target_length = max_length labels_and_decoder_mask = self( tgt_texts, add_special_tokens=True, return_tensors=return_tensors, padding=padding, max_length=max_target_length, truncation=truncation, **kwargs, ) model_inputs["labels"] = labels_and_decoder_mask["input_ids"] return model_inputs ``` ## Try modified version of ProphetNet Tokenizer ``` %cd /content/ !ls import shutil if os.path.exists("transformers_modified"): print("The repository is already cloned. Remove and re-clone it.") shutil.rmtree("transformers_modified") !git clone -b forest1988-prophetnet-prepare-seq2seq-batch https://github.com/forest1988/transformers.git transformers_modified %cd transformers_modified/ !pip install -e . --upgrade %cd /content/transformers_modified/examples/seq2seq/ # Use already downloaded XSUM in /content/transformers/examples/seq2seq/xsum/ ``` ### Run on GPU ``` # For GPU (if runtime is set to TPU, the code below is run on CPU.) # max_source_lenght 510 !python finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --max_source_length 510 \ --per_device_train_batch_size 2 \ --predict_with_generate \ --n_train 300 \ --n_val 100 \ --model_name_or_path microsoft/prophetnet-large-uncased \ --data_dir $XSUM_DIR \ --output_dir tmp_gpu \ --overwrite_output_dir # For GPU (if runtime is set to TPU, the code below is run on CPU.) # max_source_lenght 511 !python finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --max_source_length 511 \ --per_device_train_batch_size 2 \ --predict_with_generate \ --n_train 300 \ --n_val 100 \ --model_name_or_path microsoft/prophetnet-large-uncased \ --data_dir $XSUM_DIR \ --output_dir tmp_gpu \ --overwrite_output_dir # For GPU (if runtime is set to TPU, the code below is run on CPU.) # max_source_lenght 512 !python finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --max_source_length 512 \ --per_device_train_batch_size 2 \ --predict_with_generate \ --n_train 300 \ --n_val 100 \ --model_name_or_path microsoft/prophetnet-large-uncased \ --data_dir $XSUM_DIR \ --output_dir tmp_gpu \ --overwrite_output_dir ``` ### Run on TPU ``` # install torch_xla with PyTorch !pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.7-cp36-cp36m-linux_x86_64.whl # For TPU !python xla_spawn.py --num_core 1 \ finetune_trainer.py \ --learning_rate=3e-5 \ --do_train --do_eval --evaluate_during_training \ --max_source_length 200 \ --per_device_train_batch_size 32 \ --prediction_loss_only \ --model_name_or_path microsoft/prophetnet-large-uncased \ --data_dir $XSUM_DIR \ --output_dir tmp_tpu \ --overwrite_output_dir %ls tmp_tpu !ls !cat tmp_tpu/eval_results.json !cat tmp_tpu/config.json ```
github_jupyter
# Bài 8: Keras, Regression Trong bài thực hành này, chúng ta sẽ - Làm quen với Tensorflow thông qua các bài toán Regression ## 1. Dự đoán giá nhà (Lab 01) ``` import pandas as pd import numpy as np df = pd.read_csv("House_Price.csv") df.head() df.describe().transpose() from sklearn.model_selection import train_test_split df_train, df_test = train_test_split(df, test_size=0.1) ## dùng width và length để đoán price X_train = df_train[['width', 'length']].values X_test = df_test[['width', 'length']].values X_means = np.mean(X_train, axis=0) X_stds = np.std(X_train, axis=0) X_train = (X_train - X_means)/X_stds X_test = (X_test - X_means)/X_stds y_train = df_train['price'].values y_test = df_test['price'].values y_means = np.mean(y_train, axis=0) y_stds = np.std(y_train, axis=0) X_train.shape, y_train.shape X_test.shape, y_test.shape import tensorflow as tf from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model inputs = Input(shape=(2,)) ## tạo một layer Input, mỗi sample có input là 1 vector độ dài 2 dense_1 = Dense(units=10, activation='relu')(inputs) ## tạo một layer gồm 10 units, hàm kích hoạt relu outputs = Dense(units=1, activation=None)(dense_1) ## tạo layer output gồm 1 units, tượng trưng cho giá nhà, vì giá nhà thực nên không để hàm kích hoạt model = Model(inputs=inputs, outputs=outputs) ## tạo model với input và output layer đã xây dựng model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1000.0), loss='mean_squared_error') ## khai báo optimizer và loss cho model model.summary() model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=80) from sklearn.metrics import mean_absolute_error, mean_squared_error, explained_variance_score, r2_score, accuracy_score y_train_pred = model.predict(X_train) rmse = np.sqrt(mean_squared_error(y_train,y_train_pred)) r2 = r2_score(y_train,y_train_pred) print('RMSE: ', rmse) print('R2: ', r2) y_pred = model.predict(X_test) mae = mean_absolute_error(y_test, y_pred) mse = mean_squared_error(y_test, y_pred) rmse = (np.sqrt(mse)) mv = explained_variance_score(y_test, y_pred) r2 = r2_score(y_test, y_pred) print("Model testing performance:") print("--------------------------") print("Mean Absolute Error is", round(mae,1)) print('RMSE is {}'.format(rmse)) print('R2 score is {}'.format(r2)) print("Variance explained by model", round(mv*100,5), "%") ``` ## 2. Bài tập: COVID-19 Retweet Prediction Link: https://www.cikm2020.org/covid-19-retweet-prediction-challenge/ Dự đoán số lượng retweet của một tweet dựa vào các metadata như số #friends, #followers, ... của người đăng, thời gian, hashtags của tweet. Download: https://drive.google.com/drive/folders/1eZwesVW9RcW_0ZJt0ztGyhTlISx3USn5?usp=sharing ``` df_train = pd.read_csv("df_train.csv") df_train.head() df_train.isnull().sum() df_test = pd.read_csv("df_test.csv") df_test.head() df_test.isnull().sum() df_train = df_train.dropna() df_train.info() df_test = df_test.dropna() df_test.info() df_train['timestamp'] = pd.to_datetime(df_train['timestamp']) df_train.head() ``` ## Bài tập Sử dụng một vài hoặt tất cả các cột trong số các cột timestamp, #followers, #friends, #favorites, hashtags, sentiment_1, sentiment_2 để dự đoán cột #retweet: - Dùng model machine learning bất kì (nên dùng neural network) - Đạt Mean Squared Logarithmic Error (https://www.tensorflow.org/api_docs/python/tf/keras/losses/MeanSquaredLogarithmicError) trên tập test ít nhất là 0.25 mới được đầy đủ điểm ## Nộp bài - Code và chạy kết quả lưu vào file notebook NMMH_TH8_MSSV.ipynb (notebook phải có kết quả chạy nếu ko xem như chưa làm) - Nén thành file NMMH_TH8_MSSV.rar (.zip) và nộp về: dinhvietcuong1996@gmail.com - Deadline: 23g59 thứ 3 ngày 28/07/2020. Nộp trễ bị chia đôi số điểm.
github_jupyter
# Classification of quantum states with high dimensional entanglement ## Circuits and computations Version compatible with 1st and 2d pilot studies ``` import numpy as np import copy from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute, transpile, assemble from qiskit.tools.visualization import * from qiskit.ignis.mitigation.measurement import (complete_meas_cal, tensored_meas_cal, CompleteMeasFitter, TensoredMeasFitter) import json from scipy.signal import savgol_filter import time from qiskit.tools.monitor import job_monitor from o_utils import ora # classifier utilities from o_plot import opl # utilities for result plot from c_utils import new_cut # circuit building utilities def json_dic_loader(dic_name): f = open(data_directory+dic_name+'.json') return json.load(f) ``` #markdown for safety on demo def json_dic_dumper(dic, dic_name): with open(data_directory+dic_name+'.json', 'w') as f: json.dump(dic,f) ``` # common code for calling the classifier for ideal device and for real devices def add_single_dic(target_data_list): start_time = time.time() print("started",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name) # added for D,S,M choice. Mainstream : mixed set of 20 states first = 0 last = nb_states if unique_char == "D": last = int(nb_states/2) elif unique_char == "S": first = int(nb_states/2) # get the classifier error curve in function of the number of shot and the "safe shot number" error_curve, safe_rate, ernb = ora.provide_error_curve(PD_model=model_dic[model_name][first:last,:], PD_test=PD_test[first:last,:], trials=trials, window=window, epsilon=epsilon, max_shots=max_shots, pol=pol, verbosality=verbosality) tail = savgol_filter(ernb, window, pol, axis=0) len_curve = len(error_curve) safe_shot_nb = len_curve - int((window-1)/2) # OK print('safe_shot_nb',safe_shot_nb, 'safe_rate',safe_rate, "nb trials:",trials) err_rates = tail[int((window-1)/2),:]/trials err_rate_max = np.max(err_rates) err_rate_min = np.min(err_rates) r=4 print("savgol interpolated error rate mean:", np.round(np.mean(err_rates),r), "min:", np.round(err_rate_min,r), "max:", np.round(err_rate_max,r), "for", [ien for ien, jen in enumerate(err_rates) if jen == err_rate_max]) end_time = time.time() #save the data in a list of dictionaries : single_dic={"project":mitig_name, "id_gates":id_gates, "mitigation":mit_str, "model":model_name, "metric":o_metric, "device":project_device, "curve_length":len_curve, "shots": safe_shot_nb, "shots_rate": safe_rate, "error_curve":error_curve, "trials":trials,"window":window, "epsilon":epsilon,"SG_pol": pol, "computation_time":end_time-start_time, "time_completed":time.strftime('%d/%m/%Y %H:%M:%S'), "trials":trials, "QV": QV_dic[project_device], "fidelity": fidelity_dic[project_device], "error_nb":ernb} target_data_list.append(single_dic) print("completed",time.strftime('%d/%m/%Y %H:%M:%S'),mitig_name, "mitigation",mit_str,o_metric,model_name,"\n") ``` ## Set up the simulator and layout for 5 qubits ``` simulator = Aer.get_backend('qasm_simulator') #specify the layout of the devices used_qubits = 5 qubit_list = [0,1,2,3,4] #short_version = False #program_name="QAD" # 1st pilot project GHZ Psi+ / W Phi+ program_name="AL2" # 2d pilot project W Psi+ / Wbar Phi+ Flag_char = "DS" # this for a mix of two types of separable states if len(Flag_char) >= 2: unique_char = "M" else: unique_char = Flag_char # These dictionaries for the devices used in the study if program_name == "QAD": fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380, "ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0} data_directory = "data_files/" elif program_name == "AL2": fidelity_dic = {'ibmq_athens': 0.910145, 'ibmq_valencia': 0.794262, 'ibmq_ourense': 0.818974, "ibmqx2": 0.359528, 'ibmq_santiago': 0.900024, 'ibmq_vigo': 0.841831, 'ideal_device': 1.0} data_directory = "data2_files/" QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0, "ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf} dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our", "ibmqx2": 'Yor', 'ideal_device': "Ide"} # specify the device: here first the ideal noise-free device project_device = 'ideal_device' device_name = dev_dic[project_device] # specify the nb of id gates between state creation and measurements # zero for the ideal device id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) # tail of the file names for RAM storage mitig_name = program_name + "_" + device_name project_name = mitig_name + "_" + unique_char + zfilled print(mitig_name) print(project_name) # establish the result label list # meas_calibs will be used for mitigation in the real device section qr = QuantumRegister(used_qubits) meas_calibs, label_list = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal') nb_labels=len(label_list) print(nb_labels,label_list) len(meas_calibs) # permutation list # here it is simple to write down the list, # but a version using itertools will be wellcome for >5 qubits projects if used_qubits == 5: q_perm = [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 1, 4, 2, 3], [0, 2, 3, 1, 4], [0, 2, 4, 1, 3], [0, 3, 4, 1, 2], [1, 2, 3, 0, 4], [1, 2, 4, 0, 3], [1, 3, 4, 0, 2], [2, 3, 4, 0, 1]] else: print("work in progress - meanwhile please provide the list of permutations") ``` ## Create the quantum states ``` # define the two subsets of 10 separable states if program_name == "QAD": state_1a = ["W","Phi+"] state_1b = ["GHZ","Psi+"] elif program_name == "ALT" or "AL2": state_1a = ["W","Psi+"] state_1b = ["Wbar","Phi+"] l_states = state_1a+state_1b l_states # version 20 circuits for demonstration # (in the version run on real devices: two batches of 10 circuits, "shallow" and "deep") # these circuits limited to state creation are ready to be saved # for ultimately building circuits adapted to noisy simulator and real devices # as option, these circuits will include a row of id gates between creation and measurements circ_ori = [] for i_s in range(0,len(l_states),2): for perm in q_perm: mycircuit = QuantumCircuit(used_qubits, used_qubits) mycircuit = new_cut.circuit_builder(mycircuit, perm, l_states[i_s],l_states[i_s+1]) circ_ori.append(mycircuit) # add measurement section to the circuit set newly created: nb_states = len(circ_ori) circ_ideal = copy.deepcopy(circ_ori) for i_state in range(nb_states): new_cut.add_barrier_and_measure(circ_ideal[i_state],qubit_list) ideal_dic = {} ``` ## Obtain result distributions on noise free simulator #### You may skip this section and go to: #### "Obtain the matrix of probability distribution of shape(nb_state,nb_labels) used by the classifier" ``` # execute on noise free simulator s_sim = 12000 job_simul = execute(circ_ideal, backend=simulator, shots=s_sim) tot_results_simul = job_simul.result() # establish a dictionary of count results on noise free simulator: # (this step is only useful if ram storage is performed) void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) tot_results_sim_dic = {} for i_state in range(nb_states): counts_simul = copy.deepcopy(void_counts) counts_simul.update(tot_results_simul.get_counts(i_state)) ideal_dic[str(i_state)]=counts_simul ``` #markdown for security json_dic_dumper(ideal_dic,"ideal_dic_"+project_name) Example of circuit for separable state of the first type ($W\otimes\Phi^+\; or\; W\otimes\Psi^+$): ``` i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) ``` Example of circuit for separable state of the second type ($GHZ\otimes\Psi^+ \; or\; \bar{W}\otimes\Phi^+$): ``` i_state_test = 10 print(device_name, "circuit #",i_state_test) circ_ideal[i_state_test].draw(output='mpl') print(device_name, "circuit #",i_state_test) plot_histogram(ideal_dic[str(i_state_test)], legend=['noise free simulation'], color = "b", figsize=(10.,5.)) ``` ### Obtain the matrix of probability distribution of shape(nb_state,nb_labels) used by the classifier ``` # try loading the dictionary of results if its creation was skipped if len(ideal_dic) == 0: ideal_dic = json_dic_loader("ideal_dic_"+project_name) nb_states = len(ideal_dic) nb_labels = len(list(ideal_dic.values())[0]) s_sim = sum(list(ideal_dic.values())[0].values()) PD_ideal = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): PD_ideal[i_state, :] = list(ideal_dic[str(i_state)].values()) # now a little trick to get the ideal values from the simulator approximated values with np.errstate(divide='ignore'): # ignore the divide by zero warning PD_ideal = 1/np.round(s_sim/(PD_ideal)) # have a look at the matrix head and tail: print("first and last state probability distributions:") print(np.round(np.vstack((PD_ideal[0:1,:],PD_ideal[-1:,:])),4)) ``` ## Monte Carlo simulation for the ideal device ``` # here will be appended the data we want for the curve plot ideal_data_list=[] ``` ### you may skip this cell and get stored curves by running the next cell ``` # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary (readme file): trials=100 # to be set to 10000 if not demo window=5 # shorter window than for the real device counts epsilon = .001 min_shots = 5 max_shots = 100 pol=2 subset = None # variable not used here verbosality = 5 # printing step for intermediate results when increasing the experiment shot number PD_test = PD_ideal mitigation_dic = {"Na": None} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] model_dic = {"ideal_sim": PD_ideal} for mit_str, mitigation in mitigation_dic.items(): if mitigation != None: # thus only for counts on real device PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: for model_name in model_dic.keys(): add_single_dic(ideal_data_list) ``` markdown for safety json_dic_dumper(ideal_data_list,"ideal_device_data_list_"+project_name) ``` # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(ideal_data_list) == 0: ideal_data_list = json_dic_loader("ideal_device_data_list_"+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors the unsmoothed values opl.plot_curves(ideal_data_list,np.array([0,1]), "Jensen-Shannon vs squared euclidean distance - $\epsilon=0.001$" , ["model"], ["device","metric"], right_xlimit = 20, bottom_ylimit = -0.001, top_ylimit = 0.05) ``` # Real device section ``` from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() project_device = 'ibmq_valencia'# you may choice here a different backend device_name = dev_dic[project_device] mitig_name = program_name + "_" + device_name print(mitig_name) #determine here the backend device = provider.get_backend(project_device) # the backend names are listed here above properties = device.properties() coupling_map = device.configuration().coupling_map ``` # obtain mitigation filter #markdown for demo nb_shots_cal = 8192 # set here the number of shots for the calibration phase print("backend:", device.name(), "qubit_list:", qubit_list) job_cal = execute(meas_calibs, backend=device, shots=nb_shots_cal) print(job_cal.job_id()) job_monitor(job_cal) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print("DMY: ",time_exp) #markdown for demo #here we save mitigation results cal_results = job_cal.result() cal_results_dic = cal_results.to_dict() #to make date in dictionary serializable if there is a 'date' key: if 'date' in cal_results_dic.keys(): cal_results_dic['date']=str(cal_results_dic['date']) #markdown for demo and security #dump json_dic_dumper(cal_results_dic,"cal_results_dic_"+ mitig_name) ``` # retrieve the corresponding measurement mitigation filter obtained at experimental time # use a fake job because use of the from_dict method simulator = Aer.get_backend('qasm_simulator') fake_job_cal = execute(meas_calibs, backend=simulator, shots=1) fake_cal_results = fake_job_cal.result() cal_results_dic = json_dic_loader("cal_results_dic_"+mitig_name) if 'date' in cal_results_dic.keys(): str(cal_results_dic['date']) cal_results = fake_cal_results.from_dict(cal_results_dic) meas_fitter = CompleteMeasFitter(cal_results, label_list, qubit_list=qubit_list, circlabel='mcal') meas_filter = meas_fitter.filter # have a look at the average measurement fidefily of this device: print("Average Measurement Fidelity was: %f" % meas_fitter.readout_fidelity(), "for",project_device) ``` ### Transpile the basic circuits for running on real device In this demo, these are not the circuits which were actually run on real devices (not the same transpiler seed). The optimization level is set to 2 instead of 3 in real experiments, for speed and also because at this moment there is a transpiler error occuring for ibmqx2: 'Maximum iteration reached. max_iteration=1000' ``` id_gates = 0 str_nb_id = str(id_gates) zfilled = str_nb_id.zfill(4-len(str_nb_id)) project_name = mitig_name + "_" + unique_char + zfilled print(project_name) # transpile verbose = True summary_dic = {} seed_transpiler_list = list(range(nb_states)) real_circs = [] start_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Start at DMY: ",start_time) for i_state in list(range(nb_states)): # prepare circuit to be transpiled circuit = copy.deepcopy(circ_ori[i_state]) if id_gates > 0: circuit.barrier() for id_gates_index in range(id_gates): for index, value in enumerate(qubit_list): circuit.id(value) new_cut.add_barrier_and_measure(circuit, qubit_list) summary = [] depth_list = [] Q_state_opt_new = transpile(circuit, backend=device, coupling_map = coupling_map, seed_transpiler=seed_transpiler_list[i_state], optimization_level=2, initial_layout=qubit_list) summary_dic[i_state] = {"depth": Q_state_opt_new.depth(), 'circuit':Q_state_opt_new} real_circs.append(Q_state_opt_new) if verbose: print("circuit %2i" % i_state,"length",summary_dic[i_state]["depth"], "DMY: ",time.strftime('%d/%m/%Y %H:%M:%S')) end_time = time.strftime('%d/%m/%Y %H:%M:%S') print("Completed at DMY: ",end_time) i_state_test = 10 print(project_device, "circuit #",i_state_test, "circuit length:",real_circs[i_state_test].depth()) #summary_dic[i_state_test]['depth']) # you may want to skip this if large nb of id gates before measurement real_circs[i_state_test].draw(output='mpl') #check a circuit on noise-free simulator job_simul = execute(real_circs[i_state_test], backend=simulator, shots=s_sim) print(project_device, "circuit #",i_state_test, "on noise free simulator") plot_histogram(job_simul.result().get_counts(), legend=['noise free simulation'], color = "b", figsize=(10.,5.)) ``` # run job #markdown for demo #run the circuits nb_shots = 8192 print("backend:", device.name(), "qubit_list:", qubit_list) time_exp = time.strftime('%d_%m_%Y_%H_%M_%S') print("DMY: ",time_exp) job_real = execute(real_circs, backend=device, optimization_level=0, shots=nb_shots) job_real_id = job_real.job_id() print("job id:", job_real_id) job_monitor(job_real) time_exp = time.strftime('%d_%m_%Y_%H_%M_%S') print("DMY: ",time_exp, "job id:", job_real_id) tot_results_real = job_real.result() empirical_dic ={} for i_state_count, state_count in enumerate(tot_results_real.get_counts()): empirical_dic[str(i_state_count)] = state_count #markdown for safety json_dic_dumper(job_real_id,"job_real_id_"+ project_name) #markdown for safety at demo json_dic_dumper(empirical_dic,"experimental_"+ project_name) #markdown for demo #2d JOB RUN nb_shots = 8192 #run the circuits print("backend:", device.name(), "qubit_list:", qubit_list) time_exp = time.strftime('%d_%m_%Y_%H_%M_%S') print("DMY: ",time_exp) job_test = execute(real_circs, backend=device, optimization_level=0, shots=nb_shots) job_test_id = job_test.job_id() print("job id:", job_test_id) job_monitor(job_test) time_exp = time.strftime('%d_%m_%Y_%H_%M_%S') print("DMY: ",time_exp, "job id:", job_test_id) tot_results_test = job_test.result() test_dic ={} for i_state_count, state_count in enumerate(tot_results_test.get_counts()): test_dic[str(i_state_count)] = state_count #markdown for safety at demo json_dic_dumper(job_test_id,"job_test_id_"+ project_name) json_dic_dumper(test_dic,"test_"+ project_name) ### Load the transpiled circuits that were actually run ##### legacy: valid only for the GHZ Psi+ / W Phi- combination otherwise go instead to: #### "Obtain the matrix of probability distribution of shape(nb_state,nb_labels) used by the classifier" ``` #changing keys of dictionary for merging: def key_change(ini_dict, i_subset): ini_list = [] len_ini = len(ini_dict) for i in range(len_ini): ini_list.append(str(i+i_subset*len_ini)) return dict(zip(ini_list, list(ini_dict.values()))) if program_name == "QAD": #retrieve the data corresponding to the 1st project lfc = list(Flag_char) circ_ideal =[] empirical_dic = {} for i_subset, subset in enumerate(lfc): qasm_circs_dic = json_dic_loader('qasm_circs_dic_QAD_'+device_name+'_'+ subset + zfilled) j=0 # j included for project with several transpilation sessions for each device - not used here qasm_circs = qasm_circs_dic[str(j)] nb_circs = len(qasm_circs) for i_circs in range(nb_circs): circ_ideal.append(QuantumCircuit().from_qasm_str(qasm_circs[i_circs])) empirical_dic = {**empirical_dic, **key_change(json_dic_loader("experimental"+"_"+mitig_name +"_"\ +subset+zfilled), i_subset)} test_dic = copy.deepcopy(empirical_dic) #nb_states = len(circ_ideal) ``` ### Obtain the matrix of probability distribution of shape(nb_state,nb_labels) used by the classifier ``` if program_name == "AL2": empirical_dic = json_dic_loader('experimental_'+project_name) test_dic = json_dic_loader('test_'+project_name) def rectify_counts(tot_res, test_cqi,mitigation,m_filter) : void_counts = dict(zip(label_list, np.zeros(2**used_qubits))) try: counts_results_real_test = tot_res[str(test_cqi)] except KeyError as error: counts_results_real_test = tot_res[test_cqi] raw_counts_test = copy.deepcopy(void_counts) raw_counts_test.update(counts_results_real_test) if mitigation: mitigated_results_test = meas_filter.apply(raw_counts_test, method = 'least_squares') returned_counts = copy.deepcopy(void_counts) returned_counts.update(mitigated_results_test) else: returned_counts = copy.deepcopy(raw_counts_test) return returned_counts ``` ### Obtain the matrix of probability distribution of shape(nb_state,nb_labels) used by the classifier ``` def get_clean_matrix(dic, mitigation,m_filter): clean_matrix = np.ndarray((nb_states,nb_labels)) for i_state in range(nb_states): rectified_counts = rectify_counts(dic,i_state, mitigation,m_filter) # get a rectified counts dictionary clean_matrix[i_state, :] = list(rectified_counts.values()) clean_matrix = clean_matrix/clean_matrix.sum(axis=1, keepdims=True) return clean_matrix # We need to create a first matrix version. It will then vary for each considered set of distribution mitigation = False PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_exper[0:1,:],PD_exper[-1:,:])),3)) if program_name == "QAD": PD_test = copy.deepcopy(PD_exper) elif program_name == "AL2": mitigation = False PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) print("first and last state probability distributions:") print(np.round(np.vstack((PD_test[0:1,:],PD_test[-1:,:])),3)) ``` ## Monte Carlo simulation for the real device ``` # here will be appended the data we want for the final plot of this notebook empirical_data_list=[] ``` ### you may want to skip this cell and get stored curves by running the next cell ``` # you may want to skip this cell as it will require a long time # because of the high number of trials required by the Monte Carlo simulation for each nb o shots value # the following values are defined in the study summary notebook: trials=100 # should be 1000 if not demo window=11 epsilon = .001 max_shots = 500 pol=2 verbosality = 10 # printing step for intermediate results when increasing the experiment shot number # In this section you can easily make your choice of combinations: # mitigation or not, metric, model mitigation_dic = {"no":False, "yes" : True} #mitigation_dic = {"no":False} #mitigation_dic = {"yes" : True} o_metrics_desired = ['jensenshannon', 'sqeuclidean'] #o_metrics_desired = ['jensenshannon'] #o_metrics_desired = ['sqeuclidean'] model_dic = {"empirical": PD_exper, "ideal_sim": PD_ideal} #model_dic = {"empirical": PD_exper} #model_dic = {"ideal_sim": PD_ideal} # Obtain a sequence of results in form of a list of dictionaries for mit_str, mitigation in mitigation_dic.items(): # here we toggle PD_exper as we toggled mitigation status PD_exper = get_clean_matrix(empirical_dic, mitigation=mitigation, m_filter=meas_filter) PD_test = get_clean_matrix(test_dic, mitigation=mitigation, m_filter=meas_filter) for o_metric in o_metrics_desired: print(project_name, model_dic.keys(), o_metric) for model_name in model_dic.keys(): add_single_dic(empirical_data_list) ``` markdown fo security json_dic_dumper(empirical_data_list,'Tnemp_data_list_'+project_name) ``` # get the stored results of the Monte Carlo simulation in case you skipped the previous step if len(empirical_data_list) == 0: empirical_data_list = json_dic_loader('Nemp_data_list_'+project_name) # have a look at the mean error rate curves and error rate at save shot number n_s # NB the r_hat_mean curves and legend reported r_hat_max errors are the unsmoothed values opl.plot_curves(ideal_data_list + empirical_data_list, np.array(range(2+len(empirical_data_list))), "$\epsilon=0.001$" , ["device"], ["model","metric","mitigation","id_gates"], right_xlimit = 80, bottom_ylimit = -0.02, top_ylimit = 1) import winsound duration = 2000 # milliseconds freq = 800 # Hz winsound.Beep(freq, duration) import qiskit.tools.jupyter %qiskit_version_table ```
github_jupyter