text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
## Configuration _Initial steps to get the notebook ready to play nice with our repository. Do not delete this section._ Code formatting with [black](https://pypi.org/project/nb-black/). ``` %load_ext lab_black import os import pytz import glob import pathlib this_dir = pathlib.Path(os.path.abspath("")) data_dir = this_dir / "data" import requests import pandas as pd import regex as re import urllib, json from datetime import datetime from bs4 import BeautifulSoup ``` ## Download Retrieve the page ``` url = "https://gis2.stancounty.com/arcgis/rest/services/COVID19_Cases_City_Zip_Layer/FeatureServer/0/query" params = dict(f="json", where="0=0", outFields="*") session = requests.Session() r = session.get(url, headers={"User-Agent": "Mozilla/5.0"}, params=params) data = r.json() ``` ## Parse ``` cities = data["features"] dict_list = [] for item in cities: d = dict(item["attributes"]) dict_list.append(d) df = pd.DataFrame(dict_list) ``` Rename fields to standardized column headers ``` df = df.rename(columns={"city_district": "area", "confirmed": "confirmed_cases"}) ``` Eliminate unneeded rows ``` df = df.filter(["area", "confirmed_cases"], axis=1).sort_values( by="area", ascending=True ) ``` Drop where confirmed cases is NaN ``` df = df.dropna(subset=["confirmed_cases"]) ``` Convert `confirmed_cases` column to int from float ``` df = df.astype({"confirmed_cases": int}) ``` Sum districts 1-5 into unincorporated / districts ``` total = df[ df["area"].isin( ["District 1", "District 2", "District 3", "District 4", "District 5"] ) ] ``` Append districts sum row to the dataframe ``` new_row = { "area": "Unincorporated districts", "confirmed_cases": total["confirmed_cases"].sum(), } df = df.append(new_row, ignore_index=True) ``` Delete District rows ``` df.drop( df[ df["area"].isin( ["District 1", "District 2", "District 3", "District 4", "District 5"] ) ].index, inplace=True, ) df = df.reset_index(drop=True) ``` ### Adding county column ``` df.insert(0, "county", "Stanislaus") ``` Get county timestamp (using separate feed to extract unix timestamp) ``` url_date = "https://gis2.stancounty.com/arcgis/rest/services/COVID19_Cases_City_Zip_Layer/FeatureServer/0/metadata" r_date = requests.get(url_date) data_date_bad = BeautifulSoup(r_date.text).find("creadate").text data_date = datetime.strptime(data_date_bad, "%Y%m%d").strftime("%Y-%m-%d") # dropping last three digits of unix timestamp, converting to python date feed_date_obj = data_date ``` If separate feed or modified date unavailable, use now for date ``` field_date = data_date if data_date else now df["county_date"] = pd.to_datetime(field_date).date() ``` ## Vet ``` default_stan_len = 10 try: assert not len(df) < default_stan_len except AssertionError: raise AssertionError( "Stanislaus County scraper: latest spreadsheet entry is missing row(s)" ) try: assert not len(df) > default_stan_len except AssertionError: raise AssertionError( "Stanislaus County scraper: latest spreadsheet entry has more area(s) than previously reported" ) ``` ## Export Set date ``` tz = pytz.timezone("America/Los_Angeles") today = datetime.now(tz).date() slug = "stanislaus" df.to_csv(data_dir / slug / f"{today}.csv", index=False) ``` ## Combine ``` csv_list = [ i for i in glob.glob(str(data_dir / slug / "*.csv")) if not str(i).endswith("timeseries.csv") ] df_list = [] for csv in csv_list: if "manual" in csv: df = pd.read_csv(csv, parse_dates=["date"]) else: file_date = csv.split("/")[-1].replace(".csv", "") df = pd.read_csv(csv, parse_dates=["county_date"]) df["date"] = file_date df_list.append(df) df = pd.concat(df_list).sort_values(["date", "area"]) df.to_csv(data_dir / slug / "timeseries.csv", index=False) ```
github_jupyter
# Measuring crop health <img align="right" src="../Supplementary_data/dea_logo.jpg"> * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser * **Compatibility:** Notebook currently compatible with both the `NCI` and `DEA Sandbox` environments * **Products used:** [s2a_ard_granule](https://explorer.sandbox.dea.ga.gov.au/s2a_ard_granule), [s2b_ard_granule](https://explorer.sandbox.dea.ga.gov.au/s2b_ard_granule) ## Background During a normal year, sugar cane in Queensland typically flowers early May through June; July to November is typically cane harvesting season. While sugar is growing, fields may look visually similar. However, health or growth rates from these fields can be quite different, leading to variability and unpredictability in revenue. Identifying underperforming crops can have two benefits: * Ability to scout for frost or disease damage. * Ability to investigate poor performing paddocks and undertake management action such as soil testing or targeted fertilising to improve yield. ### Sentinel-2 use case Satellite imagery can be used to measure pasture health over time and identify any changes in growth patterns between otherwise similar paddocks. Sentinel-2's 10 metre resolution makes it ideal for understanding the health of paddocks. The Normalised Difference Vegetation Index (NDVI) describes the difference between visible and near-infrared reflectance of vegetation cover. This index estimates the density of green on an area of land and can be used to track the health and growth of sugar as it matures. Comparing the NDVI of two similar paddocks will help to identify any anomalies in growth patterns. ## Description In this example, data from the European Sentinel-2 satellites is used to assess crop growing patterns for the last year. This data is made available through the Copernicus Regional Data Hub and Digital Earth Australia within 1-2 days of capture. The worked example below takes users through the code required to: 1. Create a time series data cube over a farming property. 2. Select multiple paddocks for comparison. 3. Create graphs to identify crop performance trends over the last year. 4. Interpret the results. *** ## Getting started **To run this analysis**, run all the cells in the notebook, starting with the "Load packages and apps" cell. ### Load packages and apps This notebook works via two functions, which are referred to as apps: `load_crophealth_data` and `run_crophealth_app`. The apps allow the majority of the analysis code to be stored in another file, making the notebook easy to use and run. To view the code behind the apps, open the [notebookapp_crophealth.py](../Scripts/notebookapp_crophealth.py) file. ``` %matplotlib inline import sys import datacube sys.path.append("../Scripts") from notebookapp_crophealth import load_crophealth_data from notebookapp_crophealth import run_crophealth_app ``` ## Load the data The `load_crophealth_data()` command performs several key steps: * identify all available Sentinel-2 near real time data in the case-study area over the last year * remove any bad quality pixels * keep images where more than half of the image contains good quality pixels * collate images from Sentinel-2A and Sentinel-2B into a single data-set * calculate the NDVI from the red and near infrared bands * return the collated data for analysis The cleaned and collated data is stored in the `dataset_sentinel2` object. As the command runs, feedback will be provided below the cell, including information on the number of cleaned images loaded from each satellite. **Please be patient**. The load is complete when the cell status goes from `[*]` to `[number]`. ``` dataset_sentinel2 = load_crophealth_data() ``` ## Run the crop health app The `run_crophealth_app()` command launches an interactive map. Drawing polygons within the boundary (which represents the area covered by the loaded data) will result in plots of the average NDVI in that area. Draw polygons by clicking the &#11039; symbol in the app. The app works by taking the loaded data `dataset_sentinel2` as an argument. > **Note:** data points will only appear for images where more than 50% of the pixels were classified as good quality. This may cause trend lines on the average NDVI plot to appear disconnected. Available data points will be marked with the `*` symbol. ``` run_crophealth_app(dataset_sentinel2) ``` ## Drawing conclusions Here are some questions to think about: * What are some factors that might explain differences between fields? * From the NDVI value, can you tell when fields were harvested? *** ## Additional information **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Australia data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/GeoscienceAustralia/dea-notebooks). **Last modified:** June 2021 **Compatible datacube version:** ``` print(datacube.__version__) ``` ## Tags Browse all available tags on the DEA User Guide's [Tags Index](https://docs.dea.ga.gov.au/genindex.html)
github_jupyter
# Text Data - Natural Language Processing (NLP) # =================================== # Part A. Introductory Materials # =================================== Text data usually consists of a collection of documents (called the corpus) which can represent words, sentences, or even paragraphs of free flowing text. The inherent unstructured (no neatly formatted data columns!) and noisy nature of textual data makes it harder for machine learning methods to directly work on raw text data. # Feature Engineering Feature engineering dramatically improve performance of machine learning models and wins Kaggle competitions. This is especially true for text data, which is unstructured, noisy, and complex. This section will cover the following types of features for text data 1. Bag of Words 2. Bag of N-Grams (uni-gram, bi-gram, tri-gram, etc.) 3. TF-IDF (term frequency over inverse document frequency) ``` import pandas as pd import numpy as np import re import nltk import matplotlib.pyplot as plt nltk.download('stopwords') ``` A sample "corpus" of documents: the Document contains short sentences and each text belongs to a category. ``` corpus = ['The sky is blue and beautiful.', 'Love this blue and beautiful sky!', 'The quick brown fox jumps over the lazy dog.', 'The brown fox is quick and the blue dog is lazy!', 'The sky is very blue and the sky is very beautiful today', 'The dog is lazy but the brown fox is quick!' ] labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals'] corpus = np.array(corpus) corpus_df = pd.DataFrame({'Document': corpus, 'Category': labels}) corpus_df = corpus_df[['Document', 'Category']] corpus_df ``` # Text pre-processing Depending on your downstream task, cleaning and pre-processing text can involve several different components. Here are a few important components of Natural Language Processing (NLP) pipelines. 1. Removing tags: unnecessary content like HTML tags 2. Removing accented characters: other languages such as French, convert ASCII 3. Removing special characters: adds noise to text, use simple regular expressions (regexes) 4. Stemming and lemmatization: Stemming remove prefixes and suffixes of word stems (i.e. root words), ex. WATCH is the root stem of WATCHES, WATCHING, and WATCHE. Lemmatization similar but lexicographically correct word (present in the dictionary). 5. Expanding contractions: helps text standardization, ex. do not to donโ€™t and I would to Iโ€™d 6. Removing stopwords: Words without meaningful significance (ex. a, an, the, and) but high frequency. Additional pre-processing: tokenization, removing extra whitespaces, lower casing and more advanced operations like spelling corrections, grammatical error corrections, removing repeated characters. ``` wpt = nltk.WordPunctTokenizer() stop_words = nltk.corpus.stopwords.words('english') def normalize_document(doc): # lower case and remove special characters\whitespaces doc = re.sub(r'[^a-zA-Z0-9\s]', '', doc, re.I) doc = doc.lower() doc = doc.strip() # tokenize document tokens = wpt.tokenize(doc) # filter stopwords out of document filtered_tokens = [token for token in tokens if token not in stop_words] # re-create document from filtered tokens doc = ' '.join(filtered_tokens) return doc normalize_corpus = np.vectorize(normalize_document) norm_corpus = normalize_corpus(corpus) norm_corpus ``` # 1. Bag of Words Model This is perhaps the most simple vector space representational model for unstructured text. A vector space model is simply a mathematical model to represent unstructured text (or any other data) as numeric vectors, such that each dimension of the vector is a specific feature\\attribute. The bag of words model represents each text document as a numeric vector where each dimension is a specific word from the corpus and the value could be its frequency in the document, occurrence (denoted by 1 or 0) or even weighted values. The modelโ€™s name is such because each document is represented literally as a โ€˜bagโ€™ of its own words, disregarding word orders, sequences and grammar. ``` from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(min_df=0., max_df=1.) cv_matrix = cv.fit_transform(norm_corpus) cv_matrix = cv_matrix.toarray() cv_matrix ``` Thus you can see that our documents have been converted into numeric vectors such that each document is represented by one vector (row) in the above feature matrix. The following code will help represent this in a more easy to understand format. ``` # get all unique words in the corpus vocab = cv.get_feature_names() # show document feature vectors pd.DataFrame(cv_matrix, columns=vocab) ``` This should make things more clearer! You can clearly see that each column or dimension in the feature vectors represents a word from the corpus and each row represents one of our documents. The value in any cell, represents the number of times that word (represented by column) occurs in the specific document (represented by row). Hence if a corpus of documents consists of N unique words across all the documents, we would have an N-dimensional vector for each of the documents. This should make things more clearer! You can clearly see that each column or dimension in the feature vectors represents a word from the corpus and each row represents one of our documents. The value in any cell, represents the number of times that word (represented by column) occurs in the specific document (represented by row). Hence if a corpus of documents consists of N unique words across all the documents, we would have an N-dimensional vector for each of the documents. # 2. Bag of N-Grams Model A word is just a single token, often known as a unigram or 1-gram. We already know that the Bag of Words model doesnโ€™t consider order of words. But what if we also wanted to take into account phrases or collection of words which occur in a sequence? N-grams help us achieve that. An N-gram is basically a collection of word tokens from a text document such that these tokens are contiguous and occur in a sequence. Bi-grams indicate n-grams of order 2 (two words), Tri-grams indicate n-grams of order 3 (three words), and so on. The Bag of N-Grams model is hence just an extension of the Bag of Words model so we can also leverage N-gram based features. The following example depicts bi-gram based features in each document feature vector. ``` # you can set the n-gram range to 1,2 to get unigrams as well as bigrams bv = CountVectorizer(ngram_range=(2,2)) bv_matrix = bv.fit_transform(norm_corpus) bv_matrix = bv_matrix.toarray() vocab = bv.get_feature_names() pd.DataFrame(bv_matrix, columns=vocab) ``` This gives us feature vectors for our documents, where each feature consists of a bi-gram representing a sequence of two words and values represent how many times the bi-gram was present for our documents. # 3. TF-IDF Model There are some potential problems which might arise with the Bag of Words model when it is used on large corpora. Since the feature vectors are based on absolute term frequencies, there might be some terms which occur frequently across all documents and these may tend to overshadow other terms in the feature set. The TF-IDF model tries to combat this issue by using a scaling or normalizing factor in its computation. TF-IDF stands for Term Frequency-Inverse Document Frequency, which uses a combination of two metrics in its computation, namely: term frequency (tf) and inverse document frequency (idf). This technique was developed for ranking results for queries in search engines and now it is an indispensable model in the world of information retrieval and NLP. Mathematically, we can define TF-IDF as tfidf = tf x idf, which can be expanded further to be represented as follows. Here, tfidf(w, D) is the TF-IDF score for word w in document D. The term tf(w, D) represents the term frequency of the word w in document D, which can be obtained from the Bag of Words model. The term idf(w, D) is the inverse document frequency for the term w, which can be computed as the log transform of the total number of documents in the corpus C divided by the document frequency of the word w, which is basically the frequency of documents in the corpus where the word w occurs. There are multiple variants of this model but they all end up giving quite similar results. Letโ€™s apply this on our corpus now! ``` from sklearn.feature_extraction.text import TfidfVectorizer tv = TfidfVectorizer(min_df=0., max_df=1., use_idf=True) tv_matrix = tv.fit_transform(norm_corpus) tv_matrix = tv_matrix.toarray() vocab = tv.get_feature_names() pd.DataFrame(np.round(tv_matrix, 2), columns=vocab) ``` The TF-IDF based feature vectors for each of our text documents show scaled and normalized values as compared to the raw Bag of Words model values. Interested readers who might want to dive into further details of how the internals of this model work can refer to page 181 of Text Analytics with Python (Springer\\Apress; Dipanjan Sarkar, 2016). # =================================== # Part B. Intermediate Materials # =================================== There is still time left? Let's cover some more advanced clustering techniques: 1. Document Clustering with Similarity Features 2. Topic Models 3. Document Similarity # 1. Document Similarity Document similarity is the process of using a distance or similarity based metric that can be used to identify how similar a text document is with any other document(s) based on features extracted from the documents like bag of words or tf-idf. Thus you can see that we can build on top of the tf-idf based features we engineered in the previous section and use them to generate new features which can be useful in domains like search engines, document clustering and information retrieval by leveraging these similarity based features. Pairwise document similarity in a corpus involves computing document similarity for each pair of documents in a corpus. Thus if you have C documents in a corpus, you would end up with a C x C matrix such that each row and column represents the similarity score for a pair of documents, which represent the indices at the row and column, respectively. There are several similarity and distance metrics that are used to compute document similarity. These include cosine distance/similarity, euclidean distance, manhattan distance, BM25 similarity, jaccard distance and so on. In our analysis, we will be using perhaps the most popular and widely used similarity metric, cosine similarity and compare pairwise document similarity based on their TF-IDF feature vectors. ``` from sklearn.metrics.pairwise import cosine_similarity similarity_matrix = cosine_similarity(tv_matrix) similarity_df = pd.DataFrame(similarity_matrix) similarity_df ``` Cosine similarity basically gives us a metric representing the cosine of the angle between the feature vector representations of two text documents. Lower the angle between the documents, the closer and more similar they are as depicted in the following figure. Cosine similarity depictions for text document feature vectors Looking closely at the similarity matrix clearly tells us that documents (0, 1 and 6), (2, 5 and 7) are very similar to one another and documents 3 and 4 are slightly similar to each other but the magnitude is not very strong, however still stronger than the other documents. This must indicate these similar documents have some similar features. This is a perfect example of grouping or clustering that can be solved by unsupervised learning especially when you are dealing with huge corpora of millions of text documents. # 2. Document Clustering with Similarity Features Clustering leverages unsupervised learning to group data points (documents in this scenario) into groups or clusters. We will be leveraging an unsupervised hierarchical clustering algorithm here to try and group similar documents from our toy corpus together by leveraging the document similarity features we generated earlier. There are two types of hierarchical clustering algorithms namely, agglomerative and divisive methods. We will be using a agglomerative clustering algorithm, which is hierarchical clustering using a bottom up approach i.e. each observation or document starts in its own cluster and clusters are successively merged together using a distance metric which measures distances between data points and a linkage merge criterion. A sample depiction is shown in the following figure. The selection of the linkage criterion governs the merge strategy. Some examples of linkage criteria are Ward, Complete linkage, Average linkage and so on. This criterion is very useful for choosing the pair of clusters (individual documents at the lowest step and clusters in higher steps) to merge at each step is based on the optimal value of an objective function. We choose the Wardโ€™s minimum variance method as our linkage criterion to minimize total within-cluster variance. Hence, at each step, we find the pair of clusters that leads to minimum increase in total within-cluster variance after merging. Since we already have our similarity features, letโ€™s build out the linkage matrix on our sample documents. ``` from scipy.cluster.hierarchy import dendrogram, linkage Z = linkage(similarity_matrix, 'ward') pd.DataFrame(Z, columns=['Document\Cluster 1', 'Document\Cluster 2', 'Distance', 'Cluster Size'], dtype='object') ``` If you closely look at the linkage matrix, you can see that each step (row) of the linkage matrix tells us which data points (or clusters) were merged together. If you have n data points, the linkage matrix, Z will be having a shape of (nโ€Šโ€”โ€Š1) x 4 where Z[i] will tell us which clusters were merged at step i. Each row has four elements, the first two elements are either data point identifiers or cluster labels (in the later parts of the matrix once multiple data points are merged), the third element is the cluster distance between the first two elements (either data points or clusters), and the last element is the total number of elements\\data points in the cluster once the merge is complete. We recommend you refer to the scipy documentation, which explains this in detail. Letโ€™s now visualize this matrix as a dendrogram to understand the elements better! ``` plt.figure(figsize=(8, 3)) plt.title('Hierarchical Clustering Dendrogram') plt.xlabel('Data point') plt.ylabel('Distance') dendrogram(Z) plt.axhline(y=1.0, c='k', ls='--', lw=0.5) ``` # Topic Models We can also use some summarization techniques to extract topic or concept based features from text documents. The idea of topic models revolves around the process of extracting key themes or concepts from a corpus of documents which are represented as topics. Each topic can be represented as a bag or collection of words/terms from the document corpus. Together, these terms signify a specific topic, theme or a concept and each topic can be easily distinguished from other topics by virtue of the semantic meaning conveyed by these terms. However often you do end up with overlapping topics based on the data. These concepts can range from simple facts and statements to opinions and outlook. Topic models are extremely useful in summarizing large corpus of text documents to extract and depict key concepts. They are also useful in extracting features from text data that capture latent patterns in the data. There are various techniques for topic modeling and most of them involve some form of matrix decomposition. Some techniques like Latent Semantic Indexing (LSI) use matrix decomposition operations, more specifically Singular Valued Decomposition. We will be using another technique is Latent Dirichlet Allocation (LDA), which uses a generative probabilistic model where each document consists of a combination of several topics and each term or word can be assigned to a specific topic. This is similar to pLSI based model (probabilistic LSI). Each latent topic contains a Dirichlet prior over them in the case of LDA. The math behind in this technique is pretty involved, so I will try to summarize it without boring you with a lot of details. I recommend readers to go through this excellent talk by Christine Doig. The black box in the above figure represents the core algorithm that makes use of the previously mentioned parameters to extract K topics from M documents. The following steps give a simplistic explanation of what happens in the algorithm behind the scenes. Once this runs for several iterations, we should have topic mixtures for each document and then generate the constituents of each topic from the terms that point to that topic. Frameworks like gensim or scikit-learn enable us to leverage the LDA model for generating topics. For the purpose of feature engineering which is the intent of this article, you need to remember that when LDA is applied on a document-term matrix (TF-IDF or Bag of Words feature matrix), it gets decomposed into two main components. A document-topic matrix, which would be the feature matrix we are looking for. A topic-term matrix, which helps us in looking at potential topics in the corpus. Letโ€™s leverage scikit-learn to get the document-topic matrix as follows. ``` from sklearn.decomposition import LatentDirichletAllocation lda = LatentDirichletAllocation(n_components=3, max_iter=10000, random_state=0) dt_matrix = lda.fit_transform(cv_matrix) features = pd.DataFrame(dt_matrix, columns=['T1', 'T2', 'T3']) features ``` You can clearly see which documents contribute the most to which of the three topics in the above output. You can view the topics and their main constituents as follows. ``` tt_matrix = lda.components_ for topic_weights in tt_matrix: topic = [(token, weight) for token, weight in zip(vocab, topic_weights)] topic = sorted(topic, key=lambda x: -x[1]) topic = [item for item in topic if item[1] > 0.6] print(topic) print() ``` # Document Clustering with Topic Model Features We used our Bag of Words model based features to build out topic model based features using LDA. We can now actually leverage the document term matrix we obtained and use an unsupervised clustering algorithm to try and group our documents similar to what we did earlier with our similarity features. We will use a very popular partition based clustering method this time, K-means clustering to cluster or group these documents based on their topic model feature representations. In K-means clustering, we have an input parameter k, which specifies the number of clusters it will output using the document features. This clustering method is a centroid based clustering method, where it tries to cluster these documents into clusters of equal variance. It tries to create these clusters by minimizing the within-cluster sum of squares measure, also known as inertia. There are multiple ways to select the optimal value of k like using the Sum of Squared Errors metric, Silhouette Coefficients and the Elbow method. ``` from sklearn.cluster import KMeans km = KMeans(n_clusters=3, random_state=0) km.fit_transform(features) cluster_labels = km.labels_ cluster_labels = pd.DataFrame(cluster_labels, columns=['ClusterLabel']) pd.concat([corpus_df, cluster_labels], axis=1) ``` # =================================== # Part C. Advanced Materials # =================================== Done and have more time? Help your classmates with completing their exercise or try the next tutorial on word embeddings as features. https://towardsdatascience.com/understanding-feature-engineering-part-4-deep-learning-methods-for-text-data-96c44370bbfa # Shortcomings of traditional models: Traditional (count-based) feature engineering strategies for textual data involve models belonging to a family of models popularly known as the Bag of Words model. This includes term frequencies, TF-IDF (term frequency-inverse document frequency), N-grams and so on. While they are effective methods for extracting features from text, due to the inherent nature of the model being just a bag of unstructured words, we lose additional information like the semantics, structure, sequence and context around nearby words in each text document. This forms as enough motivation for us to explore more sophisticated models which can capture this information and give us features which are vector representation of words, popularly known as embeddings. # The need for word embeddings: While this does make some sense, why should we be motivated enough to learn and build these word embeddings? With regard to speech or image recognition systems, all the information is already present in the form of rich dense feature vectors embedded in high-dimensional datasets like audio spectrograms and image pixel intensities. However when it comes to raw text data, especially count based models like Bag of Words, we are dealing with individual words which may have their own identifiers and do not capture the semantic relationship amongst words. This leads to huge sparse word vectors for textual data and thus if we do not have enough data, we may end up getting poor models or even overfitting the data due to the curse of dimensionality. To overcome the shortcomings of losing out semantics and feature sparsity in bag of words model based features, we need to make use of Vector Space Models (VSMs) in such a way that we can embed word vectors in this continuous vector space based on semantic and contextual similarity. In fact the distributional hypothesis in the field of distributional semantics tells us that words which occur and are used in the same context, are semantically similar to one another and have similar meanings. In simple terms, โ€˜a word is characterized by the company it keepsโ€™. One of the famous papers talking about these semantic word vectors and various types in detail is โ€˜Donโ€™t count, predict! A systematic comparison of context-counting vs. context-predicting semantic vectorsโ€™ by Baroni et al. We wonโ€™t go into extensive depth but in short, there are two main types of methods for contextual word vectors. Count-based methods like Latent Semantic Analysis (LSA) which can be used to compute some statistical measures of how often words occur with their neighboring words in a corpus and then building out dense word vectors for each word from these measures. Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process it learns distributed representations giving us dense word embeddings. We will be focusing on these predictive methods in this article.
github_jupyter
# Introduction to Python and Jupyter notebooks Python is a programming language where you don't need to compile. You can just run it line by line (which is how we can use it in a notebook). So if you are quite new to programming, Python is a great place to start. The current version is Python 3, which is what we'll be using here. One way to code in Python is to use a Jupyter notebook. This is probably the best way to combine programming, text and images. In a notebook, everything is laid out in cells. Text cells and code cells are the most common. If you are viewing this section as a Jupyter notebook, the text you are now reading is in a text cell. A code cell can be found just below. To run the contents of a code cell, you can click on it and press Shift + Enter. Or if there is a little arrow thing on the left, you can click on that. ``` 1 + 1 ``` If you are viewing this section as a Jupyter notebook, execute each of the code cells as you read through. ``` a = 1 b = 0.5 a + b ``` Above we created two variables, which we called `a` and `b`, and gave them values. Then we added them. Simple arithmetic like this is pretty straightforward in Python. Variables in Python come in many forms. Below are some examples. ``` an_integer = 42 # Just an integer a_float = 0.1 # A non-integer number, up to a fixed precision a_boolean = True # A value that can be True or False a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text none_of_the_above = None # The absence of any actual value or variable type ``` As well as numbers, another data structure we can use is the *list*. ``` a_list = [0,1,2,3] ``` Lists in Python can contain any mixture of variable types. ``` a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ] ``` Lists are indexed from `0` in Python (unlike languages such as Fortran). So here's how you access the `42` at the beginning of the above list. ``` a_list[0] ``` A similar data structure is the *tuple*. ``` a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' ) a_tuple[0] ``` A major difference between the list and the tuple is that list elements can be changed ``` a_list[5] = 'apple' print(a_list) ``` whereas tuple elements cannot ``` a_tuple[5] = 'apple' ``` Also, we can add an element to the end of a list, which we cannot do with tuples. ``` a_list.append( 3.14 ) print(a_list) ``` Another useful data structure is the *dictionary*. This stores a set of *values*, each labeled by a unique *key*. Values can be any data type. Keys can be anything sufficiently simple (integer, float, Boolean, string). It cannot be a list, but it _can_ be a tuple. ``` a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 } ``` The values are accessed using the keys ``` a_dict['This is the key for a value 1'] ``` New key/value pairs can be added by just supplying the new value for the new key ``` a_dict['new key'] = 'new_value' ``` To loop over a range of numbers, the syntax is ``` for j in range(5): print(j) ``` Note that it starts at 0 (by default), and ends at n-1 for `range(n)`. You can also loop over any 'iterable' object, such as lists ``` for j in a_list: print(j) ``` or dictionaries ``` for key in a_dict: value = a_dict[key] print('key =',key) print('value =',value) print() ``` Conditional statements are done with `if`, `elif` and `else` with the following syntax. ``` if 'strawberry' in a_list: print('We have a strawberry!') elif a_list[5]=='apple': print('We have an apple!') else: print('Not much fruit here!') ``` Importing packages is done with a line such as ``` import numpy ``` The `numpy` package is important for doing maths ``` numpy.sin( numpy.pi/2 ) ``` We have to write `numpy.` in front of every numpy command so that it knows how to find that command defined in `numpy`. To save writing, it is common to use ``` import numpy as np np.sin( np.pi/2 ) ``` Then you only need the shortened name. Most people use `np`, but you can choose what you like. You can also pull everything straight out of `numpy` with ``` from numpy import * ``` Then you can use the commands directly. But this can cause packages to mess with each other, so use with caution. ``` sin( pi/2 ) ``` If you want to do trigonometry, linear algebra, etc, you can use `numpy`. For plotting, use `matplotlib`. For graph theory, use `networkx`. For quantum computing, use `qiskit`. For whatever you want, there will probably be a package to help you do it. A good thing to know about in any language is how to make a function. Here's a function, whose name was chosen to be `do_some_maths`, whose inputs are named `Input1` and `Input2` and whose output is named `the_answer`. ``` def do_some_maths ( Input1, Input2 ): the_answer = Input1 + Input2 return the_answer ``` It's used as follows ``` x = do_some_maths(1,72) print(x) ``` If you give a function an object, and the function calls a method of that object to alter its state, the effect will persist. So if that's all you want to do, you don't need to `return` anything. For example, let's do it with the `append` method of a list. ``` def add_sausages ( input_list ): if 'sausages' not in input_list: input_list.append('sausages') print('List before the function') print(a_list) add_sausages(a_list) # function called without an output print('\nList after the function') print(a_list) ``` Randomness can be generated using the `random` package. ``` import random for j in range(5): print('* Results from sample',j+1) print('\n Random number from 0 to 1:', random.random() ) print("\n Random choice from our list:", random.choice( a_list ) ) print('\n') ``` These are the basics. Now all you need is a search engine, and the intuition to know who is worth listening to on Stack Exchange. Then you can do anything with Python. Your code might not be the most 'Pythonic', but only Pythonistas really care about that.
github_jupyter
# Introduction This notebook presents **LSTM** network with character-wise input trained on Shakespeare plays. Dataset file is included in this repo and consists of all works of Shakespeare concatenated together (4.6MB). # Imports ``` import time import collections import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ``` # Read Data Dataset location ``` dataset_location = '../Datasets/shakespeare/shakespeare_input.txt' ``` Open text file ``` with open(dataset_location, 'r') as f: text = f.read() print(text[:173]) ``` Discard bit at the end such that text is divisible by 1024. This allow for batch sizes [1, 2, 4, 8, 16, 32, ..., 1024] ``` mod1024 = len(text) % 1024 text = text[:-mod1024] ``` Tokenize ``` tokens = collections.Counter(text).most_common() tokens[0:5] i2c = {i : c for i, (c, n) in enumerate(tokens)} c2i = {c : i for i, c in i2c.items()} print('i2c:', i2c) print('c2i:', c2i) ``` Encode text as tokens, reshape to batches, convert to tensor ``` batch_size = 128 data = np.array([c2i[c] for c in text]) data = data.reshape((batch_size, -1)) print('data:') print(data) print('shape:', data.shape) split_index = int(data.shape[1]*.8) # 80% train, 10% valid train_data, valid_data = np.split(data, [split_index], axis=1) print('train_data:', train_data.shape) print('valid_data:', valid_data.shape) ``` Move to GPU if possible ``` train_x = torch.tensor(train_data).to(device) valid_x = torch.tensor(valid_data).to(device) print('train_x:', train_x.shape) print('valid_x:', valid_x.shape) ``` Model ``` class CharRNN(nn.Module): def __init__(self, nb_layers, n_in, n_embed, n_hid, n_out, dropout): super(CharRNN, self).__init__() self.embed = nn.Embedding(num_embeddings=n_in, embedding_dim=n_embed) self.lstm = nn.LSTM(input_size=n_embed, hidden_size=n_hid, num_layers=nb_layers, batch_first=True, dropout=dropout) self.drop = nn.Dropout(p=dropout) self.fc = nn.Linear(in_features=n_hid, out_features=n_out) def forward(self, x, hidden): x = self.embed(x) # shape [n_batch, n_seq, n_embed] x, hidden = self.lstm(x, hidden) # shape [n_batch, n_seq, n_hid] x = self.drop(x) x = self.fc(x) # shape [n_batch, n_seq, n_out] return x, hidden def sample(self, inputs, hidden, topk=5): """Sample one token, conditioned on inputs and hidden Params: inputs - tensor with input tokens, shape [1, n_seq] hidden - hidden state for LSTM, can be None topk - int, how many top choices to consider when sampling Returns: token for next predicted character, tensor of shape [1, 1] containing one int """ logits, hidden = self(inputs, hidden) last_output = logits[0, -1] # keep last seq. output shape [n_out] probs = F.softmax(last_output, dim=0) # logits to probabilities shape [n_out] probs, indices = probs.topk(topk) weights = probs / probs.sum() # normalize probs tok = np.random.choice(a=indices.detach().cpu().numpy(), # no torch impl. yet :( p=weights.detach().cpu().numpy()) res = torch.tensor([[tok]], device=inputs.device) # feed to next sample() call return res, hidden ``` Hyperparameters ``` nb_layers = 2 n_in = len(i2c) n_seq = 256 n_embed = 50 n_hid = 64 n_out = len(i2c) dropout = .5 ``` Create model ``` model = CharRNN(nb_layers, n_in, n_embed, n_hid, n_out, dropout) model.to(device) optimizer = optim.Adam(model.parameters()) criterion = nn.CrossEntropyLoss() ``` Helper to generate new text ``` def generate(prompt=' ', size=1000): model.eval() inputs = [c2i[c] for c in prompt] # tokenize inputs = torch.tensor(inputs).to(device) inputs = inputs.reshape(1, -1) # shape [n_batch=1, n_seq] result = [] with torch.no_grad(): output, hidden = model.sample(inputs, None, topk=5) result.append(output.item()) for i in range(size-1): output, hidden = model.sample(output, hidden, topk=5) result.append(output.item()) return ''.join([i2c[i] for i in result]) ``` Helper function for training ``` def train(nb_epochs, trace, trace2): epoch = len(trace['epoch']) train_size = train_x.shape[1] - 1 # -1 because inputs/targets are shifted by one valid_size = valid_x.shape[1] - 1 for _ in range(nb_epochs): time_start = time.time() # # Train Model # model.train() tloss_sum = 0 hidden = None # reset LSTM hidden state for i in range(0, train_size, n_seq): # Pick mini-batch (over seqence dimension) inputs = train_x[:,i:i+n_seq] # [n_batch, n_seq], less for last batch targets = train_x[:,i+1:i+1+n_seq] # [n_batch, n_seq], less for last batch if inputs.shape[1] != targets.shape[1]: inputs = inputs[:,:-1] # fix shape for last batch in epoch # Optimize optimizer.zero_grad() outputs, hidden = model(inputs, hidden) hidden = tuple(h.detach() for h in hidden) loss = criterion(outputs.view(-1, n_out), targets.flatten()) loss.backward() optimizer.step() # Record per-iteration loss tloss_sum += loss.item() * inputs.shape[1] # size of minibatch trace2['loss'].append( loss.item() ) tloss_avg = tloss_sum / train_size # # Evaluate Model # model.eval() vloss_sum = 0 hidden = None with torch.no_grad(): for i in range(0, valid_size, n_seq): # Pick mini-batch inputs = valid_x[:,i:i+n_seq] targets = valid_x[:,i+1:i+1+n_seq] if inputs.shape[1] != targets.shape[1]: inputs = inputs[:,:-1] # Optimize outputs, hidden = model(inputs, hidden) loss = criterion(outputs.view(-1, n_out), targets.flatten()) # Record per-iteration loss vloss_sum += loss.item() * inputs.shape[1] vloss_avg = vloss_sum / valid_size # # Logging # time_delta = time.time() - time_start trace['epoch'].append(epoch) trace['tloss'].append(tloss_avg) trace['vloss'].append(vloss_avg) # # Print loss # print(f'Epoch: {epoch:3} ' f'T/V Loss: {tloss_avg:.4f} / {vloss_avg:.4f} ' f'Time: {time_delta:.2f}s') epoch += 1 ``` Test model before training ``` prompt = 'KING:\n' new_text = generate(prompt, size=1000) print(prompt, new_text, sep='') ``` Actually train the model ``` trace = {'epoch': [], 'tloss': [], 'vloss': []} # per epoch trace2 = {'loss' : []} # per iteration train(nb_epochs=10, trace=trace, trace2=trace2) ``` Train some more ``` train(nb_epochs=10, trace=trace, trace2=trace2) ``` Test model after training ``` prompt = 'KING:\n' new_text = generate(prompt, size=1000) print(prompt, new_text, sep='') ``` # Train and Valid Loss Wait, wait, wait, is valid loss less than train loss? Lets plot per-iteration train loss ``` plt.plot(trace2['loss']); ``` Plot per-epoch train and valid losses ``` plt.plot(trace['tloss'], label='tloss') plt.plot(trace['vloss'], label='vloss') plt.legend(); ``` **Why validation loss is less than train loss?** Mainly because dropout is enabled in train mode. To test this let's make helper function to evaluate model ``` def evaluate(data_x): data_size = data_x.shape[1] - 1 # # Evaluate Model # model.eval() loss_sum = 0 hidden = None with torch.no_grad(): for i in range(0, data_size, n_seq): # Pick mini-batch inputs = data_x[:,i:i+n_seq] targets = data_x[:,i+1:i+1+n_seq] if inputs.shape[1] != targets.shape[1]: inputs = inputs[:,:-1] # Optimize outputs, hidden = model(inputs, hidden) loss = criterion(outputs.view(-1, n_out), targets.flatten()) # Record per-iteration loss loss_sum += loss.item() * inputs.shape[1] loss_avg = loss_sum / data_size return loss_avg ``` Evaluate on both train and valid datasets ``` train_loss = evaluate(train_x) valid_loss = evaluate(valid_x) print('train loss:', train_loss) print('valid loss:', valid_loss) ``` Nope, all is good
github_jupyter
``` test_index = 0 from load_data import * # load_data() from load_data import * X_train,X_test,y_train,y_test = load_data() len(X_train),len(y_train) len(X_test),len(y_test) import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Test_Model(nn.Module): def __init__(self) -> None: super().__init__() self.c1 = nn.Conv2d(1,64,5) self.c2 = nn.Conv2d(64,128,5) self.c3 = nn.Conv2d(128,256,5) self.fc4 = nn.Linear(256*10*10,256) self.fc6 = nn.Linear(256,128) self.fc5 = nn.Linear(128,4) def forward(self,X): preds = F.max_pool2d(F.relu(self.c1(X)),(2,2)) preds = F.max_pool2d(F.relu(self.c2(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.c3(preds)),(2,2)) # print(preds.shape) preds = preds.view(-1,256*10*10) preds = F.relu(self.fc4(preds)) preds = F.relu(self.fc6(preds)) preds = self.fc5(preds) return preds device = torch.device('cuda') BATCH_SIZE = 32 IMG_SIZE = 112 model = Test_Model().to(device) optimizer = optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() EPOCHS = 12 from tqdm import tqdm PROJECT_NAME = 'Weather-Clf' import wandb # test_index += 1 # wandb.init(project=PROJECT_NAME,name=f'test-{test_index}') # for _ in tqdm(range(EPOCHS)): # for i in range(0,len(X_train),BATCH_SIZE): # X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) # y_batch = y_train[i:i+BATCH_SIZE].to(device) # model.to(device) # preds = model(X_batch.float()) # preds.to(device) # loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) # optimizer.zero_grad() # loss.backward() # optimizer.step() # wandb.log({'loss':loss.item()}) # wandb.finish() # for index in range(10): # print(torch.argmax(preds[index])) # print(y_batch[index]) # print('\n') class Test_Model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1,16,5) self.conv2 = nn.Conv2d(16,32,5) self.conv3 = nn.Conv2d(32,64,5) self.conv4 = nn.Conv2d(64,128,3) self.conv5 = nn.Conv2d(128,256,3) self.fc1 = nn.Linear(256,64) self.fc2 = nn.Linear(64,128) self.fc3 = nn.Linear(128,256) self.fc4 = nn.Linear(256,128) self.fc5 = nn.Linear(128,6) def forward(self,X): preds = F.max_pool2d(F.relu(self.conv1(X)),(2,2)) preds = F.max_pool2d(F.relu(self.conv2(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.conv3(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.conv4(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.conv5(preds)),(2,2)) # print(preds.shape) preds = preds.view(-1,256) preds = F.relu(self.fc1(preds)) preds = F.relu(self.fc2(preds)) preds = F.relu(self.fc3(preds)) preds = F.relu(self.fc4(preds)) preds = F.relu(self.fc5(preds)) return preds model = Test_Model().to(device) optimizer = optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() test_index += 1 wandb.init(project=PROJECT_NAME,name=f'test-{test_index}') for _ in tqdm(range(EPOCHS)): for i in range(0,len(X_train),BATCH_SIZE): X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) y_batch = y_train[i:i+BATCH_SIZE].to(device) model.to(device) preds = model(X_batch.float()) preds.to(device) loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) optimizer.zero_grad() loss.backward() optimizer.step() wandb.log({'loss':loss.item()}) wandb.finish() ```
github_jupyter
``` # coding: utf-8 # In[3]: import pandas as pd from KRRcode import open_database from NNcode import screen_3criteria as sc perovskite,values,data_total=open_database.read_database() #3 dataframe screening_data=sc.screening(data_total) #23 data after screening data_total['water_splitting']=None for i in screening_data.index: data_total['water_splitting'].iloc[i-1]=1 electroneg = pd.read_csv('Data/electronegativity.csv') def input_screening(A_ion,B_ion,anion,mass,volume): your_data=pd.DataFrame(columns=['anion', 'anion_X', 'anion_IE', 'A_ion', 'A_X', 'A_IE', 'A_s_R','A_p_R', 'A_d_R', 'A_aff', 'B_ion', 'B_X', 'B_IE','B_s_R','B_p_R','B_d_R', 'B_aff','volume','mass','density', 'A_R', 'B_R','X_A+B','X_A-B', 'IE_A+B','IE_A-B','aff_A+B','aff_A-B','A_R_max','B_R_max','standard_energy']) your_data['anion'] = anion your_data['A_ion'] = A_ion your_data['B_ion'] = B_ion your_data['A_R']=your_data['A_s_R']+your_data['A_p_R']+your_data['A_d_R'] your_data['B_R']=your_data['B_s_R']+your_data['B_p_R']+your_data['B_d_R'] your_data['X_A+B']=your_data['A_X']+your_data['B_X'] your_data['X_A-B']=your_data['A_X']-your_data['B_X'] your_data['IE_A+B']=your_data['A_IE']+your_data['B_IE'] your_data['IE_A-B']=your_data['A_IE']-your_data['B_IE'] your_data['aff_A+B']=your_data['A_aff']+your_data['B_aff'] your_data['aff_A-B']=your_data['A_aff']-your_data['B_aff'] your_data['A_R_max']=your_data[['A_s_R', 'A_p_R', 'A_d_R']].max(axis=1) your_data['B_R_max']=your_data[['B_s_R', 'B_p_R', 'B_d_R']].max(axis=1) your_data['volume']=volume your_data['mass']=mass your_data['density']=mass/volume for i in range(len(data_total)): if A_ion==data_total.iloc[i,:]['A_ion']: if B_ion==data_total.iloc[i,:]['B_ion'] : if anion==data_total.iloc[i,:]['anion']: if data_total.iloc[i,:]['water_splitting']==1: comment='Yes,it can do water-slpitting' return your_data,comment break else: comment='No,it can\'t do water-splitting.' return your_data,comment break else: continue else: continue else: continue comment='The molecule is not in our database, so we need to predict' return your_data,comment ```
github_jupyter
### ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜ ``` pip install librosa pip install imutils pip install opencv-python pip install sklearn ``` ### ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ import ``` from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.mixture import GaussianMixture from sklearn.metrics import accuracy_score from sklearn.externals import joblib from sklearn.svm import SVC from imutils import paths import matplotlib.pyplot as plt import soundfile as sf import librosa import wave, array import numpy as np import pandas as pd import pickle import json import sys import os import warnings warnings.filterwarnings('ignore') ``` ### ์ฝ”๋”ฉ ์‹œ์ž‘ ``` def get_result(y, sr): clf_load = joblib.load('saved_model.pkl') audio_mfcc = librosa.feature.mfcc(y = y, sr = sr) x_test = audio_mfcc.reshape(-1) return clf_load.predict([x_test])[0] # json ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ file = 'C:/Users/HONGHYEIN/Desktop/ํ™ํ˜œ์ธ/4ํ•™๋…„ 2ํ•™๊ธฐ/์บก์Šคํ†ค/dev/๋ฐ์ดํ„ฐ/data.json' with open(file, "r", encoding = "utf-8") as json_file: json_data = json.load(json_file) # ์Œ์„ฑ ํŒŒ์ผ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ file = 'C:/Users/HONGHYEIN/Desktop/ํ™ํ˜œ์ธ/4ํ•™๋…„ 2ํ•™๊ธฐ/์บก์Šคํ†ค/dev/๋ฐ์ดํ„ฐ/call.wav' y, sr = librosa.load(file, sr = 16000) # ํ™”์ž ์ˆ˜ ์„ค์ •ํ•˜๊ธฐ speakers = json_data['speakers'] # json ํŒŒ์ผ ์‚ฌ์šฉํ•˜์—ฌ ํ™”์ž ๋ถ„ํ• ํ•˜๊ธฐ spk = [] spk_cnt = [] for i in range(0, speakers): spk.append([]) spk_cnt.append(0) for i in range(0, len(json_data['result'])): start_time = float(json_data['result'][i]['start_time']) end_time = float(json_data['result'][i]['end_time']) cutted_y = y[int(start_time)*16000:int(end_time)*16000] if json_data['result'][i]['speaker_label'] == 'spk_0': spk[0].append([cutted_y, sr]) spk_cnt[0] += 1 if json_data['result'][i]['speaker_label'] == 'spk_1': spk[1].append([cutted_y, sr]) spk_cnt[1] += 1 # ํ™”์ž๋งˆ๋‹ค ์Œ์„ฑ ํŒŒ์ผ 1์ดˆ์”ฉ ์ž๋ฅด๊ธฐ # ์Œ์„ฑ ํŒŒ์ผ ํ…Œ์ŠคํŠธํ•˜๊ธฐ emotion = [] total_duration = [] for i in range(0, speakers): emotion.append([]) total_duration.append(0) k = 0 while k < speakers: for i in range(0, spk_cnt[k]): duration = int(librosa.get_duration(spk[k][i][0], sr)) total_duration[k] += duration for j in range(0, duration): cutted_y = spk[k][i][0][j*16000:(j+1)*16000] emotion[k].append(get_result(cutted_y, 16000)) k += 1 # ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ ๊ฐ€๊ณตํ•˜๊ธฐ emotion_count =[] for i in range(0, speakers): emotion_count.append({'happiness':0, 'neutral':0, 'sadness':0, 'anger':0, 'time':total_duration[i]}) k = 0 while k < speakers: for i in emotion[k]: try: emotion_count[k][i]+= 1 except: emotion_count[k][i] = 1 k += 1 # ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ CSV ํŒŒ์ผ๋กœ ์ €์žฅํ•˜๊ธฐ result_dict = {} for i in range(0, speakers): spk_id = "spk_" + str(i) temp_dict = {} temp_key = list(emotion_count[i].keys()) temp_value = list(emotion_count[i].values()) for j in range(0, 5): temp_dict[temp_key[j]] = temp_value[j] result_dict[spk_id] = temp_dict df = pd.DataFrame(result_dict).T df.to_csv('C:/Users/HONGHYEIN/Desktop/ํ™ํ˜œ์ธ/4ํ•™๋…„ 2ํ•™๊ธฐ/์บก์Šคํ†ค/dev/๋ฐ์ดํ„ฐ/data.csv') ```
github_jupyter
# Characters Classification with Neural Networks In this notebook we are going to use the Neural Networks for image classification. We are going to use the same dataset of the lab on SVM: Kuzushiji-MNIST or K-MNIST for short (https://github.com/rois-codh/kmnist) a dataset of traditional japanese handwritten kana. The dataset labels are the following: | Label | Hiragana Character | Romanji (Pronunciation) | | :-: | :-: | :-: | | 0 | ใŠ | o | | 1 | ใ | ki | | 2 | ใ™ | su | | 3 | ใค | tsu | | 4 | ใช | na | | 5 | ใฏ | ha | | 6 | ใพ | ma | | 7 | ใ‚„ | ya | | 8 | ใ‚Œ | re | | 9 | ใ‚’ | wo | ATTENTION! Running all the cells takes between 15 and 20 minutes on my PC. ``` #load the required packages and check Scikit-learn version %matplotlib inline import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd import sklearn print ('scikit-learn version: ', sklearn.__version__) from sklearn.neural_network import MLPClassifier from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC # helper function to load KMNIST dataset from disk def load_mnist(path, kind='train'): import os import gzip import numpy as np labels_path = os.path.join(path, 'K%s-labels-idx1-ubyte.gz' % kind) images_path = os.path.join(path, 'K%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath: labels = np.frombuffer(lbpath.read(), dtype=np.uint8,offset=8) with gzip.open(images_path, 'rb') as imgpath: images = np.frombuffer(imgpath.read(), dtype=np.uint8,offset=16).reshape(len(labels), 784) return images, labels ``` # TODO Set as seed for the random generator your Student ID (you can use your "numero di matricola"). Try to change the seed to see the impact of the randomization. ``` ID = 2048654 np.random.seed(ID) #load the MNIST dataset and let's normalize the features so that each value is in [0,1] X, y = load_mnist("data") print("Number of samples in the K-MNIST dataset:", X.shape[0]) # rescale the data X = X / 255.0 ``` Now split into training and test. We start with a small training set of 600 samples to reduce computation time while 4000 samples will be used for testing. Make sure that each label is present at least 10 times in train and test set frequencies. ``` #random permute the data and split into training and test taking the first 600 #data samples as training and 4000 as test set permutation = np.random.permutation(X.shape[0]) X = X[permutation] y = y[permutation] m_training = 600 m_test = 4000 X_train, X_test = X[:m_training], X[m_training:m_training+m_test] y_train, y_test = y[:m_training], y[m_training:m_training+m_test] labels, freqs = np.unique(y_train, return_counts=True) print("Labels in training dataset: ", labels) print("Frequencies in training dataset: ", freqs) labelsT, freqsT = np.unique(y_test, return_counts=True) print("Labels in test set: ", labels) print("Frequencies in test set: ", freqs) #function for plotting a image and printing the corresponding label def plot_input(X_matrix, labels, index): print("INPUT:") plt.imshow( X_matrix[index].reshape(28,28), cmap = plt.cm.gray_r, interpolation = "nearest" ) plt.show() print("LABEL: %i"%labels[index]) return #let's try the plotting function plot_input(X_train,y_train,10) plot_input(X_test,y_test,100) plot_input(X_test,y_test,1000) ``` ### TO DO 1 Now use a feed-forward Neural Network for prediction. Use the multi-layer perceptron classifier, with the following parameters: max_iter=100, alpha=1e-4, solver='sgd', tol=1e-4, learning_rate_init=.1, random_state=ID (this last parameter ensures the run is the same even if you run it more than once). The alpha parameter is the regularization term. Then, using the default activation function, pick four or five architectures to consider, with different numbers of hidden layers and different sizes. It is not necessary to create huge neural networks, you can limit to 3 layers and, for each layer, its maximum size can be of 50. Evaluate the architectures you chose using GridSearchCV with cv=5. You can reduce the number of iterations if the running time is too long on your computer. ``` # these are sample values but feel free to change them as you like, try to experiment with different sizes!! parameters = {'hidden_layer_sizes': [(10,), (20,), (40,), (20,20,), (40,20,10), (50, 40, 30), (10, 4, 3), (35, 30, 35), (23,), (29, 28,), (21, 34)]} #parameters = {'hidden_layer_sizes': [(i,j,k,) for i in range(33,37,1) # for j in range(28,32,1) # for k in range(33,37,1) ]} #parameters = {'hidden_layer_sizes': [(i,) for i in range(10,40)]} #parameters = {'hidden_layer_sizes': [(i,j,) for i in range(20,30,1) # for j in range(30,40,1)]} mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, learning_rate_init=.1) # increasing max iteration to avoid warning clf = GridSearchCV(mlp, parameters, cv=5) clf.fit(X_train, y_train) print ('RESULTS FOR NN\n') print("Best parameters set found:") print(clf.best_params_) best_layer_size = clf.best_params_['hidden_layer_sizes'] print("Score with best parameters:") print(clf.best_score_) print("\nAll scores on the grid:") #print(clf.cv_results_) # using pandas for better view MLPResults = pd.DataFrame.from_dict(clf.cv_results_) MLPResults ``` ### TO DO 2 Now try also different batch sizes, while keeping the best NN architecture you have found above. Remember that the batch size was previously set to the default value, i.e., min(200, n_samples). Recall that a batch size of 1 corresponds to baseline SGD, while using all the 480 training samples (there are 600 samples but in cross validation with 5 folders we use 1/5 of them for validation at each round) corresponds to standard GD and using a different mini-batch size lies in the middle between the two extreme cases. ``` # these are sample values corresponding to baseline SGD, a reasonable mini-batch size and standard GD # again feel free to change them as you like, try to experiment with different batch sizes!! #parameters = {'batch_size': [1, 32, 97, 145, 429, 480]} #parameters = {'batch_size': [i for i in range(200, 480)]} parameters = {'batch_size': [32, 97, 145, 429]} # need to specify that you would like to use the standard k-fold split otherwise sklearn create splits of different sizes kf = sklearn.model_selection.KFold(n_splits=5) # recall to use cv=kf to use the k-fold subdivision seen in the lectures mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, learning_rate_init=.1, hidden_layer_sizes=best_layer_size) clf = GridSearchCV(mlp, parameters, cv=kf) clf.fit(X_train, y_train) print ('RESULTS FOR NN\n') print("Best parameters set found:") print(clf.best_params_) best_batch_size = clf.best_params_['batch_size'] print("Score with best parameters:") print(clf.best_score_) print("\nAll scores on the grid:") #print(clf.cv_results_) # using pandas for better view MLPResults = pd.DataFrame.from_dict(clf.cv_results_) MLPResults ``` Trying to to perform the Grid Search making letting both of the parameters free to vary ``` # these are sample values but feel free to change them as you like, try to experiment with different sizes!! parameters = {'hidden_layer_sizes': [(10,), (20,), (40,), (20,20,), (40,20,10), (50, 40, 30), (10, 4, 3), (35, 30, 35), (23,), (29, 28,), (21, 34)], 'batch_size': [32, 97, 145, 429]} mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, learning_rate_init=.1) # increasing max iteration to avoid warning clf = GridSearchCV(mlp, parameters, cv=5) clf.fit(X_train, y_train) print ('RESULTS FOR NN\n') print("Best parameters set found:") print(clf.best_params_) best_layer_size = clf.best_params_['hidden_layer_sizes'] best_batch_size = clf.best_params_['batch_size'] print("Score with best parameters:") print(clf.best_score_) print("\nAll scores on the grid:") #print(clf.cv_results_) # using pandas for better view MLPResults = pd.DataFrame.from_dict(clf.cv_results_) MLPResults ``` ### QUESTION 1 What do you observe for different architectures and batch sizes? How do the number of layers and their sizes affect the performances? What do you observe for different batch sizes, in particular what happens to the training convergence for different batch sizes (notice that the algorithm could not converge for some batch sizes)? ## [ANSWER TO QUESTION 1] The best architecture is the one with three layers of 35, 30 and 35 nodes each. Whatching the simpler ones, with only one layer, for the ones with fewer neurons we see probabily an underfit of the data, leading to bad results in terms of score, while the more complex ones, with more nodes are probabily overfitting the data leading to bad results too. For what concerns the mini-batch size parameter the best result is 429. Using a minibatch size of 1 the algorithm converges very slowly and has bad performances, while using a minibatch size high, which corresponds to the standard gradient descent, we get results not satisfying. Since I was warried that the results i got where not satifying i performed a grid search letting both of the parameters described above vary: i find this results more familiar, in particular about the architecture which is simpler, not having to be too warried about overfitting phenomena since one layer with a medium amount of neurons can be more easily generalized. ### TODO 3: Plot the train and test accuracies as a function of the number of learnable parameters in your neural network. Print also the computation time for the various configurations you try (the code for getting the computation time is already provided). You can use 100 iterations (if you get a warning on convergence not reached it is not an issue for this lab) ``` import time from functools import reduce # Function to compute the number of learnable parameters of a mlp given the size of its hidden layers def param_count(hl_size): tot = 0 input_size, output_size = X_train.shape[1], len(labels) tot += (input_size+1)*hl_size[0] for i in range(1,len(hl_size)): tot += (hl_size[i-1]+1)*hl_size[i] tot += (hl_size[-1]+1)*output_size return tot #hl_sizes = [(10,), (20,), (40,), (20,20,), (40,20,10)] hl_sizes = [(10,), (20,), (40,), (20,20,), (40,20,10), (50, 40, 30), (10, 4, 3), (35, 30, 35),(23,), (29, 28,),(21, 34)] hl_labels = [param_count(t) for t in hl_sizes] ti = time.time() train_acc_list, test_acc_list = [], [] for hl_size in hl_sizes: print('Training MLP of size {} ...'.format(hl_size)) mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, learning_rate_init=.1, hidden_layer_sizes=hl_size, n_iter_no_change=50, batch_size=best_batch_size) mlp.fit(X_train, y_train) train_acc_list.append(mlp.score(X_train, y_train)) test_acc_list.append(mlp.score(X_test, y_test)) print('Done, training time: {:.2f} sec\n'.format(time.time()-ti)) ti = time.time() fig, ax = plt.subplots(1,2, figsize=(15,5)) ax[0].plot(train_acc_list) ax[0].set_xlabel('Number of learnable params') ax[0].set_title('Train accuracy') ax[0].set_xticks(np.arange(0,len(hl_labels))) ax[0].set_xticklabels(hl_labels) ax[0].grid(True) ax[1].plot(test_acc_list) ax[1].set_xlabel('Number of learnable params') ax[1].set_title('Test accuracy') ax[1].set_xticks(np.arange(0,len(hl_labels))) ax[1].set_xticklabels(hl_labels) ax[1].grid(True) ``` ## Question 2: Comment about the training and test accuracies referring to the discussion on underfitting and overfitting we did in the course ## [ANSWER TO QUESTION 2] The simplest model, which is the one with only one layer of 10 neurons, has a pretty bad result considering the test accuracy, probabily due to an underfit. Increasing the number of neurons, but maintaning the number of layer, one can see that the curve has a maximum, corresponding to the best parameter (23) and then start to decrease. This means that we start to have an overfit in the data. So we do not have that increasing the number of neurons we have better and better results. Only one configuration (10,4,3) has a bad result both in terms of train accuracy and test accuracy, in particular the test accuracy $\sim 0.5$ is a very bad result since is compatible with a random choice. ### TO DO 4 Now try also to use different learning rates, while keeping the best NN architecture and batch size you have found above. Plot the learning curves (i.e., the variation of the loss over the steps, you can get it from the loss_curve_ object of sklearn) for the different values of the learning rate. Try to run each training for 100 iterations. ``` import matplotlib.pyplot as plt import operator lr_list = [0.0002, 0.002, 0.02, 0.2] scores = {} parameters = {'learning_rate_init': lr_list} mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=best_layer_size, batch_size=best_batch_size, n_iter_no_change=50) clf = GridSearchCV(mlp, parameters, cv=5, verbose=3, return_train_score = True) clf.fit(X_train, y_train) print ('RESULTS FOR NN\n') print("Best parameters set found:") print(clf.best_params_) #best_learning_rate = clf.best_params_['learning_rate_init'] best_learning_rate = 0.02 print("Score with best parameters:") print(clf.best_score_) print("\nAll scores on the grid:") #print(clf.cv_results_) # using pandas for better view MLPResults = pd.DataFrame.from_dict(clf.cv_results_) MLPResults fig, ax = plt.subplots(figsize=(10, 10)) for l in lr_list: mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=best_layer_size, batch_size=best_batch_size, n_iter_no_change=50, learning_rate_init=l, verbose=True) mlp.fit(X_train, y_train) ax.plot(mlp.loss_curve_, label = 'learning rate = ' + str(l)) ax.set_xlabel('n_iter') ax.set_ylabel('loss') ax.legend() plt.show() ``` ! the following is just to reproduce the expected behaviour showed us in class, with the best parameters among the given ones (and not considering the new parameters added and found better then the given ones). ``` fig, ax = plt.subplots(figsize=(10, 10)) for l in lr_list: mlp = MLPClassifier(max_iter=100, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=40, batch_size=32, n_iter_no_change=100, learning_rate_init=l, verbose=False) mlp.fit(X_train, y_train) ax.plot(mlp.loss_curve_, label = 'learning rate = ' + str(l)) ax.set_xlabel('n_iter') ax.set_ylabel('loss') ax.legend() plt.show() fig, ax = plt.subplots(figsize=(10, 10)) for l in lr_list: mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=(35,30,35), batch_size=429, #n_iter_no_change=100, learning_rate_init=l, verbose=False) mlp.fit(X_train, y_train) ax.plot(mlp.loss_curve_, label = 'learning rate = ' + str(l)) ax.set_xlabel('n_iter') ax.set_ylabel('loss') ax.legend() plt.show() ``` ### QUESTION 3 Comment about the learning curves (i.e. the variation of the loss over the steps). How does the curve changes for different learning rates in terms of stability and speed of convergence ? ## [ANSWER TO QUESTION 3] From the plot above one can see that while using the biggest learning rate leads to a quite immediate convergence the smallest one does not converge in the maximum number of iterations used. It is interesting to observe that using the other set of best parameters, found letting the two parameters vary one at the time, leads to different results in term of test error, giving best results for the 0.002 parameter instead (in the case of (30,35,30) for the layer sizes and 429 for the minibatch size), or the parameter 0.02 (using in the case of (40) for the layer sizes and 32 for the minibatch size). In any case, i choose as best parameter 0.02, avoiding stability problem that I detect choosing the 'expected' best parameters. ### TO DO 5 Now get training and test error for a NN with best parameters (architecture, batch size and learning rate) from above. Plot the learning curve also for this case (you can run the training for 500 iterations). ``` #get training and test error for the best NN model from CV mlp = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=best_layer_size, batch_size=best_batch_size, n_iter_no_change=50, #verbose=True, learning_rate_init=best_learning_rate) mlp.fit(X_train, y_train) training_error = 1 - mlp.score(X_train, y_train) test_error = 1 - mlp.score(X_test, y_test) print ('\nRESULTS FOR BEST NN\n') print ("Best NN training error: %f" % training_error) print ("Best NN test error: %f" % test_error) fig, ax = plt.subplots(figsize=(10, 10)) ax.plot(mlp.loss_curve_) ax.set_xlabel('n_iter') ax.set_ylabel('loss') plt.show() ``` ## More data Now let's do the same but using 4000 (or less if it takes too long on your machine) data points for training. Use the same NN architecture as before, but you can try more if you like and have a powerful computer!! ``` X = X[permutation] y = y[permutation] m_training = 5000 X_train, X_test = X[:m_training], X[m_training:] y_train, y_test = y[:m_training], y[m_training:] labels, freqs = np.unique(y_train, return_counts=True) print("Labels in training dataset: ", labels) print("Frequencies in training dataset: ", freqs) ``` ### TO DO 6 Now train the NNs with the added data points using the optimum parameters found above. Eventually, feel free to try different architectures if you like. We suggest that you use 'verbose=True' so have an idea of how long it takes to run 1 iteration (eventually reduce also the number of iterations to 50). ``` # use best architecture and params from before mlp_large = MLPClassifier(max_iter=2000, alpha=1e-4, solver='sgd', tol=1e-4, random_state=ID, hidden_layer_sizes=best_layer_size, batch_size=best_batch_size, n_iter_no_change=50, verbose=True, learning_rate_init=best_learning_rate) mlp_large.fit(X_train, y_train) print ('\nRESULTS FOR NN\n') #get training and test error for the NN training_error = 1 - mlp_large.score(X_train, y_train) test_error = 1 - mlp_large.score(X_test, y_test) print ("NN training error: %f" % training_error) print ("NN test error: %f" % test_error) fig, ax = plt.subplots(figsize=(10, 10)) ax.plot(mlp.loss_curve_) ax.set_xlabel('n_iter') ax.set_ylabel('loss') plt.show() ``` ## QUESTION 4 Compare the train and test error you got with a large number of samples with the best one you obtained with only 600 data points. Comment about the results you obtained. #### [ANSWER TO QUESTION 4] While the training error for both is 0, the test error, as we expected, is better using more samples for training ( 0.26 vs 0.16 ). Looking at the plots the behaviours seem very similar and I don't detect any important difference. ### TO DO 7 Plot an example that was missclassified by NN with m=600 training data points and it is now instead correctly classified by NN with m=4000 training data points. ``` NN_prediction = mlp.predict(X_test) large_NN_prediction = mlp_large.predict(X_test) counter = 0 for index, input, prediction_large, prediction, label in zip(range(len(X_test)), X_test, large_NN_prediction, NN_prediction, y_test): if prediction != label and prediction_large == label: #print('input,',input, ', has been classified as', predictionLR, 'by the Logistic Regression and should be', label) plot_input(X_test, y_test, index) print('Index:', index) print("Large NN prediction: ", large_NN_prediction[index]) print("NN prediction: ", NN_prediction[index]) counter += 1 if counter > 5: break ``` ### TO DO 8 Let's plot the weigths of the multi-layer perceptron classifier, for the best NN we get with 600 data points and with 4000 data points. The code is already provided, just fix variable names (e.g., replace mlp , mlp_large with your estimators) in order to have it working with your implementation ``` print("Weights with 600 data points:") fig, axes = plt.subplots(4, 4, figsize=(10,10)) vmin, vmax = mlp.coefs_[0].min(), mlp.coefs_[0].max() for coef, ax in zip(mlp.coefs_[0].T, axes.ravel()): ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin, vmax=.5 * vmax) ax.set_xticks(()) ax.set_yticks(()) plt.show() print("Weights with 5000 data points:") fig, axes = plt.subplots(4, 4, figsize=(10,10)) vmin, vmax = mlp_large.coefs_[0].min(), mlp_large.coefs_[0].max() for coef, ax in zip(mlp_large.coefs_[0].T, axes.ravel()): ax.matshow(coef.reshape(28, 28), cmap=plt.cm.gray, vmin=.5 * vmin, vmax=.5 * vmax) ax.set_xticks(()) ax.set_yticks(()) plt.show() ``` ## QUESTION 5 Describe what do you observe by looking at the weights. ##### [ANSWER TO QUESTION 5] Looking at the weights one can recognize some pattern of the japanese characters we are studying, while in others at naked eye one can't detect anything other than random noise. In particular, comparing the two plots one can guess what the algorithm is trying to do: removing the random noise for having a more recognizable picture. ### TO DO 9 Take the best SVM model and its parameters, you found in the last notebook. Fit it on a few data points and compute its training and test scores. Then fit also a logistic regression model with C=1. ``` m_training = 5000 X_train, X_test = X[:m_training], X[m_training:]#2*m_training] y_train, y_test = y[:m_training], y[m_training:]#2*m_training] # use best parameters found in the SVM notebook, create SVM and perform fitting C_best = 10 gamma_best = 0.01 SVM = SVC(kernel = 'rbf', C = C_best, gamma = gamma_best) SVM.fit(X_train, y_train) print ('RESULTS FOR SVM') SVM_training_error = 1 - SVM.score(X_train, y_train) print("Training score SVM:") print(SVM_training_error) SVM_test_error = 1 - SVM.score(X_test, y_test ) print("Test score SVM:") print(SVM_test_error) from sklearn import linear_model regL2 = linear_model.LogisticRegression(C=1, max_iter=4000) regL2.fit(X_train, y_train) # you can re-use your code from Lab 2 print ('\nRESULTS FOR LOGISTIC REGRESSION WITH REGULARIZATION') training_error = 1-regL2.score(X_train, y_train) test_error = 1 - regL2.score(X_test, y_test) print ("Training error (reg): %f" % training_error) print ("Test error (reg): %f" % test_error) ``` ## QUESTION 6 Compare the results of Logistic Regression, SVM and NN. Which one achieve the best results? ###### [ANSWER TO QUESTION 6] As one can see comparing the test errors, the best results are provided by the SVM method, followed by NN and the logistic regression. This behaviour is what we expected since the NN works better than the other methods growing the complexity, with deep learning. We can see the behaviour for each character comparing the confusion matrixes in the plot provided at the end of this notebook. ``` LR_prediction = regL2.predict(X_test) SVM_prediction = SVM.predict(X_test) from sklearn.metrics import confusion_matrix np.set_printoptions(precision=2, suppress=True) # for better aligned printing of confusion matrix use floatmode='fixed' u, counts = np.unique(y_test, return_counts=True) print("Labels and frequencies in test set: ", counts) confusion_LNN = confusion_matrix(y_test, large_NN_prediction) print("\n Confusion matrix Large NN\n\n", confusion_LNN) print("\n Confusion matrix Large NN (normalized)\n\n", confusion_LNN /counts[:,None] ) confusion_LNN_n = confusion_matrix(y_test, large_NN_prediction, normalize='true') print("\n Confusion matrix Large NN (normalized directly)\n\n", confusion_LNN_n) confusion_NN = confusion_matrix(y_test, NN_prediction) print("\n Confusion matrix NN\n\n", confusion_NN) print("\n Confusion matrix NN (normalized)\n\n", confusion_NN /counts[:,None] ) confusion_NN_n = confusion_matrix(y_test, NN_prediction, normalize='true') print("\n Confusion matrix NN (normalized directly)\n\n", confusion_NN_n ) confusion_SVM = confusion_matrix(y_test, SVM_prediction) print("\n Confusion matrix SVM\n\n", confusion_SVM) print("\n Confusion matrix SVM (normalized)\n\n", confusion_SVM /counts[:,None] ) confusion_SVM_n = confusion_matrix(y_test, SVM_prediction, normalize='true') print("\n Confusion matrix SVM (normalized directly)\n\n", confusion_SVM_n) confusion_LR = confusion_matrix(y_test, LR_prediction) print("\n Confusion matrix LR\n\n", confusion_LR) print("\n Confusion matrix LR (normalized)\n\n", confusion_LR /counts[:,None] ) confusion_LR_n = confusion_matrix(y_test, LR_prediction, normalize='true') print("\n Confusion matrix LR (normalized directly)\n\n", confusion_LR_n ) import seaborn as sn fig, axs = plt.subplots(nrows = 3, ncols = 1, sharey=True, sharex=True, figsize = (10,30)) plt.rcParams['font.size'] = '13' axs[0].tick_params(axis='both', labelsize=3) axs[1].tick_params(axis='both', labelsize=3) axs[2].tick_params(axis='both', labelsize=3) axs[0].set_title('SVM', fontsize=17) axs[1].set_title( 'LR', fontsize=17) axs[2].set_title( 'NN', fontsize=17) axs[0].tick_params(axis = "x", which = "both", bottom = False, top = False) axs[1].tick_params(axis = "x", which = "both", bottom = False, top = False) axs[2].tick_params(axis = "x", which = "both", bottom = False, top = False) axs[0].tick_params(axis = "y", which = "both", right = False, left = False) axs[1].tick_params(axis = "y", which = "both", right = False, left = False) axs[2].tick_params(axis = "y", which = "both", right = False, left = False) df_cm = pd.DataFrame(confusion_SVM_n, index = [i for i in u], columns = [i for i in u]) sn.heatmap(df_cm, annot=True, cmap="Blues", ax = axs[0]) df_cm = pd.DataFrame(confusion_LR_n, index = [i for i in u], columns = [i for i in u]) sn.heatmap(df_cm, annot=True, cmap="Greens", ax = axs[1]) df_cm = pd.DataFrame(confusion_LNN_n, index = [i for i in u], columns = [i for i in u]) sn.heatmap(df_cm, annot=True, cmap="Greys", ax = axs[2]) plt.tight_layout() plt.show() ```
github_jupyter
``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import tensorflow as tf import numpy as np import matplotlib.pyplot as plt print(tf.__version__) def plot_series(time, series, format="-", start=0, end=None): plt.plot(time[start:end], series[start:end], format) plt.xlabel("Time") plt.ylabel("Value") plt.grid(False) def trend(time, slope=0): return slope * time def seasonal_pattern(season_time): """Just an arbitrary pattern, you can change it if you wish""" return np.where(season_time < 0.1, np.cos(season_time * # YOUR CODE HERE # * np.pi), #YOUR CODE HERE# / np.exp(#YOUR CODE HERE# * season_time)) def seasonality(time, period, amplitude=1, phase=0): """Repeats the same pattern at each period""" season_time = ((time + phase) % period) / period return amplitude * seasonal_pattern(season_time) def noise(time, noise_level=1, seed=None): rnd = np.random.RandomState(seed) return rnd.randn(len(time)) * noise_level time = np.arange(10 * 365 + 1, dtype="float32") baseline = # YOUR CODE HERE # series = trend(time, # YOUR CODE HERE#) baseline = 10 amplitude = 40 slope = # YOUR CODE HERE# noise_level = # YOUR CODE HERE# # Create the series series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude) # Update with noise series += noise(time, noise_level, seed=51) split_time = 3000 time_train = time[:split_time] x_train = series[:split_time] time_valid = time[split_time:] x_valid = series[split_time:] window_size = 20 batch_size = 32 shuffle_buffer_size = 1000 plot_series(time, series) ``` Desired output -- a chart that looks like this: ![Chart showing upward trend and seasonailty](http://www.laurencemoroney.com/wp-content/uploads/2019/07/plot1.png) ``` def windowed_dataset(series, window_size, batch_size, shuffle_buffer): dataset = tf.data.Dataset.from_tensor_slices(series) dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(window_size + 1)) dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1])) dataset = dataset.batch(batch_size).prefetch(1) return dataset dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size) model = tf.keras.models.Sequential([ tf.keras.layers.Dense(# YOUR CODE HERE #), tf.keras.layers.Dense(# YOUR CODE HERE #, activation="relu"), tf.keras.layers.Dense(1) ]) model.compile(loss=# YOUR CODE HERE #, optimizer=# YOUR CODE HERE#)) model.fit(dataset,epochs=100,verbose=0) forecast = [] for time in range(len(series) - window_size): forecast.append(model.predict(series[time:time + window_size][np.newaxis])) forecast = forecast[split_time-window_size:] results = np.array(forecast)[:, 0, 0] plt.figure(figsize=(10, 6)) plot_series(time_valid, x_valid) plot_series(time_valid, results) tf.keras.metrics.mean_absolute_error(x_valid, results).numpy() # EXPECTED OUTPUT # A Value less than 3 ```
github_jupyter
# Application of Least-Squares Fitting ## the (x,y) $\rightarrow$ (R.A., Dec.) transform ![](media/xyrd.png) ### Prof. Robert Quimby &copy; 2019 Robert Quimby ## In this tutorial you will... - Learn about one way to map points on the Celestial Sphere onto a plane - Write down a simple linear transform from $(x, y)$ to (R.A., Dec.) - Match the $(x, y)$ positions of a few stars to (R.A., Dec.) positions - Find the best fitting model parameters (in the least-squares sense) - Use the best-fit solution to predict the (R.A., Dec.) positions of other stars ## Load the `example.fits` image ``` # Launch DS9 import pyds9 ds9 = pyds9.DS9() # display the example image in ds9 ds9.set('file media/example.fits') ds9.set('scale zscale') ``` ## Projecting the Celestial Sphere onto a plane * note that this image lacks WCS info, so there is no RA, DEC in ds9 ![](https://www.researchgate.net/profile/Anuj_Srivastava5/publication/232230519/figure/fig3/AS:341657951195157@1458469011236/Projection-from-the-unit-sphere-S-to-the-tangent-space-T-id-v-i-blue-dot-is-the.png) * How do we map the curved celestial sphere onto a the (x, y) plane? * There are many choices. A good option, especially when we only care about a small patch on the celestial sphere, is to use a [gnomonic projection](https://en.wikipedia.org/wiki/Gnomonic_projection). * In astronomy, we call this the TAN projection, because we are projecting the celestial coordinates on to a plane that is tangent to a single point on the celestial sphere. * This tangent point is sometimes called the reference point ### Start with the coordinates of the reference point * on the Celestial Sphere: $(R_0, D_0)$ * on the tangent plane: $(x_0, y_0)$ ### Moving away from the reference point * if we move from $(R_0, D_0) \rightarrow (R_i, D_i)$ * we also move from $(x_0, y_0) \rightarrow (x_i, y_i)$ * so we need relations between $R_i$ and $x_i$ (and $y_i$), and $D_i$ and $y_i$ (and $x_i$) ### We can express the coordinate transformation from (x, y) to (R.A., Dec.) as $$ R_i = R_0 + a(x_i - x_0) + b(y_i - y_0) $$ $$ D_i = D_0 + c(x_i - x_0) + d(y_i - y_0) $$ * If we pick $(x_0, y_0)$ on our image, we are left with 6 unknowns * We must solve for these to determine our "plate solution" ## We can solve for all 6 parameters at once $$ R_i = R_0 + a(x_i - x_0) + b(y_i - y_0) $$ $$ D_i = D_0 + c(x_i - x_0) + d(y_i - y_0) $$ Express the equations above in the form $Y = Xp$ $$ \left[ \begin{array}{c} R_1 \\ \vdots \\ R_N \\ D_1 \\ \vdots \\ D_N \end{array} \right] = \left[ \begin{array}{cccccc} 1 & (x_1-x_0) & (y_1-y_0) & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\ 1 & (x_N-x_0) & (y_N-y_0) & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & (x_1-x_0) & (y_1-y_0) \\ \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & 1 & (x_N-x_0) & (y_N-y_0) \end{array} \right] \left[ \begin{array}{c} R_0 \\ a \\ b \\ D_0 \\ c \\ d \end{array} \right] $$ ## Match `example.fits` objects to a POSS image (with astrometry) Load the POSS image into a new frame: * "Analysis" --> "Image Servers" --> "DSS (STSCI)" * use the R.A. and Dec. from the `example.fits` header ### Need the (x, y) position for a stars with known (R.A., Dec.) * put green circles around a few stars on the MLO image * "Region" --> "Save Regions..." * save the "Physical" data in "X Y" format as "ds9.xy" * put green circles around the same stars in the POSS image * "Region" --> "Save Regions..." * save the "fk5" data in "X Y" format **and in degrees** as "ds9.rd" ## Solve for the Plate Solution Using Python ### Step 1: load the data into pyton ``` # load the (x, y) and (RA, Dec.) data import numpy as np xydata = np.genfromtxt('media/example.xy.reg', names='x, y') rddata = np.genfromtxt('media/example.rd.reg', names='ra, dec') # define the tangent point in x, y x0, y0 = ???? print(x0, y0) ``` ### Step 2: build the $Y$ and $X$ matricies ``` # function to set up the Y matrix def get_Y_matrix(ras, decs): Y = [] for ra in ras: Y.append(????) for dec in decs: Y.append(????) return np.matrix(Y) Y = get_Y_matrix(????) # function to set up the X matrix def get_X_matrix(dxs, dys): X = [] for dx, dy in zip(dxs, dys): X.append(????) for dx, dy in zip(dxs, dys): X.append(????) return np.matrix(X) X = get_X_matrix(????) ``` ### Step 3: solve for $p$ ``` # fit using least-squares p = ???? ``` ## Use the solution to find the R.A., Dec. of another star ``` xs = [????] ys = [????] X = get_X_matrix(xs, ys) ???? ```
github_jupyter
``` import sys import os.path as op sys.path.append('..') import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d import geopandas as gpd import parkingadvisor as pa DATA = op.join(pa.__path__[0], 'data') RAW_DATA = op.join(pa.__path__[0], 'data', 'raw_data') ``` # 1. Clean Annual_Parking_Data Read a .csv file as a DataFrame with specific columns and drop the columns containing missing data. ``` # import "Annual_Parking_Study_Data" to creat 'pkdt' dataframe # read data col_names = ['Date Time', 'Unitdesc', 'Side', 'Parking_Spaces', 'Total_Vehicle_Count', 'Construction', 'Event Closure'] pkdt = pa.read_data(RAW_DATA + '\Annual_Parking_Study_Data.csv', col_names) pkdt = pkdt.dropna() pkdt.head(10) ``` Drop the exceptions under construction and event closure. ``` #filter the data with 'Construction' and 'Event' column are "No" values = ['Yes', 'yes', 'ERROR: #N/A'] pkdt = pa.data_filter(pkdt, 'Construction', values) pkdt = pa.data_filter(pkdt, 'Event Closure', ['Yes']) pkdt = pa.data_filter(pkdt, 'Parking_Spaces',[0]) pkdt = pkdt.drop('Construction', axis = 1) pkdt = pkdt.drop('Event Closure', axis = 1) ``` Calculate the average occupancy of each street per hour of the day ``` #group rows with same 'Time' and 'Unitdesc', for other columns, find the sum pkdt = pkdt.groupby(['Date Time', 'Unitdesc'], as_index = False)['Parking_Spaces', 'Total_Vehicle_Count'].sum() pkdt.head(10) #find the occupancy and append it to the pkdt Occupancy = np.minimum(pkdt['Total_Vehicle_Count'] / pkdt['Parking_Spaces'], 1) pkdt['Occupancy'] = Occupancy pkdt = pkdt.dropna() pkdt = pkdt.drop('Total_Vehicle_Count', axis = 1) ``` Convert time `String` into `Datetime` ``` #retrivev 'hour' column from general datetime pkdt['Date Time'] = pd.to_datetime(pkdt['Date Time'], format = '%m-%d-%y %H:%M:%S') times = pd.DatetimeIndex(pkdt['Date Time']) pkdt['Hour'] = times.hour #for 'Hour' column, replace 0 with 24 pkdt = pkdt.replace({'Hour': 0}, 24) pkdt.head(10) #group data by 'hour' and 'Unidesc' and average other columns pkdt = pkdt.groupby(['Hour', 'Unitdesc'], as_index = False)['Parking_Spaces', 'Occupancy'].mean() pkdt.head(10) ``` Get the prelim streets flow datafile. ``` # Rename the column names to all_capital aps = pkdt.rename(index=str, columns={"Hour": "HOUR", "Unitdesc": "UNITDESC", 'Parking_Spaces':"PARKING_SPACE", 'Occupancy': "OCCUPANCY"}) ``` # 2. Clean blockface Make a subset of blockface.csv containing only the streets in Annual_Parking_Study.csv ``` #import "Blockface" to creat 'bfdt' dataframe #read data col_names = ['UNITDESC','WKD_RATE1','WKD_START1', 'WKD_END1', 'WKD_RATE2', 'WKD_START2', 'WKD_END2', 'WKD_RATE3', 'WKD_START3', 'WKD_END3', 'SAT_RATE1', 'SAT_START1', 'SAT_END1', 'SAT_RATE2', 'SAT_START2', 'SAT_END2', 'SAT_RATE3', 'SAT_START3', 'SAT_END3', 'PARKING_TIME_LIMIT'] bfdt = pa.read_data(RAW_DATA + '\Blockface.csv', col_names) bfdt.head(10) ``` Change all end time to correct format, i.e. 1199 --> 1200 ``` end_col = ['WKD_END1', 'WKD_END2', 'WKD_END3', 'SAT_END1', 'SAT_END2', 'SAT_END3'] # modify the end time of all rates pa.modify_end_time(bfdt, end_col) bfdt.head(10) # group rows by same 'UNITDESC', average other columns bfdt = bfdt.groupby(['UNITDESC'], as_index = False).mean() # convert minutes to datetime col_names = ['WKD_START1', 'WKD_END1', 'WKD_START2', 'WKD_END2', 'WKD_START3', 'WKD_END3', 'SAT_START1', 'SAT_END1', 'SAT_START2', 'SAT_END2', 'SAT_START3', 'SAT_END3'] pa.convert_datetime_to_h(bfdt, col_names) bfdt.head() # select the blockface only including in APS dataset bfdt_only_APS = pa.subset([bfdt, 'UNITDESC'], [aps, 'UNITDESC']) ``` Read the dataset we got in step 1. Compare the number of streets. ``` # The number of streets in APS print('============BEDORE===========') print('Streets in APS: {}\nStreets in Blockface: {}'.format(len(aps.UNITDESC.unique()), len(bfdt_only_APS.UNITDESC.unique()))) ``` Some streets are not included in Blockface.csv Drop these from APS file. ``` # Save the subset as .csv file # bfdt_only_APS.to_csv(DATA + '\Rate_limit.csv') aps = pa.subset([aps, 'UNITDESC'], [bfdt_only_APS, 'UNITDESC']) # Check the number of streets print('============AFTER===========') print('Streets in APS: {}\nStreets in Blockface: {}'.format(len(aps.UNITDESC.unique()),len(bfdt_only_APS.UNITDESC.unique()))) # Save the final occupancy file. # aps.to_csv(DATA + '\occupancy_per_hour.csv') ``` # 3. Clean Streets GIS file Make a subset of the streets only containing in above files. ``` # Read the gis data of Seattle streets data = gpd.read_file(RAW_DATA + '\Seattle_Streets\Seattle_Streets.shp') # Filter the gis data by parking study street_geo = pa.subset([data,'UNITDESC'], [aps, 'UNITDESC']) # Save the dataframe as a GeoJSON file # pa.convert_to_geojson(street_geo, DATA + '\Streets_gis.json') ```
github_jupyter
``` import pandas as pd import numpy as np import gensim import gensim.corpora as corpora from gensim.utils import simple_preprocess from gensim.models import CoherenceModel !pip install pyLDAvis import pyLDAvis import pyLDAvis.gensim import matplotlib.pyplot as plt import re import spacy from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/BE/Sem 8/ML/IA-2/emails.csv' emails = pd.read_csv(path) emails.head() emails.shape # email_subset = emails email_subset = emails[:50000] print(email_subset.shape) print(email_subset.head()) def parse_into_emails(messages): emails = [parse_raw_message(message) for message in messages] return { 'body': map_to_list(emails, 'body'), 'to': map_to_list(emails, 'to'), 'from_': map_to_list(emails, 'from') } # cleaning def parse_raw_message(raw_message): lines = raw_message.split('\n') email = {} message = '' keys_to_extract = ['from', 'to'] for line in lines: if ':' not in line: message += line.strip() email['body'] = message else: pairs = line.split(':') key = pairs[0].lower() val = pairs[1].strip() if key in keys_to_extract: email[key] = val return email def map_to_list(emails, key): results = [] for email in emails: if key not in email: results.append('') else: results.append(email[key]) return results email_df = pd.DataFrame(parse_into_emails(email_subset.message)) print(email_df.head()) email_df.shape import nltk nltk.download('stopwords') from nltk.corpus import stopwords stop_words = stopwords.words('english') stop_words.extend(['from', 'subject', 're', 'edu', 'use']) print(email_df.iloc[1]['body']) data = email_df.body.values.tolist() type(data) def sent_to_words(sentences): for sentence in sentences: yield(gensim.utils.simple_preprocess(str(sentence), deacc=True)) # deacc=True removes punctuations data_words = list(sent_to_words(data)) print(data_words[3]) from gensim.models.phrases import Phrases, Phraser # Build the bigram and trigram models bigram = Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases. trigram = Phrases(bigram[data_words], threshold=100) bigram_mod = Phraser(bigram) trigram_mod = Phraser(trigram) print(trigram_mod[bigram_mod[data_words[200]]]) def remove_stopwords(texts): return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts] def make_bigrams(texts): return [bigram_mod[doc] for doc in texts] def make_trigrams(texts): return [trigram_mod[bigram_mod[doc]] for doc in texts] def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']): """https://spacy.io/api/annotation""" texts_out = [] for sent in texts: doc = nlp(" ".join(sent)) texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags]) return texts_out data_words_nostops = remove_stopwords(data_words) data_words_bigrams = make_bigrams(data_words_nostops) nlp = spacy.load('en', disable=['parser', 'ner']) data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']) print(data_lemmatized[200]) # create dictionary and corpus both are needed for (LDA) topic modeling # Create Dictionary id2word = corpora.Dictionary(data_lemmatized) # Create Corpus texts = data_lemmatized # Term Document Frequency corpus = [id2word.doc2bow(text) for text in texts] import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) # Build LDA model lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=20, random_state=100, update_every=1, chunksize=100, passes=10, alpha='auto', per_word_topics=True) print(lda_model.print_topics()) ```
github_jupyter
# <center> Visualizations with pandas, part 2 </center> ### By the end of this lecture, you will be able to - visualize column pair where both columns are continuous - visualize column pair where both columns are categorical - visualize multiple columns simultaneously ## <center> Overview </center> | *Visualization types* | column continuous | column categorical | |--------------------- |:----------------------: |:-----------------: | | __column continuous__ | scatter plot, heatmap | category-specific histograms, box plot, violin plot | | __column categorical__ | category-specific histograms, box plot, violin plot | stacked bar plot | ``` import pandas as pd import numpy as np import matplotlib from matplotlib import pylab as plt df = pd.read_csv('data/adult_data.csv') print(df.columns) print(df.dtypes) ``` ### Continuous vs. continuous columns - scatter plot ``` df.plot.scatter('age','hours-per-week') plt.show() ``` ### Continuous vs. continuous columns - heatmap ``` nbins = 20 heatmap, xedges, yedges = np.histogram2d(df['age'], df['hours-per-week'], bins=nbins) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] heatmap[heatmap == 0] = 0.1 # this gets rid of division by 0 in the next line plt.imshow(np.log10(heatmap).T, origin='lower',vmin=0,vmax=3) # use log count plt.xlabel('age') plt.ylabel('hours-per-week') plt.xticks(np.arange(nbins)[::int(nbins/4)],xedges[np.arange(nbins)[::int(nbins/4)]]) plt.yticks(np.arange(nbins)[::int(nbins/4)],yedges[np.arange(nbins)[::int(nbins/4)]]) plt.colorbar(label='log10(count)') plt.show() ``` ## Exercise 1 Create a scatter plot and a heat map using the hours-per-week and the education-num columns. ### Categorical vs. categorical columns - stacked bar plot ``` count_matrix = df.groupby(['race', 'gross-income']).size().unstack() #print(count_matrix) count_matrix_norm = count_matrix.div(count_matrix.sum(axis=1),axis=0) print(count_matrix_norm) count_matrix_norm.plot(kind='bar', stacked=True) plt.ylabel('fraction of people in group') plt.legend(loc=4) plt.show() ``` ## Exercise 2 Create a stacked bar plot using the sex and the gross-income columns. ### <font color='LIGHTGRAY'>By the end of this talk, you will be able to</font> - <font color='LIGHTGRAY'>visualize one column (categorical or continuous data)</font> - <font color='LIGHTGRAY'>visualize column pairs (all variations of continuous and categorical columns)</font> - **visualize multiple columns simultaneously** #### Scatter matrix ``` pd.plotting.scatter_matrix(df.select_dtypes(int), figsize=(7, 7), marker='o',hist_kwds={'bins': 10}, s=10, alpha=.1) plt.show() pd.plotting.scatter_matrix(df.select_dtypes(int), figsize=(7, 7),c = pd.get_dummies(df['gross-income']).iloc[:,1], marker='o',hist_kwds={'bins': 10}, s=10, alpha=.4) plt.show() ```
github_jupyter
# Action-independend Heuristic Dynamic Programming, Model-based #### Import dependencies & Custom classes ``` # General imports import numpy as np import pandas as pd import gym import os import datetime from tqdm import tqdm # Plot library import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [24, 4] %matplotlib inline # Custom classes %cd pathlib.Path().resolve().parents[2] %load_ext autoreload import envs.shortperiod from utils.pid import PID ``` #### Flags & Simulation Parameters and Data Storage ``` %autoreload # Flags LOG = True SAVE = True # Locations TENSORBOARD_DIR = './logs/tensorboard/' CHECKPOINT_DIR = './logs/checkpoint/' # Simulation parameters env = gym.make('ShortPeriod-v0') dt, env.dt = 2*(1/100,) # [s] - Time step T = 120. # [s] - Episode Length t = np.arange(0, T, dt) # [s] - Time vector time_steps = len(t) # [-] - Number of timesteps pid_controller = PID(Kp = -12.0, Ki = -1.0, Kd = 0.0, dt = dt) # Data storage data = pd.DataFrame({ 'State': [np.zeros(2)]*time_steps, 'Action': [0.]*time_steps, 'Cost': [0.]*time_steps, 'Next State':[np.zeros(2)]*time_steps, 'Reference Pitch Rate': [0.]*time_steps, 'Error': [0.]*time_steps }) # Prepare training reference_signal = 10./180.*np.pi*np.sin(1/10*np.pi*t) #ReferenceSignalGenerator('sine', amplitude = 0.15, speed = 1.0, offset = 0.0) ``` #### Run training ``` %autoreload # Set run time run_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') # Initialize lists state, action, cost, error = ([] for i in range(4)) # Reset environment state.append(env.reset()) u = np.zeros(1) for i in tqdm(range(len(t))): # Sample reference signal and create augmented state ref_q = reference_signal[i] error.append(ref_q - state[i][2]) # Run environment u = pid_controller(error[i]) action.append(u) X, R, _, _ = env.step(action[i], ref_q) state.append(X) cost.append(R) # Save data to Pandas.DataFrame data['State'] = state[:-1] data['Action'] = action data['Cost'] = cost data['Next State'] = state[1:] data['Reference Pitch Rate'] = reference_signal data['Error'] = error if SAVE: data.to_pickle('./logs/data/dataframe_pid_'+ run_time +'.pkl') db_csv = pd.DataFrame(columns=['alpha', 'theta', 'q', 'q_ref', 'action', 'cost']) db_csv['alpha'] = np.vstack(data['State'].values)[:,0] db_csv['theta'] = np.vstack(data['State'].values)[:,1] db_csv['q'] = np.vstack(data['State'].values)[:,2] db_csv['q_ref'] = data['Reference Pitch Rate'] db_csv['action'] = np.vstack(data['Action']) db_csv['cost'] = data['Cost'] db_csv.to_csv('./logs/data/csv/dataframe_pid_'+ run_time +'.csv') ``` ## Visualizations #### Action ``` # Plot action u = data['Action'].values plt.plot(t, u/np.pi*180., 'r-', label=r'$\delta_{e}$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$\delta{e}\ [deg]$') plt.legend() if SAVE and os.getcwd() == '/home/dave992/JupyterServer/ms-thesis': if not os.path.exists('./logs/figures/hdp_' + run_time + '/'): os.makedirs('./logs/figures/hdp_' + run_time + '/') if not os.path.isfile('./logs/figures/hdp_' + run_time + '/elevator.png'): plt.savefig('./logs/figures/hdp_' + run_time + '/elevator.png') plt.show() ``` #### Pitch rate (and reference) ``` # Plot pitch rate and reference state = np.vstack(data['State'].values) error = data['Error'].values plt.plot(t, 180/np.pi*state[:,2], 'r-', label=r'$q$') plt.plot(t, 180/np.pi*reference_signal, 'r--', label=r'$q_{ref}$') plt.plot(t, 180/np.pi*error, 'b-', label=r'$E$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$Pitch\ rate\ [deg/s]$') plt.legend() plt.show() ``` #### Current Cost ``` cost = data['Cost'].values plt.plot(t, cost, 'r-', label=r'$r$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$Cost\ [-]$') plt.legend() error = data['Error'].values plt.plot(t, error, 'r-', label=r'$E$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$Error\ [-]$') plt.legend() def avg_error(deg): rad = deg*np.pi/180 return 120*100*(rad**2) y = 7.4 print(avg_error(y)) ``` #### Legacy code ``` 0.0003046174190905562*100*120 %autoreload # Flags LOG = True LOAD = False SAVE = True REPEAT_UPDATE = True RENDER = False # Not working with tqdm progres bar # Locations TENSORBOARD_DIR = './logs/tensorboard/' CHECKPOINT_DIR = './logs/checkpoint/' # Simulation parameters env = gym.make('ShortPeriod-v0') dt, env.dt = 2*(1/100,) # [s] - Time step T = 50. # [s] - Episode Length t = np.arange(0, T, dt) # [s] - Time vector time_steps = len(t) # [-] - Number of timesteps # HDP parameters n_repeat_update = 5 # [-] - Number of repeated updates (if REPEAT_UPDATE, else 1) if LOAD: # Load existing network from checkpoint agent = HDP.Agent(env, load = '') else: # Define network hyperparameters kwargs = { 'input_size': 1, 'output_size': 1, 'hidden_layer_size': [6], 'lr_critic': 0.001, 'lr_actor': 0.0001, 'gamma': 0.8, 'activation': tf.nn.tanh, 'log_dir': TENSORBOARD_DIR, 'session_config': tf.ConfigProto(device_count = {'GPU': 0}) # Run on CPU } agent = HDP.Agent(env, **kwargs) # Data storage data = pd.DataFrame({ 'State': [np.zeros(agent.input_size)]*time_steps, 'Action': [0.]*time_steps, 'Cost': [0.]*time_steps, 'Next State':[np.zeros(agent.input_size)]*time_steps, 'Augmented State': [np.zeros(agent.input_size)]*time_steps, 'Reference Pitch Rate': [0.]*time_steps }) # Prepare training cycles = n_repeat_update if REPEAT_UPDATE else 1 reference_signal = 10./180.*np.pi*np.sin(1/10*np.pi*t) #ReferenceSignalGenerator('sine', amplitude = 0.15, speed = 1.0, offset = 0.0) dxdu = np.array([env.B[2]])*dt %autoreload # Initialize lists state, action, cost, augmented_state = ([] for i in range(4)) # Initialize TensorBoard logging if LOG: run_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') agent.create_tensorboard_writer(TENSORBOARD_DIR + 'tb_hdp_' + run_time) # Reset environment state.append(env.reset()) for i in tqdm(range(len(t))): # Sample reference signal and create augmented state ref_q = reference_signal[i] augmented_state.append(augment_hdp_state(state[i], ref_q)) # Run environment action.append(agent.action(augmented_state[i])) X, R, _, _ = env.step(action[i], ref_q) state.append(X) cost.append(R) # Visualize environment if RENDER: env.render() # Calculate target for critic value_target = cost[i-1] + agent.gamma*agent.value(augmented_state[i]) # Run update cycles, critic then actor for j in range(cycles): # Update critic agent.update_critic(np.array([augmented_state[i-1]]), value_target) # Update Actor agent.update_actor(augmented_state[i], dxdu = dxdu) # Log training data using TensorBoard if LOG: agent.writer.add_summary(agent.summary(augmented_state[i], value_target), i) # Save network every 5% of the training phase if SAVE and i % int(.05*time_steps) == 0: agent.save(file = CHECKPOINT_DIR + 'hdp_cp_' + run_time + '/ckpt', global_step = i) # Save data to Pandas.DataFrame data['State'] = state[:-1] data['Action'] = action data['Cost'] = cost data['Next State'] = state[1:] data['Augmented State'] = augmented_state data['Reference Pitch Rate'] = reference_signal if SAVE: data.to_pickle('./logs/data/dataframe_hdp_'+ run_time +'.pkl') # generate plot q_ref = np.array([_ for _ in reference_signal]) q = np.array([_[2] for _ in state[0:-1]]) # plot control input plt.rcParams['figure.figsize'] = [16, 7] ax = plt.subplot(3,1,1) plt.plot(t, np.array(action).flatten()/np.pi*180., 'r-', label=r'$\delta_{e}$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$\delta{e}\ [deg]$') plt.legend() # plot reference signal plt.subplot(3,1,2,sharex=ax) plt.plot(t, q_ref*180./np.pi, 'r--', label=r'$q_{ref}$') plt.plot(t, q*180./np.pi, 'r-', label=r'$q$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$q\ [\frac{deg}{s}]$') plt.legend() # plot cost history plt.subplot(3,1,3,sharex=ax) plt.plot(t, np.array(cost)*(180./np.pi)**2, 'r-', label=r'$cost$') plt.xlabel(r'$t\ [s]$') plt.ylabel(r'$cost\ [\frac{deg^{2}}{s^{2}}]$') plt.subplots_adjust(hspace=.8) plt.legend() plt.show() ```
github_jupyter
# Vector Ops This tutorial will go over how to use the `--graphblas-lower` pass from `graphblas-opt` to lower some ops from the GraphBLAS dialect that deal with vectors into executable Python code. There are many such ops. We'll focus on `graphblas.reduce_to_scalar` whhen applied to vectors. Since the [ops reference](../../ops_reference.rst) already documents these ops with examples, we'll only briefly describe them here. Letโ€™s first import some necessary modules and generate an instance of our JIT engine. ``` import mlir_graphblas import numpy as np from mlir_graphblas.tools.utils import sparsify_array engine = mlir_graphblas.MlirJitEngine() ``` Here are the passes we'll use. ``` passes = [ "--graphblas-structuralize", "--graphblas-optimize", "--graphblas-lower", "--sparsification", "--sparse-tensor-conversion", "--linalg-bufferize", "--func-bufferize", "--tensor-constant-bufferize", "--tensor-bufferize", "--finalizing-bufferize", "--convert-linalg-to-loops", "--convert-scf-to-std", "--convert-memref-to-llvm", "--convert-openmp-to-llvm", "--convert-std-to-llvm", "--reconcile-unrealized-casts", ] ``` ## Overview of graphblas.reduce_to_scalar Here, we'll show how to use the `graphblas.reduce_to_scalar` op. `graphblas.reduce_to_scalar` reduces a sparse tensor (CSR matrix, CSC matrix, or sparse vector) to a scalar according to the given aggregator. We'll use the "[argmin](https://en.wikipedia.org/wiki/Arg_max#Arg_min)" operator for this example. If there are multiple values that can be the argmin, an arbitrary one is chosen from them. Let's create an example input sparse vector. ``` dense_vector = np.array( [0, 1, 0, -999, 2, 0, 3, 0], dtype=np.int64, ) sparse_vector = sparsify_array(dense_vector, [True]) ``` Here's what some MLIR code using `graphblas.vector_argmin` looks like. ``` mlir_text = """ #CV64 = #sparse_tensor.encoding<{ dimLevelType = [ "compressed" ], pointerBitWidth = 64, indexBitWidth = 64 }> module { func @vector_argmin_wrapper(%vec: tensor<?xi64, #CV64>) -> i64 { %answer = graphblas.reduce_to_scalar %vec { aggregator = "argmin" } : tensor<?xi64, #CV64> to i64 return %answer : i64 } } """ ``` Let's compile it and demonstrate its use. ``` engine.add(mlir_text, passes) argmin = engine.vector_argmin_wrapper(sparse_vector) argmin ``` Let's verify that the behavior is the same as that of [NumPy](https://numpy.org/). ``` argmin == np.argmin(dense_vector) ``` ## Overview of graphblas.equal Here, we'll show how to use the `graphblas.equal` op. `graphblas.equal` performs an equality check. Here's what some MLIR code using `graphblas.equal` looks like when used with vectors. ``` mlir_text = """ #CV64 = #sparse_tensor.encoding<{ dimLevelType = [ "compressed" ], pointerBitWidth = 64, indexBitWidth = 64 }> module { func @vector_eq(%u: tensor<?xi64, #CV64>, %v: tensor<?xi64, #CV64>) -> i1 { %answer = graphblas.equal %u, %v : tensor<?xi64, #CV64>, tensor<?xi64, #CV64> return %answer : i1 } } """ ``` Let's compile it and demonstrate its use. ``` engine.add(mlir_text, passes) ``` Let's create some example inputs. ``` a_dense = np.array([0, 1, 0], dtype=np.int64) b_dense = np.array([9, 9, 9], dtype=np.int64) c_dense = np.array([0, 1, 0], dtype=np.int64) a = sparsify_array(a_dense, [True]) b = sparsify_array(b_dense, [True]) c = sparsify_array(c_dense, [True]) engine.vector_eq(a, b) engine.vector_eq(a, c) ``` Let's verify that the behavior is the same as that of [NumPy](https://numpy.org/).
github_jupyter
<a href="https://colab.research.google.com/github/tirthasheshpatel/Generative-Models/blob/gans/DCGAN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %%shell cd /content FILES=`ls -a` flag=0 for FILE in $FILES do if [[ $FILE == "Generative-Models" ]] then cd $FILE branch=`git rev-parse --abbrev-ref HEAD` if [[ $branch == "gans" ]] then git pull origin $branch else git checkout gans git pull origin gans fi flag=1 break fi done if [[ flag -ne 1 ]] then git clone https://github.com/tirthasheshpatel/Generative-Models.git cd "Generative-Models" git checkout -b gans git pull origin gans fi %env BATCH_SIZE=16 %env IMG_SIZE=256 %env LATENT_DIMS=100 %cd /content/Generative-Models/ %tensorflow_version 1.x import os import functools import tarfile import numpy as np import scipy.io import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf import keras from keras import backend as K import cv2 from gan_utils import download_utils, tqdm_utils, keras_utils, loss_funcs, gan_discriminator, gan_generator, preprocess %matplotlib inline print(tf.__version__) print(keras.__version__) # Start tf session so we can run code. sess = tf.InteractiveSession() # Connect keras to the created session. K.set_session(sess) download_utils.download_flowers_dataset("/content/Generative-Models/data") x_train = preprocess.get_all_filenames("data/102flowers.tgz") y_train = scipy.io.loadmat('data/imagelabels.mat')['labels'][0] - 1 gan_discriminator_model = gan_discriminator.GANDiscriminator() gan_discriminator_loss = loss_funcs.discriminator_loss gan_generator_model = gan_generator.GANGenerator() gan_generator_loss = loss_funcs.generator_loss def sampling(shape): return K.random_normal(shape) sampling = functools.partial(sampling, [int(os.getenv('BATCH_SIZE')), int(os.getenv('LATENT_DIMS'))]) sample = keras.layers.Lambda(lambda x: sampling()) x = keras.Input(batch_shape=[int(os.getenv('BATCH_SIZE')), int(os.getenv('IMG_SIZE')), int(os.getenv('IMG_SIZE')), 3]) true_labels = gan_discriminator_model(x) sampled_z = sample(x) gen_img = gan_generator_model(sampled_z) gen_labels = gan_discriminator_model(gen_img) disc_loss = gan_discriminator_loss(true_labels, gen_labels) gen_loss = gan_generator_loss(gen_labels) gan_discriminator_model = keras.engine.training.Model(x, true_labels) gan_generator_model = keras.engine.training.Model(x, gen_img) gan_discriminator_model.compile( optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.0), loss=lambda *args, **kwargs: disc_loss ) gan_generator_model.compile( optimizer=keras.optimizers.Adam(lr=0.01, beta_1=0.0), loss=lambda *args, **kwargs: gen_loss ) discriminator_filename = 'gan_disc.{0:03d}' generator_filename = 'gan_gen.{0:03d}' last_finished_epoch = None for _ in range(10): # gan_discriminator_model.fit_generator( # preprocess.train_generator(x_train, y_train), # steps_per_epoch=len(x_train) // int(os.getenv('BATCH_SIZE')) // 8, # epochs = 1, # # callbacks=[keras_utils.TqdmProgressCallback(), # # keras_utils.ModelSaveCallback(discriminator_filename.format(_) + '.{0:03d}.hdf5')], # verbose=1, # initial_epoch=last_finished_epoch or 0 # ) gan_generator_model.fit_generator( preprocess.train_generator(x_train, y_train), steps_per_epoch=len(x_train) // int(os.getenv('BATCH_SIZE')) // 16, epochs = 1, # callbacks=[keras_utils.TqdmProgressCallback(), # keras_utils.ModelSaveCallback(generator_filename.format(_) + '.{0:03d}.hdf5')], verbose=1, initial_epoch=last_finished_epoch or 0 ) generated_images = sess.run(gen_img, feed_dict={x: np.random.randn(16, 256, 256, 3)}) plt.imshow(generated_images[9]) labels = sess.run(gen_labels, feed_dict={x: generated_images}) labels ```
github_jupyter
This script loads behavioral mice data (from `biasedChoiceWorld` protocol and, separately, the last three sessions of training) only from mice that pass a given (stricter) training criterion. For the `biasedChoiceWorld` protocol, only sessions achieving the `trained_1b` and `ready4ephysrig` training status are collected. The data are slightly reformatted and saved as `.csv` files. ``` import datajoint as dj dj.config['database.host'] = 'datajoint.internationalbrainlab.org' from ibl_pipeline import subject, acquisition, action, behavior, reference, data from ibl_pipeline.analyses.behavior import PsychResults, SessionTrainingStatus from ibl_pipeline.utils import psychofit as psy from ibl_pipeline.analyses import behavior as behavior_analysis import numpy as np import matplotlib.pyplot as plt import pandas as pd import os myPath = r"C:\Users\Luigi\Documents\GitHub\ibl-changepoint\data" # Write here your data path os.chdir(myPath) # Get list of mice that satisfy given training criteria (stringent trained_1b) # Check query from behavioral paper: # https://github.com/int-brain-lab/paper-behavior/blob/master/paper_behavior_functions.py subj_query = (subject.Subject * subject.SubjectLab * reference.Lab * subject.SubjectProject & 'subject_project = "ibl_neuropixel_brainwide_01"').aggr( (acquisition.Session * behavior_analysis.SessionTrainingStatus()) # & 'training_status="trained_1a" OR training_status="trained_1b"', # & 'training_status="trained_1b" OR training_status="ready4ephysrig"', & 'training_status="trained_1b"', 'subject_nickname', 'sex', 'subject_birth_date', 'institution', date_trained='min(date(session_start_time))') subjects = (subj_query & 'date_trained < "2019-09-30"') mice_names = sorted(subjects.fetch('subject_nickname')) print(mice_names) len(mice_names) sess_train = ((acquisition.Session * behavior_analysis.SessionTrainingStatus) & 'task_protocol LIKE "%training%"' & 'session_start_time < "2020-09-30"') sess_stable = ((acquisition.Session * behavior_analysis.SessionTrainingStatus) & 'task_protocol LIKE "%biased%"' & 'session_start_time < "2020-09-30"' & ('training_status="trained_1b" OR training_status="ready4ephysrig"')) stable_mice_names = list() # Perform at least this number of sessions MinSessionNumber = 4 def get_mouse_data(df): position_deg = 35. # Stimuli appear at +/- 35 degrees # Create new dataframe datamat = pd.DataFrame() datamat['trial_num'] = df['trial_id'] datamat['session_num'] = np.cumsum(df['trial_id'] == 1) datamat['stim_probability_left'] = df['trial_stim_prob_left'] signed_contrast = df['trial_stim_contrast_right'] - df['trial_stim_contrast_left'] datamat['contrast'] = np.abs(signed_contrast) datamat['position'] = np.sign(signed_contrast)*position_deg datamat['response_choice'] = df['trial_response_choice'] datamat.loc[df['trial_response_choice'] == 'CCW','response_choice'] = 1 datamat.loc[df['trial_response_choice'] == 'CW','response_choice'] = -1 datamat.loc[df['trial_response_choice'] == 'No Go','response_choice'] = 0 datamat['trial_correct'] = np.double(df['trial_feedback_type']==1) datamat['reaction_time'] = df['trial_response_time'] - df['trial_stim_on_time'] # double-check # Since some trials have zero contrast, need to compute the alleged position separately datamat.loc[(datamat['trial_correct'] == 1) & (signed_contrast == 0),'position'] = \ datamat.loc[(datamat['trial_correct'] == 1) & (signed_contrast == 0),'response_choice']*position_deg datamat.loc[(datamat['trial_correct'] == 0) & (signed_contrast == 0),'position'] = \ datamat.loc[(datamat['trial_correct'] == 0) & (signed_contrast == 0),'response_choice']*(-position_deg) return datamat # Loop over all mice for mouse_nickname in mice_names: mouse_subject = {'subject_nickname': mouse_nickname} # Get mouse data for biased sessions behavior_stable = (behavior.TrialSet.Trial & (subject.Subject & mouse_subject)) \ * sess_stable.proj('session_uuid','task_protocol','session_start_time','training_status') * subject.Subject.proj('subject_nickname') \ * subject.SubjectLab.proj('lab_name') df = pd.DataFrame(behavior_stable.fetch(order_by='subject_nickname, session_start_time, trial_id', as_dict=True)) if len(df) > 0: # The mouse has performed in at least one stable session with biased blocks datamat = get_mouse_data(df) # Take mice that have performed a minimum number of sessions if np.max(datamat['session_num']) >= MinSessionNumber: # Should add 'N' to mice names that start with numbers? # Save dataframe to CSV file filename = mouse_nickname + '.csv' datamat.to_csv(filename,index=False) stable_mice_names.append(mouse_nickname) # Get mouse last sessions of training data behavior_train = (behavior.TrialSet.Trial & (subject.Subject & mouse_subject)) \ * sess_train.proj('session_uuid','task_protocol','session_start_time') * subject.Subject.proj('subject_nickname') \ * subject.SubjectLab.proj('lab_name') df_train = pd.DataFrame(behavior_train.fetch(order_by='subject_nickname, session_start_time, trial_id', as_dict=True)) datamat_train = get_mouse_data(df_train) Nlast = np.max(datamat_train['session_num']) - 3 datamat_final = datamat_train[datamat_train['session_num'] > Nlast] # Save final training dataframe to CSV file filename = mouse_nickname + '_endtrain.csv' datamat_final.to_csv(filename,index=False) print(stable_mice_names) ss = (((acquisition.Session * behavior_analysis.SessionTrainingStatus) & 'task_protocol LIKE "%biased%"' & 'session_start_time < "2019-09-30"' & ('training_status="trained_1b" OR training_status="ready4ephysrig"')) * subject.Subject) & ('subject_nickname = "ibl_witten_07"') ss len(stable_mice_names) ```
github_jupyter
# Exemple de notebook avec Python ## Explications Le kernel Python est installรฉ par dรฉfaut avec Jupyter. ## Exemples ``` print("Ceci est du code Python") import sys print(sys.version) ``` ### Fonction factorielle Pour calculer la fonction $n! := 1 \times 2 \times \dots \times n$ ($n\in\mathbb{N}$), on peut penser ร  une solution rรฉcursive (qui coutera en espace mรฉmoire ร  cause de la pile d'appel) et une solution impรฉrative. ``` def fact(n: int) -> int: # note: ces indications de type sont optionnelles, mais apprรฉciรฉes """ Factorielle de n, n! = 1 * 2 * .. * n.""" if n <= 1: return 1 else: return n * fact(n-1) ``` Note : ces commentaires "docstring" entre """ trois guillements""" sont optionnels mais appรฉcies, car cela donne une documentation ร  chaque fonction : ``` help(fact) # depuis une console Python normale # depuis IPython ou Jupyter fact? ``` Exemples : ``` for i in range(1, 23): print(f"fact({i:2}) = {fact(i)}") ``` Et la solution impรฉrative : ``` def fact_imp(n: int) -> int: """ Factorielle de n, n! = 1 * 2 * .. * n.""" f: int = 1 for i in range(2, n+1): f = f * i # f *= i est aussi possible return f for i in range(1, 23): print(f"fact_imp({i:2}) = {fact_imp(i)}") ``` ### Figures avec TikZ Voir <https://github.com/jbn/itikz> ``` %load_ext itikz %%itikz --file-prefix tikz-figures-from-Python- --implicit-pic \draw[help lines] grid (5, 5); \draw[fill=black!50] (1, 1) rectangle (2, 2); \draw[fill=black!50] (2, 1) rectangle (3, 2); \draw[fill=black!50] (3, 1) rectangle (4, 2); \draw[fill=black!50] (3, 2) rectangle (4, 3); \draw[fill=black!50] (2, 3) rectangle (3, 4); %%itikz --file-prefix tikz-figures-from-Python- --implicit-pic --scale=0.4 \tikzstyle{vertexcover} = [circle,fill=green,draw]; \tikzstyle{matching} = [ draw=blue!55, line width=5]; \tikzstyle{matchingN} = [ draw=green!55, line width=5]; \tikzstyle{vertex} = [circle,fill=none,draw]; \node[vertex] (v2) at (0,0) {}; \node[vertexcover] (v3) at (0,3) {}; \node[vertexcover] (v4) at (2,2) {}; \node[vertexcover] (v11) at (3,0) {}; \node[vertexcover] (v5) at (2,-2) {}; \node[vertexcover] (v6) at (1,-3) {}; \node[vertexcover] (v8) at (-1,-3) {}; \node[vertexcover] (v9) at (-2,-2) {}; \node[vertexcover] (v10) at (-3,0) {}; \node[vertexcover] (v1) at (-2,2) {}; \draw (v1) edge (v2); \draw (v3) edge (v2); \draw (v4) edge (v2); \draw (v5) edge (v2); \draw (v6) edge (v2); \draw (v8) edge (v2); \draw (v9) edge (v2); \draw (v2) edge (v10); \draw (v2) edge (v11); !ls tikz-figures-from-Python-* ``` ### D'autres exemples ? TODO: plus tard ! Cellule invisible en mode slides RISE (type de diapo : sauter). ## Pour en apprendre plus - Ce petit tutoriel : <https://perso.crans.org/besson/apprendre-python.fr.html> (sous licence GPLv3) ; - Ce WikiBooks : <https://fr.wikibooks.org/wiki/Programmation_Python> (sous licence libre) ; - Ces deux livres de Python au niveau lycรฉe : <https://github.com/exo7math/python1-exo7> et <https://github.com/exo7math/python2-exo7> (sous licence Creative Commons).
github_jupyter
``` # -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # ``` # Decission trees URLs - https://scikit-learn.org/0.22/auto_examples/tree/plot_cost_complexity_pruning.html - [Post Pruning Decision Trees](https://medium.com/swlh/post-pruning-decision-trees-using-python-b5d4bcda8e23) ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier ``` ## Load titanic dataset (train dataset only) ``` data = pd.read_csv('titanic/train.csv') X, y = data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Cabin', 'Embarked']], data['Survived'] X,y = X.fillna(0),y.fillna(0) X = pd.get_dummies(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) ``` ### Overfitting example ``` model = DecisionTreeClassifier(random_state=1).fit(X_train, y_train) y_predicted = model.predict(X_test) print('Training accuracy: ',model.score(X_train,y_train)) print('Test Accuracy: ',model.score(X_test, y_test)) ``` ## Post-prunning - The DecisionTreeClassifier class in sklearn provides **ccp_alpha** as a parameter for post pruning. - The parameter ccp_alpha provides a threshold for effective alphas, i.e. the process of pruning continues until the minimal effective alpha of the pruned tree is not greater than ccp_alpha. - The DecisionTreeClassifier class also provides a method **cost_complexity_pruning_path** which implements **the pruning process** and returns the effective alphas (and the corresponding impurities of there pruned trees) ``` path=DecisionTreeClassifier(random_state=1).cost_complexity_pruning_path(X_train, y_train) ccp_alphas, impurities = path.ccp_alphas, path.impurities print(path) # plotting fig, ax = plt.subplots() ax.plot(ccp_alphas[:-1], impurities[:-1], marker='o', drawstyle="steps-post") ax.set_xlabel("effective alpha") ax.set_ylabel("total impurity of leaves") ax.set_title("Total Impurity vs effective alpha for training set") clfs = [] for ccp_alpha in ccp_alphas: clf = DecisionTreeClassifier(random_state=1,ccp_alpha=ccp_alpha) clf.fit(X_train, y_train) clfs.append(clf) print("Number of nodes in the last tree is: {} with ccp_alpha: {} and a depth of: {}".\ format(clfs[-1].tree_.node_count, ccp_alphas[-1],clfs[-1].tree_.max_depth)) ``` #### We remove the last element in **clfs** and **ccp_alphas**, because it is the trivial tree with only one node. Here we show that the number of nodes and tree depth decreases as alpha increases. ``` clfs = clfs[:-1] ccp_alphas = ccp_alphas[:-1] node_counts = [clf.tree_.node_count for clf in clfs] depth = [clf.tree_.max_depth for clf in clfs] # plotting fig, ax = plt.subplots(2, 1) ax[0].plot(ccp_alphas, node_counts, marker='o', drawstyle="steps-post") ax[0].set_xlabel("alpha") ax[0].set_ylabel("number of nodes") ax[0].set_title("Number of nodes vs alpha") ax[1].plot(ccp_alphas, depth, marker='o', drawstyle="steps-post") ax[1].set_xlabel("alpha") ax[1].set_ylabel("depth of tree") ax[1].set_title("Depth vs alpha") fig.tight_layout() ``` ## Accuracy vs alpha for training and testing sets ``` train_scores = [clf.score(X_train, y_train) for clf in clfs] test_scores = [clf.score(X_test, y_test) for clf in clfs] # plotting fig, ax = plt.subplots() ax.set_xlabel("alpha") ax.set_ylabel("accuracy") ax.set_title("Accuracy vs alpha for training and testing sets") ax.plot(ccp_alphas, train_scores, marker='o', label="train", drawstyle="steps-post") ax.plot(ccp_alphas, test_scores, marker='o', label="test", drawstyle="steps-post") ax.legend() plt.show() ``` ## Use the best model ``` index_best_model = np.argmax(test_scores) best_model = clfs[index_best_model] print('Training accuracy of best model: ', best_model.score(X_train, y_train)) print('Test accuracy of best model: ', best_model.score(X_test, y_test)) ```
github_jupyter
# ็Žฏๅขƒๅ‡†ๅค‡ ``` # set env from pyalink.alink import * import sys, os resetEnv() useLocalEnv(2) ``` # ๆ•ฐๆฎๅ‡†ๅค‡ ``` # schema of train data schemaStr = "id string, click string, dt string, C1 string, banner_pos int, site_id string, \ site_domain string, site_category string, app_id string, app_domain string, \ app_category string, device_id string, device_ip string, device_model string, \ device_type string, device_conn_type string, C14 int, C15 int, C16 int, C17 int, \ C18 int, C19 int, C20 int, C21 int" # prepare batch train data batchTrainDataFn = "http://alink-release.oss-cn-beijing.aliyuncs.com/data-files/avazu-small.csv" trainBatchData = CsvSourceBatchOp().setFilePath(batchTrainDataFn) \ .setSchemaStr(schemaStr) \ .setIgnoreFirstLine(True) # feature fit labelColName = "click" vecColName = "vec" numHashFeatures = 30000 selectedColNames =["C1","banner_pos","site_category","app_domain", "app_category","device_type","device_conn_type", "C14","C15","C16","C17","C18","C19","C20","C21", "site_id","site_domain","device_id","device_model"] categoryColNames = ["C1","banner_pos","site_category","app_domain", "app_category","device_type","device_conn_type", "site_id","site_domain","device_id","device_model"] numericalColNames = ["C14","C15","C16","C17","C18","C19","C20","C21"] # prepare stream train data wholeDataFile = "http://alink-release.oss-cn-beijing.aliyuncs.com/data-files/avazu-ctr-train-8M.csv" data = CsvSourceStreamOp() \ .setFilePath(wholeDataFile) \ .setSchemaStr(schemaStr) \ .setIgnoreFirstLine(True); # split stream to train and eval data spliter = SplitStreamOp().setFraction(0.5).linkFrom(data) train_stream_data = spliter test_stream_data = spliter.getSideOutput(0) ``` # ๅœจ็บฟๅญฆไน ไบ”ๆญฅ้ชค <ul> <li>ๆญฅ้ชคไธ€ใ€็‰นๅพๅทฅ็จ‹</li> <li>ๆญฅ้ชคไบŒใ€ๆ‰นๅผๆจกๅž‹่ฎญ็ปƒ</li> <li>ๆญฅ้ชคไธ‰ใ€ๅœจ็บฟๆจกๅž‹่ฎญ็ปƒ๏ผˆFTRL๏ผ‰</li> <li>ๆญฅ้ชคๅ››ใ€ๅœจ็บฟ้ข„ๆต‹</li> <li>ๆญฅ้ชคไบ”ใ€ๅœจ็บฟ่ฏ„ไผฐ</li> </ul> # ๆญฅ้ชคไธ€ใ€็‰นๅพๅทฅ็จ‹ ``` # setup feature enginerring pipeline feature_pipeline = Pipeline() \ .add(StandardScaler() \ .setSelectedCols(numericalColNames)) \ .add(FeatureHasher() \ .setSelectedCols(selectedColNames) \ .setCategoricalCols(categoryColNames) \ .setOutputCol(vecColName) \ .setNumFeatures(numHashFeatures)) # fit and save feature pipeline model FEATURE_PIPELINE_MODEL_FILE = os.path.join(os.getcwd(), "feature_pipe_model.csv") feature_pipeline.fit(trainBatchData).save(FEATURE_PIPELINE_MODEL_FILE); BatchOperator.execute(); # load pipeline model feature_pipelineModel = PipelineModel.load(FEATURE_PIPELINE_MODEL_FILE); ``` # ๆญฅ้ชคไบŒใ€ๆ‰นๅผๆจกๅž‹่ฎญ็ปƒ ``` # train initial batch model lr = LogisticRegressionTrainBatchOp() initModel = lr.setVectorCol(vecColName) \ .setLabelCol(labelColName) \ .setWithIntercept(True) \ .setMaxIter(10) \ .linkFrom(feature_pipelineModel.transform(trainBatchData)) ``` ### ๅœจ็บฟๆจกๅž‹่ฎญ็ปƒ๏ผˆFTRL๏ผ‰ ``` # ftrl train model = FtrlTrainStreamOp(initModel) \ .setVectorCol(vecColName) \ .setLabelCol(labelColName) \ .setWithIntercept(True) \ .setAlpha(0.1) \ .setBeta(0.1) \ .setL1(0.01) \ .setL2(0.01) \ .setTimeInterval(10) \ .setVectorSize(numHashFeatures) \ .linkFrom(feature_pipelineModel.transform(train_stream_data)) ``` ### ๅœจ็บฟ้ข„ๆต‹ ``` # ftrl predict predResult = FtrlPredictStreamOp(initModel) \ .setVectorCol(vecColName) \ .setPredictionCol("pred") \ .setReservedCols([labelColName]) \ .setPredictionDetailCol("details") \ .linkFrom(model, feature_pipelineModel.transform(test_stream_data)) predResult.print(key="predResult", refreshInterval = 30, maxLimit=20) ``` ### ๅœจ็บฟ่ฏ„ไผฐ ``` # ftrl eval EvalBinaryClassStreamOp() \ .setLabelCol(labelColName) \ .setPredictionCol("pred") \ .setPredictionDetailCol("details") \ .setTimeInterval(10) \ .linkFrom(predResult) \ .link(JsonValueStreamOp() \ .setSelectedCol("Data") \ .setReservedCols(["Statistics"]) \ .setOutputCols(["Accuracy", "AUC", "ConfusionMatrix"]) \ .setJsonPath(["$.Accuracy", "$.AUC", "$.ConfusionMatrix"])) \ .print(key="evaluation", refreshInterval = 30, maxLimit=20) StreamOperator.execute(); ```
github_jupyter
# CHEM 1000 - Spring 2022 Prof. Geoffrey Hutchison, University of Pittsburgh ## Graded Homework 6 For this homework, we'll focus on: - integrals in 2D polar and 3D spherical space - probability (including integrating continuous distributions) --- As a reminder, you do not need to use Python to solve the problems. If you want, you can use other methods, just put your answers in the appropriate places. To turn in, either download as Notebook (.ipynb) or Print to PDF and upload to Gradescope. Make sure you fill in any place that says YOUR CODE HERE or "YOUR ANSWER HERE", as well as your name and collaborators (i.e., anyone you discussed this with) below: ``` NAME = "" COLLABORATORS = "" ``` ### Cartesian to Spherical Integrals Consider the Cartesian integral: $$ \iiint z^{2} d x d y d z $$ Evaluation is fairly simple over a rectangular region, but if we wish to evaluate across a spherical volume, the limits of integration become messy. Instead, we can transform $z^2$, resulting in the integral: $$ \int_{0}^{a} \int_{0}^{\pi} \int_{0}^{2 \pi}(r \cos \theta)^{2} r^{2} \sin \theta d \varphi d \theta d r $$ Integrate across a sphere of size "a" ``` from sympy import init_session init_session() a, r, theta, phi = symbols("N r theta phi") # technically, we're integrating psi**2 but let's not worry about that now # z => (r*cos(theta)) in spherical coordinates f = (r*cos(theta)**2) integrate(# something) ``` ### Normalizing We often wish to normalize functions. Calculate a normalization constant $N^2$ for the following integral (e.g., evaluate it, set it equal to one, etc.) $$ \int_{0}^{\infty} \int_{0}^{\pi} \int_{0}^{2 \pi} N^2 \mathrm{e}^{-2 r} \cos ^{2} \theta r^{2} \sin \theta d \varphi d \theta d r $$ (This is related to a $2p_z$ hydrogen atomic orbital.) ``` # if you have an error, make sure you run the cell above this N, r, theta, phi = symbols("N r theta phi") # technically, we're integrating psi**2 but let's not worry about that now f = N**2 * exp(-2*r) * cos(theta)**2 integrate(# something) ``` ### Gaussian Distribution and Probability You may have heard much about the Gaussian "normal" distribution ("Bell curve"). If we flip a coin enough, the binomial distribution becomes essentially continuous. Moreover, the "law of large numbers" (i.e., the [central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)) indicates that by taking the enough data points, the sum - and average will tend towards a Gaussian distribution. In short, even if our underlying data comes from some different distribution, the average will become normal (e.g. consider the average velocities in an ideal gas - a mole is a big number). We will spend some time on the Gaussian distribution. - mean $x_0$ - standard deviation $\sigma$, variance $\sigma^2$ A normalized Gaussian distribution is then: $$ p(x) =\frac{1}{\sqrt{2 \pi \sigma^{2}}} \exp \left[-\frac{\left(x-x_{0}\right)^{2}}{2 \sigma^{2}}\right] $$ If the mean $x_0 = 0$, what fraction of data will fall: - within $\pm 0.5\sigma$ - within one standard deviation - within $\pm 1.5 \sigma$ - within $\pm 2.0 \sigma$ (In other words, change the limits of integration on the probability function.) ``` sigma = symbols('sigma') p = (1/sqrt(2*pi*sigma**2))*exp((-x**2)/(2*sigma**2)) simplify(integrate(p, (x, -0.5*sigma, +0.5*sigma))) ``` ### If we want to include "error bars" with 95% confidence, what intervals do we use? YOUR ANSWER HERE What about 99% confidence intervals?
github_jupyter
# Energy volume curve ## Theory Fitting the energy volume curve allows to calculate the equilibrium energy $E_0$, the equilirbium volume $V_0$, the equilibrium bulk modulus $B_0$ and its derivative $B^{'}_0$. These quantities can then be used as part of the Einstein model to get an initial prediction for the thermodynamik properties, the heat capacity $C_v$ and the free energy $F$. ## Initialisation We start by importing matplotlib, numpy and the pyiron project class. ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np from pyiron_atomistics import Project ``` In the next step we create a project, by specifying the name of the project. ``` pr = Project(path='thermo') ``` ## Atomistic structure To analyse the energy volume dependence a single super cell is sufficient, so we create an iron super cell as an example. ``` basis = pr.create_structure(element='Fe', bravais_basis='bcc', lattice_constant=2.75) basis.plot3d() ``` ## Calculation Energy volume curves are commonly calculated with ab initio codes, so we use VASP in this example. But we focus on the generic commands so the same example works with any DFT code. We choose 'vasp' as job name prefix, select an energy cut off of $320 eV$ and assign the basis to the job. Afterwards we apply the corresponding strain. ``` for strain in np.linspace(0.95, 1.05, 7): strain_str = str(strain).replace('.', '_') job_vasp_strain = pr.create_job(job_type=pr.job_type.Gpaw, job_name='gpaw_' + strain_str) job_vasp_strain.set_encut(320.0) job_vasp_strain.structure = basis.copy() job_vasp_strain.structure.set_cell(cell=basis.cell * strain ** (1/3), scale_atoms=True) job_vasp_strain.run() ``` As these are simple calculation, there is no need to submit them to the queuing sytem. We can confirm the status of the calculation with the job_table. If the status of each job is marked as finished, then we can continue with the next step. ``` pr.job_table() ``` ## Analysis We aggregate the data for further processing in two separated lists, one for the volumes and one for the energies. To do so we iterate over the jobs within the project, filter the job names which contain the string 'vasp' and from those extract the final volume and the final energy. ``` volume_lst, energy_lst = zip(*[[job['output/generic/volume'][-1], job['output/generic/energy_pot'][-1]] for job in pr.iter_jobs(convert_to_object=False) if 'gpaw' in job.job_name]) ``` We plot the aggregated data using matplotlib. ``` plt.plot(volume_lst, energy_lst, 'x-') plt.xlabel('Volume ($\AA ^ 3$)') plt.ylabel('Energy (eV)') ``` ## Encut Dependence To extend the complexity of our simulation protocol we can not only iterate over different strains but also different energy cutoffs. For this we use multiple sub projects to structure the data. And we summarize the previous code in multiple functions to maintain a high level of readability. The first function calculates a specific strained configuration for an specifc energy cut off, while the second function analyses the different strained calculations for a specific energy cutoff and returns the list of energy volume pairs. ### Functions ``` def vasp_calculation_for_strain(pr, basis, strain, encut): strain_str = str(strain).replace('.', '_') job_vasp_strain = pr.create_job(job_type=pr.job_type.Gpaw, job_name='gpaw_' + strain_str) job_vasp_strain.set_encut(encut) job_vasp_strain.structure = basis.copy() job_vasp_strain.structure.set_cell(cell=basis.cell * strain ** (1/3), scale_atoms=True) job_vasp_strain.run() def energy_volume_pairs(pr): volume_lst, energy_lst = zip(*[[job['output/generic/volume'][-1], job['output/generic/energy_pot'][-1]] for job in pr.iter_jobs(convert_to_object=False) if 'gpaw' in job.job_name]) return volume_lst, energy_lst ``` ### Calculation With these functions we can structure our code and implement the additional for loop to include multiple energy cutoffs. ``` for encut in np.linspace(270, 320, 6): encut_str = 'encut_' + str(int(encut)) pr_encut = pr.open(encut_str) for strain in np.linspace(0.95, 1.05, 7): vasp_calculation_for_strain(pr=pr_encut, basis=basis, strain=strain, encut=encut) ``` ### Analysis The analysis is structured in a similar way. Here we use iter_groups() to iterate over the existing subprojects within our project and plot the individual energy volume curves using the functions defined above. ``` for pr_encut in pr.iter_groups(): volume_lst, energy_lst = energy_volume_pairs(pr_encut) plt.plot(volume_lst, energy_lst, 'x-', label=pr_encut.base_name) plt.xlabel('Volume ($\AA ^ 3$)') plt.ylabel('Energy (eV)') plt.legend() ``` ## Fitting After we created multiple datasets we can now start to fit the converged results. While it is possible to fit the results using a simple polynomial fit we prefer to use the phyiscally motivated birch murnaghan equation or the vinet equation. For this we create the Murnaghan object and use it is fitting functionality: ``` murn = pr.create_job(job_type=pr.job_type.Murnaghan, job_name='murn') ``` ### Birch Marnaghan ``` [e0, b0, bP, v0], [e0_error, b0_error, bP_error, v0_error] = murn._fit_leastsq(volume_lst=volume_lst, energy_lst=energy_lst, fittype='birchmurnaghan') [e0, b0, bP, v0] ``` ### Vinet ``` [e0, b0, bP, v0], [e0_error, b0_error, bP_error, v0_error] = murn._fit_leastsq(volume_lst=volume_lst, energy_lst=energy_lst, fittype='vinet') [e0, b0, bP, v0] ``` We see that both equation of states give slightly different results, with overall good agreement. To validate the agreement we plot the with with the original data. ``` vol_lst = np.linspace(np.min(volume_lst), np.max(volume_lst), 1000) plt.plot(volume_lst, energy_lst, label='dft') plt.plot(vol_lst, murn.fit_module.vinet_energy(vol_lst, e0, b0/ 160.21766208, bP, v0), label='vinet') plt.xlabel('Volume ($\AA ^ 3$)') plt.ylabel('Energy (eV)') plt.legend() ``` ## Murnaghan Module Besides the fitting capabilities the Murnaghan module can also be used to run a set of calculations. For this we define a reference job, which can be either a Vasp calculation or any other pyiron job type and then specify the input parameters for the Murnaghan job. ``` job_vasp_strain = pr.create_job(job_type=pr.job_type.Gpaw, job_name='gpaw') job_vasp_strain.set_encut(320) job_vasp_strain.structure = basis.copy() murn = pr.create_job(job_type=pr.job_type.Murnaghan, job_name='murn') murn.ref_job = job_vasp_strain murn.input ``` We modify the input parameters to agree with the settings used in the examples above and execute the simulation by calling the run command on the murnaghan job object. ``` murn.input['num_points'] = 7 murn.input['vol_range'] = 0.05 type(murn.structure) pr.job_table() murn.run() ``` Afterwards we can use the build in capabilites to plot the resulting energy volume curve and fit different equations of state to the calculated energy volume pairs. ``` murn.output_to_pandas() murn.plot() murn.fit_vinet() ``` ## Common mistakes ### Not copying the basis It is important to copy the basis before applying the strain, as the strain has to be applied on the initial structure, not the previous structure: ``` volume_lst_with_copy = [] for strain in np.linspace(0.95, 1.05, 7): basis_copy = basis.copy() basis_copy.set_cell(cell=basis.cell * strain ** (1/3), scale_atoms=True) volume_lst_with_copy.append(basis_copy.get_volume()) basis_copy = basis.copy() volume_lst_without_copy = [] for strain in np.linspace(0.95, 1.05, 7): basis_copy.set_cell(cell=basis_copy.cell * strain ** (1/3), scale_atoms=True) volume_lst_without_copy.append(basis_copy.get_volume()) volume_lst_with_copy, volume_lst_without_copy ``` ### Rescaling the cell Another common issue is the rescaling of the supercell, there are multiple options to choose from. We used the option to scale the atoms with the supercell. ``` basis_copy = basis.copy() strain = 0.5 basis_copy.set_cell(cell=basis_copy.cell * strain ** (1/3), scale_atoms=True) basis_copy.plot3d() ``` A nother typical case is rescaling the cell to increase the distance between the atoms or add vacuum. But that is not what we want to fit an energy volume curve. ``` basis_copy = basis.copy() strain = 0.5 basis_copy.set_cell(cell=basis_copy.cell * strain ** (1/3), scale_atoms=False) basis_copy.plot3d() ``` The same can be achieved by setting the basis to relative coordinates. ``` basis_copy = basis.copy() strain = 0.5 basis_copy.set_relative() basis_copy.cell *= strain ** (1/3) basis_copy.plot3d() basis_copy = basis.copy() strain = 0.5 basis_copy.cell *= strain ** (1/3) basis_copy.plot3d() ```
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#Overview" data-toc-modified-id="Overview-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Overview</a></div><div class="lev2 toc-item"><a href="#pwd---Print-Working-Directory" data-toc-modified-id="pwd---Print-Working-Directory-11"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>pwd - Print Working Directory</a></div><div class="lev2 toc-item"><a href="#ls---List-files-and-directory-names,-attributes" data-toc-modified-id="ls---List-files-and-directory-names,-attributes-12"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>ls - List files and directory names, attributes</a></div><div class="lev2 toc-item"><a href="#mkdir---Make-a-new-directory" data-toc-modified-id="mkdir---Make-a-new-directory-13"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>mkdir - Make a new directory</a></div><div class="lev2 toc-item"><a href="#cd---Change-to-a-particular-directory" data-toc-modified-id="cd---Change-to-a-particular-directory-14"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>cd - Change to a particular directory</a></div><div class="lev2 toc-item"><a href="#rmdir---Remove-a-directory" data-toc-modified-id="rmdir---Remove-a-directory-15"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>rmdir - Remove a directory</a></div><div class="lev2 toc-item"><a href="#cp---Copy-Files" data-toc-modified-id="cp---Copy-Files-16"><span class="toc-item-num">1.6&nbsp;&nbsp;</span>cp - Copy Files</a></div><div class="lev2 toc-item"><a href="#rm---Remove-files" data-toc-modified-id="rm---Remove-files-17"><span class="toc-item-num">1.7&nbsp;&nbsp;</span>rm - Remove files</a></div><div class="lev2 toc-item"><a href="#mv-:-Move-a-file" data-toc-modified-id="mv-:-Move-a-file-18"><span class="toc-item-num">1.8&nbsp;&nbsp;</span>mv : Move a file</a></div><div class="lev2 toc-item"><a href="#CURL---Getting-Data-from-the-Command-Line" data-toc-modified-id="CURL---Getting-Data-from-the-Command-Line-19"><span class="toc-item-num">1.9&nbsp;&nbsp;</span>CURL - Getting Data from the Command Line</a></div><div class="lev2 toc-item"><a href="#head/tail" data-toc-modified-id="head/tail-110"><span class="toc-item-num">1.10&nbsp;&nbsp;</span>head/tail</a></div><div class="lev2 toc-item"><a href="#grep:" data-toc-modified-id="grep:-111"><span class="toc-item-num">1.11&nbsp;&nbsp;</span>grep:</a></div><div class="lev2 toc-item"><a href="#Redirection-(or-Downloading)" data-toc-modified-id="Redirection-(or-Downloading)-112"><span class="toc-item-num">1.12&nbsp;&nbsp;</span>Redirection (or Downloading)</a></div> # Overview This is by no means an exhaustive list, the point is just to give you a feeler for what's possible. If you have used Linux or Mac, or have written code in Ruby, chances are you have used Unix commands already. If you're a Windows user, here's a good resource: https://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/ Another great resource in general on the basics of unix commands: * http://matt.might.net/articles/basic-unix/ ## pwd - Print Working Directory ``` !pwd ``` ## ls - List files and directory names, attributes Some commonly used commands are below: * -A: list all of the contents of the queried directory, even hidden files. * -l: detailed format, display additional info for all files and directories. * -R: recursively list the contents of any subdirectories. * -t: sort files by the time of the last modification. * -S: sort files by size. * -r: reverse any sort order. * -h: when used in conjunction with -l, gives a more human-readable output. You can also combine the commands/flags. For example: * -al * -Al Read more on this topic here: https://www.mkssoftware.com/docs/man1/ls.1.asp ``` ls !ls ls -al ls -Al ``` ## mkdir - Make a new directory ``` !mkdir NewFolder ls ``` ## cd - Change to a particular directory ``` cd NewFolder cd .. ls ``` ## rmdir - Remove a directory If the folder is not empty, it need the "-r" flag. Example: rmdir -r NewFolder ``` rmdir NewFolder ls ``` ## cp - Copy Files Careful with the filenames! Will be overwritten without warning. ``` ls # Copy in the same directory !cp 01.Unix_and_Shell_Command_Basics.ipynb Notebook01.ipynb ls rm Notebook01.ipynb ls # Copy to another directory !mkdir TempFolder !cp 01.Unix_and_Shell_Command_Basics.ipynb TempFolder/File01.ipynb !ls cd TempFolder ls ``` ## rm - Remove files Note that this is different to rmdir, which exists to remove a directory ``` ls pwd !rm File01.ipynb !ls !pwd !ls -al !cd .. !pwd !ls cd .. ls cp -i 01.Unix_and_Shell_Command_Basics.ipynb TempFolder/NewFile01.ipynb cd Tempfolder ls cp -i NewFile01.ipynb NewFile01.ipynb ``` ## mv : Move a file This is close to the the 'cut' function available for files on Windows. When you use the 'mv' command, a file is copied to a new location, and removed from it's original location. ``` pwd ls rm -r TempFolder ls cp 01.Unix_and_Shell_Command_Basics.ipynb NewFile01.ipynb ls mkdir TempFolder02 ls mv NewFile01.ipynb TempFolder02 ls cd TempFolder02 ls cd .. ``` ## CURL - Getting Data from the Command Line Let's begin by copying a simple tab-separated file. The format is as below: * !curl -OptionalFlag 'http://url' ``` !curl -L 'https://dl.dropboxusercontent.com/s/j2yh7nvlli1nsa5/gdp.txt' !curl -L 'https://dl.dropboxusercontent.com/s/eqyhkf3tpgre0jb/foo.txt' !curl -s "http://freegeoip.net/json/" | jq . !curl -s "http://api.open-notify.org/iss-now.json" !curl -s "http://api.open-notify.org/astros.json" ``` Register for the Mashape API Market here: https://market.mashape.com ``` !curl -X POST --include 'https://community-sentiment.p.mashape.com/text/' \ -H 'X-Mashape-Key: YFWRiIyfNemshsFin8iTJy0XFUjNp1rXoY7jsnoPlVphvWnKY6' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Accept: application/json' \ -d 'txt=My team lost! :(' ``` Note: This is a free API, so I have exposed my API key in the code. In practice, if you are ever sharing code, please take adequate precautions, and never expose your private key. ## head/tail ``` pwd ls cd Data ls !head -n 3 sample.txt !tail -n 3 sample.txt !cat sample.txt # Selecting specific fields !cut -f2,3 sample.txt !sort sample.txt !sort -k 2 sample.txt !wc sample.txt !wc -w sample.txt !find ~ -sample.txt 'sample.txt' ``` ## grep: Grep is a pattern matching utility built into unix and it's flavors. The typical format is: grep [option] [pattern] [file/s] ``` pwd ls !cat nyt.txt # Count the number of matches !grep -c 'Kennedy' nyt.txt !grep -o 'Kennedy' nyt.txt ``` More options for grep: * -c Print only a count of matched lines. * -l List only filenames * -i Ignore lowercase and uppercase distinctions * -o prints only the matching part of the line * -n Print matching line with its line number * -v Negate matches; print lines that do not match the regex * -r Recursively Search subdirectories listed ``` !curl -s 'http://freegeoip.net/json/' > location.json !jq . location.json !curl -s 'http://freegeoip.net/json/' | jq . ``` ## Redirection (or Downloading) This is really useful to quickly download a dataset using what is called an API Endpoint. Let's download the 'Times Square Entertainment Venues' dataset from New York City's Open Data Portal to demonstrate this. https://data.cityofnewyork.us/Business/Times-Square-Entertainment-Venues/jxdc-hnze ``` !curl "https://data.cityofnewyork.us/resource/2pc8-n4xe.json" > venues.json !cat venues.json !grep 'Ripley' venues.json !grep -i 'Theater' venues.json # Multiple flags, and multiple conditions !grep -v -e 'Theater' -e 'Theatre' venues.json ```
github_jupyter
``` # Erasmus+ ICCT project (2018-1-SI01-KA203-047081) # Toggle cell visibility from IPython.display import HTML tag = HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide() } else { $('div.input').show() } code_show = !code_show } $( document ).ready(code_toggle); </script> Toggle cell visibility <a href="javascript:code_toggle()">here</a>.''') display(tag) # Hide the code completely # from IPython.display import HTML # tag = HTML('''<style> # div.input { # display:none; # } # </style>''') # display(tag) %matplotlib inline import control import numpy import sympy as sym from IPython.display import display, Markdown import ipywidgets as widgets import matplotlib.pyplot as plt #print a matrix latex-like def bmatrix(a): """Returns a LaTeX bmatrix - by Damir Arbula (ICCT project) :a: numpy array :returns: LaTeX bmatrix as a string """ if len(a.shape) > 2: raise ValueError('bmatrix can at most display two dimensions') lines = str(a).replace('[', '').replace(']', '').splitlines() rv = [r'\begin{bmatrix}'] rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines] rv += [r'\end{bmatrix}'] return '\n'.join(rv) # Display formatted matrix: def vmatrix(a): if len(a.shape) > 2: raise ValueError('bmatrix can at most display two dimensions') lines = str(a).replace('[', '').replace(']', '').splitlines() rv = [r'\begin{vmatrix}'] rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines] rv += [r'\end{vmatrix}'] return '\n'.join(rv) #matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value ! class matrixWidget(widgets.VBox): def updateM(self,change): for irow in range(0,self.n): for icol in range(0,self.m): self.M_[irow,icol] = self.children[irow].children[icol].value #print(self.M_[irow,icol]) self.value = self.M_ def dummychangecallback(self,change): pass def __init__(self,n,m): self.n = n self.m = m self.M_ = numpy.matrix(numpy.zeros((self.n,self.m))) self.value = self.M_ widgets.VBox.__init__(self, children = [ widgets.HBox(children = [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)] ) for j in range(n) ]) #fill in widgets and tell interact to call updateM each time a children changes value for irow in range(0,self.n): for icol in range(0,self.m): self.children[irow].children[icol].value = self.M_[irow,icol] self.children[irow].children[icol].observe(self.updateM, names='value') #value = Unicode('example@example.com', help="The email value.").tag(sync=True) self.observe(self.updateM, names='value', type= 'All') def setM(self, newM): #disable callbacks, change values, and reenable self.unobserve(self.updateM, names='value', type= 'All') for irow in range(0,self.n): for icol in range(0,self.m): self.children[irow].children[icol].unobserve(self.updateM, names='value') self.M_ = newM self.value = self.M_ for irow in range(0,self.n): for icol in range(0,self.m): self.children[irow].children[icol].value = self.M_[irow,icol] for irow in range(0,self.n): for icol in range(0,self.m): self.children[irow].children[icol].observe(self.updateM, names='value') self.observe(self.updateM, names='value', type= 'All') #self.children[irow].children[icol].observe(self.updateM, names='value') #overlaod class for state space systems that DO NOT remove "useless" states (what "professor" of automatic control would do this?) class sss(control.StateSpace): def __init__(self,*args): #call base class init constructor control.StateSpace.__init__(self,*args) #disable function below in base class def _remove_useless_states(self): pass ``` ## Rotary actuator position control <img src="Images\EX34.svg" alt="drawing" width="400x400"> The actuator consists of a DC motor actuating a disc where a disturbance torque may be exerted. System constants are: - moment of inertia of the rotor $J = 4E-6$ kg/$\text{m}^2$; - motor viscous friction constant $b = 3.3E-6$ Nms; - electromotive force constant $K_b = 0.03$ V/(rad/s); - motor torque constant $K_t = 0.03$ Nm/A; - electric resistance $R = 5$ $\Omega$; - electric inductance $L = 3E-3$ $\text{H}$. The torque generated by the motor, assuming fixed excitation field, is $T=K_t i$, and the Back EMF voltage is $e=K_b \dot{\theta}$. Assume there can also be an external disturbance torque $T_d$ that must be rejected. The dynamic equations can be written as: \begin{cases} V = Ri+L\frac{di}{dt}+e = Ri+L\frac{di}{dt}+K_b\dot{\theta} \\ J\ddot{\theta} = -b\dot{\theta}+T+T_d = -b\dot{\theta}+K_ti +T_d \end{cases} and defining $x=\begin{bmatrix} x_1 & x_2 & x_3 \end{bmatrix}^T=\begin{bmatrix} \dot{\theta} & \theta & i \end{bmatrix}^T$ yields the state space form: \begin{cases} \dot{x} = \begin{bmatrix} -\frac{b}{J} & 0 & \frac{K_t}{J} \\ 1 & 0 & 0 \\ -\frac{K_b}{L} & 0 & -\frac{R}{L} \end{bmatrix}x + \begin{bmatrix} 0 & \frac{1}{J} \\ 0 & 0 \\ \frac{1}{L} & 0 \end{bmatrix}\begin{bmatrix} V \\ T_d \end{bmatrix} \\ y = \begin{bmatrix} 0 & 1 & 0 \end{bmatrix}x \, . \end{cases} The goal is to design a regulator that regulates the variable $\theta$ using the input $V$ according to: - settling time for 5% tolerance band of less than 0.06 seconds; - no steady-state error in response to a step position request; - full rejection of step-like disturbances $T_d$ (e.g. zero steady-state error in motor position when a step disturbance is applied); - $|V|\leq 2.4$ $V$. ### Regulator design #### Controller design To meet the requirement of zero steady-state error and full rejection of step-like disturbances we add an integrator in the state feedback control by defining a new state $\dot{x_4} = \theta-y_d$, where $y_d$ is the reference input. The new state equations became: \begin{cases} \dot{x_a} = \begin{bmatrix} -\frac{b}{J} & 0 & \frac{K_t}{J} & 0 \\ 1 & 0 & 0 & 0 \\ -\frac{K_b}{L} & 0 & -\frac{R}{L} & 0 \\ 0 & 1 & 0 & 0 \end{bmatrix}x_a + \begin{bmatrix} 0 & \frac{1}{J} & 0 \\ 0 & 0 & 0 \\ \frac{1}{L} & 0 & 0 \\ 0 & 0 & -1 \end{bmatrix}\begin{bmatrix} V \\ T_d \\ y_d \end{bmatrix} \\ y_a = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}x_a \, . \end{cases} Since the augmented system still remains controllable with the input $V$ we design a state feedback control with only this input. The poles of the system are: ``` b = 3.3E-6 J = 4E-6 Kb = 0.03 Kt = 0.03 R = 5 L = 3E-3 A = [[-b/J, 0, Kt/J, 0], [1, 0, 0, 0], [-Kb/L, 0, -R/L, 0], [0, 1, 0, 0]] A = numpy.matrix(A) B = [[0, 1/J, 0], [0, 0, 0], [1/L, 0, 0], [0, 0, -1]] B = numpy.matrix(B) Bu = B[:,0] Bd = B[:,1] Br = B[:,2] C = [[0,1,0,0], [0,0,0,1]] C = numpy.matrix(C) D = numpy.zeros((2,3)) display(Markdown(bmatrix(numpy.linalg.eigvals(A).round(3)))) # print(numpy.linalg.matrix_rank(control.ctrb(A,Bu))) ``` and since the mode associated with the pole in $-1620.4$ would have a settling time shorter that $0.06$ s we leave the pole as it is. We increase the frequency of the pole from $-45.8$ to $-100$, and place the two integrators in $-110$. #### Design of the observer For the observer we consider the augmented system and $y_a$ and we place the poles in $-5000$ in order to have an estimation dynamics faster than that of the closed-loop plant poles. ### How to use this notebook? - Verify the performance with $0\leq T_d\leq +5$ mNm. - Verify the performance with $0\geq T_d\geq -5$ mNm and if the requirements are not met, attempt a control system redesign. - Verify the performance in presence of a sinusoidal $T_d$ with a period equal to $0.01$ s. - When the system is subject to a disturbance the estimated states does not converge to $0$. Why? ``` # Preparatory cell X0 = numpy.matrix('0.0; 0.0; 0.0; 0.0') K = numpy.matrix([0,0,0,0]) L = numpy.matrix([[0,0],[0,0],[0,0],[0,0]]) X0w = matrixWidget(4,1) X0w.setM(X0) Kw = matrixWidget(1,4) Kw.setM(K) Lw = matrixWidget(4,2) Lw.setM(L) eig1c = matrixWidget(1,1) eig2c = matrixWidget(2,1) eig3c = matrixWidget(1,1) eig4c = matrixWidget(2,1) eig1c.setM(numpy.matrix([-1620.357])) eig2c.setM(numpy.matrix([[-110.],[-0.0]])) eig3c.setM(numpy.matrix([-100.0])) eig4c.setM(numpy.matrix([[-110],[-0.0]])) eig1o = matrixWidget(1,1) eig2o = matrixWidget(2,1) eig3o = matrixWidget(1,1) eig4o = matrixWidget(2,1) eig1o.setM(numpy.matrix([-5000.])) eig2o.setM(numpy.matrix([[-5010.],[0.]])) eig3o.setM(numpy.matrix([-5020.])) eig4o.setM(numpy.matrix([[-5030.],[0.]])) # Misc #create dummy widget DW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px')) #create button widget START = widgets.Button( description='Test', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Test', icon='check' ) def on_start_button_clicked(b): #This is a workaround to have intreactive_output call the callback: # force the value of the dummy widget to change if DW.value> 0 : DW.value = -1 else: DW.value = 1 pass START.on_click(on_start_button_clicked) # Define type of method selm = widgets.Dropdown( options= ['Set K and L', 'Set the eigenvalues'], value= 'Set the eigenvalues', description='', disabled=False ) # Define the number of complex eigenvalues selec = widgets.Dropdown( options= ['0 complex eigenvalues', '2 complex eigenvalues', '4 complex eigenvalues'], value= '0 complex eigenvalues', description='Eig controller:', disabled=False ) seleo = widgets.Dropdown( options= ['0 complex eigenvalues', '2 complex eigenvalues'], value= '0 complex eigenvalues', description='Eig observer:', disabled=False ) #define type of ipout selu = widgets.Dropdown( options=['impulse', 'step', 'sinusoid', 'square wave'], value='step', description='Type of disturbance:', style = {'description_width': 'initial'}, disabled=False ) # Define the values of the input u = widgets.FloatSlider( value=45, min=0, max=90, step=1, description='Reference [deg]:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.3f', ) ud = widgets.FloatSlider( value=0, min=-10., max=10., step=0.1, description=r'$T_d$ [mNm]:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) period = widgets.FloatSlider( value=0.01, min=0.001, max=0.1, step=0.001, description='Period [s]: ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.3f', ) simTime = widgets.FloatText( value=0.1, description='', disabled=False ) # Support functions def eigen_choice(selec,seleo): if selec == '0 complex eigenvalues': eig1c.children[0].children[0].disabled = False eig2c.children[1].children[0].disabled = True eig3c.children[0].children[0].disabled = False eig4c.children[0].children[0].disabled = False eig4c.children[1].children[0].disabled = True eigc = 0 if seleo == '0 complex eigenvalues': eig1o.children[0].children[0].disabled = False eig2o.children[1].children[0].disabled = True eig3o.children[0].children[0].disabled = False eig4o.children[0].children[0].disabled = False eig4o.children[1].children[0].disabled = True eigo = 0 if selec == '2 complex eigenvalues': eig1c.children[0].children[0].disabled = False eig2c.children[1].children[0].disabled = False eig3c.children[0].children[0].disabled = False eig4c.children[0].children[0].disabled = True eig4c.children[1].children[0].disabled = True eigc = 2 if seleo == '2 complex eigenvalues': eig1o.children[0].children[0].disabled = False eig2o.children[1].children[0].disabled = False eig3o.children[0].children[0].disabled = False eig4o.children[0].children[0].disabled = True eig4o.children[1].children[0].disabled = True eigo = 2 if selec == '4 complex eigenvalues': eig1c.children[0].children[0].disabled = True eig2c.children[1].children[0].disabled = False eig3c.children[0].children[0].disabled = True eig4c.children[0].children[0].disabled = False eig4c.children[1].children[0].disabled = False eigc = 4 if seleo == '4 complex eigenvalues': eig1o.children[0].children[0].disabled = True eig2o.children[1].children[0].disabled = False eig3o.children[0].children[0].disabled = True eig4o.children[0].children[0].disabled = False eig4o.children[1].children[0].disabled = False eigo = 4 return eigc, eigo def method_choice(selm): if selm == 'Set K and L': method = 1 selec.disabled = True seleo.disabled = True if selm == 'Set the eigenvalues': method = 2 selec.disabled = False seleo.disabled = False return method import warnings # In order to suppress the warnings for tolerance warnings.filterwarnings("ignore") def main_callback2(ud, X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, eig3o, eig4o, u, period, selm, selec, seleo, selu, simTime, DW): eigc, eigo = eigen_choice(selec,seleo) method = method_choice(selm) if method == 1: solc = numpy.linalg.eig(A-Bu*K) solo = numpy.linalg.eig(A-L*C) if method == 2: #for bettere numerical stability of place if eig1c[0,0]==eig2c[0,0] or eig1c[0,0]==eig3c[0,0] or eig1c[0,0]==eig4c[0,0]: eig1c[0,0] *= 1.01 if eig2c[0,0]==eig3c[0,0] or eig2c[0,0]==eig4c[0,0]: eig3c[0,0] *= 1.015 if eig1o[0,0]==eig2o[0,0] or eig1o[0,0]==eig3o[0,0] or eig1o[0,0]==eig4o[0,0]: eig1o[0,0] *= 1.01 if eig2o[0,0]==eig3o[0,0] or eig2o[0,0]==eig4o[0,0]: eig3o[0,0] *= 1.015 if eigc == 0: K = control.acker(A, Bu, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]]) Kw.setM(K) if eigc == 2: K = control.acker(A, Bu, [eig3c[0,0], eig1c[0,0], numpy.complex(eig2c[0,0], eig2c[1,0]), numpy.complex(eig2c[0,0],-eig2c[1,0])]) Kw.setM(K) if eigc == 4: K = control.acker(A, Bu, [numpy.complex(eig4c[0,0], eig4c[1,0]), numpy.complex(eig4c[0,0],-eig4c[1,0]), numpy.complex(eig2c[0,0], eig2c[1,0]), numpy.complex(eig2c[0,0],-eig2c[1,0])]) Kw.setM(K) if eigo == 0: L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0], eig4o[0,0]]).T Lw.setM(L) if eigo == 2: L = control.place(A.T, C.T, [eig3o[0,0], eig1o[0,0], numpy.complex(eig2o[0,0], eig2o[1,0]), numpy.complex(eig2o[0,0],-eig2o[1,0])]).T Lw.setM(L) if eigo == 4: L = control.place(A.T, C.T, [numpy.complex(eig4o[0,0], eig4o[1,0]), numpy.complex(eig4o[0,0],-eig4o[1,0]), numpy.complex(eig2o[0,0], eig2o[1,0]), numpy.complex(eig2o[0,0],-eig2o[1,0])]).T Lw.setM(L) sys = sss(A,numpy.hstack((Bu,Bd,Br)),[[0,1,0,0],[0,0,0,1],[0,0,0,0],[0,0,0,0]],[[0,0,0],[0,0,0],[1,0,0],[0,0,1]]) syse = sss(A-L*C,numpy.hstack((Bu,Br,L)),numpy.eye(4),numpy.zeros((4,4))) sysc = sss(0,[0,0,0,0],0,-K) sys_append = control.append(sys,syse,sysc) try: sys_CL = control.connect(sys_append, [[1,9],[4,3],[5,4],[6,1],[7,2],[8,5],[9,6],[10,7],[11,8]], [3,2], [1,3]) except: sys_CL = control.connect(sys_append, [[1,9],[4,3],[5,4],[6,1],[7,2],[8,5],[9,6],[10,7],[11,8]], [3,2], [1,3]) X0w1 = numpy.zeros((8,1)) X0w1[4,0] = X0w[0,0] X0w1[5,0] = X0w[1,0] X0w1[6,0] = X0w[2,0] X0w1[7,0] = X0w[3,0] if simTime != 0: T = numpy.linspace(0, simTime, 10000) else: T = numpy.linspace(0, 1, 10000) ud = ud/1000 u = u*numpy.pi/180 if selu == 'impulse': #selu Ud = [0 for t in range(0,len(T))] Ud[0] = ud U = [u for t in range(0,len(T))] T, yout, xout = control.forced_response(sys_CL,T,[U,Ud],X0w1) if selu == 'step': U = [u for t in range(0,len(T))] Ud = [ud for t in range(0,len(T))] T, yout, xout = control.forced_response(sys_CL,T,[U,Ud],X0w1) if selu == 'sinusoid': Ud = ud*numpy.sin(2*numpy.pi/period*T) U = [u for t in range(0,len(T))] T, yout, xout = control.forced_response(sys_CL,T,[U,Ud],X0w1) if selu == 'square wave': Ud = ud*numpy.sign(numpy.sin(2*numpy.pi/period*T)) U = [u for t in range(0,len(T))] T, yout, xout = control.forced_response(sys_CL,T,[U,Ud],X0w1) try: step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T) print('Step info: \n\tRise time =',step_info_dict['RiseTime'],'\n\tSettling time (5%) =',step_info_dict['SettlingTime'],'\n\tOvershoot (%)=',step_info_dict['Overshoot']) print('Max u value (% of 2.4V)=', max(abs(yout[1]))/(2.4)*100) except: print("Error in the calculation of step info.") fig = plt.figure(num='Simulation1', figsize=(14,12)) fig.add_subplot(221) plt.title('Output response') plt.ylabel('Output [rad]') plt.plot(T,yout[0],T,U,'r--') plt.xlabel('$t$ [s]') plt.legend(['$y$','Reference']) plt.axvline(x=0,color='black',linewidth=0.8) plt.axhline(y=0,color='black',linewidth=0.8) plt.grid() fig.add_subplot(222) plt.title('Input') plt.ylabel('$u$ [V]') plt.plot(T,yout[1]) plt.plot(T,[2.4 for i in range(len(T))],'r--') plt.plot(T,[-2.4 for i in range(len(T))],'r--') plt.xlabel('$t$ [s]') plt.axvline(x=0,color='black',linewidth=0.8) plt.axhline(y=0,color='black',linewidth=0.8) plt.grid() fig.add_subplot(223) plt.title('Disturbance') plt.ylabel('$T_d$ [Nm]') plt.plot(T,Ud,'r') plt.xlabel('$t$ [s]') plt.axvline(x=0,color='black',linewidth=0.8) plt.axhline(y=0,color='black',linewidth=0.8) plt.grid() fig.add_subplot(224) plt.title('Estimation errors') plt.ylabel('Errors') plt.plot(T,xout[4]-xout[0]) plt.plot(T,xout[5]-xout[1]) plt.plot(T,xout[6]-xout[2]) plt.plot(T,xout[7]-xout[3]) plt.xlabel('$t$ [s]') plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$','$e_{4}$']) plt.axvline(x=0,color='black',linewidth=0.8) plt.axhline(y=0,color='black',linewidth=0.8) plt.grid() #plt.tight_layout() alltogether2 = widgets.VBox([widgets.HBox([selm, selec, seleo, selu]), widgets.Label(' ',border=3), widgets.HBox([widgets.HBox([widgets.Label('K:',border=3), Kw, widgets.Label('Eigenvalues:',border=3), widgets.HBox([eig1c, eig2c, eig3c, eig4c])])]), widgets.Label(' ',border=3), widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3), widgets.Label(' ',border=3), widgets.Label('Eigenvalues:',border=3), eig1o, eig2o, eig3o, eig4o, widgets.Label(' ',border=3), widgets.Label(' ',border=3), widgets.Label('X0 est.:',border=3), X0w]), widgets.Label(' ',border=3), widgets.HBox([ widgets.VBox([widgets.Label('Simulation time (s):',border=3)]), widgets.VBox([simTime])])]), widgets.Label(' ',border=3)]), widgets.Label(' ',border=3), widgets.HBox([u, ud, period, START])]) out2 = widgets.interactive_output(main_callback2, {'ud':ud, 'X0w':X0w, 'K':Kw, 'L':Lw, 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, 'eig4o':eig4o, 'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW}) out2.layout.height = '860px' display(out2, alltogether2) ```
github_jupyter
### ะ›ะฐะฑะพั€ะฐั‚ะพั€ะฝะฐั ั€ะฐะฑะพั‚ะฐ โ„–5. Capacitated Vehicle Routing Problem ะ˜ะปัŒั ะกะตะดัƒะฝะพะฒ, <br> ะ’ะฐะดะธะผ ะะปัŒะฟะตั€ะพะฒะธั‡, <br> 17ะŸะœะ˜ ![](output/images/problemn35-k5.vrp.png) ### Random solution ![](output/images/beforeABC_n35-k5.vrp.png) ## Artifical Bee Colony (ABC) algorithm ### Fitness function ![](output/images/history_n35-k5.vrp.png) ### And solution with 200 epochs ![](output/images/afterABC_n35-k5.vrp.png) # A-benchmarks --- | | benchmark | n_locations | n_trucks | capacity | optimal_cost | ABC_cost | ABC_time | error | is_feasible | |---:|:--------------|--------------:|-----------:|-----------:|---------------:|-----------:|-----------:|----------:|:--------------| | 0 | A-n32-k5.vrp | 32 | 5 | 100 | 784 | 793.689 | 34.4186 | 0.0123585 | True | | 1 | A-n33-k5.vrp | 33 | 5 | 100 | 661 | 677.849 | 33.94 | 0.0254898 | True | | 2 | A-n33-k6.vrp | 33 | 6 | 100 | 742 | 789.651 | 35.5225 | 0.0642203 | True | | 3 | A-n34-k5.vrp | 34 | 5 | 100 | 778 | 890.053 | 34.7679 | 0.144027 | True | | 4 | A-n36-k5.vrp | 36 | 5 | 100 | 799 | 902.63 | 39.6765 | 0.129699 | True | | 5 | A-n37-k5.vrp | 37 | 5 | 100 | 669 | 722.61 | 40.3947 | 0.0801341 | True | | 6 | A-n37-k6.vrp | 37 | 6 | 100 | 949 | 1002.95 | 41.3557 | 0.0568444 | True | | 7 | A-n38-k5.vrp | 38 | 5 | 100 | 730 | 796.663 | 39.2311 | 0.0913186 | True | | 8 | A-n39-k5.vrp | 39 | 5 | 100 | 822 | 917.818 | 41.4462 | 0.116567 | True | | 9 | A-n39-k6.vrp | 39 | 6 | 100 | 831 | 1039.23 | 46.8593 | 0.250572 | True | | 10 | A-n44-k6.vrp | 44 | 6 | 100 | 937 | 987.494 | 51.036 | 0.0538888 | True | | 11 | A-n45-k6.vrp | 45 | 6 | 100 | 944 | 1209.34 | 55.1767 | 0.281077 | True | | 12 | A-n45-k7.vrp | 45 | 7 | 100 | 1146 | 1270.99 | 62.4989 | 0.109066 | True | | 13 | A-n46-k7.vrp | 46 | 7 | 100 | 914 | 1030.53 | 73.3458 | 0.127491 | True | | 14 | A-n48-k7.vrp | 48 | 7 | 100 | 1073 | 1195.6 | 71.0007 | 0.114257 | True | | 15 | A-n53-k7.vrp | 53 | 7 | 100 | 1010 | 1151.61 | 82.1195 | 0.140208 | True | | 16 | A-n54-k7.vrp | 54 | 7 | 100 | 1167 | 1331.5 | 86.6397 | 0.140958 | True | | 17 | A-n55-k9.vrp | 55 | 9 | 100 | 1073 | 1147.89 | 98.8293 | 0.0697974 | True | | 18 | A-n60-k9.vrp | 60 | 9 | 100 | 1354 | 1502.62 | 118.18 | 0.109762 | True | | 19 | A-n61-k9.vrp | 61 | 9 | 100 | 1034 | 1398.01 | 129.125 | 0.352039 | True | | 20 | A-n62-k8.vrp | 62 | 8 | 100 | 1288 | 1517.37 | 119.281 | 0.178084 | True | | 21 | A-n63-k10.vrp | 63 | 10 | 100 | 1314 | 1515.19 | 127.642 | 0.153113 | True | | 22 | A-n63-k9.vrp | 63 | 9 | 100 | 1616 | 1959.36 | 131.052 | 0.212478 | True | | 23 | A-n64-k9.vrp | 64 | 9 | 100 | 1401 | 1664.51 | 122.621 | 0.188088 | True | | 24 | A-n65-k9.vrp | 65 | 9 | 100 | 1174 | 1558.45 | 133.355 | 0.327473 | True | | 25 | A-n69-k9.vrp | 69 | 9 | 100 | 1159 | 1434.53 | 154.796 | 0.237731 | True | | 26 | A-n80-k10.vrp | 80 | 10 | 100 | 1763 | 2203.57 | 184.733 | 0.249898 |True # B-benchmarks --- | | benchmark | n_locations | n_trucks | capacity | optimal_cost | ABC_cost | ABC_time | error | is_feasible | |---:|:--------------|--------------:|-----------:|-----------:|---------------:|-----------:|-----------:|----------:|:--------------| | 0 | B-n31-k5.vrp | 31 | 5 | 100 | 672 | 706.569 | 20.9377 | 0.0514423 | True | | 1 | B-n34-k5.vrp | 34 | 5 | 100 | 788 | 808.974 | 23.4713 | 0.0266171 | True | | 2 | B-n35-k5.vrp | 35 | 5 | 100 | 955 | 996.195 | 24.5341 | 0.0431363 | True | | 3 | B-n38-k6.vrp | 38 | 6 | 100 | 805 | 820.224 | 28.2701 | 0.0189118 | True | | 4 | B-n39-k5.vrp | 39 | 5 | 100 | 549 | 567.277 | 26.7929 | 0.0332911 | True | | 5 | B-n41-k6.vrp | 41 | 6 | 100 | 829 | 947.016 | 30.4575 | 0.142359 | True | | 6 | B-n43-k6.vrp | 43 | 6 | 100 | 742 | 777.761 | 33.5126 | 0.0481955 | True | | 7 | B-n44-k7.vrp | 44 | 7 | 100 | 909 | 985.969 | 36.6416 | 0.0846748 | True | | 8 | B-n45-k5.vrp | 45 | 5 | 100 | 751 | 796.818 | 32.5534 | 0.0610096 | True | | 9 | B-n45-k6.vrp | 45 | 6 | 100 | 678 | 768.834 | 37.3276 | 0.133974 | True | | 10 | B-n50-k7.vrp | 50 | 7 | 100 | 741 | 763.865 | 41.6256 | 0.0308568 | True | | 11 | B-n50-k8.vrp | 50 | 8 | 100 | 1312 | 1354.85 | 44.7541 | 0.0326566 | True | | 12 | B-n51-k7.vrp | 51 | 7 | 100 | 1032 | 1124.62 | 42.9064 | 0.0897509 | True | | 13 | B-n52-k7.vrp | 52 | 7 | 100 | 747 | 818.84 | 43.2389 | 0.0961716 | True | | 14 | B-n56-k7.vrp | 56 | 7 | 100 | 707 | 792.316 | 47.4659 | 0.120674 | True | | 15 | B-n57-k7.vrp | 57 | 7 | 100 | 1153 | 1555.21 | 66.0018 | 0.348837 | True | | 16 | B-n57-k9.vrp | 57 | 9 | 100 | 1598 | 1740.66 | 57.6039 | 0.0892725 | True | | 17 | B-n63-k10.vrp | 63 | 10 | 100 | 1496 | 1775.97 | 75.6478 | 0.187143 | True | | 18 | B-n64-k9.vrp | 64 | 9 | 100 | 861 | 1082.98 | 75.0857 | 0.257812 | True | | 19 | B-n66-k9.vrp | 66 | 9 | 100 | 1316 | 1611.2 | 82.5796 | 0.224317 | True | | 20 | B-n67-k10.vrp | 67 | 10 | 100 | 1032 | 1206.82 | 86.4656 | 0.169402 | True | | 21 | B-n68-k9.vrp | 68 | 9 | 100 | 1272 | 1442.81 | 67.5301 | 0.134288 | True | | 22 | B-n78-k10.vrp | 78 | 10 | 100 | 1221 | 1602.17 | 93.2046 | 0.312182 | True |
github_jupyter
Kantonsschule Olten (Mel), #KLASSE, #RAUM, #DATUM # Informatik-Prรผfung 1 --- __Name__: #BITTE_DIESEN_TEXT_ERSETZEN --- |#|Aufgabe|maximal|erreicht| |:---|:---|:---|:---| |1|Speichern mit richtigem Dateinamen |1| | |2|String Variable definieren |1| | |3|Liste von Strings definieren|1| | |4|Prรคfix un hinzufรผgen|1| | |5|Beliebigen Suffix hinzufรผgen|1| | |6|Letztes Element|1| | |7|Drei-Zeichen-Woerter filtern|1| | |8|Vermรถgenssteuer Paradisia|1| | |9|Liste Quadratzahlen Von Bis|1| | |10|Jeden Zweiten Buchstaben lรถschen|1| | |||| | |x|Abgabezeitfenster รผberschritten|-10| | |__Total__||10 | | __Abgabe__: via Teams, Aufgaben -> Prรผfung 1 -> Abgabe -> Anhang hinzufรผgen -> Abgeben Beachten Sie die Abgabefristen! Bei verspรคtet in Teams abgegebener Datei kann pro angefangener Minute Verspรคtung bis zu einem Punkt abgezogen werden. __Speichern__: der Dateiname laute *Klasse_NameVorname_Pruefung1.ipynb* Speichern sie ihr Notebook von Zeit zu Zeit mit einem Klick auf das Diskettensymbol oben links, um im Falle eines technischen Problems keine unnรถtige Zeit mit der Wiederherstellung ihres Codes zu verlieren. __Frรผhzeitiges Verlassen__: Die Prรผfung kann nicht frรผhzeitig verlassen werden. Wenn Sie frรผhzeitig in Teams Ihr Notebook abgegeben haben, bleiben Sie bitte ruhig bis zum Ende der Prรผfung am Platz sitzen. __Zugelassene Hilfsmittel__: - [Python-Spickzettel](http://www.jython.ch/download/spickzettel.pdf) - [Python Dokumentation](https://docs.python.org/3/library/functions.html) - [Ihre OneNote Unterlagen](https://www.office.com/launch/onenote) - [Suchmaschine Ihres Vertrauens](https://de.wikipedia.org/wiki/Liste_von_Internet-Suchmaschinen) und alle fรผr Sie relevanten Inhalte, die Sie damit finden kรถnnen --- __Unredliches Handeln:__ Sie mรผssen die Aufgaben selbstรคndig lรถsen. __Jegliche__ direkte oder indirekte __Kommunikation__ mit Menschen wรคhrend der Prรผfung oder die Benutzung anderer Hilfsmittel als des Schulcomputers wird fรผr alle Beteiligten als __Betrugsversuch__ gewertet und entsprechend der fรผr Sie aktuell gรผltigen Prรผfungsordnung __geahndet__. Wรคhrend der Prรผfung wird ihr Bildschirminhalt aufgezeichnet. Die nรคchste Zelle mรผssen Sie <span style="color:red">einmalig</span> ausfรผhren, damit spรคter die Ausfรผhrung der im Python-Docstring eingebetteten Tests funktionieren. Mittels "Cell -> All Output -> Clear" kรถnnen Sie die Ausgaben zurรผcksetzen. Sie kรถnnen das Notebook, etwa im Falle eines technischen Fehlers, via "Kernel -> Restart" neu starten. Vergessen Sie nicht, vorher zu speichern. ``` from doctest import run_docstring_examples ``` ## Speichern mit richtigem Dateinamen (1P) Speichern Sie dieses Notebook __jetzt__ unter dem Namen *Klasse_NameVorname_Pruefung1.ipynb*. Ersetzen Sie dabei *Klasse* und *NameVorname* mit den fรผr Sie zutreffenden Werten. Auf Teams hochgeladene Notebooks, die dieser Konvention strikt folgen, erhalten 1P. ## String Variable definieren (1P) Definieren Sie eine String Variable "__NAME__" und belegen sie diese mit dem Wert: Informatik Ihre Lรถsung: ## Liste von Strings definieren (1P) Definieren Sie eine Listen-Variable mit Namen "__TONLEITER__" und belegen Sie diese mit den Buchstaben c,d,e,f,g,a,h,c Ihre Lรถsung: ## Prรคfix un hinzufรผgen (1P) Erstellen Sie eine Funktion __add_prefix_un(input_string)__, die als Parameter einen String entgegennimmt. Der Rรผckgabewert der Funktion sei der Eingabestring plus Prรคfix "un". Beispiel: - add_prefix_un("lรถsbar") soll den String "unlรถsbar" zurรผckgeben. - add_prefix_un("verwundbar") soll den String "unverwundbar" zurรผckgeben. Ihre Lรถsung: ``` def add_prefix_un(input_string): """ Fรผgt den Prรคfix "un" zur Eingabe hinzu. Tests: >>> print(add_prefix_un("lรถsbar")) unlรถsbar >>> print(add_prefix_un("verwundbar")) unverwundbar """ pass run_docstring_examples(add_prefix_un, locals()) ``` ## Beliebigen Suffix hinzufรผgen (1P) Erstellen sie eine Funktion add_suffix(suffix, word), die zwei Paramter entgegennimmt. Beide Parameter seien Strings, der erste ein Suffix, der zweite ein Wort. Der Rรผckgabewert der Funktion sei das Wort mit angehรคngtem Suffix. Beispiel: - add_suffix("ung", "Lรถs") soll den String "Lรถsung" zurรผckgeben. - add_suffix("keit", "Lรถsbar") soll den String "Lรถsbarkeit" zurรผckgeben. - add_suffix("heit", "Frei") soll den String "Freiheit" zurรผckgeben. Ihre Lรถsung: ``` def add_suffix(suffix, word): """ Fรผgt den als ersten Parameter gegebenen Suffix zum zweiten Parameter, dem Wort, hinzu. Tests: >>> print(add_suffix("ung", "Lรถs")) Lรถsung >>> print(add_suffix("keit", "Lรถsbar")) Lรถsbarkeit >>> print(add_suffix("heit", "Frei")) Freiheit """ pass run_docstring_examples(add_suffix, locals()) ``` ## Letztes Element Erstellen Sie eine Funktion __letztes_listenelement(input_liste)__, die als Parameter einen Liste entgegennimmt. Der Rรผckgabewert der Funktion sei das letzte Element der Liste. Beispiel: - letztes_listenelement(["Hans", "Rot", "Bau", "Klausi"]) soll die Liste ["Klausi"] zurรผckgeben. - letztes_listenelement(["Hansi", "Klaus", "Rot"]) soll die Liste ["Rot"] zurรผckgeben. - letztes_listenelement(["Peter", "Manuela", "Maus", "Kind", "Velo"]) soll die Liste ["Velo"] zurรผckgeben. Ihre Lรถsung: ``` def letztes_listenelement(input_liste): """ Gibt das letzte Element einer Liste zurรผck Tests: >>> print(letztes_listenelement(['Hans', 'Rot', 'Bau'])) Bau >>> print(letztes_listenelement(['Hans', 'Klaus', 'Dieter'])) Dieter """ pass run_docstring_examples(letztes_listenelement, locals()) ``` ## Drei-Zeichen-Woerter filtern (dzwf) Erstellen Sie eine Funktion __dzwf(input_liste)__, die als Parameter einen Liste von Strings entgegennimmt. Der Rรผckgabewert der Funktion sei eine Liste, die alle die Eintrรคge der Eingabe enthรคlt, die drei Zeichen lang sind. Beispiel: - dzwf(["Hans", "Rot", "Bau"]) soll die Liste ["Rot", "Bau"] zurรผckgeben. - dzwf(["Hans", "Klaus", "Dieter"]) soll die Liste [] zurรผckgeben. Ihre Lรถsung: ``` def dzwf(input_liste): """ Filter alle Element von 3 Zeichen Lรคnge aus einer Liste. Tests: >>> print(dzwf(['Hans', 'Rot', 'Bau'])) ['Rot', 'Bau'] >>> print(dzwf(['Hans', 'Klaus', 'Dieter'])) ['Rot', 'Bau'] """ pass run_docstring_examples(dzwf, locals()) ``` ## Vermรถgenssteuer Paradisia Schreibe eine Funktion __vermoegenssteuer_paradisia(vermoegen)__, welche die zu zahlende Vermoegenssteuer jedes Steuerzahlers in Paradisia berechnet. Die Ausgabe der soll die zu zahlende Steuer sein. Der Vermรถgenssteuersatz in Paradisia wird gemรคss folgender Tabelle bestimmt: |Vermรถgen x|Steuersatz in % |--|-- | x < 1'000'000| 0 | x >= 1'000'000| 1 Beispiel: - vermoegenssteuer_paradisia(0) soll 0.0 zurรผckgeben - vermoegenssteuer_paradisia(20000) soll 0.0 zurรผckgeben - vermoegenssteuer_paradisia(250000) soll 0.0 zurรผckgeben - vermoegenssteuer_paradisia(1000000) soll 10000.0 zurรผckgeben Ihre Lรถsung: ``` def vermoegenssteuer_paradisia(vermoegen): """ Berechnet die Vermรถgenssteuer in Abhรคngigkeit vom Vermรถgen. Tests: >>> print(vermoegenssteuer_paradisia(0)) 0.0 >>> print(vermoegenssteuer_paradisia(20000)) 0.0 >>> print(vermoegenssteuer_paradisia(250000)) 0.0 >>> print(vermoegenssteuer_paradisia(1000000)) 10000.0 """ pass run_docstring_examples(vermoegenssteuer_paradisia, locals()) ``` ## Liste Quadratzahlen Von Bis Erstellen Sie eine Funktion __quadratzahlen_von_bis(erstes_element, letztes_element)__, die als Parameter zwei ganze Zahlen erhรคlt. Der Rรผckgabewert der Funktion sei eine Liste, welche die Quadratzahlen aller Ganzzzahlen zwischen den Parametern enthรคlt. Beispiel: - quadratzahlen_von_bis(0,3) soll die Liste [0, 1, 4, 9] zurรผckgeben. - quadratzahlen_von_bis(4,10) soll die Liste [16, 25, 36, 47, 64, 81, 100] zurรผckgeben. Ihre Lรถsung: ``` def quadratzahlen_von_bis(erstes_element, letztes_element): """ Gibt eine Liste der Quadratzahlen zwischen den Parametern zurรผck. Tests: >>> print(quadratzahlen_von_bis(0, 3)) [0, 1, 4, 9] >>> print(quadratzahlen_von_bis(4, 10)) [16, 25, 36, 49, 64, 81, 100] """ pass run_docstring_examples(quadratzahlen_von_bis, locals()) ``` ## Jeden Zweiten Buchstaben lรถschen (jzbl) Erstellen Sie eine Funktion __jzbl(input_string)__, die als Parameter einen String entgegennimmt. Der Rรผckgabewert der Funktion sei der Eingabestring, wobei jeder zweite Buchstabe entfernt wird. Beispiel: - jzbl("H") soll den String "H" zurรผckgeben. - jzbl("HA") soll den String "H" zurรผckgeben. - jzbl("HAL") soll den String "HL" zurรผckgeben. - jzbl("HALL") soll den String "HL" zurรผckgeben. - jzbl("HALLO") soll den String "HLO" zurรผckgeben. TIMTOWTDI! Die Musterlรถsung nutzt folgende Konzepte: - eine while-Schleife mit Zรคhlvariable "i" zum Interieren รผber alle Elemente von input_string - len() zur Bestimmung der Anzahl der Buchstaben in input_string - Zugriff auf einzelne Elemente mit input_string[i] - "if i % 2 == 0:" (Modus 2 = 0 -> gerade Zahl) der Zรคhlvariablen "i" um zu bestimmen, ob ein gegebener Buchstabe zum Ergebnis gehรถrt oder verworfen wird - "+" zum Zusammenfรผgen der Einzelbuchstaben zum Ergebnisses - return() zum Zurรผckgeben des Ergebnisses Ihre Lรถsung: ``` def jzbl(input_string): """ Lรถscht jeden zweiten Buchstaben des Eingabe-Strings und gibt den so verkรผrzten String zurรผck. Tests: >>> print(jzbl("H")) H >>> print(jzbl("Ha")) H >>> print(jzbl("Hallo")) Hlo """ pass run_docstring_examples(jzbl, locals()) ```
github_jupyter
# FINN - Functional Verification of End-to-End Flow ----------------------------------------------------------------- **Important: This notebook depends on the tfc_end2end_example notebook, because we are using models that are available at intermediate steps in the end-to-end flow. So please make sure the needed .onnx files are generated to run this notebook.** In this notebook, we will show how to take the intermediate results of the end-to-end tfc example and verify their functionality with different methods. In the following picture you can see the section in the end-to-end flow about the *Simulation & Emulation Flows*. Besides the methods in this notebook, there is another one that is covered in the Jupyter notebook [tfc_end2end_example](tfc_end2end_example.ipynb): remote execution. The remote execution allows functional verification directly on the PYNQ board, for details please have a look at the mentioned Jupyter notebook. <img src="verification.png" alt="Drawing" style="width: 500px;"/> We will use the following helper functions, `showSrc` to show source code of FINN library calls and `showInNetron` to show the ONNX model at the current transformation step. The Netron displays are interactive, but they only work when running the notebook actively and not on GitHub (i.e. if you are viewing this on GitHub you'll only see blank squares). ``` from finn.util.basic import make_build_dir from finn.util.visualization import showSrc, showInNetron build_dir = "/workspace/finn" ``` To verify the simulations, a "golden" output is calculated as a reference. This is calculated directly from the Brevitas model using PyTorch, by running some example data from the MNIST dataset through the trained model. ``` from pkgutil import get_data import onnx import onnx.numpy_helper as nph import torch from finn.util.test import get_test_model_trained fc = get_test_model_trained("TFC", 1, 1) raw_i = get_data("finn", "data/onnx/mnist-conv/test_data_set_0/input_0.pb") input_tensor = onnx.load_tensor_from_string(raw_i) input_brevitas = torch.from_numpy(nph.to_array(input_tensor)).float() output_golden = fc.forward(input_brevitas).detach().numpy() output_golden ``` ## Simulation using Python <a id='simpy'></a> If an ONNX model consists of [standard ONNX](https://github.com/onnx/onnx/blob/master/docs/Operators.md) nodes and/or FINN custom operations that do not belong to the fpgadataflow (backend $\neq$ "fpgadataflow") this model can be checked for functionality using Python. To simulate a standard ONNX node [onnxruntime](https://github.com/microsoft/onnxruntime) is used. onnxruntime is an open source tool developed by Microsoft to run standard ONNX nodes. For the FINN custom op nodes execution functions are defined. The following is an example of the execution function of a XNOR popcount node. ``` from finn.custom_op.xnorpopcount import xnorpopcountmatmul showSrc(xnorpopcountmatmul) ``` The function contains a description of the behaviour in Python and can thus calculate the result of the node. This execution function and onnxruntime is used when `execute_onnx` from `onnx_exec` is applied to the model. The model is then simulated node by node and the result is stored in a context dictionary, which contains the values of each tensor at the end of the execution. To get the result, only the output tensor has to be extracted. The procedure is shown below. We take the model right before the nodes should be converted into HLS layers and generate an input tensor to pass to the execution function. The input tensor is generated from the Brevitas example inputs. ``` import numpy as np from finn.core.modelwrapper import ModelWrapper input_dict = {"global_in": nph.to_array(input_tensor)} model_for_sim = ModelWrapper(build_dir+"/tfc_w1a1_ready_for_hls_conversion.onnx") import finn.core.onnx_exec as oxe output_dict = oxe.execute_onnx(model_for_sim, input_dict) output_pysim = output_dict[list(output_dict.keys())[0]] if np.isclose(output_pysim, output_golden, atol=1e-3).all(): print("Results are the same!") else: print("The results are not the same!") ``` The result is compared with the theoretical "golden" value for verification. ## Simulation (cppsim) using C++ When dealing with HLS custom op nodes in FINN the simulation using Python is no longer sufficient. After the nodes have been converted to HLS layers, the simulation using C++ can be used. To do this, the input tensor is stored in an .npy file and C++ code is generated that reads the values from the .npy array, streams them to the corresponding finn-hlslib function and writes the result to a new .npy file. This in turn can be read in Python and processed in the FINN flow. For this example the model after setting the folding factors in the HLS layers is used, please be aware that this is not the full model, but the dataflow partition, so before executing at the end of this section we have to integrate the model back into the parent model. ``` model_for_cppsim = ModelWrapper(build_dir+"/tfc_w1_a1_set_folding_factors.onnx") ``` To generate the code for this simulation and to generate the executable two transformations are used: * `PrepareCppSim` which generates the C++ code for the corresponding hls layer * `CompileCppSim` which compules the C++ code and stores the path to the executable ``` from finn.transformation.fpgadataflow.prepare_cppsim import PrepareCppSim from finn.transformation.fpgadataflow.compile_cppsim import CompileCppSim from finn.transformation.general import GiveUniqueNodeNames model_for_cppsim = model_for_cppsim.transform(GiveUniqueNodeNames()) model_for_cppsim = model_for_cppsim.transform(PrepareCppSim()) model_for_cppsim = model_for_cppsim.transform(CompileCppSim()) ``` When we take a look at the model using netron, we can see that the transformations introduced new attributes. ``` model_for_cppsim.save(build_dir+"/tfc_w1_a1_for_cppsim.onnx") showInNetron(build_dir+"/tfc_w1_a1_for_cppsim.onnx") ``` The following node attributes have been added: * `code_gen_dir_cppsim` indicates the directory where the files for the simulation using C++ are stored * `executable_path` specifies the path to the executable We take now a closer look into the files that were generated: ``` from finn.custom_op.registry import getCustomOp fc0 = model_for_cppsim.graph.node[1] fc0w = getCustomOp(fc0) code_gen_dir = fc0w.get_nodeattr("code_gen_dir_cppsim") !ls {code_gen_dir} ``` Besides the .cpp file, the folder contains .h files with the weights and thresholds. The shell script contains the compile command and *node_model* is the executable generated by compilation. Comparing this with the `executable_path` node attribute, it can be seen that it specifies exactly the path to *node_model*. To simulate the model the execution mode(exec_mode) must be set to "cppsim". This is done using the transformation SetExecMode. ``` from finn.transformation.fpgadataflow.set_exec_mode import SetExecMode model_for_cppsim = model_for_cppsim.transform(SetExecMode("cppsim")) model_for_cppsim.save(build_dir+"/tfc_w1_a1_for_cppsim.onnx") ``` Before the model can be executed using `execute_onnx`, we integrate the child model in the parent model. The function reads then the `exec_mode` and writes the input into the correct directory in a .npy file. To be able to read this in C++, there is an additional .hpp file ([npy2apintstream.hpp](https://github.com/Xilinx/finn/blob/master/src/finn/data/cpp/npy2apintstream.hpp)) in FINN, which uses cnpy to read .npy files and convert them into streams, or to read a stream and write it into an .npy. [cnpy](https://github.com/rogersce/cnpy) is a helper to read and write .npy and .npz formates in C++. The result is again compared to the "golden" output. ``` parent_model = ModelWrapper(build_dir+"/tfc_w1_a1_dataflow_parent.onnx") sdp_node = parent_model.graph.node[2] child_model = build_dir + "/tfc_w1_a1_for_cppsim.onnx" getCustomOp(sdp_node).set_nodeattr("model", child_model) output_dict = oxe.execute_onnx(parent_model, input_dict) output_cppsim = output_dict[list(output_dict.keys())[0]] if np.isclose(output_cppsim, output_golden, atol=1e-3).all(): print("Results are the same!") else: print("The results are not the same!") ``` ## Emulation (rtlsim) using PyVerilator The emulation using [PyVerilator](https://github.com/maltanar/pyverilator) can be done after IP blocks are generated from the corresponding HLS layers. Pyverilator is a tool which makes it possible to simulate verilog files using verilator via a python interface. We have two ways to use rtlsim, one is to run the model node-by-node as with the simulation methods, but if the model is in the form of the dataflow partition, the part of the graph that consist of only HLS nodes could also be executed as whole. Because at the point where we want to grab and verify the model, the model is already in split form (parent graph consisting of non-hls layers and child graph consisting only of hls layers) we first have to reference the child graph within the parent graph. This is done using the node attribute `model` for the `StreamingDataflowPartition` node. First the procedure is shown, if the child graph has ip blocks corresponding to the individual layers, then the procedure is shown, if the child graph already has a stitched IP. ### Emulation of model node-by-node The child model is loaded and the `exec_mode` for each node is set. To prepare the node-by-node emulation the transformation `PrepareRTLSim` is applied to the child model. With this transformation the emulation files are created for each node and can be used directly when calling `execute_onnx()`. Each node has a new node attribute "rtlsim_so" after transformation, which contains the path to the corresponding emulation files. Then it is saved in a new .onnx file so that the changed model can be referenced in the parent model. ``` from finn.transformation.fpgadataflow.prepare_rtlsim import PrepareRTLSim child_model = ModelWrapper(build_dir + "/tfc_w1_a1_ipgen.onnx") child_model = child_model.transform(SetExecMode("rtlsim")) child_model = child_model.transform(PrepareRTLSim()) child_model.save(build_dir + "/tfc_w1_a1_dataflow_child.onnx") ``` The next step is to load the parent model and set the node attribute `model` in the StreamingDataflowPartition node (`sdp_node`). Afterwards the `exec_mode` is set in the parent model in each node. ``` # parent model model_for_rtlsim = ModelWrapper(build_dir + "/tfc_w1_a1_dataflow_parent.onnx") # reference child model sdp_node = getCustomOp(model_for_rtlsim.graph.node[2]) sdp_node.set_nodeattr("model", build_dir + "/tfc_w1_a1_dataflow_child.onnx") model_for_rtlsim = model_for_rtlsim.transform(SetExecMode("rtlsim")) ``` Because the necessary files for the emulation are already generated in Jupyter notebook [tfc_end2end_example](tfc_end2end_example.ipynb), in the next step the execution of the model can be done directly. ``` output_dict = oxe.execute_onnx(model_for_rtlsim, input_dict) output_rtlsim = output_dict[list(output_dict.keys())[0]] if np.isclose(output_rtlsim, output_golden, atol=1e-3).all(): print("Results are the same!") else: print("The results are not the same!") ``` ### Emulation of stitched IP Here we use the same procedure. First the child model is loaded, but in contrast to the layer-by-layer emulation, the metadata property `exec_mode` is set to "rtlsim" for the whole child model. When the model is integrated and executed in the last step, the verilog files of the stitched IP of the child model are used. ``` child_model = ModelWrapper(build_dir + "/tfc_w1_a1_ipstitch.onnx") child_model.set_metadata_prop("exec_mode","rtlsim") child_model.save(build_dir + "/tfc_w1_a1_dataflow_child.onnx") # parent model model_for_rtlsim = ModelWrapper(build_dir + "/tfc_w1_a1_dataflow_parent.onnx") # reference child model sdp_node = getCustomOp(model_for_rtlsim.graph.node[2]) sdp_node.set_nodeattr("model", build_dir + "/tfc_w1_a1_dataflow_child.onnx") output_dict = oxe.execute_onnx(model_for_rtlsim, input_dict) output_rtlsim = output_dict[list(output_dict.keys())[0]] if np.isclose(output_rtlsim, output_golden, atol=1e-3).all(): print("Results are the same!") else: print("The results are not the same!") ```
github_jupyter
# Using Tensorflow DALI plugin: using various readers ### Overview This example shows how different readers could be used to interact with Tensorflow. It shows how flexible DALI is. The following readers are used in this example: - MXNetReader - CaffeReader - FileReader - TFRecordReader For details on how to use them please see other [examples](..). Let us start with defining some global constants ``` import os.path test_data_root = os.environ['DALI_EXTRA_PATH'] # MXNet RecordIO db_folder = os.path.join(test_data_root, 'db', 'recordio/') # Caffe LMDB lmdb_folder = os.path.join(test_data_root, 'db', 'lmdb') # image dir with plain jpeg files image_dir = "../images" # TFRecord tfrecord = os.path.join(test_data_root, 'db', 'tfrecord', 'train') tfrecord_idx = "idx_files/train.idx" tfrecord2idx_script = "tfrecord2idx" N = 8 # number of GPUs BATCH_SIZE = 128 # batch size per GPU ITERATIONS = 32 IMAGE_SIZE = 3 ``` Create idx file by calling `tfrecord2idx` script ``` from subprocess import call import os.path if not os.path.exists("idx_files"): os.mkdir("idx_files") if not os.path.isfile(tfrecord_idx): call([tfrecord2idx_script, tfrecord, tfrecord_idx]) ``` Let us define: - common part of pipeline, other pipelines will inherit it ``` from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops import nvidia.dali.types as types class CommonPipeline(Pipeline): def __init__(self, batch_size, num_threads, device_id): super(CommonPipeline, self).__init__(batch_size, num_threads, device_id) self.decode = ops.ImageDecoder(device = "mixed", output_type = types.RGB) self.resize = ops.Resize(device = "gpu", image_type = types.RGB, interp_type = types.INTERP_LINEAR) self.cmn = ops.CropMirrorNormalize(device = "gpu", output_dtype = types.FLOAT, crop = (227, 227), image_type = types.RGB, mean = [128., 128., 128.], std = [1., 1., 1.]) self.uniform = ops.Uniform(range = (0.0, 1.0)) self.resize_rng = ops.Uniform(range = (256, 480)) def base_define_graph(self, inputs, labels): images = self.decode(inputs) images = self.resize(images, resize_shorter = self.resize_rng()) output = self.cmn(images, crop_pos_x = self.uniform(), crop_pos_y = self.uniform()) return (output, labels.gpu()) ``` - MXNetReaderPipeline ``` from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops import nvidia.dali.types as types class MXNetReaderPipeline(CommonPipeline): def __init__(self, batch_size, num_threads, device_id, num_gpus): super(MXNetReaderPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.MXNetReader(path = [db_folder+"train.rec"], index_path=[db_folder+"train.idx"], random_shuffle = True, shard_id = device_id, num_shards = num_gpus) def define_graph(self): images, labels = self.input(name="Reader") return self.base_define_graph(images, labels) ``` - CaffeReadPipeline ``` class CaffeReadPipeline(CommonPipeline): def __init__(self, batch_size, num_threads, device_id, num_gpus): super(CaffeReadPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.CaffeReader(path = lmdb_folder, random_shuffle = True, shard_id = device_id, num_shards = num_gpus) def define_graph(self): images, labels = self.input() return self.base_define_graph(images, labels) ``` - FileReadPipeline ``` class FileReadPipeline(CommonPipeline): def __init__(self, batch_size, num_threads, device_id, num_gpus): super(FileReadPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.FileReader(file_root = image_dir) def define_graph(self): images, labels = self.input() return self.base_define_graph(images, labels) ``` - TFRecordPipeline ``` import nvidia.dali.tfrecord as tfrec class TFRecordPipeline(CommonPipeline): def __init__(self, batch_size, num_threads, device_id, num_gpus): super(TFRecordPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.TFRecordReader(path = tfrecord, index_path = tfrecord_idx, features = {"image/encoded" : tfrec.FixedLenFeature((), tfrec.string, ""), "image/class/label": tfrec.FixedLenFeature([1], tfrec.int64, -1) }) def define_graph(self): inputs = self.input() images = inputs["image/encoded"] labels = inputs["image/class/label"] return self.base_define_graph(images, labels) ``` Now let us create function which builds pipeline on demand: ``` import tensorflow as tf import nvidia.dali.plugin.tf as dali_tf try: from tensorflow.compat.v1 import GPUOptions from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import Session from tensorflow.compat.v1 import placeholder except: # Older TF versions don't have compat.v1 layer from tensorflow import GPUOptions from tensorflow import ConfigProto from tensorflow import Session from tensorflow import placeholder try: tf.compat.v1.disable_eager_execution() except: pass def get_batch_test_dali(batch_size, pipe_type): pipe_name, label_type, _ = pipe_type pipes = [pipe_name(batch_size=batch_size, num_threads=2, device_id = device_id, num_gpus = N) for device_id in range(N)] daliop = dali_tf.DALIIterator() images = [] labels = [] for d in range(N): with tf.device('/gpu:%i' % d): image, label = daliop(pipeline = pipes[d], shapes = [(BATCH_SIZE, 3, 227, 227), ()], dtypes = [tf.int32, label_type], device_id = d) images.append(image) labels.append(label) return [images, labels] ``` At the end let us test if all pipelines have been correctly built and run with TF session ``` from __future__ import print_function import numpy as np pipe_types = [[MXNetReaderPipeline, tf.float32, (0, 999)], [CaffeReadPipeline, tf.int32, (0, 999)], [FileReadPipeline, tf.int32, (0, 1)], [TFRecordPipeline, tf.int64, (1, 1000)]] for pipe_name in pipe_types: print ("RUN: " + pipe_name[0].__name__) test_batch = get_batch_test_dali(BATCH_SIZE, pipe_name) x = placeholder(tf.float32, shape=[BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3], name='x') gpu_options = GPUOptions(per_process_gpu_memory_fraction=0.8) config = ConfigProto(gpu_options=gpu_options) with Session(config=config) as sess: for i in range(ITERATIONS): imgs, labels = sess.run(test_batch) # Testing correctness of labels for label in labels: ## labels need to be integers assert(np.equal(np.mod(label, 1), 0).all()) ## labels need to be in range pipe_name[2] assert((label >= pipe_name[2][0]).all()) assert((label <= pipe_name[2][1]).all()) print("OK : " + pipe_name[0].__name__) ```
github_jupyter
``` from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import StringType import time import numpy as np sc =SparkContext.getOrCreate() sqlContext = SQLContext(sc) def readCSV(path): ''' read csv file return spark sql data frame ''' return sqlContext.read.format("csv").options(header="true")\ .load(path) team_df = readCSV("/Users/peggy/Desktop/footballManager/team_feat.csv") player_df = readCSV("/Users/peggy/Desktop/footballManager/data_clean.csv") def playerSimilarity(p1, p2): ''' length of p2 times cosine of p1 & p2 ''' cosine = np.dot(p1,p2)/(np.linalg.norm(p1)*(np.linalg.norm(p2))) r = np.sqrt(sum([i ** 2 for i in p1])) return r * cosine def findTopK(playerList, K, player, sort_type): playerList.append(player) playerList.sort(key=lambda p: sort_type * p[1]) if(len(playerList) > K): return playerList[:K] return playerList def mergeTopK(pList1, pList2, K, sort_type): result = pList1 + pList2 result.sort(key=lambda p:sort_type*p[1]) if(len(result) > K): return result[:K] return result def findSimilarPlayer(df, name, topK): ''' given dataset and target player name return top K most similar players data frame of target player ''' player_df = df.select(["ID"] + df.columns[44:73]).where(df.Name == name) if player_df == None: raise NameError("No Player Found!") playerInfo = player_df.rdd.map(list)\ .map(lambda l:(l[0], [int(l[i]) for i in range(1, len(l))])).collect()[0] (playerId, playerList) = playerInfo[0], playerInfo[1] mat = df.select(["ID"] + df.columns[44:73]).rdd.map(list)\ .map(lambda l:(l[0], [int(l[i]) for i in range(1, len(l))]))\ .filter(lambda kv: kv[0] != playerId)\ .mapValues(lambda l: playerSimilarity(l, playerList)) res = mat.aggregate([], lambda inp1, inp2: findTopK(inp1, topK, inp2, -1), lambda inp1, inp2: mergeTopK(inp1, inp2, topK, -1)) res = [id for id, score in res] id_df = sqlContext.createDataFrame(res, StringType()).toDF("ID") res = df.join(id_df, "ID", "inner").select("Name", "Age", "Nationality", "Club", "Height(cm)", "Weight(lbs)") return res time1 = time.time() findSimilarPlayer(player_df, "L. Messi", 10) run_time = time.time() - time1 print("run time: " + str(run_time)) def findBestReplicate(teamName, playerId, df, topK, weightVector): ''' return list of [(player_id, replace_id, improve score)] ''' player_info = df.select(df.columns[44:73]).where(df.ID == playerId).rdd.map(list)\ .map(lambda l: [float(i) for i in l]).collect()[0] # list candidatePlayers = df.select(["ID"] + df.columns[44:73]).where(df.Club != teamName).rdd.map(list)\ .map(lambda l:(l[0], [float(l[i]) for i in range(1, len(l))]))\ .mapValues(lambda vals: improve(vals, player_info, weightVector)) # rdd res = candidatePlayers.aggregate([], lambda inp1, inp2: findTopK(inp1, topK, inp2, -1), lambda inp1, inp2: mergeTopK(inp1, inp2, topK, -1)) res = [(playerId, id, score) for id, score in res] return res def improve(l1, l2, weight): improve = 0 for i in range(len(l1)): improve += (l1[i] - l2[i]) * weight[i] return improve def featureThreshold(l): temp = sorted(l) return temp[int(len(l) / 4)] def findWorstFeatures(teamName, team_df): ''' take the team name and team dataframe and return list of index of weak features start from 0 = Crossing ''' targ_df = team_df.select('*').where(team_df.Club == teamName).rdd.map(list)\ .map(lambda l: (l[0], [float(l[i]) for i in range(1, len(l))]))\ .mapValues(lambda l: (featureThreshold(l), l))\ .mapValues(lambda tup: [index for index, val in enumerate(tup[1]) if val < tup[0]]) feature_indexes = targ_df.collect()[0][1] return feature_indexes def createWeightVector(feature_indexes): ''' take list of weak features and return weight list of size 29 ''' norm = float(10 / (29 + len(feature_indexes))) weightVector = [2.0 * norm if index in feature_indexes else norm for index in range(29)] return weightVector def findWorstPlayers(teamName, player_df, feature_indexes): ''' take team name, player dataframe, weak features index list return list of worst players id ''' worst_players = player_df.select(["ID"] + player_df.columns[44:73]).where(player_df.Club == teamName).rdd.map(list)\ .map(lambda l: (l[0], [float(i) for i in l[1:]]))\ .mapValues(lambda l: [l[i] for i in range(len(l)) if i in feature_indexes])\ .mapValues(lambda l: sum(l)).collect() worst_players.sort(key = lambda t: t[1], reverse=True) return [id for id, index in worst_players][:10] def replaceModeRecommendation(player_df, team_df, teamName, topK): feature_indexes = findWorstFeatures(teamName, team_df) # print([team_df.columns[i + 1] for i in feature_indexes]) weight_vector = createWeightVector(feature_indexes) # print(weight_vector) worst_players = findWorstPlayers(teamName, player_df, feature_indexes) res = [] for player_id in worst_players: res += findBestReplicate(teamName, player_id, player_df, topK, weight_vector) res.sort(key = lambda l: l[2], reverse=True) return res[:topK] def printPlayerInfo(player_df, playerId): player_info = player_df.select("ID", 'Name', "Age", "Nationality", "Overall", "Club", "Position")\ .where(player_df.ID == playerId).show() # team_name = 'FC Barcelona' time1 = time.time() team_name = 'LA Galaxy' res = replaceModeRecommendation(player_df, team_df, team_name, 3) print("run time: " + str(time.time() - time1)) # for i in res: # print("player:" + i[0] +" replacement:" + i[1] + " improvement:" + str(i[2])) ```
github_jupyter
# Introduction This notebook demonstrates how BioThings Explorer can be used to answer the following query: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*"What biosamples are associated with diseases related to gene SLC15A4"* **To experiment with an executable version of this notebook, [load it in Google Colaboratory](https://colab.research.google.com/github/biothings/biothings_explorer/blob/master/jupyter%20notebooks/Demo%20of%20Integrating%20Stanford%20BioSample%20API%20into%20BTE.ipynb).** **Background**: BioThings Explorer can answer two classes of queries -- "EXPLAIN" and "PREDICT". EXPLAIN queries are described in [EXPLAIN_demo.ipynb](https://github.com/biothings/biothings_explorer/blob/master/jupyter%20notebooks/EXPLAIN_demo.ipynb), and PREDICT queries are described in [PREDICT_demo.ipynb](https://github.com/biothings/biothings_explorer/blob/master/jupyter%20notebooks/PREDICT_demo.ipynb). Here, we describe PREDICT queries and how to use BioThings Explorer to execute them. A more detailed overview of the BioThings Explorer systems is provided in [these slides](https://docs.google.com/presentation/d/1QWQqqQhPD_pzKryh6Wijm4YQswv8pAjleVORCPyJyDE/edit?usp=sharing). In the first stage of the query, BTE will first call all APIs which can provide association data between SLC15A4 and diseases, including: 1. [DISEASES API](http://smart-api.info/ui/a7f784626a426d054885a5f33f17d3f8) 2. [BIOLINK API](http://smart-api.info/ui/d22b657426375a5295e7da8a303b9893) 3. [SEMMED API](http://smart-api.info/ui/e99229fc6ccb9ad9889bcc9c77a36bad) 4. [MyDisease.info API](http://smart-api.info/ui/f307760715d91908d0ae6de7f0810b22) 5. [CTD API](http://smart-api.info/ui/0212611d1c670f9107baf00b77f0889a) In the second stage of the query, BTE will first call all APIs which can provide association data between diseases and biosamples through **[Stanford Biosample API](http://smart-api.info/ui/553a49d112bb19306253942ebd6377a9)**. ## Step 0: Load BioThings Explorer modules Install the `biothings_explorer` packages, as described in this [README](https://github.com/biothings/biothings_explorer/blob/master/jupyter%20notebooks/README.md#prerequisite). This only needs to be done once (but including it here for compability with [colab](https://colab.research.google.com/)). ``` !pip install git+https://github.com/biothings/biothings_explorer#egg=biothings_explorer from biothings_explorer.user_query_dispatcher import FindConnection from biothings_explorer.hint import Hint ``` ## Step 1: Find representation of "SLC15A4" in BTE In this step, BioThings Explorer translates our query string "SLC15A4" into BioThings objects, which contain mappings to many common identifiers. Generally, the top result returned by the `Hint` module will be the correct item, but you should confirm that using the identifiers shown. Search terms can correspond to any child of [BiologicalEntity](https://biolink.github.io/biolink-model/docs/BiologicalEntity.html) from the [Biolink Model](https://biolink.github.io/biolink-model/docs/), including `DiseaseOrPhenotypicFeature` (e.g., "lupus"), `ChemicalSubstance` (e.g., "acetaminophen"), `Gene` (e.g., "CDK2"), `BiologicalProcess` (e.g., "T cell differentiation"), and `Pathway` (e.g., "Citric acid cycle"). ``` ht = Hint() SLC15A4 = ht.query("SLC15A4")['Gene'][0] SLC15A4 ``` ## Step 2: Find biosamples that are associated with diseases which related to Gene SLC15A4 In this section, we find all paths in the knowledge graph that connect SLC15A4 to any entity that is a biosample. To do that, we will use `FindConnection`. This class is a convenient wrapper around two advanced functions for **query path planning** and **query path execution**. ``` fc = FindConnection(input_obj=SLC15A4, output_obj='Biosample', intermediate_nodes=['DiseaseOrPhenotypicFeature']) fc.connect(verbose=True) ``` ## Step 3: Explore the results Through BTE, we found **8 DiseasesOrPhenotypicFeature entities** which are associated with Gene SLC15A. And we found **770 biosample entities** which are associated with these diseases. ``` fc.display_table_view() ```
github_jupyter
``` import styling ``` <img src="https://pbs.twimg.com/media/EWOqUpFX0AcDh_X.jpg"> # Binary classification ranking: definition ## In binary classification you have a universe of objects U, like "images on websites" <style type="text/css"> .tt th { background-color:white; color: black; width:50%; padding:15px;border:10px solid black; } .tt td { background-color:black; color: white; width:50%; padding:15px;border:10px solid white; } </style> <div class="outside"> <table class="outside"> <tr> <td> <!-- giraffe --> <div class="hit"> <img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100"> </div> </td> <td> <!-- lions --> <div class="hit"> <img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100"> </div> </td> <td> <!-- penguins --> <div class="hit"> <img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100"> </div> </td> <td> <!-- kitten --> <div class="hit"> <img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100"> </div> </td> <td> <!-- panda --> <div class="hit"> <img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100"> </div> </td> <td> <!-- tiger --> <div class="hit"> <img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100"> </div> </td> <td> <!-- fawn --> <div class="hit"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100"> </div> </td> <td> <!-- mommy cat --> <div class="hit"> <img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100"> </div> </td> </tr> </table> </div> ## And a query Q, like "images that feature cats" ## A binary classification C(U, Q) returns an ordering L of objects from U (read from left to right) ## A classification is "good" if it orders the objects that satisfy Q close to the front (left end) of the ordering. <h1 class="hit">An item that satisfies Q is a "hit" (white border)</h1> <h1 class="miss">An item that doesn't satisfy Q is a "miss" (black border)</h1> # It's not obvious which of these orderings is a "better" ordering for "images featuring cats" <div class="outside"> <table class="outside"> <tr> <td> <!-- giraffe --> <div class="miss"> <img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100"> </div> </td> <td> <!-- lions --> <div class="hit"> <img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100"> </div> </td> <td> <!-- penguins --> <div class="miss"> <img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100"> </div> </td> <td> <!-- kitten --> <div class="hit"> <img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100"> </div> </td> <td> <!-- panda --> <div class="miss"> <img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100"> </div> </td> <td> <!-- tiger --> <div class="hit"> <img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100"> </div> </td> <td> <!-- fawn --> <div class="miss"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100"> </div> </td> <td> <!-- mommy cat --> <div class="hit"> <img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100"> </div> </td> </tr> </table> </div> <div class="outside"> <table class="outside"> <tr> <td> <!-- giraffe --> <div class="miss"> <img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100"> </div> </td> <td> <!-- lions --> <div class="hit"> <img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100"> </div> </td> <td> <!-- kitten --> <div class="hit"> <img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100"> </div> </td> <td> <!-- penguins --> <div class="miss"> <img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100"> </div> </td> <td> <!-- panda --> <div class="miss"> <img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100"> </div> </td> <td> <!-- fawn --> <div class="miss"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100"> </div> </td> <td> <!-- tiger --> <div class="hit"> <img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100"> </div> </td> <td> <!-- mommy cat --> <div class="hit"> <img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100"> </div> </td> </tr> </table> </div> # But this one is "better" than all the rest -- all the hits are at the front <div class="outside"> <table class="outside"> <tr> <td> <!-- tiger --> <div class="hit"> <img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100"> </div> </td> <td> <!-- mommy cat --> <div class="hit"> <img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100"> </div> </td> <td> <!-- lions --> <div class="hit"> <img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100"> </div> </td> <td> <!-- kitten --> <div class="hit"> <img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100"> </div> </td> <td> <!-- giraffe --> <div class="miss"> <img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100"> </div> </td> <td> <!-- penguins --> <div class="miss"> <img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100"> </div> </td> <td> <!-- panda --> <div class="miss"> <img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100"> </div> </td> <td> <!-- fawn --> <div class="miss"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100"> </div> </td> </tr> </table> </div> # And this one is "worst" -- all the hits are at the back <div class="outside"> <table class="outside"> <tr> <td> <!-- giraffe --> <div class="miss"> <img src="https://a-z-animals.com/media/2021/01/mammals-400x300.jpg" width="100"> </div> </td> <td> <!-- penguins --> <div class="miss"> <img src="https://www.vpr.org/sites/vpr/files/styles/medium/public/202001/emperor-penguins-istock-Mario_Hoppmann.png" width="100"> </div> </td> <td> <!-- panda --> <div class="miss"> <img src="https://miro.medium.com/max/11520/0*pAypSD1ZSCCw0NcL" width="100"> </div> </td> <td> <!-- fawn --> <div class="miss"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-168504892-1568303467.png" width="100"> </div> </td> <td> <!-- tiger --> <div class="hit"> <img src="https://cdn.vox-cdn.com/thumbor/GzQa3VMNyAITTPQU7ZYMfOjg6lQ=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/19873983/GettyImages_137497593.jpg" width="100"> </div> </td> <td> <!-- mommy cat --> <div class="hit"> <img src="https://static.boredpanda.com/blog/wp-content/uploads/2017/05/mother-shelter-cat-nurtures-orphan-kitten-ember-flame-fb.png" width="100"> </div> </td> <td> <!-- lions --> <div class="hit"> <img src="https://cosmosmagazine.com/wp-content/uploads/2019/12/GettyImages-691120979-1440x1079.jpg" width="100"> </div> </td> <td> <!-- kitten --> <div class="hit"> <img src="https://www.petage.com/wp-content/uploads/2019/09/Depositphotos_74974941_xl-2015-e1569443284386-670x627.jpg" width="100"> </div> </td> </tr> </table> </div> # A binary classification metric assigns "goodness scores" to all possible orderings L. # What is a good ordering? It depends on the purpose of the classification. What is the "use case"?
github_jupyter
# 2.6. Introducing a deeper network ## Data loading and preprocessing ``` import pandas as pd from google.colab import files #uploaded = files.upload() data = pd.read_csv('/content/preprocessed_data.csv') data = data.sample(frac=1) # a bit weird data.head() data['Winner'] = data['Winner'].map(lambda x: 1 if x == 'Red' else 0) data['title_bout'] = data['title_bout'].map(lambda x: 1 if x == 'True' else 0) train_size = int(0.8*len(data)) features = data.drop(columns=['Winner']) targets = data['Winner'] X_train, X_test = features.values[:train_size, :], features.values[train_size:, :] y_train, y_test = targets.values[:train_size], targets.values[train_size:] import seaborn as sns import matplotlib.pyplot as plt #sns.pairplot(data) corr = data.corr() cmap = sns.diverging_palette(250, 10, as_cmap=True) plt.figure(figsize=(40, 80)) sns.heatmap(corr[['Winner']], cmap=cmap, vmax=.3, square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=True) ``` ## Tensorflow ANNs ``` import tensorflow as tf from sklearn.preprocessing import StandardScaler model = tf.keras.models.Sequential([ tf.keras.layers.Dense(1024, activation=tf.nn.leaky_relu), # x if x > 0 else alpha*x tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(512, activation=tf.nn.leaky_relu), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(1, activation='sigmoid') # [0, 1] ]) red = len(y_train[y_train>0]) blue = len(y_train) - red total = len(y_train) weight_for_red = total / (2 * red) weight_for_blue = total / (2 * blue) class_weight = {0: weight_for_blue, 1: weight_for_red} print(class_weight) adam_optimizer = tf.keras.optimizers.Adam() model.compile( optimizer=adam_optimizer, loss='binary_crossentropy', metrics=[ tf.keras.metrics.TruePositives(name='tp'), tf.keras.metrics.FalsePositives(name='fp'), tf.keras.metrics.TrueNegatives(name='tn'), tf.keras.metrics.FalseNegatives(name='fn'), tf.keras.metrics.BinaryAccuracy(name='accuracy'), tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall'), tf.keras.metrics.AUC(name='auc'), ] ) save_best_callback = tf.keras.callbacks.ModelCheckpoint( '/content/model-{epoch:02d}-{val_accuracy:.2f}.hdf5', monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=False, save_frequency=1) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) model.fit(X_train_scaled, y_train, class_weight=class_weight, batch_size=64, validation_split=0.1, #callbacks=[save_best_callback], epochs=20) import numpy as np #model = tf.keras.models.load_model('/content/model-43-0.64.hdf5') X_test_scaled = scaler.transform(X_test) model.evaluate(X_test_scaled, y_test) #np.round(model.predict(X_test)) !pip install --upgrade tensorflow ```
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/1_getting_started_roadmap/9_custom_network_builder/2)%20Create%20a%20branched%20custom%20network%20while%20debugging%20it.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Goals ### Learn how to create custom network # Table of Contents ## [0. Install](#0) ## [1. Load Data](#1) ## [2. Create and debug network](#2) ## [3. Train](#3) <a id='0'></a> # Install Monk - git clone https://github.com/Tessellate-Imaging/monk_v1.git - cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt - (Select the requirements file as per OS and CUDA version) ``` !git clone https://github.com/Tessellate-Imaging/monk_v1.git # If using Colab install using the commands below !cd monk_v1/installation/Misc && pip install -r requirements_colab.txt # If using Kaggle uncomment the following command #!cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt # Select the requirements file as per OS and CUDA version when using a local system or cloud #!cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt ``` ## Dataset - Stanford Dogs classification dataset - https://www.kaggle.com/jessicali9530/stanford-dogs-dataset ``` ! wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1b4tC_Pl1O80of7U-PJ7VExmszzSX3ZEM' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1b4tC_Pl1O80of7U-PJ7VExmszzSX3ZEM" -O dogs-species-dataset.zip && rm -rf /tmp/cookies.txt ! unzip -qq dogs-species-dataset.zip ``` # Imports ``` # Monk import os import sys sys.path.append("monk_v1/monk/"); #Using mxnet-gluon backend from gluon_prototype import prototype ``` <a id='1'></a> # Load data ``` gtf = prototype(verbose=1); gtf.Prototype("project", "branched_custom_model"); ``` ## Set Data params ``` gtf.Dataset_Params(dataset_path="dogs-species-dataset/train", split=0.9, input_size=224, batch_size=2, shuffle_data=True, num_processors=3); ``` ## Apply Transforms ``` gtf.apply_random_horizontal_flip(train=True, val=True); gtf.apply_normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], train=True, val=True, test=True); ``` ## Load Dataset ``` gtf.Dataset(); ``` <a id='2'></a> # Create custom model with simultaneous debugging ``` network = []; network.append(gtf.convolution(output_channels=16)); network.append(gtf.batch_normalization()); network.append(gtf.relu()); network.append(gtf.convolution(output_channels=16)); network.append(gtf.batch_normalization()); network.append(gtf.relu()); network.append(gtf.max_pooling()); gtf.debug_custom_model_design(network); subnetwork = []; branch1 = []; branch1.append(gtf.convolution(output_channels=16)); branch1.append(gtf.batch_normalization()); branch1.append(gtf.convolution(output_channels=16)); branch1.append(gtf.batch_normalization()); branch2 = []; branch2.append(gtf.convolution(output_channels=16)); branch2.append(gtf.batch_normalization()); branch3 = []; branch3.append(gtf.identity()) subnetwork.append(branch1); subnetwork.append(branch2); subnetwork.append(branch3); subnetwork.append(gtf.concatenate()); network.append(subnetwork); gtf.debug_custom_model_design(network); network.append(gtf.convolution(output_channels=16)); network.append(gtf.batch_normalization()); network.append(gtf.relu()); network.append(gtf.max_pooling()); gtf.debug_custom_model_design(network); subnetwork = []; branch1 = []; branch1.append(gtf.convolution(output_channels=16)); branch1.append(gtf.batch_normalization()); branch1.append(gtf.convolution(output_channels=16)); branch1.append(gtf.batch_normalization()); branch2 = []; branch2.append(gtf.convolution(output_channels=16)); branch2.append(gtf.batch_normalization()); branch3 = []; branch3.append(gtf.identity()) subnetwork.append(branch1); subnetwork.append(branch2); subnetwork.append(branch3); subnetwork.append(gtf.add()); network.append(subnetwork); gtf.debug_custom_model_design(network); network.append(gtf.convolution(output_channels=16)); network.append(gtf.batch_normalization()); network.append(gtf.relu()); network.append(gtf.max_pooling()); gtf.debug_custom_model_design(network); network.append(gtf.flatten()); network.append(gtf.dropout(drop_probability=0.2)); network.append(gtf.fully_connected(units=1024)); network.append(gtf.dropout(drop_probability=0.2)); network.append(gtf.fully_connected(units=gtf.system_dict["dataset"]["params"]["num_classes"])); gtf.debug_custom_model_design(network); ``` ## Create and setup model ``` gtf.Compile_Network(network, data_shape=(3, 224, 224)); ``` ## Visualize with netron ``` gtf.Visualize_With_Netron(data_shape=(3, 224, 224), port=8081); from IPython.display import Image Image(filename='imgs/branched_custom_network.png') ``` ## Set Training params ``` gtf.Training_Params(num_epochs=5, display_progress=True, display_progress_realtime=True, save_intermediate_models=False, save_training_logs=True); ## Set Optimizer, losses and learning rate schedulers gtf.optimizer_sgd(0.0001); gtf.lr_fixed(); gtf.loss_softmax_crossentropy() #Start Training gtf.Train(); #Read the training summary generated once you run the cell and training is completed ```
github_jupyter
# ้ก”ใฎๆคœๅ‡บใจๅˆ†ๆž ใ‚ณใƒณใƒ”ใƒฅใƒผใ‚ฟใƒ“ใ‚ธใƒงใƒณใ‚ฝใƒชใƒฅใƒผใ‚ทใƒงใƒณใฏใ€ไบบ้–“ใฎ้ก”ใ‚’ๆคœๅ‡บใ€ๅˆ†ๆžใ€ใพใŸใฏ่ญ˜ๅˆฅใ™ใ‚‹ใŸใ‚ใซไบบๅทฅ็Ÿฅ่ƒฝ๏ผˆAI๏ผ‰ใ‚ฝใƒชใƒฅใƒผใ‚ทใƒงใƒณใ‚’ๅฟ…่ฆใจใ™ใ‚‹ใ“ใจใŒใ‚ˆใใ‚ใ‚Šใพใ™ใ€‚ไพ‹ใˆใฐใ€ๅฐๅฃฒไผๆฅญใฎใƒŽใƒผใ‚นใ‚ฆใ‚คใƒณใƒ‰ใƒปใƒˆใƒฌใƒผใƒ€ใƒผใ‚บใŒใ€Œใ‚นใƒžใƒผใƒˆใ‚นใƒˆใ‚ขใ€ใฎๅฐŽๅ…ฅใ‚’ๆฑบใ‚ใŸใจใ—ใพใ™ใ€‚ใ“ใ‚Œใ‚’ๅฎŸ็พใ™ใ‚‹ใŸใ‚ใฎ1ใคใฎๆ–นๆณ•ใจใ—ใฆใ€้ก”ใฎๆคœๅ‡บใจๅˆ†ๆžใ€ใคใพใ‚Š็”ปๅƒใซ้ก”ใŒๅ†™ใฃใฆใ„ใ‚‹ใ‹ใฉใ†ใ‹ใ‚’ๅˆคๆ–ญใ—ใ€ๅ†™ใฃใฆใ„ใ‚‹ๅ ดๅˆใฏใใฎ็‰นๅพดใ‚’ๅˆ†ๆžใ™ใ‚‹ใ“ใจใŒๆŒ™ใ’ใ‚‰ใ‚Œใพใ™ใ€‚ <p style='text-align:center'><img src='./images/face_analysis.jpg' alt='้ก”ใ‚’ๅˆ†ๆžใ™ใ‚‹ใƒญใƒœใƒƒใƒˆ'/></p> ## ้ก”่ช่ญ˜ใ‚ตใƒผใƒ“ใ‚นใ‚’ไฝฟใฃใฆ้ก”ใ‚’ๆคœๅ‡บใ™ใ‚‹ Northwind TradersใŒไฝœใ‚ŠใŸใ„ใ‚นใƒžใƒผใƒˆใ‚นใƒˆใ‚ขใ‚ทใ‚นใƒ†ใƒ ใŒใ€้กงๅฎขใ‚’ๆคœ็Ÿฅใ—ใฆ้ก”ใฎ็‰นๅพดใ‚’ๅˆ†ๆžใงใใ‚‹ๅฟ…่ฆใŒใ‚ใ‚‹ใจใ—ใพใ™ใ€‚Microsoft Azureใงใฏใ€**Face**ใ‚ณใ‚ฐใƒ‹ใƒ†ใ‚ฃใƒ–ใ‚ตใƒผใƒ“ใ‚นใ‚’ไฝฟ็”จใ—ใฆใ“ใ‚Œใ‚’่กŒใ†ใ“ใจใŒใงใใพใ™ใ€‚ ใพใšใฏAzureใ‚ตใƒ–ใ‚นใ‚ฏใƒชใƒ—ใ‚ทใƒงใƒณใง**Cognitive Services**ใƒชใ‚ฝใƒผใ‚นใ‚’ไฝœๆˆใ—ใฆใฟใพใ—ใ‚‡ใ†ใ€‚ > **Note**: ใ™ใงใซCognitive Servicesใƒชใ‚ฝใƒผใ‚นใŒใ‚ใ‚‹ๅ ดๅˆใฏใ€Azureใƒใƒผใ‚ฟใƒซใฎ**ใ‚ฏใ‚คใƒƒใ‚ฏใ‚นใ‚ฟใƒผใƒˆ**ใƒšใƒผใ‚ธใ‚’้–‹ใใ€ใใฎใ‚ญใƒผใจใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆใ‚’ไปฅไธ‹ใฎใ‚ปใƒซใซใ‚ณใƒ”ใƒผใ—ใพใ™ใ€‚ใใ‚Œไปฅๅค–ใฎๅ ดๅˆใฏใ€ไปฅไธ‹ใฎๆ‰‹้ †ใซๅพ“ใฃใฆใƒชใ‚ฝใƒผใ‚นใ‚’ไฝœๆˆใ—ใพใ™ใ€‚ 1. ๅˆฅใฎใƒ–ใƒฉใ‚ฆใ‚ถใ‚ฟใƒ–ใงใ€https://portal.azure.com ใฎ Azure ใƒใƒผใ‚ฟใƒซใ‚’้–‹ใใ€Microsoft ใ‚ขใ‚ซใ‚ฆใƒณใƒˆใงใ‚ตใ‚คใƒณใ‚คใƒณใ—ใพใ™ใ€‚ 2. **&#65291;Create a resource** ใƒœใ‚ฟใƒณใ‚’ใ‚ฏใƒชใƒƒใ‚ฏใ—ใฆใ€*ใ‚ณใ‚ฐใƒ‹ใƒ†ใ‚ฃใƒ–ใ‚ตใƒผใƒ“ใ‚น**ใ‚’ๆคœ็ดขใ—ใ€ๆฌกใฎ่จญๅฎšใง**ใ‚ณใ‚ฐใƒ‹ใƒ†ใ‚ฃใƒ–ใ‚ตใƒผใƒ“ใ‚น**ใƒชใ‚ฝใƒผใ‚นใ‚’ไฝœๆˆใ—ใพใ™: - **Name**: *ไธ€ๆ„ใฎๅๅ‰ใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„* - **Subscription**: *ใ‚ใชใŸใฎAzureใ‚ตใƒ–ใ‚นใ‚ฏใƒชใƒ—ใ‚ทใƒงใƒณ* - **Location**: *ๅˆฉ็”จๅฏ่ƒฝใชใƒชใƒผใ‚ธใƒงใƒณใ‚’้ธๆŠž: - **Pricing tier**: S0 - **Resource group**: *ๅ›บๆœ‰ใฎๅๅ‰ใ‚’ๆŒใคใƒชใ‚ฝใƒผใ‚นใ‚ฐใƒซใƒผใƒ—ใ‚’ไฝœๆˆใ—ใพใ™ใ€‚* 3. ใƒ‡ใƒ—ใƒญใ‚คใŒๅฎŒไบ†ใ™ใ‚‹ใฎใ‚’ๅพ…ใกใพใ™ใ€‚ๆฌกใซใ€ใ‚ณใ‚ฐใƒ‹ใƒ†ใ‚ฃใƒ–ใ‚ตใƒผใƒ“ใ‚นใƒชใ‚ฝใƒผใ‚นใซ็งปๅ‹•ใ—ใ€**ใ‚ฏใ‚คใƒƒใ‚ฏใ‚นใ‚ฟใƒผใƒˆ**ใƒšใƒผใ‚ธใงใ€ใ‚ญใƒผใจใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆใซๆณจๆ„ใ—ใฆใใ ใ•ใ„ใ€‚ใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆ ใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณใ‹ใ‚‰ใ‚ณใ‚ฐใƒ‹ใƒ†ใ‚ฃใƒ– ใ‚ตใƒผใƒ“ใ‚น ใƒชใ‚ฝใƒผใ‚นใซๆŽฅ็ถšใ™ใ‚‹ใซใฏใ€ใ“ใ‚Œใ‚‰ใŒๅฟ…่ฆใงใ™ใ€‚ 4. ใƒชใ‚ฝใƒผใ‚นใฎ **Key1** ใ‚’ใ‚ณใƒ”ใƒผใ—ใฆใ€**YOUR_COG_KEY** ใ‚’็ฝฎใๆ›ใˆใฆใ€ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใซ่ฒผใ‚Šไป˜ใ‘ใพใ™ใ€‚ 5. ใƒชใ‚ฝใƒผใ‚นใฎ **endpoint** ใ‚’ใ‚ณใƒ”ใƒผใ—ใฆใ€ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใซ่ฒผใ‚Šไป˜ใ‘ใ€ **YOUR_COG_ENDPOINT** ใ‚’็ฝฎใๆ›ใˆใพใ™ใ€‚ 6. ไธ‹ใฎใ‚ปใƒซใฎ็ท‘่‰ฒใฎ<span style="color:green">&#9655;</span>ใƒœใ‚ฟใƒณ๏ผˆใ‚ปใƒซใฎๅทฆไธŠ๏ผ‰ใ‚’ใ‚ฏใƒชใƒƒใ‚ฏใ—ใฆใ€ไธ‹ใฎใ‚ปใƒซใงใ‚ณใƒผใƒ‰ใ‚’ๅฎŸ่กŒใ—ใพใ™ใ€‚ ``` cog_key = 'YOUR_COG_KEY' cog_endpoint = 'YOUR_COG_ENDPOINT' print('Ready to use cognitive services at {} using key {}'.format(cog_endpoint, cog_key)) ``` ใ“ใ‚ŒใงCognitive Servicesใฎใ‚ปใƒƒใƒˆใ‚ขใƒƒใƒ—ใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚ ใใ—ใฆPythonใ‹ใ‚‰ๆœฌๆผ”็ฟ’ใ‚’ๅฎŸ่กŒใ™ใ‚‹ใซใฏใ€ใพใšAzureใฎ้–ข้€ฃใƒ‘ใƒƒใ‚ฑใƒผใ‚ธใ‚’ใ‚คใƒณใ‚นใƒˆใƒผใƒซใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚Šใพใ™ใ€‚ ``` ! pip install azure-cognitiveservices-vision-face ``` ใ“ใ‚Œใงๆบ–ๅ‚™ใŒๅฎŒไบ†ใ—ใพใ—ใฆใ€Faceใ‚ตใƒผใƒ“ใ‚นใ‚’ไฝฟใฃใฆๅบ—ๅ†…ใฎไบบใฎ้ก”ใ‚’ๆคœๅ‡บใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ ไปฅไธ‹ใฎใ‚ณใƒผใƒ‰ใ‚ปใƒซใ‚’ๅฎŸ่กŒใ—ใฆไพ‹ใ‚’่ฆ‹ใฆใฟใพใ—ใ‚‡ใ†ใ€‚ ``` from azure.cognitiveservices.vision.face import FaceClient from msrest.authentication import CognitiveServicesCredentials from python_code import faces import os %matplotlib inline # ้ก”ๆคœๅ‡บใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆใ‚’ไฝœๆˆใ—ใพใ™. face_client = FaceClient(cog_endpoint, CognitiveServicesCredentials(cog_key)) # ็”ปๅƒใ‚’้–‹ใ image_path = os.path.join('data', 'face', 'store_cam2.jpg') image_stream = open(image_path, "rb") # ้ก”ใ‚’ๆคœๅ‡บ detected_faces = face_client.face.detect_with_stream(image=image_stream) # ้ก”ใ‚’่กจ็คบใ™ใ‚‹ (ใ‚ณใƒผใƒ‰ใฏ python_code/faces.py ใซใ‚ใ‚Šใพใ™) faces.show_faces(image_path, detected_faces) ``` ๆคœๅ‡บใ•ใ‚ŒใŸๅ„้ก”ใซใฏๅ›บๆœ‰ใฎIDใŒๅ‰ฒใ‚Šๅฝ“ใฆใ‚‰ใ‚Œใฆใ„ใ‚‹ใฎใงใ€ใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณใฏๆคœๅ‡บใ•ใ‚ŒใŸๅ€‹ใ€…ใฎ้ก”ใ‚’่ญ˜ๅˆฅใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ ไปฅไธ‹ใฎใ‚ปใƒซใ‚’ๅฎŸ่กŒใ—ใฆใ€ใ•ใ‚‰ใซใ„ใใคใ‹ใฎ่ฒทใ„็‰ฉๅฎขใฎ้ก”ใฎIDใ‚’็ขบ่ชใ—ใฆใใ ใ•ใ„ใ€‚ ``` # ็”ปๅƒใ‚’้–‹ใ image_path = os.path.join('data', 'face', 'store_cam3.jpg') image_stream = open(image_path, "rb") # ้ก”ใ‚’ๆคœๅ‡บ detected_faces = face_client.face.detect_with_stream(image=image_stream) # ้ก”ใ‚’่กจ็คบใ™ใ‚‹ (ใ‚ณใƒผใƒ‰ใฏ python_code/faces.py ใซใ‚ใ‚Šใพใ™) faces.show_faces(image_path, detected_faces, show_id=True) ``` ## ้ก”ใฎๅฑžๆ€งใ‚’ๅˆ†ๆžใ™ใ‚‹ Face cognitive ใ‚ตใƒผใƒ“ใ‚นใฏใ€ๅ˜ใซ้ก”ใ‚’ๆคœๅ‡บใ™ใ‚‹ใ ใ‘ใงใชใใ€้ก”ใฎ็‰นๅพดใ‚„่กจๆƒ…ใ‚’ๅˆ†ๆžใ—ใ€ๆ€งๅˆฅใ€ๅนด้ฝขใ€ๆ„Ÿๆƒ…็Šถๆ…‹ใ‚’็คบๅ”†ใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ใพใŸใ€้ก”ใฎ็‰นๅพดใ‚„่กจๆƒ…ใ‚’ๅˆ†ๆžใ—ใฆใ€ๆ€งๅˆฅใ€ๅนด้ฝขใ€ๆ„Ÿๆƒ…ใฎ็Šถๆ…‹ใ‚’็คบๅ”†ใ™ใ‚‹ใ“ใจใ‚‚ใงใใพใ™ใ€‚ ``` # ็”ปๅƒใ‚’้–‹ใ image_path = os.path.join('data', 'face', 'store_cam1.jpg') image_stream = open(image_path, "rb") # ้ก”ใจๆŒ‡ๅฎšใ•ใ‚ŒใŸ้ก”ใฎๅฑžๆ€งใ‚’ๆคœๅ‡บใ—ใพใ™๏ผŽ attributes = ['age', 'gender', 'emotion'] detected_faces = face_client.face.detect_with_stream(image=image_stream, return_face_attributes=attributes) # ้ก”ใจๅฑžๆ€งใ‚’่กจ็คบใ™ใ‚‹ (ใ‚ณใƒผใƒ‰ใฏ python_code/faces.py ใซใ‚ใ‚Šใพใ™) faces.show_face_attributes(image_path, detected_faces) ``` ็”ปๅƒใซๅ†™ใฃใฆใ„ใ‚‹ใŠๅฎขๆง˜ใฎๆ„Ÿๆƒ…ใ‚นใ‚ณใ‚ขใซๅŸบใฅใ„ใฆใ€ๅฝผๅฅณใฏ่ฒทใ„็‰ฉใซๆบ€่ถณใ—ใฆใ„ใ‚‹ใ‚ˆใ†ใซ่ฆ‹ใˆใพใ™ใ€‚ ## ไผผใŸใ‚ˆใ†ใช้ก”ใ‚’ๆŽขใ™ ๆคœๅ‡บใ•ใ‚ŒใŸ้ก”ใ”ใจใซไฝœๆˆใ•ใ‚Œใ‚‹้ก”๏ผฉ๏ผคใฏใ€ๆคœๅ‡บใ•ใ‚ŒใŸ้ก”ใ‚’ๅ€‹ๅˆฅใซ่ญ˜ๅˆฅใ™ใ‚‹ใŸใ‚ใซไฝฟ็”จใ•ใ‚Œใพใ™ใ€‚ใ“ใ‚Œใ‚‰ใฎIDใ‚’ไฝฟ็”จใ—ใฆใ€ๆคœๅ‡บใ•ใ‚ŒใŸ้ก”ใ‚’ไปฅๅ‰ใซๆคœๅ‡บใ•ใ‚ŒใŸ้ก”ใจๆฏ”่ผƒใ—ใŸใ‚Šใ€้กžไผผใ—ใŸ็‰นๅพดใ‚’ๆŒใค้ก”ใ‚’่ฆ‹ใคใ‘ใŸใ‚Šใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ ไพ‹ใˆใฐใ€ไปฅไธ‹ใฎใ‚ปใƒซใ‚’ๅฎŸ่กŒใ—ใฆใ€ใ‚ใ‚‹็”ปๅƒใฎ่ฒทใ„็‰ฉๅฎขใจๅˆฅใฎ็”ปๅƒใฎ่ฒทใ„็‰ฉๅฎขใ‚’ๆฏ”่ผƒใ—ใ€ไธ€่‡ดใ™ใ‚‹้ก”ใ‚’่ฆ‹ใคใ‘ใพใ™ใ€‚ ``` # ็”ปๅƒ1ใฎๆœ€ๅˆใฎ้ก”ใฎIDใ‚’ๅ–ๅพ—ใ—ใพใ™๏ผŽ image_1_path = os.path.join('data', 'face', 'store_cam3.jpg') image_1_stream = open(image_1_path, "rb") image_1_faces = face_client.face.detect_with_stream(image=image_1_stream) face_1 = image_1_faces[0] # 2ๆžš็›ฎใฎ็”ปๅƒใง้ก”ใฎIDใ‚’ๅ–ๅพ—ใ—ใพใ™ image_2_path = os.path.join('data', 'face', 'store_cam2.jpg') image_2_stream = open(image_2_path, "rb") image_2_faces = face_client.face.detect_with_stream(image=image_2_stream) image_2_face_ids = list(map(lambda face: face.face_id, image_2_faces)) # ็”ปๅƒ2ใ‹ใ‚‰็”ปๅƒ1ใฎ้ก”ใจไผผใฆใ„ใ‚‹้ก”ใ‚’ๆŽขใ™ similar_faces = face_client.face.find_similar(face_id=face_1.face_id, face_ids=image_2_face_ids) # ็”ปๅƒ1ใซ้ก”ใ‚’่กจ็คบใ—๏ผŒ็”ปๅƒ2ใซ้กžไผผใ—ใŸ้ก”ใ‚’่กจ็คบใ—ใพใ™(code in python_code/face.py) faces.show_similar_faces(image_1_path, face_1, image_2_path, image_2_faces, similar_faces) ``` ## ้ก”ใ‚’่ช่ญ˜ใ™ใ‚‹ ใ“ใ“ใพใงใงใ€Faceใ‚ตใƒผใƒ“ใ‚นใŒ้ก”ใจ้ก”ใฎ็‰นๅพดใ‚’ๆคœๅ‡บใ—ใ€ไผผใŸใ‚ˆใ†ใช2ใคใฎ้ก”ใ‚’่ญ˜ๅˆฅใงใใ‚‹ใ“ใจใ‚’่ฆ‹ใฆใใพใ—ใŸใ€‚้ก”่ช่ญ˜*ใ‚ฝใƒชใƒฅใƒผใ‚ทใƒงใƒณใ‚’ๅฎŸ่ฃ…ใ—ใฆใ€็‰นๅฎšใฎไบบใฎ้ก”ใ‚’่ช่ญ˜ใ™ใ‚‹ใ‚ˆใ†ใซFaceใ‚ตใƒผใƒ“ใ‚นใฎใƒชใ‚ฝใƒผใ‚นใ‚’่จ“็ทดใ™ใ‚‹ใ“ใจใงใ€ใ•ใ‚‰ใซไธ€ๆญฉๅ‰้€ฒใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ใ“ใ‚Œใฏใ€ใ‚ฝใƒผใ‚ทใƒฃใƒซใƒกใƒ‡ใ‚ฃใ‚ขใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณใงๅ‹ไบบใฎๅ†™็œŸใ‚’่‡ชๅ‹•็š„ใซใ‚ฟใ‚ฐไป˜ใ‘ใ—ใŸใ‚Šใ€ใƒใ‚คใ‚ชใƒกใƒˆใƒชใ‚ฏใ‚น่ช่จผใ‚ทใ‚นใƒ†ใƒ ใฎไธ€้ƒจใจใ—ใฆ้ก”่ช่จผใ‚’ไฝฟ็”จใ—ใŸใ‚Šใ™ใ‚‹ใชใฉใ€ใ•ใพใ–ใพใชใ‚ทใƒŠใƒชใ‚ชใงๅฝน็ซ‹ใกใพใ™ใ€‚ ใ“ใ‚ŒใŒใฉใฎใ‚ˆใ†ใซๆฉŸ่ƒฝใ™ใ‚‹ใ‹ใ‚’็ขบ่ชใ™ใ‚‹ใŸใ‚ใซใ€ใƒŽใƒผใ‚นใ‚ฆใ‚คใƒณใƒ‰ใƒปใƒˆใƒฌใƒผใƒ€ใƒผใ‚บ็คพใŒ้ก”่ช่จผใ‚’ไฝฟ็”จใ—ใฆใ€IT้ƒจ้–€ใฎๆจฉ้™ใฎใ‚ใ‚‹ๅพ“ๆฅญๅ“กใ ใ‘ใŒๅฎ‰ๅ…จใชใ‚ทใ‚นใƒ†ใƒ ใซใ‚ขใ‚ฏใ‚ปใ‚นใงใใ‚‹ใ‚ˆใ†ใซใ—ใŸใ„ใจ่€ƒใˆใฆใ„ใ‚‹ใจใ—ใพใ™ใ€‚ ๆจฉ้™ใ‚’ไธŽใˆใ‚‰ใ‚ŒใŸๅพ“ๆฅญๅ“กใ‚’ไปฃ่กจใ™ใ‚‹*person group*ใ‚’ไฝœๆˆใ™ใ‚‹ใ“ใจใ‹ใ‚‰ๅง‹ใ‚ใพใ™ใ€‚ ``` group_id = 'employee_group_id' try: # ๆ—ขใซๅญ˜ๅœจใ™ใ‚‹ๅ ดๅˆใฏใ‚ฐใƒซใƒผใƒ—ใ‚’ๅ‰Š้™คใ—ใพใ™ face_client.person_group.delete(group_id) except Exception as ex: print(ex.message) finally: face_client.person_group.create(group_id, 'employees') print ('Group created!') ``` ใ“ใ‚Œใง*personใ‚ฐใƒซใƒผใƒ—*ใŒใงใใŸใฎใงใ€ใ‚ฐใƒซใƒผใƒ—ใซๅ…ฅใ‚ŒใŸใ„็คพๅ“กใ”ใจใซ*person*ใ‚’่ฟฝๅŠ ใ—ใ€้ก”ๅ†™็œŸใ‚’่ค‡ๆ•ฐๆžš็™ป้Œฒใ—ใฆใ€ใƒ•ใ‚งใ‚คใ‚นใ‚ตใƒผใƒ“ใ‚นใŒ้ก”ใฎ็‰นๅพดใ‚’็Ÿฅใ‚‹ใ“ใจใŒใงใใ‚‹ใ‚ˆใ†ใซใชใ‚Šใพใ™ใ€‚็†ๆƒณ็š„ใซใฏใ€ๅŒใ˜ไบบใŒ็•ฐใชใ‚‹ใƒใƒผใ‚บใ‚„่กจๆƒ…ใงๅ†™ใฃใฆใ„ใ‚‹ใ‚‚ใฎใŒ่‰ฏใ„ใงใ—ใ‚‡ใ†ใ€‚ ใ‚ฆใ‚งใƒณใƒ‡ใƒซใจใ„ใ†ไธ€ไบบใฎ็คพๅ“กใ‚’่ฟฝๅŠ ใ—ใ€ๅฝผใฎๅ†™็œŸใ‚’3ๆžš็™ป้Œฒใ—ใพใ™ใ€‚ ``` import matplotlib.pyplot as plt from PIL import Image import os %matplotlib inline # ไบบ(Wendell)ใ‚’ใ‚ฐใƒซใƒผใƒ—ใซ่ฟฝๅŠ ใ™ใ‚‹ wendell = face_client.person_group_person.create(group_id, 'Wendell') # Wendellใฎๅ†™็œŸใ‚’ๆ‰‹ใซๅ…ฅใ‚Œใ‚‹ folder = os.path.join('data', 'face', 'wendell') wendell_pics = os.listdir(folder) # ๅ†™็œŸใ‚’็™ป้Œฒใ™ใ‚‹ i = 0 fig = plt.figure(figsize=(8, 8)) for pic in wendell_pics: # ใ‚ฐใƒซใƒผใƒ—ๅ†…ใฎไบบ็‰ฉใซๅ†™็œŸใ‚’่ฟฝๅŠ ใ™ใ‚‹ img_path = os.path.join(folder, pic) img_stream = open(img_path, "rb") face_client.person_group_person.add_face_from_stream(group_id, wendell.person_id, img_stream) # ๅ„็”ปๅƒใ‚’่กจ็คบใ™ใ‚‹ img = Image.open(img_path) i +=1 a=fig.add_subplot(1,len(wendell_pics), i) a.axis('off') imgplot = plt.imshow(img) plt.show() ``` ไบบ็‰ฉใŒ่ฟฝๅŠ ใ•ใ‚Œใ€ๅ†™็œŸใŒ็™ป้Œฒใ•ใ‚ŒใŸใ“ใจใงใ€ไธ€ไบบไธ€ไบบใ‚’่ช่ญ˜ใ™ใ‚‹ใŸใ‚ใฎFaceใ‚ตใƒผใƒ“ใ‚นใฎใƒˆใƒฌใƒผใƒ‹ใƒณใ‚ฐใŒใงใใ‚‹ใ‚ˆใ†ใซใชใ‚Šใพใ—ใŸใ€‚ ``` face_client.person_group.train(group_id) print('Trained!') ``` ใ“ใ‚Œใงใƒขใƒ‡ใƒซใŒ่จ“็ทดใ•ใ‚ŒใŸใฎใงใ€็”ปๅƒไธญใฎ่ช่ญ˜ใ•ใ‚ŒใŸ้ก”ใ‚’่ญ˜ๅˆฅใ™ใ‚‹ใฎใซไฝฟ็”จใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ ``` # 2ๆžš็›ฎใฎ็”ปๅƒใง้ก”ใฎIDใ‚’ๅ–ๅพ—ใ—ใพใ™ image_path = os.path.join('data', 'face', 'employees.jpg') image_stream = open(image_path, "rb") image_faces = face_client.face.detect_with_stream(image=image_stream) image_face_ids = list(map(lambda face: face.face_id, image_faces)) # ่ช่ญ˜ใ•ใ‚ŒใŸ้ก”ใฎๅๅ‰ใ‚’ๅ–ๅพ—ใ™ใ‚‹ face_names = {} recognized_faces = face_client.face.identify(image_face_ids, group_id) for face in recognized_faces: person_name = face_client.person_group_person.get(group_id, face.candidates[0].person_id).name face_names[face.face_id] = person_name # ่ช่ญ˜ใ—ใŸ้ก”ใ‚’่กจ็คบ faces.show_recognized_faces(image_path, image_faces, face_names) ``` ## Learn More Cognitive ServicesใฎFaceใซใคใ„ใฆใฏใ€[Faceใƒ‰ใ‚ญใƒฅใƒกใƒณใƒˆ](https://docs.microsoft.com/azure/cognitive-services/face/)ใ‚’ๅ‚็…งใ—ใฆใใ ใ•ใ„ใ€‚
github_jupyter
# Introduction to Logistic Regression ## Learning Objectives 1. Create Seaborn plots for Exploratory Data Analysis 2. Train a Logistic Regression Model using Scikit-Learn ## Introduction This lab is in introduction to logistic regression using Python and Scikit-Learn. This lab serves as a foundation for more complex algorithms and machine learning models that you will encounter in the course. In this lab, we will use a synthetic advertising data set, indicating whether or not a particular internet user clicked on an Advertisement on a company website. We will try to create a model that will predict whether or not they will click on an ad based off the features of that user. Each learning objective will correspond to a __#TODO__ in the [student lab notebook](../labs/intro_logistic_regression.ipynb) -- try to complete that notebook first before reviewing this solution notebook. ### Import Libraries ``` # Run the chown command to change the ownership !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # You can use any Python source file as a module by executing an import statement in some other Python source file. # The import statement combines two operations; it searches for the named module, then it binds the # results of that search to a name in the local scope. import os import pandas as pd import numpy as np # Import matplotlib to visualize the model import matplotlib.pyplot as plt # Seaborn is a Python data visualization library based on matplotlib import seaborn as sns %matplotlib inline ``` ### Load the Dataset We will use a synthetic [advertising](https://www.kaggle.com/fayomi/advertising) dataset. This data set contains the following features: * 'Daily Time Spent on Site': consumer time on site in minutes * 'Age': customer age in years * 'Area Income': Avg. Income of geographical area of consumer * 'Daily Internet Usage': Avg. minutes a day consumer is on the internet * 'Ad Topic Line': Headline of the advertisement * 'City': City of consumer * 'Male': Whether or not consumer was male * 'Country': Country of consumer * 'Timestamp': Time at which consumer clicked on Ad or closed window * 'Clicked on Ad': 0 or 1 indicated clicking on Ad ``` # TODO 1: Read in the advertising.csv file and set it to a data frame called ad_data. ad_data = pd.read_csv('../advertising.csv') ``` **Check the head of ad_data** ``` # Get the first five rows of DataFrame ad_data. ad_data.head() ``` **Use info and describe() on ad_data** ``` # Get a concise summary of DataFrame ad_data. ad_data.info() # Get the statistical summary of the DataFrame ad_data. ad_data.describe() ``` Let's check for any null values. ``` # The isnull() method is used to check and manage NULL values in a data frame. ad_data.isnull().sum() ``` ## Exploratory Data Analysis (EDA) Let's use seaborn to explore the data! Try recreating the plots shown below! TODO 1: **Create a histogram of the Age** ``` # TODO 1 # Seaborn is a Python data visualization library based on matplotlib. # Set the aesthetic style of the plots. sns.set_style('whitegrid') ad_data['Age'].hist(bins=30) plt.xlabel('Age') ``` TODO 1: **Create a jointplot showing Area Income versus Age.** ``` # TODO 1 # Seabornโ€™s jointplot displays a relationship between 2 variables (bivariate) as well as # 1D profiles (univariate) in the margins. sns.jointplot(x='Age',y='Area Income',data=ad_data) ``` TODO 2: **Create a jointplot showing the kde distributions of Daily Time spent on site vs. Age.** ``` # TODO 2 sns.jointplot(x='Age',y='Daily Time Spent on Site',data=ad_data,color='red',kind='kde'); ``` TODO 1: **Create a jointplot of 'Daily Time Spent on Site' vs. 'Daily Internet Usage'** ``` # TODO 1 sns.jointplot(x='Daily Time Spent on Site',y='Daily Internet Usage',data=ad_data,color='green') ``` # Logistic Regression Logistic regression is a supervised machine learning process. It is similar to linear regression, but rather than predict a continuous value, we try to estimate probabilities by using a logistic function. Note that even though it has regression in the name, it is for classification. While linear regression is acceptable for estimating values, logistic regression is best for predicting the class of an observation Now it's time to do a train test split, and train our model! You'll have the freedom here to choose columns that you want to train on! ``` # `train_test_split` is a function in Sklearn model selection for splitting data arrays into two subsets: # for training data and for testing data. # With this function, you don't need to divide the dataset manually. # By default, Sklearn `train_test_split` will make random partitions for the two subsets. # However, you can also specify a random state for the operation. from sklearn.model_selection import train_test_split ``` Next, let's define the features and label. Briefly, feature is input; label is output. This applies to both classification and regression problems. ``` X = ad_data[['Daily Time Spent on Site', 'Age', 'Area Income','Daily Internet Usage', 'Male']] y = ad_data['Clicked on Ad'] ``` TODO 2: **Split the data into training set and testing set using train_test_split** ``` # TODO 2 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) ``` **Train and fit a logistic regression model on the training set.** ``` # Logistic Regression is one of the most simple and commonly used Machine Learning algorithms for two-class classification. # It is easy to implement and can be used as the baseline for any binary classification problem. from sklearn.linear_model import LogisticRegression logmodel = LogisticRegression() logmodel.fit(X_train,y_train) ``` ## Predictions and Evaluations **Now predict values for the testing data.** ``` # Use predict() function to predict values for the testing data. predictions = logmodel.predict(X_test) ``` **Create a classification report for the model.** ``` # The classification_report function builds a text report showing the main classification metrics. from sklearn.metrics import classification_report print(classification_report(y_test,predictions)) ``` Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
github_jupyter
# Facies classification utilizing an Adaptive Boosted Random Forest [Ryan Thielke](http://www.linkedin.com/in/ryan-thielke-b987012a) In the following, we provide a possible solution to the facies classification problem described in https://github.com/seg/2016-ml-contest. ## Exploring the data ``` import warnings warnings.filterwarnings("ignore") %matplotlib inline import sys sys.path.append("..") #Import standard pydata libs import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns filename = '../facies_vectors.csv' training_data = pd.read_csv(filename) #training_data['Well Name'] = training_data['Well Name'].astype('category') #training_data['Formation'] = training_data['Formation'].astype('category') training_data['train'] = 1 training_data.describe() validation_data = pd.read_csv("../validation_data_nofacies.csv") #validation_data['Well Name'] = validation_data['Well Name'].astype('category') #validation_data['Formation'] = validation_data['Formation'].astype('category') validation_data['train'] = 0 validation_data.describe() all_data = training_data.append(validation_data) all_data.describe() #Visualize the distribution of facies for each well wells = training_data['Well Name'].unique() fig, ax = plt.subplots(5,2, figsize=(20,20)) for i, well in enumerate(wells): row = i % ax.shape[0] column = i // ax.shape[0] counts = training_data[training_data['Well Name']==well].Facies.value_counts() data_for_well = [counts[j] if j in counts.index else 0 for j in range(1,10)] ax[row, column].bar(range(1,10), data_for_well, align='center') ax[row, column].set_title("{well}".format(well=well)) ax[row, column].set_ylabel("Counts") ax[row, column].set_xticks(range(1,10)) plt.show() plt.figure(figsize=(10,10)) sns.heatmap(training_data.drop(['Formation', 'Well Name'], axis=1).corr()) ``` # Feature Engineering Here we will do a couple things to clean the data and attempt to create new features for our model to consume. First, we will smooth the PE and GR features. Second, we replace missing PE values with the mean of the entire dataset (might want to investigate other methods) Last, we will encode the formations into integer values ``` dfs = [] for well in all_data['Well Name'].unique(): df = all_data[all_data['Well Name']==well].copy(deep=True) df.sort_values('Depth', inplace=True) for col in ['PE']: smooth_col = 'smooth_'+col df[smooth_col] = pd.rolling_mean(df[col], window=25) df[smooth_col].fillna(method='ffill', inplace=True) df[smooth_col].fillna(method='bfill', inplace=True) dfs.append(df) all_data = pd.concat(dfs) all_data['PE'] = all_data.PE.fillna(all_data.PE.mean()) all_data['smooth_PE'] = all_data.smooth_PE.fillna(all_data.smooth_PE.mean()) formation_encoder = dict(zip(all_data.Formation.unique(), range(len(all_data.Formation.unique())))) all_data['enc_formation'] = all_data.Formation.map(formation_encoder) all_data.columns from sklearn import preprocessing feature_names = all_data.drop(['Well Name', 'train', 'Depth', 'Formation', 'enc_formation', 'Facies'], axis=1).columns train_labels = all_data.train.tolist() facies_labels = all_data.Facies.tolist() well_names = all_data['Well Name'].tolist() depths = all_data.Depth.tolist() scaler = preprocessing.StandardScaler().fit(all_data.drop(['Well Name', 'train', 'Depth', 'Formation', 'enc_formation', 'Facies'], axis=1)) scaled_features = scaler.transform(all_data.drop(['Well Name', 'train', 'Depth', 'Formation', 'enc_formation', 'Facies'], axis=1)) scaled_df = pd.DataFrame(scaled_features, columns=feature_names) scaled_df['train'] = train_labels scaled_df['Facies'] = facies_labels scaled_df['Well Name'] = well_names scaled_df['Depth'] = depths def to_binary_vec(value, vec_length): vec = np.zeros(vec_length+1) vec[value] = 1 return vec catagorical_vars = [] for i in all_data.enc_formation: vec = to_binary_vec(i, all_data.enc_formation.max()) catagorical_vars.append(vec) catagorical_vars = np.array(catagorical_vars) for i in range(catagorical_vars.shape[1]): scaled_df['f'+str(i)] = catagorical_vars[:,i] dfs = list() for well in all_data['Well Name'].unique(): tmp_df = all_data[all_data['Well Name'] == well].copy(deep=True) tmp_df.sort_values('Depth', inplace=True) for feature in ['PE', 'GR']: tmp_df['3'+feature] = tmp_df[feature] / tmp_df[feature].shift(1) tmp_df['3'+feature].fillna(0, inplace=True) dfs.append(tmp_df) scaled_df = pd.concat(dfs) #Let's build a model from sklearn import preprocessing from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn import metrics, cross_validation from classification_utilities import display_cm import xgboost as xgb import xgboost as xgb #We will take a look at an F1 score for each well estimators=200 learning_rate=.01 random_state=0 facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS', 'WS', 'D','PS', 'BS'] title_length = 20 training_data = scaled_df[scaled_df.train==1] scores = list() wells = training_data['Well Name'].unique() for well in wells: blind = training_data[training_data['Well Name']==well] train = training_data[(training_data['Well Name']!=well)] train_X = train.drop(['Well Name', 'Facies', 'Depth', 'train', 'Formation'], axis=1) train_Y = train.Facies.values test_X = blind.drop(['Well Name', 'Facies', 'Depth', 'train', 'Formation'], axis=1) test_Y = blind.Facies.values gcf = xgb.XGBClassifier(n_estimators=2000, learning_rate=learning_rate) gcf.fit(train_X,train_Y) pred_Y = gcf.predict(test_X) f1 = metrics.f1_score(test_Y, pred_Y, average='micro') scores.append(f1) print("*"*title_length) print("{well}={f1:.4f}".format(well=well,f1=f1)) print("*"*title_length) print("Avg F1: {score}".format(score=sum(scores)/len(scores))) train_X, test_X, train_Y, test_Y = cross_validation.train_test_split(training_data.drop(['Well Name', 'Facies', 'Depth', 'train', 'Formation'], axis=1), training_data.Facies.values, test_size=.2) print(train_X.shape) print(train_Y.shape) print(test_X.shape) print(test_Y.shape) gcf = xgb.XGBClassifier(n_estimators=2000, learning_rate=learning_rate) gcf.fit(train_X,train_Y) pred_Y = gcf.predict(test_X) cm = metrics.confusion_matrix(y_true=test_Y, y_pred=pred_Y) display_cm(cm, facies_labels, display_metrics=True) validation_data = scaled_df[scaled_df.train==0] validation_data.describe() X = training_data.drop(['Well Name', 'Facies', 'Depth', 'train', 'Formation'], axis=1) Y = training_data.Facies.values test_X = validation_data.drop(['Well Name', 'Facies', 'Depth', 'train', 'Formation'], axis=1) gcf = xgb.XGBClassifier(n_estimators=2000, learning_rate=learning_rate) gcf.fit(X,Y) pred_Y = gcf.predict(test_X) validation_data['Facies'] = pred_Y validation_data.to_csv("Kr1m_SEG_ML_Attempt3.csv", index=False) ```
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/2_transfer_learning_roadmap/4_effect_of_training_epochs/1)%20Understand%20the%20effect%20of%20number%20of%20epochs%20in%20transfer%20learning%20-%20mxnet.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Goals ### Understand the role of number of epochs in transfer learning ### Till what point increasing epochs helps in imporving acuracy ### How overtraining can result in overfitting the data ### You will be using skin-cancer mnist to train the classifiers # Table of Contents ## [0. Install](#0) ## [1. Train a resnet18 network for 5 epochs](#1) ## [2. Re-Train a new experiment for 10 epochs](#2) ## [3. Re-Train a third experiment for 20 epochs](#3) ## [4. Compare the experiments](#4) <a id='0'></a> # Install Monk - git clone https://github.com/Tessellate-Imaging/monk_v1.git - cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt - (Select the requirements file as per OS and CUDA version) ``` !git clone https://github.com/Tessellate-Imaging/monk_v1.git # If using Colab install using the commands below !cd monk_v1/installation/Misc && pip install -r requirements_colab.txt # If using Kaggle uncomment the following command #!cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt # Select the requirements file as per OS and CUDA version when using a local system or cloud #!cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt ``` ## Dataset Details - Credits: https://www.kaggle.com/kmader/skin-cancer-mnist-ham10000 - Seven classes - benign_keratosis_like_lesions - melanocytic_nevi - dermatofibroma - melanoma - vascular_lesions - basal_cell_carcinoma - Bowens_disease ### Download the dataset ``` ! wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ" -O skin_cancer_mnist_dataset.zip && rm -rf /tmp/cookies.txt ! unzip -qq skin_cancer_mnist_dataset.zip ``` # Imports ``` # Monk import os import sys sys.path.append("monk_v1/monk/"); #Using mxnet-gluon backend from gluon_prototype import prototype ``` <a id='1'></a> # Train a resnet18 network for 5 epochs ## Creating and managing experiments - Provide project name - Provide experiment name - For a specific data create a single project - Inside each project multiple experiments can be created - Every experiment can be have diferent hyper-parameters attached to it ``` gtf = prototype(verbose=1); gtf.Prototype("Project", "Epochs-5"); ``` ### This creates files and directories as per the following structure workspace | |--------Project | | |-----Freeze_Base_Network | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) ## Set dataset and select the model ## Quick mode training - Using Default Function - dataset_path - model_name - freeze_base_network - num_epochs ## Sample Dataset folder structure parent_directory | | |------cats | |------img1.jpg |------img2.jpg |------.... (and so on) |------dogs | |------img1.jpg |------img2.jpg |------.... (and so on) ## Modifyable params - dataset_path: path to data - model_name: which pretrained model to use - freeze_base_network: Retrain already trained network or not - num_epochs: Number of epochs to train for ``` gtf.Default(dataset_path="skin_cancer_mnist_dataset/images", path_to_csv="skin_cancer_mnist_dataset/train_labels.csv", model_name="resnet18_v2", freeze_base_network=True, num_epochs=5); #Set number of epochs here #Read the summary generated once you run this cell. ``` ## From summary above Training params Num Epochs: 5 ## Train the classifier ``` #Start Training gtf.Train(); #Read the training summary generated once you run the cell and training is completed ``` ### Final training loss - 0.963 ### Final validation loss - 1.062 (You may get a different result) <a id='2'></a> # Re-Train a new experiment for 10 epochs ## Creating and managing experiments - Provide project name - Provide experiment name - For a specific data create a single project - Inside each project multiple experiments can be created - Every experiment can be have diferent hyper-parameters attached to it ``` gtf = prototype(verbose=1); gtf.Prototype("Project", "Epochs-10"); ``` ### This creates files and directories as per the following structure workspace | |--------Project | | |-----Epochs-5 (Previously created) | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) | | |-----Epochs-10 (Created Now) | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) ## Set dataset and select the model ## Quick mode training - Using Default Function - dataset_path - model_name - freeze_base_network - num_epochs ## Sample Dataset folder structure parent_directory | | |------cats | |------img1.jpg |------img2.jpg |------.... (and so on) |------dogs | |------img1.jpg |------img2.jpg |------.... (and so on) ## Modifyable params - dataset_path: path to data - model_name: which pretrained model to use - freeze_base_network: Retrain already trained network or not - num_epochs: Number of epochs to train for ``` gtf.Default(dataset_path="skin_cancer_mnist_dataset/images", path_to_csv="skin_cancer_mnist_dataset/train_labels.csv", model_name="resnet18_v2", freeze_base_network=True, num_epochs=10); #Set number of epochs here #Read the summary generated once you run this cell. ``` ## From summary above Training params Num Epochs: 10 ## Train the classifier ``` #Start Training gtf.Train(); #Read the training summary generated once you run the cell and training is completed ``` ### Final training loss - 0.911 ### Final validation loss - 1.017 (You may get a different result) <a id='3'></a> # Re-Train a third experiment for 20 epochs ## Creating and managing experiments - Provide project name - Provide experiment name - For a specific data create a single project - Inside each project multiple experiments can be created - Every experiment can be have diferent hyper-parameters attached to it ``` gtf = prototype(verbose=1); gtf.Prototype("Project", "Epochs-20"); ``` ### This creates files and directories as per the following structure workspace | |--------Project | | |-----Epochs-5 (Previously created) | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) | | |-----Epochs-10 (Previously Created) | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) | | |-----Epochs-20 (Created Now) | |-----experiment-state.json | |-----output | |------logs (All training logs and graphs saved here) | |------models (all trained models saved here) ## Modifyable params - dataset_path: path to data - model_name: which pretrained model to use - freeze_base_network: Retrain already trained network or not - num_epochs: Number of epochs to train for ``` gtf.Default(dataset_path="skin_cancer_mnist_dataset/images", path_to_csv="skin_cancer_mnist_dataset/train_labels.csv", model_name="resnet18_v2", freeze_base_network=True, num_epochs=20); #Set number of epochs here #Read the summary generated once you run this cell. ``` ## From summary above Training params Num Epochs: 20 ## Train the classifier ``` #Start Training gtf.Train(); #Read the training summary generated once you run the cell and training is completed ``` ### Final training loss - 0.750 ### Final validation loss - 0.829 (You may get a different result) <a id='4'></a> # Compare the experiments ``` # Invoke the comparison class from compare_prototype import compare ``` ### Creating and managing comparison experiments - Provide project name ``` # Create a project gtf = compare(verbose=1); gtf.Comparison("Compare-effect-of-num-epochs"); ``` ### This creates files and directories as per the following structure workspace | |--------comparison | | |-----Compare-effect-of-num-epochs | |------stats_best_val_acc.png |------stats_max_gpu_usage.png |------stats_training_time.png |------train_accuracy.png |------train_loss.png |------val_accuracy.png |------val_loss.png | |-----comparison.csv (Contains necessary details of all experiments) ### Add the experiments - First argument - Project name - Second argument - Experiment name ``` gtf.Add_Experiment("Project", "Epochs-5"); gtf.Add_Experiment("Project", "Epochs-10"); gtf.Add_Experiment("Project", "Epochs-20"); ``` ### Run Analysis ``` gtf.Generate_Statistics(); ``` ## Visualize and study comparison metrics ### Training Accuracy Curves ``` from IPython.display import Image Image(filename="workspace/comparison/Compare-effect-of-num-epochs/train_accuracy.png") ``` ### Training Loss Curves ``` from IPython.display import Image Image(filename="workspace/comparison/Compare-effect-of-num-epochs/train_loss.png") ``` ### Validation Accuracy Curves ``` from IPython.display import Image Image(filename="workspace/comparison/Compare-effect-of-num-epochs/val_accuracy.png") ``` ### Validation loss curves ``` from IPython.display import Image Image(filename="workspace/comparison/Compare-effect-of-num-epochs/val_loss.png") ``` ## Training Accuracies achieved ### With 5 epochs - 67.3% ### With 10 epochs - 68.3% ### With 20 epochs - 73.1% ## Validation accuracies achieved ### With 5 epochs - 63.7% ### With 10 epochs - 63.5% ### With 20 epochs - 72.0% #### Thing to note - After 15 epochs, accuracies and losses tend to saturate (You may get a different result)
github_jupyter
``` %matplotlib inline ``` ๋™์  ์–‘์žํ™” =========== ์ด ๋ ˆ์‹œํ”ผ์—์„œ๋Š” ๋™์  ์–‘์žํ™”(dynamic quantization)๋ฅผ ํ™œ์šฉํ•˜์—ฌ, LSTM๊ณผ ์œ ์‚ฌํ•œ ํ˜•ํƒœ์˜ ์ˆœํ™˜ ์‹ ๊ฒฝ๋ง์ด ์ข€ ๋” ๋น ๋ฅด๊ฒŒ ์ถ”๋ก ํ•˜๋„๋ก ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์„ ์‚ดํŽด ๋ด…๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ๋ชจ๋ธ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฐ€์ค‘์น˜์˜ ๊ทœ๋ชจ๋ฅผ ์ค„์ด๊ณ  ์ˆ˜ํ–‰ ์†๋„๋ฅผ ๋น ๋ฅด๊ฒŒ ๋งŒ๋“ค ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋„์ž… ---- ์šฐ๋ฆฌ๋Š” ์‹ ๊ฒฝ๋ง์„ ์„ค๊ณ„ํ•  ๋•Œ ์—ฌ๋Ÿฌ ํŠธ๋ ˆ์ด๋“œ์˜คํ”„(trade-off)๋ฅผ ๋งˆ์ฃผํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๋ชจ๋ธ์„ ๊ฐœ๋ฐœํ•˜๊ณ  ํ•™์Šตํ•  ๋•Œ ์ˆœํ™˜ ์‹ ๊ฒฝ๋ง์˜ ๋ ˆ์ด์–ด๋‚˜ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ์ˆ˜๋ฅผ ๋ฐ”๊ฟ”๋ณผ ์ˆ˜ ์žˆ์„ ํ…๋ฐ, ๊ทธ๋Ÿด ๋•Œ๋ฉด ์ •ํ™•๋„์™€ ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๋‚˜ ์‘๋‹ต ์†๋„(๋˜๋Š” ์ฒ˜๋ฆฌ๋Ÿ‰) ์‚ฌ์ด์— ํŠธ๋ ˆ์ด๋“œ์˜คํ”„๊ฐ€ ์ƒ๊ธฐ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌํ•œ ๋ณ€ํ™”๋ฅผ ์ค„ ๋•Œ๋ฉด ์‹œ๊ฐ„๊ณผ ์ปดํ“จํ„ฐ ์ž์›์ด ๋งŽ์ด ์†Œ๋ชจ๋˜๋Š”๋ฐ, ์ด๋Š” ๋ชจ๋ธ ํ•™์Šต ๊ณผ์ •์— ๋Œ€ํ•ด ๋ฐ˜๋ณต ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์–‘์žํ™” ๊ธฐ๋ฒ•์„ ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ์•Œ๋ ค์ง„ ๋ชจ๋ธ์˜ ํ•™์Šต์ด ๋๋‚œ ํ›„ ์„ฑ๋Šฅ๊ณผ ๋ชจ๋ธ์˜ ์ •ํ™•๋„ ์‚ฌ์ด์— ๋น„์Šทํ•œ ํŠธ๋ ˆ์ด๋“œ์˜คํ”„๋ฅผ ์ค„ ์ˆ˜ ์žˆ๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์—ฌ๋Ÿฌ๋ถ„์ด ์ด๋ฅผ ํ•œ ๋ฒˆ ์‹œ๋„ํ•ด ๋ณธ๋‹ค๋ฉด ์ •ํ™•๋„๊ฐ€ ๋ณ„๋กœ ์†์‹ค๋˜์ง€ ์•Š์œผ๋ฉด์„œ๋„ ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๋ฅผ ์ƒ๋‹นํžˆ ์ค„์ด๋ฉด์„œ ์‘๋‹ต ์‹œ๊ฐ„๋„ ๊ฐ์†Œ์‹œํ‚ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋™์  ์–‘์žํ™”๋ž€ ๋ฌด์—‡์ธ๊ฐ€? ----------------------- ์‹ ๊ฒฝ๋ง์„ ์–‘์žํ™”ํ•œ๋‹ค๋Š” ๋ง์˜ ์˜๋ฏธ๋Š” ๊ฐ€์ค‘์น˜๋‚˜ ํ™œ์„ฑํ™” ํ•จ์ˆ˜์—์„œ ์ •๋ฐ€๋„๊ฐ€ ๋‚ฎ์€ ์ •์ˆ˜ ํ‘œํ˜„์„ ์‚ฌ์šฉํ•˜๋„๋ก ๋ฐ”๊พผ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์œผ๋ฉฐ, CPU๋‚˜ GPU์—์„œ ์ˆ˜ํ–‰ํ•˜๋Š” ์ˆ˜์น˜ ์—ฐ์‚ฐ์˜ ์ฒ˜๋ฆฌ๋Ÿ‰๋„ ๋†’์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ถ€๋™์†Œ์ˆ˜์  ์‹ค์ˆ˜ ๊ฐ’์„ ์ •์ˆ˜๋กœ ๋ฐ”๊พธ๋Š” ๊ฒƒ์€ ๋ณธ์งˆ์ ์œผ๋กœ ์‹ค์ˆ˜ ๊ฐ’์— ์–ด๋–ค ๋ฐฐ์œจ์„ ๊ณฑํ•˜์—ฌ ๊ทธ ๊ฒฐ๊ด๊ฐ’์„ ์ •์ˆ˜๋กœ ๋ฐ˜์˜ฌ๋ฆผํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด ๋ฐฐ์œจ์„ ์–ด๋–ป๊ฒŒ ์ •ํ•  ๊ฒƒ์ด๋ƒ์— ๋”ฐ๋ผ ์–‘์žํ™”ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์—ฌ๋Ÿฌ ๊ฐ€์ง€๋กœ ๋‚˜๋‰ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์‚ดํŽด ๋ณผ ๋™์  ์–‘์žํ™”์˜ ํ•ต์‹ฌ์€ ๋ชจ๋ธ์„ ์ˆ˜ํ–‰ํ•  ๋•Œ ๋ฐ์ดํ„ฐ์˜ ๋ฒ”์œ„๋ฅผ ์‚ดํŽด ๋ณด๊ณ , ๊ทธ์— ๋”ฐ๋ผ ํ™œ์„ฑํ™” ํ•จ์ˆ˜์— ๊ณฑํ•  ๋ฐฐ์œจ์„ ๋™์ ์œผ๋กœ ๊ฒฐ์ •ํ•˜๋Š” ๋ฐ์— ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ๋ฐฐ์œจ์ด ํŠœ๋‹๋  ์ˆ˜ ์žˆ๋„๋ก, ์ฆ‰ ์‚ดํŽด๋ณด๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ์…‹์— ํฌํ•จ๋œ ์ •๋ณด๊ฐ€ ์ตœ๋Œ€ํ•œ ์œ ์ง€๋˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฐ˜๋ฉด์— ๋ชจ๋ธ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ๋ชจ๋ธ์„ ๋ณ€ํ™˜ํ•˜๋Š” ์‹œ์ ์— ์ด๋ฏธ ์•Œ๊ณ  ์žˆ๋Š” ์ƒํƒœ์ด๋ฉฐ, ๋”ฐ๋ผ์„œ ์‚ฌ์ „์— INT8 ํ˜•ํƒœ๋กœ ๋ฐ”๊ฟ”๋†“์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์–‘์žํ™”๋œ ๋ชจ๋ธ์—์„œ์˜ ์ˆ˜์น˜ ์—ฐ์‚ฐ์€ ๋ฒกํ„ฐํ™”๋œ INT8 ์—ฐ์‚ฐ์„ ํ†ตํ•ด ์ด๋ค„์ง‘๋‹ˆ๋‹ค. ๊ฐ’์„ ๋ˆ„์ ํ•˜๋Š” ์—ฐ์‚ฐ์€ ๋ณดํ†ต INT16์ด๋‚˜ INT32๋กœ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ์ด๋Š” ์˜ค๋ฒ„ํ”Œ๋กœ๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ฉ๋‹ˆ๋‹ค. ์ด์ฒ˜๋Ÿผ ๋†’์€ ์ •๋ฐ€๋„๋กœ ํ‘œํ˜„ํ•œ ๊ฐ’์€, ๊ทธ ๋‹ค์Œ ๋ ˆ์ด์–ด๊ฐ€ ์–‘์žํ™”๋˜์–ด ์žˆ๋‹ค๋ฉด ๋‹ค์‹œ INT8๋กœ ๋งž์ถ”๊ณ , ์ถœ๋ ฅ์ด๋ผ๋ฉด FP32๋กœ ๋ฐ”๊ฟ‰๋‹ˆ๋‹ค. ๋™์  ์–‘์žํ™”๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜ ํŠœ๋‹, ์ฆ‰ ๋ชจ๋ธ์„ ์ œํ’ˆ ํŒŒ์ดํ”„๋ผ์ธ์— ๋„ฃ๊ธฐ ์ ํ•ฉํ•œ ํ˜•ํƒœ๋กœ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค๋Š” ๋ถ€๋‹ด์ด ์ ์€ ํŽธ์ž…๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ์ž‘์—…์€ LSTM ๋ชจ๋ธ์„ ๋ฐฐํฌ์šฉ์œผ๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ๋ฉด ํ‘œ์ค€์ ์œผ๋กœ ๊ฑฐ์น˜๋Š” ๋‹จ๊ณ„์ž…๋‹ˆ๋‹ค. <div class="alert alert-info"><h4>Note</h4><p>์—ฌ๊ธฐ์„œ ์†Œ๊ฐœํ•  ์ ‘๊ทผ๋ฒ•์˜ ํ•œ๊ณ„ ์ด ๋ ˆ์‹œํ”ผ์—์„œ๋Š” PyTorch์˜ ๋™์  ์–‘์žํ™” ๊ธฐ๋Šฅ๊ณผ ์ด๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•œ ์ž‘์—… ํ๋ฆ„์— ๋Œ€ํ•ด ๊ฐ„๋‹จํžˆ ์‚ดํŽด๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๋Š” ๋ชจ๋ธ์„ ๋ณ€ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉํ•  ํŠน์ • ํ•จ์ˆ˜์— ์ดˆ์ ์„ ๋งž์ถฐ ์„ค๋ช…ํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…๋ฃŒํ•œ ์„ค๋ช…์„ ์œ„ํ•ด ์ƒ๋‹นํ•œ ๋ถ€๋ถ„์„ ๋‹จ์ˆœํ™”ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.</p></div> 1. ์•„์ฃผ ์ž‘์€ LSTM ๋„คํŠธ์›Œํฌ๋ฅผ ๊ฐ€์ง€๊ณ  ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. 2. ๋„คํŠธ์›Œํฌ๋ฅผ ๋žœ๋คํ•œ ์€๋‹‰ ์ƒํƒœ๋กœ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. 3. ๋„คํŠธ์›Œํฌ๋ฅผ ๋žœ๋คํ•œ ์ž…๋ ฅ์œผ๋กœ ํ…Œ์ŠคํŠธํ•ฉ๋‹ˆ๋‹ค. 4. ์ด ํŠœํ† ๋ฆฌ์–ผ์—์„œ๋Š” ๋„คํŠธ์›Œํฌ๋ฅผ ํ•™์Šตํ•˜์ง€ ์•Š์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค. 5. ์šฐ๋ฆฌ๊ฐ€ ๊ฐ€์ง€๊ณ  ์‹œ์ž‘ํ•œ ๋ถ€๋™์†Œ์ˆ˜์  ์‹ค์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋„คํŠธ์›Œํฌ๋ฅผ ์–‘์žํ™” ํ–ˆ์„ ๋•Œ, ๊ทœ๋ชจ๊ฐ€ ์ค„์–ด๋“ค๊ณ  ์ˆ˜ํ–‰ ์†๋„๊ฐ€ ๋นจ๋ผ์ง์„ ์‚ดํŽด๋ณผ ๊ฒƒ์ž…๋‹ˆ๋‹ค. 6. ๋„คํŠธ์›Œํฌ์˜ ์ถœ๋ ฅ๊ฐ’์ด FP32 ๋„คํŠธ์›Œํฌ์™€ ํฌ๊ฒŒ ๋‹ค๋ฅด์ง€ ์•Š์Œ์„ ์‚ดํŽด๋ณด๊ฒ ์ง€๋งŒ, ์‹ค์ œ๋กœ ํ•™์Šต๋œ ๋„คํŠธ์›Œํฌ์˜ ์ •ํ™•๋„ ์†์‹ค ๊ธฐ๋Œ“๊ฐ’์ด ์–ด๋–ป๊ฒŒ ๋˜๋Š”์ง€๋Š” ์‚ดํŽด๋ณด์ง€ ์•Š์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์—ฌ๋Ÿฌ๋ถ„์€ ๋™์  ์–‘์žํ™”๊ฐ€ ์–ด๋–ป๊ฒŒ ์ง„ํ–‰๋˜๋Š”์ง€ ์‚ดํŽด๋ณด๊ณ , ์ด๋ฅผ ํ†ตํ•ด ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰๊ณผ ์‘๋‹ต ์‹œ๊ฐ„์ด ์ค„์–ด๋“ ๋‹ค๋Š” ์ ์„ ์‚ดํŽด๋ณผ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด ๊ธฐ๋ฒ•์„ ํ•™์Šต๋œ LSTM์— ์ ์šฉํ•˜๋”๋ผ๋„ ์ •ํ™•๋„๋ฅผ ๋†’์€ ์ˆ˜์ค€์œผ๋กœ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ์Œ์„ ์‚ดํŽด๋ณด๋Š” ๊ฒƒ์€ ๊ณ ๊ธ‰ ํŠœํ† ๋ฆฌ์–ผ์˜ ๋‚ด์šฉ์œผ๋กœ ๋‚จ๊ฒจ๋‘๊ฒ ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์—ฌ๋Ÿฌ๋ถ„์ด ์ข€ ๋” ์—„๋ฐ€ํ•œ ๋‚ด์šฉ์œผ๋กœ ๋„˜์–ด๊ฐ€๊ณ  ์‹ถ๋‹ค๋ฉด `๊ณ ๊ธ‰ ๋™์  ์–‘์žํ™” ํŠœํ† ๋ฆฌ์–ผ <https://tutorials.pytorch.kr/advanced/dynamic_quantization_tutorial.html>`__ ์„ ์ฐธ๊ณ ํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ๋‹จ๊ณ„ ---- ์ด ๋ ˆ์‹œํ”ผ๋Š” ๋‹ค์„ฏ ๋‹จ๊ณ„๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. 1. ์ค€๋น„ - ์ด ๋‹จ๊ณ„์—์„œ๋Š” ์•„์ฃผ ๊ฐ„๋‹จํ•œ LSTM์„ ์ •์˜ํ•˜๊ณ , ํ•„์š”ํ•œ ๋ชจ๋“ˆ์„ ๋ถˆ๋Ÿฌ ์˜ค๊ณ , ๋ช‡ ๊ฐœ์˜ ๋žœ๋ค ์ž…๋ ฅ ํ…์„œ๋ฅผ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. 2. ์–‘์žํ™” ์ˆ˜ํ–‰ - ์ด ๋‹จ๊ณ„์—์„œ๋Š” ๋ถ€๋™์†Œ์ˆ˜์  ์‹ค์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ชจ๋ธ์„ ๋งŒ๋“ค๊ณ  ์ด๋ฅผ ์–‘์žํ™”ํ•œ ๋ฒ„์ „์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. 3. ๋ชจ๋ธ์˜ ๊ทœ๋ชจ ์‚ดํŽด๋ณด๊ธฐ - ์ด ๋‹จ๊ณ„์—์„œ๋Š” ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๊ฐ€ ์ค„์–ด๋“ค์—ˆ์Œ์„ ์‚ดํŽด๋ด…๋‹ˆ๋‹ค. 4. ์‘๋‹ต ์‹œ๊ฐ„ ์‚ดํŽด๋ณด๊ธฐ - ์ด ๋‹จ๊ณ„์—์„œ๋Š” ๋‘ ๋ชจ๋ธ์„ ๊ตฌ๋™์‹œํ‚ค๊ณ  ์‹คํ–‰ ์†๋„(์‘๋‹ต ์‹œ๊ฐ„)๋ฅผ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค. 5. ์ •ํ™•๋„ ์‚ดํŽด๋ณด๊ธฐ - ์ด ๋‹จ๊ณ„์—์„œ๋Š” ๋‘ ๋ชจ๋ธ์„ ๊ตฌ๋™์‹œํ‚ค๊ณ  ์ถœ๋ ฅ์„ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค. 1: ์ค€๋น„ ~~~~~~~ ์ด ๋‹จ๊ณ„์—์„œ๋Š” ์ด ๋ ˆ์‹œํ”ผ์—์„œ ๊ณ„์† ์‚ฌ์šฉํ•  ๋ช‡ ์ค„์˜ ๊ฐ„๋‹จํ•œ ์ฝ”๋“œ๋ฅผ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๊ฐ€ ์—ฌ๊ธฐ์„œ ๋ถˆ๋Ÿฌ์˜ฌ ์œ ์ผํ•œ ๋ชจ๋“ˆ์€ torch.quantization ๋ฟ์ด๋ฉฐ, ์ด ๋ชจ๋“ˆ์—๋Š” PyTorch์˜ ์–‘์žํ™” ๊ด€๋ จ ์—ฐ์‚ฐ์ž ๋ฐ ๋ณ€ํ™˜ ํ•จ์ˆ˜๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๋Š” ๋˜ ์•„์ฃผ ๊ฐ„๋‹จํ•œ LSTM ๋ชจ๋ธ์„ ์ •์˜ํ•˜๊ณ  ๋ช‡ ๊ฐœ์˜ ์ž…๋ ฅ์„ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. ``` # ์ด ๋ ˆ์‹œํ”ผ์—์„œ ์‚ฌ์šฉํ•  ๋ชจ๋“ˆ์„ ์—ฌ๊ธฐ์„œ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค import torch import torch.quantization import torch.nn as nn import copy import os import time # ์„ค๋ช…์„ ์œ„ํ•ด ์•„์ฃผ ์•„์ฃผ ๊ฐ„๋‹จํ•œ LSTM์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค # ์—ฌ๊ธฐ์„œ๋Š” ๋ ˆ์ด์–ด๊ฐ€ ํ•˜๋‚˜ ๋ฟ์ด๊ณ  ์‚ฌ์ „ ์ž‘์—…์ด๋‚˜ ์‚ฌํ›„ ์ž‘์—…์ด ์—†๋Š” # nn.LSTM์„ ๊ฐ์‹ธ์„œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค # ์ด๋Š” Robert Guthrie ์˜ # https://tutorials.pytorch.kr/beginner/nlp/sequence_models_tutorial.html ๊ณผ # https://tutorials.pytorch.kr/advanced/dynamic_quantization_tutorial.html ์—์„œ # ์˜๊ฐ์„ ๋ฐ›์€ ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค class lstm_for_demonstration(nn.Module): """๊ธฐ์ดˆ์ ์ธ LSTM๋ชจ๋ธ๋กœ, ๋‹จ์ˆœํžˆ nn.LSTM ๋ฅผ ๊ฐ์‹ผ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์„ค๋ช…์šฉ ์˜ˆ์‹œ ์ด์™ธ์˜ ์šฉ๋„๋กœ ์‚ฌ์šฉํ•˜๊ธฐ์—๋Š” ์ ํ•ฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. """ def __init__(self,in_dim,out_dim,depth): super(lstm_for_demonstration,self).__init__() self.lstm = nn.LSTM(in_dim,out_dim,depth) def forward(self,inputs,hidden): out,hidden = self.lstm(inputs,hidden) return out, hidden torch.manual_seed(29592) # ์žฌํ˜„์„ ์œ„ํ•œ ์„ค์ • # ๋งค๊ฐœ๋ณ€์ˆ˜ ๋‹ค๋“ฌ๊ธฐ(๋„คํŠธ์›Œํฌ์˜ ๋ชจ์–‘(shape) ์ •ํ•˜๊ธฐ) model_dimension=8 sequence_length=20 batch_size=1 lstm_depth=1 # ์ž…๋ ฅ์šฉ ๋žœ๋ค ๋ฐ์ดํ„ฐ inputs = torch.randn(sequence_length,batch_size,model_dimension) # hidden ์€ ์‚ฌ์‹ค ์ดˆ๊ธฐ ์€๋‹‰ ์ƒํƒœ(hidden state)์™€ ์ดˆ๊ธฐ ์…€ ์ƒํƒœ(cell state)๋กœ ๊ตฌ์„ฑ๋œ ํŠœํ”Œ์ž…๋‹ˆ๋‹ค hidden = (torch.randn(lstm_depth,batch_size,model_dimension), torch.randn(lstm_depth,batch_size,model_dimension)) ``` 2: ์–‘์žํ™” ์ˆ˜ํ–‰ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ์ด์ œ ์žฌ๋ฐŒ๋Š” ๋ถ€๋ถ„์„ ์‚ดํŽด๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค. ์šฐ์„ ์€ ์–‘์žํ™” ํ•  ๋ชจ๋ธ ๊ฐ์ฒด๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ  ๊ทธ ์ด๋ฆ„์„ float\_lstm ์œผ๋กœ ๋‘ก๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๊ฐ€ ์—ฌ๊ธฐ์„œ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜๋Š” :: torch.quantization.quantize_dynamic() ์ž…๋‹ˆ๋‹ค (`๊ด€๋ จ ๋ฌธ์„œ ์ฐธ๊ณ  <https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic>`__). ์ด ํ•จ์ˆ˜๋Š” ๋ชจ๋ธ๊ณผ, ๋งŒ์•ฝ ๋“ฑ์žฅํ•œ๋‹ค๋ฉด ์–‘์žํ™”ํ•˜๊ณ  ์‹ถ์€ ์„œ๋ธŒ๋ชจ๋“ˆ์˜ ๋ชฉ๋ก, ๊ทธ๋ฆฌ๊ณ  ์šฐ๋ฆฌ๊ฐ€ ์‚ฌ์šฉํ•˜๋ ค ํ•˜๋Š” ์ž๋ฃŒํ˜•์„ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ์›๋ณธ ๋ชจ๋ธ์„ ์–‘์žํ™”ํ•œ ๋ฒ„์ „์„ ์ƒˆ๋กœ์šด ๋ชจ๋“ˆ์˜ ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ด๊ฒŒ ๋‚ด์šฉ์˜ ์ „๋ถ€์ž…๋‹ˆ๋‹ค. ``` # ๋ถ€๋™์†Œ์ˆ˜์  ์‹ค์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค float_lstm = lstm_for_demonstration(model_dimension, model_dimension,lstm_depth) # ์ด ํ•จ์ˆ˜ ํ˜ธ์ถœ์ด ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค quantized_lstm = torch.quantization.quantize_dynamic( float_lstm, {nn.LSTM, nn.Linear}, dtype=torch.qint8 ) # ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ๋Š”์ง€ ์‚ดํŽด๋ด…๋‹ˆ๋‹ค print('Here is the floating point version of this module:') print(float_lstm) print('') print('and now the quantized version:') print(quantized_lstm) ``` 3. ๋ชจ๋ธ์˜ ๊ทœ๋ชจ ์‚ดํŽด๋ณด๊ธฐ ~~~~~~~~~~~~~~~~~~~~~~~ ์ž, ์ด์ œ ๋ชจ๋ธ์„ ์–‘์žํ™” ํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ์–ด๋–ค ์ด๋“์ด ์žˆ์„๊นŒ์š”? ์šฐ์„  ์ฒซ ๋ฒˆ์งธ๋Š” FP32 ๋ชจ๋ธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ INT8 ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜ํ–ˆ๋‹ค๋Š” (๊ทธ๋ฆฌ๊ณ  ๋ฐฐ์œจ ๊ฐ’๋„ ๊ตฌํ–ˆ๋‹ค๋Š”) ์ ์ž…๋‹ˆ๋‹ค. ์ด๋Š” ์šฐ๋ฆฌ๊ฐ€ ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ๋‹ค๋ฃจ๋Š” ๋ฐ์— ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ์˜ ์–‘์ด ์•ฝ 75% ๊ฐ์†Œํ–ˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ์ ์ธ ๊ฐ’์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ž˜์ฒ˜๋Ÿผ ๊ฐ์†Œ๋Ÿ‰์ด 75% ๋ณด๋‹ค๋Š” ์ ์ง€๋งŒ, ๋งŒ์•ฝ ์•ž์—์„œ ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๋ฅผ ๋” ํฌ๊ฒŒ ์žก์•˜๋‹ค๋ฉด (๊ฐ€๋ น ๋ชจ๋ธ์˜ ์ฐจ์›์„ 80 ๊ฐ™์€ ๊ฐ’์œผ๋กœ ๋‘์—ˆ๋‹ค๋ฉด) ๊ฐ์†Œ์œจ์ด 4๋ถ„์˜ 1๋กœ ์ˆ˜๋ ดํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด๋Š” ์ €์žฅ๋œ ๋ชจ๋ธ์˜ ๊ทœ๋ชจ๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ๊ฐ’์— ํ›จ์”ฌ ๋” ์˜์กดํ•˜๊ฒŒ ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ``` def print_size_of_model(model, label=""): torch.save(model.state_dict(), "temp.p") size=os.path.getsize("temp.p") print("model: ",label,' \t','Size (KB):', size/1e3) os.remove('temp.p') return size # ๊ทœ๋ชจ ๋น„๊ตํ•˜๊ธฐ f=print_size_of_model(float_lstm,"fp32") q=print_size_of_model(quantized_lstm,"int8") print("{0:.2f} times smaller".format(f/q)) ``` 4. ์‘๋‹ต ์‹œ๊ฐ„ ์‚ดํŽด๋ณด๊ธฐ ~~~~~~~~~~~~~~~~~~~~~ ์ข‹์€ ์  ๋‘ ๋ฒˆ์งธ๋Š” ํ†ต์ƒ์ ์œผ๋กœ ์–‘์žํ™”๋œ ๋ชจ๋ธ์˜ ์ˆ˜ํ–‰ ์†๋„๊ฐ€ ์ข€ ๋” ๋น ๋ฅด๋‹ค๋Š” ์ ์ž…๋‹ˆ๋‹ค. ์ด๋Š” 1. ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐ ์‹œ๊ฐ„์ด ๋œ ๋“ค๊ธฐ ๋•Œ๋ฌธ 2. INT8 ์—ฐ์‚ฐ์ด ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ ๋“ฑ์˜ ์ด์œ  ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์ด์ œ ์‚ดํŽด๋ณด๊ฒ ์ง€๋งŒ, ์ด ์•„์ฃผ ๊ฐ„๋‹จํ•œ ๋„คํŠธ์›Œํฌ์˜ ์–‘์žํ™”๋œ ๋ฒ„์ „์€ ๊ทธ ์ˆ˜ํ–‰ ์†๋„๊ฐ€ ๋” ๋น ๋ฆ…๋‹ˆ๋‹ค. ์ด๋Š” ์ข€ ๋” ๋ณต์žกํ•œ ๋„คํŠธ์›Œํฌ์— ๋Œ€ํ•ด์„œ๋„ ๋Œ€์ฒด๋กœ ์„ฑ๋ฆฝํ•˜๋Š” ํŠน์ง•์ด์ง€๋งŒ, ๋ชจ๋ธ์˜ ๊ตฌ์กฐ๋‚˜ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•  ํ•˜๋“œ์›จ์–ด์˜ ํŠน์„ฑ ๋“ฑ ์—ฌ๋Ÿฌ ๊ฐ€์ง€ ์š”์†Œ์— ๋”ฐ๋ผ ๊ทธ๋•Œ ๊ทธ๋•Œ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ``` # ์„ฑ๋Šฅ ๋น„๊ตํ•˜๊ธฐ print("Floating point FP32") # %timeit float_lstm.forward(inputs, hidden) print("Quantized INT8") # %timeit quantized_lstm.forward(inputs,hidden) ``` 5: ์ •ํ™•๋„ ์‚ดํŽด๋ณด๊ธฐ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ์šฐ๋ฆฌ๋Š” ์—ฌ๊ธฐ์„œ ์ •ํ™•๋„๋ฅผ ์ž์„ธํžˆ ์‚ดํŽด๋ณด์ง„ ์•Š์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด๋Š” ์šฐ๋ฆฌ๊ฐ€ ์ œ๋Œ€๋กœ ํ•™์Šต๋œ ๋„คํŠธ์›Œํฌ๊ฐ€ ์•„๋‹ˆ๋ผ ๋žœ๋คํ•˜๊ฒŒ ์ดˆ๊ธฐํ™”๋œ ๋„คํŠธ์›Œํฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๊ทธ๋Ÿผ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ์–‘์žํ™”๋œ ๋„คํŠธ์›Œํฌ์˜ ์ถœ๋ ฅ ํ…์„œ๊ฐ€ ์›๋ณธ๊ณผ 'ํฌ๊ฒŒ ๋‹ค๋ฅด์ง€ ์•Š๋‹ค'๋Š” ์ ์„ ์‚ดํŽด๋ณด๋Š” ๊ฒƒ์€ ์˜๋ฏธ๊ฐ€ ์žˆ๋‹ค๊ณ  ๋ด…๋‹ˆ๋‹ค. ์ข€ ๋” ์ž์„ธํ•œ ๋ถ„์„์€ ์ด ๋ ˆ์‹œํ”ผ์˜ ๋๋ถ€๋ถ„์— ์ฐธ๊ณ  ์ž๋ฃŒ๋กœ ์˜ฌ๋ ค๋‘” ๊ณ ๊ธ‰ ํŠœํ† ๋ฆฌ์–ผ์„ ์ฐธ๊ณ ํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ``` # ๋ถ€๋™์†Œ์ˆ˜์  ๋ชจ๋ธ ๊ตฌ๋™ํ•˜๊ธฐ out1, hidden1 = float_lstm(inputs, hidden) mag1 = torch.mean(abs(out1)).item() print('mean absolute value of output tensor values in the FP32 model is {0:.5f} '.format(mag1)) # ์–‘์žํ™”๋œ ๋ชจ๋ธ ๊ตฌ๋™ํ•˜๊ธฐ out2, hidden2 = quantized_lstm(inputs, hidden) mag2 = torch.mean(abs(out2)).item() print('mean absolute value of output tensor values in the INT8 model is {0:.5f}'.format(mag2)) # ๋‘˜์˜ ๊ฒฐ๊ณผ ๋น„๊ตํ•˜๊ธฐ mag3 = torch.mean(abs(out1-out2)).item() print('mean absolute value of the difference between the output tensors is {0:.5f} or {1:.2f} percent'.format(mag3,mag3/mag1*100)) ``` ์ข€ ๋” ์•Œ์•„๋ณด๊ธฐ -------------- ์šฐ๋ฆฌ๋Š” ๋™์  ์–‘์žํ™”๊ฐ€ ๋ฌด์—‡์ด๋ฉฐ ์–ด๋–ค ์ด์ ์ด ์žˆ๋Š”์ง€ ์‚ดํŽด๋ณด์•˜๊ณ , ๊ฐ„๋‹จํ•œ LSTM ๋ชจ๋ธ์„ ๋น ๋ฅด๊ฒŒ ์–‘์žํ™”ํ•˜๊ธฐ ์œ„ํ•ด ``torch.quantization.quantize_dynamic()`` ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ฌธ์„œ๋Š” ๋น ๋ฅด๊ณ  ๊ณ ์ˆ˜์ค€์˜ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค. ์ข€ ๋” ์ž์„ธํ•˜๊ฒŒ ๋ณด์‹œ๋ ค๋ฉด, `(beta) Dynamic Quantization on an LSTM Word Language Model Tutorial <https://tutorials.pytorch.kr/advanced/dynamic\_quantization\_tutorial.html>`_ ๋ฐฉ๋ฌธํ•˜์—ฌ ๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค ์ด ๋ ˆ์‹œํ”ผ์—์„œ๋Š” ์ด๋Ÿฌํ•œ ๋‚ด์šฉ์„ ๋น ๋ฅด๊ฒŒ, ๊ทธ๋ฆฌ๊ณ  ๊ณ ์ˆ˜์ค€์—์„œ ์‚ดํŽด ๋ณด์•˜์Šต๋‹ˆ๋‹ค. ์ข€ ๋” ์ž์„ธํ•œ ๋‚ด์šฉ์„ ์•Œ์•„๋ณด๊ณ  ์‹ถ๋‹ค๋ฉด `(๋ฒ ํƒ€) LSTM ์–ธ์–ด ๋ชจ๋ธ ๋™์  ์–‘์žํ™” ํŠœํ† ๋ฆฌ์–ผ <https://tutorials.pytorch.kr/advanced/dynamic\_quantization\_tutorial.html>`_ ์„ ๊ณ„์† ๊ณต๋ถ€ํ•ด ๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ์ฐธ๊ณ  ์ž๋ฃŒ ========= ๋ฌธ์„œ ~~~~ `์–‘์žํ™” API ๋ฌธ์„œ <https://pytorch.org/docs/stable/quantization.html>`_ ํŠœํ† ๋ฆฌ์–ผ ~~~~~~~~ `(๋ฒ ํƒ€) BERT ๋™์  ์–‘์žํ™” <https://tutorials.pytorch.kr/intermediate/dynamic\_quantization\_bert\_tutorial.html>`_ `(๋ฒ ํƒ€) LSTM ์–ธ์–ด ๋ชจ๋ธ ๋™์  ์–‘์žํ™” <https://tutorials.pytorch.kr/advanced/dynamic\_quantization\_tutorial.html>`_ ๋ธ”๋กœ๊ทธ ๊ธ€ ~~~~~~~~~ `PyTorch์—์„œ ์–‘์žํ™” ์ˆ˜ํ–‰ํ•˜๊ธฐ ์ž…๋ฌธ์„œ <https://pytorch.org/blog/introduction-to-quantization-on-pytorch/>`_
github_jupyter
## ็ฏ„ไพ‹้‡้ปž * ๅญธ็ฟ’ๅฆ‚ไฝ•ๅœจ keras ไธญๅŠ ๅ…ฅ reduce learning rate * ็Ÿฅ้“ๅฆ‚ไฝ•่จญๅฎš reduce_lr ็š„็›ฃๆŽง็›ฎๆจ™ * ๆฏ”่ผƒไฝฟ็”จๆœ‰็„กไฝฟ็”จ reduce_lr ๆ™‚็š„ performance ``` import os import keras # ๆœฌ็ฏ„ไพ‹ไธ้œ€ไฝฟ็”จ GPU, ๅฐ‡ GPU ่จญๅฎš็‚บ "็„ก" os.environ["CUDA_VISIBLE_DEVICES"] = "" train, test = keras.datasets.cifar10.load_data() ## ่ณ‡ๆ–™ๅ‰่™•็† def preproc_x(x, flatten=True): x = x / 255. if flatten: x = x.reshape((len(x), -1)) return x def preproc_y(y, num_classes=10): if y.shape[-1] == 1: y = keras.utils.to_categorical(y, num_classes) return y x_train, y_train = train x_test, y_test = test # ่ณ‡ๆ–™ๅ‰่™•็† - X ๆจ™ๆบ–ๅŒ– x_train = preproc_x(x_train) x_test = preproc_x(x_test) # ่ณ‡ๆ–™ๅ‰่™•็† -Y ่ฝ‰ๆˆ onehot y_train = preproc_y(y_train) y_test = preproc_y(y_test) from keras.layers import BatchNormalization """ ๅปบ็ซ‹็ฅž็ถ“็ถฒ่ทฏ๏ผŒไธฆๅŠ ๅ…ฅ BN layer """ def build_mlp(input_shape, output_units=10, num_neurons=[512, 256, 128]): input_layer = keras.layers.Input(input_shape) for i, n_units in enumerate(num_neurons): if i == 0: x = keras.layers.Dense(units=n_units, activation="relu", name="hidden_layer"+str(i+1))(input_layer) x = BatchNormalization()(x) else: x = keras.layers.Dense(units=n_units, activation="relu", name="hidden_layer"+str(i+1))(x) x = BatchNormalization()(x) out = keras.layers.Dense(units=output_units, activation="softmax", name="output")(x) model = keras.models.Model(inputs=[input_layer], outputs=[out]) return model ## ่ถ…ๅƒๆ•ธ่จญๅฎš LEARNING_RATE = 1e-3 EPOCHS = 50 BATCH_SIZE = 1024 MOMENTUM = 0.95 """ # ่ผ‰ๅ…ฅ Callbacks, ไธฆ่จญๅฎš็›ฃๆŽง็›ฎๆจ™็‚บ validation loss """ from keras.callbacks import ReduceLROnPlateau reduce_lr = ReduceLROnPlateau(factor=0.5, min_lr=1e-12, monitor='val_loss', patience=5, verbose=1) model = build_mlp(input_shape=x_train.shape[1:]) model.summary() optimizer = keras.optimizers.SGD(lr=LEARNING_RATE, nesterov=True, momentum=MOMENTUM) model.compile(loss="categorical_crossentropy", metrics=["accuracy"], optimizer=optimizer) model.fit(x_train, y_train, epochs=EPOCHS, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), shuffle=True, callbacks=[reduce_lr] ) # Collect results train_loss = model.history.history["loss"] valid_loss = model.history.history["val_loss"] train_acc = model.history.history["acc"] valid_acc = model.history.history["val_acc"] import matplotlib.pyplot as plt %matplotlib inline plt.plot(range(len(train_loss)), train_loss, label="train loss") plt.plot(range(len(valid_loss)), valid_loss, label="valid loss") plt.legend() plt.title("Loss") plt.show() plt.plot(range(len(train_acc)), train_acc, label="train accuracy") plt.plot(range(len(valid_acc)), valid_acc, label="valid accuracy") plt.legend() plt.title("Accuracy") plt.show() ``` ## Work 1. ่ซ‹ๆ”น่ฎŠ reduce_lr ็š„ patience ๅ’Œ factor ไธฆๆฏ”่ผƒไธๅŒ่จญๅฎšไธ‹๏ผŒๅฐ่จ“็ทด/้ฉ—่ญ‰้›†็š„ๅฝฑ้Ÿฟ 2. ่ซ‹ๅฐ‡ optimizer ๆ›ๆˆ Adamใ€RMSprop ๆญ้… reduce_lr ไธฆๆฏ”่ผƒ่จ“็ทด็ตๆžœ
github_jupyter
# Tools - Pandas *The `pandas` library provides high-performance, easy-to-use data structures and data analysis tools. The main data structure is the `DataFrame`, which you can think of as an in-memory 2D table (like a spreadsheet, with column names and row labels). Many features available in Excel are available programmatically, such as creating pivot tables, computing columns based on other columns, plotting graphs, etc. You can also group rows by column value, or join tables much like in SQL. Pandas is also great at handling time series.* Prerequisites: * NumPy โ€“ if you are not familiar with NumPy, we recommend that you go through the [NumPy tutorial](tools_numpy.ipynb) now. ## Setup First, let's import `pandas`. People usually import it as `pd`: ``` import pandas as pd ``` ## `Series` objects The `pandas` library contains these useful data structures: * `Series` objects, that we will discuss now. A `Series` object is 1D array, similar to a column in a spreadsheet (with a column name and row labels). * `DataFrame` objects. This is a 2D table, similar to a spreadsheet (with column names and row labels). * `Panel` objects. You can see a `Panel` as a dictionary of `DataFrame`s. These are less used, so we will not discuss them here. ## Creating a `Series` Let's start by creating our first `Series` object! ``` s = pd.Series([2,-1,3,5]) s ``` ## Similar to a 1D `ndarray` `Series` objects behave much like one-dimensional NumPy `ndarray`s, and you can often pass them as parameters to NumPy functions: ``` import numpy as np np.exp(s) ``` Arithmetic operations on `Series` are also possible, and they apply *elementwise*, just like for `ndarray`s: ``` s + [1000,2000,3000,4000] ``` Similar to NumPy, if you add a single number to a `Series`, that number is added to all items in the `Series`. This is called * broadcasting*: ``` s + 1000 ``` The same is true for all binary operations such as `*` or `/`, and even conditional operations: ``` s < 0 ``` ## Index labels Each item in a `Series` object has a unique identifier called the *index label*. By default, it is simply the rank of the item in the `Series` (starting at `0`) but you can also set the index labels manually: ``` s2 = pd.Series([68, 83, 112, 68], index=["alice", "bob", "charles", "darwin"]) s2 ``` You can then use the `Series` just like a `dict`: ``` s2["bob"] ``` You can still access the items by integer location, like in a regular array: ``` s2[1] ``` To make it clear when you are accessing by label or by integer location, it is recommended to always use the `loc` attribute when accessing by label, and the `iloc` attribute when accessing by integer location: ``` s2.loc["bob"] s2.iloc[1] ``` Slicing a `Series` also slices the index labels: ``` s2.iloc[1:3] ``` This can lead to unexpected results when using the default numeric labels, so be careful: ``` surprise = pd.Series([1000, 1001, 1002, 1003]) surprise surprise_slice = surprise[2:] surprise_slice ``` Oh look! The first element has index label `2`. The element with index label `0` is absent from the slice: ``` try: surprise_slice[0] except KeyError as e: print("Key error:", e) ``` But remember that you can access elements by integer location using the `iloc` attribute. This illustrates another reason why it's always better to use `loc` and `iloc` to access `Series` objects: ``` surprise_slice.iloc[0] ``` ## Init from `dict` You can create a `Series` object from a `dict`. The keys will be used as index labels: ``` weights = {"alice": 68, "bob": 83, "colin": 86, "darwin": 68} s3 = pd.Series(weights) s3 ``` You can control which elements you want to include in the `Series` and in what order by explicitly specifying the desired `index`: ``` s4 = pd.Series(weights, index = ["colin", "alice"]) s4 ``` ## Automatic alignment When an operation involves multiple `Series` objects, `pandas` automatically aligns items by matching index labels. ``` print(s2.keys()) print(s3.keys()) s2 + s3 ``` The resulting `Series` contains the union of index labels from `s2` and `s3`. Since `"colin"` is missing from `s2` and `"charles"` is missing from `s3`, these items have a `NaN` result value. (ie. Not-a-Number means *missing*). Automatic alignment is very handy when working with data that may come from various sources with varying structure and missing items. But if you forget to set the right index labels, you can have surprising results: ``` s5 = pd.Series([1000,1000,1000,1000]) print("s2 =", s2.values) print("s5 =", s5.values) s2 + s5 ``` Pandas could not align the `Series`, since their labels do not match at all, hence the full `NaN` result. ## Init with a scalar You can also initialize a `Series` object using a scalar and a list of index labels: all items will be set to the scalar. ``` meaning = pd.Series(42, ["life", "universe", "everything"]) meaning ``` ## `Series` name A `Series` can have a `name`: ``` s6 = pd.Series([83, 68], index=["bob", "alice"], name="weights") s6 ``` ## Plotting a `Series` Pandas makes it easy to plot `Series` data using matplotlib (for more details on matplotlib, check out the [matplotlib tutorial](tools_matplotlib.ipynb)). Just import matplotlib and call the `plot()` method: ``` %matplotlib inline import matplotlib.pyplot as plt temperatures = [4.4,5.1,6.1,6.2,6.1,6.1,5.7,5.2,4.7,4.1,3.9,3.5] s7 = pd.Series(temperatures, name="Temperature") s7.plot() plt.show() ``` There are *many* options for plotting your data. It is not necessary to list them all here: if you need a particular type of plot (histograms, pie charts, etc.), just look for it in the excellent [Visualization](http://pandas.pydata.org/pandas-docs/stable/visualization.html) section of pandas' documentation, and look at the example code. ## Handling time Many datasets have timestamps, and pandas is awesome at manipulating such data: * it can represent periods (such as 2016Q3) and frequencies (such as "monthly"), * it can convert periods to actual timestamps, and *vice versa*, * it can resample data and aggregate values any way you like, * it can handle timezones. ## Time range Let's start by creating a time series using `pd.date_range()`. This returns a `DatetimeIndex` containing one datetime per hour for 12 hours starting on October 29th 2016 at 5:30pm. ``` dates = pd.date_range('2016/10/29 5:30pm', periods=12, freq='H') dates ``` This `DatetimeIndex` may be used as an index in a `Series`: ``` temp_series = pd.Series(temperatures, dates) temp_series ``` Let's plot this series: ``` temp_series.plot(kind="bar") plt.grid(True) plt.show() ``` ## Resampling Pandas lets us resample a time series very simply. Just call the `resample()` method and specify a new frequency: ``` temp_series_freq_2H = temp_series.resample("2H") temp_series_freq_2H ``` The resampling operation is actually a deferred operation, which is why we did not get a `Series` object, but a `DatetimeIndexResampler` object instead. To actually perform the resampling operation, we can simply call the `mean()` method: Pandas will compute the mean of every pair of consecutive hours: ``` temp_series_freq_2H = temp_series_freq_2H.mean() ``` Let's plot the result: ``` temp_series_freq_2H.plot(kind="bar") plt.show() ``` Note how the values have automatically been aggregated into 2-hour periods. If we look at the 6-8pm period, for example, we had a value of `5.1` at 6:30pm, and `6.1` at 7:30pm. After resampling, we just have one value of `5.6`, which is the mean of `5.1` and `6.1`. Rather than computing the mean, we could have used any other aggregation function, for example we can decide to keep the minimum value of each period: ``` temp_series_freq_2H = temp_series.resample("2H").min() temp_series_freq_2H ``` Or, equivalently, we could use the `apply()` method instead: ``` temp_series_freq_2H = temp_series.resample("2H").apply(np.min) temp_series_freq_2H ``` ## Upsampling and interpolation This was an example of downsampling. We can also upsample (ie. increase the frequency), but this creates holes in our data: ``` temp_series_freq_15min = temp_series.resample("15Min").mean() temp_series_freq_15min.head(n=10) # `head` displays the top n values ``` One solution is to fill the gaps by interpolating. We just call the `interpolate()` method. The default is to use linear interpolation, but we can also select another method, such as cubic interpolation: ``` temp_series_freq_15min = temp_series.resample("15Min").interpolate(method="cubic") temp_series_freq_15min.head(n=10) temp_series.plot(label="Period: 1 hour") temp_series_freq_15min.plot(label="Period: 15 minutes") plt.legend() plt.show() ``` ## Timezones By default datetimes are *naive*: they are not aware of timezones, so 2016-10-30 02:30 might mean October 30th 2016 at 2:30am in Paris or in New York. We can make datetimes timezone *aware* by calling the `tz_localize()` method: ``` temp_series_ny = temp_series.tz_localize("America/New_York") temp_series_ny ``` Note that `-04:00` is now appended to all the datetimes. This means that these datetimes refer to [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) - 4 hours. We can convert these datetimes to Paris time like this: ``` temp_series_paris = temp_series_ny.tz_convert("Europe/Paris") temp_series_paris ``` You may have noticed that the UTC offset changes from `+02:00` to `+01:00`: this is because France switches to winter time at 3am that particular night (time goes back to 2am). Notice that 2:30am occurs twice! Let's go back to a naive representation (if you log some data hourly using local time, without storing the timezone, you might get something like this): ``` temp_series_paris_naive = temp_series_paris.tz_localize(None) temp_series_paris_naive ``` Now `02:30` is really ambiguous. If we try to localize these naive datetimes to the Paris timezone, we get an error: ``` try: temp_series_paris_naive.tz_localize("Europe/Paris") except Exception as e: print(type(e)) print(e) ``` Fortunately using the `ambiguous` argument we can tell pandas to infer the right DST (Daylight Saving Time) based on the order of the ambiguous timestamps: ``` temp_series_paris_naive.tz_localize("Europe/Paris", ambiguous="infer") ``` ## Periods The `pd.period_range()` function returns a `PeriodIndex` instead of a `DatetimeIndex`. For example, let's get all quarters in 2016 and 2017: ``` quarters = pd.period_range('2016Q1', periods=8, freq='Q') quarters ``` Adding a number `N` to a `PeriodIndex` shifts the periods by `N` times the `PeriodIndex`'s frequency: ``` quarters + 3 ``` The `asfreq()` method lets us change the frequency of the `PeriodIndex`. All periods are lengthened or shortened accordingly. For example, let's convert all the quarterly periods to monthly periods (zooming in): ``` quarters.asfreq("M") ``` By default, the `asfreq` zooms on the end of each period. We can tell it to zoom on the start of each period instead: ``` quarters.asfreq("M", how="start") ``` And we can zoom out: ``` quarters.asfreq("A") ``` Of course we can create a `Series` with a `PeriodIndex`: ``` quarterly_revenue = pd.Series([300, 320, 290, 390, 320, 360, 310, 410], index = quarters) quarterly_revenue quarterly_revenue.plot(kind="line") plt.show() ``` We can convert periods to timestamps by calling `to_timestamp`. By default this will give us the first day of each period, but by setting `how` and `freq`, we can get the last hour of each period: ``` last_hours = quarterly_revenue.to_timestamp(how="end", freq="H") last_hours ``` And back to periods by calling `to_period`: ``` last_hours.to_period() ``` Pandas also provides many other time-related functions that we recommend you check out in the [documentation](http://pandas.pydata.org/pandas-docs/stable/timeseries.html). To whet your appetite, here is one way to get the last business day of each month in 2016, at 9am: ``` months_2016 = pd.period_range("2016", periods=12, freq="M") one_day_after_last_days = months_2016.asfreq("D") + 1 last_bdays = one_day_after_last_days.to_timestamp() - pd.tseries.offsets.BDay() last_bdays.to_period("H") + 9 ``` ## `DataFrame` objects A DataFrame object represents a spreadsheet, with cell values, column names and row index labels. You can define expressions to compute columns based on other columns, create pivot-tables, group rows, draw graphs, etc. You can see `DataFrame`s as dictionaries of `Series`. ## Creating a `DataFrame` You can create a DataFrame by passing a dictionary of `Series` objects: ``` people_dict = { "weight": pd.Series([68, 83, 112], index=["alice", "bob", "charles"]), "birthyear": pd.Series([1984, 1985, 1992], index=["bob", "alice", "charles"], name="year"), "children": pd.Series([0, 3], index=["charles", "bob"]), "hobby": pd.Series(["Biking", "Dancing"], index=["alice", "bob"]), } people = pd.DataFrame(people_dict) people ``` A few things to note: * the `Series` were automatically aligned based on their index, * missing values are represented as `NaN`, * `Series` names are ignored (the name `"year"` was dropped), * `DataFrame`s are displayed nicely in Jupyter notebooks, woohoo! You can access columns pretty much as you would expect. They are returned as `Series` objects: ``` people["birthyear"] ``` You can also get multiple columns at once: ``` people[["birthyear", "hobby"]] ``` If you pass a list of columns and/or index row labels to the `DataFrame` constructor, it will guarantee that these columns and/or rows will exist, in that order, and no other column/row will exist. For example: ``` d2 = pd.DataFrame( people_dict, columns=["birthyear", "weight", "height"], index=["bob", "alice", "eugene"] ) d2 ``` Another convenient way to create a `DataFrame` is to pass all the values to the constructor as an `ndarray`, or a list of lists, and specify the column names and row index labels separately: ``` values = [ [1985, np.nan, "Biking", 68], [1984, 3, "Dancing", 83], [1992, 0, np.nan, 112] ] d3 = pd.DataFrame( values, columns=["birthyear", "children", "hobby", "weight"], index=["alice", "bob", "charles"] ) d3 ``` To specify missing values, you can either use `np.nan` or NumPy's masked arrays: ``` masked_array = np.ma.asarray(values, dtype=np.object) masked_array[(0, 2), (1, 2)] = np.ma.masked d3 = pd.DataFrame( masked_array, columns=["birthyear", "children", "hobby", "weight"], index=["alice", "bob", "charles"] ) d3 ``` Instead of an `ndarray`, you can also pass a `DataFrame` object: ``` d4 = pd.DataFrame( d3, columns=["hobby", "children"], index=["alice", "bob"] ) d4 ``` It is also possible to create a `DataFrame` with a dictionary (or list) of dictionaries (or list): ``` people = pd.DataFrame({ "birthyear": {"alice":1985, "bob": 1984, "charles": 1992}, "hobby": {"alice":"Biking", "bob": "Dancing"}, "weight": {"alice":68, "bob": 83, "charles": 112}, "children": {"bob": 3, "charles": 0} }) people ``` ## Multi-indexing If all columns are tuples of the same size, then they are understood as a multi-index. The same goes for row index labels. For example: ``` d5 = pd.DataFrame( { ("public", "birthyear"): {("Paris","alice"):1985, ("Paris","bob"): 1984, ("London","charles"): 1992}, ("public", "hobby"): {("Paris","alice"):"Biking", ("Paris","bob"): "Dancing"}, ("private", "weight"): {("Paris","alice"):68, ("Paris","bob"): 83, ("London","charles"): 112}, ("private", "children"): {("Paris", "alice"):np.nan, ("Paris","bob"): 3, ("London","charles"): 0} } ) d5 ``` You can now get a `DataFrame` containing all the `"public"` columns very simply: ``` d5["public"] d5["public", "hobby"] # Same result as d5["public"]["hobby"] ``` ## Dropping a level Let's look at `d5` again: ``` d5 ``` There are two levels of columns, and two levels of indices. We can drop a column level by calling `droplevel()` (the same goes for indices): ``` d5.columns = d5.columns.droplevel(level = 0) d5 ``` ## Transposing You can swap columns and indices using the `T` attribute: ``` d6 = d5.T d6 ``` ## Stacking and unstacking levels Calling the `stack()` method will push the lowest column level after the lowest index: ``` d7 = d6.stack() d7 ``` Note that many `NaN` values appeared. This makes sense because many new combinations did not exist before (eg. there was no `bob` in `London`). Calling `unstack()` will do the reverse, once again creating many `NaN` values. ``` d8 = d7.unstack() d8 ``` If we call `unstack` again, we end up with a `Series` object: ``` d9 = d8.unstack() d9 ``` The `stack()` and `unstack()` methods let you select the `level` to stack/unstack. You can even stack/unstack multiple levels at once: ``` d10 = d9.unstack(level = (0,1)) d10 ``` ## Most methods return modified copies As you may have noticed, the `stack()` and `unstack()` methods do not modify the object they apply to. Instead, they work on a copy and return that copy. This is true of most methods in pandas. ## Accessing rows Let's go back to the `people` `DataFrame`: ``` people ``` The `loc` attribute lets you access rows instead of columns. The result is a `Series` object in which the `DataFrame`'s column names are mapped to row index labels: ``` people.loc["charles"] ``` You can also access rows by integer location using the `iloc` attribute: ``` people.iloc[2] ``` You can also get a slice of rows, and this returns a `DataFrame` object: ``` people.iloc[1:3] ``` Finally, you can pass a boolean array to get the matching rows: ``` people[np.array([True, False, True])] ``` This is most useful when combined with boolean expressions: ``` people[people["birthyear"] < 1990] ``` ## Adding and removing columns You can generally treat `DataFrame` objects like dictionaries of `Series`, so the following work fine: ``` people people["age"] = 2018 - people["birthyear"] # adds a new column "age" people["over 30"] = people["age"] > 30 # adds another column "over 30" birthyears = people.pop("birthyear") del people["children"] people birthyears ``` When you add a new colum, it must have the same number of rows. Missing rows are filled with NaN, and extra rows are ignored: ``` people["pets"] = pd.Series({"bob": 0, "charles": 5, "eugene":1}) # alice is missing, eugene is ignored people ``` When adding a new column, it is added at the end (on the right) by default. You can also insert a column anywhere else using the `insert()` method: ``` people.insert(1, "height", [172, 181, 185]) people ``` ## Assigning new columns You can also create new columns by calling the `assign()` method. Note that this returns a new `DataFrame` object, the original is not modified: ``` people.assign( body_mass_index = people["weight"] / (people["height"] / 100) ** 2, has_pets = people["pets"] > 0 ) ``` Note that you cannot access columns created within the same assignment: ``` try: people.assign( body_mass_index = people["weight"] / (people["height"] / 100) ** 2, overweight = people["body_mass_index"] > 25 ) except KeyError as e: print("Key error:", e) ``` The solution is to split this assignment in two consecutive assignments: ``` d6 = people.assign(body_mass_index = people["weight"] / (people["height"] / 100) ** 2) d6.assign(overweight = d6["body_mass_index"] > 25) ``` Having to create a temporary variable `d6` is not very convenient. You may want to just chain the assigment calls, but it does not work because the `people` object is not actually modified by the first assignment: ``` try: (people .assign(body_mass_index = people["weight"] / (people["height"] / 100) ** 2) .assign(overweight = people["body_mass_index"] > 25) ) except KeyError as e: print("Key error:", e) ``` But fear not, there is a simple solution. You can pass a function to the `assign()` method (typically a `lambda` function), and this function will be called with the `DataFrame` as a parameter: ``` (people .assign(body_mass_index = lambda df: df["weight"] / (df["height"] / 100) ** 2) .assign(overweight = lambda df: df["body_mass_index"] > 25) ) ``` Problem solved! ## Evaluating an expression A great feature supported by pandas is expression evaluation. This relies on the `numexpr` library which must be installed. ``` people.eval("weight / (height/100) ** 2 > 25") ``` Assignment expressions are also supported. Let's set `inplace=True` to directly modify the `DataFrame` rather than getting a modified copy: ``` people.eval("body_mass_index = weight / (height/100) ** 2", inplace=True) people ``` You can use a local or global variable in an expression by prefixing it with `'@'`: ``` overweight_threshold = 30 people.eval("overweight = body_mass_index > @overweight_threshold", inplace=True) people ``` ## Querying a `DataFrame` The `query()` method lets you filter a `DataFrame` based on a query expression: ``` people.query("age > 30 and pets == 0") ``` ## Sorting a `DataFrame` You can sort a `DataFrame` by calling its `sort_index` method. By default it sorts the rows by their index label, in ascending order, but let's reverse the order: ``` people.sort_index(ascending=False) ``` Note that `sort_index` returned a sorted *copy* of the `DataFrame`. To modify `people` directly, we can set the `inplace` argument to `True`. Also, we can sort the columns instead of the rows by setting `axis=1`: ``` people.sort_index(axis=1, inplace=True) people ``` To sort the `DataFrame` by the values instead of the labels, we can use `sort_values` and specify the column to sort by: ``` people.sort_values(by="age", inplace=True) people ``` ## Plotting a `DataFrame` Just like for `Series`, pandas makes it easy to draw nice graphs based on a `DataFrame`. For example, it is trivial to create a line plot from a `DataFrame`'s data by calling its `plot` method: ``` people.plot(kind = "line", x = "body_mass_index", y = ["height", "weight"]) plt.show() ``` You can pass extra arguments supported by matplotlib's functions. For example, we can create scatterplot and pass it a list of sizes using the `s` argument of matplotlib's `scatter()` function: ``` people.plot(kind = "scatter", x = "height", y = "weight", s=[40, 120, 200]) plt.show() ``` Again, there are way too many options to list here: the best option is to scroll through the [Visualization](http://pandas.pydata.org/pandas-docs/stable/visualization.html) page in pandas' documentation, find the plot you are interested in and look at the example code. ## Operations on `DataFrame`s Although `DataFrame`s do not try to mimick NumPy arrays, there are a few similarities. Let's create a `DataFrame` to demonstrate this: ``` grades_array = np.array([[8,8,9],[10,9,9],[4, 8, 2], [9, 10, 10]]) grades = pd.DataFrame(grades_array, columns=["sep", "oct", "nov"], index=["alice","bob","charles","darwin"]) grades ``` You can apply NumPy mathematical functions on a `DataFrame`: the function is applied to all values: ``` np.sqrt(grades) ``` Similarly, adding a single value to a `DataFrame` will add that value to all elements in the `DataFrame`. This is called *broadcasting*: ``` grades + 1 ``` Of course, the same is true for all other binary operations, including arithmetic (`*`,`/`,`**`...) and conditional (`>`, `==`...) operations: ``` grades >= 5 ``` Aggregation operations, such as computing the `max`, the `sum` or the `mean` of a `DataFrame`, apply to each column, and you get back a `Series` object: ``` grades.mean() ``` The `all` method is also an aggregation operation: it checks whether all values are `True` or not. Let's see during which months all students got a grade greater than `5`: ``` (grades > 5).all() ``` Most of these functions take an optional `axis` parameter which lets you specify along which axis of the `DataFrame` you want the operation executed. The default is `axis=0`, meaning that the operation is executed vertically (on each column). You can set `axis=1` to execute the operation horizontally (on each row). For example, let's find out which students had all grades greater than `5`: ``` (grades > 5).all(axis = 1) ``` The `any` method returns `True` if any value is True. Let's see who got at least one grade 10: ``` (grades == 10).any(axis = 1) ``` If you add a `Series` object to a `DataFrame` (or execute any other binary operation), pandas attempts to broadcast the operation to all *rows* in the `DataFrame`. This only works if the `Series` has the same size as the `DataFrame`s rows. For example, let's substract the `mean` of the `DataFrame` (a `Series` object) from the `DataFrame`: ``` grades - grades.mean() # equivalent to: grades - [7.75, 8.75, 7.50] ``` We substracted `7.75` from all September grades, `8.75` from October grades and `7.50` from November grades. It is equivalent to substracting this `DataFrame`: ``` pd.DataFrame([[7.75, 8.75, 7.50]]*4, index=grades.index, columns=grades.columns) ``` If you want to substract the global mean from every grade, here is one way to do it: ``` grades - grades.values.mean() # substracts the global mean (8.00) from all grades ``` ## Automatic alignment Similar to `Series`, when operating on multiple `DataFrame`s, pandas automatically aligns them by row index label, but also by column names. Let's create a `DataFrame` with bonus points for each person from October to December: ``` bonus_array = np.array([[0,np.nan,2],[np.nan,1,0],[0, 1, 0], [3, 3, 0]]) bonus_points = pd.DataFrame(bonus_array, columns=["oct", "nov", "dec"], index=["bob","colin", "darwin", "charles"]) bonus_points grades + bonus_points ``` Looks like the addition worked in some cases but way too many elements are now empty. That's because when aligning the `DataFrame`s, some columns and rows were only present on one side, and thus they were considered missing on the other side (`NaN`). Then adding `NaN` to a number results in `NaN`, hence the result. ## Handling missing data Dealing with missing data is a frequent task when working with real life data. Pandas offers a few tools to handle missing data. Let's try to fix the problem above. For example, we can decide that missing data should result in a zero, instead of `NaN`. We can replace all `NaN` values by a any value using the `fillna()` method: ``` (grades + bonus_points).fillna(0) ``` It's a bit unfair that we're setting grades to zero in September, though. Perhaps we should decide that missing grades are missing grades, but missing bonus points should be replaced by zeros: ``` fixed_bonus_points = bonus_points.fillna(0) fixed_bonus_points.insert(0, "sep", 0) fixed_bonus_points.loc["alice"] = 0 grades + fixed_bonus_points ``` That's much better: although we made up some data, we have not been too unfair. Another way to handle missing data is to interpolate. Let's look at the `bonus_points` `DataFrame` again: ``` bonus_points ``` Now let's call the `interpolate` method. By default, it interpolates vertically (`axis=0`), so let's tell it to interpolate horizontally (`axis=1`). ``` bonus_points.interpolate(axis=1) ``` Bob had 0 bonus points in October, and 2 in December. When we interpolate for November, we get the mean: 1 bonus point. Colin had 1 bonus point in November, but we do not know how many bonus points he had in September, so we cannot interpolate, this is why there is still a missing value in October after interpolation. To fix this, we can set the September bonus points to 0 before interpolation. ``` better_bonus_points = bonus_points.copy() better_bonus_points.insert(0, "sep", 0) better_bonus_points.loc["alice"] = 0 better_bonus_points = better_bonus_points.interpolate(axis=1) better_bonus_points ``` Great, now we have reasonable bonus points everywhere. Let's find out the final grades: ``` grades + better_bonus_points ``` It is slightly annoying that the September column ends up on the right. This is because the `DataFrame`s we are adding do not have the exact same columns (the `grades` `DataFrame` is missing the `"dec"` column), so to make things predictable, pandas orders the final columns alphabetically. To fix this, we can simply add the missing column before adding: ``` grades["dec"] = np.nan final_grades = grades + better_bonus_points final_grades ``` There's not much we can do about December and Colin: it's bad enough that we are making up bonus points, but we can't reasonably make up grades (well I guess some teachers probably do). So let's call the `dropna()` method to get rid of rows that are full of `NaN`s: ``` final_grades_clean = final_grades.dropna(how="all") final_grades_clean ``` Now let's remove columns that are full of `NaN`s by setting the `axis` argument to `1`: ``` final_grades_clean = final_grades_clean.dropna(axis=1, how="all") final_grades_clean ``` ## Aggregating with `groupby` Similar to the SQL language, pandas allows grouping your data into groups to run calculations over each group. First, let's add some extra data about each person so we can group them, and let's go back to the `final_grades` `DataFrame` so we can see how `NaN` values are handled: ``` final_grades["hobby"] = ["Biking", "Dancing", np.nan, "Dancing", "Biking"] final_grades ``` Now let's group data in this `DataFrame` by hobby: ``` grouped_grades = final_grades.groupby("hobby") grouped_grades ``` We are ready to compute the average grade per hobby: ``` grouped_grades.mean() ``` That was easy! Note that the `NaN` values have simply been skipped when computing the means. ## Pivot tables Pandas supports spreadsheet-like [pivot tables](https://en.wikipedia.org/wiki/Pivot_table) that allow quick data summarization. To illustrate this, let's create a simple `DataFrame`: ``` bonus_points more_grades = final_grades_clean.stack().reset_index() more_grades.columns = ["name", "month", "grade"] more_grades["bonus"] = [np.nan, np.nan, np.nan, 0, np.nan, 2, 3, 3, 0, 0, 1, 0] more_grades ``` Now we can call the `pd.pivot_table()` function for this `DataFrame`, asking to group by the `name` column. By default, `pivot_table()` computes the mean of each numeric column: ``` pd.pivot_table(more_grades, index="name") ``` We can change the aggregation function by setting the `aggfunc` argument, and we can also specify the list of columns whose values will be aggregated: ``` pd.pivot_table(more_grades, index="name", values=["grade","bonus"], aggfunc=np.max) ``` We can also specify the `columns` to aggregate over horizontally, and request the grand totals for each row and column by setting `margins=True`: ``` pd.pivot_table(more_grades, index="name", values="grade", columns="month", margins=True) ``` Finally, we can specify multiple index or column names, and pandas will create multi-level indices: ``` pd.pivot_table(more_grades, index=("name", "month"), margins=True) ``` ## Overview functions When dealing with large `DataFrames`, it is useful to get a quick overview of its content. Pandas offers a few functions for this. First, let's create a large `DataFrame` with a mix of numeric values, missing values and text values. Notice how Jupyter displays only the corners of the `DataFrame`: ``` much_data = np.fromfunction(lambda x,y: (x+y*y)%17*11, (10000, 26)) large_df = pd.DataFrame(much_data, columns=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) large_df[large_df % 16 == 0] = np.nan large_df.insert(3,"some_text", "Blabla") large_df ``` The `head()` method returns the top 5 rows: ``` large_df.head() ``` Of course there's also a `tail()` function to view the bottom 5 rows. You can pass the number of rows you want: ``` large_df.tail(n=2) ``` The `info()` method prints out a summary of each columns contents: ``` large_df.info() ``` Finally, the `describe()` method gives a nice overview of the main aggregated values over each column: * `count`: number of non-null (not NaN) values * `mean`: mean of non-null values * `std`: [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of non-null values * `min`: minimum of non-null values * `25%`, `50%`, `75%`: 25th, 50th and 75th [percentile](https://en.wikipedia.org/wiki/Percentile) of non-null values * `max`: maximum of non-null values ``` large_df.describe() ``` ## Saving & loading Pandas can save `DataFrame`s to various backends, including file formats such as CSV, Excel, JSON, HTML and HDF5, or to a SQL database. Let's create a `DataFrame` to demonstrate this: ``` my_df = pd.DataFrame( [["Biking", 68.5, 1985, np.nan], ["Dancing", 83.1, 1984, 3]], columns=["hobby","weight","birthyear","children"], index=["alice", "bob"] ) my_df ``` ## Saving Let's save it to CSV, HTML and JSON: ``` my_df.to_csv("my_df.csv") my_df.to_html("my_df.html") my_df.to_json("my_df.json") ``` Done! Let's take a peek at what was saved: ``` for filename in ("my_df.csv", "my_df.html", "my_df.json"): print("#", filename) with open(filename, "rt") as f: print(f.read()) print() ``` Note that the index is saved as the first column (with no name) in a CSV file, as `<th>` tags in HTML and as keys in JSON. Saving to other formats works very similarly, but some formats require extra libraries to be installed. For example, saving to Excel requires the openpyxl library: ``` try: my_df.to_excel("my_df.xlsx", sheet_name='People') except ImportError as e: print(e) ``` ## Loading Now let's load our CSV file back into a `DataFrame`: ``` my_df_loaded = pd.read_csv("my_df.csv", index_col=0) my_df_loaded ``` As you might guess, there are similar `read_json`, `read_html`, `read_excel` functions as well. We can also read data straight from the Internet. For example, let's load all U.S. cities from [simplemaps.com](http://simplemaps.com/): ``` us_cities = None try: csv_url = "http://simplemaps.com/files/cities.csv" us_cities = pd.read_csv(csv_url, index_col=0) us_cities = us_cities.head() except IOError as e: print(e) us_cities ``` There are more options available, in particular regarding datetime format. Check out the [documentation](http://pandas.pydata.org/pandas-docs/stable/io.html) for more details. ## Combining `DataFrame`s ## SQL-like joins One powerful feature of pandas is it's ability to perform SQL-like joins on `DataFrame`s. Various types of joins are supported: inner joins, left/right outer joins and full joins. To illustrate this, let's start by creating a couple simple `DataFrame`s: ``` city_loc = pd.DataFrame( [ ["CA", "San Francisco", 37.781334, -122.416728], ["NY", "New York", 40.705649, -74.008344], ["FL", "Miami", 25.791100, -80.320733], ["OH", "Cleveland", 41.473508, -81.739791], ["UT", "Salt Lake City", 40.755851, -111.896657] ], columns=["state", "city", "lat", "lng"]) city_loc city_pop = pd.DataFrame( [ [808976, "San Francisco", "California"], [8363710, "New York", "New-York"], [413201, "Miami", "Florida"], [2242193, "Houston", "Texas"] ], index=[3,4,5,6], columns=["population", "city", "state"]) city_pop ``` Now let's join these `DataFrame`s using the `merge()` function: ``` pd.merge(left=city_loc, right=city_pop, on="city") ``` Note that both `DataFrame`s have a column named `state`, so in the result they got renamed to `state_x` and `state_y`. Also, note that Cleveland, Salt Lake City and Houston were dropped because they don't exist in *both* `DataFrame`s. This is the equivalent of a SQL `INNER JOIN`. If you want a `FULL OUTER JOIN`, where no city gets dropped and `NaN` values are added, you must specify `how="outer"`: ``` all_cities = pd.merge(left=city_loc, right=city_pop, on="city", how="outer") all_cities ``` Of course `LEFT OUTER JOIN` is also available by setting `how="left"`: only the cities present in the left `DataFrame` end up in the result. Similarly, with `how="right"` only cities in the right `DataFrame` appear in the result. For example: ``` pd.merge(left=city_loc, right=city_pop, on="city", how="right") ``` If the key to join on is actually in one (or both) `DataFrame`'s index, you must use `left_index=True` and/or `right_index=True`. If the key column names differ, you must use `left_on` and `right_on`. For example: ``` city_pop2 = city_pop.copy() city_pop2.columns = ["population", "name", "state"] pd.merge(left=city_loc, right=city_pop2, left_on="city", right_on="name") ``` ## Concatenation Rather than joining `DataFrame`s, we may just want to concatenate them. That's what `concat()` is for: ``` result_concat = pd.concat([city_loc, city_pop]) result_concat ``` Note that this operation aligned the data horizontally (by columns) but not vertically (by rows). In this example, we end up with multiple rows having the same index (eg. 3). Pandas handles this rather gracefully: ``` result_concat.loc[3] ``` Or you can tell pandas to just ignore the index: ``` pd.concat([city_loc, city_pop], ignore_index=True) ``` Notice that when a column does not exist in a `DataFrame`, it acts as if it was filled with `NaN` values. If we set `join="inner"`, then only columns that exist in *both* `DataFrame`s are returned: ``` pd.concat([city_loc, city_pop], join="inner") ``` You can concatenate `DataFrame`s horizontally instead of vertically by setting `axis=1`: ``` pd.concat([city_loc, city_pop], axis=1) ``` In this case it really does not make much sense because the indices do not align well (eg. Cleveland and San Francisco end up on the same row, because they shared the index label `3`). So let's reindex the `DataFrame`s by city name before concatenating: ``` pd.concat([city_loc.set_index("city"), city_pop.set_index("city")], axis=1) ``` This looks a lot like a `FULL OUTER JOIN`, except that the `state` columns were not renamed to `state_x` and `state_y`, and the `city` column is now the index. The `append()` method is a useful shorthand for concatenating `DataFrame`s vertically: ``` city_loc.append(city_pop) ``` As always in pandas, the `append()` method does *not* actually modify `city_loc`: it works on a copy and returns the modified copy. ## Categories It is quite frequent to have values that represent categories, for example `1` for female and `2` for male, or `"A"` for Good, `"B"` for Average, `"C"` for Bad. These categorical values can be hard to read and cumbersome to handle, but fortunately pandas makes it easy. To illustrate this, let's take the `city_pop` `DataFrame` we created earlier, and add a column that represents a category: ``` city_eco = city_pop.copy() city_eco["eco_code"] = [17, 17, 34, 20] city_eco ``` Right now the `eco_code` column is full of apparently meaningless codes. Let's fix that. First, we will create a new categorical column based on the `eco_code`s: ``` city_eco["economy"] = city_eco["eco_code"].astype('category') city_eco["economy"].cat.categories ``` Now we can give each category a meaningful name: ``` city_eco["economy"].cat.categories = ["Finance", "Energy", "Tourism"] city_eco ``` Note that categorical values are sorted according to their categorical order, *not* their alphabetical order: ``` city_eco.sort_values(by="economy", ascending=False) ``` ## What next? As you probably noticed by now, pandas is quite a large library with *many* features. Although we went through the most important features, there is still a lot to discover. Probably the best way to learn more is to get your hands dirty with some real-life data. It is also a good idea to go through pandas' excellent [documentation](http://pandas.pydata.org/pandas-docs/stable/index.html), in particular the [Cookbook](http://pandas.pydata.org/pandas-docs/stable/cookbook.html).
github_jupyter
# Introduction librairies sklearn, pandas - Pandas : manipuler des fichiers csv (tableaux excel), faire des statistiques descriptives (moyenne variance, mediane,histogramme) - Sklearn : Librairie orientรฉ machine learning. Simplifie les taches rรฉcurentes, telles que sรฉparer les donnรฉes, crรฉer un modรจle, entraรฎner un modรจle. La librairie "pandas" est destinรฉe ร  utiliser des fichiers csv sous python de maniรจre naturelle. Les fichiers csv sont reprรฉsentรฉs par un "DataFrame". C'est un objet python sur lesquels on peut effectuer les opรฉrations les plus courantes (calculer la moyenne d'une colonne, etc.) # Partie 1 # Importer les donnรฉes ``` import pandas import matplotlib.pyplot as plt # A COMPLETER # Importer les donnรฉes contenues dans le fichier housing.csv dans un DataFrame pandas file_housing = 'housing.csv' # Afficher le nom des colonnes ``` Le "Boston data frame" a 506 lignes and 14 colonnes. - medv : valeur moyenne des maison en milliers en millier de dollars. - crim taux de criminalitรฉ par ville - zn proportion de rรฉsidences ( lots > 25,000 sq.ft.) - indus proportion de zone industrielle par ville - chas 1 si une riviรจre passe, 0 sinon - nox nitrogen oxides concentration (pollution). - rm nombre moyen de chambres par habitation - age proportion de maisons occupรฉes construites avant 1940. - dis distance moyenne (pondรฉrรฉe) des 5 centres d'emplois de Boston. - rad indice d'accรฉs au pรฉriph - tax taxe d'habitation pour \$10,000. - ptratio taux de "pupil-teacher" par ville (?). - black 1000(Bk - 0.63)^2 ou Bk est la proportion d'afro-amรฉricain par ville (base de donnรฉe US) - lstat pourcentage de personnes en dessous du seuil de pauvretรฉ (lower status). # Outils de visualisation ## Aperรงu des donnรฉes ``` # A COMPLETER # Afficher les 5 premiรจres lignes du jeu de donnรฉes ``` # Visualisation des donnรฉes : Statistiques descriptives Avec pandas et l'objet "Dataframe", il est facile de visualiser la distribution des variables prรฉsentes dans notre jeu de donnรฉe ``` # A COMPLETER # Afficher un histogramme pour chaque feature ``` ## Selectionner une colonne ``` # A COMPLETER # Mettre la colonne age dans la variable age age = None print(age) ``` ## statistiques sur une colonne ``` # A COMPLETER # Corriger le code ci-dessous max_age=None min_age=None median_age=None print(max_age,min_age,median_age) # Inspecter la colonne rad (que constatez-vous?) #dรฉcrire medv en fonction de rad ``` ## Visualiser l'impact d'une variable sur une autre ``` # A COMPLETER # Faire le scatter plot de crim contre medv # proposer une visualisation pour dรฉcrire medv en fonction de rad ``` A faire : essayer de trouver d'autres variables importantes qui pourraient expliquer medv # Partie 2 # Sรฉparer sous la forme (X,Y) ``` y=df["medv"] # la variable a prรฉdire x=df.drop('medv', axis=1) # enlever la variable ร  prรฉdire des prรฉdicteurs print("la taille de mon jeu de donnรฉe est {}. Je cherche ร  expliquer le prix de vente d'une maison ร  partir de {} variables".format(x.shape[0],x.shape[1])) x=x.fillna(-1) # valeurs manquantes y=y.fillna(-1) # valeurs manquantes ``` # Crรฉation du jeu d'entrainement et du jeu de test Nous devons maintenant dรฉcouper notre jeu d'entrainement. Pour cela, j'utilise la fonction train_test_split fournie par sklearn. Le paramรจtre test_size me permet de choisir la proportion de mon jeu de test. En rรจgle gรฉnรฉral, cette valeur est comprise entre 0.2 et 0.3. ``` from sklearn.model_selection import train_test_split # A COMPLETER X_train,X_test,Y_train,Y_test = (None, None, None, None) ``` # Crรฉation d'un modรจle (regrรฉssion lineaire) Nous allons maintenant essayer d'expliquer la variable y (le prix de la maison) en fonction des variables x. Le modรจle est de la forme : $$y=A*x+b$$ $$ Prix=\beta_{CRIM}*X_{CRIM}+\beta_{ZN}*X_{ZN}+\beta_{INDUS}*X_{INDUS}+...$$ Oรน les coefficients du vecteur A seront ceux qui "expliquent" le mieux les donnรฉes. Par exemple, on pourrait faire l'hypothรจse que la variable "CRIM" (taux de criminalitรฉ de la zone) a un impact nรฉgatif sur le prix des maisons. On peut prรฉvoir un coefficient nรฉgatif devant cette variable. ``` from sklearn.linear_model import LinearRegression # A COMPLETER # Crรฉer un modรจle et l'entraรฎner model=None for i in range(len(df.columns)): print(df.columns[i], model.coef_[i]) ``` -Interprรฉter la valeur de ces coefficients. Sont ils crรฉdibles ? ``` for i in range(len(df.columns)): print("Le coefficient de {} est {}".format(df.columns[i],model.coef_[i])) ``` # Evaluation du modรจle Comment savoir si notre modรจle est bon ou pas ? Il faut un critรจre de comparaison. Par exemple l'รฉcart quadratique moyen pour une regression, le taux de bonnes prรฉdictions pour une classification ``` from sklearn.metrics import mean_squared_error,mean_absolute_error prediction_train=model.predict(X_train) erreur_train=mean_squared_error(Y_train,prediction_train) print(erreur_train) ``` Et sur le jeu d'entrainement ? ``` # A COMPLETER # calculer l'erreur de prรฉdiction sur le jeu de test ``` L'objectif est le suivant : avoir la plus petite erreur possible sur le jeu d'entrainement. ### Interprรฉter l'erreur cette erreur est elle acceptable ? Notre modรจle est il bon ? Nous avons ici considรฉrรฉ l'erreur moyenne au carrรฉ, peut รชtre qu'il faut scorer le modรจle avec une erreur plus comprรฉhensible. ``` erreur_train=mean_absolute_error(Y_test,prediction_test) print(erreur_train) ``` La contrainte est la suivante : avoir une erreur similaire sur le jeu de test (contrรดle d'overfitting) # Visualisation des rรฉsultats ``` import matplotlib.pyplot as plt erreurs=Y_test-prediction_test plt.figure() plt.hist(erreurs, bins=50) plt.show() ``` - Analyser l'histogramme des erreurs ``` # A COMPLETER ```
github_jupyter
<a href="https://colab.research.google.com/github/karaage0703/karaage-ai-book/blob/master/ch02/02_karaage_ai_book_image_classification_grad_cam.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ็”ปๅƒๅˆ†้กž GradCam ็”ปๅƒๅˆ†้กžใ‚’ๅฎŸ่ทตใ™ใ‚‹ใƒŽใƒผใƒˆใƒ–ใƒƒใ‚ฏใงใ™ใ€‚ ## ๆ•™ๅธซใƒ‡ใƒผใ‚ฟใฎใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ ใ‚ธใƒฃใƒณใ‚ฑใƒณใฎๆ‰‹ใฎๅฝขใฎๆ•™ๅธซใƒ‡ใƒผใ‚ฟใ‚’GitHubใ‹ใ‚‰ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰๏ผˆClone๏ผ‰ใ—ใพใ™ใ€‚ 2,3่กŒ็›ฎใฏใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใ—ใŸใƒ‡ใƒผใ‚ฟใ‹ใ‚‰ใ€ไฝฟ็”จใ™ใ‚‹ใƒ‡ใƒผใ‚ฟไปฅๅค–ใฎไธ่ฆใชใƒ•ใ‚กใ‚คใƒซใ‚’ๅ‰Š้™คใ—ใฆใ„ใพใ™ใ€‚ ``` !git clone https://github.com/karaage0703/janken_dataset datasets !rm -rf datasets/.git !rm datasets/LICENSE ``` ใƒ‡ใƒผใ‚ฟใฎไธญ่บซใฎ็ขบ่ช ``` !ls datasets !ls datasets/choki from IPython.display import Image as IPImage from IPython.display import display_jpeg display_jpeg(IPImage('datasets/choki/choki_01.jpg')) ``` ## ๆ•™ๅธซใƒ‡ใƒผใ‚ฟใ‚’่จ“็ทดใƒ‡ใƒผใ‚ฟ๏ผˆTrain Data๏ผ‰ใจใƒ†ใ‚นใƒˆใƒ‡ใƒผใ‚ฟ๏ผˆValidation Data๏ผ‰ใซๅˆ†ๅ‰ฒ ๆ•™ๅธซใƒ‡ใƒผใ‚ฟใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใจใ€ใ‚ฟใƒผใ‚ฒใƒƒใƒˆใจใชใ‚‹ใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช๏ผˆใ“ใฎไธ‹ใซ่จ“็ทดใƒ‡ใƒผใ‚ฟใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใจๆคœ่จผใƒ‡ใƒผใ‚ฟใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใŒ็”Ÿๆˆใ•ใ‚Œใ‚‹๏ผ‰ใ‚’ๆŒ‡ๅฎšใ—ใพใ™ใ€‚ ``` dataset_original_dir = 'datasets' dataset_root_dir = 'target_datasets' ``` ๆ•™ๅธซใƒ‡ใƒผใ‚ฟใ‚’่จ“็ทดใƒ‡ใƒผใ‚ฟใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช(train)ใจๆคœ่จผใƒ‡ใƒผใ‚ฟใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒช๏ผˆval๏ผ‰ใซๅˆ†ๅ‰ฒใ™ใ‚‹ใ‚นใ‚ฏใƒชใƒ—ใƒˆใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใ—ใพใ™ใ€‚ ใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎใƒ—ใƒญใ‚ฐใƒฉใƒ ใซ้–ขใ—ใฆใฏใ€ๆœฌใƒŽใƒผใƒˆใƒ–ใƒƒใ‚ฏใฎไธป้กŒใงใฏ็„กใ„ใฎใงๅ‰ฒๆ„›ใ—ใพใ™ใ€‚่ˆˆๅ‘ณใ‚ใ‚‹ๆ–นใฏไปฅไธ‹ใฎใ‚ขใƒ‰ใƒฌใ‚นใงใ€ใ‚ฝใƒ•ใƒˆใฎไธญ่บซใ‚’็ขบ่ชใ—ใฆไธ‹ใ•ใ„ใ€‚ https://raw.githubusercontent.com/karaage0703/karaage-ai-book/master/util/split_train_val.py ``` !wget https://raw.githubusercontent.com/karaage0703/karaage-ai-book/master/util/split_train_val.py import split_train_val split_train_val.image_dir_train_val_split( dataset_original_dir, dataset_root_dir, train_size=0.67) train_dir = 'target_datasets/train' val_dir = 'target_datasets/val' ``` ## ใƒฉใƒ™ใƒซใƒ•ใ‚กใ‚คใƒซใฎไฝœๆˆ ๅญฆ็ฟ’ใ™ใ‚‹ใƒ•ใ‚กใ‚คใƒซใฎใƒฉใƒ™ใƒซใ‚’ไฝœๆˆใ—ใพใ™ ๅฟ…่ฆใชใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ใ‚คใƒณใƒใƒผใƒˆใ—ใพใ™ ``` import sys import os import shutil ``` ใƒ‡ใƒผใ‚ฟใ‚’ไฟๅญ˜ใ™ใ‚‹ๅ ดๆ‰€ใ‚’ๆŒ‡ๅฎšใ—ใพใ™ ``` backup_dir = './model' ``` ใƒฉใƒ™ใƒซใƒ‡ใƒผใ‚ฟใ‚’ไฝœๆˆใ—ใพใ™๏ผˆๆœ€ๅพŒใซ่กจ็คบใ•ใ‚Œใ‚‹ class numberใŒ็”ปๅƒใฎ็จฎ้กžใฎๆ•ฐใงใ™๏ผ‰ ``` labels = [d for d in os.listdir(dataset_original_dir) \ if os.path.isdir(os.path.join(dataset_original_dir, d))] labels.sort() if os.path.exists(backup_dir): shutil.rmtree(backup_dir) os.makedirs(backup_dir) with open(backup_dir + '/labels.txt','w') as f: for label in labels: f.write(label+"\n") NUM_CLASSES = len(labels) print("class number=" + str(NUM_CLASSES)) ``` ใƒฉใƒ™ใƒซใ‚’็ขบ่ชใ—ใพใ™ใ€‚ใƒฉใƒ™ใƒซๅ๏ผˆchoki, gu, pa๏ผ‰ใŒไธฆใ‚“ใงใ„ใ‚ŒใฐOKใงใ™ ``` !cat ./model/labels.txt ``` ## ๅญฆ็ฟ’ใฎไบ‹ๅ‰ๆบ–ๅ‚™ ### ใƒฉใ‚คใƒ–ใƒฉใƒชใฎใ‚คใƒณใƒใƒผใƒˆ TensorFlow 2.xใฎEager Modeใ‚’OFFใซใ—ใฆใƒขใƒ‡ใƒซใ‚’ๅ†ๅญฆ็ฟ’ใ™ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚Šใพใ™ใ€‚ GradCamใงๅฏ่ฆ–ๅŒ–ใ™ใ‚‹ใŸใ‚ใฎใ‚ฝใƒ•ใƒˆใฎ้ƒฝๅˆใงใ™ใ€‚ ``` from tensorflow.python.framework.ops import disable_eager_execution disable_eager_execution() ``` ๅฟ…่ฆใชใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ใ‚คใƒณใƒใƒผใƒˆใ—ใพใ™ ใ“ใฎNotebookใฏTensorFlowใ€2.x็ณปใงๅ‹•ไฝœใ™ใ‚‹ใฎใงใ€TensorFlow 2.x็ณปใ‚’้ธๆŠžใ—ใฆใ‚คใƒณใƒใƒผใƒˆใ—ใพใ™ใ€‚ ``` %tensorflow_version 2.x import tensorflow as tf print(tf.__version__) ``` ็ถšใ„ใฆใ€ไป–ใซๅฟ…่ฆใชใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ใ‚คใƒณใ‚นใƒˆใƒผใƒซใ—ใพใ™ใ€‚ ``` from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator import numpy as np import matplotlib.pyplot as plt ``` ๅ…ˆใปใฉไฝœๆˆใ—ใŸใƒฉใƒ™ใƒซใƒ•ใ‚กใ‚คใƒซใ‹ใ‚‰ใ€ใƒฉใƒ™ใƒซๆƒ…ๅ ฑใ‚’่ชญใฟ่พผใฟใพใ™ ``` labels = [] with open(backup_dir + '/labels.txt','r') as f: for line in f: labels.append(line.rstrip()) print(labels) NUM_CLASSES = len(labels) ``` ### ๅญฆ็ฟ’ใฎใƒใ‚คใƒ‘ใƒผใƒ‘ใƒฉใƒกใƒผใ‚ฟใฎ่จญๅฎš ๅญฆ็ฟ’ใฎใƒใ‚คใƒ‘ใƒผใƒ‘ใƒฉใƒกใƒผใ‚ฟใฎ่จญๅฎšใ‚’ใ—ใพใ™ ``` # ๅญฆ็ฟ’็އ LEARNING_RATE = 0.001 # ใ‚จใƒใƒƒใ‚ฏ๏ผˆไธ–ไปฃๆ•ฐ๏ผ‰ EPOCHS = 20 # ใƒใƒƒใƒใ‚ตใ‚คใ‚บ BATCH_SIZE = 8 ``` ### ใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆใฎๅ‰ๅ‡ฆ็† ใƒ‡ใƒผใ‚ฟใ‚ปใƒƒใƒˆใฎๅ‰ๅ‡ฆ็†๏ผˆๅค‰ๆ›๏ผ‰ใ‚’ใ—ใพใ™ ``` IMAGE_SIZE = 64 train_data_gen = ImageDataGenerator(rescale=1./255) val_data_gen = ImageDataGenerator(rescale=1./255) train_data = train_data_gen.flow_from_directory( train_dir, target_size=(IMAGE_SIZE, IMAGE_SIZE), color_mode='rgb', batch_size=BATCH_SIZE, class_mode='categorical', shuffle=True) validation_data = val_data_gen.flow_from_directory( val_dir, target_size=(IMAGE_SIZE, IMAGE_SIZE), color_mode='rgb', batch_size=BATCH_SIZE, class_mode='categorical', shuffle=True) ``` ### ๅ‰ๅ‡ฆ็†ใฎ็ขบ่ช ใ€€ใ‚คใƒ†ใƒฌใƒผใ‚ฟใ‚’ไฝฟใ†ใจใ€ใพใจใพใฃใŸใƒ‡ใƒผใ‚ฟใ‚’้ †ใ€…ใซๅ‡ฆ็†ใ™ใ‚‹ใฎใซไพฟๅˆฉใชใฎใงใ€ๅคง้‡ใฎใƒ‡ใƒผใ‚ฟใ‚’ๅ‡ฆ็†ใ™ใ‚‹ใƒ‡ใ‚ฃใƒผใƒ—ใƒฉใƒผใƒ‹ใƒณใ‚ฐใงใฏใ‚ˆใไฝฟใ‚ใ‚Œใพใ™ใ€‚ใ‚คใƒ†ใƒฌใƒผใ‚ฟใซ้–ขใ—ใฆใ‚ˆใ‚Š่ฉณใ—ใ็Ÿฅใ‚ŠใŸใ„ๆ–นใฏใ€Pythonใฎๅ…ฅ้–€ๆ›ธใ‚„Webใงใฎๆƒ…ๅ ฑใ‚’่ชฟในใฆใฟใฆไธ‹ใ•ใ„ใ€‚ ใ“ใ“ใงใฏใ€ใ‚คใƒ†ใƒฌใƒผใ‚ฟใฎไธญ่บซใ‚’็ขบ่ชใ—ใฆใŠใใพใ™ใ€‚ใ‚คใƒ†ใƒฌใƒผใ‚ฟใฎไธญ่บซใ‚’็ขบ่ชใ™ใ‚‹ใซใฏ next้–ขๆ•ฐใ‚’ไฝฟใ†ใฎใŒ็ฐกๅ˜ใงใ™ใ€‚ ``` (image_data,label_data) = train_data.next() print(image_data) print(label_data) print(image_data.shape) print(label_data.shape) import matplotlib.pyplot as plt image_numb = 6 # 3ใฎๅ€ๆ•ฐใ‚’ๆŒ‡ๅฎšใ—ใฆใใ ใ•ใ„ for i in range(0, image_numb): ax = plt.subplot(image_numb // 3, 3, i + 1) plt.tight_layout() ax.set_title(str(i)) plt.imshow(image_data[i]) ``` ## AIใƒขใƒ‡ใƒซไฝœๆˆ ใƒ‹ใƒฅใƒผใƒฉใƒซใƒใƒƒใƒˆใƒฏใƒผใ‚ฏ๏ผˆCNN๏ผ‰ใƒขใƒ‡ใƒซใ‚’ไฝœๆˆใ—ใพใ™ ใ“ใ‚Œใฏใ€KerasใฎMNISTใจๅ‘ผใฐใ‚Œใ‚‹ๆ–‡ๅญ—่ช่ญ˜ใซไฝฟใ‚ใ‚Œใ‚‹ใƒ‹ใƒฅใƒผใƒฉใƒซใƒใƒƒใƒˆใƒฏใƒผใ‚ฏใƒขใƒ‡ใƒซใ‚’ใƒ™ใƒผใ‚นใซใ—ใฆใ„ใพใ™ใ€‚ MNISTใฏใ€0,1ใฎ2ๅ€คใงใ™ใŒใ€RGB็”ปๅƒใซๅฏพๅฟœใงใใ‚‹ใ‚ˆใ†ใซๆ”น้€ ใ—ใฆใ„ใพใ™ใ€‚ๅ…ทไฝ“็š„ใซใฏใ€ๆœ€ๅˆใฎๅฑคใฎๅ…ฅๅŠ›ใ‚ตใ‚คใ‚บใ‚’ `input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)`ใจใ™ใ‚‹ใ“ใจใงๅฏพๅฟœใ—ใฆใ„ใพใ™ใ€‚ https://keras.io/examples/mnist_cnn/ ``` model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))) model.add(Activation('relu')) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(NUM_CLASSES)) model.add(Activation('softmax')) opt = tf.keras.optimizers.Adam(lr=LEARNING_RATE) #opt = tf.keras.optimizers.SGD(lr=LEARNING_RATE) model.compile(opt, loss='categorical_crossentropy', metrics=['accuracy']) ``` ใƒขใƒ‡ใƒซใฎๆฆ‚่ฆใ‚’็ขบ่ชใ—ใพใ™ ``` model.summary() ``` AIใƒขใƒ‡ใƒซใฎๅญฆ็ฟ’ใ‚’่กŒใ„ใพใ™ ``` %%time history = model.fit(train_data, epochs=EPOCHS, validation_data=validation_data, verbose=1) ``` ## ๅญฆ็ฟ’็ตๆžœใฎๅฏ่ฆ–ๅŒ– lossใ‚’็ขบ่ชใ—ใพใ™ใ€‚ไฝŽใ„ใปใฉ่‰ฏใ„ๆ€ง่ƒฝใ‚’็คบใ—ใพใ™ใ€‚ ``` plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Training and validation loss') plt.ylabel('loss') plt.xlim([0.0, EPOCHS]) plt.xlabel('epoch') plt.legend(['loss', 'val_loss'], loc='upper left') plt.show() ``` acc๏ผˆ็ฒพๅบฆ๏ผ‰ใ‚’็ขบ่ชใ—ใพใ™ใ€‚accใŒ่จ“็ทดใƒ‡ใƒผใ‚ฟใงใฎ็ฒพๅบฆใงใ€ใ“ใฎๅ€คใŒ้ซ˜ใ„ใปใฉ่‰ฏใ„ๆ€ง่ƒฝใ‚’ๆ„ๅ‘ณใ—ใพใ™ใ€‚ ไพ‹ใˆใฐ0.5ใ ใจ50%ใฎๆญฃ่งฃ็އใจใ„ใ†ใ“ใจใซใชใ‚Šใพใ™ใ€‚ val_accใจใ„ใ†ใฎใŒ่จ“็ทดใซไฝฟใฃใฆใ„ใชใ„ใƒ†ใ‚นใƒˆใƒ‡ใƒผใ‚ฟใ‚’ไฝฟใฃใฆใฎ็ฒพๅบฆใงใ™ใ€‚ ใ„ใ‚ใ‚†ใ‚‹ใ€ๆœฌๅฝ“ใฎ็ฒพๅบฆใจ่จ€ใ‚ใ‚Œใ‚‹ใ‚‚ใฎใฏใ€val_accใฎๆ–นใจใชใ‚Šใพใ™ใ€‚ ``` plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Training and validation accuracy') plt.xlabel('epoch') plt.ylabel('accuracy') plt.xlim([0.0, EPOCHS]) plt.ylim([0.0, 1.0]) plt.legend(['acc', 'val_acc'], loc='lower right') plt.show() ``` ## ๅญฆ็ฟ’ใ•ใ›ใŸใƒขใƒ‡ใƒซใ‚’ไฝฟใฃใŸๆŽจๅฎš ๅญฆ็ฟ’ใ•ใ›ใŸใƒขใƒ‡ใƒซใ‚’ไฝฟใฃใฆใ€็”ปๅƒใฎๆŽจๅฎšใ‚’่กŒใ„ใพใ™ ``` # Get the ordered list of class names: import PIL.Image as Image class_names = validation_data.class_indices.items() class_names = np.array([key.title() for key, value in class_names]) validation_data.reset() validation_data.shuffle = True validation_data.batch_size = BATCH_SIZE # Retrieve the first batch from the validation data for validation_image_batch, validation_label_batch in validation_data: break validation_id = np.argmax(validation_label_batch, axis=-1) validation_label = class_names[validation_id] predicted_batch = model.predict(validation_image_batch) # Returns the indices of the maximum values along a given axis predicted_id = np.argmax(predicted_batch, axis=-1) # Return the maximum values along a given axis predicted_score = np.max(predicted_batch, axis=-1) predicted_label_batch = class_names[predicted_id] plt.figure(figsize=(16, 9)) plt.subplots_adjust(hspace=0.5) # Display the classification results for the first 30 images for n in range(min(validation_image_batch.shape[0], 30)): plt.subplot(6, 5, n + 1) # Convert the range from -1 to 1 to the range from 0 to 1 plt.imshow(np.array(validation_image_batch[n]*255,np.int32)) color = 'green' if predicted_id[n] == validation_id[n] else 'red' predicted_label = predicted_label_batch[n].title() plt.title(predicted_label + ' ({:.2f}, {})'.format( predicted_score[n], validation_label[n]), color=color) plt.axis('off') _ = plt.suptitle('Model predictions (green: correct, red: incorrect)') from sklearn.metrics import confusion_matrix import seaborn as sns validation_data.reset() validation_data.shuffle = False validation_data.batch_size = 1 # Retrieve the first batch from the validation data for validation_image_batch, validation_label_batch in validation_data: break predicted = model.predict_generator(validation_data, steps=validation_data.n) predicted_classes = np.argmax(predicted, axis=-1) # Apply normalization # https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html cm = confusion_matrix(validation_data.classes, predicted_classes) cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize=(12, 9)) # https://seaborn.pydata.org/generated/seaborn.heatmap.html # https://matplotlib.org/users/colormaps.html sns.heatmap(cm, annot=True, square=True, cmap=plt.cm.Blues, xticklabels=validation_data.class_indices, yticklabels=validation_data.class_indices) plt.title("Confusion Matrix") plt.ylabel('True label') plt.xlabel('Predicted label') plt.xlim([0.0, 3.0]) plt.ylim([0.0, 3.0]) plt.show() ``` ## Grad-CAMใงใฎๅฏ่ฆ–ๅŒ– Grad-CAMใงใฎๅฏ่ฆ–ๅŒ–ใ‚’ๅฎŸๆ–ฝใ—ใพใ™ใ€‚ ใƒขใƒ‡ใƒซใ‚’็ขบ่ชใ—ใพใ™ใ€‚ ``` model.summary() ``` Grad-CAMใซๅฟ…่ฆใชใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ใ‚คใƒณใƒใƒผใƒˆใ—ใพใ™ใ€‚ ``` from tensorflow.keras.layers import Lambda import tensorflow.keras.backend as K from tensorflow.keras.models import Model import cv2 ``` Grad-CAMใฎ่จˆ็ฎ—้ƒจๅˆ†ใ‚’ๅฎš็พฉใ—ใพใ™ใ€‚ ``` def target_category_loss(x, category_index, nb_classes): return tf.multiply(x, K.one_hot([category_index], nb_classes)) def target_category_loss_output_shape(input_shape): return input_shape def normalize(x): # utility function to normalize a tensor by its L2 norm return x / (K.sqrt(K.mean(K.square(x))) + 1e-5) def grad_cam(input_model, image, category_index, layer_name): nb_classes = NUM_CLASSES target_layer = lambda x: target_category_loss(x, category_index, nb_classes) x = input_model.layers[-1].output x = Lambda(target_layer, output_shape=target_category_loss_output_shape)(x) model = Model(input_model.layers[0].input, x) loss = K.sum(model.layers[-1].output) conv_output = model.get_layer(layer_name).output grads = normalize(K.gradients(loss, conv_output)[0]) gradient_function = K.function([model.layers[0].input], [conv_output, grads]) output, grads_val = gradient_function([image]) output, grads_val = output[0, :], grads_val[0, :, :, :] weights = np.mean(grads_val, axis = (0, 1)) cam = np.ones(output.shape[0 : 2], dtype = np.float32) for i, w in enumerate(weights): cam += w * output[:, :, i] cam = cv2.resize(cam, (IMAGE_SIZE, IMAGE_SIZE)) cam = (cam - cam.mean()) / cam.std() cam = np.maximum(cam, 0) heatmap = cam / np.max(cam) #Return to BGR from the preprocessed image image = image[0, :] * 255 cam = cv2.applyColorMap(np.uint8(255*heatmap), cv2.COLORMAP_JET) cam = np.float32(cam) + np.float32(image) cam = 255 * cam / np.max(cam) return np.uint8(cam), heatmap def cv2pil(image): ''' OpenCVๅž‹ -> PILๅž‹ ''' new_image = image.copy() if new_image.ndim == 2: # ใƒขใƒŽใ‚ฏใƒญ pass elif new_image.shape[2] == 3: # ใ‚ซใƒฉใƒผ new_image = new_image[:, :, ::-1] elif new_image.shape[2] == 4: # ้€้Ž new_image = new_image[:, :, [2, 1, 0, 3]] new_image = Image.fromarray(new_image) return new_image def get_grad_cam(input, layer_name): preprocessed_input = [] preprocessed_input.append(input) preprocessed_input = np.asarray(preprocessed_input) predictions = model.predict(preprocessed_input) predicted_class = np.argmax(predictions) cam, heatmap = grad_cam(model, preprocessed_input, predicted_class, layer_name=layer_name) cam = cv2pil(cam) return cam ``` ๅฏ่ฆ–ๅŒ–ใ™ใ‚‹ใƒฌใ‚คใƒคใƒผใ‚’้ธๆŠžใ—ใพใ™ใ€‚ ``` LAYER_NAME = 'conv2d' ``` Grad-CAMใ‚’ไฝฟใฃใŸๅฏ่ฆ–ๅŒ–ใ‚’ใ—ใพใ™ใ€‚ ``` # Get the ordered list of class names: import PIL.Image as Image class_names = validation_data.class_indices.items() class_names = np.array([key.title() for key, value in class_names]) validation_data.reset() validation_data.shuffle = False validation_data.batch_size = BATCH_SIZE for validation_image_batch, validation_label_batch in validation_data: break plt.figure(figsize=(9, 9)) plt.subplots_adjust(hspace=0.5) # Display the classification results for the first 30 images for n in range(min(validation_image_batch.shape[0], 30)): plt.subplot(6, 3, n + 1) plt.imshow(get_grad_cam(validation_image_batch[n], layer_name=LAYER_NAME)) plt.axis('off') ``` ๅˆฅใฎๅฑคใฎๅฏ่ฆ–ๅŒ–ใ‚’่กŒใ„ใพใ™ใ€‚ ``` LAYER_NAME = 'conv2d_1' # Get the ordered list of class names: import PIL.Image as Image class_names = validation_data.class_indices.items() class_names = np.array([key.title() for key, value in class_names]) validation_data.reset() validation_data.shuffle = False validation_data.batch_size = BATCH_SIZE for validation_image_batch, validation_label_batch in validation_data: break plt.figure(figsize=(9, 9)) plt.subplots_adjust(hspace=0.5) # Display the classification results for the first 30 images for n in range(min(validation_image_batch.shape[0], 30)): plt.subplot(6, 3, n + 1) plt.imshow(get_grad_cam(validation_image_batch[n], layer_name=LAYER_NAME)) plt.axis('off') ``` ## ๅญฆ็ฟ’ใƒขใƒ‡ใƒซใฎไฟๅญ˜ใจ่ชญใฟ่พผใฟ Google ColaboratoryไธŠใฎใƒ•ใ‚กใ‚คใƒซใฏใ€่‡ชๅ‹•็š„ใซๆถˆใˆใฆใ—ใพใ†ใฎใงใƒ•ใ‚กใ‚คใƒซใ‚’ไฟๅญ˜ใ—ใพใ™ ``` save_model_path = os.path.join(backup_dir, 'my_model.h5') model.save(save_model_path) from google.colab import drive drive.mount('/content/drive') !ls model !cp './model/my_model.h5' '/content/drive/My Drive' !cp './model/labels.txt' '/content/drive/My Drive' ``` ใ‚ใจใฏใ€Google Drive็ตŒ็”ฑใงใƒ•ใ‚กใ‚คใƒซใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใ—ใพใ™ใ€‚ ## ใพใจใ‚ ใ“ใ“ใพใงใงใ€ๅญฆ็ฟ’ใ‹ใ‚‰ๆŽจ่ซ–ใฏๅฎŒไบ†ใงใ™ใ€‚ ็™บๅฑ•ใจใ—ใฆใ€ไปฅไธ‹ใ‚’ๅฎŸๆ–ฝใ—ใฆใฉใ†ใชใ‚‹ใ‹็ขบ่ชใ—ใฆใฟใพใ—ใ‚‡ใ†ใ€‚ - ใƒใ‚คใƒ‘ใƒผใƒ‘ใƒฉใƒกใƒผใ‚ฟใ‚’ๅค‰ๆ›ดใ—ใฆๅญฆ็ฟ’ใฎๅค‰ๆ›ดๅบฆๅˆใ„ใ‚’็ขบ่ช - ๆ•™ๅธซใƒ‡ใƒผใ‚ฟใ‚’ใ‚ธใƒฃใƒณใ‚ฑใƒณไปฅๅค–ใฎใ‚‚ใฎใซใ—ใฆใฟใ‚‹ ## ๅ‚่€ƒใƒชใƒณใ‚ฏ ไปฅไธ‹ใฏๅคšใใ‚’ๅ‚่€ƒใซใ—ใŸๆƒ…ๅ ฑใงใ™ใ€‚ CNNๆง‹้€  - http://aidiary.hatenablog.com/entry/20161127/1480240182 ใƒ‡ใƒผใ‚ฟNๅข—ใ— - https://github.com/bohemian916/deeplearning_tool/blob/master/increase_picture.py GradCam - https://github.com/shinmura0/Python-study-group/blob/master/Text3.ipynb GradCam Confusion Matrix - https://colab.research.google.com/drive/1mirG8BSoB3k87mh-qyY3-8-ZXj0XB6h6 TensorFlow 2.xๅฏพๅฟœ - http://tensorflow.classcat.com/2019/11/04/tf20-tutorials-images-classification/ ไนฑๆ•ฐ(Seed)ๅ›บๅฎš - https://scrapbox.io/nwtgck/Tensorflow+Keras%E3%81%A7%E5%86%8D%E7%8F%BE%E6%80%A7%E3%81%AE%E3%81%82%E3%82%8B%E4%B9%B1%E6%95%B0%E3%82%92%E7%94%9F%E6%88%90%E3%81%99%E3%82%8B_-_%E3%82%B7%E3%83%BC%E3%83%89%E5%9B%BA%E5%AE%9A - https://qiita.com/okotaku/items/8d682a11d8f2370684c9 ไปฅไธ‹ใฏใ€ใƒ’ใƒณใƒˆใจใชใฃใŸๆƒ…ๅ ฑ - http://aidiary.hatenablog.com/entry/20161212/1481549365 - https://qiita.com/yampy/items/706d44417c433e68db0d - https://qiita.com/haru1977/items/17833e508fe07c004119 - http://hatakazu.hatenablog.com/entry/2017/06/08/045953 - https://qiita.com/Mco7777/items/2b76aba1bae35f2623ea ``` ```
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--> < [Hierarchical Indexing](03.05-Hierarchical-Indexing.ipynb) | [Contents](Index.ipynb) | [Combining Datasets: Merge and Join](03.07-Merge-and-Join.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.06-Concat-And-Append.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> # Combining Datasets: Concat and Append ``` %qtconsole --style solarized-dark ``` Some of the most interesting studies of data come from combining different data sources. These operations can involve anything from very straightforward concatenation of two different datasets, to more complicated database-style joins and merges that correctly handle any overlaps between the datasets. ``Series`` and ``DataFrame``s are built with this type of operation in mind, and Pandas includes functions and methods that make this sort of data wrangling fast and straightforward. Here we'll take a look at simple concatenation of ``Series`` and ``DataFrame``s with the ``pd.concat`` function; later we'll dive into more sophisticated in-memory merges and joins implemented in Pandas. We begin with the standard imports: ``` import pandas as pd import numpy as np ``` For convenience, we'll define this function which creates a ``DataFrame`` of a particular form that will be useful below: ``` def make_df(cols, ind): """Quickly make a DataFrame""" data = {c: [str(c) + str(i) for i in ind] for c in cols} return pd.DataFrame(data, ind) # example DataFrame make_df('ABC', range(3)) ``` In addition, we'll create a quick class that allows us to display multiple ``DataFrame``s side by side. The code makes use of the special ``_repr_html_`` method, which IPython uses to implement its rich object display: ``` class display(object): """Display HTML representation of multiple objects""" template = """<div style="float: left; padding: 10px;"> <p style='font-family:"Courier New", Courier, monospace'>{0}</p>{1} </div>""" def __init__(self, *args): self.args = args def _repr_html_(self): return '\n'.join(self.template.format(a, eval(a)._repr_html_()) for a in self.args) def __repr__(self): return '\n\n'.join(a + '\n' + repr(eval(a)) for a in self.args) ``` The use of this will become clearer as we continue our discussion in the following section. ## Recall: Concatenation of NumPy Arrays Concatenation of ``Series`` and ``DataFrame`` objects is very similar to concatenation of Numpy arrays, which can be done via the ``np.concatenate`` function as discussed in [The Basics of NumPy Arrays](02.02-The-Basics-Of-NumPy-Arrays.ipynb). Recall that with it, you can combine the contents of two or more arrays into a single array: ``` x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] np.concatenate([x, y, z]) ``` The first argument is a list or tuple of arrays to concatenate. Additionally, it takes an ``axis`` keyword that allows you to specify the axis along which the result will be concatenated: ``` x = [[1, 2], [3, 4]] np.concatenate([x, x], axis=1) ``` ## Simple Concatenation with ``pd.concat`` Pandas has a function, ``pd.concat()``, which has a similar syntax to ``np.concatenate`` but contains a number of options that we'll discuss momentarily: ```python # Signature in Pandas v0.18 pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True) ``` ``pd.concat()`` can be used for a simple concatenation of ``Series`` or ``DataFrame`` objects, just as ``np.concatenate()`` can be used for simple concatenations of arrays: ``` ser1 = pd.Series(['A', 'B', 'C'], index=[1, 2, 3]) ser2 = pd.Series(['D', 'E', 'F'], index=[4, 5, 6]) pd.concat([ser1, ser2]) ``` It also works to concatenate higher-dimensional objects, such as ``DataFrame``s: ``` df1 = make_df('AB', [1, 2]) df2 = make_df('AB', [3, 4]) display('df1', 'df2', 'pd.concat([df1, df2])') ``` By default, the concatenation takes place row-wise within the ``DataFrame`` (i.e., ``axis=0``). Like ``np.concatenate``, ``pd.concat`` allows specification of an axis along which concatenation will take place. Consider the following example: ``` df3 = make_df('AB', [0, 1]) df4 = make_df('CD', [0, 1]) display('df3', 'df4', "pd.concat([df3, df4], axis='col')") ``` We could have equivalently specified ``axis=1``; here we've used the more intuitive ``axis='col'``. ### Duplicate indices One important difference between ``np.concatenate`` and ``pd.concat`` is that Pandas concatenation *preserves indices*, even if the result will have duplicate indices! Consider this simple example: ``` x = make_df('AB', [0, 1]) y = make_df('AB', [2, 3]) y.index = x.index # make duplicate indices! display('x', 'y', 'pd.concat([x, y])') ``` Notice the repeated indices in the result. While this is valid within ``DataFrame``s, the outcome is often undesirable. ``pd.concat()`` gives us a few ways to handle it. #### Catching the repeats as an error If you'd like to simply verify that the indices in the result of ``pd.concat()`` do not overlap, you can specify the ``verify_integrity`` flag. With this set to True, the concatenation will raise an exception if there are duplicate indices. Here is an example, where for clarity we'll catch and print the error message: ``` try: pd.concat([x, y], verify_integrity=True) except ValueError as e: print("ValueError:", e) ``` #### Ignoring the index Sometimes the index itself does not matter, and you would prefer it to simply be ignored. This option can be specified using the ``ignore_index`` flag. With this set to true, the concatenation will create a new integer index for the resulting ``Series``: ``` display('x', 'y', 'pd.concat([x, y], ignore_index=True)') ``` #### Adding MultiIndex keys Another option is to use the ``keys`` option to specify a label for the data sources; the result will be a hierarchically indexed series containing the data: ``` display('x', 'y', "pd.concat([x, y], keys=['x', 'y'])") ``` The result is a multiply indexed ``DataFrame``, and we can use the tools discussed in [Hierarchical Indexing](03.05-Hierarchical-Indexing.ipynb) to transform this data into the representation we're interested in. ### Concatenation with joins In the simple examples we just looked at, we were mainly concatenating ``DataFrame``s with shared column names. In practice, data from different sources might have different sets of column names, and ``pd.concat`` offers several options in this case. Consider the concatenation of the following two ``DataFrame``s, which have some (but not all!) columns in common: ``` df5 = make_df('ABC', [1, 2]) df6 = make_df('BCD', [3, 4]) display('df5', 'df6', 'pd.concat([df5, df6])') ``` By default, the entries for which no data is available are filled with NA values. To change this, we can specify one of several options for the ``join`` and ``join_axes`` parameters of the concatenate function. By default, the join is a union of the input columns (``join='outer'``), but we can change this to an intersection of the columns using ``join='inner'``: ``` display('df5', 'df6', "pd.concat([df5, df6], join='inner')") ``` Another option is to directly specify the index of the remaininig colums using the ``join_axes`` argument, which takes a list of index objects. Here we'll specify that the returned columns should be the same as those of the first input: ``` display('df5', 'df6', "pd.concat([df5, df6], join_axes=[df5.columns])") ``` The combination of options of the ``pd.concat`` function allows a wide range of possible behaviors when joining two datasets; keep these in mind as you use these tools for your own data. ### The ``append()`` method Because direct array concatenation is so common, ``Series`` and ``DataFrame`` objects have an ``append`` method that can accomplish the same thing in fewer keystrokes. For example, rather than calling ``pd.concat([df1, df2])``, you can simply call ``df1.append(df2)``: ``` display('df1', 'df2', 'df1.append(df2)') ``` Keep in mind that unlike the ``append()`` and ``extend()`` methods of Python lists, the ``append()`` method in Pandas does not modify the original objectโ€“instead it creates a new object with the combined data. It also is not a very efficient method, because it involves creation of a new index *and* data buffer. Thus, if you plan to do multiple ``append`` operations, it is generally better to build a list of ``DataFrame``s and pass them all at once to the ``concat()`` function. In the next section, we'll look at another more powerful approach to combining data from multiple sources, the database-style merges/joins implemented in ``pd.merge``. For more information on ``concat()``, ``append()``, and related functionality, see the ["Merge, Join, and Concatenate" section](http://pandas.pydata.org/pandas-docs/stable/merging.html) of the Pandas documentation. <!--NAVIGATION--> < [Hierarchical Indexing](03.05-Hierarchical-Indexing.ipynb) | [Contents](Index.ipynb) | [Combining Datasets: Merge and Join](03.07-Merge-and-Join.ipynb) > <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/03.06-Concat-And-Append.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
#### New to Plotly? Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/). <br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/#start-plotting-online). <br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started! #### Version Check Plotly's python package is updated frequently. Run `pip install plotly --upgrade` to use the latest version. ``` import plotly plotly.__version__ ``` #### Simple Quiver Plot With Points ``` import plotly.plotly as py import plotly.tools as tls from plotly import figure_factory as ff import numpy as np import matplotlib.pyplot as plt x=[-.7, .75] y=[0, 0] plt.scatter(x,y, marker='o', color="r") plt.title('Quiver Plot with Points') fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25)) z = x*np.exp(-x**2 - y**2) v, u = np.gradient(z, .2, .2) quiver_fig = ff.create_quiver(x, y, u, v, scale=.25, arrow_scale=.4, name='quiver', line=dict(width=1)) quiver_fig.add_trace(plotly_fig['data'][0]) py.iplot(quiver_fig, filename='mpl-quiver-with-points') ``` #### Quiver Plot With Custom Arrow Size And Color ``` import plotly.plotly as py import plotly.tools as tls from plotly import figure_factory as ff import numpy as np import matplotlib.pyplot as plt x=[-.7, .75] y=[0, 0] plt.scatter(x,y, marker='o', color="r") plt.title('Quiver Plot with Custom Arrow Size') fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25)) z = x*np.exp(-x**2 - y**2) v, u = np.gradient(z, .2, .2) quiver_fig = ff.create_quiver(x, y, u, v, scale=.25, arrow_scale=.8, # Sets arrow scale name='quiver', angle=np.pi/4, line=dict(width=1)) quiver_fig.add_trace(plotly_fig['data'][0]) quiver_fig['data'][0]['line']['color'] = 'rgb(0,255,0)' py.iplot(quiver_fig, filename='mpl-quiver-with-custom-arrow-size') ``` #### Reference See https://plot.ly/python/reference/ for more information and chart attribute options! ``` from IPython.display import display, HTML display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />')) display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">')) ! pip install git+https://github.com/plotly/publisher.git --upgrade import publisher publisher.publish( 'quiver_plots.ipynb', 'matplotlib/quiver-plots/', 'Quiver Plots', 'How to make a quiver plot in Matplotlib Python. A quiver plot displays velocity vectors as arrows.', title = 'Quiver Plots | Plotly', has_thumbnail='true', thumbnail='thumbnail/quiver-plot.jpg', language='matplotlib', page_type='example_index', display_as='scientific', order=22, ipynb='~notebook_demo/249') ```
github_jupyter
# Convolutional Variational Autoencoder - MNIST Slightly modified from variational_autoencoder_deconv.py in the Keras examples folder: **https://github.com/fchollet/keras/blob/master/examples/variational_autoencoder_deconv.py** ``` WEIGHTS_FILEPATH = 'mnist_vae.hdf5' MODEL_ARCH_FILEPATH = 'mnist_vae.json' import numpy as np np.random.seed(1337) # for reproducibility import matplotlib.pyplot as plt %matplotlib inline from keras.layers import Input, Dense, Lambda, Flatten, Reshape from keras.layers import Conv2D, Conv2DTranspose from keras.models import Model from keras import backend as K from keras import objectives from keras.datasets import mnist from keras.callbacks import EarlyStopping, ModelCheckpoint # input image dimensions img_rows, img_cols, img_chns = 28, 28, 1 # number of convolutional filters to use filters = 64 # convolution kernel size num_conv = 3 batch_size = 200 original_img_size = (img_rows, img_cols, img_chns) latent_dim = 2 intermediate_dim = 128 epsilon_std = 0.01 x = Input(batch_shape=(batch_size,) + original_img_size) conv_1 = Conv2D(img_chns, kernel_size=(2,2), padding='same', activation='relu')(x) conv_2 = Conv2D(filters, kernel_size=(2,2), strides=(2,2), padding='same', activation='relu')(conv_1) conv_3 = Conv2D(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu')(conv_2) conv_4 = Conv2D(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu')(conv_3) flat = Flatten()(conv_4) hidden = Dense(intermediate_dim, activation='relu')(flat) z_mean = Dense(latent_dim)(hidden) z_log_var = Dense(latent_dim)(hidden) def sampling(args): z_mean, z_log_var = args epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0., stddev=epsilon_std) return z_mean + K.exp(z_log_var) * epsilon # note that "output_shape" isn't necessary with the TensorFlow backend # so you could write `Lambda(sampling)([z_mean, z_log_var])` z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var]) # we instantiate these layers separately so as to reuse them later decoder_hid = Dense(intermediate_dim, activation='relu') decoder_upsample = Dense(filters * 14 * 14, activation='relu') decoder_reshape = Reshape((14, 14, filters)) decoder_deconv_1 = Conv2DTranspose(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu') decoder_deconv_2 = Conv2DTranspose(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu') decoder_deconv_3_upsamp = Conv2DTranspose(filters, kernel_size=(2,2), strides=(2,2), padding='valid', activation='relu') decoder_mean_squash = Conv2D(img_chns, kernel_size=(2,2), padding='same', activation='sigmoid') hid_decoded = decoder_hid(z) up_decoded = decoder_upsample(hid_decoded) reshape_decoded = decoder_reshape(up_decoded) deconv_1_decoded = decoder_deconv_1(reshape_decoded) deconv_2_decoded = decoder_deconv_2(deconv_1_decoded) x_decoded_relu = decoder_deconv_3_upsamp(deconv_2_decoded) x_decoded_mean_squash = decoder_mean_squash(x_decoded_relu) def vae_loss(x, x_decoded_mean): # NOTE: binary_crossentropy expects a batch_size by dim # for x and x_decoded_mean, so we MUST flatten these! x = K.flatten(x) x_decoded_mean = K.flatten(x_decoded_mean) xent_loss = img_rows * img_cols * objectives.binary_crossentropy(x, x_decoded_mean) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) return xent_loss + kl_loss vae = Model(x, x_decoded_mean_squash) vae.compile(optimizer='adam', loss=vae_loss) vae.summary() epochs = 100 # train the VAE on MNIST digits (x_train, _), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') / 255. x_train = x_train.reshape((x_train.shape[0],) + original_img_size) x_test = x_test.astype('float32') / 255. x_test = x_test.reshape((x_test.shape[0],) + original_img_size) print('x_train.shape:', x_train.shape) # Early stopping early_stopping = EarlyStopping(monitor='val_loss', verbose=1, patience=5) vae.fit(x_train, x_train, validation_data=(x_test, x_test), shuffle=True, epochs=epochs, batch_size=batch_size, verbose=2, callbacks=[early_stopping]) # build a model to project inputs on the latent space encoder = Model(x, z_mean) # display a 2D plot of the digit classes in the latent space x_test_encoded = encoder.predict(x_test, batch_size=batch_size) plt.figure(figsize=(10,10)) plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test) plt.colorbar() plt.show() ``` **Decoder generator** To make the decoder generator serializable, we will redefine new layers and transfer weights over, rather than sharing the layers. Sharing layers will create new nodes, some with different output shapes, which causes problems for serialization. Here we also set batch_size to 1 ``` batch_size = 1 _hid_decoded = Dense(intermediate_dim, activation='relu') _up_decoded = Dense(filters * 14 * 14, activation='relu') _reshape_decoded = Reshape((14, 14, filters)) _deconv_1_decoded = Conv2DTranspose(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu') _deconv_2_decoded = Conv2DTranspose(filters, kernel_size=num_conv, strides=(1,1), padding='same', activation='relu') _x_decoded_relu = Conv2DTranspose(filters, kernel_size=(2,2), strides=(2,2), padding='valid', activation='relu') _x_decoded_mean_squash = Conv2D(img_chns, kernel_size=(2,2), padding='same', activation='sigmoid') decoder_input = Input(shape=(latent_dim,)) layer1 = _hid_decoded(decoder_input) layer2 = _up_decoded(layer1) layer3 = _reshape_decoded(layer2) layer4 = _deconv_1_decoded(layer3) layer5 = _deconv_2_decoded(layer4) layer6 = _x_decoded_relu(layer5) layer7 = _x_decoded_mean_squash(layer6) generator = Model(decoder_input, layer7) _hid_decoded.set_weights(decoder_hid.get_weights()) _up_decoded.set_weights(decoder_upsample.get_weights()) _deconv_1_decoded.set_weights(decoder_deconv_1.get_weights()) _deconv_2_decoded.set_weights(decoder_deconv_2.get_weights()) _x_decoded_relu.set_weights(decoder_deconv_3_upsamp.get_weights()) _x_decoded_mean_squash.set_weights(decoder_mean_squash.get_weights()) # display a 2D manifold of the digits n = 15 # figure with 15x15 digits digit_size = 28 figure = np.zeros((digit_size * n, digit_size * n)) # we will sample n points within [-1, 1] standard deviations grid_x = np.linspace(-1, 1, n) grid_y = np.linspace(-1, 1, n) for i, yi in enumerate(grid_x): for j, xi in enumerate(grid_y): z_sample = np.array([[xi, yi]]) z_sample = np.tile(z_sample, batch_size).reshape(batch_size, 2) x_decoded = generator.predict(z_sample, batch_size=batch_size) digit = x_decoded[0].reshape(digit_size, digit_size) figure[i * digit_size: (i + 1) * digit_size, j * digit_size: (j + 1) * digit_size] = digit plt.figure(figsize=(10,10)) plt.imshow(figure) plt.show() generator.save_weights(WEIGHTS_FILEPATH) with open(MODEL_ARCH_FILEPATH, 'w') as f: f.write(generator.to_json()) ```
github_jupyter
# ACTIVE REINFORCEMENT LEARNING This notebook mainly focuses on active reinforce learning algorithms. For a general introduction to reinforcement learning and passive algorithms, please refer to the notebook of **[Passive Reinforcement Learning](./Passive%20Reinforcement%20Learning.ipynb)**. Unlike Passive Reinforcement Learning in Active Reinforcement Learning, we are not bound by a policy pi and we need to select our actions. In other words, the agent needs to learn an optimal policy. The fundamental tradeoff the agent needs to face is that of exploration vs. exploitation. ## QLearning Agent The QLearningAgent class in the rl module implements the Agent Program described in **Fig 21.8** of the AIMA Book. In Q-Learning the agent learns an action-value function Q which gives the utility of taking a given action in a particular state. Q-Learning does not require a transition model and hence is a model-free method. Let us look into the source before we see some usage examples. ``` %psource QLearningAgent ``` The Agent Program can be obtained by creating the instance of the class by passing the appropriate parameters. Because of the __ call __ method the object that is created behaves like a callable and returns an appropriate action as most Agent Programs do. To instantiate the object we need a `mdp` object similar to the `PassiveTDAgent`. Let us use the same `GridMDP` object we used above. **Figure 17.1 (sequential_decision_environment)** is similar to **Figure 21.1** but has some discounting parameter as **gamma = 0.9**. The enviroment also implements an exploration function **f** which returns fixed **Rplus** until agent has visited state, action **Ne** number of times. The method **actions_in_state** returns actions possible in given state. It is useful when applying max and argmax operations. Let us create our object now. We also use the **same alpha** as given in the footnote of the book on **page 769**: $\alpha(n)=60/(59+n)$ We use **Rplus = 2** and **Ne = 5** as defined in the book. The pseudocode can be referred from **Fig 21.7** in the book. ``` import os, sys sys.path = [os.path.abspath("../../")] + sys.path from rl4e import * from mdp import sequential_decision_environment, value_iteration q_agent = QLearningAgent(sequential_decision_environment, Ne=5, Rplus=2, alpha=lambda n: 60./(59+n)) ``` Now to try out the q_agent we make use of the **run_single_trial** function in rl.py (which was also used above). Let us use **200** iterations. ``` for i in range(200): run_single_trial(q_agent,sequential_decision_environment) ``` Now let us see the Q Values. The keys are state-action pairs. Where different actions correspond according to: north = (0, 1) south = (0,-1) west = (-1, 0) east = (1, 0) ``` q_agent.Q ``` The Utility U of each state is related to Q by the following equation. $$U (s) = max_a Q(s, a)$$ Let us convert the Q Values above into U estimates. ``` U = defaultdict(lambda: -1000.) # Very Large Negative Value for Comparison see below. for state_action, value in q_agent.Q.items(): state, action = state_action if U[state] < value: U[state] = value ``` Now we can output the estimated utility values at each state: ``` U ``` Let us finally compare these estimates to value_iteration results. ``` print(value_iteration(sequential_decision_environment)) ```
github_jupyter
# Crossentropy method This notebook will teach you to solve reinforcement learning problems with crossentropy method. ``` import gym import numpy as np, pandas as pd env = gym.make("Taxi-v2") env.reset() env.render() n_states = env.observation_space.n n_actions = env.action_space.n print("n_states=%i, n_actions=%i"%(n_states, n_actions)) ``` # Create stochastic policy This time our policy should be a probability distribution. ```policy[s,a] = P(take action a | in state s)``` Since we still use integer state and action representations, you can use a 2-dimensional array to represent the policy. Please initialize policy __uniformly__, that is, probabililities of all actions should be equal. ``` policy = np.ones((n_states, n_actions)) / n_actions assert type(policy) in (np.ndarray,np.matrix) assert np.allclose(policy,1./n_actions) assert np.allclose(np.sum(policy,axis=1), 1) ``` # Play the game Just like before, but we also record all states and actions we took. ``` def generate_session(policy,t_max=10**4): """ Play game until end or for t_max ticks. :param policy: an array of shape [n_states,n_actions] with action probabilities :returns: list of states, list of actions and sum of rewards """ states,actions = [],[] total_reward = 0. s = env.reset() for t in range(t_max): a = np.random.choice(len(policy[s]), p=policy[s]) new_s, r, done, info = env.step(a) #Record state, action and add up reward to states,actions and total_reward accordingly. states.append(s) actions.append(a) total_reward += r s = new_s if done: break return states, actions, total_reward s,a,r = generate_session(policy) assert type(s) == type(a) == list assert len(s) == len(a) assert type(r) in [float,np.float] #let's see the initial reward distribution import matplotlib.pyplot as plt %matplotlib inline sample_rewards = [generate_session(policy,t_max=1000)[-1] for _ in range(200)] plt.hist(sample_rewards,bins=20); plt.vlines([np.percentile(sample_rewards, 50)], [0], [100], label="50'th percentile", color='green') plt.vlines([np.percentile(sample_rewards, 90)], [0], [100], label="90'th percentile", color='red') plt.legend() ``` ### Crossentropy method steps (2pts) ``` def select_elites(states_batch,actions_batch,rewards_batch,percentile=50): """ Select states and actions from games that have rewards >= percentile :param states_batch: list of lists of states, states_batch[session_i][t] :param actions_batch: list of lists of actions, actions_batch[session_i][t] :param rewards_batch: list of rewards, rewards_batch[session_i][t] :returns: elite_states,elite_actions, both 1D lists of states and respective actions from elite sessions Please return elite states and actions in their original order [i.e. sorted by session number and timestep within session] If you're confused, see examples below. Please don't assume that states are integers (they'll get different later). """ reward_threshold = np.percentile(rewards_batch, percentile) elite_states = [s for i in range(len(states_batch)) if rewards_batch[i] >= reward_threshold for s in states_batch[i]] elite_actions = [a for i in range(len(actions_batch)) if rewards_batch[i] >= reward_threshold for a in actions_batch[i]] return elite_states,elite_actions states_batch = [ [1,2,3], #game1 [4,2,0,2], #game2 [3,1] #game3 ] actions_batch = [ [0,2,4], #game1 [3,2,0,1], #game2 [3,3] #game3 ] rewards_batch = [ 3, #game1 4, #game2 5, #game3 ] test_result_0 = select_elites(states_batch, actions_batch, rewards_batch, percentile=0) test_result_40 = select_elites(states_batch, actions_batch, rewards_batch, percentile=30) test_result_90 = select_elites(states_batch, actions_batch, rewards_batch, percentile=90) test_result_100 = select_elites(states_batch, actions_batch, rewards_batch, percentile=100) assert np.all(test_result_0[0] == [1, 2, 3, 4, 2, 0, 2, 3, 1]) \ and np.all(test_result_0[1] == [0, 2, 4, 3, 2, 0, 1, 3, 3]),\ "For percentile 0 you should return all states and actions in chronological order" assert np.all(test_result_40[0] == [4, 2, 0, 2, 3, 1]) and \ np.all(test_result_40[1] ==[3, 2, 0, 1, 3, 3]),\ "For percentile 30 you should only select states/actions from two first" assert np.all(test_result_90[0] == [3,1]) and \ np.all(test_result_90[1] == [3,3]),\ "For percentile 90 you should only select states/actions from one game" assert np.all(test_result_100[0] == [3,1]) and\ np.all(test_result_100[1] == [3,3]),\ "Please make sure you use >=, not >. Also double-check how you compute percentile." print("Ok!") from collections import defaultdict def update_policy(elite_states,elite_actions): """ Given old policy and a list of elite states/actions from select_elites, return new updated policy where each action probability is proportional to policy[s_i,a_i] ~ #[occurences of si and ai in elite states/actions] Don't forget to normalize policy to get valid probabilities and handle 0/0 case. In case you never visited a state, set probabilities for all actions to 1./n_actions :param elite_states: 1D list of states from elite sessions :param elite_actions: 1D list of actions from elite sessions """ new_policy = np.zeros([n_states,n_actions]) #Don't forget to set 1/n_actions for all actions in unvisited states. visited_states = set(elite_states) counts = defaultdict(lambda: [0]*n_actions) for state, action in zip(elite_states, elite_actions): counts[state][action] += 1 for state in range(n_states): if state in visited_states: new_policy[state] = [count / sum(counts[state]) for count in counts[state]] else: new_policy[state] = [1 / n_actions] * n_actions return new_policy elite_states, elite_actions = ([1, 2, 3, 4, 2, 0, 2, 3, 1], [0, 2, 4, 3, 2, 0, 1, 3, 3]) new_policy = update_policy(elite_states,elite_actions) assert np.isfinite(new_policy).all(), "Your new policy contains NaNs or +-inf. Make sure you don't divide by zero." assert np.all(new_policy>=0), "Your new policy can't have negative action probabilities" assert np.allclose(new_policy.sum(axis=-1),1), "Your new policy should be a valid probability distribution over actions" reference_answer = np.array([ [ 1. , 0. , 0. , 0. , 0. ], [ 0.5 , 0. , 0. , 0.5 , 0. ], [ 0. , 0.33333333, 0.66666667, 0. , 0. ], [ 0. , 0. , 0. , 0.5 , 0.5 ]]) assert np.allclose(new_policy[:4,:5],reference_answer) print("Ok!") ``` # Training loop Generate sessions, select N best and fit to those. ``` from IPython.display import clear_output def show_progress(batch_rewards, log, percentile, reward_range=[-990,+10]): """ A convenience function that displays training progress. No cool math here, just charts. """ mean_reward, threshold = np.mean(batch_rewards), np.percentile(batch_rewards, percentile) log.append([mean_reward,threshold]) clear_output(True) print("mean reward = %.3f, threshold=%.3f"%(mean_reward, threshold)) plt.figure(figsize=[8,4]) plt.subplot(1,2,1) plt.plot(list(zip(*log))[0], label='Mean rewards') plt.plot(list(zip(*log))[1], label='Reward thresholds') plt.legend() plt.grid() plt.subplot(1,2,2) plt.hist(batch_rewards,range=reward_range); plt.vlines([np.percentile(batch_rewards, percentile)], [0], [100], label="percentile", color='red') plt.legend() plt.grid() plt.show() #reset policy just in case policy = np.ones([n_states, n_actions]) / n_actions n_sessions = 250 #sample this many sessions percentile = 25 #take this percent of session with highest rewards learning_rate = 0.5 #add this thing to all counts for stability log = [] for i in range(100): %time sessions = [generate_session(policy) for _ in range(n_sessions)] batch_states,batch_actions,batch_rewards = zip(*sessions) elite_states, elite_actions = select_elites(batch_states, batch_actions, batch_rewards, percentile) new_policy = update_policy(elite_states, elite_actions) policy = learning_rate * new_policy + (1-learning_rate) * policy #display results on chart show_progress(batch_rewards, log, percentile) ``` ### Reflecting on results You may have noticed that the taxi problem quickly converges from <-1000 to a near-optimal score and then descends back into -50/-100. This is in part because the environment has some innate randomness. Namely, the starting points of passenger/driver change from episode to episode. In case CEM failed to learn how to win from one distinct starting point, it will siply discard it because no sessions from that starting point will make it into the "elites". To mitigate that problem, you can either reduce the threshold for elite sessions (duct tape way) or change the way you evaluate strategy (theoretically correct way). You can first sample an action for every possible state and then evaluate this choice of actions by running _several_ games and averaging rewards. ### Submit to coursera ``` from submit import submit_taxi submit_taxi(generate_session, policy, '', '') ```
github_jupyter
## Lesson 1: Hello Futures The Getting Started with Futures Tutorial will walk you through the process of researching a quantitative strategy using futures, implementing that strategy in an algorithm, and backtesting it on Quantopian. It covers many of the basics of the Quantopian API, and is designed for those who are new to the platform. Each lesson focuses on a different part of the API and by the end, we will work up to a simple pairs trading algorithm. If you are unfamiliar with Futures trading, check out the Introduction to Futures Contracts lecture from our [Lecture Series](https://quanto-playground.herokuapp.com/lectures). ### What is a Trading Algorithm? On Quantopian, a trading algorithm is a Python program that defines a specific set of instructions on how to analyze, order, and manage assets. Most trading algorithms make desicions based on mathematical or statistical hypotheses that are derived by conducting research on historical data. ### Coming Up With a Strategy The first step to writing a trading algorithm is to find an economic relationship on which we can base our strategy. To do this, we can use Research to inspect and analyze pricing and volume data for 72 different US futures going as far back as 2002. Research is an IPython Notebook environment that allows us to run python code in units called 'cells'. The code below gets pricing and volume data for the Light Sweet Crude Oil contract with delivery in January 2016 and plots it. To run it, click on the grey box and press Shift + Enter to run the cell. ``` # Click somewhere in this box and press Shift + Enter to run the code. from quantopian.research.experimental import history # Create a reference to the Light Sweet Crude Oil contract # with delivery in January 2016 clf16 = symbols('CLF16') # Query historical pricing and volume data for # the contract from October 21st, 2015 to December 21st, 2015 clf16_data = history( clf16, fields=['price', 'volume'], frequency='daily', start='2015-10-21', end='2015-12-21' ) # Plot the data clf16_data.plot(subplots=True); ``` Research is the perfect tool to test a hypothesis, so let's come up with an idea to test. **Strategy:** If a pair of commodities exist on the same supply chain, we expect the spread between the prices of their futures to remain consistent. As the spread increases or decreases, we can trade on the expectation that it will revert to the steady state. In the next few lessons we will learn how to use Research to test our hypothesis. If we find our hypothesis to be valid (spoiler alert: we will), we can use it as a starting point for implementing and backetsting an algorithm in the Interactive Development Environment (IDE).
github_jupyter
``` import pandas as pd import numpy as np from telegram_notifier import send_message as telegram_bot_sendtext import torch print(f"Torch Version: {torch.__version__}") import transformers print(f"transformers (Adapter) Version: {transformers.__version__}") from transformers import BertTokenizer import numpy as np model_name = "bert-base-cased" tokenizer = BertTokenizer.from_pretrained(model_name) def encode_batch(batch): """Encodes a batch of input data using the model tokenizer.""" return tokenizer(batch["text"], max_length=80, truncation=True, padding="max_length") from ner_dataset import get_trainset_data_loader all_tags, trainset, trainloader = get_trainset_data_loader(tokenizer, BATCH_SIZE=128) from transformers import BertConfig, BertModelWithHeads config = BertConfig.from_pretrained( model_name, num_labels=len(all_tags), label2id = trainset.label_map, id2label = trainset.id2label ) ``` name = model.load_adapter("./save_adapters/ALL_tag_0730") model.add_tagging_head( name, num_labels=len(trainset.label_map.keys()), overwrite_ok=True ) model.train_adapter(name) ``` from telegram_notifier import send_message as telegram_bot_sendtext device_id = 0 device = torch.device(f"cuda:{device_id}" if torch.cuda.is_available() else "cpu") all_tags = ['Float','TemporalUnit','I-gpe','CountryCode','CurrencyCode','Timezone','CryptoCurrencyCode','Month','Party','B-tim','I-art','Time','B-per','B-gpe','B-geo','O','Location','Event','I-nat','Race','B-org','I-geo','I-tim','I-eve','SpecialTerm','B-art','US_States','B-eve','I-org','B-nat','Object','I-per','Integer'] for index, tag in enumerate(all_tags): if index % 2 == device_id: print(f"\nSkip {tag}.\n") continue model = BertModelWithHeads.from_pretrained( model_name, config=config, ) try: model.add_adapter(tag) model.add_tagging_head( tag, num_labels=1 ) except: pass model.train_adapter(tag) model = model.to(device) no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": 1e-5, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] optimizer = torch.optim.AdamW(params=optimizer_grouped_parameters, lr=1e-4) for epoch in range(4): print(f"\n{tag}: epoch {epoch}") for i, data in enumerate(trainloader): tokens_tensors, segments_tensors, \ masks_tensors, labels = [t.to(device) for t in data] outputs = model(input_ids = tokens_tensors, attention_mask=masks_tensors, token_type_ids=segments_tensors) logits = outputs[0] current_label = labels.view(-1, labels.shape[-1])[:, trainset.label_map[tag]] current_label = current_label.view(-1) active_logits = logits.view(-1, logits.shape[-1])[masks_tensors.view(-1) == 1] active_labels = current_label[masks_tensors.view(-1)== 1] actual = current_label[masks_tensors.view(-1)== 1].float().view(-1,1) """ actual = torch.ones(active_logits.shape, device = device) actual[:, 0] = (active_labels == 0).long() actual[:, 1] = (active_labels == 1).long()""" loss_fct = torch.nn.BCEWithLogitsLoss() loss = loss_fct(active_logits, actual) loss.backward() optimizer.step() optimizer.zero_grad() if i % 100 == 0: print(f"\tLoss: {loss}") telegram_bot_sendtext(f"\n{tag}: epoch {epoch}, loss = {loss}") filename = f"{tag}_epoch_{epoch}_0801_bert" model.save_adapter(f"./save_adapters/{filename}", model.active_adapters[0]) model.save_head(f"./save_heads/{filename}", model.active_head) filename = f"{tag}_0731" model.save_adapter(f"./save_adapters/{filename}", model.active_adapters[0]) model.save_head(f"./save_heads/{filename}", model.active_head) label_id_mapping = trainset.label_map id_label_mapping = dict() for key in label_id_mapping.keys(): id_label_mapping[label_id_mapping[key]] = key def test_model(model, sentence, device = "cpu"): tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) logits = outputs[0] _, pred_labels = torch.max(logits, 2) out_labels = [] for row in pred_labels: result = list(map(lambda x: id_label_mapping[int(x)], row)) out_labels.append(result) #return tokenizer.tokenize(sentence), out_labels[0], logits return tokenizer.tokenize(sentence), out_labels[0][1:-1], logits[:, 1:-1] sentence = "Dan will be deemed to have completed its delivery obligations before 2021-7-5 if in Niall's opinion, the Jeep Car satisfies the Acceptance Criteria, and Niall notifies Dan in writing that it is accepting the Jeep Car." tokenized_sentence = torch.tensor([tokenizer.encode(sentence)]) pos = torch.tensor([[0] * len(tokenized_sentence)]) tags = torch.tensor([[1] * len(tokenized_sentence)]) model = model.to(device) outputs = model(input_ids=tokenized_sentence.to(device), token_type_ids=pos.to(device), attention_mask=tags.to(device)) for i, text in enumerate(tokenizer.tokenize(sentence)): print(f"{text}: {outputs[0].view(-1)[i]}") sentence = "Dan Will be deemed to have completed its delivery obligations before 2021-7-5 if in Niall's opinion, the Jeep Car satisfies the Acceptance Criteria, and Niall notifies Dan in writing that it is accepting the Jeep Car." sen, pred, logits = test_model(model, sentence, device = 'cpu') a = tokenizer.tokenize(sentence)[1] np.array(sen) np.array(pred) from __future__ import print_function from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets def interact_word(i): print(i) print(sen[i]) target = out[i] for i in range(len(target)): print(f"{i} {id_label_mapping[i].ljust(6)} \t: {target[i]:.5f}") out = logits[0] interact(lambda x: interact_word(x), x=widgets.IntSlider(min=0, max=len(sen)-1, step=1, value=0)) print("OK") ```
github_jupyter
# Travelling Salesman Problem <em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em> ## Overview One of the most famous NP-hard problems in combinatorial optimization, the travelling salesman problem (TSP) considers 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 exactly once and returns to the origin city?" This question can also be formulated in the language of graph theory. Given a weighted undirected complete graph $G = (V,E)$, where each vertex $i \in V$ corresponds to city $i$ and the weight $w_{i,j}$ of each edge $(i,j,w_{i,j}) \in E$ represents the distance between cities $i$ and $j$, the TSP is to find the shortest Hamiltonian cycle in $G$, where a Hamiltonian cycle is a closed loop on a graph in which every vertex is visited exactly once. Note that because $G$ is an undirected graph, weights are symmetric, i.e., $w_{i,j} = w_{j,i}$. ## Encoding the TSP To transform the TSP into a problem applicable for parameterized quantum circuits, we need to encode the TSP into a Hamiltonian. We realize the encoding by first constructing an integer programming problem. Suppose there are $n=|V|$ vertices in graph $G$. Then for each vertex $i \in V$, we define $n$ binary variables $x_{i,t}$, where $t \in [0,n-1]$, such that $$ x_{i, t}= \begin{cases} 1, & \text {if in the resulting Hamiltonian cycle, vertex } i \text { is visited at time } t\\ 0, & \text{otherwise} \end{cases}. \tag{1} $$ As there are $n$ vertices, we have $n^2$ variables in total, whose value we denote by a bit string $x=x_{1,1}x_{1,2}\dots x_{n,n}$. Assume for now that the bit string $x$ represents a Hamiltonian cycle. Then for each edge $(i,j,w_{i,j}) \in E$, we will have $x_{i,t} = x_{j,t+1}=1$, i.e., $x_{i,t}\cdot x_{j,t+1}=1$, if and only if the Hamiltonian cycle visits vertex $i$ at time $t$ and vertex $j$ at time $t+1$; otherwise, $x_{i,t}\cdot x_{j,t+1}$ will be $0$. Therefore the length of a Hamiltonian cycle is $$ D(x) = \sum_{i,j} w_{i,j} \sum_{t} x_{i,t} x_{j,t+1}. \tag{2} $$ For $x$ to represent a valid Hamiltonian cycle, the following constraint needs to be met: $$ \sum_t x_{i,t} = 1 \quad \forall i \in [0,n-1] \quad \text{ and } \quad \sum_i x_{i,t} = 1 \quad \forall t \in [0,n-1], \tag{3} $$ where the first equation guarantees that each vertex is only visited once and the second guarantees that only one vertex is visited at each time $t$. Then the cost function under the constraint can be formulated below, with $A$ being the penalty parameter set to ensure that the constraint is satisfied: $$ C(x) = D(x)+ A\left( \sum_{i} \left(1-\sum_t x_{i,t}\right)^2 + \sum_{t} \left(1-\sum_i x_{i,t}\right)^2 \right). \tag{4} $$ Note that as we would like to minimize the length $D(x)$ while ensuring $x$ represents a valid Hamiltonian cycle, we had better set $A$ large, at least larger than the largest weight of edges. We now need to transform the cost function $C(x)$ into a Hamiltonian to realize the encoding of the TSP. Each variable $x_{i,j}$ has two possible values, $0$ and $1$, corresponding to quantum states $|0\rangle$ and $|1\rangle$. **Note that every variable corresponds to a qubit and so $n^2$ qubits are needed for solving the TSP.** Similar as in the Max-Cut problem, we consider the Pauli $Z$ operator as it has two eigenstates, $|0\rangle$ and $|1\rangle$. Their corresponding eigenvalues are 1 and -1, respectively. Now we would like to consider the mapping $$ x_{i,t} \mapsto \frac{I-Z_{i,t}}{2}, \tag{5} $$ where $Z_{i,t} = I \otimes I \otimes \ldots \otimes Z \otimes \ldots \otimes I$ with $Z$ operates on the qubit at position $(i,t)$. Under this mapping, if a qubit $(i,t)$ is in state $|1\rangle$, then $x_{i,t}|1\rangle = \frac{I-Z_{i,t}}{2} |1\rangle = 1 |1\rangle$, which means vertex $i$ is visited at time $t$. Also, for a qubit $(i,t)$ in state $|0\rangle$, $x_{i,t} |0\rangle= \frac{I-Z_{i,t}}{2} |0\rangle = 0|0\rangle$. Thus using the above mapping, we can transform the cost function $C(x)$ into a Hamiltonian $H_C$ for the system of $n^2$ qubits and realize the quantumization of the TSP. Then the ground state of $H_C$ is the optimal solution to the TSP. In the following section, we will show how to use a parametrized quantum circuit to find the ground state, i.e., the eigenvector with the smallest eigenvalue. ## Paddle Quantum Implementation To investigate the TSP using Paddle Quantum, there are some required packages to import, which are shown below. The ``networkx`` package is the tool to handle graphs. ``` # Import related modules from Paddle Quantum and PaddlePaddle import paddle from paddle_quantum.circuit import UAnsatz from paddle_quantum.QAOA.tsp import tsp_hamiltonian from paddle_quantum.QAOA.tsp import solve_tsp_brute_force # Import additional packages needed from numpy import pi as PI import matplotlib.pyplot as plt import networkx as nx import random ``` Next, we generate a weighted complete graph $G$ with four vertices. For the convenience of computation, the vertices here are labeled starting from $0$. ``` # n is the number of vertices in the graph G n = 4 E = [(0, 1, 3), (0, 2, 2), (0, 3, 10), (1, 2, 6), (1, 3, 2), (2, 3, 6)] G = nx.Graph() G.add_weighted_edges_from(E) # Print out the generated graph G pos = nx.spring_layout(G) options = { "with_labels": True, "font_weight": "bold", "font_color": "white", "node_size": 2000, "width": 2 } nx.draw_networkx(G, pos, **options) nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=nx.get_edge_attributes(G,'weight')) ax = plt.gca() ax.margins(0.20) plt.axis("off") plt.show() ``` ### Encoding Hamiltonian In Paddle Quantum, a Hamiltonian can be input in the form of ``list``. Here we construct the Hamiltonian $H_C$ of Eq. (4) with the replacement in Eq. (5). To save the number of qubits needed, we observe the following fact: it is clear that vertex $n-1$ must always be included in the Hamiltonian cycle, and without loss of generality, we can set $x_{n-1,t} = \delta_{n-1,t}$ for all $t$ and $x_{i,n-1} = \delta_{i,n-1}$ for all $i$. **This just means that the overall ordering of the cycle is chosen so that vertex $n-1$ comes last.** This reduces the number of qubits to $(n-1)^2$. We adopt this slight modification of the TSP Hamiltonian in our implementation. ``` # Construct the Hamiltonian H_C in the form of list A = 20 # Penalty parameter H_C_list = tsp_hamiltonian(G, A, n) ``` ### Calculating the loss function In the [Max-Cut tutorial](./MAXCUT_EN.ipynb), we use a circuit given by QAOA to find the ground state, but we can also use other circuits to solve combinatorial optimization problems. For the TSP, we adopt a parametrized quantum circuit constructed by $U_3(\vec{\theta})$ and $\text{CNOT}$ gates, which we call the [`complex entangled layer`](https://qml.baidu.com/api/paddle_quantum.circuit.uansatz.html). After running the quantum circuit, we ontain the output circuit $|\vec{\theta}\rangle$. From the output state of the circuit we can calculate the objective function, and also the loss function of the TSP: $$ L(\vec{\theta}) = \langle\vec{\theta}|H_C|\vec{\theta}\rangle. \tag{6} $$ We then use a classical optimization algorithm to minimize this function and find the optimal parameters $\vec{\theta}^*$. The following code shows a complete network built with Paddle Quantum and PaddlePaddle. ``` class Net(paddle.nn.Layer): def __init__(self, g, p, H_ls, dtype="float64",): super(Net, self).__init__() self.p = p self.theta = self.create_parameter(shape=[self.p, (len(g.nodes) - 1) ** 2, 3], default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2 * PI), dtype=dtype, is_bias=False) self.H_ls = H_ls self.num_qubits = (len(g) - 1) ** 2 def forward(self): # Define a circuit with complex entangled layers cir = UAnsatz(self.num_qubits) cir.complex_entangled_layer(self.theta, self.p) # Run the quantum circuit cir.run_state_vector() # Calculate the loss function loss = cir.expecval(self.H_ls) return loss, cir ``` ### Training the quantum neural network After defining the quantum neural network, we use gradient descent method to update the parameters to minimize the expectation value in Eq. (6). ``` p = 2 # Number of layers in the quantum circuit ITR = 120 # Number of training iterations LR = 0.5 # Learning rate of the optimization method based on gradient descent SEED = 1000 # Set a global RNG seed ``` Here, we optimize the network defined above in PaddlePaddle. ``` # Fix paddle random seed paddle.seed(SEED) net = Net(G, p, H_C_list) # Use Adam optimizer opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters()) # Gradient descent iteration for itr in range(1, ITR + 1): # Run the network defined above loss, cir = net() # Calculate the gradient and optimize loss.backward() opt.minimize(loss) opt.clear_grad() if itr % 10 == 0: print("iter:", itr, " loss:", "%.4f"% loss.numpy()) ``` Note that ideally the training network will find the shortest Hamiltonian cycle, and the final loss above would correspond to the total weights of the optimal cycle, i.e. the distance of the optimal path for the salesman. If not, then one should adjust parameters of the parameterized quantum circuits above for better training performance. ### Decoding the quantum solution After obtaining the minimum value of the loss function and the corresponding set of parameters $\vec{\theta}^*$, our task has not been completed. In order to obtain an approximate solution to the TSP, it is necessary to decode the solution to the classical optimization problem from the quantum state $|\vec{\theta}^*\rangle$ output by the circuit. Physically, to decode a quantum state, we need to measure it and then calculate the probability distribution of the measurement results, where a measurement result is a bit string that represents an answer for the TSP: $$ p(z) = |\langle z|\vec{\theta}^*\rangle|^2. \tag{7} $$ Usually, the greater the probability of a certain bit string, the greater the probability that it corresponds to an optimal solution of the TSP. Paddle Quantum provides a function to read the probability distribution of the measurement results of the state output by the quantum circuit: ``` # Repeat the simulated measurement of the circuit output state 1024 times prob_measure = cir.measure(shots=1024) reduced_salesman_walk = max(prob_measure, key=prob_measure.get) print("The reduced bit string form of the walk found:", reduced_salesman_walk) ``` As we have slightly modified the TSP Hamiltonian to reduce the number of qubits used, the bit string found above has lost the information for our fixed vertex $n-1$ and the status of other vertices at time $n-1$. So we need to extend the found bit string to include these information. We need to add a $0$ after every $(n-1)$ bits to represent $x_{i,n-1} = 0$ for $i \in [0, n-2]$. Then at last, we need to add the bit string representation for vertex $n-1$, i.e. '00...01' with $n-1$ 0s to represent $x_{n-1,t} = 0$ for all $t \in [0,n-2]$. After measurement, we have found the bit string with the highest probability of occurrence, the optimal walk in the form of the bit string. Each qubit contains the information of $x_{i,t}$ defined in Eq. (1). The following code maps the bit string back to the classic solution in the form of `dictionary`, where the `key` represents the vertex labeling and the `value` represents its order, i.e. when it is visited. Also, we have compared it with the solution found by the brute-force algorithm, to verify the correctness of the quantum algorithm. ``` # Optimal walk found by parameterized quantum circuit str_by_vertex = [reduced_salesman_walk[i:i + n - 1] for i in range(0, len(reduced_salesman_walk) + 1, n - 1)] salesman_walk = '0'.join(str_by_vertex) + '0' * (n - 1) + '1' solution = {i:t for i in range(n) for t in range(n) if salesman_walk[i * n + t] == '1'} distance = sum([G[u][v]["weight"] if solution[u] == (solution[v] + 1) % n or solution[v] == (solution[u] + 1) % n else 0 for (u, v) in G.edges]) print("The walk found by parameterized quantum circuit:", solution, "with distance", distance) # Optimal walk found by brute-force algorithm for comparison salesman_walk_brute_force, distance_brute_force = solve_tsp_brute_force(G) solution_brute_force = {i:salesman_walk_brute_force.index(i) for i in range(n)} print("The walk found by the brute-force algorithm:", solution_brute_force, "with distance", distance_brute_force) ``` Here, we draw the corresponding optimal walk in the form of graph representation suggested to the salesman: * The first number in the vertex represents the city number. * The second number in the vertex represents the order the salesman visits the corresponding city. * The red edges represent the found optimal route for the salesman. ``` label_dict = {i: str(i) + ", " + str(t) for i, t in solution.items()} edge_color = ["red" if solution[u] == (solution[v] + 1) % n or solution[v] == (solution[u] + 1) % n else "black" for (u, v) in G.edges] label_dict_bf = {i: str(i) + ", " + str(t) for i, t in solution_brute_force.items()} edge_color_bf = ["red" if solution_brute_force[u] == (solution_brute_force[v] + 1) % n or solution_brute_force[v] == (solution_brute_force[u] + 1) % n else "black" for (u, v) in G.edges] # Draw the walk corresponding to the dictionary presented above on the graph fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for i, a in enumerate(ax): a.axis('off') a.margins(0.20) nx.draw(G, pos=pos, labels=label_dict, edge_color=edge_color, ax=ax[0], **options) nx.drawing.nx_pylab.draw_networkx_edge_labels(G, pos=pos, ax=ax[0], edge_labels=nx.get_edge_attributes(G, 'weight')) nx.draw(G, pos=pos, labels=label_dict_bf, edge_color=edge_color_bf, ax=ax[1], **options) nx.drawing.nx_pylab.draw_networkx_edge_labels(G, pos=pos, ax=ax[1], edge_labels=nx.get_edge_attributes(G, 'weight')) plt.axis("off") plt.show() ``` The left graph given above shows a solution found by the parameterized quantum circuit, while the right graph given above shows a solution found by the brute-force algorithm. It can be seen that even if the order of the vertices are different, the routes are essentially the same, which verifies the correctness of using parameterized quantum circuit to solve the TSP. ## Applications The TSP naturally applies in many transportation and logistics applications, for example, the problem of arranging school bus routes. The school bus application provides the motivation for Merrill Flood, a pioneer in the field of management science, to study TSP research in the 1940s. More recent applications involve food delivery route management [1] and power delivery for cable firms [2]. Other than those transportation applications, TSP also has wide usefulness in other management problems like scheduling of a machine to drill holes in a circuit board [3], reconstructing an unknown fragment of DNA [4] and scheduling optimal route in construction management [5]. Some consulting companies like [Nexus](https://nexustech.com.ph/company/newsletter/article/Finding-the-shortest-path-Optimizing-food-trips) have utilized this to provide management service. The TSP, as one of the most famous optimization problems, also provides a platform for the study of general methods in solving combinatorial problem. This is usually the first several problems that researchers give a try for experiments of new algorithms. More applications, formulations and solution approaches can be found in [6]. _______ ## References [1] Brรคysy, Olli, et al. "An optimization approach for communal home meal delivery service: A case study." [Journal of Computational and Applied Mathematics 232.1 (2009): 46-53.](https://www.sciencedirect.com/science/article/pii/S0377042708005438) [2] Sloane, Thomas H., Frank Mann, and H. Kaveh. "Powering the last mile: an alternative to powering FITL." [Proceedings of Power and Energy Systems in Converging Markets. IEEE, 1997.](https://ieeexplore.ieee.org/document/646046) [3] Onwubolu, Godfrey C. "Optimizing CNC drilling machine operations: traveling salesman problem-differential evolution approach." [New optimization techniques in engineering. Springer, Berlin, Heidelberg, 2004. 537-565.](https://link.springer.com/chapter/10.1007/978-3-540-39930-8_22) [4] Caserta, Marco, and Stefan VoรŸ. "A hybrid algorithm for the DNA sequencing problem." [Discrete Applied Mathematics 163 (2014): 87-99.](https://www.sciencedirect.com/science/article/pii/S0166218X12003253) [5] Klanลกek, Uroลก. "Using the TSP solution for optimal route scheduling in construction management." [Organization, technology & management in construction: an international journal 3.1 (2011): 243-249.](https://www.semanticscholar.org/paper/Using-the-TSP-Solution-for-Optimal-Route-Scheduling-Klansek/3d809f185c03a8e776ac07473c76e9d77654c389) [6] Matai, Rajesh, Surya Prakash Singh, and Murari Lal Mittal. "Traveling salesman problem: an overview of applications, formulations, and solution approaches." [Traveling salesman problem, theory and applications 1 (2010).](https://www.sciencedirect.com/topics/computer-science/traveling-salesman-problem)
github_jupyter
# JSON files for d3 visualization ``` import os import copy import json import numpy as np import matplotlib.pyplot as plt with open('./data/b0.json') as infile: data = json.load(infile) data.keys() start = data['rts'][0][0] start.keys() for key in start: if key != 'children' and key != 'weights': print(key, start[key]) ``` ## Attention squares ``` !ls data/ len(data['rts'][0]) trees = [] json_files = [f for f in os.listdir('./data') if f.endswith('.json')] for n in range(len(json_files)): with open(f'./data/b{n}.json') as infile: data = json.load(infile) metadata = { 'children': data['rts'][0], 'global_coordinates': [0,0,0,0], 'coordinates': [0,0,0,0], 'relevance_value': 1 } tree = metadata # data['rts'][0][0] # field_sizes = [geom['global_size'] for geom in data['layer_geometries']] field_sizes = [8, 20, 36, 36, 36, 0] # field_sizes # kernel_sizes = [geom['size'] for geom in data['layer_geometries']] # kernel_sizes def clean(dictionary): """Only keep some keys in the nested dictionary.""" for key in list(dictionary): if key not in ['children', 'global_coordinates', 'coordinates', 'relevance_value']: del dictionary[key] else: if isinstance(dictionary[key], list): try: if isinstance(dictionary[key][0], dict): for child in dictionary[key]: clean(child) except IndexError: pass clean(tree) # def name(dictionary, layer): # """Add a layer name to all dictionaries in the nested dictionary.""" # dictionary['name'] = f'layer_{layer}' # for key in list(dictionary): # if isinstance(dictionary[key], list): # try: # if isinstance(dictionary[key][0], dict): # for child in dictionary[key]: # name(child, layer-1) # except IndexError: # pass # name(tree, layer=5) def get_coordinates(node, depth): n_layers = 6 x, y = node['global_coordinates'][1:3] size = field_sizes[-(depth + 1)] layer = n_layers - depth if layer <= 3: letter = 'C' number = str(layer) elif layer > 3 and layer < 6: letter = 'A' number = str(layer - 3) elif layer == 6: letter = 'Start' number = '' node['layer'] = layer node['square'] = (x, y, size) # center x, center y, height/width node['name'] = letter + number if layer != 6 : node['name'] += ' (' + ', '.join([str(n) for n in node['coordinates'][1:]]) + ')' for child in node['children']: get_coordinates(node=child, depth=depth+1) get_coordinates(tree, depth=0) def colorize(node, branch=None): if branch == None: color = 'black' elif branch == 1: color = 'red' elif branch == 2: color = 'red' elif branch == 3: color = 'yellow' elif branch == 4: color = 'yellow' node['color'] = color for i, child in enumerate(node['children']): if branch == None: lower_branch = i+1 else: lower_branch = branch colorize(child, branch=lower_branch) colorize(tree) # def truncate(node, factor=2): # n_children = len(node['children']) # n_truncated = int(n_children/factor) # if n_children > 0: # node['children'] = node['children'][0:n_truncated] # for child in node['children']: # truncate(child) # temp = copy.deepcopy(tree) # truncate(temp) def pick(node, depth): n_children = len(node['children']) if n_children > 1: n_layers = 6 layer = n_layers - depth mapping = { 6: None, 5: 1, 4: 1, 3: 1, 2: 1, 1: 0 } n_max = mapping[layer] node['children'] = node['children'][0:n_max] for child in node['children']: pick(child, depth=depth+1) pick(tree, depth=0) trees.append(tree) with open('trees.json', 'w') as outfile: json.dump(trees, outfile) ``` # Game background ``` screens = [] overlays = [] json_files = [f for f in os.listdir('./data') if f.endswith('.json')] for n in range(len(json_files)): with open(f'./data/b{n}.json') as infile: data = json.load(infile) tensor = np.asarray(data['input_values'], dtype=np.int) n_frames = tensor.shape[-1] for frame in range(n_frames): tensor[:, :, :, frame] = tensor[:, :, :, frame] * (n_frames - frame) # assuming that the last frame is the latest in time overlay = np.squeeze(np.amax(tensor, axis=-1)) overlay = overlay / overlay.max() * 255 overlay = overlay.astype(np.int) overlays.append(overlay) pixels = [] for y, row in enumerate(overlay): for x, value in enumerate(row): pixels.append({ 'x': int(x), 'y': int(y), 'value': int(value) }) screens.append(pixels) with open('screens.json', 'w') as outfile: json.dump(screens, outfile) for overlay in overlays: plt.imshow(overlay, cmap='gray') plt.show() ```
github_jupyter
# First 2000-volume sample of fiction This is straightforward, but I'm going to walk through it slowly to demonstrate different approaches one can use in basic Python and in Pandas. ``` # first, we "import" some modules we'll be using import pandas as pd import random ``` Now actually read in the metadata. ``` meta = pd.read_csv('../workmeta.tsv', sep = '\t', low_memory = False) meta.head() meta.shape ``` That tells us we have 138,137 rows and 28 columns in the dataset. ``` meta.columns ``` Let's count the number of volumes that have "earlyedition" flagged. To start with, I'll do it in the ordinary Python way we practiced earlier. ``` ctr = 0 for value in meta.earlyedition: if value == True: ctr += 1 print(ctr) ``` But there's a simpler way to do that. If you sum a list of Boolean (True/False) values, you get a count of the number of Trues. So, just: ``` print(sum(meta.earlyedition)) ``` In any case, this tells us that only about 129,000 of our 138,000 volumes were printed within 25 years of their author's death. I'm going to sample randomly from that group. In fact, if it were possible, I'd restrict even further to books printed within 25 years of the first publication *of that title.* But we don't always directly know a first publication date. ### Actually sampling I want to get 100 novels for each decade between 1800-09 and 2000-09. So, let's say 10 volumes a year. But I'm also conscious that we'll be rejecting a lot of books. So I'm going to initially sample 13 volumes a year, with the expectation that almost a third will be rejected. There are easy pandas-specific ways to do this. But I want to demonstrate Python logic, so I'm going to avoid easy things that look like magic tricks and do this a more laborious way. Let's just go through the whole dataset row by row and check the **document ID** and **date of publication.** If the date is between 1800 and 2010, we'll save the document ID and file it in a dictionary (set of file drawers) where the key for each drawer is a particular year, and the contents of each drawer are a list of doc IDs. Then, once we've got the volumes sorted in this manner by date, we can randomly sample 13 volumes from each drawer. ``` # To go through a pandas dataframe row by row, you can use the .iterrows() method. bydate = dict() # create the dictionary for idx, row in meta.iterrows(): date = row.inferreddate docid = row.docid early = row.earlyedition if early == False: continue # we're not going to use rows that aren't marked earlyedition # so we "continue" to the next iteration of the loop, and don't # do anything below else: if date < 1800 or date > 2009: continue else: if date not in bydate: # if we haven't encountered any volumes with this date yet, # create a list with one member bydate[date] = [docid] else: # otherwise, add this docid to the existing list bydate[date].append(docid) ``` #### A little visualization What's the date distribution of these volumes, by the way? We can find out by counting the number of volumes in each "file drawer." First we'll import a modules that's useful for plotting graphs. Then we'll go year by year from 1800 to 2009. We'll create a list of x coordinates that is simply the list of years, and a list of y coordinates that is the number of volumes in that year. The we just scatter plot (x, y). ``` from matplotlib import pyplot as plt %matplotlib inline x = [] y = [] for year in range(1800, 2010): x.append(year) y.append(len(bydate[year])) plt.scatter(x, y) plt.show() ``` You can see that the advent of copyright at 1923 makes a big difference in the size of the collection. I'm not exactly sure why; our collection is not limited to public-domain works. But possibly libraries have been less enthusiastic about digitizing fiction when it can't be made publicly available. We're going to flatten that out and select an evenly-distributed sample. #### okay, let's finally select volumes I'm going to go year by year. From the file drawer for each year (```bydate[year]```) I'm going to draw thirteen books. Then I'll add them to a constantly-growing list called ```selected.``` Notice how this echoes the counting strategy. Create a counter outside the loop; set it to zero; then loop through a sequence and add one to the counter ... Here we're extending a list instead of adding to a counter. ``` selected = list() for yr in range(1800, 2010): selected.extend(random.sample(bydate[yr], 13)) print(len(selected)) ``` Once we have a list of document ids we want to select, we can use them to extract the relevant rows from the table ```meta.``` ``` # To create a table limited to those document ids, we can just use the "docid" # column to *index* meta meta.set_index('docid', inplace = True) # and then select those rows our_meta = meta.loc[selected, : ] our_meta.shape ``` Now actually write that to disk. ``` our_meta.to_csv('firstsample.tsv', sep = '\t') ``` But in exploring this data with you, I quickly found that 28 full-width columns are overwhelming. So let's select a smaller set of twelve columns, and truncate some of them at 25 or 50 characters. ``` def truncate25(afield): if pd.isnull(afield): return '' elif len(afield) <= 25: return afield else: return afield[0:25] def shrinkframe(indf): df = indf.copy() df.reset_index(inplace = True) newdf = df[['docid', 'author', 'authordate', 'inferreddate', 'latestcomp', 'allcopiesofwork', 'copiesin25yrs', 'enumcron']] newdf = newdf.assign(imprint = df.imprint.map(truncate25)) newdf = newdf.assign(genres = df.genres.map(truncate25)) newdf = newdf.assign(subjects = df.subjects.map(truncate25)) newdf = newdf.assign(shorttitle = df.shorttitle) newdf = newdf.assign(realname = '') newdf = newdf.assign(pseudonym = '') newdf = newdf.assign(category = '') newdf = newdf.assign(firstpub = '') newdf = newdf.assign(realname = '') newdf = newdf.assign(gender = '') newdf = newdf.assign(nationality = '') newdf = newdf[['docid', 'author', 'realname', 'pseudonym', 'gender', 'nationality', 'authordate', 'inferreddate', 'firstpub', 'latestcomp', 'allcopiesofwork', 'copiesin25yrs', 'enumcron', 'imprint', 'genres', 'subjects', 'category', 'shorttitle']] return newdf shrunk = shrinkframe(our_meta) print(shrunk.shape) shrunk.head() ``` Now we need to divide this dataframe into three parts for the three of us. I'm giving 1200 rows to both of you, and taking 330 rows for myself as a sample, so I know what kind of problems you're encountering. #### divide in three parts We start by shuffling the index of our_meta, which is just a numeric index right now. ``` indices = our_meta.index.tolist() random.shuffle(indices) indices[0:20] ``` Then divide that random sequence into chunks like so: ``` forjessica = indices[0: 1200] forpatrick = indices[1200: 2400] forted = indices[2400 : ] teddf = shrinkframe(our_meta.loc[forted, ]) teddf.to_csv('ted.tsv', sep = '\t', index = False) jessdf = shrinkframe(our_meta.loc[forjessica, ]) jessdf.to_csv('jessica.tsv', sep = '\t', index = False) patdf = shrinkframe(our_meta.loc[forpatrick, ]) patdf.to_csv('patrick.tsv', sep = '\t', index = False) ``` ### Sanity checks ``` plt.hist(our_meta.inferreddate) plt.show() ``` Good. even distribution across time ``` max(our_meta.inferreddate) min(our_meta.inferreddate) ```
github_jupyter
# Transfer learning with TensorFlow/Keras 2.0 In this example we'll implement fine-tuning and feature extracting transfer learning using the CIFAR-10 dataset. _This example is partially based on_ [https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb] (https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb)<br/> _The licensing information and the author of the base version are:<br/> License: Apache License, Version 2.0<br/> Copyright 2018 The TensorFlow Authors. All rights reserved.<br/> License: MIT<br/> Copyright 2017 Franรงois Chollet. All rights reserved.<br/> Copyright 2019 Ivan Vasilev.<br/>_ Let's start with the imports: ``` import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds ``` We'll define the input image and batch size as constants: ``` IMG_SIZE = 224 BATCH_SIZE = 50 ``` We'll continue by loading the CIFAR-10 dataset using the `tensorflow_datasets` package: ``` data, metadata = tfds.load('cifar10', with_info=True, as_supervised=True) raw_train, raw_test = data['train'].repeat(), data['test'].repeat() ``` Next, we'll define the input transformations (per sample) for the training and validation phases: ``` def train_format_sample(image, label): """Transform data for training""" image = tf.cast(image, tf.float32) image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) image = (image / 127.5) - 1 image = tf.image.random_flip_left_right(image) image = tf.image.random_flip_up_down(image) label = tf.one_hot(label, metadata.features['label'].num_classes) return image, label def test_format_sample(image, label): """Transform data for testing""" image = tf.cast(image, tf.float32) image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE)) image = (image / 127.5) - 1 label = tf.one_hot(label, metadata.features['label'].num_classes) return image, label ``` Then, we'll define the training and validation data providers: ``` # assign transformers to raw data train_data = raw_train.map(train_format_sample) test_data = raw_test.map(test_format_sample) # extract batches from the training set train_batches = train_data.shuffle(1000).batch(BATCH_SIZE) test_batches = test_data.batch(BATCH_SIZE) ``` Next, we'll define 2 functions that build transfer learning models for either feature extacting, or fine-tuning. Both models use the `tf.keras.applications.ResNet50V2` ImageNet pretrained model. We'll start with feature extracting, which "locks" all model parameters (weights) except for the final fully-connected layer: ``` def build_fe_model(): """"Create feature extraction model from the pre-trained model ResNet50V2""" # create the pre-trained part of the network, excluding FC layers base_model = tf.keras.applications.ResNet50V2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False, weights='imagenet') # exclude all model layers from training base_model.trainable = False # create new model as a combination of the pre-trained net # and one fully connected layer at the top return tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense( metadata.features['label'].num_classes, activation='softmax') ]) ``` We'll continue with the fine-tuning model, which locks the first `fine_tune_at` layers, but trains all other model parameters: ``` def build_ft_model(): """"Create fine tuning model from the pre-trained model ResNet50V2""" # create the pre-trained part of the network, excluding FC layers base_model = tf.keras.applications.ResNet50V2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False, weights='imagenet') # Fine tune from this layer onwards fine_tune_at = 100 # Freeze all the layers before the `fine_tune_at` layer for layer in base_model.layers[:fine_tune_at]: layer.trainable = False # create new model as a combination of the pre-trained net # and one fully connected layer at the top return tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense( metadata.features['label'].num_classes, activation='softmax') ]) ``` Let's define the `train_model` function, which builds takes the pre-built model, fits it over the training data, and plots the training and validation results. The function is shared for both feature extraction and fine-tuning: ``` def train_model(model, epochs=5): """Train the model. This function is shared for both FE and FT modes""" # configure the model for training model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy']) # train the model history = model.fit(train_batches, epochs=epochs, steps_per_epoch=metadata.splits['train'].num_examples // BATCH_SIZE, validation_data=test_batches, validation_steps=metadata.splits['test'].num_examples // BATCH_SIZE, workers=4) # plot accuracy test_acc = history.history['val_accuracy'] plt.figure() plt.plot(test_acc) plt.xticks( [i for i in range(0, len(test_acc))], [i + 1 for i in range(0, len(test_acc))]) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.show() ``` We can now run the training procedure. Let's start by building the feature extraction model: ``` model = build_fe_model() model.summary() ``` Next, let's run the training: ``` train_model(model) ``` We can also try the fine-tuning model for comparison: ``` model = build_ft_model() model.summary() train_model(model) ``` Fine-tuning achieves better accuracy, compared to the feature-engineering model. The most likely reason is that the feature-engineering model is constrained to update only the weights of the last hidden layer.
github_jupyter
<a href="https://colab.research.google.com/github/dragonsan17/faq_retrieval_deep_learning/blob/main/flair_and_inltk_libraries_workflow.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Imports and Repo Downloading ``` !pip install torch==1.3.1+cpu -f https://download.pytorch.org/whl/torch_stable.html !pip install inltk !pip install flair import os from getpass import getpass import urllib import pandas as pd import numpy as np pd.set_option('max_colwidth', 1000) from IPython.display import display from tqdm.notebook import tqdm import flair import warnings from flair.embeddings import FlairEmbeddings, DocumentRNNEmbeddings from flair.data import Sentence from sklearn.metrics.pairwise import cosine_similarity as cs from tqdm.notebook import tqdm from inltk.inltk import get_sentence_similarity warnings.filterwarnings('ignore') # Enter Username, Password and Repo name which will then download all the repo contents here in colab. # You can then access and run all files of the same. This is to get an idea of how the code works in a cloud environment # source : https://stackoverflow.com/questions/48350226/methods-for-using-git-with-google-colab user = input('User name: ') password = getpass('Password: ') password = urllib.parse.quote(password) # repo_name = input('Repo name: ') repo_name = 'faq_retrieval_deep_learning' cmd_string = 'git clone https://{0}:{1}@github.com/{0}/{2}.git'.format(user, password, repo_name) os.system(cmd_string) cmd_string, password = "", "" %cd faq_retrieval_deep_learning ``` # Data Loading ``` df_all_data = pd.read_csv('data/all_data.csv', encoding = 'utf-8') df_test = pd.read_csv('data/test.csv', encoding = 'utf-8') df_train = pd.read_csv('data/train.csv', encoding = 'utf-8') df_test['t1'] = [(list(df_all_data[df_all_data['STT Transcript'] == q]['Broad theme']) + list(df_all_data[df_all_data['Caller query transcription'] == q]['Broad theme']))[0] for q in list(df_test['q1']) ] df_test['t2'] = [(list(df_all_data[df_all_data['STT Transcript'] == q]['Broad theme']) + list(df_all_data[df_all_data['Caller query transcription'] == q]['Broad theme']))[0] for q in list(df_test['q2']) ] ``` # Flair and iNLTK Models Take very long to predict on whole test dataset. Hence theme information is taken here itself and a score of 0 is given when theme is not same. Takes about an hour after this, for each of these models ``` """ Flair """ f_embedding = FlairEmbeddings('hi-forward') document_embeddings = DocumentRNNEmbeddings([f_embedding]) def flair_docrnn(df_test): test_q1 = df_test['q1'] test_q2 = df_test['q2'] predictions = [] dummy = np.arange(len(test_q1)) bar = tqdm(dummy) for i in bar: if df_test['t1'][i] != df_test['t2'][i]: predictions.append(0) continue q1 = Sentence(test_q1[i]) q2 = Sentence(test_q2[i]) document_embeddings.embed(q1) document_embeddings.embed(q2) e1 = q1.embedding.cpu().detach().numpy().reshape(1, -1) e2 = q2.embedding.cpu().detach().numpy().reshape(1, -1) score = cs(e1,e2)[0][0] predictions.append(score) return predictions df_test['positive_score'] = flair_docrnn(df_test) # # Run only once, to setup functions for Hindi in iNLTK # from inltk.inltk import setup # setup('hi') # """ # iNLTK # """ # def inltk_sentence_similarity(df_test): # test_q1 = df_test['q1'] # test_q2 = df_test['q2'] # predictions = [] # dummy = np.arange(len(test_q1)) # bar = tqdm(dummy) # for i in bar: # if df_test['t1'][i] != df_test['t2'][i]: # predictions.append(0) # continue # q1 = test_q1[i] # q2 = test_q2[i] # score = get_sentence_similarity(q1,q2, 'hi') # predictions.append(score) # return predictions # df_test['positive_score'] = inltk_sentence_similarity(df_test) ``` # Evaluation ``` def performance_metric(df): average_precision = 0 correct_answers = 0 success_rate = [0,0,0,0,0] precision = [0,0,0,0,0] reciprocal_rank = 0 for index,row in df.iterrows(): query_question = row['q1'] predicted_question = row['q2'] query_question_answer_index = list(df_all_data[df_all_data[TEST_COLUMN] == query_question]['Answer Index'])[0] predicted_question_answer_index = list(df_all_data[df_all_data[TRAIN_COLUMN] == predicted_question]['Answer Index'])[0] if query_question_answer_index == predicted_question_answer_index: correct_answers += 1 average_precision += correct_answers/(index + 1) for i in range(index,5): success_rate[i] = 1 precision[i] += 1/(i + 1) if reciprocal_rank == 0: reciprocal_rank = 1/(index + 1) average_precision /= len(df) calculated_metric = {'SR@1' : success_rate[0], 'SR@3' : success_rate[2], 'SR@5' : success_rate[4], 'P@1' : precision[0], 'P@3' : precision[2], 'P@5' : precision[4], 'MRR' : reciprocal_rank, 'MAP' : average_precision} return calculated_metric calculated_metric = {'SR@1' : 0, 'SR@3' : 0, 'SR@5' : 0, 'P@1' : 0, 'P@3' : 0, 'P@5' : 0, 'MRR' : 0, 'MAP' : 0} calculated_metric_with_themes = {'SR@1' : 0, 'SR@3' : 0, 'SR@5' : 0, 'P@1' : 0, 'P@3' : 0, 'P@5' : 0, 'MRR' : 0, 'MAP' : 0} query_question_groups = df_test.groupby(['q1']) for query_question in df_test['q1'].unique(): group = query_question_groups.get_group(query_question) group['ai'] = [list(df_all_data[df_all_data[TRAIN_COLUMN] == ri]['Answer Index'])[0] for ri in list(group['q2'])] ai_groups = group.groupby(['ai']) for ans_i in group['ai'].unique(): group_ai = ai_groups.get_group(ans_i) avg_score = group_ai['positive_score'].max() group['positive_score'] = group.apply(lambda x: avg_score if x['ai'] == ans_i else x['positive_score'], axis=1) group = group.drop_duplicates(subset=['ai']) query_question_theme = list(df_all_data[df_all_data[TEST_COLUMN] == query_question][BROAD_THEME])[0] group_with_themes = group.copy() for index, row in group_with_themes.iterrows(): if query_question_theme != list(df_all_data[df_all_data[TRAIN_COLUMN] == row['q2']][BROAD_THEME])[0]: group_with_themes.loc[index, 'positive_score'] = 0 group = group.sort_values(by=['positive_score'], ascending = False).reset_index(drop = True) group_with_themes = group_with_themes.sort_values(by=['positive_score'], ascending = False).reset_index(drop = True) group = group[group.index < 10] group_with_themes = group_with_themes[group_with_themes.index < 10] calculated_metric_for_group = performance_metric(group) calculated_metric_for_group_with_themes = performance_metric(group_with_themes) for key in calculated_metric_for_group: calculated_metric[key] += calculated_metric_for_group[key] calculated_metric_with_themes[key] += calculated_metric_for_group_with_themes[key] calculated_metric['Hit@1'] = calculated_metric['SR@1'] calculated_metric['Hit@3'] = calculated_metric['SR@3'] calculated_metric['Hit@5'] = calculated_metric['SR@5'] calculated_metric_with_themes['Hit@1'] = calculated_metric_with_themes['SR@1'] calculated_metric_with_themes['Hit@3'] = calculated_metric_with_themes['SR@3'] calculated_metric_with_themes['Hit@5'] = calculated_metric_with_themes['SR@5'] for key in calculated_metric: if 'Hit' not in key: calculated_metric[key] /= len(query_question_groups) calculated_metric_with_themes[key] /= len(query_question_groups) print("Results without theme information : ") print("Hit@1 : {}, 3: {}, 5 : {}, all : {}".format(calculated_metric['Hit@1'], calculated_metric['Hit@3'], calculated_metric['Hit@5'], len(df_test['q1'].unique()))) print("SR@1 : {:.3f}, 3: {:.3f}, 5 : {:.3f}".format(calculated_metric['SR@1'], calculated_metric['SR@3'], calculated_metric['SR@5'])) print("P@1 : {:.3f}, 3: {:.3f}, 5 : {:.3f}".format(calculated_metric['P@1'], calculated_metric['P@3'], calculated_metric['P@5'])) print("MAP : {:.3f}".format(calculated_metric['MAP']), end=", ") print("MRR : {:.3f}".format(calculated_metric['MRR'])) # print("NDCG : {:.3f}".format(MDCG/deno_dd["Exist"])) print("Results with theme information : ") print("Hit@1 : {}, 3: {}, 5 : {}, all : {}".format(calculated_metric_with_themes['Hit@1'], calculated_metric_with_themes['Hit@3'], calculated_metric_with_themes['Hit@5'], len(df_test['q1'].unique()))) print("SR@1 : {:.3f}, 3: {:.3f}, 5 : {:.3f}".format(calculated_metric_with_themes['SR@1'], calculated_metric_with_themes['SR@3'], calculated_metric_with_themes['SR@5'])) print("P@1 : {:.3f}, 3: {:.3f}, 5 : {:.3f}".format(calculated_metric_with_themes['P@1'], calculated_metric_with_themes['P@3'], calculated_metric_with_themes['P@5'])) print("MAP : {:.3f}".format(calculated_metric_with_themes['MAP']), end=", ") print("MRR : {:.3f}".format(calculated_metric_with_themes['MRR']), end=", ") ```
github_jupyter
<center> <img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" /> </center> # **SpaceX Falcon 9 first stage Landing Prediction** # Lab 1: Collecting the data Estimated time needed: **45** minutes In this capstone, we will predict if the Falcon 9 first stage will land successfully. SpaceX advertises Falcon 9 rocket launches on its website with a cost of 62 million dollars; other providers cost upward of 165 million dollars each, much of the savings is because SpaceX can reuse the first stage. Therefore if we can determine if the first stage will land, we can determine the cost of a launch. This information can be used if an alternate company wants to bid against SpaceX for a rocket launch. In this lab, you will collect and make sure the data is in the correct format from an API. The following is an example of a successful and launch. ![](https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/lab_v2/images/landing\_1.gif) Several examples of an unsuccessful landing are shown here: ![](https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0701EN-SkillsNetwork/lab_v2/images/crash.gif) Most unsuccessful landings are planned. Space X performs a controlled landing in the oceans. ## Objectives In this lab, you will make a get request to the SpaceX API. You will also do some basic data wrangling and formating. * Request to the SpaceX API * Clean the requested data *** ## Import Libraries and Define Auxiliary Functions We will import the following libraries into the lab ``` # Requests allows us to make HTTP requests which we will use to get data from an API import requests # Pandas is a software library written for the Python programming language for data manipulation and analysis. import pandas as pd # NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays import numpy as np # Datetime is a library that allows us to represent dates import datetime # Setting this option will print all collumns of a dataframe pd.set_option('display.max_columns', None) # Setting this option will print all of the data in a feature pd.set_option('display.max_colwidth', None) ``` Below we will define a series of helper functions that will help us use the API to extract information using identification numbers in the launch data. From the <code>rocket</code> column we would like to learn the booster name. ``` # Takes the dataset and uses the rocket column to call the API and append the data to the list def getBoosterVersion(data): for x in data['rocket']: response = requests.get("https://api.spacexdata.com/v4/rockets/"+str(x)).json() BoosterVersion.append(response['name']) ``` From the <code>launchpad</code> we would like to know the name of the launch site being used, the logitude, and the latitude. ``` # Takes the dataset and uses the launchpad column to call the API and append the data to the list def getLaunchSite(data): for x in data['launchpad']: response = requests.get("https://api.spacexdata.com/v4/launchpads/"+str(x)).json() Longitude.append(response['longitude']) Latitude.append(response['latitude']) LaunchSite.append(response['name']) ``` From the <code>payload</code> we would like to learn the mass of the payload and the orbit that it is going to. ``` # Takes the dataset and uses the payloads column to call the API and append the data to the lists def getPayloadData(data): for load in data['payloads']: response = requests.get("https://api.spacexdata.com/v4/payloads/"+load).json() PayloadMass.append(response['mass_kg']) Orbit.append(response['orbit']) ``` From <code>cores</code> we would like to learn the outcome of the landing, the type of the landing, number of flights with that core, whether gridfins were used, wheter the core is reused, wheter legs were used, the landing pad used, the block of the core which is a number used to seperate version of cores, the number of times this specific core has been reused, and the serial of the core. ``` # Takes the dataset and uses the cores column to call the API and append the data to the lists def getCoreData(data): for core in data['cores']: if core['core'] != None: response = requests.get("https://api.spacexdata.com/v4/cores/"+core['core']).json() Block.append(response['block']) ReusedCount.append(response['reuse_count']) Serial.append(response['serial']) else: Block.append(None) ReusedCount.append(None) Serial.append(None) Outcome.append(str(core['landing_success'])+' '+str(core['landing_type'])) Flights.append(core['flight']) GridFins.append(core['gridfins']) Reused.append(core['reused']) Legs.append(core['legs']) LandingPad.append(core['landpad']) ``` Now let's start requesting rocket launch data from SpaceX API with the following URL: ``` spacex_url="https://api.spacexdata.com/v4/launches/past" response = requests.get(spacex_url) ``` Check the content of the response ``` print(response.content) ``` You should see the response contains massive information about SpaceX launches. Next, let's try to discover some more relevant information for this project. ### Task 1: Request and parse the SpaceX launch data using the GET request To make the requested JSON results more consistent, we will use the following static response object for this project: ``` static_json_url='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/API_call_spacex_api.json' ``` We should see that the request was successfull with the 200 status response code ``` response.status_code ``` Now we decode the response content as a Json using <code>.json()</code> and turn it into a Pandas dataframe using <code>.json_normalize()</code> ``` # Use json_normalize meethod to convert the json result into a dataframe data = pd.json_normalize(response.json()) ``` Using the dataframe <code>data</code> print the first 5 rows ``` # Get the head of the dataframe data.head() ``` You will notice that a lot of the data are IDs. For example the rocket column has no information about the rocket just an identification number. We will now use the API again to get information about the launches using the IDs given for each launch. Specifically we will be using columns <code>rocket</code>, <code>payloads</code>, <code>launchpad</code>, and <code>cores</code>. ``` # Lets take a subset of our dataframe keeping only the features we want and the flight number, and date_utc. data = data[['rocket', 'payloads', 'launchpad', 'cores', 'flight_number', 'date_utc']] # We will remove rows with multiple cores because those are falcon rockets with 2 extra rocket boosters and rows that have multiple payloads in a single rocket. data = data[data['cores'].map(len)==1] data = data[data['payloads'].map(len)==1] # Since payloads and cores are lists of size 1 we will also extract the single value in the list and replace the feature. data['cores'] = data['cores'].map(lambda x : x[0]) data['payloads'] = data['payloads'].map(lambda x : x[0]) # We also want to convert the date_utc to a datetime datatype and then extracting the date leaving the time data['date'] = pd.to_datetime(data['date_utc']).dt.date # Using the date we will restrict the dates of the launches data = data[data['date'] <= datetime.date(2020, 11, 13)] ``` * From the <code>rocket</code> we would like to learn the booster name * From the <code>payload</code> we would like to learn the mass of the payload and the orbit that it is going to * From the <code>launchpad</code> we would like to know the name of the launch site being used, the longitude, and the latitude. * From <code>cores</code> we would like to learn the outcome of the landing, the type of the landing, number of flights with that core, whether gridfins were used, whether the core is reused, whether legs were used, the landing pad used, the block of the core which is a number used to seperate version of cores, the number of times this specific core has been reused, and the serial of the core. The data from these requests will be stored in lists and will be used to create a new dataframe. ``` #Global variables BoosterVersion = [] PayloadMass = [] Orbit = [] LaunchSite = [] Outcome = [] Flights = [] GridFins = [] Reused = [] Legs = [] LandingPad = [] Block = [] ReusedCount = [] Serial = [] Longitude = [] Latitude = [] ``` These functions will apply the outputs globally to the above variables. Let's take a looks at <code>BoosterVersion</code> variable. Before we apply <code>getBoosterVersion</code> the list is empty: ``` BoosterVersion ``` Now, let's apply <code> getBoosterVersion</code> function method to get the booster version ``` # Call getBoosterVersion getBoosterVersion(data) ``` the list has now been update ``` BoosterVersion[0:5] ``` we can apply the rest of the functions here: ``` # Call getLaunchSite getLaunchSite(data) # Call getPayloadData getPayloadData(data) # Call getCoreData getCoreData(data) ``` Finally lets construct our dataset using the data we have obtained. We we combine the columns into a dictionary. ``` launch_dict = {'FlightNumber': list(data['flight_number']), 'Date': list(data['date']), 'BoosterVersion':BoosterVersion, 'PayloadMass':PayloadMass, 'Orbit':Orbit, 'LaunchSite':LaunchSite, 'Outcome':Outcome, 'Flights':Flights, 'GridFins':GridFins, 'Reused':Reused, 'Legs':Legs, 'LandingPad':LandingPad, 'Block':Block, 'ReusedCount':ReusedCount, 'Serial':Serial, 'Longitude': Longitude, 'Latitude': Latitude} ``` Then, we need to create a Pandas data frame from the dictionary launch_dict. ``` # Create a data from launch_dict data=pd.DataFrame(launch_dict) ``` Show the summary of the dataframe ``` # Show the head of the dataframe data.head ``` ### Task 2: Filter the dataframe to only include `Falcon 9` launches Finally we will remove the Falcon 1 launches keeping only the Falcon 9 launches. Filter the data dataframe using the <code>BoosterVersion</code> column to only keep the Falcon 9 launches. Save the filtered data to a new dataframe called <code>data_falcon9</code>. ``` # Hint data['BoosterVersion']!='Falcon 1' data_falcon9=data[data['BoosterVersion']!='Falcon 1'] data_falcon9.head ``` Now that we have removed some values we should reset the FlgihtNumber column ``` data_falcon9.loc[:,'FlightNumber'] = list(range(1, data_falcon9.shape[0]+1)) data_falcon9 ``` ## Data Wrangling We can see below that some of the rows are missing values in our dataset. ``` data_falcon9.isnull().sum() ``` Before we can continue we must deal with these missing values. The <code>LandingPad</code> column will retain None values to represent when landing pads were not used. ### Task 3: Dealing with Missing Values Calculate below the mean for the <code>PayloadMass</code> using the <code>.mean()</code>. Then use the mean and the <code>.replace()</code> function to replace `np.nan` values in the data with the mean you calculated. ``` # Calculate the mean value of PayloadMass column payloadmean=data_falcon9['PayloadMass'].mean() # Replace the np.nan values with its mean value data_falcon9.replace(np.nan,payloadmean) ``` You should see the number of missing values of the <code>PayLoadMass</code> change to zero. Now we should have no missing values in our dataset except for in <code>LandingPad</code>. We can now export it to a <b>CSV</b> for the next section,but to make the answers consistent, in the next lab we will provide data in a pre-selected date range. <code>data_falcon9.to_csv('dataset_part\_1.csv', index=False)</code> ## Authors <a href="https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDS0321ENSkillsNetwork26802033-2021-01-01">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD. ## Change Log | Date (YYYY-MM-DD) | Version | Changed By | Change Description | | ----------------- | ------- | ---------- | ----------------------------------- | | 2020-09-20 | 1.1 | Joseph | get result each time you run | | 2020-09-20 | 1.1 | Azim | Created Part 1 Lab using SpaceX API | | 2020-09-20 | 1.0 | Joseph | Modified Multiple Areas | Copyright ยฉ 2021 IBM Corporation. All rights reserved.
github_jupyter
<img src="../../../../../images/qiskit_header.png" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" align="middle"> # _*Qiskit Finance: Pricing Asian Barrier Spreads*_ The latest version of this notebook is available on https://github.com/Qiskit/qiskit-iqx-tutorials. *** ### Contributors Stefan Woerner<sup>[1]</sup>, Daniel Egger<sup>[1]</sup> ### Affliation - <sup>[1]</sup>IBMQ ### Introduction <br> An Asian barrier spread is a combination of 3 different option types, and as such, combines multiple possible features that the Qiskit Finance option pricing framework supports:: - <a href="https://www.investopedia.com/terms/a/asianoption.asp">Asian option</a>: The payoff depends on the average price over the considered time horizon. - <a href="https://www.investopedia.com/terms/b/barrieroption.asp">Barrier Option</a>: The payoff is zero if a certain threshold is exceeded at any time within the considered time horizon. - <a href="https://www.investopedia.com/terms/b/bullspread.asp">(Bull) Spread</a>: The payoff follows a piecewise linear function (depending on the average price) starting at zero, increasing linear, staying constant. Suppose strike prices $K_1 < K_2$ and time periods $t=1,2$, with corresponding spot prices $(S_1, S_2)$ following a given multivariate distribution (e.g. generated by some stochastic process), and a barrier threshold $B>0$. The corresponding payoff function is defined as: <br> <br> $$ P(S_1, S_2) = \begin{cases} \min\left\{\max\left\{\frac{1}{2}(S_1 + S_2) - K_1, 0\right\}, K_2 - K_1\right\}, & \text{ if } S_1, S_2 \leq B \\ 0, & \text{otherwise.} \end{cases} $$ <br> In the following, a quantum algorithm based on amplitude estimation is used to estimate the expected payoff, i.e., the fair price before discounting, for the option: <br> <br> $$\mathbb{E}\left[ P(S_1, S_2) \right].$$ <br> The approximation of the objective function and a general introduction to option pricing and risk analysis on quantum computers are given in the following papers: - <a href="https://arxiv.org/abs/1806.06893">Quantum Risk Analysis. Woerner, Egger. 2018.</a> - <a href="https://arxiv.org/abs/1905.02666">Option Pricing using Quantum Computers. Stamatopoulos et al. 2019.</a> ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, BasicAer, execute from qiskit.aqua.algorithms import AmplitudeEstimation from qiskit.aqua.circuits import WeightedSumOperator, FixedValueComparator as Comparator from qiskit.aqua.components.uncertainty_problems import UnivariatePiecewiseLinearObjective as PwlObjective from qiskit.aqua.components.uncertainty_problems import MultivariateProblem from qiskit.aqua.components.uncertainty_models import MultivariateLogNormalDistribution ``` ### Uncertainty Model We construct a circuit factory to load a multivariate log-normal random distribution into a quantum state on $n$ qubits. For every dimension $j = 1,\ldots,d$, the distribution is truncated to a given interval $[low_j, high_j]$ and discretized using $2^{n_j}$ grid points, where $n_j$ denotes the number of qubits used to represent dimension $j$, i.e., $n_1+\ldots+n_d = n$. The unitary operator corresponding to the circuit factory implements the following: $$\big|0\rangle_{n} \mapsto \big|\psi\rangle_{n} = \sum_{i_1,\ldots,i_d} \sqrt{p_{i_1\ldots i_d}}\big|i_1\rangle_{n_1}\ldots\big|i_d\rangle_{n_d},$$ where $p_{i_1\ldots i_d}$ denote the probabilities corresponding to the truncated and discretized distribution and where $i_j$ is mapped to the right interval using the affine map: $$ \{0, \ldots, 2^{n_j}-1\} \ni i_j \mapsto \frac{high_j - low_j}{2^{n_j} - 1} * i_j + low_j \in [low_j, high_j].$$ For simplicity, we assume both stock prices are independent and identically distributed. This assumption just simplifies the parametrization below and can be easily relaxed to more complex and also correlated multivariate distributions. The only important assumption for the current implementation is that the discretization grid of the different dimensions has the same step size. ``` # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = ((r - 0.5 * vol**2) * T + np.log(S)) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2/2) variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3*stddev) high = mean + 3*stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits=[num_uncertainty_qubits]*dimension low=low*np.ones(dimension) high=high*np.ones(dimension) mu=mu*np.ones(dimension) cov=sigma**2*np.eye(dimension) # construct circuit factory u = MultivariateLogNormalDistribution(num_qubits=num_qubits, low=low, high=high, mu=mu, cov=cov) # plot PDF of uncertainty model x = [ v[0] for v in u.values ] y = [ v[1] for v in u.values ] z = u.probabilities #z = map(float, z) #z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits])*1j grid_x, grid_y = np.mgrid[min(x):max(x):resolution[0], min(y):max(y):resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) fig = plt.figure(figsize=(10, 8)) ax = fig.gca(projection='3d') ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel('Spot Price $S_1$ (\$)', size=15) ax.set_ylabel('Spot Price $S_2$ (\$)', size=15) ax.set_zlabel('Probability (\%)', size=15) plt.show() ``` ### Payoff Function For simplicity, we consider the sum of the spot prices instead of their average. The result can be transformed to the average by just dividing it by 2. The payoff function equals zero as long as the sum of the spot prices $(S_1 + S_2)$ is less than the strike price $K_1$ and then increases linearly until the sum of the spot prices reaches $K_2$. Then payoff stays constant to $K_2 - K_1$ unless any of the two spot prices exceeds the barrier threshold $B$, then the payoff goes immediately down to zero. The implementation first uses a weighted sum operator to compute the sum of the spot prices into an ancilla register, and then uses a comparator, that flips an ancilla qubit from $\big|0\rangle$ to $\big|1\rangle$ if $(S_1 + S_2) \geq K_1$ and another comparator/ancilla to capture the case that $(S_1 + S_2) \geq K_2$. These ancillas are used to control the linear part of the payoff function. In addition, we add another ancilla variable for each time step and use additional comparators to check whether $S_1$, respectively $S_2$, exceed the barrier threshold $B$. The payoff function is only applied if $S_1, S_2 \leq B$. The linear part itself is approximated as follows. We exploit the fact that $\sin^2(y + \pi/4) \approx y + 1/2$ for small $|y|$. Thus, for a given approximation scaling factor $c_{approx} \in [0, 1]$ and $x \in [0, 1]$ we consider $$ \sin^2( \pi/2 * c_{approx} * ( x - 1/2 ) + \pi/4) \approx \pi/2 * c_{approx} * ( x - 1/2 ) + 1/2 $$ for small $c_{approx}$. We can easily construct an operator that acts as $$\big|x\rangle \big|0\rangle \mapsto \big|x\rangle \left( \cos(a*x+b) \big|0\rangle + \sin(a*x+b) \big|1\rangle \right),$$ using controlled Y-rotations. Eventually, we are interested in the probability of measuring $\big|1\rangle$ in the last qubit, which corresponds to $\sin^2(a*x+b)$. Together with the approximation above, this allows to approximate the values of interest. The smaller we choose $c_{approx}$, the better the approximation. However, since we are then estimating a property scaled by $c_{approx}$, the number of evaluation qubits $m$ needs to be adjusted accordingly. For more details on the approximation, we refer to: <a href="https://arxiv.org/abs/1806.06893">Quantum Risk Analysis. Woerner, Egger. 2018.</a> Since the weighted sum operator (in its current implementation) can only sum up integers, we need to map from the original ranges to the representable range to estimate the result, and reverse this mapping before interpreting the result. The mapping essentially corresponds to the affine mapping described in the context of the uncertainty model above. ``` # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] n_s = WeightedSumOperator.get_required_sum_qubits(weights) # create circuit factory agg = WeightedSumOperator(sum(num_qubits), weights) # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = (strike_price_1 - dimension*low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) mapped_strike_price_2 = (strike_price_2 - dimension*low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2]*dimension for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) conditions += [(i, Comparator(num_qubits[i], mapped_barrier[i] + 1, geq=False))] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 bull_spread_objective = PwlObjective( n_s, 0, max_value, breakpoints, slopes, offsets, f_min, f_max, c_approx ) # define overall multivariate problem asian_barrier_spread = MultivariateProblem(u, agg, bull_spread_objective, conditions=conditions) # plot exact payoff function plt.figure(figsize=(15,5)) plt.subplot(1,2,1) x = np.linspace(sum(low), sum(high)) y = (x <= 5)*np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, 'r-') plt.grid() plt.title('Payoff Function (for $S_1 = S_2$)', size=15) plt.xlabel('Sum of Spot Prices ($S_1 + S_2)$', size=15) plt.ylabel('Payoff', size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) # plot contour of payoff function with respect to both time steps, including barrier plt.subplot(1,2,2) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum(np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title('Payoff Function', size =15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel('Spot Price $S_1$', size=15) plt.ylabel('Spot Price $S_2$', size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [ np.max(v) <= barrier for v in u.values ] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print('exact expected value:\t%.4f' % exact_value) ``` ### Evaluate Expected Payoff We first verify the quantum circuit by simulating it and analyzing the resulting probability to measure the $|1\rangle$ state in the objective qubit. ``` num_req_qubits = asian_barrier_spread.num_target_qubits num_req_ancillas = asian_barrier_spread.required_ancillas() q = QuantumRegister(num_req_qubits, name='q') q_a = QuantumRegister(num_req_ancillas, name='q_a') qc = QuantumCircuit(q, q_a) asian_barrier_spread.build(qc, q, q_a) print('state qubits: ', num_req_qubits) print('circuit width:', qc.width()) print('circuit depth:', qc.depth()) job = execute(qc, backend=BasicAer.get_backend('statevector_simulator')) # evaluate resulting statevector value = 0 for i, a in enumerate(job.result().get_statevector()): b = ('{0:0%sb}' % asian_barrier_spread.num_target_qubits).format(i)[-asian_barrier_spread.num_target_qubits:] prob = np.abs(a)**2 if prob > 1e-4 and b[0] == '1': value += prob # all other states should have zero probability due to ancilla qubits if i > 2**num_req_qubits: break # map value to original range mapped_value = asian_barrier_spread.value_to_estimation(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print('Exact Operator Value: %.4f' % value) print('Mapped Operator value: %.4f' % mapped_value) print('Exact Expected Payoff: %.4f' % exact_value) ``` Next we use amplitude estimation to estimate the expected payoff. Note that this can take a while since we are simulating a large number of qubits. The way we designed the operator (asian_barrier_spread) implies that the number of actual state qubits is significantly smaller, thus, helping to reduce the overall simulation time a bit. ``` # set number of evaluation qubits (=log(samples)) m = 3 # construct amplitude estimation ae = AmplitudeEstimation(m, asian_barrier_spread) # result = ae.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100) result = ae.run(quantum_instance=BasicAer.get_backend('statevector_simulator')) print('Exact value: \t%.4f' % exact_value) print('Estimated value:\t%.4f' % (result['estimation'] / (2**num_uncertainty_qubits - 1) * (high_ - low_))) print('Probability: \t%.4f' % result['max_probability']) # plot estimated values for "a" plt.bar(result['values'], result['probabilities'], width=0.5/len(result['probabilities'])) plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title('"a" Value', size=15) plt.ylabel('Probability', size=15) plt.ylim((0,1)) plt.grid() plt.show() # plot estimated values for option price (after re-scaling and reversing the c_approx-transformation) mapped_values = np.array(result['mapped_values']) / (2**num_uncertainty_qubits - 1) * (high_ - low_) plt.bar(mapped_values, result['probabilities'], width=1/len(result['probabilities'])) plt.plot([exact_value, exact_value], [0,1], 'r--', linewidth=2) plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title('Estimated Option Price', size=15) plt.ylabel('Probability', size=15) plt.ylim((0,1)) plt.grid() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright ```
github_jupyter
``` import pandas as pd from pathlib import Path import numpy as np from typing import Iterable from tqdm.auto import tqdm import pickle from scipy.spatial import distance from sklearn.metrics import accuracy_score from sklearn.metrics import roc_curve FIW_FEATURES = Path("/Users/zkhan/Dropbox/rfiw2020-data/FIDs-features/") validation_csv = pd.read_csv("/Users/zkhan/Dropbox/rfiw2020-data/trisubject_verification.v2/val/val_triples_competition_with_label.csv") test_csv = pd.read_csv("/Users/zkhan/Dropbox/rfiw2020-data/trisubject_verification.v2/test/test_triples_reference.csv") def read_features_from_iterable_of_pictures(iterable: Iterable[str], feature_dir: Path, feature_len: int = 512): """ For each picture in the iterable, read the corresponding feature file from a directory of feature files. Parameters ------------ iterable: An iterable of face image names. feature_dir: A Path to a directory containing features of faces, organized in the same way as FIW. feature_len: The size of the feature vector. Returns ------------ A mxn matrix, where m is the number of images in the iterable, and n is the feature len. """ dims = (len(iterable), feature_len) features = np.zeros(dims) for idx, img in enumerate(tqdm(iterable)): feature_file_name = (FIW_FEATURES / img).with_suffix(".pkl") with open(feature_file_name, "rb") as f: feature_vector = pickle.load(f) features[idx] = feature_vector return features ``` # Finding the best thresholds We will use the mean of the cosine sim between (father, child) and (mother, child), then threshold it. ``` val_father_features = read_features_from_iterable_of_pictures(validation_csv.F.values, FIW_FEATURES) val_mother_features = read_features_from_iterable_of_pictures(validation_csv.M.values, FIW_FEATURES) val_child_features = read_features_from_iterable_of_pictures(validation_csv.C.values, FIW_FEATURES) def combine_fmc_features(father_feats, mother_feats, child_feats): fc_cosine_sim = np.array([distance.cosine(u, v) for u, v in zip(father_feats, child_feats)]).reshape(-1, 1) mc_cosine_sim = np.array([distance.cosine(u, v) for u, v in zip(mother_feats, child_feats)]).reshape(-1, 1) fc_mc_cosine_sim = np.hstack((fc_cosine_sim, mc_cosine_sim)) return np.mean(fc_mc_cosine_sim, axis=1) val_scores = combine_fmc_features(val_father_features, val_mother_features, val_child_features) val_labels = validation_csv.label.values.copy() thresholds = np.arange(1, 0, step=-0.0125) accuracy_scores = [] for thresh in tqdm(thresholds): accuracy_scores.append(accuracy_score(val_labels, val_scores > thresh)) accuracies = np.array(accuracy_scores) max_accuracy = accuracies.max() max_accuracy_threshold = thresholds[accuracies.argmax()] print(f"Max accuracy: {max_accuracy}") print(f"Max accuracy threshold: {max_accuracy_threshold}") ``` The max accuracy is 0.5, and the threshold is 0.6125. # Evaluation on test set ``` test_father_features = read_features_from_iterable_of_pictures(test_csv.father_img.values, FIW_FEATURES) test_mother_features = read_features_from_iterable_of_pictures(test_csv.mother_img.values, FIW_FEATURES) test_child_features = read_features_from_iterable_of_pictures(test_csv.child_img.values, FIW_FEATURES) test_scores = combine_fmc_features(test_father_features, test_mother_features, test_child_features) test_labels = test_csv.label.values.copy() test_csv["tag"] = test_csv["child_gender"].apply(lambda r: "FM-D" if r == "f" else "FM-S") test_csv["pred"] = test_scores > max_accuracy_threshold reltypes = test_csv.tag.unique() accuracy_df = pd.DataFrame(columns=reltypes, dtype=float) for rel in reltypes: y_true = test_csv[test_csv.tag == rel]["label"].values y_pred = test_csv[test_csv.tag == rel ]["pred"].values accuracy_df.loc[0, rel] = accuracy_score(y_true, y_pred) accuracy_df.round(3) ```
github_jupyter
<center> <img src="../../img/ods_stickers.jpg"> ## ะžั‚ะบั€ั‹ั‚ั‹ะน ะบัƒั€ั ะฟะพ ะผะฐัˆะธะฝะฝะพะผัƒ ะพะฑัƒั‡ะตะฝะธัŽ <center>ะะฒั‚ะพั€ ะผะฐั‚ะตั€ะธะฐะปะฐ: ะ•ะปะตะฝะฐ ะ”ะตะฒัั‚ะฐะนะบะธะฝะฐ (@elenadevyataykina) # ะžั†ะตะฝะบะฐ ะฟะปะพั‚ะฝะพัั‚ะธ, ะธัะฟะพะปัŒะทัƒั Gaussian Mixture Models ะ’ ะดะฐะฝะฝะพะผ ะบัƒั€ัะต ะฑั‹ะปะธ ั€ะฐััะผะฐะพั‚ั€ะตะฝั‹ ัะปะตะดัƒัŽั‰ะธะต ะฐะปะณะพั€ะธั‚ะผั‹ ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธะธ: - K-means - Affinity Propagation - ะกะฟะตะบั‚ั€ะฐะปัŒะฝะฐั ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธั - ะะณะปะพะผะตั€ะฐั‚ะธะฒะฝะฐั ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธั ะ—ะดะตััŒ ะฑัƒะดะตั‚ ั€ะฐััะผะพั‚ั€ะตะฝ EM-ะฐะปะณะพั€ะธั‚ะผ, ั€ะตะฐะปะธะทะพะฒะฐะฝะฝั‹ะน ะฒ ะผะพะดัƒะปะต `sklearn.mixture.GMM`. **ะงั‚ะพ ัั‚ะพ ั‚ะฐะบะพะต?** ะญั‚ะพ ะฐะปะณะพั€ะธั‚ะผ, ะธัะฟะพะปัŒะทัƒะตะผั‹ะน ะดะปั ะฝะฐั…ะพะถะดะตะฝะธั ะพั†ะตะฝะพะบ ะผะฐะบัะธะผะฐะปัŒะฝะพะณะพ ะฟั€ะฐะฒะดะพะฟะพะดะพะฑะธั ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะฒะตั€ะพัั‚ะฝะพัั‚ะฝั‹ั… ะผะพะดะตะปะตะน, ะฒ ัะปัƒั‡ะฐะต, ะบะพะณะดะฐ ะผะพะดะตะปัŒ ะทะฐะฒะธัะธั‚ ะพั‚ ะฝะตะบะพั‚ะพั€ั‹ั… ัะบั€ั‹ั‚ั‹ั… ะฟะตั€ะตะผะตะฝะฝั‹ั…. **ะšะฐะบ ะพะฝ ั€ะฐะฑะพั‚ะฐะตั‚?** ะžั†ะตะฝะธะฒะฐั ะผะฐะบัะธะผะฐะปัŒะฝะพะต ะฟั€ะฐะฒะดะพะฟะพะดะพะฑะธะต, EM-ะฐะปะณะพั€ะธั‚ะผ ัะพะทะดะฐะตั‚ ะผะพะดะตะปัŒ, ะบะพั‚ะพั€ะฐั ะฝะฐะทะฝะฐั‡ะฐะตั‚ ะผะตั‚ะบะธ ะบะปะฐััะฐ ั‚ะพั‡ะบะฐะผ ะดะฐะฝะฝั‹ั…. EM-ะฐะปะณะพั€ะธั‚ะผ ะฝะฐั‡ะธะฝะฐะตั‚ ั ั‚ะพะณะพ, ั‡ั‚ะพ ะฟั‹ั‚ะฐะตั‚ัั ัะดะตะปะฐั‚ัŒ ะฒั‹ะฒะพะด ะฝะฐ ะพัะฝะพะฒะฐะฝะธะธ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะผะพะดะตะปะธ. ะ—ะฐั‚ะตะผ ัะปะตะดัƒะตั‚ ะธั‚ะตั€ะฐั†ะธะพะฝะฝั‹ะน ั‚ั€ะตั…ัˆะฐะณะพะฒั‹ะน ะฟั€ะพั†ะตัั: 1. E-ัˆะฐะณ: ะะฐ ัั‚ะพะผ ัˆะฐะณะต ะฝะฐ ะพัะฝะพะฒะฐะฝะธะธ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะผะพะดะตะปะธ ะฒั‹ั‡ะธัะปััŽั‚ัั ะฒะตั€ะพัั‚ะฝะพัั‚ัŒ ะฟั€ะธะฝะฐะดะปะตะถะฝะพัั‚ะธ ะบะฐะถะดะพะน ั‚ะพั‡ะบะธ ะดะฐะฝะฝั‹ั… ะบ ะบะปะฐัั‚ะตั€ัƒ. 2. ะœ-ัˆะฐะณ: ะžะฑะฝะพะฒะปัะตั‚ ะฟะฐั€ะฐะผะตั‚ั€ั‹ ะผะพะดะตะปะธ ะฒ ัะพะพั‚ะฒะตั‚ัั‚ะฒะธะธ ั ะบะปะฐัั‚ะตั€ะฝั‹ะผ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะตะผ, ะฟั€ะพะฒะตะดะตะฝะฝั‹ะผ ะฝะฐ ัˆะฐะณะต E. 3. ะŸั€ะตะดั‹ะดัƒั‰ะธะต ะดะฒะฐ ัˆะฐะณะฐ ะฟะพะฒั‚ะพั€ััŽั‚ัั ะดะพ ั‚ะตั… ะฟะพั€, ะฟะพะบะฐ ะฟะฐั€ะฐะผะตั‚ั€ั‹ ะผะพะดะตะปะธ ะธ ะบะปะฐัั‚ะตั€ะฝะพะต ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะต ะฝะต ัƒั€ะฐะฒะฝััŽั‚ัั. ะงะฐัั‚ะพ ะดะฐะฝะฝั‹ะน ะฐะปะณะพั€ะธั‚ะผ ะธัะฟะพะปัŒะทัƒัŽั‚ ะดะปั ั€ะฐะทะดะตะปะตะฝะธั ัะผะตัะธ ะณะฐัƒัะธะฐะฝ (GMM). ะขะพ ะตัั‚ัŒ ะฒ ั€ะตะทัƒะปัŒั‚ะฐั‚ะต GMM-EM ะฟะพะปัƒั‡ะฐะตะผ ะฟะพะปะฝะพั†ะตะฝะฝัƒัŽ ัะผะตััŒ ะ“ะฐัƒััะธะฐะฝะพะฒ ะฟะพะปัƒั‡ะตะฝะฝัƒัŽ ะฒ ะปะพะบะฐะปัŒะฝะพะผ ะผะฐะบัะธะผัƒะผะต ะฟั€ะฐะฒะดะพะฟะพะดะพะฑะธั. ะ”ะฐะปะตะต ั€ะฐััะผะฐะพั‚ั€ะธะผ GMM ะฑะพะปะตะต ะฟะพะดั€ะพะฑะฝะพ. **GMM** - ะพะดะธะฝ ะธะท ะฐะปะณะพั€ะธั‚ะผะพะฒ ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธะธ ะฝะฐั€ัะดัƒ ั ะธะตั€ะฐั€ั…ะธั‡ะตัะบะพะน ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธะตะน (ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธั ะฝะฐ ะพัะฝะพะฒะต ัะฒัะทะฝะพัั‚ะธ), k-means (ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธั ะฝะฐ ะพัะฝะพะฒะต ั†ะตะฝั‚ั€ะพะฒ), DBSCAN (ะบะปะฐัั‚ะตั€ะธะทะฐั†ะธั ะฝะฐ ะพัะฝะพะฒะต ะฟะปะพั‚ะฝะพัั‚ะธ). ะ’ ะพัะฝะพะฒะต ะดะฐะฝะฝะพะณะพ ะฐะปะณะพั€ะธั‚ะผะฐ ะปะตะถะฐั‚ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธั. **ะ“ะฐัƒััะพะฒะฐ ัะผะตััŒ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะน (GMM โ€” Gaussian mixture models)** - ัั‚ะฐั‚ะธัั‚ะธั‡ะตัะบะฐั ะผะพะดะตะปัŒ ะดะปั ะฟั€ะตะดัั‚ะฐะฒะปะตะฝะธั ะฝะพั€ะผะฐะปัŒะฝะพ ั€ะฐัะฟั€ะตะดะตะปะตะฝะฝั‹ั… ะฟะพะดะฒั‹ะฑะพั€ะพะบ ะฒะฝัƒั‚ั€ะธ ะพะฑั‰ะตะน ะฒั‹ะฑะพั€ะบะธ. ะ“ะฐัƒััะพะฒะฐ ัะผะตััŒ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะน ะฟะฐั€ะฐะผะตั‚ั€ะธะทะธั€ัƒะตั‚ัั ะดะฒัƒะผั ั‚ะธะฟะฐะผะธ ะทะฝะฐั‡ะตะฝะธะน โ€” ัะผะตััŒ ะฒะตัะพะฒ ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ ะธ ัั€ะตะดะฝะธั… ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ ะธะปะธ ะบะพะฒะฐั€ะธะฐั†ะธะน (ะดะปั ะผะฝะพะณะพะผะตั€ะฝะพะณะพ ัะปัƒั‡ะฐั) ะธ ะดั€. ะ•ัะปะธ ะบะพะปะธั‡ะตัั‚ะฒะพ ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ ะธะทะฒะตัั‚ะฝะพ, ั‚ะตั…ะฝะธะบะฐ, ั‡ะฐั‰ะต ะฒัะตะณะพ ะธัะฟะพะปัŒะทัƒะตะผะฐั ะดะปั ะพั†ะตะฝะบะธ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ัะผะตัะธ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะน โ€” ะ•ะœ-ะฐะปะณะพั€ะธั‚ะผ. ะœะตั‚ะพะด GMM ะฝะตะฟะพัั€ะตะดัั‚ะฒะตะฝะฝะพ ะฒั‹ั‚ะตะบะฐะตั‚ ะธะท ั‚ะตะพั€ะตะผั‹, ะณะปะฐััั‰ะตะน, ั‡ั‚ะพ ะปัŽะฑะฐั ั„ัƒะฝะบั†ะธั ะฟะปะพั‚ะฝะพัั‚ะธ ะฒะตั€ะพัั‚ะฝะพัั‚ะธ ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ะฟั€ะตะดัั‚ะฐะฒะปะตะฝะฐ ะบะฐะบ ะฒะทะฒะตัˆะตะฝะฝะฐั ััƒะผะผะฐ ะฝะพั€ะผะฐะปัŒะฝั‹ั… ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะน $$ p = \sum_{j=1}^k w_i \varphi (x; \theta_j),$$ $$ \sum_{j=1}^k w_j = 1,$$ ะณะดะต $\varphi (x; \theta_j)$ - ั„ัƒะฝะบั†ะธั ั€ะฐัะฟั€ะตะดะตะปะตะฝะธั ะผะฝะพะณะพะผะตั€ะฝะพะณะพ ะฐั€ะณัƒะผะตะฝั‚ะฐ $x$ ั ะฟะฐั€ะฐะผะตั‚ั€ะฐะผะธ $\theta_j,$ $$\varphi (x; \theta_j) = p(x | \mu_j, R_j) = \frac{1}{{2\pi}^{n/2}{|R_j|}^{1/2}}e^{-\frac{1}{2}{(x-\mu_j)}^TR_j^{-1}(x-\mu_j)}, x \in \mathbb R^n$$ $w_j$ - ะตะต ะฒะตั, $k$ - ะบะพะปะธั‡ะตัั‚ะฒะพ ะบะพะผะฟะพะฝะตะฝั‚ ะฒ ัะผะตัะธ. ะ—ะดะตััŒ $n$ - ั€ะฐะทะผะตั€ะฝะพัั‚ัŒ ะฟั€ะพัั‚ั€ะฐะฝัั‚ะฒะฐ ะฟั€ะธะทะฝะฐะบะพะฒ, $\mu_j \in \mathbb R^n$ - ะฒะตะบั‚ะพั€ ะผะฐั‚ะตะผะฐั‚ะธั‡ะตัะบะพะณะพ ะพะถะธะดะฐะฝะธั $j$-ะน ะบะพะผะฟะพะฝะตะฝั‚ั‹ ัะผะตัะธ, $R_j \in \mathbb R^{n*n}$ - ะบะพะฒะฐั€ะธะฐั†ะธะพะฝะฝะฐั ะผะฐั‚ั€ะธั†ะฐ. ``` import warnings warnings.simplefilter('ignore') %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats import seaborn as sns; sns.set() from sklearn.mixture import GMM from sklearn.neighbors import KernelDensity ``` ## ะ’ะฒะตะดะตะฝะธะต ะฒ GMM ะกะพะทะดะฐะดะธะผ ะพะดะฝะพะผะตั€ะฝั‹ะน ะฝะฐะฑะพั€ ะดะฐะฝะฝั‹ั… ั ะฐะทะฐะดะฝะฝั‹ะผ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะตะผ ะธ ะฟะพัั‚ั€ะพะธะผ ะณะธัั‚ะพะณั€ะฐะผะผัƒ ``` np.random.seed(2) x = np.concatenate([np.random.normal(0, 2, 2000), np.random.normal(5, 5, 2000), np.random.normal(3, 0.5, 600)]) plt.hist(x, 80, normed=True) plt.xlim(-10, 20); ``` ะก ะฟะพะผะพั‰ัŒัŽ GMM ะพั‚ะพะฑั€ะฐะทะธะผ ะฟะปะพั‚ะฝะพัั‚ัŒ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธั ``` X = x[:, np.newaxis] clf = GMM(4, n_iter=500, random_state=3).fit(X) xpdf = np.linspace(-10, 20, 1000) density = np.exp(clf.score(xpdf[:, np.newaxis])) plt.hist(x, 80, normed=True, alpha=0.5) plt.plot(xpdf, density, '-r') plt.xlim(-10, 20); ``` ะŸะพัะผะพั‚ั€ะธะผ ะฝะฐ ะฟะพะปัƒั‡ะตะฝะฝั‹ะต ะฐั‚ั€ะธะฑัƒั‚ั‹ GMM. ะกั€ะตะดะฝะตะต ะทะฝะฐั‡ะตะฝะธะต ะบะฐะถะดะพะน ะบะพะผะฟะพะฝะตะฝั‚ั‹: ``` clf.means_ ``` ะšะพะฒะฐั€ะธะฐั†ะธั ะบะฐะถะดะพะน ะบะพะผะฟะพะฝะตะฝั‚ั‹ ``` clf.covars_ ``` ะ’ะตั ะบะฐะถะดะพะน ะบะพะผะฟะพะฝะตะฝั‚ั‹ ``` clf.weights_ ``` ะขะฐะบ ะบะฐะบ ะฒ GMM ะทะฐะดะฐะฝะพ 4 ะบะพะผะฟะพะฝะตะฝั‚ั‹, ะฟะพัั‚ั€ะพะธะผ ะฒัะต ะฟะปะพั‚ะฝะพัั‚ะธ ั€ะฐัะฟั€ะตะดะตะปะตะฝะธั ``` plt.hist(x, 80, normed=True, alpha=0.3) plt.plot(xpdf, density, '-r') for i in range(clf.n_components): pdf = clf.weights_[i] * stats.norm(clf.means_[i, 0], np.sqrt(clf.covars_[i, 0])).pdf(xpdf) plt.fill(xpdf, pdf, facecolor='gray', edgecolor='none', alpha=0.3) plt.xlim(-10, 20); ``` ะ”ะปั ะฟะพัั‚ั€ะพะตะฝะฝะพะน ะผะพะดะตะปะธ ะผะพะถะฝะพ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ะพะดะฝะพ ะธะท ะฝะตัะบะพะปัŒะบะธั… ัั€ะตะดะฝะธั…, ั‡ั‚ะพะฑั‹ ะพั†ะตะฝะธั‚ัŒ, ะฝะฐัะบะพะปัŒะบะพ ั…ะพั€ะพัˆะพ ะพะฝ ะฟะพะดั…ะพะดะธั‚ ะดะฐะฝะฝั‹ะผ. ะžะฑั‹ั‡ะฝะพ ะดะปั ัั‚ะพะณะพ ะธัะฟะพะปัŒะทัƒะตั‚ัั **ะ˜ะฝั„ะพั€ะผะฐั†ะธะพะฝะฝั‹ะน ะบั€ะธั‚ะตั€ะธะน ะะบะฐะธะบะต (AIC)** ะธะปะธ **ะ‘ะฐะนะตัะพะฒัะบะธะน ะธะฝั„ะพั€ะผะฐั†ะธะพะฝะฝั‹ะน ะบั€ะธั‚ะตั€ะธะน (BIC)**. **ะ˜ะฝั„ะพั€ะผะฐั†ะธะพะฝะฝั‹ะน ะบั€ะธั‚ะตั€ะธะน ะะบะฐะธะบะต** - ะบั€ะธั‚ะตั€ะธะน, ะฟั€ะธะผะตะฝััŽั‰ะธะนัั ะธัะบะปัŽั‡ะธั‚ะตะปัŒะฝะพ ะดะปั ะฒั‹ะฑะพั€ะฐ ะธะท ะฝะตัะบะพะปัŒะบะธั… ัั‚ะฐั‚ะธัั‚ะธั‡ะตัะบะธั… ะผะพะดะตะปะตะน. $$aic = 2k - 2l,$$ ะณะดะต $k$ - ั‡ะธัะปะพ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะฒ ัั‚ะฐั‚ะธัั‚ะธั‡ะตัะบะพะน ะผะพะดะตะปะธ, $l$ - ะทะฝะฐั‡ะตะฝะธะต ะปะพะณะฐั€ะธั„ะผะธั‡ะตัะบะพะน ั„ัƒะฝะบั†ะธะธ ะฟั€ะฐะฒะดะพะฟะพะดะพะฑะธั ะฟะพัั‚ั€ะพะตะฝะฝะพะน ะผะพะดะตะปะธ. ะšั€ะธั‚ะตั€ะธะน ะฝะต ั‚ะพะปัŒะบะพ ะฒะพะทะฝะฐะณั€ะฐะถะดะฐะตั‚ ะทะฐ ะบะฐั‡ะตัั‚ะฒะพ ะฟั€ะธะฑะปะธะถะตะฝะธั, ะฝะพ ะธ ัˆั‚ั€ะฐั„ัƒะตั‚ ะทะฐ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธะต ะธะทะปะธัˆะฝะตะณะพ ะบะพะปะธั‡ะตัั‚ะฒะฐ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะผะพะดะตะปะธ. ะกั‡ะธั‚ะฐะตั‚ัั, ั‡ั‚ะพ ะฝะฐะธะปัƒั‡ัˆะตะน ะฑัƒะดะตั‚ ะผะพะดะตะปัŒ ั ะฝะฐะธะผะตะฝัŒัˆะธะผ ะทะฝะฐั‡ะตะฝะธะตะผ ะบั€ะธั‚ะตั€ะธั aic. **ะ‘ะฐะนะตัะพะฒัะบะธะน ะธะฝั„ะพั€ะผะฐั†ะธะพะฝะฝั‹ะน ะบั€ะธั‚ะตั€ะธะน** - ะบั€ะธั‚ะตั€ะธะน, ั€ะฐะทั€ะฐะฑะพั‚ะฐะฝะฝั‹ะน ะธัั…ะพะดั ะธะท ะฑะฐะตัะพะฒัะบะพะณะพ ะฟะพะดั…ะพะดะฐ, ะผะพะดะธั„ะธะบะฐั†ะธั aic. $$bic = k ln(n) - 2l$$ ะ”ะฐะฝะฝั‹ะน ะบั€ะธั‚ะตั€ะธะน ะฝะฐะปะฐะณะฐะตั‚ ะฑะพะปัŒัˆะธะน ัˆั‚ั€ะฐั„ ะฝะฐ ัƒะฒะตะปะธั‡ะตะฝะธะต ะบะพะปะธั‡ะตัั‚ะฒะฐ ะฟะฐั€ะฐะผะตั‚ั€ะพะฒ ะฟะพ ัั€ะฐะฒะฝะตะฝะธัŽ ั aic. ะŸะพัะผะพั‚ั€ะธะผ ะฝะฐ ะทะฝะฐั‡ะตะฝะธะต aic, bic ะฝะฐ ะทะฐะดะฐะฝะฝะพะน ะฒั‹ะฑะพั€ะบะต ``` print(clf.bic(X)) print(clf.aic(X)) ``` ะ”ะฐะฒะฐะนั‚ะต ั€ะฐััะผะพั‚ั€ะธะผ ะธั… ะบะฐะบ ั„ัƒะฝะบั†ะธัŽ ั‡ะธัะปะฐ ะณะฐัƒััะธะฐะฝ: ``` n_estimators = np.arange(1, 10) clfs = [GMM(n, n_iter=1000).fit(X) for n in n_estimators] bics = [clf.bic(X) for clf in clfs] aics = [clf.aic(X) for clf in clfs] plt.plot(n_estimators, bics, label='BIC') plt.plot(n_estimators, aics, label='AIC') plt.xlabel('Number of components') plt.legend(); ``` ะกัƒะดั ะฟะพ ะณั€ะฐั„ะธะบัƒ ะผะพะถะฝะพ ัะบะฐะทะฐั‚ัŒ, ั‡ั‚ะพ ะดะปั aic ะฟั€ะตะดะฟะพั‡ั‚ะธั‚ะตะปัŒะฝะตะต 4 ะบะพะผะฟะพะฝะตะฝั‚ั‹, ะฐ ะดะปั bic - 2 ะขะฐะบ ะบะฐะบ GMM ัะฒะปัะตั‚ัั Generative Model(ะฒะตั€ะพัั‚ะฝะพัั‚ะฝะฐั ะผะพะดะตะปัŒ ะดะปั ะณะตะฝะตั€ะฐั†ะธะธ ะฝะฐะฑะพั€ะฐ ะดะฐะฝะฝั‹ั…). ะก ะฟะพะผะพั‰ัŒัŽ ะดะฐะฝะฝะฝะพะน ะผะพะดะตะปะธ ะผะพะถะฝะพ ะพะฑะฝะฐั€ัƒะถะธั‚ัŒ ะฒั‹ะฑั€ะพัั‹ (ะ ะฐััั‡ะธั‚ั‹ะฒะฐะตั‚ัั ะฒะตั€ะพัั‚ะฝะพัั‚ัŒ ะบะฐะถะดะพะน ั‚ะพั‡ะบะธ ะฟะพะด ะผะพะดะตะปัŒัŽ ะธ ั‡ะตะผ ะฝะธะถะต $p(x)$, ั‚ะตะผ ะฒะตั€ะพัั‚ะฝะตะต, ั‡ั‚ะพ ะดะฐะฝะฝะฐั ั‚ะพั‡ะบะฐ ัะฒะปัะตั‚ัั ะฒั‹ะฑั€ะพัะพะผ. ะ•ัั‚ัŒ ะฟะพะดั€ะพะฑะฝะฐั ัั‚ะฐั‚ัŒั, ัะฒัะทะฐะฝะฝะฐั ั ัั‚ะพะน ั‚ะตะผะพะน - https://arxiv.org/pdf/1706.02690.pdf) ``` np.random.seed(0) # ะ”ะพะฑะฐะฒะธะผ ะบ ะฒั‹ะฑะพั€ะบะต 20 ะฒั‹ะฑั€ะพัะพะฒ true_outliers = np.sort(np.random.randint(0, len(x), 20)) y = x.copy() y[true_outliers] += 50 * np.random.randn(20) clf = GMM(4, n_iter=500, random_state=0).fit(y[:, np.newaxis]) xpdf = np.linspace(-10, 20, 1000) density_noise = np.exp(clf.score(xpdf[:, np.newaxis])) plt.hist(y, 80, normed=True, alpha=0.5) plt.plot(xpdf, density_noise, '-r') plt.xlim(-15, 30); ``` ะ”ะฐะปะตะต ะพั†ะตะฝะธะผ ะปะพะณะฐั€ะธั„ะผะธั‡ะตัะบัƒัŽ ะฒะตั€ะพัั‚ะฝะพัั‚ัŒ ะบะฐะถะดะพะน ั‚ะพั‡ะบะธ ะฟะพะด ะผะพะดะตะปัŒัŽ ``` log_likelihood = clf.score_samples(y[:, np.newaxis])[0] plt.plot(y, log_likelihood, '.k'); detected_outliers = np.where(log_likelihood < -9)[0] print("ะ’ัะต ะฒั‹ะฑั€ะพัั‹:") print(true_outliers) print("\nะžะฑะฝะฐั€ัƒะถะตะฝะฝั‹ะต ะฒั‹ะฑั€ะพัั‹:") print(detected_outliers) ``` ะšะฐะบ ะผะพะถะฝะพ ะทะฐะผะตั‚ะธั‚ัŒ, ะฐะปะณะพั€ะธั‚ะผ ะฟั€ะพะฟัƒัั‚ะธะป ะฝะตัะบะพะปัŒะบะพ ั‚ะพั‡ะตะบ (ั‚ะต, ะบะพั‚ะพั€ั‹ะต ะฝะฐั…ะพะดัั‚ัั ะฒ ัะตั€ะตะดะธะฝะต ั€ะฐัะฟั€ะตะดะตะปะตะฝะธั). ะ’ะพั‚ ะฟั€ะพะฟัƒั‰ะตะฝะฝั‹ะต ะฒั‹ะฑั€ะพัั‹: ``` set(true_outliers) - set(detected_outliers) ``` ะ˜ ะฒะพั‚ ะทะฝะฐั‡ะตะฝะธั, ะบะพั‚ะพั€ั‹ะต ะฑั‹ะปะธ ะฝะตะฒะตั€ะฝะพ ะพะฟั€ะตะดะตะปะตะฝั‹ ะบะฐะบ ะฒั‹ะฑั€ะพัั‹ ``` set(detected_outliers) - set(true_outliers) ``` ะะตะพะฑั…ะพะดะธะผะพ ะพั‚ะผะตั‚ะธั‚ัŒ, ั‡ั‚ะพ ะทะดะตััŒ ะธัะฟะพะปัŒะทัƒัŽั‚ัั ะพะดะฝะพะผะตั€ะฝั‹ะต ะดะฐะฝะฝั‹ะต, ะฝะพ GMM ั‚ะฐะบะถะต ะผะพะถะตั‚ ะดะตะปะฐั‚ัŒ ะพะฑะพะฑั‰ะตะฝะธั ะฝะฐ ะฝะตัะบะพะปัŒะบะพ ะธะทะผะตั€ะตะฝะธะน. ## ะ”ั€ัƒะณะธะต ะพั†ะตะฝะบะธ ะฟะปะพั‚ะฝะพัั‚ะธ ะ’ะฐะถะฝั‹ะผ ัั€ะตะดัั‚ะฒะพะผ ะพั†ะตะฝะบะธ ะฟะปะพั‚ะฝะพัั‚ะธ ัะฒะปัะตั‚ัั ะพั†ะตะฝะบะฐ ะฟะปะพั‚ะฝะพัั‚ะธ ัะดั€ะฐ, ั€ะตะฐะปะธะทะพะฒะฐะฝะฝะฐั ะฒ `sklearn.neighbors.KernelDensity`. ะœะพะถะฝะพ ัั‚ะพ ั€ะฐััะผะฐั‚ั€ะธะฒะฐั‚ัŒ ะบะฐะบ ะพะฑะพะฑั‰ะตะฝะธะต GMM. ``` kde = KernelDensity(0.15).fit(x[:, None]) density_kde = np.exp(kde.score_samples(xpdf[:, None])) plt.hist(x, 80, normed=True, alpha=0.5) plt.plot(xpdf, density, '-b', label='GMM') plt.plot(xpdf, density_kde, '-r', label='KDE') plt.xlim(-10, 20) plt.legend(); ``` ะ’ัะต ะพั†ะตะฝะบะธ ะฟะปะพั‚ะฝะพัั‚ะธ ะผะพะถะฝะพ ั€ะฐััะผะฐั‚ั€ะธะฒะฐั‚ัŒ ะบะฐะบ ะณะตะฝะตั€ะธั€ัƒัŽั‰ะธะต ะผะพะดะตะปะธ ะดะฐะฝะฝั‹ั…: ั‚ะพ ะตัั‚ัŒ ัั‚ะพ ะฟะพะทะฒะพะปัะตั‚ ะฟะพะฝัั‚ัŒ, ะบะฐะบ ัะพะทะดะฐะฒะฐั‚ัŒ ะฑะพะปัŒัˆะต ะดะฐะฝะฝั‹ั…, ะบะพั‚ะพั€ั‹ะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‚ ะผะพะดะตะปะธ.
github_jupyter
## Process and Run Experiment on the Infrared Dataset This notebook contains all the code needed to train PeopleNet using TAO on an infrared dataset. This notebook is required to run in the TLT Stream Analysytics container which can be found here. https://ngc.nvidia.com/catalog/containers/nvidia:tlt-streamanalytics The github readme has steps on how pull and launch the container. This notebook requires the FLIR dataset split archives to be downloaded and placed in /datasets/infrared It can be found here https://www.flir.com/oem/adas/adas-dataset-form/ This notebook takes the following steps 1) Combine and unzip the FLIR dataset 2) Convert the dataset labels into kitti labels 3) Move images and labels into a kitti directory structure 4) Use TAO Offline Augmentation to resize the images 5) Split the dataset into a test set and 20%, 40%, 60% and 80% train subsets 6) Generate TF records for test set and all training sets 7) Download pretrained PeopleNet weights 8) Train models with and without PeopleNet weights 9) Graph Results ``` dataset_home = "/datasets/infrared/" exp_home = "/tlt_exp/peoplenet_ir/" ``` ### Combine and unzip the data ``` %cd /datasets/infrared !cat FLIR_ADAS_1_3.zip* > FLIR_combined.zip !unzip FLIR_combined.zip ``` ### Convert to kitti labels ``` #Read the json data that contains truth data import json import os js_file_path = os.path.join(dataset_home, "FLIR_ADAS_1_3/train/thermal_annotations.json") js_file = open(js_file_path, "r") label_data = json.load(js_file) js_file.close() print(label_data.keys()) #Convert the json data into kitti labels import os ir_kitti = os.path.join(dataset_home, "ir_kitti") label_out = os.path.join(ir_kitti, "labels") os.makedirs(label_out, exist_ok=True) for label in label_data["annotations"]: label_name = "FLIR_" + str(label["image_id"] + 1).zfill(5) + ".txt" cat_id = label["category_id"] with open(os.path.join(label_out, label_name), "a+") as file: cat = label_data["categories"][cat_id-1]["name"] xmin = label["bbox"][0] ymin = label["bbox"][1] xmax = xmin + label["bbox"][2] ymax = ymin + label["bbox"][3] file.write(f"{cat} 0 0 0 {xmin} {ymin} {xmax} {ymax} 0 0 0 0 0 0 0\n") ``` ### Move images and labels into a kitti directory structure ``` #copy images that match with a label into the kitti image folder import shutil image_out = os.path.join(ir_kitti, "images") os.makedirs(image_out, exist_ok=True) for label in os.listdir(label_out): image_name1 = label.split(".")[0] + ".jpeg" image_name2 = label.split(".")[0] + ".jpg" shutil.copy(os.path.join(dataset_home,"FLIR_ADAS_1_3/train/thermal_8_bit", image_name1), os.path.join(image_out, image_name2)) ``` ### Use TAO Offline Augmentation to resize the images ``` #Generate the augmentation spec file img_x = 960 img_y = 544 ext = ".jpg" aug_spec = f""" # Setting up dataset config. dataset_config{{ image_path: "images" label_path: "labels" }} output_image_width: {img_x} output_image_height: {img_y} output_image_channel: 3 image_extension: "{ext}" """ aug_spec_path = os.path.join(ir_kitti, "aug_spec.txt") with open(aug_spec_path, "w+") as file: file.write(aug_spec) #Run augment command resized_output = os.path.join(dataset_home,"ir_resized") !augment -d $ir_kitti -a $aug_spec_path -o $resized_output ``` ### Split the dataset into a test set and 20%, 40%, 60% and 80% train subsets ``` def create_subset(original, name_list, output_folder): #determine image ext ext = os.path.splitext(os.listdir(os.path.join(original, "images"))[0])[1] image_out = os.path.join(output_folder, "images") label_out = os.path.join(output_folder, "labels") os.makedirs(image_out, exist_ok=True) os.makedirs(label_out, exist_ok=True) with open(name_list, "r") as ls: for line in ls: line = line.strip() shutil.copy(os.path.join(original,"images", line + ext), os.path.join(image_out, line + ext)) shutil.copy(os.path.join(original, "labels", line + ".txt"), os.path.join(label_out, line + ".txt")) subset_lists = ["test_set.txt", "train_20.txt", "train_40.txt", "train_60.txt", "train_80.txt"] for list_file in subset_lists: output_name = list_file.split(".")[0] output_path = os.path.join(dataset_home, output_name) input_list_path = os.path.join(exp_home, list_file) create_subset(resized_output, input_list_path, output_path) ``` ### Generate TF records for test set and all training sets ``` def gen_tf_spec(dataset_path): spec_str = f""" kitti_config {{ root_directory_path: "{dataset_path}" image_dir_name: "images" label_dir_name: "labels" image_extension: ".jpg" partition_mode: "random" num_partitions: 2 val_split: 20 num_shards: 10 }} """ return spec_str #Create the spec and generate tf records for all sets datasets = ["test_set", "train_20", "train_40", "train_60", "train_80"] for path in datasets: dataset_path = os.path.join(dataset_home, path) record_path = os.path.join(dataset_path, "tfrecord_spec.txt") record_output = os.path.join(dataset_path, "tfrecords/") with open(record_path, "w+") as spec: spec.write(gen_tf_spec(dataset_path)) !detectnet_v2 dataset_convert -d $record_path -o $record_output ``` ### Download pretrained PeopleNet weights ``` %cd /tlt_exp/models !ngc registry model download-version "nvidia/tlt_peoplenet:unpruned_v2.1" ``` ### Train models with and without PeopleNet weights ``` !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/peoplenet_20/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/peoplenet_20 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/peoplenet_40/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/peoplenet_40 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/peoplenet_60/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/peoplenet_60 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/peoplenet_80/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/peoplenet_80 -n "final_model" -k "tlt_encode" ``` Train without peoplenet (random starting weights) ``` !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/random_20/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/random_20 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/random_40/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/random_40 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/random_60/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/random_60 -n "final_model" -k "tlt_encode" !detectnet_v2 train -e /tlt_exp/peoplenet_ir/experiments/random_80/training_spec.txt -r /tlt_exp/peoplenet_ir/experiments/random_80 -n "final_model" -k "tlt_encode" ``` ### Graph Results ``` import matplotlib.pyplot as plt def get_map_data(filepath): x_vals_map = [] y_vals_map = [] with open(filepath, "r") as f: epoch = 0 for line in f: data = eval(line) if "cur_epoch" in data.keys(): epoch = data["cur_epoch"] elif "mean average precision" in data.keys(): mAP = data["mean average precision"] y_vals_map.append(mAP) x_vals_map.append(epoch) return x_vals_map, y_vals_map ``` PeopleNet mAP ``` f1 = "/tlt_exp/peoplenet_ir/experiments/peoplenet_20/status.json" f2 = "/tlt_exp/peoplenet_ir/experiments/peoplenet_40/status.json" f3 = "/tlt_exp/peoplenet_ir/experiments/peoplenet_60/status.json" f4 = "/tlt_exp/peoplenet_ir/experiments/peoplenet_80/status.json" files = [f4,f3,f2,f1] #modify for trainings that are complete plt.figure(figsize=(10,5)) plt.title('PeopleNet on IR Data \n mAP Over Epoch') plt.xlabel("Epoch") plt.ylabel("mAP %") plt.ylim([0,100]) plt.yticks(range(0,101,10)) plt.tick_params(right=True, labelright=True) for f in files: x,y = get_map_data(f) print(f + "\n max mAP: " + str(max(y)) + " \n") plt.plot(x,y) leg = ["x4", "x3", "x2", "x1"] plt.legend(leg, title="Dataset Size \nx1 = 1,572") plt.show() ``` Without PeopleNet mAP ``` f1 = "/tlt_exp/peoplenet_ir/experiments/random_20/status.json" f2 = "/tlt_exp/peoplenet_ir/experiments/random_40/status.json" f3 = "/tlt_exp/peoplenet_ir/experiments/random_60/status.json" f4 = "/tlt_exp/peoplenet_ir/experiments/random_80/status.json" files = [f4,f3,f2,f1] #modify for trainings that are complete plt.figure(figsize=(10,5)) plt.title('Without PeopleNet on IR Data \n mAP Over Epoch') plt.xlabel("Epoch") plt.ylabel("mAP %") plt.ylim([0,100]) plt.yticks(range(0,101,10)) plt.tick_params(right=True, labelright=True) for f in files: x,y = get_map_data(f) print(f + "\n max mAP: " + str(max(y)) + " \n") plt.plot(x,y) leg = ["x4", "x3", "x2", "x1"] plt.legend(leg, title="Dataset Size \nx1 = 1,572") plt.show() ```
github_jupyter
``` # @title Copyright & License (click to expand) # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Vertex AI Model Monitoring <table align="left"> <td> <a href="https://console.cloud.google.com/ai/platform/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/raw/master/notebooks/official/model_monitoring/model_monitoring.ipynb" <img src="https://cloud.google.com/images/products/ai/ai-solutions-icon.svg" alt="Google Cloud Notebooks"> Open in GCP Notebooks </a> </td> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/model_monitoring/model_monitoring.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Open in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/model_monitoring/model_monitoring.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> </table> ## Overview ### What is Model Monitoring? Modern applications rely on a well established set of capabilities to monitor the health of their services. Examples include: * software versioning * rigorous deployment processes * event logging * alerting/notication of situations requiring intervention * on-demand and automated diagnostic tracing * automated performance and functional testing You should be able to manage your ML services with the same degree of power and flexibility with which you can manage your applications. That's what MLOps is all about - managing ML services with the best practices Google and the broader computing industry have learned from generations of experience deploying well engineered, reliable, and scalable services. Model monitoring is only one piece of the ML Ops puzzle - it helps answer the following questions: * How well do recent service requests match the training data used to build your model? This is called **training-serving skew**. * How significantly are service requests evolving over time? This is called **drift detection**. If production traffic differs from training data, or varies substantially over time, that's likely to impact the quality of the answers your model produces. When that happens, you'd like to be alerted automatically and responsively, so that **you can anticipate problems before they affect your customer experiences or your revenue streams**. ### Objective In this notebook, you will learn how to... * deploy a pre-trained model * configure model monitoring * generate some artificial traffic * understand how to interpret the statistics, visualizations, other data reported by the model monitoring feature ### Costs This tutorial uses billable components of Google Cloud: * Vertext AI * BigQuery Learn about [Vertext AI pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage pricing](https://cloud.google.com/storage/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage. ### The example model The model you'll use in this notebook is based on [this blog post](https://cloud.google.com/blog/topics/developers-practitioners/churn-prediction-game-developers-using-google-analytics-4-ga4-and-bigquery-ml). The idea behind this model is that your company has extensive log data describing how your game users have interacted with the site. The raw data contains the following categories of information: - identity - unique player identitity numbers - demographic features - information about the player, such as the geographic region in which a player is located - behavioral features - counts of the number of times a player has triggered certain game events, such as reaching a new level - churn propensity - this is the label or target feature, it provides an estimated probability that this player will churn, i.e. stop being an active player. The blog article referenced above explains how to use BigQuery to store the raw data, pre-process it for use in machine learning, and train a model. Because this notebook focuses on model monitoring, rather than training models, you're going to reuse a pre-trained version of this model, which has been exported to Google Cloud Storage. In the next section, you will setup your environment and import this model into your own project. ## Before you begin ### Setup your dependencies ``` import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" import os import sys import IPython assert sys.version_info.major == 3, "This notebook requires Python 3." # Install Python package dependencies. print("Installing TensorFlow 2.4.1 and TensorFlow Data Validation (TFDV)") ! pip3 install {USER_FLAG} --quiet --upgrade tensorflow==2.4.1 tensorflow_data_validation[visualization] ! pip3 install {USER_FLAG} --quiet --upgrade google-api-python-client google-auth-oauthlib google-auth-httplib2 oauth2client requests ! pip3 install {USER_FLAG} --quiet --upgrade google-cloud-aiplatform ! pip3 install {USER_FLAG} --quiet --upgrade google-cloud-storage==1.32.0 # Automatically restart kernel after installing new packages. if not os.getenv("IS_TESTING"): print("Restarting kernel...") app = IPython.Application.instance() app.kernel.do_shutdown(True) print("Done.") import os import random import sys import time # Import required packages. import numpy as np ``` ### Set up your Google Cloud project **The following steps are required, regardless of your notebook environment.** 1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs. 1. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project). 1. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk). 1. You'll use the *gcloud* command throughout this notebook. In the following cell, enter your project name and run the cell to authenticate yourself with the Google Cloud and initialize your *gcloud* configuration settings. **For this lab, we're going to use region us-central1 for all our resources (BigQuery training data, Cloud Storage bucket, model and endpoint locations, etc.). Those resources can be deployed in other regions, as long as they're consistently co-located, but we're going to use one fixed region to keep things as simple and error free as possible.** ``` PROJECT_ID = "[your-project-id]" # @param {type:"string"} REGION = "us-central1" SUFFIX = "aiplatform.googleapis.com" API_ENDPOINT = f"{REGION}-{SUFFIX}" PREDICT_API_ENDPOINT = f"{REGION}-prediction-{SUFFIX}" if os.getenv("IS_TESTING"): !gcloud --quiet components install beta !gcloud --quiet components update !gcloud config set project $PROJECT_ID !gcloud config set ai/region $REGION ``` ### Login to your Google Cloud account and enable AI services ``` # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # If on Google Cloud Notebooks, then don't execute this code if not IS_GOOGLE_CLOUD_NOTEBOOK: if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' !gcloud services enable aiplatform.googleapis.com ``` ### Define some helper functions Run the following cell to define some utility functions used throughout this notebook. Although these functions are not critical to understand the main concepts, feel free to expand the cell if you're curious or want to dive deeper into how some of your API requests are made. ``` # @title Utility functions import copy import os from google.cloud.aiplatform_v1beta1.services.endpoint_service import \ EndpointServiceClient from google.cloud.aiplatform_v1beta1.services.job_service import \ JobServiceClient from google.cloud.aiplatform_v1beta1.services.prediction_service import \ PredictionServiceClient from google.cloud.aiplatform_v1beta1.types.io import BigQuerySource from google.cloud.aiplatform_v1beta1.types.model_deployment_monitoring_job import ( ModelDeploymentMonitoringJob, ModelDeploymentMonitoringObjectiveConfig, ModelDeploymentMonitoringScheduleConfig) from google.cloud.aiplatform_v1beta1.types.model_monitoring import ( ModelMonitoringAlertConfig, ModelMonitoringObjectiveConfig, SamplingStrategy, ThresholdConfig) from google.cloud.aiplatform_v1beta1.types.prediction_service import \ PredictRequest from google.protobuf import json_format from google.protobuf.duration_pb2 import Duration from google.protobuf.struct_pb2 import Value DEFAULT_THRESHOLD_VALUE = 0.001 def create_monitoring_job(objective_configs): # Create sampling configuration. random_sampling = SamplingStrategy.RandomSampleConfig(sample_rate=LOG_SAMPLE_RATE) sampling_config = SamplingStrategy(random_sample_config=random_sampling) # Create schedule configuration. duration = Duration(seconds=MONITOR_INTERVAL) schedule_config = ModelDeploymentMonitoringScheduleConfig(monitor_interval=duration) # Create alerting configuration. emails = [USER_EMAIL] email_config = ModelMonitoringAlertConfig.EmailAlertConfig(user_emails=emails) alerting_config = ModelMonitoringAlertConfig(email_alert_config=email_config) # Create the monitoring job. endpoint = f"projects/{PROJECT_ID}/locations/{REGION}/endpoints/{ENDPOINT_ID}" predict_schema = "" analysis_schema = "" job = ModelDeploymentMonitoringJob( display_name=JOB_NAME, endpoint=endpoint, model_deployment_monitoring_objective_configs=objective_configs, logging_sampling_strategy=sampling_config, model_deployment_monitoring_schedule_config=schedule_config, model_monitoring_alert_config=alerting_config, predict_instance_schema_uri=predict_schema, analysis_instance_schema_uri=analysis_schema, ) options = dict(api_endpoint=API_ENDPOINT) client = JobServiceClient(client_options=options) parent = f"projects/{PROJECT_ID}/locations/{REGION}" response = client.create_model_deployment_monitoring_job( parent=parent, model_deployment_monitoring_job=job ) print("Created monitoring job:") print(response) return response def get_thresholds(default_thresholds, custom_thresholds): thresholds = {} default_threshold = ThresholdConfig(value=DEFAULT_THRESHOLD_VALUE) for feature in default_thresholds.split(","): feature = feature.strip() thresholds[feature] = default_threshold for custom_threshold in custom_thresholds.split(","): pair = custom_threshold.split(":") if len(pair) != 2: print(f"Invalid custom skew threshold: {custom_threshold}") return feature, value = pair thresholds[feature] = ThresholdConfig(value=float(value)) return thresholds def get_deployed_model_ids(endpoint_id): client_options = dict(api_endpoint=API_ENDPOINT) client = EndpointServiceClient(client_options=client_options) parent = f"projects/{PROJECT_ID}/locations/{REGION}" response = client.get_endpoint(name=f"{parent}/endpoints/{endpoint_id}") model_ids = [] for model in response.deployed_models: model_ids.append(model.id) return model_ids def set_objectives(model_ids, objective_template): # Use the same objective config for all models. objective_configs = [] for model_id in model_ids: objective_config = copy.deepcopy(objective_template) objective_config.deployed_model_id = model_id objective_configs.append(objective_config) return objective_configs def send_predict_request(endpoint, input): client_options = {"api_endpoint": PREDICT_API_ENDPOINT} client = PredictionServiceClient(client_options=client_options) params = {} params = json_format.ParseDict(params, Value()) request = PredictRequest(endpoint=endpoint, parameters=params) inputs = [json_format.ParseDict(input, Value())] request.instances.extend(inputs) response = client.predict(request) return response def list_monitoring_jobs(): client_options = dict(api_endpoint=API_ENDPOINT) parent = f"projects/{PROJECT_ID}/locations/us-central1" client = JobServiceClient(client_options=client_options) response = client.list_model_deployment_monitoring_jobs(parent=parent) print(response) def pause_monitoring_job(job): client_options = dict(api_endpoint=API_ENDPOINT) client = JobServiceClient(client_options=client_options) response = client.pause_model_deployment_monitoring_job(name=job) print(response) def delete_monitoring_job(job): client_options = dict(api_endpoint=API_ENDPOINT) client = JobServiceClient(client_options=client_options) response = client.delete_model_deployment_monitoring_job(name=job) print(response) # Sampling distributions for categorical features... DAYOFWEEK = {1: 1040, 2: 1223, 3: 1352, 4: 1217, 5: 1078, 6: 1011, 7: 1110} LANGUAGE = { "en-us": 4807, "en-gb": 678, "ja-jp": 419, "en-au": 310, "en-ca": 299, "de-de": 147, "en-in": 130, "en": 127, "fr-fr": 94, "pt-br": 81, "es-us": 65, "zh-tw": 64, "zh-hans-cn": 55, "es-mx": 53, "nl-nl": 37, "fr-ca": 34, "en-za": 29, "vi-vn": 29, "en-nz": 29, "es-es": 25, } OS = {"IOS": 3980, "ANDROID": 3798, "null": 253} MONTH = {6: 3125, 7: 1838, 8: 1276, 9: 1718, 10: 74} COUNTRY = { "United States": 4395, "India": 486, "Japan": 450, "Canada": 354, "Australia": 327, "United Kingdom": 303, "Germany": 144, "Mexico": 102, "France": 97, "Brazil": 93, "Taiwan": 72, "China": 65, "Saudi Arabia": 49, "Pakistan": 48, "Egypt": 46, "Netherlands": 45, "Vietnam": 42, "Philippines": 39, "South Africa": 38, } # Means and standard deviations for numerical features... MEAN_SD = { "julianday": (204.6, 34.7), "cnt_user_engagement": (30.8, 53.2), "cnt_level_start_quickplay": (7.8, 28.9), "cnt_level_end_quickplay": (5.0, 16.4), "cnt_level_complete_quickplay": (2.1, 9.9), "cnt_level_reset_quickplay": (2.0, 19.6), "cnt_post_score": (4.9, 13.8), "cnt_spend_virtual_currency": (0.4, 1.8), "cnt_ad_reward": (0.1, 0.6), "cnt_challenge_a_friend": (0.0, 0.3), "cnt_completed_5_levels": (0.1, 0.4), "cnt_use_extra_steps": (0.4, 1.7), } DEFAULT_INPUT = { "cnt_ad_reward": 0, "cnt_challenge_a_friend": 0, "cnt_completed_5_levels": 1, "cnt_level_complete_quickplay": 3, "cnt_level_end_quickplay": 5, "cnt_level_reset_quickplay": 2, "cnt_level_start_quickplay": 6, "cnt_post_score": 34, "cnt_spend_virtual_currency": 0, "cnt_use_extra_steps": 0, "cnt_user_engagement": 120, "country": "Denmark", "dayofweek": 3, "julianday": 254, "language": "da-dk", "month": 9, "operating_system": "IOS", "user_pseudo_id": "104B0770BAE16E8B53DF330C95881893", } ``` ## Import your model The churn propensity model you'll be using in this notebook has been trained in BigQuery ML and exported to a Google Cloud Storage bucket. This illustrates how you can easily export a trained model and move a model from one cloud service to another. Run the next cell to import this model into your project. **If you've already imported your model, you can skip this step.** ``` MODEL_NAME = "churn" IMAGE = "us-docker.pkg.dev/cloud-aiplatform/prediction/tf2-cpu.2-4:latest" ARTIFACT = "gs://mco-mm/churn" output = !gcloud --quiet beta ai models upload --container-image-uri=$IMAGE --artifact-uri=$ARTIFACT --display-name=$MODEL_NAME --format="value(model)" print("model output: ", output) MODEL_ID = output[1].split("/")[-1] print(f"Model {MODEL_NAME}/{MODEL_ID} created.") ``` ## Deploy your endpoint Now that you've imported your model into your project, you need to create an endpoint to serve your model. An endpoint can be thought of as a channel through which your model provides prediction services. Once established, you'll be able to make prediction requests on your model via the public internet. Your endpoint is also serverless, in the sense that Google ensures high availability by reducing single points of failure, and scalability by dynamically allocating resources to meet the demand for your service. In this way, you are able to focus on your model quality, and freed from adminstrative and infrastructure concerns. Run the next cell to deploy your model to an endpoint. **This will take about ten minutes to complete. If you've already deployed a model to an endpoint, you can reuse your endpoint by running the cell after the next one.** ``` ENDPOINT_NAME = "churn" output = !gcloud --quiet beta ai endpoints create --display-name=$ENDPOINT_NAME --format="value(name)" print("endpoint output: ", output) ENDPOINT = output[-1] ENDPOINT_ID = ENDPOINT.split("/")[-1] output = !gcloud --quiet beta ai endpoints deploy-model $ENDPOINT_ID --display-name=$ENDPOINT_NAME --model=$MODEL_ID --traffic-split="0=100" DEPLOYED_MODEL_ID = output[1].split()[-1][:-1] print( f"Model {MODEL_NAME}/{MODEL_ID}/{DEPLOYED_MODEL_ID} deployed to Endpoint {ENDPOINT_NAME}/{ENDPOINT_ID}/{ENDPOINT}." ) # @title Run this cell only if you want to reuse an existing endpoint. if not os.getenv("IS_TESTING"): ENDPOINT_ID = "" # @param {type:"string"} ENDPOINT = f"projects/mco-mm/locations/us-central1/endpoints/{ENDPOINT_ID}" ``` ## Run a prediction test Now that you have imported a model and deployed that model to an endpoint, you are ready to verify that it's working. Run the next cell to send a test prediction request. If everything works as expected, you should receive a response encoded in a text representation called JSON. **Try this now by running the next cell and examine the results.** ``` import pprint as pp print(ENDPOINT) print("request:") pp.pprint(DEFAULT_INPUT) try: resp = send_predict_request(ENDPOINT, DEFAULT_INPUT) print("response") pp.pprint(resp) except Exception: print("prediction request failed") ``` Taking a closer look at the results, we see the following elements: - **churned_values** - a set of possible values (0 and 1) for the target field - **churned_probs** - a corresponding set of probabilities for each possible target field value (5x10^-40 and 1.0, respectively) - **predicted_churn** - based on the probabilities, the predicted value of the target field (1) This response encodes the model's prediction in a format that is readily digestible by software, which makes this service ideal for automated use by an application. ## Start your monitoring job Now that you've created an endpoint to serve prediction requests on your model, you're ready to start a monitoring job to keep an eye on model quality and to alert you if and when input begins to deviate in way that may impact your model's prediction quality. In this section, you will configure and create a model monitoring job based on the churn propensity model you imported from BigQuery ML. ### Configure the following fields: 1. Log sample rate - Your prediction requests and responses are logged to BigQuery tables, which are automatically created when you create a monitoring job. This parameter specifies the desired logging frequency for those tables. 1. Monitor interval - the time window over which to analyze your data and report anomalies. The minimum window is one hour (3600 seconds). 1. Target field - the prediction target column name in training dataset. 1. Skew detection threshold - the skew threshold for each feature you want to monitor. 1. Prediction drift threshold - the drift threshold for each feature you want to monitor. ``` USER_EMAIL = "" # @param {type:"string"} JOB_NAME = "churn" # Sampling rate (optional, default=.8) LOG_SAMPLE_RATE = 0.8 # @param {type:"number"} # Monitoring Interval in seconds (optional, default=3600). MONITOR_INTERVAL = 3600 # @param {type:"number"} # URI to training dataset. DATASET_BQ_URI = "bq://mco-mm.bqmlga4.train" # @param {type:"string"} # Prediction target column name in training dataset. TARGET = "churned" # Skew and drift thresholds. SKEW_DEFAULT_THRESHOLDS = "country,language" # @param {type:"string"} SKEW_CUSTOM_THRESHOLDS = "cnt_user_engagement:.5" # @param {type:"string"} DRIFT_DEFAULT_THRESHOLDS = "country,language" # @param {type:"string"} DRIFT_CUSTOM_THRESHOLDS = "cnt_user_engagement:.5" # @param {type:"string"} ``` ### Create your monitoring job The following code uses the Google Python client library to translate your configuration settings into a programmatic request to start a model monitoring job. Instantiating a monitoring job can take some time. If everything looks good with your request, you'll get a successful API response. Then, you'll need to check your email to receive a notification that the job is running. ``` skew_thresholds = get_thresholds(SKEW_DEFAULT_THRESHOLDS, SKEW_CUSTOM_THRESHOLDS) drift_thresholds = get_thresholds(DRIFT_DEFAULT_THRESHOLDS, DRIFT_CUSTOM_THRESHOLDS) skew_config = ModelMonitoringObjectiveConfig.TrainingPredictionSkewDetectionConfig( skew_thresholds=skew_thresholds ) drift_config = ModelMonitoringObjectiveConfig.PredictionDriftDetectionConfig( drift_thresholds=drift_thresholds ) training_dataset = ModelMonitoringObjectiveConfig.TrainingDataset(target_field=TARGET) training_dataset.bigquery_source = BigQuerySource(input_uri=DATASET_BQ_URI) objective_config = ModelMonitoringObjectiveConfig( training_dataset=training_dataset, training_prediction_skew_detection_config=skew_config, prediction_drift_detection_config=drift_config, ) model_ids = get_deployed_model_ids(ENDPOINT_ID) objective_template = ModelDeploymentMonitoringObjectiveConfig( objective_config=objective_config ) objective_configs = set_objectives(model_ids, objective_template) monitoring_job = create_monitoring_job(objective_configs) # Run a prediction request to generate schema, if necessary. try: _ = send_predict_request(ENDPOINT, DEFAULT_INPUT) print("prediction succeeded") except Exception: print("prediction failed") ``` After a minute or two, you should receive email at the address you configured above for USER_EMAIL. This email confirms successful deployment of your monitoring job. Here's a sample of what this email might look like: <br> <br> <img src="https://storage.googleapis.com/mco-general/img/mm6.png" /> <br> As your monitoring job collects data, measurements are stored in Google Cloud Storage and you are free to examine your data at any time. The circled path in the image above specifies the location of your measurements in Google Cloud Storage. Run the following cell to take a look at your measurements in Cloud Storage. ``` !gsutil ls gs://cloud-ai-platform-fdfb4810-148b-4c86-903c-dbdff879f6e1/*/* ``` You will notice the following components in these Cloud Storage paths: - **cloud-ai-platform-..** - This is a bucket created for you and assigned to capture your service's prediction data. Each monitoring job you create will trigger creation of a new folder in this bucket. - **[model_monitoring|instance_schemas]/job-..** - This is your unique monitoring job number, which you can see above in both the response to your job creation requesst and the email notification. - **instance_schemas/job-../analysis** - This is the monitoring jobs understanding and encoding of your training data's schema (field names, types, etc.). - **instance_schemas/job-../predict** - This is the first prediction made to your model after the current monitoring job was enabled. - **model_monitoring/job-../serving** - This folder is used to record data relevant to drift calculations. It contains measurement summaries for every hour your model serves traffic. - **model_monitoring/job-../training** - This folder is used to record data relevant to training-serving skew calculations. It contains an ongoing summary of prediction data relative to training data. ### You can create monitoring jobs with other user interfaces In the previous cells, you created a monitoring job using the Python client library. You can also use the *gcloud* command line tool to create a model monitoring job and, in the near future, you will be able to use the Cloud Console, as well for this function. ## Generate test data to trigger alerting Now you are ready to test the monitoring function. Run the following cell, which will generate fabricated test predictions designed to trigger the thresholds you specified above. It takes about five minutes to run this cell and at least an hour to assess and report anamolies in skew or drift so after running this cell, feel free to proceed with the notebook and you'll see how to examine the resulting alert later. ``` def random_uid(): digits = [str(i) for i in range(10)] + ["A", "B", "C", "D", "E", "F"] return "".join(random.choices(digits, k=32)) def monitoring_test(count, sleep, perturb_num={}, perturb_cat={}): # Use random sampling and mean/sd with gaussian distribution to model # training data. Then modify sampling distros for two categorical features # and mean/sd for two numerical features. mean_sd = MEAN_SD.copy() country = COUNTRY.copy() for k, (mean_fn, sd_fn) in perturb_num.items(): orig_mean, orig_sd = MEAN_SD[k] mean_sd[k] = (mean_fn(orig_mean), sd_fn(orig_sd)) for k, v in perturb_cat.items(): country[k] = v for i in range(0, count): input = DEFAULT_INPUT.copy() input["user_pseudo_id"] = str(random_uid()) input["country"] = random.choices([*country], list(country.values()))[0] input["dayofweek"] = random.choices([*DAYOFWEEK], list(DAYOFWEEK.values()))[0] input["language"] = str(random.choices([*LANGUAGE], list(LANGUAGE.values()))[0]) input["operating_system"] = str(random.choices([*OS], list(OS.values()))[0]) input["month"] = random.choices([*MONTH], list(MONTH.values()))[0] for key, (mean, sd) in mean_sd.items(): sample_val = round(float(np.random.normal(mean, sd, 1))) val = max(sample_val, 0) input[key] = val print(f"Sending prediction {i}") try: send_predict_request(ENDPOINT, input) except Exception: print("prediction request failed") time.sleep(sleep) print("Test Completed.") test_time = 300 tests_per_sec = 1 sleep_time = 1 / tests_per_sec iterations = test_time * tests_per_sec perturb_num = {"cnt_user_engagement": (lambda x: x * 3, lambda x: x / 3)} perturb_cat = {"Japan": max(COUNTRY.values()) * 2} monitoring_test(iterations, sleep_time, perturb_num, perturb_cat) ``` ## Interpret your results While waiting for your results, which, as noted, may take up to an hour, you can read ahead to get sense of the alerting experience. ### Here's what a sample email alert looks like... <img src="https://storage.googleapis.com/mco-general/img/mm7.png" /> This email is warning you that the *cnt_user_engagement*, *country* and *language* feature values seen in production have skewed above your threshold between training and serving your model. It's also telling you that the *cnt_user_engagement* feature value is drifting significantly over time, again, as per your threshold specification. ### Monitoring results in the Cloud Console You can examine your model monitoring data from the Cloud Console. Below is a screenshot of those capabilities. #### Monitoring Status <img src="https://storage.googleapis.com/mco-general/img/mm1.png" /> #### Monitoring Alerts <img src="https://storage.googleapis.com/mco-general/img/mm2.png" /> ## Clean up To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: ``` # Delete endpoint resource !gcloud ai endpoints delete $ENDPOINT_NAME --quiet # Delete model resource !gcloud ai models delete $MODEL_NAME --quiet ``` ## Learn more about model monitoring **Congratulations!** You've now learned what model monitoring is, how to configure and enable it, and how to find and interpret the results. Check out the following resources to learn more about model monitoring and ML Ops. - [TensorFlow Data Validation](https://www.tensorflow.org/tfx/guide/tfdv) - [Data Understanding, Validation, and Monitoring At Scale](https://blog.tensorflow.org/2018/09/introducing-tensorflow-data-validation.html) - [Vertex Product Documentation](https://cloud.google.com/vertex) - [Model Monitoring Reference Docs](https://cloud.google.com/vertex/docs/reference) - [Model Monitoring blog article](https://cloud.google.com/blog/topics/developers-practitioners/monitor-models-training-serving-skew-vertex-ai)
github_jupyter
# Setup On some systems, this cell needs to be run twice to get the correct settings of matplotlib. ``` from rrk import * from scipy import interpolate import time import scipy as sp plt.rc("font", family="serif", size=16.) ``` # Harmonic Oscillator ``` def f(w): q = w[0] p = w[1] return np.array([p, -q]) def eta(w): q = w[0] p = w[1] return 0.5*p*p + 0.5*q*q def d_eta(w): fw = f(w) dq = fw[0] dp = fw[1] return np.array([-dp, dq]) def symplectic_euler(dt, w0, t_final): w = np.array(w0) # current value of the unknown function t = 0 # current time ww = np.zeros([np.size(w0), 1]) # values at each time step ww[:,0] = w.copy() tt = np.zeros(1) # time points for ww tt[0] = t while t < t_final and not np.isclose(t, t_final): if t + dt > t_final: dt = t_final - t qold = w[0] pold = w[1] qnew = qold + dt * pold pnew = pold + dt * (-qnew) w = np.array([qnew, pnew]) t += dt tt = np.append(tt, t) ww = np.append(ww, np.reshape(w.copy(), (len(w), 1)), axis=1) return tt, ww t_final = 50.0 t_final_values = np.linspace(0., t_final, 11)[1:] erk = rk4; dt = 0.25 u0 = np.array([1., 0.0]) num_points = 200 * 2 np.random.seed(42) radius = np.sqrt(np.random.uniform(0, 0.001**2, num_points)) angle = np.random.uniform(0, 2*np.pi, num_points) u0_values = np.zeros((num_points, 2)) u0_values[:,0] = radius * np.cos(angle) + u0[0] u0_values[:,1] = radius * np.sin(angle) + u0[1] u0_hull = sp.spatial.ConvexHull(u0_values) vol0 = u0_hull.volume def phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed): u_values = np.zeros_like(u0_values) for i in np.arange(num_points): # Find the last output time that is less than t_final start_ind = np.nonzero(np.where(tts[i]<t_final,1,0))[0].max() if relaxed == None: tt, uu = symplectic_euler(dt, uus[i][:,start_ind], t_final-tts[i][start_ind]) else: # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, uus[i][:,start_ind], t_final-tts[i][start_ind], # relaxed=relaxed, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, uus[i][:,start_ind], t_final-tts[i][start_ind], relaxed=relaxed, newdt=True, gammatol=0.5) u_values[i,:] = uu[:,-1] u_hull = sp.spatial.ConvexHull(u_values) rel_change = (u_hull.volume - vol0) / vol0 return rel_change def precompute_trajectories(erk, dt, t_final): # Precompute the trajectories. Later we'll "interpolate" from these results. tts = [] uus = [] for i in np.arange(num_points): # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, # relaxed=False, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, relaxed=False, newdt=True, gammatol=0.5) tts.append(tt) uus.append(uu) tts_r = [] uus_r = [] for i in np.arange(num_points): # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, # relaxed=True, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, relaxed=True, newdt=True, gammatol=0.5) tts_r.append(tt) uus_r.append(uu) tts_s = [] uus_s = [] for i in np.arange(num_points): tt, uu = symplectic_euler(dt, u0_values[i,:], t_final) tts_s.append(tt) uus_s.append(uu) return tts, uus, tts_r, uus_r, tts_s, uus_s tts, uus, tts_r, uus_r, tts_s, uus_s = precompute_trajectories(erk, dt, t_final) baseline_rel_change = np.zeros_like(t_final_values) relaxation_rel_change = np.zeros_like(t_final_values) symplectic_rel_change = np.zeros_like(t_final_values) for (t_final_idx, t_final) in enumerate(t_final_values): baseline_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed=False) relaxation_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_r, uus_r, relaxed=True) symplectic_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_s, uus_s, relaxed=None) plt.close("all") fig, ax = plt.subplots(1, 1) ax.set_prop_cycle(marker_cycler) plt.plot(t_final_values, baseline_rel_change, label="Baseline") plt.plot(t_final_values, relaxation_rel_change, label="Relaxation") plt.plot(t_final_values, symplectic_rel_change, label="Symplectic Euler") plt.xlabel(r"$t$") plt.ylabel("Rel. Change of Phase Space Vol.") plt.legend(loc="best") plt.savefig("../figures/phase_space_volume__RK4__linear_osc.pdf", bbox_inches="tight") print(np.linalg.lstsq(t_final_values.reshape(-1,1), baseline_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), relaxation_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), symplectic_rel_change, rcond=None)) print(vol0) fig, ax = plt.subplots(1, 1) ax.set_aspect("equal"); xlim = plt.xlim(); ylim = plt.ylim() time_tmp = time.time() for idx in np.arange(len(uus)): plt.scatter(uus[idx][0,-1], uus[idx][1,-1], color="blue", marker=".") fig, ax = plt.subplots(1, 1) ax.set_aspect("equal"); xlim = plt.xlim(); ylim = plt.ylim() time_tmp = time.time() for idx in np.arange(len(uus_r)): plt.scatter(uus_r[idx][0,-1], uus_r[idx][1,-1], color="blue", marker=".") fig, ax = plt.subplots(1, 1) ax.set_aspect("equal"); xlim = plt.xlim(); ylim = plt.ylim() time_tmp = time.time() for idx in np.arange(len(uus_s)): plt.scatter(uus_s[idx][0,-1], uus_s[idx][1,-1], color="blue", marker=".") ``` # Two Harmonic Oscillators ``` def f(w): q1 = w[0] q2 = w[1] p1 = w[2] p2 = w[3] return np.array([p1, p2, -q1, -q2]) def eta(w): q1 = w[0] q2 = w[1] p1 = w[2] p2 = w[3] return 0.5 * (p1*p1 + p2*p2 + q1*q1 + q2*q2) def d_eta(w): fw = f(w) dq1 = fw[0] dq2 = fw[1] dp1 = fw[2] dp2 = fw[3] return np.array([-dp1, -dp2, dq1, dq2]) def symplectic_euler(dt, w0, t_final): w = np.array(w0) # current value of the unknown function t = 0 # current time ww = np.zeros([np.size(w0), 1]) # values at each time step ww[:,0] = w.copy() tt = np.zeros(1) # time points for ww tt[0] = t while t < t_final and not np.isclose(t, t_final): if t + dt > t_final: dt = t_final - t q1old = w[0] q2old = w[1] p1old = w[2] p2old = w[3] q1new = q1old + dt * p1old q2new = q2old + dt * p2old p1new = p1old + dt * (-q1new) p2new = p2old + dt * (-q2new) w = np.array([q1new, q2new, p1new, p2new]) t += dt tt = np.append(tt, t) ww = np.append(ww, np.reshape(w.copy(), (len(w), 1)), axis=1) return tt, ww t_final = 50.0 t_final_values = np.linspace(0., t_final, 11)[1:] erk = rk4; dt = 0.25 u0 = np.array([1.0, 0.0, 0.5, 0.5]) num_points = 100 * 1 np.random.seed(42) u0_values = np.zeros((num_points, 4)) u0_values[:,0] = u0[0] + np.random.uniform(-0.0005, 0.0005, num_points) u0_values[:,1] = u0[1] + np.random.uniform(-0.0005, 0.0005, num_points) u0_values[:,2] = u0[2] + np.random.uniform(-0.0005, 0.0005, num_points) u0_values[:,3] = u0[3] + np.random.uniform(-0.0005, 0.0005, num_points) u0_hull = sp.spatial.ConvexHull(u0_values) vol0 = u0_hull.volume def phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed): u_values = np.zeros_like(u0_values) for i in np.arange(num_points): # Find the last output time that is less than t_final start_ind = np.nonzero(np.where(tts[i]<t_final,1,0))[0].max() if relaxed == None: tt, uu = symplectic_euler(dt, uus[i][:,start_ind], t_final-tts[i][start_ind]) else: # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, uus[i][:,start_ind], t_final-tts[i][start_ind], # relaxed=relaxed, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, uus[i][:,start_ind], t_final-tts[i][start_ind], relaxed=relaxed, newdt=True, gammatol=0.5) u_values[i,:] = uu[:,-1] u_hull = sp.spatial.ConvexHull(u_values) rel_change = (u_hull.volume - vol0) / vol0 return rel_change def precompute_trajectories(erk, dt, t_final): # Precompute the trajectories. Later we'll "interpolate" from these results. tts = [] uus = [] for i in np.arange(num_points): # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, # relaxed=False, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, relaxed=False, newdt=True, gammatol=0.5) tts.append(tt) uus.append(uu) tts_r = [] uus_r = [] for i in np.arange(num_points): # tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, # relaxed=True, method="brentq", newdt=True) tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, relaxed=True, newdt=True, gammatol=0.5) tts_r.append(tt) uus_r.append(uu) tts_s = [] uus_s = [] for i in np.arange(num_points): tt, uu = symplectic_euler(dt, u0_values[i,:], t_final) tts_s.append(tt) uus_s.append(uu) return tts, uus, tts_r, uus_r, tts_s, uus_s tts, uus, tts_r, uus_r, tts_s, uus_s = precompute_trajectories(erk, dt, t_final) baseline_rel_change = np.zeros_like(t_final_values) relaxation_rel_change = np.zeros_like(t_final_values) symplectic_rel_change = np.zeros_like(t_final_values) for (t_final_idx, t_final) in enumerate(t_final_values): baseline_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed=False) relaxation_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_r, uus_r, relaxed=True) symplectic_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_s, uus_s, relaxed=None) plt.close("all") fig, ax = plt.subplots(1, 1) ax.set_prop_cycle(marker_cycler) plt.plot(t_final_values, baseline_rel_change, label="Baseline") plt.plot(t_final_values, relaxation_rel_change, label="Relaxation") plt.plot(t_final_values, symplectic_rel_change, label="Symplectic Euler") plt.xlabel(r"$t$") plt.ylabel("Rel. Change of Phase Space Vol.") plt.legend(loc="best") plt.savefig("../figures/phase_space_volume__RK4__linear_osc_2.pdf", bbox_inches="tight") print(np.linalg.lstsq(t_final_values.reshape(-1,1), baseline_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), relaxation_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), symplectic_rel_change, rcond=None)) print(vol0) fig, ax = plt.subplots(1, 2) ax[0].set_aspect("equal") for idx in np.arange(len(uus)): ax[0].scatter(uus[idx][0,-1], uus[idx][2,-1], color="black", marker=".") ax[0].set_xlabel(r"$q_1$") ax[0].set_ylabel(r"$p_1$") ax[1].set_aspect("equal") for idx in np.arange(len(uus)): ax[1].scatter(uus[idx][1,-1], uus[idx][3,-1], color="black", marker=".") ax[1].set_xlabel(r"$q_2$") ax[1].set_ylabel(r"$p_2$") plt.tight_layout() plt.suptitle("Baseline") fig, ax = plt.subplots(1, 2) ax[0].set_aspect("equal") for idx in np.arange(len(uus_r)): ax[0].scatter(uus_r[idx][0,-1], uus_r[idx][2,-1], color="black", marker=".") ax[0].set_xlabel(r"$q_1$") ax[0].set_ylabel(r"$p_1$") ax[1].set_aspect("equal") for idx in np.arange(len(uus_r)): ax[1].scatter(uus_r[idx][1,-1], uus_r[idx][3,-1], color="black", marker=".") ax[1].set_xlabel(r"$q_2$") ax[1].set_ylabel(r"$p_2$") plt.tight_layout() plt.suptitle("Relaxation") fig, ax = plt.subplots(1, 2) ax[0].set_aspect("equal") for idx in np.arange(len(uus_s)): ax[0].scatter(uus_s[idx][0,-1], uus_s[idx][2,-1], color="black", marker=".") ax[0].set_xlabel(r"$q_1$") ax[0].set_ylabel(r"$p_1$") ax[0].set_xlim( np.min([uus_s[idx][0,-1] for idx in np.arange(len(uus_s))]), np.max([uus_s[idx][0,-1] for idx in np.arange(len(uus_s))])) ax[0].set_ylim( np.min([uus_s[idx][2,-1] for idx in np.arange(len(uus_s))]), np.max([uus_s[idx][2,-1] for idx in np.arange(len(uus_s))])) ax[1].set_aspect("equal") for idx in np.arange(len(uus_s)): ax[1].scatter(uus_s[idx][1,-1], uus_s[idx][3,-1], color="black", marker=".") ax[1].set_xlabel(r"$q_2$") ax[1].set_ylabel(r"$p_2$") ax[1].set_xlim( np.min([uus_s[idx][1,-1] for idx in np.arange(len(uus_s))]), np.max([uus_s[idx][1,-1] for idx in np.arange(len(uus_s))])) ax[1].set_ylim( np.min([uus_s[idx][3,-1] for idx in np.arange(len(uus_s))]), np.max([uus_s[idx][3,-1] for idx in np.arange(len(uus_s))])) plt.tight_layout() plt.suptitle("Symplectic Euler") ``` # Undamped Duffing Oscillator ``` def f(w): q = w[0] p = w[1] return np.array([p, q - q*q*q]) def eta(w): q = w[0] p = w[1] return 0.5*p*p - 0.5*q*q + 0.25*q*q*q*q def d_eta(w): fw = f(w) dq = fw[0] dp = fw[1] return np.array([-dp, dq]) def symplectic_euler(dt, w0, t_final): w = np.array(w0) # current value of the unknown function t = 0 # current time ww = np.zeros([np.size(w0), 1]) # values at each time step ww[:,0] = w.copy() tt = np.zeros(1) # time points for ww tt[0] = t while t < t_final and not np.isclose(t, t_final): if t + dt > t_final: dt = t_final - t qold = w[0] pold = w[1] qnew = qold + dt * pold pnew = pold + dt * (qnew - qnew*qnew*qnew) w = np.array([qnew, pnew]) t += dt tt = np.append(tt, t) ww = np.append(ww, np.reshape(w.copy(), (len(w), 1)), axis=1) return tt, ww t_final = 200 t_final_values = np.linspace(0., t_final, 11)[1:] # erk = rk4; dt = 0.25 # erk = rk4; dt = 0.4 erk = ssp33; dt = 0.1 u0 = np.array([1., 0.0]) num_points = 200 * 1 np.random.seed(42) radius = np.sqrt(np.random.uniform(0, 0.001**2, num_points)) angle = np.random.uniform(0, 2*np.pi, num_points) u0_values = np.zeros((num_points, 2)) u0_values[:,0] = radius * np.cos(angle) + u0[0] u0_values[:,1] = radius * np.sin(angle) + u0[1] u0_hull = sp.spatial.ConvexHull(u0_values) vol0 = u0_hull.volume def phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed): u_values = np.zeros_like(u0_values) for i in np.arange(num_points): # Find the last output time that is less than t_final start_ind = np.nonzero(np.where(tts[i]<t_final,1,0))[0].max() if relaxed == None: tt, uu = symplectic_euler(dt, uus[i][:,start_ind], t_final-tts[i][start_ind]) else: tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, uus[i][:,start_ind], t_final-tts[i][start_ind], relaxed=relaxed, method="brentq", newdt=True) # tt, uu = relaxed_ERK(erk, dt, f, uus[i][:,start_ind], t_final-tts[i][start_ind], # relaxed=relaxed, newdt=True, gammatol=0.5) u_values[i,:] = uu[:,-1] u_hull = sp.spatial.ConvexHull(u_values) rel_change = (u_hull.volume - vol0) / vol0 return rel_change def precompute_trajectories(erk, dt, t_final): # Precompute the trajectories. Later we'll "interpolate" from these results. tts = [] uus = [] for i in np.arange(num_points): tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, relaxed=False, method="brentq", newdt=True) # tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, # relaxed=False, newdt=True, gammatol=0.5) tts.append(tt) uus.append(uu) tts_r = [] uus_r = [] for i in np.arange(num_points): tt, uu = convex_relaxed_ERK(erk, dt, f, eta, d_eta, u0_values[i,:], t_final, relaxed=True, method="brentq", newdt=True) # tt, uu = relaxed_ERK(erk, dt, f, u0_values[i,:], t_final, # relaxed=True, newdt=True, gammatol=0.5) tts_r.append(tt) uus_r.append(uu) tts_s = [] uus_s = [] for i in np.arange(num_points): tt, uu = symplectic_euler(dt, u0_values[i,:], t_final) tts_s.append(tt) uus_s.append(uu) return tts, uus, tts_r, uus_r, tts_s, uus_s tts, uus, tts_r, uus_r, tts_s, uus_s = precompute_trajectories(erk, dt, t_final) baseline_rel_change = np.zeros_like(t_final_values) relaxation_rel_change = np.zeros_like(t_final_values) symplectic_rel_change = np.zeros_like(t_final_values) for (t_final_idx, t_final) in enumerate(t_final_values): baseline_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts, uus, relaxed=False) relaxation_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_r, uus_r, relaxed=True) symplectic_rel_change[t_final_idx] = phase_space_volume_change(erk, dt, t_final, tts_s, uus_s, relaxed=None) plt.close("all") fig, ax = plt.subplots(1, 1) ax.set_prop_cycle(marker_cycler) plt.plot(t_final_values, baseline_rel_change, label="Baseline") plt.plot(t_final_values, relaxation_rel_change, label="Relaxation") plt.plot(t_final_values, symplectic_rel_change, label="Symplectic Euler") plt.xlabel(r"$t$") plt.ylabel("Rel. Change of Phase Space Vol.") plt.legend(loc="best") plt.savefig("../figures/phase_space_volume__SSP33__duffing_osc.pdf", bbox_inches="tight") print(np.linalg.lstsq(t_final_values.reshape(-1,1), baseline_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), relaxation_rel_change, rcond=None)) print(np.linalg.lstsq(t_final_values.reshape(-1,1), symplectic_rel_change, rcond=None)) print(vol0) fig, ax = plt.subplots(1, 1) ax.set_aspect("equal"); xlim = plt.xlim(); ylim = plt.ylim() time_tmp = time.time() for idx in np.arange(len(uus)): plt.scatter(uus[idx][0,-1], uus[idx][1,-1], color="blue", marker=".") fig, ax = plt.subplots(1, 1) ax.set_aspect("equal"); xlim = plt.xlim(); ylim = plt.ylim() time_tmp = time.time() for idx in np.arange(len(uus_r)): plt.scatter(uus_r[idx][0,-1], uus_r[idx][1,-1], color="blue", marker=".") ```
github_jupyter
``` import os import cv2 import numpy as np #browser_name = "LayerNone" browser_names = ['LayerExtob', 'LayerFat', 'LayerNone', 'LayerSack', 'LayerSkin', 'LayerSpchd'] data_folder = r"D:\HerniaModelStudy\NpyData" image_name = "Webcam_Webcam" #name_prefix = "layer_" under_sampling_factor = 1 test_split_ratio = 0.10 shuffle_test = True cropped_size = 256 scaled_size = 64 if not os.path.exists(data_folder): os.makedirs(data_folder) print("Created data folder: " + output_training_folder) # Make sure input sequence browser and video exists for browser_name in browser_names: browser_node = slicer.util.getFirstNodeByName(browser_name, className='vtkMRMLSequenceBrowserNode') if browser_node is None: logging.error("Could not find browser node: {}".format(browser_name)) raise else: print("Found: " + browser_name) image_node = slicer.util.getFirstNodeByName(image_name) if image_node is None: logging.error("Could not find image node: {}".format(image_name)) raise def get_train_test_from_browser_node(browser_name, tissue_class, class_num): browser_node = slicer.util.getFirstNodeByName(browser_name, className='vtkMRMLSequenceBrowserNode') n = browser_node.GetNumberOfItems()//under_sampling_factor #print("Number of images in browser: {}".format(n)) n_test = int(n * test_split_ratio) all_indices = range(n) if shuffle_test: test_indices = np.random.choice(all_indices, n_test, replace=False) # replace must be false or error, out of range else: test_indices = range(n_test) browser_node.SelectFirstItem() trainCount = 0 testCount = 0 train_arrays = np.zeros((len(all_indices) - len(test_indices), scaled_size, scaled_size, 3), dtype=np.float32) test_arrays = np.zeros((len(test_indices), scaled_size, scaled_size, 3), dtype = np.float32) print(train_arrays.shape) print(test_arrays.shape) for i in range(n): image = image_node.GetImageData() shape = list(image.GetDimensions()) shape.reverse() components = image.GetNumberOfScalarComponents() if components > 1: shape.append(components) shape.remove(1) image_array = vtk.util.numpy_support.vtk_to_numpy(image.GetPointData().GetScalars()).reshape(shape) try: if i in test_indices: test_arrays[testCount] = cv2.resize(image_array[70:70+cropped_size, 150:150+cropped_size], dsize=(scaled_size, scaled_size)) testCount+=1 else: train_arrays[trainCount] = cv2.resize(image_array[70:70+cropped_size, 150:150+cropped_size], dsize=(scaled_size, scaled_size)) trainCount+=1 except IndexError: print("n = {}".format(n)) print("i = {}".format(i)) print("n_test = {}".format(n_test)) print("len(all_indices) = {}".format(len(all_indices))) print("len(test_indices) = {}".format(len(test_indices))) print("trainCount = {}".format(trainCount)) print("testCount = {}".format(testCount)) print("n = {}".format(n)) return 0,0 for x in range(under_sampling_factor): browser_node.SelectNextItem() slicer.app.processEvents() train_y = np.full(train_arrays.shape[0], class_num, dtype = np.float32) test_y = np.full(test_arrays.shape[0], class_num, dtype = np.float32) print("Exported {} images of class {} for train. ".format(trainCount, tissue_class)) print("Exported {} images of class {} for test. ".format(testCount, tissue_class)) return train_arrays, test_arrays, train_y, test_y #x_train, x_test, y_train, y_test = get_train_test_from_browser_node(browser_names[0], "Extob", 0) #print(x_train.shape) #print(y_train.shape) #print(x_test.shape) #print(y_test.shape) #None.shape #print(x_test.dtype) for count in range(len(browser_names)): if count==0: x_train, x_test, y_train, y_test = get_train_test_from_browser_node(browser_names[count], browser_names[count], count) else: x_train_new, x_test_new, y_train_new, y_test_new = get_train_test_from_browser_node(browser_names[count], browser_names[count], count) x_train = np.concatenate((x_train, x_train_new)) x_test = np.concatenate((x_test, x_test_new)) y_train = np.concatenate((y_train, y_train_new)) y_test = np.concatenate((y_test, y_test_new)) print(count) print(x_train.shape) print(y_train.shape) np.save(os.path.join(data_folder, "x_train_second.npy"), x_train) np.save(os.path.join(data_folder, "x_test_second.npy"), x_test) np.save(os.path.join(data_folder, "y_train_second.npy"), y_train) np.save(os.path.join(data_folder, "y_test_second.npy"), y_test) # def returnMany(): # return np.array([1,2,3]), np.array([4,5,6]) # z = np.array([9,8,7,]) # np.concatenate(z, returnMany()) print(x_train.shape) print(x_test.shape) print(y_train.shape) print(y_test.shape) # Prepare test image indices #image_name = name_prefix + "%06d" % i + ".npy" #image_fullname = os.path.join(output_training_folder, image_name) # write to file #image_brg = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR) # print(image_brg) #np.save(image_fullname, image_array) #print("Exported {} image in {}".format(testCount, output_testing_folder)) #print("Exported {} image in {}".format((trainCount), output_training_folder)) ```
github_jupyter
# SVM-SMOๅฎž็Žฐ [ๅ‚่€ƒ้“พๆŽฅ](https://www.cnblogs.com/pinard/p/6111471.html) ``` import numpy as np np.random.seed(0) data_src = 'svm' x_train = np.load('./data/{}/train_data.npy'.format(data_src)) y_train = np.load('./data/{}/train_target.npy'.format(data_src)) x_test = np.load('./data/{}/test_data.npy'.format(data_src)) y_test = np.load('./data/{}/test_target.npy'.format(data_src)) class LinearSVM: def __init__(self, x_train, y_train, C=5.0, max_iter=100000): self.x_train = x_train self.y_train = y_train self.C = C self.alpha = np.random.randn(self.m) self.b = np.random.randn(1) * x_train[:, 1].std(ddof=1) + x_train[:, 1].mean() self.max_iter = max_iter self.phi = lambda x: x def K(self, xi, xj): return self.phi(xi) @ self.phi(xj) @property def x_dim(self): return len(self.x_train[0]) @property def m(self): return self.x_train.shape[0] @property def w(self): w = np.zeros(self.x_dim) for i in range(self.m): w += self.alpha[i] * self.y_train[i] * self.x_train[i] return w def f(self, x): return x @ self.w + self.b def choose_i(self): # ็กฎๅฎš i ## ่€ƒ่™‘ 0 < alpha < C where = np.where((0 < self.alpha) & (self.alpha < self.C)) if where[0].size != 0: criterion = np.abs(self.y_train[where] * self.f(self.x_train[where]) - 1) i_index_in_where = np.argmax(criterion) if criterion[i_index_in_where] != 0: return where[0][i_index_in_where] ## ่€ƒ่™‘ alpha == 0 where = np.where(self.alpha == 0) if where[0].size != 0: criterion = 1 - self.y_train[where] * self.f(self.x_train[where]) i_index_in_where = np.argmax(criterion) if criterion[i_index_in_where] > 0: return where[0][i_index_in_where] ## ่€ƒ่™‘ alpha == C where = np.where(self.alpha == self.C) if where[0].size != 0: criterion = self.y_train[where] * self.f(self.x_train[where]) - 1 i_index_in_where = np.argmax(criterion) if criterion[i_index_in_where] > 0: return where[0][i_index_in_where] return None def E(self, i=None): if i is None: return self.f(x_train) - y_train else: return self.f(x_train[i]) - y_train[i] def train(self): for _ in range(self.max_iter): # ็กฎๅฎš alpha_i i = self.choose_i() # i = np.random.choice(list(range(self.m)), 1)[0] Ei = self.E(i=i) max_delta = -np.inf best_j = -1 # ็กฎๅฎš alpha_j criterion = np.abs(np.array([Ei - self.E(i=j) for j in range(self.m)])) criterion[i] = -1 j = np.argmax(criterion) Ej = self.E(i=j) # ๆฑ‚ K Kii = self.K(self.x_train[i], self.x_train[i]) Kjj = self.K(self.x_train[j], self.x_train[j]) Kij = self.K(self.x_train[i], self.x_train[j]) # ๆฑ‚ๆ–ฐ็š„ alpha_i, alpha_j new_alpha_j_unc = self.alpha[j] + self.y_train[j] * (Ei-Ej) / (Kii + Kjj - 2*Kij) ## ๆฑ‚ L, H ไปฅ้™ๅˆถ 0 <= alpha <= C L = max(0, self.alpha[j]-self.alpha[i]) if self.y_train[i] != self.y_train[j] else max(0, self.alpha[j]+self.alpha[i]-self.C) H = min(self.C, self.C+self.alpha[j]-self.alpha[i]) if self.y_train[i] != self.y_train[j] else min(self.C, self.alpha[j]+self.alpha[i]) ## ้™ๅˆถๆ–ฐ็š„ alpha_j new_alpha_j = H if new_alpha_j_unc > H else L if new_alpha_j_unc < L else new_alpha_j_unc new_alpha_i = (self.alpha[i] * self.y_train[i] + self.alpha[j] * self.y_train[j] - new_alpha_j * self.y_train[j]) * self.y_train[i] # ๆฑ‚ๆ–ฐ็š„ b new_bi = -Ei - self.y_train[i] * Kii * (new_alpha_i - self.alpha[i]) - self.y_train[j] * Kij * (new_alpha_j - self.alpha[j]) + self.b new_bj = -Ej - self.y_train[i] * Kij * (new_alpha_i - self.alpha[i]) - self.y_train[j] * Kjj * (new_alpha_j - self.alpha[j]) + self.b self.b = (new_bi + new_bj) / 2 # ๆ›ดๆ–ฐ alpha self.alpha[i], self.alpha[j] = new_alpha_i, new_alpha_j def predict(self, x_test): return np.sign(self.f(x_test)) def test(self, x_test, y_test): x_test = np.array(x_test) p = self.predict(x_test) acc = 1 - np.sum(np.abs(p - y_test)) / (2*self.m) return p, acc def get_xxyy(self, span): xx = np.linspace(*span, int((span[1]-span[0])*100)) yy = (-self.b-self.w[0]*xx) / self.w[1] return xx, yy np.random.seed(2020) lsvm = LinearSVM(x_train, y_train, max_iter=200) lsvm.train() print(lsvm.test(x_train, y_train)[1]) print(lsvm.test(x_test, y_test)[1]) import matplotlib.pyplot as plt xx, yy = lsvm.get_xxyy((np.round(x_train[:, 0].min(), 2), np.round(x_train[:, 0].max(), 2))) plt.xlabel('x_train[0]', size=16) plt.ylabel('x_train[1]', size=16) plt.xticks(size=12) plt.yticks(size=12) red = np.where(y_train == 1) blue = np.where(y_train == -1) plt.scatter(x_train[red][:, 0], x_train[red][:, 1], c='red', label='y=1') plt.scatter(x_train[blue][:, 0], x_train[blue][:, 1], c='blue', label='y=-1') plt.legend() plt.xlim(np.round(x_train[:, 0].min(), 2) - 0.5, np.round(x_train[:, 0].max(), 2) + 0.5) plt.ylim(np.round(x_train[:, 1].min(), 2) - 0.5, np.round(x_train[:, 1].max(), 2) + 0.5) plt.plot(xx, yy, c='green') import matplotlib.pyplot as plt xx, yy = lsvm.get_xxyy((int(np.floor(x_train[:, 0].min())), int(np.ceil(x_train[:, 0].max())))) plt.xlabel('x_test[0]', size=16) plt.ylabel('x_test[1]', size=16) plt.xticks(size=12) plt.yticks(size=12) red = np.where(y_test == 1) blue = np.where(y_test == -1) plt.scatter(x_test[red][:, 0], x_test[red][:, 1], c='red', label='y=1') plt.scatter(x_test[blue][:, 0], x_test[blue][:, 1], c='blue', label='y=-1') plt.legend() plt.xlim(np.round(x_train[:, 0].min(), 2) - 0.5, np.round(x_train[:, 0].max(), 2) + 0.5) plt.ylim(np.round(x_train[:, 1].min(), 2) - 0.5, np.round(x_train[:, 1].max(), 2) + 0.5) plt.plot(xx, yy, c='green') from sklearn.svm import LinearSVC lsvc = LinearSVC(max_iter=100000, C=5) lsvc.fit(x_train, y_train) print(lsvc.score(x_train, y_train)) print(lsvc.score(x_test, y_test)) ```
github_jupyter
**AutoML Assignment:** *Problem statement*: **Machine Learning Pipeline Automation** Build an accelerator to automate all the steps in ML model development # Write an Automated ML function to be called using any data frame (dataset) to give a good trained model. ``` #AutoML function def automl(**kwargs): from sklearn import datasets import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable from autokeras import StructuredDataClassifier from sklearn.model_selection import train_test_split #Web Scraping url_list = ["https://www.kaggle.com/datasets?datasetsOnly=true", "https://public.knoema.com/", "https://www.kaggle.com/c/nfl-health-and-safety-helmet-assignment/data", "http://www.cs.ubc.ca/labs/beta/Projects/autoweka/datasets/", "https://www.kaggle.com/mysarahmadbhat/bmw-used-car-listing", "https://www.climate.gov/maps-data/datasets"] for url in url_list: # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: kaggle_data = pd.DataFrame(data = kaggle_data, columns = each_new_col) kaggle_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = state_data[each_new_col].map(int) #dataset from mlbox.optimisation import Optimiser, Regressor #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(train_data.iloc[:,:-1]), "target" : pd.Series(test_data.iloc[:,-1])} #build a keras model import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential() #relu: Rectified Linear Unit # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) # Add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) #define a ConvModel class ConvModel(tf.keras.Model): def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False): super(ConvModel, self).__init__(name='mlp') self.use_bn = use_bn self.use_dp = use_dp self.num_classes = num_classes # backbone layers self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)] self.convs += [ConvLayer(nf) for nf in nfs[1:]] # classification layers self.convs.append(AveragePooling2D()) self.convs.append(Dense(output_shape, activation='softmax')) def call(self, inputs): for layer in self.convs: inputs = layer(inputs) return inputs #compile the model model.compile(loss='categorical crossentropy', metrics=['accuracy'], optimizer='rmsprop') model.build((None, 32, 32, 3)) model.summary() import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) history = model.fit(x_train, y_train, batch_size=64, epochs=1000) model.summary() input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) tf.keras.layers.LSTM(3, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False) #define a ConvLayer class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, padding = "same", use_bias = False, activation = "linear")) super(ConvLayer, self).__init__(**kwargs) def rsub(self): return -self.grelu.sub def set_sub(self, v): self.grelu.sub = -v def conv_weights(self): return self.conv.weight[0] def build(self, input_shape): # No weight to train. super(ConvLayer, self).build(input_shape) # Be sure to call this at the end def compute_output_shape(self, input_shape): output_shape = (input_shape[0], input_shape[1]/2, input_shape[2]/2, self.nf) return output_shape def call(self, x): return self.grelu(self.conv(x)) def __repr__(self): return f'ConvLayer(nf={self.nf}, activation={self.grelu})' opt.evaluate(params, df) datasets_dict = { "iris": datasets.load_iris(), "boston": datasets.load_boston(), "breast_cancer": datasets.load_breast_cancer(), "diabetes": datasets.load_diabetes(), "wine": datasets.load_wine(), "linnerud": datasets.load_linnerud(), "digits": datasets.load_digits(), "kaggle_data_list": pd.DataFrame({ "Latest_Covid-19_India_Status":pd.read_csv("Latest Covid-19 India Status.csv", sep=','), "Pueblos_Magicos": pd.read_csv("pueblosMagicos.csv", sep=','), "Apple_iphone_SE_reviews&ratings": pd.read_csv("APPLE_iPhone_SE.csv", sep=',') }) } if len(datasets_dict["kaggle_data_list"])!=0: for i in range(len(datasets_dict.get("kaggle_data_list"))): df=df.iloc[:] print(df.head()) print(df.tail()) print(df.info()) print(df.describe()) from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.metrics X, y = df.to_numpy() X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) else: for each_dataset in datasets_dict: print(each_dataset," dataset:") print("Data: ",each_dataset.data) print("Target: ", each_dataset.target) print("Target names: ", each_dataset.target_names) print("Description: ", each_dataset.DESCR) #shape print("Shape of the data: ", each_dataset.data.shape) print("Shape of the target: ",each_dataset.target.shape) #type print("Type of the data: ", type(each_dataset.data.shape)) print("Type of the data: ", type(each_dataset.target.shape)) #dimensions print("Number of dimensions of the data: ", each_dataset.data.ndim) print("Number of dimensions of the target: ",each_dataset.target.ndim) #number of samples and features n_samples, n_features = each_dataset.data.shape print("Number of samples: ", n_samples) print("Number of features: ", n_features) #keys print("Keys: ", each_dataset.keys()) X, y = digits.data, digits.target #view the first and last 5 rows of the pandas dataframe df=pd.DataFrame(X, columns=digits.feature_names) print(df.head()) print(df.tail()) #print(digits.data[0]) #visualize data on its principal components #PCA from sklearn.decomposition import PCA import matplotlib.pyplot as plt pca = PCA(n_components=2) proj = pca.fit_transform(each_dataset.data) plt.scatter(proj[:,0], proj[:,1], c=each_dataset.target, cmap="Paired") plt.colorbar() #Gaussian Naive-Bayes classification from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split # split the dataset into training and validation sets X_train, X_test, y_train, y_test = train_test_split( each_dataset.data, each_dataset.target) # train the model clf = GaussianNB() clf.fit(X_train, y_train) # use the model to predict the labels of the test data predicted = clf.predict(X_test) expected = y_test # Plot the prediction fig = plt.figure(figsize=(6, 6)) # figure size in inches fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) # plot the digits: each image is 8x8 pixels for i in range(64): ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=plt.cm.binary, interpolation='nearest') # label the image with the target value if predicted[i] == expected[i]: ax.text(0, 7, str(predicted[i]), color='green') else: ax.text(0, 7, str(predicted[i]), color='red') #Quantify performance: #number of correct matches matches = (predicted == expected) print(matches.sum()) #total nunber of data points print(len(matches)) #ratio of correct predictions matches.sum() / float(len(matches)) #Classification report from sklearn import metrics print(metrics.classification_report(expected, predicted)) #Obtain the confusion matrix print(metrics.confusion_matrix(expected, predicted)) plt.show() #AutoGluon: #Tabular prediction with AutoGluon #Predicting Columns in a Table from autogluon.tabular import TabularDataset, TabularPredictor train_data = TabularDataset(each_dataset) subsample_size = 55500000 # subsample subset of data for faster demo train_data = train_data.sample(n=subsample_size, random_state=0) train_data.head() label = 'class' print("Summary of class variable: \n", train_data[label].describe()) #use AutoGluon to train multiple models save_path = 'agModels-predictClass' # specifies folder to store trained models predictor = TabularPredictor(label=label, path=save_path).fit(train_data) test_data = TabularDataset(each_dataset) y_test = test_data[label] # values to predict test_data_nolab = test_data.drop(columns=[label]) # delete label column to prove we're not cheating test_data_nolab.head() #predictor = TabularPredictor.load(save_path) y_pred = predictor.predict(test_data_nolab) print("Predictions: \n", y_pred) perf = predictor.evaluate_predictions(y_true=y_test, y_pred=y_pred, auxiliary_metrics=True) predictor.leaderboard(test_data, silent=True) from autogluon.tabular import TabularPredictor predictor = TabularPredictor(label=label).fit(train_data=each_dataset) #.fit() returns a predictor object pred_probs = predictor.predict_proba(test_data_nolab) pred_probs.head(5) #summarize what happened during fit results = predictor.fit_summary(show_plot=True) print("AutoGluon infers problem type is: ", predictor.problem_type) print("AutoGluon identified the following types of features:") print(predictor.feature_metadata) predictor.leaderboard(test_data, silent=True) predictor.predict(test_data, model='LightGBM') #Maximizing predictive performance time_limit = 11 metric = 'roc_auc' # specify the evaluation metric here predictor = TabularPredictor(label, eval_metric=metric).fit(train_data, time_limit=time_limit, presets='best_quality') predictor.leaderboard(test_data, silent=True) #Regression (predicting numeric table columns) column = 'column' print("Summary of PUEBLO variable: \n", train_data[column].describe()) predictor_column = TabularPredictor(label=column, path="agModels-predictAge").fit(train_data, time_limit=60) performance = predictor_column.evaluate(test_data) #see the per-model performance predictor_column.leaderboard(test_data, silent=True) #MLbox: from mlbox.optimisation import Optimiser from sklearn import datasets best = opt.optimise(space, df, 3) #optimising the pipeline opt = Optimiser() space = { 'fs__strategy':{"search":"choice","space":["variance","rf_feature_importance"]}, 'est__colsample_bytree':{"search":"uniform", "space":[0.3,0.7]} } df = {"train" : pd.DataFrame(each_dataset.data), "target" : pd.Series(each_dataset.target)} #evaluating the pipeline opt = Optimiser() params = { "ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear" } df = {"train" : pd.DataFrame(each_dataset.data), "target" : pd.Series(each_dataset.target)} opt.evaluate(params, df) #TPOT #Classification from tpot import TPOTClassifier from sklearn.model_selection import train_test_split #perform a train test split X_train, X_test, y_train, y_test = train_test_split(each_dataset.data, each_dataset.target, train_size=0.75, test_size=0.25) tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=111, cv=5, subsample=0.98, verbosity=2, n_jobs=-2, max_eval_time_mins=0.00000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_datasets_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export('tpot_datasets_pipeline.py') plt.hist(each_dataset.target) for index, feature_name in enumerate(each_dataset.feature_names): plt.figure() plt.scatter(each_dataset.data[:, index], each_dataset.target) plt.show() from sklearn import model_selection X = each_dataset.data y = each_dataset.target X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.25, random_state=0) print("%r, %r, %r" % (X.shape, X_train.shape, X_test.shape)) clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train) y_pred = clf.predict(X_test) print(metrics.confusion_matrix(y_test, y_pred)) print(metrics.classification_report(y_test, y_pred)) #Auto-Pytorch from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = each_dataset(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch on the datasets autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) #Auto-Sklearn from sklearn import datasets import autosklearn.classification cls = autosklearn.classification.AutoSklearnClassifier() X, y = each_dataset(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) cls.fit(X_train, y_train) predictions = cls.predict(X_test) import sklearn.model_selection import sklearn.metrics if __name__ == "__main__": X, y = each_dataset(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) automl = autosklearn.classification.AutoSklearnClassifier() automl.fit(X_train, y_train) y_hat = automl.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat)) import numpy as np import tensorflow as tf import autokeras as ak input_node = ak.ImageInput() output_node = ak.Normalization()(input_node) output_node1 = ak.ConvBlock()(output_node) output_node2 = ak.ResNetBlock(version="v2")(output_node) output_node = ak.Merge()([output_node1, output_node2]) output_node = ak.ClassificationHead()(output_node) auto_model = ak.AutoModel(inputs=input_node, outputs=output_node, overwrite=True, max_trials=100) #prepare data to run the model (x_train, y_train), (x_test, y_test) = each_datset print(x_train.shape) print(y_train.shape) print(y_train[:3]) # Feed the AutoModel with training data. auto_model.fit(x_train[:100], y_train[:100], epochs=1000) # Predict with the best model predicted_y = auto_model.predict(x_test) # Evaluate the best model with testing data print(auto_model.evaluate(x_test, y_test)) #implement new block class SingleDenseLayerBlock(ak.Block): def build(self, hp, inputs=None): # Get the input_node from inputs. input_node = tf.nest.flatten(inputs)[0] layer = tf.keras.layers.Dense( hp.Int("num_units", min_value=32, max_value=512, step=32) ) output_node = layer(input_node) return output_node # Build the AutoModel input_node = ak.Input() output_node = SingleDenseLayerBlock()(input_node) output_node = ak.RegressionHead()(output_node) auto_model = ak.AutoModel(input_node, output_node, overwrite=True, max_trials=100) # Prepare Data num_instances = 100 x_train = np.random.rand(num_instances, 20).astype(np.float32) y_train = np.random.rand(num_instances, 1).astype(np.float32) x_test = np.random.rand(num_instances, 20).astype(np.float32) y_test = np.random.rand(num_instances, 1).astype(np.float32) # Train the model auto_model.fit(x_train, y_train, epochs=1000) print(auto_model.evaluate(x_test, y_test)) print(kwargs) #return the trained model return trained_model !pip install scipy !pip install sphinx !pip install geopandas !pip install deltalake #yet to use in near future ``` **Install various libraries** ``` #install necessary libraries install_list=[ "!pip install mlbox", "!pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o", "!pip install --upgrade pip", "user$ conda install -c h2oai h2o", "!python3 -m pip install --upgrade pip", "!pip3 install auto-sklearn", "!pip3 install --upgrade scipy", "!pip3 install --upgrade auto-sklearn", "!pip install auto-sklearn==0.10.0", "!sudo apt-get install build-essential swig", "!curl https://raw.githubusercontent.com/automl/auto-sklearn/master/requirements.txt | xargs -n 1 -L 1 pip install", "!pip install auto-sklearn==0.10.0", "!python3 -m pip install -U pip", "!python3 -m pip install -U setuptools wheel", "!python3 -m pip install -U 'mxnet<2.0.0'", "!python3 -m pip install autogluon", "!pip install matplotlib-venn", "!apt-get -qq install -y libfluidsynth1", "!pip install Pillow", "!pip uninstall PIL", "!pip uninstall Pillow", "!ypip install Pillow", "!pip3 install --upgrade pandas", "!pip install seaborn", "!pip install matplotlib", "!pip install --upgrade matplotlib", "!pip install geopandas", "!pip install autopytorch", "!pip install tpot", "!pip install ConfigSpace", "!pip install autokeras", "!pip install deltalake", #yet to use in near future "sns.set_style(style='ticks')", "conda install -c conda-forge tpot", "conda install -c conda-forge tpot xgboost dask dask-ml scikit-mdr skrebate", "conda env create -f tpot-cuml.yml -n tpot-cuml", "conda activate tpot-cuml", "alpha, Type:UniformFloat, Range: [0.0, 1.0], Default: 0.5", "$ cat requirements.txt | xargs -n 1 -L 1 pip install", "$ python setup.py install", "$ cd examples/", "Optimiser()", "opt.evaluate(params, df)", "classmlbox.model.classification.StackingClassifier(base_estimators=[<mlbox.model.classification.classifier.Classifier object>, <mlbox.model.classification.classifier.Classifier object>, <mlbox.model.classification.classifier.Classifier object>], level_estimator=<Mock name='mock()' id='139653242018560'>, n_folds=5, copy=False, drop_first=True, random_state=1, verbose=True)", 'pyinstaller -F --hidden-import="sklearn.utils._cython_blas" --hidden-import="sklearn.neighbors.typedefs" --hidden-import="sklearn.neighbors.quad_tree" --hidden-import="sklearn.tree._utils" Datamanager.py'] for each_command in install_list: if each_command: try: each_command except IOError: print("Invalid command.") # Syntax error: invalid syntax else: print("Search for another alternative") !python3 -m pip install autogluon !python3 -m pip install --upgrade pip #install autosklearn !pip3 install auto-sklearn !pip3 install --upgrade scipy !pip3 install --upgrade auto-sklearn !pip install auto-sklearn==0.10.0 !sudo apt-get install build-essential swig !curl https://raw.githubusercontent.com/automl/auto-sklearn/master/requirements.txt | xargs -n 1 -L 1 pip install !pip install auto-sklearn==0.10.0 !pip install matplotlib-venn !apt-get -qq install -y libfluidsynth1 !pip install geopandas !pip3 uninstall statsmodels ``` **Install MLBox and H2O** ``` !pip install mlbox !pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o !pip install seaborn !pip install matplotlib !pip install --upgrade matplotlib ``` Train and Test a Gradient Boosting Model (GBM) model: ``` import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/fatiimaezzahra/famous-iconic-women" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(stats_train.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #Weather forecast using H2O import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url="https://www.climate.gov/maps-data/datasets" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype weather_data[each_new_col] = stats_data[each_new_col].map(int) X, y = weather_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(weather_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #MLbox: from mlbox.optimisation import Optimiser, Regressor import pandas as pd #Weather forecast using H2O import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url="https://www.kaggle.com/mattiuzc/stock-exchange-data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype stock_data[each_new_col] = stock_data[each_new_col].map(int) X, y = stock_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(stock_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(dataset.data), "target" : pd.Series(dataset.target)} opt.evaluate(params, df) #MNIST dataset from mlbox.optimisation import Optimiser, Regressor import pandas as pd mnist_train_data=pd.read_csv("/content/sample_data/mnist_train_small.csv") mnist_test_data=pd.read_csv("/content/sample_data/mnist_test.csv") mnist_data = pd.merge(mnist_train_data, mnist_test_data) #load data dataset = mnist_data #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(mnist_train_data.iloc[:,:-1]), "target" : pd.Series(mnist_test_data.iloc[:,-1])} #build a keras model import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential() #relu: Rectified Linear Unit # add a densely-connected layer with 64 units to the model model.add(keras.layers.Dense(64, activation='relu')) # add another: model.add(keras.layers.Dense(64, activation='relu')) # add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) #define a ConvModel class ConvModel(tf.keras.Model): def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False): super(ConvModel, self).__init__(name='mlp') self.use_bn = use_bn self.use_dp = use_dp self.num_classes = num_classes # backbone layers self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)] self.convs += [ConvLayer(nf) for nf in nfs[1:]] # classification layers self.convs.append(AveragePooling2D()) self.convs.append(Dense(output_shape, activation='softmax')) def call(self, inputs): for layer in self.convs: inputs = layer(inputs) return inputs #compile the model model.compile(loss='categorical crossentropy', metrics=['accuracy'], optimizer='rmsprop') model.build((None, 32, 32, 3)) model.summary() import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator #Famous iconic women dataset url = "https://www.kaggle.com/fatiimaezzahra/famous-iconic-women" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) history = model.fit(x_train, y_train, batch_size=64, epochs=1) model.summary() input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) tf.keras.layers.LSTM(3, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False) #define a ConvLayer class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, padding = "same", use_bias = False, activation = "linear")) super(ConvLayer, self).__init__(**kwargs) def rsub(self): return -self.grelu.sub def set_sub(self, v): self.grelu.sub = -v def conv_weights(self): return self.conv.weight[0] def build(self, input_shape): # No weight to train. super(ConvLayer, self).build(input_shape) # Be sure to call this at the end def compute_output_shape(self, input_shape): output_shape = (input_shape[0], input_shape[1]/2, input_shape[2]/2, self.nf) return output_shape def call(self, x): return self.grelu(self.conv(x)) def __repr__(self): return f'ConvLayer(nf={self.nf}, activation={self.grelu})' opt.evaluate(params, df) #Outbrain Click Prediction dataset from mlbox.optimisation import Optimiser, Regressor import pandas as pd clicks_train_data=pd.read_csv("C:/Users/Administrator/OneDrive - Bitwise Solutions Private Limited/Documents/AutoML/OutbrainClickPrediction/clicks_train.csv") clicks_test_data=pd.read_csv("C:/Users/Administrator/OneDrive - Bitwise Solutions Private Limited/Documents/AutoML/OutbrainClickPrediction/clicks_test.csv") clicks_data = pd.merge(clicks_train_data, clicks_test_data) #load data dataset = clicks_data #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(clicks_train_data.iloc[:,:-1]), "target" : pd.Series(clicks_test_data.iloc[:,-1])} #build a keras model import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential() #relu: Rectified Linear Unit # add a densely-connected layer with 64 units to the model model.add(keras.layers.Dense(64, activation='relu')) # add another: model.add(keras.layers.Dense(64, activation='relu')) # add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) #define a ConvModel class ConvModel(tf.keras.Model): def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False): super(ConvModel, self).__init__(name='mlp') self.use_bn = use_bn self.use_dp = use_dp self.num_classes = num_classes # backbone layers self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)] self.convs += [ConvLayer(nf) for nf in nfs[1:]] # classification layers self.convs.append(AveragePooling2D()) self.convs.append(Dense(output_shape, activation='softmax')) def call(self, inputs): for layer in self.convs: inputs = layer(inputs) return inputs #compile the model model.compile(loss='categorical crossentropy', metrics=['accuracy'], optimizer='rmsprop') model.build((None, 32, 32, 3)) model.summary() import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/c/outbrain-click-prediction/data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) history = model.fit(x_train, y_train, batch_size=64, epochs=1) model.summary() input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) tf.keras.layers.LSTM(3, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False) #define a ConvLayer class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, padding = "same", use_bias = False, activation = "linear")) super(ConvLayer, self).__init__(**kwargs) def rsub(self): return -self.grelu.sub def set_sub(self, v): self.grelu.sub = -v def conv_weights(self): return self.conv.weight[0] def build(self, input_shape): # No weight to train. super(ConvLayer, self).build(input_shape) # Be sure to call this at the end def compute_output_shape(self, input_shape): output_shape = (input_shape[0], input_shape[1]/2, input_shape[2]/2, self.nf) return output_shape def call(self, x): return self.grelu(self.conv(x)) def __repr__(self): return f'ConvLayer(nf={self.nf}, activation={self.grelu})' opt.evaluate(params, df) ``` Image Prediction with AutoGluon ``` #Image Prediction with AutoGluon #import autogluon %matplotlib inline import autogluon.core as ag from autogluon.vision import ImageDataset import pandas as pd #celeb faces (celebA) dataset import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/jessicali9530/celeba-dataset" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype olympics2021_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1221) csv_file_list=["list_attr_celeba.csv", "list_bbox_celeba.csv", "list_eval_partition.csv", "list_landmarks_align_celeba.csv"] for each_csv_file in csv_file_list: csv_file = ag.utils.download(each_csv_file) df = pd.read_csv(csv_file) df.head() df = ImageDataset.from_csv(csv_file) df.head() train_data, _, test_data = ImageDataset.from_folders("img_align_celeba.zip", train='train', test='test') print('train #', len(train_data), 'test #', len(test_data)) train_data.head() #load the splits with from_folder root = os.path.join(os.path.dirname(train_data.iloc[0]['image']), '..') all_data = ImageDataset.from_folder(root) all_data.head() #split the dataset train, val, test = all_data.random_split(val_size=0.1, test_size=0.1) print('train #:', len(train), 'test #:', len(test)) #convert a list of images to dataset celeba = ag.utils.download("img_align_celeba.zip") celeba = ag.utils.unzip(celeba) image_list = [x for x in os.listdir(os.path.join(pets, 'images')) if x.endswith('jpg')] new_data = ImageDataset.from_name_func(image_list, label_fn, root=os.path.join(os.getcwd(), celeba, 'images')) new_data #visualize the images new_data.show_images() #image prediction import autogluon.core as ag from autogluon.vision import ImagePredictor, ImageDataset train_dataset, _, test_dataset = ImageDataset.from_folders("img_align_celeba.zip") print(train_dataset) #fit a classifier predictor = ImagePredictor() # since the original dataset does not provide validation split, the `fit` function splits it randomly with 90/10 ratio predictor.fit(train_dataset, hyperparameters={'epochs': 2}) #The best Top-1 accuracy achieved on the validation set is fit_result = predictor.fit_summary() print('Top-1 train acc: %.3f, val acc: %.3f' %(fit_result['train_acc'], fit_result['valid_acc'])) #predict on a new image image_path = test_dataset.iloc[0]['image'] result = predictor.predict(image_path) print(result) bulk_result = predictor.predict(test_dataset) print(bulk_result) #generate image features with a classifier image_path = test_dataset.iloc[0]['image'] feature = predictor.predict_feature(image_path) print(feature) #validation and test top-1 accuracy test_acc = predictor.evaluate(test_dataset) print('Top-1 test acc: %.3f' % test_acc['top1']) #save and load the classifiers filename = 'predictor.ag' predictor.save(filename) predictor_loaded = ImagePredictor.load(filename) # use predictor_loaded as usual result = predictor_loaded.predict(image_path) print(result) #use AutoGluon to produce an ImagePredictor to classify images import autogluon.core as ag from autogluon.vision import ImagePredictor, ImageDataset train_data, _, test_data = ImageDataset.from_folders("img_align_celeba.zip") model = ag.Categorical('resnet18_v1b', 'mobilenetv3_small') model_list = ImagePredictor.list_models() #Specify the training hyper-parameters batch_size = 8 lr = ag.Categorical(1e-2, 1e-3) #Bayesian Optimization hyperparameters={'model': model, 'batch_size': batch_size, 'lr': lr, 'epochs': 2} predictor = ImagePredictor() predictor.fit(train_data, time_limit=60*10, hyperparameters=hyperparameters, hyperparameter_tune_kwargs={'searcher': 'bayesopt', 'num_trials': 2}) print('Top-1 val acc: %.3f' % predictor.fit_summary()['valid_acc']) #Load the test dataset and evaluate results = predictor.evaluate(test_data) print('Test acc on hold-out data:', results) #install !pip install torch #upgrade pytorch !pip install --upgrade torch torchvision #install h2o !pip install h2o #install autokeras !pip install autokeras #upgrade tensorflow !pip install --ignore-installed --upgrade tensorflow #install pytorch !pip install pytorch import pandas as pd #using AutoGluon subsample_size = 2000 feature_columns = ['Product_Description', 'Product_Type'] label = 'Sentiment' train_df = pd.read_csv('Participants_Data.zip', index_col=0).sample(2000, random_state=123) dev_df = pd.read_csv('Participants_Data.zip', index_col=0) test_df = pd.read_csv('Participants_Data.zip', index_col=0) train_df = train_df[feature_columns + [label]] dev_df = dev_df[feature_columns + [label]] test_df = test_df[feature_columns] print('Number of training samples:', len(train_df)) print('Number of dev samples:', len(dev_df)) print('Number of test samples:', len(test_df)) train_df.head() dev_df.head() test_df.head() from autogluon.tabular import TabularPredictor predictor = TabularPredictor(label='Sentiment', path='ag_tabular_product_sentiment_multimodal') predictor.fit(train_df, hyperparameters='multimodal') predictor.leaderboard(dev_df) #mprove predictive performance by using stack ensembling predictor.fit(train_df, hyperparameters='multimodal', num_bag_folds=5, num_stack_levels=1) #NFL Big Data Bowl 2022 kaggle dataset import numpy as np import pandas as pd from autokeras import StructuredDataClassifier from sklearn.model_selection import train_test_split import requests from bs4 import BeautifulSoup import tensorflow as tf import autokeras as ak # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/c/nfl-big-data-bowl-2022/data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype nfl_2022_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1221) csv_file_list=["PFFScoutingData.csv", "games.csv", "players.csv", "plays.csv", "tracking2018.csv", "tracking2019.csv", "tracking2020.csv"] for each_csv_file in csv_file_list: csv_file = ag.utils.download(each_csv_file) df = pd.read_csv(csv_file) df.head() df = ImageDataset.from_csv(csv_file) df.head() #StructuredDataClassifier autokeras.StructuredDataClassifier( column_names=None, column_types=None, num_classes=None, multi_label=False, loss=None, metrics=None, project_name="structured_data_classifier", max_trials=100, directory=None, objective="val_accuracy", tuner=None, overwrite=False, seed=None, max_model_size=None, **kwargs) #fit StructuredDataClassifier.fit( x=None, y=None, epochs=None, callbacks=None, validation_split=0.2, validation_data=None, **kwargs) #predict StructuredDataClassifier.predict(x, **kwargs) #evaluate StructuredDataClassifier.evaluate(x, y=None, **kwargs) #export_model StructuredDataClassifier.export_model() #MNIST dataset from mlbox.optimisation import Optimiser, Regressor import pandas as pd mnist_train_data=pd.read_csv("/content/sample_data/mnist_train_small.csv") mnist_test_data=pd.read_csv("/content/sample_data/mnist_test.csv") mnist_data = pd.merge(mnist_train_data, mnist_test_data) #load data dataset = mnist_data #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(mnist_train_data.iloc[:,:-1]), "target" : pd.Series(mnist_test_data.iloc[:,-1])} #build a keras model import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential() #relu: Rectified Linear Unit # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) # Add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) #define a ConvModel class ConvModel(tf.keras.Model): def __init__(self, nfs, input_shape, output_shape, use_bn=False, use_dp=False): super(ConvModel, self).__init__(name='mlp') self.use_bn = use_bn self.use_dp = use_dp self.num_classes = num_classes # backbone layers self.convs = [ConvLayer(nfs[0], s=1, input_shape=input_shape)] self.convs += [ConvLayer(nf) for nf in nfs[1:]] # classification layers self.convs.append(AveragePooling2D()) self.convs.append(Dense(output_shape, activation='softmax')) def call(self, inputs): for layer in self.convs: inputs = layer(inputs) return inputs #compile the model model.compile(loss='categorical crossentropy', metrics=['accuracy'], optimizer='rmsprop') model.build((None, 32, 32, 3)) model.summary() #Olympics 2021 dataset import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator #dataset url = "https://www.kaggle.com/arjunprasadsarkhel/2021-olympics-in-tokyo" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype olympics2021_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) history = model.fit(x_train, y_train, batch_size=64, epochs=1) model.summary() input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) tf.keras.layers.LSTM(3, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False) #define a ConvLayer class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, padding = "same", use_bias = False, activation = "linear")) super(ConvLayer, self).__init__(**kwargs) def rsub(self): return -self.grelu.sub def set_sub(self, v): self.grelu.sub = -v def conv_weights(self): return self.conv.weight[0] def build(self, input_shape): # No weight to train. super(ConvLayer, self).build(input_shape) # Be sure to call this at the end def compute_output_shape(self, input_shape): output_shape = (input_shape[0], input_shape[1]/2, input_shape[2]/2, self.nf) return output_shape def call(self, x): return self.grelu(self.conv(x)) def __repr__(self): return f'ConvLayer(nf={self.nf}, activation={self.grelu})' opt.evaluate(params, df) import pandas as pd dataset_dict={"New York City Airport Activity": "https://www.kaggle.com/sveneschlbeck/new-york-city-airport-activity?select=nyc-flights.csv"} trained_model = automl(**dataset_dict) print(trained_model) import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/andrewmvd/heart-failure-clinical-data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype olympics2021_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1001) history = model.fit(x_train, y_train, batch_size=64, epochs=1000) model.summary() input_shape = (2, 3, 4) x1 = tf.random.normal(input_shape) x2 = tf.random.normal(input_shape) y = tf.keras.layers.Add()([x1, x2]) print(y.shape) tf.keras.layers.LSTM(3, activation='tanh', recurrent_activation='sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, dropout=0.0, recurrent_dropout=0.0, return_sequences=False, return_state=False, go_backwards=False, stateful=False, time_major=False, unroll=False) #define a ConvLayer class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, padding = "same", use_bias = False, activation = "linear")) super(ConvLayer, self).__init__(**kwargs) def rsub(self): return -self.grelu.sub def set_sub(self, v): self.grelu.sub = -v def conv_weights(self): return self.conv.weight[0] def build(self, input_shape): # No weight to train. super(ConvLayer, self).build(input_shape) # Be sure to call this at the end def compute_output_shape(self, input_shape): output_shape = (input_shape[0], input_shape[1]/2, input_shape[2]/2, self.nf) return output_shape def call(self, x): return self.grelu(self.conv(x)) def __repr__(self): return f'ConvLayer(nf={self.nf}, activation={self.grelu})' opt.evaluate(params, df) #California housing dataset using MLBoX from mlbox.optimisation import Optimiser, Regressor import pandas as pd cal_house_train_data=pd.read_csv("/content/sample_data/california_housing_train.csv") cal_house_test_data=pd.read_csv("/content/sample_data/california_housing_test.csv") cal_house_data = pd.merge(cal_house_train_data, cal_house_test_data) #load data dataset = cal_house_data #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(cal_house_train_data.iloc[:,:-1]), "target" : pd.Series(cal_house_test_data.iloc[:,-1])} opt.evaluate(params, df) #amazon dataset using MLBoX from mlbox.optimisation import Optimiser, Regressor import pandas as pd amazon_train_data=pd.read_csv("C:\Users\Administrator\OneDrive - Bitwise Solutions Private Limited\Documents\AutoML\amazon 2\train.arff") amazon_test_data=pd.read_csv("C:\Users\Administrator\OneDrive - Bitwise Solutions Private Limited\Documents\AutoML\amazon 2\test.arff") amazon_data = pd.merge(amazon_train_data, amazon_test_data) #load data dataset = amazon_data #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(amazon_train_data.iloc[:,:-1]), "target" : pd.Series(amazon_test_data.iloc[:,-1])} opt.evaluate(params, df) #Covid-19 in India dataset import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable url = "https://www.kaggle.com/sudalairajkumar/covid19-in-india" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) #present the data using Pretty table table = PrettyTable() table.field_names = (new_cols) for i in stats: table.add_row(i) table.add_row(['','Total', sum(state_data["Confirmed"]), sum(state_data["Recovered"]), sum(state_data["Deceased"])]) print(table) # barplot to show total confirmed cases Statewise sns.set_style("ticks") plt.figure(figsize=(15,10)) plt.barh(state_data["States/UT"], state_data["Confirmed"].map(int), align = 'center', color = 'lightblue', edgecolor = 'blue') plt.xlabel('No. of Confirmed cases', fontsize = 18) plt.ylabel('States/UT', fontsize = 18) plt.gca().invert_yaxis() # this is to maintain the order in which the states appear plt.xticks(fontsize = 14) plt.yticks(fontsize = 14) plt.title('Total Confirmed Cases Statewise', fontsize = 20) for index, value in enumerate(state_data["Confirmed"]): plt.text(value, index, str(value), fontsize = 12, verticalalignment = 'center') plt.show() # donut chart representing nationwide total confirmed, cured and deceased cases group_size = [sum(state_data['Confirmed']), sum(state_data['Recovered']), sum(state_data['Deceased'])] group_labels = ['Confirmed\n' + str(sum(state_data['Confirmed'])), 'Recovered\n' + str(sum(state_data['Recovered'])), 'Deceased\n' + str(sum(state_data['Deceased']))] custom_colors = ['skyblue','yellowgreen','tomato'] plt.figure(figsize = (5,5)) plt.pie(group_size, labels = group_labels, colors = custom_colors) central_circle = plt.Circle((0,0), 0.5, color = 'white') fig = plt.gcf() fig.gca().add_artist(central_circle) plt.rc('font', size = 12) plt.title('Nationwide total Confirmed, Recovered and Deceased Cases', fontsize = 16) plt.show() import fiona # reading the shape file of map of India in GeoDataFrame map_data = gpd.read_file("Indian_States.shp") map_data.rename(columns = {"st_nm":"States/UT"}, inplace = True) map_data.head() map_data["States/UT"] = map_data["States/UT"].str.replace("&","and") map_data["States/UT"].replace("Arunanchal Pradesh", "Arunachal Pradesh", inplace = True) map_data["States/UT"].replace("Telangana", "Telengana", inplace = True) map_data["States/UT"].replace("NCT of Delhi", "Delhi", inplace = True) map_data["States/UT"].replace("Andaman and Nicobar Island", "Andaman and Nicobar Islands", inplace = True) merged_data = pd.merge(map_data, state_data, how = "left", on = "States/UT") merged_data.fillna(0, inplace = True) merged_data.drop("Sr.No", axis = 1, inplace = True) merged_data.head() #MLbox: from mlbox.optimisation import Optimiser #evaluating the pipeline opt = Optimiser() params = {"ne__numerical_strategy" : 0, "ce__strategy" : "label_encoding", "fs__threshold" : 0.1, "stck__base_estimators" : [Regressor(strategy="RandomForest"), Regressor(strategy="ExtraTrees")], "est__strategy" : "Linear"} df = {"train" : pd.DataFrame(dataset.data), "target" : pd.Series(dataset.target)} opt.evaluate(params, df) import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.mygov.in/corona-data/covid19-statewise-status/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) #present the data using Pretty table table = PrettyTable() table.field_names = (new_cols) for i in stats: table.add_row(i) table.add_row(['','Total', sum(state_data["Confirmed"]), sum(state_data["Recovered"]), sum(state_data["Deceased"])]) print(table) from mlbox.preprocessing import Reader from mlbox.preprocessing import Drift_thresholder from mlbox.optimisation import Optimiser from mlbox.prediction import Predictor # Paths to the train set and the test set. url = "https://www.kaggle.com/shivamb/netflix-shows" # Name of the feature to predict. # This columns should only be present in the train set. target_name = "rating" # Reading and cleaning all files # Declare a reader for csv files rd = Reader(sep=',') # Return a dictionnary containing three entries # dict["train"] contains training samples withtout target columns # dict["test"] contains testing elements withtout target columns # dict["target"] contains target columns for training samples. data = rd.train_test_split("https://www.kaggle.com/shivamb/netflix-shows", target_name) dft = Drift_thresholder() data = dft.fit_transform(data) # Tuning # Declare an optimiser. Scoring possibilities for classification lie in : # {"accuracy", "roc_auc", "f1", "neg_log_loss", "precision", "recall"} opt = Optimiser(scoring='accuracy', n_folds=3) opt.evaluate(None, data) # Space of hyperparameters # The keys must respect the following syntax : "enc__param". # "enc" = "ne" for na encoder # "enc" = "ce" for categorical encoder # "enc" = "fs" for feature selector [OPTIONAL] # "enc" = "stck"+str(i) to add layer nยฐi of meta-features [OPTIONAL] # "enc" = "est" for the final estimator # "param" : a correct associated parameter for each step. # Ex: "max_depth" for "enc"="est", ... # The values must respect the syntax: {"search":strategy,"space":list} # "strategy" = "choice" or "uniform". Default = "choice" # list : a list of values to be tested if strategy="choice". # Else, list = [value_min, value_max]. # Available strategies for ne_numerical_strategy are either an integer, a float # or in {'mean', 'median', "most_frequent"} # Available strategies for ce_strategy are: # {"label_encoding", "dummification", "random_projection", entity_embedding"} space = {'ne__numerical_strategy': {"search": "choice", "space": [0]}, 'ce__strategy': {"search": "choice", "space": ["label_encoding", "random_projection", "entity_embedding"]}, 'fs__threshold': {"search": "uniform", "space": [0.01, 0.3]}, 'est__max_depth': {"search": "choice", "space": [3, 4, 5, 6, 7]} } # Optimises hyper-parameters of the whole Pipeline with a given scoring # function. Algorithm used to optimize : Tree Parzen Estimator. # # IMPORTANT : Try to avoid dependent parameters and to set one feature # selection strategy and one estimator strategy at a time. best = opt.optimise(space, data, 15) # Make prediction and save the results in save folder. prd = Predictor() prd.fit_predict(best, data) ``` kaggle competitions download -c petfinder-adoption-predictionkaggle competitions download -c petfinder-adoption-url = u$ brew install jenv$!val scoreFn = new OpWorkflowRunnerLocal(workflow).scoreFunction(opParams) val scoreFn = new OpWorkflowRunnerLocal(workflow).scoreFunction(opParams) valInstall GraphViz & PyDot ``` # https://pypi.python.org/pypi/pydot !apt-get -qq install -y graphviz && pip install pydot import pydot ``` Install cartopy ``` !pip install cartopy import cartopy ``` **TPOT** Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science [link text](https://)Randal S. Olson, Nathan Bartley, Ryan J. Urbanowicz, and Jason H. Moore (2016). Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science. Proceedings of GECCO 2016, pages 485-492. > Developed by Randal S. Olson and others at the University of Pennsylvania. **Install TPOT:** > ``` !pip install tpot ``` **Classification using TPOT:** Wine dataset ``` #TPOT from tpot import TPOTClassifier from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split wine=load_wine() #perform a train test split X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, train_size=0.75, test_size=0.25) #TPOT classifier tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=11, cv=5, subsample=0.98, verbosity=2, n_jobs=-2, max_eval_time_mins=0.00000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_digits_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export('tpot_wine_pipeline.py') #TPOT to only use a PyTorch-based logistic regression classifier as its main estimator is: tpot_config = { 'tpot.nn.PytorchLRClassifier': { 'learning_rate': [1e-3, 1e-2, 1e-1, 0.5, 1.] } } ``` Digits dataset ``` #TPOT from tpot import TPOTClassifier from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split wine = load_digits() #perform a train test split X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, train_size=0.75, test_size=0.25) #TPOT classifier tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=1110, cv=5, subsample=0.98, verbosity=2, n_jobs=-2, max_eval_time_mins=0.00000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_digits_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export("tpot_digits_pipeline.py") #TPOT to only use a PyTorch-based logistic regression classifier as its main estimator is: tpot_config = { 'tpot.nn.PytorchLRClassifier': { 'learning_rate': [1e-3, 1e-2, 1e-1, 0.5, 1.] } } ``` Diabetes dataset ``` #TPOT from tpot import TPOTClassifier from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split diabetes = load_diabetes() #perform a train test split X_train, X_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, train_size=0.75, test_size=0.25) #TPOT classifier tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=131, cv=5, subsample=0.999999999, verbosity=2, n_jobs=-2, max_eval_time_mins=0.00000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_diabetes_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export('tpot_diabetes_pipeline.py') #TPOT to only use a PyTorch-based logistic regression classifier as its main estimator is: tpot_config = { 'tpot.nn.PytorchLRClassifier': { 'learning_rate': [1e-3, 1e-2, 1e-1, 0.5, 1.] } } ``` Iris dataset ``` #TPOT from tpot import TPOTClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split diabetes = load_iris() #perform a train test split X_train, X_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, train_size=0.75, test_size=0.25) #TPOT classifier tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=131, cv=5, subsample=0.98, verbosity=2, n_jobs=-2, max_eval_time_mins=0.000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_iris_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export('tpot_iris_pipeline.py') #TPOT to only use a PyTorch-based logistic regression classifier as its main estimator is: tpot_config = { 'tpot.nn.PytorchLRClassifier': { 'learning_rate': [1e-3, 1e-2, 1e-1, 0.5, 1.] } } ``` Latest India Covid-19 status dataset ``` #TPOT from tpot import TPOTClassifier from sklearn.model_selection import train_test_split # data and metric imports import sklearn.model_selection import sklearn.metrics import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.kaggle.com/sudalairajkumar/covid19-in-india" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) India_covid_status = state_data #perform a train test split X_train, X_test, y_train, y_test = train_test_split(India_covid_status.data, India_covid_status.target, train_size=0.75, test_size=0.25) #TPOT classifier tpot=TPOTClassifier(generations=99, population_size=99, mutation_rate=0.7, crossover_rate=0.3, random_state=131, cv=5, subsample=0.98, verbosity=2, n_jobs=-2, max_eval_time_mins=0.00000001, config_dict='TPOT light', memory='รกuto', log_file='tpot_India_covid_status_logs') tpot.fit(X_train, y_train) print(tpot.score(X_test, y_test)) tpot.export('tpot_India_covid_status_pipeline.py') #TPOT to only use a PyTorch-based logistic regression classifier as its main estimator is: tpot_config = { 'tpot.nn.PytorchLRClassifier': { 'learning_rate': [1e-3, 1e-2, 1e-1, 0.5, 1.] } } ``` California housing dataset train_data = /content/sample_data/california_housing_train.csv, test_data = /content/sample_data/california_housing_test.csv ``` import pandas as pd cal_house_train_data=pd.read_csv("/content/sample_data/california_housing_train.csv") cal_house_test_data=pd.read_csv("/content/sample_data/california_housing_test.csv") cal_house_data = pd.merge(cal_house_train_data, cal_house_test_data) #regression #dataset for regression from tpot import TPOTRegressor from sklearn.model_selection import train_test_split #perform a train test split X_train, X_test, y_train, y_test = train_test_split(cal_house_data.data, cal_house_data.target, train_size=0.75, test_size=0.25) tpot_reg=TPOTRegressor(generations=99, population_size=99, mutation_rate=0.75, crossover_rate=0.25, cv=5, subsample=0.95, verbosity=2, n_jobs=-2, scoring='r2', random_state=21, max_eval_time_mins=0.5, config_dict='TPOT light', memory='รกuto', log_file='tpot_cal_house_data_logs') tpot_reg.fit(X_train, y_train) print(tpot_reg.score(X_test, y_test)) tpot_reg.export('tpot_california_house_prices_pipeline.py') ``` Latest India Covid-19 statewise status dataset: ``` import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable # offical ministry of health website url = "https://www.mygov.in/corona-data/covid19-statewise-status/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace("\n", "") for x in row] stats = [] # initialize stats all_rows = soup.find_all("tr") # find all table rows for row in all_rows: stat = extract_contents(row.find_all("td")) # find all data cells # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) # now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) # converting the 'string' data to 'int' state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) # pretty table representation table = PrettyTable() table.field_names = (new_cols) for i in stats: table.add_row(i) table.add_row(["","Total", sum(state_data["Confirmed"]), sum(state_data["Recovered"]), sum(state_data["Deceased"])]) print(table) # barplot to show total confirmed cases Statewise sns.set_style("ticks") plt.figure(figsize = (15,10)) plt.barh(state_data["States/UT"], state_data["Confirmed"].map(int), align = "center", color = "lightblue", edgecolor = "blue") plt.xlabel("No. of Confirmed cases", fontsize = 18) plt.ylabel("States/UT", fontsize = 18) plt.gca().invert_yaxis() # this is to maintain the order in which the states appear plt.xticks(fontsize = 14) plt.yticks(fontsize = 14) plt.title("Total Confirmed Cases Statewise", fontsize = 20) for index, value in enumerate(state_data["Confirmed"]): plt.text(value, index, str(value), fontsize = 12, verticalalignment = "center") plt.show() # donut chart representing nationwide total confirmed, cured and deceased cases group_size = [sum(state_data["Confirmed"]), sum(state_data["Recovered"]), sum(state_data["Deceased"])] group_labels = ["Confirmed\n" + str(sum(state_data["Confirmed"])), "Recovered\n" + str(sum(state_data["Recovered"])), "Deceased\n" + str(sum(state_data["Deceased"]))] custom_colors = ["skyblue", "yellowgreen", "tomato"] plt.figure(figsize = (5,5)) plt.pie(group_size, labels = group_labels, colors = custom_colors) central_circle = plt.Circle((0,0), 0.5, color = "white") fig = plt.gcf() fig.gca().add_artist(central_circle) plt.rc("font", size = 12) plt.title("Nationwide total Confirmed, Recovered and Deceased Cases", fontsize = 16) plt.show() # read the state wise shapefile of India in a GeoDataFrame and preview it map_data = gpd.read_file("Indian_States.shp") map_data.rename(columns = {"st_nm":"States/UT"}, inplace = True) map_data.head() # correct the name of states in the map dataframe map_data["States/UT"] = map_data["States/UT"].str.replace('&', 'and') map_data["States/UT"].replace("Arunanchal Pradesh", "Arunachal Pradesh", inplace = True) map_data["States/UT"].replace("Telangana", "Telengana", inplace = True) map_data["States/UT"].replace("NCT of Delhi", "Delhi", inplace = True) # merge both the dataframes - state_data and map_data merged_data = pd.merge(map_data, state_data, how = "left", on = "States/UT") merged_data.fillna(0, inplace = True) merged_data.drop("Sr.No", axis = 1, inplace = True) merged_data.head() # create figure and axes for Matplotlib and set the title fig, ax = plt.subplots(1, figsize=(20, 12)) ax.axis('off') ax.set_title('Covid-19 Statewise Data - Confirmed Cases', fontdict = {'fontsize': '25', 'fontweight' : '3'}) # plot the figure merged_data.plot(column = 'Confirmed', cmap='YlOrRd', linewidth=0.8, ax=ax, edgecolor='0.8', legend = True) plt.show() import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from tpot.export_utils import set_param_recursive #TPOT from tpot import TPOTClassifier from sklearn.model_selection import train_test_split # data and metric imports import sklearn.model_selection import sklearn.metrics import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.mygov.in/corona-data/covid19-statewise-status/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) import csv data = state_data data = csv.reader(data) print(data) # NOTE: Make sure that the outcome column is labeled 'target' in the data file tpot_data = pd.read_csv(data, sep=',', dtype=np.float64) features = tpot_data.drop('target', axis=1) training_features, testing_features, training_target, testing_target = \ train_test_split(features, tpot_data['target'], random_state=42) # Average CV score on the training set was: 0.9826086956521738 exported_pipeline = make_pipeline( Normalizer(norm="l2"), KNeighborsClassifier(n_neighbors=5, p=2, weights="distance") ) # Fix random state for all the steps in exported pipeline set_param_recursive(exported_pipeline.steps, 'random_state', 42) exported_pipeline.fit(training_features, training_target) results = exported_pipeline.predict(testing_features) ``` **TPOT Regressor** ``` #regression #dataset for regression from sklearn.datasets import load_boston from tpot import TPOTRegressor from sklearn.model_selection import train_test_split import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from tpot.export_utils import set_param_recursive #TPOT from tpot import TPOTRegressor from sklearn.model_selection import train_test_split # data and metric imports import sklearn.model_selection import sklearn.metrics import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.mygov.in/corona-data/covid19-statewise-status/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) #perform a train test split X_train, X_test, y_train, y_test = train_test_split(state_data.data, state_data.target, train_size=0.75, test_size=0.25) tpot_reg=TPOTRegressor(generations=99, population_size=99, mutation_rate=0.75, crossover_rate=0.25, cv=7, subsample=0.95, verbosity=2, n_jobs=-2, scoring='r2', random_state=21, max_eval_time_mins=0.5, config_dict='TPOT light', memory='รกuto', log_file='tpot_state_data_logs') tpot_reg.fit(X_train, y_train) print(tpot_reg.score(X_test, y_test)) tpot_reg.export("tpot_state_data_pipeline.py") #regression #dataset for regression from sklearn.datasets import load_boston from tpot import TPOTRegressor from sklearn.model_selection import train_test_split house_data = load_boston() #perform a train test split X_train, X_test, y_train, y_test = train_test_split(house_data.data, house_data.target, train_size=0.75, test_size=0.25) tpot_reg=TPOTRegressor(generations=99, population_size=99, mutation_rate=0.75, crossover_rate=0.25, cv=5, subsample=0.95, verbosity=2, n_jobs=-2, scoring='r2', random_state=21, max_eval_time_mins=0.5, config_dict='TPOT light', memory='รกuto', log_file='tpot_logs') tpot_reg.fit(X_train, y_train) print(tpot_reg.score(X_test, y_test)) tpot_reg.export('tpot_reg_house_prices_pipeline.py') ``` **Neural network classifier using TPOT-NN:** ``` #Weather forecast using H2O import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.climate.gov/maps-data/datasets" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype weather_data[each_new_col] = stats_data[each_new_col].map(int) X, y = weather_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(weather_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_weather_data_pipeline.py') import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/c/chaii-hindi-and-tamil-question-answering/data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype weather_data[each_new_col] = stats_data[each_new_col].map(int) X, y = weather_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(weather_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_weather_data_pipeline.py') ``` Music dataset using TPOT-NN: ``` #Weather forecast using H2O import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/imsparsh/musicnet-dataset?select=musicnet_metadata.csv" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype music_data[each_new_col] = stats_data[each_new_col].map(int) X, y = music_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(music_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_music_data_pipeline.py') import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "http://www.cs.ubc.ca/labs/beta/Projects/autoweka/datasets/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype autoweka_datasets[each_new_col] = stats_data[each_new_col].map(int) X, y = autoweka_datasets X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(autoweka_datasets.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_autoweka_datasets_pipeline.py') #Weather forecast using H2O import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.climate.gov/maps-data/datasets" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype covid19_india_data[each_new_col] = covid19_india_data[each_new_col].map(int) X, y = covid19_india_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(covid19_india_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, test_size=0.3) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_covid19_india_data_pipeline.py') fig, ax = plt.subplots(1, figsize=(20, 12)) ax.axis(โ€˜offโ€™) ax.set_title(โ€˜Covid-19 Statewise Data โ€” Confirmed Casesโ€™, fontdict = {โ€˜fontsizeโ€™: โ€˜25โ€™, โ€˜fontweightโ€™ : โ€˜3โ€™}) merged_data.plot(column = โ€˜Confirmedโ€™, cmap=โ€™YlOrRdโ€™, linewidth=0.8, ax=ax, edgecolor=โ€™0.8', legend = True) plt.show() import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://docs.gitlab.com/ee/development/value_stream_analytics.html#data-collector" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype covid19_india_data[each_new_col] = covid19_india_data[each_new_col].map(int) X, y = covid19_india_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(covid19_india_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) perf = model.model_performance(test) print(perf.__class__) #Area Under the ROC Curve (AUC) perf.auc() perf.mse() #Cross-validated Performanceยถ cvmodel = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=1000, max_depth=4, learn_rate=0.1, nfolds=5) cvmodel.train(x=x, y=y, training_frame=data) print(cvmodel.auc(train=True)) print(cvmodel.auc(xval=True)) #Grid Search ntrees: Number of trees max_depth: Maximum depth of a tree learn_rate: Learning rate in the GBM ntrees_opt = [5,50,100] max_depth_opt = [2,3,5] learn_rate_opt = [0.1,0.2] hyper_params = {'ntrees': ntrees_opt, 'max_depth': max_depth_opt, 'learn_rate': learn_rate_opt} #Define an "H2OGridSearch" object by specifying the algorithm (GBM) and the hyper parameters from h2o.grid.grid_search import H2OGridSearch gs = H2OGridSearch(H2OGradientBoostingEstimator, hyper_params = hyper_params) gs.train(x=x, y=y, training_frame=train, validation_frame=valid) print(gs) # print out the auc for all of the models auc_table = gs.sort_by('auc(valid=True)',increasing=False) print(auc_table) #best model in terms of auc best_model = h2o.get_model(auc_table['Model Id'][0]) best_model.auc() #generate predictions on the test set using the "best" model, and evaluate the test set AUC best_perf = best_model.model_performance(test) best_perf.auc() #using TPOT-NN from tpot import TPOTClassifier from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, test_size=0.3) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_covid19_india_data_pipeline.py') fig, ax = plt.subplots(1, figsize=(20, 12)) ax.axis(โ€˜offโ€™) ax.set_title(โ€˜Covid-19 Statewise Data โ€” Confirmed Casesโ€™, fontdict = {โ€˜fontsizeโ€™: โ€˜25โ€™, โ€˜fontweightโ€™ : โ€˜3โ€™}) merged_data.plot(column = โ€˜Confirmedโ€™, cmap=โ€™YlOrRdโ€™, linewidth=0.8, ax=ax, edgecolor=โ€™0.8', legend = True) plt.show() #kaggle famous iconic women dataset: import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/kiva/data-science-for-good-kiva-crowdfunding" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype women_data[each_new_col] = stats_data[each_new_col].map(int) X, y = women_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=131311) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(women_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=100, generations=100) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_women_data_pipeline.py') from tpot import TPOTClassifier from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split X, y = make_blobs(n_samples=100, centers=2, n_features=3, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_data_pipeline.py') ``` **NOTE:** Turns out TPOT cannot solve multi label regression problems at this time as below; ``` #Latest India Covid-19 statewise status using TPOT-NN from tpot import TPOTClassifier import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from tpot.export_utils import set_param_recursive #TPOT from tpot import TPOTClassifier from sklearn.model_selection import train_test_split # data and metric imports import sklearn.model_selection import sklearn.metrics import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.mygov.in/corona-data/covid19-statewise-status/" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) def getNumbers(): return 'one', 'two' one, two = getNumbers() X, y = getNumbers() X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=0.25) #TPOT-NN clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) #NOTE: Turns out TPOT cannot solve multi label regression problems at this time '''clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_state_data_pipeline.py') ''' #import scikit-learn import sklearn ``` **Auto-Sklearn** arXiv:2007.04074v2 [cs.LG] arXiv:2007.04074 @article{ASKL2, title = {Auto-Sklearn 2.0}, author = {Feurer, Matthias and Eggensperger, Katharina and Falkner, Stefan and Lindauer, Marius and Hutter, Frank}, booktitle = {Advances in Neural Information Processing Systems 28}, year = {2020}, journal = {arXiv:2007.04074 [cs.LG]}, } **Install Auto-Sklearn** ``` !python3 -m pip install --upgrade pip !pip3 install --upgrade pandas !pip3 install auto-sklearn !pip3 install --upgrade scipy !pip3 install --upgrade auto-sklearn !pip install auto-sklearn==0.10.0 !pip install --upgrade pip !sudo apt-get install build-essential swig !curl https://raw.githubusercontent.com/automl/auto-sklearn/master/requirements.txt | xargs -n 1 -L 1 pip install !pip install auto-sklearn==0.10.0 !pip install matplotlib-venn !apt-get -qq install -y libfluidsynth1 ``` Install 7zip reader libarchive ``` # https://pypi.python.org/pypi/libarchive !apt-get -qq install -y libarchive-dev && pip install -U libarchive import libarchive import autosklearn.classification cls = autosklearn.classification.AutoSklearnClassifier() import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = sklearn.datasets.load_iris(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) cls.fit(X_train, y_train) predictions = cls.predict(X_test) import sklearn.model_selection import sklearn.datasets import sklearn.metrics if __name__ == "__main__": X, y = sklearn.datasets.load_iris(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) automl = autosklearn.classification.AutoSklearnClassifier() automl.fit(X_train, y_train) y_hat = automl.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat)) import autosklearn.classification cls = autosklearn.classification.AutoSklearnClassifier() import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = sklearn.datasets.load_digits(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) cls.fit(X_train, y_train) predictions = cls.predict(X_test) import sklearn.model_selection import sklearn.datasets import sklearn.metrics if __name__ == "__main__": X, y = sklearn.datasets.load_digits(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) automl = autosklearn.classification.AutoSklearnClassifier() automl.fit(X_train, y_train) y_hat = automl.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_hat)) # make a GET request to fetch the raw HTML content web_content = requests.get("https://www.kaggle.com/kiva/data-science-for-good-kiva-crowdfunding").content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols=[] ozone_data = pd.DataFrame(data = stats, columns = new_cols) ozone_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype ozone_data[new_cols] = ozone_data[new_cols].map(int) X, y = ozone_data X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=110011) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train) y_pred = clf.predict(X_test) print(metrics.confusion_matrix(y_test, y_pred)) print(metrics.classification_report(y_test, y_pred)) ``` **ConfigSpace** @article{ title = {BOAH: A Tool Suite for Multi-Fidelity Bayesian Optimization & Analysis of Hyperparameters}, author = {M. Lindauer and K. Eggensperger and M. Feurer and A. Biedenkapp and J. Marben and P. Mรผller and F. Hutter}, journal = {arXiv:1908.06756 {[cs.LG]}}, date = {2019}, } **Install ConfigSpace:** ``` !pip install ConfigSpace import ConfigSpace as CS cs = CS.ConfigurationSpace(seed=1234) #choose hyperparameter alpha import ConfigSpace.hyperparameters as CSH alpha = CSH.UniformFloatHyperparameter(name='alpha', lower=0, upper=1) #create a ConfigurationSpace object import ConfigSpace as CS import ConfigSpace.hyperparameters as CSH cs = CS.ConfigurationSpace(seed=1234) a = CSH.UniformIntegerHyperparameter('a', lower=10, upper=100, log=False) b = CSH.CategoricalHyperparameter('b', choices=['red', 'green', 'blue']) cs.add_hyperparameters([a, b]) cs.sample_configuration() #add ordinal hyper-parameter ord_hp = CSH.OrdinalHyperparameter('ordinal_hp', sequence=['10', '20', '30']) cs.add_hyperparameter(ord_hp) #sample a configuration from the ConfigurationSpace object cs.sample_configuration() ``` **Install Auto-PyTorch** ``` !pip install autopytorch from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.metrics import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable #Web Scraping url = "https://www.kaggle.com/sudalairajkumar/covid19-in-india" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = ["Sr.No", "States/UT","Confirmed","Recovered","Deceased"] state_data = pd.DataFrame(data = stats, columns = new_cols) state_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype state_data["Confirmed"] = state_data["Confirmed"].map(int) state_data["Recovered"] = state_data["Recovered"].map(int) state_data["Deceased"] = state_data["Deceased"].map(int) X, y = state_data X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = sklearn.datasets.load_iris(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = sklearn.datasets.load_wine(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) from autoPyTorch import AutoNetClassification # data and metric imports import sklearn.model_selection import sklearn.datasets import sklearn.metrics X, y = sklearn.datasets.load_linnerud(return_X_y=True) X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=1) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) # data and metric imports import sklearn.model_selection import sklearn.metrics import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns url = "https://www.kaggle.com/brsdincer/ozone-tendency-new-data-20182021-nasa" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols=[] ozone_data = pd.DataFrame(data = stats, columns = new_cols) ozone_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype ozone_data[new_cols] = ozone_data[new_cols].map(int) X, y = ozone_data X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=110011) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=30, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) # data and metric imports import sklearn.model_selection import sklearn.metrics import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns url = "https://www.kaggle.com/kiva/data-science-for-good-kiva-crowdfunding" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols=[] coll_data = pd.DataFrame(data = stats, columns = new_cols) coll_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype coll_data[new_cols] = coll_data[new_cols].map(int) X, y = coll_data X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=11001100) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=333, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) # data and metric imports import sklearn.model_selection import sklearn.metrics import requests from bs4 import BeautifulSoup import geopandas as gpd from prettytable import PrettyTable import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns url = "https://www.kaggle.com/nipunarora8/age-gender-and-ethnicity-face-data-csv" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols=[] face_data = pd.DataFrame(data = stats, columns = new_cols) face_data.head() #scraped data columns are of โ€˜stringโ€™ datatype #convert them into โ€˜int' datatype face_data[new_cols] = face_data[new_cols].map(int) X, y = face_data X_train, X_test, y_train, y_test = \ sklearn.model_selection.train_test_split(X, y, random_state=11001100) # running Auto-PyTorch autoPyTorch = AutoNetClassification("tiny_cs", # config preset log_level='info', max_runtime=999999999**10000000, min_budget=333, max_budget=999999999*100000) autoPyTorch.fit(X_train, y_train, validation_split=0.3) y_pred = autoPyTorch.predict(X_test) print("Accuracy score", sklearn.metrics.accuracy_score(y_test, y_pred)) ``` Install AutoGluon ``` #Install autogluon python3 -m pip install -U pip python3 -m pip install -U setuptools wheel python3 -m pip install -U "mxnet<2.0.0" python3 -m pip install autogluon #Image Prediction with AutoGluon #import autogluon %matplotlib inline import autogluon.core as ag from autogluon.vision import ImageDataset import pandas as pd #celeb faces (celebA) dataset import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/c/petfinder-adoption-prediction/data" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype olympics2021_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1221) csv_file_list=["BreedLabels.csv", "ColorLabels.csv", "PetFinder-BreedLabels.csv", "PetFinder-ColorLabels.csv", "PetFinder-StateLabels.csv", "PetFinder-StateLabels.csv (285 B)", "StateLabels.csv", "breed_labels.csv", "color_labels.csv", "state_labels.csv"] for each_csv_file in csv_file_list: csv_file = ag.utils.download(each_csv_file) df = pd.read_csv(csv_file) df.head() df = ImageDataset.from_csv(csv_file) df.head() train_data, _, test_data = ImageDataset.from_folders(each_csv_file, train='train', test='test') print('train #', len(train_data), 'test #', len(test_data)) train_data.head() #load the splits with from_folder root = os.path.join(os.path.dirname(train_data.iloc[0]['image']), '..') all_data = ImageDataset.from_folder(root) all_data.head() #split the dataset train, val, test = all_data.random_split(val_size=0.1, test_size=0.1) print('train #:', len(train), 'test #:', len(test)) #convert a list of images to dataset pets = ag.utils.download(each_csv_file) pets = ag.utils.unzip(pets) image_list = [x for x in os.listdir(os.path.join(pets, 'images')) if x.endswith('jpg')] new_data = ImageDataset.from_name_func(image_list, label_fn, root=os.path.join(os.getcwd(), pets, 'images')) new_data #visualize the images new_data.show_images() #image prediction import autogluon.core as ag from autogluon.vision import ImagePredictor, ImageDataset train_dataset, _, test_dataset = ImageDataset.from_folders("img_align_pets.zip") print(train_dataset) #fit a classifier predictor = ImagePredictor() # since the original dataset does not provide validation split, the `fit` function splits it randomly with 90/10 ratio predictor.fit(train_dataset, hyperparameters={'epochs': 1000}) #The best Top-1 accuracy achieved on the validation set is fit_result = predictor.fit_summary() print('Top-1 train acc: %.3f, val acc: %.3f' %(fit_result['train_acc'], fit_result['valid_acc'])) #predict on a new image image_path = test_dataset.iloc[0]['image'] result = predictor.predict(image_path) print(result) bulk_result = predictor.predict(test_dataset) print(bulk_result) #generate image features with a classifier image_path = test_dataset.iloc[0]['image'] feature = predictor.predict_feature(image_path) print(feature) #validation and test top-1 accuracy test_acc = predictor.evaluate(test_dataset) print('Top-1 test acc: %.3f' % test_acc['top1']) #save and load the classifiers filename = 'predictor.ag' predictor.save(filename) predictor_loaded = ImagePredictor.load(filename) # use predictor_loaded as usual result = predictor_loaded.predict(image_path) print(result) #use AutoGluon to produce an ImagePredictor to classify images import autogluon.core as ag from autogluon.vision import ImagePredictor, ImageDataset train_data, _, test_data = ImageDataset.from_folders("img_align_celeba.zip") model = ag.Categorical('resnet18_v1b', 'mobilenetv3_small') model_list = ImagePredictor.list_models() #Specify the training hyper-parameters batch_size = 8 lr = ag.Categorical(1e-2, 1e-3) #Bayesian Optimization hyperparameters={'model': model, 'batch_size': batch_size, 'lr': lr, 'epochs': 2} predictor = ImagePredictor() predictor.fit(train_data, time_limit=60*10, hyperparameters=hyperparameters, hyperparameter_tune_kwargs={'searcher': 'bayesopt', 'num_trials': 2}) print('Top-1 val acc: %.3f' % predictor.fit_summary()['valid_acc']) #Load the test dataset and evaluate results = predictor.evaluate(test_data) print('Test acc on hold-out data:', results) #Global Superstore Orders 2016 dataset #Tabular prediction with AutoGluon #Predicting Columns in a Table from autogluon.tabular import TabularDataset, TabularPredictor train_data = TabularDataset('Global Superstore Orders 2016.csv') subsample_size = 999000000000 # subsample subset of data for faster demo, try setting this to much larger values train_data = train_data.sample(n=subsample_size, random_state=0) train_data.head() label = 'class' print("Summary of class variable: \n", train_data[label].describe()) #use AutoGluon to train multiple models save_path = 'agModels-predictClass' # specifies folder to store trained models predictor = TabularPredictor(label=label, path=save_path).fit(train_data) test_data = TabularDataset('Global Superstore Orders 2016.csv') y_test = test_data[label] # values to predict test_data_nolab = test_data.drop(columns=[label]) # delete label column to prove we're not cheating test_data_nolab.head() #predictor = TabularPredictor.load(save_path) y_pred = predictor.predict(test_data_nolab) print("Predictions: \n", y_pred) perf = predictor.evaluate_predictions(y_true=y_test, y_pred=y_pred, auxiliary_metrics=True) predictor.leaderboard(test_data, silent=True) from autogluon.tabular import TabularPredictor predictor = TabularPredictor(label=label).fit(train_data='Global Superstore Orders 2016.csv') #.fit() returns a predictor object pred_probs = predictor.predict_proba(test_data_nolab) pred_probs.head(5) #summarize what happened during fit results = predictor.fit_summary(show_plot=True) print("AutoGluon infers problem type is: ", predictor.problem_type) print("AutoGluon identified the following types of features:") print(predictor.feature_metadata) predictor.leaderboard(test_data, silent=True) predictor.predict(test_data, model='LightGBM') #Maximizing predictive performance time_limit = 11 metric = 'roc_auc' # specify the evaluation metric here predictor = TabularPredictor(label, eval_metric=metric).fit(train_data, time_limit=time_limit, presets='best_quality') predictor.leaderboard(test_data, silent=True) #Tabular prediction with AutoGluon #Predicting Columns in a Table from autogluon.tabular import TabularDataset, TabularPredictor train_data = TabularDataset('pueblosMagicos.csv') subsample_size = 999000000000 # subsample subset of data for faster demo, try setting this to much larger values train_data = train_data.sample(n=subsample_size, random_state=0) train_data.head() label = 'class' print("Summary of class variable: \n", train_data[label].describe()) #use AutoGluon to train multiple models save_path = 'agModels-predictClass' # specifies folder to store trained models predictor = TabularPredictor(label=label, path=save_path).fit(train_data) test_data = TabularDataset('pueblosMagicos.csv') y_test = test_data[label] # values to predict test_data_nolab = test_data.drop(columns=[label]) # delete label column to prove we're not cheating test_data_nolab.head() #predictor = TabularPredictor.load(save_path) y_pred = predictor.predict(test_data_nolab) print("Predictions: \n", y_pred) perf = predictor.evaluate_predictions(y_true=y_test, y_pred=y_pred, auxiliary_metrics=True) predictor.leaderboard(test_data, silent=True) from autogluon.tabular import TabularPredictor predictor = TabularPredictor(label=label).fit(train_data='pueblosMagicos.csv') #.fit() returns a predictor object pred_probs = predictor.predict_proba(test_data_nolab) pred_probs.head(5) #summarize what happened during fit results = predictor.fit_summary(show_plot=True) print("AutoGluon infers problem type is: ", predictor.problem_type) print("AutoGluon identified the following types of features:") print(predictor.feature_metadata) predictor.leaderboard(test_data, silent=True) predictor.predict(test_data, model='LightGBM') #Maximizing predictive performance time_limit = 11 metric = 'roc_auc' # specify the evaluation metric here predictor = TabularPredictor(label, eval_metric=metric).fit(train_data, time_limit=time_limit, presets='best_quality') predictor.leaderboard(test_data, silent=True) #Regression (predicting numeric table columns) pueblo_column = 'PUEBLO' print("Summary of PUEBLO variable: \n", train_data[pueblo_column].describe()) predictor_pueblo = TabularPredictor(label=pueblo_column, path="agModels-predictAge").fit(train_data, time_limit=60) performance = predictor_pueblo.evaluate(test_data) #see the per-model performance predictor_pueblo.leaderboard(test_data, silent=True) #All NeurIPS (NIPS) Papers dataset import requests from bs4 import BeautifulSoup # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/rowhitswami/nips-papers-1987-2019-updated" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype weather_data[each_new_col] = stats_data[each_new_col].map(int) X, y = weather_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=1313) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(weather_data.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) #using TPOT-NN from tpot import TPOTClassifier 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, test_size=0.25) clf = TPOTClassifier(config_dict='TPOT NN', template='Selector-Transformer-PytorchLRClassifier', verbosity=2, population_size=10, generations=10) clf.fit(X_train, y_train) print(clf.score(X_test, y_test)) clf.export('tpot_nn_weather_data_pipeline.py') ``` Install AutoKeras ``` !pip install autokeras import numpy as np import tensorflow as tf from tensorflow.keras.datasets import mnist import autokeras as ak input_node = ak.ImageInput() output_node = ak.Normalization()(input_node) output_node1 = ak.ConvBlock()(output_node) output_node2 = ak.ResNetBlock(version="v2")(output_node) output_node = ak.Merge()([output_node1, output_node2]) output_node = ak.ClassificationHead()(output_node) auto_model = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=100 ) #prepare data to run the model x_train, y_train), (x_test, y_test) = mnist.load_data() print(x_train.shape) print(y_train.shape) print(y_train[:3]) # Feed the AutoModel with training data. auto_model.fit(x_train[:100], y_train[:100], epochs=1000) # Predict with the best model predicted_y = auto_model.predict(x_test) # Evaluate the best model with testing data print(auto_model.evaluate(x_test, y_test)) #implement new block class SingleDenseLayerBlock(ak.Block): def build(self, hp, inputs=None): # Get the input_node from inputs. input_node = tf.nest.flatten(inputs)[0] layer = tf.keras.layers.Dense( hp.Int("num_units", min_value=32, max_value=512, step=32) ) output_node = layer(input_node) return output_node # Build the AutoModel input_node = ak.Input() output_node = SingleDenseLayerBlock()(input_node) output_node = ak.RegressionHead()(output_node) auto_model = ak.AutoModel(input_node, output_node, overwrite=True, max_trials=100) # Prepare Data num_instances = 100 x_train = np.random.rand(num_instances, 20).astype(np.float32) y_train = np.random.rand(num_instances, 1).astype(np.float32) x_test = np.random.rand(num_instances, 20).astype(np.float32) y_test = np.random.rand(num_instances, 1).astype(np.float32) # Train the model auto_model.fit(x_train, y_train, epochs=1000) print(auto_model.evaluate(x_test, y_test)) import numpy as np import pandas as pd from autokeras import StructuredDataClassifier from sklearn.model_selection import train_test_split import requests from bs4 import BeautifulSoup import tensorflow as tf import autokeras as ak input_node = ak.ImageInput() output_node = ak.Normalization()(input_node) output_node1 = ak.ConvBlock()(output_node) output_node2 = ak.ResNetBlock(version="v2")(output_node) output_node = ak.Merge()([output_node1, output_node2]) output_node = ak.ClassificationHead()(output_node) # Import H2O GBM: from h2o.estimators.gbm import H2OGradientBoostingEstimator url = "https://www.kaggle.com/kannan1314/apple-stock-price-all-time?select=Apple.csv" # make a GET request to fetch the raw HTML content web_content = requests.get(url).content # parse the html content soup = BeautifulSoup(web_content, "html.parser") # remove any newlines and extra spaces from left and right extract_contents = lambda row: [x.text.replace('\n', '') for x in row] # find all table rows and data cells within stats = [] all_rows = soup.find_all('tr') for row in all_rows: stat = extract_contents(row.find_all('td')) # notice that the data that we require is now a list of length 5 if len(stat) == 5: stats.append(stat) #now convert the data into a pandas dataframe for further processing new_cols = [] for each_new_col in row: stats_data = pd.DataFrame(data = stats, columns = each_new_col) stats_data.head() #scraped data columns are of โ€˜stringโ€™ datatype so convert them into โ€˜int' datatype kaggle_data[each_new_col] = stats_data[each_new_col].map(int) X, y = stats_data X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, random_state=11) model = H2OGradientBoostingEstimator(distribution='bernoulli', ntrees=100, max_depth=4, learn_rate=0.1) #Specify the predictor set and response x = list(stats_train.columns) x #train the model model.train(x=x, y=y, training_frame=train, validation_frame=valid) print(model) auto_model = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=100) #prepare data to run the model x_train, y_train), (x_test, y_test) = kaggle_data print(x_train.shape) print(y_train.shape) print(y_train[:3]) # Feed the AutoModel with training data. auto_model.fit(x_train[:100], y_train[:100], epochs=1000) # Predict with the best model predicted_y = auto_model.predict(x_test) # Evaluate the best model with testing data print(auto_model.evaluate(x_test, y_test)) #implement new block class SingleDenseLayerBlock(ak.Block): def build(self, hp, inputs=None): # Get the input_node from inputs. input_node = tf.nest.flatten(inputs)[0] layer = tf.keras.layers.Dense( hp.Int("num_units", min_value=32, max_value=512, step=32) ) output_node = layer(input_node) return output_node # Build the AutoModel input_node = ak.Input() output_node = SingleDenseLayerBlock()(input_node) output_node = ak.RegressionHead()(output_node) auto_model = ak.AutoModel(input_node, output_node, overwrite=True, max_trials=100) # Prepare Data num_instances = 100 x_train = np.random.rand(num_instances, 20).astype(np.float32) y_train = np.random.rand(num_instances, 1).astype(np.float32) x_test = np.random.rand(num_instances, 20).astype(np.float32) y_test = np.random.rand(num_instances, 1).astype(np.float32) # Train the model auto_model.fit(x_train, y_train, epochs=1000) print(auto_model.evaluate(x_test, y_test)) import argparse import os import autokeras as ak import tensorflow_cloud as tfc from tensorflow.keras.datasets import mnist parser = argparse.ArgumentParser(description="Model save path arguments.") parser.add_argument("--path", required=True, type=str, help="Keras model save path") args = parser.parse_args() tfc.run( chief_config=tfc.COMMON_MACHINE_CONFIGS["V100_1X"], docker_base_image="haifengjin/autokeras:1.0.3", ) # Prepare the dataset. (x_train, y_train), (x_test, y_test) = mnist.load_data() print(x_train.shape) # (60000, 28, 28) print(y_train.shape) # (60000,) print(y_train[:3]) # array([7, 2, 1], dtype=uint8) # Initialize the ImageClassifier. clf = ak.ImageClassifier(max_trials=2) # Search for the best model. clf.fit(x_train, y_train, epochs=10) # Evaluate on the testing data. print("Accuracy: {accuracy}".format(accuracy=clf.evaluate(x_test, y_test)[1])) clf.export_model().save(os.path.join(args.path, "model.h5")) ``` **Deliverables:** * Python package with an Automated ML function to be called using any data frame (dataset) to give a good trained model. * Details on the steps automated and the scenario in which they execute. * Any scenario which is not automated. TPOT cannot solve multi-label regression problems at this point of time.
github_jupyter
``` import random from typing import Optional import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm_notebook as tqdm %matplotlib inline def random_position(max_height, max_width): return np.random.randint(0, max_height), np.random.randint(0, max_width) def compare(x, y): return np.array_equal(x, y) class Gridworld: def __init__(self, height, width): self.height = height self.width = width self.initial_state = None self.initial_player_pos = None self.state = np.zeros((height, width, 4), dtype=int) self.player = np.array([0, 0, 0, 1]) self.wall = np.array([0, 0, 1, 0]) self.pit = np.array([0, 1, 0, 0]) self.goal = np.array([1, 0, 0, 0]) self.player_position = None self.world_ = None self.up = 0 self.right = 1 self.down = 2 self.left = 3 def set_player_position(self, position): if self.player_position is not None: self.state[tuple(self.player_position)] = np.zeros(4) self.player_position = tuple(position) self.state[tuple(position)] = self.player def save_state(self): self.initial_state = np.copy(self.state) self.initial_player_pos = np.copy(self.player_position) @classmethod def deterministic_easy(cls, height=4, width=4): world = cls(height, width) #place player world.set_player_position((0, 1)) #place goal world.state[3, 3] = world.goal world.save_state() return world @classmethod def deterministic(cls, height=4, width=4): world = cls(height, width) #place player world.set_player_position((0, 1)) #place wall world.state[2, 2] = world.wall #place pit world.state[1, 1] = world.pit #place goal world.state[3, 3] = world.goal world.save_state() return world @classmethod def random_player_pos(cls, height=4, width=4): world = cls(height, width) pos = random_position(height, width) while pos in ((2, 2), (1, 1), (1, 2)): pos = random_position(height, width) #place player world.set_player_position(pos) #place wall world.state[2, 2] = world.wall #place pit world.state[1, 1] = world.pit #place goal world.state[1, 2] = world.goal world.save_state() return world @classmethod def random(cls, height=4, width=4): world = cls(height, width) length = height * width places = [(i, j) for i in range(height) for j in range(width)] positions = random.sample(places, 4) #place player world.set_player_position(positions[0]) #place wall world.state[positions[1]] = world.wall #place pit world.state[positions[2]] = world.pit #place goal world.state[positions[3]] = world.goal world.save_state() return world def step(self, action): diff = (0, 0) if action == self.up and self.player_position[0] > 0: diff = (-1, 0) elif action == self.right and self.player_position[1] < self.width - 1: diff = (0, 1) elif action == self.down and self.player_position[0] < self.height - 1: diff = (1, 0) elif action == self.left and self.player_position[1] > 0: diff = (0, -1) old_pos = tuple(np.copy(self.player_position)) new_pos = tuple(np.add(self.player_position, diff)) done = False reward = -1 if compare(self.state[new_pos], self.wall): new_pos = old_pos elif compare(self.state[new_pos], self.pit): done = True reward = -10 elif compare(self.state[new_pos], self.goal): done = True reward = 10 old_state = np.copy(self.state) self.set_player_position(new_pos) return old_state, reward, self.state, done def reset(self): self.state = np.copy(self.initial_state) self.player_position = np.copy(self.initial_player_pos) return self.state def display(self): grid = np.empty((self.height, self.width), dtype=str) for i in range(self.height): for j in range(self.width): point = self.state[i, j] if compare(point, self.player): grid[i, j] = '@' elif compare(point, self.wall): grid[i, j] = 'W' elif compare(point, self.goal): grid[i, j] = '+' elif compare(point, self.pit): grid[i, j] = '^' else: grid[i, j] = ' ' return grid class QDistFunction(nn.Module): def __init__(self): super().__init__() self.l1 = nn.Linear(64, 164) self.l2 = nn.Linear(164, 150) self.l3 = nn.Linear(150, 21 * 4) self.smax = nn.Softmax() def forward(self, x): x = x.view(-1) x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = self.l3(x) # view -> softmax x = torch.cat( [F.softmax(x[21 * a:21 * (a + 1)]) for a in range(4)], dim=0 ) return x def fit_step( self, old_state, new_state, action, reward, range_, gamma, loss_fun, optimizer, grad_clip: Optional[float] = None, ) -> None: self.train() optimizer.zero_grad() # forward + backward + optimize outputs = self(old_state) new_qdist = self(new_state) len_range = len(range_) # Softmax this rather than using max EV evs = [ sum(z * p for z, p in zip(range_, new_qdist[len_range * a:len_range * (a + 1)])) for a in range(4) ] a = np.argmax(evs) dist = new_qdist[21 * a:21 * (a + 1)] m = torch.zeros((21,)) for i, z in enumerate(range_): tzj = reward + gamma * z if tzj < -10: tzj = -10 elif tzj > 10: tzj = 10 bj = tzj + 10 l = int(np.floor(bj)) u = int(np.ceil(bj)) m[l] += dist[i] * (u - bj) m[u] += dist[i] * (bj - l) loss = loss_fun(outputs[21 * action:21 * (action + 1)], m.detach()) loss.backward() if grad_clip is not None: torch.nn.utils.clip_grad_norm_( self.parameters(), grad_clip ) optimizer.step() self.eval() class Agent: def __init__(self, env, epsilon, gamma, lr=0.01, max_steps=100): self.q = QDistFunction() self.env = env self.epsilon = epsilon self.gamma = gamma self.max_steps = max_steps self.loss_fun = nn.BCELoss() self.optimizer = torch.optim.Adam(self.q.parameters(), lr) self.range_ = list(range(-10, 11)) def run_episode(self): done = False total_reward = 0.0 while not done: qdist = self.q( torch.tensor(self.env.state, dtype=torch.float32) ) samples = torch.cat( [torch.multinomial(qdist[21 * a:21 * (a + 1)], 1) for a in range(4)] ) action = samples.max(0)[1] old_state, reward, _, done = self.env.step(action) total_reward += reward self.q.fit_step( torch.tensor(old_state, dtype=torch.float32), torch.tensor(self.env.state, dtype=torch.float32), action, reward, self.range_, self.gamma, self.loss_fun, self.optimizer ) return total_reward def run_model(self, world=0): done = False self.env.reset() print(self.env.display()) for _ in range(self.max_steps): qdist = self.q(torch.tensor(self.env.state, dtype=torch.float32)) len_range = len(self.range_) evs = [ sum(z * p for z, p in zip(self.range_, qdist[len_range * a:len_range * (a + 1)])) for a in range(4) ] action = np.argmax(evs) _, _, _, done = self.env.step(action) print(self.env.display()) if done: break def train(self, epochs=1000): self.env.reset() rewards = np.zeros(epochs) for i in tqdm(range(epochs)): rewards[i] = self.run_episode() self.env.reset() return pd.Series(rewards) agent = Agent( Gridworld.deterministic_easy(), epsilon=0.1, gamma=0.9, ) rewards = agent.train(2000) rewards.expanding().mean().plot() plt.show() agent.run_model() ```
github_jupyter
``` import matplotlib.pyplot as plt import pandas as pd import os import numpy as np import datetime import glob from pathlib import Path from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score DOWNLOAD_DIR = 'c:/entsoe-data' ``` This will import the data, you have to run it to be able to solve the homework. ``` def read_single_csv_entso_e(file): return pd.read_csv(file, sep='\t', encoding='utf-16', parse_dates=["DateTime"]) def load_complete_entso_e_data(directory): pattern = Path(directory) / '*.csv' files = glob.glob(str(pattern)) if not files: raise ValueError(f"No files found when searching in {pattern}, wrong directory?") print(f'Concatenating {len(files)} csv files...') each_csv_file = [read_single_csv_entso_e(file) for file in files] data = pd.concat(each_csv_file, ignore_index=True) data = data.sort_values(by=["AreaName", "DateTime"]) data = data.set_index("DateTime") print("Loading done.") return data power_demand = load_complete_entso_e_data(DOWNLOAD_DIR) ``` # Exercise 1 - Calculate the relation of Wednesday average consumption to Sunday average consumption for selected countries In this exercise, calculate the relation of Wednesday average consumption to Sunday average consumption for the following countries: Austria, Germany, United Kingdom, Spain, Sweden, Italy, Croatia. (1) First create a variable that contains only power consumption data for these countries. The pandas command ```isin()``` may be very helpful here. Reduce the data to only consider the period 2015-01-01 until 2019-12-31. The lecture slides may contain relevant code here. (2) Then, group the data by weekday and country (i.e. AreaName). Use ```groupby``` and ```mean```for that purpose. (3) Calculate for all countries the proportion of Wednesday (day 2) and Sunday (day 6) by dividing the two values. (4) For which country, this relative value is highest? What could this indicate? ``` power_demand #(1) power_demand_1= power_demand["AreaName"].isin(["Austria", "Germany", "United Kingdom", "Spain", "Sweden", "Italy", "Croatia"]) power_consumption_data = power_consumption_data['2015-01-01':'2019-12-31'] print(power_consumption_data) #(2) power_consumption_mean = power_consumption_data.groupby([power_consumption_data.index.weekday, "AreaName"]).mean() power_consumption_mean #(3) Wednesday = power_consumption_mean[(power_consumption_mean.index.get_level_values("DateTime")==2)] Sunday = power_consumption_mean[(power_consumption_mean.index.get_level_values("DateTime")==6)] proportion = Wednesday["TotalLoadValue"].values/Sunday["TotalLoadValue"].values print (proportion) #(4) # For which country, this relative value is highest? What could this indicate? รคh ``` # Exercise 2 - Calculate the monthly average consumption as deviation from mean consumption For the same countries as in the above dataset, calculate the monthly mean consumption as deviation from the mean of consumption over the whole time. Plot the curves for all countries. (1) First create a variable that contains only power consumption data for the selected countries. The pandas command ```isin()``` may be very helpful here. If you did Exercise 1, you can use the same dataset. (2) Then, aggregate the data by country (i.e. AreaName) and month. Use ```groupby``` and ```mean``` for that purpose. Select the column ```TotalLoadValue``` from the result. (3) Aggregate the data by country (i..e AreaName) only, i.e. calculate the average consumption by country using ```groupby``` and ```mean```. Select the column ```TotalLoadValue``` from the result. (4) Divide the result of (2) by (3) and observe how well broadcasting works here. (5) Use the command ```unstack``` on the result. How does the table look now? Plot the result. If your resulting, unstacked dataframe is called ```result```, you may use ```result.plot()``` to get a nice plot. (6) How would you explain the difference in the curve between Croatia and Sweden? ``` #1 power_demand_2= power_demand["AreaName"].isin(["Austria", "Germany", "United Kingdom", "Spain", "Sweden", "Italy", "Croatia"]) power_consumption = power_consumption_data['2015-01-01':'2019-12-31'] #2 power_consumption_month = power_consumption.groupby([power_consumption.index.month, "AreaName"]).mean() TotalLoad_month = power_consumption_month['TotalLoadValue'] #3 power_consumption_country_mean = power_consumption.groupby("AreaName").mean() TotalLoad_country_mean = power_consumption_country_mean['TotalLoadValue'] #4 TotalLoad = TotalLoad_month/TotalLoad_country_mean result = TotalLoad.unstack result().plot() #How would you explain the difference in the curve between Croatia and Sweden? Hm ``` # Exercise 3 - calculate the hourly average consumption as deviation from mean consumption Do the same as in exercise 2, but now for the hourly average consumption. I.e. how much is consumed on each of the 24 hours of a day? Which country has the lowest, which the highest variability? What may be the reason for it? ``` #1 power_demand_2= power_demand["AreaName"].isin(["Austria", "Germany", "United Kingdom", "Spain", "Sweden", "Italy", "Croatia"]) power_consumption = power_consumption_data['2015-01-01':'2019-12-31'] #2 power_consumption_hour = power_consumption.groupby([power_consumption.index.hour, "AreaName"]).mean() TotalLoad_hour = power_consumption_hour['TotalLoadValue'] #3 power_consumption_country_mean = power_consumption.groupby("AreaName").mean() TotalLoad_country_mean = power_consumption_country_mean['TotalLoadValue'] #4 TotalLoad = TotalLoad_hour/TotalLoad_country_mean result = TotalLoad.unstack result().plot() #Which country has the lowest, which the highest variability? Croatia, United Kingdom #What may be the reason for it? Hm ``` # Exercise 4 - Calculate the average load per capita Below you find a table with population data for our selected countries. You should use it to calculate per capita consumption. (1) Calculate the average load in all countries using ```groupby``` and ```mean``` and select the column ```TotalLoadValue``` from the result. (2) Divide the result by the ```Population``` column of the dataframe ```population```. Observe, how broadcasting helps here nicely. (3) Plot the result. Which country has the highest load, which the lowest? What may be the reason? In which unit is this value? How could we convert it to MWh per year? ``` population = pd.DataFrame({'Country': ["Austria", "Croatia", "Germany", "Italy", "Spain", "Sweden", "United Kingdom"], 'Population': [8840521, 4087843, 82905782, 60421760, 46796540, 10175214, 66460344]}) population.index = population["Country"] population #1 average_load = power_demand.groupby("AreaName").mean() average_total_load = average_load["TotalLoadValue"] #2 load_population = average_total_load/population["Population"] #3 load_population.dropna().plot(style='o') #highest load: Sweden #lowest load: Croatia #Unit: MW per person # hm ```
github_jupyter
``` import pandas as pd from pathlib import Path from sklearn.pipeline import make_pipeline from yellowbrick.model_selection import LearningCurve from yellowbrick.regressor import ResidualsPlot from yellowbrick.regressor import PredictionError from sklearn.gaussian_process.kernels import RBF,WhiteKernel,ConstantKernel from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.feature_selection import VarianceThreshold from sklearn.model_selection import KFold from imblearn import over_sampling as ovs from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler from sklearn.model_selection import cross_val_score from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score from sklearn import metrics from sklearn.externals import joblib from sklearn.model_selection import GridSearchCV,RepeatedKFold from sklearn.model_selection import train_test_split %matplotlib inline ConstantKernel? sns.set_context(context="paper") ABPRED_DIR = Path().cwd().parent #dataframe final df_final = pd.read_csv("../data/DF_contact400_energy_2019.f_corr.csv",index_col=0) # Quitar modelos por homologia deltraining set #df_final_onlyHM = df_final.loc[df_final.index.str.startswith("HM")] #df_final= df_final.loc[~df_final.index.str.startswith("HM")] index_ddg8 = (df_final['ddG_exp']==8) df_final = df_final.loc[-index_ddg8] #testiar eliminando estructuras con ddg menor o igual a -4 kcal/mol , outliers index_ddg_4 = (df_final['ddG_exp'] <= -4) df_final = df_final.loc[-index_ddg_4] pdb_names = df_final.index features_names = df_final.drop('ddG_exp',axis=1).columns X = df_final.drop('ddG_exp',axis=1) y = df_final['ddG_exp'] # split for final test X_train, X_test, y_train, y_test = train_test_split(X, y,train_size=0.8,random_state=13) cross_val_score? # Load a regression dataset selector = VarianceThreshold() scaler = MinMaxScaler() #scaler = StandardScaler() #2) kernel = 0.5 * RBF(length_scale=0.5, length_scale_bounds=(1e-2, 1e3)) + WhiteKernel(noise_level=1, noise_level_bounds=(1e-10, 1e+1)) + ConstantKernel() gr_model = GaussianProcessRegressor(random_state=1313,kernel=kernel,normalize_y=True) #3) Crear pipeline pipeline1 = make_pipeline(scaler,selector,gr_model) cv = RepeatedKFold(n_splits=10,n_repeats=5,random_state=13) # 5) hiperparametros a ajustar r2 = cross_val_score(X=X_train,y=y_train,estimator=pipeline1,n_jobs=-1,cv=cv,verbose=5) print(r2.mean(),r2.std()) r2 # index of best scores rmse_bestCV_test_index = grid1.cv_results_['mean_test_neg_mean_squared_error'].argmax() rmse_bestCV_train_index = grid1.cv_results_['mean_train_neg_mean_squared_error'].argmax() r2_bestCV_test_index = grid1.cv_results_['mean_test_r2'].argmax() r2_bestCV_train_index = grid1.cv_results_['mean_train_r2'].argmax() # scores rmse_bestCV_test_score = grid1.cv_results_['mean_test_neg_mean_squared_error'][rmse_bestCV_test_index] rmse_bestCV_test_std = grid1.cv_results_['std_test_neg_mean_squared_error'][rmse_bestCV_test_index] rmse_bestCV_train_score = grid1.cv_results_['mean_train_neg_mean_squared_error'][rmse_bestCV_train_index] rmse_bestCV_train_std = grid1.cv_results_['std_train_neg_mean_squared_error'][rmse_bestCV_train_index] r2_bestCV_test_score = grid1.cv_results_['mean_test_r2'][r2_bestCV_test_index] r2_bestCV_test_std = grid1.cv_results_['std_test_r2'][r2_bestCV_test_index] r2_bestCV_train_score = grid1.cv_results_['mean_train_r2'][r2_bestCV_train_index] r2_bestCV_train_std = grid1.cv_results_['std_train_r2'][r2_bestCV_train_index] print('CV test RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_test_score),np.sqrt(rmse_bestCV_test_std))) print('CV train RMSE {:f} +/- {:f}'.format(np.sqrt(-rmse_bestCV_train_score),np.sqrt(rmse_bestCV_train_std))) print('CV test r2 {:f} +/- {:f}'.format(r2_bestCV_test_score,r2_bestCV_test_std)) print('CV train r2 {:f} +/- {:f}'.format(r2_bestCV_train_score,r2_bestCV_train_std)) print(grid1.best_params_) y_test_pred = grid1.best_estimator_.predict(X_test) y_train_pred = grid1.best_estimator_.predict(X_train) print("\nRMSE for test dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_test, y_test_pred)), 2))) print("RMSE for train dataset: {}".format(np.round(np.sqrt(mean_squared_error(y_train, y_train_pred)), 2))) print("pearson corr {:f}".format(np.corrcoef(y_test_pred,y_test)[0][1])) print('R2 test',grid1.score(X_test,y_test)) print('R2 train',grid1.score(X_train,y_train)) ```
github_jupyter
# Definition ``` forward_seq = 4 backward_seq = 4 valid_tropical_seq_num =4 predict_seq_num = 4 trainYear = (2000, 2014) testYear = (2015, 2018) """ typhoonYear tid Typhoon ID typhoonRecordNum typhoonName typhoonRecords """ class TyphoonHeader: def __init__(self, typhoonYear, tid): self.typhoonYear = typhoonYear self.tid = tid self.typhoonRecordNum = 0 self.typhoonRecords = [] def printer(self): print("tid: %d, typhoonYear: %d, typhoonYear: %s, typhoonRecordNum: %d" % (self.tid, self.typhoonYear, self.typhoonName, self.typhoonRecordNum)) for typhoonRecord in self.typhoonRecords: typhoonRecord.printer() # ๅฐ้ฃŽ่ฎฐๅฝ•ไฟกๆฏ็ฑป """ typhoonTime Tyhoon Record Time lat long wind totalNum Typhoon Record ID """ class TyphoonRecord: def __init__(self, typhoonTime, lat, long, wind, totalNum): self.typhoonTime = typhoonTime self.lat = lat self.long = long self.wind = wind self.totalNum = totalNum def printer(self): print("totalNum: %d, typhoonTime: %d, lat: %d, long: %d, wind: %d" % (self.totalNum, self.typhoonTime, self.lat, self.long, self.wind)) import math import numpy as np def get_vector_angle(vector1, vector2): a_abs = math.sqrt(vector1[0]*vector1[0] + vector1[1] * vector1[1]) b_abs = math.sqrt(vector2[0]*vector2[0] + vector2[1] * vector2[1]) a_b = vector1[0]*vector2[0] + vector1[1]*vector2[1] cos_angle = a_b/(a_abs*b_abs) if cos_angle > 1: cos_angle = 1 elif cos_angle < -1: cos_angle = -1 angle = np.arccos(cos_angle) * 360 / 2 / np.pi return angle def read_cma_dfs(cma_list): totalNum = 1 typhoonHeaderList = [] for df in cma_list: tid = df.loc[0, 'TID'] typhoonYear = df.loc[0, 'YEAR'] typhoonHeader = TyphoonHeader(typhoonYear, tid, ) for i in range(len(df)): typhoonTime = int( str(df.loc[i, 'YEAR'])+ str(df.loc[i, 'MONTH']).zfill(2)+ str(df.loc[i, 'DAY']).zfill(2)+ str(df.loc[i, 'HOUR']).zfill(2) ) lat = df.loc[i, 'LAT'] * 0.1 long = df.loc[i, 'LONG'] * 0.1 wind = df.loc[i, 'WND'] typhoonRecord = TyphoonRecord(typhoonTime, lat, long, wind, totalNum) totalNum += 1 typhoonHeader.typhoonRecords.append(typhoonRecord) typhoonHeader.typhoonRecordNum = len(typhoonHeader.typhoonRecords) typhoonHeaderList.append(typhoonHeader) return typhoonHeaderList from geopy.distance import great_circle def buildup_feature(typhoonRecordsList, tid, fileXWriter, pred_num): for start in range(forward_seq, len(typhoonRecordsList) - predict_seq_num): strXLine = str(typhoonRecordsList[start].totalNum) + \ ',' + str(tid) + \ ',' + str(typhoonRecordsList[start].typhoonTime) + \ ',' + str(typhoonRecordsList[start + pred_num].lat) + \ ',' + str(typhoonRecordsList[start + pred_num].long) + \ ',' + str(typhoonRecordsList[start].typhoonTime//1000000) + \ ',' + str(typhoonRecordsList[start].lat) + \ ',' + str(typhoonRecordsList[start].long) + \ ',' + str(typhoonRecordsList[start].wind) # ๅ‰24ๅฐๆ—ถ็š„ๆ•ฐๆฎ็บฌๅบฆ strXLine += ',' + str(typhoonRecordsList[start - 1].lat) strXLine += ',' + str(typhoonRecordsList[start - 2].lat) strXLine += ',' + str(typhoonRecordsList[start - 3].lat) strXLine += ',' + str(typhoonRecordsList[start - 4].lat) # ๅ‰24ๅฐๆ—ถ็š„ๆ•ฐๆฎ็บฌๅบฆ strXLine += ',' + str(typhoonRecordsList[start - 1].long) strXLine += ',' + str(typhoonRecordsList[start - 2].long) strXLine += ',' + str(typhoonRecordsList[start - 3].long) strXLine += ',' + str(typhoonRecordsList[start - 4].long) # ๅ‰24ๅฐๆ—ถ็š„ๆ•ฐๆฎ้ฃŽ้€Ÿ strXLine += ',' + str(typhoonRecordsList[start - 1].wind) strXLine += ',' + str(typhoonRecordsList[start - 2].wind) strXLine += ',' + str(typhoonRecordsList[start - 3].wind) strXLine += ',' + str(typhoonRecordsList[start - 4].wind) # ๅขžๅŠ ๆœˆไปฝ strXLine += ',' + str(typhoonRecordsList[start].typhoonTime//10000 % 100) # ้ฃŽ้€Ÿๅทฎ strXLine += ',' + str(typhoonRecordsList[start].wind - typhoonRecordsList[start - 1].wind) strXLine += ',' + str(typhoonRecordsList[start - 1].wind - typhoonRecordsList[start - 2].wind) strXLine += ',' + str(typhoonRecordsList[start - 2].wind - typhoonRecordsList[start - 3].wind) strXLine += ',' + str(typhoonRecordsList[start - 3].wind - typhoonRecordsList[start - 4].wind) # ็บฌๅบฆๅทฎ 0-6, 0-12,0-18,0-24 latdiff = [] latdiff.append((typhoonRecordsList[start].lat - typhoonRecordsList[start - 1].lat)) strXLine += ',' + str(latdiff[-1]) latdiff.append((typhoonRecordsList[start - 1].lat - typhoonRecordsList[start - 2].lat)) strXLine += ',' + str(latdiff[-1]) latdiff.append((typhoonRecordsList[start - 2].lat - typhoonRecordsList[start - 3].lat)) strXLine += ',' + str(latdiff[-1]) latdiff.append((typhoonRecordsList[start - 3].lat - typhoonRecordsList[start - 4].lat)) strXLine += ',' + str(latdiff[-1]) # ็ปๅบฆๅทฎ longdiff = [] longdiff.append((typhoonRecordsList[start].long - typhoonRecordsList[start - 1].long)) strXLine += ',' + str(longdiff[-1]) longdiff.append((typhoonRecordsList[start - 1].long - typhoonRecordsList[start - 2].long)) strXLine += ',' + str(longdiff[-1]) longdiff.append((typhoonRecordsList[start - 2].long - typhoonRecordsList[start - 3].long)) strXLine += ',' + str(longdiff[-1]) longdiff.append((typhoonRecordsList[start - 3].long - typhoonRecordsList[start - 4].long)) strXLine += ',' + str(longdiff[-1]) # ็บฌๅบฆๅทฎ็š„ๅนณๆ–นๅ’Œๅผ€ๆ นๅท sum = 0 for i in range(len(latdiff)): sum += latdiff[i]**2 strXLine += ',' + str(sum) strXLine += ',' + str("{:.4f}".format(math.sqrt(sum))) # ็ปๅบฆๅทฎ็š„ๅนณๆ–นๅ’Œๅผ€ๆ นๅท sum = 0 for i in range(len(latdiff)): sum += longdiff[i] ** 2 strXLine += ',' + str(sum) strXLine += ',' + str("{:.4f}".format(math.sqrt(sum))) # ็‰ฉ็†ๅŠ ้€Ÿๅบฆ strXLine += ',' + str("{:.4f}".format( 2 * great_circle( (typhoonRecordsList[start].lat, typhoonRecordsList[start].long), (typhoonRecordsList[start - 1].lat,typhoonRecordsList[start - 1].long) ).kilometers / (6 ** 2) )) strXLine += ',' + str("{:.4f}".format( 2 * great_circle( (typhoonRecordsList[start - 1].lat,typhoonRecordsList[start - 1].long), (typhoonRecordsList[start - 2].lat,typhoonRecordsList[start - 2].long) ).kilometers / (6 ** 2) )) strXLine += ',' + str("{:.4f}".format( 2 * great_circle( (typhoonRecordsList[start].lat,typhoonRecordsList[start].long), (typhoonRecordsList[start - 2].lat,typhoonRecordsList[start - 2].long) ).kilometers / (12 ** 2) )) strXLine += ',' + str("{:.4f}".format( 2 * great_circle( (typhoonRecordsList[start -2].lat,typhoonRecordsList[start -2].long), (typhoonRecordsList[start - 4].lat,typhoonRecordsList[start - 4].long) ).kilometers / (12 ** 2) )) # ๅฝ“ๅ‰็บฌๅบฆๅผ€ๆ นๅท strXLine += ',' + str("{:.4f}".format(math.sqrt(typhoonRecordsList[start].lat))) # ๅฝ“ๅ‰็ปๅบฆๅผ€ๆ นๅท strXLine += ',' + str("{:.4f}".format(math.sqrt(typhoonRecordsList[start].long))) ######################################################################################################## # ็บฌๅ‘ๅŠ ้€Ÿๅบฆ strXLine += ',' + str( (typhoonRecordsList[start].lat - typhoonRecordsList[start - 1].lat) - (typhoonRecordsList[start - 1].lat - typhoonRecordsList[start - 2].lat) ) strXLine += ',' + str( (typhoonRecordsList[start - 2].lat - typhoonRecordsList[start - 3].lat) - (typhoonRecordsList[start - 3].lat - typhoonRecordsList[start - 4].lat) ) # ็ปๅ‘ๅŠ ้€Ÿๅบฆ strXLine += ',' + str( (typhoonRecordsList[start].long - typhoonRecordsList[start - 1].long) - (typhoonRecordsList[start - 1].long - typhoonRecordsList[start - 2].long) ) strXLine += ',' + str( (typhoonRecordsList[start - 2].long - typhoonRecordsList[start - 3].long) - (typhoonRecordsList[start - 3].long - typhoonRecordsList[start - 4].long) ) # ่ฎก็ฎ—็บฌๅบฆๅคน่ง’ for i in range(1, forward_seq + 1): diff_lat = typhoonRecordsList[start - i + 1].lat - typhoonRecordsList[start - i].lat diff_long = typhoonRecordsList[start - i + 1].long - typhoonRecordsList[start - i].long vector1 = [diff_lat, diff_long] vector2 = [1, 0] if diff_lat < 0 and diff_long < 0: strXLine += ',' + str(90 + get_vector_angle(vector1, vector2)) elif diff_lat > 0 and diff_long < 0: strXLine += ',' + str(270 + get_vector_angle(vector1, vector2)) elif diff_lat == 0 and diff_long == 0: strXLine += ',' + str(0) else: strXLine += ',' + str(get_vector_angle(vector1, vector2)) # ่ฎก็ฎ—็ปๅบฆๅบฆๅคน่ง’ for i in range(1, forward_seq + 1): diff_lat = typhoonRecordsList[start - i + 1].lat - typhoonRecordsList[start - i].lat diff_long = typhoonRecordsList[start - i + 1].long - typhoonRecordsList[start - i].long vector1 = [diff_lat, diff_long] vector2 = [0, 1] if diff_lat > 0 and diff_long < 0: strXLine += ',' + str(90 + get_vector_angle(vector1, vector2)) elif diff_lat > 0 and diff_long > 0: strXLine += ',' + str(270 + get_vector_angle(vector1, vector2)) elif diff_lat == 0 and diff_long == 0: strXLine += ',' + str(0) else: strXLine += ',' + str(get_vector_angle(vector1, vector2)) # ่ฎก็ฎ—็ƒญๅธฆๆฐ”ๆ—‹ไธคไธช่ทฏๅพ„็š„ๅคน่ง’ for i in range(1, forward_seq): diff_lat1 = typhoonRecordsList[start - i + 1].lat - typhoonRecordsList[start - i].lat diff_long1 = typhoonRecordsList[start - i + 1].long - typhoonRecordsList[start - i].long vector1 = [diff_lat1, diff_long1] diff_lat2 = typhoonRecordsList[start - i - 1].lat - typhoonRecordsList[start - i].lat diff_long2 = typhoonRecordsList[start - i - 1].long - typhoonRecordsList[start - i].long vector2 = [diff_lat2, diff_long2] if diff_lat1 == 0 and diff_long1 == 0 or diff_lat2 == 0 and diff_long2 == 0: strXLine += ',' + str(0) else: strXLine += ',' + str(get_vector_angle(vector1, vector2)) fileXWriter.write(strXLine + '\n') ``` # Read CMA ``` import os import pandas as pd path = "./data/CMA" files = os.listdir(path) files.sort() pd_list = [] for file in files: cma_pd = pd.read_csv(path+'//'+file, delim_whitespace=True, names=['TROPICALTIME', 'I', 'LAT', 'LONG', 'PRES', 'WND' , 'OWD', 'NAME', 'RECORDTIME']) pd_list.append(cma_pd) df = pd.concat(pd_list, axis=0) df=df.reset_index(drop=True) df ``` # CMA data ``` df = df.drop(columns=['OWD','RECORDTIME']) df = pd.concat([df, pd.DataFrame(columns=['TID','YEAR','MONTH','DAY','HOUR'])], axis=1) df = df[['TID','YEAR','MONTH','DAY','HOUR','TROPICALTIME', 'I', 'LAT', 'LONG', 'WND', 'PRES', 'NAME']] tid = 0 name = None for i in range(0, len(df)): if df.at[i, 'TROPICALTIME'] == 66666: tid += 1 name = df.loc[i, 'NAME'] else: df.at[i, 'TID'] = tid df.at[i, 'NAME'] = name df.at[i, 'YEAR'] = df.loc[i, 'TROPICALTIME'] // 1000000 df.at[i, 'MONTH'] = df.loc[i, 'TROPICALTIME'] // 10000 % 100 df.at[i, 'DAY'] = df.loc[i, 'TROPICALTIME'] // 100 % 100 df.at[i, 'HOUR'] = df.loc[i, 'TROPICALTIME'] % 100 df = df.drop(df[df['TROPICALTIME']==66666].index, axis=0) df = df.drop(columns=['TROPICALTIME']) df=df.reset_index(drop=True) df df.loc[df['NAME']=='In-fa', 'NAME'] = 'Infa' df[df['NAME']=='Infa'] # ๅขžๅŠ KEYๅˆ— df['KEY'] = None # ๆŒ‰ๅนดไปฝๅปบ็ซ‹่ฎฐๅฝ•ๅญ—ๅ…ธ years = df['YEAR'].unique() years_dict = dict(zip(years , np.ones(years.shape))) # ๅญ˜ๆ”พ่ฎก็ฎ—ๅฅฝ็š„็ป“ๆžœ result_list = [] # ไธๅŒๅฐ้ฃŽ่ฎก็ฎ—ๅฝ“ๅนดๅฐ้ฃŽๅบๅท for tid in df['TID'].unique(): temp_df = df[df['TID']==tid].copy() # ่ทจๅนดๅฐ้ฃŽ็ฎ—ๅ‰ไธ€ๅนด็š„ๅฐ้ฃŽ tid_year = temp_df['YEAR'].unique()[0] cy = int(years_dict[tid_year]) years_dict[tid_year] += 1 temp_df['KEY'] = str(tid_year) + '-' + str(cy).zfill(2) result_list.append(temp_df) df = pd.concat(result_list, axis=0) # ๅˆๅนถๅŽ้‡็ฝฎ็ดขๅผ• df=df.reset_index(drop=True) df ``` # Unique ``` import pandas as pd df = df.drop(df[~df['HOUR'].isin([0,6,12,18])].index, axis=0) df=df.reset_index(drop=True) df df = df.drop_duplicates() df=df.reset_index(drop=True) df df.to_csv('./data/raw.csv', index=False) print('raw.csv ไฟๅญ˜ๆˆๅŠŸ') ``` # Data Preprocessing ``` import pandas as pd # ๆฏไธ€ไธชๅฐ้ฃŽๅˆ’ๅˆ†ไธบไธ€ไธชdataframe df = pd.read_csv('./data/raw.csv') tids = df['TID'].unique() cma_list = [] for tid in tids: temp_df = df[df['TID']==tid] temp_df = temp_df.reset_index(drop=True) cma_list.append(temp_df) len(cma_list) valid_tropical_len = forward_seq + valid_tropical_seq_num + backward_seq temp = [] for df in cma_list: if df.shape[0] >= valid_tropical_len: temp.append(df) cma_list = temp len(cma_list) df = pd.concat(cma_list, axis=0) df=df.reset_index(drop=True) train_range = [ str(x) for x in range(trainYear[0], trainYear[1]+1) ] train_keys = [v for i, v in enumerate(df['KEY'].unique()) if any(s in v for s in train_range)] test_range = [ str(x) for x in range(testYear[0], testYear[1]+1) ] test_keys = [v for i, v in enumerate(df['KEY'].unique()) if any(s in v for s in test_range)] df = df[(df['KEY'].isin(train_keys)) | (df['KEY'].isin(test_keys))] df=df.reset_index(drop=True) tname = pd.read_csv('./data/typhoon_name.csv') dict_name = {} for i in range(len(tname)): dict_name[tname.at[i, 'en'].lower()] = tname.at[i, 'cn'] dict_name['(nameless)']='ๆœชๅ‘ฝๅ' df['CN_NAME'] = None for i in range(len(df)): try: df.at[i, 'CN_NAME'] = dict_name[df.at[i, 'NAME'].lower()] except KeyError: print(df.at[i, 'NAME'].lower()) df.to_csv('./data/pre_processing.csv', index=False) df typhoonHeaderList = read_cma_dfs(cma_list) for i in range(1, predict_seq_num+1): trainXFile = open('./data/CMA_train_'+str(i*6)+'h.csv', 'w') testXFile = open('./data/CMA_test_'+str(i*6)+'h.csv', 'w') for typhoonHeader in typhoonHeaderList: typhoonRecordsList = typhoonHeader.typhoonRecords if typhoonHeader.typhoonYear in range(trainYear[0], trainYear[1]+1): buildup_feature(typhoonRecordsList, typhoonHeader.tid, trainXFile, i) elif typhoonHeader.typhoonYear in range(testYear[0], testYear[1]+1): buildup_feature(typhoonRecordsList, typhoonHeader.tid, testXFile, i) trainXFile.close() testXFile.close() ``` # For Reanalysis data ``` cma_ecwmf_train = open('./data/cma_ecwmf_train.csv', 'w') cma_ecwmf_test = open('./data/cma_ecwmf_test.csv', 'w') for typhoonHeader in typhoonHeaderList: typhoonRecordsList = typhoonHeader.typhoonRecords for start in range(0, len(typhoonRecordsList) - 4): strXLine = str(typhoonRecordsList[start].totalNum) + \ ',' + str(typhoonRecordsList[start].typhoonTime) + \ ',' + str(typhoonRecordsList[start].lat) + \ ',' + str(typhoonRecordsList[start].long) + \ ',' + str(typhoonHeader.tid) if typhoonHeader.typhoonYear in range(trainYear[0], trainYear[1]+1): cma_ecwmf_train.write(strXLine + '\n') elif typhoonHeader.typhoonYear in range(testYear[0], testYear[1]+1): cma_ecwmf_test.write(strXLine + '\n') cma_ecwmf_train.close() cma_ecwmf_test.close() ```
github_jupyter
<img src="http://fsharp.org/img/logo/fsharp512.png" style="align:center" /> # Lightweight Dependent Types for Scientific Computing # Allister Beharry ``` /// Setup MathJax and HTML helpers @"<script src=""https://raw.githubusercontent.com/mathjax/MathJax/master/latest.js?config=TeX-AMS-MML_CHTM""></script>" |> Util.Html |> Display let html x = { Html = x } let h1 text = { Html = "<h1>" + text + "</h1>" } let h2 text = { Html = "<h2>" + text + "</h2>" } let h3 text = { Html = "<h3>" + text + "</h3>" } let ul text = { Html = "<ul><li>" + text + "</li></ul>" } let ul3 text = { Html = "<ul><li><h3>" + text + "</h3></li></ul>" } let img url = { Html = "<img src=\"" + url + "\"" + " style=\"align:center\" />" } let uli text url = { Html = "<ul><li>" + text + "<img src=\"" + url + "\"" + " style=\"align:center\" />" + "</li></ul>" } let uli2 text url = { Html = "<h2><ul><li>" + text + "<img src=\"" + url + "\"" + " style=\"align:center\" />" + "</li></ul></h2>" } let uli3 text url = { Html = "<h3><ul><li>" + text + "<img src=\"" + url + "\"" + " style=\"align:center\" />" + "</li></ul></h3>" } let inline (^+^) (x:HtmlOutput) (y:HtmlOutput) = { Html = x.Html + y.Html } // Use the Sylvester.Tensors package from NuGet #load "Paket.fsx" Paket.Package["Sylvester.Arithmetic"; "Sylvester.Tensors"; "Sylvester.DataFrame"; "FSharp.Interop.Dynamic"] #load "Paket.Generated.Refs.fsx" open System open System.Collections.Generic open System.Linq; open FSharp.Interop.Dynamic open Sylvester.Data open Sylvester.Arithmetic open Sylvester.Arithmetic.N10 open Sylvester.Arithmetic.Collections open Sylvester.Tensors ``` # About me * ### From Trinidad W.I. ``` uli2 "West Indies" "https://upload.wikimedia.org/wikipedia/commons/9/98/Caribbean_general_map.png" uli2 "Indians came to Trinidad in the 19th century as indentured labourers" "https://thepeopleafterslavery.files.wordpress.com/2014/03/indentured-labourers-2.png" uli2 "Today Trinidad is multi-ethnic and multi-cultural" "http://currentriggers.com/wp-content/uploads/2016/11/4-17.jpg" uli2 "Divali and other religious festivals celebrated by all" "https://www.guardian.co.tt/image-3.1974716.c274fa76ed?size=512" uli2 "Cricket!" "https://akm-img-a-in.tosshub.com/indiatoday/images/story/201810/AP18297590913026.jpeg?P8W81HcX8oQiGA9xATv_s0lOWQKR3LH9" ``` # About Sylvester project ## https://github.com/allisterb/Sylvester ## Sylvester * An F# DSL for scientific computing focused on safety, expressiveness, and interoperability * Take the best bits of typed functional programming and apply it to scientific and mathematical computing * Use F# features to create a more advanced type system for scientific computing # Why functional programming for scientific computing? ## Scientific programming today * Dominated by C/C++, Fortran, Java, Matlab, Python, R, Julia, * Older languages are statically typed and procedural * Newer languages are dynamically typed and have object-oriented features * All are imperative languages that depend on mutable state and variables * Newer languages like Python and Julia rely heavily on meta-programming ## F# Language Strengths * Functional first: - Everything is an expression - Functions as first-class citizens - Higher-order functions - Immutable variables - Avoid side-effects - Pattern matching - User-defined operators ## F# Language Strengths * Best of both worlds: - Functional + object-oriented - Immutable + mutable variables - Static + dynamic types using the .NET DLR * Classes, interfaces, inheritance, polymorphism * Type extensibility with object expressions, extension methods * Powerful meta-programming capabilities: type providers, computation expressions * Interoperabilty - Can interoperate with any library or language with C FFI - C++, Python, Java - NumPy, Keras, TensorFlow, Torch ## Example - Exploratory Data Analysis in F# using Sylvester ``` let titanic = new CsvFile("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic.["Pclass"].First().Type <- typeof<int> let dt = Frame(titanic) query { for r in dt do groupBy r?Pclass into g sortBy g.Key select ( let survived = (g.Where(fun p -> p?Survived = "1").Count()) |> float let died = (g.Where(fun p -> p?Survived = "0").Count()) |> float let ctotal = survived + died let psurvived = round(100.0 * survived / ctotal) let pdied = round(100.0 * died / ctotal) (g.Key, pdied, psurvived) )} |> Util.Table ``` ## F# Language Strengths * Built on .NET runtime and SDK * Comprehensive open-source tooling and environments - .NET Core / VS Code / Jupyter,...et.al * Huge open-source community providing libraries, resources, support * Microsoft fully committed to open source .NET and regularly releases libraries like ML.NET # We can use F# features to create more advanced type systems for scientific programming... ``` let v1 = Vec<1000>.Rand //Create a vector of length 1000 let v2 = Vec<500>.Rand //Create a vector of length 500 v1 + v2 //Can we do this? ``` # Lightweight Dependent Types ## Dependent types depend on values * E.g. A vector or array type that depends on its length * More advanced program verification than regular types * More errors can be caught before the program is run ## Example ## Full spectrum dependent types * Types can depend on most *runtime* values * Idris, Agda, ATS, F*.... * Programmers write proof-carrying code ## Full spectrum dependent types are cool... >The Future of Programming is Dependent Types... https://medium.com/background-thread/the-future-of-programming-is-dependent-types-programming-word-of-the-day-fcd5f2634878 >Idris, a language that will change the way you think about programming...https://crufter.com/idris-a-language-that-will-change-the-way-you-think-about-programming ...but * Still a niche area in programming * Languages like Idris and ATS have a relatively small user community * Lack of tooling, libraries, resources, commercial support ## Light-weight or restricted dependent typing * http://okmij.org/ftp/Computation/lightweight-dependent-typing.html * Attempt to bring safety benefits of dependent typing to mainstream languages * Began with Dependent ML - precursor to ATS > Dependent ML (DML) is a conservative extension of the functional programming language ML. The type system of DML enriches that of ML with a restricted form of dependent types. This allows many interesting program properties such as memory safety and termination to be captured in the type system of DML and then be verified at compiler-time. * Values must be statically known before evaluation ## Sylvester implements light-weight dependent typing for arrays, vectors, matrices, tensors... * Type-level arithmetic on natural number dimensions - Addition, subtraction, multiplication, equal to, greater than, et..al * Define function constraints which accept only objects of certain dimensions e.g only 3x3 real matrices * Define function constraints which accept objects with dimensions in a certain range e.g matrix functions that only accept square matrices * Sylvester can express type-level constraints and conditions simply without elaborate logical apparatus ### Type-level programming vs. lightweight dependent typing * Many languages like C++ and D support type-level arithmetic * C++ can use static numeric values as template parameters * Both languages can use static checks and compiler asserts to do type level static checks ### Lightweight dependent types * Types can vary with values and not simply fail statjc checks * Do not rely on compiler asserts * Types are part of the problem domain e.g. arithmetic, linear algebra * Rich set of type operators and constraints and checks e.g arithmetic comparison operators ## (Lightweight) dependently-typed natural number arithmetic ``` // Create typed instance of some natural numbers let a = new N<1000>() let b = new N<900>() a +< b a +> b a +!= b a +== b check((b * a) +== zero) //Causes type error check ((a - b) +> zero) // But this is ok zero - a //This results in another type, not a compiler error ``` ## (Lightweight) dependently-typed vectors and matrices ### Example ## https://github.com/allisterb/Sylvester ## @allisterbeharry
github_jupyter
``` from functions import * import pandas as pd import numpy as np import matplotlib.pyplot as plt %config Completer.use_jedi = False %matplotlib inline font = {'size': 15} #import degli spettri puri pure_material_names,pure_materials=import_pure_spectra('../data/raw/Database Raman/BANK_LIST.dat','../data/raw/Database Raman/') ``` # Exploratory data analysis ## Spettri puri Andiamo prima di tutto a vedere come sono fatti gli spettri dei materiali puri che, come capiamo subito, sono molto meno rumorosi rispetto agli spettri del nostro campione. Di seguito plottiamo come esempio lo **spettro puro dell'Albite**. Notiamo come lo spettro รจ poco rumoroso e non presenti offset significativi inoltre lontano dalle frequenze di assorbimento degli stati rotazionali/vibrazionali delle molecole lo spettro va a zero. ``` raman_plot() plt.plot(pure_materials.Albite_wn,pure_materials.Albite_I) plt.legend(['Albite']); plt.rc('font',**font) ``` Vogliamo ora comparare diversi spettri puri per imparare il piรน possibile l'andamento delle curve Raman. Notiamo che gli spettri raman dei materiali puri non sono normalizzati tra di loro. Dato che l'area sotto lo spettro risulta proporzionale al tempo di esposizione della misura (fonte: pdf di introduzione), questa non รจ una quantitร  a cui siamo interessati, scegliamo di normalizzare in modo che tutti gli spettri abbiamo area unitaria. Il seguente รจ il risultato. ![pure normalized spectrums.](./figures/pure_normalized_specrtums.png) Notiamo che nessuno degli spettri puri presenta un rumore rilevante, assumiamo dunque che questi spettri rappresentino gli spettri Raman corretti per i materiali nella lista. Assumiamo inoltre che i materiali puri dati coprano quelli di cui sono composti i nostri campioni incogniti (anche se questo non fosse vero รจ sufficente che coprano i materiali principali). Osservando il grafico appena plottato deduciamo che: 1. **Per numeri d'onda superiori a 1230 $cm^{-1}$ (linea arancione verticale) tutti gli spettri Raman non presentano picchi rilevanti, l'intensitร  a piccole lunghezze d'onda รจ nulla.** 2. **Gli spettri Raman, relativamente alle altezze dei picchi, non presentano un offset rilevante. Nella coda del grafico tutti gli spettri Raman vanno a zero.** 3. **Le FWHM dei picchi sono, certe volte, importanti: fino a 100 $cm^{-1}$.** 4. **Lo spettro fino a circa 1230 $cm^{-1}$ รจ densamente popolato.** ## Spettri incogniti ### Con cosa stiamo lavorando? Andiamo a vedere come sono gli **spettri sperimentali**, abbiamo visto che gli spettri con rumore di fondo non contengono informazioni ulteriori rispetto a quelli a background rimosso, dunque non li prendiamo in considerazione. Ne plottiamo alcuni (i primi) e poi tutti per capire con cosa stiamo lavorando. ![first spectrums.](./figures/first_spectrums.png) ![all spectrums.](./figures/all_spectrums.png) Da questi grafici prendiamo le seguenti scelte nel trattare i dati. - **Rimozione dell'offset** Come abbiamo visto dagli spettri puri, diversamente dagli spettri incogniti nessuno spettro presentava un offset rilevante. Per eliminare/ridurre questo offset utilizziamo il fatto che l'intensita' di tutti gli spettri puri per wave number > 1230 $cm^{-1}$ va a zero. Imponiamo dunque questo constrain agli spettri incogiti per rimuovere l'offset (calcoliamo l'offset sulla coda e lo sottraiamo a tutto lo spettro). - **Scegliamo di eliminare la parte destra del grafico** Questo perchรจ, come si vede dagli spettri puri, non abbiamo picchi oltre alla frequenza di soglia fissata a $1230 cm^{-1}$. - **Normalizzazione degli spettri del sample** Normalizziamo in fine i dati per poterli confrontare. - **Eliminazione degli spettri "non fisici"** Se questa opzione รจ stata selezionata gli spettri non fisici, selezionati utilizzando un bound sull'intensitร  massima della coda, vengono messi a zero, clusterizzati a parte e non utilizzati nel calcolo delle abbondanze. ## Risultato dell'EDA Importiamo i dati elaborati come spiegato (utilizzando make) e vediamo il risultato. ``` data = pd.read_csv('../repo_raman/data/EDA_processed_data.csv') names=define_names() #definisce il nome degli spettri del campione data.head() raman_plot() plt.rc('font',**font) for temp in names[1:]: plt.plot(data.wn,data[temp]) ``` # Clustering La prcedura qui รจ ben spiegata in modo dettagliato nei notebooks utilizzati per sviluppare il progetto (in './notebooks/CLUSTERING.ipynb'). Per il motivo che le altezze dei picchi, come i materiali, variano in modo continuo, abbiamo scelto di utilizzare l'algoritmo Kmeans. In questo modo abbiamo cluster utili a identificare materiali abbastanza diversi (la definizione di cluster non รจ univoca quรฌ, dato che le abbondanze variano in modo continuo). Ci concentriamo ora su due aspetti: 1. **Capire se la clusterizzazione correla con la posizione** 2. **Generare dei centroidi dei cluster che permettono di eliminare il rumore sugli spettri, senza alterare troppo i picchi** ## Il risultato del clustering correla con la posizione? Vogliamo ora capire se esiste una correlazione spaziale nella cluserizzazione. Questo corrispondde al chiedersi se punti vicini hanno materiali simili. Per fare ciรฒ sceglaimo di utilizzare un basso numero di cluster (5), in modo di poter avere una corrispondenza visiva su una griglia $11x11$. **Questa scelta equivale a ritenere uguali materiali con abbondanze piuttosto diverse.** Di seguito il risultato del clustering con KMeans (#cluster=5). ![correlation_cluster.](./figures/correlation_clusters.png) ### Definizione di correlazione spaziale Per descrivere in modo quantitativo la correlazione utilizziamo il coeficiente di Moran (vedi definizione alla [pagina Wikipedia](https://en.wikipedia.org/wiki/Moran%27s_I)). La metrica che utilizziamo รจ un *nearest neighbour*. Di seguito degli esempi che spiegano in modo pratico questo indice. ### Esempi **Esempio con una matrice Random 11x11 (P($\in$cluster)=$\frac{1}{2}$)** Un esempio di cluster completamente random, notare come il coeficiente di Morange sia circa 0 (in questo caso -0.036). ![example1.](./figures/example1.png) **Esempio di alta correlazione: metร  reticolo nel cluster(10x5), metร  no (10x5)** Quรฌ un esempio di un cluster evidentemente molto correlato spazialmente, notare come il coeficiente di Morange รจ vicino a 1 (0.90). ![example2.](./figures/example2.png) **Esempio di alta correlazione: caso in cui il cluster รจ piccolo** Notiamo qui infine che il coeficiente di Morange tende a uno anche nel caso di un cluster piccolo e compatto (correlato spazialmente). Vogliamo evidenziare qui che questo coeficiente non dipende dal numero di punti nel cluster rispetto al numero di punti del reticolo. Anche in questo caso il coeficiente di morange รจ tendente a 1 (0.75). ![example3.](./figures/example3.png) ### Coeficiente di Morane per i nostri cluster Andiamo a calcolare i coefficienti di Morange per i nostri cluster. Chiaramente ne dobbiamo calcolare uno per cluster. I coefficienti di Moran sono scritti nelle labels. Negli spettri dati come esempio questi coefficienti sono vicini allo zero, non รจ evidenziata alcuna correlazione particolare. Questo si capisce anche da un impatto visivo con la figura. ![correlation_grid.](./figures/correlation_grid.png) ## Utilizziamo i centroidi per effettuare i FIT ai materiali puri ### Come scegliamo il numero di cluster? Vogliamo utilizzare la clasterizzazione per rimuovere il rumore dagli spettri, mediando sul cluster (utilizzando i centroidi). Per scegliere il numero di cluster andiamo a vedere come varia l'errore della clusterizzazione al variare del numero di cluster(attributo "inertia" della classe KMeans). Come abbiamo visto a lezione ci aspettiamo una zona a decrescenza rapida e una a decrescenza piรน lenta, vogliamo lavorare sul ginocchio di questa curva. Abbiamo posto come stop un bound alla decrescita dell'errore sui cluster (0.001). Di seguito la curva di decrescitร  dell'errore in funzione del numero di cluster, con il punto scelto utilizzando il nostro bound. ![number_cluster.png.](./figures/number_cluster.png) Questo รจ il risultato della clusterizzazione con il numero di cluster mostarto sopra. ![FIT_cluster.](./figures/FIT_cluster.png) Di questo clustering teniamo i centroidi, con i quali fitteremo gli spettri puri (questo ci รจ utile per rimuovere il rumore di fondo). Di seguito importiamo e plottiamo i centroidi generati dalla clusterizzazione automatizzata con make. ``` #import dei pesi dei cluster labels=np.loadtxt("../repo_raman/data/CLUSTERING_labels.txt") # import dei centroidi del data data = pd.read_csv("../repo_raman/data/CLUSTERING_data_centres.csv") data.drop(labels='Unnamed: 0',inplace=True,axis=1) data.head() raman_plot() for temp in np.unique(labels): plt.plot(data.wn,data[str(int(temp))]) ``` # FIT Per trovare i materiali che compongono i cluster scegliamo di **non eseguire un fit su ogni spettro all'interno di un determinato cluster**, ma **procediamo mediando su tutti gli spettri presenti nei singoli cluster e fittiamo sul risultato della media.** Questo ci permette di ridurre sensibilmente il rumore, sebbene modifichi parzialmente i picchi. Per ogni cluster effettuiamo una regressione lineare estrappolando i coefficienti che poi, normalizzati, costituiranno le abbondanze dei cluster. Per calcolare quest'ultime abbiamo chiaramente pesato i cluster in base al numero di spettri che sono costituiti. La regressione รจ del tipo $C = \sum \alpha_{i}P_{i} + c$ dove i $P_{i}$ sono gli spettri puri, $C$ il centroide del cluster. Il risultato dei fit รจ il seguente. ![final_FIT.](./figures/final_FIT.png) ed infine dai coeficineti pesati per il numero di elementi per cluster e normalizzati otteniamo le abbondanze. Le importiamo dall'output dell'FIT automatizzato con make e mostriamo i materiali con un'abbondanza maggiore dell' 5%. **Questo รจ il risultato finale**. ``` abb_table = pd.read_csv("../repo_raman/data/abb_table.csv") abb_table.drop(labels='Unnamed: 0',inplace=True,axis=1) abb_table[abb_table['abbundances']>0.05] ```
github_jupyter
## Data Preparation ``` import pandas as pd movies_data_path = '../dataset/movies.csv' finantial_data_path = '../dataset/finantials.csv' opening_data_path = '../dataset/opening_gross.csv' fin_data = pd.read_csv(finantial_data_path) movie_data = pd.read_csv(movies_data_path) opening_data = pd.read_csv(opening_data_path) numeric_columns_mask = (movie_data.dtypes == float) | (movie_data.dtypes == int) numeric_columns = [column for column in numeric_columns_mask.index if numeric_columns_mask[column]] movie_data = movie_data[numeric_columns+['movie_title']] fin_data = fin_data[['movie_title','production_budget','worldwide_gross']] fin_movie_data = pd.merge(fin_data, movie_data, on= 'movie_title', how='left') full_movie_data = pd.merge( opening_data,fin_movie_data, on = 'movie_title', how='left') full_movie_data[(full_movie_data.worldwide_gross != 0) & (full_movie_data.worldwide_gross.notnull())].shape full_movie_data = full_movie_data.drop(['movie_title','gross'],axis=1) full_movie_data.columns ``` ## Modeling ``` from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.ensemble import GradientBoostingRegressor from sklearn.model_selection import cross_validate import numpy as np X = full_movie_data.drop(['worldwide_gross'], axis = 1) y = full_movie_data['worldwide_gross'] pipeline = Pipeline([ ('imputer', SimpleImputer(missing_values=np.nan, strategy='mean')), ('core_model', GradientBoostingRegressor()) ]) results = cross_validate(pipeline ,X,y,return_train_score=True,cv=10) results train_score = np.mean(results['train_score']) test_score = np.mean(results['test_score']) assert train_score > 0.7 assert test_score > 0.65 print(f'Train Score: {train_score}') print(f'Test Score: {test_score}') ``` ## Hyperparameter tunning ``` from sklearn.model_selection import GridSearchCV param_tunning = {'core_model__n_estimators': range(20,501,20)} estimator = Pipeline([ ('imputer', SimpleImputer(missing_values=np.nan, strategy='mean')), ('core_model', GradientBoostingRegressor()) ]) grid_search= GridSearchCV(estimator, param_grid = param_tunning, scoring='r2', cv=5) X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.35,random_state= 42) grid_search.fit(X_train, y_train) final_result = cross_validate(grid_search.best_estimator_,X_train,y_train,return_train_score=True,cv=7) train_score = np.mean(final_result['train_score']) test_score = np.mean(final_result['test_score']) assert train_score > 0.7 assert test_score > 0.65 print(f'Train Score: {train_score}') print(f'Test Score: {test_score}') grid_search.best_estimator_.get_params() estimator = Pipeline([ ('imputer', SimpleImputer(missing_values=np.nan, strategy='mean')), ('core_model', GradientBoostingRegressor(n_estimators=220, alpha=0.9, ccp_alpha=0.0, criterion='friedman_mse', init=None, learning_rate=0.1, loss='squared_error', max_depth=3, max_features=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_iter_no_change=None, random_state=None, subsample=1.0, tol=0.0001, validation_fraction=0.1, verbose=0, warm_start=False)) ]) estimator.fit(X_train,y_train) estimator.score(X_test, y_test) ``` ## Saving model ``` from joblib import dump dump(estimator, '../model/model.pkl') X_train.columns ```
github_jupyter
# Mask R-CNN - Inspect Leaf Training Data Inspect and visualize data loading and pre-processing code. ``` import os import sys import itertools import math import logging import json import re import random from collections import OrderedDict import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.lines as lines from matplotlib.patches import Polygon # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from mrcnn import visualizeLeaf as visualize from mrcnn.visualize import display_images import mrcnn.model as modellib from mrcnn.model import log from samples.leaf import leaf %matplotlib inline ``` ## Configurations Configurations are defined in leaf.py ``` config = leaf.CustomConfig() LEAF_DIR = os.path.join(ROOT_DIR, "datasets/leaf") ``` ## Dataset ``` # Load dataset # Get the dataset from the releases page # https://github.com/matterport/Mask_RCNN/releases dataset = leaf.CustomDataset() dataset.load_custom(LEAF_DIR, "train") # Must call before using the dataset dataset.prepare() print("Image Count: {}".format(len(dataset.image_ids))) print("Class Count: {}".format(dataset.num_classes)) for i, info in enumerate(dataset.class_info): print("{:3}. {:50}".format(i, info['name'])) ``` ## Display Samples Load and display images and masks. ``` # Load and display random samples image_ids = np.random.choice(dataset.image_ids, 4) for image_id in image_ids: image = dataset.load_image(image_id) mask, class_ids = dataset.load_mask(image_id) visualize.display_top_masks(image, mask, class_ids, dataset.class_names) ``` ## Bounding Boxes Rather than using bounding box coordinates provided by the source datasets, we compute the bounding boxes from masks instead. This allows us to handle bounding boxes consistently regardless of the source dataset, and it also makes it easier to resize, rotate, or crop images because we simply generate the bounding boxes from the updates masks rather than computing bounding box transformation for each type of image transformation. ``` # Load random image and mask. image_id = random.choice(dataset.image_ids) image = dataset.load_image(image_id) mask, class_ids = dataset.load_mask(image_id) # Compute Bounding box bbox = utils.extract_bboxes(mask) # Display image and additional stats print("image_id ", image_id, dataset.image_reference(image_id)) log("image", image) log("mask", mask) log("class_ids", class_ids) log("bbox", bbox) # Display image and instances visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names) ``` ## Resize Images To support multiple images per batch, images are resized to one size (1024x1024). Aspect ratio is preserved, though. If an image is not square, then zero padding is added at the top/bottom or right/left. ``` # Load random image and mask. image_id = np.random.choice(dataset.image_ids, 1)[0] image = dataset.load_image(image_id) mask, class_ids = dataset.load_mask(image_id) original_shape = image.shape # Resize image, window, scale, padding, _ = utils.resize_image( image, min_dim=config.IMAGE_MIN_DIM, max_dim=config.IMAGE_MAX_DIM, mode=config.IMAGE_RESIZE_MODE) mask = utils.resize_mask(mask, scale, padding) # Compute Bounding box bbox = utils.extract_bboxes(mask) # Display image and additional stats print("image_id: ", image_id, dataset.image_reference(image_id)) print("Original shape: ", original_shape) log("image", image) log("mask", mask) log("class_ids", class_ids) log("bbox", bbox) # Display image and instances visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names) ``` ## Mini Masks Instance binary masks can get large when training with high resolution images. For example, if training with 1024x1024 image then the mask of a single instance requires 1MB of memory (Numpy uses bytes for boolean values). If an image has 100 instances then that's 100MB for the masks alone. To improve training speed, we optimize masks by: * We store mask pixels that are inside the object bounding box, rather than a mask of the full image. Most objects are small compared to the image size, so we save space by not storing a lot of zeros around the object. * We resize the mask to a smaller size (e.g. 56x56). For objects that are larger than the selected size we lose a bit of accuracy. But most object annotations are not very accuracy to begin with, so this loss is negligable for most practical purposes. Thie size of the mini_mask can be set in the config class. To visualize the effect of mask resizing, and to verify the code correctness, we visualize some examples. ``` image_id = np.random.choice(dataset.image_ids, 1)[0] image, image_meta, class_ids, bbox, mask = modellib.load_image_gt( dataset, config, image_id, use_mini_mask=False) log("image", image) log("image_meta", image_meta) log("class_ids", class_ids) log("bbox", bbox) log("mask", mask) display_images([image]+[mask[:,:,i] for i in range(min(mask.shape[-1], 7))]) visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names) # Add augmentation and mask resizing. image, image_meta, class_ids, bbox, mask = modellib.load_image_gt( dataset, config, image_id, augment=True, use_mini_mask=True) log("mask", mask) display_images([image]+[mask[:,:,i] for i in range(min(mask.shape[-1], 7))]) mask = utils.expand_mask(bbox, mask, image.shape) visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names) ``` ## Anchors The order of anchors is important. Use the same order in training and prediction phases. And it must match the order of the convolution execution. For an FPN network, the anchors must be ordered in a way that makes it easy to match anchors to the output of the convolution layers that predict anchor scores and shifts. * Sort by pyramid level first. All anchors of the first level, then all of the second and so on. This makes it easier to separate anchors by level. * Within each level, sort anchors by feature map processing sequence. Typically, a convolution layer processes a feature map starting from top-left and moving right row by row. * For each feature map cell, pick any sorting order for the anchors of different ratios. Here we match the order of ratios passed to the function. **Anchor Stride:** In the FPN architecture, feature maps at the first few layers are high resolution. For example, if the input image is 1024x1024 then the feature meap of the first layer is 256x256, which generates about 200K anchors (256*256*3). These anchors are 32x32 pixels and their stride relative to image pixels is 4 pixels, so there is a lot of overlap. We can reduce the load significantly if we generate anchors for every other cell in the feature map. A stride of 2 will cut the number of anchors by 4, for example. In this implementation we use an anchor stride of 2, which is different from the paper. ``` # Generate Anchors backbone_shapes = modellib.compute_backbone_shapes(config, config.IMAGE_SHAPE) anchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES, config.RPN_ANCHOR_RATIOS, backbone_shapes, config.BACKBONE_STRIDES, config.RPN_ANCHOR_STRIDE) # Print summary of anchors num_levels = len(backbone_shapes) anchors_per_cell = len(config.RPN_ANCHOR_RATIOS) print("Count: ", anchors.shape[0]) print("Scales: ", config.RPN_ANCHOR_SCALES) print("ratios: ", config.RPN_ANCHOR_RATIOS) print("Anchors per Cell: ", anchors_per_cell) print("Levels: ", num_levels) anchors_per_level = [] for l in range(num_levels): num_cells = backbone_shapes[l][0] * backbone_shapes[l][1] anchors_per_level.append(anchors_per_cell * num_cells // config.RPN_ANCHOR_STRIDE**2) print("Anchors in Level {}: {}".format(l, anchors_per_level[l])) ``` Visualize anchors of one cell at the center of the feature map of a specific level. ``` ## Visualize anchors of one cell at the center of the feature map of a specific level # Load and draw random image image_id = np.random.choice(dataset.image_ids, 1)[0] image, image_meta, _, _, _ = modellib.load_image_gt(dataset, config, image_id) fig, ax = plt.subplots(1, figsize=(10, 10)) ax.imshow(image) levels = len(backbone_shapes) for level in range(levels): colors = visualize.random_colors(levels) # Compute the index of the anchors at the center of the image level_start = sum(anchors_per_level[:level]) # sum of anchors of previous levels level_anchors = anchors[level_start:level_start+anchors_per_level[level]] print("Level {}. Anchors: {:6} Feature map Shape: {}".format(level, level_anchors.shape[0], backbone_shapes[level])) center_cell = backbone_shapes[level] // 2 center_cell_index = (center_cell[0] * backbone_shapes[level][1] + center_cell[1]) level_center = center_cell_index * anchors_per_cell center_anchor = anchors_per_cell * ( (center_cell[0] * backbone_shapes[level][1] / config.RPN_ANCHOR_STRIDE**2) \ + center_cell[1] / config.RPN_ANCHOR_STRIDE) level_center = int(center_anchor) # Draw anchors. Brightness show the order in the array, dark to bright. for i, rect in enumerate(level_anchors[level_center:level_center+anchors_per_cell]): y1, x1, y2, x2 = rect p = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=2, facecolor='none', edgecolor=(i+1)*np.array(colors[level]) / anchors_per_cell) ax.add_patch(p) ``` ## Data Generator ``` # Create data generator random_rois = 2000 g = modellib.data_generator( dataset, config, shuffle=True, random_rois=random_rois, batch_size=4, detection_targets=True) # Uncomment to run the generator through a lot of images # to catch rare errors # for i in range(1000): # print(i) # _, _ = next(g) # Get Next Image if random_rois: [normalized_images, image_meta, rpn_match, rpn_bbox, gt_class_ids, gt_boxes, gt_masks, rpn_rois, rois], \ [mrcnn_class_ids, mrcnn_bbox, mrcnn_mask] = next(g) log("rois", rois) log("mrcnn_class_ids", mrcnn_class_ids) log("mrcnn_bbox", mrcnn_bbox) log("mrcnn_mask", mrcnn_mask) else: [normalized_images, image_meta, rpn_match, rpn_bbox, gt_boxes, gt_masks], _ = next(g) log("gt_class_ids", gt_class_ids) log("gt_boxes", gt_boxes) log("gt_masks", gt_masks) log("rpn_match", rpn_match, ) log("rpn_bbox", rpn_bbox) image_id = modellib.parse_image_meta(image_meta)["image_id"][0] print("image_id: ", image_id, dataset.image_reference(image_id)) # Remove the last dim in mrcnn_class_ids. It's only added # to satisfy Keras restriction on target shape. mrcnn_class_ids = mrcnn_class_ids[:,:,0] b = 0 # Restore original image (reverse normalization) sample_image = modellib.unmold_image(normalized_images[b], config) # Compute anchor shifts. indices = np.where(rpn_match[b] == 1)[0] refined_anchors = utils.apply_box_deltas(anchors[indices], rpn_bbox[b, :len(indices)] * config.RPN_BBOX_STD_DEV) log("anchors", anchors) log("refined_anchors", refined_anchors) # Get list of positive anchors positive_anchor_ids = np.where(rpn_match[b] == 1)[0] print("Positive anchors: {}".format(len(positive_anchor_ids))) negative_anchor_ids = np.where(rpn_match[b] == -1)[0] print("Negative anchors: {}".format(len(negative_anchor_ids))) neutral_anchor_ids = np.where(rpn_match[b] == 0)[0] print("Neutral anchors: {}".format(len(neutral_anchor_ids))) # ROI breakdown by class for c, n in zip(dataset.class_names, np.bincount(mrcnn_class_ids[b].flatten())): if n: print("{:23}: {}".format(c[:20], n)) # Show positive anchors fig, ax = plt.subplots(1, figsize=(16, 16)) visualize.draw_boxes(sample_image, boxes=anchors[positive_anchor_ids], refined_boxes=refined_anchors, ax=ax) # Show negative anchors visualize.draw_boxes(sample_image, boxes=anchors[negative_anchor_ids]) # Show neutral anchors. They don't contribute to training. visualize.draw_boxes(sample_image, boxes=anchors[np.random.choice(neutral_anchor_ids, 100)]) ``` ## ROIs ``` if random_rois: # Class aware bboxes bbox_specific = mrcnn_bbox[b, np.arange(mrcnn_bbox.shape[1]), mrcnn_class_ids[b], :] # Refined ROIs refined_rois = utils.apply_box_deltas(rois[b].astype(np.float32), bbox_specific[:,:4] * config.BBOX_STD_DEV) # Class aware masks mask_specific = mrcnn_mask[b, np.arange(mrcnn_mask.shape[1]), :, :, mrcnn_class_ids[b]] visualize.draw_rois(sample_image, rois[b], refined_rois, mask_specific, mrcnn_class_ids[b], dataset.class_names) # Any repeated ROIs? rows = np.ascontiguousarray(rois[b]).view(np.dtype((np.void, rois.dtype.itemsize * rois.shape[-1]))) _, idx = np.unique(rows, return_index=True) print("Unique ROIs: {} out of {}".format(len(idx), rois.shape[1])) if random_rois: # Dispalay ROIs and corresponding masks and bounding boxes ids = random.sample(range(rois.shape[1]), 8) images = [] titles = [] for i in ids: image = visualize.draw_box(sample_image.copy(), rois[b,i,:4].astype(np.int32), [255, 0, 0]) image = visualize.draw_box(image, refined_rois[i].astype(np.int64), [0, 255, 0]) images.append(image) titles.append("ROI {}".format(i)) images.append(mask_specific[i] * 255) titles.append(dataset.class_names[mrcnn_class_ids[b,i]][:20]) display_images(images, titles, cols=4, cmap="Blues", interpolation="none") # Check ratio of positive ROIs in a set of images. if random_rois: limit = 10 temp_g = modellib.data_generator( dataset, config, shuffle=True, random_rois=10000, batch_size=1, detection_targets=True) total = 0 for i in range(limit): _, [ids, _, _] = next(temp_g) positive_rois = np.sum(ids[0] > 0) total += positive_rois print("{:5} {:5.2f}".format(positive_rois, positive_rois/ids.shape[1])) print("Average percent: {:.2f}".format(total/(limit*ids.shape[1]))) ```
github_jupyter
# INFO My solution for the recomendation problem using kNN (task 1 from [moodle](https://moodle.mimuw.edu.pl/pluginfile.php/134822/course/section/17036/kNN%20and%20Decision%20Tree.pdf?time=1615386150480)) # **SOLUTION** # DATA Let's start with uploading our dataset - file `u.data` ``` from google.colab import files from io import StringIO import pandas as pd uploaded_files = files.upload() movie_rates_file_name = next(iter(uploaded_files)) movie_rates_data = uploaded_files[movie_rates_file_name] print('\nFile {name} uploaded ({length} bytes)! Extracting required data...\n'.format( name=movie_rates_file_name, length=len(movie_rates_data))) movie_rates_data_string = StringIO(movie_rates_data.decode('utf-8')) movie_rates = pd.read_csv(movie_rates_data_string, sep="\t", header=None, usecols=[0,1, 2], names=['user_id', 'movie_id', 'rating']) print("Extracted {number_of_lines} lines!".format( number_of_lines=len(movie_rates))) print("First 10 lines of the file:", movie_rates[:10]) ``` Let's find `N` (number of users) and `M` (number of movies) ``` N = len(movie_rates.apply(lambda element: element[0], axis=1).unique()) M = len(movie_rates.apply(lambda element: element[1], axis=1).unique()) print("N (number of users): {number_of_users},\nM (number of movies): {number_of_movies}".format( number_of_users=N, number_of_movies=M)) ``` **It's time for data splitting!** Training / testing sets size ratio is 80/20 (can be set below) ``` training_to_testing_ratio = 0.8 ``` Firstly, let's get shuffled training set: ``` training_movie_rates = movie_rates.sample(frac=training_to_testing_ratio, random_state=1237) ``` And now, extract testing set and shuffle it as well: ``` testing_movie_rates = movie_rates.drop(training_movie_rates.index).sample(frac=1.0) ``` Some info and examples: ``` print("Splited into sets of sizes - training: {trainig_length}, testing: {testing_length}\n".format( trainig_length=len(training_movie_rates), testing_length=len(testing_movie_rates))) print("First 10 rows of the training set:\n", training_movie_rates[:10]) print() print("First 10 rows of the testing set:\n", testing_movie_rates[:10]) ``` # KNN model Firstly, we have to feed up our knn model. We do it by forming a N x M matrix `given_ratings_matrix` (N - number of users, M - number of movies), where `given_ratings_matrix[i][j]` equals `i`-th user's rating for `j`-th movie. ``` def insert_rating_into_given_ratings_matrix(movie_rates_element): user_id = movie_rates_element[1] movie_id = movie_rates_element[2] rating = movie_rates_element[3] given_ratings_matrix[user_id][movie_id] = rating import numpy as np given_ratings_matrix = np.zeros((N+1, M+1), dtype=np.float) [insert_rating_into_given_ratings_matrix(element) for element in training_movie_rates.itertuples()] print("`given_ratings_matrix` updated! (check by running test #1 from the `UNIT TESTS` section)") ``` **Finally, it's time for the KNN algorithm!** This function calculates distance (skipping first array value) from user's ratings row to another user ratings row, and insert it at index 0 of another user rating row (since movies are indexed from 1, index 0 is "empty" and we can use it to store the distance) ``` from scipy import spatial def calculate_distance_from_user_and_insert_to_row(user_ratings, ratings): cosine_distance = spatial.distance.cosine(user_ratings[1:], ratings[1:]) np.put(ratings, 0, cosine_distance) return ratings ``` Now, since distances between users do *not* depend on `k` we can prepare dictionary with sorted neighbors for every user. ``` def get_sorted_neighbors_for_user(ratings_matrix, user_id): print("Sorting neighbors for user: {user_id}".format( user_id=user_id)) user_ratings = ratings_matrix[user_id] other_users_ratings_matrix = np.delete(ratings_matrix, (0, user_id), axis=0) other_users_ratings_matrix_with_distance = np.apply_along_axis( lambda row: calculate_distance_from_user_and_insert_to_row(user_ratings, row), 1, other_users_ratings_matrix) sorted_by_distance_other_users_ratings_matrix = \ other_users_ratings_matrix_with_distance[other_users_ratings_matrix_with_distance[:, 0].argsort()] return sorted_by_distance_other_users_ratings_matrix def create_neighbors_dict(ratings_matrix): neighbors_dict = {} for user_id in range(1, len(ratings_matrix)): neighbors_dict[user_id] = get_sorted_neighbors_for_user(ratings_matrix, user_id) return neighbors_dict ``` And now use it to create dictionary for our input. ``` given_ratings_dict = create_neighbors_dict(given_ratings_matrix) ``` This is "main" algorithm function, it takes neighbors dictionary (created with function above), `k` and actual user id, returns list with k nearest neighbors ratings sorted by distance from actual user ``` def get_k_nearest_neighbors_for_user(neighbors_dict, k, user_id): sorted_by_distance_other_users_ratings_matrix = neighbors_dict[user_id] k_nearest_ratings_matrix = sorted_by_distance_other_users_ratings_matrix[:k, :] return k_nearest_ratings_matrix ``` Function gets neighbors dictionary, k, actual user and movie id and predict this user rating for this movie. If there is not enough data (no ratings for this movie from neighbors) returns `None` ``` def predict_rating(neighbors_dict, k, user_id, movie_id): print("Predicting movie rating for user: {user_id} and movie: {movie_id} with k: {k}".format( user_id=user_id, movie_id=movie_id, k=k)) neighbors = get_k_nearest_neighbors_for_user(neighbors_dict, k, user_id) movie_ratings = neighbors[:, movie_id] non_zero_movie_ratings = movie_ratings[movie_ratings > 0] if len(non_zero_movie_ratings) == 0: print("Not enough data to predict rating for user: {user_id} of movie: {movie_id}. Skipping.".format( user_id=user_id, movie_id=movie_id)) return None else: return round(np.average(non_zero_movie_ratings)) ``` # Finding K It's time for function which calculates RMSE for given dictionary, k, and testing set. It goes through testing set, runs `predict_rating` for every entity and count it in final RMSE if answer was a number (skipping `None`) ``` import math def calculate_RMSE_for_k(neighbors_dict, k, testing_set): sum_of_roots = 0 n = 0 print("\n\nCalculating RMSE for k: {k}".format(k=k)) for test_case in testing_set.itertuples(): predicted_rating = predict_rating(neighbors_dict, k, test_case[1], test_case[2]) expected_rating = test_case[3] if predicted_rating is not None: difference = expected_rating - predicted_rating sum_of_roots += difference * difference n += 1 return math.sqrt(sum_of_roots / n) ``` It's time to calculate RMSE for every possible `k` (`1 <= k <= N`) ``` xs = range(1, N) ys = [calculate_RMSE_for_k(given_ratings_dict, x, testing_movie_rates) for x in xs] ``` And let's plote this data: ``` import matplotlib.pyplot as plt plt.plot(xs, ys) plt.xlabel('k') plt.ylabel('rmse') plt.show() ``` And find the optimal `k` (the `k` with the smallest RMSE value) ``` optimal_k = xs[ys.index(min(ys))] print("The optimal k equals: {k} with RMSE: {rmse}".format(k=optimal_k, rmse = min(ys))) ``` # Recommendation We know the optimal k, so now we can use it to recommend movies for users Let's define function which takes neighbors dictionary, k, n and user id and returns list of size n with no rated movies ordered by predicted rating. ``` def recommend_for_user(ratings_matrix, neighbors_dict, k, n, user_id): user_ratings = ratings_matrix[user_id] unrated_movies = np.where(user_ratings == 0)[0][1:] predicted_ratings = [(predict_rating(neighbors_dict, k, user_id, movie_id), movie_id) for movie_id in unrated_movies] valid_predicted_ratings = np.array([rating for rating in predicted_ratings if rating[0] is not None]) sorted_predicted_ratings = valid_predicted_ratings[valid_predicted_ratings[:, 0].argsort()[::-1]] sorted_movies = np.array([prediction_with_movie[1] for prediction_with_movie in sorted_predicted_ratings]) return sorted_movies[:n] ``` Let's set our N: ``` recommendation_N = 10 ``` Let's fill rating matrix with all ratings: ``` def insert_rating_into_all_ratings_matrix(movie_rates_element): user_id = movie_rates_element[1] movie_id = movie_rates_element[2] rating = movie_rates_element[3] all_ratings_matrix[user_id][movie_id] = rating all_ratings_matrix = np.zeros((N+1, M+1), dtype=np.float) [insert_rating_into_all_ratings_matrix(element) for element in movie_rates.itertuples()] print(all_ratings_matrix) ``` Now we can recommend movies for all users! ``` recommendations_for_users = [(user_id, recommend_for_user(all_ratings_matrix, given_ratings_dict, optimal_k, recomendation_N, user_id)) for user_id in range(1, N+1)] ``` And create a pretty table: ``` from prettytable import PrettyTable table = PrettyTable() table.field_names = ["user id", "recommendations"] for (movie_id, recommendations) in recommendations_for_users: table.add_row([movie_id, recommendations]) print(table) ``` # **UNIT TESTS** (some sort of TDD) # [test #1] `training_movie_rates` maping to `given_ratings_matrix` test ``` def assert_given_ratings_value(training_rate_element): user_id = training_rate_element[1] movie_id = training_rate_element[2] expected_rating = training_rate_element[3] matrix_value = given_ratings_matrix[user_id][movie_id] assert matrix_value == expected_rating [assert_given_ratings_value(element) for element in training_movie_rates.itertuples()] print("Test #1 passed!") ``` # [test #2] `create_neighbors_dict` method test ``` given_ratings = np.array([[0, 0, 0, 0, 0, 0], [0, 2, 3, 0, 5, 1], [0, 1, 0, 0, 3, 0], [0, 1, 1, 1, 2, 0], [0, 4, 3, 5, 4, 3], [0, 1, 2, 3, 1, 2]], dtype=np.float) expected_order_for_user_1 = np.array([[1, 1, 1, 2, 0], [1, 0, 0, 3, 0], [4, 3, 5, 4, 3], [1, 2, 3, 1, 2]], dtype=np.float) expected_order_for_user_2 = np.array([[2, 3, 0, 5, 1], [1, 1, 1, 2, 0], [4, 3, 5, 4, 3], [1, 2, 3, 1, 2]], dtype=np.float) expected_order_for_user_3 = np.array([[2, 3, 0, 5, 1], [4, 3, 5, 4, 3], [1, 0, 0, 3, 0], [1, 2, 3, 1, 2]], dtype=np.float) expected_order_for_user_4 = np.array([[1, 2, 3, 1, 2], [1, 1, 1, 2, 0], [2, 3, 0, 5, 1], [1, 0, 0, 3, 0]], dtype=np.float) expected_order_for_user_5 = np.array([[4, 3, 5, 4, 3], [1, 1, 1, 2, 0], [2, 3, 0, 5, 1], [1, 0, 0, 3, 0]], dtype=np.float) expected_dict = dict([(1, expected_order_for_user_1), (2, expected_order_for_user_2), (3, expected_order_for_user_3), (4, expected_order_for_user_4), (5, expected_order_for_user_5)]) result = create_neighbors_dict(given_ratings) assert (result[1][:, 1:] == expected_order_for_user_1).all() assert (result[2][:, 1:] == expected_order_for_user_2).all() assert (result[3][:, 1:] == expected_order_for_user_3).all() assert (result[4][:, 1:] == expected_order_for_user_4).all() assert (result[5][:, 1:] == expected_order_for_user_5).all() print("Test #2 passed!") ``` # [test #3] ``` given_dict = expected_dict given_user_id = 3 given_k = 3 expected_result = np.array([[2, 3, 0, 5, 1], [4, 3, 5, 4, 3], [1, 0, 0, 3, 0]], dtype=np.float) result = get_k_nearest_neighbors_for_user(given_dict, given_k, given_user_id) assert (result == expected_result).all() print("Test #3 passed!") ```
github_jupyter
# ํ˜‘์—… ํ•„ํ„ฐ๋ง (Collaborative filtering) ``` # arena_util.py # -*- coding: utf-8 -*- import io import os import json import distutils.dir_util from collections import Counter import numpy as np def write_json(data, fname): def _conv(o): if isinstance(o, np.int64) or isinstance(o, np.int32): return int(o) raise TypeError parent = os.path.dirname(fname) distutils.dir_util.mkpath("../arena_data/" + parent) with io.open("../arena_data/" + fname, "w", encoding="utf8") as f: json_str = json.dumps(data, ensure_ascii=False, default=_conv) f.write(json_str) def load_json(fname): with open(fname, encoding='utf8') as f: json_obj = json.load(f) return json_obj def debug_json(r): print(json.dumps(r, ensure_ascii=False, indent=4)) ``` Custom evaluating (weak) ``` # evaluate.py # -*- coding: utf-8 -*- # import fire import numpy as np # from arena_util import load_json class CustomEvaluator: def _idcg(self, l): return sum((1.0 / np.log(i + 2) for i in range(l))) def __init__(self): self._idcgs = [self._idcg(i) for i in range(101)] def _ndcg(self, gt, rec): dcg = 0.0 for i, r in enumerate(rec): if r in gt: dcg += 1.0 / np.log(i + 2) return dcg / self._idcgs[len(gt)] def _eval(self, gt_fname, rec_fname): gt_playlists = load_json(gt_fname) gt_dict = {g["id"]: g for g in gt_playlists} rec_playlists = load_json(rec_fname) music_ndcg = 0.0 tag_ndcg = 0.0 for rec in rec_playlists: gt = gt_dict[rec["id"]] music_ndcg += self._ndcg(gt["songs"], rec["songs"][:100]) tag_ndcg += self._ndcg(gt["tags"], rec["tags"][:10]) music_ndcg = music_ndcg / len(rec_playlists) tag_ndcg = tag_ndcg / len(rec_playlists) score = music_ndcg * 0.85 + tag_ndcg * 0.15 return music_ndcg, tag_ndcg, score def evaluate(self, gt_fname, rec_fname): try: music_ndcg, tag_ndcg, score = self._eval(gt_fname, rec_fname) print(f"Music nDCG: {music_ndcg:.6}") print(f"Tag nDCG: {tag_ndcg:.6}") print(f"Score: {score:.6}") except Exception as e: print(e) # if __name__ == "__main__": # fire.Fire(ArenaEvaluator) from collections import Counter import numpy as np import pandas as pd import scipy.sparse as spr import pickle path = '/Volumes/Seagate Backup Plus Drive/KIE/dataset/melon/' song_meta = pd.read_json(path + "song_meta.json") train = pd.read_json(path + "train.json") test = pd.read_json(path + "val.json") ``` playlist, song, tag์˜ id(๊ฐ๊ฐ nid, sid, tid)๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜๋Š” ์ด์œ ๋Š”, ์ƒˆ๋กœ ์ƒ์„ฑํ•  id๋ฅผ matrix์˜ row, column index๋กœ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. - plylst_id_nid : playlist id -> nid - plylst_nid_id : playlist nid -> id - song_id_sid : song id -> sid - song_sid_id : song sid -> id - tag_id_tid : tag id -> tid - tag_tid_id : tag tid -> id - song_dict : song id -> count - tag_dict : tag id -> count ``` train['istrain'] = 1 test['istrain'] = 0 n_train = len(train) n_test = len(test) # train + test plylst = pd.concat([train, test], ignore_index=True) # playlist id plylst["nid"] = range(n_train + n_test) # id <-> nid plylst_id_nid = dict(zip(plylst["id"],plylst["nid"])) plylst_nid_id = dict(zip(plylst["nid"],plylst["id"])) plylst.head() plylst_tag = plylst['tags'] tag_counter = Counter([tg for tgs in plylst_tag for tg in tgs]) tag_dict = {x: tag_counter[x] for x in tag_counter} tag_id_tid = dict() tag_tid_id = dict() for i, t in enumerate(tag_dict): tag_id_tid[t] = i tag_tid_id[i] = t n_tags = len(tag_dict) plylst_song = plylst['songs'] song_counter = Counter([sg for sgs in plylst_song for sg in sgs]) song_dict = {x: song_counter[x] for x in song_counter} song_id_sid = dict() song_sid_id = dict() for i, t in enumerate(song_dict): song_id_sid[t] = i song_sid_id[i] = t n_songs = len(song_dict) ``` plylst์˜ songs์™€ tags๋ฅผ ์ƒˆ๋กœ์šด id๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ DataFrame์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค ``` plylst['songs_id'] = plylst['songs'].map(lambda x: [song_id_sid.get(s) for s in x if song_id_sid.get(s) != None]) plylst['tags_id'] = plylst['tags'].map(lambda x: [tag_id_tid.get(t) for t in x if tag_id_tid.get(t) != None]) plylst.head() plylst_use = plylst[['istrain','nid','updt_date','songs_id','tags_id']] plylst_use.loc[:,'num_songs'] = plylst_use['songs_id'].map(len) plylst_use.loc[:,'num_tags'] = plylst_use['tags_id'].map(len) plylst_use = plylst_use.set_index('nid') plylst_use.head() plylst_train = plylst_use.iloc[:n_train,:] plylst_test = plylst_use.iloc[n_train:,:] ``` test set์—์„œ ์ƒ˜ํ”Œ 300๊ฐœ๋งŒ ๋ฝ‘์•„ ํ…Œ์ŠคํŠธํ•ด๋ด…๋‹ˆ๋‹ค. ``` # sample test np.random.seed(33) n_sample = 300 test = plylst_test.iloc[np.random.choice(range(n_test), n_sample, replace=False),:] # real test test = plylst_test print(len(test)) test ``` row๊ฐ€ playlist(nid)์ด๊ณ  column์ด item(sid or tid)์ธ sparse matrix A๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ``` row = np.repeat(range(n_train), plylst_train['num_songs']) col = [song for songs in plylst_train['songs_id'] for song in songs] dat = np.repeat(1, plylst_train['num_songs'].sum()) train_songs_A = spr.csr_matrix((dat, (row, col)), shape=(n_train, n_songs)) row = np.repeat(range(n_train), plylst_train['num_tags']) col = [tag for tags in plylst_train['tags_id'] for tag in tags] dat = np.repeat(1, plylst_train['num_tags'].sum()) train_tags_A = spr.csr_matrix((dat, (row, col)), shape=(n_train, n_tags)) train_songs_A_T = train_songs_A.T.tocsr() train_tags_A_T = train_tags_A.T.tocsr() train_songs_A from tqdm import tqdm import os, sys sys.path.append('..') from arena_util import most_popular from arena_util import remove_seen train = load_json(path + 'train.json') _, song_mp = most_popular(train, "songs", 100) def rec(pids): tt = 1 res = [] for pid in tqdm(pids): p = np.zeros((n_songs,1)) p[test.loc[pid,'songs_id']] = 1 val = train_songs_A.dot(p).reshape(-1) songs_already = test.loc[pid, "songs_id"] tags_already = test.loc[pid, "tags_id"] cand_song = train_songs_A_T.dot(val) cand_song_idx = cand_song.reshape(-1).argsort()[-150:][::-1] cand_song_idx = cand_song_idx[np.isin(cand_song_idx, songs_already) == False][:100] rec_song_idx = [song_sid_id[i] for i in cand_song_idx] rec_song_idx += remove_seen(rec_song_idx + songs_already, song_mp) rec_song_idx = rec_song_idx[:100] cand_tag = train_tags_A_T.dot(val) cand_tag_idx = cand_tag.reshape(-1).argsort()[-15:][::-1] cand_tag_idx = cand_tag_idx[np.isin(cand_tag_idx, tags_already) == False][:10] rec_tag_idx = [tag_tid_id[i] for i in cand_tag_idx] res.append({ "id": plylst_nid_id[pid], "songs": rec_song_idx, "tags": rec_tag_idx }) if tt % 1000 == 0: print(tt) tt += 1 return res answers = rec(test.index) write_json(answers, "results/results.json") tmp = answers for idx, answer in enumerate(tmp): answer = answer['songs'] + song_mp tmp[idx]['songs'] = answer[:100] write_json(answers, "results/results.json") evaluator = CustomEvaluator() evaluator.evaluate("../arena_data/answers/val.json", "../arena_data/results/results.json") a = pd.read_json("../arena_data/results/tmp_results.json") arr = [] for i in range(len(a)): tmp = a.loc[i]['songs'][0] a.loc[i]['songs'] = list(set(tmp)) a['songs'] = a['songs'].apply(lambda x : list(set(x[0]))[:100]) a.to_json("../arena_data/results/results.json", orient='records') print(len(a.loc[0]['songs'])) a ```
github_jupyter
<a href="https://colab.research.google.com/github/davidnoone/PHYS332_FluidExamples/blob/main/08_Convection_FV.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Thermal (Rayleigh-Benard) convection in 2d We wish to consider a problem of thermal convection using the non-divergent euler equations in 2d. We can formulate the problem terms of vorticity, and uses simple numerical methods to do so. For an nearly incompressible invisid fluid that is near hydrostatic (i.e., like water, or air), the governing equations are: $$ \frac{d u}{d t} = -\frac{\partial \Phi}{\partial x} $$ $$ \frac{d v}{d t} = -\frac{\partial \Phi}{\partial y} + b $$ Where the buoyancy, b, is defined $$ b = g \frac{\theta}{\theta_0} $$ Being related to entropy via the potential temperature, $\theta$, b is conserved, but may have an external source (e.g., such as heating) $$ \frac{d b}{d t} = Q $$ With incompressibility, density is assumed constant, and mass continuity is just a statement that the divergence is zero. $$ \frac{\partial u}{dx} + \frac{\partial v}{dy} = 0 $$ This immediately allows us to define a streamfunction as the only quantity needed to describe the velocity field. That is: $$ u = - \frac{\partial \Psi}{\partial y} $$ $$ v = \frac{\partial \Psi}{\partial x} $$ The vorticity is related to the streamfunction as: $$ \zeta = \frac{\partial^2 \psi}{\partial x^2} + \frac{\partial^2 \psi}{\partial y^2} $$ The momentum can be described entirely by predicting the evolution of vorticity. Taking the curl of the u and v equations we find the pressure terms cancell leading to a rearkably elegant prognostic equation for voticity: $$ \frac{d \zeta}{d t} = \frac{\partial}{\partial x}(\frac{d v}{d t}) - \frac{\partial}{\partial y}(\frac{d u}{d t}) $$ We may note that the total derivative can be expanded to find the advective terms for each quantity "A" $$ \frac{d A}{dt} = \frac{\partial A}{\partial t} + u \frac{\partial A}{\partial x} + v \frac{\partial A}{\partial y} $$ Here "y" is considered to be the vertical, such that gravity points downward in the y coordinate. Since the flow is incompressible, the $\rho$ is constant, and this second form becomes particularly convinient for numerical methods. With the non-divergent condition, the advection term can be written in a conservative form: $$ u \frac{\partial A}{\partial x} + v \frac{\partial A}{\partial y} = \frac{\partial (uA)}{\partial x} + \frac{\partial (vA)}{\partial y} $$ The final Eulerian prognostic model is therefore described with two equations that describe conservation with the the addition of buoyancy which can induce rotation: $$ \frac{\partial \zeta}{\partial t} = - \frac{\partial (u \zeta)}{\partial x} - \frac{\partial (v \zeta)}{\partial y} + \frac{\partial b}{\partial x} $$ And $$ \frac{\partial b}{\partial t} = - \frac{\partial (ub)}{\partial x} - \frac{\partial (vb)}{\partial y} + Q $$ ## Solution scheme From the above, it should be clear that the eevolution of this system can be developed as follows: 1. Begining with with the $\zeta^n$ and $b^n$ at some initial time ($\zeta$ could be calculated if u and v are known, of course) 2. Solve the poisson equation to evaluate the streamfunction from the known vorticity. i.e., obtain $\psi^n$ 3. Caluclate the velocities $(u,n)^n$ as the gradients in $\psi^n$ 4. Use the velocities to calculate the advection of $\zeta$ and b. 5. Compute the x-gradient of b to add contributions to the acceleration due to buoyancy. At this stage a (viscous) diffusion term can also be added. (Not shown algebraically) 6. Finally, advance $\zeta$ and b in time: step from time $n$ to $n+1$ This scheme can be repeated until the desired integration in time is complete. # Solution method Finite difference methods can be used to evaluate gradients. The poisson equation is solved using an iterative method that applies the finite difference analog of the Laplacian in 2d. If advection is evaluated using finite difference methods, a substantial amount of diffusion is needed to stabilize the numerical result. This is possible, however, a more accurate scheme can also be used with better results.The stepping in time is done using a 3rd order scheme, rather than a simple single forward step, because it has some nice stability properties. This is accomplished using the weighted result from three applications of a simple forward Euler time step. ``` from matplotlib import rc rc('animation', html='jshtml') import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.animation as animation print("Modules imported.") ``` Some run time initialization ``` # Some constants gravity = 9.81 # acceleration due to gravity theta0 = 300. # reference potential temperature [Kelvin] # dimensions nx = 30 # must be even ny = 30 # even or odd dx = 1.0 # grid spacing [metres] dtime = 0.5 # time step [seconds] nelapse = 50 # number of steps to run #nelapse = 200 # number of steps to run nskip = 5 # steps between plotting output nstep = 0 xmax = nx*dx ymax = ny*dx xmid = np.linspace(0,xmax,nx) ymid = np.linspace(0,ymax,ny) # Boundary conditions: top and bottom streamfunction, and buoyancy flux psi_top = 0.0 psi_bot = 0.0 bpert = 0.001*gravity/theta0 # Random buoyancy perturbation b = g * theta/theta0 bflux = 0*0.010*gravity/theta0 # units "per second" # {TRY THIS} bbubl = 1.000*gravity/theta0 # add a bubble # {TRY THIS} kdiff = 0.*dx*dx/50. # [Optional] diffusivity m2/sec (little bit for stability) # Define the working arrays here to make them global (mostly so we can plot them) vort = np.zeros((ny,nx)) buoy = np.zeros((ny,nx)) + bpert*np.random.randn(ny,nx) psi = np.zeros((ny,nx)) uwnd = np.zeros((ny,nx)) vwnd = np.zeros((ny,nx)) # Initialize a hot bubble def add_bubble(xpos, ypos, width): xx,yy = np.meshgrid(xmid,ymid) dist = np.sqrt((xx-xpos)**2 + (yy-ypos)**2)/width bone = np.exp(-dist**2) # gaussian return bone width = 4.0 bone = add_bubble(xmax/2.,ymax/3,4) buoy = buoy + bone*bbubl print('Initialization complete.') ``` A collection of finite difference opperators needed later on. Use the numpy "roll" function to impliment periodic boundary conditions, but explictly use one-sided derivatives in the "y" direction at boundary edges. ``` # Centered finite difference X derivative (2nd order), with periodic BCs: dF/dx def fd_dfdx(fld,dx): dfdx = 0.5*(np.roll(fld,-1, axis=1) - np.roll(fld,+1, axis=1))/dx return dfdx #Centered finite difference in Z with single sided ends: dF/dy def fd_dfdy(fld,dx): global ny dfdy = np.zeros_like(fld) dfdy[0 ,:] = (fld[1 ,:] - fld[ 0,:])/dx dfdy[1:ny-1,:] = (fld[2:ny-0,:] - fld[0:ny-2,:])/(2*dx) dfdy[ ny-1,:] = (fld[ ny-1,:] - fld[ ny-2,:])/dx return dfdy # Laplacian: del^2(F) def fd_lap(fld,dx): flap = -4*fld + np.roll(fld,-1, axis=1) + np.roll(fld,+1, axis=1) flap[0 ,:] = flap[0 ,:] + (fld[1 ,:] ) flap[1:ny-1,:] = flap[1:ny-1,:] + (fld[2:ny-0,:] + fld[0:ny-2,:]) flap[ ny-1,:] = flap[ ny-1,:] + ( fld[ ny-2,:]) return flap # Curl/vorticity: del x (u,v) [Same as fd_div(v,-u)] def fd_curl(u, v, dx): return fd_dfdx(v,dx) - fd_dfdy(u,dx) # Divergence: del.(u,v) def fd_div(u, v, dx): return fd_dfdx(u,dx) + fd_dfdy(v,dx) # Advection opperator using finite differences [not very accurate] def advect(fld,u,v,dx): return -1.0*(u*fd_dfdx(fld,dx) + v*fd_dfdy(fld,dx)) ``` ## Advection using finite volume methods A finite volume method is used to evaluate the (non-linear) advection. Finite volume methods have some appealing mass conservation properties, and they can be configured to help prevent noisy solutions that come about from low order approximations to the continuous equations. This is especially important for managing non-linear terms. Here we use a second order scheme where the advection tendency is computed as $$ \left( \frac{\partial \zeta}{\partial t}\right)_n = \frac{1}{\Delta x} \left( F_{i+1/2} - F_{i-1/2} \right) $$ The fluxes $F$ are at the interfaces (locations at "half" levles), and which must be estimated by linear reconstruction. The details of the estimation gives rise to a robust and accurate scheme. Note that an estimate of the value at each interface is can be obtained from either side. That is, the left side of the interface at $i-1/2$ can be estimated using values from the left or from the right side. Consider the two options: $$ F_{L,i-1/2} = F_{i-1} + \frac{1}{2}\Delta F_{1-1/2} $$ $$ F_{R,i-1/2} = F_{i} - \frac{1}{2}\Delta F_{1+1/2} $$ The half here emerges from wanting to extrapolate half a grid length, $\Delta x$, to get from the cell center to the cell interfaces. The gradients $\Delta F$ can adjusted to ensure monotonicity (and piece wise linear), which equivieltly ensures that no new oscillations are produced in the solution. The slope is set to be no larger (in magnitude) than estimates of $\Delta F$ from the upstream, downstream and centered pairs of values of $\zeta$ that can from the possible combinations in the range from $i-1$ to $i+1$. (_There are a range of specific limiting functions, the "minmod" method used here is simple to impliment and works well._) Finally, the flux is estimated as the mean of these two estimates. The mean takes a special form involving a correction associate with the maximum possible (wave) speed supported by the equations of motion. This correction term effectivivly stabilizes the solution. $$ F = \frac{1}{2} \left[ (F_L + F_R) + \alpha (\zeta_R - \zeta_L) \right] $$ where $\alpha = max(u_L, u_R)$. More formally, $\alpha$ is the Jacobian of the flux $\partial F/\partial u$. If we were to select $\alpha = 0$, we would identically recover the a centered finite difference method! Using these fluxes for each interface the advection tendency is obtained. ``` # Two-D advection using a 2nd order FV method R = -1 # right L = 1 # left # Piecewise linear reconstruction of interface values, using a minmod slope limiter def reconstruct(f, dx, axis): # Compute limited slope/gradient f_dx = 0.5*( np.roll(f,R,axis=axis) - np.roll(f,L,axis=axis) ) # centered difference f_dx = np.maximum(0., np.minimum(1., ( (f-np.roll(f,L,axis=axis)))/(f_dx + 1.0e-8*(f_dx==0)))) * f_dx f_dx = np.maximum(0., np.minimum(1., (-(f-np.roll(f,R,axis=axis)))/(f_dx + 1.0e-8*(f_dx==0)))) * f_dx # get left and right side estimates of the fluxes f_R = f + 0.5*f_dx f_L = f - 0.5*f_dx f_L = np.roll(f_L,R,axis=axis) return f_L, f_R # Form the fluxes: Lax-Freidrichs type scheme def advect_flux_1d(f, u, dx, axis): u_L, u_R = reconstruct(u, dx, axis) f_L, f_R = reconstruct(f, dx, axis) alpha = np.maximum( np.abs(u_L), np.abs(u_R) ) flx = 0.5*((u_L*f_L + u_R*f_R) - alpha*(f_L - f_R)) return flx # Evaluate advective tendency as divegence of (interface) fluxes def advect_tend(f,u,v,dx): dy = dx flx_x = advect_flux_1d(f, u, dx, 1) flx_y = advect_flux_1d(f, v, dy, 0) fadv = (np.roll(flx_x,L,axis=1) - flx_x)/dx + \ (np.roll(flx_y,L,axis=0) - flx_y)/dy return fadv ``` ## Inverting $\zeta$: a Poisson equation Finding $\psi$ from $\zeta$ requires solution of the poisson equation $$ \nabla^2 \psi = \zeta $$ Accomplishing this is one of the main numerical tasks in this calculation. Solving this equation effectly solves for mass continuity by defining a streamfunction. Using finite differences we have: $$ \frac{ \left( \psi_{i+1,j} - 2\psi_{i,j} + \psi_{i-1,j} \right) }{(\Delta x)^2} + \frac{ \left( \psi_{i,j+1} - 2\psi_{i,j} + \psi_{i,j-1} \right) }{(\Delta y)^2} = \zeta_i $$ Let's assume $\Delta x = \Delta y$, and rearrange to obtain: $$ \psi_{i,j} = \frac{1}{4} \left( \psi_{i-1,j} + \psi_{i+1,j} + \psi_{i,j-1} + \psi_{i,j+1} - \frac{\zeta_{i,j}}{(\Delta x)^2} \right) $$ This result suggest we can compute an updated estimate of $\psi_{i,j}$ knowing the value of $\zeta_{i,j}$, and the values of $\psi$ nearby. Notice the detail that for i and j as odd values, the right hand side has only even values (i+1, i-1, j+1, and j-1). One can imagine the red and black squares on a chess board. Therefore this equation can be solved for the black squares, needing only the red squares, then solved again for the red squares needing only the black squares. Indeed, the approach can be repeated to obtain increasingly better estimates of $\psi$. Ususually numerous iterations are required to obtain the needed accuracy. This approach is called a relaxation method, and described as the Gauss-Seidel method. The method can be accelerated by introducing an "over relaxation" in which we take the view that any updated estimate is still likely to be an underestimate, so multiply the size of the update by some factor. That is, $$ \psi_{i,j}^* = (1-w)\psi_{i,j} + \frac{w}{4} \left( \psi_{i-1,j} + \psi_{i+1,j} + \psi_{i,j-1} + \psi_{i,j+1} - \frac{\zeta_{i,j}}{(\Delta x)^2} \right) $$ Where the * denotes the updated estimate and the parameter w is tuned to accelerate the convergence in the range $1 \le w \lt 2$. The case of $w=1$ has no accelaration and larger numers are faster, but can be unstable for noisy fields. Some care is needed in selecting it. Finally, the convergence is faster if we start with a good guess! One good guess is the value from the previous model timestep. While not implimented here, another good guess is from simple linear extrapolation in time. $$ \psi_{guess}^{n+1} = 2\psi^{n} - \psi^{n-1} $$ ``` # initialize red/black indices (jm, im) = np.meshgrid(np.arange(ny),np.arange(nx)) x = np.zeros((nx,ny),dtype=np.int) x[:,1:-1] = im[:,1:-1]+jm[:,1:-1] ir, jr = np.where((x>0) & (x%2 == 0)) ib, jb = np.where((x>0) & (x%2 == 1)) # set periodic boundary conditions in the "i" direction irp = ir + 1 irp[irp>nx-1] -= nx irm = ir - 1 irm[irm< 0] += nx ibp = ib + 1 ibp[ibp>nx-1] -= nx ibm = ib - 1 ibm[ibm< 0] += nx # Solve possion equation using Red/Black Gauss-Siedel method def psolve(psi_bot,psi_top,psi0,vor,dx): err_max = 1.0e-5 # acceptable fractional error. niter_max = 200 # maximum allowable iterations (usually less) w = 1.5 # Over relaxation parameter (1 to 2) dxsq = dx*dx # Set first guess and boundary conditions psi = psi0 psi[ny-1,:] = psi_top psi[ 0,:] = psi_bot # Iterative solver by relaxation: red then black for niter in range(niter_max): psi_last = psi.copy() psi[jr,ir] = (1-w)*psi[jr,ir] + 0.25*w*(psi[jr,irp] + psi[jr,irm] + psi[jr+1,ir] + psi[jr-1,ir] - vor[jr,ir]*dxsq) psi[jb,ib] = (1-w)*psi[jb,ib] + 0.25*w*(psi[jb,ibp] + psi[jb,ibm] + psi[jb+1,ib] + psi[jb-1,ib] - vor[jb,ib]*dxsq) err = np.sum(np.abs(psi - psi_last))/(np.sum(np.abs(psi)) + 1.0e-18) if err < err_max: break if (niter >= niter_max): print("PSOLVE: Failed to converge (good luck!) err=",err) return psi ``` # Integrating the convection equations The hard part is more or less done. We now just need to set up the main formation of the time derivatives ("tendencies"), following the numbered stratergy given above. Then, finaly, do the time stepping. ``` def tendency(): global vort, buoy, uwnd, vwnd, psi, dx, psi_bot, psi_top global dtime, nstep, nskip psi = psolve(psi_bot,psi_top,psi,vort,dx) uwnd = -fd_dfdy(psi,dx) vwnd = fd_dfdx(psi,dx) ztend = advect_tend(vort,uwnd,vwnd,dx) + kdiff*fd_lap(vort,dx) + fd_dfdx(buoy,dx) btend = advect_tend(buoy,uwnd,vwnd,dx) + kdiff*fd_lap(buoy,dx) # Heating at bottom btend[ 0,:] += bflux # Cooling at top # btend[ny-1,:] -= bflux # Cooling everyhere ("atmosphere") btend[:,:] -= bflux/ny return (ztend, btend) # Use a 3rd order SSP RK scheme to integrate: F(n+1) = F(n) + dt*dF/dt def advance(dtime): global vort, buoy vort0 = vort buoy0 = buoy (ztend, btend) = tendency() vort = vort0 + dtime*ztend buoy = buoy0 + dtime*btend (ztend, btend) = tendency() vort = (vort0 + vort + dtime*ztend)/2.0 buoy = (buoy0 + buoy + dtime*btend)/2.0 (ztend, btend) = tendency() vort = (vort0 + 2.0*(vort + dtime*ztend))/3.0 buoy = (buoy0 + 2.0*(buoy + dtime*btend))/3.0 return #for nstep in range(ntime): # advance(dtime) ``` We will want to visualize the model state, define a function to plot the vorticity, buoyancy, and velocty field. ``` def init_frame(): cf.set_array([]) cl.set_array([]) return cl,cf, def advance_frame(w): global vort, buoy, uwnd, vwnd, psi global dtime, nstep, nskip global cl, cf cno = np.max(np.sqrt(uwnd*uwnd + vwnd*vwnd))*dtime/(1.41*dx) # INTEGRATE THE EQUATIONS IN TIME: update to the next save time for n in range(nskip): nstep = nstep + 1 if (cno > 2): print('CFL instability detected: abort! cno=',cno) advance(dtime) # Do the plot on the predefine plotting axes print('Frame: ',w,' nstep =',nstep, 'CFL=',cno) ax.set(title="Vorticity and streamfunction nstep="+str(nstep).zfill(4)) for c in cf.collections: c.remove() cf = ax.contourf(xx,yy,buoy,cmap=colormap,levels=19) for c in cl.collections: c.remove() cl = ax.contour(xx,yy,psi,colors='black') return cl, cf, ``` To actually run the integration, plot at various the needed time interval. ``` # Create an animation object, with frames created as the model runs xx, yy = np.meshgrid(xmid,ymid) colormap = 'jet' fig = plt.figure(figsize=(6,6)) ax = plt.axes(xlim=(0, xmax), ylim=(0, ymax)) ax.set(xlabel='X position [m]', ylabel='Y position [m]') cf = ax.contourf(xx,yy,buoy,cmap=colormap,levels=19) cl = ax.contour(xx,yy,psi,colors='black') anim = animation.FuncAnimation(fig, advance_frame, init_func=init_frame, frames=nelapse, interval=50,repeat=True) plt.close() print('Finished') # Run the model by instantiating the animation. anim # playground ```
github_jupyter
We have now come across three important structures that Python uses to store and access data: * arrays * data frames * series Here we stop to go back over the differences between these structures, and how to convert between them. ## Data frames We start by loading a data frame from a Comma Separated Value file (CSV file). The data file we will load is a table with average <https://ratemyprofessors.com> scores across all professors teaching a particular academic discipline. See the [array indexing page](../03/array_indexing) for more detail. Each row in this table corresponds to one *discipline*. Each column corresponds to a different *rating*. If you are running on your laptop, you should download the [rate_my_course.csv]({{ site.baseurl }}/data/rate_my_course.csv) file to the same directory as this notebook. ``` # Load the Numpy library, rename to "np" import numpy as np # Load the Pandas data science library, rename to "pd" import pandas as pd # Read the file. courses = pd.read_csv('rate_my_course.csv') # Show the first five rows. courses.head() ``` The `pd.read_csv` function returned this table in a structure called a *data frame*. ``` type(courses) ``` The data frame is a two-dimensional structure. It has rows, and columns. We can see the number of rows and columns with: ``` courses.shape ``` This means there are 75 rows. In this case, each row corresponds to one discpline. There are 6 columns. In this case, each column corresponds to a different student rating. Passing the data frame to the Python `len` function shows us the number of rows: ``` len(courses) ``` ### Indexing into data frames There are two simple ways of indexing into data frames. We index into a data frame to get a subset of of the data. To index into anything, we can give the name of thing - in this case `courses` - followed by an opening square bracket `[`, followed by something to specify which subset of the data we want, followed by a closing square bracket `]`. The two simple ways of indexing into a data frame are: * Indexing with a string to get a column. * Indexing with a Boolean sequence to get a subset of the rows. When we index with a string, the string should be a column name: ``` easiness = courses['Easiness'] ``` The result is a *series*: ``` type(easiness) ``` The Series is a structure that holds the data for a single column. ``` easiness ``` We will come back to the Series soon. Notice that, if your string specifying the column name does not match a column name exactly, you will get a long error. This gives you some practice in reading long error messages - skip to the end first, you will often see the most helpful information there. ``` # The exact column name starts with capital E courses['easiness'] ``` You have just seen indexing into the data frame with a string to get the data for one column. The other simple way of indexing into a data frame is with a Boolean sequence. A Boolean sequence is a sequence of values, all of which are either True or False. Examples of sequences are series and arrays. For example, imagine we only wanted to look at courses with an easiness rating of greater than 3.25. We first make the Boolean sequence, by asking the question `> 3.25` of the values in the "Easiness" column, like this: ``` is_easy = easiness > 3.25 ``` This is a series that has True and False values: ``` type(is_easy) is_easy ``` It has True values where the corresponding row had an "Easiness" score greater than 3.25, and False values where the corresponding row had an "Easiness" score of less than or equal to 3.25. We can index into the data frame with this Boolean series. When we do this, we ask the data frame to give us a new version of itself, that only has the rows where there was a True value in the Boolean series: ``` easy_courses = courses[is_easy] ``` The result is a data frame: ``` type(easy_courses) ``` The data frame contains only the rows where the "Easiness" score is greater than 3.25: ``` easy_courses ``` The way this works can be easier to see when we use a smaller data frame. Here we take the first eight rows from the data frame, by using the `head` method. The `head` method can take an argument, which is the number of rows we want. ``` first_8 = courses.head(8) ``` The result is a new data frame: ``` type(first_8) first_8 ``` We index into the new data frame with a string, to get the "Easiness" column: ``` easiness_first_8 = first_8["Easiness"] easiness_first_8 ``` This Boolean series has True where the "Easiness" score is greater than 3.25, and False otherwise: ``` is_easy_first_8 = easiness_first_8 > 3.25 is_easy_first_8 ``` We index into the `first_8` data frame with this Boolean series, to select the rows where `is_easy_first_8` has True, and throw away the rows where it has False. ``` easy_first_8 = first_8[is_easy_first_8] easy_first_8 ``` Oh dear, Psychology looks pretty easy. ## Series and array The series, as you have seen, is the structure that Pandas uses to store the data from a column: ``` first_8 easiness_first_8 = first_8["Easiness"] easiness_first_8 ``` You can index into a series, but this indexing is powerful and sophisticated, so we will not use that for now. For now, you can convert the series to an array, like this: ``` easi_8 = np.array(easiness_first_8) easi_8 ``` Then you can use the usual [array indexing](../03/array_indexing) to get the values you want: ``` # The first value easi_8[0] # The first five values easi_8[:5] ``` You can think of a data frame as sequence of columns, where each column is series. Here I take two columns from the data frame, as series: ``` disciplines = first_8['Discipline'] disciplines clarity = first_8['Clarity'] clarity ``` I can make a new data frame by inserting these two columns: ``` # A new data frame thinner_courses = pd.DataFrame() thinner_courses['Discipline'] = disciplines thinner_courses['Clarity'] = clarity thinner_courses ```
github_jupyter
``` from os import listdir import numpy as np import pandas as pd import cv2 import random import scipy.ndimage import scipy.misc import pickle ``` # Neural Network Implementation ``` class NN: def __init__(self, n_inputs): self.label_names = ['แƒฃ', 'แƒง', 'แƒ›', 'แƒจ', 'แƒซ', 'แƒฌ', 'แƒก', 'แƒฎ', 'แƒš', 'แƒฉ' , '-'] # learning info self.n_iterations = 100 self.l_rate = 0.001 # layer info self.l_sizes = [n_inputs, 30 , 10] self.n_layer = len(self.l_sizes) # generating biases and weights on every hidden layer self.biases = [np.random.randn(i, 1) for i in self.l_sizes[1:]] self.weights = [np.random.randn(j, i) for i, j in zip(self.l_sizes[:-1], self.l_sizes[1:])] # Activation function def sigmoid(self, s): return 1.0 / (np.exp(-s) + 1.0) # Derivative of activation function def sigmoid_der(self, s): return self.sigmoid(s) * (1.0 - self.sigmoid(s)) # Forward propagation def forward(self, data): data = data.reshape(data.shape[0] , 1) curr = data for i in range(len(self.biases)): bias = self.biases[i] weight = self.weights[i] mult = np.dot(weight , curr) curr = self.sigmoid(mult + bias) return curr # Backward propagation def backward(self, X, y): X = X.reshape(X.shape[0] , 1) biases_err = [np.zeros((i, 1)) for i in self.l_sizes[1:]] weights_err = [np.zeros((j, i)) for i, j in zip(self.l_sizes[:-1], self.l_sizes[1:])] # forward propagation while saving a and z values a = [X] z = [] for i in range(len(self.biases)): bias = self.biases[i] weight = self.weights[i] curr = a[-1] mult = np.dot(weight , curr) z.append(mult + bias) curr = self.sigmoid(mult + bias) a.append(curr) # backpropagation loss = (a[-1] - y) * self.sigmoid_der(z[-1]) weights_err[-1] = np.dot(loss, a[-2].transpose()) biases_err[-1] = loss for i in range(2 , self.n_layer): loss = np.dot(self.weights[-i + 1].transpose(), loss) * self.sigmoid_der(z[-i]) weights_err[-i] = np.dot(loss, a[-i - 1].transpose()) biases_err[-i] = loss #update weights and biases for i in range(len(self.biases)): self.weights[i] -= self.l_rate * weights_err[i] self.biases[i] -= self.l_rate * biases_err[i] def training(self, data): for i in range(self.n_iterations): print("iteration number " + str(i)) print(self.weights) for j in range(len(data)): X = data[j][0] X = X.reshape(X.shape[0],1) y = data[j][1] y = y.reshape(y.shape[0],1) self.backward(X , y) def classify(self , data): ans = self.forward(data)[0] res = [0] * len(ans) ind = -1 for i in range(len(ans)): if ans[i] > 0.5: res[i] = 1 ind = i else: res[i] = 0 if (sum(res) > 1): return '-' return self.label_names[ind] ``` # Data Processing ``` class DataObject: # These are variables to prevent adding the same feature twice accidently. ROTATE = False SCALE = False BLUR = False NOISE = False def __init__(self, image): self.image_arr = image self.flat_arr_len = image.shape[0] * image.shape[1] def get_matrix(self): return self.image_arr def get_array(self, shape=None): shape = (self.flat_arr_len, 1) if shape is None else shape (thresh, im_bw) = cv2.threshold(self.image_arr.astype(np.uint8), 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) return ((im_bw.reshape(shape)).astype(int))/255.0 def set_parent_features(self, parent_obj): self.ROTATE = parent_obj.ROTATE self.SCALE = parent_obj.SCALE self.BLUR = parent_obj.BLUR self.NOISE = parent_obj.NOISE class TrainingDataFrame: data = {} letters = [] DEFAULT_COLOR = 255.0 # If images are white on black, pass false as a first argument, please. def __init__(self, black_on_white=True, max_from_class=625, root_dir="./data/แƒแƒกแƒแƒ”แƒ‘แƒ˜/", height=25, width=25): self.HEIGHT = height self.WIDTH = width self.add_data(root_dir, max_from_class, black_on_white) # Taking parent (children of root_dir) folder names as labels, they should be only 1 letter long. # Data should be in labeled letter folders. # If images are white on black, pass false as a second argument, please. def add_data(self, root_dir, max_from_class, black_on_white=True): for letter in listdir(root_dir): if len(letter) > 1: continue count = 0 for image_name in listdir(root_dir + letter): count += 1 if count > max_from_class: continue img = cv2.imread(root_dir + letter + "/" + image_name, cv2.IMREAD_GRAYSCALE) if img is None: print("wrong image path") else: if not black_on_white: img = 255 - img self.DEFAULT_COLOR = 0.0 resized_img = cv2.resize(img, dsize=(self.WIDTH, self.HEIGHT), interpolation=cv2.INTER_CUBIC) if letter not in self.data: self.data[letter] = [] self.letters.append(letter) self.data[letter].append(DataObject(resized_img)) # Rotate alphas are angles. def add_rotate_f(self, rotate_alphas=(-15, -5, 5, 15)): rotate_alphas = list(set(rotate_alphas)) rotate_alphas = [i for i in rotate_alphas if i % 360 != 0] # removes angles which are useless if len(rotate_alphas) == 0: return for letter in self.letters: appendix = [] for sample in self.data[letter]: if not sample.ROTATE: sample.ROTATE = True for angle in rotate_alphas: new_sample = scipy.ndimage.interpolation.rotate(sample.get_matrix(), angle, mode='constant', cval=self.DEFAULT_COLOR, reshape=False) new_dataobject = DataObject(new_sample) new_dataobject.set_parent_features(sample) # To prevent accidently using same feature twice. appendix.append(new_dataobject) self.data[letter].extend(appendix) # Scale alphas are pixels to add edges (then resize to original size). # Warning: alphas that are bigger than 3 or smaller than -3 . passing them would cause an error. def add_scale_f(self, scale_alphas=(2, 0)): scale_alphas = list(set([int(i) for i in scale_alphas])) if 0 in scale_alphas: scale_alphas.remove(0) if len(scale_alphas) == 0: return for alpha in scale_alphas: assert -4 <= alpha <= 4 if not -4 <= alpha <= 4: print(str(alpha) + " is forbidden, please pass correct scale alphas") return for letter in self.letters: appendix = [] for sample in self.data[letter]: if not sample.SCALE: sample.SCALE = True for pixels in scale_alphas: if pixels > 0: new_sample = np.c_[np.full((self.HEIGHT + 2 * pixels, pixels), self.DEFAULT_COLOR), np.r_[np.full((pixels, self.WIDTH), self.DEFAULT_COLOR), sample.get_matrix(), np.full((pixels, self.WIDTH), self.DEFAULT_COLOR)], np.full((self.HEIGHT + 2 * pixels, pixels), self.DEFAULT_COLOR)] else: pixels *= -1 new_sample = sample.get_matrix()[pixels:-pixels, pixels:-pixels] new_sample = cv2.resize(new_sample, dsize=(self.WIDTH, self.HEIGHT), interpolation=cv2.INTER_CUBIC) new_dataobject = DataObject(new_sample) new_dataobject.set_parent_features(sample) # To prevent accidently using same feature twice. appendix.append(new_dataobject) self.data[letter].extend(appendix) # Sigmas are values for blur coefficient. How much pixels should be interpolated to neighbour pixels. # Please keep values between 0 < sigma < 1. def add_blur_f(self, sigmas=(.3, 0)): sigmas = list(set(sigmas)) sigmas = [i for i in sigmas if 0 < i < 1] # removes values which are forbidden if len(sigmas) == 0: return for letter in self.letters: appendix = [] for sample in self.data[letter]: if not sample.BLUR: sample.BLUR = True for sigma in sigmas: new_sample = scipy.ndimage.gaussian_filter(sample.get_matrix(), sigma=sigma) new_dataobject = DataObject(new_sample) new_dataobject.set_parent_features(sample) # To prevent accidently using same feature twice. appendix.append(new_dataobject) self.data[letter].extend(appendix) # noise is maximum value added or decreased(max.:100), dots are how many dots are changed. def add_noise_f(self, noise=20, dots=10): if dots < 1 or 0 < noise < 100: return for letter in self.letters: appendix = [] for sample in self.data[letter]: if not sample.NOISE: sample.NOISE = True new_sample = np.copy(sample.get_matrix()) for _ in range(dots): x = random.randint(0, self.WIDTH - 1) y = random.randint(0, self.HEIGHT - 1) if new_sample[y][x] > 200: noise *= -1 elif new_sample[y][x] > 50: noise = random.randint(-noise, noise) new_sample[y][x] = new_sample[y][x] + noise new_dataobject = DataObject(new_sample) new_dataobject.set_parent_features(sample) # To prevent accidently using same feature twice. appendix.append(new_dataobject) self.data[letter].extend(appendix) def get_random(self, letter): return random.choice(self.data[letter]) def get_letter_list(self, letter): return self.data[letter] def get_letters(self): return self.letters def describe(self): print("data contains " + str(len(self.letters)) + " letters, ") total = 0 for letter in self.letters: amount = len(self.data[letter]) total += amount print(str(amount) + " - " + letter + "'s.") print("\nTOTAL: " + str(total) + " letters.") trainingData = TrainingDataFrame() trainingData.add_rotate_f() trainingData.add_blur_f() trainingData.add_scale_f() trainingData.describe() ``` # Learning Process ``` labels = {'แƒฃ' : np.array([1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0]), 'แƒง' : np.array([0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0]), 'แƒ›' : np.array([0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0]), 'แƒจ' : np.array([0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0]), 'แƒซ' : np.array([0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0]), 'แƒฌ' : np.array([0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0]), 'แƒก' : np.array([0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0]), 'แƒฎ' : np.array([0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0]), 'แƒš' : np.array([0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0]), 'แƒฉ' : np.array([0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1]) } n_inputs = 625 net = NN(625) train = [] for letter in trainingData.get_letters(): for dataObj in trainingData.get_letter_list(letter): numpy_arr = dataObj.get_array() train.append((numpy_arr , labels[letter])) net.training(train) ``` # Save Newtork to File ``` filename = "7_model.sav" with open(filename , 'wb') as file: net_info = { "biases" : net.biases, "weights" : net.weights, } pickle.dump(net_info, file, 2 ) net.weights ```
github_jupyter
``` import pandas as pd ames_housing = pd.read_csv("datasets/house_prices.csv", na_values="?") target_name = "SalePrice" data = ames_housing.drop(columns=target_name) target = ames_housing[target_name] numerical_features = [ "LotFrontage", "LotArea", "MasVnrArea", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "TotalBsmtSF", "1stFlrSF", "2ndFlrSF", "LowQualFinSF", "GrLivArea", "BedroomAbvGr", "KitchenAbvGr", "TotRmsAbvGrd", "Fireplaces", "GarageCars", "GarageArea", "WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "PoolArea", "MiscVal", ] data_numerical = data[numerical_features] from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.pipeline import make_pipeline from sklearn.model_selection import cross_val_score, cross_validate from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler model1 = make_pipeline(StandardScaler(), SimpleImputer(strategy = "mean"), LinearRegression()) model2 = make_pipeline(SimpleImputer(strategy = "mean"), DecisionTreeRegressor()) cv1 = cross_val_score(model1, data_numerical, target, cv = 10, scoring='r2') cv2 = cross_val_score(model2, data_numerical, target, cv = 10, scoring='r2') print("linear : ", cv1.mean(), cv1.std()) print("dec. tree : ", cv2.mean(), cv2.std()) ``` # Solution ``` # Linear Regression from sklearn.model_selection import cross_validate from sklearn.pipeline import make_pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression linear_regression = make_pipeline( StandardScaler(), SimpleImputer(), LinearRegression() ) cv_results_linear_regression = cross_validate( linear_regression, data_numerical, target, cv=10, return_estimator=True, n_jobs=2 ) cv_results_linear_regression["test_score"].mean() from sklearn.tree import DecisionTreeRegressor tree = make_pipeline( SimpleImputer(), DecisionTreeRegressor(random_state=0) ) cv_results_tree = cross_validate( tree, data_numerical, target, cv=10, n_jobs=2 ) cv_results_tree["test_score"].mean() ``` # Moi ``` from sklearn.model_selection import GridSearchCV print(model2.get_params()) param_grid = {"decisiontreeregressor__max_depth" : np.arange(1, 15, 1)} tree_clf = GridSearchCV(model2, param_grid = param_grid, cv = 10) tree_clf.fit(data_numerical, target) print(">> Clรฉs des rรฉsultats : ", tree_clf.cv_results_.keys()) print(">> Profondeur : ", tree_clf.best_params_['decisiontreeregressor__max_depth']) tree_clf.best_params_ ``` # Solution ``` import numpy as np from sklearn.model_selection import GridSearchCV params = {"decisiontreeregressor__max_depth": np.arange(1, 15)} search = GridSearchCV(tree, params, cv=10) cv_results_tree_optimal_depth = cross_validate( search, data_numerical, target, cv=10, return_estimator=True, n_jobs=2, ) cv_results_tree_optimal_depth["test_score"].mean() cv_results_tree_optimal_depth["test_score"] import seaborn as sns sns.set_context("talk") # Meilleurs paramรจtres par folds max_depth = [ estimator.best_params_["decisiontreeregressor__max_depth"] for estimator in cv_results_tree_optimal_depth["estimator"] ] max_depth = pd.Series(max_depth, name="max depth") sns.swarmplot(max_depth) ``` # Moi ``` from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_selector as selector from sklearn.compose import ColumnTransformer numerical_columns_selector = selector(dtype_exclude=object) categorical_columns_selector = selector(dtype_include=object) numerical_columns = numerical_columns_selector(data) categorical_columns = categorical_columns_selector(data) categorical_preprocessor = OneHotEncoder(handle_unknown="ignore") numerical_preprocessor = make_pipeline(StandardScaler(), SimpleImputer(strategy="mean")) preprocessor = ColumnTransformer([ ('one-hot-encoder', categorical_preprocessor, categorical_columns), ('standard-impute', numerical_preprocessor, numerical_columns)]) model = make_pipeline(preprocessor, DecisionTreeRegressor()) test_scores = cross_val_score(model, data, target, cv = 10) print(test_scores.mean()) ``` # Solution Pour les var. catรฉgorielles, utilisation de : ``` SimpleImputer(strategy="constant", fill_value="missing"), OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) ``` Utilisation de `make_column_transformer` ``` from sklearn.compose import make_column_transformer from sklearn.compose import make_column_selector as selector from sklearn.preprocessing import OrdinalEncoder # Utilisation de SimpleImputer et de categorical_processor = make_pipeline( SimpleImputer(strategy="constant", fill_value="missing"), OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) ) numerical_processor = SimpleImputer() preprocessor = make_column_transformer( (categorical_processor, selector(dtype_include=object)), (numerical_processor, selector(dtype_exclude=object)) ) tree = make_pipeline(preprocessor, DecisionTreeRegressor(random_state=0)) cv_results = cross_validate( tree, data, target, cv=10, return_estimator=True, n_jobs=2 ) cv_results["test_score"].mean() ```
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #@title MIT License # # Copyright (c) 2017 Franรงois Chollet # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ``` # Image Classification with Convolutional Neural Networks <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l04c01_image_classification_with_cnns.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l04c01_image_classification_with_cnns.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> In this tutorial, we'll build and train a neural network to classify images of clothing, like sneakers and shirts. It's okay if you don't understand everything. This is a fast-paced overview of a complete TensorFlow program, with explanations along the way. The goal is to get the general sense of a TensorFlow project, not to catch every detail. This guide uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow. ## Install and import dependencies We'll need [TensorFlow Datasets](https://www.tensorflow.org/datasets/), an API that simplifies downloading and accessing datasets, and provides several sample datasets to work with. We're also using a few helper libraries. ``` from __future__ import absolute_import, division, print_function, unicode_literals try: # Use the %tensorflow_version magic if in colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf # Import TensorFlow Datasets import tensorflow_datasets as tfds tfds.disable_progress_bar() # Helper libraries import math import numpy as np import matplotlib.pyplot as plt import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) ``` ## Import the Fashion MNIST dataset This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset, which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 $\times$ 28 pixels), as seen here: <table> <tr><td> <img src="https://tensorflow.org/images/fashion-mnist-sprite.png" alt="Fashion MNIST sprite" width="600"> </td></tr> <tr><td align="center"> <b>Figure 1.</b> <a href="https://github.com/zalandoresearch/fashion-mnist">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp; </td></tr> </table> Fashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) datasetโ€”often used as the "Hello, World" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc) in an identical format to the articles of clothing we'll use here. This guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code. We will use 60,000 images to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow, using the [Datasets](https://www.tensorflow.org/datasets) API: ``` dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True) train_dataset, test_dataset = dataset['train'], dataset['test'] ``` Loading the dataset returns metadata as well as a *training dataset* and *test dataset*. * The model is trained using `train_dataset`. * The model is tested against `test_dataset`. The images are 28 $\times$ 28 arrays, with pixel values in the range `[0, 255]`. The *labels* are an array of integers, in the range `[0, 9]`. These correspond to the *class* of clothing the image represents: <table> <tr> <th>Label</th> <th>Class</th> </tr> <tr> <td>0</td> <td>T-shirt/top</td> </tr> <tr> <td>1</td> <td>Trouser</td> </tr> <tr> <td>2</td> <td>Pullover</td> </tr> <tr> <td>3</td> <td>Dress</td> </tr> <tr> <td>4</td> <td>Coat</td> </tr> <tr> <td>5</td> <td>Sandal</td> </tr> <tr> <td>6</td> <td>Shirt</td> </tr> <tr> <td>7</td> <td>Sneaker</td> </tr> <tr> <td>8</td> <td>Bag</td> </tr> <tr> <td>9</td> <td>Ankle boot</td> </tr> </table> Each image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images: ``` class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] ``` ### Explore the data Let's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, and 10000 images in the test set: ``` num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.splits['test'].num_examples print("Number of training examples: {}".format(num_train_examples)) print("Number of test examples: {}".format(num_test_examples)) ``` ## Preprocess the data The value of each pixel in the image data is an integer in the range `[0,255]`. For the model to work properly, these values need to be normalized to the range `[0,1]`. So here we create a normalization function, and then apply it to each image in the test and train datasets. ``` def normalize(images, labels): images = tf.cast(images, tf.float32) images /= 255 return images, labels # The map function applies the normalize function to each element in the train # and test datasets train_dataset = train_dataset.map(normalize) test_dataset = test_dataset.map(normalize) # The first time you use the dataset, the images will be loaded from disk # Caching will keep them in memory, making training faster train_dataset = train_dataset.cache() test_dataset = test_dataset.cache() ``` ### Explore the processed data Let's plot an image to see what it looks like. ``` # Take a single image, and remove the color dimension by reshaping for image, label in test_dataset.take(1): break image = image.numpy().reshape((28,28)) # Plot the image - voila a piece of fashion clothing plt.figure() plt.imshow(image, cmap=plt.cm.binary) plt.colorbar() plt.grid(False) plt.show() ``` Display the first 25 images from the *training set* and display the class name below each image. Verify that the data is in the correct format and we're ready to build and train the network. ``` plt.figure(figsize=(10,10)) i = 0 for (image, label) in test_dataset.take(25): image = image.numpy().reshape((28,28)) plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(image, cmap=plt.cm.binary) plt.xlabel(class_names[label]) i += 1 plt.show() ``` ## Build the model Building the neural network requires configuring the layers of the model, then compiling the model. ### Setup the layers The basic building block of a neural network is the *layer*. A layer extracts a representation from the data fed into it. Hopefully, a series of connected layers results in a representation that is meaningful for the problem at hand. Much of deep learning consists of chaining together simple layers. Most layers, like `tf.keras.layers.Dense`, have internal parameters which are adjusted ("learned") during training. ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), padding='same', activation=tf.nn.relu, input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10) ]) ``` This network layers are: * **"convolutions"** `tf.keras.layers.Conv2D and MaxPooling2D`โ€” Network start with two pairs of Conv/MaxPool. The first layer is a Conv2D filters (3,3) being applied to the input image, retaining the original image size by using padding, and creating 32 output (convoluted) images (so this layer creates 32 convoluted images of the same size as input). After that, the 32 outputs are reduced in size using a MaxPooling2D (2,2) with a stride of 2. The next Conv2D also has a (3,3) kernel, takes the 32 images as input and creates 64 outputs which are again reduced in size by a MaxPooling2D layer. So far in the course, we have described what a Convolution does, but we haven't yet covered how you chain multiples of these together. We will get back to this in lesson 4 when we use color images. At this point, it's enough if you understand the kind of operation a convolutional filter performs * **output** `tf.keras.layers.Dense` โ€” A 128-neuron, followed by 10-node *softmax* layer. Each node represents a class of clothing. As in the previous layer, the final layer takes input from the 128 nodes in the layer before it, and outputs a value in the range `[0, 1]`, representing the probability that the image belongs to that class. The sum of all 10 node values is 1. ### Compile the model Before the model is ready for training, it needs a few more settings. These are added during the model's *compile* step: * *Loss function* โ€” An algorithm for measuring how far the model's outputs are from the desired output. The goal of training is this measures loss. * *Optimizer* โ€”An algorithm for adjusting the inner parameters of the model in order to minimize loss. * *Metrics* โ€”Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified. ``` model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) ``` ## Train the model First, we define the iteration behavior for the train dataset: 1. Repeat forever by specifying `dataset.repeat()` (the `epochs` parameter described below limits how long we perform training). 2. The `dataset.shuffle(60000)` randomizes the order so our model cannot learn anything from the order of the examples. 3. And `dataset.batch(32)` tells `model.fit` to use batches of 32 images and labels when updating the model variables. Training is performed by calling the `model.fit` method: 1. Feed the training data to the model using `train_dataset`. 2. The model learns to associate images and labels. 3. The `epochs=5` parameter limits training to 5 full iterations of the training dataset, so a total of 5 * 60000 = 300000 examples. (Don't worry about `steps_per_epoch`, the requirement to have this flag will soon be removed.) ``` BATCH_SIZE = 32 train_dataset = train_dataset.cache().repeat().shuffle(num_train_examples).batch(BATCH_SIZE) test_dataset = test_dataset.cache().batch(BATCH_SIZE) model.fit(train_dataset, epochs=10, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE)) ``` As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.97 (or 97%) on the training data. ## Evaluate accuracy Next, compare how the model performs on the test dataset. Use all examples we have in the test dataset to assess accuracy. ``` test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32)) print('Accuracy on test dataset:', test_accuracy) ``` As it turns out, the accuracy on the test dataset is smaller than the accuracy on the training dataset. This is completely normal, since the model was trained on the `train_dataset`. When the model sees images it has never seen during training, (that is, from the `test_dataset`), we can expect performance to go down. ## Make predictions and explore With the model trained, we can use it to make predictions about some images. ``` for test_images, test_labels in test_dataset.take(1): test_images = test_images.numpy() test_labels = test_labels.numpy() predictions = model.predict(test_images) predictions.shape ``` Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction: ``` predictions[0] ``` A prediction is an array of 10 numbers. These describe the "confidence" of the model that the image corresponds to each of the 10 different articles of clothing. We can see which label has the highest confidence value: ``` np.argmax(predictions[0]) ``` So the model is usually most confident that this image is a Shirt, or `class_names[6]`. Let's check the label: ``` test_labels[0] ``` We can graph this to look at the full set of 10 class predictions ``` def plot_image(i, predictions_array, true_labels, images): predictions_array, true_label, img = predictions_array[i], true_labels[i], images[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img[...,0], cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array[i], true_label[i] plt.grid(False) plt.xticks([]) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') ``` Let's look at the 0th image, predictions, and prediction array. ``` i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) ``` Let's plot several images with their predictions. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percent (out of 100) for the predicted label. Note that it can be wrong even when very confident. ``` # Plot the first X test images, their predicted label, and the true label # Color correct predictions in blue, incorrect predictions in red num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions, test_labels, test_images) plt.subplot(num_rows, 2*num_cols, 2*i+2) plot_value_array(i, predictions, test_labels) ``` Finally, use the trained model to make a prediction about a single image. ``` # Grab an image from the test dataset img = test_images[0] print(img.shape) ``` `tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. So even though we're using a single image, we need to add it to a list: ``` # Add the image to a batch where it's the only member. img = np.array([img]) print(img.shape) ``` Now predict the image: ``` predictions_single = model.predict(img) print(predictions_single) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45) ``` `model.predict` returns a list of lists, one for each image in the batch of data. Grab the predictions for our (only) image in the batch: ``` np.argmax(predictions_single[0]) ``` And, as before, the model predicts a label of 6 (shirt). # Exercises Experiment with different models and see how the accuracy results differ. In particular change the following parameters: * Set training epochs set to 1 * Number of neurons in the Dense layer following the Flatten one. For example, go really low (e.g. 10) in ranges up to 512 and see how accuracy changes * Add additional Dense layers between the Flatten and the final Dense(10), experiment with different units in these layers * Don't normalize the pixel values, and see the effect that has Remember to enable GPU to make everything run faster (Runtime -> Change runtime type -> Hardware accelerator -> GPU). Also, if you run into trouble, simply reset the entire environment and start from the beginning: * Edit -> Clear all outputs * Runtime -> Reset all runtimes
github_jupyter
``` import numpy as np import pandas as pd import os PIC_DIR = '/home/vignesh_pagadala/Desktop/GAN-Project/Main/Image-Pairs/Original/test2/' from tqdm import tqdm from PIL import Image IMAGES_COUNT = 20 ORIG_WIDTH = 1000 ORIG_HEIGHT = 500 diff = (ORIG_HEIGHT - ORIG_WIDTH) // 2 WIDTH = 128 HEIGHT = 128 crop_rect = (0, diff, ORIG_WIDTH, ORIG_HEIGHT - diff) images = [] for pic_file in tqdm(os.listdir(PIC_DIR)[:IMAGES_COUNT]): pic = Image.open(PIC_DIR + pic_file).crop(crop_rect) pic.thumbnail((WIDTH, HEIGHT), Image.ANTIALIAS) images.append(np.uint8(pic)) images = np.array(images) / 255 print(images.shape) from matplotlib import pyplot as plt plt.figure(1, figsize=(10, 10)) for i in range(25): plt.subplot(5, 5, i+1) plt.imshow(images[i]) plt.axis('off') plt.show() from keras import Input from keras.layers import Dense, Reshape, LeakyReLU, Conv2D, Conv2DTranspose, Flatten, Dropout from keras.models import Model from keras.optimizers import RMSprop LATENT_DIM = 32 CHANNELS = 3 def create_generator(): gen_input = Input(shape=(LATENT_DIM, )) x = Dense(128 * 16 * 16)(gen_input) x = LeakyReLU()(x) x = Reshape((16, 16, 128))(x) x = Conv2D(256, 5, padding='same')(x) x = LeakyReLU()(x) x = Conv2DTranspose(256, 4, strides=2, padding='same')(x) x = LeakyReLU()(x) x = Conv2DTranspose(256, 4, strides=2, padding='same')(x) x = LeakyReLU()(x) x = Conv2DTranspose(256, 4, strides=2, padding='same')(x) x = LeakyReLU()(x) x = Conv2D(512, 5, padding='same')(x) x = LeakyReLU()(x) x = Conv2D(512, 5, padding='same')(x) x = LeakyReLU()(x) x = Conv2D(CHANNELS, 7, activation='tanh', padding='same')(x) generator = Model(gen_input, x) return generator def create_discriminator(): disc_input = Input(shape=(HEIGHT, WIDTH, CHANNELS)) x = Conv2D(256, 3)(disc_input) x = LeakyReLU()(x) x = Conv2D(256, 4, strides=2)(x) x = LeakyReLU()(x) x = Conv2D(256, 4, strides=2)(x) x = LeakyReLU()(x) x = Conv2D(256, 4, strides=2)(x) x = LeakyReLU()(x) x = Conv2D(256, 4, strides=2)(x) x = LeakyReLU()(x) x = Flatten()(x) x = Dropout(0.4)(x) x = Dense(1, activation='sigmoid')(x) discriminator = Model(disc_input, x) optimizer = RMSprop( lr=.0001, clipvalue=1.0, decay=1e-8 ) discriminator.compile( optimizer=optimizer, loss='binary_crossentropy' ) return discriminator generator = create_generator() discriminator = create_discriminator() discriminator.trainable = False gan_input = Input(shape=(LATENT_DIM, )) gan_output = discriminator(generator(gan_input)) gan = Model(gan_input, gan_output) optimizer = RMSprop(lr=.0001, clipvalue=1.0, decay=1e-8) gan.compile(optimizer=optimizer, loss='binary_crossentropy') import time #iters = 15000 iters = 20 batch_size = 3 RES_DIR = 'res2' FILE_PATH = '%s/generated_%d.png' if not os.path.isdir(RES_DIR): os.mkdir(RES_DIR) CONTROL_SIZE_SQRT = 6 control_vectors = np.random.normal(size=(CONTROL_SIZE_SQRT**2, LATENT_DIM)) / 2 start = 0 d_losses = [] a_losses = [] images_saved = 0 for step in range(iters): start_time = time.time() latent_vectors = np.random.normal(size=(batch_size, LATENT_DIM)) generated = generator.predict(latent_vectors) real = images[start:start + batch_size] combined_images = np.concatenate([generated, real]) labels = np.concatenate([np.ones((batch_size, 1)), np.zeros((batch_size, 1))]) labels += .05 * np.random.random(labels.shape) d_loss = discriminator.train_on_batch(combined_images, labels) d_losses.append(d_loss) latent_vectors = np.random.normal(size=(batch_size, LATENT_DIM)) misleading_targets = np.zeros((batch_size, 1)) a_loss = gan.train_on_batch(latent_vectors, misleading_targets) a_losses.append(a_loss) start += batch_size if start > images.shape[0] - batch_size: start = 0 if True: #step % 5 == 4: gan.save_weights('/home/vignesh_pagadala/Desktop/gan.h5') print('%d/%d: d_loss: %.4f, a_loss: %.4f. (%.1f sec)' % (step + 1, iters, d_loss, a_loss, time.time() - start_time)) control_image = np.zeros((WIDTH * CONTROL_SIZE_SQRT, HEIGHT * CONTROL_SIZE_SQRT, CHANNELS)) control_generated = generator.predict(control_vectors) for i in range(CONTROL_SIZE_SQRT ** 2): x_off = i % CONTROL_SIZE_SQRT y_off = i // CONTROL_SIZE_SQRT control_image[x_off * WIDTH:(x_off + 1) * WIDTH, y_off * HEIGHT:(y_off + 1) * HEIGHT, :] = control_generated[i, :, :, :] im = Image.fromarray(np.uint8(control_image * 255)) im.save(FILE_PATH % (RES_DIR, images_saved)) images_saved += 1 plt.figure(1, figsize=(12, 8)) plt.subplot(121) plt.plot(d_losses) plt.xlabel('epochs') plt.ylabel('discriminant losses') plt.subplot(122) plt.plot(a_losses) plt.xlabel('epochs') plt.ylabel('adversary losses') plt.show() import imageio import shutil images_to_gif = [] for filename in os.listdir(RES_DIR): images_to_gif.append(imageio.imread(RES_DIR + '/' + filename)) imageio.mimsave('/home/vignesh_pagadala/Desktop/visual.gif', images_to_gif) #shutil.rmtree(RES_DIR) ```
github_jupyter
``` import pandas import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker df_abril = pandas.read_csv("./data/Cluster-Crime-Abril.csv") crime_tipos = df_abril[['NATUREZA DA OCORRรŠNCIA']] crime_tipo_total = crime_tipos.groupby('NATUREZA DA OCORRรŠNCIA').size() crime_tipo_counts = df_abril[['NATUREZA DA OCORRรŠNCIA']].groupby('NATUREZA DA OCORRรŠNCIA').sum() crime_tipo_counts['TOTAL'] = crime_tipo_total all_crime_tipos = crime_tipo_counts.sort_values(by='TOTAL', ascending=False) ``` ### Filtro dos 10 crimes com mais ocorrรชncias em abril ``` all_crime_tipos.head(10) all_crime_tipos_top10 = all_crime_tipos.head(10) all_crime_tipos_top10.plot(kind='barh', figsize=(12,6), color='#3f3fff') plt.title('Top 10 crimes por tipo (Abr 2017)') plt.xlabel('Nรบmero de crimes') plt.ylabel('Crime') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Todas as ocorrรชncias criminais de abril ``` all_crime_tipos group_df_abril = df_abril.groupby('CLUSTER') crimes = group_df_abril['NATUREZA DA OCORRรŠNCIA'].count() crimes.plot(kind='barh', figsize=(10,7), color='#3f3fff') plt.title('Nรบmero de crimes por regiรฃo (Abr 2017)') plt.xlabel('Nรบmero') plt.ylabel('Regiรฃo') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### As 5 regiรตes com mais ocorrรชncias ``` regioes = df_abril.groupby('CLUSTER').count() grupo_de_regioes = regioes.sort_values('NATUREZA DA OCORRรŠNCIA', ascending=False) grupo_de_regioes['TOTAL'] = grupo_de_regioes.ID top_5_regioes_qtd = grupo_de_regioes.TOTAL.head(6) top_5_regioes_qtd.plot(kind='barh', figsize=(10,4), color='#3f3fff') plt.title('Top 5 regiรตes com mais crimes') plt.xlabel('Nรบmero de crimes') plt.ylabel('Regiรฃo') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Acima podemos ver que a regiรฃo 1 teve o maior nรบmero de ocorrรชncias criminais ### Podemos agora ver quais sรฃo essas ocorrรชncias de forma mais detalhada ``` regiao_1_detalhe = df_abril[df_abril['CLUSTER'] == 1] regiao_1_detalhe ``` ### Uma anรกlise sobre as 5 ocorrรชncias mais comuns ``` crime_types = regiao_1_detalhe[['NATUREZA DA OCORRรŠNCIA']] crime_type_total = crime_types.groupby('NATUREZA DA OCORRรŠNCIA').size() crime_type_counts = regiao_1_detalhe[['NATUREZA DA OCORRรŠNCIA']].groupby('NATUREZA DA OCORRรŠNCIA').sum() crime_type_counts['TOTAL'] = crime_type_total all_crime_types = crime_type_counts.sort_values(by='TOTAL', ascending=False) crimes_top_5 = all_crime_types.head(5) crimes_top_5.plot(kind='barh', figsize=(11,3), color='#3f3fff') plt.title('Top 5 crimes na regiรฃo 1') plt.xlabel('Nรบmero de crimes') plt.ylabel('Crime') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Filtro dos 10 horรกrios com mais ocorrรชncias em abril ``` horas_mes = df_abril.HORA.value_counts() horas_mes_top10 = horas_mes.head(10) horas_mes_top10.plot(kind='barh', figsize=(11,4), color='#3f3fff') plt.title('Crimes por hora (Abr 2017)') plt.xlabel('Nรบmero de ocorrรชncias') plt.ylabel('Hora do dia') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Filtro dos 5 horรกrios com mais ocorrรชncias na regiรฃo 1 (regiรฃo com mais ocorrรชncias em abril) ``` crime_hours = regiao_1_detalhe[['HORA']] crime_hours_total = crime_hours.groupby('HORA').size() crime_hours_counts = regiao_1_detalhe[['HORA']].groupby('HORA').sum() crime_hours_counts['TOTAL'] = crime_hours_total all_hours_types = crime_hours_counts.sort_values(by='TOTAL', ascending=False) all_hours_types.head(5) all_hours_types_top5 = all_hours_types.head(5) all_hours_types_top5.plot(kind='barh', figsize=(11,3), color='#3f3fff') plt.title('Top 5 crimes por hora na regiรฃo 1') plt.xlabel('Nรบmero de ocorrรชncias') plt.ylabel('Hora do dia') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Filtro dos 10 bairros com mais ocorrรชncias em abril ``` crimes_mes = df_abril.BAIRRO.value_counts() crimes_mes_top10 = crimes_mes.head(10) crimes_mes_top10.plot(kind='barh', figsize=(11,4), color='#3f3fff') plt.title('Top 10 Bairros com mais crimes (Abr 2017)') plt.xlabel('Nรบmero de ocorrรชncias') plt.ylabel('Bairro') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### O Bairro com o maior nรบmero de ocorrรชncias em abril foi o Jangurussรบ ### Vamos agora ver de forma mais detalhadas quais foram estes crimes ``` barra_do_ceara = df_abril[df_abril['BAIRRO'] == 'JANGURUSSU'] crime_types = barra_do_ceara[['NATUREZA DA OCORRรŠNCIA']] crime_type_total = crime_types.groupby('NATUREZA DA OCORRรŠNCIA').size() crime_type_counts = barra_do_ceara[['NATUREZA DA OCORRรŠNCIA']].groupby('NATUREZA DA OCORRรŠNCIA').sum() crime_type_counts['TOTAL'] = crime_type_total all_crime_types = crime_type_counts.sort_values(by='TOTAL', ascending=False) all_crime_tipos_5 = all_crime_types.head(5) all_crime_tipos_5.plot(kind='barh', figsize=(15,4), color='#3f3fff') plt.title('Top 5 crimes no Jangurussรบ') plt.xlabel('Nรบmero de Crimes') plt.ylabel('Crime') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Os 5 bairros mais comuns na regiรฃo 1 ``` crime_types_bairro = regiao_1_detalhe[['BAIRRO']] crime_type_total_bairro = crime_types_bairro.groupby('BAIRRO').size() crime_type_counts_bairro = regiao_1_detalhe[['BAIRRO']].groupby('BAIRRO').sum() crime_type_counts_bairro['TOTAL'] = crime_type_total_bairro all_crime_types_bairro = crime_type_counts_bairro.sort_values(by='TOTAL', ascending=False) crimes_top_5_bairro = all_crime_types_bairro.head(5) crimes_top_5_bairro.plot(kind='barh', figsize=(11,3), color='#3f3fff') plt.title('Top 5 bairros na regiรฃo 1') plt.xlabel('Quantidade') plt.ylabel('Bairro') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ``` ### Anรกlise sobre o bairro Barra do Cearรก ``` barra_do_ceara = df_abril[df_abril['BAIRRO'] == 'BARRA DO CEARA'] crime_types = barra_do_ceara[['NATUREZA DA OCORRรŠNCIA']] crime_type_total = crime_types.groupby('NATUREZA DA OCORRรŠNCIA').size() crime_type_counts = barra_do_ceara[['NATUREZA DA OCORRรŠNCIA']].groupby('NATUREZA DA OCORRรŠNCIA').sum() crime_type_counts['TOTAL'] = crime_type_total all_crime_types = crime_type_counts.sort_values(by='TOTAL', ascending=False) all_crime_tipos_5 = all_crime_types.head(5) all_crime_tipos_5.plot(kind='barh', figsize=(15,4), color='#3f3fff') plt.title('Top 5 crimes na Barra do Cearรก') plt.xlabel('Nรบmero de Crimes') plt.ylabel('Crime') plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) plt.show() ```
github_jupyter
### soft hierarchical + convolution for extracting features using word embeddings #### without pretraining #### batch size = 128, learning rate = 0.001, kernel size = 7, num_gpus = 6 ``` import tensorflow as tf tf.logging.set_verbosity(tf.logging.WARN) import pickle import numpy as np import os from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score import os from tensorflow.python.client import device_lib from collections import Counter import time VERY_BIG_NUMBER = 1e30 f = open('../../Glove/word_embedding_glove', 'rb') word_embedding = pickle.load(f) f.close() word_embedding = word_embedding[: len(word_embedding)-1] f = open('../../Glove/vocab_glove', 'rb') vocab = pickle.load(f) f.close() word2id = dict((w, i) for i,w in enumerate(vocab)) id2word = dict((i, w) for i,w in enumerate(vocab)) unknown_token = "UNKNOWN_TOKEN" # Model Description model_name = 'model-aw-lex-hierarchical-3' model_dir = '../output/all-word/' + model_name save_dir = os.path.join(model_dir, "save/") log_dir = os.path.join(model_dir, "log") if not os.path.exists(model_dir): os.mkdir(model_dir) if not os.path.exists(save_dir): os.mkdir(save_dir) if not os.path.exists(log_dir): os.mkdir(log_dir) with open('../../../dataset/train_val_data_fine/hierarchical_all_word_lex','rb') as f: train_data, val_data = pickle.load(f) with open('../../../dataset/test_data_fine/hierarchical_all_word_lex','rb') as f: test_data = pickle.load(f) with open('../../../dataset/train_val_data_fine/mask_mat_lex','rb') as f: mask_mat = pickle.load(f) # Parameters mode = 'train' num_senses = 44 num_pos = 12 num_sense_pos = 4 batch_size = 128 vocab_size = len(vocab) unk_vocab_size = 1 word_emb_size = len(word_embedding[0]) max_sent_size = 200 hidden_size = 256 num_filter = 256 window_size = 5 kernel_size = 7 keep_prob = 0.3 l2_lambda = 0.001 init_lr = 0.001 decay_steps = 500 decay_rate = 0.99 clip_norm = 1 clipping = True crf_lambda = 0.05 moving_avg_deacy = 0.999 num_gpus = 6 width = int(window_size/2) def average_gradients(tower_grads): average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(grads, 0) grad = tf.reduce_mean(grad, axis=0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads # MODEL device_num = 0 tower_grads = [] losses = [] predictions = [] predictions_pos = [] total_trans_params = [] x = tf.placeholder('int32', [num_gpus, batch_size, max_sent_size], name="x") y = tf.placeholder('int32', [num_gpus, batch_size, max_sent_size], name="y") y_sp = tf.placeholder('int32', [num_gpus, batch_size, max_sent_size], name="y_sp") y_pos = tf.placeholder('int32', [num_gpus, batch_size, max_sent_size], name="y_pos") x_mask = tf.placeholder('bool', [num_gpus, batch_size, max_sent_size], name='x_mask') sense_mask = tf.placeholder('bool', [num_gpus, batch_size, max_sent_size], name='sense_mask') is_train = tf.placeholder('bool', [], name='is_train') word_emb_mat = tf.placeholder('float', [None, word_emb_size], name='emb_mat') input_keep_prob = tf.cond(is_train,lambda:keep_prob, lambda:tf.constant(1.0)) pretrain = tf.placeholder('bool', [], name="pretrain") mask_matrix = tf.tile(tf.expand_dims(tf.constant(value=mask_mat, shape=list(np.array(mask_mat).shape), dtype='float32'), 0), [batch_size, 1, 1]) global_step = tf.Variable(0, trainable=False, name="global_step") learning_rate = tf.train.exponential_decay(init_lr, global_step, decay_steps, decay_rate, staircase=True) summaries = [] def local_attention(input_x, input_mask, W_att): flat_x = tf.reshape(input_x, [-1, tf.shape(input_x)[2]]) h_tanh = tf.tanh(flat_x) u_flat = tf.matmul(h_tanh, W_att) u = tf.reshape(u_flat, [batch_size, -1]) + input_mask a = tf.expand_dims(tf.nn.softmax(u, 1), 2) c = tf.reduce_sum(tf.multiply(input_x, a), axis=1) return c def global_attention(input_x, input_mask, W_att): flat_x = tf.reshape(input_x, [batch_size*max_sent_size, tf.shape(input_x)[2]]) h_tanh = tf.tanh(flat_x) u_flat = tf.matmul(h_tanh, W_att) u = tf.reshape(u_flat, [batch_size, max_sent_size]) + input_mask a = tf.expand_dims(tf.nn.softmax(u, 1), 2) c = tf.reduce_sum(tf.multiply(input_x, a), axis=1) return c with tf.variable_scope("word_embedding"): unk_word_emb_mat = tf.get_variable("word_emb_mat", dtype='float', shape=[unk_vocab_size, word_emb_size], initializer=tf.contrib.layers.xavier_initializer(uniform=True, seed=0, dtype=tf.float32)) final_word_emb_mat = tf.concat([word_emb_mat, unk_word_emb_mat], 0) with tf.variable_scope(tf.get_variable_scope()): for gpu_idx in range(num_gpus): if gpu_idx>=3: device_num = 1 with tf.name_scope("model_{}".format(gpu_idx)) as scope, tf.device('/gpu:%d' % device_num): if gpu_idx > 0: tf.get_variable_scope().reuse_variables() with tf.name_scope("word"): Wx = tf.nn.embedding_lookup(final_word_emb_mat, x[gpu_idx]) float_x_mask = tf.cast(x_mask[gpu_idx], 'float') x_len = tf.reduce_sum(tf.cast(x_mask[gpu_idx], 'int32'), axis=1) tile_x_mask = tf.tile(tf.expand_dims(float_x_mask, 2), [1, 1, word_emb_size]) Wx_masked = tf.multiply(Wx, tile_x_mask) with tf.variable_scope("convolution"): conv1 = tf.layers.conv1d(inputs=Wx_masked, filters=num_filter, kernel_size=[kernel_size], padding='same', activation=tf.nn.relu) conv2 = tf.layers.conv1d(inputs=conv1, filters=num_filter, kernel_size=[kernel_size], padding='same') with tf.variable_scope("lstm1"): cell_fw1 = tf.contrib.rnn.BasicLSTMCell(hidden_size,state_is_tuple=True) cell_bw1 = tf.contrib.rnn.BasicLSTMCell(hidden_size,state_is_tuple=True) d_cell_fw1 = tf.contrib.rnn.DropoutWrapper(cell_fw1, input_keep_prob=input_keep_prob) d_cell_bw1 = tf.contrib.rnn.DropoutWrapper(cell_bw1, input_keep_prob=input_keep_prob) (fw_h1, bw_h1), _ = tf.nn.bidirectional_dynamic_rnn(d_cell_fw1, d_cell_bw1, conv2, sequence_length=x_len, dtype='float', scope='lstm1') h1 = tf.concat([fw_h1, bw_h1], 2) with tf.variable_scope("lstm2"): cell_fw2 = tf.contrib.rnn.BasicLSTMCell(hidden_size,state_is_tuple=True) cell_bw2 = tf.contrib.rnn.BasicLSTMCell(hidden_size,state_is_tuple=True) d_cell_fw2 = tf.contrib.rnn.DropoutWrapper(cell_fw2, input_keep_prob=input_keep_prob) d_cell_bw2 = tf.contrib.rnn.DropoutWrapper(cell_bw2, input_keep_prob=input_keep_prob) (fw_h2, bw_h2), _ = tf.nn.bidirectional_dynamic_rnn(d_cell_fw2, d_cell_bw2, h1, sequence_length=x_len, dtype='float', scope='lstm2') h = tf.concat([fw_h2, bw_h2], 2) attention_mask = (tf.cast(x_mask[gpu_idx], 'float') -1)*VERY_BIG_NUMBER with tf.variable_scope("global_attention"): W_att_global = tf.get_variable("W_att_global", shape=[2*hidden_size, 1], initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1, seed=gpu_idx*10)) flat_h = tf.reshape(h, [batch_size*max_sent_size, tf.shape(h)[2]]) h_tanh = tf.tanh(flat_h) u_flat = tf.matmul(h_tanh, W_att_global) u = tf.reshape(u_flat, [batch_size, max_sent_size]) + attention_mask a = tf.expand_dims(tf.nn.softmax(u, 1), 2) c = tf.reduce_sum(tf.multiply(h, a), axis=1) c_final = tf.tile(tf.expand_dims(c, 1), [1, max_sent_size, 1]) h_final = tf.concat([c_final, h], 2) flat_h_final = tf.reshape(h_final, [batch_size*max_sent_size, tf.shape(h_final)[2]]) with tf.variable_scope("hidden_layer"): W = tf.get_variable("W", shape=[4*hidden_size, 2*hidden_size], initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1, seed=gpu_idx*20)) b = tf.get_variable("b", shape=[2*hidden_size], initializer=tf.zeros_initializer()) drop_flat_h_final = tf.nn.dropout(flat_h_final, input_keep_prob) flat_hl = tf.matmul(drop_flat_h_final, W) + b with tf.variable_scope("softmax_layer_pos"): W = tf.get_variable("W", shape=[2*hidden_size, num_pos], initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1, seed=gpu_idx*30)) b = tf.get_variable("b", shape=[num_pos], initializer=tf.zeros_initializer()) flat_h1 = tf.reshape(h1, [-1, tf.shape(h1)[2]]) drop_flat_hl = tf.nn.dropout(flat_hl, input_keep_prob) flat_logits_pos = tf.matmul(drop_flat_hl, W) + b logits_pos = tf.reshape(flat_logits_pos, [batch_size, max_sent_size, num_pos]) log_likelihood, trans_params = tf.contrib.crf.crf_log_likelihood(logits_pos, y_pos[gpu_idx], x_len) loss_pos = crf_lambda*tf.reduce_mean(-log_likelihood) predictions_pos.append(logits_pos) total_trans_params.append(trans_params) hierarchy = tf.matmul(logits_pos[:, :, :num_sense_pos], mask_matrix) with tf.variable_scope("softmax_layer"): W = tf.get_variable("W", shape=[2*hidden_size, num_senses], initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1, seed=gpu_idx*20)) b = tf.get_variable("b", shape=[num_senses], initializer=tf.zeros_initializer()) drop_flat_hl = tf.nn.dropout(flat_hl, input_keep_prob) flat_logits_sense = tf.matmul(drop_flat_hl, W) + b logits_org = tf.reshape(flat_logits_sense, [batch_size, max_sent_size, num_senses]) logits = tf.multiply(logits_org, hierarchy) predictions.append(tf.argmax(logits, 2)) float_sense_mask = tf.cast(sense_mask[gpu_idx], 'float') loss = tf.contrib.seq2seq.sequence_loss(logits, y[gpu_idx], float_sense_mask, name="loss") l2_loss = l2_lambda * tf.losses.get_regularization_loss() total_loss = tf.cond(pretrain, lambda:loss_pos, lambda:loss + loss_pos + l2_loss) summaries.append(tf.summary.scalar("loss_{}".format(gpu_idx), loss)) summaries.append(tf.summary.scalar("loss_pos_{}".format(gpu_idx), loss_pos)) summaries.append(tf.summary.scalar("total_loss_{}".format(gpu_idx), total_loss)) optimizer = tf.train.AdamOptimizer(learning_rate) grads_vars = optimizer.compute_gradients(total_loss) clipped_grads = grads_vars if(clipping == True): clipped_grads = [(tf.clip_by_norm(grad, clip_norm), var) for grad, var in clipped_grads] tower_grads.append(clipped_grads) losses.append(total_loss) with tf.device('/gpu:0'): tower_grads = average_gradients(tower_grads) losses = tf.add_n(losses)/len(losses) apply_grad_op = optimizer.apply_gradients(tower_grads, global_step=global_step) summaries.append(tf.summary.scalar('total_loss', losses)) summaries.append(tf.summary.scalar('learning_rate', learning_rate)) variable_averages = tf.train.ExponentialMovingAverage(moving_avg_deacy, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) train_op = tf.group(apply_grad_op, variables_averages_op) saver = tf.train.Saver(tf.global_variables()) summary = tf.summary.merge(summaries) os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"]="2,3" # print (device_lib.list_local_devices()) config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True sess = tf.Session(config=config) sess.run(tf.global_variables_initializer()) # For initializing all the variables summary_writer = tf.summary.FileWriter(log_dir, sess.graph) # For writing Summaries save_period = 100 log_period = 100 def model(xx, yy, yy_pos, mask, smask, train_cond=True, pretrain_cond=False): num_batches = int(len(xx)/(batch_size*num_gpus)) _losses = 0 temp_loss = 0 preds_sense = [] true_sense = [] preds_pos = [] true_pos = [] for j in range(num_batches): s = j * batch_size * num_gpus e = (j+1) * batch_size * num_gpus xx_re = xx[s:e].reshape([num_gpus, batch_size, -1]) yy_re = yy[s:e].reshape([num_gpus, batch_size, -1]) yy_pos_re = yy_pos[s:e].reshape([num_gpus, batch_size, -1]) mask_re = mask[s:e].reshape([num_gpus, batch_size, -1]) smask_re = smask[s:e].reshape([num_gpus, batch_size, -1]) feed_dict = {x:xx_re, y:yy_re, y_pos:yy_pos_re, x_mask:mask_re, sense_mask:smask_re, pretrain:pretrain_cond, is_train:train_cond, input_keep_prob:keep_prob, word_emb_mat:word_embedding} if(train_cond==True): _, _loss, step, _summary = sess.run([train_op, losses, global_step, summary], feed_dict) summary_writer.add_summary(_summary, step) temp_loss += _loss if((j+1)%log_period==0): print("Steps: {}".format(step), "Loss:{0:.4f}".format(temp_loss/log_period), ", Current Loss: {0:.4f}".format(_loss)) temp_loss = 0 if((j+1)%save_period==0): saver.save(sess, save_path=save_dir) else: _loss, pred, crf_logits, trans_params_ = sess.run([total_loss, predictions, predictions_pos, total_trans_params], feed_dict) for i in range(num_gpus): preds_sense.append(pred[i][smask_re[i]]) true_sense.append(yy_re[i][smask_re[i]]) true_pos.append(yy_pos_re[i][mask_re[i]]) temp = [] for k in range(batch_size): logit_ = crf_logits[i][k][:sum(mask_re[i][k])] # keep only the valid steps viterbi_seq, viterbi_score = tf.contrib.crf.viterbi_decode(logit_, trans_params_[i]) temp += viterbi_seq preds_pos.append(temp) _losses +=_loss if(train_cond==False): sense_preds = [] sense_true = [] pos_preds = [] pos_true = [] for preds in preds_sense: for ps in preds: sense_preds.append(ps) for trues in true_sense: for ts in trues: sense_true.append(ts) for preds in preds_pos: for ps in preds: pos_preds.append(ps) for trues in true_pos: for ts in trues: pos_true.append(ts) return _losses/num_batches, sense_preds, sense_true, pos_preds, pos_true return _losses/num_batches, step def eval_score(yy, pred, yy_pos, pred_pos): f1 = f1_score(yy, pred, average='macro') accu = accuracy_score(yy, pred) f1_pos = f1_score(yy_pos, pred_pos, average='macro') accu_pos = accuracy_score(yy_pos, pred_pos) return f1*100, accu*100, f1_pos*100, accu_pos*100 x_id_train = train_data['x'] mask_train = train_data['x_mask'] sense_mask_train = train_data['sense_mask'] y_train = train_data['y'] y_pos_train = train_data['pos'] x_id_val = val_data['x'] mask_val = val_data['x_mask'] sense_mask_val = val_data['sense_mask'] y_val = val_data['y'] y_pos_val = val_data['pos'] x_id_test = test_data['x'] mask_test = test_data['x_mask'] sense_mask_test = test_data['sense_mask'] y_test = test_data['y'] y_pos_test = test_data['pos'] def testing(): start_time = time.time() val_loss, val_pred, val_true, val_pred_pos, val_true_pos = model(x_id_val, y_val, y_pos_val, mask_val, sense_mask_val, train_cond=False) f1_, accu_, f1_pos_, accu_pos_ = eval_score(val_true, val_pred, val_true_pos, val_pred_pos) time_taken = time.time() - start_time print("Val: F1 Score:{0:.2f}".format(f1_), "Accuracy:{0:.2f}".format(accu_), " POS: F1 Score:{0:.2f}".format(f1_pos_), "Accuracy:{0:.2f}".format(accu_pos_), "Loss:{0:.4f}".format(val_loss), ", Time: {0:.1f}".format(time_taken)) return f1_, accu_, f1_pos_, accu_pos_ def evaluate(): start_time = time.time() test_loss1, test_pred1, test_true1, test_pred_pos1, test_true_pos1 = model(x_id_test, y_test, y_pos_test, mask_test, sense_mask_test, train_cond=False) test_loss2, test_pred2, test_true2, test_pred_pos2, test_true_pos2 = model(x_id_test[-num_gpus*batch_size:], y_test[-num_gpus*batch_size:], y_pos_test[-num_gpus*batch_size:], mask_test[-num_gpus*batch_size:], sense_mask_test[-num_gpus*batch_size:], train_cond=False) test_loss = test_loss1 + test_loss2 test_true = test_true1 + test_true2 test_pred = test_pred1 + test_pred2 test_pred_pos = test_pred_pos1 + test_pred_pos2 test_true_pos = test_true_pos1 + test_true_pos2 f1_, accu_, f1_pos_, accu_pos_ = eval_score(test_true, test_pred, test_true_pos, test_pred_pos) time_taken = time.time() - start_time print("Test: F1 Score:{0:.2f}".format(f1_), "Accuracy:{0:.2f}".format(accu_), " POS: F1 Score:{0:.2f}".format(f1_pos_), "Accuracy:{0:.2f}".format(accu_pos_), "Loss:{0:.4f}".format(test_loss), ", Time: {0:.1f}".format(time_taken)) return f1_, accu_, f1_pos_, accu_pos_ def training(current_epoch, pre_train_cond): random = np.random.choice(len(y_train), size=(len(y_train)), replace=False) x_id_train_tmp = x_id_train[random] y_train_tmp = y_train[random] mask_train_tmp = mask_train[random] sense_mask_train_tmp = sense_mask_train[random] y_pos_train_tmp = y_pos_train[random] start_time = time.time() train_loss, step = model(x_id_train_tmp, y_train_tmp, y_pos_train_tmp, mask_train_tmp, sense_mask_train_tmp, pretrain_cond=pre_train_cond) time_taken = time.time() - start_time print("Epoch: {}".format(current_epoch+1),", Step: {}".format(step), ", loss: {0:.4f}".format(train_loss), ", Time: {0:.1f}".format(time_taken)) saver.save(sess, save_path=save_dir) print("Model Saved") return [step, train_loss] loss_collection = [] val_collection = [] num_epochs = 20 val_period = 2 for i in range(num_epochs): loss_collection.append(training(i, False)) if((i+1)%val_period==0): val_collection.append(testing()) loss_collection = [] val_collection = [] num_epochs = 20 val_period = 2 for i in range(num_epochs): loss_collection.append(training(i, False)) if((i+1)%val_period==0): val_collection.append(testing()) testing() evaluate() start_time = time.time() train_loss, train_pred, train_true, train_pred_pos, train_true_pos = model(x_id_train, y_train, y_pos_train, mask_train, sense_mask_train, train_cond=False) f1_, accu_, f1_pos_, accu_pos_ = etrain_score(train_true, train_pred, train_true_pos, train_pred_pos) time_taken = time.time() - start_time print("train: F1 Score:{0:.2f}".format(f1_), "Accuracy:{0:.2f}".format(accu_), " POS: F1 Score:{0:.2f}".format(f1_pos_), "Accuracy:{0:.2f}".format(accu_pos_), "Loss:{0:.4f}".format(train_loss), ", Time: {0:.1f}".format(time_taken)) saver.restore(sess, save_dir) ```
github_jupyter
# Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask - **Twitter**: @iamtrask - **Blog**: http://iamtrask.github.io ### What You Should Already Know - neural networks, forward and back-propagation - stochastic gradient descent - mean squared error - and train/test splits ### Where to Get Help if You Need it - Re-watch previous Udacity Lectures - Leverage the recommended Course Reading Material - [Grokking Deep Learning](https://www.manning.com/books/grokking-deep-learning) (40% Off: **traskud17**) - Shoot me a tweet @iamtrask ### Tutorial Outline: - Intro: The Importance of "Framing a Problem" - Curate a Dataset - Developing a "Predictive Theory" - **PROJECT 1**: Quick Theory Validation - Transforming Text to Numbers - **PROJECT 2**: Creating the Input/Output Data - Putting it all together in a Neural Network - **PROJECT 3**: Building our Neural Network - Understanding Neural Noise - **PROJECT 4**: Making Learning Faster by Reducing Noise - Analyzing Inefficiencies in our Network - **PROJECT 5**: Making our Network Train and Run Faster - Further Noise Reduction - **PROJECT 6**: Reducing Noise by Strategically Reducing the Vocabulary - Analysis: What's going on in the weights? # Lesson: Curate a Dataset ``` def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].upper(),g.readlines())) g.close() len(reviews) reviews[0] labels[0] ``` # Lesson: Develop a Predictive Theory ``` print("labels.txt \t : \t reviews.txt\n") pretty_print_review_and_label(2137) pretty_print_review_and_label(12816) pretty_print_review_and_label(6267) pretty_print_review_and_label(21934) pretty_print_review_and_label(5297) pretty_print_review_and_label(4998) from collections import Counter import numpy as np positive_counts = Counter() negative_counts = Counter() total_counts = Counter() for i in range(len(reviews)): if(labels[i]=='POSITIVE'): for word in reviews[i].split(" "): positive_counts[word] += 1 total_counts[word] += 1 else: for word in reviews[i].split(" "): negative_counts[word] += 1 total_counts[word] += 1 positive_counts.most_common() pos_neg_ratios = Counter() for term, cnt in list(total_counts.most_common()): if(cnt> 100): pos_neg_ratio = positive_counts[term] / float(negative_counts[term]+1) pos_neg_ratios[term] = pos_neg_ratio for word, ratio in pos_neg_ratios.most_common(): if(ratio > 1): pos_neg_ratios[word] = np.log(ratio) else: pos_neg_ratios[word] = -np.log((1/(ratio+0.01))) pos_neg_ratios.most_common() ```
github_jupyter
# Correlations between the EPSC and IPSCs with increasing input Since the CA1 neuron saturates in its $V_{max}$ with increasing input, and this saturation is dependent on the inhibition, the shapes of the two functions must approach each other with increases in input. $$C(t) = E(t) - I(t)$$ As $C_{max}$ goes to constant, E and I should converge. ``` import numpy as np import pickle %matplotlib notebook import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors import os import sys from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm fileList = ['/media/sahil/NCBS_Shares_BGStim/patch_data/161220/c1_EI/plots/c1_EI_fits.pkl', '/media/sahil/NCBS_Shares_BGStim/patch_data/161220/c2_EI/plots/c2_EI_fits.pkl', '/media/sahil/NCBS_Shares_BGStim/patch_data/170117/c1_EI/plots/c1_EI_fits.pkl', '/media/sahil/NCBS_Shares_BGStim/patch_data/170117/c2_EI/plots/c2_EI_fits.pkl', '/media/sahil/NCBS_Shares_BGStim/patch_data/170317/c5_EI/plots/c5_EI_fits.pkl'] fileList = ['/media/sahil/NCBS_Shares_BGStim/patch_data/161220/c2_EI/plots/c2_EI_fits.pkl'] ``` ### Sliding window cross correlation between E and I ``` def periodicallyNormalizedCrossCorrelation(vec1, vec2, windowSize): ''' Returns the cross correlation of 2 vectors by running a window of same size through the 2 vectors''' normalizationLength = windowSize - 1 assert len(vec1) == len(vec2), "Lengths of vectors don't match" return np.array([np.correlate(normalizeTrace(vec1[i:i+windowSize])/normalizationLength, normalizeTrace(vec2[i:i+windowSize]))[0] for i in range(0,len(vec1),windowSize)]) def traceNormalizedCrossCorrelation(vec1, vec2, windowSize): ''' Returns the cross correlation of 2 vectors by running a window of same size through the 2 vectors''' assert len(vec1) == len(vec2), "Lengths of vectors don't match" return np.array([np.correlate(vec1[i:i+windowSize], vec2[i:i+windowSize])[0] for i in range(0,len(vec1),windowSize)]) ``` ### Sorted trials with maximum excitatory current values. ``` def sortTrialsByGmax(trials): gmax_array = np.array([trial.fit["g_max"].value for trial in trials]) sortIndices = np.argsort(gmax_array) return sortIndices, gmax_array[sortIndices] ``` ### Normalize to $\frac{x-\mu}{\sigma}$ for normalized correlation coefficients ``` def normalizeTrace(trace): return (trace - np.mean(trace))/(np.std(trace)) ``` ### Plot heatmap with the same. ``` def heatmap(corrMatrix, extent, title, fig = None, ax = None): if not ax: fig, ax = plt.subplots() heatmap = ax.imshow(corrMatrix, cmap='plasma', aspect='auto', extent=extent, origin='lower') cbar = fig.colorbar(heatmap, orientation='horizontal') ax.set_xlabel("Time (ms)") ax.set_ylabel("Current (pA)") cbar.ax.get_xaxis().labelpad = 15 cbar.ax.set_xlabel('Normalized correlation') if not ax: return fig def phaseplot(x,y,axis,c='blue'): phasePlot = axis.plot(x,y,c=c) return phasePlot def colorline( x, y, z=None, cmap='inferno', norm=plt.Normalize(0.0, 1.0), linewidth=0.5, alpha=0.5): """ http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a line width """ # Default colors equally spaced on [0,1]: if z is None: z = np.linspace(0.0, 1.0, len(x)) # Special case if a single number: # to check for numerical input -- this is a hack if not hasattr(z, "__iter__"): z = np.array([z]) z = np.asarray(z) segments = make_segments(x, y) lc = LineCollection(segments, array=z, cmap=cmap, norm=norm, linewidth=linewidth, alpha=alpha) ax = plt.gca() ax.add_collection(lc) return lc def make_segments(x, y): """ Create list of line segments from x and y coordinates, in the correct format for LineCollection: an array of the form numlines x (points per line) x 2 (x and y) array """ points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) return segments ``` ### Plotting EI correlations over time for four different cells with current recordings. ``` for i,analysisFile in enumerate(fileList): plotDir = os.path.dirname(analysisFile) with open (analysisFile,'rb') as p: neuron = pickle.load(p) windowSize = 20 fullWindowSize = 1000 totalTime = fullWindowSize/windowSize #ms excTrialList, inhTrialList= [], [] exc, inh = neuron.experiment[1], neuron.experiment[2] for numSquares in (set(exc) & set(inh)): excTrialList+=[exc[numSquares].trial[trialNum] for trialNum in exc[numSquares].trial] inhTrialList+=[inh[numSquares].trial[trialNum] for trialNum in inh[numSquares].trial] sortIndices, sortedValues = sortTrialsByGmax(excTrialList) extent = [0, fullWindowSize/windowSize, min(sortedValues)*1e3, max(sortedValues)*1e3] # tmin, tmax, gmin, gmax in ms, and nA nrows, ncols = 15,12 scalingFactor = 1e9 #Converting currents to picoAmperes cmap = cm.get_cmap('inferno') norm = colors.Normalize(vmin=sortedValues[0]*1e3, vmax=sortedValues[-1]*1e3) colorSpace = np.linspace(0.,1.,nrows*ncols) # Phase plot of E and I fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, sharey=True,figsize=(12,8)) position = [(x,y) for x in range(nrows) for y in range(ncols)] for trialIndex,pos in zip(sortIndices, position): axis = phaseplot(excTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, inhTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, ax[pos[0]][pos[1]], c=cmap(i)) fig.text(0.5, 0.0, 'Excitation', ha='center') fig.text(0.0, 0.5, 'Inhibition', va='center', rotation='vertical') fig.tight_layout() fig.show() # Phase plot of E and I fig, ax = plt.subplots(ncols=2, gridspec_kw = {'width_ratios':[20, 1]}) for trialIndex,i in zip(sortIndices[::-1],colorSpace[::-1]): ax[0].plot(excTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, inhTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, c=cmap(i), alpha=0.5) ax[0].set_xlabel("Excitation") ax[0].set_ylabel("Inhibition") cbar = matplotlib.colorbar.ColorbarBase(ax[1], cmap=cmap, norm=norm, orientation='vertical') cbar.set_label('$Exc_{max}$') fig.show() # Phase plot of E and I colored in time fig, ax = plt.subplots() z = np.linspace(0, 1, len(excTrialList[0].interestWindow[:fullWindowSize])) #plt.sca(ax[0]) for trialIndex,i in zip(sortIndices[::-1],colorSpace[::-1]): lc = colorline(excTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, inhTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor, z) ax.set_xlabel("Excitation") ax.set_ylabel("Inhibition") #lc = colorline(x, y, cmap='inferno') cbar = fig.colorbar(lc, norm = colors.Normalize(vmin=0, vmax=len(excTrialList[0].interestWindow[:fullWindowSize])/20)) #plt.show() #cbar = matplotlib.colorbar.ColorbarBase(ax[1], cmap=cmap, norm=norm, orientation='vertical') cbar.set_label('$Time$') fig.show() # Sliding window, normalized to window correlations print ("Periodically normalized correlations") correlationMatrix = [] fig,ax = plt.subplots(nrows=2, sharex=True) for trialIndex in sortIndices: correlationMatrix.append(periodicallyNormalizedCrossCorrelation(excTrialList[trialIndex].interestWindow[:fullWindowSize], inhTrialList[trialIndex].interestWindow[:fullWindowSize], windowSize)) ax[0].plot(np.linspace(0, totalTime, fullWindowSize), excTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor) ax[0].plot(np.linspace(0, totalTime, fullWindowSize), inhTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor) ax[0].set_xlabel("Time (ms)") ax[0].set_ylabel("Current (pA)") correlationMatrix = np.matrix(correlationMatrix) heatmap(correlationMatrix, extent, title=str(neuron.date) + '_' + str(neuron.index), fig=fig, ax=ax[1]) fig.show() # Sliding window, normalized to trial correlations print ("Trace normalized correlations") correlationMatrix = [] fig,ax = plt.subplots(nrows=2, sharex=True) for trialIndex in sortIndices: correlationMatrix.append(traceNormalizedCrossCorrelation(normalizeTrace(excTrialList[trialIndex].interestWindow[:fullWindowSize])/(fullWindowSize-1), normalizeTrace(inhTrialList[trialIndex].interestWindow[:fullWindowSize]), windowSize)) ax[0].plot(np.linspace(0, totalTime, fullWindowSize), excTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor) ax[0].plot(np.linspace(0, totalTime, fullWindowSize), inhTrialList[trialIndex].interestWindow[:fullWindowSize]*scalingFactor) ax[0].set_xlabel("Time (ms)") ax[0].set_ylabel("Current (pA)") correlationMatrix = np.matrix(correlationMatrix) heatmap(correlationMatrix, extent, title=str(neuron.date) + '_' + str(neuron.index), fig=fig, ax=ax[1]) fig.show() # full trace cross-correlation normalized to trial correlations #print "Trace normalized correlations" #correlationMatrix = [] #for trialIndex in sortIndices: # correlationMatrix.append(traceNormalizedCrossCorrelation(normalizeTrace(excTrialList[trialIndex].interestWindow)/(fullWindowSize-1), normalizeTrace(-inhTrialList[trialIndex].interestWindow), windowSize)) #correlationMatrix = np.matrix(correlationMatrix) #fig = heatmap(correlationMatrix, extent, title=str(neuron.date) + '_' + str(neuron.index)) #fig.show() ``` First figure is phase plots of E vs I, sorted from lowest to highest $Exc_{max}$ and arranged as left to right rasters. If the two variables are correlated in time, we expect to see a diagonal line with negative slope. The same is overplotted below on Figure 2. Will have to tidy this up a bit. Figure 3 is bin-normalized correlations, looking at just shape changes in every bin. Periodically normalized correlations Figure 4 is trace-normalized correlations, looking at bin-wise correlations normalized to the whole trace.
github_jupyter
MIT License Copyright (c) 2021 Taiki Miyagawa and Akinori F. Ebihara Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # <font color=red> Lite version reduces GPU memory consumption at the expense of CPU memory and runtime. </font> Take care of your CPU memory. # Plot Speed-Accuracy Tradeoff (SAT) Curve of Validation dataset ``` from __future__ import absolute_import, division, print_function import os, sys, glob, time from itertools import zip_longest import optuna import matplotlib.pyplot as plt from matplotlib.ticker import LogFormatter, ScalarFormatter, NullFormatter import numpy as np import tensorflow as tf from datasets.data_processing import read_tfrecords_UCF101,\ decode_feat, sequential_slice, sequential_concat from models.backbones_ti import LSTMModelLite from models.optimizers import get_optimizer from models.losses import get_gradient_lstm from utils.misc import load_yaml, set_gpu_devices, fix_random_seed,\ restrict_classes, extract_positive_row, add_max_to_diag from utils.performance_metrics import multiplet_sequential_confmx,\ llr_sequential_confmx,\ truncated_MSPRT, threshold_generator,\ calc_llrs, calc_oblivious_llrs, threshold_generator, thresh_sanity_check,\ NP_test,\ get_LLR_min_and_max, get_linspace, threshold_generator_with_values,\ seqconfmx_to_metrics ``` # User-defined params ``` # User-defined order_sprt = 10 # order of MSPRT-TANDEM oblivious = False # M-TANDEM (False) or M-TANDEMwO (True) name_model = "./data-directory/sprt_multiclass/UCF101/ckptlogs/MSPRT-TANDEM_ver20210331_stat/__20210424_150952523/" # for example # User-defined num_thresh = 10 # Total number of thresholds to be used to plot the SAT curve batch_thresh = 5 # Memory consuming!! How many thresholds to be feeded at a time. < 10 is recommended sparsity = "linspace" # "linspace" or logspace". Used for threshold generation. class_plot = -2 # -1:micro-averaged recall, -2:macro-averaged recall. dataname = "UCF101-50-240-320" # "UCF101-150-240-320", "UCF101-50-256-256", ... tfr_train = "DATADIR/UCF101TFR-50-240-320/train01.tfrecords" tfr_valid = "DATADIR/UCF101TFR-50-240-320/valid01.tfrecords" tfr_test = "DATADIR/UCF101TFR-50-240-320/test01.tfrecords" batch_size = 100 # Must be a divisor of the num of test datapoints. Memory consumption << batch_thresh. batch_size2 = 50 # used for calc_llrs, NP_test, and trundated_MSPRT. Not necessarily a divisor of the sample size. gpu = 0 # Which GPU to be used assert num_thresh % batch_thresh == 0 # Make sure # Must be consistent with the model (name_model). duration = 50 feat_dim = 2048 # input feature dimension num_classes = 101 width_lstm = 256 # dim of hidden layers of LSTM dropout = 0. activation = "tanh" # Which GPU to be used set_gpu_devices(gpu) ``` # 0. Start calc logits and LLRs ``` # Load data ################################## # Reed tfr and make dataset_tr, dataset_va,\ dataset_te = \ read_tfrecords_UCF101( record_file_tr=tfr_train, record_file_va=tfr_valid, record_file_te=tfr_test, batch_size=batch_size, flag_shuffle=False, shuffle_buffer_size=10000) # Model ################################## model = LSTMModelLite( num_classes=num_classes, width_lstm=width_lstm, dropout=dropout, activation=activation) # Restore parameters ################################# ckpt = tf.train.Checkpoint(net=model) ckpt_manager_restore = tf.train.CheckpointManager(ckpt, name_model, max_to_keep=3) ckpt.restore(ckpt_manager_restore.latest_checkpoint) print("Restored latest model\n{}".format( ckpt_manager_restore.latest_checkpoint)) # Evaluaton loop ################################## for iter_b, feats in enumerate(dataset_va): cnt = iter_b + 1 x_batch = feats[0] x_batch = tf.reshape(x_batch, (-1, duration, feat_dim)) # (batch, duration, feat dims) y_batch = feats[1] # (batch, ) x_slice, y_slice = sequential_slice(x_batch, y_batch, order_sprt) # Calc logits if iter_b == 0: ls_logits = [] ls_labels = [] # Calc loss logits_tmp = model(x_slice, False) logits_tmp, _ = sequential_concat(logits_tmp, y_slice, duration) ls_logits.append(logits_tmp.numpy()) ls_labels.append(y_batch.numpy()) # Verbose if ((iter_b+1)%10 == 0) or (iter_b == 0): sys.stdout.write("\rEvaluation Iter: {:3d}".format(iter_b+1)) sys.stdout.flush() print() logits_all = np.concatenate(ls_logits, axis=0) labels_all = np.concatenate(ls_labels, axis=0) # Calc LLRs num_data = labels_all.shape[0] num_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1 llrs_all = [] start = -1 stop = -1 for i in range(num_iter): itr_logits = logits_all[i * batch_size2 : (i + 1) * batch_size2] if oblivious: itr_llrs = calc_oblivious_llrs(itr_logits) else: itr_llrs = calc_llrs(itr_logits) llrs_all.append(itr_llrs.numpy()) # Used to generate thresholds tmp_start, tmp_stop = get_LLR_min_and_max(itr_llrs) # A bit memory consuming. tmp_start = tmp_start.numpy() tmp_stop = tmp_stop.numpy() if i == 0: start = tmp_start stop = tmp_stop continue if tmp_start < start: start = tmp_start if tmp_stop > stop: stop = tmp_stop # Verbose if ((iter_b + 1) % 10 == 0) or (iter_b == 0): sys.stdout.write("\rEvaluation Iter: {:3d}/{}".format(iter_b+1, num_iter)) sys.stdout.flush() values = get_linspace(start, stop, num_thresh, sparsity).numpy() llrs_all = np.concatenate(llrs_all, axis=0) tic = time.time() print("This cell takes a few minutes because of the two mini-batch processes...") # Batch processing for thresh axis to save GPU memory ###################################################### num_data = labels_all.shape[0] ls_confmx_th = [] ls_mht_th = [] ls_vht_th = [] ls_trt_th = [] for i in range(num_thresh // batch_thresh): print("Thresh Iter {}/{} ...".format(i+1, num_thresh // batch_thresh)) # Generate Thresholds for SPRT idx = batch_thresh * i itr_values = values[idx : idx + batch_thresh] itr_thresh = threshold_generator_with_values(itr_values, duration, num_classes) # memory consuming thresh_sanity_check(itr_thresh) # Batch processing for data axis to save GPU memory #################################################### num_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1 tmp_confmx_th = 0 tmp_mht_th = [] tmp_sqr_th = [] tmp_trt_th = [] for i in range(num_iter): itr_llrs = llrs_all[i * batch_size2 : (i + 1) * batch_size2] itr_labels = labels_all[i * batch_size2 : (i + 1) * batch_size2] _len = itr_labels.shape[0] # Confusion matrix of SPRT, mean/var hitting time, # and truncation rate _tmp_confmx_th, _tmp_mht_th, _tmp_vht_th, _tmp_trt_th = \ truncated_MSPRT( llr_mtx=itr_llrs, labels_concat=itr_labels, thresh_mtx=itr_thresh) # Super GPU memory super-consuming # if batch_thresh or batch_size2 is large. # The shapes of the outputs are: # (batch_thresh, num classes, num classes) # (batch_thresh,) # (batch_thresh,) # (batch_thresh,) _tmp_sqr_th = _tmp_vht_th + _tmp_mht_th ** 2 tmp_confmx_th += _tmp_confmx_th.numpy() tmp_mht_th.append(np.expand_dims(_tmp_mht_th.numpy(), axis=0) * _len) tmp_sqr_th.append(np.expand_dims(_tmp_sqr_th.numpy(), axis=0) * _len) tmp_trt_th.append(np.expand_dims(_tmp_trt_th.numpy(), axis=0) * _len) #<- should be integers tmp_mht_th = np.concatenate(tmp_mht_th, axis=0) # (num_iter, batch_thresh) tmp_mht_th = np.sum(tmp_mht_th, axis=0) / num_data # (batch_thresh, ) tmp_sqr_th = np.concatenate(tmp_sqr_th, axis=0) # (num_iter, batch_thresh) tmp_sqr_th = np.sum(tmp_sqr_th, axis=0) / num_data # (batch_thresh, ) tmp_vht_th = tmp_sqr_th - tmp_mht_th ** 2 # (batch_thresh, ) tmp_trt_th = np.concatenate(tmp_trt_th, axis=0) # (num_iter, batch_thresh) tmp_trt_th = np.sum(tmp_trt_th, axis=0) / num_data # (batch_thresh, ) ls_confmx_th.append(tmp_confmx_th) ls_mht_th.append(tmp_mht_th) ls_vht_th.append(tmp_vht_th) ls_trt_th.append(tmp_trt_th) confmx_th = np.concatenate(ls_confmx_th, axis=0) # (num thresh, num cls, num cls) mht_th = np.concatenate(ls_mht_th, axis=0) # (num thresh, ) vht_th = np.concatenate(ls_vht_th, axis=0) # (num thresh, ) trt_th = np.concatenate(ls_trt_th, axis=0) # (num thresh, ) print(time.time() - tic, "seconds") # SPRT results ########################### # Extract recalls (sensitivities) dc_mtr = seqconfmx_to_metrics(confmx_th) # Output ls_sns = dc_mtr["SNS"].numpy() # (num thresh, num classes + 2) # [[recall of class 0, 1, 2, ..., recall of the last class, balanced accuracy, accuracy], ...] ls_mht = mht_th#.numpy() # (num thresh,) ls_vht = vht_th#.numpy() # (num thresh,) ls_trt = trt_th#.numpy() # (num thresh,) # NPT confmx ############################ num_iter = num_data // batch_size2 if num_data % batch_size2 == 0 else num_data // batch_size2 + 1 seqconfmx_llr = 0 for i in range(num_iter): if (i + 1) % 50 == 0: print("Iter {}/{}".format(i+1, num_iter)) itr_llrs = llrs_all[i * batch_size2 : (i + 1) * batch_size2] itr_labels = labels_all[i * batch_size2 : (i + 1) * batch_size2] _tmp_seqconfmx_llr = NP_test(itr_llrs, itr_labels) # (duration, num classes, num classes) seqconfmx_llr += _tmp_seqconfmx_llr.numpy() # (duration, num classes, num classes) # NPT results ########################### dc_mtr_llr = seqconfmx_to_metrics(seqconfmx_llr) # Output ls_sns_NPT = dc_mtr_llr["SNS"].numpy() # (duration, num classes + 2) # [[recall of class 0, 1, 2, ..., recall of the last class, balanced accuracy, accuracy], ...] ################## end TMmod 20210106 ############### ls_trt # truncation rate. All 0 or all 1 signal a problem. ``` __Materials__ 1. `ls_mht` 2. `ls_vht` 3. `ls_trt` 4. `ls_sns` 5. `ls_sns_NPT` # 1. Plot SAT (Speed-Accuracy Tradeoff) Curve ``` # Start plotting SP curve ###################################### # Parameters x = ls_mht y = 100 * (1 - ls_sns[:, class_plot]) # macro-averaged recall title = "SAT curve, data={}, order={}".format(dataname, order_sprt) xlabel = "Mean hitting time (# frames)" if class_plot < num_classes: _tmp = "(Class={})".format(class_plot) elif class_plot == num_classes: _tmp = "(Mac-ave)" elif class_plot == num_classes + 1: _tmp = "(Mic-ave)" else: raise ValueError ylabel = "100 - Recall ({}) (%)".format(_tmp) # Size plt.rcParams["font.size"] = 25 fig, ax = plt.subplots(figsize=(13,8)) fig.patch.set_facecolor('white') # Scale ax.set_xscale('log') # Grid major_ticks = np.arange(0, duration + 1, 10) major_ticks[0] += 1 minor_ticks = np.arange(0, duration + 1, 1) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_xticklabels(['0, 10, 20, 30, 40, 50']) for axis in [ax.xaxis, ax.yaxis]: # ? axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) # Plot plt.scatter( x, y, s=10, color="red", marker='o', vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None ) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.grid(which='both') #plt.legend(loc=None, fontsize='15') plt.title(title) plt.xlim(0.95, duration+0.3)# 1stO, 19thO #plt.xlim(3.95, duration+0.3)# 1stO, 19thO #plt.ylim(99.08, 99.65) # 1stO, 19thO #plt.xlim(4.-0.3, duration+0.3)# 1stO, 19thO #plt.ylim(70.08, 80.65) # 1stO, 19thO plt.tight_layout() # Save figure #plt.savefig(***) ``` ## 1-1. SPRT vs NPT ``` # Plot NPT vs SPRT ############################### # Parameters x = ls_mht y = 100 * (1 - ls_sns[:, class_plot]) x_np = np.array([i + 1 for i in range(duration)]) y_np = 100 * (1 - ls_sns_NPT[:, class_plot]) label = "SPRT" label_np = "NPT" title = "SAT curve, data={}, order={}".format(dataname, order_sprt) xlabel = "Mean hitting time (# frames)" if class_plot < num_classes: _tmp = "(Class={})".format(class_plot) elif class_plot == num_classes: _tmp = "(Mac-ave)" elif class_plot == num_classes + 1: _tmp = "(Mic-ave)" else: raise ValueError ylabel = "100 - Recall ({}) (%)".format(_tmp) # Size plt.rcParams["font.size"] = 25 fig, ax = plt.subplots(figsize=(13,8)) # Scale ax.set_xscale('log') # Grid major_ticks = np.arange(0, duration + 1, 10) major_ticks[0] += 1 minor_ticks = np.arange(0, duration + 1, 1) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_xticklabels(['0, 10, 20, 30, 40, 50']) for axis in [ax.xaxis, ax.yaxis]: # ? axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) # Plot SPRT plt.scatter( x, y, s=10, color="red", marker='o', vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None, label="SPRT" ) # Plot NPT plt.scatter( x_np, y_np, s=10, color="blue", marker='o', vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None, label="NPT" ) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.grid(which='both') plt.legend(loc=1, fontsize='15') plt.title(title) plt.xlim(0.95, duration+0.3) #plt.xlim(10.95, duration+0.3) #plt.ylim(88., 99.7) # v1 #plt.ylim(95, 99.7) # v2 plt.tight_layout() # Save figure # plt.savefig(***) ``` # 2. Plot SAT Curve with Standard Deviation of Hitting Times ``` # Start plotting SP curve with variance ###################################### # Parameters x = ls_mht y = 100. * ls_sns[:, -2] # macro-averaged recall xerr = np.sqrt(ls_vht) title = "SAT Curve, data=NMNIST, order={}".format(order_sprt) xlabel = "Mean Hitting Time (# frames)" ylabel = "Macro-averaged recall (%)" # Size plt.rcParams["font.size"] = 25 fig, ax = plt.subplots(figsize=(13,8)) fig.patch.set_facecolor('white') # Scale #ax.set_xscale('log') # Grid major_ticks = np.arange(0, duration + 1, 10) major_ticks[0] += 1 minor_ticks = np.arange(0, duration + 1, 1) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_xticklabels(['0, 10, 20, 30, 40, 50']) for axis in [ax.xaxis, ax.yaxis]: # ? axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) # Plot plt.errorbar( x, y, xerr = xerr, capsize=3, fmt='o', markersize=2, ecolor='black', markeredgecolor = "black", color='red', elinewidth=0.5) plt.ylabel(ylabel) plt.xlabel(xlabel) plt.grid(which='both') #plt.legend(loc=4, fontsize='15') plt.title(title) #plt.xlim(0.95, duration+0.3) #plt.ylim(88., 99.7) # v1 #plt.ylim(95, 99.7) # v2 plt.tight_layout() # Save figure # plt.savefig(***) ``` # 3. Plot Trajectories of LLRs - min LLR. - $\mathrm{max}_k \mathrm{min}_{l \neq k} \mathrm{LLR}_{kl} (t)$ on a single plane - min LLR for each class ($K$ plots). - $\mathrm{min}_{l \neq k} \mathrm{LLR}_{kl} (t)$. One $k$, one plane - all LLRs for each class ($K$ plots in each of which there are $K$ - 1 types of trajectories). - $\mathrm{LLR}_{kl} (t)$, where $k \neq l$. One $k$, one plane. - all LLRs, positive class mins (red) and negative class mins (blue). - $\mathrm{min}_{l \neq k} \mathrm{LLR}_{kl} (t)$, where `color = red` if $k = y_i$ else `color = blue`. - positive LLR row. All and each k. - $\mathrm{LLR}_{y_{i}\, l}$, where $l \neq y_i$ \begin{equation} \lambda(t) := \begin{pmatrix} 0 & \cdots & \lambda_{1l}(t) & \cdots & \lambda_{1K}(t)\\ \vdots & \ddots & & & \vdots \\ -\lambda_{1l}(t) & & 0 & & \lambda_{kK}(t) \\ \vdots & & & \ddots & \vdots \\ -\lambda_{1K}(t) & \cdots & -\lambda_{kK}(t) & \cdots & 0 \end{pmatrix} \end{equation} \begin{equation} \lambda_{kl}(t) := \log(\frac{p(X^{(1,t)}\,\,\,|y=k)}{p(X^{(1,t)}\,\,\,|y=l)})\,\,\, (k, l \in [K], K\in\mathbb{N}) \end{equation} ## 3-4-1. All LLR rows with minimum $l - $\mathrm{min}_{l\neq k} \mathrm{LLR}_{k\, l}$ ``` num_trj = 1 plot_classes = [] # optional: default=[] shuffle = True # currently not supported # Initialization llrs_trj = llrs_all[:num_trj] labels_trj = labels_all[:num_trj] # Restrict classes (optional) llrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes) labels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj ### Add max LLR to diag llrs_trj = add_max_to_diag(llrs_trj) ### Extract min column: shape change (batch, duration, num classes num classes) -> (batch, duration, num classes) llrs_trj = tf.reduce_min(llrs_trj, axis=3) # Shuffle (optional) if shuffle: idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32) labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32) # Pick some out llrs_trj = llrs_trj[:num_trj].numpy() labels_trj = labels_trj[:num_trj].numpy() # Color definitions ls_color = [ "red", "blue", ] ls_plotLabel =[ "min_l {LLR_k =yi l}", "min_l {LLR_k!=yi l}", ] # Start plotting trajectory ###################################### # Parameters x = [i for i in range(0, duration+1)] title = "Random example LLR trajectory,\ndata=NMNIST-100f15pix, order={}".format(order_sprt) xlabel = "Frame" ylabel = "Log-likelihood ratio" # Size plt.rcParams["font.size"] = 25 plt.figure(figsize=(13,8)) # plt.xticks([1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], # []) _tmp = set() for itr_llrs, itr_label in zip(llrs_trj, labels_trj): itr_llrs = np.transpose(itr_llrs, [1, 0]) # (num classes, duration) for itr_i, itr_trj in enumerate(itr_llrs): y = np.append(0, itr_trj) # Color and plot label if itr_i == itr_label: color = ls_color[0] if not (_tmp >= {ls_plotLabel[0]}): plot_label = ls_plotLabel[0] _tmp.add(plot_label) else: plot_label = None else: color = ls_color[1] if not (_tmp >= {ls_plotLabel[1]}): plot_label = ls_plotLabel[1] _tmp.add(plot_label) else: plot_label = None # Plot plt.plot( x, y, color=color, marker='o', linewidth=1, markersize=0, label=plot_label, alpha=0.7 ) cnt += 1 plt.xlabel(xlabel) plt.ylabel(ylabel) plt.yscale("symlog") plt.grid(True) plt.legend(fontsize='15') plt.title(title) plt.xticks([i for i in range(0, duration + 1)]) #plt.xlim(-0.1, 20.1) plt.locator_params(axis='x', nbins=11) plt.tight_layout() # Save figure # plt.savefig( # "./traj_order{}.svg".format(order_sprt), # format="svg", # dpi=1200) ``` ## 3-1. Positive LLR row - $\mathrm{LLR}_{y_{i}\, l}$, where $l \neq y_i$ ``` num_trj = 10 plot_classes = [] # optional: default=[] shuffle = True # currently not supported # Initialization llrs_trj = llrs_all[:50] labels_trj = labels_all[:50] # Restrict classes (optional) llrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes) labels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj ################### TMmod 20210106 ############### ### Extract positive rows: shape change -> (batch, duration, num classes) llrs_trj = extract_positive_row(llrs_trj, labels_trj) # Shuffle (optional) if shuffle: idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32) labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32) # Pick some up llrs_trj = llrs_trj[:num_trj].numpy() labels_trj = labels_trj[:num_trj].numpy() # Color definitions ls_color = [ None ] * num_classes ls_plotLabel =[ "_"] * num_classes # Start plotting trajectory ###################################### # Parameters x = [i for i in range(0, duration+1)] title = "Random example LLR trajectory, data=NMNIST, order={}".format(order_sprt) xlabel = "Frame" ylabel = "Log-likelihood ratio" # Size plt.rcParams["font.size"] = 25 plt.figure(figsize=(13,8)) _tmp = set() for itr_llrs, itr_label in zip(llrs_trj, labels_trj): itr_llrs = np.transpose(itr_llrs, [1, 0]) itr_llrs = np.delete(itr_llrs, obj=itr_label, axis=0) # (num classes - 1, duration) for itr_trj in itr_llrs: y = np.append(0, itr_trj) # Color color = ls_color[itr_label] # Label if _tmp >= {itr_label}: plot_label = None else: _tmp.add(itr_label) plot_label = ls_plotLabel[itr_label] # Plot plt.plot( x, y, color=color, marker='o', linewidth=1, markersize=0, label=plot_label ) cnt += 1 plt.xlabel(xlabel) plt.ylabel(ylabel) plt.yscale("symlog") plt.grid(True) #plt.legend(fontsize='15') plt.title(title) plt.xticks([i for i in range(0, duration + 1)]) #plt.xlim(-0.1, 20.1) plt.tight_layout() # Save figure # plt.savefig( # "./traj_order{}.svg".format(order_sprt), # format="svg", # dpi=1200) ``` ## 3-3. Positive LLR row with minimum $l$ - $\mathrm{min}_{l (\neq y_i)} \mathrm{LLR}_{y_{i}\, l}$ ``` num_trj = 20 plot_classes = [] # optional: default=[] shuffle = True # currently not supported # Initialization llrs_trj = llrs_all[:100] labels_trj = labels_all[:100] # Restrict classes (optional) llrs_trj, labels_trj = restrict_classes(llrs_trj, labels_trj, plot_classes) labels_trj = labels_trj.numpy() if len(plot_classes) != 0 else labels_trj ################### TMmod 20210106 ############### ### Add max LLR to diag llrs_trj = add_max_to_diag(llrs_trj) ### Extract positive rows: shape change -> (batch, duration, num classes) llrs_trj = extract_positive_row(llrs_trj, labels_trj) ### Extract min column: shape change (batch, duration, num classes) -> (batch, duration) llrs_trj = tf.reduce_min(llrs_trj, axis=2) # Shuffle (optional) if shuffle: idx_perm = np.random.permutation(labels_trj.shape[0]) # randomly take some LLRs llrs_trj = tf.constant(llrs_trj.numpy()[idx_perm], dtype=tf.float32) labels_trj = tf.constant(labels_trj[idx_perm], dtype=tf.int32) # Pick some up llrs_trj = llrs_trj[:num_trj].numpy() labels_trj = labels_trj[:num_trj].numpy() # Color definitions ls_color = [ None ] * num_classes ls_plotLabel =[ "_"] * num_classes # Start plotting trajectory ###################################### # Parameters x = [i for i in range(0, duration+1)] title = "Random example LLR trajectory, data=NMNIST, order={}".format(order_sprt) xlabel = "Frame" ylabel = "Log-likelihood ratio" # Size plt.rcParams["font.size"] = 25 plt.figure(figsize=(13,8)) _tmp = set() for itr_trj, itr_label in zip(llrs_trj, labels_trj): y = np.append(0, itr_trj) # Color color = ls_color[itr_label] # Label if _tmp >= {itr_label}: plot_label = None else: _tmp.add(itr_label) plot_label = ls_plotLabel[itr_label] # Plot plt.plot( x, y, color=color, marker='o', linewidth=2, markersize=0, label=plot_label ) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.yscale("symlog") plt.grid(True) #plt.legend(fontsize='15') #plt.title(title) plt.xticks([10 * i for i in range(0, 6)]) #plt.xlim(-0.1, 20.1) plt.tight_layout() # Save figure # filename = "/data/t-miyagawa/sprt_multiclass/nosaic_mnist-1000f/graphs/LLRtrajectory_UCF101v4" # plt.savefig( # "{}.svg".format(filename), # format="svg", # dpi=1200) ```
github_jupyter
# WorkFlow ## Classes ## Load the data ## Test Modelling ## Modelling **<hr>** ## Classes ``` BATCH_SIZE = 250 import os import cv2 import torch import numpy as np def load_data(img_size=112): data = [] index = -1 labels = {} for directory in os.listdir('./data/'): index += 1 labels[f'./data/{directory}/'] = [index,-1] print(len(labels)) for label in labels: for file in os.listdir(label): filepath = label + file img = cv2.imread(filepath,cv2.IMREAD_GRAYSCALE) img = cv2.resize(img,(img_size,img_size)) img = img / 255.0 data.append([ np.array(img), labels[label][0] ]) labels[label][1] += 1 for _ in range(12): np.random.shuffle(data) print(len(data)) np.save('./data.npy',data) return data import torch def other_loading_data_proccess(data): X = [] y = [] print('going through the data..') for d in data: X.append(d[0]) y.append(d[1]) print('splitting the data') VAL_SPLIT = 0.25 VAL_SPLIT = len(X)*VAL_SPLIT VAL_SPLIT = int(VAL_SPLIT) X_train = X[:-VAL_SPLIT] y_train = y[:-VAL_SPLIT] X_test = X[-VAL_SPLIT:] y_test = y[-VAL_SPLIT:] print('turning data to tensors') X_train = torch.from_numpy(np.array(X_train)) y_train = torch.from_numpy(np.array(y_train)) X_test = torch.from_numpy(np.array(X_test)) y_test = torch.from_numpy(np.array(y_test)) return [X_train,X_test,y_train,y_test] ``` **<hr>** ## Load the data ``` REBUILD_DATA = True if REBUILD_DATA: data = load_data() np.random.shuffle(data) X_train,X_test,y_train,y_test = other_loading_data_proccess(data) ``` ## Test Modelling ``` import torch import torch.nn as nn import torch.nn.functional as F class Test_Model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 8, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 25 * 25, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 36) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 25 * 25) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x device = torch.device('cuda') model = Test_Model().to(device) # preds = model(X_test.reshape(-1,1,112,112).float()) # preds[0] optimizer = torch.optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() BATCH_SIZE = 250 EPOCHS = 5 loss_logs = [] from tqdm import tqdm PROJECT_NAME = "Sign-Language-Recognition" def test(net,X,y): correct = 0 total = 0 net.eval() with torch.no_grad(): for i in range(len(X)): real_class = torch.argmax(y[i]).to(device) net_out = net(X[i].view(-1,1,112,112).to(device).float()) net_out = net_out[0] predictied_class = torch.argmax(net_out) if predictied_class == real_class: correct += 1 total += 1 return round(correct/total,3) import wandb len(os.listdir('./data/')) import random index = random.randint(0,29) print(index) wandb.init(project=PROJECT_NAME,name='test') for _ in tqdm(range(EPOCHS)): for i in range(0,len(X_train),BATCH_SIZE): X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) y_batch = y_train[i:i+BATCH_SIZE].to(device) model.to(device) preds = model(X_batch.float()) loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) optimizer.zero_grad() loss.backward() optimizer.step() wandb.log({'loss':loss.item(),'accuracy':test(model,X_train,y_train)*100,'val_accuracy':test(model,X_test,y_test)*100,'pred':torch.argmax(preds[index]),'real':torch.argmax(y_batch[index])}) wandb.finish() import matplotlib.pyplot as plt import pandas as pd df = pd.Series(loss_logs) df.plot.line(figsize=(12,6)) test(model,X_test,y_test) test(model,X_train,y_train) preds for real,pred in zip(y_batch,preds): print(real) print(torch.argmax(pred)) print('\n') ```
github_jupyter
# Hats Instance Specific Eval instance specific hats ``` import numpy as np import os import fnmatch import pandas as pd import sklearn.metrics as sm import scipy.stats as ss import matplotlib.pyplot as plt import dense_correspondence_manipulation.utils.utils as utils utils.add_dense_correspondence_to_python_path() from dense_correspondence.evaluation.evaluation import DenseCorrespondenceEvaluationPlotter as DCEP folder_name = "hats" path_to_nets = os.path.join("/home/manuelli/code/data_volume/pdc/trained_models", folder_name) all_nets = sorted(os.listdir(path_to_nets)) nets_to_plot = [] for net in all_nets: if "specific" in net and "2.000" in net and not "half" in net: nets_to_plot.append(os.path.join(folder_name,net)) # nets_list = [] # nets_list.append("caterpillar_dont_scale_hard_negatives_e3_3d") # nets_list.append("caterpillar_scale_hard_negatives_e0_3d") # for net in nets_list: # nets_to_plot.append(os.path.join("l2_questions/",net)) # print nets_to_plot print nets_to_plot # nets_to_plot = ["starbot_1_train_3"] ``` # Training ``` p = DCEP() dc_source_dir = utils.getDenseCorrespondenceSourceDir() network_name = nets_to_plot[0] path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/train/data.csv") fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, save=False) for network_name in nets_to_plot[1:]: path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/train/data.csv") fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, previous_fig_axes=fig_axes, save=False) _, axes = fig_axes # axes[0].set_title("Training Set") plt.show() ``` # Test ``` p = DCEP() dc_source_dir = utils.getDenseCorrespondenceSourceDir() network_name = nets_to_plot[0] path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/test/data.csv") fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, save=False) for network_name in nets_to_plot[1:]: path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/test/data.csv") fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, previous_fig_axes=fig_axes, save=False) _, axes = fig_axes # axes[0].set_title("Test Set") plt.show() ``` ## Cross Scene Single Object ``` # p = DCEP() # dc_source_dir = utils.getDenseCorrespondenceSourceDir() # network_name = nets_to_plot[0] # path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/cross_scene/data.csv") # fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, save=False) # for network_name in nets_to_plot[1:]: # path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis/cross_scene/data.csv") # fig_axes = DCEP.run_on_single_dataframe(path_to_csv, label=network_name, previous_fig_axes=fig_axes, save=False) # _, axes = fig_axes # # axes[0].set_title("Cross Scene Set") # plt.show() ``` # Separating Distinct Objects ``` p = DCEP() dc_source_dir = utils.getDenseCorrespondenceSourceDir() network_name = nets_to_plot[0] path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis", 'across_object', "data.csv") fig_axes = DCEP.run_on_single_dataframe_across_objects(path_to_csv, label=network_name, save=False) for network_name in nets_to_plot[1:]: path_to_csv = os.path.join(dc_source_dir, "data_volume", "pdc", "trained_models", network_name, "analysis", 'across_object', "data.csv") fig_axes = DCEP.run_on_single_dataframe_across_objects(path_to_csv, label=network_name, previous_fig_axes=fig_axes, save=False) _, axes = fig_axes # axes[0].set_title("Across Object") plt.show() ```
github_jupyter
# Ungraded Lab: Fully Convolutional Neural Networks for Image Segmentation This notebook illustrates how to build a Fully Convolutional Neural Network for semantic image segmentation. You will train the model on a [custom dataset](https://drive.google.com/file/d/0B0d9ZiqAgFkiOHR1NTJhWVJMNEU/view?usp=sharing) prepared by [divamgupta](https://github.com/divamgupta/image-segmentation-keras). This contains video frames from a moving vehicle and is a subsample of the [CamVid](http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/) dataset. You will be using a pretrained VGG-16 network for the feature extraction path, then followed by an FCN-8 network for upsampling and generating the predictions. The output will be a label map (i.e. segmentation mask) with predictions for 12 classes. Let's begin! ## Imports ``` import os import zipfile import PIL.Image, PIL.ImageFont, PIL.ImageDraw import numpy as np try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf from matplotlib import pyplot as plt import tensorflow_datasets as tfds import seaborn as sns print("Tensorflow version " + tf.__version__) ``` ## Download the Dataset We hosted the dataset in a Google bucket so you will need to download it first and unzip to a local directory. ``` # download the dataset (zipped file) !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/fcnn-dataset.zip \ -O /tmp/fcnn-dataset.zip # extract the downloaded dataset to a local directory: /tmp/fcnn local_zip = '/tmp/fcnn-dataset.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/fcnn') zip_ref.close() ``` The dataset you just downloaded contains folders for images and annotations. The *images* contain the video frames while the *annotations* contain the pixel-wise label maps. Each label map has the shape `(height, width , 1)` with each point in this space denoting the corresponding pixel's class. Classes are in the range `[0, 11]` (i.e. 12 classes) and the pixel labels correspond to these classes: | Value | Class Name | | -------| -------------| | 0 | sky | | 1 | building | | 2 | column/pole | | 3 | road | | 4 | side walk | | 5 | vegetation | | 6 | traffic light | | 7 | fence | | 8 | vehicle | | 9 | pedestrian | | 10 | byciclist | | 11 | void | For example, if a pixel is part of a road, then that point will be labeled `3` in the label map. Run the cell below to create a list containing the class names: - Note: bicyclist is mispelled as 'byciclist' in the dataset. We won't handle data cleaning in this example, but you can inspect and clean the data if you want to use this as a starting point for a personal project. ``` # pixel labels in the video frames class_names = ['sky', 'building','column/pole', 'road', 'side walk', 'vegetation', 'traffic light', 'fence', 'vehicle', 'pedestrian', 'byciclist', 'void'] ``` ## Load and Prepare the Dataset Next, you will load and prepare the train and validation sets for training. There are some preprocessing steps needed before the data is fed to the model. These include: * resizing the height and width of the input images and label maps (224 x 224px by default) * normalizing the input images' pixel values to fall in the range `[-1, 1]` * reshaping the label maps from `(height, width, 1)` to `(height, width, 12)` with each slice along the third axis having `1` if it belongs to the class corresponding to that slice's index else `0`. For example, if a pixel is part of a road, then using the table above, that point at slice #3 will be labeled `1` and it will be `0` in all other slices. To illustrate using simple arrays: ``` # if we have a label map with 3 classes... n_classes = 3 # and this is the original annotation... orig_anno = [0 1 2] # then the reshaped annotation will have 3 slices and its contents will look like this: reshaped_anno = [1 0 0][0 1 0][0 0 1] ``` The following function will do the preprocessing steps mentioned above. ``` def map_filename_to_image_and_mask(t_filename, a_filename, height=224, width=224): ''' Preprocesses the dataset by: * resizing the input image and label maps * normalizing the input image pixels * reshaping the label maps from (height, width, 1) to (height, width, 12) Args: t_filename (string) -- path to the raw input image a_filename (string) -- path to the raw annotation (label map) file height (int) -- height in pixels to resize to width (int) -- width in pixels to resize to Returns: image (tensor) -- preprocessed image annotation (tensor) -- preprocessed annotation ''' # Convert image and mask files to tensors img_raw = tf.io.read_file(t_filename) anno_raw = tf.io.read_file(a_filename) image = tf.image.decode_jpeg(img_raw) annotation = tf.image.decode_jpeg(anno_raw) # Resize image and segmentation mask image = tf.image.resize(image, (height, width,)) annotation = tf.image.resize(annotation, (height, width,)) image = tf.reshape(image, (height, width, 3,)) annotation = tf.cast(annotation, dtype=tf.int32) annotation = tf.reshape(annotation, (height, width, 1,)) stack_list = [] # Reshape segmentation masks for c in range(len(class_names)): mask = tf.equal(annotation[:,:,0], tf.constant(c)) stack_list.append(tf.cast(mask, dtype=tf.int32)) annotation = tf.stack(stack_list, axis=2) # Normalize pixels in the input image image = image/127.5 image -= 1 return image, annotation ``` The dataset also already has separate folders for train and test sets. As described earlier, these sets will have two folders: one corresponding to the images, and the other containing the annotations. ``` # show folders inside the dataset you downloaded !ls /tmp/fcnn/dataset1 ``` You will use the following functions to create the tensorflow datasets from the images in these folders. Notice that before creating the batches in the `get_training_dataset()` and `get_validation_set()`, the images are first preprocessed using the `map_filename_to_image_and_mask()` function you defined earlier. ``` # Utilities for preparing the datasets BATCH_SIZE = 64 def get_dataset_slice_paths(image_dir, label_map_dir): ''' generates the lists of image and label map paths Args: image_dir (string) -- path to the input images directory label_map_dir (string) -- path to the label map directory Returns: image_paths (list of strings) -- paths to each image file label_map_paths (list of strings) -- paths to each label map ''' image_file_list = os.listdir(image_dir) label_map_file_list = os.listdir(label_map_dir) image_paths = [os.path.join(image_dir, fname) for fname in image_file_list] label_map_paths = [os.path.join(label_map_dir, fname) for fname in label_map_file_list] return image_paths, label_map_paths def get_training_dataset(image_paths, label_map_paths): ''' Prepares shuffled batches of the training set. Args: image_paths (list of strings) -- paths to each image file in the train set label_map_paths (list of strings) -- paths to each label map in the train set Returns: tf Dataset containing the preprocessed train set ''' training_dataset = tf.data.Dataset.from_tensor_slices((image_paths, label_map_paths)) training_dataset = training_dataset.map(map_filename_to_image_and_mask) training_dataset = training_dataset.shuffle(100, reshuffle_each_iteration=True) training_dataset = training_dataset.batch(BATCH_SIZE) training_dataset = training_dataset.repeat() training_dataset = training_dataset.prefetch(-1) return training_dataset def get_validation_dataset(image_paths, label_map_paths): ''' Prepares batches of the validation set. Args: image_paths (list of strings) -- paths to each image file in the val set label_map_paths (list of strings) -- paths to each label map in the val set Returns: tf Dataset containing the preprocessed validation set ''' validation_dataset = tf.data.Dataset.from_tensor_slices((image_paths, label_map_paths)) validation_dataset = validation_dataset.map(map_filename_to_image_and_mask) validation_dataset = validation_dataset.batch(BATCH_SIZE) validation_dataset = validation_dataset.repeat() return validation_dataset ``` You can now generate the training and validation sets by running the cell below. ``` # get the paths to the images training_image_paths, training_label_map_paths = get_dataset_slice_paths('/tmp/fcnn/dataset1/images_prepped_train/','/tmp/fcnn/dataset1/annotations_prepped_train/') validation_image_paths, validation_label_map_paths = get_dataset_slice_paths('/tmp/fcnn/dataset1/images_prepped_test/','/tmp/fcnn/dataset1/annotations_prepped_test/') # generate the train and val sets training_dataset = get_training_dataset(training_image_paths, training_label_map_paths) validation_dataset = get_validation_dataset(validation_image_paths, validation_label_map_paths) ``` ## Let's Take a Look at the Dataset You will also need utilities to help visualize the dataset and the model predictions later. First, you need to assign a color mapping to the classes in the label maps. Since our dataset has 12 classes, you need to have a list of 12 colors. We can use the [color_palette()](https://seaborn.pydata.org/generated/seaborn.color_palette.html) from Seaborn to generate this. ``` # generate a list that contains one color for each class colors = sns.color_palette(None, len(class_names)) # print class name - normalized RGB tuple pairs # the tuple values will be multiplied by 255 in the helper functions later # to convert to the (0,0,0) to (255,255,255) RGB values you might be familiar with for class_name, color in zip(class_names, colors): print(f'{class_name} -- {color}') # Visualization Utilities def fuse_with_pil(images): ''' Creates a blank image and pastes input images Args: images (list of numpy arrays) - numpy array representations of the images to paste Returns: PIL Image object containing the images ''' widths = (image.shape[1] for image in images) heights = (image.shape[0] for image in images) total_width = sum(widths) max_height = max(heights) new_im = PIL.Image.new('RGB', (total_width, max_height)) x_offset = 0 for im in images: pil_image = PIL.Image.fromarray(np.uint8(im)) new_im.paste(pil_image, (x_offset,0)) x_offset += im.shape[1] return new_im def give_color_to_annotation(annotation): ''' Converts a 2-D annotation to a numpy array with shape (height, width, 3) where the third axis represents the color channel. The label values are multiplied by 255 and placed in this axis to give color to the annotation Args: annotation (numpy array) - label map array Returns: the annotation array with an additional color channel/axis ''' seg_img = np.zeros( (annotation.shape[0],annotation.shape[1], 3) ).astype('float') for c in range(12): segc = (annotation == c) seg_img[:,:,0] += segc*( colors[c][0] * 255.0) seg_img[:,:,1] += segc*( colors[c][1] * 255.0) seg_img[:,:,2] += segc*( colors[c][2] * 255.0) return seg_img def show_predictions(image, labelmaps, titles, iou_list, dice_score_list): ''' Displays the images with the ground truth and predicted label maps Args: image (numpy array) -- the input image labelmaps (list of arrays) -- contains the predicted and ground truth label maps titles (list of strings) -- display headings for the images to be displayed iou_list (list of floats) -- the IOU values for each class dice_score_list (list of floats) -- the Dice Score for each vlass ''' true_img = give_color_to_annotation(labelmaps[1]) pred_img = give_color_to_annotation(labelmaps[0]) image = image + 1 image = image * 127.5 images = np.uint8([image, pred_img, true_img]) metrics_by_id = [(idx, iou, dice_score) for idx, (iou, dice_score) in enumerate(zip(iou_list, dice_score_list)) if iou > 0.0] metrics_by_id.sort(key=lambda tup: tup[1], reverse=True) # sorts in place display_string_list = ["{}: IOU: {} Dice Score: {}".format(class_names[idx], iou, dice_score) for idx, iou, dice_score in metrics_by_id] display_string = "\n\n".join(display_string_list) plt.figure(figsize=(15, 4)) for idx, im in enumerate(images): plt.subplot(1, 3, idx+1) if idx == 1: plt.xlabel(display_string) plt.xticks([]) plt.yticks([]) plt.title(titles[idx], fontsize=12) plt.imshow(im) def show_annotation_and_image(image, annotation): ''' Displays the image and its annotation side by side Args: image (numpy array) -- the input image annotation (numpy array) -- the label map ''' new_ann = np.argmax(annotation, axis=2) seg_img = give_color_to_annotation(new_ann) image = image + 1 image = image * 127.5 image = np.uint8(image) images = [image, seg_img] images = [image, seg_img] fused_img = fuse_with_pil(images) plt.imshow(fused_img) def list_show_annotation(dataset): ''' Displays images and its annotations side by side Args: dataset (tf Dataset) - batch of images and annotations ''' ds = dataset.unbatch() ds = ds.shuffle(buffer_size=100) plt.figure(figsize=(25, 15)) plt.title("Images And Annotations") plt.subplots_adjust(bottom=0.1, top=0.9, hspace=0.05) # we set the number of image-annotation pairs to 9 # feel free to make this a function parameter if you want for idx, (image, annotation) in enumerate(ds.take(9)): plt.subplot(3, 3, idx + 1) plt.yticks([]) plt.xticks([]) show_annotation_and_image(image.numpy(), annotation.numpy()) ``` Please run the cells below to see sample images from the train and validation sets. You will see the image and the label maps side side by side. ``` list_show_annotation(training_dataset) list_show_annotation(validation_dataset) ``` ## Define the Model You will now build the model and prepare it for training. AS mentioned earlier, this will use a VGG-16 network for the encoder and FCN-8 for the decoder. This is the diagram as shown in class: <img src='https://drive.google.com/uc?export=view&id=1lrqB4YegV8jXWNfyYAaeuFlwXIc54aRP' alt='fcn-8'> For this exercise, you will notice a slight difference from the lecture because the dataset images are 224x224 instead of 32x32. You'll see how this is handled in the next cells as you build the encoder. ### Define Pooling Block of VGG As you saw in Course 1 of this specialization, VGG networks have repeating blocks so to make the code neat, it's best to create a function to encapsulate this process. Each block has convolutional layers followed by a max pooling layer which downsamples the image. ``` def block(x, n_convs, filters, kernel_size, activation, pool_size, pool_stride, block_name): ''' Defines a block in the VGG network. Args: x (tensor) -- input image n_convs (int) -- number of convolution layers to append filters (int) -- number of filters for the convolution layers activation (string or object) -- activation to use in the convolution pool_size (int) -- size of the pooling layer pool_stride (int) -- stride of the pooling layer block_name (string) -- name of the block Returns: tensor containing the max-pooled output of the convolutions ''' for i in range(n_convs): x = tf.keras.layers.Conv2D(filters=filters, kernel_size=kernel_size, activation=activation, padding='same', name="{}_conv{}".format(block_name, i + 1))(x) x = tf.keras.layers.MaxPooling2D(pool_size=pool_size, strides=pool_stride, name="{}_pool{}".format(block_name, i+1 ))(x) return x ``` ### Download VGG weights First, please run the cell below to get pre-trained weights for VGG-16. You will load this in the next section when you build the encoder network. ``` # download the weights !wget https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5 # assign to a variable vgg_weights_path = "vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5" ``` ### Define VGG-16 You can build the encoder as shown below. * You will create 5 blocks with increasing number of filters at each stage. * The number of convolutions, filters, kernel size, activation, pool size and pool stride will remain constant. * You will load the pretrained weights after creating the VGG 16 network. * Additional convolution layers will be appended to extract more features. * The output will contain the output of the last layer and the previous four convolution blocks. ``` def VGG_16(image_input): ''' This function defines the VGG encoder. Args: image_input (tensor) - batch of images Returns: tuple of tensors - output of all encoder blocks plus the final convolution layer ''' # create 5 blocks with increasing filters at each stage. # you will save the output of each block (i.e. p1, p2, p3, p4, p5). "p" stands for the pooling layer. x = block(image_input,n_convs=2, filters=64, kernel_size=(3,3), activation='relu',pool_size=(2,2), pool_stride=(2,2), block_name='block1') p1= x x = block(x,n_convs=2, filters=128, kernel_size=(3,3), activation='relu',pool_size=(2,2), pool_stride=(2,2), block_name='block2') p2 = x x = block(x,n_convs=3, filters=256, kernel_size=(3,3), activation='relu',pool_size=(2,2), pool_stride=(2,2), block_name='block3') p3 = x x = block(x,n_convs=3, filters=512, kernel_size=(3,3), activation='relu',pool_size=(2,2), pool_stride=(2,2), block_name='block4') p4 = x x = block(x,n_convs=3, filters=512, kernel_size=(3,3), activation='relu',pool_size=(2,2), pool_stride=(2,2), block_name='block5') p5 = x # create the vgg model vgg = tf.keras.Model(image_input , p5) # load the pretrained weights you downloaded earlier vgg.load_weights(vgg_weights_path) # number of filters for the output convolutional layers n = 4096 # our input images are 224x224 pixels so they will be downsampled to 7x7 after the pooling layers above. # we can extract more features by chaining two more convolution layers. c6 = tf.keras.layers.Conv2D( n , ( 7 , 7 ) , activation='relu' , padding='same', name="conv6")(p5) c7 = tf.keras.layers.Conv2D( n , ( 1 , 1 ) , activation='relu' , padding='same', name="conv7")(c6) # return the outputs at each stage. you will only need two of these in this particular exercise # but we included it all in case you want to experiment with other types of decoders. return (p1, p2, p3, p4, c7) ``` ### Define FCN 8 Decoder Next, you will build the decoder using deconvolution layers. Please refer to the diagram for FCN-8 at the start of this section to visualize what the code below is doing. It will involve two summations before upsampling to the original image size and generating the predicted mask. ``` def fcn8_decoder(convs, n_classes): ''' Defines the FCN 8 decoder. Args: convs (tuple of tensors) - output of the encoder network n_classes (int) - number of classes Returns: tensor with shape (height, width, n_classes) containing class probabilities ''' # unpack the output of the encoder f1, f2, f3, f4, f5 = convs # upsample the output of the encoder then crop extra pixels that were introduced o = tf.keras.layers.Conv2DTranspose(n_classes , kernel_size=(4,4) , strides=(2,2) , use_bias=False )(f5) o = tf.keras.layers.Cropping2D(cropping=(1,1))(o) # load the pool 4 prediction and do a 1x1 convolution to reshape it to the same shape of `o` above o2 = f4 o2 = ( tf.keras.layers.Conv2D(n_classes , ( 1 , 1 ) , activation='relu' , padding='same'))(o2) # add the results of the upsampling and pool 4 prediction o = tf.keras.layers.Add()([o, o2]) # upsample the resulting tensor of the operation you just did o = (tf.keras.layers.Conv2DTranspose( n_classes , kernel_size=(4,4) , strides=(2,2) , use_bias=False ))(o) o = tf.keras.layers.Cropping2D(cropping=(1, 1))(o) # load the pool 3 prediction and do a 1x1 convolution to reshape it to the same shape of `o` above o2 = f3 o2 = ( tf.keras.layers.Conv2D(n_classes , ( 1 , 1 ) , activation='relu' , padding='same'))(o2) # add the results of the upsampling and pool 3 prediction o = tf.keras.layers.Add()([o, o2]) # upsample up to the size of the original image o = tf.keras.layers.Conv2DTranspose(n_classes , kernel_size=(8,8) , strides=(8,8) , use_bias=False )(o) # append a softmax to get the class probabilities o = (tf.keras.layers.Activation('softmax'))(o) return o ``` ### Define Final Model You can now build the final model by connecting the encoder and decoder blocks. ``` def segmentation_model(): ''' Defines the final segmentation model by chaining together the encoder and decoder. Returns: keras Model that connects the encoder and decoder networks of the segmentation model ''' inputs = tf.keras.layers.Input(shape=(224,224,3,)) convs = VGG_16(image_input=inputs) outputs = fcn8_decoder(convs, 12) model = tf.keras.Model(inputs=inputs, outputs=outputs) return model # instantiate the model and see how it looks model = segmentation_model() model.summary() ``` ### Compile the Model Next, the model will be configured for training. You will need to specify the loss, optimizer and metrics. You will use `categorical_crossentropy` as the loss function since the label map is transformed to one hot encoded vectors for each pixel in the image (i.e. `1` in one slice and `0` for other slices as described earlier). ``` sgd = tf.keras.optimizers.SGD(lr=1E-2, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) ``` ## Train the Model The model can now be trained. This will take around 30 minutes to run and you will reach around 85% accuracy for both train and val sets. ``` # number of training images train_count = 367 # number of validation images validation_count = 101 EPOCHS = 170 steps_per_epoch = train_count//BATCH_SIZE validation_steps = validation_count//BATCH_SIZE history = model.fit(training_dataset, steps_per_epoch=steps_per_epoch, validation_data=validation_dataset, validation_steps=validation_steps, epochs=EPOCHS) ``` ## Evaluate the Model After training, you will want to see how your model is doing on a test set. For segmentation models, you can use the intersection-over-union and the dice score as metrics to evaluate your model. You'll see how it is implemented in this section. ``` def get_images_and_segments_test_arrays(): ''' Gets a subsample of the val set as your test set Returns: Test set containing ground truth images and label maps ''' y_true_segments = [] y_true_images = [] test_count = 64 ds = validation_dataset.unbatch() ds = ds.batch(101) for image, annotation in ds.take(1): y_true_images = image y_true_segments = annotation y_true_segments = y_true_segments[:test_count, : ,: , :] y_true_segments = np.argmax(y_true_segments, axis=3) return y_true_images, y_true_segments # load the ground truth images and segmentation masks y_true_images, y_true_segments = get_images_and_segments_test_arrays() ``` ### Make Predictions You can get output segmentation masks by using the `predict()` method. As you may recall, the output of our segmentation model has the shape `(height, width, 12)` where `12` is the number of classes. Each pixel value in those 12 slices indicates the probability of that pixel belonging to that particular class. If you want to create the predicted label map, then you can get the `argmax()` of that axis. This is shown in the following cell. ``` # get the model prediction results = model.predict(validation_dataset, steps=validation_steps) # for each pixel, get the slice number which has the highest probability results = np.argmax(results, axis=3) ``` ### Compute Metrics The function below generates the IOU and dice score of the prediction and ground truth masks. From the lectures, it is given that: $$IOU = \frac{area\_of\_overlap}{area\_of\_union}$$ <br> $$Dice Score = 2 * \frac{area\_of\_overlap}{combined\_area}$$ The code below does that for you. A small smoothening factor is introduced in the denominators to prevent possible division by zero. ``` def compute_metrics(y_true, y_pred): ''' Computes IOU and Dice Score. Args: y_true (tensor) - ground truth label map y_pred (tensor) - predicted label map ''' class_wise_iou = [] class_wise_dice_score = [] smoothening_factor = 0.00001 for i in range(12): intersection = np.sum((y_pred == i) * (y_true == i)) y_true_area = np.sum((y_true == i)) y_pred_area = np.sum((y_pred == i)) combined_area = y_true_area + y_pred_area iou = (intersection + smoothening_factor) / (combined_area - intersection + smoothening_factor) class_wise_iou.append(iou) dice_score = 2 * ((intersection + smoothening_factor) / (combined_area + smoothening_factor)) class_wise_dice_score.append(dice_score) return class_wise_iou, class_wise_dice_score ``` ### Show Predictions and Metrics You can now see the predicted segmentation masks side by side with the ground truth. The metrics are also overlayed so you can evaluate how your model is doing. ``` # input a number from 0 to 63 to pick an image from the test set integer_slider = 0 # compute metrics iou, dice_score = compute_metrics(y_true_segments[integer_slider], results[integer_slider]) # visualize the output and metrics show_predictions(y_true_images[integer_slider], [results[integer_slider], y_true_segments[integer_slider]], ["Image", "Predicted Mask", "True Mask"], iou, dice_score) ``` ### Display Class Wise Metrics You can also compute the class-wise metrics so you can see how your model performs across all images in the test set. ``` # compute class-wise metrics cls_wise_iou, cls_wise_dice_score = compute_metrics(y_true_segments, results) # print IOU for each class for idx, iou in enumerate(cls_wise_iou): spaces = ' ' * (13-len(class_names[idx]) + 2) print("{}{}{} ".format(class_names[idx], spaces, iou)) # print the dice score for each class for idx, dice_score in enumerate(cls_wise_dice_score): spaces = ' ' * (13-len(class_names[idx]) + 2) print("{}{}{} ".format(class_names[idx], spaces, dice_score)) ``` **That's all for this lab! In the next section, you will work on another architecture for building a segmentation model: the UNET.**
github_jupyter
# Multiline TRL This example demonstrates how to use `skrf`'s NIST-style Multiline calibration (`NISTMultilineTRL`). First a [simple application](#Simple-Multiline-TRL) is presented, followed by a [full simulation](#Compare-calibration's-with-different-combinations-of-lines) to demonstrate the improvements in calibration accuracy vs the number of lines. All data is used in the demonstration is generated by skrf, and the code for this is given [at the end of the example](#Simulation-to-Generate-Data). ## Simple Multiline TRL ### Setup ``` %matplotlib inline import skrf import numpy as np import matplotlib.pyplot as plt skrf.stylely() ``` ### Load data into skrf ``` #load all measurement data into a dictionary data = skrf.read_all_networks('multiline_trl_data/') # pull out measurements by name into an ordered list measured_names = ['thru','reflect','linep3mm','line2p3mm','line10mm'] measured = [data[k] for k in measured_names] # switch terms gamma_f,gamma_r = data['gamma_f'],data['gamma_r'] # DUT dut_meas= data['DUT'] ``` ### Simple Multiline TRL ``` # define the line lengths in meters (including thru) l = [0, 0.3e-3, 2.3e-3, 10e-3] #Do the calibration cal = skrf.NISTMultilineTRL( measured = measured, #Measured standards Grefls = [-1], #Reflection coefficient of the reflect, -1 for short l = l, #Lengths of the lines er_est = 7, #Estimate of transmission line effective permittivity switch_terms = (gamma_f, gamma_r) #Switch terms ) #Correct the DUT using the above calibration corrected = cal.apply_cal(dut_meas) corrected.plot_s_db() ``` ## Compare calibration's with different combinations of lines Here we loop through different line combinations to demonstrate the difference in calibration accuracy. ``` # Run NIST Multiline TRL calibation with different combinations of lines #Put through and reflect to their own list ... mtr = measured[:2] #and lines on their own mlines = measured[2:] # define the line lengths in meters line_len = [0.3e-3, 2.3e-3, 10e-3] cals = [] duts = [] line_combinations = [ [0], [1], [0,1,2]] for used_lines in line_combinations: m = mtr + [mlines[i] for i in used_lines] #Add thru length to list of line lengths l = [0] + [line_len[i] for i in used_lines] #Do the calibration cal = skrf.NISTMultilineTRL( measured = m, #Measured standards Grefls = [-1], #Reflection coefficient of the reflect, -1 for short l = l, #Lengths of the lines er_est = 7, #Estimate of transmission line effective permittivity switch_terms = (gamma_f, gamma_r) #Switch terms ) #Correct the DUT using the above calibration corrected = cal.apply_cal(dut_meas) corrected.name = 'DUT, lines {}'.format(used_lines) duts.append(corrected) cals.append(cal) ``` ## Results and discussion ### Transmission of corrected DUT Plot the corrected DUT with different amount of lines ``` plt.figure() plt.title('DUT S21') for dut in duts: dut.plot_s_db(m=1, n=0) ``` ### S11 of corrected DUT with different amount of lines S11 shows bigger changes. * With one line low frequencies are very noisy * With only the medium length line calibration is very inaccurate at frequencies where phase of the line is multiple of 180 degrees * With three lines calibration accuracy is excellent everywhere ``` plt.figure() plt.title('DUT S11') for dut in duts: dut.plot_s_db(m=0, n=0) ``` ### Normalized standard deviation of different calibrations This measures the accuracy of the calibration. Lower number means less noise. * TRL calibration with one 90 degrees long line has normalized standard deviation of 1. * With multiple lines normalized standard deviations less than one is possible. ``` f_ghz = dut.frequency.f_scaled plt.figure() plt.title('Calibration normalized standard deviation') for e, cal in enumerate(cals): plt.plot(f_ghz, cal.nstd, label='Lines: {}'.format(line_combinations[e])) plt.ylim([0,30]) plt.legend(loc='upper right') dut.frequency.labelXAxis() ``` ### Calculate effective permittivity of the transmission lines used in the calibration Is there no existing way to get the real er_eff? Anyway, this is how it can be calculated from the propagation constant. CPW line propagation constant can be approximated as average of substrate and air permittivities, but this is not completely true at low frequencies when the line is lossy ``` #define calibration standard media freq = dut.frequency cpw = skrf.media.CPW(freq, z0=50, w=40e-6, s=25e-6, ep_r=12.9, t=5e-6, rho=2e-8) #Get the cal with all the lines cal = cals[-1] #Plot the solved effective permittivity of the transmission lines c = 299792458.0 real_er_eff = -(cpw.gamma/(2*np.pi*f_ghz*1e9/c))**2 plt.figure() plt.title('CPW effective permittivity') plt.plot(f_ghz, cal.er_eff.real, label='Solved er_eff') plt.plot(f_ghz, real_er_eff.real, label='Actual er_eff') plt.legend(loc='upper right') ``` Depending on the noise there might be some wrong choices for some lines during the propagation constant determination that cause small spikes in the solved effective permittivity. In general they don't matter much, but incorrectly determined propagation constant affects the weighting of the lines and accuracy of the calibration at that frequency. With many lines though even if one line has incorrectly determined propagation constant the effect to the total calibration will be small. Plot the phase of the solved reflection coefficient ### Is reflect correct? Since we know the ideals in this simulation we can re-define them here, and compare the determined reflect to the actual reflect. (see below for simulation details) ``` lines = [cpw.line(l, 'm') for l in line_len] short = cpw.delay_short(10e-6, 'm') actuals = [ cpw.thru(), skrf.two_port_reflect(short, short), ] actuals.extend(lines) plt.figure() plt.title('Solved and actual reflection coefficient of the reflect standard') cal.apply_cal(measured[1]).plot_s_deg(n=0, m=0) actuals[1].plot_s_deg(n=0, m=0) plt.show(block=True) ``` ## Simulation to Generate Data Here is how we made the data used above. ### Create frequency and Media ``` freq = skrf.F(1,100,401) #CPW media used for DUT and the calibration standards cpw = skrf.media.CPW(freq, z0=50, w=40e-6, s=25e-6, ep_r=12.9, t=5e-6, rho=2e-8) #1.0 mm coaxial media for calibration error boxes coax1mm = skrf.media.Coaxial(freq, z0=50, Dint=0.44e-3, Dout=1.0e-3, sigma=1e8) f_ghz = cpw.frequency.f*1e-9 ``` ### Make realistic looking error networks. Propagation constant determination is iterative and doesn't work as well when the error networks are randomly generated ``` X = coax1mm.line(1, 'm', z0=58, name='X', embed=True) Y = coax1mm.line(1.1, 'm', z0=40, name='Y', embed=True) plt.figure() plt.title('Error networks') X.plot_s_db() Y.plot_s_db() #Realistic looking switch terms gamma_f = coax1mm.delay_load(0.2, 21e-3, 'm', z0=60, embed=True) gamma_r = coax1mm.delay_load(0.25, 16e-3, 'm', z0=56, embed=True) plt.figure() plt.title('Switch terms') gamma_f.plot_s_db() gamma_r.plot_s_db() ``` ### Generate Ficticous measurements ``` #Lengths of the lines used in the calibration, units are in meters line_len = [0.3e-3, 2.3e-3, 10e-3] lines = [cpw.line(l, 'm') for l in line_len] #Attenuator with mismatched feed lines dut_feed = cpw.line(1.5e-3, 'm', z0=55, embed=True) dut = dut_feed**cpw.attenuator(-10)**dut_feed #Through and non-ideal short #Real reflection coefficient is solved during the calibration short = cpw.delay_short(10e-6, 'm') actuals = [ cpw.thru(), skrf.two_port_reflect(short, short), ] actuals.extend(lines) #Measured measured = [X**k**Y for k in actuals] #Switch termination measured = [skrf.terminate(m, gamma_f, gamma_r) for m in measured] #Add little noise to the measurements for m in measured: m.add_noise_polar(0.0005, 0.005) names = ['thru','reflect','linep3mm','line2p3mm','line10mm'] for k,name in enumerate(names): measured[k].name=name #Noiseless DUT so that all the noise will be from the calibration dut_meas = skrf.terminate(X**dut**Y, gamma_f, gamma_r) dut_meas.name = 'DUT' #Put through and reflect to their own list ... mtr = measured[:2] #and lines on their own mlines = measured[2:] # write data to disk write_data = False if write_data: [k.write_touchstone(dir='multiline_trl_data/') for k in measured] gamma_f.write_touchstone('multiline_trl_data/gamma_f.s1p') gamma_r.write_touchstone('multiline_trl_data/gamma_r.s1p') dut_meas.write_touchstone(dir='multiline_trl_data/') ```
github_jupyter
# I. Introduction In this exercise, you'll implement several local search algorithms and test them on the [Traveling Salesman Problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem) (TSP) between a few dozen US state capitals. Briefly, the TSP is an optimization problem that seeks to find the shortest path passing through every city exactly once. In our example the TSP path is defined to start and end in the same city (so the path is a closed loop). Local search algorithms are important in artificial intelligence because many tasks can be represented as [optimization problems](https://en.wikipedia.org/wiki/Optimization_problem). For example, [here](https://blog.openai.com/evolution-strategies/) researches used evolutionary strategies to perform gradient-free training of deep neural networks (which allows non-differentiable activation and loss functions), and [here](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/BeamSearchDecoder) is an example of using beam search for tasks like optimal sentence translation in natural language processing. The TSP problem itself is interesting and has been studied extensively because it can be applied to a variety of useful real-world problems. It has been used in logistics & operations research for vehicle routing and order-picking in warehouses, product development and design like computer wiring & printed circuit board masking, and various scheduling problems, among others. ![Simulated Annealing](SA_animation.gif) Image Source: [Simulated Annealing - By Kingpin13 (Own work) [CC0], via Wikimedia Commons (Attribution not required)](https://commons.wikimedia.org/wiki/File:Hill_Climbing_with_Simulated_Annealing.gif) ## Overview Search for `#TODO` tags to quickly find the functions you are required to implement. Descriptions and pseudocode for each function are provided in the notebook, along with links to external readings. 0. Complete the `TravelingSalesmanProblem` class by implementing the `successors()`, `get_successor()`, and `__get_value()` methods 0. Complete the `HillClimbingSolver` class 0. Complete the `LocalBeamSolver` class 0. Complete the `SimulatedAnnealingSolver` class 0. Complete the `LAHCSolver` class ``` import json import math # contains sqrt, exp, pow, etc. import random import time from collections import deque from helper import * import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline ``` ## I. Representing the Problem The first step is to build a representation of the problem domain. The choice of representation can have a significant impact on the performance of the various optimization algorithms. Since the TSP deals with a closed loop that visits each city in a list once, we will represent each city by a tuple containing the city name and its position specified by an (x,y) location on a grid: (<NAME>, (x, y)). The _state_ will then consist of an ordered sequence of the cities in the path. In other words, the path is defined as the sequence generated by traveling from each city in the list to the next in order. For example, the path (("City1", (x1, y1)), ("City2", (x2, y2)), ("City3", (x3, y3))) defines a circuit from City1 -> City2 -> City3 -> City1. ``` def dist(xy1, xy2): """ Calculate the distance between two points. You may choose to use Euclidean distance, Manhattan distance, or some other metric """ # TODO: Implement this function! raise NotImplementedError class TravelingSalesmanProblem: """ Representation of a traveling salesman optimization problem. An instance of this class represents a complete circuit of the cities in the `path` attribute. Parameters ---------- cities : iterable An iterable sequence of cities; each element of the sequence must be a tuple (name, (x, y)) containing the name and coordinates of a city on a rectangular grid. e.g., ("Atlanta", (585.6, 376.8)) shuffle : bool If True, then the order of the input cities (and therefore the starting city) is randomized. Attributes ---------- names : sequence An iterable sequence (list by default) containing only the names from the cities in the order they appear in the current TSP path coords : sequence An iterable sequence (list by default) containing only the coordinates from the cities in the order they appear in the current TSP path path : tuple A path between cities as specified by the order of the city tuples in the list. """ def __init__(self, cities, shuffle=False): ##### YOU DO NOT NEED TO MODIFY THIS FUNCTION ##### if shuffle: cities = list(cities) random.shuffle(cities) self.path = tuple(cities) # using a tuple makes the path sequence immutable self.__utility = None # access this attribute through the .utility property def copy(self, shuffle=False): ##### YOU DO NOT NEED TO MODIFY THIS FUNCTION ##### cities = list(self.path) if shuffle: random.shuffle(cities) return TravelingSalesmanProblem(cities) @property def names(self): """Strip and return only the city name from each element of the path list. For example, [("Atlanta", (585.6, 376.8)), ...] -> ["Atlanta", ...] """ ##### YOU DO NOT NEED TO MODIFY THIS FUNCTION ##### names, _ = zip(*self.path) return names @property def coords(self): """ Strip the city name from each element of the path list and return a list of tuples containing only pairs of xy coordinates for the cities. For example, [("Atlanta", (585.6, 376.8)), ...] -> [(585.6, 376.8), ...] """ ##### YOU DO NOT NEED TO MODIFY THIS FUNCTION ##### _, coords = zip(*self.path) return coords @property def utility(self): """ Calculate and cache the total distance of the path in the current state. """ ##### YOU DO NOT NEED TO MODIFY THIS FUNCTION ##### if self.__utility is None: self.__utility = self.__get_value() return self.__utility def successors(self): """ Return a list of states in the neighborhood of the current state. You may define the neighborhood in many different ways; although some will perform better than others. One method that usually performs well for TSP is to generate neighbors of the current path by selecting a starting point and an ending point in the current path and reversing the order of the nodes between those boundaries. For example, if the current list of cities (i.e., the path) is [A, B, C, D] then the neighbors will include [B, A, C, D], [C, B, A, D], and [A, C, B, D]. (The order of successors does not matter.) Returns ------- iterable<Problem> A list of TravelingSalesmanProblem instances initialized with their list of cities set to one of the neighboring permutations of cities in the present state """ # TODO: Implement this function! raise NotImplementedError def get_successor(self): """ Return a random state from the neighborhood of the current state. You may define the neighborhood in many different ways; although some will perform better than others. One method that usually performs well for TSP is to generate neighbors of the current path by selecting a starting point and an ending point in the current path and reversing the order of the nodes between those boundaries. For example, if the current list of cities (i.e., the path) is [A, B, C, D] then the neighbors will include [B, A, C, D], [C, B, A, D], and [A, C, B, D]. (The order of successors does not matter.) Returns ------- list<Problem> A list of TravelingSalesmanProblem instances initialized with their list of cities set to one of the neighboring permutations of cities in the present state """ # TODO: Implement this function! raise NotImplementedError def __get_value(self): """ Calculate the total length of the closed-circuit path of the current state by summing the distance between every pair of cities in the path sequence. For example, if the current path is (A, B, C, D) then the total path length is: dist = DIST(A, B) + DIST(B, C) + DIST(C, D) + DIST(D, A) You may use any distance metric that obeys the triangle inequality (e.g., Manhattan distance or Euclidean distance) for the DIST() function. Since the goal of our optimizers is to maximize the value of the objective function, multiply the total distance by -1 so that short path lengths are larger numbers than long path lengths. Returns ------- float A floating point value with the total cost of the path given by visiting the cities in the order according to the self.cities list Notes ----- (1) Remember to include the edge from the last city back to the first city (2) Remember to multiply the path length by -1 so that short paths have higher value relative to long paths """ # TODO: Implement this function! raise NotImplementedError # Construct an instance of the TravelingSalesmanProblem and test `.__get_value()` test_cities = [('DC', (11, 1)), ('SF', (0, 0)), ('PHX', (2, -3)), ('LA', (0, -4))] tsp = TravelingSalesmanProblem(test_cities) assert round(-tsp.utility, 2) == 28.97, \ "There was a problem with the utility value returned by your TSP class." print("Looks good!") # Test the successors() method successor_paths = set([x.path for x in tsp.successors()]) expected_paths = [ (('SF', (0, 0)), ('DC', (11, 1)), ('PHX', (2, -3)), ('LA', (0, -4))), (('DC', (11, 1)), ('LA', (0, -4)), ('SF', (0, 0)), ('PHX', (2, -3))), (('LA', (0, -4)), ('PHX', (2, -3)), ('DC', (11, 1)), ('SF', (0, 0))) ] assert all(contains(successor_paths, x) for x in expected_paths), \ "It looks like your successors list does not implement the suggested neighborhood function." print("Looks good!") ``` ### Create an instance of the TSP for testing Run the next cell to create an instance of the TSP that will be used to test each of the local search functions by finding a shortest-path circuit through several of the US state capitals. You can increase the `num_cities` parameter (up to 30) to experiment with increasingly larger domains, and set `shuffle=True` to randomize the starting city. Try running the solvers repeatedly -- how stable are the results? ``` # Create the problem instance and plot the initial state num_cities = 10 shuffle = False capitals_tsp = TravelingSalesmanProblem(capitals_list[:num_cities], shuffle=shuffle) starting_city = capitals_tsp.path[0] print("Initial path value: {:.2f}".format(-capitals_tsp.utility)) print(capitals_tsp.path) # The start/end point is indicated with a yellow star show_path(capitals_tsp.coords, starting_city) ``` ## II. Hill Climbing Next, complete the `solve()` method for the `HillClimbingSolver` class below. > The hill-climbing search algorithm is the most basic local search technique. At each step the current node is replaced by the neighbor with the highest value. [AIMA 3rd ed, Chapter 4] ![](pseudocode/hill_climbing.png) Pseudocode for the [hill climbing function](https://github.com/aimacode/aima-pseudocode/blob/master/md/Hill-Climbing.md) from the AIMA textbook. Note that our Problem class is already a "node", so the MAKE-NODE line is not required. ``` class HillClimbingSolver: """ Parameters ---------- epochs : int The upper limit on the number of rounds to perform hill climbing; the algorithm terminates and returns the best observed result when this iteration limit is exceeded. """ def __init__(self, epochs=100): self.epochs = epochs def solve(self, problem): """ Optimize the input problem by applying greedy hill climbing. Parameters ---------- problem : Problem An initialized instance of an optimization problem. The Problem class interface must implement a callable method "successors()" which returns a iterable sequence (i.e., a list or generator) of the states in the neighborhood of the current state, and a property "utility" which returns a fitness score for the state. (See the `TravelingSalesmanProblem` class for more details.) Returns ------- Problem The resulting approximate solution state of the optimization problem Notes ----- (1) DO NOT include the MAKE-NODE line from the AIMA pseudocode """ # TODO: Implement this function! raise NotImplementedError ``` ### Run the Hill Climbing Solver ``` solver = HillClimbingSolver(epochs=100) start_time = time.perf_counter() result = solver.solve(capitals_tsp) stop_time = time.perf_counter() print("solution_time: {:.2f} milliseconds".format((stop_time - start_time) * 1000)) print("Initial path length: {:.2f}".format(-capitals_tsp.utility)) print("Final path length: {:.2f}".format(-result.utility)) print(result.path) show_path(result.coords, starting_city) ``` ## III. Local Beam Search Next, complete the `solve()` method for the `LocalBeamSolver` class below. Local beam search is identical to the hill climbing algorithm except that it begins with k randomly generated states and at each step it selects the k best successors from the complete list of neighbors over all k states, then repeats. ``` class LocalBeamSolver: """ Parameters ---------- beam_width : int The number of samples to maintain during search. epochs : int The upper limit on the number of rounds to perform hill climbing; the algorithm terminates and returns the best observed result when this iteration limit is exceeded. """ def __init__(self, beam_width=5, epochs=100): self.beam_width = beam_width self.epochs = epochs def solve(self, problem): """ Optimize the input problem by applying local beam search. Parameters ---------- problem : Problem An initialized instance of an optimization problem. The Problem class interface must implement a callable method "successors()" which returns a iterable sequence (i.e., a list or generator) of the states in the neighborhood of the current state, and a property "utility" which returns a fitness score for the state. (See the `TravelingSalesmanProblem` class for more details.) Returns ------- Problem The resulting approximate solution state of the optimization problem See Also -------- local_beam_search() pseudocode https:// """ # TODO: Implement this function! raise NotImplementedError ``` ### Run the Local Beam Search Solver ``` solver = LocalBeamSolver(beam_width=5, epochs=20) start_time = time.perf_counter() result = solver.solve(capitals_tsp) stop_time = time.perf_counter() print("solution_time: {:.2f} milliseconds".format((stop_time - start_time) * 1000)) print("Initial path length: {:.2f}".format(-capitals_tsp.utility)) print("Final path length: {:.2f}".format(-result.utility)) print(result.path) show_path(result.coords, starting_city) ``` ## IV. Simulated Annealing Complete the `schedule()` and `solve()` methods of the `SimulatedAnnealingSolver` class below. Simulated annealing repeatedly generates successors in the neighborhood of the current state and considers moving there according to an acceptance probability distribution parameterized by a cooling schedule. > The simulated annealing algorithm, a version of stochastic hill climbing where some downhill moves are allowed. Downhill moves are accepted readily early in the annealing schedule and then less often as time goes on. The schedule input determines the value of the temperature T as a function of time. [AIMA 3rd ed, Chapter 4] ![](pseudocode/simulated_annealing.png) Pseudocode for the [simulated-annealing function](https://github.com/aimacode/aima-pseudocode/blob/master/md/Simulated-Annealing.md) from the AIMA textbook. Note that our Problem class is already a "node", so the MAKE-NODE line is not required. ``` class SimulatedAnnealingSolver: """ Parameters ---------- alpha : numeric The decay rate parameter controlling the exponential temperature distribution. initial_temperature : numeric The initial temperature for the temperature distribution. """ def __init__(self, alpha=0.95, initial_temperature=1e6): self.alpha = alpha self.initial_temperature = initial_temperature self.__cutoff_temperature = 1e-8 # arbitrary small constant def schedule(self, time): """ Return the temperature at the specified time according to the temperature schedule The most commonly used temperature schedule is an exponential: T = T_i * alpha^t Where T_i is the intial temperature, alpha is a decay rate constant, and t is the current time step number. """ # TODO: implement this function raise NotImplementedError def solve(self, problem): """ Optimize the input problem by applying simulated annealing. Parameters ---------- problem : Problem An initialized instance of an optimization problem. The Problem class interface must implement a callable method "get_successors()" which returns a random neighbor of the current states, and a property "utility" which returns a fitness score for the state. (See the `TravelingSalesmanProblem` class for more details.) Returns ------- Problem The resulting approximate solution state of the optimization problem Notes ----- (1) DO NOT include the MAKE-NODE line from the AIMA pseudocode (2) Modify the termination condition in the pseudocode so that the function returns when the temperature falls below `self.__cutoff_temperature` """ # TODO: Implement this function raise NotImplementedError ``` ### Run the Simulated Annealing Solver ``` solver = SimulatedAnnealingSolver(alpha=.995, initial_temperature=1e8) start_time = time.perf_counter() result = solver.solve(capitals_tsp) stop_time = time.perf_counter() print("solution_time: {:.2f} milliseconds".format((stop_time - start_time) * 1000)) print("Initial path length: {:.2f}".format(-capitals_tsp.utility)) print("Final path length: {:.2f}".format(-result.utility)) print(result.path) show_path(result.coords, starting_city) ``` ## V. Late Acceptance Hill Climbing The late acceptance hill-climbing search algorithm combines properties of both basic hill climbing and simulated annealing by accepting some downhill moves when the neighbor's value is higher than one of the previous best values in an array. ![](pseudocode/lahc.png) You can read about LAHC (including pseudocode) in "The Late Acceptance Hill-Climbing Heuristic" by Burke & Bykov [here](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.261.3472&rep=rep1&type=pdf). (A copy of the PDF is also included in the git repo for this project.) ``` class LAHCSolver: """ Parameters ---------- Lfa : numeric The size of the late acceptance value array. epochs : numeric The upper limit on the number of rounds to perform hill climbing; the algorithm terminates and returns the best observed result when this iteration limit is exceeded. """ def __init__(self, Lfa=5, epochs=100): self.epochs = epochs self.Lfa = Lfa def solve(self, problem): """ Optimize the input problem by applying late-acceptance hill climbing. Parameters ---------- problem : Problem An initialized instance of an optimization problem. The Problem class interface must implement a callable method "successors()" which returns a iterable sequence (i.e., a list or generator) of the states in the neighborhood of the current state, and a property "utility" which returns a fitness score for the state. (See the `TravelingSalesmanProblem` class for more details.) Returns ------- Problem The resulting approximate solution state of the optimization problem See Also -------- late_acceptance() pseudocode https:// """ # TODO: Implement this function! raise NotImplementedError ``` ### Run the Late Acceptance Hill Climbing Solver ``` solver = LAHCSolver(Lfa=5, epochs=25) start_time = time.perf_counter() result = solver.solve(capitals_tsp) stop_time = time.perf_counter() print("solution_time: {:.2f} milliseconds".format((stop_time - start_time) * 1000)) print("Initial path length: {:.2f}".format(-capitals_tsp.utility)) print("Final path length: {:.2f}".format(-result.utility)) print(result.path) show_path(result.coords, starting_city) ``` ## VI. Additional Experiments (Optional) Here are some ideas for additional experiments with various settings and parameters once you've completed the lab. - Experiment with the parameters for each solver. How do they affect the results? - Use a different schedule function for the simulated annealing solver (something other than exponential decay). Is the algorithm still effective? - Use a different distance metric for get_value (e.g., we used the L2-norm (Euclidean distance), try the L1-norm (manhattan distance) or L$\infty$-norm (uniform norm) - Implement a genetic algorithm solver (ref: [here](https://iccl.inf.tu-dresden.de/w/images/b/b7/GA_for_TSP.pdf)) and compare with the other local search algorithms Share and discuss your results with your peers!
github_jupyter
Example 5 - Cross-coupled bearings. ===== In this example, we use the rotor seen in Example 5.9.4 from 'Dynamics of Rotating Machinery' by MI Friswell, JET Penny, SD Garvey & AW Lees, published by Cambridge University Press, 2010. This system is the same as that of Example 3, except that some coupling is introduced in the bearings between the x and y directions. The bearings have direct stiffnesses of $1 MN/m$ and cross-coupling stiffnesses of $0.5 MN/m$. ``` from bokeh.io import output_notebook, show import ross as rs import numpy as np output_notebook() #Classic Instantiation of the rotor shaft_elements = [] bearing_seal_elements = [] disk_elements = [] Steel = rs.steel for i in range(6): shaft_elements.append(rs.ShaftElement(L=0.25, material=Steel, n=i, i_d=0, o_d=0.05)) disk_elements.append(rs.DiskElement.from_geometry(n=2, material=Steel, width=0.07, i_d=0.05, o_d=0.28 ) ) disk_elements.append(rs.DiskElement.from_geometry(n=4, material=Steel, width=0.07, i_d=0.05, o_d=0.35 ) ) bearing_seal_elements.append(rs.BearingElement(n=0, kxx=1e6, kyy=1e6, kxy=.5e6, cxx=0, cyy=0)) bearing_seal_elements.append(rs.BearingElement(n=6, kxx=1e6, kyy=1e6, kxy=.5e6, cxx=0, cyy=0)) rotor594c = rs.Rotor(shaft_elements=shaft_elements, bearing_seal_elements=bearing_seal_elements, disk_elements=disk_elements,n_eigen = 12) show(rotor594c.plot_rotor(plot_type='bokeh')) #From_section class method instantiation. bearing_seal_elements = [] disk_elements = [] shaft_length_data = 3*[0.5] i_d = 3*[0] o_d = 3*[0.05] disk_elements.append(rs.DiskElement.from_geometry(n=1, material=Steel, width=0.07, i_d=0.05, o_d=0.28 ) ) disk_elements.append(rs.DiskElement.from_geometry(n=2, material=Steel, width=0.07, i_d=0.05, o_d=0.35 ) ) bearing_seal_elements.append(rs.BearingElement(n=0, kxx=1e6, kyy=1e6, cxx=0, cyy=0)) bearing_seal_elements.append(rs.BearingElement(n=3, kxx=1e6, kyy=1e6, cxx=0, cyy=0)) rotor594fs = rs.Rotor.from_section(brg_seal_data=bearing_seal_elements, disk_data=disk_elements,leng_data=shaft_length_data, i_ds_data=i_d,o_ds_data=o_d ) show(rotor594fs.plot_rotor(plot_type='bokeh')) #Obtaining results for w=0 (wn is in rad/s) modal594c = rotor594c.run_modal(0) modal594fs = rotor594fs.run_modal(0) print('Normal Instantiation =', modal594c.wn) print('\n') print('From Section Instantiation =', modal594fs.wn) #Obtaining results for w=4000RPM (wn is in rad/s) modal594c = rotor594c.run_modal(4000*np.pi/30) print('Normal Instantiation =', modal594c.wn) ```
github_jupyter
``` # Import most generic modules import importlib import pathlib import os import sys from datetime import datetime, timedelta import pandas as pd from IPython.display import display, Markdown import warnings warnings.filterwarnings("ignore") module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Parameters that will be replaced when calling this notebook ticker = "AMC" report_name = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_dark_pool_{ticker.upper()}" display( Markdown( f"# {ticker.upper()} - Dark Pool - {datetime.now().strftime('%Y/%m/%d %H:%M:%S')}" ) ) ``` ## Top 10 Negative Dark Pool Positions ``` from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_view stockgrid_view.dark_pool_short_positions( num=10, sort_field="dpp_dollar", ascending=True, export="" ) ``` ## Top 10 Most Highly Shorted Stocks ``` from gamestonk_terminal.stocks.dark_pool_shorts import shortinterest_view shortinterest_view.high_short_interest(num=10, export="") ``` ## Dark Pool Activity ``` from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_view stockgrid_view.net_short_position(ticker=ticker.upper(), num=60, raw=False, export="") stockgrid_view.net_short_position(ticker=ticker.upper(), num=10, raw=True, export="") from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_view stockgrid_view.short_interest_volume( ticker=ticker.upper(), num=60, raw=False, export="" ) stockgrid_view.short_interest_volume(ticker=ticker.upper(), num=10, raw=True, export="") ``` ## Options info ``` from gamestonk_terminal.stocks.options import barchart_view barchart_view.print_options_data(ticker=ticker.upper(), export="") ``` ## Put and Call Open Interest Expiring next ``` from gamestonk_terminal.stocks.options import yfinance_model, yfinance_view selected_date = yfinance_model.option_expirations(ticker)[0] options = yfinance_model.get_option_chain(ticker, selected_date) yfinance_view.plot_oi( ticker=ticker, expiry=selected_date, min_sp=-1, max_sp=-1, calls_only=False, puts_only=False, export="", ) ``` ## Failure-to-deliver (30 days lag) ``` from gamestonk_terminal.stocks import stocks_helper from gamestonk_terminal.stocks.dark_pool_shorts import sec_view stock = stocks_helper.load(ticker) sec_view.fails_to_deliver( ticker=ticker.upper(), stock=stock, start=datetime.now() - timedelta(days=60), end=datetime.now(), num=0, raw=False, export="", ) !jupyter nbconvert {report_name + ".ipynb"} --to html --no-input ```
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/CentralTendency/central-tendency.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a> ``` %%html <script> function code_toggle() { if (code_shown){ $('div.input').hide('500'); $('#toggleButton').val('Show Code') } else { $('div.input').show('500'); $('#toggleButton').val('Hide Code') } code_shown = !code_shown } $( document ).ready(function(){ code_shown=false; $('div.input').hide() }); </script> <form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form> !pip install --upgrade --force-reinstall --user git+git://github.com/callysto/nbplus.git#egg=geogebra\&subdirectory=geogebra import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from ipywidgets import interact, widgets, Button, Layout from scipy import stats from collections import Counter from array import array import IPython import pandas from statistics import mean, median, mode from IPython.display import HTML import random from IPython.display import IFrame def display(question, answerList): print(question) IPython.display.display(answerList) ``` # Data Analysis: Mean, Median, and Mode ##### Grade 7 Statistics This notebook will cover 3 important statistics: mean, median, and mode. These three statistics are known as the measures of central tendency because they tell us where data is centered or clustered together. It will also cover the topic of range. Here are a few questions this notebook will answer: * What is range? * What is mean? * What is median? * What is mode? * When do we use each of these statistics? If you want a good summary of this topic, check out [this website for Australian junior high students](https://www.mathsteacher.com.au/year8/ch17_stat/02_mean/mean.htm) or watch the video at the end! ## 1. Definitions <img style="float: right;" src="https://images-na.ssl-images-amazon.com/images/I/51JWOlyyH9L._SY445_.jpg" width="200" height="500"> ### What is range? Given a set of values, the range is just the difference between the highest value and the lowest value. This quickly tells us if the values are spread apart or close together. ##### Example The time it took Avery to walk to school each day this week was 10 minutes, 15 minutes, 12 minutes, 20 minutes, and 8 minutes. What is the range of the time it takes to walk to school? range = highest value - lowest value <br> range = 20 minutes - 8 minutes <br> range = 12 minutes <br> Based on the value of the range, we know that the time it takes to walk to school can be quite different. ### What is 'mean'? No, we don't mean being rude to other people. A **mean (sometimes called an average)** of a set of numbers is the sum of all the values divided by the number of number of values. ##### Example 1 Here is a data set: $2, 6, 3, 7, 5, 3, 9$ <br> Number of elements in this data set: $7$ <br>So the mean is: $$\text{mean} = \frac{2 + 6 + 3 + 7 + 5 + 3 + 9}{7} = \frac{35}{7} = 5 $$ Now these are just numbers, let's see where the mean applies in real life. <img style="float: left;" src="images/positive-classroom.jpg" width="300" height="400"> ##### Example 2 In Rose Middle School, there's 3 classes of Grade 8 students. The first one has 25 students, the second has 18 students, and the third has 20 students. What is the average number of students in one class? <br> **Remember that average is the same as mean** Our set of data is $(25, 18, 20)$ and there is $3$ elements in this set. Now we can calculate the mean. $$\text{mean} = \frac{25 + 18 + 20}{3} = \frac{63}{3} = 21 $$ That means that Grade 8 students in Rose Middle School have an average of 21 students per class. Picture from [teachub.com](https://www.teachhub.com/5-effective-teaching-strategies-positive-classroom) ### Try for yourself! ``` question612 = "What is the mean of the following numbers? \n 10, 91, 39, 71, 17, 39, 76, 37, 25" answer612 = widgets.RadioButtons(options=['45', '45.11', '43.67', '46', 'None of the above'], value=None, description='Choices:') def check612(b): IPython.display.clear_output(wait=False) display(question612, answer612) if answer612.value == '45': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question612, answer612) answer612.observe(check612, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question612"> <button id = "612" onclick="toggle('answer612');">Solution</button> </div> <div style="display:none" id="answer612"> To find out the mean of semester 1 we divide the sum of all data by the numbers of data.<br/> Therefore, Mean $= \frac{10 + 91 + 39 + 71 + 17 + 39 + 76 + 37 + 25}{9} = 45$ <br/> </div> </body> </html> ``` ### What is median? Let's play monkey in the middle! The **median** is the middle number in a sequence of numbers.To compute the median, the set needs to be ordered from smallest to largest. Then it's easy to find the middle number!<br> <img style="float: left;" src="https://i0.wp.com/www.thegamegal.com/wp-content/uploads/2016/02/monkey-in-the-middle.png?fit=391%2C501&ssl=1&w=640" width="275" height="3500"> ##### Example 1 Data set: $2, 6, 3, 7, 5, 3, 9$ <br> Now if we sort the data set: $2, 3, 3, 5, 6, 7, 9$ <br> So, median will be $5$ because it's 4 numbers in from both sides Did you notice that this data set has an odd number of values? What is the problem if there's an even number of values in a set? How can we figure out the median? We still want the middle number, so we can't choose one closer to either the left or the right side. We can average the two numbers closest to the middle to get a true middle number for the whole set! ##### Example 2 Data set: $2, 6, 3, 7, 5, 3, 9, 4 $ <br> **Notice how there's 8 values in this set** <br> Sorted data set: $2, 3, 3, 4, 5, 6, 7, 9$ <br> There two middle numbers are $4$ and $5$ <br> Therefore, the median will be $\frac{(4+5)}{2} = 4.5$ Picture from [thegamegal.com](https://www.thegamegal.com/2016/02/02/monkey-in-the-middle-game/) ### Try for yourself! ``` answer622 = widgets.RadioButtons(options=['11', '11.5', '12', '12.5', 'None of the above'], value = None, description='Choices:') question622 = "Suppose, the front row in your classroom has 23 seats. If you were asked to sit in the seat \n in the median position, in which seat would you have to sit?" def check622(d): IPython.display.clear_output(wait=False) display(question622, answer622) if answer622.value == '12': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question622,answer622 ) answer622.observe(check622, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question622"> <button id = "622" onclick="toggle('answer622');">Solution</button> </div> <div style="display:none" id="answer622"> <br/> The number of seats is odd (23). To find out the median of the seats we need to divide the total number of seats by 2 and we get 11.5. <br/> So, 12-th seat is in the median position in the first row. <br/> We can also think of it as the seat 12 has 11 seat on the left, and 11 seats on the right. <br/> So the correct answer is 12.<br/> </div> </body> </html> ``` ### What is mode? The **mode** for a data set is the element that occurs the most often.<br> It's possible for a data set to have no modes, one mode, two modes (bimodal), or even three modes (trimodal)!<br> To find the mode, you don't have to sort the set, but it is very helpful to sort it as the mode(s) will be where a number is repeated and that's easier to see when they are next to each other. <img style="float: left;" src="https://zookyworld.files.wordpress.com/2013/03/stop-repeating.gif" width="400" height="700"> ##### Example 1 Data set: $2, 6, 3, 7, 5, 3, 9$ <br> Sorted data set: $2, 3, 3, 5, 6, 7, 9$ <br> Here, only the value $3$ repeats and all other values only appear once. <br>So, mode will be $3$. ##### Example 2 Data set: $2, 6, 3, 7, 5, 3, 9, 5, 3, 5, 6 $ <br> Sorted data set: $2, 3, 3, 3, 5, 5, 5, 6, 6, 7, 9$ <br> Values $3$ and $5$ have same number of repetitions. <br> Notice how $6$ is also repeated but it is not as many times as $3$ or $5$ so it is not part of the mode. <br>So, the mode will be, $3, 5$ ##### Example 3 Data set: $2, 6, 3, 7, 5, 8, 9, 4 $ <br> Sorted data set: $2, 3, 4, 5, 6, 7, 8, 9$ <br>There are no value that repeats. <br> So, there is no mode. Picture from [zooky world](https://zookyworld.wordpress.com/2013/03/26/stop-repeating/) ### Try for yourself! A student recorded her scores on weekly math quizzes that were marked out of a possible 10 points. Her scores were as follows: <br> 5, 6, 9, 8, 9, 10, 7, 6, 8, 7, 6, 7 ``` answer641 = widgets.RadioButtons(options=['6', ' 7', '6 and 7', '8 and 9', 'None of the above'], value=None,description='Choices:') question641 = "What is/are the mode of her records?" def checkAnswer641(f): IPython.display.clear_output(wait=False) display(question641, answer641 ) if answer641.value == '6 and 7': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question641, answer641) answer641.observe(checkAnswer641, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question641"> <button id = "641" onclick="toggle('answer641');">Solution</button> </div> <div style="display:none" id="answer641"> At first, let sort the scores on weekly math quizzes: <br/> $ 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10$ <br/> From the sorted points, we can imply, <br/> 5 only apears once, <br/> 6 and 7 repeat three times, <br/> 8 and 9 repeat two times, <br/> and 10 only appears once. <br/> Therefore, the mode of her scores are: 6 and 7 <br/> </div> </body> </html> ``` ## 2. Interactive bar graph Now you can play with a bar graph and examine how to calculate mean, median, and mode by changing values of the dataset. ### Instructions: * Step 1: enter how many data points you have in "Enter the numbers of the dataset." **Max of 10** <br> * based on your input in step 1, sliders will be available (one for each data point). <br> * Step 2: change the value of sliders and see the associated changes in the bar graph.<br> * Step 3: to show the breakdown for calculating mean check the box Mean, for median check Median and so on.<br> ``` from importlib import reload import site reload(site) from geogebra.ggb import * ggb = GGB() ggb.file('sources/centralTendency.ggb').draw() ``` ## Example Using A Large Dataset We will be using a computer to calculate the mean, median, and mode for both the x and y values of this graph. <img src="images/JustTRex.png" width="400" height="400" align="center"/> This dataset was originally created by [Alberto Cairo](http://www.thefunctionalart.com/2016/08/download-datasaurus-never-trust-summary.html) which is named "Datasaurus" (for obvious reasons). It was made to show how we shouldn't blindly trust only central tendency to tell the full picture of the data. He also made this data free for everyone to use! There are 142 values in this dataset! If you want to compute mean, median, or mode by hand, feel free to display the whole dataset using the button below. ``` dataset = pandas.read_csv("sources/Datasaurus.csv") show = widgets.ToggleButton(value=False,description='Show dataset',disabled=False) def display_data(a): if show.value == True: print(round(dataset.head(142),3)) else: IPython.display.clear_output() IPython.display.display(show) IPython.display.display(show) show.observe(display_data, 'value') ``` ### Mean ``` #Mean fullDataframeMean = [] fullDataframeMean = dataset.mean() print(round(fullDataframeMean.head(2),3)) ``` What does this tell us? We now know that the average of the x values is larger than 50 which means there are **more** dots on the **right** than the left. We also know the average of the y values is less than 50 which means there are **more** dots on the **bottom** than the top. We can see this as the T-Rex is on the right of the graph and it took lots of dots to make the details of the claws and bottom jaw compared to the top of the head. ### Median ``` #Median fullDataframeMedian = [] fullDataframeMedian = dataset.median() print(round(fullDataframeMedian.head(2),3)) ``` What does this tell us? We now know what the middles values are so we can find the middle of the T-Rex at this location. ### Mode ``` #Mode fullDataFrameMode = [] fullDataFrameMode = dataset.mode() print(round(fullDataFrameMode.head(1),3)) ``` What does this tell us? The mode tells us where to find the straightest line up and down by the x value and the straightest line left to right by the y value. [Autodesk Research](https://www.autodeskresearch.com/publications/samestats) used this dataset to create the "Datasaurus Dozen". They created 12 new graphs with the same x and y mean as "Datasaurus". <img src="images/DinoSequential.gif" width="400" height="400" align="center"/> ## Create Your Own Data Set You can click "Show/hide next box" and change the numbers in "YourDataSet". You can even add new ones or take away some. Try making a set with small numbers and one with large numbers. Try to make sets with an even amount of numbers and an odd amount of numbers. *Just make sure there's a comma ( , ) between each number.* Then we tell the computer to compute the mean, then the median, then the mode. It's important to know how to calculate these by hand, but computers are very smart now. We have these tools to help us calculate things like mean, median, and mode once we understand what they mean. After making your changes, to run the cell with code below click on the "Run" button at the top or hit "Ctrl+Enter/Return" key. ``` #found on https://stackoverflow.com/questions/31517194/how-to-hide-one-specific-cell-input-or-output-in-ipython-notebook def hide_toggle(): this_cell = """$('div.cell.code_cell.rendered.selected')""" toggle_text = 'Show/hide next box' # text shown on toggle link target_cell = this_cell + '.next()' js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64))) html = """ <script> function {f_name}() {{ {cell_selector}.find('div.input').toggle(); }} </script> <a href="javascript:{f_name}()">{toggle_text}</a> """.format( f_name=js_f_name, cell_selector=target_cell, toggle_text=toggle_text ) return HTML(html) hide_toggle() YourDataSet = [0,1,2,3,4,5,6] #don't forget a comma between each number! #the word "print" tells the computer to write it below this block so you can read it! print("Your mean is: ") print(mean(YourDataSet)) #this calculates your mean print("Your median is: ") print(median(YourDataSet)) #this calculates your median try: print("Your mode is: ") print(mode(YourDataSet)) #this calculates your mode except: print("There is no mode in your data set") #this is incase there is no mode ``` ************** ## Test yourself Try out some of these harder questions on your own! ``` question611 = "What number would you divide by to calculate the mean of 3, 4, 5, and 6?" answer611 = widgets.RadioButtons(options=['3', '4', '4.5', '5', 'None of the above'], value= None, description='Choices:') def checkAnswer(a): IPython.display.clear_output(wait=False) display(question611, answer611) if answer611.value == '4': print("Correct Answer!") else: print("Wrong answer! Try again.") display(question611, answer611) answer611.observe(checkAnswer, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question611"> <button id = "611" onclick="toggle('answer611');">Solution</button> </div> <div style="display:none" id="answer611"> From the definition of mean, we know that we have to divide by the total number of elements in the data set.<br/> In this case, that number is 4. <br/> So, to compute the mean, we have to divide the sum of the data set by 4. <br/> </div> </body> </html> question621 = "The mean of four numbers is 71.5. If three of the numbers are 58, 76, and 88, what is the value of the fourth number?" answer621 = widgets.RadioButtons(options=['62', '73.37', '64', '74', 'None of the above'], value = None, description='Choices:') def check621(c): IPython.display.clear_output(wait=False) display(question621, answer621) if answer621.value == '64': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question621, answer621) answer621.observe(check621, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question621"> <button id = "621" onclick="toggle('answer621');">Solution</button> </div> <div style="display:none" id="answer621"> We are given three numbers but told the mean of four numbers is 71.5. Let assume the fourth number is x. <br/> So, by the definition of mean, we can write <br> $\frac{58 + 76 + 88 + x}{4} = 71.5 $ <br/> or, $222 + x = 71.5 \times 4 $ <br/> or, $x = 286 - 222 $ <br/> or, $x = 64 $ <br/> Therefore, the fourth number is 64. <br/> </div> </body> </html> ``` Sara tried to compute the mean average of her 8 test scores. She mistakenly divided the correct sum of all her test scores by 7, which yields 96. ``` answer631 = widgets.RadioButtons(options=['78', '83.5', '100', '84', 'None of the above'], value = None, description='Choices:') question631 = "What is Sara's mean test score? (Source: dummies)" def check631(e): IPython.display.clear_output(wait=False) display(question631, answer631) if answer631.value == '84': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question631, answer631) answer631.observe(check631, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question631"> <button id = "631" onclick="toggle('answer631');">Solution</button> </div> <div style="display:none" id="answer631"> You know the test score mean of Sara when divided by 7, you can determine the sum of her scores. This information will then allow you to determine her mean average over eight tests.<br/> Apply the average formula to her wrong calculation. <br/> 96 = sum of scores รท 7 <br/> 96 ร— 7 = sum of scores <br/> 672 = sum of scores <br/> Now that you know her test score sum, you can figure her true mean average.<br/> Mean average = 672 รท 8 <br/> Mean average = 84 <br/> So, the correct answer is D. <br/> </div> </body> </html> answer632 = widgets.RadioButtons(options=['32, 34, 35, 36', '32, 35, 36, 41', '32, 34, 40, 44', '32, 32, 38, 38', 'None of the above'], value = None, description='Choices:') question632 = "A set of four numbers that begins with the number 32 is arranged from smallest to largest.\n If the median is 35, which of the following could be the set of numbers?" def check632(e): IPython.display.clear_output(wait=False) display(question632, answer632) if answer632.value == '32, 32, 38, 38': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question632, answer632) answer632.observe(check632, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question632"> <button id = "632" onclick="toggle('answer632');">Solution</button> </div> <div style="display:none" id="answer632"> We are given the median of four numbers 35. We can imply from the given information is that the sum <br/> of the numbers is 140. Now we check all the choices one by one. We add all the numbers of the first choice and get 137. <br/> So it is not our correct answer. <br/> Similarly, for the next choices we get 144, 150, and 140 for second, third and fourth choices, respectively, <br/> Therefore, the correct series is: 32, 32, 38, 38.<br/> </div> </body> </html> answer642 = widgets.RadioButtons(options=['1', '2', '4', '19', 'None of the above'], value = None, description='Choices:') question642 = "The average of five positive integers is less than 20. What is the smallest possible median of this set?" def check642(g): IPython.display.clear_output(wait=False) display(question642, answer642) if answer642.value == '1': print("Correct Answer!") else: print("Wrong answer! Try again.") IPython.display.clear_output(wait=False) display(question642, answer642) answer642.observe(check642, 'value') %%html <html> <head> <script type="text/javascript"> <!-- function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } //--> </script> </head> <body> <div id="question642"> <button id = "642" onclick="toggle('answer642');">Solution</button> </div> <div style="display:none" id="answer642"> As we are given that the numbers are positive integers that means all numbers should be <br/>greater than or equal 1. Let assume the five numbers are 1, 1, 1, 1, 16. The sum is equal <br/>to 20, and the average is 20/5 = 4 which is less than 20. All given conditions are satisfied. <br > <b>Therefore, the smallest possible median is 1. <b> <br/> </div> </body> </html> ``` ## Let's summarize what we have learned in this notebook: * Mean is the average and is found by adding all values then dividing my the quantity of values * Median is the middle value and is found by sorting the set and finding the middle * Mode is the most used value and is found by counting how many times a value is repeated * Range is the highest value minus the lowest value Here is a video made by Dylan Peters EDU that is a parody of the song Lazy Song by Bruno Mars that sums up these 4 concepts. ``` IFrame(width="560", height="315", src="https://www.youtube.com/embed/IHginNwss5c", allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; allowfullscreen") ``` [![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
github_jupyter
![tweepy-python-twitter.png](attachment:tweepy-python-twitter.png) ## Anรกlisis de Twitter con Tweepy y TexBlob Un "tuit" o tweet es una publicaciรณn de un usuario en la red social Twitter. Como parte del mensaje, podemos encontrar ademรกs de texto, diferentes elementos multimedia (imagenes, videos, audio, etc.), enlaces y los populares emoticones. La estructura de un tweet la podemos observar en la siguiente imagen: ![TwitterMap.jpg](attachment:TwitterMap.jpg) ### 1. ยฟCรณmo extraemos datos de Twitter? Para acceder al **API de Twitter**, es requisito indispensable obtener las credenciales como developer. Dichas credenciales las otorga Twitter luego de registrarse en su plataforma developer en este enlace: https://developer.twitter.com/en/apply-for-access Las credenciales estan compuestas por cuatro datos: * CONSUMER_KEY * CONSUMER_SECRET * ACCESS_TOKEN * ACCESS_SECRET Al ser datos privados, crearemos un archivo Python llamado credenciales.py y configuramos los valores de estas variables asi: ### Consume: * CONSUMER_KEY = "tu c-key" * CONSUMER_SECRET = "tu c-secret" ### Access: * ACCESS_TOKEN = "tu a-token" * ACCESS_SECRET = "tu a-secret" ### 2. Importaciรณn de librerias ``` # La libreria Tweepy permitira acceder a Twitter via las credenciales de developer from tweepy import OAuthHandler from tweepy.streaming import StreamListener import tweepy,json # Importamos nuestras claves de acceso a Twitter desde el archivo credenciales # Tenerlas en un archivo, nos permite manejarlas como variables from credenciales import * import pandas as pd import numpy as np ``` ### 3. Configuraciรณn de acceso a Twitter App ``` # Configuracion del API: def twitter_setup(): """ Esta funcion permite configurar el API de Twitter con nuestras credenciales como developer """ # Autenticacion y acceso utilizando las claves: auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) # Devolver API con autenticaciรณn api = tweepy.API(auth) return api ``` ### 4. Extracciรณn de Tweets **OPCION #1:** utilizando la funcion **extractor** de Tweepy Extraeremos los tweets de un usuario especifico. Se especifica en screen_name="el nombre del usuario", count=la cantidad de tweets ``` # Extracciรณn de tweets # Creamos el objeto extractor: extractor = twitter_setup() # Creamos una lista de tweets de la siguiente manera: tweets = extractor.user_timeline(screen_name="CocaCola", count=200) print("Nรบmero de tweets extraรญdos: {}.\n".format(len(tweets))) # Visualizamos los 5 tweets mรกs recientes: print("5 tweets recientes:\n") for tweet in tweets[:5]: print(tweet.text) print() ``` **OPCION #2:** utilizando la clase **MyStreamListener** de Tweepy Extraeremos los tweets de acuerdo a las palabras clave que se especifiquen (idenpendientemente del nombre del usuario) Despuรฉs de obtener acceso a los datos de Twitter, ahora crearemos un archivo para guardar todos los tweets encontrados. ``` # Autenticacion y acceso utilizando las claves: auth_l = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_l.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) tweet_list=[] class MyStreamListener(tweepy.StreamListener): def __init__(self,api=None): super(MyStreamListener,self).__init__() self.num_tweets=0 self.file=open("tweet.txt","w") def on_status(self,status): tweet=status._json self.file.write(json.dumps(tweet)+ '\n') tweet_list.append(status) self.num_tweets+=1 if self.num_tweets<1000: return True else: return False self.file.close() ``` Ahora crearemos un filtro que extraerรก tweets basados **en ciertas palabras que se mencionan**. Bรกsicamente, extraerรก tweets que contengan las palabras vรกlidas que desemos. Los tweets los graba en el archivo **tweet.txt** ``` # Creamos un objeto de transmisiรณn y autenticamos l = MyStreamListener () stream = tweepy.Stream (auth_l, l) # esta lรญnea filtra flujos de datos en Twitter para capturar datos por palabras clave stream.filter (track = ['covid', 'corona', 'covid19', 'coronavirus', 'mascarilla', 'desinfectante', 'distanciamiento social']) stream.filter (track = ['fraudeenmesa','keiko fujimori','pedro castillo', 'conteo','actas','sagasti']) ``` Verificamos la extstencia del archivo **text.txt** en nuestro directorio de trabajo y le hacemos una copia. Leemos luego los tweets almacenados en el archivo **copia** de la siguiente manera: ``` tweets_data_path='tweet_covid.txt' tweets_data=[] tweets_file=open(tweets_data_path,"r") # Leemos los tweets y los pasamos a una lista for line in tweets_file: tweet=json.loads(line) tweets_data.append(tweet) tweets_file.close() # Visualizamos el contenido del primer tweet print(tweets_data[0]) # Extraemos algunas variables relevantes ids = [tweet['id_str'] for tweet in tweets_data] times = [tweet['created_at'] for tweet in tweets_data] users = [tweet['user']['name'] for tweet in tweets_data] texts = [tweet['text'] for tweet in tweets_data] lats = [(T['geo']['coordinates'][0] if T['geo'] else None) for T in tweets_data] lons = [(T['geo']['coordinates'][1] if T['geo'] else None) for T in tweets_data] place_names = [(T['place']['full_name'] if T['place'] else None) for T in tweets_data] place_types = [(T['place']['place_type'] if T['place'] else None) for T in tweets_data] ids[0],times[0], users[0], texts[0] ``` **OPCION #3:** utilizando el metodo **api.search** de Tweepy ``` import csv #Import csv import os api = twitter_setup() csvFile = open("segunda_vuelta1.csv", 'a', newline='', encoding='utf-8') try: writer = csv.writer(csvFile, quoting=csv.QUOTE_ALL) writer.writerow(["created_at", "text", "len", "likes", "RTs", "user_name"]) for tweet in tweepy.Cursor(api.search, q = "#fraudeenmesa -filter:retweets", count=5000, since = "2021-06-8", until = "2021-06-14", lang = "es").items(): writer.writerow([tweet.created_at, tweet.text, tweet.favorite_count, tweet.retweet_count, tweet.user.screen_name]) finally: csvFile.close() ``` Como se puede observar, en la opcion 1 y 2 los datos se encuentran crudos. Tendremos que pasar los datos relevantes de los tweets a un dataframe para pader trabajarlos. En cambio, bajo la opcion 3, ya tenemos los datos relevantes en un archivo delimintado por comas. ### 1.4. Creaciรณn del Dataframe ``` # Creamos el dataframe de pandas desde la lista de tweets obtenidos mediante las credenciales de Twitter # y contenidos en la lista tweets: data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets']) # Mostramos las 10 primeras observaciones del dataframe: display(data.head(10)) # Creamos el dataframe de pandas desde la lista de tweets obtenidos mediante las credenciales de Twitter: data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets']) # Mostramos los as 10 primeras observaciones del dataframe: display(data.head(10)) # Mรฉtodos internos de un solo objeto de tweet: print(dir(tweets[0])) # Imprimimos informaciรณn del primer tweet: print(tweets[0].id) print(tweets[0].created_at) print(tweets[0].source) print(tweets[0].favorite_count) print(tweets[0].retweet_count) print(tweets[0].geo) print(tweets[0].coordinates) print(tweets[0].entities) ``` ### 1.5. Adiciรณn de datos relevantes ``` # Datos relevantes en nuevas columnas: data['len'] = np.array([len(tweet.text) for tweet in tweets]) data['ID'] = np.array([tweet.id for tweet in tweets]) data['Date'] = np.array([tweet.created_at for tweet in tweets]) data['Source'] = np.array([tweet.source for tweet in tweets]) data['Likes'] = np.array([tweet.favorite_count for tweet in tweets]) data['RTs'] = np.array([tweet.retweet_count for tweet in tweets]) # Visualizaciรณn de los primeros 10 elementos del dataframe: display(data.head(10)) ``` ## 2. Visualizaciรณn y estadisticas bรกsicas Primero queremos calcular algunos datos estadรญsticos bรกsicos, como la media de la longitud de los caracteres de todos los tweets, el tweet con mรกs me gusta y retweets, etc. ### 2.1. Cรกlculo de media, mรกximo y mรญnimo ``` #Para obtener la "media", el valor maximo y minimo utilizamos la libreria numpy: # Extraemos la media de la variable 'len' que contiene las longitudes de los tweets: mean = np.mean(data['len']) print("Longitud promedio de los tweets: {}".format(mean)) #To extract more data, we will use some pandas' functionalities: # Extraemos los tweets con mas Me gusta (Likes) y mas retweets (RTs): fav_max = np.max(data['Likes']) rt_max = np.max(data['RTs']) fav = data[data.Likes == fav_max].index[0] rt = data[data.RTs == rt_max].index[0] # Max Likes: print("El tweet con mas likes es: \n{}".format(data['Tweets'][fav])) print("Numero de likes: {}".format(fav_max)) print("{} caracteres.\n".format(data['len'][fav])) # Max RTs: print("EL tweet con mas retweets es: \n{}".format(data['Tweets'][rt])) print("Numero de retweets: {}".format(rt_max)) print("{} caracteres.\n".format(data['len'][rt])) ``` ### 2.2. Time series Pandas tiene su propio objeto para series de tiempo. Dado que tenemos un vector completo con fechas de creaciรณn, podemos construir series de tiempo respetando la duraciรณn de los tweets, los me gusta y los retweets. La forma en que lo hacemos es: ``` # We create time series for data: tlen = pd.Series(data=data['len'].values, index=data['Date']) tfav = pd.Series(data=data['Likes'].values, index=data['Date']) tret = pd.Series(data=data['RTs'].values, index=data['Date']) ``` Y si queremos trazar la serie temporal, los pandas ya tienen su propio mรฉtodo en el objeto. Podemos trazar una serie de tiempo de la siguiente manera: ``` # Lenghts along time: tlen.plot(figsize=(16,4), color='r'); ``` Y para trazar los me gusta frente a los retweets en el mismo grรกfico: ``` # Likes vs retweets visualization: tfav.plot(figsize=(16,4), label="Likes", legend=True) tret.plot(figsize=(16,4), label="Retweets", legend=True); ``` ### 2.3. Grรกficos circulares (Pie) Ahora trazaremos las fuentes en un grรกfico circular, ya que nos dimos cuenta de que no todos los tweets provienen de la misma fuente. ``` # Obtenemos los posibles fuentes de los tweets: sources = [] for source in data['Source']: if source not in sources: sources.append(source) # Visualizamos la lista de fuentes: print("Lista de fuentes origen de los tweets:") for source in sources: print("* {}".format(source)) ``` Ahora contamos el nรบmero de cada fuente y creamos un grรกfico circular. ``` # We create a numpy vector mapped to labels: percent = np.zeros(len(sources)) for source in data['Source']: for index in range(len(sources)): if source == sources[index]: percent[index] += 1 pass percent /= 100 # Pie chart: pie_chart = pd.Series(percent, index=sources, name='Sources') pie_chart.plot.pie(fontsize=11, autopct='%.2f', figsize=(6, 6)); ``` ## 3. Anรกlisis de Sentimientos Textblob nos permitirรก hacer anรกlisis de sentimiento de una manera muy sencilla. Tambiรฉn usaremos la biblioteca re de Python, que se usa para trabajar con expresiones regulares. Para esto, le proporcionarรฉ dos funciones de utilidad para: a) limpiar texto (lo que significa que cualquier sรญmbolo distinto a un valor alfanumรฉrico serรก reasignado a uno nuevo que satisfaga esta condiciรณn), y b) crear un clasificador para analizar el polaridad de cada tweet despuรฉs de limpiar el texto que contiene. ### 3.1 Importando Textblob ``` from textblob import TextBlob import re def clean_tweet(tweet): ''' Funciรณn de utilidad para limpiar el texto de un tweet eliminando enlaces y caracteres especiales que utilizan expresiones regulares. ''' return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) def analize_sentiment(tweet): ''' Funciรณn de utilidad para clasificar la polaridad de un tweet usando textblob. ''' analysis = TextBlob(clean_tweet(tweet)) if analysis.sentiment.polarity > 0: return 1 elif analysis.sentiment.polarity == 0: return 0 else: return -1 ``` La forma en que funciona es que textblob ya proporciona un analizador entrenado (genial, ยฟverdad?). Textblob puede trabajar con diferentes modelos de aprendizaje automรกtico utilizados en el procesamiento del lenguaje natural. Solo agregaremos una columna adicional a nuestros datos. Esta columna contendrรก el anรกlisis de sentimiento y podemos trazar el dataframe para ver la actualizaciรณn: ``` # Creamos una columna con el resultado del anรกlisis: data['SA'] = np.array([ analize_sentiment(tweet) for tweet in data['Tweets'] ]) # Mostramos el dataframe actualizado con la nueva columna: display(data.head(10)) ``` ### 3.2. Analizando los resultados Para tener una forma sencilla de verificar los resultados, contaremos el nรบmero de tweets neutrales, positivos y negativos y extraeremos los porcentajes. ``` # Construimos listas con tweets clasificados: pos_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] > 0] neu_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] == 0] neg_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] < 0] ``` Ahora que tenemos las listas, solo imprimimos los porcentajes: ``` # Visualizamos los %: print("Percentaje de positivos tweets: {}%".format(len(pos_tweets)*100/len(data['Tweets']))) print("Percentaje de neutrales tweets: {}%".format(len(neu_tweets)*100/len(data['Tweets']))) print("Percentaje de negativos tweets: {}%".format(len(neg_tweets)*100/len(data['Tweets']))) ``` Tenemos que considerar que estamos trabajando solo con los 1000 tweets mรกs recientes. Para obtener resultados mรกs precisos, podemos considerar mรกs tweets.
github_jupyter
# Using ipyWidgets In this notebook, we will use ipyWidgets to make dynamic selections of the data being visualized. ``` import matplotlib.pyplot as plt import plotnine as p9 import pandas as pd import numpy as np from copy import copy from ipywidgets import widgets from IPython.display import display from plotnine.data import mtcars ``` First of all, [install ipywidgets](https://ipywidgets.readthedocs.io/en/stable/user_install.html): ```bash pip install ipywidgets # for jupyter notebooks: jupyter nbextension enable --py widgetsnbextension # for jupyter lab (requires npm): jupyter labextension install @jupyter-widgets/jupyterlab-manager ``` Let's have alook on the plot with all the data. We are comparing cars with their horse-power in the X axis and miles-per-gallon in the Y axis. The points are collored by car weight. ``` # This has to be used the first time you make a plot. This magic allows the notebook to update plots. %matplotlib notebook p = p9.ggplot(mtcars, p9.aes(x="hp", y="mpg", color="wt")) + \ p9.geom_point() + p9.theme_linedraw() p ``` Now we will get relevant values for the creation of plots with sub-sets of data. Initially, select cars based on number of cylinders ``` # Prepre the list we will use to selec sub-sets of data based on number of cylinders. cylList = np.unique( mtcars['cyl'] ) # The first selection is a drop-down menu for number of cylinders cylSelect = widgets.Dropdown( options=list(cylList), value=cylList[1], description='Cylinders:', disabled=False, ) # For the widgets to update the same plot, instead of creating one new image every time # a selection changes. We keep track of the matplotlib image and axis, so we create only one # figure and set of axis, for the first plot, and then just re-use the figure and axis # with plotnine's "_draw_using_figure" function. fig = None axs = None # This is the main function that is called to update the plot every time we chage a selection. def plotUpdate(*args): # Use global variables for matplotlib's figure and axis. global fig, axs # Get current values of the selection widget cylValue = cylSelect.value # Create a temporary dataset that is constrained by the user's selections. tmpDat = mtcars.loc[(mtcars['cyl'] == cylValue),:] # Create plotnine's plot # Using the maximum and minimum values we gatehred before, we can keep the plot axis from # changing with the cyinder selection p = p9.ggplot(tmpDat, p9.aes(x="hp", y="mpg", color="wt")) + \ p9.geom_point() + p9.theme_linedraw() if fig is None: # If this is the first time a plot is made in the notebook, we let plotnine create a new # matplotlib figure and axis. fig, plot = p.draw(return_ggplot=True) axs = plot.axs else: #p = copy(p) # This helps keeping old selected data from being visualized after a new selection is made. # We delete all previously reated artists from the matplotlib axis. for artist in plt.gca().lines +\ plt.gca().collections +\ plt.gca().artists + plt.gca().patches + plt.gca().texts: artist.remove() # If a plot is being updated, we re-use the figure an axis created before. p._draw_using_figure(fig, axs) cylSelect.observe(plotUpdate, 'value') # Display the widgets display(cylSelect) # Plots the first image, with inintial values. plotUpdate() # Matplotlib function to make the image fit within the plot dimensions. plt.tight_layout() # Trick to get the first rendered image to follow the previous "tight_layout" command. # without this, only after the first update would the figure be fit inside its dimensions. cylSelect.value = cylList[0] ``` Having axis ranges change between selections does not help probing the data. ``` # We now get the maximum ranges of relevant variables to keep axis constant between images. # Get range of weight minWt = min(mtcars['wt']) maxWt = max(mtcars['wt']) # We get all unique values of weigh, sort them, and transform the numpy.array into a python list. wtOptions = list( np.sort(np.unique(mtcars.loc[mtcars['cyl']==cylList[0],'wt'])) ) minHP = min(mtcars['hp']) maxHP = max(mtcars['hp']) minMPG = min(mtcars['mpg']) maxMPG = max(mtcars['mpg']) # The first selection is a drop-down menu for number of cylinders cylSelect = widgets.Dropdown( options=list(cylList), value=cylList[1], description='Cylinders:', disabled=False, ) # For the widgets to update the same plot, instead of creating one new image every time # a selection changes. We keep track of the matplotlib image and axis, so we create only one # figure and set of axis, for the first plot, and then just re-use the figure and axis # with plotnine's "_draw_using_figure" function. fig = None axs = None # This is the main function that is called to update the plot every time we chage a selection. def plotUpdate(*args): # Use global variables for matplotlib's figure and axis. global fig, axs # Get current values of the selection widget cylValue = cylSelect.value # Create a temporary dataset that is constrained by the user's selections. tmpDat = mtcars.loc[(mtcars['cyl'] == cylValue),:] # Create plotnine's plot # Using the maximum and minimum values we gatehred before, we can keep the plot axis from # changing with the cyinder selection p = p9.ggplot(tmpDat, p9.aes(x="hp", y="mpg", color="wt")) + \ p9.geom_point() + p9.theme_linedraw() + \ p9.xlim([minHP, maxHP]) + p9.ylim([minMPG, maxMPG]) + \ p9.scale_color_continuous(limits=(minWt, maxWt)) if fig is None: fig, plot = p.draw(return_ggplot=True) axs = plot.axs else: #p = copy(p) for artist in plt.gca().lines +\ plt.gca().collections +\ plt.gca().artists + plt.gca().patches + plt.gca().texts: artist.remove() p._draw_using_figure(fig, axs) cylSelect.observe(plotUpdate, 'value') # Display the widgets display(cylSelect) # Plots the first image, with inintial values. plotUpdate() # Matplotlib function to make the image fit within the plot dimensions. plt.tight_layout() # Trick to get the first rendered image to follow the previous "tight_layout" command. # without this, only after the first update would the figure be fit inside its dimensions. cylSelect.value = cylList[0] ``` Now we can make our selection more complicated by restricting the car data being visualized. Using a range slider we can restric data based on car weight. ``` # The first selection is a drop-down menu for number of cylinders cylSelect = widgets.Dropdown( options=list(cylList), value=cylList[1], description='Cylinders:', disabled=False, ) # The second selection is a range of weights wtSelect = widgets.SelectionRangeSlider( options=wtOptions, index=(0,len(wtOptions)-1), description='Weight', disabled=False ) widgetsCtl = widgets.HBox([cylSelect, wtSelect]) # The range of weights needs to always be dependent on the cylinder selection. def updateRange(*args): '''Updates the selection range from the slider depending on the cylinder selection.''' cylValue = cylSelect.value wtOptions = list( np.sort(np.unique(mtcars.loc[mtcars['cyl']==cylValue,'wt'])) ) wtSelect.options = wtOptions wtSelect.index = (0,len(wtOptions)-1) cylSelect.observe(updateRange,'value') # For the widgets to update the same plot, instead of creating one new image every time # a selection changes. We keep track of the matplotlib image and axis, so we create only one # figure and set of axis, for the first plot, and then just re-use the figure and axis # with plotnine's "_draw_using_figure" function. fig = None axs = None # This is the main function that is called to update the plot every time we chage a selection. def plotUpdate(*args): # Use global variables for matplotlib's figure and axis. global fig, axs # Get current values of the selection widgets cylValue = cylSelect.value wrRange = wtSelect.value # Create a temporary dataset that is constrained by the user's selections. tmpDat = mtcars.loc[(mtcars['cyl'] == cylValue) & \ (mtcars['wt'] >= wrRange[0]) & \ (mtcars['wt'] <= wrRange[1]),:] # Create plotnine's plot p = p9.ggplot(tmpDat, p9.aes(x="hp", y="mpg", color="wt")) + \ p9.geom_point() + p9.theme_linedraw() + \ p9.xlim([minHP, maxHP]) + p9.ylim([minMPG, maxMPG]) + \ p9.scale_color_continuous(limits=(minWt, maxWt)) if fig is None: fig, plot = p.draw(return_ggplot=True) axs = plot.axs else: for artist in plt.gca().lines +\ plt.gca().collections +\ plt.gca().artists + plt.gca().patches + plt.gca().texts: artist.remove() p._draw_using_figure(fig, axs) cylSelect.observe(plotUpdate, 'value') wtSelect.observe(plotUpdate, 'value') # Display the widgets display(widgetsCtl) # Plots the first image, with inintial values. plotUpdate() # Matplotlib function to make the image fit within the plot dimensions. plt.tight_layout() # Trick to get the first rendered image to follow the previous "tight_layout" command. # without this, only after the first update would the figure be fit inside its dimensions. cylSelect.value = cylList[0] ``` Finally, we can change some plot properties to make the final figure more understandable. ``` # The first selection is a drop-down menu for number of cylinders cylSelect = widgets.Dropdown( options=list(cylList), value=cylList[1], description='Cylinders:', disabled=False, ) # The second selection is a range of weights wtSelect = widgets.SelectionRangeSlider( options=wtOptions, index=(0,len(wtOptions)-1), description='Weight', disabled=False ) widgetsCtl = widgets.HBox([cylSelect, wtSelect]) # The range of weights needs to always be dependent on the cylinder selection. def updateRange(*args): '''Updates the selection range from the slider depending on the cylinder selection.''' cylValue = cylSelect.value wtOptions = list( np.sort(np.unique(mtcars.loc[mtcars['cyl']==cylValue,'wt'])) ) wtSelect.options = wtOptions wtSelect.index = (0,len(wtOptions)-1) cylSelect.observe(updateRange,'value') fig = None axs = None # This is the main function that is called to update the plot every time we chage a selection. def plotUpdate(*args): # Use global variables for matplotlib's figure and axis. global fig, axs # Get current values of the selection widgets cylValue = cylSelect.value wrRange = wtSelect.value # Create a temporary dataset that is constrained by the user's selections of # number of cylinders and weight. tmpDat = mtcars.loc[(mtcars['cyl'] == cylValue) & \ (mtcars['wt'] >= wrRange[0]) & \ (mtcars['wt'] <= wrRange[1]),:] # Create plotnine's plot showing all data ins smaller grey points, and # the selected data with coloured points. p = p9.ggplot(tmpDat, p9.aes(x="hp", y="mpg", color="wt") ) + \ p9.geom_point(mtcars, p9.aes(x="hp", y="mpg"), color="grey") + \ p9.geom_point(size=3) + p9.theme_linedraw() + \ p9.xlim([minHP, maxHP]) + p9.ylim([minMPG, maxMPG]) + \ p9.scale_color_continuous(name="spring",limits=(np.floor(minWt), np.ceil(maxWt))) +\ p9.labs(x = "Horse-Power", y="Miles Per Gallon", color="Weight" ) if fig is None: fig, plot = p.draw(return_ggplot=True) axs = plot.axs else: for artist in plt.gca().lines +\ plt.gca().collections +\ plt.gca().artists + plt.gca().patches + plt.gca().texts: artist.remove() p._draw_using_figure(fig, axs) cylSelect.observe(plotUpdate, 'value') wtSelect.observe(plotUpdate, 'value') # Display the widgets display(widgetsCtl) # Plots the first image, with inintial values. plotUpdate() # Matplotlib function to make the image fit within the plot dimensions. plt.tight_layout() # Trick to get the first rendered image to follow the previous "tight_layout" command. # without this, only after the first update would the figure be fit inside its dimensions. cylSelect.value = cylList[0] ```
github_jupyter
# Convolutional Neural Networks: Application Welcome to Course 4's second assignment! In this notebook, you will: - Implement helper functions that you will use when implementing a TensorFlow model - Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:** - Build and train a ConvNet in TensorFlow for a classification problem We assume here that you are already familiar with TensorFlow. If you are not, please refer the *TensorFlow Tutorial* of the third week of Course 2 ("*Improving deep neural networks*"). ## 1.0 - TensorFlow model In the previous assignment, you built helper functions using numpy to understand the mechanics behind convolutional neural networks. Most practical applications of deep learning today are built using programming frameworks, which have many built-in functions you can simply call. As usual, we will start by loading in the packages. ``` import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1) ``` Run the next cell to load the "SIGNS" dataset you are going to use. ``` # Loading the data (signs) X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() ``` As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5. <img src="images/SIGNS.png" style="width:800px;height:300px;"> The next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples. ``` # Example of a picture index = 6 plt.imshow(X_train_orig[index]) print ("y = " + str(np.squeeze(Y_train_orig[:, index]))) ``` In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it. To get started, let's examine the shapes of your data. ``` X_train = X_train_orig/255. X_test = X_test_orig/255. 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)) conv_layers = {} ``` ### 1.1 - Create placeholders TensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session. **Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the moment. To do so, you could use "None" as the batch size, it will give you the flexibility to choose it later. Hence X should be of dimension **[None, n_H0, n_W0, n_C0]** and Y should be of dimension **[None, n_y]**. [Hint](https://www.tensorflow.org/api_docs/python/tf/placeholder). ``` # GRADED FUNCTION: create_placeholders def create_placeholders(n_H0, n_W0, n_C0, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_H0 -- scalar, height of an input image n_W0 -- scalar, width of an input image n_C0 -- scalar, number of channels of the input n_y -- scalar, number of classes Returns: X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float" Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float" """ ### START CODE HERE ### (โ‰ˆ2 lines) X = tf.placeholder(tf.float32, shape=(None, n_H0, n_W0, n_C0)) Y = tf.placeholder(tf.float32, shape=(None, n_y)) ### END CODE HERE ### return X, Y X, Y = create_placeholders(64, 64, 3, 6) print ("X = " + str(X)) print ("Y = " + str(Y)) ``` **Expected Output** <table> <tr> <td> X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32) </td> </tr> <tr> <td> Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32) </td> </tr> </table> ### 1.2 - Initialize parameters You will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias variables as you will soon see that TensorFlow functions take care of the bias. Note also that you will only initialize the weights/filters for the conv2d functions. TensorFlow initializes the layers for the fully connected part automatically. We will talk more about that later in this assignment. **Exercise:** Implement initialize_parameters(). The dimensions for each group of filters are provided below. Reminder - to initialize a parameter $W$ of shape [1,2,3,4] in Tensorflow, use: ```python W = tf.get_variable("W", [1,2,3,4], initializer = ...) ``` [More Info](https://www.tensorflow.org/api_docs/python/tf/get_variable). ``` # GRADED FUNCTION: initialize_parameters def initialize_parameters(): """ Initializes weight parameters to build a neural network with tensorflow. The shapes are: W1 : [4, 4, 3, 8] W2 : [2, 2, 8, 16] Returns: parameters -- a dictionary of tensors containing W1, W2 """ tf.set_random_seed(1) # so that your "random" numbers match ours ### START CODE HERE ### (approx. 2 lines of code) W1 = tf.get_variable("W1", [4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0)) W2 = tf.get_variable("W2", [2, 2, 8, 16], initializer = tf.contrib.layers.xavier_initializer(seed = 0)) ### END CODE HERE ### parameters = {"W1": W1, "W2": W2} return parameters tf.reset_default_graph() with tf.Session() as sess_test: parameters = initialize_parameters() init = tf.global_variables_initializer() sess_test.run(init) print("W1 = " + str(parameters["W1"].eval()[1,1,1])) print("W2 = " + str(parameters["W2"].eval()[1,1,1])) ``` ** Expected Output:** <table> <tr> <td> W1 = </td> <td> [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394 <br> -0.06847463 0.05245192] </td> </tr> <tr> <td> W2 = </td> <td> [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058 <br> -0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228 <br> -0.22779644 -0.1601823 -0.16117483 -0.10286498] </td> </tr> </table> ### 1.2 - Forward propagation In TensorFlow, there are built-in functions that carry out the convolution steps for you. - **tf.nn.conv2d(X,W1, strides = [1,s,s,1], padding = 'SAME'):** given an input $X$ and a group of filters $W1$, this function convolves $W1$'s filters on X. The third input ([1,f,f,1]) represents the strides for each dimension of the input (m, n_H_prev, n_W_prev, n_C_prev). You can read the full documentation [here](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d) - **tf.nn.max_pool(A, ksize = [1,f,f,1], strides = [1,s,s,1], padding = 'SAME'):** given an input A, this function uses a window of size (f, f) and strides of size (s, s) to carry out max pooling over each window. You can read the full documentation [here](https://www.tensorflow.org/api_docs/python/tf/nn/max_pool) - **tf.nn.relu(Z1):** computes the elementwise ReLU of Z1 (which can be any shape). You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/nn/relu) - **tf.contrib.layers.flatten(P)**: given an input P, this function flattens each example into a 1D vector it while maintaining the batch-size. It returns a flattened tensor with shape [batch_size, k]. You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/flatten) - **tf.contrib.layers.fully_connected(F, num_outputs):** given a the flattened input F, it returns the output computed using a fully connected layer. You can read the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/fully_connected) In the last function above (`tf.contrib.layers.fully_connected`), the fully connected layer automatically initializes weights in the graph and keeps on training them as you train the model. Hence, you did not need to initialize those weights when initializing the parameters. **Exercise**: Implement the `forward_propagation` function below to build the following model: `CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED`. You should use the functions above. In detail, we will use the following parameters for all the steps: - Conv2D: stride 1, padding is "SAME" - ReLU - Max pool: Use an 8 by 8 filter size and an 8 by 8 stride, padding is "SAME" - Conv2D: stride 1, padding is "SAME" - ReLU - Max pool: Use a 4 by 4 filter size and a 4 by 4 stride, padding is "SAME" - Flatten the previous output. - FULLYCONNECTED (FC) layer: Apply a fully connected layer without an non-linear activation function. Do not call the softmax here. This will result in 6 neurons in the output layer, which then get passed later to a softmax. In TensorFlow, the softmax and cost function are lumped together into a single function, which you'll call in a different function when computing the cost. ``` # GRADED FUNCTION: forward_propagation def forward_propagation(X, parameters): """ Implements the forward propagation for the model: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED Arguments: X -- input dataset placeholder, of shape (input size, number of examples) parameters -- python dictionary containing your parameters "W1", "W2" the shapes are given in initialize_parameters Returns: Z3 -- the output of the last LINEAR unit """ # Retrieve the parameters from the dictionary "parameters" W1 = parameters['W1'] W2 = parameters['W2'] ### START CODE HERE ### # CONV2D: stride of 1, padding 'SAME' Z1 = tf.nn.conv2d(X,W1, strides = [1,1,1,1], padding = 'SAME') # RELU A1 = tf.nn.relu(Z1) # MAXPOOL: window 8x8, sride 8, padding 'SAME' P1 = tf.nn.max_pool(A1, ksize = [1,8,8,1], strides = [1,8,8,1], padding = 'SAME') # CONV2D: filters W2, stride 1, padding 'SAME' Z2 = tf.nn.conv2d(P1, W2, strides = [1,1,1,1], padding = 'SAME') # RELU A2 = tf.nn.relu(Z2) # MAXPOOL: window 4x4, stride 4, padding 'SAME' P2 = tf.nn.max_pool(A2, ksize = [1,4,4,1], strides = [1,4,4,1], padding = 'SAME') # FLATTEN P2 = tf.contrib.layers.flatten(P2) # FULLY-CONNECTED without non-linear activation function (not not call softmax). # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None" Z3 = tf.contrib.layers.fully_connected(P2, 6, activation_fn=None) ### END CODE HERE ### return Z3 tf.reset_default_graph() with tf.Session() as sess: np.random.seed(1) X, Y = create_placeholders(64, 64, 3, 6) parameters = initialize_parameters() Z3 = forward_propagation(X, parameters) init = tf.global_variables_initializer() sess.run(init) a = sess.run(Z3, {X: np.random.randn(2,64,64,3), Y: np.random.randn(2,6)}) print("Z3 = " + str(a)) ``` **Expected Output**: <table> <td> Z3 = </td> <td> [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064] <br> [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]] </td> </table> ### 1.3 - Compute cost Implement the compute cost function below. You might find these two functions helpful: - **tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y):** computes the softmax entropy loss. This function both computes the softmax activation function as well as the resulting loss. You can check the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits) - **tf.reduce_mean:** computes the mean of elements across dimensions of a tensor. Use this to sum the losses over all the examples to get the overall cost. You can check the full documentation [here.](https://www.tensorflow.org/api_docs/python/tf/reduce_mean) ** Exercise**: Compute the cost below using the function above. ``` # GRADED FUNCTION: compute_cost def compute_cost(Z3, Y): """ Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the cost function """ ### START CODE HERE ### (1 line of code) cost = tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y) cost = tf.reduce_mean(cost) ### END CODE HERE ### return cost tf.reset_default_graph() with tf.Session() as sess: np.random.seed(1) X, Y = create_placeholders(64, 64, 3, 6) parameters = initialize_parameters() Z3 = forward_propagation(X, parameters) cost = compute_cost(Z3, Y) init = tf.global_variables_initializer() sess.run(init) a = sess.run(cost, {X: np.random.randn(4,64,64,3), Y: np.random.randn(4,6)}) print("cost = " + str(a)) ``` **Expected Output**: <table> <td> cost = </td> <td> 2.91034 </td> </table> ## 1.4 Model Finally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset. You have implemented `random_mini_batches()` in the Optimization programming assignment of course 2. Remember that this function returns a list of mini-batches. **Exercise**: Complete the function below. The model below should: - create placeholders - initialize parameters - forward propagate - compute the cost - create an optimizer Finally you will create a session and run a for loop for num_epochs, get the mini-batches, and then for each mini-batch you will optimize the function. [Hint for initializing the variables](https://www.tensorflow.org/api_docs/python/tf/global_variables_initializer) ``` # GRADED FUNCTION: model def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009, num_epochs = 100, minibatch_size = 64, print_cost = True): """ Implements a three-layer ConvNet in Tensorflow: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED Arguments: X_train -- training set, of shape (None, 64, 64, 3) Y_train -- test set, of shape (None, n_y = 6) X_test -- training set, of shape (None, 64, 64, 3) Y_test -- test set, of shape (None, n_y = 6) learning_rate -- learning rate of the optimization num_epochs -- number of epochs of the optimization loop minibatch_size -- size of a minibatch print_cost -- True to print the cost every 100 epochs Returns: train_accuracy -- real number, accuracy on the train set (X_train) test_accuracy -- real number, testing accuracy on the test set (X_test) parameters -- parameters learnt by the model. They can then be used to predict. """ ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables tf.set_random_seed(1) # to keep results consistent (tensorflow seed) seed = 3 # to keep results consistent (numpy seed) (m, n_H0, n_W0, n_C0) = X_train.shape n_y = Y_train.shape[1] costs = [] # To keep track of the cost # Create Placeholders of the correct shape ### START CODE HERE ### (1 line) X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y) ### END CODE HERE ### # Initialize parameters ### START CODE HERE ### (1 line) parameters = initialize_parameters() ### END CODE HERE ### # Forward propagation: Build the forward propagation in the tensorflow graph ### START CODE HERE ### (1 line) Z3 = forward_propagation(X, parameters) ### END CODE HERE ### # Cost function: Add cost function to tensorflow graph ### START CODE HERE ### (1 line) cost = compute_cost(Z3, Y) ### END CODE HERE ### # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost. ### START CODE HERE ### (1 line) optimizer = tf.train.AdamOptimizer( learning_rate=learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam' ).minimize(cost) ### END CODE HERE ### # Initialize all the variables globally init = tf.global_variables_initializer() # Start the session to compute the tensorflow graph with tf.Session() as sess: # Run the initialization sess.run(init) # Do the training loop for epoch in range(num_epochs): minibatch_cost = 0. num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set seed = seed + 1 minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed) for minibatch in minibatches: # Select a minibatch (minibatch_X, minibatch_Y) = minibatch # IMPORTANT: The line that runs the graph on a minibatch. # Run the session to execute the optimizer and the cost, the feedict should contain a minibatch for (X,Y). ### START CODE HERE ### (1 line) _ , temp_cost = sess.run((optimizer, cost), feed_dict={X: minibatch_X, Y: minibatch_Y}) ### END CODE HERE ### minibatch_cost += temp_cost / num_minibatches # Print the cost every epoch if print_cost == True and epoch % 5 == 0: print ("Cost after epoch %i: %f" % (epoch, minibatch_cost)) if print_cost == True and epoch % 1 == 0: costs.append(minibatch_cost) # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() # Calculate the correct predictions predict_op = tf.argmax(Z3, 1) correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1)) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print(accuracy) train_accuracy = accuracy.eval({X: X_train, Y: Y_train}) test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) print("Train Accuracy:", train_accuracy) print("Test Accuracy:", test_accuracy) return train_accuracy, test_accuracy, parameters ``` Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code! ``` _, _, parameters = model(X_train, Y_train, X_test, Y_test) ``` **Expected output**: although it may not match perfectly, your expected output should be close to ours and your cost value should decrease. <table> <tr> <td> **Cost after epoch 0 =** </td> <td> 1.917929 </td> </tr> <tr> <td> **Cost after epoch 5 =** </td> <td> 1.506757 </td> </tr> <tr> <td> **Train Accuracy =** </td> <td> 0.940741 </td> </tr> <tr> <td> **Test Accuracy =** </td> <td> 0.783333 </td> </tr> </table> Congratulations! You have finised the assignment and built a model that recognizes SIGN language with almost 80% accuracy on the test set. If you wish, feel free to play around with this dataset further. You can actually improve its accuracy by spending more time tuning the hyperparameters, or using regularization (as this model clearly has a high variance). Once again, here's a thumbs up for your work! ``` fname = "images/thumbs_up.jpg" image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(64,64)) plt.imshow(my_image) ```
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #@title MIT License # # Copyright (c) 2017 Franรงois Chollet # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ``` # ๋ชจ๋ธ ์ €์žฅ๊ณผ ๋ณต์› <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tutorials/keras/save_and_restore_models"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />TensorFlow.org์—์„œ ๋ณด๊ธฐ</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/ko/r2/tutorials/keras/save_and_restore_models.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />๊ตฌ๊ธ€ ์ฝ”๋žฉ(Colab)์—์„œ ์‹คํ–‰ํ•˜๊ธฐ</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/ko/r2/tutorials/keras/save_and_restore_models.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />๊นƒํ—ˆ๋ธŒ(GitHub) ์†Œ์Šค ๋ณด๊ธฐ</a> </td> </table> Note: ์ด ๋ฌธ์„œ๋Š” ํ…์„œํ”Œ๋กœ ์ปค๋ฎค๋‹ˆํ‹ฐ์—์„œ ๋ฒˆ์—ญํ–ˆ์Šต๋‹ˆ๋‹ค. ์ปค๋ฎค๋‹ˆํ‹ฐ ๋ฒˆ์—ญ ํ™œ๋™์˜ ํŠน์„ฑ์ƒ ์ •ํ™•ํ•œ ๋ฒˆ์—ญ๊ณผ ์ตœ์‹  ๋‚ด์šฉ์„ ๋ฐ˜์˜ํ•˜๊ธฐ ์œ„ํ•ด ๋…ธ๋ ฅํ•จ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  [๊ณต์‹ ์˜๋ฌธ ๋ฌธ์„œ](https://www.tensorflow.org/?hl=en)์˜ ๋‚ด์šฉ๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ฒˆ์—ญ์— ๊ฐœ์„ ํ•  ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด [tensorflow/docs](https://github.com/tensorflow/docs) ๊นƒํ—™ ์ €์žฅ์†Œ๋กœ ํ’€ ๋ฆฌํ€˜์ŠคํŠธ๋ฅผ ๋ณด๋‚ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ๋ฌธ์„œ ๋ฒˆ์—ญ์ด๋‚˜ ๋ฆฌ๋ทฐ์— ์ง€์›ํ•˜๋ ค๋ฉด [์ด ์–‘์‹](https://bit.ly/tf-translate)์„ ์ž‘์„ฑํ•˜๊ฑฐ๋‚˜ [docs@tensorflow.org](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs)๋กœ ๋ฉ”์ผ์„ ๋ณด๋‚ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค. ํ›ˆ๋ จํ•˜๋Š” ๋„์ค‘์ด๋‚˜ ํ›ˆ๋ จ์ด ๋๋‚œ ํ›„์— ๋ชจ๋ธ์„ ์ €์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ชจ๋ธ์„ ์ค‘์ง€๋œ ์ง€์ ๋ถ€ํ„ฐ ๋‹ค์‹œ ํ›ˆ๋ จํ•  ์ˆ˜ ์žˆ์–ด ํ•œ ๋ฒˆ์— ์˜ค๋žซ๋™์•ˆ ํ›ˆ๋ จํ•˜์ง€ ์•Š์•„๋„ ๋ฉ๋‹ˆ๋‹ค. ๋˜ ๋ชจ๋ธ์„ ์ €์žฅํ•˜๋ฉด ๋‹ค๋ฅธ ์‚ฌ๋žŒ์—๊ฒŒ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ๊ณ  ์ž‘์—…์„ ์žฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์—ฐ๊ตฌํ•œ ๋ชจ๋ธ๊ณผ ๊ธฐ๋ฒ•์„ ๊ณต๊ฐœํ•  ๋•Œ ๋งŽ์€ ๋จธ์‹  ๋Ÿฌ๋‹ ๊ธฐ์ˆ ์ž๋“ค์ด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒƒ๋“ค์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค: * ๋ชจ๋ธ์„ ๋งŒ๋“œ๋Š” ์ฝ”๋“œ * ๋ชจ๋ธ์˜ ํ›ˆ๋ จ๋œ ๊ฐ€์ค‘์น˜ ๋˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ ์ด๋Ÿฐ ๋ฐ์ดํ„ฐ๋ฅผ ๊ณต์œ ํ•˜๋ฉด ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์ด ๋ชจ๋ธ์˜ ์ž‘๋™ ๋ฐฉ์‹์„ ์ดํ•ดํ•˜๊ณ  ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋กœ ๋ชจ๋ธ์„ ์‹คํ—˜ํ•˜๋Š”๋ฐ ๋„์›€์ด ๋ฉ๋‹ˆ๋‹ค. ์ฃผ์˜: ์‹ ๋ขฐํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋“œ๋Š” ์กฐ์‹ฌํ•˜์„ธ์š”. ํ…์„œํ”Œ๋กœ ๋ชจ๋ธ์€ ํ”„๋กœ๊ทธ๋žจ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค. ์ž์„ธํ•œ ๋‚ด์šฉ์€ [ํ…์„œํ”Œ๋กœ๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๊ธฐ](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”. ### ์ €์žฅ ๋ฐฉ์‹ ์‚ฌ์šฉํ•˜๋Š” API์— ๋”ฐ๋ผ์„œ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์œผ๋กœ ํ…์„œํ”Œ๋กœ ๋ชจ๋ธ์„ ์ €์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ฌธ์„œ๋Š” ํ…์„œํ”Œ๋กœ ๋ชจ๋ธ์„ ๋งŒ๋“ค๊ณ  ํ›ˆ๋ จํ•˜๊ธฐ ์œ„ํ•œ ๊ณ ์ˆ˜์ค€ API์ธ [tf.keras](https://www.tensorflow.org/guide/keras)๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•๋“ค์— ๋Œ€ํ•ด์„œ๋Š” ํ…์„œํ”Œ๋กœ์˜ [์ €์žฅ๊ณผ ๋ณต์›](https://www.tensorflow.org/guide/saved_model) ๋ฌธ์„œ์™€ ์ฆ‰์‹œ ์‹คํ–‰(eager execution) ๋ฌธ์„œ์˜ [์ €์žฅํ•˜๊ธฐ](https://www.tensorflow.org/guide/eager#object-based_saving) ์„น์…˜์„ ์ฐธ๊ณ ํ•˜์„ธ์š”. ## ์„ค์ • ### ์„ค์น˜์™€ ์ž„ํฌํŠธ ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์„ค์น˜ํ•˜๊ณ  ํ…์„œํ”Œ๋กœ๋ฅผ ์ž„ํฌํŠธ(import)ํ•ฉ๋‹ˆ๋‹ค: ``` !pip install h5py pyyaml ``` ### ์˜ˆ์ œ ๋ฐ์ดํ„ฐ์…‹ ๋ฐ›๊ธฐ [MNIST ๋ฐ์ดํ„ฐ์…‹](http://yann.lecun.com/exdb/mnist/)์œผ๋กœ ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•˜์—ฌ ๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•˜๋Š” ์˜ˆ์ œ๋ฅผ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๋ชจ๋ธ ์‹คํ–‰ ์†๋„๋ฅผ ๋น ๋ฅด๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ์ƒ˜ํ”Œ์—์„œ ์ฒ˜์Œ 1,000๊ฐœ๋งŒ ์‚ฌ์šฉ๊ฒ ์Šต๋‹ˆ๋‹ค: ``` from __future__ import absolute_import, division, print_function, unicode_literals import os !pip install tf-nightly-2.0-preview import tensorflow as tf from tensorflow import keras tf.__version__ (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() train_labels = train_labels[:1000] test_labels = test_labels[:1000] train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0 test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0 ``` ### ๋ชจ๋ธ ์ •์˜ ๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•˜๊ณ  ๋ถˆ๋Ÿฌ์˜ค๋Š” ์˜ˆ์ œ๋ฅผ ์œ„ํ•ด ๊ฐ„๋‹จํ•œ ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ๋ณด์ฃ . ``` # ๊ฐ„๋‹จํ•œ Sequential ๋ชจ๋ธ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค def create_model(): model = tf.keras.models.Sequential([ keras.layers.Dense(512, activation='relu', input_shape=(784,)), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) return model # ๋ชจ๋ธ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค model = create_model() model.summary() ``` ## ํ›ˆ๋ จํ•˜๋Š” ๋™์•ˆ ์ฒดํฌํฌ์ธํŠธ ์ €์žฅํ•˜๊ธฐ *ํ›ˆ๋ จ ์ค‘๊ฐ„*๊ณผ *ํ›ˆ๋ จ ๋งˆ์ง€๋ง‰*์— ์ฒดํฌํฌ์ธํŠธ(checkpoint)๋ฅผ ์ž๋™์œผ๋กœ ์ €์žฅํ•˜๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ›ˆ๋ จํ•˜์ง€ ์•Š๊ณ  ๋ชจ๋ธ์„ ์žฌ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ํ›ˆ๋ จ ๊ณผ์ •์ด ์ค‘์ง€๋œ ๊ฒฝ์šฐ ์ด์–ด์„œ ํ›ˆ๋ จ์„ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. `tf.keras.callbacks.ModelCheckpoint`์€ ์ด๋Ÿฐ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์ฝœ๋ฐฑ(callback)์ž…๋‹ˆ๋‹ค. ์ด ์ฝœ๋ฐฑ์€ ์ฒดํฌํฌ์ธํŠธ ์ž‘์—…์„ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ๋„๋ก ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ### ์ฒดํฌํฌ์ธํŠธ ์ฝœ๋ฐฑ ์‚ฌ์šฉํ•˜๊ธฐ `ModelCheckpoint` ์ฝœ๋ฐฑ์„ ์ „๋‹ฌํ•˜์—ฌ ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•ด ๋ณด์ฃ : ``` checkpoint_path = "training_1/cp.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) # ์ฒดํฌํฌ์ธํŠธ ์ฝœ๋ฐฑ ๋งŒ๋“ค๊ธฐ cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1) model = create_model() model.fit(train_images, train_labels, epochs = 10, validation_data = (test_images,test_labels), callbacks = [cp_callback]) # ํ›ˆ๋ จ ๋‹จ๊ณ„์— ์ฝœ๋ฐฑ์„ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค # ์˜ตํ‹ฐ๋งˆ์ด์ €์˜ ์ƒํƒœ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ๊ณผ ๊ด€๋ จ๋˜์–ด ๊ฒฝ๊ณ ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. # ์ด ๊ฒฝ๊ณ ๋Š” (๊ทธ๋ฆฌ๊ณ  ์ด ๋…ธํŠธ๋ถ์˜ ๋‹ค๋ฅธ ๋น„์Šทํ•œ ๊ฒฝ๊ณ ๋Š”) ์ด์ „ ์‚ฌ์šฉ ๋ฐฉ์‹์„ ๊ถŒ์žฅํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•จ์ด๋ฉฐ ๋ฌด์‹œํ•ด๋„ ์ข‹์Šต๋‹ˆ๋‹ค. ``` ์ด ์ฝ”๋“œ๋Š” ํ…์„œํ”Œ๋กœ ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ์„ ๋งŒ๋“ค๊ณ  ์—ํฌํฌ๊ฐ€ ์ข…๋ฃŒ๋  ๋•Œ๋งˆ๋‹ค ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค: ``` !ls {checkpoint_dir} ``` ํ›ˆ๋ จํ•˜์ง€ ์•Š์€ ์ƒˆ๋กœ์šด ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ฐ€์ค‘์น˜๋งŒ ๋ณต์›ํ•  ๋• ์›๋ณธ ๋ชจ๋ธ๊ณผ ๋™์ผํ•œ ๊ตฌ์กฐ๋กœ ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ๋Š” ๋™์ผํ•œ ๊ตฌ์กฐ๋กœ ๋ชจ๋ธ์„ ๋งŒ๋“ค์—ˆ์œผ๋ฏ€๋กœ ๋‹ค๋ฅธ *๊ฐ์ฒด*์ด์ง€๋งŒ ๊ฐ€์ค‘์น˜๋ฅผ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ›ˆ๋ จํ•˜์ง€ ์•Š์€ ์ƒˆ ๋ชจ๋ธ์„ ๋งŒ๋“ค๊ณ  ํ…Œ์ŠคํŠธ ์„ธํŠธ์—์„œ ํ‰๊ฐ€ํ•ด ๋ณด์ฃ . ํ›ˆ๋ จ๋˜์ง€ ์•Š์€ ๋ชจ๋ธ์˜ ์„ฑ๋Šฅ์€ ๋ฌด์ž‘์œ„๋กœ ์„ ํƒํ•˜๋Š” ์ •๋„์˜ ์ˆ˜์ค€์ž…๋‹ˆ๋‹ค(~10% ์ •ํ™•๋„): ``` model = create_model() loss, acc = model.evaluate(test_images, test_labels) print("ํ›ˆ๋ จ๋˜์ง€ ์•Š์€ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ์ฒดํฌํฌ์ธํŠธ์—์„œ ๊ฐ€์ค‘์น˜๋ฅผ ๋กœ๋“œํ•˜๊ณ  ๋‹ค์‹œ ํ‰๊ฐ€ํ•ด ๋ณด์ฃ : ``` model.load_weights(checkpoint_path) loss,acc = model.evaluate(test_images, test_labels) print("๋ณต์›๋œ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ### ์ฒดํฌํฌ์ธํŠธ ์ฝœ๋ฐฑ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ด ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋Š” ๋ช‡ ๊ฐ€์ง€ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ์ฒดํฌํฌ์ธํŠธ ์ด๋ฆ„์„ ๊ณ ์œ ํ•˜๊ฒŒ ๋งŒ๋“ค๊ฑฐ๋‚˜ ์ฒดํฌํฌ์ธํŠธ ์ฃผ๊ธฐ๋ฅผ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ƒˆ๋กœ์šด ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•˜๊ณ  ๋‹ค์„ฏ ๋ฒˆ์˜ ์—ํฌํฌ๋งˆ๋‹ค ๊ณ ์œ ํ•œ ์ด๋ฆ„์œผ๋กœ ์ฒดํฌํฌ์ธํŠธ๋ฅผ ์ €์žฅํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค: ``` # ํŒŒ์ผ ์ด๋ฆ„์— ์—ํฌํฌ ๋ฒˆํ˜ธ๋ฅผ ํฌํ•จ์‹œํ‚ต๋‹ˆ๋‹ค(`str.format` ํฌ๋งท) checkpoint_path = "training_2/cp-{epoch:04d}.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) cp_callback = tf.keras.callbacks.ModelCheckpoint( checkpoint_path, verbose=1, save_weights_only=True, # ๋‹ค์„ฏ ๋ฒˆ์งธ ์—ํฌํฌ๋งˆ๋‹ค ๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค period=5) model = create_model() model.save_weights(checkpoint_path.format(epoch=0)) model.fit(train_images, train_labels, epochs = 50, callbacks = [cp_callback], validation_data = (test_images,test_labels), verbose=0) ``` ๋งŒ๋“ค์–ด์ง„ ์ฒดํฌํฌ์ธํŠธ๋ฅผ ํ™•์ธํ•ด ๋ณด๊ณ  ๋งˆ์ง€๋ง‰ ์ฒดํฌํฌ์ธํŠธ๋ฅผ ์„ ํƒํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค: ``` ! ls {checkpoint_dir} latest = tf.train.latest_checkpoint(checkpoint_dir) latest ``` ๋…ธํŠธ: ํ…์„œํ”Œ๋กœ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ตœ๊ทผ 5๊ฐœ์˜ ์ฒดํฌํฌ์ธํŠธ๋งŒ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋ธ์„ ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ์ตœ๊ทผ ์ฒดํฌํฌ์ธํŠธ๋ฅผ ๋กœ๋“œํ•˜์—ฌ ํ…Œ์ŠคํŠธํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค: ``` model = create_model() model.load_weights(latest) loss, acc = model.evaluate(test_images, test_labels) print("๋ณต์›๋œ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ## ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ์œ„ ์ฝ”๋“œ๋Š” ๊ฐ€์ค‘์น˜๋ฅผ ์ผ๋ จ์˜ [์ฒดํฌํฌ์ธํŠธ](https://www.tensorflow.org/guide/saved_model#save_and_restore_variables) ํฌ๋งท์˜ ํŒŒ์ผ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ์ด ํŒŒ์ผ์— ํฌํ•จ๋˜๋Š” ๊ฒƒ์€ ํ›ˆ๋ จ๋œ ์ด์ง„ ํฌ๋งท์˜ ๊ฐ€์ค‘์น˜์ž…๋‹ˆ๋‹ค. ์ฒดํฌํฌ์ธํŠธ๊ฐ€ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฒƒ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค: * ๋ชจ๋ธ์˜ ๊ฐ€์ค‘์น˜๋ฅผ ํฌํ•จํ•˜๋Š” ํ•˜๋‚˜ ์ด์ƒ์˜ ์ƒค๋“œ(shard) * ๊ฐ€์ค‘์น˜๊ฐ€ ์–ด๋А ์ƒค๋“œ์— ์ €์žฅ๋˜์–ด ์žˆ๋Š”์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ธ๋ฑ์Šค ํŒŒ์ผ ๋‹จ์ผ ๋จธ์‹ ์—์„œ ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•œ๋‹ค๋ฉด `.data-00000-of-00001` ํ™•์žฅ์ž๋ฅผ ๊ฐ€์ง„ ์ƒค๋“œ ํ•˜๋‚˜๋งŒ ๋งŒ๋“ค์–ด ์ง‘๋‹ˆ๋‹ค. ## ์ˆ˜๋™์œผ๋กœ ๊ฐ€์ค‘์น˜ ์ €์žฅํ•˜๊ธฐ ์•ž์—์„œ ๊ฐ€์ค‘์น˜๋ฅผ ๋ชจ๋ธ์— ๋กœ๋“œํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ณด์•˜์Šต๋‹ˆ๋‹ค. ์ˆ˜๋™์œผ๋กœ ๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ๋„ ์‰ฝ์Šต๋‹ˆ๋‹ค. `Model.save_weights` ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ``` # ๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค model.save_weights('./checkpoints/my_checkpoint') # ๊ฐ€์ค‘์น˜๋ฅผ ๋ณต์›ํ•ฉ๋‹ˆ๋‹ค model = create_model() model.load_weights('./checkpoints/my_checkpoint') loss,acc = model.evaluate(test_images, test_labels) print("๋ณต์›๋œ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ## ๋ชจ๋ธ ์ „์ฒด๋ฅผ ์ €์žฅํ•˜๊ธฐ ์ „์ฒด ๋ชจ๋ธ์„ ํŒŒ์ผ ํ•˜๋‚˜์— ์ €์žฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์—๋Š” ๊ฐ€์ค‘์น˜, ๋ชจ๋ธ ๊ตฌ์„ฑ ์‹ฌ์ง€์–ด ์˜ตํ‹ฐ๋งˆ์ด์ €์— ์ง€์ •ํ•œ ์„ค์ •๊นŒ์ง€ ํฌํ•จ๋ฉ๋‹ˆ๋‹ค. ๋ชจ๋ธ์˜ ์ฒดํฌํฌ์ธํŠธ๋ฅผ ์ €์žฅํ•˜๋ฏ€๋กœ ์›๋ณธ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‚˜์ค‘์— ์ •ํ™•ํžˆ ๋™์ผํ•œ ์ƒํƒœ์—์„œ ํ›ˆ๋ จ์„ ๋‹ค์‹œ ์‹œ์ž‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ „์ฒด ๋ชจ๋ธ์„ ์ €์žฅํ•˜๋Š” ๊ธฐ๋Šฅ์€ ๋งค์šฐ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค. TensorFlow.js๋กœ ๋ชจ๋ธ์„ ๋กœ๋“œํ•œ ๋‹ค์Œ ์›น ๋ธŒ๋ผ์šฐ์ €์—์„œ ๋ชจ๋ธ์„ ํ›ˆ๋ จํ•˜๊ณ  ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค([HDF5](https://js.tensorflow.org/tutorials/import-keras.html), [Saved Model](https://js.tensorflow.org/tutorials/import-saved-model.html)). ๋˜๋Š” ๋ชจ๋ฐ”์ผ ์žฅ์น˜์— ๋งž๋„๋ก ๋ณ€ํ™˜ํ•œ ๋‹ค์Œ TensorFlow Lite๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค([HDF5](https://www.tensorflow.org/lite/convert/python_api#exporting_a_tfkeras_file_), [Saved Model](https://www.tensorflow.org/lite/convert/python_api#exporting_a_savedmodel_)). ### HDF5 ํŒŒ์ผ๋กœ ์ €์žฅํ•˜๊ธฐ ์ผ€๋ผ์Šค๋Š” [HDF5](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) ํ‘œ์ค€์„ ๋”ฐ๋ฅด๋Š” ๊ธฐ๋ณธ ์ €์žฅ ํฌ๋งท์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ์ €์žฅ๋œ ๋ชจ๋ธ์„ ํ•˜๋‚˜์˜ ์ด์ง„ ํŒŒ์ผ(binary blob)์ฒ˜๋Ÿผ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ``` model = create_model() model.fit(train_images, train_labels, epochs=5) # ์ „์ฒด ๋ชจ๋ธ์„ HDF5 ํŒŒ์ผ๋กœ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค model.save('my_model.h5') ``` ์ด์ œ ์ด ํŒŒ์ผ๋กœ๋ถ€ํ„ฐ ๋ชจ๋ธ์„ ๋‹ค์‹œ ๋งŒ๋“ค์–ด ๋ณด์ฃ : ``` # ๊ฐ€์ค‘์น˜์™€ ์˜ตํ‹ฐ๋งˆ์ด์ €๋ฅผ ํฌํ•จํ•˜์—ฌ ์ •ํ™•ํžˆ ๋™์ผํ•œ ๋ชจ๋ธ์„ ๋‹ค์‹œ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค new_model = keras.models.load_model('my_model.h5') new_model.summary() ``` ์ •ํ™•๋„๋ฅผ ํ™•์ธํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค: ``` loss, acc = new_model.evaluate(test_images, test_labels) print("๋ณต์›๋œ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ์ด ๊ธฐ๋ฒ•์€ ๋ชจ๋“  ๊ฒƒ์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค: * ๊ฐ€์ค‘์น˜ ๊ฐ’ * ๋ชจ๋ธ ์„ค์ •(๊ตฌ์กฐ) * ์˜ตํ‹ฐ๋งˆ์ด์ € ์„ค์ • ์ผ€๋ผ์Šค๋Š” ๋ชจ๋ธ ๊ตฌ์กฐ๋ฅผ ํ™•์ธํ•˜๊ณ  ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ํ˜„์žฌ๋Š” ํ…์„œํ”Œ๋กœ ์˜ตํ‹ฐ๋งˆ์ด์ €(`tf.train`)๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” ๋ชจ๋ธ์„ ๋กœ๋“œํ•œ ํ›„์— ๋‹ค์‹œ ์ปดํŒŒ์ผํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ตํ‹ฐ๋งˆ์ด์ €์˜ ์ƒํƒœ๋Š” ์œ ์ง€๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ### `saved_model`์„ ์‚ฌ์šฉํ•˜๊ธฐ ์ฃผ์˜: `tf.keras` ๋ชจ๋ธ์„ ์ €์žฅํ•˜๋Š” ์ด ๋ฉ”์„œ๋“œ๋Š” ์‹คํ—˜์ ์ด๋ฏ€๋กœ ํ–ฅํ›„ ๋ฒ„์ „์—์„œ ๋ณ€๊ฒฝ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ƒˆ๋กœ์šด ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค: ``` model = create_model() model.fit(train_images, train_labels, epochs=5) ``` `saved_model`์„ ๋งŒ๋“ค์–ด ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ์ด๋ฆ„์œผ๋กœ ๊ฐ€์ง„ ๋””๋ ‰ํ† ๋ฆฌ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค: ``` import time saved_model_path = "./saved_models/{}".format(int(time.time())) tf.keras.experimental.export_saved_model(model, saved_model_path) saved_model_path ``` ์ €์žฅ๋œ ๋ชจ๋ธ์˜ ๋ชฉ๋ก์„ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค: ``` !ls saved_models/ ``` ์ €์žฅ๋œ ๋ชจ๋ธ๋กœ๋ถ€ํ„ฐ ์ƒˆ๋กœ์šด ์ผ€๋ผ์Šค ๋ชจ๋ธ์„ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค. ``` new_model = tf.keras.experimental.load_from_saved_model(saved_model_path) new_model.summary() ``` ๋ณต์›๋œ ๋ชจ๋ธ์„ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. ``` model.predict(test_images).shape # ์ด ๋ชจ๋ธ์„ ํ‰๊ฐ€ํ•˜๋ ค๋ฉด ๊ทธ์ „์— ์ปดํŒŒ์ผํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. # ๋‹จ์ง€ ์ €์žฅ๋œ ๋ชจ๋ธ์˜ ๋ฐฐํฌ๋ผ๋ฉด ์ด ๋‹จ๊ณ„๊ฐ€ ํ•„์š”ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. new_model.compile(optimizer=model.optimizer, # ๋ณต์›๋œ ์˜ตํ‹ฐ๋งˆ์ด์ €๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. loss='sparse_categorical_crossentropy', metrics=['accuracy']) # ๋ณต์›๋œ ๋ชจ๋ธ์„ ํ‰๊ฐ€ํ•ฉ๋‹ˆ๋‹ค loss, acc = new_model.evaluate(test_images, test_labels) print("๋ณต์›๋œ ๋ชจ๋ธ์˜ ์ •ํ™•๋„: {:5.2f}%".format(100*acc)) ``` ## ๊ทธ ๋‹ค์Œ์—” ์ด ๋ฌธ์„œ์—์„œ๋Š” `tf.keras`๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ชจ๋ธ์„ ์ €์žฅํ•˜๊ณ  ๋กœ๋“œํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๊ฐ„๋‹จํ•˜๊ฒŒ ์•ˆ๋‚ดํ–ˆ์Šต๋‹ˆ๋‹ค. * [tf.keras ๊ฐ€์ด๋“œ](https://www.tensorflow.org/guide/keras)์—์„œ `tf.keras`๋กœ ๋ชจ๋ธ์„ ์ €์žฅํ•˜๊ณ  ๋กœ๋“œํ•˜๋Š” ์ •๋ณด๋ฅผ ๋” ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์ฆ‰์‹œ ์‹คํ–‰ ๋ชจ๋“œ์—์„œ ๋ชจ๋ธ์„ ์ €์žฅํ•˜๋ ค๋ฉด [์ฆ‰์‹œ ์‹คํ–‰์—์„œ ์ €์žฅํ•˜๊ธฐ](https://www.tensorflow.org/guide/eager#object_based_saving) ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”. * [์ €์žฅ๊ณผ ๋ณต์›](https://www.tensorflow.org/guide/saved_model) ๋ฌธ์„œ๋Š” ์ €์ˆ˜์ค€์˜ ํ…์„œํ”Œ๋กœ ์ €์žฅ ๊ธฐ๋Šฅ์— ๋Œ€ํ•ด ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค.
github_jupyter
![ ](https://www.pon-cat.com/application/files/7915/8400/2602/home-banner.jpg) # <center> **Data Visualization and Exploratory Data Analysis** </center> Visualization is an important part of data analysis. By presenting information visually, you facilitate the process of its perception, which makes it possible to highlight additional patterns, evaluate the ratios of quantities, and quickly communicate key aspects in the data. Let's start with a little "memo" that should always be kept in mind when creating any graphs. ### <center> How to visualize data and make everyone hate you </center> 1. Chart **titles** are unnecessary. It is always clear from the graph what data it describes. 2. Do not label under any circumstances both **axes** of the graph. Let the others check their intuition! 3. **Units** are optional. What difference does it make if the quantity was measured, in people or in liters! 4. The smaller the **text** on the graph, the sharper the viewer's eyesight. 5. You should try to fit all the **information** that you have in the dataset in one chart. With full titles, transcripts, footnotes. The more text, the more informative! 6. Whenever possible, use as many 3D and special effects as you have. There will be less visual distortion rather than 2D. As an example, consider the pandemic case. Let's use a dataset with promptly updated statistics on coronavirus (COVID-19), which is publicly available on Kaggle: https://www.kaggle.com/imdevskp/corona-virus-report?select=covid_19_clean_complete.csv The main libraries for visualization in Python that we need today are **matplotlib, seaborn, plotly**. ``` # Download required binded packages !pip install plotly-express !pip install nbformat==4.2.0 !pip install plotly import matplotlib.pyplot as plt %matplotlib inline import numpy as np import seaborn as sns import pandas as pd import pickle # for JSON serialization import plotly import plotly_express as px import plotly.graph_objects as go from plotly.subplots import make_subplots from plotly.offline import init_notebook_mode init_notebook_mode(connected=True) %config InlineBackend.figure_format = 'svg' # graphs in svg look sharper # Change the default plot size from pylab import rcParams rcParams['figure.figsize'] = 7, 5 import warnings warnings.filterwarnings('ignore') ``` We read the data and look at the number of countries in the dataset and what time period it covers. ``` data = pd.read_csv('./data/covid_19_clean.csv') data.head(10) ``` How many countries there are in this table? ``` data['Country/Region'].nunique() data.shape data.describe() data.describe(include=['object']) ``` How many cases in average were confirmed per report? Metrics of centrality: ``` data['Confirmed'].mode() data['Confirmed'].median() data['Confirmed'].mean() ``` What is the maximum number of confirmed cases in every country? ``` data.groupby('Country/Region')['Confirmed'].agg(max) data.groupby('Country/Region')['Confirmed'].max().sort_values(ascending=False) ``` More info on groupby: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html * **mean()**: Compute mean of groups * **sum()**: Compute sum of group values * **size()**: Compute group sizes * **count()**: Compute count of group * **std()**: Standard deviation of groups * **var()**: Compute variance of groups * **sem()**: Standard error of the mean of groups * **describe()**: Generates descriptive statistics * **first()**: Compute first of group values * **last()**: Compute last of group values * **nth()** : Take nth value, or a subset if n is a list * **min()**: Compute min of group values * **max()**: Compute max of group values You can see several characteristics at once (mean, median, prod, sum, std, var) - both in DataFrame and Series: ``` data.groupby('Country/Region')['Confirmed'].agg(['mean', 'median', 'std']) data.pivot_table(columns='WHO Region', index='Date', values='Confirmed', aggfunc='sum') data['Active'] > 0 data[ data['WHO Region'] == 'Western Pacific']['Country/Region'].unique() data[(data['WHO Region'] == 'Western Pacific') & (data['Confirmed'] > data.Confirmed.mean())] data[(data['WHO Region'] == 'Western Pacific') & (data['Confirmed'] > data.Confirmed.mean())]['Country/Region'].unique() some_countries = ['China', 'Singapore', 'Philippines', 'Japan'] data[data['Country/Region'].isin(some_countries)].head(10) ``` Let's make a small report: ``` data = pd.read_csv('./data/covid_19_clean.csv') print("Number of countries: ", data['Country/Region'].nunique()) print(f"Day from {min(data['Date'])} till {max(data['Date'])}, overall {data['Date'].nunique()} days.") data['Date'] = pd.to_datetime(data['Date'], format = '%Y-%m-%d') display(data[data['Country/Region'] == 'Russia'].tail()) ``` The coronavirus pandemic is a clear example of an exponential distribution. To demonstrate this, let's build a graph of the total number of infected and dead. We will use a linear chart type (** Line Chart **), which can reflect the dynamics of one or several indicators. It is convenient to use it to see how a value changes over time. ``` # Line chart ax = data[['Confirmed', 'Deaths', 'Date']].groupby('Date').sum().plot(title='Title') ax.set_xlabel("X axes") ax.set_ylabel("Y axes"); # TODO # Change the title and axes names ``` The graph above shows us general information around the world. Let's select the 10 most affected countries (based on the results of the last day from the dataset) and on one **Line Chart** show data for each of them according to the number of registered cases of the disease. This time, let's try using the **plotly** library. ``` # Preparation steps fot the table # Extract the top 10 countries by the number of confirmed cases df_top = data[data['Date'] == max(data.Date)] df_top = df_top.groupby('Country/Region', as_index=False)['Confirmed'].sum() df_top = df_top.nlargest(10,'Confirmed') # Extract trend across time df_trend = data.groupby(['Date','Country/Region'], as_index=False)['Confirmed'].sum() df_trend = df_trend.merge(df_top, on='Country/Region') df_trend.rename(columns={'Country/Region' : 'Countries', 'Confirmed_x':'Cases', 'Date' : 'Dates'}, inplace=True) # Plot a graph # px stands for plotly_express px.line(df_trend, title='Increased number of cases of COVID-19', x='Dates', y='Cases', color='Countries') ``` Let's put a logarithm on this column. ``` # Add a column to visualize the logarithmic df_trend['ln(Cases)'] = np.log(df_trend['Cases'] + 1) # Add 1 for log (0) case px.line(df_trend, x='Dates', y='ln(Cases)', color='Countries', title='COVID19 Total Cases growth for top 10 worst affected countries(Logarithmic Scale)') ``` What interesting conclusions can you draw from this graph? Try to do similar graphs for the deaths and active cases. ``` # TODO ``` Another popular chart is the **Pie chart**. Most often, this graph is used to visualize the relationship between parts (ratios). ``` # Pie chart fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]]) labels_donut = [country for country in df_top['Country/Region']] fig.add_trace(go.Pie(labels=labels_donut, hole=.4, hoverinfo="label+percent+name", values=[cases for cases in df_top.Confirmed], name="Ratio", ), 1, 1) labels_pie = [country for country in df_top['Country/Region']] fig.add_trace(go.Pie(labels=labels_pie, pull=[0, 0, 0.2, 0], values=[cases for cases in df_top.Confirmed], name="Ratio"), 1, 2) fig.update_layout( title_text="Donut & Pie Chart: Distribution of COVID-19 cases among the top-10 affected countries", # Add annotations in the center of the donut pies. annotations=[dict(text=' ', x=0.5, y=0.5, font_size=16, showarrow=False)], colorway=['rgb(69, 135, 24)', 'rgb(136, 204, 41)', 'rgb(204, 204, 41)', 'rgb(235, 210, 26)', 'rgb(209, 156, 42)', 'rgb(209, 86, 42)', 'rgb(209, 42, 42)', ]) fig.show() ``` In the line graphs above, we have visualized aggregate country information by the number of cases detected. Now, let's try to plot a daily trend chart by calculating the difference between the current value and the previous day's value. For this purpose, we will use a histogram (**Histogram**). Also, let's add pointers to key events, for example, lockdown dates in Wuhan province in China, Italy and the UK. ``` # Histogram def add_daily_diffs(df): # 0 because the previous value is unknown df.loc[0,'Cases_daily'] = 0 df.loc[0,'Deaths_daily'] = 0 for i in range(1, len(df)): df.loc[i,'Cases_daily'] = df.loc[i,'Confirmed'] - df.loc[i - 1,'Confirmed'] df.loc[i,'Deaths_daily'] = df.loc[i,'Deaths'] - df.loc[i - 1,'Deaths'] return df df_world = data.groupby('Date', as_index=False)['Deaths', 'Confirmed'].sum() df_world = add_daily_diffs(df_world) fig = go.Figure(data=[ go.Bar(name='The number of cases', marker={'color': 'rgb(0,100,153)'}, x=df_world.Date, y=df_world.Cases_daily), go.Bar(name='The number of cases', x=df_world.Date, y=df_world.Deaths_daily) ]) fig.update_layout(barmode='overlay', title='Statistics on the number of Confirmed and Deaths from COVID-19 across the world', annotations=[dict(x='2020-01-23', y=1797, text="Lockdown (Wuhan)", showarrow=True, arrowhead=1, ax=-100, ay=-200), dict(x='2020-03-09', y=1797, text="Lockdown (Italy)", showarrow=True, arrowhead=1, ax=-100, ay=-200), dict(x='2020-03-23', y=19000, text="Lockdown (UK)", showarrow=True, arrowhead=1, ax=-100, ay=-200)]) fig.show() # Save plotly.offline.plot(fig, filename='my_beautiful_histogram.html', show_link=False) ``` A histogram is often mistaken for a bar chart due to its visual similarity, but these charts have different purposes. The bar graph shows how the data is distributed over a continuous interval or a specific period of time. Frequency is located along the vertical axis of the histogram, intervals or some time period along the horizontal axis. Let's build the **Bar Chart** now. It can be vertical and horizontal, let's choose the second option. Let's build a graph only for the top 20 countries in mortality. We will calculate this statistics as the ratio of the number of deaths to the number of confirmed cases for each country. For some countries in the dataset, statistics are presented for each region (for example, for all US states). For such countries, we will leave only one (maximum) value. Alternatively, one could calculate the average for the regions and leave it as an indicator for the country. ``` # Bar chart df_mortality = data.query('(Date == "2020-07-17") & (Confirmed > 100)') df_mortality['mortality'] = df_mortality['Deaths'] / df_mortality['Confirmed'] df_mortality['mortality'] = df_mortality['mortality'].apply(lambda x: round(x, 3)) df_mortality.sort_values('mortality', ascending=False, inplace=True) # Keep the maximum mortality rate for countries for which statistics are provided for each region. df_mortality.drop_duplicates(subset=['Country/Region'], keep='first', inplace=True) fig = px.bar(df_mortality[:20].iloc[::-1], x='mortality', y='Country/Region', labels={'mortality': 'Death rate', 'Country\Region': 'Country'}, title=f'Death rate: top-20 affected countries on 2020-07-17', text='mortality', height=800, orientation='h') # ะณะพั€ะธะทะพะฝั‚ะฐะปัŒะฝั‹ะน fig.show() # TODO: ั€ะฐัะบั€ะฐัะธั‚ัŒ ัั‚ะพะปะฑั†ั‹ ะฟะพ ั‚ะตะฟะปะพะฒะพะน ะบะฐั€ั‚ะต (ะธัะฟะพะปัŒะทัƒั ัƒั€ะพะฒะตะฝัŒ ัะผะตั€ะฝะพัั‚ะธ) # ะ”ะปั ัั‚ะพะณะพ ะดะพะฑะฐะฒัŒั‚ะต ะฐั€ะณัƒะผะตะฝั‚ั‹ color = 'mortality' ``` **Heat Maps** quite useful for additional visualization of correlation matrices between features. When there are a lot of features, with the help of such a graph you can more quickly assess which features are highly correlated or do not have a linear relationship. ``` # Heat map sns.heatmap(data.corr(), annot=True, fmt='.2f', cmap='cividis'); # try another color, e.g.'RdBu' ``` The scatter plot helps to find the relationship between the two indicators. To do this, you can use pairplot, which will immediately display a histogram for each variable and a scatter plot for two variables (along different plot axes). ``` # Pairplot sns_plot = sns.pairplot(data[['Deaths', 'Confirmed']]) sns_plot.savefig('pairplot.png') # save ``` **Pivot table** can automatically sort and aggregate your data. ``` # Pivot table plt.figure(figsize=(12, 4)) df_new = df_mortality.iloc[:10] df_new['Confirmed'] = df_new['Confirmed'].astype(np.int) df_new['binned_fatalities'] = pd.cut(df_new['Deaths'], 3) platform_genre_sales = df_new.pivot_table( index='binned_fatalities', columns='Country/Region', values='Confirmed', aggfunc=sum).fillna(int(0)).applymap(np.int) sns.heatmap(platform_genre_sales, annot=True, fmt=".1f", linewidths=0.7, cmap="viridis"); # Geo # file with abbreviations with open('./data/countries_codes.pkl', 'rb') as file: countries_codes = pickle.load(file) df_map = data.copy() df_map['Date'] = data['Date'].astype(str) df_map = df_map.groupby(['Date','Country/Region'], as_index=False)['Confirmed','Deaths'].sum() df_map['iso_alpha'] = df_map['Country/Region'].map(countries_codes) df_map['ln(Confirmed)'] = np.log(df_map.Confirmed + 1) df_map['ln(Deaths)'] = np.log(df_map.Deaths + 1) px.choropleth(df_map, locations="iso_alpha", color="ln(Confirmed)", hover_name="Country/Region", hover_data=["Confirmed"], animation_frame="Date", color_continuous_scale=px.colors.sequential.OrRd, title = 'Total Confirmed Cases growth (Logarithmic Scale)') ``` What important information did the new graph provide (visualization by time and geolocation)? Is it possible to answer the questions according to the schedule: * Which country did the spread of the coronavirus start from? * Which countries are most affected by the pandemic? * What part of the hemisphere accounts for the majority of cases? What hypotheses can be formulated regarding the temperature and rate of spread of the virus? What other observations can you make from the graph? ### **Recommended materials** 1. Matplotlib documentation https://matplotlib.org/3.2.1/tutorials/index.html 2. Seaborn documentation https://seaborn.pydata.org/tutorial.html 3. Plotly https://plotly.com/python/ 4. [Kaggle COVID19-Explained through Visualizations](https://www.kaggle.com/anshuls235/covid19-explained-through-visualizations/#data) 5. Open Data Science lecture on these topics: https://www.youtube.com/watch?v=fwWCw_cE5aI&list=PLVlY_7IJCMJeRfZ68eVfEcu-UcN9BbwiX&index=2 https://www.youtube.com/watch?v=WNoQTNOME5g&list=PLVlY_7IJCMJeRfZ68eVfEcu-UcN9BbwiX&index=3 ### **Additional libraries**: * Bokeh * ggplot * geoplotlib * pygal
github_jupyter
# Shakespeare & Model Robustness Selecting which texts belong in the corpus you plan to analyze (and which ones don't!) is a major interpretive problem. This process of selection is closely tied to the definition of our research question. At the same time, when we seek out patterns across texts, our scholarly arguments are strongest when they hold true across reasonable variations in selection critera. For example, say that we perform a distant reading of Shakespeare's Comedies. We analyze them computationaly and present our findings to a scholarly audience. However, during Q&A, an objection is raised that the late romances like <i>The Tempest</i> and the problem plays like <i>Measure for Measure</i> are having a disporportionate impact on the pattens we have discovered. Their status as comedy is subject to debate. Clearly our claim about the Comedies as a whole has been invalidated! We can anticipate this kind of objection by testing variations in our selection criteria. If a pattern holds true across variations that reflect scholarly debates about the categories themselves, then it offers a strong argumentative foothold. Alternately, if the linguistic pattern changes with variant corpora, then it offers a wider view of the discursive field. ## Distinctive Words In this set of exercises, we will identify words that are distinctive of Shakespeare's Comedies, as opposed to the Tragedies and Histories. The corpus for this task is the set of Shakespeare's plays, stripped of all character names and stage directions. Only dialogue remains. These have been <a href="http://winedarksea.org/?p=2225">made available by Michael Witmore</a> from the Folger Digital Texts collection. First, we will perform our distinctive word test using the three genres as they are assigned to the plays in the First Folio. * <b>COMEDY</b> * The Tempest, The Two Gentlemen of Verona, The Merry Wives of Windsor, Measure for Measure, The Comedy of Errors, Much Ado About Nothing, Love's Labour's Lost, A Midsummer Night's Dream, The Merchant of Venice, As You Like It, The Taming of the Shrew, All's Well That Ends Well, Twelfth Night, The Winter's Tale * <b>HISTORY</b> * King John, Richard II, Henry IV-Part 1, Henry IV-Part 2, Henry V, Henry VI-Part 1, Henry VI-Part 2, Henry VI-Part 3, Richard III, Henry VIII * <b>TRAGEDY</b> * Troilus and Cressida, Coriolanus, Titus Andronicus, Romeo and Juliet, Timon of Athens, Julius Caesar, Macbeth, Hamlet, King Lear, Othello, Antony and Cleopatra, Cymbeline Second, we will repeat the process using slightly different categories. In addition to COMEDY, HISTORY, and TRAGEDY, we will include ROMANCE and PROBLEM. Several plays will be shifted into these latter, contested categories. * <b>ROMANCE</b> * Pericles, Cymbeline, The Winter's Tale, The Tempest, Two Noble Kinsmen * <b>PROBLEM</b> * All's Well That Ends Well, Measure for Measure, Troilus and Cressida # Exercise 1 * Read the text of Shakespeare's plays from files * Create a DataFrame with 4 columns * Filename * Genre as assigned in the First Folio * Genre as revised to include Romances and Problem Plays * Text Note: Pericles and Two Noble Kinsmen were not included in the First Folio, both have been argued to be romances. How will you handle this in your labeling? ``` import os # Get a list of filenames for the corpus filenames = os.listdir("corpora/FDT Shakespeare Stripped/") # Read the files texts = [ open("corpora/FDT Shakespeare Stripped/"+filename, 'rb').read() for filename in filenames ] ``` # Exercise 2 * Transform the texts of the plays in to a DTM, using Tf-Idf weighting * Create a new DataFrame with the First Folio genres and the DTM * Produce a list of distinctive words belonging to Comedies # Exercise 3 * Create a new DataFrame with the revised genres and the DTM * Produce a list of distinctive words belonging to Comedies * Compare results with those from Exercise 2 # Bonus Exercise * Train a classifier to distinguish between Comedy and Tragedy (in the First Folio) * Predict whether Pericles and Two Noble Kinsmen belong to either group * How confident are the predictions? * Produce a list of the most important features in the model
github_jupyter