code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # "The Latent Space of Podcasts" # > "We train a podcast recommender using matrix-based collaborative filtering. Visualizing the resulting latent factors gives us some insight into what the model has learned." # - toc: True # Nowadays we encounter recommender systems on a daily basis in search engines, streaming platforms, and social media. There exist many different mechanisms behind recommender systems, but we will focus on a a class of methods known as **collaborative filtering**. In a nutshell, this approach consists of taking the set of all known user preferences and using that to "predict" the user's preference for an **item** (movie, song, news article) that the user hasn't seen yet (or for which the user hasn't indicated a preference). The basis for establishing this preference depends on the context. Some examples include user ratings on Netflix, or how many times a user has listened to a song on Spotify. # # Collaborative filtering relies on the assumption that similar users will like similar items. Furthermore, similarity is derived solely from the known user preferences, such as ratings, without any knowledge of the content of the items. Note that in practice only a tiny fraction of all user preferences are known. For example, Netflix users will only have watched a small fraction of all available content. # # I find **matrix-based** collaborative filtering methods especially interesting. In those methods both the users and the items are represented by vectors in some high-dimensional space, called **latent factors**, which encapsulate both user *preferences* and item *similarity*: Vectors for two similar items (or for a user with a positive preference for an item) point in similar directions. # # This latent space reflects patterns or structures in the set of items (for example movie genres), which we can visualize. For this we will need **dimensionality reduction techniques**, such as Principal Component Analysis, or PCA. It is interesting to see which structures emerge just from the set of user preferences, without providing any information about the items or users themselves. It is a useful check for our intuitions in regards to which items are more similar based on concepts like music style or movie genres. # # Learning about this made me wonder which patterns the **latent space of podcasts** might reveal, given that I am a big fan of podcasts myself. This has likely already been studied internally by companies such as Apple and Spotify, but I haven't found any publicly available recommender system for podcasts. I imagine that part of the reason is the lack of large open access datasets, which do exist for [movies](https://grouplens.org/datasets/movielens), [music](http://millionsongdataset.com/challenge), and [books](http://www2.informatik.uni-freiburg.de/~cziegler/BX). This is probably because the mainstream appeal of podcasts is a relatively recent phenomenon. # # Luckily I was able to find one pretty decent dataset of podcasts reviews on [Kaggle](https://www.kaggle.com/thoughtvector/podcastreviews). It consists of almost a million reviews for over 46,000 podcasts, stored in an SQLite database. Thanks to <NAME> for collecting the reviews and making them available for everyone! # # We will use this dataset to create a recommender and visualize the latent factors for some popular podcasts. Before we can do that we will need to clean the data first. The data is a bit more raw than some more mainstream recommeder datasets like MovieLens. #collapse-hide import sqlite3 import pandas as pd import numpy as np from implicit.als import AlternatingLeastSquares from implicit.evaluation import precision_at_k, leave_k_out_split from scipy import sparse from sklearn.decomposition import PCA import matplotlib.pyplot as plt # + [markdown] tags=[] # ## Import from SQLite # # The whole data is in an SQLite file. The SQLite database contains three tables: # - `podcasts` table containing the podcast ID, name and URL. # - `reviews` table containing all the information associated with every review: the star rating, the review title and content, the date and time it was posted, and finally the author ID of the user who made the review as well as the podcast ID. # - `categories` table, which simply contains a column with podcasts IDs and a column with categories into which to those podcasts have been classified. # # We will load the data from the SQLite file into a pandas DataFrame. Specifically, we will take a left join of the podcasts table and reviews table and select a subset of the columns. # # For our purposes we will not need the review title and content. However, it would be interesting to do some NLP on the contents as a future project. Maybe some topic modeling which can be combined with collaborative filtering in a hybrid recommender system. # - con = sqlite3.connect('data/database.sqlite') get_ratings = """SELECT author_id AS user_id, p.podcast_id, rating, p.title AS name, created_at FROM podcasts p INNER JOIN reviews r USING(podcast_id) """ ratings_raw = pd.read_sql(get_ratings, con, parse_dates='created_at') ratings_raw # Next we create a table of podcasts with some rating statistics: number of ratings, mean rating, and the years of the first and the last rating. def extract_podcasts(ratings): 'Get the podcasts with rating count, rating mean and rating years.' ratings_copy = ratings.copy() return (ratings_copy.groupby('podcast_id', as_index=False) .agg( name = ('name', 'first'), rating_count = ('rating', 'count'), rating_mean = ('rating', 'mean'), earliest_rating_year = ('created_at', lambda c: c.min().year), latest_rating_year = ('created_at', lambda c: c.max().year), ) ) podcasts_raw = extract_podcasts(ratings_raw) podcasts_raw # ## Data Exploration and Cleaning # # In this section we will deal with some issues in the data and prepare it for the recommender system below. # ### How far back do the reviews go? # # A couple of ratings go all the way back to 2005 although most of them only go back to 2018. For many popular podcasts the reviews start in 2019. # # When I asked the curator of the dataset on Kaggle why the reviews go much further back for some podcasts than for most others, he clarified that the reason is that the Apple API only gives access the latest 500 reviews of each podcast. This explains why for popular podcasts those 500 reviews only go back a couple of months, but for others they go back many years. # # Inspecting the dates of the reviews of some popular podcasts, I found no gaps since 2019. This confirms that the reviews have been downloaded without interruption since then. # ### Curating the Ratings # # We need to take care of the following complications: # - Some users have left a suspiciously high number of reviews. Indeed, looking at the content of their reviews they do not look genuine at all: they repeat the same text hundreds of times, with slight variations. We will remove all the users with a rating volume beyond a specific threshold to weed out bots. We set the threshold at 135 reviews by inspecting the content of the reviews and making a judgment call. # - It appears that some podcasts are no longer active, given that their latest review was made years ago. We need to decide whether we want to remove these seemingly inactive podcasts. While we don't want to recommend podcasts that don't exist anymore, their reviews can still help the collaborative filtering model. We will simply remove podcasts which have zero reviews made on or after 2020. Another option would be to include old podcasts in the training of the recommender system but skip them when making recommendations. # - It turns out that there are repeat reviews in the data, meaning that some users left multiple reviews for the same podcast. They are probably just edited or updated reviews. Consequently, we will only consider the latest rating for each user-podcast pairing. # - For the collaborative filtering approach to work, the users need to have rated multiple podcasts and, similarly, the podcasts need to have been rated by multiple users. To ensure this, we need to remove all users and podcasts with a number of reviews below a certain threshold. For example, we could remove all users with under 3 reviews and all podcasts with under 15 reviews. We have to be careful here: removing some users will reduce the number of reviews for some podcasts, which might push some podcasts below the threshold. In turn, removing those podcasts might push some users below the threshold. We need to keep doing this back and forth until the ratings DataFrame stops changing. # # We will write a separate function to deal with each point. # + def remove_suspicious_users(ratings, max_reviews=135): 'Remove users with suspiciously high review count.' mask = ratings.groupby('user_id')['podcast_id'].transform('count') <= max_reviews return ratings[mask] def remove_inactive_podcasts(ratings, latest_rating_year=2020): 'Remove podcasts with no reviews at or after latest_rating_year.' active = (ratings.groupby('podcast_id')['created_at'] .transform(lambda c: c.max().year) >= latest_rating_year ) return ratings[active] def keep_only_latest_rating(ratings): 'Remove repeat reviews, keeping the latest. Also sorts the ratings by date.' return ratings.sort_values(by='created_at', ascending=False).drop_duplicates(subset=['podcast_id', 'user_id']) def remove_low_rating_users_and_podcasts(ratings, min_user_reviews=3, min_podcast_reviews=15): 'Alternate between removing podcasts and users with insufficient reviews until there are none left.' result = ratings.copy() while result.shape: previous_shape = result.shape mask = result.groupby('podcast_id')['user_id'].transform('count') >= min_podcast_reviews result = result[mask] mask = result.groupby('user_id')['podcast_id'].transform('count') >= min_user_reviews result = result[mask] if result.shape == previous_shape: return result # - ratings = remove_suspicious_users(ratings_raw) ratings = remove_inactive_podcasts(ratings) ratings = keep_only_latest_rating(ratings) ratings = remove_low_rating_users_and_podcasts(ratings) ratings podcasts = extract_podcasts(ratings) podcasts.sort_values(by='rating_count', ascending=False) # Out of the 46,693 podcasts we started with, we are left with 936. Unfortunately, it is inevitable that we have to discard a large fraction of the podcasts because most of them have only a few reviews on Apple Podcasts. Consider the fact that more than a fourth of the podcasts (13,922 to be precise) had only a *single review*. More that half of the podcasts (a total of 25,104) had only up to 3 reviews! # # That said, it's worth noting that there are actually as many as 8323 podcasts with at least 15 ratings. However, a sizable portion of the users leaving those ratings had to be removed because they only rated one or two podcasts in total (and of course removing some podcasts led to having to remove more users and so on). Thus, this is how we are left with just 936 podcasts. # # The remaining ratings are still sufficient to yield interesting results, though! # The minimum threshold of ratings for users and podcasts is also reflected in the **density of the ratings matrix**. The so called *ratings matrix* contains all the ratings such that each row corresponds to one user and each column corresponds to one podcast. If there is a particular user hasn't rated a particular podcast, the corresponding entry (where the user row and podcast column meet) is simply $0$. Furthermore, the *density* of the ratings matrix is the percentage of non-zero entries. In other words, the density is the percentage of user-podcast pairs for which a rating exists in the dataset. def compute_density(ratings): n_ratings = ratings.shape[0] n_podcasts = ratings['podcast_id'].nunique() n_users = ratings['user_id'].nunique() return n_ratings / (n_podcasts * n_users) print(f'The density of the curated rating matrix is {compute_density(ratings) * 100:.2f}%, while the density of the original rating matrix is {compute_density(ratings_raw) * 100:.4f}%.') # We went from 755,438 users to 12,212 users after cleaning up the data and discarding users and podcasts with too few reviews. # # Unfortunately, the vast majority of users left only a single review (in this dataset at least). This is probably at least partly due to the fact that many popular podcasts are missing and even for those included the reviews go back only three years. However, even taking this into account, it is conceivable that most people listen to fewer podcasts than Netflix users watch different shows and movies, for example. There is also more friction (more time and steps involved) for leaving a review on Apple Podcasts than rating a show on Netflix, again as an example. # + [markdown] tags=[] # ## Implicit Recommender System # - # It turns out that the overwhelming majority of the ratings are 5 star ratings. It appears that most users do not go out of their way to give a negative rating unless they really dislike a show. The following bar chart shows the frequency of each star rating in the curated ratings table. The situation is even more skewed in favor of 5 star ratings in the raw ratings data. # + fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 4)) ax0.set_title('Star Ratings Before Curating') ax0.bar(ratings_raw['rating'].value_counts().index, ratings_raw['rating'].value_counts().values) ax1.set_title('Star Ratings After Curating ') ax1.bar(ratings['rating'].value_counts().index, ratings['rating'].value_counts().values); # - # ### Why Implicit? # # When I started this project I intended to use a model which tries to predict the *specific star rating* a user would give to "unseen" items, in order to recommend the item with the highest predicted rating. This is how **explicit recommender systems** work, which are trained on *explicit* user feedback (in this case, star ratings). However, the extreme imbalance in the ratings suggests that the explicit recommender system approach might not be appropriate here. # # First of all, there is a well-known issue with imbalanced data which can be illustrated as follows. The simple baseline model which predicts that every user will rate every podcast with 5 stars would have a high accuracy, because it would be right almost all of the time. That said, this is not a big deal and can be corrected by choosing a more appropriate metric than plain accuracy. # # The deeper concern in this case is the **reason behind the class imbalance**. It appears that that most users simply stop listening to a podcast they don't like without bothering to leave a negative review. Not only that, but people clearly don't just pick podcasts at random to listen to. Instead, there is a pre-selection: they follow a friend's recommendation, seek out podcasts on a particular topic or featuring a particular guest, and so on. Needless to say, users are unlikely to leave a review for a podcast they never listened to (although I am sure that a handful of people do). # # All of this is to say: # - In explicit recommender systems missing ratings are viewed simply as missing information. However, it appears that there actually *is* some information given by the fact that a podcast wasn't rated by a user. Maybe we should think of missing ratings as suggesting a *negative preference*, but assigning *low confidence* to that preference. Some reasons why a missing rating potentially reveals a negative preference were given above. Namely, users are less likely to rate a podcast they don't like and many are even unlikely to listen to it in the first place. On the other hand, the confidence in this negative preference is low because the rating might be missing for a variety of other reasons. The most likely reason is that the user isn't even aware of that particular podcast's existence. # - Focusing mostly on the precise ratings (1 to 5 stars) is of limited value because users seem to be using the stars mostly to give a "thumbs up" (5 stars). # # It turns out that there is an approach which seems to be perfectly suited to address the two issues above: **implicit recommender systems**. They are called implicit because they usually do not use (explicit) feedback given by the users. Instead they infer the preferences of users from their activity, such as how often a user has listened to a song on Spotify, or if a user has watched the entirety of a movie on Netflix. The fundamental change from explicit to implicit systems is that instead of giving *ratings*, users have *preferences* and those preferences are known to us with a certain *confidence*. What this allows us to do is to interpret the absence of activity (user didn't watch a particular movie) as a negative preference, but with low confidence. # # Unfortunately, we don't have access to user activity, but the ratings (which are explicit feedback) can be made "implicit" with the following interpretation: high ratings (4 or 5 stars) correspond to positive preferences with high confidence, while missing ratings and all lower ratings (1 to 3 stars) correspond to negative preferences with low confidence. It is possible to treat low ratings separately from missing ratings but this doesn't seem to improve the results, maybe due to the low frequency of low ratings. # ### Alternating Least Squares # # We will use the `implicit`, a very fast recommender library written in Cython by <NAME>. Specifically, we will use the **Alternating Least Squares** algorithm, or ALS. The ALS algorithm for implicit recommenders was introduced in [this paper](http://yifanhu.net/PUB/cf.pdf) by Hu, Koren and Volinsky. I will not go into too much detail here, but a general explanation is outlined below. In addition to the original paper, I recommend reading [this](https://jessesw.com/Rec-System/) blog post, in which the algorithm is implemented in Python (although the implicit library is actually used for speed). # # Here is a brief overview of the model we will use: Each user $u$ is assumed to have a **preference** $p_{ui}$ for podcast $i$ and we want to find **latent factors** $x_u$ and $y_i$ such that their inner product approximates the preference: $p_{ui} \approx x_u\cdot y_i$. More precisely, we want to find $x_u$ and $y_i$ which minimize the following cost function: # $$ # \sum_{u,i} c_{ui}(p_{ui} - x_u\cdot y_i)^2 + \lambda \left(\sum_u \|x_u\|^2 + \sum_i \|y_i\|^2\right) # $$ # # The weights $c_{ui}$ are the **confidence** that we have in the respective preference $p_{ui}$. The higher the confidence, the more importance we give to approximating the particular preference $p_{ui}$ by $x_u\cdot y_i$. The summands multiplied by $\lambda$ are there to avoid overfitting. # # If we hold constant the user vectors $x_u$, the cost function is quadratic in the podcast vectors $y_i$ and can be minimized efficiently. The same is true swapping $x_u$ and $y_i$. This where the Alternating Least Squares trick comes in: First compute the $y_i$ which minimize the cost function with $x_u$ held constant. Then fix $y_i$ at that (provisional) minimum and in turn find $x_u$ minimizing the resulting cost function. Amazingly, simply doing this back and forth several times yields pretty good results. # ### The Implicit Matrix # # In order to feed our data to the implicit ALS model, we need to transform our table of explicit ratings into a matrix of implicit data. The entries of the matrix need to incorporate both the confidence factors $c_{ui}$ and the preference factors $p_{ui}$. # # In order to construct the matrix correctly, we need to know which input the model `implicit.AlternatingLeastSquares` expects. We feed the ALS model a single matrix, which then (internally) deduces preferences and confidence from that single matrix. If there is a positive entry at a position $(u,i)$, this is taken to mean that $p_{ui} = 1$ (positive preference), otherwise $p_{ui} = 0$ (negative entries). The precise values of the entries are also important: The element at position $(u,i)$ equals the confidence $c_{ui}$, after adding 1 to make sure that the confidence is at least 1 for all $(u,i)$ (if the confidence at some point were 0 the preference $p_{ui}$ would be irrelevant in the cost function, which we want to avoid in the implicit setting). # # In light of the above, it's clear that our implicit matrix needs strictly positive entries for each pair $(u,i)$ for which the user $u$ gave the podcast $i$ a high ratings, and all other entries should be set to 0. Marking low ratings (1 or 2 stars, say) with negative entries in the matrix did not help much when I tried it, so we will avoid this. (That would mean a higher confidence in the negative preference for low ratings, as opposed to missing ratings.) # # Here is what we will do: The implicit matrix will have a 1 at every position corresponding to a high rating (4 or 5 stars) and a 0 everywhere else. There is nothing special about the value 1, which can be changed later to any other number (by simply multiplying the matrix by that number). Note that most entries are 0, given that most users have not left reviews for most podcasts. In other words, the matrix will have a **high sparsity** (low density). This is why it makes sense to use a `scipy` sparse matrix instead of a NumPy array. def make_implicit(ratings, threshold=4): '''Replace star rating (1 to 5) by a +1 if rating >= threshold and if rating < threshold either replace it by a -1 (if negative is True) or remove it (if negative is False). Return a csr sparse matrix with the ratings (users rows and podcasts cols) and two lists: one with the user_ids corresponding to the rows and one with the podcast names corresponding to the columns. ''' positive = ratings['rating'] >= threshold implicit_ratings = ratings.loc[positive].copy() implicit_ratings['rating'] = 1 # Remove low rating users and podcasts again implicit_ratings = remove_low_rating_users_and_podcasts(implicit_ratings, 2, 5) user_idx = implicit_ratings['user_id'].astype('category').cat.codes podcast_idx = implicit_ratings['podcast_id'].astype('category').cat.codes # The codes simply number the user_id and podcast_id in alphabetical order # We keep track of the order of the users and podcasts with the following arrays user_ids = implicit_ratings['user_id'].sort_values().unique() podcast_names = implicit_ratings.sort_values(by='podcast_id')['name'].unique() implicit_ratings = sparse.csr_matrix((implicit_ratings['rating'], (user_idx, podcast_idx))) return implicit_ratings, user_ids, podcast_names implicit_ratings, user_ids, podcast_names = make_implicit(ratings) implicit_ratings.shape # ### Training and Evaluation # # At last, we are ready to train our recommender! # # To evaluate the performance of a recommender we need to be able to decide if recommendations are relevant. However, if the system simply recommends podcasts that it already "knows" the user likes (positive entry in the implicit matrix), this doesn't reflect how well the system can make recommendations for podcasts the user hasn't shown a preference for yet (0 in the implicit matrix). # # To address this, we will turn one positive entry into a 0 entry for each user. In other words, for each user we will forget one podcast the user rated highly. Then we train the recommender system on this modified implicit dataset (called the **training set**). Next, we let the model make one recommendation per user, but require that for each user the podcast recommended has not already been "liked" by that user in the training set. Finally, we compute the **precision** of the recommender: the fraction of the users for which the recommendation is precisely the podcast we "forgot" for that user when creating the training set. Recall that we know those "forgotten" podcasts to be relevant recommendations, because the user gave them a high rating (which we omitted in the training set). # # Note that recommendations other than the one positive preference we omitted (for each user) might also be relevant, but there is no way for us to verify that with our data. In light of this, the precision might in fact underestimate how often the recommendations are relevant. # # The (simple) precision is not the best metric. For example, it would be better to omit several ratings for each user and then compute the **precision at k (denoted p@k)**, which consists of recommending $k$ podcasts for each user and determining which fraction of those recommendations is relevant. What we are doing above is effectively p@1 (precision at 1). There are other more sophisticated metrics, but they also require making multiple recommendations per user. The reason we cannot use these metrics is that most users only have 3 ratings and removing more than one would leave them with 1 rating, which is basically useless for collaborative filtering. If we instead only removed ratings from a subset of users who left many ratings, we would be biasing our metric in favor of a minority of very active users. # + tags=[] ratings_train, ratings_test = leave_k_out_split(implicit_ratings, K=1) # - import os os.environ["MKL_NUM_THREADS"] = "1" als_recommender = AlternatingLeastSquares(factors=50, regularization=0.1, random_state=42) als_recommender.fit(2 * ratings_train.T) precision_at_k(als_recommender, ratings_train, ratings_test, K=1) # As a baseline, we will also compute the precision for a simple recommender which recommends the most popular podcast to all users. To be precise, it recommends the most popular podcast among those not already liked by the user in the training set, because those recommendations are not scored as hits when computing the precision (we want the recommender to suggest "new" podcasts after all). # # We write the baseline in such a way that it can also recommend multiple podcasts. It simply recommends the $N$ most popular podcasts, given some $N$. # + class PopularityBaseline(): def __init__(self, implicit_ratings): podcast_ids, count = np.unique(implicit_ratings.tocoo().col, return_counts=True) self.top_podcasts = podcast_ids[np.argsort(-count)] def recommend(self, user_id, user_items, N=10): '''Recommend the most popular podcasts, but exclude podcasts which the users in user_ids have already interacted with according to user_items''' user_items = user_items.tocoo() this_user = user_items.row == user_id liked_podcasts = set(user_items.col[this_user]) recom = [] for podcast in self.top_podcasts: if podcast not in liked_podcasts: recom.append(podcast) if len(recom) == N: break else: raise Exception('Not enough podcasts remaining to recommend') return list(zip(recom, [0] * N)) # The implicit API expects a score for each podcast popularity_baseline = PopularityBaseline(implicit_ratings) # + tags=[] precision_at_k(popularity_baseline, ratings_train, ratings_test, K=1) # - # Our recommender system is significantly better than the baseline recommender ($9.3\%$ versus $2.9\%$). It appears the recommender learned something! # Now we will train the recommender again but with the whole implicit rating set, not just the a smaller training set. We will use this recommender going forward. als_recommender = AlternatingLeastSquares(factors=50, regularization=0.1, random_state=42) als_recommender.fit(2 * implicit_ratings.T) # ## Latent Factors # # Recall that the our recommender works by finding latent factors for all podcasts and all users, such that the inner product of the user and podcast vectors is as close as possible to the corresponding user preferences. Another way of looking at this is that preference (of a user for a podcast) or similarity (of two podcasts, or two users, to each other) corresponds to vectors pointing in a similar direction (technically, having a high cosine similarity, or low cosine distance). # # In light of the above, to introspect the recommender we must visualize the latent factors. We will do this for the most popular podcasts in the dataset. Because the latent space is 50-dimensional we will project it down to 2 dimensions. We will use **Principal Component Analysis** (PCA) to find the two directions in which the latent factors vary the most and project down to those. podcast_ids, count = np.unique(implicit_ratings.tocoo().col, return_counts=True) top_podcasts = podcast_ids[np.argsort(-count)][:25] # + tags=[] pca = PCA(n_components=5) reduced_item_factors = pca.fit_transform(als_recommender.item_factors) # + tags=[] fig, ax = plt.subplots(figsize=(15, 15)) X = reduced_item_factors[top_podcasts].T[1] Y = reduced_item_factors[top_podcasts].T[0] ax.set_title('Latent Podcast Space', fontdict = {'fontsize' : 20}) ax.scatter(X, Y) for i, x, y in zip(podcast_names[top_podcasts], X, Y): ax.text(x, y, i, color=np.random.rand(3)*0.7, fontsize=14) # - # We must take the visualization with a grain of salt because obviously information is lost when we project a 50-dimensional space down to two dimensions. Specifically, podcasts that appear close in the projection might not be close at all in the full space. # # That said, there appears to be some clear structure, which we will describe below. We must also remember that this is not some random 2D projection, but a projection to the two axes of highest variability (principal components). # # Let's start with the **horizontal direction** (or x axis). Podcasts targeted at children are on the right and podcasts targeted at more mature audiences are to the left. The most extreme values are attained by 'Wow to the World' and 'Story Pirates', which are the most popular podcasts for kids. Judging from the content of the reviews there seems to be a bit of a rivalry between those two podcasts, although they have a large overlap in preference. 'Smash Boom Best' and 'Pants on Fire' are for children as well. It is interesting that the two podcasts on stories for kids are so close to each other. # # In the **vertical direction** (or y axis), the situation is not as clear-cut but we can recognize different genres bunch together. The podcasts at the top all focus on self-improvement or self-help. The tiles 'The Learning Leader Show', 'Discover Your Talent', and 'Mindulness Mode' are self-explanatory. 'Confessions of a Terrible Husband' is about relationship advice. As for 'Leveling Up', this is a (partial) quote from the official website: "Leveling Up is a radical new perspective on achieving success \[...\]". On the other hand the podcasts at the bottom are all for pure entertainment (true crime themed and slightly above, pop culture and comedy). # + [markdown] tags=[] # ## Podcast Similarity # - # As a reality check, we will go through a couple of popular podcasts and inspect the 10 most similar podcasts according to our model. I find the results pretty impressive considering the limited information the model was trained on. Click on "show output" to view the list of similar podcasts. def get_k_most_similar_podcasts(name, recommender, podcast_names, K=10): this_name = np.where(podcast_names == name)[0][0] return [podcast_names[idx] for idx, _ in recommender.similar_items(this_name, N=K+1)[1:]] #collapse-output get_k_most_similar_podcasts('My Favorite Murder with <NAME> and <NAME>', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('The Joe Rogan Experience', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Story Pirates', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Best Real Estate Investing Advice Ever', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Mindfulness Mode', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('ADHD reWired', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Good Night Stories for Rebel Girls', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Leveling Up with <NAME>', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Pants on Fire', als_recommender, podcast_names, 10) #collapse-output get_k_most_similar_podcasts('Bachelor Happy Hour with Rachel & Ali – The Official Bachelor Podcast', als_recommender, podcast_names, 10)#collapse-output #collapse-output get_k_most_similar_podcasts("And That's Why We Drink", als_recommender, podcast_names, 10) # + [markdown] tags=[] # ## Discussion # Despite the fact that the dataset was drastically reduced after curation (removing podcasts with insufficient reviews and so on), the recommender still has 933 podcasts and about 10,607 users to work with, with a total of 40,585 positive ratings. The density is around $0.4\%$, meaning that around $0.4\%$ of all possible ratings (in other words, of all user-podcast pairs) are are actually realized in the data. # # While this is a relatively small dataset for collaborative filtering, our recommender did pretty well: # - On our test set, the accuracy was $0.09$ which is three times as high as the baseline recommender (which simply recommends the most popular podcasts). Recall that we computed this number by training the recommender while omitting 1 rating per user and then checking how often the omitted podcast was the *first* recommendation for each user. Getting precisely the omitted podcast as the first recommendation for $9\%$ of users seems pretty good, considering that there are probably many relevant podcasts that the users just haven't rated yet (we consider those irrelevant by default because we cannot verify their relevance). # - When we looked at recommendations of individual podcasts they were very compelling. # - Finally, as we described above, there are clear patterns in the latent factors of the podcasts which can be visualized with PCA. We can summarize those findings as follows: The first principal component seems to correspond to a spectrum going from self-improvement to pure entertainment (with true crime at the very end). Along the second principal component the podcasts separate according to whether they are targeted at kids or adults. # + [markdown] tags=[] # ## Closing Thoughts # # It seems that it was a good choice to turn the star ratings into an **implicit** dataset, with preferences and confidences. Remember that we did this because the vast majority of ratings give 5 stars, which suggests that a lot of information lies in the podcasts a user did *not* rate. That information is lost in the explicit paradigm because missing ratings are ignored, unlike in the implicit paradigm, where they are taken into account as low confidence negative preferences. # # I noticed that many **popular podcasts** are missing (based on [this](https://chartable.com/charts/chartable/podcast-global-all-podcasts-reach) list of top 200 podcasts as of early 2022). When I brought this up with the curator of the dataset on Kaggle he confirmed that many podcasts are left out on purpose. However, he admitted that he hadn't realized how many popular podcasts were missing. This is unfortunate because if we do not know exactly how podcasts have been selected, we cannot correct for sampling bias. # # On a related note: <NAME>'s immensely popular and controversial podcast is not on Apple Podcasts since 2020, when it became a Spotify exclusive in a deal involving [reportedly](https://www.theverge.com/2022/2/17/22939587/joe-rogan-experience-spotify-podcast-deal) two hundred million dollars. Nonetheless, it appears many users were still able to leave reviews after the move, and some even wonder in their review why they aren't able to access the podcast anymore (and sometimes leave a negative rating in protest). This doesn't seem to have thrown off the recommender, judging by the list of podcasts most similar to 'The Joe Rogan Experience', which seems very appropriate. # # The **next steps** would be to put together a **larger dataset** in which most popular podcasts are actually included. Then we would **tune the hyperparameters** of our model and evaluate the model with the best parameters using **cross-validation**. Note that a **larger dataset is needed** to properly carry out the parameter search and final evaluation. The parameter search requires cross-validation to evaluate the models with different parameters and this needs to be nested within a larger cross-validation to evaluate the performance of the best parameters found in the search. The nested cross-validation in this context requires removing one rating per user for the outer split and an additional rating per user for the inner split. In our data a majority of users only have 3 ratings, which would leave them with only a single rating in the training set (useless for collaborative filtering). If we wanted to use a better metric such as p@3, a total of 6 ratings per user would be omitted, needing even more ratings per user.
_notebooks/2022-03-19-podcasts-recommender.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Brute Forces, Secretaries, and Dichotomies # # Chapter 11 of [Real World Algorithms](https://mitpress.mit.edu/books/real-world-algorithms). # # --- # # > <NAME><br /> # > Athens University of Economics and Business # + [markdown] slideshow={"slide_type": "slide"} # ## Sequential Search # # Sequential search is perhaps the most straightforward search method. # # We start from the beginning and check each item in turn until we find the one we want. # # It can be used for both sorted and unsorted data, but there are much better methods for sorted data. # # Here is a straightforward implementation: # + slideshow={"slide_type": "slide"} def sequential_search(a, s): for i, element in enumerate(a): if element == s: return i return -1 # + [markdown] slideshow={"slide_type": "slide"} # Let's check it on a random list: # + slideshow={"slide_type": "fragment"} import random a = list(range(1000)) random.shuffle(a) pos = sequential_search(a, 314) print(a[pos], 'found at', pos) pos = sequential_search(a, 1001) print(pos) # + [markdown] slideshow={"slide_type": "slide"} # We need not write `sequential_search(a, s)` in Python. # # If `a` is a list, we can use `a.index(s)` instead. # # In fact that's what we should do, because it is way faster (we saw that also in Chapter 7). # + [markdown] slideshow={"slide_type": "slide"} # Here is the timing for our version: # + slideshow={"slide_type": "fragment"} import timeit total_elapsed = 0 for i in range(100): a = list(range(10000)) random.shuffle(a) start = timeit.default_timer() index = sequential_search(a, 314) end = timeit.default_timer() total_elapsed += end - start print(total_elapsed) # + [markdown] slideshow={"slide_type": "slide"} # And here is the timing for the native version (which actually calls a function written in C): # + slideshow={"slide_type": "fragment"} total_elapsed = 0 for i in range(100): a = list(range(10000)) random.shuffle(a) start = timeit.default_timer() index = a.index(314) end = timeit.default_timer() total_elapsed += end - start print(total_elapsed) # + [markdown] slideshow={"slide_type": "slide"} # ## Matching, Comparing, Records, Keys # # When we are searching for an item in the list, Python performs an equality test between each item and the item we are searching for. # # The equality test is performed with the operator `==`. # # Checking for equality is not the same as checking whether two items are the *same*. # # This is called *strict comparison* and in Python it is implemented with the operator `is`. # + [markdown] slideshow={"slide_type": "slide"} # That means that the following two are equal: # + slideshow={"slide_type": "slide"} an_item = (1, 2) another_item = (1, 2) an_item == another_item # + [markdown] slideshow={"slide_type": "slide"} # But they are not the same: # + slideshow={"slide_type": "fragment"} an_item is another_item # + [markdown] slideshow={"slide_type": "slide"} # As another example, let's see what happens with Python's support for complex numbers: # + slideshow={"slide_type": "fragment"} x = 3.14+1.62j y = 3.14+1.62j print(x == y) print(x is y) # + [markdown] slideshow={"slide_type": "slide"} # String comparison is must faster than equality checking, but it is not what we usually want to use. # # A common idiom for identity checking in Python is checking for `None`, like `if a is None` or `if a is not None`. # + [markdown] slideshow={"slide_type": "slide"} # In many cases, we hold information for entities in *records*, which are collections of *attributes*. # # In that case, we want to search for an entity based on a particular attribute that identifies it. # # The attribute is called a *key*. # + [markdown] slideshow={"slide_type": "slide"} # In Python we can represent records as *objects* that are instances of a class. # # Alternatively, we can represent them as dictionaries. # # In fact, Python objects use dictionaries internally. # # Let's get a list of two persons. # + slideshow={"slide_type": "slide"} john = { 'first_name': 'John', 'surname': 'Doe', 'passport_no': 'AI892495', 'year_of_birth': 1990, 'occupation': 'teacher' } jane = { 'first_name': 'Jane', 'surname': 'Roe', 'passport_no': 'AI485713', 'year_of_birth': 1986, 'occupation': 'civil engineer' } persons = [john, jane] # + [markdown] slideshow={"slide_type": "slide"} # In this example, the key for our search would be the passport number, because we would like to find the full information for a person with that particular piece of identification. # # To do that we could re-implement sequential search so that we provide to it the comparison function. # + slideshow={"slide_type": "fragment"} def sequential_search_m(a, s, matches): for i, element in enumerate(a): if matches(element, s): return i return -1 def match_passport(person, passport_no): return person['passport_no'] == passport_no pos = sequential_search_m(persons, 'AI485713', match_passport) print(persons[pos], 'found at', pos) # + [markdown] slideshow={"slide_type": "slide"} # Although you would probably use something more Pythonic like: # + slideshow={"slide_type": "fragment"} results = [(i, p) for i, p in enumerate(persons) if p['passport_no'] == 'AI485713'] results # + [markdown] slideshow={"slide_type": "slide"} # ## Self-Organizing Search # # In self-organizing search, we take advantage of an item's popularity to move it to the front of the collection in which we are performing our searches. # # In the move-to-front method, when we find an item we move it directly to the front. # # In the transposition method, when we find an item we swap it with its predecessor (if any). # + [markdown] slideshow={"slide_type": "slide"} # We cannot implement directly the algorithms for lists given in the book (that is, algorithm 11.2 and algorithm 11.3) for the simple reason that Python hides the list implementation from us. # # Moreover, Python lists are *not* linked lists. They are variable-length arrays (see the online documentation for details on the [implementation of lists in Python](https://docs.python.org/3/faq/design.html#how-are-lists-implemented)). # # We can implement algorithm 11.3, which is the transposition method for arrays. # + slideshow={"slide_type": "slide"} def transposition_search(a, s): for i, item in enumerate(a): if item == s: if i > 0: a[i-1], a[i] = a[i], a[i-1] return i-1 else: return i return -1 # + [markdown] slideshow={"slide_type": "slide"} # How can we test `transposition_search(a, s)`? # # We need to do some groundwork to emulate a situation of popularity-biased searches. # # In particular, we will create a setting where the items we are searching for are governed by Zipf's law. # # First, we'll write a function that provides the Zipf probability for $n$ items. # + slideshow={"slide_type": "slide"} def zipf(n): h = 0 for x in range(1, n+1): h += 1/x z = [ 1/x * 1/h for x in range(1, n+1) ] return z # + [markdown] slideshow={"slide_type": "slide"} # We'll work with 1000 items: # + slideshow={"slide_type": "fragment"} zipf_1000 = zipf(1000) # + [markdown] slideshow={"slide_type": "slide"} # We can check that they sum up to 1, and see the first 20 of the probabilities. # + slideshow={"slide_type": "fragment"} print(sum(zipf_1000)) print(zipf_1000[:20]) # + [markdown] slideshow={"slide_type": "slide"} # Again we will be performing our searches on 1000 items, in random order. # + slideshow={"slide_type": "fragment"} a = list(range(1000)) random.shuffle(a) print(a[:20]) # + [markdown] slideshow={"slide_type": "slide"} # We will perform 100000 searches among these items. # # We want the searches to follow Zipf's law. # # First, we will create another list of 1000 items in random order. # + slideshow={"slide_type": "fragment"} b = list(range(1000)) random.shuffle(b) print(b[:20]) # + [markdown] slideshow={"slide_type": "slide"} # Then, we will select 100000 items from the second list, using the Zipf probabilities. # # That means that we will be selecting the first item with probability `zipf_1000[0]`, the second item with probability `zipf_1000[1]`, and so on. # # + slideshow={"slide_type": "fragment"} searches = random.choices(b, weights=zipf_1000, k=100000) # + [markdown] slideshow={"slide_type": "slide"} # Indeed, we can verify that the popularity of items in `searches` mirrors `b`: # + slideshow={"slide_type": "fragment"} from collections import Counter counted = Counter(searches) counted.most_common(20) # + [markdown] slideshow={"slide_type": "slide"} # So, we will perform 100000 searches in the first list, using as keys the items in `searches`. # # Because `transposition_search(a, s)` changes `a`, we will keep a copy of it to use it to compare the performance with simple sequential search. # # At the end, apart from displaying the time elapsed we will also show the first items of the changed `a`, to see how popular searches have gone to the beginning. # + slideshow={"slide_type": "slide"} a_copy = a[:] total_elapsed = 0 for s in searches: start = timeit.default_timer() index = transposition_search(a, s) end = timeit.default_timer() total_elapsed += end - start print(total_elapsed) print(a[:20]) # + [markdown] slideshow={"slide_type": "slide"} # We will now perform the same searches with `a_copy` using simple sequential search. # + slideshow={"slide_type": "slide"} total_elapsed = 0 for s in searches: start = timeit.default_timer() index = sequential_search(a_copy, s) end = timeit.default_timer() total_elapsed += end - start print(total_elapsed) # + [markdown] slideshow={"slide_type": "slide"} # ## The Secretary Problem # # The secretary problem requires selecting the best item when we have not seen, and we cannot wait to see, the full sets of items. # # The solution is an online algorithm. We find the best item among the first $n/e$, where $n$ is the total expected number of items, and $e \approx 2.71828$ is [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant). # # Then we select the first of the remaining items that is better than that. The probability that we'll indeed select the best item is $n/e \approx 37\%$. # # Here is how we can do that: # + slideshow={"slide_type": "slide"} import math def secretary_search(a): # Calculate |a|/n items. m = int((len(a) // math.e) + 1) # Find the best among the first |a|/n. c = 0 for i in range(1, m): if a[i] > a[c]: c = i # Get the first that is better from the one # we found, if possible. for i in range(m, len(a)): if a[i] > a[c]: return i return - 1 # + [markdown] slideshow={"slide_type": "slide"} # Does `secretary_search(a)` find the best item in `a` about 37% of the time? # # To check that, we'll continue working in a similar fashion. We'll perform 1000 searches in 1000 items and see how often we do come up with the best item. # + slideshow={"slide_type": "slide"} total_found = 0 for i in range(1000): a = list(range(1000)) random.shuffle(a) index = secretary_search(a) max_index = a.index(max(a)) if index == max_index: total_found += 1 print(f"found {total_found} out of {i+1}, {100*total_found/(i+1)}%") # + [markdown] slideshow={"slide_type": "slide"} # ## Binary Search # # Binary search is the most efficient way to search for an item when the search space is *ordered*. # # It is an iterative algorithm, where in each iteration we split the search space in half. # # We start by asking if the search item is in the middle of the search space. Let's assume that the items are ordered in ascending orded. # # If it is greater than the item in the middle, we repeat the question on the right part of the search space; it it is smaller, we repeat the question on the left part of the search space. We continue until we find the item, or we cannot perform a split any more. # + slideshow={"slide_type": "slide"} def binary_search(a, item): # Initialize borders of search space. low = 0 high = len(a) - 1 # While the search space is not empty: while low <= high: # Split the search space in the middle. mid = low + (high - low) // 2 # Compare with midpoint. c = (a[mid] > item) - (a[mid] < item) # If smaller, repeat on the left half. if c < 0: low = mid + 1 # If greater, repeat on the right half. elif c > 0: high = mid - 1 # If found, we are done. else: return mid return -1 # + [markdown] slideshow={"slide_type": "slide"} # In Python 3 there is no `cmp(x, y)` function that compares `x` and `y` and returns -1, 0, or 1, if `x > y`, `x == y`, or `x < y`, respectively. We use the # ```python # (x > y) - (y < x)``` # idiom instead. # # Note also the line where we calculate the midpoint: # ```python # mid = low + (high - low) // 2 # ``` # # This guards against overflows. In Python that is not necessary, because there is no upper limit in integers, so it could be: # ```python # mid = (low + high) // 2 # ``` # # However, this is a problem in most other languages, so we'll stick with the foolproof version. # + [markdown] slideshow={"slide_type": "slide"} # To see how binary search works we can add some tracing information in `binary_search(a, item)`: # + slideshow={"slide_type": "slide"} def binary_search_trace(a, item): print("Searching for", item) # Initialize borders of search space. low = 0 high = len(a) - 1 # While the search space is not empty: while low <= high: # Split the search space in the middle. mid = low + (high - low) // 2 # Compare with midpoint. c = (a[mid] > item) - (a[mid] < item) print(f"({low}, {a[low]}), ({mid}, {a[mid]}), ({high}, {a[high]})") # If smaller, repeat on the left half. if c < 0: low = mid + 1 # If greater, repeat on the right half. elif c > 0: high = mid - 1 # If found, we are done. else: return mid return -1 a = [4, 10, 31, 65, 114, 149, 181, 437, 480, 507, 551, 613, 680, 777, 782, 903] binary_search_trace(a, 149) binary_search_trace(a, 181) binary_search_trace(a, 583) binary_search_trace(a, 450) binary_search_trace(a, 3) # + [markdown] slideshow={"slide_type": "slide"} # Binary search is very efficient&mdash;in fact, it is as efficient as a search method can be (there is a smalll caveat here, concerning searching in quantum computers, but we can leave that aside). # # If have have $n$ items, it will complete the search in $O(\lg(n))$. # # Once again, we can verify that theory agrees with practice. We will perform 1000 searches, 500 of them successful and 500 of them unsuccessful and count the average number of iterations required. To do that, we'll change `binary_search(a, item)` so that it also returns the number of iterations. # + slideshow={"slide_type": "slide"} def binary_search_count(a, item): # Initialize borders of search space. low = 0 high = len(a) - 1 i = 0 # While the search space is not empty: while low <= high: i += 1 # Split the search space in the middle. mid = low + (high - low) // 2 # Compare with midpoint. c = (a[mid] > item) - (a[mid] < item) # If smaller, repeat on the left half. if c < 0: low = mid + 1 # If greater, repeat on the right half. elif c > 0: high = mid - 1 # If found, we are done. else: return (i, mid) return (i, -1) # + [markdown] slideshow={"slide_type": "slide"} # We build up our test suite. Our items will be 1000 random numbers in the range from 0 to 999,999. # # We will select 500 of them to perform matching searches, and another 500, not in them, to perform non-matching searches. # + slideshow={"slide_type": "fragment"} num_range = 1000000 # Get 1000 random numbers from 0 to 999999. a = random.sample(range(num_range), k=1000) # Select 500 from them for our matching searches. existing = random.sample(a, k=500) # Select another 500 random numbers in the range, # not in the set a, for our non-matching searches non_existing = random.sample(set(range(num_range)) - set(a), k=500) # Verify that the matching and non-matchin sets are distinct. print(set(existing) & set(non_existing)) # + [markdown] slideshow={"slide_type": "slide"} # So now we can see how the average number of iterations in practice fares compared to what predicted by theory. # + slideshow={"slide_type": "fragment"} total_iters = 0 for matching, non_matching in zip(existing, non_existing): matching_iters, _ = binary_search_count(a, matching) non_matching_iters, _ = binary_search_count(a, non_matching) total_iters += (matching_iters + non_matching_iters) print(f"Average iterations:", total_iters / (len(existing) + len(non_existing))) print(f"lg(1000) = {math.log(1000, 2)}")
content/notebooks/chapter_11.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] nbgrader={"grade": false, "grade_id": "q1_prompt", "locked": true, "schema_version": 1, "solution": false} # # Q1 # # In this question, we'll compute some basic probabilities of events using loops, lists, and dictionaries. # + [markdown] nbgrader={"grade": false, "grade_id": "q1a_prompt", "locked": true, "schema_version": 1, "solution": false} # ### Part A # # The [Polya urn model](https://en.wikipedia.org/wiki/P%C3%B3lya_urn_model) is a popular model for both statistics and to illustrate certain mental exercises. # # ![polyaurn](urn.png) # # Typically, these exercises involve randomly selecting colored balls, and these selection exercises can vary the properties of the remaining contents of the urn. A common question to ask is: given some number of colors and some number of balls, what are the chances of randomly selecting a ball of a specific color? # # Write a function which: # # - is named `urn_to_dict` # - takes 1 argument: a list of color names (e.g. "blue", "red", "green", etc) # - returns 1 value: a dictionary, with color names for keys and the frequency counts of those colors as values # # The contents of the urn will be handed to you in a list form (the input argument), where each element of the list represents a ball in an urn, and the element itself will be a certain color. You then need to count how many times each color occurs in the list, and assemble those counts in the dictionary that your function should return. # # For example, the list `["blue", "blue", "green", "blue"]` should result in the dictionary `{"blue": 3, "green": 1}`. Use the `urn_dict` dictionary object to store the results. # + nbgrader={"grade": false, "grade_id": "q1a", "locked": false, "schema_version": 1, "solution": true} # + nbgrader={"grade": true, "grade_id": "q1a_test1", "locked": true, "points": 4.0, "schema_version": 1, "solution": false} u1 = ["green", "green", "blue", "green"] a1 = set({("green", 3), ("blue", 1)}) assert a1 == set(urn_to_dict(u1).items()) # + nbgrader={"grade": true, "grade_id": "q1a_test2", "locked": true, "points": 5, "schema_version": 1, "solution": false} u2 = ["red", "blue", "blue", "green", "yellow", "black", "black", "green", "blue", "yellow", "red", "green", "blue", "black", "yellow", "yellow", "yellow", "green", "blue", "red", "red", "blue", "red", "blue", "yellow", "yellow", "yellow"] a2 = set({('black', 3), ('blue', 7), ('green', 4), ('red', 5), ('yellow', 8)}) assert a2 == set(urn_to_dict(u2).items()) # + [markdown] nbgrader={"grade": false, "grade_id": "q1b_prompt", "locked": true, "schema_version": 1, "solution": false} # ### Part B # # In this part, you'll write code to compute the probabilities of certain colors using the dictionary object in the previous part. Your code will receive a dictionary of colors with their relative counts (i.e., the output of Part A), and a "query" color, and you will need to return the chances of randomly selecting a ball of that query color. # # Write a function which: # # - is named `chances_of_color` # - takes 2 arguments: a dictionary mapping colors to counts (output of Part A), and a string that will contain a query color # - returns 1 value: a floating-point number, the probability of selecting the "query" color at random # # Remember, probability is a fraction: the numerator is the number of occurrences of the event you're interested in, and the denominator is the number of all possible events. It's kind of like an average. # # For example, if the input dictionary is `{"red": 3, "blue": 1}` and the query color is `"blue"`, then the fraction you would return is `1/4`, or 0.25 (probabilities should **always** be between 0 and 1). # + nbgrader={"grade": false, "grade_id": "q1b", "locked": false, "schema_version": 1, "solution": true} # + nbgrader={"grade": true, "grade_id": "q1b_test1", "locked": true, "points": 5.0, "schema_version": 1, "solution": false} import numpy.testing as t c1 = {"blue": 3, "red": 1} t.assert_allclose(chances_of_color(c1, "blue"), 0.75) # + nbgrader={"grade": true, "grade_id": "q1b_test2", "locked": true, "points": 5.0, "schema_version": 1, "solution": false} import numpy.testing as t c2 = {"red": 934, "blue": 493859, "yellow": 31, "green": 3892, "black": 487} t.assert_allclose(chances_of_color(c2, "green"), 0.007796427505443677) # + nbgrader={"grade": true, "grade_id": "q1b_test3", "locked": true, "points": 4.0, "schema_version": 1, "solution": false} import numpy.testing as t c3 = {"red": 5, "blue": 5, "yellow": 5, "green": 5, "black": 5} t.assert_allclose(chances_of_color(c2, "orange"), 0.0) # + [markdown] nbgrader={"grade": false, "grade_id": "q1c_prompt", "locked": true, "schema_version": 1, "solution": false} # ### Part C # # In this part, you'll do the opposite of what you implemented in Part B: you'll get a dictionary and a query color, but you'll need to return the chances of drawing a ball that is *not* the same color as the query. # # Write a function which: # # - is named `chances_of_not_color` # - takes 2 arguments: a dictionary mapping colors to counts (output of Part A), and a string that will contain a query color # - returns 1 value: a floating-point number, the probability of **NOT** selecting the "query" color at random # # For example, if the input dictionary is `{"red": 3, "blue": 1}` and the query color is `"blue"`, then the fraction you would return is `3/4`, or 0.75. # # HINT: You can use the function you wrote in Part B to help! # + nbgrader={"grade": false, "grade_id": "q1c", "locked": false, "schema_version": 1, "solution": true} # + nbgrader={"grade": true, "grade_id": "q1c_test1", "locked": true, "points": 5.0, "schema_version": 1, "solution": false} import numpy.testing as t c1 = {"blue": 3, "red": 1} t.assert_allclose(chances_of_not_color(c1, "blue"), 0.25) # + nbgrader={"grade": true, "grade_id": "q1c_test2", "locked": true, "points": 5.0, "schema_version": 1, "solution": false} import numpy.testing as t c2 = {"red": 934, "blue": 493859, "yellow": 31, "green": 3892, "black": 487} t.assert_allclose(chances_of_not_color(c2, "blue"), 0.010705063871811693) # + nbgrader={"grade": true, "grade_id": "q1c_test3", "locked": true, "points": 4.0, "schema_version": 1, "solution": false} import numpy.testing as t c3 = {"red": 5, "blue": 5, "yellow": 5, "green": 5, "black": 5} t.assert_allclose(chances_of_not_color(c2, "orange"), 1.0) # + [markdown] nbgrader={"grade": false, "grade_id": "q1d_prompt", "locked": true, "schema_version": 1, "solution": false} # ### Part D # # Even more interesting is when we start talking about combinations of colors. Let's say I'm reaching into a Polya urn to pull out *two* balls; it's valuable to know what my chances of *at least 1 ball* being a certain color would be. # # Write a function which: # # - is named `select_chances` # - takes 3 arguments: a list of colors of balls in an urn (same as input to Part A), an integer number (number of balls to draw out of the urn), and a string containing a single color # - returns 1 value: a floating-point number, the probability that at least one ball from the "number" drawn from the urn is the specified color # # Remember, you compute probability exactly as before--the number of events of interest (selecting a certain number of balls with at least one of a certain color) divided by the total number of possible events (all possible draws)--only this time you'll need to account for *combinations* of multiple balls. # # For example, if I give you an urn list of `["blue", "green", "red"]`, the number `2`, and the query color `"blue"`, then you would return `2/3`, or 0.66666 (There are three possible combinations of groupings of 2 balls: blue-green, blue-red, and green-red. Two of these three combinations contain the query color blue). # # *HINT*: It will be very, very helpful if make use of the `itertools` module for generating combinations of colored balls. If you can't remember how the module works, [consult its documentation](https://docs.python.org/3/library/itertools.html). Seriously though, it will vastly simplify your life in this question. # + nbgrader={"grade": false, "grade_id": "q1d", "locked": false, "schema_version": 1, "solution": true} # + nbgrader={"grade": true, "grade_id": "q1d_test1", "locked": true, "points": 4.0, "schema_version": 1, "solution": false} import numpy.testing as t q1 = ["blue", "green", "red"] t.assert_allclose(select_chances(q1, 2, "red"), 2/3) # + nbgrader={"grade": true, "grade_id": "q1d_test2", "locked": true, "points": 5, "schema_version": 1, "solution": false} q2 = ["red", "blue", "blue", "green", "yellow", "black", "black", "green", "blue", "yellow", "red", "green", "blue", "black", "yellow", "yellow", "yellow", "green", "blue", "red", "red", "blue", "red", "blue", "yellow", "yellow", "yellow"] t.assert_allclose(select_chances(q2, 3, "red"), 0.4735042735042735) # + [markdown] nbgrader={"grade": false, "grade_id": "q1e_prompt", "locked": true, "schema_version": 1, "solution": false} # ### Part E # # One final wrinkle: let's say I'm no longer picking colored balls simultaneously from the urn, but rather in sequence--that is, one right after the other. Now I can ask, for a given urn and a certain number of balls I'm going to pick, what are the chances that I draw a ball of a certain color *first*? # # For example, if I give you an urn list of `["blue", "green", "red"]`, the number `2`, and the query color `"blue"`, then you would return `2/6`, or 0.33333. # # (There are six possible ways of drawing two balls in sequence: # - BLUE then GREEN # - BLUE then RED # - GREEN then BLUE # - GREEN then RED # - RED then GREEN # - RED then BLUE # # and two of those six involve drawing the blue one first) # # Write a function which: # # - is named `select_chances_first` # - takes 3 arguments: a list of colors in the urn (same input as Part A and Part D), an integer number of balls to draw in sequence, and a string containing the query color for the first draw # - returns 1 value: a floating-point number, the probability of drawing the query color first in a sequence of draws of the specified length # # You are welcome to again use `itertools`. # + nbgrader={"grade": false, "grade_id": "q1e", "locked": false, "schema_version": 1, "solution": true} # + nbgrader={"grade": true, "grade_id": "q1e_test1", "locked": true, "points": 4.0, "schema_version": 1, "solution": false} import numpy.testing as t q1 = ["blue", "green", "red"] t.assert_allclose(select_chances_first(q1, 2, "red"), 2/6) # + nbgrader={"grade": true, "grade_id": "q1e_test2", "locked": true, "points": 5, "schema_version": 1, "solution": false} q2 = ["red", "blue", "blue", "green", "yellow", "black", "black", "green", "blue", "yellow", "red", "green", "blue", "black", "yellow", "yellow", "yellow", "green", "blue", "red", "red", "blue", "red", "blue", "yellow", "yellow", "yellow"] t.assert_allclose(select_chances_first(q2, 3, "red"), 0.18518518518518517)
assignments/A6/A6_Q1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] lc_cell_meme={"current": "fe1ca510-c280-11ea-87c0-0242ac110002-2-21aa-741f", "history": [{"current": "fe1ca510-c280-11ea-87c0-0242ac110002-2-21aa-741f", "next": "fe1ca5ce-c280-11ea-87c0-0242ac110002", "previous": null}], "next": "fe1ca510-c280-11ea-87c0-0242ac110002-1-f2f4", "previous": null} # # ステージ3 # # このステージ3の概要を説明する。 # + [markdown] lc_cell_meme={"current": "fe1ca510-c280-11ea-87c0-0242ac110002-1-f2f4", "history": [{"current": "fe1ca510-c280-11ea-87c0-0242ac110002-1-f2f4", "next": "fe1ca5ce-c280-11ea-87c0-0242ac110002", "previous": null}], "next": "fe1ca5ce-c280-11ea-87c0-0242ac110002-1-1bc3", "previous": "fe1ca510-c280-11ea-87c0-0242ac110002-2-21aa-741f"} # ## 後始末 # + lc_cell_meme={"current": "fe1ca5ce-c280-11ea-87c0-0242ac110002-1-1bc3", "history": [{"current": "fe1ca5ce-c280-11ea-87c0-0242ac110002-1-1bc3", "next": null, "previous": "fe1ca510-c280-11ea-87c0-0242ac110002"}], "next": null, "previous": "fe1ca510-c280-11ea-87c0-0242ac110002-1-f2f4"}
stage3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Pneumonia detection on chest X-rays # Pneumonia is an inflammatory condition of the lung affecting primarily the small air sacs known as alveoli.Symptoms typically include some combination of productive or dry cough, chest pain, fever and difficulty breathing. # The severity of the condition is variable. Pneumonia is usually caused by infection with viruses or bacteria and less commonly by other microorganisms, certain medications or conditions such as autoimmune diseases. # Risk factors include cystic fibrosis, chronic obstructive pulmonary disease (COPD), asthma, diabetes, heart failure, a history of smoking, a poor ability to cough such as following a stroke and a weak immune system. # Diagnosis is often based on symptoms and physical examination.Chest X-ray, blood tests, and culture of the sputum may help confirm the diagnosis. # The disease may be classified by where it was acquired, such as community- or hospital-acquired or healthcare-associated pneumonia. # #### Importing the necessary libraries import tensorflow as tf import keras from keras import Input from keras.preprocessing.image import ImageDataGenerator, load_img from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D,BatchNormalization from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K from keras.optimizers import Adam,SGD,RMSprop import os from os import listdir, makedirs, getcwd, remove import numpy as np import pandas as pd import glob2 import matplotlib.pyplot as plt from keras.utils import to_categorical from sklearn.preprocessing import LabelEncoder import os import scipy import skimage from skimage.transform import resize import glob import h5py import shutil import seaborn as sns import cv2 import random as rn from mlxtend.plotting import plot_confusion_matrix from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score # %matplotlib inline print(os.listdir('C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/chest_xray/train')) # The dataset is organized into 3 folders (train, test, val) and contains subfolders for each image category (Pneumonia/Normal). # There are 5,863 X-Ray images (JPEG) and 2 categories (Pneumonia/Normal). # #### preparing dataset # here we have checked type of our images in our dataset. #Since we are inputting 3 channels in our model so,images in our dataset must have 3 channels i.e.,RGB images. img_name = 'IM-0117-0001.jpeg' img_normal = load_img('C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/chest_xray/train/NORMAL/' + img_name) img = cv2.imread('C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/chest_xray/train/NORMAL/' + img_name) print(img.shape) print('NORMAL') plt.imshow(img_normal) plt.show() img_name = 'person63_bacteria_306.jpeg' img_pneumonia = load_img('C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/chest_xray/train/PNEUMONIA/' + img_name) print('PNEUMONIA') plt.imshow(img_pneumonia) plt.show() # In order to avoid overfitting problem, we need to expand artificially our dataset. We can make your existing dataset even larger. The idea is to alter the training data with small transformations to reproduce the variations. Approaches that alter the training data in ways that change the array representation while keeping the label the same are known as data augmentation techniques. Some popular augmentations people use are grayscales, horizontal flips, vertical flips, random crops, color jitters, translations, rotations, and much more. By applying just a couple of these transformations to our training data, we can easily double or triple the number of training examples and create a very robust model. img_width, img_height = 224,224 train_dir = 'C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/train' validation_dir ='C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/val' test_dir = 'C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/test' if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height,3) # #### Data augmentation and normalisation to avoide overfitting # + batch_size=10 train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) train_generator = train_datagen.flow_from_directory( train_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') # - test_datagen = ImageDataGenerator(rescale=1. / 255) validation_generator = test_datagen.flow_from_directory( validation_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') test_generator = test_datagen.flow_from_directory( test_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') # Since the target dataset is small, it is not a good idea to fine-tune the ConvNet due to the risk of overfitting. Since the target data is similar to the base data, we expect higher-level features in the ConvNet to be relevant to this dataset as well. Hence, we: # # 1. Remove the fully connected layers near the end of the pretrained base ConvNet # 2. Add a new fully connected layer that matches the number of classes in the target dataset # 3. Randomize the weights of the new fully connected layer and freeze all the weights from the pre-trained network # 4. Train the network to update the weights of the new fully connected layers # #### Importing VGG-16 model as our pretrained model with imagenet weights from keras.applications.resnet50 import ResNet50 base_model=ResNet50(include_top=False, weights='imagenet', input_shape=(224,224,3), pooling='avg') # #### Adding our own fully connected layers # + model=Sequential() model.add(base_model) model.add(Dense(256,activation='relu')) model.add(BatchNormalization()) model.add(Dense(1,activation='sigmoid')) for layer in base_model.layers[:15]: layer.trainable=False for layer in base_model.layers[15:]: layer.trainable=True model.summary() model.compile(optimizer=Adam(lr=1e-4),loss='binary_crossentropy',metrics=['accuracy']) # - history=model.fit_generator( train_generator, steps_per_epoch=10, epochs=50, validation_data=validation_generator,validation_steps=1) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend(['train', 'test']) plt.show() # #### model evaluation scores = model.evaluate_generator(test_generator) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) # #### preparing test data for other scores and prediction X=[] Y=[] normal_img_dir='C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/test/NORMAL' infected_img_dir='C:/Users/<NAME>/Desktop/X-ray dataset/17810_23812_bundle_archive (1)/chest_xray/test/PNEUMONIA' # + from tqdm import tqdm IMG_SIZE= 120 def locate_label(img,img_typ): return img_typ def test_data(img_typ,DIR): for img in tqdm(os.listdir(DIR)): label=locate_label(img,img_typ) path=os.path.join(DIR,img) img = cv2.imread(path,cv2.IMREAD_COLOR) img = cv2.resize(img, (IMG_SIZE,IMG_SIZE)) X.append(np.array(img)) Y.append((label)) # - test_data('0',normal_img_dir) print(len(X)) test_data('1',infected_img_dir) print(len(X)) # + fig,ax=plt.subplots(5,2) fig.set_size_inches(15,15) for i in range(5): for j in range (2): l=rn.randint(0,len(Y)) ax[i,j].imshow(X[l]) ax[i,j].set_title('objects: '+Y[l]) plt.tight_layout() # - e=LabelEncoder() E=e.fit_transform(Y) print(E) E=E.reshape(624,1) print(E) le=LabelEncoder() Z=le.fit_transform(Y) Z=to_categorical(Z,2) X=np.array(X) X=X/255 print(Z) # + y_pred = model.predict_classes(X) print(accuracy_score(np.argmax(Z, axis=1),y_pred)) # + preds = model.predict_classes(X, batch_size=10) print(preds) preds=preds.reshape(624,) #preds = np.argmax(preds, axis=0) # Original labels #orig_test_labels = np.argmax(Z, axis=-1) #print(orig_test_labels.shape) print(preds.shape) #print(preds) # - cm = confusion_matrix(E, preds) plt.figure() plot_confusion_matrix(cm,figsize=(12,8), hide_ticks=True,cmap=plt.cm.Blues) plt.xticks(range(2), ['Normal', 'Pneumonia'], fontsize=16) plt.yticks(range(2), ['Normal', 'Pneumonia'], fontsize=16) plt.show() # + # Calculate Precision and Recall tn, fp, fn, tp = cm.ravel() precision = tp/(tp+fp) recall = tp/(tp+fn) print("Recall of the model is {:.2f}".format(recall)) print("Precision of the model is {:.2f}".format(precision)) # - from sklearn.metrics import classification_report,confusion_matrix print(classification_report(E, preds, target_names = ['Pneumonia (Class 1)','Normal (Class 0)'])) del model K.clear_session()
pneumonia detection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import sys import matplotlib.pyplot as plt from skimage import io from scipy import ndimage as ndi from skimage import feature from skimage.filters import gaussian from skimage.filters import sobel from skimage.exposure import equalize_hist from skimage.exposure import equalize_adapthist from skimage.exposure import rescale_intensity from skimage.feature import canny from scipy.ndimage.morphology import binary_fill_holes from skimage.measure import label from skimage.measure import regionprops import pandas as pd sys.path.insert(0, '/Users/shrilakshmisbonageri/Desktop/UW/DIRECT/capstone/musical-robot/musicalrobot') frames = io.imread('../musicalrobot/data/CHCl_CA_DES_5_31_19.tiff') frames.shape plt.imshow(frames[1]) plt.colorbar() # ### Adding all the images in the frame to get a better contrast and reduce noise for II in range(frames.shape[0]): frame = frames[II] img_eq = (frame - np.amin(frame))/(np.amax(frame)-np.amin(frame)) if II == 0: img_ave = img_eq else: img_ave = img_ave + img_eq img_average = img_ave/frames.shape[0] img_eq = (img_ave - np.amin(img_ave))/(np.amax(img_ave)-np.amin(img_ave)) plt.imshow(img_eq) # gaus = gaussian(img_eq,sigma=0.25) # sob = sobel(img_eq) contrast = equalize_adapthist(img_eq, clip_limit=0.01) plt.imshow(contrast) plt.colorbar() edges = feature.canny(contrast, sigma=1) plt.imshow(edges) stretch = rescale_intensity(contrast) plt.imshow(stretch) edges1 = feature.canny(stretch) plt.imshow(edges1) rows = img_eq.shape[0] columns = img_eq.shape[1] column_sum = [] for i in range(0,columns): column_sum.append(sum(img_eq[:,i])) row_sum = [] for j in range(0,rows): row_sum.append(sum(img_eq[j,:])) plt.plot(np.arange(len(column_sum)),column_sum) plt.plot(np.arange(len(row_sum)),row_sum) column_sum = [x * -1 for x in column_sum] row_sum = [x * -1 for x in row_sum] from scipy.signal import find_peaks column_troughs = find_peaks(column_sum,distance=10) row_troughs = find_peaks(row_sum,distance=10) row_troughs = row_troughs[0] column_troughs = column_troughs[0] row_troughs # + # loc = np.ones((8,12)) # i = 0 # j = 0 # for element_y in row_troughs: # for element_x in column_troughs: # loc[i][j] = [[element_x,element_y]] # j = j + 1 # i = i + 1 # - i X = [] Y = [] i = 0 j = 0 for i in range(0,8): for j in range(0,12): X.append(column_troughs[j]) j = j + 1 Y.append(row_troughs[i]) i = i + 1 well_location = pd.DataFrame(list(zip(X, Y)),columns =['X', 'Y']) well_location flatplate = io.imread('../musicalrobot/data/Proline_MA_DES_5_31_19_flat_plate_1.jpeg',as_gray=True) plt.imshow(flatplate) flat_edges = feature.canny(flatplate) plt.imshow(flat_edges)
scripts/edge_detection_31.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # + [markdown] origin_pos=0 # # Information Theory # :label:`sec_information_theory` # # The universe is overflowing with information. Information provides a common language across disciplinary rifts: from Shakespeare's Sonnet to researchers' paper on Cornell ArXiv, from Van Gogh's printing Starry Night to Beethoven's music Symphony No. 5, from the first programming language Plankalkül to the state-of-the-art machine learning algorithms. Everything must follow the rules of information theory, no matter the format. With information theory, we can measure and compare how much information is present in different signals. In this section, we will investigate the fundamental concepts of information theory and applications of information theory in machine learning. # # Before we get started, let us outline the relationship between machine learning and information theory. Machine learning aims to extract interesting signals from data and make critical predictions. On the other hand, information theory studies encoding, decoding, transmitting, and manipulating information. As a result, information theory provides fundamental language for discussing the information processing in machine learned systems. For example, many machine learning applications use the cross entropy loss as described in :numref:`sec_softmax`. This loss can be directly derived from information theoretic considerations. # # # ## Information # # Let us start with the "soul" of information theory: information. *Information* can be encoded in anything with a particular sequence of one or more encoding formats. Suppose that we task ourselves with trying to define a notion of information. What could be our starting point? # # Consider the following thought experiment. We have a friend with a deck of cards. They will shuffle the deck, flip over some cards, and tell us statements about the cards. We will try to assess the information content of each statement. # # First, they flip over a card and tell us, "I see a card." This provides us with no information at all. We were already certain that this was the case so we hope the information should be zero. # # Next, they flip over a card and say, "I see a heart." This provides us some information, but in reality there are only $4$ different suits that were possible, each equally likely, so we are not surprised by this outcome. We hope that whatever the measure of information, this event should have low information content. # # Next, they flip over a card and say, "This is the $3$ of spades." This is more information. Indeed there were $52$ equally likely possible outcomes, and our friend told us which one it was. This should be a medium amount of information. # # Let us take this to the logical extreme. Suppose that finally they flip over every card from the deck and read off the entire sequence of the shuffled deck. There are $52!$ different orders to the deck, again all equally likely, so we need a lot of information to know which one it is. # # Any notion of information we develop must conform to this intuition. Indeed, in the next sections we will learn how to compute that these events have $0\text{ bits}$, $2\text{ bits}$, $~5.7\text{ bits}$, and $~225.6\text{ bits}$ of information respectively. # # If we read through these thought experiments, we see a natural idea. As a starting point, rather than caring about the knowledge, we may build off the idea that information represents the degree of surprise or the abstract possibility of the event. For example, if we want to describe an unusual event, we need a lot information. For a common event, we may not need much information. # # In 1948, <NAME> published *A Mathematical Theory of Communication* :cite:`Shannon.1948` establishing the theory of information. In his article, Shannon introduced the concept of information entropy for the first time. We will begin our journey here. # # # ### Self-information # # Since information embodies the abstract possibility of an event, how do we map the possibility to the number of bits? Shannon introduced the terminology *bit* as the unit of information, which was originally created by <NAME>. So what is a "bit" and why do we use it to measure information? Historically, an antique transmitter can only send or receive two types of code: $0$ and $1$. Indeed, binary encoding is still in common use on all modern digital computers. In this way, any information is encoded by a series of $0$ and $1$. And hence, a series of binary digits of length $n$ contains $n$ bits of information. # # Now, suppose that for any series of codes, each $0$ or $1$ occurs with a probability of $\frac{1}{2}$. Hence, an event $X$ with a series of codes of length $n$, occurs with a probability of $\frac{1}{2^n}$. At the same time, as we mentioned before, this series contains $n$ bits of information. So, can we generalize to a math function which can transfer the probability $p$ to the number of bits? Shannon gave the answer by defining *self-information* # # $$I(X) = - \log_2 (p),$$ # # as the *bits* of information we have received for this event $X$. Note that we will always use base-2 logarithms in this section. For the sake of simplicity, the rest of this section will omit the subscript 2 in the logarithm notation, i.e., $\log(.)$ always refers to $\log_2(.)$. For example, the code "0010" has a self-information # # $$I(\text{"0010"}) = - \log (p(\text{"0010"})) = - \log \left( \frac{1}{2^4} \right) = 4 \text{ bits}.$$ # # We can calculate self information as shown below. Before that, let us first import all the necessary packages in this section. # # + origin_pos=3 tab=["tensorflow"] import tensorflow as tf def log2(x): return tf.math.log(x) / tf.math.log(2.) def nansum(x): return tf.reduce_sum(tf.where(tf.math.is_nan( x), tf.zeros_like(x), x), axis=-1) def self_information(p): return -log2(tf.constant(p)).numpy() self_information(1 / 64) # + [markdown] origin_pos=4 # ## Entropy # # As self-information only measures the information of a single discrete event, we need a more generalized measure for any random variable of either discrete or continuous distribution. # # # ### Motivating Entropy # # Let us try to get specific about what we want. This will be an informal statement of what are known as the *axioms of Shannon entropy*. It will turn out that the following collection of common-sense statements force us to a unique definition of information. A formal version of these axioms, along with several others may be found in :cite:`Csiszar.2008`. # # 1. The information we gain by observing a random variable does not depend on what we call the elements, or the presence of additional elements which have probability zero. # 2. The information we gain by observing two random variables is no more than the sum of the information we gain by observing them separately. If they are independent, then it is exactly the sum. # 3. The information gained when observing (nearly) certain events is (nearly) zero. # # While proving this fact is beyond the scope of our text, it is important to know that this uniquely determines the form that entropy must take. The only ambiguity that these allow is in the choice of fundamental units, which is most often normalized by making the choice we saw before that the information provided by a single fair coin flip is one bit. # # ### Definition # # For any random variable $X$ that follows a probability distribution $P$ with a probability density function (p.d.f.) or a probability mass function (p.m.f.) $p(x)$, we measure the expected amount of information through *entropy* (or *Shannon entropy*) # # $$H(X) = - E_{x \sim P} [\log p(x)].$$ # :eqlabel:`eq_ent_def` # # To be specific, if $X$ is discrete, $$H(X) = - \sum_i p_i \log p_i \text{, where } p_i = P(X_i).$$ # # Otherwise, if $X$ is continuous, we also refer entropy as *differential entropy* # # $$H(X) = - \int_x p(x) \log p(x) \; dx.$$ # # We can define entropy as below. # # + origin_pos=7 tab=["tensorflow"] def entropy(p): return nansum(- p * log2(p)) entropy(tf.constant([0.1, 0.5, 0.1, 0.3])) # + [markdown] origin_pos=8 # ### Interpretations # # You may be curious: in the entropy definition :eqref:`eq_ent_def`, why do we use an expectation of a negative logarithm? Here are some intuitions. # # First, why do we use a *logarithm* function $\log$? Suppose that $p(x) = f_1(x) f_2(x) \ldots, f_n(x)$, where each component function $f_i(x)$ is independent from each other. This means that each $f_i(x)$ contributes independently to the total information obtained from $p(x)$. As discussed above, we want the entropy formula to be additive over independent random variables. Luckily, $\log$ can naturally turn a product of probability distributions to a summation of the individual terms. # # Next, why do we use a *negative* $\log$? Intuitively, more frequent events should contain less information than less common events, since we often gain more information from an unusual case than from an ordinary one. However, $\log$ is monotonically increasing with the probabilities, and indeed negative for all values in $[0, 1]$. We need to construct a monotonically decreasing relationship between the probability of events and their entropy, which will ideally be always positive (for nothing we observe should force us to forget what we have known). Hence, we add a negative sign in front of $\log$ function. # # Last, where does the *expectation* function come from? Consider a random variable $X$. We can interpret the self-information ($-\log(p)$) as the amount of *surprise* we have at seeing a particular outcome. Indeed, as the probability approaches zero, the surprise becomes infinite. Similarly, we can interpret the entropy as the average amount of surprise from observing $X$. For example, imagine that a slot machine system emits statistical independently symbols ${s_1, \ldots, s_k}$ with probabilities ${p_1, \ldots, p_k}$ respectively. Then the entropy of this system equals to the average self-information from observing each output, i.e., # # $$H(S) = \sum_i {p_i \cdot I(s_i)} = - \sum_i {p_i \cdot \log p_i}.$$ # # # # ### Properties of Entropy # # By the above examples and interpretations, we can derive the following properties of entropy :eqref:`eq_ent_def`. Here, we refer to $X$ as an event and $P$ as the probability distribution of $X$. # # * Entropy is non-negative, i.e., $H(X) \geq 0, \forall X$. # # * If $X \sim P$ with a p.d.f. or a p.m.f. $p(x)$, and we try to estimate $P$ by a new probability distribution $Q$ with a p.d.f. or a p.m.f. $q(x)$, then $$H(X) = - E_{x \sim P} [\log p(x)] \leq - E_{x \sim P} [\log q(x)], \text{ with equality if and only if } P = Q.$$ Alternatively, $H(X)$ gives a lower bound of the average number of bits needed to encode symbols drawn from $P$. # # * If $X \sim P$, then $x$ conveys the maximum amount of information if it spreads evenly among all possible outcomes. Specifically, if the probability distribution $P$ is discrete with $k$-class $\{p_1, \ldots, p_k \}$, then $$H(X) \leq \log(k), \text{ with equality if and only if } p_i = \frac{1}{k}, \forall i.$$ If $P$ is a continuous random variable, then the story becomes much more complicated. However, if we additionally impose that $P$ is supported on a finite interval (with all values between $0$ and $1$), then $P$ has the highest entropy if it is the uniform distribution on that interval. # # # ## Mutual Information # # Previously we defined entropy of a single random variable $X$, how about the entropy of a pair random variables $(X, Y)$? We can think of these techniques as trying to answer the following type of question, "What information is contained in $X$ and $Y$ together compared to each separately? Is there redundant information, or is it all unique?" # # For the following discussion, we always use $(X, Y)$ as a pair of random variables that follows a joint probability distribution $P$ with a p.d.f. or a p.m.f. $p_{X, Y}(x, y)$, while $X$ and $Y$ follow probability distribution $p_X(x)$ and $p_Y(y)$, respectively. # # # ### Joint Entropy # # Similar to entropy of a single random variable :eqref:`eq_ent_def`, we define the *joint entropy* $H(X, Y)$ of a pair random variables $(X, Y)$ as # # $$H(X, Y) = −E_{(x, y) \sim P} [\log p_{X, Y}(x, y)]. $$ # :eqlabel:`eq_joint_ent_def` # # Precisely, on the one hand, if $(X, Y)$ is a pair of discrete random variables, then # # $$H(X, Y) = - \sum_{x} \sum_{y} p_{X, Y}(x, y) \log p_{X, Y}(x, y).$$ # # On the other hand, if $(X, Y)$ is a pair of continuous random variables, then we define the *differential joint entropy* as # # $$H(X, Y) = - \int_{x, y} p_{X, Y}(x, y) \ \log p_{X, Y}(x, y) \;dx \;dy.$$ # # We can think of :eqref:`eq_joint_ent_def` as telling us the total randomness in the pair of random variables. As a pair of extremes, if $X = Y$ are two identical random variables, then the information in the pair is exactly the information in one and we have $H(X, Y) = H(X) = H(Y)$. On the other extreme, if $X$ and $Y$ are independent then $H(X, Y) = H(X) + H(Y)$. Indeed we will always have that the information contained in a pair of random variables is no smaller than the entropy of either random variable and no more than the sum of both. # # $$ # H(X), H(Y) \le H(X, Y) \le H(X) + H(Y). # $$ # # Let us implement joint entropy from scratch. # # + origin_pos=11 tab=["tensorflow"] def joint_entropy(p_xy): joint_ent = -p_xy * log2(p_xy) # nansum will sum up the non-nan number out = nansum(joint_ent) return out joint_entropy(tf.constant([[0.1, 0.5], [0.1, 0.3]])) # + [markdown] origin_pos=12 # Notice that this is the same *code* as before, but now we interpret it differently as working on the joint distribution of the two random variables. # # # ### Conditional Entropy # # The joint entropy defined above the amount of information contained in a pair of random variables. This is useful, but oftentimes it is not what we care about. Consider the setting of machine learning. Let us take $X$ to be the random variable (or vector of random variables) that describes the pixel values of an image, and $Y$ to be the random variable which is the class label. $X$ should contain substantial information---a natural image is a complex thing. However, the information contained in $Y$ once the image has been show should be low. Indeed, the image of a digit should already contain the information about what digit it is unless the digit is illegible. Thus, to continue to extend our vocabulary of information theory, we need to be able to reason about the information content in a random variable conditional on another. # # In the probability theory, we saw the definition of the *conditional probability* to measure the relationship between variables. We now want to analogously define the *conditional entropy* $H(Y \mid X)$. We can write this as # # $$ H(Y \mid X) = - E_{(x, y) \sim P} [\log p(y \mid x)],$$ # :eqlabel:`eq_cond_ent_def` # # where $p(y \mid x) = \frac{p_{X, Y}(x, y)}{p_X(x)}$ is the conditional probability. Specifically, if $(X, Y)$ is a pair of discrete random variables, then # # $$H(Y \mid X) = - \sum_{x} \sum_{y} p(x, y) \log p(y \mid x).$$ # # If $(X, Y)$ is a pair of continuous random variables, then the *differential conditional entropy* is similarly defined as # # $$H(Y \mid X) = - \int_x \int_y p(x, y) \ \log p(y \mid x) \;dx \;dy.$$ # # # It is now natural to ask, how does the *conditional entropy* $H(Y \mid X)$ relate to the entropy $H(X)$ and the joint entropy $H(X, Y)$? Using the definitions above, we can express this cleanly: # # $$H(Y \mid X) = H(X, Y) - H(X).$$ # # This has an intuitive interpretation: the information in $Y$ given $X$ ($H(Y \mid X)$) is the same as the information in both $X$ and $Y$ together ($H(X, Y)$) minus the information already contained in $X$. This gives us the information in $Y$ which is not also represented in $X$. # # Now, let us implement conditional entropy :eqref:`eq_cond_ent_def` from scratch. # # + origin_pos=15 tab=["tensorflow"] def conditional_entropy(p_xy, p_x): p_y_given_x = p_xy/p_x cond_ent = -p_xy * log2(p_y_given_x) # nansum will sum up the non-nan number out = nansum(cond_ent) return out conditional_entropy(tf.constant([[0.1, 0.5], [0.2, 0.3]]), tf.constant([0.2, 0.8])) # + [markdown] origin_pos=16 # ### Mutual Information # # Given the previous setting of random variables $(X, Y)$, you may wonder: "Now that we know how much information is contained in $Y$ but not in $X$, can we similarly ask how much information is shared between $X$ and $Y$?" The answer will be the *mutual information* of $(X, Y)$, which we will write as $I(X, Y)$. # # Rather than diving straight into the formal definition, let us practice our intuition by first trying to derive an expression for the mutual information entirely based on terms we have constructed before. We wish to find the information shared between two random variables. One way we could try to do this is to start with all the information contained in both $X$ and $Y$ together, and then we take off the parts that are not shared. The information contained in both $X$ and $Y$ together is written as $H(X, Y)$. We want to subtract from this the information contained in $X$ but not in $Y$, and the information contained in $Y$ but not in $X$. As we saw in the previous section, this is given by $H(X \mid Y)$ and $H(Y \mid X)$ respectively. Thus, we have that the mutual information should be # # $$ # I(X, Y) = H(X, Y) - H(Y \mid X) − H(X \mid Y). # $$ # # Indeed, this is a valid definition for the mutual information. If we expand out the definitions of these terms and combine them, a little algebra shows that this is the same as # # $$I(X, Y) = E_{x} E_{y} \left\{ p_{X, Y}(x, y) \log\frac{p_{X, Y}(x, y)}{p_X(x) p_Y(y)} \right\}. $$ # :eqlabel:`eq_mut_ent_def` # # # We can summarize all of these relationships in image :numref:`fig_mutual_information`. It is an excellent test of intuition to see why the following statements are all also equivalent to $I(X, Y)$. # # * $H(X) − H(X \mid Y)$ # * $H(Y) − H(Y \mid X)$ # * $H(X) + H(Y) − H(X, Y)$ # # ![Mutual information's relationship with joint entropy and conditional entropy.](../img/mutual-information.svg) # :label:`fig_mutual_information` # # # In many ways we can think of the mutual information :eqref:`eq_mut_ent_def` as principled extension of correlation coefficient we saw in :numref:`sec_random_variables`. This allows us to ask not only for linear relationships between variables, but for the maximum information shared between the two random variables of any kind. # # Now, let us implement mutual information from scratch. # # + origin_pos=19 tab=["tensorflow"] def mutual_information(p_xy, p_x, p_y): p = p_xy / (p_x * p_y) mutual = p_xy * log2(p) # Operator nansum will sum up the non-nan number out = nansum(mutual) return out mutual_information(tf.constant([[0.1, 0.5], [0.1, 0.3]]), tf.constant([0.2, 0.8]), tf.constant([[0.75, 0.25]])) # + [markdown] origin_pos=20 # ### Properties of Mutual Information # # Rather than memorizing the definition of mutual information :eqref:`eq_mut_ent_def`, you only need to keep in mind its notable properties: # # * Mutual information is symmetric, i.e., $I(X, Y) = I(Y, X)$. # * Mutual information is non-negative, i.e., $I(X, Y) \geq 0$. # * $I(X, Y) = 0$ if and only if $X$ and $Y$ are independent. For example, if $X$ and $Y$ are independent, then knowing $Y$ does not give any information about $X$ and vice versa, so their mutual information is zero. # * Alternatively, if $X$ is an invertible function of $Y$, then $Y$ and $X$ share all information and $$I(X, Y) = H(Y) = H(X).$$ # # ### Pointwise Mutual Information # # When we worked with entropy at the beginning of this chapter, we were able to provide an interpretation of $-\log(p_X(x))$ as how *surprised* we were with the particular outcome. We may give a similar interpretation to the logarithmic term in the mutual information, which is often referred to as the *pointwise mutual information*: # # $$\mathrm{pmi}(x, y) = \log\frac{p_{X, Y}(x, y)}{p_X(x) p_Y(y)}.$$ # :eqlabel:`eq_pmi_def` # # We can think of :eqref:`eq_pmi_def` as measuring how much more or less likely the specific combination of outcomes $x$ and $y$ are compared to what we would expect for independent random outcomes. If it is large and positive, then these two specific outcomes occur much more frequently than they would compared to random chance (*note*: the denominator is $p_X(x) p_Y(y)$ which is the probability of the two outcomes were independent), whereas if it is large and negative it represents the two outcomes happening far less than we would expect by random chance. # # This allows us to interpret the mutual information :eqref:`eq_mut_ent_def` as the average amount that we were surprised to see two outcomes occurring together compared to what we would expect if they were independent. # # ### Applications of Mutual Information # # Mutual information may be a little abstract in it pure definition, so how does it related to machine learning? In natural language processing, one of the most difficult problems is the *ambiguity resolution*, or the issue of the meaning of a word being unclear from context. For example, recently a headline in the news reported that "Amazon is on fire". You may wonder whether the company Amazon has a building on fire, or the Amazon rain forest is on fire. # # In this case, mutual information can help us resolve this ambiguity. We first find the group of words that each has a relatively large mutual information with the company Amazon, such as e-commerce, technology, and online. Second, we find another group of words that each has a relatively large mutual information with the Amazon rain forest, such as rain, forest, and tropical. When we need to disambiguate "Amazon", we can compare which group has more occurrence in the context of the word Amazon. In this case the article would go on to describe the forest, and make the context clear. # # # ## Kullback–Leibler Divergence # # As what we have discussed in :numref:`sec_linear-algebra`, we can use norms to measure distance between two points in space of any dimensionality. We would like to be able to do a similar task with probability distributions. There are many ways to go about this, but information theory provides one of the nicest. We now explore the *Kullback–Leibler (KL) divergence*, which provides a way to measure if two distributions are close together or not. # # # ### Definition # # Given a random variable $X$ that follows the probability distribution $P$ with a p.d.f. or a p.m.f. $p(x)$, and we estimate $P$ by another probability distribution $Q$ with a p.d.f. or a p.m.f. $q(x)$. Then the *Kullback–Leibler (KL) divergence* (or *relative entropy*) between $P$ and $Q$ is # # $$D_{\mathrm{KL}}(P\|Q) = E_{x \sim P} \left[ \log \frac{p(x)}{q(x)} \right].$$ # :eqlabel:`eq_kl_def` # # As with the pointwise mutual information :eqref:`eq_pmi_def`, we can again provide an interpretation of the logarithmic term: $-\log \frac{q(x)}{p(x)} = -\log(q(x)) - (-\log(p(x)))$ will be large and positive if we see $x$ far more often under $P$ than we would expect for $Q$, and large and negative if we see the outcome far less than expected. In this way, we can interpret it as our *relative* surprise at observing the outcome compared to how surprised we would be observing it from our reference distribution. # # Let us implement the KL divergence from Scratch. # # + origin_pos=23 tab=["tensorflow"] def kl_divergence(p, q): kl = p * log2(p / q) out = nansum(kl) return tf.abs(out).numpy() # + [markdown] origin_pos=24 # ### KL Divergence Properties # # Let us take a look at some properties of the KL divergence :eqref:`eq_kl_def`. # # * KL divergence is non-symmetric, i.e., there are $P,Q$ such that $$D_{\mathrm{KL}}(P\|Q) \neq D_{\mathrm{KL}}(Q\|P).$$ # * KL divergence is non-negative, i.e., $$D_{\mathrm{KL}}(P\|Q) \geq 0.$$ Note that the equality holds only when $P = Q$. # * If there exists an $x$ such that $p(x) > 0$ and $q(x) = 0$, then $D_{\mathrm{KL}}(P\|Q) = \infty$. # * There is a close relationship between KL divergence and mutual information. Besides the relationship shown in :numref:`fig_mutual_information`, $I(X, Y)$ is also numerically equivalent with the following terms: # 1. $D_{\mathrm{KL}}(P(X, Y) \ \| \ P(X)P(Y))$; # 1. $E_Y \{ D_{\mathrm{KL}}(P(X \mid Y) \ \| \ P(X)) \}$; # 1. $E_X \{ D_{\mathrm{KL}}(P(Y \mid X) \ \| \ P(Y)) \}$. # # For the first term, we interpret mutual information as the KL divergence between $P(X, Y)$ and the product of $P(X)$ and $P(Y)$, and thus is a measure of how different the joint distribution is from the distribution if they were independent. For the second term, mutual information tells us the average reduction in uncertainty about $Y$ that results from learning the value of the $X$'s distribution. Similarly to the third term. # # # ### Example # # Let us go through a toy example to see the non-symmetry explicitly. # # First, let us generate and sort three tensors of length $10,000$: an objective tensor $p$ which follows a normal distribution $N(0, 1)$, and two candidate tensors $q_1$ and $q_2$ which follow normal distributions $N(-1, 1)$ and $N(1, 1)$ respectively. # # + origin_pos=27 tab=["tensorflow"] tensor_len = 10000 p = tf.random.normal((tensor_len, ), 0, 1) q1 = tf.random.normal((tensor_len, ), -1, 1) q2 = tf.random.normal((tensor_len, ), 1, 1) p = tf.sort(p) q1 = tf.sort(q1) q2 = tf.sort(q2) # + [markdown] origin_pos=28 # Since $q_1$ and $q_2$ are symmetric with respect to the y-axis (i.e., $x=0$), we expect a similar value of KL divergence between $D_{\mathrm{KL}}(p\|q_1)$ and $D_{\mathrm{KL}}(p\|q_2)$. As you can see below, there is only a less than 3% off between $D_{\mathrm{KL}}(p\|q_1)$ and $D_{\mathrm{KL}}(p\|q_2)$. # # + origin_pos=29 tab=["tensorflow"] kl_pq1 = kl_divergence(p, q1) kl_pq2 = kl_divergence(p, q2) similar_percentage = abs(kl_pq1 - kl_pq2) / ((kl_pq1 + kl_pq2) / 2) * 100 kl_pq1, kl_pq2, similar_percentage # + [markdown] origin_pos=30 # In contrast, you may find that $D_{\mathrm{KL}}(q_2 \|p)$ and $D_{\mathrm{KL}}(p \| q_2)$ are off a lot, with around 40% off as shown below. # # + origin_pos=31 tab=["tensorflow"] kl_q2p = kl_divergence(q2, p) differ_percentage = abs(kl_q2p - kl_pq2) / ((kl_q2p + kl_pq2) / 2) * 100 kl_q2p, differ_percentage # + [markdown] origin_pos=32 # ## Cross Entropy # # If you are curious about applications of information theory in deep learning, here is a quick example. We define the true distribution $P$ with probability distribution $p(x)$, and the estimated distribution $Q$ with probability distribution $q(x)$, and we will use them in the rest of this section. # # Say we need to solve a binary classification problem based on given $n$ data examples {$x_1, \ldots, x_n$}. Assume that we encode $1$ and $0$ as the positive and negative class label $y_i$ respectively, and our neural network is parameterized by $\theta$. If we aim to find a best $\theta$ so that $\hat{y}_i= p_{\theta}(y_i \mid x_i)$, it is natural to apply the maximum log-likelihood approach as was seen in :numref:`sec_maximum_likelihood`. To be specific, for true labels $y_i$ and predictions $\hat{y}_i= p_{\theta}(y_i \mid x_i)$, the probability to be classified as positive is $\pi_i= p_{\theta}(y_i = 1 \mid x_i)$. Hence, the log-likelihood function would be # # $$ # \begin{aligned} # l(\theta) &= \log L(\theta) \\ # &= \log \prod_{i=1}^n \pi_i^{y_i} (1 - \pi_i)^{1 - y_i} \\ # &= \sum_{i=1}^n y_i \log(\pi_i) + (1 - y_i) \log (1 - \pi_i). \\ # \end{aligned} # $$ # # Maximizing the log-likelihood function $l(\theta)$ is identical to minimizing $- l(\theta)$, and hence we can find the best $\theta$ from here. To generalize the above loss to any distributions, we also called $-l(\theta)$ the *cross entropy loss* $\mathrm{CE}(y, \hat{y})$, where $y$ follows the true distribution $P$ and $\hat{y}$ follows the estimated distribution $Q$. # # This was all derived by working from the maximum likelihood point of view. However, if we look closely we can see that terms like $\log(\pi_i)$ have entered into our computation which is a solid indication that we can understand the expression from an information theoretic point of view. # # # ### Formal Definition # # Like KL divergence, for a random variable $X$, we can also measure the divergence between the estimating distribution $Q$ and the true distribution $P$ via *cross entropy*, # # $$\mathrm{CE}(P, Q) = - E_{x \sim P} [\log(q(x))].$$ # :eqlabel:`eq_ce_def` # # By using properties of entropy discussed above, we can also interpret it as the summation of the entropy $H(P)$ and the KL divergence between $P$ and $Q$, i.e., # # $$\mathrm{CE} (P, Q) = H(P) + D_{\mathrm{KL}}(P\|Q).$$ # # # We can implement the cross entropy loss as below. # # + origin_pos=35 tab=["tensorflow"] def cross_entropy(y_hat, y): ce = -tf.math.log(y_hat[:, :len(y)]) return tf.reduce_mean(ce) # + [markdown] origin_pos=36 # Now define two tensors for the labels and predictions, and calculate the cross entropy loss of them. # # + origin_pos=39 tab=["tensorflow"] labels = tf.constant([0, 2]) preds = tf.constant([[0.3, 0.6, 0.1], [0.2, 0.3, 0.5]]) cross_entropy(preds, labels) # + [markdown] origin_pos=40 # ### Properties # # As alluded in the beginning of this section, cross entropy :eqref:`eq_ce_def` can be used to define a loss function in the optimization problem. It turns out that the following are equivalent: # # 1. Maximizing predictive probability of $Q$ for distribution $P$, (i.e., $E_{x # \sim P} [\log (q(x))]$); # 1. Minimizing cross entropy $\mathrm{CE} (P, Q)$; # 1. Minimizing the KL divergence $D_{\mathrm{KL}}(P\|Q)$. # # The definition of cross entropy indirectly proves the equivalent relationship between objective 2 and objective 3, as long as the entropy of true data $H(P)$ is constant. # # # ### Cross Entropy as An Objective Function of Multi-class Classification # # If we dive deep into the classification objective function with cross entropy loss $\mathrm{CE}$, we will find minimizing $\mathrm{CE}$ is equivalent to maximizing the log-likelihood function $L$. # # To begin with, suppose that we are given a dataset with $n$ examples, and it can be classified into $k$-classes. For each data example $i$, we represent any $k$-class label $\mathbf{y}_i = (y_{i1}, \ldots, y_{ik})$ by *one-hot encoding*. To be specific, if the example $i$ belongs to class $j$, then we set the $j$-th entry to $1$, and all other components to $0$, i.e., # # $$ y_{ij} = \begin{cases}1 & j \in J; \\ 0 &\text{otherwise.}\end{cases}$$ # # For instance, if a multi-class classification problem contains three classes $A$, $B$, and $C$, then the labels $\mathbf{y}_i$ can be encoded in {$A: (1, 0, 0); B: (0, 1, 0); C: (0, 0, 1)$}. # # # Assume that our neural network is parameterized by $\theta$. For true label vectors $\mathbf{y}_i$ and predictions $$\hat{\mathbf{y}}_i= p_{\theta}(\mathbf{y}_i \mid \mathbf{x}_i) = \sum_{j=1}^k y_{ij} p_{\theta} (y_{ij} \mid \mathbf{x}_i).$$ # # Hence, the *cross entropy loss* would be # # $$ # \mathrm{CE}(\mathbf{y}, \hat{\mathbf{y}}) = - \sum_{i=1}^n \mathbf{y}_i \log \hat{\mathbf{y}}_i # = - \sum_{i=1}^n \sum_{j=1}^k y_{ij} \log{p_{\theta} (y_{ij} \mid \mathbf{x}_i)}.\\ # $$ # # On the other side, we can also approach the problem through maximum likelihood estimation. To begin with, let us quickly introduce a $k$-class multinoulli distribution. It is an extension of the Bernoulli distribution from binary class to multi-class. If a random variable $\mathbf{z} = (z_{1}, \ldots, z_{k})$ follows a $k$-class *multinoulli distribution* with probabilities $\mathbf{p} =$ ($p_{1}, \ldots, p_{k}$), i.e., $$p(\mathbf{z}) = p(z_1, \ldots, z_k) = \mathrm{Multi} (p_1, \ldots, p_k), \text{ where } \sum_{i=1}^k p_i = 1,$$ then the joint probability mass function(p.m.f.) of $\mathbf{z}$ is # $$\mathbf{p}^\mathbf{z} = \prod_{j=1}^k p_{j}^{z_{j}}.$$ # # # It can be seen that the label of each data example, $\mathbf{y}_i$, is following a $k$-class multinoulli distribution with probabilities $\boldsymbol{\pi} =$ ($\pi_{1}, \ldots, \pi_{k}$). Therefore, the joint p.m.f. of each data example $\mathbf{y}_i$ is $\mathbf{\pi}^{\mathbf{y}_i} = \prod_{j=1}^k \pi_{j}^{y_{ij}}.$ # Hence, the log-likelihood function would be # # $$ # \begin{aligned} # l(\theta) # = \log L(\theta) # = \log \prod_{i=1}^n \boldsymbol{\pi}^{\mathbf{y}_i} # = \log \prod_{i=1}^n \prod_{j=1}^k \pi_{j}^{y_{ij}} # = \sum_{i=1}^n \sum_{j=1}^k y_{ij} \log{\pi_{j}}.\\ # \end{aligned} # $$ # # Since in maximum likelihood estimation, we maximizing the objective function $l(\theta)$ by having $\pi_{j} = p_{\theta} (y_{ij} \mid \mathbf{x}_i)$. Therefore, for any multi-class classification, maximizing the above log-likelihood function $l(\theta)$ is equivalent to minimizing the CE loss $\mathrm{CE}(y, \hat{y})$. # # # To test the above proof, let us apply the built-in measure `NegativeLogLikelihood`. Using the same `labels` and `preds` as in the earlier example, we will get the same numerical loss as the previous example up to the 5 decimal place. # # + origin_pos=43 tab=["tensorflow"] def nll_loss(y_hat, y): # Convert labels to binary class matrix. y = tf.keras.utils.to_categorical(y, num_classes=3) # Since tf.keras.losses.binary_crossentropy returns the mean # over the last axis, we calculate the sum here. return tf.reduce_sum( tf.keras.losses.binary_crossentropy(y, y_hat, from_logits=True)) loss = nll_loss(tf.math.log(preds), labels) loss # + [markdown] origin_pos=44 # ## Summary # # * Information theory is a field of study about encoding, decoding, transmitting, and manipulating information. # * Entropy is the unit to measure how much information is presented in different signals. # * KL divergence can also measure the divergence between two distributions. # * Cross Entropy can be viewed as an objective function of multi-class classification. Minimizing cross entropy loss is equivalent to maximizing the log-likelihood function. # # # ## Exercises # # 1. Verify that the card examples from the first section indeed have the claimed entropy. # 1. Show that the KL divergence $D(p\|q)$ is nonnegative for all distributions $p$ and $q$. Hint: use Jensen's inequality, i.e., use the fact that $-\log x$ is a convex function. # 1. Let us compute the entropy from a few data sources: # * Assume that you are watching the output generated by a monkey at a typewriter. The monkey presses any of the $44$ keys of the typewriter at random (you can assume that it has not discovered any special keys or the shift key yet). How many bits of randomness per character do you observe? # * Being unhappy with the monkey, you replaced it by a drunk typesetter. It is able to generate words, albeit not coherently. Instead, it picks a random word out of a vocabulary of $2,000$ words. Let us assume that the average length of a word is $4.5$ letters in English. How many bits of randomness per character do you observe now? # * Still being unhappy with the result, you replace the typesetter by a high quality language model. The language model can currently obtain a perplexity as low as $15$ points per word. The character *perplexity* of a language model is defined as the inverse of the geometric mean of a set of probabilities, each probability is corresponding to a character in the word. To be specific, if the length of a given word is $l$, then $\mathrm{PPL}(\text{word}) = \left[\prod_i p(\text{character}_i)\right]^{ -\frac{1}{l}} = \exp \left[ - \frac{1}{l} \sum_i{\log p(\text{character}_i)} \right].$ Assume that the test word has 4.5 letters, how many bits of randomness per character do you observe now? # 1. Explain intuitively why $I(X, Y) = H(X) - H(X|Y)$. Then, show this is true by expressing both sides as an expectation with respect to the joint distribution. # 1. What is the KL Divergence between the two Gaussian distributions $\mathcal{N}(\mu_1, \sigma_1^2)$ and $\mathcal{N}(\mu_2, \sigma_2^2)$? # # + [markdown] origin_pos=47 tab=["tensorflow"] # [Discussions](https://discuss.d2l.ai/t/1105) #
d2l-en/tensorflow/chapter_appendix-mathematics-for-deep-learning/information-theory.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # #### Exercícios Python # Primeiro Exercício def freqdist(texto): d = {} lista = texto.split('\n') texto = ' '.join(lista) lista = texto.split(' ') for palavra in lista: palavra = palavra.strip().lower() if palavra not in d: d[palavra] = 1 else: d[palavra] += 1 return d confortablynumb = ''' Hello Is there anybody in there? Just nod if you can hear me Is there anyone at home? Come on now I hear you're feeling down Well, I can ease your pain And get you on your feet again Relax I'll need some information first Just the basic facts Can you show me where it hurts There is no pain, you are receding A distant ship's smoke on the horizon You are only coming through in waves Your lips move but I can't hear what you're saying When I was a child I had a fever My hands felt just like two balloons Now I've got that feeling once again I can't explain, you would not understand This is not how I am I have become comfortably numb I have become comfortably numb Ok Just a little pin prick There'll be no more Ah! But you might feel a little sick Can you stand up? I do belive it's working, good That'll keep you going, through the show Come on it's time to go. There is no pain you are receding A distant ship's smoke on the horizon You are only coming through in waves Your lips move, but I can't hear what you're saying When I was a child I caught a fleeting glimpse Out of the corner of my eye I turned to look but it was gone I cannot put my finger on it now The child is grown The dream is gone And I have become Comfortably num''' confortablynumb d = freqdist(confortablynumb) d import operator d2 = sorted(d.items(), key=operator.itemgetter(1), reverse=True) d2 # Segundo Exercício import nltk sw = nltk.corpus.stopwords.words('english') d3 = d.copy() for word in sw: if word in d3: print('Retirando palavra {}'.format(word)) d3.pop(word) d3 # Terceiro Exercício import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # + lista1 = [1,2,3,4,5,6] lista2 = [2,4,6,8,10,12] lista3 = [3,6,9,12,15,18] def plota_num(*listas): plt.figure() for lista in listas: plt.plot(lista,'o') plt.show() # - plota_num(lista1,lista2,lista3) # Quarto Exercício s = 'Minha STring com Algumas Palavras começando COM maiúsculas' l = s.split() s2 = filter(lambda x:x.istitle(),l) list(s2) # Quinto Exercício import requests url = 'http://emap.fgv.br' pagina = requests.get(url) texto = pagina.text lista_palavras = texto.split(' ') links = [p.strip() for p in lista_palavras if '://' in p] #for link in links: # print(link[link.find('http'):link.find('"',link.find('http'))]) emails = [p.strip() for p in lista_palavras if '@' in p] emails # Transposição de Matrizes M = np.arange(1,10).reshape(3,3) N = np.empty(9).reshape(3,3) for i in range(M.shape[0]): for j in range(M.shape[1]): N[i,j] = M[j,i] M M.T N.astype(int)
Exercises/draft/Exercicios_text_operations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Self-Consistent Dust Reddening # In [Mirocha, Mason, & Stark (2020)](https://ui.adsabs.harvard.edu/abs/2020arXiv200507208M/abstract), we describe a simple extension to the now-standard galaxy model in ARES that generates ultraviolet colours self-consistently, rather than invoking IRX-$\beta$ relations to perform a dust correction. Here, we describe how to work with these new models. # ### Preliminaries # # Before getting started, two lookup tables are required that don't ship by default with ARES (via the ``remote.py`` script; [see ARES installation](../install.html)): # # - A new halo mass function lookup table that employs the Tinker et al. 2010 results, rather than Sheth-Tormen (used in most earlier work with ARES). # - A lookup table of halo mass assembly histories. # # To create these yourself, you'll need the [hmf](https://github.com/steven-murray/hmf>) code, which is installable via pip. # # This should only take a few minutes even in serial. First, navigate to ``$ARES/input/hmf``, where you should see a few ``.hdf5`` files and Python scripts. Open the file ``generate_hmf_tables.py`` and make the following adjustments to the parameter dictionary: def_kwargs = \ { "hmf_model": 'Tinker10', "hmf_tmin": 30, "hmf_tmax": 2e3, "hmf_dt": 1, "cosmology_id": 'paul', "cosmology_name": 'user', "sigma_8": 0.8159, 'primordial_index': 0.9652, 'omega_m_0': 0.315579, 'omega_b_0': 0.0491, 'hubble_0': 0.6726, 'omega_l_0': 1. - 0.315579, } # The new HMF table will use constant 1 Myr time-steps, rather than the default redshift steps, and employ a cosmology designed to remain consistent with another project (led by a collaborator whose name you can probably guess)! # # Once you've run the ``generate_hmf_tables.py`` script, you should have a new file, ``hmf_Tinker10_user_paul_logM_1400_4-18_t_1971_30-2000.hdf5``, sitting inside ``$ARES/input/hmf``. Now, we're almost done. Simply execute: # # `python generate_halo_histories.py hmf_Tinker10_user_paul_logM_1400_4-18_t_1971_30-2000.hdf5` # # The additional resulting file, ``hgh_Tinker10_user_paul_logM_1400_4-18_t_1971_30-2000_xM_10_0.10.hdf5``, will be found automatically in subsequent calculations. # ### Example # # # With the required lookup tables now in hand, we can start in the usual way: # %pylab inline import ares import numpy as np import matplotlib.pyplot as pl # and read-in the best-fit parameters via pars = ares.util.ParameterBundle('mirocha2020:univ') # Now, we create a ``GalaxyPopulation`` object, pop = ares.populations.GalaxyPopulation(**pars) # which is an instance of the ``GalaxyEnsemble`` class, rather than the ``GalaxyCohort`` class, the latter of which is described in [this example](example_pop_galaxy). This offers a more general approach, including more complex star formation histories and proper treatment of spectral synthesis. # # We can plot the UVLF in the usual way, # + # First, some data obslf = ares.analysis.GalaxyPopulation() ax = obslf.PlotLF(z=6, round_z=0.2) # Now, the predicted/calibrated UVLF mags = np.arange(-25, -5, 0.1) phi = pop.LuminosityFunction(6, mags) ax.semilogy(mags, phi) # - # The main difference between these models and the simpler models (from, e.g., the ``mirocha2017`` parameter bundle) is access to UV colours. The following high-level routine will make a plot like Figure 4 from the paper: axes = obslf.PlotColors(pop, fig=2) # This will take order $\simeq 10$ seconds, as modeling UV colours requires synthesizing a reasonbly high resolution ($\Delta \lambda = 20 \unicode{x212B}$ by default) spectrum for each galaxy in the model, so that there are multiple points within photometric windows. You can adjust the keyword arguments ``z_uvlf`` and ``z_beta`` to see different redshifts, while ``sources`` will control the datasets being plotted. # # **NOTE:** Computing colors from fits in the [Calzetti et al. 1994](https://ui.adsabs.harvard.edu/abs/1994ApJ...429..582C/abstract>) windows requires higher resolution, given that these windows are each only $\Delta \lambda \sim 10 \unicode{x212B}$ wide. Adjust the ``dlam`` keyword argument to increase the wavelength-sampling used prior to photometric UV slope estimation. # # To access the magnitudes and colours more directly, you can do something like # + mags = pop.Magnitude(6., presets='hst') beta = pop.Beta(6., presets='hst') pl.scatter(mags, beta, alpha=0.1, color='b', edgecolors='none') # - # which computes the UV slope $\beta$ using the *Hubble* filters appropriate for the input redshift (see Table A1 in the paper). # # **NOTE:** Other ``presets`` include ``'jwst'``, ``'jwst-w'``, ``'jwst-m'``, and ``'calzetti1994'``. # # You can bin points in the $M_{\text{UV}}-\beta$ plane, if you prefer it, via the ``return_binned`` keyword argument, # + # Plot scatter in each MUV bin as errorbars mags = np.arange(-25, -10, 0.5) # bin centers beta, beta_s = pop.Beta(6., presets='hst', Mbins=mags, return_binned=True, return_scatter=True) pl.errorbar(mags, beta, yerr=beta_s.T, color='b', marker='s', fmt='o') # - # Recall that each galaxy in the model actually represents an "average" galaxy in some halo mass bin, i.e., there is not a 1:1 correspondence between galaxies and elements in ``mags`` and ``beta`` above, which is why we generally weight by halo abundance in each bin. The default mass-bins have $\Delta \log_{10} M_h = 0.01$ wide, within which ARES inject ``pop_thin_hist`` halos and down-weights their abundance accordingly. # # Lastly, to extract the "raw" galaxy population properties, like SFR, stellar mass, etc., you can use the ``get_field`` method, e.g., Ms = pop.get_field(6., 'Ms') # stellar mass Md = pop.get_field(6., 'Md') # dust mass Sd = pop.get_field(6., 'Sd') # dust surface density # etc. # To see what's available, check out pop.histories.keys() # From these simple commands, most plots and analyses from the paper can be reproduced in relatively short order. # ### Notes on performance # # The compute time for these models is determined largely by three factors: # # * The number of halos (really halo bins) we evolve forward in time. The default ``mirocha2020:univ`` models use $\Delta \log_{10} M_h = 0.01$ mass-bins, each with 10 halos (``pop_thin_hist=10``). For a larger sample, e.g., when lots of scatter is being employed, larger values of ``pop_thin_hist`` may be warranted. # * The number of observed redshifts at which $\beta$ is synthesize, since new spectra must be generated. # * The number of wavelengths used to sample the intrinsic UV spectrum of galaxies. When computing $\beta$ via photometry (Hubble or JWST), $\Delta \lambda = 20 \unicode{x212B}$ will generally suffice. # # For the models in [Mirocha, Mason, & Stark (2020)](https://ui.adsabs.harvard.edu/abs/2020arXiv200507208M/abstract>), with $\Delta \log_{10} M_h = 0.01$ (``hmf_logM=0.01``), ``pop_thin_hist=10``, calibrating at two redshifts for $\beta$ (4 and 6), with $\Delta \lambda = 20 \unicode{x212B}$, each model takes $\sim 10-20$ seconds, depending on your machine. # # **NOTE:** Generating the UVLF is essentially free compared to computing $\beta$. # # For more information on what's happening under the hood, e.g., with regards to spectral synthesis and noisy star-formation histories, see [Example: spectral synthesis](../example_pop_sps.html). #
docs/examples/example_pop_dusty.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] papermill={"duration": 0.01986, "end_time": "2020-09-26T13:34:40.716441", "exception": false, "start_time": "2020-09-26T13:34:40.696581", "status": "completed"} tags=[] # ## Dependencies # + _kg_hide-input=true papermill={"duration": 7.012383, "end_time": "2020-09-26T13:34:47.747786", "exception": false, "start_time": "2020-09-26T13:34:40.735403", "status": "completed"} tags=[] from openvaccine_scripts import * import warnings, json from sklearn.model_selection import KFold, StratifiedKFold import tensorflow.keras.layers as L import tensorflow.keras.backend as K from tensorflow.keras import optimizers, losses, Model from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau SEED = 0 seed_everything(SEED) warnings.filterwarnings('ignore') # + [markdown] papermill={"duration": 0.018025, "end_time": "2020-09-26T13:34:47.784124", "exception": false, "start_time": "2020-09-26T13:34:47.766099", "status": "completed"} tags=[] # # Model parameters # + _cell_guid="79c7e3d0-c299-4dcb-8224-4455121ee9b0" _kg_hide-input=true _uuid="d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" papermill={"duration": 0.033576, "end_time": "2020-09-26T13:34:47.835193", "exception": false, "start_time": "2020-09-26T13:34:47.801617", "status": "completed"} tags=[] config = { "BATCH_SIZE": 32, "EPOCHS": 60, "LEARNING_RATE": 1e-3, "ES_PATIENCE": 10, "N_FOLDS": 5, "N_USED_FOLDS": 5, "PB_SEQ_LEN": 107, "PV_SEQ_LEN": 130, } with open('config.json', 'w') as json_file: json.dump(json.loads(json.dumps(config)), json_file) config # + [markdown] papermill={"duration": 0.019721, "end_time": "2020-09-26T13:34:47.872990", "exception": false, "start_time": "2020-09-26T13:34:47.853269", "status": "completed"} tags=[] # # Load data # + _kg_hide-input=true papermill={"duration": 0.761886, "end_time": "2020-09-26T13:34:48.653022", "exception": false, "start_time": "2020-09-26T13:34:47.891136", "status": "completed"} tags=[] database_base_path = '/kaggle/input/stanford-covid-vaccine/' train = pd.read_json(database_base_path + 'train.json', lines=True) test = pd.read_json(database_base_path + 'test.json', lines=True) print('Train samples: %d' % len(train)) display(train.head()) print(f'Test samples: {len(test)}') display(test.head()) # + [markdown] papermill={"duration": 0.023056, "end_time": "2020-09-26T13:34:48.699686", "exception": false, "start_time": "2020-09-26T13:34:48.676630", "status": "completed"} tags=[] # ## Auxiliary functions # + _kg_hide-input=true papermill={"duration": 0.039451, "end_time": "2020-09-26T13:34:48.760606", "exception": false, "start_time": "2020-09-26T13:34:48.721155", "status": "completed"} tags=[] def get_dataset(x, y=None, sample_weights=None, labeled=True, shuffled=True, batch_size=32, buffer_size=-1, seed=0): input_map = {'inputs_seq': x['sequence'], 'inputs_struct': x['structure'], 'inputs_loop': x['predicted_loop_type'], 'inputs_bpps_max': x['bpps_max'], 'inputs_bpps_sum': x['bpps_sum'], 'inputs_bpps_mean': x['bpps_mean'], 'inputs_bpps_scaled': x['bpps_scaled']} if labeled: output_map = {'output_react': y['reactivity'], 'output_bg_ph': y['deg_Mg_pH10'], 'output_ph': y['deg_pH10'], 'output_mg_c': y['deg_Mg_50C'], 'output_c': y['deg_50C']} if sample_weights is not None: dataset = tf.data.Dataset.from_tensor_slices((input_map, output_map, sample_weights)) else: dataset = tf.data.Dataset.from_tensor_slices((input_map, output_map)) else: dataset = tf.data.Dataset.from_tensor_slices((input_map)) if shuffled: dataset = dataset.shuffle(2048, seed=seed) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(buffer_size) return dataset # + [markdown] papermill={"duration": 0.020934, "end_time": "2020-09-26T13:34:48.802341", "exception": false, "start_time": "2020-09-26T13:34:48.781407", "status": "completed"} tags=[] # # Model # + _kg_hide-output=true papermill={"duration": 5.040121, "end_time": "2020-09-26T13:34:53.864040", "exception": false, "start_time": "2020-09-26T13:34:48.823919", "status": "completed"} tags=[] def model_fn(hidden_dim=384, dropout=.5, pred_len=68, n_outputs=5): inputs_seq = L.Input(shape=(None, 1), name='inputs_seq') inputs_struct = L.Input(shape=(None, 1), name='inputs_struct') inputs_loop = L.Input(shape=(None, 1), name='inputs_loop') inputs_bpps_max = L.Input(shape=(None, 1), name='inputs_bpps_max') inputs_bpps_sum = L.Input(shape=(None, 1), name='inputs_bpps_sum') inputs_bpps_mean = L.Input(shape=(None, 1), name='inputs_bpps_mean') inputs_bpps_scaled = L.Input(shape=(None, 1), name='inputs_bpps_scaled') def _one_hot(x, num_classes): return K.squeeze(K.one_hot(K.cast(x, 'uint8'), num_classes=num_classes), axis=2) ohe_seq = L.Lambda(_one_hot, arguments={'num_classes': len(token2int_seq)}, input_shape=(None, 1))(inputs_seq) ohe_struct = L.Lambda(_one_hot, arguments={'num_classes': len(token2int_struct)}, input_shape=(None, 1))(inputs_struct) ohe_loop = L.Lambda(_one_hot, arguments={'num_classes': len(token2int_loop)}, input_shape=(None, 1))(inputs_loop) ### Encoder block # Conv block conv_seq = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(ohe_seq) conv_struct = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(ohe_struct) conv_loop = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(ohe_loop) conv_bpps_max = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(inputs_bpps_max) conv_bpps_sum = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(inputs_bpps_sum) # conv_bpps_mean = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(inputs_bpps_mean) # conv_bpps_scaled = L.Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(inputs_bpps_scaled) x_concat = L.concatenate([conv_seq, conv_struct, conv_loop, conv_bpps_max, conv_bpps_sum], axis=-1, name='conv_concatenate') # Recurrent block encoder, encoder_state_f, encoder_state_b = L.Bidirectional(L.GRU(hidden_dim, dropout=dropout, return_sequences=True, return_state=True, kernel_initializer='orthogonal'), name='Encoder_RNN')(x_concat) ### Decoder block decoder = L.Bidirectional(L.GRU(hidden_dim, dropout=dropout, return_sequences=True, kernel_initializer='orthogonal'), name='Decoder')(encoder, initial_state=[encoder_state_f, encoder_state_b]) # Attention attention = L.AdditiveAttention()([encoder, decoder]) attention = L.concatenate([attention, decoder]) # Since we are only making predictions on the first part of each sequence, we have to truncate it decoder_truncated = attention[:, :pred_len] output_react = L.Dense(1, name='output_react')(decoder_truncated) output_bg_ph = L.Dense(1, name='output_bg_ph')(decoder_truncated) output_ph = L.Dense(1, name='output_ph')(decoder_truncated) output_mg_c = L.Dense(1, name='output_mg_c')(decoder_truncated) output_c = L.Dense(1, name='output_c')(decoder_truncated) model = Model(inputs=[inputs_seq, inputs_struct, inputs_loop, inputs_bpps_max, inputs_bpps_sum, inputs_bpps_mean, inputs_bpps_scaled], outputs=[output_react, output_bg_ph, output_ph, output_mg_c, output_c]) opt = optimizers.Adam(learning_rate=config['LEARNING_RATE']) model.compile(optimizer=opt, loss={'output_react': MCRMSE, 'output_bg_ph': MCRMSE, 'output_ph': MCRMSE, 'output_mg_c': MCRMSE, 'output_c': MCRMSE}, loss_weights={'output_react': 2., 'output_bg_ph': 2., 'output_ph': 1., 'output_mg_c': 2., 'output_c': 1.}) return model model = model_fn() model.summary() # + [markdown] papermill={"duration": 0.023721, "end_time": "2020-09-26T13:34:53.910642", "exception": false, "start_time": "2020-09-26T13:34:53.886921", "status": "completed"} tags=[] # # Pre-process # + _kg_hide-input=true papermill={"duration": 11.784085, "end_time": "2020-09-26T13:35:05.717093", "exception": false, "start_time": "2020-09-26T13:34:53.933008", "status": "completed"} tags=[] # Add bpps as features bpps_max = [] bpps_sum = [] bpps_mean = [] bpps_scaled = [] bpps_nb_mean = 0.077522 # mean of bpps_nb across all training data bpps_nb_std = 0.08914 # std of bpps_nb across all training data for row in train.itertuples(): probability = np.load(f'{database_base_path}/bpps/{row.id}.npy') bpps_max.append(probability.max(-1).tolist()) bpps_sum.append((1-probability.sum(-1)).tolist()) bpps_mean.append((1-probability.mean(-1)).tolist()) # bpps nb bpps_nb = (probability > 0).sum(axis=0) / probability.shape[0] bpps_nb = (bpps_nb - bpps_nb_mean) / bpps_nb_std bpps_scaled.append(bpps_nb) train = train.assign(bpps_max=bpps_max, bpps_sum=bpps_sum, bpps_mean=bpps_mean, bpps_scaled=bpps_scaled) bpps_max = [] bpps_sum = [] bpps_mean = [] bpps_scaled = [] for row in test.itertuples(): probability = np.load(f'{database_base_path}/bpps/{row.id}.npy') bpps_max.append(probability.max(-1).tolist()) bpps_sum.append((1-probability.sum(-1)).tolist()) bpps_mean.append((1-probability.mean(-1)).tolist()) # bpps nb bpps_nb = (probability > 0).sum(axis=0) / probability.shape[0] bpps_nb = (bpps_nb - bpps_nb_mean) / bpps_nb_std bpps_scaled.append(bpps_nb) test = test.assign(bpps_max=bpps_max, bpps_sum=bpps_sum, bpps_mean=bpps_mean, bpps_scaled=bpps_scaled) feature_cols = ['sequence', 'structure', 'predicted_loop_type', 'bpps_max', 'bpps_sum', 'bpps_mean', 'bpps_scaled'] pred_cols = ['reactivity', 'deg_Mg_pH10', 'deg_pH10', 'deg_Mg_50C', 'deg_50C'] encoder_list = [token2int_seq, token2int_struct, token2int_loop, None, None, None, None] public_test = test.query("seq_length == 107").copy() private_test = test.query("seq_length == 130").copy() x_test_public = get_features_dict(public_test, feature_cols, encoder_list, public_test.index) x_test_private = get_features_dict(private_test, feature_cols, encoder_list, private_test.index) # To use as stratified col train['signal_to_noise_int'] = train['signal_to_noise'].astype(int) # + [markdown] papermill={"duration": 0.022498, "end_time": "2020-09-26T13:35:05.762258", "exception": false, "start_time": "2020-09-26T13:35:05.739760", "status": "completed"} tags=[] # # Training # + _kg_hide-input=true _kg_hide-output=true papermill={"duration": 2228.14864, "end_time": "2020-09-26T14:12:13.932107", "exception": false, "start_time": "2020-09-26T13:35:05.783467", "status": "completed"} tags=[] AUTO = tf.data.experimental.AUTOTUNE skf = KFold(n_splits=config['N_FOLDS'], shuffle=True, random_state=SEED) history_list = [] oof = train[['id', 'SN_filter', 'signal_to_noise'] + pred_cols].copy() oof_preds = np.zeros((len(train), 68, len(pred_cols))) test_public_preds = np.zeros((len(public_test), config['PB_SEQ_LEN'], len(pred_cols))) test_private_preds = np.zeros((len(private_test), config['PV_SEQ_LEN'], len(pred_cols))) for fold,(train_idx, valid_idx) in enumerate(skf.split(train['signal_to_noise_int'])): if fold >= config['N_USED_FOLDS']: break print(f'\nFOLD: {fold+1}') ### Create datasets x_train = get_features_dict(train, feature_cols, encoder_list, train_idx) x_valid = get_features_dict(train, feature_cols, encoder_list, valid_idx) y_train = get_targets_dict(train, pred_cols, train_idx) y_valid = get_targets_dict(train, pred_cols, valid_idx) w_train = np.log(train.iloc[train_idx]['signal_to_noise'].values+1.2)+1 w_valid = np.log(train.iloc[valid_idx]['signal_to_noise'].values+1.2)+1 train_ds = get_dataset(x_train, y_train, w_train, labeled=True, shuffled=True, batch_size=config['BATCH_SIZE'], buffer_size=AUTO, seed=SEED) valid_ds = get_dataset(x_valid, y_valid, w_valid, labeled=True, shuffled=False, batch_size=config['BATCH_SIZE'], buffer_size=AUTO, seed=SEED) oof_ds = get_dataset(get_features_dict(train, feature_cols, encoder_list, valid_idx), labeled=False, shuffled=False, batch_size=config['BATCH_SIZE'], buffer_size=AUTO, seed=SEED) test_public_ds = get_dataset(x_test_public, labeled=False, shuffled=False, batch_size=config['BATCH_SIZE'], buffer_size=AUTO, seed=SEED) test_private_ds = get_dataset(x_test_private, labeled=False, shuffled=False, batch_size=config['BATCH_SIZE'], buffer_size=AUTO, seed=SEED) ### Model K.clear_session() model = model_fn() model_path = f'model_{fold}.h5' es = EarlyStopping(monitor='val_loss', mode='min', patience=config['ES_PATIENCE'], restore_best_weights=True, verbose=1) rlrp = ReduceLROnPlateau(monitor='val_loss', mode='min', factor=0.1, patience=5, verbose=1) ### Train history = model.fit(train_ds, validation_data=valid_ds, callbacks=[es, rlrp], epochs=config['EPOCHS'], batch_size=config['BATCH_SIZE'], verbose=2).history history_list.append(history) # Save last model weights model.save_weights(model_path) ### Inference oof_ds_preds = np.array(model.predict(oof_ds)).reshape((len(pred_cols), len(valid_idx), 68)).transpose((1, 2, 0)) oof_preds[valid_idx] = oof_ds_preds # Short sequence (public test) model = model_fn(pred_len=config['PB_SEQ_LEN']) model.load_weights(model_path) test_public_ds_preds = np.array(model.predict(test_public_ds)).reshape((len(pred_cols), len(public_test), config['PB_SEQ_LEN'])).transpose((1, 2, 0)) test_public_preds += test_public_ds_preds * (1 / config['N_USED_FOLDS']) # Long sequence (private test) model = model_fn(pred_len=config['PV_SEQ_LEN']) model.load_weights(model_path) test_private_ds_preds = np.array(model.predict(test_private_ds)).reshape((len(pred_cols), len(private_test), config['PV_SEQ_LEN'])).transpose((1, 2, 0)) test_private_preds += test_private_ds_preds * (1 / config['N_USED_FOLDS']) # + [markdown] papermill={"duration": 0.352093, "end_time": "2020-09-26T14:12:14.546974", "exception": false, "start_time": "2020-09-26T14:12:14.194881", "status": "completed"} tags=[] # ## Model loss graph # + _kg_hide-input=true papermill={"duration": 2.905748, "end_time": "2020-09-26T14:12:17.703784", "exception": false, "start_time": "2020-09-26T14:12:14.798036", "status": "completed"} tags=[] for fold, history in enumerate(history_list): print(f'\nFOLD: {fold+1}') print(f"Train {np.array(history['loss']).min():.5f} Validation {np.array(history['val_loss']).min():.5f}") plot_metrics_agg(history_list) # + [markdown] papermill={"duration": 0.247401, "end_time": "2020-09-26T14:12:18.199138", "exception": false, "start_time": "2020-09-26T14:12:17.951737", "status": "completed"} tags=[] # # Post-processing # + _kg_hide-input=true papermill={"duration": 18.585365, "end_time": "2020-09-26T14:12:37.029257", "exception": false, "start_time": "2020-09-26T14:12:18.443892", "status": "completed"} tags=[] # Assign preds to OOF set for idx, col in enumerate(pred_cols): val = oof_preds[:, :, idx] oof = oof.assign(**{f'{col}_pred': list(val)}) oof.to_csv('oof.csv', index=False) oof_preds_dict = {} for col in pred_cols: oof_preds_dict[col] = oof_preds[:, :, idx] # Assign values to test set preds_ls = [] for df, preds in [(public_test, test_public_preds), (private_test, test_private_preds)]: for i, uid in enumerate(df.id): single_pred = preds[i] single_df = pd.DataFrame(single_pred, columns=pred_cols) single_df['id_seqpos'] = [f'{uid}_{x}' for x in range(single_df.shape[0])] preds_ls.append(single_df) preds_df = pd.concat(preds_ls) # + [markdown] papermill={"duration": 0.238497, "end_time": "2020-09-26T14:12:37.531744", "exception": false, "start_time": "2020-09-26T14:12:37.293247", "status": "completed"} tags=[] # # Model evaluation # + _kg_hide-input=true papermill={"duration": 0.439124, "end_time": "2020-09-26T14:12:38.211114", "exception": false, "start_time": "2020-09-26T14:12:37.771990", "status": "completed"} tags=[] y_true_dict = get_targets_dict(train, pred_cols, train.index) y_true = np.array([y_true_dict[col] for col in pred_cols]).transpose((1, 2, 0, 3)).reshape(oof_preds.shape) display(evaluate_model(train, y_true, oof_preds, pred_cols)) # + [markdown] papermill={"duration": 0.241822, "end_time": "2020-09-26T14:12:38.695710", "exception": false, "start_time": "2020-09-26T14:12:38.453888", "status": "completed"} tags=[] # # Visualize test predictions # + _kg_hide-input=true papermill={"duration": 1.270272, "end_time": "2020-09-26T14:12:40.211666", "exception": false, "start_time": "2020-09-26T14:12:38.941394", "status": "completed"} tags=[] submission = pd.read_csv(database_base_path + 'sample_submission.csv') submission = submission[['id_seqpos']].merge(preds_df, on=['id_seqpos']) # + [markdown] papermill={"duration": 0.249359, "end_time": "2020-09-26T14:12:40.746434", "exception": false, "start_time": "2020-09-26T14:12:40.497075", "status": "completed"} tags=[] # # Test set predictions # + _kg_hide-input=true papermill={"duration": 7.276814, "end_time": "2020-09-26T14:12:48.269129", "exception": false, "start_time": "2020-09-26T14:12:40.992315", "status": "completed"} tags=[] display(submission.head(10)) display(submission.describe()) submission.to_csv('submission.csv', index=False)
Model backlog/Models/68-openvaccine-tf-bahdanau-attention-safe-features.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # PSFs # # PSFs in prysm have a very simple constructor, import numpy as np from prysm import PSF x = y = np.linspace(-1,1,128) z = np.random.random((128,128)) ps = PSF(data=z, x=x, y=y) # PSFs are usually created from a [Pupil](./Pupils.ipynb) instance in a model, but the constructor can be used with e.g. experimental data. from prysm import Pupil ps = PSF.from_pupil(Pupil(dia=10), efl=20) # F/2 # The encircled energy can be computed, for either a single point or an iterable (tuple, list, numpy array, …) of points, ps.encircled_energy(0.1), ps.encircled_energy([0.1, 0.2, 0.3]) # encircled energy is computed via the method described in <NAME>, <NAME>, “Simplified Method For Calculating Encircled Energy,” Proc. SPIE 0892, Simulation and Modeling of Optical Systems, (9 June 1988). # The inverse can also be computed using the a nonlinear optimization routine, provided the wavelength and F/# are known to support the initial guess. ps.ee_radius(0.838) # Baliga’s method is relatively slow for large arrays, so a dictionary is kept of all computed encircled energies at `ps._ee`. # # The encircled energy can be plotted. An axis limit must be provided if no encircled energy values have been computed. If some have, by default prysm will plot the computed values if no axis limit is given ps.plot_encircled_energy() ps.plot_encircled_energy(axlim=3, npts=50) # The PSF can be plotted in 2D, # ~0.838, exact value of energy contained in first airy zero from prysm.psf import FIRST_AIRY_ENCIRCLED ps.plot2d(xlim=5*1.22*ps.wavelength*FIRST_AIRY_ENCIRCLED, power=1/2, interpolation='lanczos', show_axlabels=True, show_colorbar=True) # Both `plot_encircled_energy` and `plot2d` take the usual `fig` and `ax` kwargs as well. For `plot2d`, the `axlim` arg sets the x and y axis limits to symmetrical values of axlim, i.e. the limits above will be `[0.8, 0.8]`, `[0.8, 0.8]`. `power` controls the stretch of the color scale. The image will be stretched by the 1/power power, e.g. 2 plots psf^(1/2). `interpolation` is passed to matplotlib. `show_axlabels` and `show_colorbar` both default to True, and control whether the axis labels are set and if the colorbar is drawn. # # PSFs are a subclass of [Convolvable](./convolvables.ipynb) and inherit all methods and attributes.
docs/source/user_guide/PSFs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/kundyyy/100-Days-Of-ML-Code/blob/master/Installing_and_Testing_Plotly.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="ou-opEnpYkqb" colab_type="text" # #### Installing Plotly # + id="xyi0TJOtYkqb" colab_type="code" colab={} outputId="cad575ab-0419-4127-ff03-19891d57e06b" import sys # !conda install --yes plotly # + [markdown] id="NSEA72h4Ykqf" colab_type="text" # # + [markdown] id="mnaZVeGLYkqf" colab_type="text" # #### Testing Installation # + id="mdjL2VOnYkqg" colab_type="code" colab={} import plotly.express as px # + id="DA3QMcxrYkqi" colab_type="code" colab={} outputId="c96b181f-933c-4a3d-eda5-18e4403e4ac3" px.bar(x = ['a','b','c'], y = [21,32,13]) # + id="M455jHgpYkqk" colab_type="code" colab={}
Installing_and_Testing_Plotly.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] nbsphinx="hidden" slideshow={"slide_type": "skip"} # This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org. # # Copyright (c) $\omega radlib$ developers. # Distributed under the MIT License. See LICENSE.txt for more info. # + [markdown] slideshow={"slide_type": "slide"} # # Attenuation correction # + [markdown] slideshow={"slide_type": "fragment"} # In this example, we will compare different approaches to **constrain the gate-by-gate retrieval** of path-integrated attenuation. # + [markdown] slideshow={"slide_type": "skip"} # ## Introduction # + [markdown] slideshow={"slide_type": "skip"} # Rainfall-induced attenuation is a major source of underestimation for radar-based precipitation estimation at C-band and X-band. Unconstrained forward gate-by-gate correction is known to be inherently unstable and thus not suited for unsupervised quality control procedures. Ideally, reference measurements (e.g. from microwave links) should be used to constrain gate-by-gate procedures. However, such attenuation references are usually not available. $\omega radlib$ provides a pragmatic approach to constrain gate-by-gate correction procedures, inspired by the work of [Kraemer et al., 2008](https://docs.wradlib.org/en/latest/zreferences.html#kraemer2008). It turned out that these procedures can effectively reduce the error introduced by attenuation, and, at the same time, minimize instability issues [(Jacobi et al., 2016)](https://docs.wradlib.org/en/latest/zreferences.html#jacobi2016). # + nbsphinx="hidden" slideshow={"slide_type": "fragment"} import wradlib as wrl import matplotlib.pyplot as pl import warnings warnings.filterwarnings('ignore') try: get_ipython().magic("matplotlib inline") except: pl.ion() import numpy as np # + [markdown] slideshow={"slide_type": "slide"} # ## The Example Event: June 2nd, 2008, SW-Germany # + [markdown] slideshow={"slide_type": "skip"} # Let's have a look at the situation in South-West Germany on June 2nd, 2008, at 16:55 UTC, as observed by the DWD C-band radar on mount Feldberg. # # The data can be read by the following lines and then visualized by [wradlib.vis.plot_ppi()](https://docs.wradlib.org/en/latest/generated/wradlib.vis.plot_ppi.html): # + slideshow={"slide_type": "fragment"} fpath = 'dx/raa00-dx_10908-0806021655-fbg---bin.gz' f = wrl.util.get_wradlib_data_file(fpath) data, attrs = wrl.io.read_dx(f) # + slideshow={"slide_type": "fragment"} pl.figure(figsize=(10,8)) ax, cf = wrl.vis.plot_ppi(data, cmap="viridis") pl.xlabel("Easting from radar (km)") pl.ylabel("Northing from radar (km)") pl.title("Radar Feldberg, 2008-06-02 16:55 UTC") cb = pl.colorbar(cf, shrink=0.8) cb.set_label("dBZ") pl.plot([0,105.6],[0,73.4],"-", color="white", lw=2) pl.xlim(-128,128) pl.ylim(-128,128) pl.grid(color="grey") # + [markdown] slideshow={"slide_type": "fragment"} # We see a set of convective cells with high rainfall intensity in the NE-sector of the Feldberg radar. Let us examine the reflectivity profile along **three beams which at azimuths 53-55 degree** (as marked by the white line in the PPI above). # + slideshow={"slide_type": "fragment"} # just a little helper function def plot_beams(data, mybeams, sub=111): ax = fig.add_subplot(sub) labelsize=13 for beam in range(mybeams.start, mybeams.stop): pl.plot(data[beam], label="{0} deg".format(beam)) pl.grid() pl.text(0.99, 0.88, "Reflectivity along beams", horizontalalignment='right', transform = ax.transAxes, fontsize="large") pl.xlabel("range (km)", fontsize="large") pl.ylabel("Reflectivity (dBZ)", fontsize="large") pl.legend(loc="upper left") ax.tick_params(axis='x', labelsize=labelsize) ax.tick_params(axis='y', labelsize=labelsize) pl.xlim(0,128) # + slideshow={"slide_type": "fragment"} mybeams = slice(53,56) fig = pl.figure(figsize=(10,3)) plot_beams(data, mybeams) # + [markdown] slideshow={"slide_type": "slide"} # ## Examining different attenuation correction procedures # + [markdown] slideshow={"slide_type": "slide"} # ### Hitschfeld and Bordan # # Unconstrained gate-by-gate retrieval (1954) # + [markdown] slideshow={"slide_type": "skip"} # First, we examine the behaviour of the "classical" unconstrained forward correction which is typically referred to [Hitschfeld et al., 1954](https://docs.wradlib.org/en/latest/zreferences.html#hitschfeld1954), although Hitschfeld and Bordan themselves rejected this approach. The Path Integrated Attenuation (PIA) according to this approach can be obtained as follows: # + slideshow={"slide_type": "fragment"} pia_hibo = wrl.atten.correct_attenuation_hb( data, coefficients = dict(a=8.e-5, b=0.731, gate_length=1.0), mode="warn", thrs=59.) # + [markdown] slideshow={"slide_type": "skip"} # In the coefficients dictionary, we can pass the power law parameters of the A(Z) relation as well as the gate length (in km). If we pass "warn" as the mode argument, we will obtain a warning log in case the corrected reflectivity exceeds the value of argument ``thrs`` (dBZ). # # Plotting the result below the reflectivity profile, we obtain the following figure. # + slideshow={"slide_type": "fragment"} # another little helper function def plot_pia(pia, sub=111, title=None): ax = fig.add_subplot(sub) labelsize=13 pl.plot(pia.T) pl.grid() pl.ylim(0,30) pl.ylabel("PIA (dB)", fontsize="large") pl.text(0.01, 0.88, title, transform = ax.transAxes, fontsize="large") ax.tick_params(axis='x', labelsize=labelsize) ax.tick_params(axis='y', labelsize=labelsize) pl.xlim(0,128) # + slideshow={"slide_type": "fragment"} fig = pl.figure(figsize=(10,6)) plot_beams(data, mybeams, 211) plot_pia(pia_hibo[mybeams], 212, "PIA according to Hitchfeld and Bordan") pl.tight_layout() # + [markdown] slideshow={"slide_type": "skip"} # Apparently, slight differences in the reflectivity profile can cause a dramatic change in the behaviour. While at 54 and 55 degrees, the retrieval of PIA appears to be fairly stable, the profile of PIA for 53 degree demonstrates a case of instability. # + [markdown] slideshow={"slide_type": "slide"} # ### Harrison # Harrison et.al. (2000): Cap PIA at a factor of two # + [markdown] slideshow={"slide_type": "skip"} # [Harrison et al., 2000](https://docs.wradlib.org/en/latest/zreferences.html#harrison2000) suggested to simply cap PIA in case it would cause a correction of rainfall intensity by more than a factor of two. Depending on the parameters of the Z(R) relationship, that would correpond to PIA values between 4 and 5 dB (4.8 dB if we assume exponent b=1.6). # # One way to implement this approach would be the following: # + slideshow={"slide_type": "fragment"} pia_harrison = wrl.atten.correct_attenuation_hb( data, coefficients = dict(a=4.57e-5, b=0.731, gate_length=1.0), mode="warn", thrs=59.) pia_harrison[pia_harrison > 4.8] = 4.8 # + [markdown] slideshow={"slide_type": "skip"} # And the results would look like this: # + slideshow={"slide_type": "fragment"} fig = pl.figure(figsize=(10,6)) mybeams = slice(53,56) labelsize=13 plot_beams(data, mybeams, 211) plot_pia(pia_harrison[mybeams], 212, "PIA according to Harrison") pl.tight_layout() # + [markdown] slideshow={"slide_type": "slide"} # ### Kraemer # Kraemer et al. (2008): Iterative estimation of A(Z) relationsip # + [markdown] slideshow={"slide_type": "skip"} # [Kraemer et al., 2008](https://docs.wradlib.org/en/latest/zreferences.html#kraemer2008) suggested to iteratively determine the power law parameters of the A(Z). In particular, the power law coefficient is interatively decreased until the attenuation correction does not lead to reflectivity values above a given threshold (Kraemer suggested 59 dBZ). Using $\omega radlib$, this would be called by using the function [wradlib.atten.correct_attenuation_constrained()](https://docs.wradlib.org/en/latest/generated/wradlib.atten.correct_attenuation_constrained.html) with a specific ``constraints`` argument: # + slideshow={"slide_type": "fragment"} pia_kraemer = wrl.atten.correct_attenuation_constrained( data, a_max=1.67e-4, a_min=2.33e-5, n_a=100, b_max=0.7, b_min=0.65, n_b=6, gate_length=1., constraints=[wrl.atten.constraint_dbz], constraint_args=[[59.0]]) # + [markdown] slideshow={"slide_type": "skip"} # In brief, this call specifies ranges of the power parameters a and b of the A(Z) relation. Beginning from the maximum values (``a_max`` and ``b_max``), the function searches for values of ``a`` and ``b`` so that the corrected reflectivity will not exceed the dBZ constraint of 59 dBZ. Compared to the previous results, the corresponding profiles of PIA look like this: # + slideshow={"slide_type": "fragment"} fig = pl.figure(figsize=(10,6)) plot_beams(data, mybeams, 211) plot_pia(pia_kraemer[mybeams], 212, "PIA according to Kraemer") pl.tight_layout() # + [markdown] slideshow={"slide_type": "slide"} # ### Modified Kraemer # Generalised Kraemer procedure: adding additional constraints # + [markdown] slideshow={"slide_type": "skip"} # The function [wradlib.atten.correct_attenuation_constrained()](https://docs.wradlib.org/en/latest/generated/wradlib.atten.correct_attenuation_constrained.html) allows us to pass any kind of constraint function or lists of constraint functions via the argument ``constraints``. The arguments of these functions are passed via a nested list as argument ``constraint_args``. For example, [Jacobi et al., 2016](https://docs.wradlib.org/en/latest/zreferences.html#jacobi2016) suggested to constrain *both* the corrected reflectivity (by a maximum of 59 dBZ) *and* the resulting path-intgrated attenuation PIA (by a maximum of 20 dB): # + slideshow={"slide_type": "fragment"} pia_mkraemer = wrl.atten.correct_attenuation_constrained( data, a_max=1.67e-4, a_min=2.33e-5, n_a=100, b_max=0.7, b_min=0.65, n_b=6, gate_length=1., constraints=[wrl.atten.constraint_dbz, wrl.atten.constraint_pia], constraint_args=[[59.0],[20.0]]) # + slideshow={"slide_type": "fragment"} fig = pl.figure(figsize=(10,6)) plot_beams(data, mybeams, 211) plot_pia(pia_mkraemer[mybeams], 212, "PIA according to modified Kraemer") pl.tight_layout() # + [markdown] slideshow={"slide_type": "slide"} # ## Comparison of all Methods # + [markdown] slideshow={"slide_type": "skip"} # Plotting all of the above methods ([Hitschfeld and Bordan](#Hitschfeld-and-Bordan), [Harrison](#Harrison), [Kraemer](#Kraemer), [Modified Kraemer](#Modified-Kraemer) allows for a better comparison of their behaviour. Please refer to [Jacobi et al., 2016](https://docs.wradlib.org/en/latest/zreferences.html#jacobi2016) for an in-depth discussion of this example. # + slideshow={"slide_type": "fragment"} fig = pl.figure(figsize=(10,12)) plot_beams(data, mybeams, 511) plot_pia(pia_hibo[mybeams], 512, "PIA according to Hitschfeld and Bordan" ) plot_pia(pia_harrison[mybeams], 513, "PIA according to Harrison") plot_pia(pia_kraemer[mybeams], 514, "PIA according to Kraemer") plot_pia(pia_mkraemer[mybeams], 515, "PIA according to modified Kraemer") pl.tight_layout() # -
notebooks/attenuation/wradlib_attenuation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import pandas as pd df = pd.read_csv(filepath_or_buffer='https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv', sep='\t').iloc[:100,:] df.head() dfsel = df[df['order_id'] == 1] n_pedidos = dfsel.shape[0] dfsel dfsel = df[df['order_id'] == 2] n_pedidos = dfsel.shape[0] dfsel dfsel = df[df['order_id'] == 3] n_pedidos = dfsel.shape[0] dfsel dic_pedidos = {} dfsel = df[df['order_id'] == 1] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[1] = n_pedidos dic_pedidos dfsel = df[df['order_id'] == 2] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[2] = n_pedidos dic_pedidos dfsel = df[df['order_id'] == 3] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[3] = n_pedidos dic_pedidos dic_pedidos = {} # + dfsel = df[df['order_id'] == 3] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[3] = n_pedidos dic_pedidos # - dic_pedidos = {} # + dfsel = df[df['order_id'] == pepa] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[pepa] = n_pedidos dic_pedidos # - dic_pedidos = {} for pepa in [1,2,3]: dfsel = df[df['order_id'] == pepa] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[pepa] = n_pedidos dic_pedidos dic_pedidos df df.order_id pedidos = df.order_id.unique() dic_pedidos = {} for pepa in pedidos: dfsel = df[df['order_id'] == pepa] n_pedidos = dfsel.shape[0] dfsel dic_pedidos[pepa] = n_pedidos dic_pedidos dic_pedidos pd.Series(dic_pedidos) df.order_id.value_counts() df.order_id.value_counts(sort=False) df.order_id.value_counts(sort=False) # + dic_pedidos = {} for pepa in pedidos: dfsel = df[df['order_id'] == pepa] n_pedidos = dfsel.shape[0] dic_pedidos[pepa] = n_pedidos pd.Series(dic_pedidos) # - df.item_price.sum() for i in df.item_price: print(i) i = '$2.39 ' clean_i = i.replace('$', '').replace(' ', '') float_i = float(clean_i) float_i # + i = '$2.39 ' clean_i = i.replace('$', '').replace(' ', '') float_i = float(clean_i) float_i # - i = '$2.39 ' clean_i = i.replace('$', '').replace(' ', '') float_i = float(clean_i) float_i for i in df.item_price: clean_i = i.replace('$', '').replace(' ', '') float_i = float(clean_i) float_i float_i lista_precios = [] for i in df.item_price: clean_i = i.replace('$', '').replace(' ', '') float_i = float(clean_i) lista_precios.append(float_i) lista_precios df['precio'] = lista_precios df df.item_price.sum() df.precio.sum() df for item in df.choice_description: print(item) item = '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]' item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item # + item = '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]' item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item # - item = '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]' item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item for item in df.choice_description: item = '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]' item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item for item in df.choice_description: item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item for item in df.choice_description: print(item) item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item import numpy as np np.nan np.nan.replace() if type(item) == float: print('bingo') else: print('nanai') for item in df.choice_description: if type(item) == float: item else: item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_item for item in df.choice_description: if type(item) == float: item else: item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') print(lista_item) for item in df.choice_description: if type(item) == float: lista_item = [] else: item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') print(lista_item) lista_todos = [] for item in df.choice_description: if type(item) == float: lista_item = [] lista_todos.append(lista_item) else: item = item.replace('[', '').replace(']', '') item lista_item = item.split(', ') lista_todos.append(lista_item) lista_todos # + from sklearn.feature_extraction.text import TfidfVectorizer bag_of_words = CountVectorizer(tokenizer=lambda doc: doc, lowercase=False).fit_transform(lista_todos) # - bag_of_words.get vec = TfidfVectorizer() lista_todos = [','.join(i) for i in lista_todos] vec.fit(lista_todos) data = vec.transform(lista_todos).toarray() vec.get_feature_names_out() pd.DataFrame(data) pd.DataFrame(bag_of_words.toarray())
I Resolving Python with Data Science/07_Applied For Loops vs DataFrame Functionalities/solutions/06session_pandas-vs-for_loop.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from IPython.display import Image, display Image("ryoko.png", width="70") # # The Final Stage # *Dr. Ryoko is stuck in the quantum multiverse due to noise clusters interfering with her device. <br/> # Please DM <NAME> and ask her about the **noise clusters** and you will find out more. <br/> # Dr. Ryoko is trying to clear noise clusters with her laser beams, but has only 3 shots left.<br/> # To make matters worse, there seems to be one area (board) that cannot be cleared within 3 shots. <br/> # Help Dr. Ryoko identify that one area (board) with noise clusters that **cannot be cleared within 3 shots**. Good luck!<br/>* # # [<< Click here to communicate with Dr. Ryoko through the web cam >>](https://youtu.be/Bkk5-j6rpoM) # # *You can do this by learning how to solve a famous classic puzzle called “Asteroids puzzle”.* # # Week3: False Asteroids # Asteroids is a famous puzzle with the following setup and rules: # - The asteroids are placed on a grid. # - The objective is to destroy all the asteroids by shooting laser beams: either vertically or horizontally. # - Determine how to destroy all the asteroids by shooting no more than the specified number of beams. # # The following image is an example of an Asteroids puzzle. In this example, the board size is 4 × 4 and we have six asteroids. Image('asteroids_example.png') # As shown below, we can destroy all the asteroids by shooting 3 lasers vertically. Each thick blue line represents a laser beam. Image('asteroids_beam_example.png') # There are also false Asteroid problems. An Asteroid problem is false if the asteroids cannot be cleared within the specified number of beams. The following example is a false Asteroid problem with 3 laser beams. Image('false_asteroids_example.png') # ---------- # # Final Exercise # There are 16 areas (boards) that Dr. Ryoko needs to clear, each of which has 6 noise clusters that correspond to an asteroid in "Asteroids puzzle". However, there happens to be one area that cannot be cleared within three laser shots! Use Grover's algorithm you learned in Weeks 1 & 2 to find that one area (board)! # A board with asteroids is represented with a list of tuples. Each tuple represents the coordinate of an asteroid in the format `[row index, column index]`. Therefore, a board according to the following image can be represented as: # # ``` # [['0', '0'], ['1', '1'], ['2', '2'], ['3', '0'], ['3', '1'], ['3', '2']] # ``` # Image('asteroids_example.png') # There are 16 areas (boards) with the following configurations. # Find the area that cannot be cleared with 3 laser shots by using Grover's algorithm to help Dr. Ryoko! problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] # def str_to_int(x): # y = [0]*6 # for i in range (len(x)): # z = x[i] # y[i] = 4*int(z[0])+int(z[1]) # return y # def str_to_int(x): y = [0]*16 for i in range (len(x)): z = x[i] y[4*int(z[0])+int(z[1])] = 1 return y def int_to_binary(x): y = [0]*4 y[3] = x//8 y[2] = (x-y[3]*8)//4 y[1] = (x-y[3]*8-y[2]*4)//2 y[0] = x-y[3]*8-y[2]*4-y[1]*2 return y x = [['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']] def binary_to_qubits(x): y = [] for i in range (4): if x[i] ==1: y.append(i+20) return y str_to_int(x) x = 11 for i in range(16): print(int_to_binary(i)) binary_to_qubits(int_to_binary(x)) def diffuser(nqubits): from qiskit import QuantumCircuit qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "$U_s$" return U_s # Answer by creating a quantum circuit to solve the puzzle shown with the problem set above. In the quantum circuit to be submitted, measure **only the `solution` (4bit)** that solves the puzzle. <br/> # To submit your solution, create a function that takes `problem_set` as an input and then returns a `QuantumCircuit`. You can name the function as you like. Make sure it works even with another dataset of "problem_set". We will validate your circuit with different inputs.<br/> # Make a circuit that gets the correct answer at a low cost. The lower the cost, the better. # # ## <span style="color: red; ">IMPORTANT: Final exercise submission rules</span> # # **For solving this problem:**<br/> # - **Please implement the quantum circuit within <span style="color: red; ">28 qubits.</span>**<br/> # - Use **Grover's algorithm** you learned in Week1 & 2 with **<span style="color: red; ">iteration = 1.</span>** # - The initial state for Grover's algorithm must be equal probability distributions. For example, if you want use only 3 computational bases for 2 qubits instead of 4 as the initial state. Then, the state will be $\sqrt\frac{1}{3} (|00\rangle + |01\rangle + |11\rangle)$ # # - Please note that you can get the answer with the same endian as the one used in Week2 explanation. You should map the index of the problem into four classical registers *`c[0:4]`* in binary. `c[0]` is the highest bit and `c[3]` is the lowest bit. For example, when mapping 12, the furthest left bit of the `1100` will be mapped to `c[0]`. # - Make sure you **create an oracle** that **doesn't require any knowledge of what the answers are**. (For example, you are not allowed to create an oracle by using a classical optimization solver to get your answers for it.) # - With the exception of the Unroller, which is required for decomposing your circuit to calculate quantum costs, you are not allowed to use any existing transpiler passes nor original transpilers for making simplifications in this competition. # - Please **do not run jobs in succession** even if you are concerned that your job is not running properly. This can create a long queue and clog the backend. You can check whether your job is running properly at:<br/> # https://quantum-computing.ibm.com/results # - Your score for this exercise will be same as the cost of your QuantumCircuit. The lower the cost, the better. # - Judges will check top 10 solutions manually to see if their solutions adhere to the rules. **Please note that your ranking is subject to change after the challenge period as a result of the judging process.** # - Top 10 participants will be recognized and asked to submit a write up on how they solved the exercise. # # 1. Score 100k # def week3_ans_func(problem_set): # ##### build your quantum circuit here # ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. # # #### Code for Grover's algorithm with iterations = 1 will be as follows. # #### for i in range(1): # #### oracle() # #### diffusion() # from qiskit import QuantumCircuit # # qc = QuantumCircuit(28,4) # # qc.h([20,21,22,23]) # # # for i in range (16): # x = str_to_int(problem_set[i]) # y = int_to_binary(i) # for k in range(4): # if y[k] == 1: # qc.x(20+k) # for j in range (len(x)): # if x[j] == 1: # qc.mct([20,21,22,23],j) # # # for k in range(4): # if y[k] == 1: # qc.x(20+k) # # qc.h(18) # qc.z(18) # qc.mct([0,5,10,15],18,[24,25,26,27]) # qc.mct([0,5,11,14],18,[24,25,26,27]) # qc.mct([0,6,9,15],18,[24,25,26,27]) # qc.mct([0,6,11,13],18,[24,25,26,27]) # qc.mct([0,7,9,14],18,[24,25,26,27]) # qc.mct([0,7,10,13],18,[24,25,26,27]) # # qc.mct([1,4,10,15],18,[24,25,26,27]) # qc.mct([1,4,11,14],18,[24,25,26,27]) # qc.mct([1,6,8,15],18,[24,25,26,27]) # qc.mct([1,6,11,12],18,[24,25,26,27]) # qc.mct([1,7,8,14],18,[24,25,26,27]) # qc.mct([1,7,10,12],18,[24,25,26,27]) # # qc.mct([2,4,9,15],18,[24,25,26,27]) # qc.mct([2,4,11,13],18,[24,25,26,27]) # qc.mct([2,5,8,15],18,[24,25,26,27]) # qc.mct([2,5,11,12],18,[24,25,26,27]) # qc.mct([2,7,8,13],18,[24,25,26,27]) # qc.mct([2,7,9,12],18,[24,25,26,27]) # # # # qc.mct([3,4,9,14],18,[24,25,26,27]) # qc.mct([3,4,10,13],18,[24,25,26,27]) # qc.mct([3,5,8,14],18,[24,25,26,27]) # qc.mct([3,5,10,12],18,[24,25,26,27]) # qc.mct([3,6,8,13],18,[24,25,26,27]) # qc.mct([3,6,9,12],18,[24,25,26,27]) # # for i in range (16): # x = str_to_int(problem_set[i]) # y = int_to_binary(i) # for k in range(4): # if y[k] == 1: # qc.x(20+k) # for j in range (len(x)): # if x[j] == 1: # qc.mct([20,21,22,23],j,[24,25,26,27]) # # # for k in range(4): # if y[k] == 1: # qc.x(20+k) # # # qc.append(diffuser(4), [20,21,22,23]) # # # qc.measure([20,21,22,23],[0,1,2,3]) # return qc # # 2. Score 44k # def week3_ans_func(problem_set): # ##### build your quantum circuit here # ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. # # #### Code for Grover's algorithm with iterations = 1 will be as follows. # #### for i in range(1): # #### oracle() # #### diffusion() # from qiskit import QuantumCircuit # # qc = QuantumCircuit(28,4) # # qc.h([20,21,22,23]) # # # # for i in range (16): # x = str_to_int(problem_set[i]) # y = int_to_binary(i) # for k in range(4): # if y[k] == 1: # qc.x(20+k) # if i ==0: # qc.mct([20,21,22,23],16) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # elif i ==1: # qc.mct([20,21,22,23],17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(17,j) # # if i ==2: # qc.mct([20,21,22,23],19) # for j in range (len(x)): # if x[j] == 1: # qc.cx(19,j) # # elif i ==3: # qc.mct([20,21,22,23],24) # for j in range (len(x)): # if x[j] == 1: # qc.cx(24,j) # # elif i ==4: # qc.mct([20,21,22,23],25) # for j in range (len(x)): # if x[j] == 1: # qc.cx(25,j) # # elif i ==5: # qc.mct([20,21,22,23],26) # for j in range (len(x)): # if x[j] == 1: # qc.cx(26,j) # else: # qc.mct([20,21,22,23],27) # for j in range (len(x)): # if x[j] == 1: # qc.cx(27,j) # qc.mct([20,21,22,23],27) # # for k in range(4): # if y[k] == 1: # qc.x(20+k) # # qc.h(18) # qc.z(18) # qc.mct([0,5,10,15],18) # qc.mct([0,5,11,14],18) # qc.mct([0,6,9,15],18) # qc.mct([0,6,11,13],18) # qc.mct([0,7,9,14],18) # qc.mct([0,7,10,13],18) # # qc.mct([1,4,10,15],18) # qc.mct([1,4,11,14],18) # qc.mct([1,6,8,15],18) # qc.mct([1,6,11,12],18) # qc.mct([1,7,8,14],18) # qc.mct([1,7,10,12],18) # # qc.mct([2,4,9,15],18) # qc.mct([2,4,11,13],18) # qc.mct([2,5,8,15],18) # qc.mct([2,5,11,12],18) # qc.mct([2,7,8,13],18) # qc.mct([2,7,9,12],18) # # # # qc.mct([3,4,9,14],18) # qc.mct([3,4,10,13],18) # qc.mct([3,5,8,14],18) # qc.mct([3,5,10,12],18) # qc.mct([3,6,8,13],18) # qc.mct([3,6,9,12],18) # # # for i in range (16): # x = str_to_int(problem_set[i]) # y = int_to_binary(i) # for k in range(4): # if y[k] == 1: # qc.x(20+k) # if i ==0: # qc.mct([20,21,22,23],16) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # elif i ==1: # qc.mct([20,21,22,23],17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(17,j) # # if i ==2: # qc.mct([20,21,22,23],19) # for j in range (len(x)): # if x[j] == 1: # qc.cx(19,j) # # elif i ==3: # qc.mct([20,21,22,23],24) # for j in range (len(x)): # if x[j] == 1: # qc.cx(24,j) # # elif i ==4: # qc.mct([20,21,22,23],25) # for j in range (len(x)): # if x[j] == 1: # qc.cx(25,j) # # elif i ==5: # qc.mct([20,21,22,23],26) # for j in range (len(x)): # if x[j] == 1: # qc.cx(26,j) # else: # qc.mct([20,21,22,23],27) # for j in range (len(x)): # if x[j] == 1: # qc.cx(27,j) # qc.mct([20,21,22,23],27) # # # for k in range(4): # if y[k] == 1: # qc.x(20+k) # # # qc.append(diffuser(4), [20,21,22,23]) # # # qc.measure([20,21,22,23],[0,1,2,3]) # return qc # # 3. Score 24k # def week3_ans_func(problem_set): # ##### build your quantum circuit here # ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. # # #### Code for Grover's algorithm with iterations = 1 will be as follows. # #### for i in range(1): # #### oracle() # #### diffusion() # from qiskit import QuantumCircuit # # qc = QuantumCircuit(28,4) # # qc.h([20,21,22,23]) # # # # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # qc.mct([20,21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # #qc.mct([20,21,22,23],16) # # # # # # qc.h(18) # qc.z(18) # qc.mct([0,5,10,15],18,[24,25,26,27]) # qc.mct([0,5,11,14],18,[24,25,26,27]) # qc.mct([0,6,9,15],18,[24,25,26,27]) # qc.mct([0,6,11,13],18,[24,25,26,27]) # qc.mct([0,7,9,14],18,[24,25,26,27]) # qc.mct([0,7,10,13],18,[24,25,26,27]) # # qc.mct([1,4,10,15],18,[24,25,26,27]) # qc.mct([1,4,11,14],18,[24,25,26,27]) # qc.mct([1,6,8,15],18,[24,25,26,27]) # qc.mct([1,6,11,12],18,[24,25,26,27]) # qc.mct([1,7,8,14],18,[24,25,26,27]) # qc.mct([1,7,10,12],18,[24,25,26,27]) # # qc.mct([2,4,9,15],18,[24,25,26,27]) # qc.mct([2,4,11,13],18,[24,25,26,27]) # qc.mct([2,5,8,15],18,[24,25,26,27]) # qc.mct([2,5,11,12],18,[24,25,26,27]) # qc.mct([2,7,8,13],18,[24,25,26,27]) # qc.mct([2,7,9,12],18,[24,25,26,27]) # # # # qc.mct([3,4,9,14],18,[24,25,26,27]) # qc.mct([3,4,10,13],18,[24,25,26,27]) # qc.mct([3,5,8,14],18,[24,25,26,27]) # qc.mct([3,5,10,12],18,[24,25,26,27]) # qc.mct([3,6,8,13],18,[24,25,26,27]) # qc.mct([3,6,9,12],18,[24,25,26,27]) # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # qc.mct([20,21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # # # qc.append(diffuser(4), [20,21,22,23]) # # # qc.measure([20,21,22,23],[3,2,1,0]) # return qc from numpy import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumCircuit,Aer, execute # + qc1 = QuantumCircuit(3) qc1.ch(0,2) qc1.crz(-pi,1,2) qc1.ch(0,2) # + qc2 = QuantumCircuit(7) qc2.append(qc1,[0,1,5]) qc2.append(qc1,[2,3,6]) qc2.ccx(5,6,4) qc2.append(qc1,[0,1,5]) qc2.append(qc1,[2,3,6]) # - qc4 = QuantumCircuit(7) qc4.append(qc1,[0,1,5]) qc4.append(qc1,[2,3,6]) qc4.append(qc1,[5,6,4]) qc4.append(qc1,[0,1,5]) qc4.append(qc1,[2,3,6]) # + qc5 = QuantumCircuit(8) qc5.append(qc1,[0,1,5]) qc5.append(qc1,[2,3,6]) qc5.ccx(5,6,4) qc5.cz(4,7) qc5.ch(4,7) qc5.ccx(5,6,4) qc5.append(qc1,[0,1,5]) qc5.append(qc1,[2,3,6]) # - qc3 = QuantumCircuit(5) qc3.append(qc1,[0,1,4]) qc3.append(qc1,[4,2,3]) qc3.append(qc1,[0,1,4]) # # 4. Score 20k # def week3_ans_func(problem_set): # ##### build your quantum circuit here # ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. # # #### Code for Grover's algorithm with iterations = 1 will be as follows. # #### for i in range(1): # #### oracle() # #### diffusion() # from qiskit import QuantumCircuit, ClassicalRegister, QuantumCircuit,Aer, execute # # qc = QuantumCircuit(28,4) # # qc.h([20,21,22,23]) # # # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # qc.mct([20,21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # # # # # # qc.h(18) # qc.z(18) # qc.append(qc2,[0,5,10,15,18,24,25]) # qc.append(qc2,[0,5,11,14,18,24,25]) # qc.append(qc2,[0,6,9,15,18,24,25]) # qc.append(qc2,[0,6,11,13,18,24,25]) # qc.append(qc2,[0,7,9,14,18,24,25]) # qc.append(qc2,[0,7,10,13,18,24,25]) # # qc.append(qc2,[1,4,10,15,18,24,25]) # qc.append(qc2,[1,4,11,14,18,24,25]) # qc.append(qc2,[1,6,8,15,18,24,25]) # qc.append(qc2,[1,6,11,12,18,24,25]) # qc.append(qc2,[1,7,8,14,18,24,25]) # qc.append(qc2,[1,7,10,12,18,24,25]) # # qc.append(qc2,[2,4,9,15,18,24,25]) # qc.append(qc2,[2,4,11,13,18,24,25]) # qc.append(qc2,[2,5,8,15,18,24,25]) # qc.append(qc2,[2,5,11,12,18,24,25]) # qc.append(qc2,[2,7,8,13,18,24,25]) # qc.append(qc2,[2,7,9,12,18,24,25]) # # # # qc.append(qc2,[3,4,9,14,18,24,25]) # qc.append(qc2,[3,4,10,13,18,24,25]) # qc.append(qc2,[3,5,8,14,18,24,25]) # qc.append(qc2,[3,5,10,12,18,24,25]) # qc.append(qc2,[3,6,8,13,18,24,25]) # qc.append(qc2,[3,6,9,12,18,24,25]) # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # qc.mct([20,21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.ccx(20,21,17) # qc.ccx(22,23,19) # qc.ccx(17,19,16) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.ccx(17,19,16) # qc.ccx(22,23,19) # qc.ccx(20,21,17) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # # # qc.append(diffuser(4), [20,21,22,23]) # # # qc.measure([20,21,22,23],[3,2,1,0]) # return qc # # # # 5. Score 17k # def week3_ans_func(problem_set): # ##### build your quantum circuit here # ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. # # #### Code for Grover's algorithm with iterations = 1 will be as follows. # #### for i in range(1): # #### oracle() # #### diffusion() # from qiskit import QuantumCircuit, ClassicalRegister, QuantumCircuit,Aer, execute # # qc = QuantumCircuit(28,4) # # qc.h([20,21,22,23]) # # # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # #qc.mct([20,21,22,23],16,[24,25,26,27]) # qc.append(qc2,[20,21,22,23,16,24,25]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # #qc.ccx(20,21,17) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # # # # # # qc.h(18) # qc.z(18) # qc.append(qc2,[0,5,10,15,18,24,25]) # qc.append(qc2,[0,5,11,14,18,24,25]) # qc.append(qc2,[0,6,9,15,18,24,25]) # qc.append(qc2,[0,6,11,13,18,24,25]) # qc.append(qc2,[0,7,9,14,18,24,25]) # qc.append(qc2,[0,7,10,13,18,24,25]) # # qc.append(qc2,[1,4,10,15,18,24,25]) # qc.append(qc2,[1,4,11,14,18,24,25]) # qc.append(qc2,[1,6,8,15,18,24,25]) # qc.append(qc2,[1,6,11,12,18,24,25]) # qc.append(qc2,[1,7,8,14,18,24,25]) # qc.append(qc2,[1,7,10,12,18,24,25]) # # qc.append(qc2,[2,4,9,15,18,24,25]) # qc.append(qc2,[2,4,11,13,18,24,25]) # qc.append(qc2,[2,5,8,15,18,24,25]) # qc.append(qc2,[2,5,11,12,18,24,25]) # qc.append(qc2,[2,7,8,13,18,24,25]) # qc.append(qc2,[2,7,9,12,18,24,25]) # # # # qc.append(qc2,[3,4,9,14,18,24,25]) # qc.append(qc2,[3,4,10,13,18,24,25]) # qc.append(qc2,[3,5,8,14,18,24,25]) # qc.append(qc2,[3,5,10,12,18,24,25]) # qc.append(qc2,[3,6,8,13,18,24,25]) # qc.append(qc2,[3,6,9,12,18,24,25]) # # # x = str_to_int(problem_set[0]) # qc.x([20,21,22,23]) # #qc.mct([20,21,22,23],16,[24,25,26,27]) # qc.append(qc2,[20,21,22,23,16,24,25]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # x = str_to_int(problem_set[1]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[2]) # #qc.ccx(20,21,17) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[3]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[4]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[5]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[6]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[7]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[8]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(22,19) # qc.cx(23,19) # qc.x(23) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[9]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[10]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[11]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[12]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.x(22) # qc.cx(23,19) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[13]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[14]) # qc.append(qc1,[20,21,17]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[17,19,16]) # qc.x(20) # qc.cx(20,17) # qc.cx(21,17) # qc.x(21) # qc.append(qc1,[17,19,16]) # qc.append(qc1,[22,23,19]) # qc.append(qc1,[20,21,17]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # x = str_to_int(problem_set[15]) # qc.x(20) # qc.append(qc3,[21,22,23,16,24]) # #qc.mct([21,22,23],16,[24,25,26,27]) # for j in range (len(x)): # if x[j] == 1: # qc.cx(16,j) # # # # # qc.append(diffuser(4), [20,21,22,23]) # # # qc.measure([20,21,22,23],[3,2,1,0]) # return qc # # # # 6. Correct Solution. Score 26k def week3_ans_func(problem_set): ##### build your quantum circuit here ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. #### Code for Grover's algorithm with iterations = 1 will be as follows. #### for i in range(1): #### oracle() #### diffusion() from qiskit import QuantumCircuit, ClassicalRegister, QuantumCircuit,Aer, execute qc = QuantumCircuit(28,4) qc.h([20,21,22,23]) x = str_to_int(problem_set[0]) qc.x([20,21,22,23]) qc.append(qc2,[20,21,22,23,16,24,25]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[1]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[2]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[3]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[4]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(23,19) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[5]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[6]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[7]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[8]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(22,19) qc.cx(23,19) qc.x(23) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[9]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[10]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[11]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[12]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(23,19) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[13]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[14]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[15]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) qc.h(18) qc.z(18) qc.append(qc2,[0,5,10,15,18,24,25]) qc.append(qc2,[0,5,11,14,18,24,25]) qc.append(qc2,[0,6,9,15,18,24,25]) qc.append(qc2,[0,6,11,13,18,24,25]) qc.append(qc2,[0,7,9,14,18,24,25]) qc.append(qc2,[0,7,10,13,18,24,25]) qc.append(qc2,[1,4,10,15,18,24,25]) qc.append(qc2,[1,4,11,14,18,24,25]) qc.append(qc2,[1,6,8,15,18,24,25]) qc.append(qc2,[1,6,11,12,18,24,25]) qc.append(qc2,[1,7,8,14,18,24,25]) qc.append(qc2,[1,7,10,12,18,24,25]) qc.append(qc2,[2,4,9,15,18,24,25]) qc.append(qc2,[2,4,11,13,18,24,25]) qc.append(qc2,[2,5,8,15,18,24,25]) qc.append(qc2,[2,5,11,12,18,24,25]) qc.append(qc2,[2,7,8,13,18,24,25]) qc.append(qc2,[2,7,9,12,18,24,25]) qc.append(qc2,[3,4,9,14,18,24,25]) qc.append(qc2,[3,4,10,13,18,24,25]) qc.append(qc2,[3,5,8,14,18,24,25]) qc.append(qc2,[3,5,10,12,18,24,25]) qc.append(qc2,[3,6,8,13,18,24,25]) qc.append(qc2,[3,6,9,12,18,24,25]) #new qc.h(26) qc.append(qc5,[0,5,10,15,27,24,25,26]) qc.append(qc5,[0,5,11,14,27,24,25,26]) qc.append(qc5,[0,6,9,15,27,24,25,26]) qc.append(qc5,[0,6,11,13,27,24,25,26]) qc.append(qc5,[0,7,9,14,27,24,25,26]) qc.append(qc5,[0,7,10,13,27,24,25,26]) qc.append(qc5,[1,4,10,15,27,24,25,26]) qc.append(qc5,[1,4,11,14,27,24,25,26]) qc.append(qc5,[1,6,8,15,27,24,25,26]) qc.append(qc5,[1,6,11,12,27,24,25,26]) qc.append(qc5,[1,7,8,14,27,24,25,26]) qc.append(qc5,[1,7,10,12,27,24,25,26]) qc.append(qc5,[2,4,9,15,27,24,25,26]) qc.append(qc5,[2,4,11,13,27,24,25,26]) qc.append(qc5,[2,5,8,15,27,24,25,26]) qc.append(qc5,[2,5,11,12,27,24,25,26]) qc.append(qc5,[2,7,8,13,27,24,25,26]) qc.append(qc5,[2,7,9,12,27,24,25,26]) qc.append(qc5,[3,4,9,14,27,24,25,26]) qc.append(qc5,[3,4,10,13,27,24,25,26]) qc.append(qc5,[3,5,8,14,27,24,25,26]) qc.append(qc5,[3,5,10,12,27,24,25,26]) qc.append(qc5,[3,6,8,13,27,24,25,26]) qc.append(qc5,[3,6,9,12,27,24,25,26]) x = str_to_int(problem_set[0]) qc.x([20,21,22,23]) qc.append(qc2,[20,21,22,23,16,24,25]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[1]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[2]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[3]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[4]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(23,19) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[5]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[6]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[7]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[8]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(22,19) qc.cx(23,19) qc.x(23) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[9]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[10]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[11]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[12]) qc.ccx(20,21,17) qc.ccx(22,23,19) qc.ccx(17,19,16) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.x(22) qc.cx(23,19) qc.ccx(17,19,16) qc.ccx(22,23,19) qc.ccx(20,21,17) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[13]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[14]) qc.append(qc1,[20,21,17]) qc.append(qc1,[22,23,19]) qc.append(qc1,[17,19,16]) qc.x(20) qc.cx(20,17) qc.cx(21,17) qc.x(21) qc.append(qc1,[17,19,16]) qc.append(qc1,[22,23,19]) qc.append(qc1,[20,21,17]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) x = str_to_int(problem_set[15]) qc.x(20) qc.append(qc3,[21,22,23,16,24]) for j in range (len(x)): if x[j] == 1: qc.cx(16,j) qc.append(diffuser(4), [20,21,22,23]) qc.measure([20,21,22,23],[3,2,1,0]) return qc # + # Submission code from qc_grader import grade_ex3, prepare_ex3, submit_ex3 # Execute your circuit with following prepare_ex3() function. # The prepare_ex3() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex3(week3_ans_func) result = job.result() counts = result.get_counts() original_problem_set_counts = counts[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # - # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The lower the cost, the better. grade_ex3(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex3(job)
EX3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 22}) import math name = "gr" plt.rcParams.update({'font.size': 22}) data = pd.read_csv(name + ".csv", names=["V", "B"]) X = data["V"].values sigma_X = 0.8 Y = data["B"].values * data["B"].values / 1000000 sigma_Y = 0.7 A = np.vstack([X, np.ones(len(X))]).T k, b = np.linalg.lstsq(A, Y, rcond=None)[0] #sigma_k = math.sqrt((Y.std() - Y.mean()**2 ) / (X.std() - X.mean()**2 ) - b**2 ) / math.sqrt(len(X)) #eps_k = sigma_k / k #sigma_b = sigma_k * math.sqrt(X.std() / X.mean() - X.mean()**2 ) fig = plt.figure(figsize=(12, 7)) ax = fig.gca() plt.scatter(X, Y, marker=".") plt.errorbar(X, Y, xerr=sigma_X, yerr=sigma_Y, linestyle="None") delta_x = (X.max() - X.min()) / len(X) delta_y = (Y.max() - Y.min()) / len(Y) ax.set_xlim(X.min() - delta_x/2, X.max() + delta_x/2) ax.set_ylim((Y.min() - delta_y/2), Y.max() + delta_y/2) plt.ylabel("$B_{кр}^2, {Тл}^2$") plt.xlabel("$V, B$") plt.plot(X, (k*X + b), 'r', label='Fitted line') plt.grid(True) plt.savefig("../" + name + ".png") k b data print(data.to_latex()) data["d"].mean()
3.3.1/Terekhov_M/graphs/2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: tfp-env # language: python # name: anaconda-tfp_env # --- # # Mixture Consistency Projection # $$ # \hat{s_m} = \underline{s}_m + \frac{1}{M}(x - \sum_{m'}\underline{s}_{m'} ) # $$ # * $x$ is mixed input source # * $\underline{s}_m$ is the outputted seperate sources import tensorflow as tf import numpy as np def enforce_mixture_consistency_time_domain(mixture_waveforms, separated_waveforms): """Projection implementing mixture consistency in time domain. This projection makes the sum across sources of separated_waveforms equal mixture_waveforms and minimizes the unweighted mean-squared error between the sum across sources of separated_waveforms and mixture_waveforms. See https://arxiv.org/abs/1811.08521 for the derivation. Args: mixture_waveforms: Tensor of mixture waveforms in waveform format. separated_waveforms: Tensor of separated waveforms in source image format. Returns: Projected separated_waveforms as a Tensor in source image format. """ # Modify the source estimates such that they sum up to the mixture, where # the mixture is defined as the sum across sources of the true source # targets. Uses the least-squares solution under the constraint that the # resulting source estimates add up to the mixture. num_sources = 4.0 mix_estimate = tf.reduce_sum(separated_waveforms, axis=1, keepdims=True) #mix_weights = tf.reduce_mean(tf.square(separated_waveforms), axis=[1, 2],keepdims=True) #mix_weights /= tf.reduce_sum(mix_weights, axis=1, keepdims=True) mix_weights = (1.0 / num_sources) mix_weights = tf.cast(mix_weights, tf.float32) correction = mix_weights * (mixture_waveforms - mix_estimate) separated_waveforms = separated_waveforms + correction return separated_waveforms # + mix_wave = tf.Variable([[1,2,3],[4,5,6]],dtype=tf.float32) mix_wave = tf.expand_dims(mix_wave,axis=1) print(mix_wave.shape) sep_wave = tf.Variable([[[1,2,4],[3,5,7]],[[1,2,4],[3,5,7]]],dtype=tf.float32) print(sep_wave.shape) projected_sep = enforce_mixture_consistency_time_domain(mix_wave,sep_wave) print(projected_sep) print(projected_sep.shape) # -
AudioSeparator/src/MixtureConsistencyProjection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + def greeting(): print ("Hello World!") greeting() greeting.lang = "English" print (greeting.lang) # + def square (x): return x * x square(5) def foo(square): return square * square foo(6) # - # + def formalGreeting(): print ("How are you?") def casualGreeting(): print ("What's up?") def greet(type, greetFormal, greetCasual): if type == "formal": greetFormal() elif type == "casual": greetCasual() greet("formal", formalGreeting, casualGreeting) # + arr1 = [1, 2, 3] arr2 = [] for x in range(0, len(arr1)): arr2 = arr1[x] * 2 # prints [ 2, 4, 6 ] print(arr2) # - arr1 = [1, 2, 3] squares = map(lambda x: x * 2, arr1) print (*squares) birthYear = [1975, 1997, 2002, 1995, 1985] ages = map(lambda x: 2018 - x, birthYear) # prints [ 43, 21, 16, 23, 33 ] print(*ages) # + persons = { 1 : { "name" : "Peter", "age" : 16 }, 2 : { "name" : "Mark", "age" : 18 }, 3 : { "name" : "John", "age" : 27 }, 4 : { "name" : "Jane", "age" : 14 }, 5 : { "name" : "Tony", "age" : 24 } } # fullAge = [] # for data in persons: # for data2 in data: # if data2["age"] >= 18: # fullAge.append(persons[data]) for age in persons.items(): if age["age"] >= 18: fullAge.append() print(fullAge) # print (persons) # - birthYear = [1975, 1997, 2002, 1995, 1985] ages = [] for x in range(0, len(birthYear)): ages = 2018 - birthYear[x] # prints [ 2, 4, 6 ] print(ages) # + persons = { 1 : { "name" : "Peter", "age" : 16 }, 2 : { "name" : "Mark", "age" : 18 }, 3 : { "name" : "John", "age" : 27 }, 4 : { "name" : "Jane", "age" : 14 }, 5 : { "name" : "Tony", "age" : 24 } # arr1 = [1, 2, 3] squares = filter(lambda x: x >= 18, persons{"age"}) print (*squares) # - arr = [5, 7, 1, 8, 4] sum = arr.(function(accumulator, currentValue): return accumulator + currentValue # // prints 25 print(sum);
novice/02-01/kasus/kasus.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Features derived from an limit order book # # In this book we make an attempt to create features based on bids and asks in a limit orderbook. # We discuss what how the data could be processed such that machine learning models can understand certain patterns and possibly act in favour of execution optimization. # %cd .. from ctc_executioner.orderbook import Orderbook orderbook = Orderbook() orderbook.loadFromEvents('data/events/ob-1-small.tsv') orderbook.plot() # First we draw a random state (index) from the orderbook with which we have enough time remaining to proceed an execution of 120 seconds. state, state_index = orderbook.getRandomState(120) state # Here the bids and asks in dictionary form. d_state = orderbook.getDictState(state_index) d_state # # Private Variables # # Private variables in the context of order execution is a tuple of the remaining time (seconds) and inventory (share size). (120, 1.0) # 1.0 BTC left to be executed within 120 seconds # As we can see, there is not much information to be drawn from the private variables. Hence we lay our focus on the market variables. # # Market Variables # # Market variables contain information derived from the market at the time right before the execution is being placed. # # However, the fact that this is a non-stationary time series setting, one would have to 1) preprocess features either beforehand or on demand and 2) likely be forced to approximate the resulted values in order get an indication of the value relative to the values derived from other states. # # An alternative approach would be to use raw inputs as market variables and in a later learning process let a funciton approximator derive relations. Thus, the following section will present a way of representing a limit order book as a matrix, acting as a raw set of features. # # ## Bids / Asks import numpy as np from collections import OrderedDict import pandas as pd state = orderbook.getDictState(state_index) asks = state['asks'] bids = state['bids'] bestAsk = min(asks.keys()) # We now represent the bids and asks as a numpy array in the shape of `(2, levels, count(features))`. # In case both features, price and size are enabled, the output is as follows: # # ``` # [ # [ # [bid_price bid_size] # [... ... ] # ] # [ # [ask_price ask_size] # [... ... ] # ] # ] # ``` # # If eiether price or size is choosen only, the output has the shape `(2, levels)` and is as follows: # # ``` # [ # [ # bid_price # ... # ] # [ # ask_price # ... # ] # ] # ``` # # or respectively: # # ``` # [ # [ # bid_size # ... # ] # [ # ask_size # ... # ] # ] # ``` def getBidAskFeature(bids, asks, qty=None, price=True, size=True, normalize=False, levels=20): """Creates feature to represent bids and asks. The prices and sizes of the bids and asks are normalized by the provided (naturally current) bestAsk and the provided quantity respectively. Shape: (2, levels, count(features)), whereas features can be [price, size] [ [ [bid_price bid_size] [... ... ] ] [ [ask_price ask_size] [... ... ] ] ] """ assert(price is True or size is True) def toArray(d): s = pd.Series(d, name='size') s.index.name='price' s = s.reset_index() return np.array(s) def force_levels(a, n=levels): """Shrinks or expands array to n number of records.""" gap = (n - a.shape[0]) if gap > 0: gapfill = np.zeros((gap, 2)) a = np.vstack((a, gapfill)) return a elif gap <= 0: return a[:n] bids = OrderedDict(sorted(bids.items(), reverse=True)) asks = OrderedDict(sorted(asks.items())) bids = toArray(bids) asks = toArray(asks) if normalize is True: assert(qty is not None) bestAsk = np.min(asks[:,0]) bids = np.column_stack((bids[:,0] / bestAsk, bids[:,1] / qty)) asks = np.column_stack((asks[:,0] / bestAsk, asks[:,1] / qty)) bidsAsks = np.array([force_levels(bids), force_levels(asks)]) if price is True and size is True: return bidsAsks if price is True: return bidsAsks[:,:,0] if size is True: return bidsAsks[:,:,1] feature_ba = getBidAskFeature(d_state['bids'], d_state['asks'], qty=1.0, normalize=True, price=True, size=True, levels = 10) print(feature_ba.shape) print(feature_ba) feature_ba = getBidAskFeature(d_state['bids'], d_state['asks'], qty=1.0, normalize=True, price=True, size=False, levels = 5) print(feature_ba) # Given the function `getBidAskFeature` with which we can represent the order book state as a numpy array, we now want to combine a certain number of states into one data structure. # Hence, a `lookback` is defined which tells how many states in the past (relative to the `state_index`) shall be considered. # # The output of this funciton def getBidAskFeatures(d, state_index, lookback, qty=None, price=True, size=True, normalize=False, levels=20): """ Creates feature to represent bids and asks with a lookback of previous states. Shape: (2*lookback, levels, count(features)) """ state = d[list(d.keys())[state_index]] asks = state['asks'] bids = state['bids'] bestAsk = min(asks.keys()) i = 0 while i < lookback: state_index = state_index - 1 state = d[list(d.keys())[state_index]] asks = state['asks'] bids = state['bids'] features_next = getBidAskFeature( bids=bids, asks=asks, qty=qty, price=price, size=size, normalize=normalize, levels=levels ) if i == 0: features = features_next else: features = np.vstack((features, features_next)) i = i + 1 return features features = getBidAskFeatures(orderbook.dictBook, state_index, lookback=3, qty=1.0, normalize=True, price=True, size=True, levels = 5) features # As we can see, the bids and asks are currently threated separately. # As the orderbook comes natural with both sides, which are already ordered such that best-bid and best-ask are in the middle, we can combine the sides and shrink the number of features by half and instead merge the second dimension. # Hence the shaps is: `(lookback, 2*levels, count(features))` features_combined = features.reshape((int(features.shape[0]/2), features.shape[1]*2, features.shape[2])) print(features_combined.shape) features_combined # **Note:** The demonstrated features has been integrated in the Orderbook class and can be used directly: orderbook.getBidAskFeatures(state_index, lookback=3, qty=1.0, normalize=True, price=True, size=True, levels = 5) # ## Correlation of order book states # # We now want to make a statement about the correlation of the previous states in order to determiene what an appropriate lookback might be. # # At first, however, let us understand how many states occur per second and what the change of price in dollar is per second. orderbook.summary() # After having a brief understanding of the states the order book contains, we go further and take a random state and determine the pearson correlations of the prices and sizes from the previous n states. # This shall provide an intuition of how much information is provided by previous order book states. # + import scipy as sp lookback = 100 lookback_range = range(lookback) prices = [] sizes = [] for _ in range(10): state, state_index = orderbook.getRandomState(runtime=120, min_head=lookback) features = orderbook.getBidAskFeatures(state_index, lookback=lookback, qty=1.0, normalize=False, levels = 20) bidsasks = features.reshape((int(features.shape[0]/2), features.shape[1]*2, features.shape[2])) arr_price = [] for i in lookback_range: corr, p = sp.stats.pearsonr(bidsasks[0,:,0], bidsasks[i,:,0]) arr_price.append(corr) prices.append(arr_price) arr_size = [] for i in lookback_range: corr, p = sp.stats.pearsonr(bidsasks[0,:,1], bidsasks[i,:,1]) arr_size.append(corr) sizes.append(arr_size) prices_mean = np.mean(np.array(prices), axis=0) sizes_mean = np.mean(np.array(sizes), axis=0) import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams.update({'font.size': 22}) plt.figure(figsize=(24, 18)) plt.title("Price correlation") plt.plot(lookback_range, prices_mean) plt.show() # + import matplotlib.pyplot as plt plt.figure(figsize=(24, 18)) plt.title("Size correlation") plt.plot(lookback_range, sizes_mean) plt.show() # - # As we can see, price constellations in order books correlate much more than the sizes. # Furthermore, the correlation of the price positions remain more or less constant, followed by a signigicant drop after a few states into the past. The size correlation however drops immediately. # Given the high correlation of prices, a *lookback* of >40 states is suggested. # + import scipy as sp lookback = 1000 lookback_range = range(lookback) p_bids = [] p_asks = [] s_bids = [] s_asks = [] for _ in range(10): state, state_index = orderbook.getRandomState(runtime=120, min_head=lookback) features = orderbook.getBidAskFeatures(state_index, lookback=lookback, qty=1.0, normalize=False, levels = 40) bidsasks = features.reshape((int(features.shape[0]), features.shape[1], features.shape[2])) bids = bidsasks[::2,:,:] asks = bidsasks[1::2,:,:] p_bid = bids[:,:,0] p_ask = asks[:,:,0] s_bid = bids[:,:,1] s_ask = asks[:,:,1] p_bids.append(sp.stats.entropy(p_bid)) p_asks.append(sp.stats.entropy(p_ask)) s_bids.append(sp.stats.entropy(s_bid)) s_asks.append(sp.stats.entropy(s_ask)) p_bids_mean = np.mean(np.array(p_bids), axis=0) p_asks_mean = np.mean(np.array(p_asks), axis=0) s_bids_mean = np.mean(np.array(s_bids), axis=0) s_asks_mean = np.mean(np.array(s_asks), axis=0) import matplotlib.pyplot as plt plt.figure(figsize=(24, 18)) plt.title("Price entropy") plt.plot(p_bids_mean, label='bid') plt.plot(p_asks_mean, label='ask') plt.legend() plt.show() import matplotlib.pyplot as plt plt.figure(figsize=(24, 18)) plt.title("Size entropy") plt.plot(s_bids_mean, label='bid') plt.plot(s_asks_mean, label='ask') plt.legend() plt.show() # - # We take 1000 random order book states for which we measure the entropy for a range of 40 limit levels on the bid and ask side, applied to price (see Figure 1) and size (see Figure 2). # It is noticable that the entropy remains high regarding the pices for for limit levels 0-30 on both, bid and ask side. # The price becomes slightly more constant for limit levels >30. # The entropy for order sizes drop after 20 limit levels, which means that the accumulated order size deep in the book is more constant. # We therefore suggest to consider at least 30 limit levels of the bid-ask feature. # # Conclusion # # This analysis provides an example on how to model a limit order book as a matrix. We further show how to incorporate multiple order book states from the past into the order book matrix and thereby define the number of steps to include as *lookback*. # By briefly highlighting the sparse amount of *private variables* (2) and their purpose we ensure the reader understands the importance of *market variables*. Thereby we highlight the difficulties of creating features within a time series setting and suggest to use raw features. A raw feature set is being derived from the order book and is demonstrated as the mentioned order book matrix. # To get an understanding on the correlation of the prices and sized contained in a set of order book states, we draw the pearson correlation and conclude that prices are much more related among order book states than the offered sizes.
ctc-executioner/notebooks/orderbook_features.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt house_data = pd.read_csv('house_prices.csv') house_data.head() str_columns = house_data.columns[house_data.dtypes == 'object'] for col in str_columns: del house_data[col] del house_data['Id'] house_data.head() y = house_data['SalePrice'] del house_data['SalePrice'] from sklearn.cross_validation import train_test_split Xtrain, Xtest, Ytrain, Ytest = train_test_split(house_data, y, test_size=0.2) from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(Xtrain, Ytrain) from sklearn.metrics import mean_squared_error, mean_absolute_error mean_absolute_error(model.predict(Xtest), Ytest)
research-1/house_prices_prediction_baseline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/NoCodeProgram/CodingTest/blob/main/sorting/countingSort.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="bV43KiJML_md" # Title : Counting Sort # # Chapter : sort # # Link : # # ChapterLink : # # 문제: 주어진 array를 countingSort 하여라 # + colab={"base_uri": "https://localhost:8080/"} id="FUvWAIKeL3bg" outputId="c970e175-6878-4a2e-df90-afd7ce62e51d" from typing import List def countingSort(nums:List[int])->List[int]: length = len(nums) min_num = min(nums) #offset max_num = max(nums) range = max_num - min_num + 1 counts = [0]*range for num in nums: count_idx = num - min_num counts[count_idx] += 1 acc_counts = [] acc_count = 0 for count in counts: acc_count += count acc_counts.append(acc_count) end_locs = [ c-1 for c in acc_counts] sorted = [0] * length for num in reversed(nums): count_idx = num - min_num end_loc = end_locs[count_idx] sorted[end_loc] = num end_locs[count_idx] -= 1 return sorted print(countingSort(nums=[3,4,0,1,2])) print(countingSort(nums=[3,0,5,1,0,5])) # + id="DFprq7ngNwkx"
sorting/countingSort.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import cv2 import numpy as np import matplotlib.pyplot as plt import os import pathlib import tensorflow_addons as tfa from tensorflow.python.client import device_lib print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) physical_devices = tf.config.list_physical_devices('GPU') tf.config.set_visible_devices( physical_devices[1], 'GPU' ) # # Data Loading # Data pre-processing details: # # * The only pre-processing they do is subtracting the mean RGB value, computed on the training set, from each pixel. # # Data augmentation: # # * To further augment the training set, the crops underwent random horizontal flipping and random RGB colour shift. path_train = 'CINIC10/train/' path_val = 'CINIC10/valid/' path_test = 'CINIC10/test/' data_dir_train = pathlib.Path(path_train) data_dir_val = pathlib.Path(path_val) data_dir_test = pathlib.Path(path_test) list_ds_train = tf.data.Dataset.list_files(str(data_dir_train/'*/*')) list_ds_val = tf.data.Dataset.list_files(str(data_dir_val/'*/*')) list_ds_test = tf.data.Dataset.list_files(str(data_dir_test/'*/*')) CLASS_NAMES = np.array([item.name for item in data_dir_train.glob('*')]) def get_label(file_path): parts = tf.strings.split(file_path, os.path.sep) return parts[-2] == CLASS_NAMES def decode_img(img, dsize): img = tf.image.decode_jpeg(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) return tf.image.resize(img, [dsize[0], dsize[1]]) def process_path(file_path): size = (224,224) label = get_label(file_path) img = tf.io.read_file(file_path) img = decode_img(img,size ) return img, label AUTOTUNE = tf.data.experimental.AUTOTUNE labeled_ds_train = list_ds_train.map(process_path, num_parallel_calls=AUTOTUNE) labeled_ds_valid = list_ds_val.map(process_path, num_parallel_calls=AUTOTUNE) labeled_ds_test = list_ds_test.map(process_path, num_parallel_calls=AUTOTUNE) def augmentation(x, y): x = tf.image.random_flip_left_right(x) x = tf.image.random_brightness(x, max_delta=0.5) return x, y def normalize(x, y): x = tf.image.per_image_standardization(x) return x, y def prepare_for_training(ds, training = False, cache=True, shuffle_buffer_size=1000, batch_size = 128): if cache: if isinstance(cache, str): ds = ds.cache(cache) else: ds = ds.cache() ds = ds.map(normalize) if training: ds = ds.map(augmentation) ds = ds.shuffle(buffer_size=shuffle_buffer_size) ds = ds.repeat() ds = ds.batch(batch_size) ds = ds.prefetch(buffer_size=AUTOTUNE) return ds train_ds = prepare_for_training(labeled_ds_train, training = True, batch_size=64) val_ds = prepare_for_training(labeled_ds_valid, batch_size = 64) test_ds = prepare_for_training(labeled_ds_test, batch_size = 64) # # VGG Details # * This architecture was built based on AlexNet, by visualizing the features in a fully AlexNet trained model # * optimizer = SGD # * batch_size = 256 # * momentum = 0.9 # * weight decay = 0.0005 # * weights random initialization: mean-0 variance-0.01 # * bias = 0 # * lr_initial = 0.01 (reduced three time prior termination) # * num_epochs = 74 # * cross-entropy loss # # Model Definition # A little vit verbose but in the next models we are going to define the models in a smarter way. def Model(num_classes = 1000): kernel_init = tf.keras.initializers.GlorotNormal() model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(64,kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu', input_shape=(224,224,3)), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(64,kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)), tf.keras.layers.Conv2D(128, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(128, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)), tf.keras.layers.Conv2D(256, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(256, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(256, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.Conv2D(512, kernel_size=(3,3), kernel_initializer = kernel_init, padding='same', strides=(1,1), activation='relu'), tf.keras.layers.BatchNormalization(), tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(4096, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(4096, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(num_classes, 'softmax') ]) return model model = Model(10) model.summary() # # Training model.compile(optimizer=tfa.optimizers.SGDW(momentum=0.9,weight_decay=0.0005,learning_rate=0.01), loss = 'categorical_crossentropy', metrics = ['accuracy']) history = model.fit(train_ds, epochs = 74, steps_per_epoch=100, verbose = 1, validation_data = val_ds, validation_steps = 100) # # Evaluation loss_test, accuracy_test = model.evaluate(test_ds, verbose = 1, steps = 5) loss_test, accuracy_test # # Training results visualization plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train','validation'], loc='upper left') plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Loss Curve') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper right') plt.show()
CNNs/1-Image_Classification/3_VGG16.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Express sklearn pipeline as codeflare pipeline # Reference: https://scikit-learn.org/stable/auto_examples/kernel_approximation/plot_scalable_poly_kernels.html#sphx-glr-auto-examples-kernel-approximation-plot-scalable-poly-kernels-py # %matplotlib inline # # # Scalable learning with polynomial kernel aproximation # # This example illustrates the use of :class:`PolynomialCountSketch` to # efficiently generate polynomial kernel feature-space approximations. # This is used to train linear classifiers that approximate the accuracy # of kernelized ones. # # .. currentmodule:: sklearn.kernel_approximation # # We use the Covtype dataset [2], trying to reproduce the experiments on the # original paper of Tensor Sketch [1], i.e. the algorithm implemented by # :class:`PolynomialCountSketch`. # # First, we compute the accuracy of a linear classifier on the original # features. Then, we train linear classifiers on different numbers of # features (`n_components`) generated by :class:`PolynomialCountSketch`, # approximating the accuracy of a kernelized classifier in a scalable manner. # # + print(__doc__) # Author: <NAME> <<EMAIL>> # License: BSD 3 clause import matplotlib.pyplot as plt from sklearn.datasets import fetch_covtype from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, Normalizer from sklearn.svm import LinearSVC from sklearn.kernel_approximation import PolynomialCountSketch from sklearn.pipeline import Pipeline, make_pipeline import time # - # Load the Covtype dataset, which contains 581,012 samples # with 54 features each, distributed among 6 classes. The goal of this dataset # is to predict forest cover type from cartographic variables only # (no remotely sensed data). After loading, we transform it into a binary # classification problem to match the version of the dataset in the # LIBSVM webpage [2], which was the one used in [1]. # # # + X, y = fetch_covtype(return_X_y=True) y[y != 2] = 0 y[y == 2] = 1 # We will try to separate class 2 from the other 6 classes. # - # Here we select 5,000 samples for training and 10,000 for testing. # To actually reproduce the results in the original Tensor Sketch paper, # select 100,000 for training. # # X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=5_000, test_size=10_000, random_state=42) # Now scale features to the range [0, 1] to match the format of the dataset in # the LIBSVM webpage, and then normalize to unit length as done in the # original Tensor Sketch paper [1]. # # mm = make_pipeline(MinMaxScaler(), Normalizer()) X_train = mm.fit_transform(X_train) X_test = mm.transform(X_test) # As a baseline, train a linear SVM on the original features and print the # accuracy. We also measure and store accuracies and training times to # plot them latter. # # # + results = {} lsvm = LinearSVC() start = time.time() lsvm.fit(X_train, y_train) lsvm_time = time.time() - start lsvm_score = 100 * lsvm.score(X_test, y_test) results["LSVM"] = {"time": lsvm_time, "score": lsvm_score} print(f"Linear SVM score on raw features: {lsvm_score:.2f}%") # - # Then we train linear SVMs on the features generated by # :class:`PolynomialCountSketch` with different values for `n_components`, # showing that these kernel feature approximations improve the accuracy # of linear classification. In typical application scenarios, `n_components` # should be larger than the number of features in the input representation # in order to achieve an improvement with respect to linear classification. # As a rule of thumb, the optimum of evaluation score / run time cost is # typically achieved at around `n_components` = 10 * `n_features`, though this # might depend on the specific dataset being handled. Note that, since the # original samples have 54 features, the explicit feature map of the # polynomial kernel of degree four would have approximately 8.5 million # features (precisely, 54^4). Thanks to :class:`PolynomialCountSketch`, we can # condense most of the discriminative information of that feature space into a # much more compact representation. We repeat the experiment 5 times to # compensate for the stochastic nature of :class:`PolynomialCountSketch`. # # n_runs = 3 for n_components in [250, 500, 1000, 2000]: ps_lsvm_time = 0 ps_lsvm_score = 0 for _ in range(n_runs): pipeline = Pipeline(steps=[("kernel_approximator", PolynomialCountSketch( n_components=n_components, degree=4)), ("linear_classifier", LinearSVC())]) start = time.time() pipeline.fit(X_train, y_train) ps_lsvm_time += time.time() - start ps_lsvm_score += 100 * pipeline.score(X_test, y_test) ps_lsvm_time /= n_runs ps_lsvm_score /= n_runs results[f"LSVM + PS({n_components})"] = { "time": ps_lsvm_time, "score": ps_lsvm_score } print(f"Linear SVM score on {n_components} PolynomialCountSketch " + f"features: {ps_lsvm_score:.2f}%") # Train a kernelized SVM to see how well :class:`PolynomialCountSketch` # is approximating the performance of the kernel. This, of course, may take # some time, as the SVC class has a relatively poor scalability. This is the # reason why kernel approximators are so useful: # # # + from sklearn.svm import SVC ksvm = SVC(C=500., kernel="poly", degree=4, coef0=0, gamma=1.) start = time.time() ksvm.fit(X_train, y_train) ksvm_time = time.time() - start ksvm_score = 100 * ksvm.score(X_test, y_test) results["KSVM"] = {"time": ksvm_time, "score": ksvm_score} print(f"Kernel-SVM score on raw featrues: {ksvm_score:.2f}%") # - # Finally, plot the resuts of the different methods against their training # times. As we can see, the kernelized SVM achieves a higher accuracy, # but its training time is much larger and, most importantly, will grow # much faster if the number of training samples increases. # # # + N_COMPONENTS = [250, 500, 1000, 2000] fig, ax = plt.subplots(figsize=(7, 7)) ax.scatter([results["LSVM"]["time"], ], [results["LSVM"]["score"], ], label="Linear SVM", c="green", marker="^") ax.scatter([results["LSVM + PS(250)"]["time"], ], [results["LSVM + PS(250)"]["score"], ], label="Linear SVM + PolynomialCountSketch", c="blue") for n_components in N_COMPONENTS: ax.scatter([results[f"LSVM + PS({n_components})"]["time"], ], [results[f"LSVM + PS({n_components})"]["score"], ], c="blue") ax.annotate(f"n_comp.={n_components}", (results[f"LSVM + PS({n_components})"]["time"], results[f"LSVM + PS({n_components})"]["score"]), xytext=(-30, 10), textcoords="offset pixels") ax.scatter([results["KSVM"]["time"], ], [results["KSVM"]["score"], ], label="Kernel SVM", c="red", marker="x") ax.set_xlabel("Training time (s)") ax.set_ylabel("Accurary (%)") ax.legend() plt.show() # - # ## References # # [1] <NAME> and <NAME>. "Fast and scalable polynomial kernels via # explicit feature maps." KDD '13 (2013). # https://doi.org/10.1145/2487575.2487591 # # [2] LIBSVM binary datasets repository # https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html # # # + import ray import codeflare.pipelines.Datamodel as dm import codeflare.pipelines.Runtime as rt from codeflare.pipelines.Datamodel import Xy from codeflare.pipelines.Datamodel import XYRef from codeflare.pipelines.Runtime import ExecutionType ray.shutdown() ray.init() n_runs = 3 score_250 = 0 score_500 = 0 score_1000 = 0 score_2000 = 0 run_time = 0 for _ in range(n_runs): start = time.time() pipeline = dm.Pipeline() node_pcs250 = dm.EstimatorNode("kernel_approximator_250", PolynomialCountSketch(n_components=250, degree=4)) node_pcs500 = dm.EstimatorNode("kernel_approximator_500", PolynomialCountSketch(n_components=500, degree=4)) node_pcs1000 = dm.EstimatorNode("kernel_approximator_1000", PolynomialCountSketch(n_components=1000, degree=4)) node_pcs2000 = dm.EstimatorNode("kernel_approximator_2000", PolynomialCountSketch(n_components=2000, degree=4)) node_clf250 = dm.EstimatorNode("linear_classifier_250", LinearSVC()) node_clf500 = dm.EstimatorNode("linear_classifier_500", LinearSVC()) node_clf1000 = dm.EstimatorNode("linear_classifier_1000", LinearSVC()) node_clf2000 = dm.EstimatorNode("linear_classifier_2000", LinearSVC()) pipeline.add_edge(node_pcs250, node_clf250) pipeline.add_edge(node_pcs500, node_clf500) pipeline.add_edge(node_pcs1000, node_clf1000) pipeline.add_edge(node_pcs2000, node_clf2000) # create training input train_input = dm.PipelineInput() xy_train = dm.Xy(X_train, y_train) train_input.add_xy_arg(node_pcs250, xy_train) train_input.add_xy_arg(node_pcs500, xy_train) train_input.add_xy_arg(node_pcs1000, xy_train) train_input.add_xy_arg(node_pcs2000, xy_train) # codeflare pipeline is able to execute model FIT once with four n_components pipeline_fitted = rt.execute_pipeline(pipeline, ExecutionType.FIT, train_input) xy_test = dm.Xy(X_test, y_test) test_input = dm.PipelineInput() test_input.add_xy_arg(node_pcs250, xy_test) pipeline_250 = rt.select_pipeline(pipeline_fitted, pipeline_fitted.get_xyrefs(node_clf250)[0]) score_250 += 100 * ray.get(rt.execute_pipeline(pipeline_250, ExecutionType.SCORE, test_input) .get_xyrefs(node_clf250)[0].get_Xref()) test_input = dm.PipelineInput() test_input.add_xy_arg(node_pcs500, xy_test) pipeline_500 = rt.select_pipeline(pipeline_fitted, pipeline_fitted.get_xyrefs(node_clf500)[0]) score_500 += 100 * ray.get(rt.execute_pipeline(pipeline_500, ExecutionType.SCORE, test_input) .get_xyrefs(node_clf500)[0].get_Xref()) test_input = dm.PipelineInput() test_input.add_xy_arg(node_pcs1000, xy_test) pipeline_1000 = rt.select_pipeline(pipeline_fitted, pipeline_fitted.get_xyrefs(node_clf1000)[0]) score_1000 += 100 * ray.get(rt.execute_pipeline(pipeline_1000, ExecutionType.SCORE, test_input) .get_xyrefs(node_clf1000)[0].get_Xref()) test_input = dm.PipelineInput() test_input.add_xy_arg(node_pcs2000, xy_test) pipeline_2000 = rt.select_pipeline(pipeline_fitted, pipeline_fitted.get_xyrefs(node_clf2000)[0]) score_2000 += 100 * ray.get(rt.execute_pipeline(pipeline_2000, ExecutionType.SCORE, test_input) .get_xyrefs(node_clf2000)[0].get_Xref()) run_time += ((time.time() - start)/4) # all runs have the the same run time since they are FITTED together results[f"LSVM + PS(250)"] = { "time": run_time/n_runs, "score": score_250/n_runs } results[f"LSVM + PS(500)"] = { "time": run_time/n_runs, "score": score_500/n_runs } results[f"LSVM + PS(1000)"] = { "time": run_time/n_runs, "score": score_1000/n_runs } results[f"LSVM + PS(2000)"] = { "time": run_time/n_runs, "score": score_2000/n_runs } N_COMPONENTS = [250, 500, 1000, 2000] fig, ax = plt.subplots(figsize=(7, 7)) ax.scatter([results["LSVM"]["time"], ], [results["LSVM"]["score"], ], label="Linear SVM", c="green", marker="^") ax.scatter([results["LSVM + PS(250)"]["time"], ], [results["LSVM + PS(250)"]["score"], ], label="Linear SVM + PolynomialCountSketch", c="blue") for n_components in N_COMPONENTS: ax.scatter([results[f"LSVM + PS({n_components})"]["time"], ], [results[f"LSVM + PS({n_components})"]["score"], ], c="blue") ax.annotate(f"n_comp.={n_components}", (results[f"LSVM + PS({n_components})"]["time"], results[f"LSVM + PS({n_components})"]["score"]), xytext=(-30, 10), textcoords="offset pixels") ax.scatter([results["KSVM"]["time"], ], [results["KSVM"]["score"], ], label="Kernel SVM", c="red", marker="x") ax.set_xlabel("Training time (s)") ax.set_ylabel("Accurary (%)") ax.legend() plt.show() ray.shutdown() # -
notebooks/plot_scalable_poly_kernels.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # Initial imports import numpy as np import pandas as pd from pathlib import Path import arch as arch # %matplotlib inline # - file_path = Path('PrivateEquityReturnsFinal.csv') pe_df = pd.read_csv(file_path, parse_dates=True, index_col='Date', infer_datetime_format=True) pe_df df = pd.DataFrame(pe_df['Private Equity Returns']) df file_path_2 = Path('SPXReturns.csv') eq_df = pd.read_csv(file_path_2, parse_dates=True, index_col='Date', infer_datetime_format=True) eq_df eq_df.dropna() returns_df = pd.concat([df, eq_df], axis=1, join='inner') returns_df #Calculating the Funds STD rolling_std = returns_df.rolling(window=4).std() rolling_std #Plotting Fund Returns STD rolling_std['Private Equity Returns'].plot() #Plotting Market STD rolling_std['SPX_Return'].plot() #Calculating Covariance rolling_covariance = returns_df['Private Equity Returns'].rolling(window=4).cov(returns_df['SPX_Return']) rolling_covariance #Calculate Rolling Variance rolling_variance_spx = returns_df['SPX_Return'].rolling(window=4).var() rolling_variance_spx #Calculate the rolling 1 year beta of the Fund rolling_beta = rolling_covariance / rolling_variance_spx rolling_beta.plot() #Calculating Sharpes sharpe_ratio = (returns_df['Private Equity Returns'].mean()*4)/(returns_df['Private Equity Returns'].std()*np.sqrt(4)) sharpe_ratio #Start of the Monte Carlo Analysis avg_qtr_return_pe = returns_df.mean()['Private Equity Returns'] avg_qtr_return_spx = returns_df.mean()['SPX_Return'] avg_qtr_return_spx #Calculating the Std for Private Equity Returns and S&P std_dev_qtr_return_pe = returns_df.std()['Private Equity Returns'] std_dev_qtr_return_spx = returns_df.std()['SPX_Return'] std_dev_qtr_return_spx # Save the last day's closing price pe_last_price = returns_df['Private Equity Returns'][-1] spx_last_price = returns_df['SPX_Return'][-1] # Setup the Monte Carlo Parameters number_simulations = 500 number_records = 4 * 30 monte_carlo = pd.DataFrame() portfolio_cumulative_returns = pd.DataFrame() # + # Run the Monte Carlo Simulation for n in range(number_simulations): # Initialize last Prices simulated_pe_prices = [pe_last_price] simulated_spx_prices = [spx_last_price] # Simulate the returns for last 5 years for i in range(number_records): # Calculate the simulated SPY and AGG prices simulated_pe_price = simulated_pe_prices[-1] * (1 + np.random.normal(avg_qtr_return_pe, std_dev_qtr_return_pe)) simulated_spx_price = simulated_spx_prices[-1] * (1 + np.random.normal(avg_qtr_return_spx, std_dev_qtr_return_spx)) # Append the simulated price to the list simulated_pe_prices.append(simulated_pe_price) simulated_spx_prices.append(simulated_spx_price) # Append a simulated prices of each simulation to DataFrame monte_carlo["PE prices"] = pd.Series(simulated_pe_prices) monte_carlo["SPX prices"] = pd.Series(simulated_spx_prices) # Calculate the daily returns of simulated prices simulated_qtr_returns = monte_carlo.pct_change() # Set the portfolio weights (60% SPY; 40% AGG) weights = [1,0] # Use the `dot` function with the weights to multiply weights with each column's simulated daily returns portfolio_qtr_returns = simulated_qtr_returns.dot(weights) # Calculate the normalized, cumulative return series portfolio_cumulative_returns[n] = (1 + portfolio_qtr_returns.fillna(0)).cumprod() # Print records from the DataFrame portfolio_cumulative_returns.head() # - # Visualize the Simulation plot_title = f"{n+1} Simulations of Cumulative Portfolio Return Trajectories Over the Next 30 Years" portfolio_cumulative_returns.plot(legend=None, title=plot_title) pd.DataFrame(scaled_returns).hist() pe_df['Private Equity Returns'].hist() pe_df.pe_returns.hist() # + #pe_df = pe_df.dropna() #pe_df # + #pe_2_df = pe_df.set_index(['Date']) #pe_2_df # + #pe_final = pe_df['Private Equity Returns'].copy() #pe_final# # + #pe_final = pd.DataFrame(columns=['Date','Private Equity Returns']) #pe_final # + #pe_final = pe_final.drop([134]) #pe_final # + #pe_final = pe_final.set_index('Date') #pe_final # - pe_df['Private Equity Returns'].plot() pe_df['Cumulative'].plot() pe_df = df.asfreq('Q-DEC') pd.infer_freq(pe_df.index) from arch import arch_model # 'p' and 'q' are akin to the 'p' and 'q' of an ARMA model. # 'vol="GARCH"' means that we're using a GARCH model. # The 'mean="Zero"' means that we're estimating a GARCH. model = arch_model(pe_df.pe_returns, mean="Zero", vol="Garch", p=3, q=3) # Fit the GARCH Model res = model.fit() import statsmodels.api as sm ts_noise, ts_trend = sm.tsa.filters.hpfilter(pe_df.pe_returns) ts_noise.plot() ts_trend.plot() fit. pe_df.pe_returns.plot() # Summarize the model results res.summary() # Plot the model estimate of annualized volatility fig = res.plot() # Construct Volatility Forecasts for the next 3 days forecast_horizon = 3 # Take the last day of the data we used above. # If forecast horizon is 3, then the resulting 'h.1', 'h.2', and 'h.3' # are the forecasts for the following 3 days. forecasts = res.forecast(start='2019-06-30', horizon=forecast_horizon) forecasts.mean pe_df.tail() pe_df.tail() forecasts = res.forecast(start='2019-12-01', horizon=3) forecasts.variance # Annualize the forecast intermediate = np.sqrt(forecasts.variance.dropna() * 12) intermediate # The name of the column here is the date of the forecast. # Each row represents the forecast of volatility for the following days. # Transposing makes the forecast easier to plot final = intermediate.dropna().T final final.plot()
Python-Scripts/RiskStats.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] tags=["remove_cell"] # # Simulating Molecules using VQE # - # In this tutorial, we introduce the Variational Quantum Eigensolver (VQE), motivate its use, explain the necessary theory, and demonstrate its implementation in finding the ground state energy of molecules. # # ## Contents # 1. [Introduction](#introduction) # 2. [The Variational Method of Quantum Mechanics](#varmethod) # 1. [Mathematical Background](#backgroundmath) # 2. [Bounding the Ground State](#groundstate) # 3. [The Variational Quantum Eigensolver](#vqe) # 1. [Variational Forms](#varforms) # 2. [Simple Variational Forms](#simplevarform) # 3. [Parameter Optimization](#optimization) # 4. [Example with a Single Qubit Variational Form](#example) # 5. [Structure of Common Variational Forms](#commonvarforms) # 4. [VQE Implementation in Qiskit](#implementation) # 1. [Running VQE on a Statevector Simulator](#implementationstatevec) # 2. [Running VQE on a Noisy Simulator](#implementationnoisy) # 5. [Problems](#problems) # 6. [References](#references) # ## Introduction<a id='introduction'></a> # In many applications it is important to find the minimum eigenvalue of a matrix. For example, in chemistry, the minimum eigenvalue of a Hermitian matrix characterizing the molecule is the ground state energy of that system. In the future, the quantum phase estimation algorithm may be used to find the minimum eigenvalue. However, its implementation on useful problems requires circuit depths exceeding the limits of hardware available in the NISQ era. Thus, in 2014, Peruzzo *et al.* proposed VQE to estimate the ground state energy of a molecule using much shallower circuits [1]. # # Formally stated, given a Hermitian matrix $H$ with an unknown minimum eigenvalue $\lambda_{min}$, associated with the eigenstate $|\psi_{min}\rangle$, VQE provides an estimate $\lambda_{\theta}$ bounding $\lambda_{min}$: # # \begin{align*} # \lambda_{min} \le \lambda_{\theta} \equiv \langle \psi(\theta) |H|\psi(\theta) \rangle # \end{align*} # # where $|\psi(\theta)\rangle$ is the eigenstate associated with $\lambda_{\theta}$. By applying a parameterized circuit, represented by $U(\theta)$, to some arbitrary starting state $|\psi\rangle$, the algorithm obtains an estimate $U(\theta)|\psi\rangle \equiv |\psi(\theta)\rangle$ on $|\psi_{min}\rangle$. The estimate is iteratively optimized by a classical controller changing the parameter $\theta$ minimizing the expectation value of $\langle \psi(\theta) |H|\psi(\theta) \rangle$. # # # ## The Variational Method of Quantum Mechanics<a id='varmethod'></a> # ### Mathematical Background<a id='backgroundmath'></a> # # VQE is an application of the variational method of quantum mechanics. To better understand the variational method, some preliminary mathematical background is provided. An eigenvector, $|\psi_i\rangle$, of a matrix $A$ is invariant under transformation by $A$ up to a scalar multiplicative constant (the eigenvalue $\lambda_i$). That is, # # \begin{align*} # A |\psi_i\rangle = \lambda_i |\psi_i\rangle # \end{align*} # # Furthermore, a matrix $H$ is Hermitian when it is equal to its own conjugate transpose. # # \begin{align*} # H = H^{\dagger} # \end{align*} # # The spectral theorem states that the eigenvalues of a Hermitian matrix must be real. Thus, any eigenvalue of $H$ has the property that $\lambda_i = \lambda_i^*$. As any measurable quantity must be real, Hermitian matrices are suitable for describing the Hamiltonians of quantum systems. Moreover, $H$ may be expressed as # # \begin{align*} # H = \sum_{i = 1}^{N} \lambda_i |\psi_i\rangle \langle \psi_i | # \end{align*} # # where each $\lambda_i$ is the eigenvalue corresponding to the eigenvector $|\psi_i\rangle$. Furthermore, the expectation value of the observable $H$ on an arbitrary quantum state $|\psi\rangle$ is given by # # \begin{align} # \langle H \rangle_{\psi} &\equiv \langle \psi | H | \psi \rangle # \end{align} # # Substituting $H$ with its representation as a weighted sum of its eigenvectors, # # \begin{align} # \langle H \rangle_{\psi} = \langle \psi | H | \psi \rangle &= \langle \psi | \left(\sum_{i = 1}^{N} \lambda_i |\psi_i\rangle \langle \psi_i |\right) |\psi\rangle\\ # &= \sum_{i = 1}^{N} \lambda_i \langle \psi | \psi_i\rangle \langle \psi_i | \psi\rangle \\ # &= \sum_{i = 1}^{N} \lambda_i | \langle \psi_i | \psi\rangle |^2 # \end{align} # # # The last equation demonstrates that the expectation value of an observable on any state can be expressed as a linear combination using the eigenvalues associated with $H$ as the weights. Moreover, each of the weights in the linear combination is greater than or equal to 0, as $| \langle \psi_i | \psi\rangle |^2 \ge 0$ and so it is clear that # # \begin{align} # \lambda_{min} \le \langle H \rangle_{\psi} = \langle \psi | H | \psi \rangle = \sum_{i = 1}^{N} \lambda_i | \langle \psi_i | \psi\rangle |^2 # \end{align} # # The above equation is known as the **variational method** (in some texts it is also known as the variational principle) [2]. It is important to note that this implies that the expectation value of any wave function will always be at least the minimum eigenvalue associated with $H$. Moreover, the expectation value of the eigenstate $|\psi_{min}\rangle$ is given by $\langle \psi_{min}|H|\psi_{min}\rangle = \langle \psi_{min}|\lambda_{min}|\psi_{min}\rangle = \lambda_{min}$. Thus, as expected, $\langle H \rangle_{\psi_{min}}=\lambda_{min}$. # # ### Bounding the Ground State<a id='groundstate'></a> # When the Hamiltonian of a system is described by the Hermitian matrix $H$ the ground state energy of that system, $E_{gs}$, is the smallest eigenvalue associated with $H$. By arbitrarily selecting a wave function $|\psi \rangle$ (called an *ansatz*) as an initial guess approximating $|\psi_{min}\rangle$, calculating its expectation value, $\langle H \rangle_{\psi}$, and iteratively updating the wave function, arbitrarily tight bounds on the ground state energy of a Hamiltonian may be obtained. # # # # ## The Variational Quantum Eigensolver<a id='vqe'></a> # ### Variational Forms<a id='varforms'></a> # A systematic approach to varying the ansatz is required to implement the variational method on a quantum computer. VQE does so through the use of a parameterized circuit with a fixed form. Such a circuit is often called a *variational form*, and its action may be represented by the linear transformation $U(\theta)$. A variational form is applied to a starting state $|\psi\rangle$ (such as the vacuum state $|0\rangle$, or the Hartree Fock state) and generates an output state $U(\theta)|\psi\rangle\equiv |\psi(\theta)\rangle$. Iterative optimization over $|\psi(\theta)\rangle$ aims to yield an expectation value $\langle \psi(\theta)|H|\psi(\theta)\rangle \approx E_{gs} \equiv \lambda_{min}$. Ideally, $|\psi(\theta)\rangle$ will be close to $|\psi_{min}\rangle$ (where 'closeness' is characterized by either state fidelity, or Manhattan distance) although in practice, useful bounds on $E_{gs}$ can be obtained even if this is not the case. # # Moreover, a fixed variational form with a polynomial number of parameters can only generate transformations to a polynomially sized subspace of all the states in an exponentially sized Hilbert space. Consequently, various variational forms exist. Some, such as Ry and RyRz are heuristically designed, without consideration of the target domain. Others, such as UCCSD, utilize domain specific knowledge to generate close approximations based on the problem's structure. The structure of common variational forms is discussed in greater depth later in this document. # # ### Simple Variational Forms<a id='simplevarform'></a> # When constructing a variational form we must balance two opposing goals. Ideally, our $n$ qubit variational form would be able to generate any possible state $|\psi\rangle$ where $|\psi\rangle \in \mathbb{C}^N$ and $N=2^n$. However, we would like the variational form to use as few parameters as possible. Here, we aim to give intuition for the construction of variational forms satisfying our first goal, while disregarding the second goal for the sake of simplicity. # # Consider the case where $n=1$. The U3 gate takes three parameters, $\theta, \phi$ and $\lambda$, and represents the following transformation: # # $$ # \begin{align} # U3(\theta, \phi, \lambda) = \begin{pmatrix}\cos(\frac{\theta}{2}) & -e^{i\lambda}\sin(\frac{\theta}{2}) \\ e^{i\phi}\sin(\frac{\theta}{2}) & e^{i\lambda + i\phi}\cos(\frac{\theta}{2}) \end{pmatrix} # \end{align} # $$ # # Up to a global phase, any possible single qubit transformation may be implemented by appropriately setting these parameters. Consequently, for the single qubit case, a variational form capable of generating any possible state is given by the circuit: # # ![image1](./images/U3_var_form.png) # # # Moreover, this universal 'variational form' only has 3 parameters and thus can be efficiently optimized. It is worth emphasising that the ability to generate an arbitrary state ensures that during the optimization process, the variational form does not limit the set of attainable states over which the expectation value of $H$ can be taken. Ideally, this ensures that the minimum expectation value is limited only by the capabilities of the classical optimizer. # # A less trivial universal variational form may be derived for the 2 qubit case, where two body interactions, and thus entanglement, must be considered to achieve universality. Based on the work presented by *Shende et al.* [3] the following is an example of a universal parameterized 2 qubit circuit: # # ![image2](./images/two_qubit_var_form.png) # # Allow the transformation performed by the above circuit to be represented by $U(\theta)$. When optimized variationally, the expectation value of $H$ is minimized when $U(\theta)|\psi\rangle \equiv |\psi(\theta)\rangle \approx |\psi_{min}\rangle$. By formulation, $U(\theta)$ may produce a transformation to any possible state, and so this variational form may obtain an arbitrarily tight bound on two qubit ground state energies, only limited by the capabilities of the classical optimizer. # # ### Parameter Optimization<a id='optimization'></a> # Once an efficiently parameterized variational form has been selected, in accordance with the variational method, its parameters must be optimized to minimize the expectation value of the target Hamiltonian. The parameter optimization process has various challenges. For example, quantum hardware has various types of noise and so objective function evaluation (energy calculation) may not necessarily reflect the true objective function. Additionally, some optimizers perform a number of objective function evaluations dependent on cardinality of the parameter set. An appropriate optimizer should be selected by considering the requirements of an application. # # A popular optimization strategy is gradient decent where each parameter is updated in the direction yielding the largest local change in energy. Consequently, the number of evaluations performed depends on the number of optimization parameters present. This allows the algorithm to quickly find a local optimum in the search space. However, this optimization strategy often gets stuck at poor local optima, and is relatively expensive in terms of the number of circuit evaluations performed. While an intuitive optimization strategy, it is not recommended for use in VQE. # # An appropriate optimizer for optimizing a noisy objective function is the *Simultaneous Perturbation Stochastic Approximation* optimizer (SPSA). SPSA approximates the gradient of the objective function with only two measurements. It does so by concurrently perturbing all of the parameters in a random fashion, in contrast to gradient decent where each parameter is perturbed independently. When utilizing VQE in either a noisy simulator or on real hardware, SPSA is a recommended as the classical optimizer. # # When noise is not present in the cost function evaluation (such as when using VQE with a statevector simulator), a wide variety of classical optimizers may be useful. Two such optimizers supported by Qiskit Aqua are the *Sequential Least Squares Programming* optimizer (SLSQP) and the *Constrained Optimization by Linear Approximation* optimizer (COBYLA). It is worth noting that COBYLA only performs one objective function evaluation per optimization iteration (and thus the number of evaluations is independent of the parameter set's cardinality). Therefore, if the objective function is noise-free and minimizing the number of performed evaluations is desirable, it is recommended to try COBYLA. # # ### Example with a Single Qubit Variational Form<a id='example'></a> # # We will now use the simple single qubit variational form to solve a problem similar to ground state energy estimation. Specifically, we are given a random probability vector $\vec{x}$ and wish to determine a possible parameterization for our single qubit variational form such that it outputs a probability distribution that is close to $\vec{x}$ (where closeness is defined in terms of the Manhattan distance between the two probability vectors). # # We first create the random probability vector in python: import numpy as np np.random.seed(999999) target_distr = np.random.rand(2) # We now convert the random vector into a valid probability vector target_distr /= sum(target_distr) # We subsequently create a function that takes the parameters of our single U3 variational form as arguments and returns the corresponding quantum circuit: from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister def get_var_form(params): qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') qc = QuantumCircuit(qr, cr) qc.u3(params[0], params[1], params[2], qr[0]) qc.measure(qr, cr[0]) return qc # Now we specify the objective function which takes as input a list of the variational form's parameters, and returns the cost associated with those parameters: # + from qiskit import Aer, execute backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 def get_probability_distribution(counts): output_distr = [v / NUM_SHOTS for v in counts.values()] if len(output_distr) == 1: output_distr.append(0) return output_distr def objective_function(params): # Obtain a quantum circuit instance from the paramters qc = get_var_form(params) # Execute the quantum circuit to obtain the probability distribution associated with the current parameters result = execute(qc, backend, shots=NUM_SHOTS).result() # Obtain the counts for each measured state, and convert those counts into a probability vector output_distr = get_probability_distribution(result.get_counts(qc)) # Calculate the cost as the distance between the output distribution and the target distribution cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)]) return cost # - # Finally, we create an instance of the COBYLA optimizer, and run the algorithm. Note that the output varies from run to run. Moreover, while close, the obtained distribution might not be exactly the same as the target distribution, however, increasing the number of shots taken will increase the accuracy of the output. # + from qiskit.aqua.components.optimizers import COBYLA # Initialize the COBYLA optimizer optimizer = COBYLA(maxiter=500, tol=0.0001) # Create the initial parameters (noting that our single qubit variational form has 3 parameters) params = np.random.rand(3) ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc) output_distr = get_probability_distribution(counts) print("Target Distribution:", target_distr) print("Obtained Distribution:", output_distr) print("Output Error (Manhattan Distance):", ret[1]) print("Parameters Found:", ret[0]) # - # ### Structure of Common Variational Forms<a id='commonvarforms'></a> # As already discussed, it is not possible for a polynomially parameterized variational form to generate a transformation to any state. Variational forms can be grouped into two categories, depending on how they deal with this limitation. The first category of variational forms use domain or application specific knowledge to limit the set of possible output states. The second approach uses a heuristic circuit without prior domain or application specific knowledge. # # The first category of variational forms exploit characteristics of the problem domain to restrict the set of transformations that may be required. For example, when calculating the ground state energy of a molecule, the number of particles in the system is known *a priori*. Therefore, if a starting state with the correct number of particles is used, by limiting the variational form to only producing particle preserving transformations, the number of parameters required to span the new transformation subspace can be greatly reduced. Indeed, by utilizing similar information from Coupled-Cluster theory, the variational form UCCSD can obtain very accurate results for molecular ground state energy estimation when starting from the Hartree Fock state. Another example illustrating the exploitation of domain-specific knowledge follows from considering the set of circuits realizable on real quantum hardware. Extant quantum computers, such as those based on super conducting qubits, have limited qubit connectivity. That is, it is not possible to implement 2-qubit gates on arbitrary qubit pairs (without inserting swap gates). Thus, variational forms have been constructed for specific quantum computer architectures where the circuits are specifically tuned to maximally exploit the natively available connectivity and gates of a given quantum device. Such a variational form was used in 2017 to successfully implement VQE for the estimation of the ground state energies of molecules as large as BeH$_2$ on an IBM quantum computer [4]. # # In the second approach, gates are layered such that good approximations on a wide range of states may be obtained. Qiskit Aqua supports three such variational forms: RyRz, Ry and SwapRz (we will only discuss the first two). All of these variational forms accept multiple user-specified configurations. Three essential configurations are the number of qubits in the system, the depth setting, and the entanglement setting. A single layer of a variational form specifies a certain pattern of single qubit rotations and CX gates. The depth setting says how many times the variational form should repeat this pattern. By increasing the depth setting, at the cost of increasing the number of parameters that must be optimized, the set of states the variational form can generate increases. Finally, the entanglement setting selects the configuration, and implicitly the number, of CX gates. For example, when the entanglement setting is linear, CX gates are applied to adjacent qubit pairs in order (and thus $n-1$ CX gates are added per layer). When the entanglement setting is full, a CX gate is applied to each qubit pair in each layer. The circuits for RyRz corresponding to `entanglement="full"` and `entanglement="linear"` can be seen by executing the following code snippet: from qiskit.circuit.library import EfficientSU2 entanglements = ["linear", "full"] for entanglement in entanglements: form = EfficientSU2(num_qubits=4, entanglement=entanglement) if entanglement == "linear": print("=============Linear Entanglement:=============") else: print("=============Full Entanglement:=============") # We initialize all parameters to 0 for this demonstration display(form.draw(fold=100)) print() # Assume the depth setting is set to $d$. Then, RyRz has $n\times (d+1)\times 2$ parameters, Ry with linear entanglement has $2n\times(d + \frac{1}{2})$ parameters, and Ry with full entanglement has $d\times n\times \frac{(n + 1)}{2} + n$ parameters. # ## VQE Implementation in Qiskit<a id='implementation'></a> # This section illustrates an implementation of VQE using the programmatic approach. Qiskit Aqua also enables a declarative implementation, however, it reveals less information about the underlying algorithm. This code, specifically the preparation of qubit operators, is based on the code found in the Qiskit Tutorials repository (and as of July 2019, may be found at: https://github.com/Qiskit/qiskit-tutorials ). # # The following libraries must first be imported. # from qiskit.aqua.algorithms import VQE, NumPyEigensolver import matplotlib.pyplot as plt import numpy as np from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.circuit.library import EfficientSU2 from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP from qiskit.aqua.operators import Z2Symmetries from qiskit import IBMQ, BasicAer, Aer from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator from qiskit import IBMQ from qiskit.aqua import QuantumInstance from qiskit.ignis.mitigation.measurement import CompleteMeasFitter from qiskit.providers.aer.noise import NoiseModel # ### Running VQE on a Statevector Simulator<a id='implementationstatevec'></a> # We demonstrate the calculation of the ground state energy for LiH at various interatomic distances. A driver for the molecule must be created at each such distance. Note that in this experiment, to reduce the number of qubits used, we freeze the core and remove two unoccupied orbitals. First, we define a function that takes an interatomic distance and returns the appropriate qubit operator, $H$, as well as some other information about the operator. def get_qubit_op(dist): driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() freeze_list = [0] remove_list = [-3, -2] repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) shift = energy_shift + repulsion_energy return qubitOp, num_particles, num_spin_orbitals, shift # First, the exact ground state energy is calculated using the qubit operator and a classical exact eigensolver. Subsequently, the initial state $|\psi\rangle$ is created, which the VQE instance uses to produce the final ansatz $\min_{\theta}(|\psi(\theta)\rangle)$. The exact result and the VQE result at each interatomic distance is stored. Observe that the result given by `vqe.run(backend)['energy'] + shift` is equivalent the quantity $\min_{\theta}\left(\langle \psi(\theta)|H|\psi(\theta)\rangle\right)$, where the minimum is not necessarily the global minimum. # # When initializing the VQE instance with `VQE(qubitOp, var_form, optimizer, 'matrix')` the expectation value of $H$ on $|\psi(\theta)\rangle$ is directly calculated through matrix multiplication. However, when using an actual quantum device, or a true simulator such as the `qasm_simulator` with `VQE(qubitOp, var_form, optimizer, 'paulis')` the calculation of the expectation value is more complicated. A Hamiltonian may be represented as a sum of a Pauli strings, with each Pauli term acting on a qubit as specified by the mapping being used. Each Pauli string has a corresponding circuit appended to the circuit corresponding to $|\psi(\theta)\rangle$. Subsequently, each of these circuits is executed, and all of the results are used to determine the expectation value of $H$ on $|\psi(\theta)\rangle$. In the following example, we initialize the VQE instance with `matrix` mode, and so the expectation value is directly calculated through matrix multiplication. # # Note that the following code snippet may take a few minutes to run to completion. # + tags=["output_scroll"] backend = BasicAer.get_backend("statevector_simulator") distances = np.arange(0.5, 4.0, 0.1) exact_energies = [] vqe_energies = [] optimizer = SLSQP(maxiter=5) for dist in distances: qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist) result = NumPyEigensolver(qubitOp).run() exact_energies.append(np.real(result.eigenvalues) + shift) initial_state = HartreeFock( num_spin_orbitals, num_particles, qubit_mapping='parity' ) var_form = UCCSD( num_orbitals=num_spin_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping='parity' ) vqe = VQE(qubitOp, var_form, optimizer) vqe_result = np.real(vqe.run(backend)['eigenvalue'] + shift) vqe_energies.append(vqe_result) print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", vqe_result, "Exact Energy:", exact_energies[-1]) print("All energies have been calculated") # - plt.plot(distances, exact_energies, label="Exact Energy") plt.plot(distances, vqe_energies, label="VQE Energy") plt.xlabel('Atomic distance (Angstrom)') plt.ylabel('Energy') plt.legend() plt.show() # Note that the VQE results are very close to the exact results, and so the exact energy curve is hidden by the VQE curve. # ### Running VQE on a Noisy Simulator<a id='implementationnoisy'></a> # # Here, we calculate the ground state energy for H$_2$ using a noisy simulator and error mitigation. # # First, we prepare the qubit operator representing the molecule's Hamiltonian: driver = PySCFDriver(atom='H .0 .0 -0.3625; H .0 .0 0.3625', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta qubitOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals).mapping(map_type='parity') qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) # Now, we load a device coupling map and noise model from the IBMQ provider and create a quantum instance, enabling error mitigation: # + tags=["uses-hardware"] IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend("qasm_simulator") device = provider.get_backend("ibmq_vigo") coupling_map = device.configuration().coupling_map noise_model = NoiseModel.from_backend(device.properties()) quantum_instance = QuantumInstance(backend=backend, shots=1000, noise_model=noise_model, coupling_map=coupling_map, measurement_error_mitigation_cls=CompleteMeasFitter, cals_matrix_refresh_period=30) # - # Finally, we must configure the optimizer, the variational form, and the VQE instance. As the effects of noise increase as the number of two qubit gates circuit depth increases, we use a heuristic variational form (RYRZ) rather than UCCSD as RYRZ has a much shallower circuit than UCCSD and uses substantially fewer two qubit gates. # # The following code may take a few minutes to run to completion. # + tags=["uses-hardware"] exact_solution = NumPyEigensolver(qubitOp).run() print("Exact Result:", np.real(exact_solution.eigenvalues)) optimizer = SPSA(max_trials=100) var_form = EfficientSU2(qubitOp.num_qubits, entanglement="linear") vqe = VQE(qubitOp, var_form, optimizer=optimizer) ret = vqe.run(quantum_instance) vqe_result = np.real(ret['eigenvalue']) print("VQE Result:", vqe_result) # - # When noise mitigation is enabled, even though the result does not fall within chemical accuracy (defined as being within 0.0016 Hartree of the exact result), it is fairly close to the exact solution. # ## Problems<a id='problems'></a> # 1. You are given a Hamiltonian $H$ with the promise that its ground state is close to a maximally entangled $n$ qubit state. Explain which variational form (or forms) is likely to efficiently and accurately learn the ground state energy of $H$. You may also answer by creating your own variational form, and explaining why it is appropriate for use with this Hamiltonian. # 2. Calculate the number of circuit evaluations performed per optimization iteration, when using the COBYLA optimizer, the `qasm_simulator` with 1000 shots, and a Hamiltonian with 60 Pauli strings. # 3. Use VQE to estimate the ground state energy of BeH$_2$ with an interatomic distance of $1.3$Å. You may re-use the function `get_qubit_op(dist)` by replacing `atom="Li .0 .0 .0; H .0 .0 " + str(dist)` with `atom="Be .0 .0 .0; H .0 .0 -" + str(dist) + "; H .0 .0 " + str(dist)` and invoking the function with `get_qubit_op(1.3)`. Note that removing the unoccupied orbitals does not preserve chemical precision for this molecule. However, to get the number of qubits required down to 6 (and thereby allowing efficient simulation on most laptops), the loss of precision is acceptable. While beyond the scope of this exercise, the interested reader may use qubit tapering operations to reduce the number of required qubits to 7, without losing any chemical precision. # ## References<a id='references'></a> # 1. Peruzzo, Alberto, et al. "A variational eigenvalue solver on a photonic quantum processor." *Nature communications* 5 (2014): 4213. # 2. Griffiths, <NAME>., and <NAME>. Introduction to quantum mechanics. *Cambridge University Press*, 2018. # 3. Shende, <NAME>., <NAME>, and <NAME>. "Minimal universal two-qubit cnot-based circuits." arXiv preprint quant-ph/0308033 (2003). # 4. Kandala, Abhinav, et al. "Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets." Nature 549.7671 (2017): 242. import qiskit qiskit.__qiskit_version__
content/ch-applications/vqe-molecules.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Семинар по numpy # # В этом семинаре мы познакомимся с первой библиотекой, которая понадобится нам в курсе - библиотекой numpy. Это библиотека для работы с матрицами, и она может быть также полезна для матричных вычислений в других дисциплинах. Но сначала познакомимся с интерфейсом jupyter notebook. Это инструмент, позволяющий писать код в интерактивном режиме, рисовать графики и оформлять материалы. # # ## Очень краткий обзор интерфейса jupyter notebook # Jupyter notebook состоит из ячеек. # В ячейку можно записывать код, выполнять, а потом использовать созданные переменные / определенные функции и т. д. в других ячейках: x = [1, 2, 3] print(x) x = 9 y = 3 # Выполнить ячейку: shift + enter, показать аргументы функции: shift + tab. Есть много других горячих клавиш, см. Help -> Keyboard Shortcuts (вверху интерфейса). Там же есть Help -> User Interface Tool! # # Обратите внимание на кнопки + (добавить ячейку), ножницы (удалить ячейку), стрелки, меняющие ячейки местами, кнопку остановить выполнение. # # Ноутбук сохраняется автоматически. Чтобы скачать: File -> Download as -> ipynb. # # Этот текст написан в ячейке типа Markdown, она позволяет красиво оформлять код. Переключение типа ячейки справа от кнопки стоп (черный квадрат). Ячейки с кодом имеют тип Code. # ## Создание массивов в numpy # # Numpy - библиотека для работы с матрицами. Импортируем библиотеку: import numpy as np # Предположим, что мы провели опрос, в котором было четыре вопроса, на каждый можно ответить Да, Нет, Воздержался. В итоге получим таблицу размера 4 на 3. Создадим такую таблицу в numpy: l = [[30, 2, 0], [3, 27, 1], [28, 1, 1], [6, 17, 5]] ar = np.array(l) ar # выводится созданное в последней строке, если в ней нет присваивания (знак =) # Можно создавать массивы из нулей (np.zeros) или из единиц (np.ones): import numpy as np A = np.ones((7, 9)) # Также часто используется создание векторов из натуральных чисел: vec = np.arange(15) # И случайно сгенерированные массивы: r = np.random.rand(3, 4) r # ### Размерности массивов # Размерности: ar.shape A.shape vec.shape # В numpy нулевая размерность отвечает за строки, первая - за столбцы. В нашей матрице ar 4 строки и 3 столбца. Вообще в numpy можно создавать массивы любых размерностей точно таким же образом, как мы сделали выше - numpy не различает векторы, матрицы и тензоры, все они называются массивами. Например, vec имеет длину 15 только по одной размерности, поэтому его shape равен (15,). Shape - это обычный кортеж языка python. # Можно вытянуть все ответы в одну строку: ar.ravel() # Можно наоборот: преобразовать вектор в матрицу: vec.reshape(3, 5) # Обратите внимание, что числа записываются по строкам. vec.reshape(3, 5).shape # По одной из осей можно указывать -1, тогда библиотека сама посчитает число элементов по этой размерности: vec.reshape(3, -1) # Аналогичным образом можно дублироать функционал функции ravel: vec.reshape(-1) # ### Операции с массивами # Можно выделить три группы операций с массивами в numpy: # * поэлементные # * матричные # * агрегирующие # Поэлементные выполняются между массивами одной формы (shape), хотя ниже мы обсудим некое обощение правила одной формы. vec + vec A * 10 x = np.array([1, 2, 3]) y = np.array([-1, 1, -1]) x * y # Обратите внимание, что * - это поэлементное умножение, а не матричное! np.exp(x) # Матричные операции - операции из линейной алгебры. Например, матричное произведение: A = np.random.rand(7, 8) B = np.random.rand(8, 3) A.dot(B) # Можно писать и так: np.dot(A, B) # И так: A @ B # Проверим форму: A.dot(B).shape # Обращение матрицы: np.linalg.inv(np.random.rand(3, 3)) # Модуль np.linalg содержит много полезных матричных функций, их можно посмотреть в документации модуля. # Агрегирующие операции агрерируют информацию в троках, столбцах, во всем массиве и т. д. Самые популярные такие операции - суммирование np.sum, усреднение np.mean, медиана np.median, максимум np.max и минимум np.min. # Число полученных ответов на вопросы (всего): np.sum(ar) # Пробуем выяснить число респондентов. Для этого просуммируем матрицу по строкам (это делается с помощью указания axis=1): np.sum(ar, axis = 1) np.sum(ar, axis = 1).shape # По столбцам: axis=0, по строкам: axis=1. # # В результате суммирования получился вектор (размерность на 1 меньше, чем у исходной матрицы). Можно указать keepdims=True, чтобы сохранть размерности: np.sum(ar, axis = 1, keepdims=True).shape # Задание для студентов: посчитать сумму по строкам, используя матричное произведение. # + # student's code here # - # Считаем число ответов "да", "нет", "воздержался" двумя способами: np.sum(ar, axis=0) ones = np.ones(4) np.dot(ones, ar) # ### Индексация # Для индексации ставим [ ] и через запятую перечисляем действия с осями. В матрице 0 - по вертикали, 1 - по горизонтали ar[2, 1] # выбрать 1 элемент ar # вывели для проверки ar[:, 2] # выделить столбец ar[:, -1] # выделить последний столбец ar[1] # выделить строку ar[:, ::2] # выделить все столбы с четными номерами # Можно делать логическую индексацию, чтобы выбирались только те элементы, для которых стоит True. Выберем ответы на вопросы с номерами, кратными 2: ar[np.arange(ar.shape[0])%2==0] # ### Добавление оси # # Для удобного перехода между размерностями используют добавление оси. Вектор можно сделать матрицей с размером 1 по одной из размерностей. ones[:, np.newaxis] ones[:, np.newaxis].shape # вместо вектора с формой (4,) стала матрциа с формой (4, 1) ones[np.newaxis, :] # вместо вектора с формой (4,) стала матрциа с формой (1, 4) ones[np.newaxis, :].shape # ### Добавление оси в поэлементных операциях # В поэлементных операциях можно использовать не только массивы в одинаковым в точности размером. В общем виде условие такое: по каждой размерности либо размер совпадает, либо в одном из массивов размер 1. Например, матрица размера (4, 3) и вектор размера (4, 1). В этом случае при выполнении операции столбец будет как бы "дублироваться" для каждого столбца в первой матрице. Воспользуемся этим, чтобы найти долю каждого ответа на все вопросы: sums = ar.sum(axis=1) # всего ответов на каждый вопрос sums.shape sums[:, np.newaxis].shape # добавили ось ar / sums[:, np.newaxis] # поделили число каждого варианта на общее число ответов на вопрос # ### Объединение массивов # Добавляем новый вопрос в таблицу: row = np.array([5, 12, 15]) row = row[np.newaxis, :] # конкретно тут можно без увеличения размерности # но в других случаях может быть ошибка, лучше добавлять ar = np.vstack((ar, row)) # Добавляем новый столбец в таблицу - максимальное число ответов: mx = np.max(ar, 1) mx mx.shape mx = mx[:, np.newaxis] ar = np.hstack ((ar, mx)) ar # Удаление строки (аналогично можно удалять столбец): np.delete(ar, np.arange(3, 5), axis=0) # ### Задания для студентов # Выделите строки, у которых ответов "нет" больше, чем ответов "да": # + # student's code here import numpy as np arr = np.array([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 1], [1, 1, 1, 1]]) ar = np.array(arr, dtype=bool) a = np.sum(ar[0, :]) if a > 2: print(ar[0, :]) b = np.sum(ar[1, :]) if b > 2: print(ar[1, :]) c = np.sum(ar[2, :]) if c > 2: print(ar[2, :]) d = np.sum(ar[3, :]) if d > 2: print(ar[3, :]) # - # Вывести квадраты первых десяти натуральных чисел: # student's code here c = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) c2 = c*c print(c2) # Перемешать числа натуральные числа от 1 до 10 (воспользуйтесь np.random.permutation): # помощь по функции # ?np.random.permutation # student's code here d = np.random.permutation(10) print(d) # Составить таблицу умножения от 1 до 10: # student's code here r = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) col = np.copy(r) col = col.reshape(10, 1) table = r * col print(table)
Homework Numpy 1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: pygmt06 # language: python # name: pygmt06 # --- # # Automatically plot Antarctic cross-section/profiles # This notebook contains a simple script to plot cross-sections of Antarctica earth layers and data profiles. Choose your cross-section location as either a straight lines between 2 points, or to follow the path of a shapefile. Choose which earth layers to plot, such as Bedmachine or Bedmap. Also, include dataset to plot profiles of, such as ice velocity, gravity, or magnetics. # # Feel free to reach out with any questions or suggestions. # # *<NAME>* # *Antarctic Research Centre, Victoria University of Wellington, NZ* # *<EMAIL>* # ### Datasets # # The following datasets are provided in /sample_data: # * BedMachine bathymetry (Morlighem et al., 2020. https://doi.org/10.1038/s41561-019-0510-8) # - https://nsidc.org/data/NSIDC-0756/versions/2 # * MEaSUREs grounding line and coastline (Rignot et al., 2013. https://doi.org/10.1126/science.1235798) # - https://nsidc.org/data/nsidc-0709 # * Antarctic gravity grids, from <NAME>, "Preliminary compilation of Antarctic gravity and gravity gradient data", 2020 # - https://ftp.space.dtu.dk/pub/RF/4D-ANTARCTICA/ # - Free air anomalies: ant4d_fa.tif # - Bouguer anomalies: ant4d_bafa.tif # # These datasets need to be download and added to the /sample_data folder: # * MODIS-MOA satellite imagery (Scambos et al., 2007. https://doi.org/10.1016/j.rse.2006.12.020) # - https://nsidc.org/data/NSIDC-0593 # - get geotiff "moa750_2009_hp1_v02.0.tif" # * [MEaSUREs Phase-Based Antarctica Ice Velocity Map, v1](https://nsidc.org/data/NSIDC-0754/versions/1) # - turned into velocity magnitude by [Venturelli et al. 2020]( https://doi.org/10.1029/2020GL088476) #import necessary packages import pygmt import pandas as pd import numpy as np import geopandas as gpd # ### Define cross-section/profile location # 2 options: # * input 2 sets of x/y coordinates (in EPSG 3031) marking the beginning and end of the line. # * set path to a shapefile which defines the line # # # Note: shapefiles can be made quickly in QGIS. To increase the sampling resolution, use the QGIS tools "Points along geometry" and "Points to path" to increase the number of points on your shapefile # + # choose one of the below methods #### # METHOD = "points" METHOD = "shapefile" #### # Example profiles to plot # siple coast # a=(-590000,-1070000) # b=(-100000,-545000) # discovery deep # a=(307320,-1140665) # b=(274470,-1156657) # West to East Antarcitca # a=(-1689974,-874525) # b=(2174939,1721844) # Line from <NAME> to ice front through Discover Deep gdf=gpd.read_file('sample_data\Disco_deep_transect_1k.shp') # Line from ice shelf calving front to the grounding zone through Roosevelt Island # gdf=gpd.read_file('sample_data\Roosevelt_Island_10k.shp') # N-S line along center of Ross Ice Shelf, as defined by the Mid-Shelf High basement feature (Tankersley et al. 2022, GRL) # gdf=gpd.read_file('C:/Users\matthewt\Documents\Python_Scripts\shapefiles\EANT_WANT_divide_10k.shp') # - # ### Choose input datasets and colors # + tags=[] # earth-layer data to plot in cross-section earth_profilelist=( 'sample_data/BedMachine_surface_wgs_10k.nc', 'sample_data/BedMachine_icebase_wgs_10k.nc', 'sample_data/BedMachine_bed_wgs_10k.nc', # 'C:/Users/matthewt/Documents/BedMachine/BedMachine_surface_wgs.nc', # 'C:/Users/matthewt/Documents/BedMachine/BedMachine_icebase_wgs.nc', # 'C:/Users/matthewt/Documents/BedMachine/BedMachine_bed_wgs.nc', # 'C:/Users/matthewt/Documents/Python_Scripts/GRL_2021_Figures/rosetta_lindeque_basement_g80kfilt.nc', ) x_section_colorlist=( 'lightskyblue', 'darkblue', 'lightbrown', 'chocolate', 'darkbrown', ) # data to plot as a seperate profile data_profiledict={ 'sample_data/ant4d_fa.tif' : ('FA grav', 'blue'), 'sample_data/ant4d_bafa.tif' : ('Boug grav', 'black'), 'sample_data/antarctic_ice_vel_phase_map_v01-vmag.nc' : ('Ice vel', 'purple'), # 'C:/Users/matthewt/Documents/Python_Scripts/GRL_2021_Figures/RIS_Grav_5k.nc' : ('Grav', 'black'), # 'C:/Users/matthewt/Documents/Python_Scripts/GRL_2021_Figures/RIS_Mag_5k.nc' : ('Mag', 'black'), } # background grid and colorscale for map plot_grid='sample_data/moa750_2009_hp1_v1.1.tif' plot_cmap='gray' # buffer as percentage added to profile location on map; i.e. .4 adds 40% of profile extent on map. buffer_perc=.2 # - # ### Code for sampling the data # + def create_profile(a, b): # function to create points every 1000m between points 'a' and 'b' df = pd.DataFrame(data=np.linspace(start=a, stop=b, num=1000), columns=["x", "y"]) return df def sample_line(points, data): # function to sample data at every point along line points[data] = (pygmt.grdtrack(points=points, grid=data, newcolname=str(data)))[data] return points if METHOD == 'points': points = create_profile(a, b) elif METHOD == 'shapefile': shape=pd.DataFrame() shape['coords']=gdf.geometry[0].coords[:] points=shape.coords.apply(pd.Series, index=['x','y']) else: print("please choose a valid method, either 'points', or 'shapefile'") # distance along line points['Distance'] = np.sqrt( (points.x-points.x.iloc[0])**2 + (points.y-points.y.iloc[0])**2 ) # sample cross-section layers from grids for i in earth_profilelist: earth_profiles=sample_line(points, i) # use this to fill NaN's in layers with the values from layer above for i in range(len(earth_profilelist))[1:]: #fill NaN's in lower layer with upper layer earth_profiles[earth_profilelist[i]] = np.where(earth_profiles[earth_profilelist[i]].isnull(), earth_profiles[earth_profilelist[i-1]], earth_profiles[earth_profilelist[i]]) # reset points dataframe before sampling data_profiledict(remove sampled columns) points=points[['x','y','Distance']].copy() # if grids in Data profile dict, sample them try: for key in data_profiledict: data_profiles=sample_line(points, key) except: print('no data profiles to plot') # use this to shorten line on either end # earth_profiles=earth_profiles[earth_profiles.Distance>20000] # data_profiles=data_profiles[data_profiles.Distance>20000] # # reset distance # earth_profiles['Distance'] = np.sqrt( (earth_profiles.x-earth_profiles.x.iloc[0])**2 + (earth_profiles.y-earth_profiles.y.iloc[0])**2 ) # data_profiles['Distance'] = np.sqrt( (data_profiles.x-data_profiles.x.iloc[0])**2 + (data_profiles.y-data_profiles.y.iloc[0])**2 ) # - # ### Plot the results # + figheight=90 # in mm # Automatic data extent + buffer as % of line length buffer=earth_profiles.Distance.max()*buffer_perc xl= earth_profiles.x.min()-buffer yl= earth_profiles.y.min()-buffer xh= earth_profiles.x.max()+buffer yh= earth_profiles.y.max()+buffer # Set figure parameters figwidth=figheight*(xh-xl)/(yh-yl) fig_ratio = (yh - yl) / (figheight/1000) fig_reg = str(xl) + '/' + str(xh) + '/' + str(yl) + '/' + str(yh) #W/E/S/N fig_proj = "x1:" + str(fig_ratio) fig_proj_ll = "s0/-90/-71/1:" + str(fig_ratio) # Initialize figure fig = pygmt.Figure() """ PLOT MAP """ fig.coast(region=fig_reg, projection=fig_proj_ll, land = 'grey', water = 'grey', frame = ["nwse", "xf100000", "yf100000", "g0"],verbose='e') fig.grdimage(projection = fig_proj, grid=plot_grid, cmap=plot_cmap) # plot groundingline and coastlines fig.plot(data=gpd.read_file('sample_data/GroundingLine_Antarctica_v02.shp'), pen = '1.2p,black', verbose='e') fig.plot(data=gpd.read_file('sample_data/Coastline_Antarctica_v02.shp'), pen='1.2p,black', verbose='e') # Plot graticules overtop, at 4d latitude and 30d longitude with pygmt.config(MAP_ANNOT_OFFSET_PRIMARY = '-2p', MAP_FRAME_TYPE = 'inside', MAP_ANNOT_OBLIQUE = 0, FONT_ANNOT_PRIMARY = '6p,black,-=2p,white', MAP_GRID_PEN_PRIMARY = 'grey', MAP_TICK_LENGTH_PRIMARY = '-10p', MAP_TICK_PEN_PRIMARY = 'thinnest,grey', FORMAT_GEO_MAP = 'dddF', MAP_POLAR_CAP = '90/90', ): fig.basemap(projection = fig_proj_ll, region = fig_reg, frame = ["NSWE", "xa30g15", "ya4g2"], verbose='e') with pygmt.config(FONT_ANNOT_PRIMARY = '6p,black'): fig.basemap(projection = fig_proj_ll, region = fig_reg, frame = ["NSWE", "xa30", "ya4"], verbose='e') # plot profile location, and endpoints on map fig.plot(projection=fig_proj, region=fig_reg, x=earth_profiles.x, y=earth_profiles.y, pen='2p,red') fig.text(x = earth_profiles.loc[earth_profiles.Distance.idxmin()].x, y = earth_profiles.loc[earth_profiles.Distance.idxmin()].y, text = "A", fill = 'white', font = '12p,Helvetica,black', justify="CM", clearance = '+tO') fig.text(x = earth_profiles.loc[earth_profiles.Distance.idxmax()].x, y = earth_profiles.loc[earth_profiles.Distance.idxmax()].y, text = "B", fill = 'white', font = '12p,Helvetica,black', justify='CM', clearance = '+tO') # shift figure to the right to make space for x-section and profiles fig.shift_origin(xshift=(figwidth/10)+1) """ PLOT CROSS-SECTION AND PROFILES """ # add space above and below top and bottom x-section layers y_buffer=(earth_profiles[earth_profilelist[0]].max()-earth_profiles[earth_profilelist[-1]].min())*.1 # set region for x-section region_layers=[earth_profiles.Distance.min(), earth_profiles.Distance.max(), earth_profiles[earth_profilelist[-1]].min()-y_buffer, earth_profiles[earth_profilelist[0]].max()+y_buffer] # if data for profiles is set, set region and plot them, if not, make region for x-section fill space if data_profiledict: try: for key, value in data_profiledict.items(): region_data=[data_profiles.Distance.min(), data_profiles.Distance.max(), data_profiles[key].min(), data_profiles[key].max()] fig.plot(region=region_data, projection="X9c/2.5c", frame=['nSew','ag'], x=data_profiles.Distance, y=data_profiles[key], pen='2p,'+str(value[1]), label=value[0]) fig.legend(position="JBR+jBL+o0c", box=True) fig.shift_origin(yshift="h+.5c") fig.basemap(region=region_layers, projection="X9c/6c", frame=True) except: print('error plotting data profiles') else: print('No data profiles to plot') fig.basemap(region=region_layers, projection="X9c/9c", frame=True) # plot x-section colored layers for i in list(range(len(earth_profilelist)))[1:]: fig.plot(x=earth_profiles.Distance, y=earth_profiles[earth_profilelist[i]], close='+yb', color=x_section_colorlist[i], frame=['nSew','a'],) # plot lines between layers for i in earth_profilelist: fig.plot(x=earth_profiles.Distance, y=earth_profiles[i], pen='1p,black') # plot 'A', 'B' locations fig.text(x=region_layers[0], y=region_layers[3], text='A', font='20p,Helvetica,black', justify='CM', fill='white', no_clip=True) fig.text(x=region_layers[1], y=region_layers[3], text='B', font='20p,Helvetica,black', justify='CM', fill='white', no_clip=True) fig.show() # - # ## Save figure out='cover_fig.png' fig.savefig(out, dpi=300)
auto_xsection.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from sdgym import load_dataset import numpy as np import pandas as pd import matplotlib.pyplot as plt import networkx as nx from synthsonic.models.kde_utils import kde_smooth_peaks_1dim, kde_smooth_peaks from sklearn.model_selection import train_test_split import xgboost as xgb # %matplotlib inline data = load_dataset('alarm') # + #data, categorical_columns, ordinal_columns = load_dataset('alarm') # - data data['tables'] data import pgmpy from pgmpy.models import BayesianModel from pgmpy.estimators import TreeSearch from pgmpy.estimators import HillClimbSearch, BicScore, ExhaustiveSearch df = pd.DataFrame(data) df.columns = [str(i) for i in df.columns] # + # learn graph structure est = TreeSearch(df, root_node=df.columns[0]) dag = est.estimate(estimator_type="tan", class_node='1') # - # + # alternative graph structure est2 = TreeSearch(df, root_node=df.columns[0]) dag2 = est2.estimate(estimator_type="chow-liu") # - est = HillClimbSearch(df) best_model = est.estimate() # start_dag=dag) nx.draw(best_model, with_labels=True, arrowsize=30, node_size=800, alpha=0.3, font_weight='bold') plt.show() edges = best_model.edges() edges # + from pgmpy.estimators import BayesianEstimator # there are many choices of parametrization, here is one example model = BayesianModel(best_model.edges()) model.fit(df, estimator=BayesianEstimator, prior_type='dirichlet', pseudo_counts=0.1) # - print(model.get_cpds('2')) # + # set up train-test sample. # the test sample is used to calibrate the output of the classifier # + X1_train, X1_test, y1_train, y1_test = train_test_split(data, np.ones(data.shape[0]), test_size=0.35, random_state=0) # - X1_train.shape from sklearn.neural_network import MLPClassifier import xgboost as xgb from sklearn.svm import SVC clf=MLPClassifier(random_state=0, max_iter=1000, early_stopping=True) clf = xgb.XGBClassifier( n_estimators=250, reg_lambda=1, gamma=0, max_depth=9 ) import inspect argspecs = inspect.getfullargspec(clf.fit) support_weight = 'sample_weight' in argspecs.args n_one = len(X1_train) n_zero = n_one # + from pgmpy.sampling import BayesianModelSampling # sample data from BN inference = BayesianModelSampling(model) df_data = inference.forward_sample(size=n_zero, return_type='dataframe', seed=0) df_data.columns = [int(c) for c in df_data.columns] X0_train = df_data[sorted(df_data.columns)].values # - # + zeros = np.zeros(n_zero) ones = np.ones(n_one) yy = np.concatenate([zeros, ones], axis = 0) XX = np.concatenate([X0_train, X1_train], axis = 0) # - clf = clf.fit(XX, yy) p0 = clf.predict_proba(X0_train)[:, 1] p2 = clf.predict_proba(X1_train)[:, 1] nbins = 100 plt.figure(figsize=(12,7)) plt.hist(p0, bins=100, range=(0,1), alpha=0.5, log=True, density=True) plt.hist(p2, bins=100, range=(0,1), alpha=0.5, log=True, density=True) # + # calibrate the probabilities, using the test sample and a new null sample # + df_data = inference.forward_sample(size=100000, return_type='dataframe', seed=10) df_data.columns = [int(c) for c in df_data.columns] X = df_data[sorted(df_data.columns)].values # - p0 = clf.predict_proba(X)[:, 1] p2 = clf.predict_proba(X1_test)[:, 1] nbins = 100 plt.figure(figsize=(12,7)) plt.hist(p0, bins=100, range=(0,1), alpha=0.5, log=True, density=True) plt.hist(p2, bins=100, range=(0,1), alpha=0.5, log=True, density=True) 0.5 / np.power(3500, 1/3.) # + nbins = 100 binning = np.linspace(0, 1, nbins+1) hist_p0, bin_edges = np.histogram(p0, binning) hist_p1, bin_edges = np.histogram(p2, binning) hist_p0 hist_p1 def poisson_uncertainty(n): sigman = np.sqrt(n) # correct poisson counts of zero. sigman[sigman == 0] = 1. return sigman def fraction_and_uncertainty(a, b, sigma_a, sigma_b): frac_a = a / (a + b) frac_b = b / (a + b) sigma_fa2 = np.power(frac_b * sigma_a, 2) / np.power(a + b, 2) + np.power(frac_a * sigma_b, 2) / np.power(a + b, 2) return frac_a, np.sqrt(sigma_fa2) rest_p0 = np.sum(hist_p0) - hist_p0 rest_p1 = np.sum(hist_p1) - hist_p1 sigma_bin0 = poisson_uncertainty(hist_p0) sigma_rest0 = poisson_uncertainty(rest_p0) sigma_bin1 = poisson_uncertainty(hist_p1) sigma_rest1 = poisson_uncertainty(rest_p1) frac0, sigma_frac0 = fraction_and_uncertainty(hist_p0, rest_p0, sigma_bin0, sigma_rest0) frac1, sigma_frac1 = fraction_and_uncertainty(hist_p1, rest_p1, sigma_bin1, sigma_rest1) p1calib, sigma_p1calib = fraction_and_uncertainty(frac1, frac0, sigma_frac1, sigma_frac0) sample_weight = 1 / (sigma_p1calib * sigma_p1calib) min(sample_weight) sample_weight /= min(sample_weight) sample_weight # - from sklearn.isotonic import IsotonicRegression from scipy import interpolate # + # we recalibrate per probability bin. NO interpolation (not valid in highest bin) hist_p0, bin_edges = np.histogram(p0, bins=nbins, range=(0, 1)) hist_p1, bin_edges = np.histogram(p2, bins=nbins, range=(0, 1)) #### !!!! p2 bin_centers = bin_edges[:-1] + 0.5/nbins hnorm_p0 = hist_p0 / sum(hist_p0) hnorm_p1 = hist_p1 / sum(hist_p1) hnorm_sum = hnorm_p0 + hnorm_p1 p1cb = np.divide(hnorm_p1, hnorm_sum, out=np.zeros_like(hnorm_p1), where=hnorm_sum != 0) # self.p1cb = p1cb, bin_centers # use isotonic regression to smooth out potential fluctuations in the p1 values # isotonic regression assumes that p1 can only be a rising function. # I’m assuming that if a classifier predicts a higher probability, the calibrated probability # will also be higher. This may not always be right, but I think generally it is a safe one. iso_reg = IsotonicRegression(y_min=0, y_max=1).fit(bin_centers, p1calib, sample_weight) p1pred = iso_reg.predict(bin_centers) p1f_ = interpolate.interp1d(bin_edges[:-1], p1pred, kind='previous', bounds_error=False, fill_value="extrapolate") # - p1lin = p1f_(bin_centers) plt.figure(figsize=(12,7)) #plt.plot(bin_centers, p1cb) plt.plot(bin_centers, p1cb) plt.plot(bin_centers, bin_centers) plt.plot(bin_centers, p1lin) #plt.plot(bin_centers, p2lin) x = np.linspace(0.95,1,500) pp = p1f_(x) plt.figure(figsize=(12,7)) #plt.plot(bin_centers, p1cb) plt.plot(x, pp) maxp1 = p1f_(0.999) max_weight = maxp1 / (1. - maxp1) max_weight # + # validation - part 1: check if reweighting works okay # + from pgmpy.sampling import BayesianModelSampling # sample data from BN inference = BayesianModelSampling(model) df_data = inference.forward_sample(size=250000, return_type='dataframe', seed=1) df_data.columns = [int(c) for c in df_data.columns] X = df_data[sorted(df_data.columns)].values # - p0 = clf.predict_proba(X)[:, 1] nominator = p1f_(p0) denominator = 1 - nominator weight = np.divide(nominator, denominator, out=np.ones_like(nominator), where=denominator != 0) len(X), sum(weight) np.sqrt(np.sum(weight * weight)) plt.hist(weight[weight < 10], bins=100, log=True) max_weight p0 = clf.predict_proba(X)[:, 1] nominator = p1f_(p0) denominator = 1 - nominator weight = np.divide(nominator, denominator, out=np.ones_like(nominator), where=denominator != 0) from random import choices #data, sample_weights = self._sample_no_transform(n_samples, random_state) pop = np.asarray(range(X.shape[0])) probs = weight/np.sum(weight) sample = choices(pop, probs, k=X.shape[0]) Xtrans = X[sample] p0 = clf.predict_proba(Xtrans)[:, 1] p2 = clf.predict_proba(X1_test)[:, 1] plt.figure(figsize=(12,7)) plt.hist(p0, bins=100, range=(0,1), alpha=0.5, density=True, log=True) #, weights=weight)#, log=True) plt.hist(p2, bins=100, range=(0,1), alpha=0.5, density=True) # + # validation - part 2: plot distributions # - i = 1 plt.figure(figsize=(12,7)) plt.hist(X[:, i], bins=100, range=(0,1), alpha=0.5, density=True)#, log=True) plt.hist(X1_test[:, i], bins=100, range=(0,1), alpha=0.5, density=True) # + # validation part 3: check number of duplicates # - df_data = inference.forward_sample(size=500000, return_type='dataframe', seed=2) df_data.columns = [int(c) for c in df_data.columns] X10k = df_data[sorted(df_data.columns)].values p0 = clf.predict_proba(X10k)[:, 1] nominator = p1f_(p0) denominator = 1 - nominator weight = np.divide(nominator, denominator, out=np.ones_like(nominator), where=denominator != 0) sum(weight) np.sqrt(np.sum(weight * weight)) uo, co = np.unique(X10k, axis=0, return_counts=True) countso = np.sort(co)[::-1] / 50 pop = np.asarray(range(X10k.shape[0])) probs = weight/np.sum(weight) sample = choices(pop, probs, k=X10k.shape[0]) Xtrans = X10k[sample] u, c = np.unique(Xtrans, axis=0, return_counts=True) counts = np.sort(c)[::-1] / 50 u, c = np.unique(data, axis=0, return_counts=True) c2 = np.sort(c)[::-1] plt.figure(figsize=(12,7)) plt.bar(list(range(40)), c2[:40], alpha=0.3) plt.bar(list(range(40)), counts[:40], alpha=0.3) plt.bar(list(range(40)), countso[:40], alpha=0.3) plt.figure(figsize=(12,7)) plt.bar(list(range(40)), c2[:40], alpha=0.3) plt.bar(list(range(40)), counts[:40], alpha=0.3) plt.figure(figsize=(12,7)) plt.bar(list(range(40)), c2[:40], alpha=0.3) plt.bar(list(range(40)), counts[:40], alpha=0.3) # + import numpy as np import pandas as pd from sdgym import benchmark from sdgym import load_dataset from xgboost import XGBClassifier from sklearn.neural_network import MLPClassifier from synthsonic.models.kde_copula_nn_pdf import KDECopulaNNPdf from synthsonic.models.categorical_utils import categorical_round, vec_translate, categorical_frequency_mapping, \ categorical_frequency_inverse_mapping, encode_one_hot, decode_one_hot from timeit import default_timer as timer import xgboost as xgb from sklearn.decomposition import PCA # %matplotlib inline from functools import partial # + df = pd.DataFrame(Xtrans) df.to_csv('test.csv', index=False) # - def KDECopulaNNPdf_RoundCategorical(real_data, categorical_columns, ordinal_columns, times=None): df = pd.read_csv('test.csv') data = df.values[:25000] return data alarm_times = [] alarm_thing = partial(KDECopulaNNPdf_RoundCategorical, times=alarm_times) alarm_thing.__name__ = KDECopulaNNPdf_RoundCategorical.__name__ alarm_scores = benchmark(synthesizers=[alarm_thing], datasets=['alarm']) alarm_scores if False: alarm_scores = benchmark(synthesizers=[alarm_thing], datasets=['alarm']) alarm_scores.drop(columns=['timestamp'], inplace=True) exec_time = ['N/A'] * 9 + [round(np.mean(alarm_times), 2)] alarm_scores['alarm/exec_time(s)'] = exec_time
notebooks/002-mb-bn_reweighting-examples/alarm_categorical_variables_bayesian_network_reweighted_stat_errors.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pickle import matplotlib.pyplot as plt from scipy.stats.mstats import gmean import seaborn as sns from statistics import stdev from math import log import numpy as np from scipy import stats from statistics import mean # %matplotlib inline price_100c = pickle.load(open("total_price.p","rb")) price_100 = pickle.load(open("C:\\Users\\ymamo\Google Drive\\1. PhD\\Dissertation\\SugarScape\Initial\\NetScape_Elegant\\total_price1.p", "rb")) # + from collections import defaultdict def make_distro(price_100): all_stds =[] total_log = defaultdict(list) for run, output in price_100.items(): for step, prices in output.items(): log_pr = [log(p) for p in prices] if len(log_pr) <2: pass else: out = stdev(log_pr) total_log[run].append(out) all_stds.append(out) return all_stds # - price_cluster = make_distro(price_100c) price_norm = make_distro(price_100) fig7, ax7 = plt.subplots(figsize = (7,7)) ax7.hist(price_norm, 500, label = "No Groups") ax7.hist(price_cluster, 500, label = "Agent Groups") plt.title("Network Approach:\nPrice Distribution of SDLM of 100 Runs", fontsize = 20, fontweight = "bold") plt.xlabel("SDLM of Step", fontsize = 15, fontweight = "bold") plt.ylabel("Frequency of SDLM", fontsize = 15, fontweight = "bold") #plt.xlim(.75,2) #plt.ylim(0,5) plt.legend() # + ## Calculate price # - ind_e = price_100c["Run42"] # + x = [] y =[] for st, pr in ind_e.items(): #if step <=400: x.append(st) y.append(gmean(pr)) y[0] # - fig, ax = plt.subplots(figsize = (7,7)) ax.scatter(x,y) plt.title("Network Approach: Mean Trade Price\n 10 Trades - No Policy", fontsize = 20, fontweight = "bold") plt.xlabel("Time", fontsize = 15, fontweight = "bold") plt.ylabel("Price", fontsize = 15, fontweight = "bold") x_vol = [] y_vol = [] total = 0 for s, p in ind_e.items(): #if step <=400: x_vol.append(s) y_vol.append(len(p)) total += len(p) total fig2, ax2 = plt.subplots(figsize = (7,7)) ax2.hist(y_vol, 100) plt.title("Network Approach:\nTrade Volume Histogram", fontsize = 20, fontweight = "bold") plt.xlabel("Trade Volume of Step", fontsize = 15, fontweight = "bold") plt.ylabel("Frequency Trade Volume", fontsize = 15, fontweight = "bold") #plt.ylim(0,400) fig2, ax2 = plt.subplots(figsize = (7,7)) ax2.plot(x_vol, y_vol) plt.title("Network Approach:\nTrade Volume", fontsize = 20, fontweight = "bold") plt.xlabel("Time", fontsize = 15, fontweight = "bold") plt.ylabel("Volume", fontsize = 15, fontweight = "bold") #ax2.text(600,300, "Total Trade Volume: \n "+str(total), fontsize = 15, fontweight = 'bold') #plt.ylim(0,400) # + x_dev =[] y_dev = [] x_all = [] y_all = [] log_prices = {} for step, prices in ind_e.items(): log_prices[step] = [log(p) for p in prices] for step, log_p in log_prices.items(): #if step <= 400: if len(log_p) <2: pass else: for each in log_p: x_all.append(step) y_all.append(each) x_dev.append(step) y_dev.append(stdev(log_p)) # - from numpy.polynomial.polynomial import polyfit fig3, ax3 = plt.subplots(figsize=(7,7)) ax3.scatter(x_all,y_all) plt.plot(x_dev,y_dev,'-', color ='red') plt.title("Network Approach:\nStandard Deviation of Logarithmic Mean", fontsize = 20, fontweight = "bold") plt.xlabel("Time", fontsize = 15, fontweight = "bold") plt.ylabel("Logarithmic Price", fontsize = 15, fontweight = "bold") stan_multi_s = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Standard\\stan_multi_sur.p", "rb")) stan_multi_t = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Standard\\stan_multi_time.p", "rb")) brute_multi_s = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Brute\\brute_multi_sur.p", "rb")) brute_multi_t = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Brute\\brute_multi_time.p", "rb")) net_multi_s = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Elegant\\net_multi_sur.p", "rb")) net_multi_t =pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Elegant\\net_multi_time.p", "rb")) net_mean = mean(net_multi_s) brute_mean = mean(brute_multi_s) stan_mean = mean(stan_multi_s) net_time = round(mean(net_multi_t),2) brute_time = round(mean(brute_multi_t),2) stan_time = round(mean(stan_multi_t),2) # + t, p = stats.ttest_ind(stan_multi_s[0:35],brute_multi_s[0:35]) brute_p = round(p * 2, 3) t2, p2 = stats.ttest_ind(stan_multi_s[0:35],net_multi_s[0:35]) net_p = round(p2 * 2, 8) t3, p3 = stats.ttest_ind(net_multi_s[0:35], stan_multi_s[0:35]) alt_p = round(p3 *2, 8) print (net_p,brute_p, alt_p) # - fig5, ax5 = plt.subplots(figsize=(7,7)) plt.hist(stan_multi_s, label = "Standard Approach") plt.hist(net_multi_s, label = "Network Approach") plt.hist(brute_multi_s, label = "Explicit Approach") #plt.text(60, 29, "Network Mean: "+str(net_mean) +"\nExplicit Mean: "+str(brute_mean) +"\nStandard Mean: " +str(stan_mean)) plt.legend() plt.title("Survivor Histogram of 100 Runs, 1000 Steps \nTrade Threshold 10; No Policy", fontweight = "bold", fontsize = 15) t, p = stats.ttest_ind(stan_multi_t,brute_multi_t) brute_t_p = (p * 2,10) t2, p2 = stats.ttest_ind(stan_multi_t,net_multi_t) net_t_p = (p2 * 2, 10) brute_t_p, net_t_p fig6, ax6 = plt.subplots(figsize=(7,7)) plt.hist(stan_multi_t, label = "Standard Approach") plt.hist(net_multi_t, label = "Network Approach") plt.hist(brute_multi_t, label = "Explicit Approach") #plt.text(78, 25, "Network p-value: "+str(net_t_p) +"\nExplicit p-value: "+str(brute_t_p)) plt.legend() plt.title("Time Histogram of 100 Runs, 1000 steps \nTrade Threshold 10; No Policy", fontweight = "bold", fontsize = 15) plt.text(48, 24, "\nStandard Mean: "+str(stan_time) + "\nNetwork Mean: "+str(net_time) +"\nExplicit Mean: "+str(brute_time)) # ## NOT USED stan_time = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Standard\\Time_stats.p", "rb")) brute_time = pickle.load(open("C:\\Users\\ymamo\\Google Drive\\1. PhD\\Dissertation\\SugarScape\\NetScape_Brute\\Time_stats.p", "rb")) net_time = pickle.load(open("net_multi_time.p", "rb")) # + stan_time.head() # - from statistics import mean def time_summary(df): net_by_100 = [] net_x = [] net_temp = [] idx = 100 total = 0 for k,v in df.iterrows(): if k % idx != 0 or k == 0: net_temp.append(v["Time Per Step"]) total += v["Time Per Step"] else: net_x.append(idx) net_by_100.append(mean(net_temp)) net_temp = [] idx += 100 net_temp.append(v["Time Per Step"]) total += v["Time Per Step"] return net_by_100, net_x, round(total,2) net_100, net_x, total_n = time_summary(net_time) stan_100, stan_x, total_s = time_summary(stan_time) brute_100, brute_x, total_b = time_summary(brute_time) fig4, ax4 = plt.subplots(figsize=(7,7)) plt.plot(net_x, net_100, label = "Network Approach") plt.plot(stan_x, stan_100, label = "Standard Approach") plt.plot(brute_x, brute_100, label = "Explicit Approach") plt.text(660, .075, "Network Total: "+str(total_n) +"\nStandard Time: "+str(total_s) + "\nExplicit Approach: "+str(total_b)) #plt.scatter(brute_time.index.values, stan_time["Time Per Step"]) plt.legend() plt.title("Typical Time Result Between Approaches", fontsize= 15, fontweight = "bold") def smooth_time(sur,time,group_size): survivors = zip(*(iter(sur),) * group_size) timey = zip(*(iter(time),) * group_size) sur = [] tim = [] for s in survivors: sur.append(mean(s)) for t in timey: tim.append(mean(t)) return sur, tim net_s, net_t = smooth_time(net_multi_s, net_multi_t, 10) brut_s, brut_t = smooth_time(brute_multi_s, brute_multi_t, 10) stan_s, stan_t = smooth_time(stan_multi_s, stan_multi_t, 10) fig5, ax5 = plt.subplots(figsize=(7,7)) plt.plot(list(range(10)), net_s, label = "Network Approach") plt.plot(list(range(10)), stan_s, label = "Standard Approach") plt.plot(list(range(10)), brut_s, label = "Explicit Approach") plt.legend() plt.title("Survivors 100 Runs", fontsize= 15, fontweight = "bold") fig5, ax5 = plt.subplots(figsize=(7,7)) plt.plot(list(range(10)), net_t, label = "Network Approach") plt.plot(list(range(10)), stan_t, label = "Standard Approach") plt.plot(list(range(10)), brut_t, label = "Explicit Approach") plt.legend() plt.title("Time 100 Runs", fontsize= 15, fontweight = "bold") #plt.text(75, 70, "Network Mean: "+str(net_mean) +"\nStandard Time: "+str(stan_mean) + "\nExplicit Approach: "+str(brute_mean))
Policy-Network/.ipynb_checkpoints/Data Analysis-checkpoint.ipynb
# ##HandWritten Digit Recognition using SVM, CNN with TensorFlow and Keras # ### MNIST Dataset # The MNIST database (Modified National Institute of Standards and Technology database) is a large database of handwritten digits that is commonly used for training various image processing systems. The database is also widely used for training and testing in the field of machine learning. It was created by "re-mixing" the samples from NIST's original datasets. These images were normalized in size and centered. Each image is in a 28x28 square (784 pixels). 60,000 images were used to train a model and 10,000 were used to test it. # ### Digit Recognition using Convolutional Layer Networks # ##### Imports from matplotlib import pyplot import numpy # We need to import several things from Keras. from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D # fix dimension ordering issue from keras import backend as K K.set_image_dim_ordering('th') # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load data (X_train, y_train), (X_test, y_test) = mnist.load_data() # reshape to be [samples][channels][width][height] X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32') X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 # The class-labels are One-Hot encoded, which means that each label is a vector with 10 elements, all of which are zero except for one element. The index of this one element is the class-number, that is, the digit shown in the associated image. # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # #### Simple Convolutional Neural Network # Here we will be using one convolutional layer, one max pooling layer and one hidden layer # ##### The neural network structure is shown below # # Visible Layer (1x28x28 Inputs) >> Convolutional Layer (32 maps, 5x5) >> Max Pooling Layer (2x2) >> Dropout Layer (20%) >> Flatten Layer >> Hidden Layer (128 Neurons) >> Output Layer (10 Outputs) # #####Sequential Model # The Keras API has two modes of constructing Neural Networks. The simplest is the Sequential Model which only allows for the layers to be added in sequence. # define a simple CNN model def baseline_model(): # create model # The Keras API has two modes of constructing Neural Networks. The simplest is the Sequential Model which only allows for the layers to be added in sequence. model = Sequential() # Convolutional layer with ReLU-activation and max-pooling. model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) # Flatten the 4-rank output of the convolutional layers to 2-rank that can be input to a fully-connected / dense layer. model.add(Flatten()) # First fully-connected / dense layer with ReLU-activation. model.add(Dense(128, activation='relu')) # Last fully-connected / dense layer with softmax-activation for use in classification. model.add(Dense(num_classes, activation='softmax')) # Compile model # The Neural Network has now been defined and must be finalized by adding a loss-function, optimizer and performance metrics. This is called model "compilation" in Keras. # For a classification-problem such as MNIST which has 10 possible classes, we need to use the loss-function called categorical_crossentropy. The performance metric we are # interested in is the classification accuracy. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # ###### Build, Fit and Final evalution of the model # Here the epochs are given 10, which means the function iterates 10 times with a batch size of 200. # build the model model = baseline_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("CNN Error for the Simple Convolutional Network is: %.2f%%" % (100-scores[1]*100)) # ##### Summary of a model model.summary() # ### Large Convolutional Neural Network # Here we will be using Two convolutional layers, Two max pooling layers and Two hidden layers # ##### The neural network structure is shown below # # Visible Layer (1x28x28 Inputs) >> Convolutional Layer (30 maps, 5x5) >> Max Pooling Layer (2x2) >> Convolutional Layer (15 maps, 3x3) >> Max Pooling Layer (2x2) >> Dropout Layer (20%) >> Hidden Layer (128 Neurons) >> Hidden Layer (50 Neurons) >> Output Layer (10 Outputs # #######Sequential Model # The Keras API has two modes of constructing Neural Networks. The simplest is the Sequential Model which only allows for the layers to be added in sequence. # define a simple CNN model def larger_model(): # create model # The Keras API has two modes of constructing Neural Networks. The simplest is the Sequential Model which only allows for the layers to be added in sequence. model = Sequential() # First convolutional layer with ReLU-activation and max-pooling. model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) # Second convolutional layer with ReLU-activation and max-pooling. model.add(Conv2D(15, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) # Flatten the 4-rank output of the convolutional layers to 2-rank that can be input to a fully-connected / dense layer. model.add(Flatten()) # First fully-connected / dense layer with ReLU-activation. model.add(Dense(128, activation='relu')) # Second fully-connected / dense layer with ReLU-activation. model.add(Dense(50, activation='relu')) # Last fully-connected / dense layer with softmax-activation for use in classification. model.add(Dense(num_classes, activation='softmax')) # Compile model # The Neural Network has now been defined and must be finalized by adding a loss-function, optimizer and performance metrics. This is called model "compilation" in Keras. # For a classification-problem such as MNIST which has 10 possible classes, we need to use the loss-function called categorical_crossentropy. The performance metric we are # interested in is the classification accuracy. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # ###### Build, Fit and final evaluation of the model # Here the epochs are given 10, which means the function iterates 10 times with a batch size of 200. # build the model model = larger_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("CNN Error for the Large Convolutional Network is: %.2f%%" % (100-scores[1]*100)) # ### Large Convolutional Neural network with image flip of degree 180 # Different people write in different angles. Here we randomly rotate images up to 180 degrees. # + # Simple CNN for the MNIST Dataset import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.utils import np_utils # fix dimension ordering issue from keras import backend as K K.set_image_dim_ordering('th') # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load data (X_train, y_train), (X_test, y_test) = mnist.load_data() # reshape to be [samples][channels][width][height] X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32') X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # define data preparation datagen = ImageDataGenerator(rotation_range=180) # + # define a simple CNN model def baseline_model(): # create model model = Sequential() model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(num_classes, activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # build the model model = baseline_model() # Fit the model model.fit_generator(datagen.flow(X_train.reshape(60000,1,28,28), y_train, batch_size=200), validation_data=(X_test.reshape(10000,1,28,28), y_test), epochs=10) # - # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("CNN Error for Large Convolutional Network with image flip of degree 180: %.2f%%" % (100-scores[1]*100)) model.summary() # ### Support Vector Machine(SVM) # ##### Imports import matplotlib.pyplot as plt import numpy as np import time import datetime as dt #fetch original mnist dataset from sklearn.datasets import fetch_mldata # Import datasets, classifiers and performance metrics from sklearn import datasets, svm, metrics # ##### Fetching of data from MNIST mnist = fetch_mldata('MNIST original', data_home='./') # ##### Looking up keys present in data # + mnist.keys() # - #data field is 70k x 784 array, each row represents pixels from 28x28=784 image images = mnist.data targets = mnist.target #full dataset classification X_data = images/255.0 Y = targets #split data to train and test #from sklearn.cross_validation import train_test_split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_data, Y, test_size=0.15, random_state=42) # + # Create a classifier: a support vector classifier param_C = 5 param_gamma = 0.05 classifier = svm.SVC(C=param_C,gamma=param_gamma) # We learn the digits on train part start_time = dt.datetime.now() print('Start learning at {}'.format(str(start_time))) classifier.fit(X_train, y_train) end_time = dt.datetime.now() print('Stop learning {}'.format(str(end_time))) elapsed_time= end_time - start_time print('Elapsed learning {}'.format(str(elapsed_time))) expected = y_test predicted = classifier.predict(X_test) print("Classification report for classifier %s:\n%s\n" % (classifier, metrics.classification_report(expected, predicted))) cm = metrics.confusion_matrix(expected, predicted) print("Confusion matrix:\n%s" % cm) print("Accuracy={}".format(metrics.accuracy_score(expected, predicted))) # - # ##### Citations # https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/03C_Keras_API.ipynb # ## Results # ##### Accuracy of Finding the digit using Simple Convolutional Layer : 99.07 # # ##### Accuracy of Finding the digit using Large Convolutional Layer : 99.26 # # ##### Accuracy of Finding the digit using Large Convolutional Layer with image flip of degree 180 : 96.46 % # # ##### Accuracy of Finding the digit using Support Vector Machine (SVM) : 98.52 % # The text in the document by <NAME> is licensed under CC BY 3.0 https://creativecommons.org/licenses/by/3.0/us/ # # The code in the document by <NAME> is licensed under the MIT License https://opensource.org/licenses/MIT # # Copyright 2018 <NAME> # # 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.
ADS Project.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Rasterising vectors & vectorising rasters <img align="right" src="../Supplementary_data/DE_Africa_Logo_Stacked_RGB_small.jpg"> # # * **Products used:** # [ga_ls8c_wofs_2_annual_summary](https://explorer.digitalearth.africa/ga_ls8c_wofs_2_annual_summary) # + raw_mimetype="text/restructuredtext" active="" # **Keywords** :index:`data used; WOfS`, :index:`data methods; rasterize`, :index:`data methods; vectorize`, :index:`data format; GeoTIFF`, :index:`data format; shapefile` # - # ## Background # # Many remote sensing and/or geospatial workflows require converting between vector data (e.g. shapefiles) and raster data (e.g. pixel-based data like that in an `xarray.DataArray`). # For example, we may need to use a shapefile as a mask to limit the analysis extent of a raster, or have raster data that we want to convert into vector data to allow for easy geometry operations. # ## Description # In this notebook, we show how to use the Digital Earth Africa function `xr_rasterize` and `xr_vectorize` in [deafrica_spatialtools.py](../Scripts/deafrica_spatialtools.py). The notebook demonstrates how to: # # 1. Load in data from the [Water Observations from Space (WOfS)](https://maps.digitalearth.africa/#share=s-jENTWtaN98vMumZGcwM2iZXzFBo) product # 2. Vectorise the pixel-based `xarray.DataArray` WOfS object into a vector-based `geopandas.GeoDataFrame` object containing persistent water-bodies as polygons # 3. Export the `geopandas.GeoDataFrame` as a shapefile # 4. Rasterise the `geopandas.GeoDataFrame` vector data back into an `xarray.DataArray` object and export the results as a GeoTIFF # # *** # ## Getting started # To run this analysis, run all the cells in the notebook, starting with the "Load packages" cell. # ### Load packages # # + # %matplotlib inline import datacube from deafrica_tools.datahandling import mostcommon_crs from deafrica_tools.spatial import xr_vectorize, xr_rasterize # - # ### Connect to the datacube dc = datacube.Datacube(app='Rasterise_vectorise') # ## Load WOfS data from the datacube # # We will load in an annual summary from the Water Observations from Space (WOfS) product to provide us with some data to work with. # + #enter a location lat, lon = 13.50, -15.42 buffer = 0.2 # Create a reusable query query = { 'x': (lon-buffer, lon+buffer), 'y': (lat+buffer, lat-buffer), 'time': ('2017') } # Identify the most common projection system in the input query output_crs = mostcommon_crs(dc=dc, product='ls8_sr', query=query) # Load WoFS through the datacube ds = dc.load(product='ga_ls8c_wofs_2_annual_summary', output_crs=output_crs, align=(15, 15), resolution=(-30, 30), **query) print(ds) # - # ### Plot the WOfS summary # # Let's plot the WOfS data to get an idea of the objects we will be transforming. # In the code below, we first select the pixels where the satellite has observed water at least 25% of the year, this is so we can isolate the more persistent water bodies and reduce some of the noise before we vectorise the raster. # + # Select pixels that are classified as water > 25 % of the year water_bodies = ds.frequency > 0.25 # Plot the data water_bodies.plot(size=5) # - # ## Vectorising an `xarray.DataArray` # # To convert our `xarray.DataArray` object into a vector based `geopandas geodataframe`, we can use the DE Africa function `xr_vectorize` in the script [deafrica_spatialtools.py](../Scripts/deafrica_spatialtools.py). This tool is based on the [rasterio.features.shape](https://rasterio.readthedocs.io/en/stable/api/rasterio.features.html) function, and can accept any of the arguments in `rasterio.features.shape` using the same syntax. # # In the cell below, we use the argument `mask=water_bodies.values==1` to indicate we only want to convert the values in the xarray object that are equal to 1. # # # > **Note**: Both `xr_rasterize` and `xr_vectorize` will attempt to automatically obtain the `crs` and `transform` from the input data, but if the data does not contain this information, you will need to manually provide this. In the cell below, we will get the `crs` and `transform` from the original dataset. # + gdf = xr_vectorize(water_bodies, crs=ds.crs, transform=ds.geobox.transform, mask=water_bodies.values==1) print(gdf.head()) # - # ### Plot our vectorised raster gdf.plot(figsize=(6, 6)) # ### Export as shapefile # # Our function also allows us to very easily export the `GeoDataFrame` as a `shapefile` for use in other applications using the `export_shp` parameter. gdf = xr_vectorize(da=water_bodies, crs=ds.crs, transform=ds.geobox.transform, mask=water_bodies.values == 1., export_shp='test.shp') # ## Rasterising a shapefile # # Using the `xr_rasterize` function in [deafrica_spatialtools.py](../Scripts/deafrica_spatialtools.py) (based on the rasterio function: [rasterio.features.rasterize](https://rasterio.readthedocs.io/en/stable/api/rasterio.features.html), and can accept any of the arguments in `rasterio.features.rasterize` using the same syntax) we can turn the `geopandas.GeoDataFrame` back into a `xarray.DataArray`. # # As we already have the `GeoDataFrame` loaded we don't need to read in the shapefile, but if we wanted to read in a shapefile first we can use [gpd.read_file()](http://geopandas.org/reference/geopandas.read_file.html). # # This function uses an `xarray.dataArray` object as a **template** for converting the `geodataframe` into a raster object (the template provides the `size`, `crs`, `dimensions`, `transform`, and `attributes` of the output array). # + water_bodies_again = xr_rasterize(gdf=gdf, da=water_bodies, transform=ds.geobox.transform, crs=ds.crs) print(water_bodies_again) # - # ### Export as GeoTIFF # # `xr_rasterize` also allows for exporting the results as a GeoTIFF using the parameter `export_tiff`. To do this, a `named` array is required. If one is not provided, the functon wil provide a default one. water_bodies_again = xr_rasterize(gdf=gdf, da=water_bodies, transform=ds.geobox.transform, crs=ds.crs, export_tiff='test.tif') # --- # # ## Additional information # # **License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). # Digital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license. # # **Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)). # If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks). # # **Compatible datacube version:** print(datacube.__version__) # **Last Tested:** from datetime import datetime datetime.today().strftime('%Y-%m-%d')
Frequently_used_code/Rasterise_vectorise.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import warnings warnings.filterwarnings("ignore") import os import pickle import numpy as np import pandas as pd import scipy.io as sio import matplotlib.pyplot as plt import sklearn.metrics as metrics from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import auc # ### Ablation Study def precision_recall_k(y_true, y_score, k=50): desc_sort_order = np.argsort(y_score)[::-1] y_true_sorted = y_true[desc_sort_order] true_positives = y_true_sorted[:k].sum() pk = true_positives / k rk = true_positives / np.sum(y_true) return pk, rk import pickle for dataset in ["enron"]: for flag in ["", "_none", "_base"]: if os.path.exists(f"../outputs/{dataset}{flag}.mat"): data = sio.loadmat(f"../outputs/{dataset}{flag}.mat") with open(f"../outputs/{dataset}{flag}.pkl", 'wb') as fw: pickle.dump(data, fw) # + dataset = "pubmed" with open(f"../outputs/{dataset}.pkl", "rb") as fr: result = pickle.load(fr) with open(f"../outputs/{dataset}_none.pkl", "rb") as fr: result_v1 = pickle.load(fr) with open(f"../outputs/{dataset}_base.pkl", "rb") as fr: result_v2 = pickle.load(fr) methods = ["Full", "w/o sampling", "w/o clustering"] data_list = [result, result_v1, result_v2] for data, method in zip(data_list, methods): print(f"{method}") labels, scores = data['labels'].flatten(), data['scores'].flatten() auc = roc_auc_score(labels, scores) print(f"AUC: {auc:.4f}") k_list = [10, 50, 100, 200, 300] for k in k_list: pk, rk = precision_recall_k(labels, scores, k) print(f"Precision@{k}: {pk:.4f}; Recall@{k}: {rk:.4f};") # -
notebooks/evaluation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: pyKIS # language: python # name: pykis # --- # ## 1. GitLab introduction # ## 2. DataCamp # To get you used to [DataCamp](https://learn.datacamp.com/), do the first few exercises on its introduction to python: # # 2.1. [The python interface](https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-1-python-basics?ex=2) # # 2.2. [Comments](https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-1-python-basics?ex=4) # # 2.3. [Python as a Calculator](https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-1-python-basics?ex=5) # # 2.4. [Variable Assignment](https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-1-python-basics?ex=7) # # 2.5. [Calculations with Variables](https://campus.datacamp.com/courses/intro-to-python-for-data-science/chapter-1-python-basics?ex=8) # ## 3. First Steps # **3.1.** Write code that prints `Hello, world!`, without directly using the letter `l` more than once (in your code). a = 'l' print("He" + 2 * a + "o, wor" + a + "d!") # 3.2. A magician approaches you and asks you to think of any (integer) number. He then asks you to double it. Then add 10 to it, then halve it again. As a last step, subtract your original number. To your surprise, the magician already knows your new number: 5! # # Use python to explain the magicians trick. # + number = 42 result = ((((number * 2) + 10) / 2) - number) print(result) result = number * 2/2 + 10/2 - number print(result) result = 10 / 2 print(result) # -
exercises/sol_1_1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] id="vlBQLYLv2YTQ" # # "Lección 3: Conceptos fundamentales de deep learning" # > "Primer acercamiento al problema y el Descenso del Gradiente" # # - toc: false # - branch: master # - badges: true # - comments: true # - categories: [curso_Fast.ai] # - image: images/some_folder/your_image.png # - hide: false # - search_exclude: true # - metadata_key1: metadata_value1 # - metadata_key2: metadata_value2 # + [markdown] id="2dn53DMr2LkR" # # + [markdown] id="8bf50001" # # Lección 03: Conceptos fundamentales de deep learning # + [markdown] id="4e2e2b16" # <a href="https://course.fast.ai/">Practical Deep Learning for Coders</a> # # + [markdown] id="1b97e477" # > Tip 1: ser tenaz, seguir intentándo resolver los problemas. # + [markdown] id="71e94c33" # > Tip 2: Antes de empezar con modelos más complejos se recomienda: # - Usar un modelo muy sencillo y fácil de implementar: será mejor que un resultado aleatorio y servirá de base # - Usar un modelo creado por otra persona con tus datos # + [markdown] id="9f4761e0" # ### Paso 1: Veamos un modelo sencillo para un clasificador de imagenes: **distancia a la media** # + [markdown] id="b06662cd" # - Se calcula la media de cada uno de los grupos de imagenes a clasificar # + id="ba45213e" outputId="f4cc775d-4316-4d54-b9ab-9b61ca37f998" # creo dos tensores que agrupen todas las imagenes de cada uno tensores3=[tensor(Image.open(i)) for i in treses] tensores7=[tensor(Image.open(i)) for i in sietes] len(tensores3),len(tensores7) # + id="45fa5529" outputId="e890239b-7464-4735-eb26-db6302823860" # mostrar una imagen a partir de un tensor show_image(tensores3[1]) # + id="a710b10f" # crear tensores con las imagenes apiladas pila3s = torch.stack(tensores3).float()/255 pila7s = torch.stack(tensores7).float()/255 # + id="5520e2b1" outputId="9ef97515-991d-4556-d29f-95b6e64db41f" # medir dimensiones del tensor pila3s.shape # + id="b70519c9" outputId="854ccdfe-d608-4aa9-8e53-22a62e31b693" # dos métodos de medir rango del tensor len(pila3s.shape), pila3s.ndim # + id="38f2c5ba" # calcular la media de cada uno de la primera dimensión (0) media3= pila3s.mean(0) media7= pila7s.mean(0) # + id="4d6bf026" outputId="5864b010-60dc-4f9f-cd60-4b18abf71097" show_image(media3) show_image(media7) # + [markdown] id="6634558e" # <hr/> # # - Buscamos la **distancia** que hay entre cada imagen y la media. # # Opciones: # # * Diferencias de valores absolutos (L1 norm) # * Raiz del error medio cuadrático (RMSE o L2 norm): se penaliza más cuanto mayor sea el error # # + id="93e6c3cb" outputId="48c4ea4a-1a47-46fb-f172-69389b2287ba" a_3 = pila3s[1] show_image(a_3); # + id="fac1fa1e" outputId="25737343-92ae-4ef8-f2eb-561f85b18367" # cálculo de las distancias dist_abs_3= (a_3-media3).abs().mean() dist_sqr_3= ((a_3-media3)**2).mean().sqrt() dist_abs_3,dist_sqr_3 # + id="8cef5066" outputId="d634afe5-07e3-4031-f65c-6037eb200604" dist_abs_7= (a_3-media7).abs().mean() dist_sqr_7= ((a_3-media7)**2).mean().sqrt() dist_abs_7,dist_sqr_7 # + [markdown] id="cb3ab657" # Se puede ver que la distancia al 3 "ideal" es menor al 7 "ideal", por lo tanto, el modelo predice correctamente. # # + id="ee38be40" outputId="97680f7f-fe9b-4e19-98e2-fcde36c4e689" # usando la libreria de Pytorch F.l1_loss(a_3.float(),media3),F.mse_loss(a_3.float(),media3).sqrt() # + [markdown] id="2ef7ea2e" # > Tip 1: Evitar el uso de loops, son mucho más lentos que los métodos que tienen vectores y tensores. # + [markdown] id="a55015e1" # > Tip 2: Usar la funcionalidad Broadcasting para mayor eficiencia.Consiste en expandir un tensor de rango inferior al rango de otro con el que se quiere operar. # <br>Se optimiza el uso de la memoria y se ejecuta de manera rápida a través de C o GPUs # + [markdown] id="15721c3f" # ### Paso 2: aprendizaje automático con red neuronal (artificial) # + [markdown] id="5a2d85a4" # Buscaremos un sistema que vaya mejorando las predicciones de forma automática. # # Para ello, usaremos una red neuronal que está formada por una serie de capas de neuronas interconectadas. # # Están compuestas por números: # - parámetros: valores que definen el modelo, se inicializan de forma aleatoria y se irán optimizando # - activaciones: valores calculados # # Las capas pueden ser lineales o no lineales (por ejemplo, función de activación ReLU). Combinando estas capas se puede resolver cualquier problema. # # Cada neurona tendrá una función de activación que recibe los inputs de la capa anterior: # # f(x) = w * x + b , donde w son los pesos y b es el sesgo (w y b -> parámetros) # # Esta función nos dará las predicciones en base a los pesos que tenemos. # # + [markdown] id="1e48a9ef" # <hr> # Para lograr el aprendizaje automático usamos la técnica del Descenso del Gradiente **Stochastic Gradient Descent (SGD)** : # # 1- inicializar los pesos (w) de forma aleatoria o de un modelo pre-entrenado # 2- calcular la predicciones para cada entrada (usando la función de activación) -> 'forward pass' # 3- calcular la bondad del modelo con una función de pérdida / distancia (L1 norm, RMSE,..) # # pérdida -> cuanto menor sea mejor # función de pérdida: # - no usar la 'precisión' # - usar 'sigmoid': acepta cualquier valor real, valores entre 0 y 1 y derivada con sentido # - usar ReLU para capas no lineares, función que asigna un 0 a las entradas negativas. # # 4- calcular el gradiente de w para saber cómo afecta la variación en cada uno en la función de pérdida. Cómo tenemos que variar los w para minimizar la pérdida (optimizar el modelo) -> 'backward pass' # # y = f(x) # y.backward() // calcular el gradiente # x.grad // consulta del gradiente # # 5- dar un paso: modificar los w en base al gradiente: w := w + grad(w)* lr (ratio de aprendizaje/learning rate) # # lr suele estar entre 0.001 y 0.1 # # Si es pequeño tardará demasiado en llegar al óptimo # Si es grande puede no llegar nunca, se saltaría el óptimo # # 6- volver y repetir el proceso # 7- parar cuando se estime que el modelo es suficientemente bueno o no se puede esperar más (num. epochs) # + [markdown] id="227eb0e0" # ### Mini lotes (batches) # + [markdown] id="42fc9515" # En lugar de realizar el proceso sobre todas entradas (llevaría mucho tiempo) o sobre una (muy impreciso), se calculará sobre un número reducido. # El tamaño del lote llevará a un modelo más preciso o a uno más rápido. # # La GPUs usarán estos lotes para acelerar el proceso # + id="68f5b4e4"
_notebooks/2021-07-24-Leccion-03-Conceptos-fundamentales-DL.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="OdNiA5tcv5Ym" colab_type="code" outputId="07c334af-12d5-4bf2-9d41-b96df61cb3e1" executionInfo={"status": "ok", "timestamp": 1584033328507, "user_tz": -330, "elapsed": 1194, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17863093696646821487"}} colab={"base_uri": "https://localhost:8080/", "height": 34} from google.colab import drive drive.mount('/content/drive') # + id="yxOOVzB1H6d5" colab_type="code" outputId="1c8de925-0cf4-4639-8e70-82c1509c1b39" executionInfo={"status": "ok", "timestamp": 1584033332926, "user_tz": -330, "elapsed": 5354, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17863093696646821487"}} colab={"base_uri": "https://localhost:8080/", "height": 221} # !pip install scikit-plot # + id="8Oh2H8zQwHLA" colab_type="code" outputId="5879eb3e-f739-4b85-a930-90396ec6af5c" executionInfo={"status": "ok", "timestamp": 1584033334319, "user_tz": -330, "elapsed": 6529, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17863093696646821487"}} colab={"base_uri": "https://localhost:8080/", "height": 119} #import statements import os os.environ['CUDA_LAUNCH_BLOCKING'] = "1" import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt from torch.autograd import Variable from torch.utils import data from torchsummary import summary import pandas as pd import numpy import sys import torch from torch.nn import functional as F import numpy as np from torchtext import data from torchtext import datasets from torchtext.vocab import Vectors, GloVe import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torchtext.datasets import TranslationDataset from torchtext.data import Field, BucketIterator from torch.autograd import Variable from torchsummary import summary from torchtext import data import torchtext import re import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer from string import punctuation nltk.download('stopwords') nltk.download('punkt') import spacy import matplotlib.pyplot as plt import pandas as pd from tqdm.auto import tqdm device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') import random import math import time import string import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords cachedStopWords = stopwords.words("english") # + id="pkCQZ6ALwKlU" colab_type="code" colab={} # path os.chdir('/content/drive/My Drive/DL_Group/Assignments/Assignment_2') # + [markdown] id="HqglHxeXX-pH" colab_type="text" # ## DATA LOADING AND PREPROCESSING # + id="Brxjnh-fTSW9" colab_type="code" colab={} dataset_loc = 'Data/Q2/train_data.csv' raw_data = pd.read_csv(dataset_loc) np.random.shuffle(raw_data.values) stop_words = list(set(stopwords.words('english'))) stop_words.extend(list(set(string.punctuation))) spacy_en = spacy.load('en') sentiments = {'worry' : 0, 'happiness' : 1, 'relief' : 2, 'boredom' : 3, 'neutral' : 4, 'love' : 5, 'anger' : 6, 'empty' : 7, 'surprise' : 8, 'fun' : 9, 'enthusiasm' : 10, 'hate' : 11, 'sadness' : 12} # + id="L9suu8uNy11V" colab_type="code" colab={} def convert_to_encoding(labels): for i in range(len(labels)): labels[i] = sentiments[labels[i]] return labels # + id="aF4vlTL7wP-R" colab_type="code" colab={} contraction_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have"} def _get_contractions(contraction_dict): contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys())) return contraction_dict, contraction_re contractions, contractions_re = _get_contractions(contraction_dict) def replace_contractions(text): def replace(match): return contractions[match.group(0)] return contractions_re.sub(replace, text) # + id="-5qCQjRx9KnN" colab_type="code" colab={} def preprocess_sentence(sentence): sentence=replace_contractions(sentence) sentence = re.sub(r'(?:\@|https?\://)\S+', '', sentence).strip() sentence = word_tokenize(sentence) stemmer = SnowballStemmer('english') sentence = [(stemmer.stem(i)).lower() for i in sentence] sentence = [i for i in sentence if i not in cachedStopWords] return ' '.join(sentence) # + id="BX4wsQP288cD" colab_type="code" colab={} def preprocess(sentences): for i in range(len(sentences)): sentences[i] = preprocess_sentence(sentences[i]) return sentences # + id="6m9ZuPoetoxt" colab_type="code" colab={} reviews = preprocess(list(raw_data['content'])) labels = convert_to_encoding(list(raw_data['sentiment'])) # + id="WZTtGSifJRrI" colab_type="code" colab={} train_x = reviews[:24000] train_y = labels[:24000] train = pd.concat([pd.Series(train_x, name = 'content'), pd.Series(train_y, name = 'sentiment')], axis = 1) # + id="WcFNo1sMH3fT" colab_type="code" colab={} val_x = reviews[24000:] val_y = labels[24000:] val = pd.concat([pd.Series(val_x, name = 'content'), pd.Series(val_y, name = 'sentiment')], axis = 1) # + id="rfL95utUJDQY" colab_type="code" colab={} train.to_csv('Data/Q2/train.csv', index=False) val.to_csv('Data/Q2/val.csv', index=False) # + id="nq1l1OGoIgHr" colab_type="code" colab={} TEXT = data.Field(sequential = True, tokenize = 'spacy') LABEL = data.LabelField(dtype = torch.long, sequential = False) # + id="_KQ79N9mRKGw" colab_type="code" colab={} train_data, val_data = data.TabularDataset.splits( path = 'Data/Q2/', train = 'train.csv', validation = 'val.csv', format = 'csv', skip_header = True, fields = [('Text', TEXT), ('Label', LABEL)] ) # + id="yb5wBMTSRXrx" colab_type="code" outputId="204769cd-e6ca-410b-9e5a-7b5974858db7" executionInfo={"status": "ok", "timestamp": 1584033361333, "user_tz": -330, "elapsed": 30290, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17863093696646821487"}} colab={"base_uri": "https://localhost:8080/", "height": 34} print(len(train_data), len(val_data)) # + id="IpvwOE03Jqs8" colab_type="code" colab={} glove_file = 'Data/Q2/glove.6B.300d.txt' TEXT.build_vocab(train_data, vectors = torchtext.vocab.Vectors(glove_file)) LABEL.build_vocab(train_data) # import dill # with open("Data/Q2/TEXT.Field","wb")as f: # dill.dump(TEXT,f) # with open("Data/Q2/LABEL.Field","wb")as f: # dill.dump(LABEL,f) # with open("Data/Q2/TEXT.Field","rb")as f: # TEXT=dill.load(f) # with open("Data/Q2/LABEL.Field","rb")as f: # LABEL=dill.load(f) # + id="6KLoBJgAK5zM" colab_type="code" colab={} device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size = 256 ## CHANGE BATCH SIZE HERE TO CHANGE IT IN THE ITERATOR embedding_weights = TEXT.vocab.vectors embedding_weights.cpu() vocab_size = len(TEXT.vocab) embedding_length = 300 output_size = 13 train_iter, valid_iter = data.BucketIterator.splits( (train_data, val_data), sort_key = lambda x: len(x.Text), batch_size = batch_size, device = device) # + [markdown] id="qVkTfvnGX5O9" colab_type="text" # ## LSTM + ATTENTION # + id="Hmr6h7BHwdqL" colab_type="code" colab={} # LSTM MODEL + ATTENTION import torch import torch.nn as nn from torch.autograd import Variable from torch.nn import functional as F import numpy as np class AttentionModel(torch.nn.Module): def __init__(self, hidden_size, output_size, vocab_size, embedding_length, embedding_weights, num_layers, bidirectional, dropout): super(AttentionModel, self).__init__() """ Arguments --------- batch_size : Size of the batch which is same as the batch_size of the data returned by the TorchText BucketIterator output_size : 2 = (pos, neg) hidden_sie : Size of the hidden_state of the LSTM vocab_size : Size of the vocabulary containing unique words embedding_length : Embeddding dimension of GloVe word embeddings weights : Pre-trained GloVe word_embeddings which we will use to create our word_embedding look-up table -------- """ self.hidden_size = hidden_size self.output_size = output_size self.vocab_size = vocab_size self.embedding_length = embedding_length self.embedding_weights = embedding_weights self.num_layers = num_layers self.num_dir = 2 if bidirectional else 1 self.bidirectional = bidirectional self.dropout = dropout # Embeding Layer self.embedding = nn.Embedding(self.vocab_size, self.embedding_length, padding_idx = 0) self.embedding.weight = nn.Parameter(self.embedding_weights, requires_grad = False) self.lstm = nn.LSTM(self.embedding_length, self.hidden_size, num_layers = self.num_layers, bidirectional = self.bidirectional, dropout = self.dropout) self.linear = nn.Linear(self.num_layers * self.num_dir * self.hidden_size, self.output_size) self.W_s1 = nn.Linear(2*hidden_size, 350) self.W_s2 = nn.Linear(350, 30) self.fc_layer = nn.Linear(30*2*hidden_size, 2000) self.label = nn.Linear(2000, output_size) self.softmax = nn.Softmax() def attention_net(self, lstm_output,final_state): """ Now we will incorporate Attention mechanism in our LSTM model. In this new model, we will use attention to compute soft alignment score corresponding between each of the hidden_state and the last hidden_state of the LSTM. We will be using torch.bmm for the batch matrix multiplication. Arguments --------- lstm_output : Final output of the LSTM which contains hidden layer outputs for each sequence. final_state : Final time-step hidden state (h_n) of the LSTM --------- Returns : It performs attention mechanism by first computing weights for each of the sequence present in lstm_output and and then finally computing the new hidden state. Tensor Size : hidden.size() = (batch_size, hidden_size, num_layer) lstm_output.size() = (batch_size, num_seq, hidden_size) attn_weights.size() = (batch_size, num_seq, num_layer) soft_attn_weights.size() = (batch_size, num_seq * num_layer) new_hidden_state.size() = (batch_size, hidden_size, num_layer) """ if bidirectional==False: hidden = final_state.permute(1, 2, 0) attn_weights = torch.bmm(lstm_output, hidden) soft_attn_weights = F.softmax(attn_weights.flatten(start_dim = 1), 1) new_hidden_state = torch.bmm(lstm_output.transpose(1, 2), soft_attn_weights.reshape(attn_weights.shape)) return new_hidden_state.flatten(start_dim = 1) else: #for bidirection- true attn_weight_matrix = self.W_s2(F.tanh(self.W_s1(lstm_output))) attn_weight_matrix = attn_weight_matrix.permute(0, 2, 1) attn_weight_matrix = F.softmax(attn_weight_matrix, dim=2) return attn_weight_matrix def forward(self, x): x = x.permute(1, 0) batch_size = x.shape[0] inp = self.embedding(x) inp = inp.permute(1, 0, 2) h_0 = Variable(torch.zeros(self.num_layers * self.num_dir, batch_size, self.hidden_size).cuda()) c_0 = Variable(torch.zeros(self.num_layers * self.num_dir, batch_size, self.hidden_size).cuda()) out, (h_n, c_n) = self.lstm(inp, (h_0, c_0)) out=out.permute(1,0,2) # print("out") # print(out.shape) # print("h_n") # print(h_n.shape) # print("inp") # print(inp.shape) # print("h_0") # print(h_0.shape) #for bidirection- false if bidirectional==False: attn_output = self.attention_net(out,h_n) labels = self.linear(attn_output) output = self.softmax(labels) return labels,output else: attn_weight_matrix = self.attention_net(out,h_n) hidden_matrix = torch.bmm(attn_weight_matrix, out) fc_out = self.fc_layer(hidden_matrix.view(-1, hidden_matrix.size()[1]*hidden_matrix.size()[2])) logits = self.label(fc_out) output = self.softmax(logits) return logits,output # + [markdown] id="vVzhzeVok4HB" colab_type="text" # FINAL MAIN RUN -> LSTM # + id="Ijjrsfd4wgLK" colab_type="code" colab={} # FINAL RUN -. LSTM import os import time import torch import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import numpy as np def clip_gradient(model, clip_value): params = list(filter(lambda p: p.grad is not None, model.parameters())) for p in params: p.grad.data.clamp_(-clip_value, clip_value) def train_model(model, train_iter, epoch): total_epoch_loss = 0 total_epoch_acc = 0 model.cuda() optim = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters())) steps = 0 model.train() for idx, batch in enumerate(train_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() optim.zero_grad() prediction,pred_prob = model(text) #if using softmax # loss = loss_fn(pred_prob, target) # num_corrects = (torch.max(pred_prob, 1)[1].view(target.size()).data == target.data).sum() loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).float().sum() acc = 100.0 * num_corrects/len(batch) loss.backward() clip_gradient(model, 1e-1) optim.step() steps += 1 # if steps % 100 == 0: # print (f'Epoch: {epoch+1}, Idx: {idx+1}, Training Loss: {loss.item():.4f}, Training Accuracy: {acc.item(): .2f}%') total_epoch_loss += loss.item() total_epoch_acc += acc.item() return total_epoch_loss/len(train_iter), total_epoch_acc/len(train_iter) def eval_model(model, val_iter): total_epoch_loss = 0 total_epoch_acc = 0 model.eval() with torch.no_grad(): for idx, batch in enumerate(val_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() prediction,pred_prob = model(text) #if using softmax # loss = loss_fn(pred_prob, target) # num_corrects = (torch.max(pred_prob, 1)[1].view(target.size()).data == target.data).sum() loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).sum() acc = 100.0 * num_corrects/len(batch) total_epoch_loss += loss.item() total_epoch_acc += acc.item() return total_epoch_loss/len(val_iter), total_epoch_acc/len(val_iter) learning_rate = 2e-5 num_epochs = 20 hidden_size = 32 num_layers = 3 # batch_size change from iterator bidirectional = True momentum = 0.9 dropout = 0.5 model = AttentionModel(hidden_size, output_size, vocab_size, embedding_length, embedding_weights, num_layers, bidirectional, dropout) loss_fn = F.cross_entropy pbar = tqdm(range(num_epochs)) train_acc_list=[] val_acc_list=[] train_loss_list=[] val_loss_list=[] best_val_accuracy=0 best_epoch=0 for epoch in range(num_epochs): train_loss, train_acc = train_model(model, train_iter, epoch) val_loss, val_acc = eval_model(model, valid_iter) train_acc_list.append(train_acc) val_acc_list.append(val_acc) train_loss_list.append(train_loss) val_loss_list.append(val_loss) torch.save(model,"Outputs/Q2/test-final/lr-2e-5_bidir-t_3lay_32hid"+str(epoch)+".pt") print(f'Epoch: {epoch+1:02}, Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%, Val. Loss: {val_loss:3f}, Val. Acc: {val_acc:.2f}%') if(val_acc>best_val_accuracy): best_val_accuracy=val_acc best_epoch=epoch print(best_epoch,best_val_accuracy) # + id="cZhlFX3eJLZa" colab_type="code" colab={} # quick evaluation of model modeltest=torch.load("Outputs/Q2/test-final/lr-2e-5_bidir-t_3lay_32hid"+str(10)+".pt") # train_loss, train_acc = train_model(modeltest, train_iter) val_loss, val_acc = eval_model(modeltest, valid_iter) print(val_acc) # + [markdown] id="lpAHygOueM2v" colab_type="text" # **LOSS PLOTS, CONFUSION MATRIX, ROC CURVES** # FOR LSTM MODEL # + id="aWl9ADKLfWrP" colab_type="code" outputId="d69e1df0-5a7b-4303-c87b-ddda25a3fca9" colab={"base_uri": "https://localhost:8080/", "height": 1000} iterfortest = data.BucketIterator.splits( (val_data), sort_key = lambda x: len(x.Text), batch_size=batch_size, device = device) def eval_modeltest(model, val_iter): total_epoch_loss = 0 total_epoch_acc = 0 model.eval() pred=[] targ=[] probpred=[] with torch.no_grad(): for idx, batch in enumerate(val_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() prediction,pred_prob = model(text) loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).sum() acc = 100.0 * num_corrects/len(batch) total_epoch_loss += loss.item() total_epoch_acc += acc.item() # print(torch.max(prediction, 1)[1]) # print(prediction.shape) # print(pred_prob.shape) sss=torch.max(prediction.cpu(), 1)[1] targ.extend(target.cpu().numpy()) pred.extend(sss.numpy()) probpred.extend(pred_prob.cpu().numpy()) return pred,targ,probpred ####### PUT UR MODEL HERE modeltest=torch.load("Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hid"+str(best_epoch)+".pt") # train_loss, train_acc = train_model(modeltest, train_iter, 1) val_loss, val_acc = eval_model(modeltest, valid_iter) print(f' Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%, Val. Loss: {val_loss:3f}, Val. Acc: {val_acc:.2f}%') ypred, ytarget,yprobpred = eval_modeltest(modeltest, valid_iter) #confusion matrix from sklearn.metrics import confusion_matrix a=confusion_matrix(ytarget, ypred) print(a) #ACCURACY PLOTS # print(train_acc_list) # print(val_acc_list) # print(train_loss_list) # print(val_loss_list) import matplotlib.pyplot as plt epochnum=list(range(1,num_epochs+1)) plt.plot(epochnum,train_acc_list,label = "Training Accuracy") plt.plot(epochnum,val_acc_list,label = "Validation Accuracy") # naming the x axis plt.xlabel('epochs') # naming the y axis plt.ylabel('Accuracies') # giving a title to my graph plt.title('Accuracy Plot') # show a legend on the plot plt.legend() # function to show the plot plt.show() #LOSS PLOTS import matplotlib.pyplot as plt2 epochnum=list(range(1,num_epochs+1)) plt2.plot(epochnum,train_loss_list,label = "Training Loss") plt2.plot(epochnum,val_loss_list,label = "Validation Loss") # naming the x axis plt2.xlabel('epochs') # naming the y axis plt2.ylabel('Losses') # giving a title to my graph plt2.title('Loss Plot') # show a legend on the plot plt2.legend() # function to show the plot plt2.show() # print("ypred") # print((ypred[0])) # print("ytarget") # print((ytarget[0])) # print("yprobpred") # print(yprobpred[0]) #ROC CURVE import scikitplot as skplt skplt.metrics.plot_roc(ytarget, yprobpred) plt.show() import scikitplot as skplt skplt.metrics.plot_roc(ytarget, yprobpred) plt.legend("") plt.show() # + [markdown] id="MFlSvFXSccLC" colab_type="text" # ## RNN + ATTENTION # # + id="FTP0RJjPyJVt" colab_type="code" colab={} # RNN MODEL + ATTENTION import torch import torch.nn as nn from torch.autograd import Variable from torch.nn import functional as F import numpy as np class rnnAttentionModel(torch.nn.Module): def __init__(self, hidden_size, output_size, vocab_size, embedding_length, embedding_weights, num_layers, bidirectional, dropout): super(rnnAttentionModel, self).__init__() """ Arguments --------- batch_size : Size of the batch which is same as the batch_size of the data returned by the TorchText BucketIterator output_size : 2 = (pos, neg) hidden_sie : Size of the hidden_state of the LSTM vocab_size : Size of the vocabulary containing unique words embedding_length : Embeddding dimension of GloVe word embeddings weights : Pre-trained GloVe word_embeddings which we will use to create our word_embedding look-up table -------- """ self.hidden_size = hidden_size self.output_size = output_size self.vocab_size = vocab_size self.embedding_length = embedding_length self.embedding_weights = embedding_weights self.num_layers = num_layers self.num_dir = 2 if bidirectional else 1 self.bidirectional = bidirectional self.dropout = dropout # Embeding Layer self.embedding = nn.Embedding(self.vocab_size, self.embedding_length, padding_idx = 0) self.embedding.weight = nn.Parameter(self.embedding_weights, requires_grad = False) self.rnn = nn.RNN(self.embedding_length, self.hidden_size, num_layers = self.num_layers, bidirectional = self.bidirectional, dropout = self.dropout) self.linear = nn.Linear(self.num_layers * self.num_dir * self.hidden_size, self.output_size) self.W_s1 = nn.Linear(2*hidden_size, 350) self.W_s2 = nn.Linear(350, 30) self.fc_layer = nn.Linear(30*2*hidden_size, 2000) self.label = nn.Linear(2000, output_size) self.softmax = nn.Softmax() def attention_net(self, lstm_output,final_state): """ Now we will incorporate Attention mechanism in our LSTM model. In this new model, we will use attention to compute soft alignment score corresponding between each of the hidden_state and the last hidden_state of the LSTM. We will be using torch.bmm for the batch matrix multiplication. Arguments --------- lstm_output : Final output of the LSTM which contains hidden layer outputs for each sequence. final_state : Final time-step hidden state (h_n) of the LSTM --------- Returns : It performs attention mechanism by first computing weights for each of the sequence present in lstm_output and and then finally computing the new hidden state. Tensor Size : hidden.size() = (batch_size, hidden_size, num_layer) lstm_output.size() = (batch_size, num_seq, hidden_size) attn_weights.size() = (batch_size, num_seq, num_layer) soft_attn_weights.size() = (batch_size, num_seq * num_layer) new_hidden_state.size() = (batch_size, hidden_size, num_layer) """ if bidirectional==False: hidden = final_state.permute(1, 2, 0) attn_weights = torch.bmm(lstm_output, hidden) soft_attn_weights = F.softmax(attn_weights.flatten(start_dim = 1), 1) new_hidden_state = torch.bmm(lstm_output.transpose(1, 2), soft_attn_weights.reshape(attn_weights.shape)) return new_hidden_state.flatten(start_dim = 1) else: #for bidirection- true attn_weight_matrix = self.W_s2(F.tanh(self.W_s1(lstm_output))) attn_weight_matrix = attn_weight_matrix.permute(0, 2, 1) attn_weight_matrix = F.softmax(attn_weight_matrix, dim=2) return attn_weight_matrix def forward(self, x): x = x.permute(1, 0) batch_size = x.shape[0] inp = self.embedding(x) inp = inp.permute(1, 0, 2) h_0 = Variable(torch.zeros(self.num_layers * self.num_dir, batch_size, self.hidden_size).cuda()) # c_0 = Variable(torch.zeros(self.num_layers * self.num_dir, batch_size, self.hidden_size).cuda()) out, (h_n) = self.rnn(inp, (h_0)) out=out.permute(1,0,2) #for bidirection- false if bidirectional==False: attn_output = self.attention_net(out,h_n) labels = self.linear(attn_output) output = self.softmax(labels) return labels,output else: attn_weight_matrix = self.attention_net(out,h_n) hidden_matrix = torch.bmm(attn_weight_matrix, out) fc_out = self.fc_layer(hidden_matrix.view(-1, hidden_matrix.size()[1]*hidden_matrix.size()[2])) logits = self.label(fc_out) output = self.softmax(logits) return logits,output # + [markdown] id="a2YhbChqkYyI" colab_type="text" # FINAL MAIN RUN -> RNN # + id="TAEo6KFXJu3i" colab_type="code" outputId="5c52df30-e916-47a9-d63b-db8482b8be4a" executionInfo={"status": "ok", "timestamp": 1584025780354, "user_tz": -330, "elapsed": 152953, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "17863093696646821487"}} colab={"base_uri": "https://localhost:8080/", "height": 851, "referenced_widgets": ["fff603ba81934bb39e1c0841b04cb03a", "d09355f53b644e7a93d844341583d42a", "d025ea0c8bae4a65ba68e09a7dae30f4", "c42c01facf2743c0a31038c76337de06", "15f0e8dc8a20444ba9aabd04e7f5742b", "e8a9c6c571974df094fd98c83b5a653c", "b8cc6d23028e48a495e6176ba58c06e5", "49b68a8a674d41db890b2542299a5a9f"]} # FINAL RUN -. RNN import os import time import torch import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import numpy as np def clip_gradient(model, clip_value): params = list(filter(lambda p: p.grad is not None, model.parameters())) for p in params: p.grad.data.clamp_(-clip_value, clip_value) def train_model(model, train_iter, epoch): total_epoch_loss = 0 total_epoch_acc = 0 model.cuda() optim = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters())) steps = 0 model.train() for idx, batch in enumerate(train_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() optim.zero_grad() prediction,pred_prob = model(text) #if using softmax # loss = loss_fn(pred_prob, target) # num_corrects = (torch.max(pred_prob, 1)[1].view(target.size()).data == target.data).sum() loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).float().sum() acc = 100.0 * num_corrects/len(batch) loss.backward() clip_gradient(model, 1e-1) optim.step() steps += 1 # if steps % 100 == 0: # print (f'Epoch: {epoch+1}, Idx: {idx+1}, Training Loss: {loss.item():.4f}, Training Accuracy: {acc.item(): .2f}%') total_epoch_loss += loss.item() total_epoch_acc += acc.item() return total_epoch_loss/len(train_iter), total_epoch_acc/len(train_iter) def eval_model(model, val_iter): total_epoch_loss = 0 total_epoch_acc = 0 model.eval() with torch.no_grad(): for idx, batch in enumerate(val_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() prediction,pred_prob = model(text) #if using softmax # loss = loss_fn(pred_prob, target) # num_corrects = (torch.max(pred_prob, 1)[1].view(target.size()).data == target.data).sum() loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).sum() acc = 100.0 * num_corrects/len(batch) total_epoch_loss += loss.item() total_epoch_acc += acc.item() return total_epoch_loss/len(val_iter), total_epoch_acc/len(val_iter) learning_rate = 2e-5 num_epochs = 40 hidden_size = 32 num_layers = 3 # batch_size change from iterator bidirectional = True momentum = 0.9 dropout = 0.5 model = rnnAttentionModel(hidden_size, output_size, vocab_size, embedding_length, embedding_weights, num_layers, bidirectional, dropout) loss_fn = F.cross_entropy pbar = tqdm(range(num_epochs)) train_acc_list=[] val_acc_list=[] train_loss_list=[] val_loss_list=[] best_val_accuracy=0 best_epoch=0 for epoch in range(num_epochs): train_loss, train_acc = train_model(model, train_iter, epoch) val_loss, val_acc = eval_model(model, valid_iter) train_acc_list.append(train_acc) val_acc_list.append(val_acc) train_loss_list.append(train_loss) val_loss_list.append(val_loss) torch.save(model,"Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hidRNN"+str(epoch)+".pt") print(f'Epoch: {epoch+1:02}, Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%, Val. Loss: {val_loss:3f}, Val. Acc: {val_acc:.2f}%') if(val_acc>best_val_accuracy): best_val_accuracy=val_acc best_epoch=epoch print(best_epoch,best_val_accuracy) # + id="9y_nV9ZjSCNE" colab_type="code" colab={} modeltest=torch.load("Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hidRNN"+str(9)+".pt") # train_loss, train_acc = train_model(modeltest, train_iter, 1) val_loss, val_acc = eval_model(modeltest, valid_iter) train_loss, train_acc = eval_model(modeltest, train_iter) print(f'Epoch: {epoch+1:02}, Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%, Val. Loss: {val_loss:3f}, Val. Acc: {val_acc:.2f}%') # Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hidRNN9.pt # + [markdown] id="2scNvrHRkTFD" colab_type="text" # **LOSS PLOTS, CONFUSION MATRIX, ROC CURVES** # FOR RNN MODEL # + id="wwlhHB6XJ7nY" colab_type="code" outputId="b0180a16-e5da-43b3-e1ba-1a6d76cb92be" colab={"base_uri": "https://localhost:8080/", "height": 1000} iterfortest = data.BucketIterator.splits( (val_data), sort_key = lambda x: len(x.Text), batch_size=batch_size, device = device) def eval_modeltest(model, val_iter): total_epoch_loss = 0 total_epoch_acc = 0 model.eval() pred=[] targ=[] probpred=[] with torch.no_grad(): for idx, batch in enumerate(val_iter): text = batch.Text target = batch.Label target = torch.autograd.Variable(target).long() if torch.cuda.is_available(): text = text.cuda() target = target.cuda() prediction,pred_prob = model(text) loss = loss_fn(prediction, target) num_corrects = (torch.max(prediction, 1)[1].view(target.size()).data == target.data).sum() acc = 100.0 * num_corrects/len(batch) total_epoch_loss += loss.item() total_epoch_acc += acc.item() # print(torch.max(prediction, 1)[1]) # print(prediction.shape) # print(pred_prob.shape) sss=torch.max(prediction.cpu(), 1)[1] targ.extend(target.cpu().numpy()) pred.extend(sss.numpy()) probpred.extend(pred_prob.cpu().numpy()) return pred,targ,probpred modeltest=torch.load("Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hid"+str(best_epoch)+".pt") # train_loss, train_acc = train_model(modeltest, train_iter, 1) val_loss, val_acc = eval_model(modeltest, valid_iter) train_loss, train_acc = eval_model(modeltest, train_iter) print(f' Train Loss: {train_loss:.3f}, Train Acc: {train_acc:.2f}%, Val. Loss: {val_loss:3f}, Val. Acc: {val_acc:.2f}%') ypred, ytarget,yprobpred = eval_modeltest(modeltest, valid_iter) #confusion matrix from sklearn.metrics import confusion_matrix a=confusion_matrix(ytarget, ypred) print(a) # import scikitplot as skplt # skplt.metrics.plot_confusion_matrix(ytarget, ypred) # plt.show() #ACCURACY PLOTS # print(train_acc_list) # print(val_acc_list) # print(train_loss_list) # print(val_loss_list) import matplotlib.pyplot as plt epochnum=list(range(1,num_epochs+1)) plt.plot(epochnum,train_acc_list,label = "Training Accuracy") plt.plot(epochnum,val_acc_list,label = "Validation Accuracy") plt.xlabel('epochs') plt.ylabel('Accuracies') plt.title('Accuracy Plot') plt.legend() plt.show() #LOSS PLOTS import matplotlib.pyplot as plt2 epochnum=list(range(1,num_epochs+1)) plt2.plot(epochnum,train_loss_list,label = "Training Loss") plt2.plot(epochnum,val_loss_list,label = "Validation Loss") plt2.xlabel('epochs') plt2.ylabel('Losses') plt2.title('Loss Plot') plt2.legend() plt2.show() # print("ypred") # print((ypred[0])) # print("ytarget") # print((ytarget[0])) # print("yprobpred") # print(yprobpred[0]) #ROC CURVE import scikitplot as skplt skplt.metrics.plot_roc(ytarget, yprobpred) plt.show() import scikitplot as skplt skplt.metrics.plot_roc(ytarget, yprobpred) plt.legend("") plt.show() # + [markdown] id="l2x5CqzHiHay" colab_type="text" # # CSV FILE GENERATOR WITH SENTIMENT CLASSES # Assumption - The input test file is a csv with text headers as "id" and "content". # + id="VfPjvdjVTUYB" colab_type="code" colab={} # preparing the test data dataset_loc = 'Data/Q2/train2_data.csv' raw_data = pd.read_csv(dataset_loc) np.random.shuffle(raw_data.values) stop_words = list(set(stopwords.words('english'))) stop_words.extend(list(set(string.punctuation))) spacy_en = spacy.load('en') sentiments = {'worry' : 0, 'happiness' : 1, 'relief' : 2, 'boredom' : 3, 'neutral' : 4, 'love' : 5, 'anger' : 6, 'empty' : 7, 'surprise' : 8, 'fun' : 9, 'enthusiasm' : 10, 'hate' : 11, 'sadness' : 12} inv_emo = dict(zip(sentiments.values(), sentiments.keys())) #preprocessing and embedding the test data contraction_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have"} def _get_contractions(contraction_dict): contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys())) return contraction_dict, contraction_re contractions, contractions_re = _get_contractions(contraction_dict) def replace_contractions(text): def replace(match): return contractions[match.group(0)] return contractions_re.sub(replace, text) def preprocess_sentence(sentence): sentence=replace_contractions(sentence) sentence = re.sub(r'(?:\@|https?\://)\S+', '', sentence).strip() sentence = word_tokenize(sentence) stemmer = SnowballStemmer('english') sentence = [(stemmer.stem(i)).lower() for i in sentence] sentence = [i for i in sentence if i not in cachedStopWords] return ' '.join(sentence) def preprocess(sentences): for i in range(len(sentences)): sentences[i] = preprocess_sentence(sentences[i]) return sentences reviews = preprocess(list(raw_data['content'])) ids = (list(raw_data['id'])) test = pd.concat([pd.Series(reviews, name = 'content'), pd.Series(ids, name = 'id')], axis = 1) test.to_csv('Data/Q2/testfilegenerate.csv', index=False) TEXT = data.Field(sequential = True, tokenize = 'spacy') LABEL = data.LabelField(dtype = torch.long, sequential = False) test_data = data.TabularDataset( path = 'Data/Q2/testfilegenerate.csv',format = 'csv', skip_header = True, fields = [('Text', TEXT), ('Label', LABEL)] ) glove_file = 'Data/Q2/glove.6B.300d.txt' TEXT.build_vocab(test_data, vectors = torchtext.vocab.Vectors(glove_file)) LABEL.build_vocab(test_data) batch_size = 50 embedding_weights = TEXT.vocab.vectors embedding_weights.cuda() vocab_size = len(TEXT.vocab) embedding_length = 300 output_size = 13 test_iter = data.BucketIterator( (test_data), sort_key = lambda x: len(x.Text), batch_size = batch_size, device = device) #finding predictions def eval_modeltest(model, test_iter): pred=[] with torch.no_grad(): for idx, batch in enumerate(test_iter): text = batch.Text if torch.cuda.is_available(): text = text.cuda() prediction,pred_prob = model(text) sss=torch.max(prediction.cpu(), 1)[1] pred.extend(sss.numpy()) return pred #load best model modelcsv=torch.load("Outputs/Q2/test-6174/lr-2e-5_bidir-t_3lay_32hid"+str(8)+".pt") all_preds=eval_modeltest(modelcsv, test_iter) import csv csv_rows=[] # generating labels in csv with open('Outputs/Q2/csv/generated.csv', mode='w') as testcsvfile: csv_writer = csv.writer(testcsvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['ID','Class']) for i in range(len(all_preds)): csv_writer.writerow([str(i+1),inv_emo[all_preds[i]]])
main.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/kalz2q/mycolabnotebooks/blob/master/haskell_lipovaca.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="11HWYhSX8JHL" # # メモ # Learn You a Haskell for Great Good! by <NAME> を jupyter notebook にしてくれた人がいる。これを colab 化する。 # # https://github.com/jamesdbrock/learn-you-a-haskell-notebook/tree/master/notebook # # いまここ # https://colab.research.google.com/github/jamesdbrock/learn-you-a-haskell-notebook/blob/master/notebook/02-starting-out.ipynb # + id="u8BK7s-v9R6o" # 準備 # %%capture # !apt install haskell-platform # + id="eMR9fs65-M3I" colab={"base_uri": "https://localhost:8080/"} outputId="24c0c135-dd7a-447c-8820-ff19281f9477" # !ghc -e 'putStrLn "hello world!"' # + id="06N_qZSm-Ng0" # ファイルを作る # %%writefile hello.hs main = putStrLn "hello, world" # + id="Cmw4Q8vV-RGh" # !runghc hello.hs # + id="WROVZMZ0Bl_8" colab={"base_uri": "https://localhost:8080/", "height": 181} outputId="e0006102-40bb-40ed-8a37-b48bbaa1a7ec" language="html" # <table border="1"> # <thead> # <tr><th>キーボードショートカット </th><th> 作 用 </th></tr> # </thead> # <tbody> # <tr><td>Shift+Enter </td><td> 実行して次のセルに移る </td></tr> # <tr><td>Ctrl+Enter </td><td> 実行してそのセルに留まる </td></tr> # <tr><td>Alt+Enter </td><td> 実行して次に新しいセルを作って移る </td></tr> # <tr><td>Enter </td><td> セルを編集する </td></tr> # <tr><td>Ctrl+Shift+Enter </td><td> 選択範囲を全て実行する </td></tr> # <tr><td>Ctrl+Shift+- </td><td> カーサーポジションでセルを分割する</td></tr> # </tbody> # </table> # + [markdown] id="Ofw8HkU4_66G" # Here's some simple arithmetic. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="nQDSlSkL_66G" # !ghc -e '2 + 15' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="QNI5QMaO_66H" # !ghc -e '49 * 100' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="FB31kju8_66I" # !ghc -e '1892 - 1472' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="gpx8ai_h_66I" # !ghc -e '5 / 2' #=> 2.5 になる # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="Vc08RRfS_66J" # !ghc -e '(50 * 100) - 4999' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="JYSOYB-Z_66K" # !ghc -e '50 * 100 - 4999' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="r43BCjRU_66K" # !ghc -e '50 * (100 - 4999)' # + id="usrAOlpHDtJM" # 次のコードはエラーになる # マイナス符号がついた数値は括弧で囲む必要がある # %%script false # !ghc -e '5 * -3' # + id="xr0hY2zVD41y" # !ghc -e '3 == 4' #=> False と出力される # + id="NuCc20DyEHud" # !ghc -e 'True || False' #=> True # + id="lG4kjiaDElN0" # !ghc -e 'False && False' #=> False # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="iQhTGA5m_66L" # !ghc -e 'True' #=> True # + id="z4yHtkW0E8n_" magic_args="False" language="script" # !ghc -e 'true' #=> error Variable not in scope: true # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="tgFzeSu3_66M" # !ghc -e 'not False' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="cZ4vOEBr_66M" # !ghc -e 'not (True && True)' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="sp9IOGai_66N" # !ghc -e '5 == 5' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="y7qldU1y_66N" # !ghc -e '1 == 0' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="l1kHrjdD_66O" # !ghc -e '5 /= 5' #=> False `/=` は not equal の意味 # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="I58XZ1L2_66O" # !ghc -e '5 /= 4' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="_DCMlZk3_66O" # !ghc -e '"hello" == "hello"' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="w-d5Zm2__66O" # 次のコードはエラーになる # # %%script false の行を消して実行してエラーを確認すること # %%script false # !ghc -e '5 + "llama"' # + id="za-sZ6iCNqTm" # 文字列の連結は `++` を用いる # !ghc -e '"5" ++ "llama"' #=> 5llama # + id="6SS5Y4CXN0Pl" # Haskell のエラーは比較的親切 # `+` は両辺の引数が number でなければならない # `==` は両辺のデータの型が同じで比較可能なこと # 5 + 4.0 の場合は整数と浮動小数点数の足し算で浮動小数点数になる # + id="ieqlUnkiXLSx" # `*` のように数字と数字の間に置かれて作用する関数を中置関数 infix function と呼ぶ # 他の殆どの関数は前置 prefix function である # Haskell では前置関数の後にスペースを入れて引数を書く。括弧は要らない # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="5jRmWm8c_66P" # succ 関数は順序の定義された型を引数に取り次に来る値を返す # !ghc -e 'succ 8' # !ghc -e 'pred 8' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="IcPl9WGQ_66Q" # min , max 関数は引数をそれぞれ 2つ取る # !ghc -e 'min 9 10' # !ghc -e 'min 3.4 3.2' # !ghc -e 'max 100 101' # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="vf5dGTbQ_66Q" colab={"base_uri": "https://localhost:8080/"} outputId="7be7f5d1-da4e-41ab-a5c4-2d6d36b08b2c" # 関数の優先順位が最も高い # !ghc -e 'succ 9 + max 5 4 + 1' #=> 16 # !ghc -e '(succ 9) + (max 5 4) + 1' #=>16 # !echo # !ghc -e 'succ 9 * 10' #=> 100 # !ghc -e 'succ (9 * 10)' #=> 91 # + id="NI0PFae20L6C" # 前置関数を中置関数として使うとわかりやすい # 前置関数を中置関数として使う方法 => バッククオートで囲む # !ghc -e 'div 92 10' #=> 9 # !ghc -e '92 `div` 10' #=> 9 # + id="3sGhw4MZ1IBH" # Haskell で `bar (bar 3)` は括弧が必須の言語で言えば `bar(bar(3))` に当たることを理解すること # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="sFYhFRJC_66R" # 関数の作り方 # 関数名と変数と `=` とその後に定義を書く # !ghc -e 'doubleMe x = x + x' # + colab={"base_uri": "https://localhost:8080/"} id="e1npC11e25eQ" outputId="e64e660e-ddc5-4b90-d0a3-9c901e82e7d0" # コマンドラインワンライナーで Haskell で関数定義して使う # 次のようには書けない # # !ghc -e 'doubleMe x = x + x; doubleMe 9' # `let in` を使う # !ghc -e 'let doubleMe x = x + x in doubleMe 9' #=> 18 # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="93ulsol4_66S" outputId="c18f8a39-911f-4fc8-d233-bd607dff2373" colab={"base_uri": "https://localhost:8080/"} # 引数を 2つ取る関数 # !ghc -e 'doubleUs x y = x*2 + y*2' # !ghc -e 'let doubleUs x y = x*2 + y*2 in doubleUs 4 9' # 定義が複数あるとき波括弧とセミコロンでまとめられる # Haskellの関数は特定の順序である必要はないので、最初にdoubleMeを定義し、 # 次にdoubleUsを定義するか、その逆にするかは問題ではありません。 # !ghc -e 'let {doubleUs x y = doubleMe x + doubleMe y; doubleMe x = x + x} in doubleUs 4 9' # + id="AkM_UIdOKx9v" outputId="e85af0d4-ff8f-46e5-e801-ff5bd9db9cd1" colab={"base_uri": "https://localhost:8080/"} # プログラムファイルを作って実行する # %%writefile temp.hs main = doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y putStrLin doubleUs 28 88 + doubleMe 123' # + id="UIADvhuZXUgB" outputId="c1183481-e16d-4553-fb53-dc0ea37a0169" colab={"base_uri": "https://localhost:8080/"} # 実験 プログラムファイルを作って実行する # %%writefile temp.hs doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y main = print $ doubleUs 28 88 + doubleMe 123 # + id="U13OrHwsLW1N" outputId="40ea61cf-6be9-4042-94d2-aa12def7d8af" colab={"base_uri": "https://localhost:8080/"} # !runghc temp.hs #=> 56+176+246 # !ghc -e '56+176+246' # + id="kScsCRUmghF_" # 次に、数値に2を掛ける関数を作成しますが、100より大きい数値はそのままで十分な大きさであるため、 # その数値が100以下の場合に限ります。 # %%script false doubleSmallNumber x = if x > 100 then x else x*2 # + colab={"base_uri": "https://localhost:8080/"} id="iEW-CplZu2GS" outputId="fb1ea452-5bb8-478a-9d5a-147ceb499970" # !ghc -e 'let doubleSmallNumber x = if x > 100 then x else x*2 in doubleSmallNumber 42' # + id="0WO0eMdFwUZG" # Haskell の if ステートメントは、else部 分が必須である # Haskell ではすべての式と関数が何かを返す必要があります # Haskellの if ステートメントは式であり、常に何かを返します # 前の関数で生成されたすべての数値に1を追加したい場合は、その本体をこのように書くことができます。 # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="fKi0Sp6c_66T" magic_args="false" language="script" # doubleSmallNumber' x = (if x > 100 then x else x*2) + 1 # + colab={"base_uri": "https://localhost:8080/"} id="aIcB-nPsxhZI" outputId="6d773df1-70a1-44ef-f812-1b2aa20d4fd3" # !ghc -e "let doubleSmallNumber' x = (if x > 100 then x else x*2) + 1 in doubleSmallNumber' 42" # + id="5Gv1jpMGxdc-" # このテキストではこのように関数をちょっと変更した時に関数名の末尾に # アポストロフィ `'` をつけることにしている # コマンドラインワンライナーにする際、通常文字列をワンクオート (= アポストロフィ) # で囲むのでこれはトラブルの原因になるのでよろしくない # functionname02 とかにする # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="kZQLauwV_66U" colab={"base_uri": "https://localhost:8080/"} outputId="5f0afa74-2e1c-4186-8ffa-3799ef34f457" # パラメーター なしの関数 # %%writefile temp.hs conanO'Brien = "It's a-me, Conan O'Brien!" main = putStrLn conanO'Brien # + colab={"base_uri": "https://localhost:8080/"} id="LtNPLto1zada" outputId="1fede8d6-714e-4ae8-cfc5-3a05de459a66" # !runghc temp.hs # + id="9CFXx4FGzz1G" # 上の関数はパラメーターをとらない例である # 関数名は大文字で始めることが出来ない # パラメーターを受け取らない関数は通常定義(名前)である、と言う # Haskell は意味を変更出来ないため # conanO'Brienと文字列「It'sa-me、ConanO'Brien!」 を互換的に使用できます # + colab={"base_uri": "https://localhost:8080/"} id="89fdbI6R0pvS" outputId="85f5bc44-07a4-4799-d14d-1d820db9e7ee" # しかし!!!! アポストロフィは面倒なので外してみる!!!! # !ghc -e 'let conanOBrien = "Its a-me, Conan OBrien!" in putStrLn conanOBrien' # + [markdown] id="FoM-FaDF3rgF" # --- # リスト # + id="omwh-pk64AaP" # 連続した整数のリストは範囲を使って次のように書く # %%script false [1..20] # + id="Tyis9Le64INb" outputId="74a6b951-49ab-4579-92db-ed6d0202852d" colab={"base_uri": "https://localhost:8080/"} # !ghc -e '[1..20]' # !ghc -e "['a'..'z']" # !ghc -e "['K'..'Z']" # + id="zRTI9QvG_66e" outputId="65792924-fec4-4216-8835-0e4cf03efc19" colab={"base_uri": "https://localhost:8080/"} # 範囲にステップを指定する方法 # !ghc -e '[2,4..20]' # !ghc -e '[3,6..20]' # + id="4C92QDBB5dsx" outputId="0dc6cadd-56a7-4829-f586-cae7a9b082cb" colab={"base_uri": "https://localhost:8080/"} # 等差数列にしか使えないみたい # マイナスは出来る [20,19..1] # 小数点の差はどうするのか #=> 使わない方が良い # !ghc -e '[0.1, 0.3 .. 1]' # + id="O3S5cL5Q7x8p" colab={"base_uri": "https://localhost:8080/"} outputId="a62cef6c-e470-415e-dd79-ed47d74c138b" # 無限リスト # Haskell は lazy なので無限リストは使う時まで評価しない # 例えば 13 の倍数のリストの最初の 24個が欲しいとする # 範囲 range で上限を指定しないと無限リストになる # !ghc -e '[13,26 .. 13*24]' # !ghc -e 'take 24 [13,26 ..]' # + colab={"base_uri": "https://localhost:8080/"} id="SDkmxahDKJjS" outputId="aa80607c-897a-4cd1-d75e-2636ae628df3" # 無限リストを生成する関数 # cycle は与えられたリストを無限に繰り返す # !ghc -e 'take 10 (cycle [1,2,3])' # !ghc -e 'take 12 (cycle "LOL ")' # + colab={"base_uri": "https://localhost:8080/"} id="sCWuQVnELloi" outputId="704aeaad-52ce-4e18-a14b-d0946ee3c3bd" # repeat # !ghc -e 'take 10 (repeat 5)' # !ghc -e 'take 10 (repeat "LOL")' # 単一要素の繰り返せは replicate の方が便利だろう # !ghc -e 'replicate 3 10' # !ghc -e 'replicate 3 "LOL"' # + [markdown] id="YEW7zMeF2V-j" # # いまここ # + [markdown] id="caViNeJrOpNx" # $ S=\{2 \centerdot x | x \in \mathbb{N}, x \le 10 \}$ # + id="hrd1q5xiMO2z" # 内包表記 list comprehension # 数学で集合を習った時に次のような あなたが今までに取ったことがあれば 数学のコースでは、おそらく*セットの理解*に遭遇したことがあります。 それらは通常、一般的なものからより具体的なセットを構築するために使用されます セット。最初の10個を含むセットの基本的な理解 自然数は$S= \ {2 \ centerdot x | x \ in \ mathbb {N}、x \ le 10\}$。前の部分 パイプは出力関数と呼ばれ、 `x`は変数、`N`は 入力セットと`x<=10`が述語です。つまり、セット 述語を満たすすべての自然数の倍精度が含まれます。 Haskellでそれを書きたいのなら、`takeのようなことをすることができます 10 [2,4..]`。しかし、最初の10個のナチュラルの2倍が必要ない場合はどうなりますか 数字ですが、ある種のより複雑な関数がそれらに適用されていますか?我々は出来た そのためにリスト内包を使用してください。リスト内包表記は非常に似ています 理解度を設定します。最初の10個の偶数を取得することに固執します 今のところ。使用できるリスト内包表記は`[x* 2 | x<-[1..10]]`。 `x`は`[1..10]`から引き出され、`[1..10]`のすべての要素に対して( `x`にバインドされている場合、その要素を取得しますが、2倍になります。これが 実行中の理解。 # + [markdown] id="IEjFunlp_66g" # If you've ever taken a # course in mathematics, you've probably run into *set comprehensions*. # They're normally used for building more specific sets out of general # sets. A basic comprehension for a set that contains the first ten even # natural numbers is # # $ S=\{2 \centerdot x | x \in \mathbb{N}, x \le 10 \}$ # # . The part before # the pipe is called the output function, `x` is the variable, `N` is the # input set and `x <= 10` is the predicate. That means that the set # contains the doubles of all natural numbers that satisfy the predicate. # # If we wanted to write that in Haskell, we could do something like `take # 10 [2,4..]`. But what if we didn't want doubles of the first 10 natural # numbers but some kind of more complex function applied on them? We could # use a list comprehension for that. List comprehensions are very similar # to set comprehensions. We'll stick to getting the first 10 even numbers # for now. The list comprehension we could use is `[x*2 | x <- [1..10]]`. # `x` is drawn from `[1..10]` and for every element in `[1..10]` (which we have # bound to `x`), we get that element, only doubled. Here's that # comprehension in action. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="kZpiXKhD_66g" [x*2 | x <- [1..10]] # + [markdown] id="VgUf-L9f_66g" # As you can see, we get the desired results. Now let's add a condition # (or a predicate) to that comprehension. Predicates go after the binding # parts and are separated from them by a comma. Let's say we want only the # elements which, doubled, are greater than or equal to 12. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="iZfR0CMZ_66g" [x*2 | x <- [1..10], x*2 >= 12] # + [markdown] id="0G_YJazS_66g" # Cool, it works. How about if we wanted all numbers from 50 to 100 whose # remainder when divided with the number 7 is 3? Easy. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="3-qVlQOX_66g" [ x | x <- [50..100], x `mod` 7 == 3] # + [markdown] id="tynpbm6h_66h" # Success! Note that weeding out lists by predicates is also called # *filtering*. We took a list of numbers and we filtered them by the # predicate. Now for another example. Let's say we want a comprehension # that replaces each odd number greater than 10 with `"BANG!"` and each odd # number that's less than 10 with `"BOOM!"`. If a number isn't odd, we throw # it out of our list. For convenience, we'll put that comprehension inside # a function so we can easily reuse it. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="hR9uQ8U1_66h" boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x] # + [markdown] id="UjTDYf6Z_66h" # The last part of the comprehension is the predicate. The function [`odd`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:odd) # returns [`True`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:True) on an odd number and [`False`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:False) on an even one. The element is # included in the list only if all the predicates evaluate to [`True`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:True). # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="L3BcG5N8_66h" boomBangs [7..13] # + [markdown] id="SnBX6CwC_66h" # We can include several predicates. If we wanted all numbers from 10 to # 20 that are not 13, 15 or 19, we'd do: # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="_oYbozbl_66i" [ x | x <- [10..20], x /= 13, x /= 15, x /= 19] # + [markdown] id="3iBLk3lL_66i" # Not only can we have multiple predicates in list comprehensions (an # element must satisfy all the predicates to be included in the resulting # list), we can also draw from several lists. When drawing from several # lists, comprehensions produce all combinations of the given lists and # then join them by the output function we supply. A list produced by a # comprehension that draws from two lists of length 4 will have a length # of 16, provided we don't filter them. If we have two lists, `[2,5,10]` and # `[8,10,11]` and we want to get the products of all the possible # combinations between numbers in those lists, here's what we'd do. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="T0NJ_Qfl_66i" [ x*y | x <- [2,5,10], y <- [8,10,11]] # + [markdown] id="VbhxYLLh_66i" # As expected, the length of the new list is 9. What if we wanted all # possible products that are more than 50? # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="mAN2MmPj_66i" [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50] # + [markdown] id="HcQ0FCZ3_66i" # How about a list comprehension that combines a list of adjectives and a # list of nouns … for epic hilarity. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="UBgajw85_66j" let nouns = ["hobo","frog","pope"] let adjectives = ["lazy","grouchy","scheming"] [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns] # + [markdown] id="LbM5l5Fi_66j" # I know! Let's write our own version of [`length`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:length)! We'll call it `length'`. # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="LcbJ49A6_66j" length' xs = sum [1 | _ <- xs] # + [markdown] id="cfgUEGGF_66j" # `_` means that we don't care what we'll draw from the list anyway so # instead of writing a variable name that we'll never use, we just write # `_`. This function replaces every element of a list with `1` and then sums # that up. This means that the resulting sum will be the length of our # list. # # Just a friendly reminder: because strings are lists, we can use list # comprehensions to process and produce strings. Here's a function that # takes a string and removes everything except uppercase letters from it. # + attributes={"classes": ["haskell:", "hs"], "id": "", "name": "\"code\""} id="4Lk4pTCg_66j" removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']] # + [markdown] id="uySh9hDs_66j" # Testing it out: # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="_aDBjpBY_66j" removeNonUppercase "Hahaha! Ahahaha!" # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="EXl_OWPS_66k" removeNonUppercase "IdontLIKEFROGS" # + [markdown] id="1nFNrTj4_66k" # The predicate here does all the work. It says that the character will be # included in the new list only if it's an element of the list `['A'..'Z']`. # Nested list comprehensions are also possible if you're operating on # lists that contain lists. A list contains several lists of numbers. # Let's remove all odd numbers without flattening the list. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="wWw5iLTb_66k" let xxs = [[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]] [ [ x | x <- xs, even x ] | xs <- xxs] # + [markdown] id="BeSOvR5N_66k" # You can write list comprehensions across several lines. It's better to split longer list comprehensions across multiple # lines, especially if they're nested. # # Tuples # ------ # # <img src="https://github.com/kalz2q/mycolabnotebooks/blob/master/img/tuple.png?raw=1" title="tuples" style="float:right;margin-left:2em;" /> # # In some ways, tuples are like lists — they are a way to store several # values into a single value. However, there are a few fundamental # differences. A list of numbers is a list of numbers. That's its type and # it doesn't matter if it has only one number in it or an infinite amount # of numbers. Tuples, however, are used when you know exactly how many # values you want to combine and its type depends on how many components # it has and the types of the components. They are denoted with # parentheses and their components are separated by commas. # # Another key difference is that they don't have to be homogenous. Unlike # a list, a tuple can contain a combination of several types. # # Think about how we'd represent a two-dimensional vector in Haskell. One # way would be to use a list. That would kind of work. So what if we # wanted to put a couple of vectors in a list to represent points of a # shape on a two-dimensional plane? We could do something like # `[[1,2],[8,11],[4,5]]`. The problem with that method is that we could also # do stuff like `[[1,2],[8,11,5],[4,5]]`, which Haskell has no problem with # since it's still a list of lists with numbers but it kind of doesn't # make sense. But a tuple of size two (also called a pair) is its own # type, which means that a list can't have a couple of pairs in it and # then a triple (a tuple of size three), so let's use that instead. # Instead of surrounding the vectors with square brackets, we use # parentheses: `[(1,2),(8,11),(4,5)]`. What if we tried to make a shape like # `[(1,2),(8,11,5),(4,5)]`? Well, we'd get this error: # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="VrwFTxtm_66k" [(1,2),(8,11,5),(4,5)] # + [markdown] id="q6vkdaHk_66l" # It's telling us that we tried to use a pair and a triple in the same # list, which is not supposed to happen. You also couldn't make a list # like `[(1,2),("One",2)]` because the first element of the list is a pair # of numbers and the second element is a pair consisting of a string and a # number. Tuples can also be used to represent a wide variety of data. For # instance, if we wanted to represent someone's name and age in Haskell, # we could use a triple: `("Christopher", "Walken", 55)`. As seen in this # example, tuples can also contain lists. # # Use tuples when you know in advance how many components some piece of # data should have. Tuples are much more rigid because each different size # of tuple is its own type, so you can't write a general function to # append an element to a tuple — you'd have to write a function for # appending to a pair, one function for appending to a triple, one # function for appending to a 4-tuple, etc. # # While there are singleton lists, there's no such thing as a singleton # tuple. It doesn't really make much sense when you think about it. A # singleton tuple would just be the value it contains and as such would # have no benefit to us. # # Like lists, tuples can be compared with each other if their components # can be compared. Only you can't compare two tuples of different sizes, # whereas you can compare two lists of different sizes. Two useful # functions that operate on pairs: # # __[`fst`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:fst)__ takes a pair and returns its first component. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="UmMwrzoa_66l" fst (8,11) # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="9tmLV3wQ_66l" fst ("Wow", False) # + [markdown] id="glyf1-Cz_66l" # __[`snd`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:snd)__ takes a pair and returns its second component. Surprise! # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="PZ0XbQzt_66l" snd (8,11) # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="1zMkhARp_66l" snd ("Wow", False) # + [markdown] id="JajSw-nc_66m" # > __Note:__ these functions operate only on pairs. They won't work on # > triples, 4-tuples, 5-tuples, etc. We'll go over extracting data from # > tuples in different ways a bit later. # # A cool function that produces a list of pairs: __[`zip`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:zip)__. It takes two lists # and then zips them together into one list by joining the matching # elements into pairs. It's a really simple function but it has loads of # uses. It's especially useful for when you want to combine two lists in a # way or traverse two lists simultaneously. Here's a demonstration. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="3UxrMwyk_66m" zip [1,2,3,4,5] [5,5,5,5,5] # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="suoVp7-B_66m" zip [1 .. 5] ["one", "two", "three", "four", "five"] # + [markdown] id="zrXDEKbY_66m" # It pairs up the elements and produces a new list. The first element goes # with the first, the second with the second, etc. Notice that because # pairs can have different types in them, [`zip`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:zip) can take two lists that # contain different types and zip them up. What happens if the lengths of # the lists don't match? # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="ejj3sfUg_66m" zip [5,3,2,6,2,7,2,5,4,6,6] ["im","a","turtle"] # + [markdown] id="YyBxXy4L_66m" # The longer list simply gets cut off to match the length of the shorter # one. Because Haskell is lazy, we can zip finite lists with infinite # lists: # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="DxPRHC5q_66m" zip [1..] ["apple", "orange", "cherry", "mango"] # + [markdown] id="CpqEsBSc_66n" # <img src="https://github.com/kalz2q/mycolabnotebooks/blob/master/img/pythag.png?raw=1" title="look at meee" style="margin-left:auto;margin-right:auto;" /> # # Here's a problem that combines tuples and list comprehensions: which # right triangle that has integers for all sides and all sides equal to or # smaller than 10 has a perimeter of 24? First, let's try generating all # triangles with sides equal to or smaller than 10: # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="nHJLf7ts_66n" let triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ] # + [markdown] id="nFtbJIvK_66n" # We're just drawing from three lists and our output function is combining # them into a triple. If you evaluate that by typing out `triangles` in # GHC, you'll get a list of all possible triangles with sides under or # equal to 10. Next, we'll add a condition that they all have to be right # triangles. We'll also modify this function by taking into consideration # that side b isn't larger than the hypotenuse and that side a isn't # larger than side b. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="Auu9Uc-j_66n" let rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2] # + [markdown] id="bYyaj653_66n" # We're almost done. Now, we just modify the function by saying that we # want the ones where the perimeter is 24. # + attributes={"classes": ["haskell:", "ghci"], "id": "", "name": "\"code\""} id="WvEXeId7_66n" let rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24] rightTriangles' # + [markdown] id="v7D1jLDP_66n" # And there's our answer! This is a common pattern in functional # programming. You take a starting set of solutions and then you apply # transformations to those solutions and filter them until you get the # right ones.
haskell_lipovaca.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:insight] * # language: python # name: conda-env-insight-py # --- # ## Unit operations to access the raw data and label file from file_io import * import os import numpy as np import pandas as pd import mne import matplotlib.pyplot as plt # relabeling config LEN_PRE = 15 LEN_POS = 60 SEC_GAP = 0 # + train_path = '../tusz_1_5_2/edf/train' tcp_type = '01_tcp_ar' patient_group = '004' patient = '00000492' session = 's003_2003_07_18' token = '<PASSWORD>' token_path = os.path.join(train_path, tcp_type, patient_group, patient, session, token) # Read 1 token file fsamp_mont, sig_mont, labels_mont = read_1_token(token_path) np.shape(fsamp_mont), np.shape(sig_mont), np.shape(labels_mont) # - # Sort channels if montages are different sig_mont = sort_channel(sig_mont, labels_mont, STD_CHANNEL_01_AR) np.shape(sig_mont) # Intervals that have been annotated # 00000492_s003_t001 0.0000 33.1425 bckg 1.0000 # 00000492_s003_t001 33.1425 53.0000 seiz 1.0000 # 00000492_s003_t001 53.0000 184.0000 bckg 1.0000 intvs, labls = load_tse_bi(token_path) np.shape(intvs), np.shape(labls) # Relabel intervals by assigning pre-seizure stage # pre-seizure stage is defined as SEC_GAP seconds preceding the seizure intvs, labls = relabel_tse_bi(intvs=intvs, labels=labls, len_pre=LEN_PRE, len_post=LEN_POS, sec_gap=SEC_GAP) np.shape(intvs), np.shape(labls) # ## Segment data into 1 second per piece # # 1. Chop seizure # Comparing the sampling rate, time and annotated time, we extract some chunks of seizure signal. # 2. Chop pre-ictal # Chop from 10 to 20 seconds preceding seizures. # 3. Chop background # 10 minutes preceding seizures and 10 minutes after seizures. # Segment data into 1 second per piece fsamp = int(np.mean(fsamp_mont)) dataset, labels = signal_to_dataset(raw=sig_mont, fsamp=fsamp, intvs=intvs, labels=labls) print('before:\t', np.shape(sig_mont)) print('after:\t', np.shape(dataset)) assert np.shape(dataset)[0] == np.shape(labels)[0] # # Gotcha: montage issue # For each edf file, we cannot assume the first channel is always the same physical location of electrode. # 1. Set some standard label and order. # Ideally I can use data.frame, however I will first see what format others used. The order can be arbitrary, but I will see what other used first. # 2. Read edf file and its montage, # This can be done using the aforementioned functions from pystream # 3. Convert edf reading to standard format. # This can be done using numpy and panda
notebooks/data-examples.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %pylab inline import pandas as pd import seaborn as sns # <h3>Load the CSV file into memory</h3> df = pd.read_csv('uber-raw-data-apr14.csv') df.head() df['Date/Time'] = df['Date/Time'].map(pd.to_datetime) df.head() # <p>Date and time helper functions</p> # + def get_day_of_month(dt): return dt.day def get_weekday(dt): return dt.weekday() def get_hour(dt): return dt.hour # - df['day_of_month'] = df['Date/Time'].map(get_day_of_month) df['weekday'] = df['Date/Time'].map(get_weekday) df['hour'] = df['Date/Time'].map(get_hour) df.head() # <h3>Date Anaylsis</h3> hist(df.day_of_month, bins=30, rwidth=.8, range=(0.5, 30.5)) xlabel('date of the month') ylabel('frequency') title("Frequency by Day of Month - Uber April 2014") ; # + def count_rows(rows): return len(rows) calls_by_date = df.groupby('day_of_month').apply(count_rows) calls_sorted_by_date = calls_by_date.sort_values() # - bar(range(1,31), calls_sorted_by_date) xticks(range(1,31), calls_sorted_by_date.index) ; # ### Analyse the hour hist(df.hour, bins=24, rwidth=.8, range=(-.5,23.5)) ; # ### Analyse the weekday hist(df.weekday, bins=7, range=(-.5, 6.5), rwidth=.8, color='#AA5533', alpha=.4) ; # ### Analysis hour vs day_of_month hour_matrix = df.groupby('hour weekday'.split()).apply(count_rows).unstack() sns.heatmap(hour_matrix) ; # ### Analysis of Latitude and Longitude hist(df['Lon'], bins=100, range=(-74.1, -73.9), color='green', alpha=.5, label='Longitude') grid() legend(loc='upper left') twiny() hist(df['Lat'], bins=100, range=(40.5, 41), color='red', alpha=.5, label='Latitude') legend(loc='best') # ### Geo plot the data figure(figsize=(20, 20)) plot(df['Lon'], df['Lat'], '.', alpha=.5) xlim(-74.2, -73.7) ylim(40.7, 41) ;
uber_analysis_apr14/Uber analysis apr 14.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import datetime from finrl.config import config from finrl.marketdata.yahoodownloader import YahooDownloader from finrl.preprocessing.preprocessors import FeatureEngineer from finrl.preprocessing.data import data_split from finrl.env.env_stocktrading import StockTradingEnv from finrl.model.models import DRLAgent from finrl.trade.backtest import backtest_stats, backtest_plot, get_daily_return, get_baseline from stable_baselines3.common.vec_env import VecCheckNan from pprint import pprint import sys import itertools import os today = datetime.datetime.today() # os.environ['CUDA_VISIBLE_DEVICES'] = ARGS.gpu processed_full = pd.read_csv("data/datasets/processed_sz50.csv") start_date = '2009-01-01' end_date = '2019-01-01' trade_date = '2021-01-01' train = data_split(processed_full, start_date, end_date) trade = data_split(processed_full, end_date, trade_date) print(len(train)) print(len(trade)) stock_dimension = len(train.tic.unique()) state_space = 1 + 2*stock_dimension + len(config.TECHNICAL_INDICATORS_LIST)*stock_dimension print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}") data_turbulence = processed_full[(processed_full.date< end_date) & (processed_full.date>=start_date)] insample_turbulence = data_turbulence.drop_duplicates(subset=['date']) turbulence_threshold = np.quantile(insample_turbulence.turbulence.values,1) print("turbulence_threshold:", turbulence_threshold) env_kwargs = { "hmax": 100, "initial_amount": 1000000, "buy_cost_pct": 0.001, "sell_cost_pct": 0.001, "state_space": state_space, "stock_dim": stock_dimension, "tech_indicator_list": config.TECHNICAL_INDICATORS_LIST, "action_space": stock_dimension, "reward_scaling": 1e-4 } e_train_gym = StockTradingEnv(df = train, **env_kwargs) env_train, _ = e_train_gym.get_sb_env() print(type(env_train)) agent = DRLAgent(env = env_train) # + def get_model(model_name): if model_name == "s2c" or model_name == "ddpg": model = agent.get_model(model_name) elif model_name == "ppo": PPO_PARAMS = { "n_steps": 2048, "ent_coef": 0.01, "learning_rate": 0.00025, "batch_size": 128, } model = agent.get_model(model_name, model_kwargs = PPO_PARAMS) elif model_name == 'td3': TD3_PARAMS = {"batch_size": 100, "buffer_size": 1000000, "learning_rate": 0.001} model = agent.get_model("td3",model_kwargs = TD3_PARAMS) elif model_name == 'sac': SAC_PARAMS = { "batch_size": 128, "buffer_size": 1000000, "learning_rate": 0.0001, "learning_starts": 100, "ent_coef": "auto_0.1", } model = agent.get_model("sac",model_kwargs = SAC_PARAMS) return model model_path = "./trained_models/" def train(model_name, total_timesteps): model = get_model(model_name) trained = agent.train_model(model=model, tb_log_name=model_name, total_timesteps=total_timesteps) trained.save(model_path + model_name) return trained def load(model_name): return agent.load_model(model_name,model_path+ model_name) def load_or_train(model_name, total_timesteps = 30000): if os.path.exists(model_path + model_name + ".zip"): print("load " + model_name) return load(model_name) else: return train(model_name, total_timesteps) #train("a2c", 100000) #train("ddpg", 50000) #train("ppo", 50000) #train("td3", 30000) #train("sac", 80000) # + # train model #train("td3", 10) #m = load_or_train("ddpg", 10) #m = load_or_train("ppo", 50000) #m = load_or_train("ddpg", 50000) # m = load_or_train("sac", 80000) m = load_or_train("ddpg", 2) print(m) # simulate for trade e_trade_gym = StockTradingEnv(df = trade, turbulence_threshold = turbulence_threshold, **env_kwargs) df_account_value, df_actions = DRLAgent.DRL_prediction( model=m, environment = e_trade_gym) print(df_account_value) print(df_actions) # + print("==============Get Backtest Results===========") now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M') perf_stats_all = backtest_stats(account_value=df_account_value) perf_stats_all = pd.DataFrame(perf_stats_all) perf_stats_all.to_csv("./"+config.RESULTS_DIR+"/perf_stats_all_"+now+'.csv') # -
astock.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Unveiling a classification model- Whether the patient is at diabetes risk or not. # 1. for Data Scientist[to understand underlying patterns discovered by the model] using `Boolean Rule Column Generation` explained provided by AI 360 Explainability Toolkit. # 2. For doctors- to compare similar profile using `Protodash Explainer.` # 3. For patient- what do they need to be not at risk using `Contrastive Explanations Method` (CEM) algorithm using AI Explainability 360 on Diabetes Data. # # ### Install the required Libraries. # Uncomment them and Run the Cells # + # # !pip install aix360 # + # # !pip install lightgbm # + # # !pip install pandas_profiling # + # # !pip install keras # - # ## Part-1 Boolean Rule Column Generation explainer # Using the `Diabetes Data`, we will do # # - Exploratory Data Analysis # - Build Lightgbm model. # - Feature importance. # - Unveiling Fraud Detection AI Model for Data Scientist using `Boolean Rule Column Generation explainer` provided by AI 360 Explainability Toolkit. # ### Import the Libraries. import numpy as np import pandas as pd import matplotlib.pyplot as plt import ipaddress import pandas_profiling as pp # %matplotlib inline from sklearn import preprocessing plt.rc("font", size=14) import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import warnings warnings.filterwarnings("ignore") import time from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split import lightgbm as lgb from lightgbm import LGBMClassifier import seaborn as sns sns.set(style="white") sns.set(style="whitegrid", color_codes=True) # #### Load the `Diabetes-Data` as csv in the notebook. # # * Click on the `0100` on the top right corner. # * Drag and Drop `diabetes-data.csv` # * Select the Cell below. # * Click on `Insert to Code` and then `Pandas Dataframe.` # + #load the data here # - # As we can see, some of the columns have zero values to it. Insulin have zeros, Skin thickness is zero which is not possible. Let's check all the columns having zeros and treat them. df.hist(color='green', figsize=(20,15)); # - SkinThickness, Insulin is right skewed. # - BMI, and BloodPressure is normally distributed. # - Glucose is left skewed. # - is normally distributed like BMI, and BloodPressure. If we fill zeros with median of that columns, we wouldn't disrupt the data. For left, and right skewed data, we can fill zeros with median of that columns. df_treated = df.copy() df_treated['Insulin'].replace(0, df_treated['Insulin'].median(), inplace=True) df_treated['SkinThickness'].replace(0, df_treated['SkinThickness'].median(), inplace=True) df_treated['BMI'].replace(0, df_treated['BMI'].mean(), inplace=True) df_treated['Glucose'].replace(0, df_treated['Glucose'].median(), inplace=True) df_treated['BloodPressure'].replace(0,df_treated['BloodPressure'].mean(), inplace=True) # + # pp.ProfileReport(df_treated) # - count_Diabet_risk = len(df[df['Outcome']==0]) count_non_Diabet_risk = len(df[df['Outcome']==1]) pct_of_non_Diabet_risk =count_non_Diabet_risk/(count_non_Diabet_risk +count_Diabet_risk ) print("percentage of non_Diabet_risk is", round(pct_of_non_Diabet_risk*100,2)) pct_of_Diabet_risk= count_Diabet_risk/(count_non_Diabet_risk +count_Diabet_risk) print("percentage of Fraud Risk", round(pct_of_Diabet_risk*100,2)) # #### Select input and target variables # + # label encoding the data from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df_treated['Age']= le.fit_transform(df_treated['Age']) # - df_treated # + from sklearn.preprocessing import OneHotEncoder # creating instance of one-hot-encoder enc = OneHotEncoder(handle_unknown='ignore') # passing bridge-types-cat column (label encoded values of bridge_types) enc_df = pd.DataFrame(enc.fit_transform(df_treated[['Age']]).toarray()) # - df_final = df_treated.drop(['Age'], axis = 1) df_final X = df_final[df_final.columns[0:7]] # merge one hot encoded 'Age' column with the other features of the dataframe X = X.join(enc_df) X y = df_final[df_final.columns[7:]] y from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) print("Train_x Shape :: ", X_train.shape) print("Train_y Shape :: ", y_train.shape) print("Test_x Shape :: ", X_test.shape) print("Test_y Shape :: ", y_test.shape) d_train = lgb.Dataset(X_train, label=y_train) # #### Building the model with default parameters # + def LGBM_classifier(features, target): """ To train the LGBM classifier with features and target data :param features: :param target: :return: trained LGBM classifier """ model = LGBMClassifier(metric='binary_logloss', objective='binary') model.fit(features, target) return model start = time.time() trained_model = LGBM_classifier(X_train, y_train.values.ravel()) print("> Completion Time : ", time.time() - start) print("Trained LGBM model :: ", trained_model) predictions = trained_model.predict(X_test) # - print("Train Accuracy :: ", accuracy_score(y_train, trained_model.predict(X_train))) print("LGBM Model Test Accuracy is :: ", accuracy_score(y_test, predictions)) # #### Check The feature Importance. feat_imp = pd.Series(trained_model.feature_importances_, index=X.columns) feat_imp.nlargest(12).plot(kind='barh', figsize=(8,10)) # ## Unveiling Diabetes Detection AI Model for Data Scientist using Boolean Rule Column Generation explainer and Logistic Rule Regression models provided by AI 360 Explainability Toolkit. # Data scientist: Boolean Rule and Logistic Rule Regression models # In evaluating a machine learning model for deployment, a data scientist would ideally like to understand the behavior of the model as a whole, not just in specific instances. This is especially true in regulated industries such as banking where higher standards of explainability may be required. # # For example, the data scientist may have to present the model to: # # 1) technical and business managers for review before deployment, 2) a lending expert to compare the model to the expert's knowledge, or 3) a regulator to check for compliance. # # BRCG, which is designed to produce a very simple OR-of-ANDs rule (known more formally as disjunctive normal form, DNF) or alternatively an AND-of-ORs rule (conjunctive normal form, CNF) to predict whether an applicant is not at Fraud risk (Y = 1). For a binary classification problem such as we have here, a DNF rule is equivalent to a rule set, where AND clauses in the DNF correspond to individual rules in the rule set. Furthermore, it can be shown that a CNF rule for Y = 1 is equivalent to a DNF rule for Y = 0. # BRCG is distinguished by its use of the optimization technique of column generation to search the space of possible clauses, which is exponential in size. To learn more about column generation, please see NeurIPS paper. # + X = df_final[df_final.columns[0:7]] # merge one hot encoded 'Age' column with the other features of the dataframe X = X.join(enc_df) X # - y = df_final["Outcome"] y print(X.shape) print(y.shape) from sklearn.model_selection import train_test_split dfTrain, dfTest, yTrain, yTest = train_test_split(X, y, random_state=0,test_size=0.3) dfTrain.head() # ### Binarize data and also return standardized ordinal features # Binarize data and also return standardized ordinal features from aix360.algorithms.rbm import FeatureBinarizer fb = FeatureBinarizer(negations=True, returnOrd=True) dfTrain, dfTrainStd = fb.fit_transform(dfTrain) dfTest, dfTestStd = fb.transform(dfTest) dfTrain['Glucose'].head() # + # Instantiate BRCG with small complexity penalty and large beam search width from aix360.algorithms.rbm import BooleanRuleCG br = BooleanRuleCG(lambda0=1e-3, lambda1=1e-3, CNF=True) # Train, print, and evaluate model br.fit(dfTrain, yTrain) # - from sklearn.metrics import accuracy_score print('Training accuracy:', accuracy_score(yTrain, br.predict(dfTrain))) print('Test accuracy:', accuracy_score(yTest, br.predict(dfTest))) print('Predict Y=0 if ANY of the following rules are satisfied, otherwise Y=1:') print(br.explain()['rules']) # #### You will see something like this, # Predict Y=0 if ANY of the following rules are satisfied, otherwise Y=1: # # ['Glucose <= 86.60', 'BMI <= 26.64', 'Glucose <= 135.20 AND DiabetesPedigreeFunction <= 0.22', 'Pregnancies <= 4.00 AND Glucose <= 125.60', 'Pregnancies <= 7.00 AND Glucose <= 168.00 AND Glucose > 95.20 AND BloodPressure > 70.00 AND BMI <= 41.74 AND BMI > 24.06 AND 0 not AND 1 '] # # `The above results shows the rules identified by the model in the data to a data Scientist.` # ## Part-2 Protodash Explainer # # * The method selects applications from the training set that are similar in different ways to the user application we want to explain. For example, a patient is predicted at Diabetes Risk. There could be mutliple reasons for that, this algorithm compares the profile of differently similar patients and give a doctor better perspective and wholistic view of the patient so that they give better and personalised guidance. # # * It doesn't give standard explanation for every case by using basic similarity techniques such as which use metrics such as euclidean distance, cosine similarity amongst others. # `Protodash provides a much more well rounded and comprehensive view of why the decision for the applicant may be justifiable.` # # # More Technical definition of Protodash : # # ProtodashExplainer provides exemplar-based explanations for summarizing datasets as well # as explaining predictions made by an AI model. It employs a fast gradient based algorithm to find prototypes along with their (non-negative) importance weights. The algorithm minimizes the maximummean discrepancy metric and has constant factor approximation guarantees for this weakly submodular function. # # [References:](https://arxiv.org/abs/1707.01212). # Paper by : `<NAME>, <NAME>, <NAME>,"ProtoDash: Fast Interpretable Prototype Selection" # # + import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import tensorflow as tf from keras.models import Sequential, Model, load_model, model_from_json from keras.layers import Dense from keras.callbacks import EarlyStopping import matplotlib.pyplot as plt from IPython.core.display import display, HTML from matplotlib import pyplot from sklearn.model_selection import train_test_split import numpy as np from aix360.algorithms.protodash import ProtodashExplainer # - # #### load the data again here! Follow the steps: # # * Load the `diabetes-data` as csv in the notebook. # * Click on the 0100 on the top right corner. # * Drag and Drop Fraud-Data.csv # * Click on `Insert to Code` and then `Pandas Dataframe.` # * Name the dataframe as `df` # # + #load the data here # - df_treated = df.copy() df_treated['Insulin'].replace(0, df_treated['Insulin'].median(), inplace=True) df_treated['SkinThickness'].replace(0, df_treated['SkinThickness'].median(), inplace=True) df_treated['BMI'].replace(0, df_treated['BMI'].mean(), inplace=True) df_treated['Glucose'].replace(0, df_treated['Glucose'].median(), inplace=True) df_treated['BloodPressure'].replace(0,df_treated['BloodPressure'].mean(), inplace=True) # + # generate binary values using get_dummies dum_df = pd.get_dummies(df_treated, columns=["Age"], prefix=["Age_is"] ) dum_df dum_df.columns # + df_final = dum_df[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age_is_Old', 'Age_is_Young','Outcome']] df_final # + X = df_final[df_final.columns[0:9]] X # + y =df_final[df_final.columns[9:]] y # - # ### Splitting the data with 70:30 mix X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # + Z = np.vstack((X_train, X_test)) Zmax = np.max(Z, axis=0) Zmin = np.min(Z, axis=0) #normalize an array of samples to range [-0.5, 0.5] def normalize(V): VN = (V - Zmin)/(Zmax - Zmin) VN = VN - 0.5 return(VN) # rescale a sample to recover original values for normalized values. def rescale(X): return(np.multiply ( X + 0.5, (Zmax - Zmin) ) + Zmin) N = normalize(Z) xn_train = N[0:X_train.shape[0], :] xn_test = N[X_train.shape[0]:, :] # - xn_test[4] ## Designing a basic Neural Network. def nn_small(): model = Sequential() model.add(Dense(10, input_dim=9, kernel_initializer='normal', activation='relu')) model.add(Dense(4, kernel_initializer='normal' ) ) model.add(Dense(2, kernel_initializer='normal' ) ) return model # + # Set random seeds for repeatability np.random.seed(1) tf.set_random_seed(2) class_names = ['Diabetes-Risk', 'No-Diabetes-Risk'] # loss function def fn(correct, predicted): return tf.nn.softmax_cross_entropy_with_logits(labels=correct, logits=predicted) # compile and print model summary nn = nn_small() nn.compile(loss=fn, optimizer='adam', metrics=['accuracy']) nn.summary() es = EarlyStopping(monitor='val_loss', patience=10) history = nn.fit(xn_train, y_train, batch_size=50, epochs=200, verbose=1, shuffle=False, callbacks=[es]) # evaluate model accuracy score = nn.evaluate(xn_train, y_train, verbose=0) #Compute training set accuracy #print('Train loss:', score[0]) print('Train accuracy:', score[1]) score = nn.evaluate(xn_test, y_test, verbose=0) #Compute test set accuracy #print('Test loss:', score[0]) print('Test accuracy:', score[1]) # + p_train = nn.predict_classes(xn_train) # Use trained neural network to predict train points print(p_train) p_train = p_train.reshape((p_train.shape[0],1)) z_train = np.hstack((xn_train, p_train)) # Store (normalized) instances that were predicted as Good/No Fraud Risk z_train_good = z_train[z_train[:,-1]==1, :] zun_train = np.hstack((xn_train, p_train)) # Store (unnormalized) instances that were predicted as Good zun_train_good = zun_train[zun_train[:,-1]==1, :] print(zun_train_good) # - p_test = nn.predict_classes(xn_test) p_test # + idx = 0 X = xn_test[idx].reshape((1,) + xn_test[idx].shape) # print(X) print("Chosen Sample:", idx) print("Prediction made by the model:", class_names[np.argmax(nn.predict_proba(X))]) print("Prediction probabilities:", nn.predict_proba(X)) print("") # attach the prediction made by the model to X X = np.hstack((X, nn.predict_classes(X).reshape((1,1)))) print(X) x_test = X_test.to_numpy() Xun = x_test[idx].reshape((1, ) + x_test[idx].shape) print(Xun) dfx = pd.DataFrame.from_records(Xun) # Create dataframe with original feature values dfx dfx[7] = int(X[0, -1]) dfx.columns = df.columns dfx.transpose() # - explainer = ProtodashExplainer() (W, S, setValues) = explainer.explain(X, z_train_good, m=5) class_names = ['Diabetes-Risk ', 'No-Diabetes-Risk'] dfs = pd.DataFrame.from_records(zun_train_good[S, 0:-1].astype('double')) RP=[] for i in range(S.shape[0]): RP.append(class_names[int(z_train_good[S[i], -1])]) # Append class names dfs[23] = RP dfs.columns = df_final.columns dfs["Weight"] = np.around(W, 5)/np.sum(np.around(W, 5)) # Calculate normalized importance weights dfs.transpose() # ### Note : The above table `This gives the profile of the instances similar to each other who have no Diabetes risk to the Doctor.` # ## Part-3 : Demostrating `Contrastive Explanations Method (CEM) algorithm using AI Explainability 360` on Diabetes Data # ### Contrastive Explanations Method (CEM) algorithm available in AI Explainability 360. # * `The algorithm outputs a contrastive explanation which consists of two parts: a) pertinent negatives (PNs) and b) pertinent positives (PPs). PNs identify a minimal set of features which if altered would change the classification of the original input.` # # # Compute Pertinent Negatives (PN): # In order to compute pertinent negatives, the CEM explainer computes a user profile that is close to the original applicant but for whom the decision of fraud risk is different. The explainer alters a minimal set of features by a minimal (positive) amount. This will help the user whose loan application was initially rejected say, to ascertain how to get it accepted. # # # # + import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import tensorflow as tf from keras.models import Sequential, Model, load_model, model_from_json from keras.layers import Dense from keras.callbacks import EarlyStopping import matplotlib.pyplot as plt from IPython.core.display import display, HTML from matplotlib import pyplot from sklearn.model_selection import train_test_split import numpy as np # - # #### Load the `Diabetes-Data` as csv in the notebook. # # * Click on the `0100` on the top right corner. # * Drag and Drop `diabetes-data.csv` # * Select the Cell below. # * Click on `Insert to Code` and then `Pandas Dataframe.` # + #load the data here # - df['Insulin'].replace(0, df['Insulin'].median(), inplace=True) df['SkinThickness'].replace(0, df['SkinThickness'].median(), inplace=True) df['BMI'].replace(0, df['BMI'].mean(), inplace=True) df['Glucose'].replace(0, df['Glucose'].median(), inplace=True) df['BloodPressure'].replace(0,df['BloodPressure'].mean(), inplace=True) # + dum_df = pd.get_dummies(df, columns=["Age"], prefix=["Age_is"] ) df_final = dum_df[['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin','BMI', 'DiabetesPedigreeFunction', 'Age_is_Old', 'Age_is_Young','Outcome']] df_final # + X = df_final[df_final.columns[0:9]] X # + y =df_final[df_final.columns[9:]] y # - x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1,stratify=y) # ### Normalising the dataset # + Z = np.vstack((x_train, x_test)) Zmax = np.max(Z, axis=0) Zmin = np.min(Z, axis=0) #normalize an array of samples to range [-0.5, 0.5] def normalize(V): VN = (V - Zmin)/(Zmax - Zmin) VN = VN - 0.5 return(VN) # rescale a sample to recover original values for normalized values. def rescale(X): return(np.multiply ( X + 0.5, (Zmax - Zmin) ) + Zmin) N = normalize(Z) xn_train = N[0:x_train.shape[0], :] xn_test = N[x_train.shape[0]:, :] # - xn_test[0] # ### Define and train a Neural Network Classifier from aix360.algorithms.contrastive import CEMExplainer, KerasClassifier def nn_small(): model = Sequential() model.add(Dense(10, input_dim=9, kernel_initializer='normal', activation='relu')) # model.add(Dense(4, kernel_initializer='normal' ) ) model.add(Dense(2, kernel_initializer='normal' ) ) return model # + # Set random seeds for repeatability np.random.seed(1) tf.set_random_seed(2) class_names = ['no-Diabetes-risk', 'Diabetes-risk'] # loss function def fn(correct, predicted): return tf.nn.softmax_cross_entropy_with_logits(labels=correct, logits=predicted) # compile and print model summary nn = nn_small() nn.compile(loss=fn, optimizer='adam', metrics=['accuracy']) nn.summary() nn.fit(xn_train, y_train, batch_size=100, epochs=200, verbose=1, shuffle=False) # evaluate model accuracy score = nn.evaluate(xn_train, y_train, verbose=0) #Compute training set accuracy #print('Train loss:', score[0]) print('Train accuracy:', score[1]) score = nn.evaluate(xn_test, y_test, verbose=0) #Compute test set accuracy print('Test loss:', score[0]) print('Test accuracy:', score[1]) # + # try on samples. idx =1 # print(xn_test[idx].reshape((1,) + xn_test[idx].shape)) X = xn_test[idx].reshape((1,) + xn_test[idx].shape) print("Computing PN for Sample:", idx) print("Prediction made by the model:", nn.predict_proba(X)) print("Prediction probabilities:", class_names[np.argmax(nn.predict_proba(X))]) print("") mymodel = KerasClassifier(nn) explainer = CEMExplainer(mymodel) arg_mode = 'PN' # Find pertinent negatives arg_max_iter = 500 # Maximum number of iterations to search for the optimal PN for given parameter settings arg_init_const = 10.0 # Initial coefficient value for main loss term that encourages class change arg_b = 9 # No. of updates to the coefficient of the main loss term arg_kappa = 0.02 # Minimum confidence gap between the PNs (changed) class probability and original class' probability arg_beta = 1e-1 # Controls sparsity of the solution (L1 loss) arg_gamma = 100 # Controls how much to adhere to a (optionally trained) auto-encoder my_AE_model = None # Pointer to an auto-encoder arg_alpha = 0.01 # Penalizes L2 norm of the solution arg_threshold = 1. # Automatically turn off features <= arg_threshold if arg_threshold < 1 arg_offset = 0.5 # the model assumes classifier trained on data normalized # in [-arg_offset, arg_offset] range, where arg_offset is 0 or 0.5 # Find PN for patient 1 (adv_pn, delta_pn, info_pn) = explainer.explain_instance(X, arg_mode, my_AE_model, arg_kappa, arg_b, arg_max_iter, arg_init_const, arg_beta, arg_gamma, arg_alpha, arg_threshold, arg_offset) # + Xpn = adv_pn classes = [ class_names[np.argmax(nn.predict_proba(X))], class_names[np.argmax(nn.predict_proba(Xpn))], 'NIL' ] print("Sample:", idx) print("prediction(X)", nn.predict_proba(X), class_names[np.argmax(nn.predict_proba(X))]) print("prediction(Xpn)", nn.predict_proba(Xpn), class_names[np.argmax(nn.predict_proba(Xpn))] ) X_re = rescale(X) # Convert values back to original scale from normalized Xpn_re = rescale(Xpn) Xpn_re = np.around(Xpn_re.astype(np.double), 2) delta_re = Xpn_re - X_re delta_re = np.around(delta_re.astype(np.double), 2) delta_re[np.absolute(delta_re) < 1e-4] = 0 X3 = np.vstack((X_re, Xpn_re, delta_re)) dfre = pd.DataFrame.from_records(X3) # Create dataframe to display original point, PN and difference (delta) dfre[23] = classes dfre.columns = df_final.columns dfre.rename(index={0:'X',1:'X_PN', 2:'(X_PN - X)'}, inplace=True) dfret = dfre.transpose() def highlight_ce(s, col, ncols): if (type(s[col]) != str): if (abs(s[col]) > 1): return(['background-color: yellow']*ncols) return(['background-color: white']*ncols) dfret.style.apply(highlight_ce, col='X_PN', ncols=3, axis=1) # - # ### The above results show that the patient should have 'less Glucose, Blood Pressure', 'Skin Thickness', Insulin, BMI for it to classified as `No-Diabetes-risk`
notebooks/Explainability.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # [ATM 623: Climate Modeling](../index.ipynb) # # [<NAME>](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany # # ## Assignment 1: Feedback in the zero-dimensional EBM # ## Warning: content out of date and not maintained # # You really should be looking at [The Climate Laboratory book](https://brian-rose.github.io/ClimateLaboratoryBook) by <NAME>, where all the same content (and more!) is kept up to date. # # ***Here you are likely to find broken links and broken code.*** # - Make a copy or branch of this notebook file so you can add your answer in additional cells. # - Complete all the problems below. # - For each problem, show your code and calculations. # - Feel free to include comments in your code to explain your method as necessary. # - Submit your solutions in a single Jupyter notebook that contains your text, your code, and your figures. # - *Make sure that your notebook runs cleanly from start to finish:* # - Save your notebook # - From the `Kernel` menu, select `Restart & Run All` # - Did the notebook run from start to finish without error and produe the expected output? # - If yes, save again and submit your notebook file # - If no, fix the errors and try again. # - Save your notebook as `[your last name].ipynb`, e.g. my notebook should be called `Rose.ipynb`. *This makes it easier for me when I collect all your answers* # - Submit your answers by email before class on **Thursday February 7 2019**. # ### Reading assignment # # Read this review paper: # # [<NAME> (2009): Feedbacks, Timescales, and Seeing Red. Annu. Rev. Earth Planet. Sci. 37:93–115. doi:10.1146/annurev.earth.061008.134734](http://annualreviews.org/doi/abs/10.1146/annurev.earth.061008.134734) # # Write at least one paragraph commentary on this article. What did you find most interesting or surprising? You are also welcome to offer criticisms or rebuttals to anything in the article. # *Your commentary here* # ### Question 1: Radiative forcing in the zero-dimensional energy balance model # In lecture we defined a zero-dimensional energy balance model for the global mean surface temperature $T$ as follows # # $$C \frac{dT}{dt} =(1-α)Q- OLR(T)$$ # # $$OLR= \tau \sigma T^4$$ # # where we defined these terms: # - $C$ is a heat capacity for the atmosphere-ocean column # - $\alpha$ is the global mean planetary albedo # - $\sigma = 5.67 \times 10^{-8}$ W m$^{-2}$ K$^{-4}$ is the Stefan-Boltzmann constant # - $\tau$ is our parameter for the atmospheric transmissivity # - $Q$ is the global-mean incoming solar radiation. # Following our course notes, set up values for all parameters so that the model reproduces the observed global average surface temperature $T=288$ K at equilibrium given the observed top-of-atmosphere shortwave and longwave radiative fluxes from the Trenberth and Fasullo figure from [Lecture 1](../Lectures/Lecture01 -- Planetary energy budget.ipynb). # # Suppose (for now) that the planetary albedo $\alpha$ is fixed at its observed value. # Doubling atmospheric CO$_2$ makes the atmosphere more opaque to longwave radiation. Suppose that we can represent this in the EBM as a 1.5 % decrease in the value of $\tau$. # (a) Calculate the radiative forcing $\Delta R$ in this model due to a doubling of CO$_2$. # (b) Calculate the no-feedback equilibrium response $\Delta T_0$. # (c) Using numerical timestepping, make a well-labeled graph of the timeseries of temperature $T(t)$ as it adjusts from initial temperature 288 K to its new equilibrium. # ### Question 2: Water vapor feedback in the EBM # In reality, the longwave opacity increases further as the planet warms because the atmosphere tends to get moister and water vapor provides an additional greenhouse effect. # # Let's parameterize the water vapor feedback in the EBM through a formula # # $$ \tau(T) = \tau_0 - \frac{T - 288 \text{K}}{400 \text{ K}} $$ # # where $\tau_0$ is the value at $T = 288$ K. # (a) Implement this formula in a Python function. # # As in Question 1, use numerical timestepping to investigate the adjustment of the EBM to its new equilibrium temperature after doubling CO$_2$. # # Make a well-labeled graph to compare the timeseries $T(t)$ with and without the water vapor feedback. Comment on the differences in climate sensitivity and in adjustment time. # (b) Calculate the **system gain** $g$ due to the water vapor feedback and the corresponding **feedback amount** $f_w$. # ### Question 3: Albedo feedback in the EBM # For this exercise, we will introduce a new physical process into our model by letting the planetary albedo depend on temperature. The idea is that a warmer planet has less ice and snow at the surface, and thus a lower planetary albedo. # # Represent the ice-albedo feedback through the following formula: # # $$ \alpha(T) = \left\{ \begin{array}{ccc} # \alpha_i & & T \le T_i \\ # \alpha_o + (\alpha_i-\alpha_o) \frac{(T-T_o)^2}{(T_i-T_o)^2} & & T_i < T < T_o \\ # \alpha_o & & T \ge T_o \end{array} \right\}$$ # # with the following parameter values: # # - $\alpha_o = 0.289$ is the albedo of a warm, ice-free planet # - $\alpha_i = 0.7$ is the albedo of a very cold, completely ice-covered planet # - $T_o = 293$ K is the threshold temperature above which our model assumes the planet is ice-free # - $T_i = 260$ K is the threshold temperature below which our model assumes the planet is completely ice covered. # # For intermediate temperature, this formula gives a smooth variation in albedo with global mean temperature. It is tuned to reproduce the observed albedo $\alpha = 0.299$ for $T = 288$ K. # (a): # # - Define a Python function that implements the above albedo formula. *There is definitely more than one way to do it. It doesn't matter how you do it as long as it works!* # - Use your function to calculate albedos for a wide range on planetary temperature (e.g. from $T=250$ K to $T=300$ K.) # - Present your results (albedo as a function of global mean temperature) in a nicely labeled figure. # (b): # # Repeat question 2(a), this time including the albedo feedback but ignoring the water vapor feedback (i.e. $\beta$ does not decrease with temperature). Again, use numerical timestepping to calculate the new equilibrium temperature after the increase in greenhouse gases, including the albedo feedback. Show your code, and make sure that you iterate enough times to ensure your solution is very very close to equilibrium. Make a graph comparing the timeseries in the three model versions used so far. # (c): # # Repeat question 2(b), calculating the **system gain** $g$ and **feedback amount** $f_i$ associated with this albedo feedback. # ### Question 4: Combining feedbacks # # Repeat 3(b) and 3(c) but this time including *both* the water vapor and albedo feedback processes in the EBM. # # Comment on the following: # # - Are the feedback amounts additive? (in other words, do you find the $f = f_i + f_w$? # - Are the system gains additive? # - How does the feedback amount change the timescale of adjustment? # ### Question 5: Uncertainty in feedback and response # # Inspired by Figure 5 of the paper by <NAME>, show that a *small uncertainty in the magnitude of the water vapor feedback* translates to a *larger uncertainty* in climate sensitivity if the model also includes the albedo feedback, even if there is no uncertainty in the albedo feedback itself. # # Present your arguments and results any way you see fit, but make sure your method and your code are clear. # <div class="alert alert-success"> # [Back to ATM 623 notebook home](../index.ipynb) # </div> # ____________ # # ## Credits # # The author of this notebook is [<NAME>](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany. # # It was developed in support of [ATM 623: Climate Modeling](http://www.atmos.albany.edu/facstaff/brose/classes/ATM623_Spring2015/), a graduate-level course in the [Department of Atmospheric and Envionmental Sciences](http://www.albany.edu/atmos/index.php) # # Development of these notes and the [climlab software](https://github.com/brian-rose/climlab) is partially supported by the National Science Foundation under award AGS-1455071 to <NAME>ose. Any opinions, findings, conclusions or recommendations expressed here are mine and do not necessarily reflect the views of the National Science Foundation. # ____________
Assignments/Assignment01 -- Feedback in the zero-dimensional EBM.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="-g6yvz65FsP0" # # Chapter6 再帰型ニューラルネットワーク(テキストデータの分類) ~映画レビューの感情分析プログラムを作る~ # ## 4. 感情分析の高速化 # + id="hgUxPWcrFsP1" executionInfo={"status": "ok", "timestamp": 1602452103789, "user_tz": -540, "elapsed": 29346, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="655ed443-a555-4f76-b5bd-7f34200da5be" colab={"base_uri": "https://localhost:8080/", "height": 1000} # 必要なパッケージのインストール # !pip3 install torch==1.6.0+cu101 # !pip3 install torchvision==0.7.0+cu101 # !pip3 install torchtext==0.3.1 # !pip3 install numpy==1.18.5 # !pip3 install matplotlib==3.2.2 # !pip3 install scikit-learn==0.23.1 # !pip3 install seaborn==0.11.0 # !pip3 install spacy==2.2.4 # + [markdown] id="9Paw1phvFsP8" # ## 4.2. 前準備(パッケージのインポート) # + id="hOS15uOnFsP9" # 必要なパッケージのインストール import numpy as np import spacy import matplotlib.pyplot as plt import torch from torchtext import data from torchtext import datasets from torch import nn import torch.nn.functional as F from torch import optim # + [markdown] id="qAfVO9CZFsQB" # ## 4.3. 訓練データとテストデータの用意 # + id="ezxP55Z5uq3E" executionInfo={"status": "ok", "timestamp": 1602452110322, "user_tz": -540, "elapsed": 35870, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="d45f4a4e-16ae-4135-9f7c-0cc7f93bad46" colab={"base_uri": "https://localhost:8080/", "height": 35} def generate_bigrams(x): n_grams = set(zip(*[x[i:] for i in range(2)])) # bi-gram, 2文字ずつに分割 for n_gram in n_grams: x.append(' '.join(n_gram)) # 分割した部分語をリスト化 return x generate_bigrams(['This', 'film', 'is', 'terrible']) # + id="pFr16YJuFsQC" # Text, Label Fieldの定義 all_texts = data.Field(tokenize = 'spacy', preprocessing = generate_bigrams) # テキストデータのField all_labels = data.LabelField(dtype = torch.float) # ラベルデータのField # + id="Rr7sDNDQFsQH" executionInfo={"status": "ok", "timestamp": 1602452225027, "user_tz": -540, "elapsed": 150565, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="9d90f589-554f-4f67-96c2-a53f4f358a4f" colab={"base_uri": "https://localhost:8080/", "height": 90} # データの取得 train_dataset, test_dataset = datasets.IMDB.splits(all_texts, all_labels) print("train_dataset size: {}".format(len(train_dataset))) # 訓練データのサイズ print("test_dataset size: {}".format(len(test_dataset))) # テストデータのサイズ # + id="7CEHqRepFsQL" executionInfo={"status": "ok", "timestamp": 1602452225028, "user_tz": -540, "elapsed": 150558, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="55dcbee3-a38c-42da-d616-a80bf333fd29" colab={"base_uri": "https://localhost:8080/", "height": 55} # 訓練データの中身の確認 print(vars(train_dataset.examples[0])) # + id="FtkcK1aMFsQP" executionInfo={"status": "ok", "timestamp": 1602452672865, "user_tz": -540, "elapsed": 598389, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="3dfb2363-4636-40a0-e6a3-bf132e6d3fa7" colab={"base_uri": "https://localhost:8080/", "height": 92} # 単語帳(Vocabulary)の作成 max_vocab_size = 25_000 all_texts.build_vocab(train_dataset, max_size = max_vocab_size, vectors = 'glove.6B.100d', # 学習済み単語埋め込みベクトル unk_init = torch.Tensor.normal_) # ランダムに初期化 all_labels.build_vocab(train_dataset) print("Unique tokens in all_texts vocabulary: {}".format(len(all_texts.vocab))) print("Unique tokens in all_labels vocabulary: {}".format(len(all_labels.vocab))) # + id="0wtFI748FsQT" executionInfo={"status": "ok", "timestamp": 1602452672865, "user_tz": -540, "elapsed": 598382, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="053732a0-31d3-47b7-864c-2b82ff7c0c95" colab={"base_uri": "https://localhost:8080/", "height": 55} # 上位20位の単語 print(all_texts.vocab.freqs.most_common(20)) # + id="A_yHoPS3FsQX" executionInfo={"status": "ok", "timestamp": 1602452672866, "user_tz": -540, "elapsed": 598377, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="d4e1fd2c-3d28-4297-ddfb-e9e1bc146507" colab={"base_uri": "https://localhost:8080/", "height": 35} # テキストはID化されているがテキストに変換することもできる。 print(all_texts.vocab.itos[:10]) # + id="orHs-DCGFsQb" executionInfo={"status": "ok", "timestamp": 1602452672866, "user_tz": -540, "elapsed": 598371, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="c8e20f88-e993-4bf0-addc-b298924ea81a" colab={"base_uri": "https://localhost:8080/", "height": 35} # labelの0と1がネガティブとポジティブどちらかを確認できる。 print(all_labels.vocab.stoi) # + id="WxxC5RVyFsQe" executionInfo={"status": "ok", "timestamp": 1602452683285, "user_tz": -540, "elapsed": 608785, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="9ce12c65-79c0-4277-854c-b8544b698d1f" colab={"base_uri": "https://localhost:8080/", "height": 90} # ミニバッチの作成 batch_size = 64 # CPUとGPUどちらを使うかを指定 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # デバイスの確認 print("Device: {}".format(device)) train_batch, test_batch = data.BucketIterator.splits( (train_dataset, test_dataset), # データセット batch_size = batch_size, # バッチサイズ device = device) # CPUかGPUかを指定 for batch in train_batch: print("text size: {}".format(batch.text[0].size())) # テキストデータのサイズ print("squence size: {}".format(batch.text[1].size())) # シーケンス長のサイズ print("label size: {}".format(batch.label.size())) # ラベルデータのサイズ break # + [markdown] id="mk1DQVaaFsQi" # ## 4.4. ニューラルネットワークの定義 # + id="X2K3a-IsFsQi" # ニューラルネットワークの定義 class Net(nn.Module): def __init__(self, D_in, D_embedding, D_out, pad_idx): super(Net, self).__init__() self.embedding = nn.Embedding(D_in, D_embedding, padding_idx = pad_idx) # 単語埋め込み層 self.linear = nn.Linear(D_embedding, D_out) # 全結合層 def forward(self, x): embedded = self.embedding(x) #text = [sent len, batch size] embedded = embedded.permute(1, 0, 2) #embedded = [sent len, batch size, emb dim] pooled = F.avg_pool2d(embedded, (embedded.shape[1], 1)).squeeze(1) #embedded = [batch size, sent len, emb dim] output = self.linear(pooled) #pooled = [batch size, embedding_dim] return output # + id="z5nl1NLzFsQm" executionInfo={"status": "ok", "timestamp": 1602452683286, "user_tz": -540, "elapsed": 608779, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="2fea7df1-7569-401f-fcca-ef97b486db43" colab={"base_uri": "https://localhost:8080/", "height": 90} # ニューラルネットワークのロード D_in = len(all_texts.vocab) # 入力層の次元 D_embedding = 100 # 単語埋め込み層の次元 D_out = 1 # 出力層の次元 pad_idx = all_texts.vocab.stoi[all_texts.pad_token] # <pad>トークンのインデックス net = Net(D_in, D_embedding, D_out, pad_idx).to(device) print(net) # + id="Ad0qeXOqh2Ty" executionInfo={"status": "ok", "timestamp": 1602452683287, "user_tz": -540, "elapsed": 608775, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="d19623f8-58b9-49c3-9e6c-4d7eb8f42ce1" colab={"base_uri": "https://localhost:8080/", "height": 35} # 学習済みの埋め込みを読み込み pretrained_embeddings = all_texts.vocab.vectors print(pretrained_embeddings.shape) # + id="5vSEDTqYml7y" executionInfo={"status": "ok", "timestamp": 1602452683775, "user_tz": -540, "elapsed": 609259, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="cda4daec-ce2f-4512-c565-26a54d54f7a6" colab={"base_uri": "https://localhost:8080/", "height": 163} # 埋め込み層の重みを学習済みの埋め込みに置き換え net.embedding.weight.data.copy_(pretrained_embeddings) # + id="lomt0kzgiGj0" executionInfo={"status": "ok", "timestamp": 1602452683776, "user_tz": -540, "elapsed": 609254, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="581ef8b6-5a74-4d87-eeb1-6a8349e58f45" colab={"base_uri": "https://localhost:8080/", "height": 163} # 不明なトークン<unk>のインデックス取得 unk_idx = all_texts.vocab.stoi[all_texts.unk_token] # <unk_idx>と<pad_idx>トークンのTensorをゼロで初期化 net.embedding.weight.data[unk_idx] = torch.zeros(D_embedding) net.embedding.weight.data[pad_idx] = torch.zeros(D_embedding) print(net.embedding.weight.data) # + [markdown] id="ZC7S1DLAFsQp" # ## 4.5. 損失関数と最適化関数の定義 # + id="pR8FauFwFsQq" # 損失関数の定義 criterion = nn.BCEWithLogitsLoss().to(device) # 最適化関数の定義 optimizer = optim.Adam(net.parameters()) # + [markdown] id="ePP1vHH3FsQv" # ## 4.6. 学習 # + id="W93xFErnFsQw" executionInfo={"status": "ok", "timestamp": 1602452849478, "user_tz": -540, "elapsed": 774949, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="6174fcfd-60ab-4581-ce88-549b2a50050b" colab={"base_uri": "https://localhost:8080/", "height": 765} # 損失と正解率を保存するリストを作成 train_loss_list = [] # 学習損失 train_accuracy_list = [] # 学習データの正答率 test_loss_list = [] # 評価損失 test_accuracy_list = [] # テストデータの正答率 # 学習(エポック)の実行 epoch = 10 for i in range(epoch): # エポックの進行状況を表示 print('---------------------------------------------') print("Epoch: {}/{}".format(i+1, epoch)) # 損失と正解率の初期化 train_loss = 0 # 学習損失 train_accuracy = 0 # 学習データの正答数 test_loss = 0 # 評価損失 test_accuracy = 0 # テストデータの正答数 # ---------学習パート--------- # # ニューラルネットワークを学習モードに設定 net.train() # ミニバッチごとにデータをロードし学習 for batch in train_batch: # GPUにTensorを転送 texts = batch.text labels = batch.label # 勾配を初期化 optimizer.zero_grad() # データを入力して予測値を計算(順伝播) y_pred_prob = net(texts).squeeze(1) # 損失(誤差)を計算 loss = criterion(y_pred_prob, labels) # 勾配の計算(逆伝搬) loss.backward() # パラメータ(重み)の更新 optimizer.step() # ミニバッチごとの損失を蓄積 train_loss += loss.item() # 予測したラベルを予測確率y_pred_probから計算 y_pred_labels = torch.round(torch.sigmoid(y_pred_prob)) # ミニバッチごとに正解したラベル数をカウント train_accuracy += torch.sum(y_pred_labels == labels).item() / len(labels) # エポックごとの損失と正解率を計算(ミニバッチの平均の損失と正解率を計算) epoch_train_loss = train_loss / len(train_batch) epoch_train_accuracy = train_accuracy / len(train_batch) # ---------学習パートはここまで--------- # # ---------評価パート--------- # # ニューラルネットワークを評価モードに設定 net.eval() # 評価時の計算で自動微分機能をオフにする with torch.no_grad(): for batch in test_batch: # GPUにTensorを転送 texts = batch.text labels = batch.label # データを入力して予測値を計算(順伝播) y_pred_prob = net(texts).squeeze(1) # 損失(誤差)を計算 loss = criterion(y_pred_prob, labels) # ミニバッチごとの損失を蓄積 test_loss += loss.item() # 予測したラベルを予測確率y_pred_probから計算 y_pred_labels = torch.round(torch.sigmoid(y_pred_prob)) # ミニバッチごとに正解したラベル数をカウント test_accuracy += torch.sum(y_pred_labels == labels).item() / len(labels) # エポックごとの損失と正解率を計算(ミニバッチの平均の損失と正解率を計算) epoch_test_loss = test_loss / len(test_batch) epoch_test_accuracy = test_accuracy / len(test_batch) # ---------評価パートはここまで--------- # # エポックごとに損失と正解率を表示 print("Train_Loss: {:.4f}, Train_Accuracy: {:.4f}".format( epoch_train_loss, epoch_train_accuracy)) print("Test_Loss: {:.4f}, Test_Accuracy: {:.4f}".format( epoch_test_loss, epoch_test_accuracy)) # 損失と正解率をリスト化して保存 train_loss_list.append(epoch_train_loss) # 学習損失 train_accuracy_list.append(epoch_train_accuracy) # 学習正答率 test_loss_list.append(epoch_test_loss) # テスト損失 test_accuracy_list.append(epoch_test_accuracy) # テスト正答率 # + [markdown] id="gUTQLlJUFsQ0" # ## 4.7. 結果の可視化 # + id="plNJBVVDFsQ0" executionInfo={"status": "ok", "timestamp": 1602452849806, "user_tz": -540, "elapsed": 775271, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="221d0e6c-fd96-45d4-806e-b79beca7054b" colab={"base_uri": "https://localhost:8080/", "height": 573} # 損失 plt.figure() plt.title('Train and Test Loss') # タイトル plt.xlabel('Epoch') # 横軸名 plt.ylabel('Loss') # 縦軸名 plt.plot(range(1, epoch+1), train_loss_list, color='blue', linestyle='-', label='Train_Loss') # Train_lossのプロット plt.plot(range(1, epoch+1), test_loss_list, color='red', linestyle='--', label='Test_Loss') # Test_lossのプロット plt.legend() # 凡例 # 正解率 plt.figure() plt.title('Train and Test Accuracy') # タイトル plt.xlabel('Epoch') # 横軸名 plt.ylabel('Accuracy') # 縦軸名 plt.plot(range(1, epoch+1), train_accuracy_list, color='blue', linestyle='-', label='Train_Accuracy') # Train_lossのプロット plt.plot(range(1, epoch+1), test_accuracy_list, color='red', linestyle='--', label='Test_Accuracy') # Test_lossのプロット plt.legend() # 表示 plt.show() # + [markdown] id="U8HFkd3XpR7J" # ## 4.8. 新しいレビューに対する感情分析 # + id="XuJMQ-TkpNZ2" nlp = spacy.load('en') def predict_sentiment(net, sentence): net.eval() # 評価モードに設定 tokenized = [tok.text for tok in nlp.tokenizer(sentence)] # 文をトークン化して、リストに分割 indexed = [all_texts.vocab.stoi[t] for t in tokenized] # トークンにインデックスを付与 tensor = torch.LongTensor(indexed).to(device) # インデックスをTensorに変換 tensor = tensor.unsqueeze(1) # バッチの次元を追加 prediction = torch.sigmoid(net(tensor)) # シグモイド関数で0から1の出力に return prediction # + id="2-5_GVjppaii" executionInfo={"status": "ok", "timestamp": 1602453473524, "user_tz": -540, "elapsed": 857, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="34d45683-2061-4ed7-fc6e-2328f78647ae" colab={"base_uri": "https://localhost:8080/", "height": 54} # ネガティブなレビューを入力して、感情分析 y_pred_prob = predict_sentiment(net, "This film is terrible") y_pred_label = torch.round(y_pred_prob) print("Probability: {:.4f}".format(y_pred_prob.item())) print("Pred Label: {:.0f}".format(y_pred_label.item())) # + id="3qrIKP1Spd37" executionInfo={"status": "ok", "timestamp": 1602453474756, "user_tz": -540, "elapsed": 583, "user": {"displayName": "\u658e\u85e4\u52c7\u54c9", "photoUrl": "", "userId": "06964401837614789891"}} outputId="d423a676-2b72-41fb-c595-c3d8f24974c8" colab={"base_uri": "https://localhost:8080/", "height": 54} # ポジティブなレビューを入力して、感情分析 y_pred_prob = predict_sentiment(net, "This film is great") y_pred_label = torch.round(y_pred_prob) print("Probability: {:.4f}".format(y_pred_prob.item())) print("Pred Label: {:.0f}".format(y_pred_label.item()))
Google_Colaboratory/Chapter6/Section6-4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import matplotlib.pyplot as plt x = (1,2,3,4,5) y = (3,2,3,4,5) #x,y = [(1,2,3,4,5), (3,2,3,4,5)] plt.bar(x,y,align='center') # A bar chart plt.xlabel('Bins') plt.ylabel('Frequency') for i in range(len(y)): plt.hlines(y[i],0,x[i]) # Here you are drawing the horizontal lines plt.show()
Data Visualization with python/Histogram.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # CSAL4243: Introduction to Machine Learning # <NAME> (<EMAIL>) # + [markdown] slideshow={"slide_type": "slide"} # # Assignment 1: Linear Regression # # In this assignment you are going to learn how Linear Regression works by using the code for linear regression and gradient descent we have been looking at in the class. You are also going to use linear regression from [scikit-learn](http://scikit-learn.org/) library for machine learning. You are going to learn how to download data from [kaggle](https://www.kaggle.com/) (a website for datasets and machine learning) and upload submissions to kaggle competitions. And you will be able to compete with the world. # + [markdown] slideshow={"slide_type": "fragment"} # ### Overview # + [markdown] slideshow={"slide_type": "fragment"} # - [Pseudocode](#Pseudocode) # - [Tasks](#Tasks) # - [Load and analyze data](#Load-and-analyze-data) # - [Task 1: Effect of Learning Rate $\alpha$](#Task-1:-Effect-of-Learning-Rate-$\alpha$) # - [Load X and y](#Load-X-and-y) # - [Linear Regression with Gradient Descent code](#Linear-Regression-with-Gradient-Descent-code) # - [Run Gradient Descent on training data](#Run-Gradient-Descent-on-training-data) # - [Plot trained line on data](#Plot-trained-line-on-data) # - [Task 2: Predict test data output and submit it to Kaggle](#Task-2:-Predict-test-data-output-and-submit-it-to-Kaggle) # - [Upload .csv file to Kaggle.com](#Upload-.csv-file-to-Kaggle.com) # - [Task 3: Use scikit-learn for Linear Regression](#Task-3:-Use-scikit-learn-for-Linear-Regression) # - [Task 4: Multivariate Linear Regression](#Task-4:-Multivariate-Linear-Regression) # - [Resources](#Resources) # - [Credits](#Credits) # - # <br> # <br> # + [markdown] slideshow={"slide_type": "slide"} # # Pseudocode # ## Linear Regressio with Gradient Descent # + [markdown] slideshow={"slide_type": "fragment"} # - Load training data into X_train and y_train # - [Optionally] normalize features X_train using $x^i = \frac{x^i - \mu^i}{\rho^i}$ where $\mu^i$ is mean and $\rho^i$ is standard deviation of feature $i$ # - Initialize hyperparameters # - iterations # - learning rate $\alpha$ # - Initialize $\theta_s$ # - At each iteration # - Compute cost using $J(\theta) = \frac{1}{2m}\sum_{i=1}^{m} (h(x^i) - y^i)^2$ where $h(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 .... + \theta_n x_n$ # - Update $\theta_s$ using $\begin{align*} \; \; & \theta_j := \theta_j - \alpha \frac{1}{m} \sum\limits_{i=1}^{m} (h_\theta(x_{i}) - y_{i}) \cdot x^j_{i} \; & & \text{for j := 0...n} \end{align*}$ # - [Optionally] Break if cost $J(\theta)$ does not change. # # - # <br> # <br> # # Download House Prices dataset # # # The dataset you are going to use in this assignment is called [House Prices](https://www.kaggle.com/c/house-prices-advanced-regression-techniques), available at kaggle. To download the dataset go to dataset data tab. Download 'train.csv', 'test.csv', 'data_description.txt' and 'sample_submission.csv.gz' files. 'train.csv' is going to be used for training the model. 'test.csv' is used to test the model i.e. generalization. 'data_description.txt' contain feature description of the dataset. 'sample_submission.csv.gz' contain sample submission file that you need to generate to be submitted to kaggle. # # <br> # + [markdown] slideshow={"slide_type": "slide"} # # Tasks # # 1. Effect of Learning Rate $\alpha$ # 2. Predict test data output and submit it to Kaggle # 3. Use scikit-learn for Linear Regression # 4. Multivariate Linear Regression # # + [markdown] slideshow={"slide_type": "subslide"} # ## Load and analyze data # + slideshow={"slide_type": "fragment"} # %matplotlib inline import pandas as pd import numpy as np import seaborn as sns from sklearn import linear_model import matplotlib.pyplot as plt import matplotlib as mpl # read house_train.csv data in pandas dataframe df_train using pandas read_csv function df_train = pd.read_csv('datasets/house_price/train.csv', encoding='utf-8') # + slideshow={"slide_type": "fragment"} # check data by printing first few rows df_train.head() # - # check columns in dataset df_train.columns # check correlation matrix, darker means more correlation corrmat = df_train.corr() f, aX_train= plt.subplots(figsize=(12, 9)) sns.heatmap(corrmat, vmax=.8, square=True); # SalePrice correlation matrix with top k variables k = 10 #number of variables for heatmap cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index cm = np.corrcoef(df_train[cols].values.T) sns.set(font_scale=1.25) hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values) plt.show() #scatterplot with some important variables cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'YearBuilt'] sns.set() sns.pairplot(df_train[cols], size = 2.5) plt.show(); # <br> # # Task 1: Effect of Learning Rate $\alpha$ # Use Linear Regression code below using X="GrLivArea" as input variable and y="SalePrice" as target variable. Use different values of $\alpha$ given in table below and comment on why they are useful or not and which one is a good choice. # # - $\alpha=0.000001$: # - $\alpha=0.00000001$: # - $\alpha=0.000000001$: # <br> # ## Load X and y # + # Load X and y variables from pandas dataframe df_train cols = ['GrLivArea'] X_train = np.array(df_train[cols]) y_train = np.array(df_train[["SalePrice"]]) # Get m = number of samples and n = number of features m = X_train.shape[0] n = X_train.shape[1] # append a column of 1's to X for theta_0 X_train = np.insert(X_train,0,1,axis=1) # - # ## Linear Regression with Gradient Descent code # + iterations = 1500 alpha = 0.000000001 # change it and find what happens def h(X, theta): #Linear hypothesis function hx = np.dot(X,theta) return hx def computeCost(theta,X,y): #Cost function """ theta is an n- dimensional vector, X is matrix with n- columns and m- rows y is a matrix with m- rows and 1 column """ #note to self: *.shape is (rows, columns) return float((1./(2*m)) * np.dot((h(X,theta)-y).T,(h(X,theta)-y))) #Actual gradient descent minimizing routine def gradientDescent(X,y, theta_start = np.zeros((n+1,1))): """ theta_start is an n- dimensional vector of initial theta guess X is input variable matrix with n- columns and m- rows. y is a matrix with m- rows and 1 column. """ theta = theta_start j_history = [] #Used to plot cost as function of iteration theta_history = [] #Used to visualize the minimization path later on for meaninglessvariable in range(iterations): tmptheta = theta # append for plotting j_history.append(computeCost(theta,X,y)) theta_history.append(list(theta[:,0])) #Simultaneously updating theta values for j in range(len(tmptheta)): tmptheta[j] = theta[j] - (alpha/m)*np.sum((h(X,theta) - y)*np.array(X[:,j]).reshape(m,1)) theta = tmptheta return theta, theta_history, j_history # - # ## Run Gradient Descent on training data # + #Actually run gradient descent to get the best-fit theta values initial_theta = np.zeros((n+1,1)); theta, theta_history, j_history = gradientDescent(X_train,y_train,initial_theta) plt.plot(j_history) plt.title("Convergence of Cost Function") plt.xlabel("Iteration number") plt.ylabel("Cost function") plt.show() # - # ## Plot trained line on data # + # predict output for training data hx_train= h(X_train, theta) # plot it plt.scatter(X_train[:,1],y_train) plt.plot(X_train[:,1],hx_train[:,0], color='red') plt.show() # - # <br> # # Task 2: Predict test data output and submit it to Kaggle # In this task we will use the model trained above to predict "SalePrice" on test data. Test data has all the input variables/features but no target variable. Out aim is to use the trained model to predict the target variable for test data. This is called generalization i.e. how good your model works on unseen data. The output in the form "Id","SalePrice" in a .csv file should be submitted to kaggle. Please provide your score on kaggle after this step as an image. It will be compared to the 5 feature Linear Regression later. # + # read data in pandas frame df_test and check first few rows # write code here df_test.head() # - # check statistics of test data, make sure no data is missing. print(df_test.shape) df_test[cols].describe() # + # Get X_test, no target variable (SalePrice) provided in test data. It is what we need to predict. X_test = np.array(df_test[cols]) #Insert the usual column of 1's into the "X" matrix X_test = np.insert(X_test,0,1,axis=1) # - # predict test data labels i.e. y_test predict = h(X_test, theta) # save prediction as .csv file pd.DataFrame({'Id': df_test.Id, 'SalePrice': predict[:,0]}).to_csv("predict1.csv", index=False) # ## Upload .csv file to Kaggle.com # # - Create an account at https://www.kaggle.com # - Go to https://www.kaggle.com/c/house-prices-advanced-regression-techniques/submit # - Upload "predict1.csv" file created above. # - Upload your score as an image below. from IPython.display import Image Image(filename='images/asgn_01.png', width=500) # <br> # # Task 3: Use scikit-learn for Linear Regression # # In this task we are going to use [Linear Regression class from scikit-learn](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) library to train the same model. The aim is to move from understanding algorithm to using an exisiting well established library. There is a [Linear Regression example](http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py) available on scikit-learn website as well. # # - Use the scikit-learn linear regression class to train the model on df_train # - Compare the parameters from scikit-learn linear_model.LinearRegression.coef_ to the $\theta_s$ from earlier. # - Use the linear_model.LinearRegression.predict on test data and upload it to kaggle. See if your score improves. Provide screenshot. # - Note: no need to append 1's to X_train. Scitkit linear regression has parameter called fit_intercept that is by defauly enabled. # + # import scikit-learn linear model from sklearn import linear_model # get X and y # write code here # Create linear regression object # write code here check link above for example # Train the model using the training sets. Use fit(X,y) command # write code here # The coefficients print('Intercept: \n', regr.intercept_) print('Coefficients: \n', regr.coef_) # The mean squared error print("Mean squared error: %.2f" % np.mean((regr.predict(X_train) - y_train) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(X_train, y_train)) # - # read test X without 1's # write code here # predict output for test data. Use predict(X) command. predict2 = # write code here # remove negative sales by replacing them with zeros predict2[predict2<0] = 0 # save prediction as predict2.csv file # write code here # <br> # # Task 4: Multivariate Linear Regression # # Lastly use columns ['OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'YearBuilt'] and scikit-learn or the code given above to predict output on test data. Upload it to kaggle like earlier and see how much it improves your score. # # - Everything remains same except dimensions of X changes. # - There might be some data missing from the test or train data that you can check using pandas.DataFrame.describe() function. Below we provide some helping functions for removing that data. # + # define columns ['OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'YearBuilt'] # write code here # check features range and statistics. Training dataset looks fine as all features has same count. df_train[cols].describe() # + # Load X and y variables from pandas dataframe df_train # write code here # Get m = number of samples and n = number of features # write code here # + #Feature normalizing the columns (subtract mean, divide by standard deviation) #Store the mean and std for later use #Note don't modify the original X matrix, use a copy stored_feature_means, stored_feature_stds = [], [] Xnorm = np.array(X_train).copy() for icol in range(Xnorm.shape[1]): stored_feature_means.append(np.mean(Xnorm[:,icol])) stored_feature_stds.append(np.std(Xnorm[:,icol])) #Skip the first column if 1's # if not icol: continue #Faster to not recompute the mean and std again, just used stored values Xnorm[:,icol] = (Xnorm[:,icol] - stored_feature_means[-1])/stored_feature_stds[-1] # check data after normalization pd.DataFrame(data=Xnorm,columns=cols).describe() # + # Run Linear Regression from scikit-learn or code given above. # write code here. Repeat from above. # - # To predict output using ['OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'YearBuilt'] as input features. # Check features range and statistics to see if there is any missing data. # As you can see from count "GarageCars" and "TotalBsmtSF" has 1 missing value each. df_test[cols].describe() # Replace missing value with the mean of the feature df_test['GarageCars'] = df_test['GarageCars'].fillna((df_test['GarageCars'].mean())) df_test['TotalBsmtSF'] = df_test['TotalBsmtSF'].fillna((df_test['TotalBsmtSF'].mean())) df_test[cols].describe() # + # read test X without 1's # write code here # predict using trained model predict3 = # write code here # replace any negative predicted saleprice by zero predict3[predict3<0] = 0 # - # predict target/output variable for test data using the trained model and upload to kaggle. # write code to save output as predict3.csv here # + [markdown] slideshow={"slide_type": "slide"} # # Resources # # Course website: [https://w4zir.github.io/ml17s/](https://w4zir.github.io/ml17s/) # # [Course resources](https://github.com/w4zir/ml17s) # + [markdown] slideshow={"slide_type": "fragment"} # # Credits # Raschka, Sebastian. Python machine learning. Birmingham, UK: Packt Publishing, 2015. Print. # # [<NAME>, Machine Learning, Coursera](#https://www.coursera.org/learn/machine-learning) # # [Scikit Learn Linear Regression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html)
assignments/assignment01-house-price-using-regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Задание 5 # <NAME> ПИ19-4 # В заданном на рисунке 3 бинарном дереве реализовать: # 1. графически для заданных элементов добавление чисел: 38, 20, 8, 13, 47. # 2. программную реализацию добавления элементов. # 3. графически для заданных элементов удаления чисел: 33, 14, 5, 32. # 4. программную реализацию удаления элементов. # ![](./img/task.png) from sortedbinarytree_module import SortedTree # + items = [21, 7, 32, 5, 14, 4, 6, 2, 12, 9, 18, 27, 25, 24, 30, 37, 34, 39, 33] tree = SortedTree() for value in items: tree.push(value) print("Исходное дерево") print(tree) # - # ## Добавление элементов # ### Графически # Исходное дерево # ![](./img/0.png) # Добавляем 38 # ![](./img/1.png) # Добавляем 20 # ![](./img/2.png) # Добавляем 8 # ![](./img/3.png) # Добавляем 13 # ![](./img/4.png) # Добавляем 47 # ![](./img/5.png) # Итог после добавления # ![](./img/6.png) # ### Программно # Добавляем элементы add_list = [38, 20, 8, 13, 47] for value in add_list: tree.push(value) print("Дерево после добавления элементов",add_list) print(tree) # ## Удаление элементов # ### Графически # ![](./img/remove.png) # ### Программно # + #Удаляем элементы remove_list = [33, 14, 5, 32] for value in remove_list: tree.pull(value) print("Дерево после удаления элементов", remove_list) print(tree) # -
Course I/Алгоритмы Python/Part2/семинары/pract6/task5/task.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # RCS Document NoSQL RCS Document NoSQL # https://www.mongodb.com/ # # ![Mongo](https://webassets.mongodb.com/_com_assets/global/mongodb-logo-white.png) # # MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemata. # # Python # https://docs.mongodb.com/manual/tutorial/getting-started/ # + ## https://github.com/mongodb/mongo-python-driver # - # https://api.mongodb.com/python/current/installation.html # !pip install pymongo # https://github.com/mongodb/mongo-python-driver/blob/master/doc/installation.rst # !pip install pymongo[srv] import pymongo import json config = {"user":"RCS_U1","pw":"needrealpwhere"} with open("Mongo_config.json", "w") as write_file: json.dump(config, write_file, indent=4) with open('Mongo_config.json') as f: data = json.load(f) # + # can test with data['pw] # - # https://stackoverflow.com/questions/48665104/how-to-connect-to-mongodb-with-python # + # https://docs.atlas.mongodb.com/driver-connection/#python-driver-example client = pymongo.MongoClient(f"mongodb+srv://RCS_U1:{data['pw']}@clustervs0-<EMAIL>z.mongodb.net/test?retryWrites=true") # - # https://docs.atlas.mongodb.com/driver-connection/#python-driver-example # mongodb://<dbuser>:<dbpassword>@<EMAIL>:47190/cleanclimb client = pymongo.MongoClient("mongodb://RCS_U1:<EMAIL>:47190/cleanclimb") # client = pymongo.MongoClient(f"mongodb+srv://RCS_U1:{data['pw']}<EMAIL>/cleanclimb") db = client.cleanclimb type(client),type(db) # https://docs.mongodb.com/manual/tutorial/getting-started/#getting-started db.inventory.insert_many([ # MongoDB adds the _id field with an ObjectId if _id is not present { "item": "journal", "qty": 25, "status": "A", "size": { "h": 14, "w": 21, "uom": "cm" }, "tags": [ "blank", "red" ] }, { "item": "notebook", "qty": 50, "status": "A", "size": { "h": 8.5, "w": 11, "uom": "in" }, "tags": [ "red", "blank" ] }, { "item": "paper", "qty": 100, "status": "D", "size": { "h": 8.5, "w": 11, "uom": "in" }, "tags": [ "red", "blank", "plain" ] }, { "item": "planner", "qty": 75, "status": "D", "size": { "h": 22.85, "w": 30, "uom": "cm" }, "tags": [ "blank", "red" ] }, { "item": "postcard", "qty": 45, "status": "A", "size": { "h": 10, "w": 15.25, "uom": "cm" }, "tags": [ "blue" ] } ]) # To select all documents in the collection, pass an empty document as the query filter document to the pymongo.collection.Collection.find() method: cursor = db.inventory.find({}) type(cursor) mylist = list(cursor) len(mylist) mylist dir(cursor) # How to search by specific key in MongoDB? If we have millions of records we do not want to grab everything... # selects from the inventory collection all documents where the status equals "D": cursor = db.inventory.find({"status": "D"}) res=list(cursor) res cursor = db.inventory.find({'size': {'h': 22.85, 'w': 30, 'uom': 'cm'}}) list(cursor) # https://stackoverflow.com/questions/51888323/pymango-throws-error-on-son # https://api.mongodb.com/python/current/api/bson/son.html cursor = db.inventory.find({"size": SON([("h", 14), ("w", 21), ("uom", "cm")])}) import bson # + # AHA! bson.son.SON # Time to answer this https://stackoverflow.com/questions/51888323/pymango-throws-error-on-son # - cursor = db.inventory.find({"size": bson.son.SON([("h", 14), ("w", 21), ("uom", "cm")])}) list(cursor) import bson ## Match a Field in an Embedded Document cursor = db.inventory.find({"size.uom": "in"}) list(cursor) # Match an Element in an Array cursor = db.inventory.find({"tags": "blank"}) list(cursor) db.name # + #https://docs.mongodb.com/manual/core/databases-and-collections/ # - db.collection_names # # How to find exact text in MongoDB! # ### remember each db has collections (similar to tables in SQL) #https://stackoverflow.com/questions/48371016/pymongo-how-to-use-full-text-search db.inventory.create_index([('item', 'text')]) cur = db.inventory.find({"$text": {"$search": 'planner'}}) type(cur) list(cur) # # How to fuzzy search MongoDB documents?! # # Sadly this is not built into MongoDB (but some stemming support is incoming) # # * https://medium.com/xeneta/fuzzy-search-with-mongodb-and-python-57103928ee5d big freight operator # * https://medium.com/statuscode/how-to-speed-up-mongodb-regex-queries-by-a-factor-of-up-to-10-73995435c606 # + # To delete ALL documents...dangerous!! # db.inventory.delete_many({}) # + # Grabbing JSON immediately # https://stackoverflow.com/questions/4404742/how-do-i-turn-mongodb-query-into-a-json # - # # CouchDB # ![CouchDB](http://couchdb.apache.org/image/couch@2x.png) # http://couchdb.apache.org/ # # Apache CouchDB is open source database software that focuses on ease of use and having a scalable architecture. It has a document-oriented NoSQL database architecture and is implemented in the concurrency-oriented language Erlang; it uses JSON to store data, JavaScript as its query language using MapReduce, and HTTP for an API # + # Sadly CouchDB wrappers are not well maintaned the curse of open source # - # https://www.ibm.com/cloud/cloudant # # What is Cloudant? # # # **A scalable JSON document database for web, mobile, IoT and serverless applications** # # # IBM Cloudant is a distributed database that is optimized for handling heavy workloads that are typical of large, fast-growing web and mobile apps. Available as an SLA-backed, fully managed IBM Cloud service, Cloudant elastically scales throughput and storage independently. # # Cloudant is also available as a downloadable on-premises installation, and its API and powerful replication protocol are compatible with an open source ecosystem that includes CouchDB, PouchDB and libraries for the most popular web and mobile development stacks.
NoSQL/Document NoSQL Databases MongoDB.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # %matplotlib inline import matplotlib.pyplot as plt import cv2 import numpy as np xx = np.load('result.npy') xx.shape plt.imshow(np.mean(xx[:27],0)) plt.imshow(cv2.imread('image.png')) plt.imshow(np.mean(xx[27:51],0)) plt.imshow(np.mean(xx[51:81],0)) plt.imshow(np.mean(xx[81:100],0)) plt.imshow(np.mean(xx[100:119],0)) plt.imshow(cv2.imread('image.png')) plt.imshow(np.mean(xx[208:223],0)) bill = np.mean(xx[0:27],0,keepdims=True) wing = np.mean(xx[27:51],0,keepdims=True) upperparts = np.mean(xx[51:81],0,keepdims=True) breast = np.mean(xx[81:100],0,keepdims=True) #19 back = np.mean(xx[100:119],0,keepdims=True) #19 tail = np.mean(xx[119:159],0,keepdims=True) #40 head = np.mean(xx[159:170],0,keepdims=True) #11 throat = np.mean(xx[170:185],0,keepdims=True) #15 eye = np.mean(xx[185:208],0,keepdims=True) #23 forehead = np.mean(xx[208:223],0,keepdims=True) #15 nape = np.mean(xx[223:238],0,keepdims=True) #15 belly = np.mean(xx[238:257],0,keepdims=True) #19 leg = np.mean(xx[257:272],0,keepdims=True) #15 crown = np.mean(xx[272:287],0,keepdims=True) #15 bill = np.max(xx[0:27],0,keepdims=True) wing = np.max(xx[27:51],0,keepdims=True) upperparts = np.max(xx[51:81],0,keepdims=True) breast = np.max(xx[81:100],0,keepdims=True) #19 back = np.max(xx[100:119],0,keepdims=True) #19 tail = np.max(xx[119:159],0,keepdims=True) #40 head = np.max(xx[159:170],0,keepdims=True) #11 throat = np.max(xx[170:185],0,keepdims=True) #15 eye = np.max(xx[185:208],0,keepdims=True) #23 forehead = np.max(xx[208:223],0,keepdims=True) #15 nape = np.max(xx[223:238],0,keepdims=True) #15 belly = np.max(xx[238:257],0,keepdims=True) #19 leg = np.max(xx[257:272],0,keepdims=True) #15 crown = np.max(xx[272:287],0,keepdims=True) #15 seg = np.concatenate((bill, wing, upperparts, breast, back, tail, head, throat, eye, forehead, nape, belly, leg, crown)) seg = np.argmax(cv2.resize(np.transpose(seg, (1,2,0)), (441,441)),axis=2) plt.imshow(seg*20) label = cv2.imread('gray.png',-1) plt.imshow(seg*20*label) plt.imshow(cv2.imread('image.png')) cam_list = np.concatenate((bill, wing, upperparts, breast, back, tail, head, throat, eye, forehead, nape, belly, leg, crown)) norm_cam = cam_list / (np.max(cam_list, (1, 2), keepdims=True) + 1e-5) norm_cam.shape plt.imshow(norm_cam[0]) xx = np.load('result.npy') xx = xx / (np.max(xx, (1, 2), keepdims=True) + 1e-5) xx
fail_wok/cub_deeplab_withseg/Untitled.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Platte # Die Steifigkeit einer linear elastischen Platte mit Höhe $h$ und Breite $2a$ ist nach dem vereinfachten 2D Kirchhof-Love-Plattenmodell gebeben durch $$D=\frac{Eh^3}{12(1-\nu^2)}.$$ # # Wobei $E,\nu$ wie beim Zugstab Materialkonstanten sind; siehe z.B. [Timoshenko, Woinowski-Krieger, 2016]. # <table><tr> # <td> <img src="FIGURES/platteRandbedingungen.PNG" width="500" height="500"/> </td> # </tr></table> # Wenn $f$ eine Flächenlast ("Druck") ist, die in der Platte wirkt, dann ist die Durchbiegung $w$ der Platte gegeben durch $$D\Delta^2 w=f.$$ # # Wobei $$\Delta^2 w=\frac{\partial^4 w}{\partial x^4}+2\frac{\partial^4 w}{\partial x^2 \partial y^2}+\frac{\partial^4 w}{\partial x^4}.$$ # # Am Rand $\sqrt{x^2+y^2}=a$ sei $w=0$ d.h. die Platte fixiert (Ableitung verschwindet Rand und in der Mitte). # In Radialkoordinaten formuliert ergibt sich $$D\frac{1}{r}\frac{\partial}{\partial r}\left(\frac{1}{r}\frac{\partial}{\partial r}\left(\frac{1}{r}\frac{\partial}{\partial r}\left(r\frac{\partial w}{\partial r}\right)\right)\right)=f$$ # Nach [Timoshenko, Woinowski-Krieger, 2016] ergibt sich dann die Verschiebung $$w(r)=\frac{f}{64D}\left(a^2-r^2\right)^2.$$ # # Daraus ergibt sich die maximale Verschiebung in der Mitte # # $$w_{max}=\frac{fa^4}{64D}$$ # # und die maximale Spannung ergibt sich am Rand durch $$\sigma_{max}=\frac{3}{4}\frac{fa^2}{h^2},$$ # # siehe [Timoshenko, Woinowski-Krieger, 2016]; siehe auch [Landau, Lifschitz, 1975]. # ## Konkretes Beispiel # # $h=1 m$, $a=30 m$, $f=7850\cdot h\cdot9.8066\frac{N}{m^2}$ # + import numpy as np # h=1 und 0.75 z.B., Bild fuer h=1 m emod=200 #stahl nu=0.3 A=np.pi*(30.)**2 hoehe=0.75 a=30 E=emod*10**9 gewicht=(7850)*(hoehe*A) kraft=gewicht*9.8066 f=hoehe*7850*9.8066 D=(E*hoehe**3)/(12*(1-nu**2)) wmax=(f*a**4)/(64*D) wmax # + sigmamax=(3/4.)*(f*(a**2))/(hoehe**2) sigmamax*10**(-6) # - sigmamax*10**(-7) (f)/(64*D) # <table><tr> # <td> <img src="FIGURES/plate_analytical_uz_scaled_3.PNG" width="400" height="200"/> </td> # <td> <img src="FIGURES/platte_ansys_w_seitlich.PNG" width="450" height="300"/> </td> # </tr></table> # Die Verschiebungen können gut approximiert werden. Auch die maximale Spannung wird relativ gut approximiert und tritt wie analytisch vorhergesagt, am Rand auf. Die Unterschiede zwischen 3D FEM und analytischer Approximation können analog zum Zugstabbeispiel durch genauere analytische Approximationen reduziert werden. Der Aufwand für genauere Approximationen ist bei Platten jedoch höher, da im Gegensatz zu Biegebalken, Zugstab, Torsionsttab, die Platte analytisch in 2D ist. # %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import ticker import numpy as np from scipy import integrate from fem.funktionen import * import seaborn as sns #sns.set() mpl.rcParams["figure.figsize"] = (20,7) mpl.rcParams['lines.linewidth'] = 5 mpl.rcParams['lines.markersize'] = 15 #sns.set() farben = sns.color_palette() plt.style.use('seaborn-darkgrid') farben = sns.color_palette() r = np.linspace(-30, 30) ax=plt.axes() ax.tick_params(labelsize=15) ax.plot(r, -f/(64*D)*(a**2-r**2)**2, label = r'w analytisch', color=farben[0]), ax.tick_params(labelsize=15) ax.set_xlabel(xlabel='x in m',fontsize=15) ax.set_ylabel(ylabel='u in m',fontsize=15) plt.legend(loc='best',fontsize=15) ax.set_title(r"$w(r)=\frac{f}{64D}\left(a^2-r^2\right)^2$", fontsize=25)
3_Platte.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # RK_01_EarthCube_GeoEDF_Demo # ## Author(s) # List authors, their current affiliations, up-to-date contact information, and ORCID if available. Add as many author lines as you need. # # - Author1 = {"name": "<NAME>", "affiliation": "Purdue Research Computing", "email": "<EMAIL>", "orcid": "0000-0002-7026-7419"} # - Author2 = {"name": "<NAME>", "affiliation": "Purdue Research Computing", "email": "<EMAIL>"} # - Author3 = {"name": "<NAME>", "affiliation": "Purdue Research Computing", "email": "<EMAIL>"} # # # ## Purpose # This notebook demonstrates **GeoEDF**, a new Python-based plug-and-play workflow framework for composing and executing end-to-end geospatial research workflows in a cyberinfrastructure environment. GeoEDF seeks to free researchers from the time-consuming data wrangling tasks and focus on their scientific research. # # ## Technical contributions # # * **GeoEDF** (Geospatial **E**xtensible **D**ata **F**ramework)[<sup id="fn1-back">1</sup>](#fn1) is a novel abstraction of geospatial workflows as a sequence of reusable data acquisition (_connector_) and processing (_processor_) steps. # * A YAML-based workflow syntax for composing geospatial workflows out of data _connectors_ and data _processors_. # * A Python-based **GeoEDF** workflow engine for planning and executing the YAML workflows on diverse compute resources. # * A growing repository of community contributed connectors and processors that can be used in research workflows. # # ## Methodology # # 1. GeoEDF data connectors and processors are essentially Python classes that implement a standard interface. # 2. Connectors implement various data access protocols and assist in acquiring data from remote repositories (for e.g., NASA, USGS, etc.). Processors implement various domain agnostic and domain specific geospatial processing operations. # 3. Data connectors and processors are contributed as open-source to GitHub where a CI/CD (continuous integration/continuous deployment) pipeline packages them as Singularity containers and deploys them to a GeoEDF Singularity registry. # 4. Users can utilize any of these connectors or processors for their workflows or design and contribute their own. # 5. The GeoEDF workflow engine can be used standalone as in this Docker container example, or integrated into a science gateway. # # The GeoEDF workflow engine leverages the [Pegasus Workflow Management System](https://pegasus.isi.edu/) for workflow planning and execution on diverse compute resources (local machine, Condor pool, HPC, etc.). This container is based on the [Pegasus Workflow Development Environment](https://github.com/pegasus-isi/pegasus-workflow-development-environment). # # # ## Results # # This notebook demonstrates a GeoEDF hydrologic workflow that acquires data (in HDF format) from a NASA Distributed Active Archive Center (DAAC) and aggregates the data across a provided watershed region. This is often the first step before running a hydrologic model. # # ![Workflow](files/img/research.png) # # In GeoEDF, this workflow combines a data connector (**NASAInput**) and processor (**HDFEOSShapefileMask**) as follows: # # ![Workflow](files/img/mcd.png) # # The corresponding YAML GeoEDF workflow [file](./workflow/mcd15.yml) is as follows: # # ``` # $1: # Input: # NASAInput: # url: https://e4ftl01.cr.usgs.gov/MOTA/MCD15A3H.006/%{filename} # user: rkalyana # password: # Filter: # filename: # PathFilter: # pattern: '%{dtstring}/MCD15A3H.*.h09v07*.hdf' # dtstring: # DateTimeFilter: # pattern: '%Y.%m.%d' # start: 07/16/2002 # $2: # HDFEOSShapefileMask: # hdffile: $1 # shapefile: /home/earthcube/geoedf/files/watershed/subs1_projected_171936.shp # datasets: [Lai] # ``` # # **Note:** # # 1. A GeoEDF workflow combines _instances_ of connector or processor classes. The YAML syntax enables the user to specify bindings for the class arguments for the connector or processor (e.g., url, user, shapefile, etc.). # 2. Filters enhance the generality of connectors. In this specific case, HDF data for a specific time period can be acquired by modifying the _DateTimeFilter_ appropriately. Similarly, wildcards ('*') in the _PathFilter_ enable search across all the files hosted in that directory on the repository. # 3. Filters essentially provide one or more binding values for variables referenced in other connectors or filters. For example, the _filename_ variable in the _NASAInput_ connector is bound by the _PathFilter_; and the _dtstring_ variable in _PathFilter_ is bound by the _DateTimeFilter_. # 3. Numeric indices are used to denote the workflow step and establish output-input linkages between steps. # 4. Fields left blank (for e.g., _password_) are instantiated at workflow execution time by prompting the user to specify a value. # # ## Funding # # - Award1 = {"agency": "NSF", "award_code": "1835833", "award_URL": "https://www.nsf.gov/awardsearch/showAward?AWD_ID=1835822"} # # ## Keywords # # keywords=["workflow", "geospatial", "Pegasus", "containers", "cyberinfrastructure"] # # ## Citation # # <NAME>., <NAME>., <NAME>., GeoEDF Demo Notebook, EarthCube 2021 Annual Conference. # # ## Suggested next steps # # * Further documentation on GeoEDF can be found at [GeoEDF Documentation] (https://geoedf.readthedocs.io/en/latest/) # * GeoEDF is coming soon to the Jupyter tool environment on the [MyGeoHub Science Gateway] (https://mygeohub.org). Users will be able to create and execute workflows, and manage and publish the workflow results on this gateway. # * Current connector and processor definitions can be found in the [GeoEDF GitHub Repositories](https://github.com/geoedf). # # Setup # # ## Library import # # **GeoEDFWorkflow** is the primary class that will be used to instantiate and execute the workflow above. # # GeoEDF uses the _sregistry_ Singularity client library to interact with the GeoEDF Singularity registry. In order to turn off the informational messages from this library, we first set the _MESSAGELEVEL_ environment variable to _QUIET_. # + import os os.environ['MESSAGELEVEL'] = 'QUIET' from geoedfengine.GeoEDFWorkflow import GeoEDFWorkflow # - # # Workflow Instantiation # # A new workflow object is created by instantiating the _GeoEDFWorkflow_ class with the workflow YML file path. # # **Note:** # # 1. At this point, the GeoEDF engine will validate the workflow file for proper syntax (ensuring no cyclic dependencies, all variables are bound by filters, etc.). # 2. The user will be prompted to enter values for any variables that have been left blank (for e.g., _password_). # 3. Enter the value _<PASSWORD>_ when prompted for the password. workflow = GeoEDFWorkflow('/home/earthcube/geoedf/workflow/mcd15.yml') # # # Workflow Execution # # _GeoEDFWorkflow_ provides a method for executing workflows. In this case, we execute workflows locally on a Condor pool running in the container. Other execution sites can be configured in the Pegasus site catalog and provided as input during workflow instantiation. We do not include this feature in this demonstration due to its setup complexity. # # **Note:** # # 1. Workflow execution is synchronous; on execution, a progress bar (0 - 100%) will be displayed. # 2. Workflow may take a while to run based on the resources available to your local Docker engine. # 2. Workflow may report a _Failure_ from time to time since it is reaching out to an external NASA DAAC. If this happens, please check to see if https://e4ftl01.cr.usgs.gov/MOTA/MCD15A3H.006 is reachable in your browser and then repeat the steps (a) instantiate the workflow, (b) execute the workflow. workflow.execute() # # Discussion # # If the workflow succeeded, the output is an ESRI Shapefile which can be found in the output directory reported by the execute step above. However, there is no easy way to verify or visualize the result. There are Python mapping libraries (e.g. Folium or ipyLeaflet) that work with geospatial files, but require vector data to be in the GeoJSON format. # # As a next step, we demonstrate how a new processor can be developed for converting a shapefile into a GeoJSON file and appended as a third step to the above workflow. This demonstration can be found in the **_RK_02_EarthCube_GeoEDF_Demo_** notebook. # # # References # # [<sup id="fn1">1</sup>](#fn1-back) <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. and <NAME>., 2020. Geoedf: An extensible geospatial data framework for fair science. In Practice and Experience in Advanced Research Computing (pp. 207-214).
geoedf/RK_01_EarthCube_GeoEDF_Demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.7.5 64-bit # name: python37564bitcec697e8df1e4b95a8b71588e12c06eb # --- # # Lab 1: Introduction to Pytorch # This is the introduction to Pytorch. # # This notebook contains `auto_grad` and # ## Import modules import torch # ## Autograd Automatic Differentiation x = torch.ones(2, 2, requires_grad=True) print(x) # + y = x+2 print(y) # - # Note: `backward()` can be created only for scalar outputs y.backward() z = y.mean() z.backward() print(x.grad) # ## Simple Neural Network
Deep Learning/lab/lab1.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import matplotlib.pyplot as plt import sys import numpy as np sys.path.append("..") import utils as ut from assets import Account # # Make a stock and view its performance # Create a stock of Fortis Inc and view its performance over 20 years based on the current dividend and perspective growth # + # Create a Brokerage Account a = Account() FTS = a.Stock(a, name='FTS.TO', shares=50, price=50.78, dividend=1.8, annual_growth=5, volatility='med', drip=True, dividend_percent_growth=10) # View the summary of the stock before compounding FTS.summary() # - values, prices, cash = FTS.compound(years=20) # View the summary of the stock after compounding FTS.summary() # We see that 12 new shares were perchased over the 20 years through the DRIP program, remaining dividends went to a collective cash account called 'a' in the code. # The results can also be plotted. # The stock price can be plotted ut.plot_growth(prices, 'Stock Price', FTS.name) plt.show() # The value of the cash account as well as the cumulative value (stock + cash) can also be plotted plt.figure(figsize=(18,5)) x = np.array([i / 12 for i in range(len(values))]) plt.plot(x,values,label='Cumulative'); plt.plot(x,cash,label='Cash'); plt.ylabel('Value ($)'); plt.xlabel('Years'); plt.grid() plt.legend(); # We see that the cash account does not grow as quickly after approximately 17 years. This is because the dividends are reinvested by buying shares since at this point the quarterly dividend was finally large enough to purchase at least one share. There also appears to be more cumulative growth after this time due to more compounding from the DRIP. # Next we can simulate various scenarios of the stock growth to get a better idea of potential outcomes. (With high volitility to see some more variation) # + plt.figure(figsize=(18,6)) # make 20 simulations for _ in range(20): a = Account() FTS = a.Stock(a, name='FTS.TO', shares=50, price=50.78, dividend=1.8, annual_growth=5, volatility='high', drip=True, dividend_percent_growth=10) values, prices, cash = FTS.compound(years=20) plt.plot(x,prices); plt.ylabel('Value ($)'); plt.xlabel('Years'); plt.title('Fortis Price') plt.grid() # - # Annual/monthly deposits and withdrawals can be made where new stocks are purchased or sold with a commission price. Let's see how a $1000 annual deposit helps grow an account. # + a = Account() FTS = a.Stock(a, name='FTS.TO', shares=50, price=50.78, dividend=1.8, annual_growth=5, volatility='med', drip=True, dividend_percent_growth=10) values, prices, cash = FTS.compound(years=20, annual_deposit=1000) ut.plot_growth(values, 'Stock Price', FTS.name) plt.show() # - # If the user makes excessive withdrawals resulting in the account going broke, an error arrises telling the user how long it took for the account to go broke. Here the user will go broke in 4 years with a $1000/year withdrawal. # + a = Account() FTS = a.Stock(a, name='FTS.TO', shares=50, price=50.78, dividend=1.8, annual_growth=5, volatility='med', drip=True, dividend_percent_growth=10) values, prices, cash = FTS.compound(years=20, annual_withdrawal=1000) ut.plot_growth(values, 'Stock Price', FTS.name) plt.show() # -
Notebooks/stock_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %matplotlib inline import matplotlib.pyplot as plt import numpy as np g = 10 h = 100 L = 250e3 K = 0.8e-3 omega = 1.4e-4 period = 2*np.pi/omega print (period/3600.) A = 20 co = np.sqrt(g*h) wavelength = co*period print (co, wavelength/4.) fric_r = np.sqrt(1+(K + 2*A/L**2)**2/omega**2) * np.cos(0.5*np.arctan2(K+2*A/L**2,omega)) fric_i = np.sqrt(1+(K + 2*A/L**2)**2/omega**2) * np.sin(0.5*np.arctan2(K+2*A/L**2,omega)) tr = fric_r*omega/co ti = fric_i*omega/co x = np.arange(-250e3,0+1e3,1e3) eta0 = 0.5 print (fric_r, fric_i) k = 2*np.pi/wavelength fig, ax = plt.subplots(1,3,figsize=(15,5)) for t in np.arange(0,np.pi/omega,np.pi/8./omega): eta = eta0 * np.exp(-x*ti) * np.cos(x*tr-omega*t) \ + eta0 * np.exp(x*ti) * np.cos(-x*tr-omega*t) etar = ( eta0 * np.cos(x*tr - omega*t) + eta0 *np.cos(-x*tr - omega*t) ) etafree = ( eta0 * np.cos(x*k - omega*t) + eta0 *np.cos(-x*k - omega*t) ) ax[0].plot(x,eta) ax[1].plot(x,etafree) ax[2].plot(x,etar) # + etac = eta0 * (np.exp(-x*ti) * np.cos(x*tr) + np.exp(x*ti) * np.cos(-x*tr)) etas = eta0 * (np.exp(-x*ti) * np.sin(x*tr) + np.exp(x*ti) * np.sin(-x*tr)) amp = np.sqrt(etac**2+etas**2) pha = np.arctan2(etas,etac) plt.figure(figsize=(8,4)) plt.subplot(1,2,1) plt.plot(x,amp) plt.subplot(1,2,2) plt.plot(x,pha*180./np.pi) print ((pha[-1]-pha[0])*180./np.pi, amp[-1]/amp[0]) # + x0 = -50e3 x = np.arange(-150e3,-50e3,2e3) h2=150. nk = omega/np.sqrt(g*h2) etac = eta0 * (np.exp(-x0*ti) * np.cos(x*nk) + np.exp(x0*ti) * np.cos(-x*nk)) etas = eta0 * (np.exp(-x0*ti) * np.sin(x*nk) + np.exp(x0*ti) * np.sin(-x*nk)) amp = np.sqrt(etac**2+etas**2) pha = np.arctan2(etas,etac) plt.figure(figsize=(8,4)) plt.subplot(1,2,1) plt.plot(x,amp) plt.subplot(1,2,2) plt.plot(x,pha*180./np.pi) print ((pha[-1]-pha[0])*180./np.pi, amp[-1]/amp[0]) # -
Standing_Wave_Theory/Understanding Semi-standing Tides.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.6.5 # language: julia # name: julia-1.6 # --- # # PRAKTIKUM 3b # __Solusi Akar Persamaan Tak-Linear 2__ # # *Topik* # 1. Metode Newton-Raphson # 2. Metode _Secant_ # # <hr style="border:2px solid black"> </hr> # # 1 Metode Newton-Raphson # Metode _bisection_ dan _regula falsi_ yang telah dipelajari sebelumnya masih memiliki jumlah iterasi dan waktu komputasi yang cukup lama. Dengan tambahan informasi mengenai turunan dari fungsi $ f(x) $, metode Newton-Raphson dapat digunakan untuk mencari nilai akar dengan lebih cepat dibandingkan metode sebelumnya. # # Persamaan iterasi metode Newton-Raphson didefinisikan sebagai berikut. # $$p_k = p_{k-1} - \frac{f(p_{k-1})}{f'(p_{k-1})}$$ # untuk $ k = 1,2,3,\dots $ dan $p_0$ diketahui serta $f(x)$ terturunkan. # ## _Simple Root_ dan _Double Root_ # Persamaan dengan solusi _**simple root**_ adalah suatu persamaan yang memiliki akar tunggal. # # Contohnya, persamaan $ x^2-1=0 $ memiliki 2 akar tunggal, yaitu $ x_1=-1 $ dan $ x_2=1 $. Dengan kata lain, $x_1$ dan $x_2$ nilainya berbeda. # # Persamaan dengan solusi _**double root**_ adalah suatu persamaan yang memiliki akar ganda, artinya satu persamaan memiliki 2 akar yang bernilai sama. # # Contohnya, persamaan $ x^2-2x+1=0 $ memiliki akar ganda, yaitu $ x_1=1 $ dan $ x_2=1 $. # # Suatu persamaan dapat memiliki akar tunggal maupun ganda sekaligus. Misalnya, persamaan $f(x) = x^3-3x+2$ memiliki nilai akar yaitu $x_1=-2$, $x_2=1$ dan $x_3=1$. Perhatikan grafik fungsi ```f(x)``` berikut. # # <div style="width: 500px;"> # <img src="attachment:Bab2_9.JPG" width="500"> #= %%METODE NEWTON-RAPHSON % [pk, flag, M] = newtonRaphson (f,df,p0) % Input : f -> fungsi f % : df -> fungsi turunan dari f % p0 -> starting value % Output : pk -> nilai akar % flag -> tanda : 0 -> berhasil % 1 -> gagal % M -> matriks yang berisi nilai iterasi, hampiran akar dan % galat =# function newtonRaphson(f,df,p0) # Definisikan nilai toleransi, maksimum iterasi dan tebakan awal yang telah ditentukan. delta = 10^-7; maxi = 100; pk = p0 M = [0 pk NaN]; # Mulai langkah iterasi flag = 1; for k = 2:maxi # Rumus metode Newton-Raphson pk1 = pk pk = pk1 - f(pk1)/df(pk1); # Hitung nilai galat mutlak dan relatif err = abs(pk-pk1); rel = 2*err/(abs(pk)+eps()); M = [M; [k-1 pk err]] # Kriteria penghentian iterasi jika galat memenuhi toleransi. if err<delta || rel<delta flag = 0; break end end return pk, flag, M end # ### Contoh 1 : Solusi _Simple Root_ # Diberikan fungsi $ f(x)=x^3-3x+2 $ dan $ p_0=-2.4 $. Berikut merupakan langkah-langkah untuk mencari hampiran akar $ f(x)=0 $ yaitu $ P=-2 $ menggunakan metode Newton-Raphson serta menunjukkan bahwa metode Newton-Raphson memiliki ordo kekonvergenan $ R=2 $ untuk _simple root_. # **Langkah 1** : Hitung fungsi turunan dari $ f(x) $. # # Diketahui bahwa $ f(x)=x^3-3x+2 $, sehingga turunan fungsi $ f $ adalah # $$ f'(x)=3x^2-3 $$ # **Langkah 2** : Definisikan fungsi $ f $ dan turunannya $ f' $ serta nilai awal $ p_0 $. f(x) = x^3-3*x+2; df(x) = 3*x^2-3; p0 = -2.4; # **Langkah 3** : Hitung nilai hampiran akar menggunakan program Newton-Raphson. pk,flag,M = newtonRaphson(f,df,p0) @show pk @show flag M # **Langkah 4** : Hitung nilai galat $ E_k=P-p_k $. P = -2; Ek = P.-M[:,2] # **Langkah 5** : Hitung nilai rasio galat $ |E_{k+1}|/|E_k|^R $. Pilih $R=2$ R = 2; RasioGalat = abs.(Ek[2:end]) ./ abs.(Ek[1:end-1].^R) # Berdasarkan hasil yang didapatkan, nilai $ |E_{k+1}|/|E_k|^2 $ konvergen menuju suatu bilangan, yaitu $ \dfrac{2}{3} $. # # Jadi, metode Newton-Raphson memiliki ordo kekonvergenan $ R=2 $ untuk _single root_. # ### Contoh 2 : Solusi _Double Root_ # # Diberikan fungsi $ f(x)=x^3-3x+2 $ dengan $ p_0=1.2 $. Berikut merupakan langkah-langkah untuk mencari nilai hampiran akar $ f(x)=0 $ yaitu $ P=1 $ menggunakan metode Newton-Raphson serta menunjukkan bahwa metode Newton-Raphson memiliki ordo kekonvergenan $ R=1 $ untuk _double root_. # **Langkah 1** : Hitung fungsi turunan dari $ f(x) $. # # Diketahui bahwa $ f(x)=x^3-3x+2 $, sehingga turunan fungsi $ f $ adalah # $$ f'(x)=3x^2-3 $$ # **Langkah 2** : Definisikan fungsi $ f $ dan turunannya $ f' $ serta nilai awal $ p_0 $. f(x) = x^3-3*x+2; df(x) = 3*x^2-3; p0 = 1.2; # **Langkah 3** : Hitung nilai hampiran akar menggunakan program Newton-Raphson. pk, flag, M = newtonRaphson(f,df,p0) @show pk @show flag M # **Langkah 4** : Hitung nilai galat $ E_k=P-p_k $. P = 1; Ek = P .- M[:,2] # **Langkah 5** : Hitung nilai rasio galat $ |E_{k+1}|/|E_k|^R $. Pilih $R=1$ R = 1; RasioGalat = abs.(Ek[2:end]) ./ abs.(Ek[1:end-1].^R) # Berdasarkan hasil yang didapatkan, nilai $ |E_{k+1}|/|E_k|^1 $ konvergen menuju suatu bilangan, yaitu $\dfrac{1}{2}$. # # Jadi, metode Newton-Raphson memiliki ordo kekonvergenan $ R=1 $ untuk _double root_. # # 2 Metode _Secant_ # Metode _secant_ merupakan metode alternatif yang digunakan, apabila metode Newton-Raphson tidak mungkin untuk dicari fungsi turunannya. # # Metode _secant_ memiliki ordo kekonvergenan yaitu $ R=\dfrac{1+\sqrt{5}}{2}\approx1.618 $ yang hampir mendekati metode Newton-Raphson yaitu $ R=2 $. # Bentuk umum dari secant adalah # $$ p_{k+1}=p_k - f(p_{k}) \dfrac{p_k-p_{k-1}}{f(p_k)-f(p_{k-1})}$$ #= # %%METODE SECANT % [pk, flag, M] = secant(f,p0,p1) % Input : f -> fungsi f % p0,p1-> starting value % Output : pk -> nilai akar % flag -> tanda % 0 -> berhasil % 1 -> gagal % M -> matriks yang berisi nilai iterasi, hampiran akar dan galat =# function secant(f,p0,p1) # Definisikan nilai toleransi, maksimum iterasi dan tebakan awal yang telah ditentukan. delta = 10^-12; maxi = 100; M = [0 p0 NaN 1 p1 NaN]; p = [p0 p1]; pk = p1; flag = 1; # Mulai langkah iterasi for k = 2:maxi # rumus metode secant pk=p[k]-f(p[k])*(p[k]-p[k-1])/(f(p[k])-f(p[k-1])); p = [p pk] # Hitung nilai galat mutlak dan relatif err=abs(p[k+1]-p[k]); rel=2*err/(abs(p[k]) + eps()); M = [M; [k pk err]] # Kriteria penghentian iterasi jika galat memenuhi toleransi. if err<delta || rel<delta flag = 0; break end end return pk, flag, M end # ### Contoh 3 # Diberikan fungsi $ f(x)=x^3-3x+2 $ dengan $ p_0=-2.6 $ dan $ p_1=-2.4 $. Berikut merupakan langkah-langkah untuk mencari nilai hampiran akar $ f(x)=0 $ yaitu $ P=-2 $ menggunakan metode _secant_ serta menunjukkan bahwa metode _secant_ memiliki ordo kekonvergenan $ R=\dfrac{1+\sqrt{5}}{2} $ untuk _simple root_. # __Langkah 1__ : Definisikan fungsi $ f $ serta nilai awal $ p_0 $ dan $ p_1 $. f(x) = x^3-3*x+2; p0 = -2.6; p1 = -2.4; # __Langkah 2__ : Hitung nilai hampiran akar $ f(x)=0 $ menggunakan metode _secant_ di atas pk, flag, M = secant(f,p0,p1) @show pk @show flag M # **Langkah 3** : Hitung nilai galat $ E_k=P-p_k $. P = -2; Ek = P .- M[:,2] # **Langkah 5** : Hitung nilai rasio galat $ |E_{k+1}|/|E_k|^R $. Pilih $ R=\dfrac{1+\sqrt{5}}{2} $ R = (1+sqrt(5))/2; RasioGalat = abs.(Ek[2:end]) ./ abs.(Ek[1:end-1].^R) # Berdasarkan hasil yang didapatkan, nilai $ |E_{k+1}|/|E_k|^R $ konvergen menuju suatu bilangan, yaitu $0.8$. # # Jadi, metode Newton-Raphson memiliki ordo kekonvergenan $ R=\dfrac{1+\sqrt{5}}{2} $ untuk _single root_. # <hr style="border:2px solid black"> </hr> # # # Soal Latihan # Kerjakan soal berikut pada saat kegiatan praktikum berlangsung. # # `Nama: ________` # # `NIM: ________` # ### Soal 1 # Ulangi langkah-langkah pada **Contoh 1** untuk mencari nilai hampiran akar persamaan dari $$ f(x)=x^3+3x^2-4 $$ dengan nilai awal $ p_0=1.2 $ menggunakan metode Newton-Raphson. # ### Soal 2 # Ulangi langkah-langkah pada **Contoh 2** untuk mencari nilai hampiran akar persamaan dari $$ f(x)=x^3+3x^2-4 $$ dengan nilai awal $ p_0=-2.4 $ menggunakan metode Newton-Raphson. # ### Soal 3 # Diberikan $ f(x)=x^3+3x^2-4 $ dengan nilai $ p_0=1.6 $ dan $ p_1=1.4 $. # # Carilah nilai hampiran akar persamaan $ f(x)=0 $ menggunakan metode _secant_ serta tunjukkan bahwa metode _secant_ memiliki ordo kekonvergenan $ R=1 $ untuk _double root_.
notebookpraktikum/Praktikum 03b.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Write A Function In Machine Code - Basically a String but more complicated # # Linux memory == files? # # memory mapped file - https://man7.org/linux/man-pages/man2/mmap.2.html # # memory with code in must be marked "executable" # # Code from https://github.com/tonysimpson/pointbreak > # + import ctypes import mmap def create_callable_from_machine_code(machine_code, doc=None, restype=None, argtypes=None, use_errno=False, use_last_error=False): if argtypes is None: argtypes = [] exec_code = mmap.mmap(-1, len(machine_code), prot=mmap.PROT_WRITE | mmap.PROT_READ | mmap.PROT_EXEC) exec_code.write(machine_code) c_type = ctypes.c_byte * len(machine_code) c_var = c_type.from_buffer(exec_code) address = ctypes.addressof(c_var) c_func_factory = ctypes.CFUNCTYPE(restype, *argtypes, use_errno=use_errno, use_last_error=use_last_error) func = c_func_factory(address) func._exec_code = exec_code # prevent GC of code func.__doc__ = doc return func # - # linux x86_64 calling convention # # The calling convention of the System V AMD64 ABI is followed on GNU/Linux. The registers RDI, RSI, RDX, RCX, R8, and R9 are used for integer and memory address arguments and XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for floating point arguments. # # For system calls, R10 is used instead of RCX. Additional arguments are passed on the stack and the return value is stored in RAX. # # https://www.felixcloutier.com/x86/ # # RET in hex C3 just_return = create_callable_from_machine_code(b'\xC3') just_return() import distorm3 return_21_code = b'\x48\xB8\x15\x00\x00\x00\x00\x00\x00\x00\xC3' for offset, length, assembler, hex in distorm3.Decode(0, return_21_code, distorm3.Decode64Bits): print(f'{assembler}') return_21 = create_callable_from_machine_code(return_21_code, restype=ctypes.c_int64) return_21()
notebooks/Machine Code 001.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:learn-env] * # language: python # name: conda-env-learn-env-py # --- # + # Import libraries and packages # import PyPi package for cohort libraries using shortcut # #!pip install -U fsds_100719 # comment out after install so it won't run again # Import packages import fsds_100719 as fs from fsds_100719.imports import * #inline_rc = dict(mpl.rcParams) sns.set_style('whitegrid') import statsmodels.api as sm import statsmodels.stats.api as sms import statsmodels.formula.api as smf import scipy.stats as stats from scipy.stats import normaltest as normtest # D'Agostino and Pearson's omnibus test from collections import Counter from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler # #!pip install uszipcode #ignore pink warnings import warnings warnings.filterwarnings('ignore') # Allow for large # columns pd.set_option('display.max_columns', 0) # pd.set_option('display.max_rows','') # - # tips = sns.load_dataset("tips") # g = sns.FacetGrid(tips, col="time") # + tips = sns.load_dataset("tips") # g = sns.FacetGrid(tips, col="time") g = sns.FacetGrid(tips, col="sex", hue="smoker") g.map(plt.scatter, "total_bill", "tip", alpha=.7) g.add_legend(); # - g = sns.FacetGrid(tips, col="day", height=4, aspect=.5) g.map(sns.barplot, "sex", "total_bill"); ordered_days = tips.day.value_counts().index g = sns.FacetGrid(tips, row="day", row_order=ordered_days, height=1.7, aspect=4,) g.map(sns.distplot, "total_bill", hist=False, rug=True); pal = dict(Lunch="seagreen", Dinner="gray") g = sns.FacetGrid(tips, hue="time", palette=pal, height=5) g.map(plt.scatter, "total_bill", "tip", s=50, alpha=.7, linewidth=.5, edgecolor="white") g.add_legend(); g = sns.FacetGrid(tips, hue="sex", palette="Set1", height=5, hue_kws={"marker": ["^", "v"]}) g.map(plt.scatter, "total_bill", "tip", s=100, linewidth=.5, edgecolor="white") g.add_legend(); g = sns.FacetGrid(tips, col="smoker", margin_titles=True, height=4) g.map(plt.scatter, "total_bill", "tip", color="#338844", edgecolor="white", s=50, lw=1) for ax in g.axes.flat: ax.plot((0, 50), (0, .2 * 50), c=".2", ls="--") g.set(xlim=(0, 60), ylim=(0, 14)); # + def hexbin(x, y, color, **kwargs): cmap = sns.light_palette(color, as_cmap=True) plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs) with sns.axes_style("dark"): g = sns.FacetGrid(tips, hue="time", col="time", height=4) g.map(hexbin, "total_bill", "tip", extent=[0, 50, 0, 10]); # - iris = sns.load_dataset("iris") # g = sns.PairGrid(iris) g = sns.pairplot(iris, hue="species", palette="Set2", diag_kind="kde", height=2.5) # + names = [ 'mpg' , 'cylinders' , 'displacement' , 'horsepower' , 'weight' , 'acceleration' , 'model_year' , 'origin' , 'car_name' ] df = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data", sep='\s+', names=names) df['maker'] = df.car_name.map(lambda x: x.split()[0]) df.origin = df.origin.map({1: 'America', 2: 'Europe', 3: 'Asia'}) df=df.applymap(lambda x: np.nan if x == '?' else x).dropna() df['horsepower'] = df.horsepower.astype(float) df.head() # + g = sns.pairplot(df[["mpg", "horsepower", "weight", "origin"]], hue="origin", diag_kind="hist") for ax in g.axes.flat: plt.setp(ax.get_xticklabels(), rotation=45) # - df['tons'] = (df.weight/2000).astype(int) g = sns.FacetGrid(df, col="origin", row="tons") g.map(sns.kdeplot, "horsepower", "mpg") plt.xlim(0, 250) plt.ylim(0, 60) sns.factorplot(data=df, x="model_year", y="mpg", col="origin") sns.factorplot(data=df, x="model_year", y="mpg") # + ### # Re-cast REGION and Countries into quadrant based on global hemispheres: NW, NE, SW, SE ### # grouped bar plot with sem and Value Labels above bars labels = ['G1', 'G2', 'G3', 'G4', 'G5'] men_means = [20, 34, 30, 35, 27] women_means = [25, 32, 34, 20, 25] x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, men_means, width, label='Men') rects2 = ax.bar(x + width/2, women_means, width, label='Women') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show() # + from numpy.random import beta # import matplotlib.pyplot as plt plt.style.use('bmh') def plot_beta_hist(ax, a, b): ax.hist(beta(a, b, size=10000), histtype="stepfilled", bins=25, alpha=0.8, density=True) fig, ax = plt.subplots() plot_beta_hist(ax, 10, 10) plot_beta_hist(ax, 4, 12) plot_beta_hist(ax, 50, 12) plot_beta_hist(ax, 6, 55) ax.set_title("'bmh' style sheet") plt.show() # + methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'] # Fixing random state for reproducibility np.random.seed(19680801) grid = np.random.rand(4, 4) fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6), subplot_kw={'xticks': [], 'yticks': []}) for ax, interp_method in zip(axs.flat, methods): ax.imshow(grid, interpolation=interp_method, cmap='viridis') ax.set_title(str(interp_method)) plt.tight_layout() plt.show() # + from scipy import stats def print_normtest(x,label=None,as_series=False): """Runs scipy.stats.normaltest and prints results, may also return them if as_series=True """ if label is None: try: label=x.name except: label='' results = ['Survived','Norm Stat','p value','(p<0.05)'] out = stats.normaltest(x) values = [label, out.statistic.round(3), out.pvalue.round(4), out.pvalue<0.05] results=dict(zip(results,values)) print(f"\n--- stats.normtest results:") [print(f"{k:{15}} : {v}")for k,v in results.items()] if as_series: return pd.Series(results) # + # for col in x_cols: # sns.catplot(x=col, y='price', height=10, legend=True, data=df) # + # OVERLAPPING DENSITIES (RIDGE PLOT) sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)}) # Create the data rs = np.random.RandomState(1979) x = g = np.tile(list("ABCDEFGHIJ"), 50) df = pd.DataFrame(dict(x=x, g=g)) #df = pd.DataFrame(dict(x=x,g=g)) m = df.g.map(ord) df["x"] += m # Initialize the FacetGrid object pal = sns.cubehelix_palette(10, rot=-.25, light=.7) g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal) # Draw the densities in a few steps g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2) g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2) g.map(plt.axhline, y=0, lw=2, clip_on=False) # Define and use a simple function to label the plot in axes coordinates def label(x, color, label): ax = plt.gca() ax.text(0, .2, label, fontweight="bold", color=color, ha="left", va="center", transform=ax.transAxes) g.map(label, "x") # Set the subplots to overlap g.fig.subplots_adjust(hspace=-.25) # Remove axes details that don't play well with overlap g.set_titles("") g.set(yticks=[]) g.despine(bottom=True, left=True)
notes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # > 本文由 [简悦 SimpRead](http://ksria.com/simpread/) 转码, 原文地址 https://blog.csdn.net/lovewangtaotao/article/details/102907540 # # 前言 # -- # # 读研发论文难啊,之前所有的 blog 都写在了自己的笔记本上,因为觉的写的太好了浪费时间,自己可以看懂就够了,但是白岩松老师的 "机会大多数取决于别人背后怎么评价你" 和雄子的 “将复杂的问题直观的阐述思想” 还是让我有了很大的触动。所以以后我会多更新 blog,并且尽力将问题讲解透彻。 # # 问题起源 # ---- # # Xserver 可以说是第二次碰到了,之前玩 Ubuntu 的时候就是各种问题,但是每次都是以重装系统为结果。这次准备装 x11vnc 来捣鼓远程桌面的时候出现了问题,问题挺简单,也挺常见,也就是 display 变量和 xauthority 文件之类的。但是最关键的是 loggin greeting 界面连接不上,所以就花了一下午时间搞明白了,也解决了问题。 # # abstract # -------- # # 这篇 blog 解决以下几个问题 # # 1. Xserver 中一些经典概念 # 2. x11vnc 如何配置 - display -auth 参数 (见下文 Authority Process) # 3. gdm3 和 wayland 以及 greeting 界面下如何 x11vnc 配置 (no one logs in) (见下文 display manager + gdm3) # # Solution to Abstract # -------------------- # # 首先,Xserver 中有很多概念,这里只给出常见的: X 架构,Xserver,Xclient,Xsession,Xauthority file,MIT-MAGIC-COOKIES,display number, # **X architecture** : 所谓的 X 架构是一个开源的图像绘制架构,一般的 Linux 操作系统都是靠这个来实现 windows 下的桌面的。X 架构是一个 C/S 架构的软件,为 Xserver 和 Xclient。主要的团队好像是 Xorg,一般 linux 下 X11 或者 Xorg 啥的就是和这个相关的软件或者配置文件。 # # **Xserver**: 作为 X 架构的中心,Xserver 负责处理处理输入,将输入传送给 XClient,接受 XClient 的绘制请求并且绘图。和 Windows 不一样,Xserver 的绘制服务器可以有多个!!每个对应了一个 Display,这点很关键。 # # **Xclient** : 简单的讲,就是我们的每一个 Application。例如,gnome-terminal, firefox 等。这些程序包含了具体的绘制代码。学习过 windows 窗口机制就知道,application 绘制代码其实是对不同的 Event 向 Xserver 发送绘制操作,具体绘制的过程是靠 Xserver 实现的。这样的好处是 Xserver 可以给每个 Xclient 维护有效区,app 端就不要考虑这些重叠啥的东西了。 # # **Display**:每个 Xserver 和一个 display 标志相对应。display 是 $local_host:$display_num.$sceen_num 的格式。例如 ":0.0" , "127.0.0.1:1.0" # 都是合法的。具体 man x 。然后有个 DISPLAY 栏目专门讲的格式。 # # **Connection Process** 连接和安全是 C/S 架构很关键的一点。这里讲解具体的过程: # 首先,要想运行一个 XClient 程序,必须要启动一个 Xserver,这个过程可以使用多个方法,例如 startx,或者是一个 display manager(下面会讲)。启动之后会有一个 display number,如果你的 Server 是第一个那就是: 0 第二个就是 :1 # 然后,XClient 只是负责绘制的,所以需要连接到 Xserver 才可以实现图形的绘制,所以我们需要给 XClient 提供,因此 $DISPLAY 变量作为 XServer 的标识符需要被提供,但是为了解决安全问题,需要一个验证机制 XSecurity(后面 Authority Process 有具体过程),因此为了连接成功,还需要提供要给 xauth 文件(后面 Authority Process 会讲具体如何寻找个文件),这个文件的位置通过 $XAUTHORITY 传递,然后 XClient 通过一定解析,发送给 XServer,如果验证通过,就相当于是通过了验证,这个 XClient 就可以绘图了。如果没有,那么就会有一些无法连接的错误之类的。 # # **Authority Process** 验证过程有很多个步骤,具体可以看 man xsecurity 。这里讲解一下什么是 MIT-MAGIC-COOKIES 验证和 host 验证。首先 xhost 可以添加和删除信任列表。列表如果是空,那么全都可以信任,否则只有在列表上的才可以进行连接。这个方法只可以控制 host 阶段的一些验证问题,同一个机器的的不同程序就无法判断了,所以有后面的 COOKIES 验证机制。COOKIES 机制是最为关键的,因为很多都是使用这个方法。原理很简单,那就是在每个 XServer 中都有一个可接受的 COOKIES,是个特定格式的字符串。然后每个连接都要附带这个信息,如果存在,那么就可以,否则失败。 XServer 中 Cookies 是在启动的时候指定的一个 xauthority 文件。 X -auth=XXX 中的 auth 参数就是文件,这个文件一般是 Display Manager(后面会讲)生成的,然后由 DM 管理。所以需要得到正确的 COOKIES 需要知道启动 X 的时候 - auth 指定的是哪个 xauthority 文件,这个文件就是包含了 COOKIES 的文件,要是想要做实验的,可以通过 xauth -f FILE_NAME 然后 list 命令来看到具体的 cookies 是什么。 同时我们可以通过 ps aux | grep Xorg 来看到服务器启动时候的命令,来找到最关键的 -auth 文件位置,有了上面的知识,基本上就没问题了,都可以完美运行 x11vnc 或者别的 XClient 了。 # # **Display Manager** 因为一个主机可有多个 Display,也就是多个 XServer,一般是一个 User 一个,所以有的软件负责管理 Xserver。这些软件就是 Display Manager(DM),这些软件的主要作用就是:greetting 界面来问候,请求输入密码和账号,然后验证,成功之后启动一个 XServer,并且生成和管理 xauthority 文件,并且设置 $DISPLAY $XAUTHORITY 环境变量。主要目的就是将这些过程对用户透明化。这也是为什么很多人不需要知道这些细节的原因。我们这里关心的就是 Display Manager 是如何生成 xauthority 文件的(因为我们需要,但是其实通过 ps 的方法可以直接找出来,所以也不是很关键。)。这些软件的例子有很多,例如 gdm gdm3 xdm lightdm 都是,而且他们有不同的行为,所以当你发现你的问题在这里的话,一定要记得去看文档,而不是一味的谷歌,文档才是最核心的东西。 # # **GDM3** 我使用的是 GDM3,所以这里我来解析一下 GDM3 的一些坑点。首先文档我只找到了 GDM 的,而且很不一样。其中一个还可以的是 man gdm3 有一些资料。所以通过一些探索,这里记录一下没有的东西。 最关键的一点就是,GDM3 的登陆界面,可能没有 Xserver。但是 GDM3 确实是图形界面啊,是的,它使用了一个新的 wayland 图形架构,具体可以维基百科一下,简单来说,这个东西的作者和 X 架构是同一个人,然后他为了改良 X 中的一些低效的环节,重新设计了这个架构,这个架构更加简单,但是还在开发测试阶段。所以在 greeting 阶段是没有 Xserver 的,所以 x11vnc 是不可以连接的,也就是当电脑没有用户登陆的时候,不可以通过 x11vnc 远程桌面,一定会显示 can’t open display :0 等的错误。所以需要在 /etc/gdm3/custom.conf 中 uncomment 掉一个 wayland 相关的参数(会有英文提示),然后就可以了。但是注意这样的话,greetting 的 display number 为 :0 ,你登陆之后启动的用户的 Xserver 是 display number 2。所以需要建立两个 x11vnc 监听。 # # **x11vnc 总体过程**: 先注释掉 wayland,重启,在 greeting 界面的时候,通过远程登陆 / tty / 登陆之后 ps aux | grep -i xorg 看 auth 是哪个 (如果登陆了,有两个,一个是 greet 的,一个是用户的,一般是 1000 是用户,121 是登陆界面的 auth 文件),然后: # # ``` # x11vnc -auth 上面的file -display :0 #greetting用户 # x11vnc -auth 上面的file -display :1 #用户 # ``` # # **Xserver 的 port 映射** Xserver 对应的 port(如果开启了 TCP,可以在 gdm 的配置文件中开启,具体看 gdm 文档和 gdm3 节)。6000+display number 是监听端口,可使用 netstat -nap + 来看 # # _**reference:**_ linux man page
技术/XServer基本概念 + x11vnc配置远程桌面.ipynb
# ## OpenCV Integration Example # Note: SwiftCV package requires OpenCV installed in order to compile. # Uncomment line below when using Colab (this installs OpenCV4) # %system SwiftCV/install/install_colab.sh %install-location $cwd/swift-install %install '.package(path: "$cwd/SwiftCV")' SwiftCV %install '.package(path: "$cwd/FastaiNotebook_08_data_block")' FastaiNotebook_08_data_block # ### Imports %include "EnableIPythonDisplay.swift" import Foundation import SwiftCV import Path import FastaiNotebook_08_data_block // display opencv version print(cvVersion()) # ### Load image func readImage(_ path:String)->Mat { let cvImg = imread(path) return cvtColor(cvImg, nil, ColorConversionCode.COLOR_BGR2RGB) } let path = downloadImagenette(sz:"") let allNames = fetchFiles(path: path/"train/n03425413", recurse: false, extensions: ["jpeg", "jpg"]) let fNames = Array(allNames[0..<256]) let ns = fNames.map {$0.string} let imgpath = ns[2] var cvImg = readImage(imgpath) # ### Timing cvImg.size print(type(of:cvImg.dataPtr)) # [next slide](https://docs.google.com/presentation/d/1dc6o2o-uYGnJeCeyvgsgyk05dBMneArxdICW5vF75oU/edit#slide=id.g512a2e238a_144_0) let ptr = UnsafeRawPointer(cvImg.dataPtr).assumingMemoryBound(to: UInt8.self) ptr[2] time(repeating:10) {_ = readImage(imgpath)} cvImg.rows import Python import TensorFlow let plt = Python.import("matplotlib.pyplot") let np = Python.import("numpy") IPythonDisplay.shell.enable_matplotlib("inline") func show_img(_ img: Mat, _ w: Int = 7, _ h: Int = 5) { show_img(Tensor<UInt8>(cvMat: img)!, w, h) } show_img(cvImg) time(repeating:10) {_ = resize(cvImg, nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_NEAREST)} time(repeating:10) {_ = resize(cvImg, nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_LINEAR)} time(repeating:10) {_ = resize(cvImg, nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_CUBIC)} time(repeating:10) {_ = resize(cvImg, nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_AREA)} cvImg = resize(cvImg, nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_CUBIC) func readResized(_ fn:String)->Mat { return resize(readImage(fn), nil, Size(224, 224), 0, 0, InterpolationFlag.INTER_CUBIC) } var imgs = ns[0..<10].map(readResized) time(repeating:10) {_ = readResized(imgpath)} # + public protocol Countable { var count:Int {get} } extension Mat :Countable {} extension Array:Countable {} public extension Sequence where Element:Countable { var totalCount:Int { return map{ $0.count }.reduce(0, +) } } # - func collateMats(_ imgs:[Mat])->Tensor<Float> { let c = imgs.totalCount let ptr = UnsafeMutableRawPointer.allocate(byteCount: c, alignment: 1) defer {ptr.deallocate()} var p = ptr for img in imgs { p.copyMemory(from: img.dataPtr, byteCount: img.count) p += img.count } let r = UnsafeBufferPointer(start: ptr.bindMemory(to: UInt8.self, capacity: c), count: c) cvImg = imgs[0] let shape = TensorShape([imgs.count, cvImg.rows, cvImg.cols, cvImg.channels]) let res = Tensor(shape: shape, scalars: r) return Tensor<Float>(res)/255.0 } var t = collateMats(imgs) t.shape show_img(t[2]) time(repeating:10) {_ = collateMats(imgs)} time { _ = ns.map(readResized) } # ### OpenCV Transformations # #### Resize show_img( resize(cvImg, nil, Size(100, 50), 0, 0, InterpolationFlag.INTER_AREA) ) # #### Zoom / Crop let zoomMat = getRotationMatrix2D(Size(cvImg.cols, cvImg.rows / 2), 0, 1) show_img( warpAffine(cvImg, nil, zoomMat, Size(600, 600)) ) # #### Rotate let rotMat = getRotationMatrix2D(Size(cvImg.cols / 2, cvImg.rows / 2), 20, 1) show_img( warpAffine(cvImg, nil, rotMat, Size(cvImg.cols, cvImg.rows)) ) # #### Pad show_img( copyMakeBorder(cvImg, nil, 40, 40, 40, 40, BorderType.BORDER_CONSTANT, RGBA(0, 127, 0, 0)) ) # #### Blur show_img( GaussianBlur(cvImg, nil, Size(25, 25)) ) # #### Flip show_img( flip(cvImg, nil, FlipMode.HORIZONTAL) ) # #### Transpose show_img( transpose(cvImg, nil) )
nbs/swift/opencv_integration_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # PHP 2020 # <img src="https://www.php.net/images/logos/new-php-logo.svg" width="40%"/> # Welcome to the PHP course! # The [Jupyter](https://jupyter.org/) notebooks will be used throughout the course to organise the exercises. The instructions will be usually minimal, and the focus will be put on practical coding aspects. There will be two types of notebooks used in PHP course: tutorial notebooks with bash commands (Python 3 kernel) and notebooks with pure PHP code (PHP kernel). The type of used kernel can be found in the upper-right corner. # To start working with the course material, select one of below topics: # # 01. [Platform](01_platform/index.ipynb) # 02. [Superglobals](02_superglobals/index.ipynb) # 03. [Pretty URL](03_pretty_url/index.ipynb) # 04. [Object-Oriented Programming](04_object_oriented/index.ipynb) # 05. [PHP Data Objects](05_data_objects/index.ipynb) # 06. [Dependency Manager](06_dependency_manager/index.ipynb) # 07. [Testing](07_testing/index.ipynb) # 08. [Laravel](08_laravel/index.ipynb) # 09. [Laravel TDD](09_laravel_tdd/index.ipynb) # 10. [Laravel TDD](10_laravel_tdd/index.ipynb)
public/media/2/index.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- import holoviews as hv from holoviews import opts from holoviews.streams import PointDraw hv.extension('bokeh') # ## Declaring data points = hv.Points([(0, 0), (0.5, 0.5), (1, 0)]) point_stream = PointDraw(data=points.columns(), source=points) trimesh = hv.DynamicMap(hv.TriMesh.from_vertices, streams=[point_stream]) # ## Plot (trimesh * points).opts( opts.Points(width=500, height=500, size=10, line_color='black', nonselection_alpha=0.3)) # <center><img src="https://assets.holoviews.org/gifs/gallery/demos/bokeh/point_draw_triangulate.gif" width=500></center>
examples/gallery/demos/bokeh/point_draw_triangulate.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # This notebook shows the process of extracting features from the face. It detects 68 facial landmarks using `opencv` and `dlib`. Based on this video: https://www.youtube.com/watch?v=MrRGVOhARYY # + tags=[] import numpy as np import cv2 import dlib cap = cv2.VideoCapture("../resources/test_video.mp4") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("../resources/shape_predictor_68_face_landmarks.dat") while(True): _, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) for face in faces: x1 = face.left() y1 = face.top() x2 = face.right() y2 = face.bottom() cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 5) landmarks = predictor(gray, face) for i in range(68): x = landmarks.part(i).x y = landmarks.part(i).y cv2.circle(frame, (x, y), 3, (0, 255, 0), -1) cv2.imshow('frame', frame) key = cv2.waitKey(1) if key == 27: break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
notebooks/face_extract.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.7 # language: julia # name: julia-0.7 # --- # # Recursive resumable function # # Example provided by @mohamed82008 # ## Description # # Given a vector with as elements values or other vectors, iterate over all the values, i.e. $a=[[1, 2, 3], [4, 5, 6]]$ will have as output an iterator containing the elements $1, 2, 3, 4, 5, 6$. # ## Package installation Pkg.update() Pkg.add("ResumableFunctions") # ## Use ResumableFunctions.jl using ResumableFunctions # ## Define `@resumable function` @resumable function g(x) if isa(x, Number) @yield x else for i in x for j in g(i) @yield j end end end end # ## Test # + a = [0, [1,2,3],[4,5,6]] for i in g(a) println(i) end # -
examples/Recursive resumable function.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Cost Search # In this exercise you'll implement extend breadth-first search by incorporating a cost penalty. from queue import Queue, PriorityQueue import numpy as np from enum import Enum # https://wiki.python.org/moin/TimeComplexity gives a solid overview of Python data structures and their time complexity. # * [`Enum`](https://docs.python.org/3/library/enum.html#module-enum) is used to represent possible actions on the grid. # * A [`PriorityQueue`](https://docs.python.org/3/library/queue.html#queue.PriorityQueue) is used in order to prioritize expanding nodes with lower cost. The naive approach would take `O(n)` time since we would scan the entire queue to determine the position of the item. A `PriorityQueue` allows this insertion to be done in `O(log(n))` time instead. # + class Action(Enum): """ An action is represented by a 3 element tuple. The first 2 values are the delta of the action relative to the current grid position. The third and final value is the cost of performing the action. """ LEFT = (0, -1, 1) RIGHT = (0, 1, 1) UP = (-1, 0, 1) DOWN = (1, 0, 1) def __str__(self): if self == self.LEFT: return '<' elif self == self.RIGHT: return '>' elif self == self.UP: return '^' elif self == self.DOWN: return 'v' @property def cost(self): return self.value[2] @property def delta(self): return (self.value[0], self.value[1]) def valid_actions(grid, current_node): """ Returns a list of valid actions given a grid and current node. """ valid = [Action.UP, Action.LEFT, Action.RIGHT, Action.DOWN] n, m = grid.shape[0] - 1, grid.shape[1] - 1 x, y = current_node # check if the node is off the grid or # it's an obstacle if x - 1 < 0 or grid[x-1, y] == 1: valid.remove(Action.UP) if x + 1 > n or grid[x+1, y] == 1: valid.remove(Action.DOWN) if y - 1 < 0 or grid[x, y-1] == 1: valid.remove(Action.LEFT) if y + 1 > m or grid[x, y+1] == 1: valid.remove(Action.RIGHT) return valid def visualize_path(grid, path, start): sgrid = np.zeros(np.shape(grid), dtype=np.str) sgrid[:] = ' ' sgrid[grid[:] == 1] = 'O' pos = start for a in path: da = a.value sgrid[pos[0], pos[1]] = str(a) pos = (pos[0] + da[0], pos[1] + da[1]) sgrid[pos[0], pos[1]] = 'G' sgrid[start[0], start[1]] = 'S' return sgrid # - # ### Cost Search # # In this section you will extend the breadth-first search algorithm by incorporating a cost for each action. Your task is to compute the lowest cost path. # # You will need to implement the remaining `TODOs`. def uniform_cost(grid, start, goal): # TODO: Initialize the starting variables path = [] queue = PriorityQueue() queue.put((0, start)) visited = set(start) branch = {} found = False while not queue.empty(): # TODO: Remove the first element from the queue item = queue.get() current_cost = item[0] current_node = item[1] # TODO: Check if the current vertex corresponds to the goal state # and set `found` to True if that's the case. if current_node == goal: print('Found a path.') found = True break else: for action in valid_actions(grid, current_node): # get the tuple representation da = action.delta cost = action.cost next_node = (current_node[0] + da[0], current_node[1] + da[1]) new_cost = current_cost + cost # TODO: Check if the new vertex has not been visited before. # If the node has not been visited you will need to # 1. Mark it as visited # 2. Add it to the queue if next_node not in visited: visited.add(next_node) queue.put((new_cost, next_node)) branch[next_node] = (new_cost, current_node, action) path = [] path_cost = 0 if found: # retrace steps path = [] n = goal path_cost = branch[n][0] while branch[n][1] != start: path.append(branch[n][2]) n = branch[n][1] path.append(branch[n][2]) return path[::-1], path_cost # ### Executing the search # # Run `uniform_cost()` and reference the grid to see if the path makes sense. # + start = (0, 0) goal = (4, 4) grid = np.array([ [0, 1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0], ]) # - path, path_cost = uniform_cost(grid, start, goal) print(path_cost, path) # S -> start, G -> goal, O -> obstacle visualize_path(grid, path, start)
Cost Search.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Data Loading Tutorial # cd ../.. save_path = 'data/' from scvi.dataset import LoomDataset, CsvDataset, Dataset10X, AnnDataset import urllib.request import os from scvi.dataset import BrainLargeDataset, CortexDataset, PbmcDataset, RetinaDataset, HematoDataset, CbmcDataset, BrainSmallDataset, SmfishDataset # ## Generic Datasets # `scvi v0.1.3` supports dataset loading for the following three generic file formats: # * `.loom` files # * `.csv` files # * `.h5ad` files # * datasets from `10x` website # # Most of the dataset loading instances implemented in scvi use a positional argument `filename` and an optional argument `save_path` (value by default: `data/`). Files will be downloaded or searched for at the location `os.path.join(save_path, filename)`, make sure this path is valid when you specify the arguments. # ### Loading a `.loom` file # Any `.loom` file can be loaded with initializing `LoomDataset` with `filename`. # # Optional parameters: # * `save_path`: save path (default to be `data/`) of the file # * `url`: url the dataset if the file needs to be downloaded from the web # * `new_n_genes`: the number of subsampling genes - set it to be `False` to turn off subsampling # * `subset_genes`: a list of gene names for subsampling # Loading a remote dataset remote_loom_dataset = LoomDataset("osmFISH_SScortex_mouse_all_cell.loom", save_path=save_path, url='http://linnarssonlab.org/osmFISH/osmFISH_SScortex_mouse_all_cells.loom') # Loading a local dataset local_loom_dataset = LoomDataset("osmFISH_SScortex_mouse_all_cell.loom", save_path=save_path) # ### Loading a `.csv` file # Any `.csv` file can be loaded with initializing `CsvDataset` with `filename`. # # Optional parameters: # * `save_path`: save path (default to be `data/`) of the file # * `url`: url of the dataset if the file needs to be downloaded from the web # * `compression`: set `compression` as `.gz`, `.bz2`, `.zip`, or `.xz` to load a zipped `csv` file # * `new_n_genes`: the number of subsampling genes - set it to be `False` to turn off subsampling # * `subset_genes`: a list of gene names for subsampling # # Note: `CsvDataset` currently only supoorts `.csv` files that are genes by cells. # If the dataset has already been downloaded at the location `save_path`, it will not be downloaded again. # Loading a remote dataset remote_csv_dataset = CsvDataset("GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", save_path=save_path, compression='gzip', url = "https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE100866&format=file&file=GSE100866%5FCBMC%5F8K%5F13AB%5F10X%2DRNA%5Fumi%2Ecsv%2Egz") # Loading a local dataset local_csv_dataset = CsvDataset("GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", save_path=save_path, compression='gzip') # ### Loading a `.h5ad` file # [AnnData](http://anndata.readthedocs.io/en/latest/) objects can be stored in `.h5ad` format. Any `.h5ad` file can be loaded with initializing `AnnDataset` with `filename`. # # Optional parameters: # * `save_path`: save path (default to be `data/`) of the file # * `url`: url the dataset if the file needs to be downloaded from the web # * `new_n_genes`: the number of subsampling genes - set it to be `False` to turn off subsampling # * `subset_genes`: a list of gene names for subsampling # Loading a local dataset local_ann_dataset = AnnDataset("TM_droplet_mat.h5ad", save_path = save_path) # ### Loading a file from `10x` website # If the dataset has already been downloaded at the location `save_path`, it will not be downloaded again. # `10x` has published several datasets on their [website](https://www.10xgenomics.com). # Initialize `Dataset10X` by passing in the dataset name of one of the following datasets that `scvi` currently supports: `frozen_pbmc_donor_a`, `frozen_pbmc_donor_b`, `frozen_pbmc_donor_c`, `pbmc8k`, `pbmc4k`, `t_3k`, `t_4k`, and `neuron_9k`. # # Optional parameters: # * `save_path`: save path (default to be `data/`) of the file # * `type`: set `type` (default to be `filtered`) to be `filtered` or `raw` to choose one from the two datasets that's available on `10X` # * `new_n_genes`: the number of subsampling genes - set it to be `False` to turn off subsampling tenX_dataset = Dataset10X("neuron_9k", save_path=save_path) # ### Loading local `10x` data # It is also possible to create a Dataset object from 10X data saved locally. Initialize Dataset10X by passing in the optional remote argument as False to specify you're loading local data and give the name of the directory that contains the gene expression matrix and gene names of the data as well as the path to this directory. # If your data (the genes.tsv and matrix.mtx files) is located inside the directory 'mm10' which is located at 'data/10X/neuron_9k/filtered_gene_bc_matrices/'. Then filename should have the value 'mm10' and save_path should be the path to the directory containing 'mm10'. local_10X_dataset = Dataset10X('mm10', save_path=os.path.join(save_path, '10X/neuron_9k/filtered_gene_bc_matrices/'), remote=False) # ## Built-In Datasets # We've also implemented seven built-in datasets to make it easier to reproduce results from the scVI paper. # # * **PBMC**: 12,039 human peripheral blood mononuclear cells profiled with 10x; # * **RETINA**: 27,499 mouse retinal bipolar neurons, profiled in two batches using the Drop-Seq technology; # * **HEMATO**: 4,016 cells from two batches that were profiled using in-drop; # * **CBMC**: 8,617 cord blood mononuclear cells profiled using 10x along with, for each cell, 13 well-characterized mononuclear antibodies; # * **BRAIN SMALL**: 9,128 mouse brain cells profiled using 10x. # * **BRAIN LARGE**: 1.3 million mouse brain cells profiled using 10x; # * **CORTEX**: 3,005 mouse Cortex cells profiled using the Smart-seq2 protocol, with the addition of UMI # * **SMFISH**: 4,462 mouse Cortex cells profiled using the osmFISH protocol # * **DROPSEQ**: 71,639 mouse Cortex cells profiled using the Drop-Seq technology # * **STARMAP**: 3,722 mouse Cortex cells profiled using the STARmap technology # ### Loading `STARMAP` dataset # `StarmapDataset` consists of 3722 cells profiled in 3 batches. The cells come with spatial coordinates of their location inside the tissue from which they were extracted and cell type labels retrieved by the authors ofthe original publication. # # Reference: X.Wang et al., Science10.1126/science.aat5691 (2018) # ### Loading `DROPSEQ` dataset # `DropseqDataset` consists of 71,639 mouse Cortex cells profiled using the Drop-Seq technology. To facilitate comparison with other methods we use a random filtered set of 15000 cells and then keep only a filtered set of 6000 highly variable genes. Cells have cell type annotaions and even sub-cell type annotations inferred by the authors of the original publication. # # Reference: https://www.biorxiv.org/content/biorxiv/early/2018/04/10/299081.full.pdf # ### Loading `SMFISH` dataset # `SmfishDataset` consists of 4,462 mouse cortex cells profiled using the OsmFISH protocol. The cells come with spatial coordinates of their location inside the tissue from which they were extracted and cell type labels retrieved by the authors of the original publication. # # Reference: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Spatial organization of the somatosensory cortex revealed by cyclic smFISH. bioRxiv, 2018. smfish_dataset = SmfishDataset(save_path=save_path) # ### Loading `BRAIN-LARGE` dataset # # <font color='red'>Loading BRAIN-LARGE requires at least 32 GB memory!</font> # # `BrainLargeDataset` consists of 1.3 million mouse brain cells, spanning the cortex, hippocampus and subventricular zone, and profiled with 10x chromium. We use this dataset to demonstrate the scalability of scVI. It can be used to demonstrate the scalability of scVI. # # Reference: 10x genomics (2017). URL https://support.10xgenomics.com/single-cell-gene-expression/datasets. brain_large_dataset = BrainLargeDataset(save_path=save_path) # ### Loading `CORTEX` dataset # `CortexDataset` consists of 3,005 mouse cortex cells profiled with the Smart-seq2 protocol, with the addition of UMI. To facilitate com- parison with other methods, we use a filtered set of 558 highly variable genes. The `CortexDataset` exhibits a clear high-level subpopulation struc- ture, which has been inferred by the authors of the original publication using computational tools and annotated by inspection of specific genes or transcriptional programs. Similar levels of annotation are provided with the `PbmcDataset` and `RetinaDataset`. # # Reference: <NAME>. et al. Cell types in the mouse cortex and hippocampus revealed by single-cell rna-seq. Science 347, 1138–1142 (2015). cortex_dataset = CortexDataset(save_path=save_path) # ### Loading `PBMC` dataset # `PbmcDataset` consists of 12,039 human peripheral blood mononu- clear cells profiled with 10x. # # Reference: Zheng, <NAME>. et al. Massively parallel digital transcriptional profiling of single cells. Nature Communications 8, 14049 (2017). pbmc_dataset = PbmcDataset(save_path=save_path) # ### Loading `RETINA` dataset # `RetinaDataset` includes 27,499 mouse retinal bipolar neu- rons, profiled in two batches using the Drop-Seq technology. # # Reference: <NAME>. et al. Comprehensive classification of retinal bipolar neurons by single-cell transcriptomics. Cell 166, 1308–1323.e30 (2017). retina_dataset = RetinaDataset(save_path=save_path) # ### Loading `HEMATO` dataset # `HematoDataset` includes 4,016 cells from two batches that were profiled using in-drop. This data provides a snapshot of hematopoietic progenitor cells differentiating into various lineages. We use this dataset as an example for cases where gene expression varies in a continuous fashion (along pseudo-temporal axes) rather than forming discrete subpopulations. # # Reference: <NAME>. et al. Population snapshots predict early haematopoietic and erythroid hierarchies. Nature 555, 54–60 (2018). hemato_dataset = HematoDataset(save_path=os.path.join(save_path, 'HEMATO/')) # ### Loading `CBMC` dataset # `CbmcDataset` includes 8,617 cord blood mononuclear cells pro- filed using 10x along with, for each cell, 13 well-characterized mononuclear antibodies. We used this dataset to analyze how the latent spaces inferred by dimensionality-reduction algorithms summarize protein marker abundance. # # Reference: <NAME>. et al. Simultaneous epitope and transcriptome measurement in single cells. Nature Methods 14, 865–868 (2017). cbmc_dataset = CbmcDataset(save_path=os.path.join(save_path, "citeSeq/")) # ### Loading `BRAIN-SMALL` dataset # `BrainSmallDataset` consists of 9,128 mouse brain cells profiled using 10x. This dataset is used as a complement to PBMC for our study of zero abundance and quality control metrics correlation with our generative posterior parameters. # # Reference: brain_small_dataset = BrainSmallDataset(save_path=save_path) def allow_notebook_for_test(): print("Testing the data loading notebook")
tests/notebooks/data_loading.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import pandas as pd import numpy as np import pkg_resources import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline import model_bias_analysis # autoreload makes it easier to interactively work on code in the model_bias_analysis module. # %load_ext autoreload # %autoreload 2 # - model_families = [ ['wiki_cnn_v3_100'],#, 'wiki_cnn_v3_101', 'wiki_cnn_v3_102'], #['wiki_debias_cnn_v3_100', 'wiki_debias_cnn_v3_101', 'wiki_debias_cnn_v3_102'], ] # Read the scored data into DataFrame balanced_madlibs = pd.read_csv('eval_datasets/bias_madlibs_77k_scored.csv') # Add columns for each subgroup. f = open('bias_madlibs_data/adjectives_people.txt', 'r') terms = [line.strip() for line in f] model_bias_analysis.add_subgroup_columns_from_text(balanced_madlibs, 'text', terms) # + def skew_group(balanced, subgroup, label): non_toxic_subgroup_items = balanced[balanced[subgroup] & ~balanced[label]] drop_indices = np.random.choice( non_toxic_subgroup_items.index, len(non_toxic_subgroup_items) // 2, replace=False) return balanced.drop(drop_indices) unbalanced_madlibs = balanced_madlibs for group in ['lesbian', 'gay', 'bisexual', 'transgender', 'trans', 'queer']: unbalanced_madlibs = skew_group(unbalanced_madlibs, group, 'label') len(unbalanced_madlibs) # - eq_diff = model_bias_analysis.per_subgroup_auc_diff_from_overall( balanced_madlibs, terms, model_families, squared_error=True, normed_auc=False) # sort to guarantee deterministic output eq_diff.sort_values(by=['model_family'], inplace=True) eq_diff.reset_index(drop=True, inplace=True) eq_diff.style.background_gradient() eq_diff = model_bias_analysis.per_subgroup_auc_diff_from_overall( unbalanced_madlibs, terms, model_families, squared_error=True, normed_auc=False) # sort to guarantee deterministic output eq_diff.sort_values(by=['model_family'], inplace=True) eq_diff.reset_index(drop=True, inplace=True) eq_diff.style.background_gradient() eq_diff = model_bias_analysis.per_subgroup_auc_diff_from_overall( balanced_madlibs, terms, model_families, squared_error=True, normed_auc=True) # sort to guarantee deterministic output eq_diff.sort_values(by=['model_family'], inplace=True) eq_diff.reset_index(drop=True, inplace=True) eq_diff.style.background_gradient() eq_diff = model_bias_analysis.per_subgroup_auc_diff_from_overall( unbalanced_madlibs, terms, model_families, squared_error=True, normed_auc=True) # sort to guarantee deterministic output eq_diff.sort_values(by=['model_family'], inplace=True) eq_diff.reset_index(drop=True, inplace=True) eq_diff.style.background_gradient() balanced_pinned_auc_results = model_bias_analysis.per_subgroup_aucs(balanced_madlibs, terms, model_families, 'label') unbalanced_pinned_auc_results = model_bias_analysis.per_subgroup_aucs(unbalanced_madlibs, terms, model_families, 'label') # + #df = pd.DataFrame() subgroups = list(balanced_pinned_auc_results.subgroup) balanced_pinned_aucs = [a[0] for a in balanced_pinned_auc_results.wiki_cnn_v3_100_aucs] balanced_normed_pinned_aucs = [a[0] for a in balanced_pinned_auc_results.wiki_cnn_v3_100_normalized_pinned_aucs] unbalanced_pinned_aucs = [a[0] for a in unbalanced_pinned_auc_results.wiki_cnn_v3_100_aucs] unbalanced_normed_pinned_aucs = [a[0] for a in unbalanced_pinned_auc_results.wiki_cnn_v3_100_normalized_pinned_aucs] df = pd.DataFrame({'subgroup': subgroups, 'pinned_auc_balanced_set': balanced_pinned_aucs, 'normed_pinned_auc_balanced_set': balanced_normed_pinned_aucs, 'pinned_auc_unbalanced_set': unbalanced_pinned_aucs, 'normed_pinned_auc_unbalanced_set': unbalanced_normed_pinned_aucs, }, columns=['subgroup', 'pinned_auc_balanced_set', 'pinned_auc_unbalanced_set', 'normed_pinned_auc_balanced_set', 'normed_pinned_auc_unbalanced_set']) df['pinned_auc_diff'] = df['pinned_auc_balanced_set'] - df['pinned_auc_unbalanced_set'] df['normed_pinned_auc_diff'] = df['normed_pinned_auc_balanced_set'] - df['normed_pinned_auc_unbalanced_set'] df[0:14].style.set_precision(3) # - for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( balanced_pinned_auc_results, 'subgroup', name + '_aucs', title=name + ' Pinned AUC (Balanced Set)', y_lim=(0.8, 1.0)) for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( unbalanced_pinned_auc_results, 'subgroup', name + '_aucs', title=name + ' Pinned AUC (Unbalanced Set)', y_lim=(0.8, 1.0)) for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( balanced_pinned_auc_results, 'subgroup', name + '_normalized_pinned_aucs', title=name + ' Normalized Pinned AUC (Balanced Set)', y_lim=(0.8, 1.0)) for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( unbalanced_pinned_auc_results, 'subgroup', name + '_normalized_pinned_aucs', title=name + ' Normalized Pinned AUC (Unbalanced Set)', y_lim=(0.8, 1.0)) for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( balanced_pinned_auc_results, 'subgroup', name + '_within_negative_label_mwus', title=name + ' Within Negative Label MWUs', y_lim=(0.5, 1.0)) for family in model_families: name = model_bias_analysis.model_family_name(family) model_bias_analysis.per_subgroup_scatterplots( balanced_pinned_auc_results, 'subgroup', name + '_within_positive_label_mwus', title=name + ' Within Positive Label MWUs', y_lim=(0.5, 1.0))
unintended_ml_bias/mann_whitney_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Task 3 # # Imports import numpy as np import pandas as pd from joblib import dump, load from sklearn.metrics import mean_squared_error from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt plt.style.use('ggplot') plt.rcParams.update({'font.size': 16, 'axes.labelweight': 'bold', 'figure.figsize': (8,6)}) # ## Part 1: # Recall as a final goal of this project. We want to build and deploy ensemble machine learning models in the cloud, where features are outputs of different climate models and the target is the actual rainfall observation. In this milestone, you'll actually build these ensemble machine learning models in the cloud. # # **Your tasks:** # # 1. Read the data CSV from your s3 bucket. # 2. Drop rows with nans. # 3. Split the data into train (80%) and test (20%) portions with `random_state=123`. # 4. Carry out EDA of your choice on the train split. # 5. Train ensemble machine learning model using `RandomForestRegressor` and evaluate with metric of your choice (e.g., `RMSE`) by considering `Observed` as the target column. # 6. Discuss your results. Are you getting better results with ensemble models compared to the individual climate models? # # > Recall that individual columns in the data are predictions of different climate models. ## You could download it from your bucket, or you can use the file that I have in my bucket. ## You should be able to access it from my bucket using your key and secret aws_credentials ={"key": "<KEY>","secret": "<KEY>"} df = pd.read_csv("s3://mds-s3-student60/ml_data_SYD.csv", index_col=0, parse_dates=True) df = df.dropna() X = df.drop(columns=['observed']) y = df['observed'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123) X_train.describe() model = RandomForestRegressor(n_estimators=100, max_depth=20) model.fit(X_train,y_train) y_predicted = model.predict(X_train) train_rms = mean_squared_error(y_train, y_predicted, squared=False) train_rms y_predicted = model.predict(X_test) test_rms = mean_squared_error(y_test, y_predicted, squared=False) test_rms for col in X_test.columns.tolist(): print(f"model {col} RMSE: {mean_squared_error(y_test, X_test[col], squared=False)}") # > Yes, we are getting better results with the ensemble of models compared to the individual models as can be seen above. # ## Part 2: # ### Preparation for deploying model next week # #### Complete task 4 from the milestone3 before coming here # We’ve found ```n_estimators=100, max_depth=5``` to be the best hyperparameter settings with MLlib (from the task 4 from milestone3), here we then use the same hyperparameters to train a scikit-learn model. model = RandomForestRegressor(n_estimators=100, max_depth=20) model.fit(X_train, y_train) print(f"Train RMSE: {mean_squared_error(y_train, model.predict(X_train), squared=False):.2f}") print(f" Test RMSE: {mean_squared_error(y_test, model.predict(X_test), squared=False):.2f}") # ready to deploy dump(model, "model.joblib") # ***Upload model.joblib to s3. You choose how you want to upload it.*** # In terminal: # # # cd /mnt/var/lib/jupyter/home/jovyan/ # # aws s3 cp model.joblib s3://mds-s3-student60/model.joblib
Milestone3-Task3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python3 # language: python # name: python3 # --- # # 整数計画問題による複数文書要約モデル # ## McDonaldモデル # 次の目的関数の最小化を考える。 # # **目的関数** # $$f(q) = -\sum_{i} r_{i}q_{i} + \lambda \sum_{i < j} s_{ij} q_{i}q_{j}$$ # # **制約条件** # $$\sum_{i} c_{i} q_{i} \leq K$$ # $$\forall i, \forall j, q_{i} q_{j}-q_{i} \leq 0$$ # $$\forall i, \forall j, q_{i} q_{j}-q_{j} \leq 0$$ # $$\forall i, \forall j, q_{i}+q_{j}-q_{i} q_{j} \leq 1$$ # $$\forall i, q_{i} \in\{0,1\}$$ # # **変数** # $q_{i}$: 文$i$が要約に含まれれば1、そうでなければ0 # $K$: 許容される要約文の長さ # $c_{i}$: 文$i$の長さ # $r_{i}$: 文$i$と入力文書全体の類似度 # $s_{ij}$: 文$i$と文$j$の類似度 # **QUBOの定式化** # 要約文の長さに関する制約条件を罰金項の形で加える。 # $$f(q) = -\sum_{i} r_{i}q_{i} + \lambda_{1} \sum_{i < j} s_{ij} q_{i}q_{j} + \lambda_{2} \sum_{i} \left(c_{i}q_{i} - K \right)^2$$ # # あるいは、定式化の上で$K$を定めずに以下の最小化を考える。$\lambda_{2}$を調整し、解の後処理として$\sum_{i} c_{i} x_{i} \leq K$となる解を選択すればよい。 # $$f(q) = -\sum_{i} r_{i}q_{i} + \lambda_{1} \sum_{i < j} s_{ij} q_{i}q_{j} + \lambda_{2} \sum_{i} c_{i}q_{i}$$ # # 今回は多くの文を含む文章を扱うため、後者の定式化を採用する。 # # 実験 # 以下、スティーブジョブスのスピーチを対象とした実験を行う。 original_text = """I am honored to be with you today at your commencement from one of the finest universities in the world. I never graduated from college. Truth be told, this is the closest I've ever gotten to a college graduation. Today I want to tell you three stories from my life. That's it. No big deal. Just three stories. The first story is about connecting the dots. I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out? It started before I was born. My biological mother was a young, unwed college graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: "We have an unexpected baby boy; do you want him?" They said: "Of course." My biological mother later found out that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would someday go to college. And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn't interest me, and begin dropping in on the ones that looked interesting. It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms, I returned coke bottles for the 5 - deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example: Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and san serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating. None of this had even a hope of any practical application in my life. But ten years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, it's likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backwards ten years later. Again, you can't connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something - your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life. My second story is about love and loss. I was lucky I found what I loved to do early in life. Woz and I started Apple in my parents garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4000 employees. We had just released our finest creation -the Macintosh- a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating. I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down - that I had dropped the baton as it was being passed to me. I met with <NAME> and <NAME> and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over. I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life. During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the worlds first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is at the heart of Apple's current renaissance. And Laurene and I have a wonderful family together. I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle. My third story is about death. When I was 17, I read a quote that went something like: "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "No" for too many days in a row, I know I need to change something. Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life. Because almost everything - all external expectations, all pride, all fear of embarrassment or failure - these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart. About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor's code for prepare to die. It means to try to tell your kids everything you thought you'd have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes. I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and I'm fine now. This was the closest I've been to facing death, and I hope it's the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept: No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life's change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true. Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma -which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary. When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960's, before personal computers and desktop publishing, so it was all made with typewriters, scissors, and polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: it was idealistic, and overflowing with neat tools and great notions. Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: "Stay Hungry. Stay Foolish." It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you. Stay Hungry. Stay Foolish. Thank you all very much. """ # + from nltk.tokenize import sent_tokenize # import nltk # nltk.download('punkt') import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # + code_folding=[] # 文章を文単位で分割する morphemes = sent_tokenize(original_text) # 単語に数値を割り当てる word2id = {} for line in morphemes: for word in line.split(): if word in word2id: continue word2id[word] = len(word2id) # Bag of Words bow_set = [] for line in morphemes: bow = [0] * len(word2id) for word in line.split(): try: bow[word2id[word]] += 1 except: pass bow_set.append(bow) # + def cos_sim(bow1, bow2): """ コサイン類似度を求める """ narr_bow1 = np.array(bow1) narr_bow2 = np.array(bow2) return np.sum(narr_bow1 * narr_bow2) / (np.linalg.norm(narr_bow1) * np.linalg.norm(narr_bow2)) # それぞれの文の長さ sentence_lengths = [len(m) for m in morphemes] # 文章全体に対する類似度 bow_all = np.sum(bow_set, axis=0) sim2all = [cos_sim(b, bow_all) for b in bow_set] # 文同士の類似度 sim2each = [[cos_sim(b, c) if i < j else 0 for j, c in enumerate(bow_set)] for i, b in enumerate(bow_set)] # + from pyqubo import * def normalize(exp): """ 各制約項を正規化する関数 """ qubo, offset = exp.compile().to_qubo() max_coeff = abs(max(qubo.values())) min_coeff = abs(min(qubo.values())) norm = max_coeff if max_coeff - min_coeff > 0 else min_coeff return exp / norm # + num_var = len(morphemes) q = Array.create(name='q', shape=num_var, vartype='BINARY') H = - normalize(sum(sim2all[i] * q[i] for i in range(num_var))) \ + Placeholder('sim') * normalize(sum(sim2each[i][j] * q[i] * q[j] for i in range(num_var) for j in range(i+1, num_var))) \ + Placeholder('len') * normalize(sum(sentence_lengths[i] * q[i] for i in range(num_var))) model = H.compile() # - feed_dict = {'sim': 1.0, 'len': 0.5} qubo, offset = model.to_qubo(feed_dict=feed_dict) def show_qubo(qubo_, N): import re narr_qubo = np.zeros((N, N)) for pos, coeff in qubo_.items(): pos0 = int(re.search(r'.+\[([0-9]+)\]', pos[0]).group(1)) pos1 = int(re.search(r'.+\[([0-9]+)\]', pos[1]).group(1)) if pos0 < pos1: narr_qubo[pos0][pos1] = coeff else: narr_qubo[pos1][pos0] = coeff # 描画 plt.imshow(narr_qubo, cmap="GnBu") plt.colorbar() plt.show() show_qubo(qubo, num_var) from dwave_qbsolv import QBSolv response = QBSolv().sample_qubo(qubo, num_reads=10) solution_list = [] summarized_text_list = [] for i, sample in enumerate(response.samples()): solution_list.append([sample['q[{}]'.format(i)] for i in range(num_var)]) summarized_text_list.append(" ".join([morphemes[i] for i, s in enumerate(solution_list[-1]) if s == 1])) print(summarized_text_list[0])
quantum_summarization.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # # Bilma Classification demo from bilma import bilma_model import numpy as np # ## Load the model # # You can load the model using `bilma_model.load`. model = bilma_model.load("models-final/bilma_small_MX_epoch-1_classification_epochs-13.h5" ) # The layers and parameters of the model are: model.summary() # The input is an array of shape `(bs, 280)` where bs is the batch size and 280 is the max lenght of the sequences. # # The outputs have shape `(bs, 280, 29025)` and `(bs, 15)`. The first output is the same as the MLM model. The second output predicts the probability of each of the 15 emoticons. model.inputs, model.outputs # To input data into the model we need a tokenizer just like in the MLM model. tokenizer = bilma_model.tokenizer(vocab_file="d:/data/twitts/vocab_file_ALL.txt", max_length=280) texts = ["Tenemos tres días sin internet ni señal de celular en el pueblo.", "Incomunicados en el siglo XXI tampoco hay servicio de telefonía fija", "Vamos a comer unos tacos", "Los del banco no dejan de llamarme"] tweet = tokenizer.tokenize(texts) We can now predict the emoticons p = model.predict(tweet) p[1].shape tokenizer.decode_emo(p[1])
bilma-cls-demo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import logging import importlib importlib.reload(logging) # see https://stackoverflow.com/a/21475297/1469195 log = logging.getLogger() log.setLevel('INFO') import sys logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO, stream=sys.stdout) # + # %%capture import os import site os.sys.path.insert(0, '/home/schirrmr/code/reversible/') os.sys.path.insert(0, '/home/schirrmr/braindecode/code/braindecode/') os.sys.path.insert(0, '/home/schirrmr/code/explaining/reversible//') # %load_ext autoreload # %autoreload 2 import numpy as np import logging log = logging.getLogger() log.setLevel('INFO') import sys logging.basicConfig(format='%(asctime)s %(levelname)s : %(message)s', level=logging.INFO, stream=sys.stdout) import matplotlib from matplotlib import pyplot as plt from matplotlib import cm # %matplotlib inline # %config InlineBackend.figure_format = 'png' matplotlib.rcParams['figure.figsize'] = (12.0, 1.0) matplotlib.rcParams['font.size'] = 14 import seaborn seaborn.set_style('darkgrid') from reversible2.sliced import sliced_from_samples from numpy.random import RandomState import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import copy import math import itertools import torch as th from braindecode.torch_ext.util import np_to_var, var_to_np from reversible2.splitter import SubsampleSplitter from reversible2.view_as import ViewAs from reversible2.affine import AdditiveBlock from reversible2.plot import display_text, display_close from reversible2.bhno import load_file, create_inputs th.backends.cudnn.benchmark = True # + from reversible2.util import set_random_seeds cuda=True set_random_seeds(2019011641, cuda) rand_inputs = th.randn(440,128,1024,1, device='cuda') print((rand_inputs.numel()* 4) / (1024 ** 2)) # + def conv_add_block_3x3(n_c, n_i_c): return AdditiveBlock( nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), switched_order=False) def dense_add_block(n_c, n_i_c): return AdditiveBlock( nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), switched_order=False) cuda = True from reversible2.graph import Node from reversible2.branching import CatChans, ChunkChans, Select from copy import deepcopy from reversible2.graph import Node from reversible2.distribution import TwoClassDist from reversible2.rfft import RFFT, Interleave from reversible2.util import set_random_seeds from torch.nn import ConstantPad2d import torch as th from reversible2.splitter import SubsampleSplitter set_random_seeds(2019011641, cuda) n_chans = 128 base_model = nn.Sequential( SubsampleSplitter(stride=[2,1],chunk_chans_first=False),# 2 x 256 conv_add_block_3x3(2*n_chans,32), conv_add_block_3x3(2*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 4 x 128 conv_add_block_3x3(4*n_chans,32), conv_add_block_3x3(4*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 8 x 64 conv_add_block_3x3(8*n_chans,32), conv_add_block_3x3(8*n_chans,32)) base_model.cuda(); branch_1_a = nn.Sequential( SubsampleSplitter(stride=[2,1],chunk_chans_first=False), # 8 x 32 conv_add_block_3x3(8*n_chans,32), conv_add_block_3x3(8*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 16 x 16 conv_add_block_3x3(16*n_chans,32), conv_add_block_3x3(16*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 32 x 8 conv_add_block_3x3(32*n_chans,32), conv_add_block_3x3(32*n_chans,32), ) branch_1_b = nn.Sequential( *(list(deepcopy(branch_1_a).children()) + [ ViewAs((-1, 32*n_chans,16,1), (-1,512*n_chans)), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32), ])) branch_1_a.cuda(); branch_1_b.cuda(); branch_2_a = nn.Sequential( SubsampleSplitter(stride=[2,1], chunk_chans_first=False), # 32 x 4 conv_add_block_3x3(32*n_chans,32), conv_add_block_3x3(32*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 64 x 2 conv_add_block_3x3(64*n_chans,32), conv_add_block_3x3(64*n_chans,32), SubsampleSplitter(stride=[2,1],chunk_chans_first=True), # 128 x 1 ViewAs((-1, 128*n_chans,2,1), (-1,256*n_chans)), dense_add_block(256*n_chans,64), dense_add_block(256*n_chans,64), dense_add_block(256*n_chans,64), dense_add_block(256*n_chans,64), ) branch_2_b = deepcopy(branch_2_a).cuda() branch_2_a.cuda(); branch_2_b.cuda(); final_model = nn.Sequential( dense_add_block(1024*n_chans,256), dense_add_block(1024*n_chans,256), dense_add_block(1024*n_chans,256), dense_add_block(1024*n_chans,256), RFFT() ) final_model.cuda(); o = Node(None, base_model) o = Node(o, ChunkChans(2)) o1a = Node(o, Select(0)) o1b = Node(o, Select(1)) o1a = Node(o1a, branch_1_a) o1b = Node(o1b, branch_1_b) o2 = Node(o1a, ChunkChans(2)) o2a = Node(o2, Select(0)) o2b = Node(o2, Select(1)) o2a = Node(o2a, branch_2_a) o2b = Node(o2b, branch_2_b) o = Node([o1b,o2a,o2b], CatChans()) o = Node(o, final_model) feature_model = o if cuda: feature_model.cuda() feature_model.eval(); # - outs = feature_model(rand_inputs[:20]) inverted = feature_model.invert(outs) loss = th.sum(inverted ** 2) feature_model.zero_grad() loss.backward() # + from reversible2.wrap_invertible import WrapInvertible from reversible2.constantmemory import AdditiveBlockConstantMemory def sequential_to_invertible(seq_model): children = list(seq_model.children()) new_children = [] for i_c, c in enumerate(children): keep_input = i_c == 0 keep_output = i_c == len(children) - 1 new_c = module_to_invertible(c, keep_input, keep_output) new_children.append(new_c) new_seq_model = nn.Sequential(*new_children) assert new_seq_model[0].keep_input == True assert new_seq_model[-1].keep_output == True return new_seq_model def module_to_invertible(c, keep_input, keep_output): c = deepcopy(c) classname = c.__class__.__name__ if classname == 'AdditiveBlock': assert c.switched_order == False return AdditiveBlockConstantMemory(c.FA, c.GA, keep_input=keep_input, keep_output=keep_output) elif classname in ['SubsampleSplitter', 'ViewAs']: return WrapInvertible(c, keep_input=keep_input, keep_output=keep_output, grad_is_inverse=True) elif classname in ['RFFT']: return WrapInvertible(c, keep_input=keep_input, keep_output=keep_output, grad_is_inverse=False) else: raise ValueError("Unknown class to convert invertible {:s}".format( classname)) # + from reversible2.constantmemory import AdditiveBlockConstantMemory def conv_add_3x3_const(n_c, n_i_c, keep_input=False, keep_output=False): return AdditiveBlockConstantMemory( nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), keep_input=keep_input, keep_output=keep_output) def dense_add_const(n_c, n_i_c, keep_input=False, keep_output=False): return AdditiveBlockConstantMemory( nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), keep_input=keep_input, keep_output=keep_output) cuda = True from reversible2.graph import Node from reversible2.branching import CatChans, ChunkChans, Select from reversible2.graph import Node from reversible2.wrap_invertible import WrapInvertible from copy import deepcopy from reversible2.graph import Node from reversible2.rfft import RFFT, Interleave from reversible2.util import set_random_seeds from torch.nn import ConstantPad2d import torch as th from reversible2.splitter import SubsampleSplitter set_random_seeds(2019011641, cuda) n_chans = 128 base_model_2 = nn.Sequential( WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=False), grad_is_inverse=True, keep_input=True),# 2 x 256 conv_add_3x3_const(2*n_chans,32), conv_add_3x3_const(2*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 4 x 128 conv_add_3x3_const(4*n_chans,32), conv_add_3x3_const(4*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 8 x 64 conv_add_3x3_const(8*n_chans,32), conv_add_3x3_const(8*n_chans,32, keep_output=True)) base_model_2.cuda(); branch_1_a_2 = nn.Sequential( WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=False), grad_is_inverse=True, keep_input=True), # 8 x 32 conv_add_3x3_const(8*n_chans,32), conv_add_3x3_const(8*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True),# 16 x 16 conv_add_3x3_const(16*n_chans,32), conv_add_3x3_const(16*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 32 x 8 conv_add_3x3_const(32*n_chans,32), conv_add_3x3_const(32*n_chans,32, keep_output=True), ) branch_1_b_2 = nn.Sequential( *(list(deepcopy(branch_1_a_2).children()) + [ WrapInvertible(ViewAs((-1, 32*n_chans,16,1), (-1,512*n_chans)), grad_is_inverse=True, keep_input=True), dense_add_const(512*n_chans,32), dense_add_const(512*n_chans,32), dense_add_const(512*n_chans,32), dense_add_const(512*n_chans,32, keep_output=True), ])) branch_1_a_2.cuda(); branch_1_b_2.cuda(); branch_2_a_2 = nn.Sequential( WrapInvertible(SubsampleSplitter(stride=[2,1], chunk_chans_first=False), keep_input=True, grad_is_inverse=True),# 32 x 4 conv_add_3x3_const(32*n_chans,32), conv_add_3x3_const(32*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True),# 64 x 2 conv_add_3x3_const(64*n_chans,32), conv_add_3x3_const(64*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 128 x 1 WrapInvertible(ViewAs((-1, 128*n_chans,2,1), (-1,256*n_chans)), grad_is_inverse=True), dense_add_const(256*n_chans,64), dense_add_const(256*n_chans,64), dense_add_const(256*n_chans,64), dense_add_const(256*n_chans,64, keep_output=True), ) branch_2_b_2 = deepcopy(branch_2_a_2).cuda() branch_2_a_2.cuda(); branch_2_b_2.cuda(); final_model_2 = nn.Sequential( dense_add_const(1024*n_chans,256,keep_input=True), dense_add_const(1024*n_chans,256), dense_add_const(1024*n_chans,256), dense_add_const(1024*n_chans,256), WrapInvertible(RFFT(), keep_output=True), ) final_model_2.cuda(); o_2 = Node(None, base_model_2) o_2 = Node(o_2, ChunkChans(2)) o1a_2 = Node(o_2, Select(0)) o1b_2 = Node(o_2, Select(1)) o1a_2 = Node(o1a_2, branch_1_a_2) o1b_2 = Node(o1b_2, branch_1_b_2) o2_2 = Node(o1a_2, ChunkChans(2)) o2a_2 = Node(o2_2, Select(0)) o2b_2 = Node(o2_2, Select(1)) o2a_2 = Node(o2a_2, branch_2_a_2) o2b_2 = Node(o2b_2, branch_2_b_2) o_2 = Node([o1b_2,o2a_2,o2b_2], CatChans()) o_2 = Node(o_2, final_model_2) feature_model2 = o_2 if cuda: feature_model2.cuda() feature_model2.eval(); # + outs2 = feature_model2(rand_inputs[:20]) inverted2 = feature_model2.invert(outs2) loss2 = th.sum(inverted2 ** 2) feature_model2.zero_grad() loss2.backward() assert th.allclose(outs, outs2) assert th.allclose(inverted, inverted2) assert th.allclose(loss, loss2) for p1,p2 in zip(feature_model.parameters(), feature_model2.parameters()): assert th.allclose(p1,p2) if not th.allclose(p1.grad, p2.grad): print("Mean: {:.0E}".format(th.mean(th.abs(p1.grad - p2.grad)).item())) print("Max: {:.0E}".format(th.max(th.abs(p1.grad - p2.grad)).item())) assert th.allclose(p1.grad, p2.grad, rtol=1e-3, atol=1e-2) # + from reversible2.constantmemory import AdditiveBlockConstantMemory def conv_add_3x3_const(n_c, n_i_c, keep_input=False, keep_output=False): return AdditiveBlockConstantMemory( nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), nn.Sequential( nn.Conv2d(n_c // 2, n_i_c, (3, 1), stride=1, padding=(1, 0), bias=True), nn.ReLU(), nn.Conv2d(n_i_c, n_c // 2, (3, 1), stride=1, padding=(1, 0), bias=True)), keep_input=keep_input, keep_output=keep_output) def dense_add_const(n_c, n_i_c, keep_input=False, keep_output=False): return AdditiveBlockConstantMemory( nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), nn.Sequential( nn.Linear(n_c // 2, n_i_c, ), nn.ReLU(), nn.Linear(n_i_c, n_c // 2, )), keep_input=keep_input, keep_output=keep_output) cuda = True from reversible2.graph import Node from reversible2.branching import CatChans, ChunkChans, Select from reversible2.graph import Node from reversible2.wrap_invertible import WrapInvertible from copy import deepcopy from reversible2.graph import Node from reversible2.rfft import RFFT, Interleave from reversible2.util import set_random_seeds from torch.nn import ConstantPad2d import torch as th from reversible2.splitter import SubsampleSplitter set_random_seeds(2019011641, cuda) n_chans = 128 base_model_2 = nn.Sequential( WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=False), grad_is_inverse=True, keep_input=True),# 2 x 256 conv_add_3x3_const(2*n_chans,32), conv_add_3x3_const(2*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 4 x 128 conv_add_3x3_const(4*n_chans,32), conv_add_3x3_const(4*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 8 x 64 conv_add_3x3_const(8*n_chans,32), conv_add_3x3_const(8*n_chans,32, keep_output=True)) base_model_2.cuda(); branch_1_a_2 = nn.Sequential( WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=False), grad_is_inverse=True, keep_input=True), # 8 x 32 conv_add_3x3_const(8*n_chans,32), conv_add_3x3_const(8*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True),# 16 x 16 conv_add_3x3_const(16*n_chans,32), conv_add_3x3_const(16*n_chans,32), WrapInvertible(SubsampleSplitter(stride=[2,1],chunk_chans_first=True), grad_is_inverse=True), # 32 x 8 conv_add_3x3_const(32*n_chans,32), conv_add_3x3_const(32*n_chans,32, keep_output=True), ) branch_1_b_2 = nn.Sequential( *(list(sequential_to_invertible(branch_1_a).children()) + list(sequential_to_invertible( nn.Sequential( ViewAs((-1, 32*n_chans,16,1), (-1,512*n_chans)), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32), dense_add_block(512*n_chans,32),)).children()) )) branch_1_b_2 = sequential_to_invertible(branch_1_b) # causes problems branch_1_a_2.cuda(); branch_1_b_2.cuda(); branch_2_a_2 = sequential_to_invertible(branch_2_a) branch_2_b_2 = deepcopy(branch_2_a_2).cuda() branch_2_a_2.cuda(); branch_2_b_2.cuda(); final_model_2 = sequential_to_invertible(final_model) final_model_2.cuda(); o_2 = Node(None, base_model_2) o_2 = Node(o_2, ChunkChans(2)) o1a_2 = Node(o_2, Select(0)) o1b_2 = Node(o_2, Select(1)) o1a_2 = Node(o1a_2, branch_1_a_2) o1b_2 = Node(o1b_2, branch_1_b_2) o2_2 = Node(o1a_2, ChunkChans(2)) o2a_2 = Node(o2_2, Select(0)) o2b_2 = Node(o2_2, Select(1)) o2a_2 = Node(o2a_2, branch_2_a_2) o2b_2 = Node(o2b_2, branch_2_b_2) o_2 = Node([o1b_2,o2a_2,o2b_2], CatChans()) o_2 = Node(o_2, final_model_2) feature_model2 = o_2 if cuda: feature_model2.cuda() feature_model2.eval(); # - from reversible2.constantmemory import clear_ctx_dicts outs2 = feature_model2(rand_inputs[:20]) inverted2 = feature_model2.invert(outs2) loss2 = th.sum(inverted2 ** 2) feature_model2.zero_grad() loss2.backward() assert th.allclose(outs, outs2) assert th.allclose(inverted, inverted2) assert th.allclose(loss, loss2) for p1,p2 in zip(feature_model.parameters(), feature_model2.parameters()): assert th.allclose(p1,p2) if not th.allclose(p1.grad, p2.grad): print("Mean: {:.0E}".format(th.mean(th.abs(p1.grad - p2.grad)).item())) print("Max: {:.0E}".format(th.max(th.abs(p1.grad - p2.grad)).item())) assert th.allclose(p1.grad, p2.grad, rtol=1e-3, atol=1e-2) clear_ctx_dicts(feature_model2) # # # Old # + from reversible2.constantmemory import AdditiveBlockConstantMemory cuda = True from reversible2.graph import Node from reversible2.branching import CatChans, ChunkChans, Select from reversible2.graph import Node from reversible2.wrap_invertible import WrapInvertible from copy import deepcopy from reversible2.graph import Node from reversible2.rfft import RFFT, Interleave from reversible2.util import set_random_seeds from torch.nn import ConstantPad2d import torch as th from reversible2.splitter import SubsampleSplitter set_random_seeds(2019011641, cuda) n_chans = 128 base_model_2 = sequential_to_invertible(base_model) base_model_2.cuda(); branch_1_a_2 = sequential_to_invertible(branch_1_a) branch_1_b_2 = sequential_to_invertible(branch_1_b) branch_1_a_2.cuda(); branch_1_b_2.cuda(); branch_2_a_2 = sequential_to_invertible(branch_2_a) branch_2_b_2 = deepcopy(branch_2_a_2).cuda() branch_2_a_2.cuda(); branch_2_b_2.cuda(); final_model_2 = sequential_to_invertible(final_model) final_model_2.cuda(); o_2 = Node(None, base_model_2) o_2 = Node(o_2, ChunkChans(2)) o1a_2 = Node(o_2, Select(0)) o1b_2 = Node(o_2, Select(1)) o1a_2 = Node(o1a_2, branch_1_a_2) o1b_2 = Node(o1b_2, branch_1_b_2) o2_2 = Node(o1a_2, ChunkChans(2)) o2a_2 = Node(o2_2, Select(0)) o2b_2 = Node(o2_2, Select(1)) o2a_2 = Node(o2a_2, branch_2_a_2) o2b_2 = Node(o2b_2, branch_2_b_2) o_2 = Node([o1b_2,o2a_2,o2b_2], CatChans()) o_2 = Node(o_2, final_model_2) feature_model2 = o_2 if cuda: feature_model2.cuda() feature_model2.eval(); # - th.stack([p.norm() for p in feature_model2.parameters()]) feature_model.zero_grad() th.stack([p.grad.norm() for p in feature_model2.parameters()]) # + outs2 = feature_model2(rand_inputs[:50]) inverted2 = feature_model2.invert(outs2) loss2 = th.sum(inverted2 ** 2) feature_model2.zero_grad() loss2.backward() assert th.allclose(outs, outs2) assert th.allclose(inverted, inverted2) assert th.allclose(loss, loss2) for p1,p2 in zip(feature_model.parameters(), feature_model2.parameters()): assert th.allclose(p1,p2) if not th.allclose(p1.grad, p2.grad): print("Mean: {:.0E}".format(th.mean(th.abs(p1.grad - p2.grad)).item())) print("Max: {:.0E}".format(th.max(th.abs(p1.grad - p2.grad)).item())) assert th.allclose(p1.grad, p2.grad, rtol=1e-3, atol=1e-2) # -
notebooks/constant-memory/BigTestWithAutomaticTransformation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/alirezash97/BRATS2015/blob/master/main.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="BZrH-sn7AZww" colab_type="code" colab={} # !sudo apt-get install python-pip python-numpy python-scipy libboost-python-dev build-essential # + id="P-IVUCknAgux" colab_type="code" colab={} # !sudo pip install nibabel pydicom medpy # + id="aVQisU1x8bwL" colab_type="code" colab={} # !pip install kaggle # !mkdir .kaggle import json token = {"username":"alirezashafaei97","key":"<KEY>"} with open('/content/.kaggle/kaggle.json', 'w') as file: json.dump(token, file) # !mkdir ~/.kaggle # !cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json # !kaggle config set -n path -v{/content} # !chmod 600 /root/.kaggle/kaggle.json # !kaggle datasets download -d andrewmvd/brain-tumor-segmentation-in-mri-brats-2015 -p /content # + id="TW9OhHBd8_IU" colab_type="code" colab={} # !unzip /content/brain-tumor-segmentation-in-mri-brats-2015.zip -d /content/BTS # + id="vB8LBFb4zYDd" colab_type="code" colab={} # + id="tgqS6C6J_2Z_" colab_type="code" colab={} import glob, os HGG = glob.glob('/content/BTS/train/HGG/**/*.mha', recursive=True) LGG = glob.glob('/content/BTS/train/LGG/**/*.mha', recursive=True) # + id="Z0xnV0q3DdiU" colab_type="code" outputId="ba631bf8-414f-49a8-be47-3000c665ad63" colab={"base_uri": "https://localhost:8080/", "height": 50} print(len(HGG)) print(len(LGG)) # + id="MfUQ55lBKnPE" colab_type="code" colab={} T1_HGG = [] S_HGG = [] T1_LGG = [] S_LGG = [] for item in HGG: if 'T1.' in item: T1_HGG.append(item) elif 'O.OT.' in item: S_HGG.append(item) else: pass # for item in LGG: # if 'T1.' in item: # T1_LGG.append(item) # elif 'O.OT.' in item: # S_LGG.append(item) # else: # pass # + id="LYsA6IXNOk35" colab_type="code" outputId="c69473d3-f9cd-4c58-d0e4-595092b468aa" colab={"base_uri": "https://localhost:8080/", "height": 50} print(len(T1_HGG)) print(len(S_HGG)) # print(len(T1_LGG)) # print(len(S_LGG)) # + id="Tdq_DDhdhic8" colab_type="code" colab={} T1_HGG_validation = T1_HGG[199:215] S_HGG_validation = S_HGG[199:] T1_HGG = T1_HGG[:199] S_HGG = S_HGG[:199] # + id="Yub4OLKIPuNL" colab_type="code" colab={} from medpy.io import load import numpy as np def generator(samples, targets, batch_size=2): num_samples = len(samples) while True: # Loop forever so the generator never terminates # Get index to start each batch: [0, batch_size, 2*batch_size, ..., max multiple of batch_size &lt;= num_samples] for offset in range(0, num_samples, batch_size): # Get the samples you'll use in this batch batch_samples = samples[offset:offset+batch_size] batch_targets = targets[offset:offset+batch_size] # Initialise X_train and y_train arrays for this batch X_train = [] y_train = [] # For each example for batch_sample in batch_samples: # Load image (X) temp, header = load(batch_sample) tempp = np.zeros((48, 240, 240, 3)) for i in range (1, 49): tempp[i-1, :, :, :] = temp[:, :, i*3:(i+1)*3] X_train.append(tempp) for batch_target in batch_targets: # Load image (X) temp, header = load(batch_target) tempp = np.zeros((48, 240, 240, 3)) for i in range (1, 49): tempp[i-1, :, :, :] = temp[:, :, i*3:(i+1)*3] y_train.append(tempp) # Make sure they're numpy arrays (as opposed to lists) X_train = np.array(X_train) y_train = np.array(y_train) # The generator-y part: yield the next training batch yield X_train, y_train # + id="D1GZffAoffcI" colab_type="code" colab={} train_generator = generator(T1_HGG, S_HGG, batch_size=1) validation_generator = generator(T1_HGG_validation, S_HGG_validation, batch_size=1) # + id="oEXSDmkV9WMN" colab_type="code" colab={} # from medpy.io import load # import matplotlib.pyplot as plt # import numpy as np # trainset_HGG = np.zeros((10, 240, 240, 155)) # targetset_HGG = np.zeros((10, 240, 240, 155)) # # trainset_LGG = np.zeros((100, 240, 240, 155)) # # for index, dir_address in enumerate(HGG) : # # temp = load(dir_address) # # trainset_HGG[index, :, :, :] = np.array(temp) # for index, dir_address in enumerate(T1_HGG) : # temp, header = load(dir_address) # trainset_HGG[index, :, :, :] = np.array(temp) # for index, dir_address in enumerate(S_HGG) : # temp, header = load(dir_address) # targetset_HGG[index, :, :, :] = np.array(temp) # + id="Qc9aJsKdEfAR" colab_type="code" outputId="5403ccda-762e-4d25-fa11-6749b21c22f0" colab={"base_uri": "https://localhost:8080/", "height": 286} # plt.imshow((trainset_HGG[9, :, :, 70:73] * 255).astype(np.uint8)) # + id="h-TxSQptq4Vn" colab_type="code" outputId="de85c74d-fd9c-4dce-9fe5-a3516a1deb21" colab={"base_uri": "https://localhost:8080/", "height": 286} # plt.imshow(targetset_HGG[9, :, :, 92], cmap='gray') # plt.imshow((targetset_HGG[12, :, :, 80:83] * 255).astype(np.uint8)) # + id="6dFD_YGqHQ4W" colab_type="code" colab={} # import numpy as np # import matplotlib.pyplot as plt # def ploter(image_data, a, b): # fig=plt.figure(figsize=(10, 10)) # columns = 4 # rows = 5 # counter = 0 # for i in range(a, b): # counter += 1 # img = image_data[:, :, i] # fig.add_subplot(rows, columns, counter) # plt.imshow(img, cmap='gray') # plt.show() # + id="BmSuvtSaMcmR" colab_type="code" outputId="a05467bd-38b9-47b8-ffc5-bc0c5aa90728" colab={"base_uri": "https://localhost:8080/", "height": 595} # ploter(targetset_HGG[12, :, :, :], 80, 100) # + id="XqIsRce2WdaZ" colab_type="code" outputId="f4a28d80-6194-4d7f-e611-a65c7c033dbd" colab={"base_uri": "https://localhost:8080/", "height": 50} # print(trainset_HGG.shape) # print(targetset_HGG.shape) # + id="e3a4LcHtLZGi" colab_type="code" colab={} # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(trainset_HGG, targetset_HGG, test_size=0.2) # + id="WT--KEgrKFhc" colab_type="code" colab={} pip install keras-segmentation # + id="s4tsa7MR0dZ7" colab_type="code" colab={} # + id="Jr-U5PhDSI0n" colab_type="code" colab={} from keras.layers import Conv3D, Dropout, MaxPooling3D, concatenate, UpSampling3D from keras import Model, Input import numpy as np import os import skimage.io as io import skimage.transform as trans import numpy as np from keras.metrics import MeanIoU from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras prev_chance0, checker0 = (0.1, 0) prev_chance1, checker1 = (0.1, 0) prev_chance2, checker2 = (0.1, 0) def unet(prev_chance0, checker0, prev_chance1, checker1, prev_chance2, checker2, pretrained_weights = None, input_size = (48, 240, 240, 3)): inputs = Input(input_size) conv1 = Conv3D(4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs) conv1 = Conv3D(4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1) pool1 = MaxPooling3D(pool_size=(1, 2, 2))(conv1) conv2 = Conv3D(8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1) conv2 = Conv3D(8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2) pool2 = MaxPooling3D(pool_size=(1, 2, 2))(conv2) conv3 = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2) ####### prev_chance0, conv3, checker0 = Acid16(prev_chance0, conv3, checker0) # conv3 = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3) ####### pool3 = MaxPooling3D(pool_size=(1, 2, 2))(conv3) conv4 = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3) ####### prev_chance1, conv4, checker1 = Acid32(prev_chance1, conv4, checker1) # conv4 = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4) ####### drop4 = Dropout(0.5)(conv4) pool4 = MaxPooling3D(pool_size=(1, 2, 2))(drop4) conv5 = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4) ######## prev_chance2, conv5, checker2 = Acid64(prev_chance2, conv5, checker2) # conv5 = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5) ######## drop5 = Dropout(0.5)(conv5) up6 = Conv3D(32, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling3D(size = (1, 2, 2))(drop5)) merge6 = concatenate([drop4,up6], axis = -1) conv6 = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6) conv6 = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6) up7 = Conv3D(16, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling3D(size = (1, 2, 2))(conv6)) merge7 = concatenate([conv3,up7], axis = -1) conv7 = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7) conv7 = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7) up8 = Conv3D(8, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling3D(size = (1, 2, 2))(conv7)) # merge8 = concatenate([conv2,up8], axis = -1) conv8 = Conv3D(8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8) conv8 = Conv3D(8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8) up9 = Conv3D(4, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling3D(size = (1, 2, 2))(conv8)) merge9 = concatenate([conv1,up9], axis = -1) conv9 = Conv3D(4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9) conv9 = Conv3D(4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv10 = Conv3D(3, 1, activation = 'sigmoid')(conv9) model = Model(input=inputs, output = conv10) model.compile(optimizer = Adam(lr = 1e-4), loss = soft_dice_loss, metrics = [dice_coefficient]) #model.summary() if(pretrained_weights): model.load_weights(pretrained_weights) return model # + id="ntKESDf4nKSV" colab_type="code" colab={} from keras import backend as K def soft_dice_loss(y_true, y_pred, axis=(1, 2, 3), epsilon=0.00001): dice_numerator = 2. * K.sum(y_true * y_pred, axis=axis) + epsilon dice_denominator = K.sum(y_true**2, axis=axis) + K.sum(y_pred**2, axis=axis) + epsilon dice_loss = 1 - K.mean((dice_numerator)/(dice_denominator)) return dice_loss def dice_coefficient(y_true, y_pred, axis=(1, 2, 3), epsilon=0.00001): dice_numerator = 2. * K.sum(y_true * y_pred, axis=axis) + epsilon dice_denominator = K.sum(y_true, axis=axis) + K.sum(y_pred, axis=axis) + epsilon dice_coefficient = K.mean((dice_numerator)/(dice_denominator)) return dice_coefficient # def dice_coefficient(y_true, y_pred, smooth=1.): # y_true_f = K.flatten(y_true) # y_pred_f = K.flatten(y_pred) # intersection = K.sum(y_true_f * y_pred_f) # return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) # def dice_coefficient_loss(y_true, y_pred): # return 1-dice_coefficient(y_true, y_pred) # + id="uVv3SKpZTZ0l" colab_type="code" outputId="370987d6-2e72-4694-e957-db13157c9269" colab={"base_uri": "https://localhost:8080/", "height": 1000} model = unet(prev_chance0, checker0, prev_chance1, checker1, prev_chance2, checker2) model.summary() # + id="1C2mmTejmTo7" colab_type="code" outputId="7f72d708-9e15-4d55-ca77-229d80fb4e9a" colab={"base_uri": "https://localhost:8080/", "height": 138} from keras.callbacks import EarlyStopping, ModelCheckpoint # callback my_callbacks = [ EarlyStopping(monitor='val_loss', patience=6), ModelCheckpoint(filepath='/content/drive/My Drive/BRATS2020/AcidModel.{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=False) ] # Fit model using generator history = model.fit_generator(train_generator, steps_per_epoch=199, epochs=20, validation_data=validation_generator, validation_steps=16, callbacks=my_callbacks) # history = model.fit(X_train, y_train, epochs=40, batch_size=4, validation_data=(X_test, y_test)) # + id="YjOo-B2-nM34" colab_type="code" colab={} import numpy as np import random def Acid16(prev_chance, X, checker): if checker == 0: chance = random.uniform(0, 1) checker = 1 else: chance = prev_chance checker = 0 if chance > 0.8: X = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.8 > chance > 0.6: X = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.6 > chance > 0.4: X = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.4 > chance > 0.2: X = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.2 > chance : X = Conv3D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) return chance, X, checker # + id="K9nZ-aAoxqUQ" colab_type="code" colab={} import numpy as np import random def Acid32(prev_chance, X, checker): if checker == 0: chance = random.uniform(0, 1) checker = 1 else: chance = prev_chance checker = 0 if chance > 0.8: X = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.8 > chance > 0.6: X = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.6 > chance > 0.4: X = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.4 > chance > 0.2: X = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.2 > chance : X = Conv3D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) return chance, X, checker # + id="LZXaZZ-Mxrcy" colab_type="code" colab={} import numpy as np import random def Acid64(prev_chance, X, checker): if checker == 0: chance = random.uniform(0, 1) checker = 1 else: chance = prev_chance checker = 0 if chance > 0.8: X = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.8 > chance > 0.6: X = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.6 > chance > 0.4: X = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.4 > chance > 0.2: X = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) elif 0.2 > chance : X = Conv3D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(X) return chance, X, checker
2015/main.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: DeepLearning # language: python # name: deeplearning # --- import os import pandas as pd import numpy as np #Set notebook preferences pd.set_option('display.float_format', lambda x: '%.3f' % x) # + #Load modules os.chdir('/Users/ksharma/Documents/ML Engineer/Machine Learning/Projects/paysim_credit_fraud_analysis/') from src.data.import_export_data import load_config #Import data path= r'/Users/ksharma/Documents/ML Engineer/Machine Learning/Projects/paysim_credit_fraud_analysis/' config_name= 'config.yaml' config= load_config(config_name= config_name, path=path) dtypes= {'isFraud':'bool', 'step':'object'} rawData= pd.read_csv(config['paths']['cleanedData'] + 'processedData.csv', dtype= dtypes, index_col= [0]) # - # **Data Overview** display(rawData.shape) display(rawData.head()) rawData.info() # **Preprocess Data** # + #Create ColumnTransformer Preprocessor for training data from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer numeric_features= list(X.select_dtypes(include='float64').columns) num_transformer= StandardScaler() cat_features= list(X.select_dtypes(exclude='float64').columns) cat_transformer= OneHotEncoder(handle_unknown= 'ignore') preprocessor= ColumnTransformer(transformers=[('num', num_transformer, numeric_features), ('cat', cat_transformer, cat_features)]) # - # + #Split data into X and y X= rawData.drop(columns= 'isFraud', axis= 1) y= rawData.loc[:, 'isFraud'] #Initialize Data object from src.models.modeling import Data baseData= Data(X, y) #Take sample that mirrors target distribution # + from sklearn.model_selection import train_test_split train_test_split() # - # + #Init base models for evaluation from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB baseModels= [LogisticRegression(), RandomForestClassifier(), KNeighborsClassifier(), GaussianNB(), GradientBoostingClassifier(), AdaBoostClassifier()] # + #Init scoring for ml models from sklearn.metrics import confusion_matrix, fbeta_score, make_scorer scoring= {'Recall':'recall', 'F2': make_scorer(fbeta_score, beta= 2)} # - # **Test base models on baseline data (No over/under sampling applied)**
notebooks/Modeling/06042021_Model_Testing_Sandbox.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="lBnaYLtyZcJF" colab_type="code" colab={} import math import re import time from google.colab import drive import warnings warnings.filterwarnings('ignore') # + id="BInxdKa5ZfXj" colab_type="code" colab={} try : # %tensorflow_version 2.x except : pass import tensorflow as tf from tensorflow.keras import layers import tensorflow_datasets as tfds # + id="WO_Q8mg8Zg9C" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 108} outputId="107bb42d-58e6-4844-c0b3-acd209dd1d52" import pandas as pd import numpy as np import gensim.models from gensim.models import Word2Vec from tensorflow import keras from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.models import Sequential from sklearn.metrics import roc_auc_score from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.sequence import pad_sequences import re from nltk.tokenize import word_tokenize import nltk nltk.download('punkt') from nltk.corpus import stopwords nltk.download('stopwords') # + id="GLUjgjw4Zizy" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="dc47c301-0c1a-4662-87fb-ae226321e617" drive.mount("/content/drive") # + id="I8rE44VZwjmQ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 216} outputId="3489b957-d967-4254-b05a-fe389491a16f" data_clickbait = pd.read_csv ('/content/drive/My Drive/clickbait_data' , sep = ' \ n ' , header = None ) data_noclickbait = pd.read_csv ('/content/drive/My Drive/non_clickbait_data' , sep = ' \ n ' , header = None ) data_clickbait['class'] = [1 for i in range(data_clickbait.shape[0])] data_noclickbait['class'] = [0 for i in range(data_noclickbait.shape[0])] data_Final = pd.concat((data_clickbait , data_noclickbait), ignore_index = True ) df = data_Final.rename(columns = { 0 : "text" }) print(df.shape) df.head(5) # + id="VyA7JmVAZ50Z" colab_type="code" colab={} stop_words = set(stopwords.words('english')) # + id="87wv0ADBZ7tq" colab_type="code" colab={} L = [] for i , token in enumerate (df['text']) : words = [w for w in token.split()] L.append(len(words)) sequence_size = max (L) X = df['text'] y = df['class'] X_train, X_test, y_train, y_test = train_test_split(X , y, test_size = 0.2, random_state = 42) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.25, random_state = 42) # + id="8J-6KN_ZZ9dp" colab_type="code" colab={} y_train = np.array(y_train) y_test = np.array(y_test) y_val = np.array(y_val) # + id="OM9dY7aUZ_Pq" colab_type="code" colab={} WORD2VEC_VECTORS_BIN = '/content/drive/My Drive/GoogleNews-vectors-negative300.bin' w2v = gensim.models.KeyedVectors.load_word2vec_format(WORD2VEC_VECTORS_BIN , binary = True ) # + id="EPH4XjAjLBhw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="3cc00131-3d60-4532-cee7-42c91be8847a" train_data = np.zeros((len(X_train), sequence_size, 300)) val_data = np.zeros((len(X_val), sequence_size, 300)) test_data = np.zeros((len(X_test), sequence_size, 300)) for i,sentence in enumerate(X_train) : sentence = sentence.replace('-', ' ') words = nltk.word_tokenize(sentence) j = 0 for w in words : try : train_data[i , j] = w2v [w] j += 1 except : pass for i,sentence in enumerate(X_val) : sentence = sentence.replace('-',' ') words = nltk.word_tokenize(sentence) j = 0 for w in words : try : val_data[i , j] = w2v[w] j += 1 except : pass for i,sentence in enumerate(X_test) : sentence = sentence.replace('-',' ') words = nltk.word_tokenize(sentence) j = 0 for w in words : try : test_data[i , j] = w2v[w] j += 1 except : pass print(test_data.shape) print(train_data.shape) print(val_data.shape) # + id="jFl9wNKwaQm2" colab_type="code" colab={} class PositionalEncoding(layers.Layer): def __init__(self) : super(PositionalEncoding, self).__init__() def get_angles(self, pos, i, d_model) : angles = 1 / np.power(10000., (2*(i//2)) / np.float32(d_model)) return pos * angles def call(self, inputs) : seq_length = inputs.shape.as_list()[-2] d_model = inputs.shape.as_list()[-1] angles = self.get_angles(np.arange(seq_length)[:, np.newaxis],np.arange(d_model)[np.newaxis, :],d_model) angles[:, 0::2] = np.sin(angles[:, 0::2]) angles[:, 1::2] = np.cos(angles[:, 1::2]) pos_encoding = angles[np.newaxis, ...] return inputs + tf.cast(pos_encoding, tf.float32) # + id="1Q7LtllFaV12" colab_type="code" colab={} def scaled_dot_product_attention(queries, keys, values, mask) : product = tf.matmul(queries, keys, transpose_b = True) keys_dim = tf.cast(tf.shape(keys)[-1], tf.float32) scaled_product = product / tf.math.sqrt(keys_dim) attention = tf.matmul(tf.nn.softmax(scaled_product, axis = -1), values) return attention # + id="2lDxXvPwaeN0" colab_type="code" colab={} class MultiHeadAttention(layers.Layer): def __init__(self, nb_proj) : super(MultiHeadAttention, self).__init__() self.nb_proj = nb_proj def build(self, input_shape) : self.d_model = input_shape[-1] assert self.d_model % self.nb_proj == 0 self.d_proj = self.d_model // self.nb_proj self.query_lin = layers.Dense(units=self.d_model) self.key_lin = layers.Dense(units=self.d_model) self.value_lin = layers.Dense(units=self.d_model) self.final_lin = layers.Dense(units=self.d_model) def split_proj(self, inputs, batch_size): # inputs: (batch_size, seq_length, d_model) shape = (batch_size,-1, self.nb_proj,self.d_proj) splited_inputs = tf.reshape(inputs, shape=shape) # (batch_size, seq_length, nb_proj, d_proj) return tf.transpose(splited_inputs, perm=[0, 2, 1, 3]) # (batch_size, nb_proj, seq_length, d_proj) def call(self, queries, keys, values, mask) : batch_size = tf.shape(queries)[0] queries = self.query_lin(queries) keys = self.key_lin(keys) values = self.value_lin(values) queries = self.split_proj(queries, batch_size) keys = self.split_proj(keys, batch_size) values = self.split_proj(values, batch_size) attention = scaled_dot_product_attention(queries, keys, values, mask) attention = tf.transpose(attention, perm=[0, 2, 1, 3]) concat_attention = tf.reshape(attention,shape=(batch_size, -1, self.d_model)) outputs = self.final_lin(concat_attention) return outputs # + id="4uvjMQttaeQ7" colab_type="code" colab={} class EncoderLayer(layers.Layer): def __init__(self, FFN_units, nb_proj, dropout_rate) : super(EncoderLayer, self).__init__() self.FFN_units = FFN_units self.nb_proj = nb_proj self.dropout_rate = dropout_rate def build(self, input_shape) : self.d_model = input_shape[-1] self.multi_head_attention = MultiHeadAttention(self.nb_proj) self.dropout_1 = layers.Dropout(rate=self.dropout_rate) self.norm_1 = layers.LayerNormalization(epsilon=1e-6) self.dense_1 = layers.Dense(units=self.FFN_units, activation="relu") self.dense_2 = layers.Dense(units=self.d_model) self.dropout_2 = layers.Dropout(rate=self.dropout_rate) self.norm_2 = layers.LayerNormalization(epsilon=1e-6) def call(self, inputs, mask, training) : attention = self.multi_head_attention(inputs, inputs, inputs, mask) attention = self.dropout_1(attention, training=training) attention = self.norm_1(attention + inputs) outputs = self.dense_1(attention) outputs = self.dense_2(outputs) outputs = self.dropout_2(outputs, training=training) outputs = self.norm_2(outputs + attention) return outputs # + id="kaF-Q2K_lm16" colab_type="code" colab={} class Encoder(layers.Layer) : def __init__(self, nb_layers, FFN_units, nb_proj, dropout_rate, d_model, name="encoder") : super(Encoder, self).__init__(name=name) self.nb_layers = nb_layers self.d_model = d_model self.pos_encoding = PositionalEncoding() self.dropout = layers.Dropout(rate=dropout_rate) self.enc_layers = [EncoderLayer(FFN_units, nb_proj, dropout_rate) for _ in range(nb_layers)] def call(self, inputs, mask, training) : inputs *= tf.math.sqrt(tf.cast(self.d_model, tf.float32)) outputs = self.pos_encoding(inputs) outputs = self.dropout(outputs, training) for i in range(self.nb_layers) : outputs = self.enc_layers[i](outputs, mask, training) return outputs # + id="GJcIjNCQlseu" colab_type="code" colab={} class Transformer(tf.keras.Model): def __init__(self, d_model, nb_layers, FFN_units, nb_proj, dropout_rate, name="transformer"): super(Transformer, self).__init__(name=name) self.encoder = Encoder(nb_layers, FFN_units, nb_proj, dropout_rate, d_model) # self.last_linear = layers.Dense(units=vocab_size_dec, name="lin_ouput") def create_padding_mask(self, seq): mask = tf.cast(tf.math.equal(seq, 0), tf.float32) return mask[:, tf.newaxis, tf.newaxis, :] def create_look_ahead_mask(self, seq): seq_len = tf.shape(seq)[1] look_ahead_mask = 1 - tf.linalg.band_part(tf.ones((seq_len, seq_len)), -1, 0) return look_ahead_mask def call(self, enc_inputs, training = True): enc_mask = self.create_padding_mask(enc_inputs) enc_outputs = self.encoder(enc_inputs, enc_mask, training) return enc_outputs # + id="9moaXe9eaBqR" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 454} outputId="fd372bae-1c7c-4aa5-a55e-02dcb980ce23" D_MODEL = 300 NB_LAYERS = 2 FFN_UNITS = 512 NB_PROJ = 4 DROPOUT_RATE = 0.1 transformer = Transformer(d_model = D_MODEL, nb_layers = NB_LAYERS, FFN_units = FFN_UNITS, nb_proj = NB_PROJ, dropout_rate = DROPOUT_RATE) inputs = layers.Input(shape = (sequence_size,D_MODEL)) x = transformer(inputs) x = layers.Flatten()(x) x = layers.Dense(512, activation="relu")(x) x = layers.Dropout(0.1)(x) x = layers.Dense(256, activation="relu")(x) x = layers.Dropout(0.1)(x) outputs = layers.Dense(1, activation="sigmoid")(x) model = keras.Model(inputs = inputs, outputs = outputs) model.summary() model.compile(loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = ['accuracy']) # + id="oOnxkZRdaEAi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 783} outputId="b3ed4a45-5b75-49c8-bb85-ede4efd2534f" history = model.fit(train_data , y_train , batch_size = 64 , epochs = 20 , validation_data = (val_data , y_val), verbose = 1) # + id="AWJflmuvaIqM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="883f1dd4-b936-4476-e237-b1b29f029d8c" plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Validation'], loc='lower right') plt.show() # + id="lVl-R4EDaKj9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="fd54d391-a880-45e1-bd81-c68f9adb1041" plt.plot(history.history['loss'], label='Training data') plt.plot(history.history['val_loss'], label='Validation data') plt.title('Loss') plt.ylabel('Loss value') plt.xlabel('No. epoch') plt.legend(loc="upper left") plt.show() # + id="aTT31txecTt6" colab_type="code" colab={} y_pred = model.predict(test_data) # + id="NHOi5fpPPWDt" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 145} outputId="79895a9e-d023-434e-8244-2f0f884733df" y_pred # + id="w5vxqml_MkH6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="9197c4a0-c0e9-4acf-e4bd-386e04ac68b8" score , acc = model.evaluate(test_data , y_test , batch_size = 64) # + id="UP2pwTHMPYA2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="cf077c39-9cd7-4d5d-9892-15ecf660bcf4" print(' Test Score : ' , score) # + id="Y68He4g3PfGY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="92cd3bd5-4f5c-4ad6-fcc4-4a260308fc7a" print('Test Accuracy : ', acc) # + id="vTIR0MNrcYxR" colab_type="code" colab={} def predict_function(y_pred) : for i in range(y_pred.shape[0]) : if y_pred[i][0] >= 0.5 : y_pred[i][0] = 1 else : y_pred[i][0] = 0 return y_pred.astype('int64') # + id="1HcxwByxcZTY" colab_type="code" colab={} y_pred = predict_function(y_pred) # + id="7g58nYSbdYr4" colab_type="code" colab={} y_test = y_test.reshape(-1,1) # + id="EKB3RgAndTTh" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 326} outputId="57d46f05-79fb-475f-d8fa-f67d65bb6685" metrics = classification_report(y_test , y_pred , digits = 4) print('Classification Report ') print("\n") print(metrics) cm = confusion_matrix (y_test,y_pred) print('Confusion Matrix') print("\n") print(cm) # + id="wKs712yBM4OO" colab_type="code" colab={} def TestingOwnData(sentence) : X = np.zeros((1,sequence_size,300)) sentence = sentence.replace('-',' ') words = nltk.word_tokenize(sentence) j = 0 for w in words : try : X[0,j] = w2v[w] j += 1 except : pass if predict_function(model.predict(X))[0][0] == 1 : return 'Clickbait' return 'Not A Clickbait' # + id="F7A59GgSZv-r" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="1d5abaca-4a47-41a9-e896-d83944996c02" TestingOwnData('Amazing Inventions You Won’t Believe Exist') # + id="yTWkeysIRp5l" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="e1957695-8d3c-417d-f6d8-249256586a42" TestingOwnData('Tamil Nadu reports 4,280 fresh COVID-19 cases and 65 deaths') # + id="EFDKxdQCSRem" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="7dd126d6-227b-4475-94a4-b2ebc2b74609" TestingOwnData('Can Face Masks Prevent You From Getting the Coronavirus? Doctors Weight In') # + id="8MVbsB9fTA88" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="6e7aad15-9afe-480d-9e0f-56ea6ea4aa56" TestingOwnData('PM Modi asks to prepare Digital booklets documenting the relief works') # + id="OGfcrnKnTF_8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="9a4d1c38-b7a2-45ae-ec35-db8be53cb418" TestingOwnData('No passenger flights to Kolkata from Delhi, Mumbai, Chennai and 3 other cities between Jul 6-19')
Clickbait.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: conda_python3 # language: python # name: conda_python3 # --- # # This is a Markdown cell # # Use these cells to add more elaborate documentation to your notebooks. # # This includes: # [hyperlinks](https://en.wikipedia.org/wiki/Hyperlink) # # Images: # ![success](https://i.kym-cdn.com/photos/images/newsfeed/000/011/296/success_baby.jpg?1251168454) # # Math: # $$\text{argmin}_{w_0, \mathbf{w}} \sum_{i=1}^{N} (w_0 + \mathbf{x_i}^\intercal \mathbf{w} - y_i)^2$$ # + # This is a code cell from random import randint random_integers = [randint(0, 1000) for i in range(1000)] print(random_integers[:10]) def doubler(number): result = number * 2 print(number, "doubled is", result) return result doubled_numbers = [doubler(n) for n in random_integers[:10]] # -
ipynb/hello.ipynb
# -*- coding: utf-8 -*- # # Combining dependency management with conda and Docker # We can combine an environment.yml file with a Dockerfile and an install.R # script to cover many container use cases for Bioinformatics. # # ### **Overview** # # The [`nf-core`](https://github.com/nf-core) community has established a highly practical convention for creating docker containers by re-using an **environment.yml** file that can be also used for installing dependencies in an interactive session. # # There are 3 main ingredients to this Dockerfile formula: # # 1. The **environment.yml** file # 2. The template **Dockerfile** # 3. An **install.R** file _**\(optional\)**_ # # The latter is only optional and can be possibly proven useful for R libraries that are _**not**_ available via **conda**. # # ### Templates for each of the 3 files # # 1. **environment.yml** # # This file has no difference when used within a Dockerfile installation or when used natively for installing dependencies via conda. We will utilise this to create a concise Dockerfile. # # ```yaml # name: my-new-env # channels: # - conda-forge # - bioconda # - r # dependencies: # - python # - r-base # - r-devtools=2.2 # ``` # # **2. install.R** # _**Optional**_ but frequently useful, when dependencies are not available via conda. The file requires 2 lines that will prevent issues that come with non-interactive R installation. # ```r # Sys.setenv(TAR = "/bin/tar") # options(repos = "https://cloud.r-project.org/") # install.packages("remotes") # install.packages("BiocManager") # ``` # # **3. Dockerfile** # # The Dockerfile is the most integral file in the process, it constitutes the main installation blueprint in which the auxillary files **`environment.yml`** ``and **`install.R`** will be included in. # # The only part of the following **Dockerfile** that may be useful to update is the name of the environment: # # ```Dockerfile # # Snippet to update (See in the full template below the line 5) # ARG ENV_NAME="my-test-env" # ``` # ```Dockerfile # # Full contents of Dockerfile # # FROM continuumio/miniconda3:4.8.2 # LABEL description="Base docker image with conda and util libraries" # ARG ENV_NAME="my-test-env" # # # Install mamba for faster installation in the subsequent step # # Install r-base for being able to run the install.R script # RUN conda install -c conda-forge mamba r-base -y # # # Install the conda environment # COPY environment.yml / # RUN mamba env create --quiet --name ${ENV_NAME} --file /environment.yml && conda clean -a # # # Install R packages that are possibly not available via conda # COPY bin/install.R / # RUN Rscript /install.R # # # Add conda installation dir to PATH (instead of doing 'conda activate') # ENV PATH /opt/conda/envs/${ENV_NAME}/bin:$PATH # # # Dump the details of the installed packages to a file for posterity # RUN mamba env export --name ${ENV_NAME} > ${ENV_NAME}_exported.yml # # # Copy additional scripts from bin and add to PATH # RUN mkdir /opt/bin # COPY bin/* /opt/bin/ # RUN chmod +x /opt/bin/* # ENV PATH="$PATH:/opt/bin/" # ``` # # ### **Combining all the files to build the docker image**🐳 # # To build the docker container and create the docker image we will need the auxillary files to be in the same directory or a subdirectory of the root repo of the Dockerfile. # # It is typical that all files reside in the same directory. An also common practice is to create a helper folder named `bin` to hold all of the scripts and executables. To proceed withh the installation commands, make sure that your files in your directory look similar to this if you want to use the template without updating any paths: # ```bash # ➜ tree # . # ├── Dockerfile # ├── bin # │ └── install.R # ├── environment.yml # ``` # The command to build the docker container is the following, when the Dockerfile resides in the current directory: # ```bash # docker build -t lifebitai/test-docker-image:v0.1 . # ``` # It is advised to you the tag, the mark after the colon to label the version of the docker image that will be created. # # ### Pushing the docker image to the Docker Hub registry # # After the successful build process we are able to store in a registry the created docker image. # To do so, make sure you have used the login command from the terminal and have followed the command prompt to authenticate: # ```bash # docker login # ``` # After successfully logging in you will be able to run the final command to push the docker image by typing: # # ```bash # docker push lifebitai/test-docker-image:v0.1 # ``` # ### Testing or running the docker image # # To use the created docker image, a simple yet very practical way is to mount as a volume the current working directory. This will ensure access to the files available in the folder but also allow the generated results of the analysis to be retained after exiting the docker container. # # To run the docker container with the current working directory mounted, type the following command: # # ```bash # docker run -v $PWD:$PWD -w $PWD -it lifebitai/test-docker-image:v0.1 # ``` # #
classes/class_3/2-build-test-share-reuse-docker.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- import pandas as pd import numpy as np import re from ast import literal_eval # # MovieLens dataset # Files: # ``` # u.data -- The full u data set, 100000 ratings by 943 users on 1682 items. # Each user has rated at least 20 movies. Users and items are # numbered consecutively from 1. The data is randomly # ordered. This is a tab separated list of # user id | item id | rating | timestamp. # The time stamps are unix seconds since 1/1/1970 UTC # # u.info -- The number of users, items, and ratings in the u data set. # # u.item -- Information about the items (movies); this is a tab separated # list of # movie id | movie title | release date | video release date | # IMDb URL | unknown | Action | Adventure | Animation | # Children's | Comedy | Crime | Documentary | Drama | Fantasy | # Film-Noir | Horror | Musical | Mystery | Romance | Sci-Fi | # Thriller | War | Western | # The last 19 fields are the genres, a 1 indicates the movie # is of that genre, a 0 indicates it is not; movies can be in # several genres at once. # The movie ids are the ones used in the u.data data set. # # u.genre -- A list of the genres. # # u.user -- Demographic information about the users; this is a tab # separated list of # user id | age | gender | occupation | zip code # The user ids are the ones used in the u.data data set. # # u.occupation -- A list of the occupations. # # u1.base -- The data sets u1.base and u1.test through u5.base and u5.test # u1.test are 80%/20% splits of the u data into training and test data. # u2.base Each of u1, ..., u5 have disjoint test sets; this if for # u2.test 5 fold cross validation (where you repeat your experiment # u3.base with each training and test set and average the results). # u3.test These data sets can be generated from u.data by mku.sh. # u4.base # u4.test # u5.base # u5.test # # ua.base -- The data sets ua.base, ua.test, ub.base, and ub.test # ua.test split the u data into a training set and a test set with # ub.base exactly 10 ratings per user in the test set. The sets # ub.test ua.test and ub.test are disjoint. These data sets can # be generated from u.data by mku.sh. # ``` # [Movielens](https://movielens.org) is a personalized movie recommendation system. # Several datasets have been built using this database, the smallest being Movielens 100k. # It contains 100,000 ratings from 1000 users on 1700 movies. # Various information is available about the users (e.g., age, gender, occupation, zip code) and the movies (e.g., release date, genre). # Additional features can be retrieved as movie titles are available. # Two graphs can be built out of this dataset, and they can be connected using the ratings. # # The main purpose of this data is to build a recommender system that can be formulated as a semi-supervised learning problem: given a user, can you predict the ratings that they will give to a new movie? # Graph neural networks can be used for this purpose, but other graph based approaches can be explored as well. # # | Users graph | Description | Amount | # | ----------- | --------------------------------- | -----------------------------: | # | nodes | users | 1000 | # | edges | similar features | depends how the graph is built | # | features | age, gender, occupation, zip code | 4 | # | labels | ratings of the movies | 100k | # # | Movies graph | Description | Amount | # | ------------ | ------------------------- | -----------------------------: | # | nodes | movies | 1700 | # | edges | similar features | depends how the graph is built | # | features | name, release date, genre | 2 + 19 genres | # | labels | ratings given by users | 100k | # # * **Data acquisition**: already collected and packaged # * **Requires down-sampling**: no # * **Network creation**: needs to be built from features # # Resources: # * [Data](https://grouplens.org/datasets/movielens/) # * Papers using graph neural networks: # * [Geometric Matrix Completion with Recurrent Multi-Graph Neural Networks](https://arxiv.org/abs/1704.06803) # * [Graph Convolutional Matrix Completion](https://arxiv.org/abs/1706.02263) # #### Ratings # + column_ratings = ["user_id", "movie_id_ml", "rating", "rating_timestamp"] df_ratings = pd.read_csv('data/original/u.data', delimiter='\t', names=column_ratings) df_ratings["rating_timestamp"] = pd.to_datetime(df_ratings["rating_timestamp"], unit="s") print(df_ratings.shape) print(df_ratings.dtypes) df_ratings.head() # - # #### Movies def clean_movie_title(movie_title): if movie_title.split(" ")[-1].startswith("("): # remove year from the title, e.g. Toy Story (1995) --> Toy Story movie_title = (" ".join(movie_title.split(" ")[:-1])).strip() if movie_title.title().split(',')[-1].strip() in ['The', 'A']: # article + movie title, e.g. Saint, The --> The Saint movie_title = (movie_title.title().split(',')[-1].strip() + " " + " ".join(movie_title.title().split(',')[:-1])).strip() # otherwise, it was converting The Devil's Advocate to The Devil'S Advocate movie_title = movie_title.lower() return movie_title # + column_item = ["movie_id_ml", "title", "release", "vrelease", "url", "unknown", "action", "adventure", "animation", "childrens", "comedy", "crime", "documentary", "drama", "fantasy", "noir", "horror", "musical", "mystery", "romance", "scifi", "thriller", "war", "western"] df_ML_movies = pd.read_csv('data/original/u.item', delimiter='|', names=column_item, encoding = "ISO-8859-1") df_ML_movies = df_ML_movies.drop(columns=["vrelease"]) df_ML_movies["title"] = df_ML_movies["title"].apply(lambda row : clean_movie_title(row)) df_ML_movies["release"] = df_ML_movies["release"].apply(lambda x : str(x).split("-")[-1]) # drop rows where movie starts with brackets, those are some strange names... df_ML_movies = df_ML_movies[~df_ML_movies.title.str.startswith("(")] # handle seven (se7en) movies, creating new rows containing the content of brackets _df = df_ML_movies[df_ML_movies.title.str.contains("(", regex=False)] _df.title = _df.title.apply(lambda x: re.search(r'\((.*?)\)', x).group(1).strip() if re.search(r'\((.*?)\)', x) else x.strip()) df_ML_movies = df_ML_movies.append(_df) print(df_ML_movies.shape) print(df_ML_movies.dtypes) df_ML_movies.head() # - # #### Users # + column_user = ["user_id", "user_age", "user_gender", "user_occupation", "user_zipcode"] df_users = pd.read_csv('data/original/u.user', delimiter='|', names=column_user, encoding = "ISO-8859-1") df_users.head() # - # # IMDb dataset # Files: # ``` # cast_info.csv # name.csv # title.csv # movie_keywords.csv # movie_companies.csv # company_name.csv # keyword.csv # role_type.csv # ``` # The IMDb datasets contain information such as crew, rating, and genre for every entertainment product in its database. The Kaggle dataset linked above is a smaller, but similar dataset, and could be used instead of the IMDb one, which is much larger. The goal of this project is to analyze this database in graph form, and attempt to recover missing information from data on cast/crew co-appearance in movies. The graphical analysis requires network creation, for which two possible paths are possible, according to which instances one wishes to consider as the nodes of the network. # # The first approach could be to construct a social network of cast/crew members, where the edges are weighted according to co-appearance For example, actor_1 becomes strongly connected to actor_2 if they have appeared in a lot of movies together. The edges of the graph could be weighted according to a count on the number of entertainment products in which the two corresponding people participated together. We can take as a signal on this constructed graph the aggregate ratings of movies each person has participated in. # # | | Description | Amount | # | -------- | -------------------------------------- | ------------------------------: | # | nodes | cast/crew | millions (IMDb), ~8500 (Kaggle) | # | edges | co-apearance in movies/TV/etc. | O(10) per node | # | features | ratings of movies taken part in | O(10) per node | # | labels | movie genre | unknown (IMDb), 3 (Kaggle)| # # A second approach could be to create a movie-network, in which movies are strongly connected if they share a lot of crew/cast members (or some other similarity measure combining this and genres, running times, release years, etc.). There are more options for the signal the students could consider on this graph, as they could use either the movie ratings, or the genre labels. # # | | Description | Amount | # | -------- | ----------------------------------------------------- | ------------------------------: | # | nodes | movies | millions (IMDb), ~5000 (Kaggle) | # | edges | count of common cast/crew + other feature similarity. | O(10) per node | # | features | average rating | 1 | # | labels | movie genre | unknown (IMDb), 3 (Kaggle) | # # For the extra work, there is plenty of extra information. For instance, the students could try to predict the revenue of movies by potentially including extra metadata. Note however that the number of instances in the original dataset is of the order of **millions**, so a smaller subset of those should be used. # # * **Data acquisition**: already collected and packaged # * **Requires down-sampling**: yes if using the original datasets from IMDb, no if using the subsampled dataset from Kaggle # * **Network creation**: needs to be built from features # # Resources: # * <https://www.imdb.com/interfaces> # * <https://www.kaggle.com/tmdb/tmdb-movie-metadata/home> # + column_cast = ["cast_id", "person_id", "movie_id", "person_role_id", "note", "nr_order", "role_id"] df_cast = pd.read_csv('data/original/cast_info.csv', delimiter=',', names=column_cast, encoding = "ISO-8859-1", low_memory=False) df_cast['role_id'] = pd.to_numeric(df_cast['role_id'], errors='coerce') df_cast = df_cast.drop(columns=["note", "nr_order", "person_role_id"]) print(df_cast.dtypes) print(df_cast.shape) df_cast.head() # + column_people = ["person_id", "cast_name", "imdb_idx", "imdb_id", "cast_gender", "name_cf", "name_nf", "surname", "md5"] df_people = pd.read_csv('data/original/name.csv', delimiter=',', names=column_people, encoding = "ISO-8859-1", low_memory=False) print(df_people.dtypes) print(df_people.shape) df_people = df_people.drop(columns=["imdb_idx", "imdb_id", "md5", "name_cf", "name_nf", "surname"]) df_people.head() # + columns_movies = ["movie_id", "title", "imdb_idx", "movie_kind", "release", "imdb_id", "phonetic", "episode_id", "season", "episode", "series_years", "md5"] df_IMDb_movies = pd.read_csv('data/original/title.csv', delimiter=',', names=columns_movies, encoding = "ISO-8859-1", low_memory=False) df_IMDb_movies = df_IMDb_movies.drop(columns=["imdb_idx", "imdb_id", "phonetic", "md5", "episode_id", "episode", "movie_kind", "season", "series_years"]) df_IMDb_movies = df_IMDb_movies.dropna(subset=['release']) df_IMDb_movies["release"] = df_IMDb_movies["release"].apply(lambda x : str(int(x)).split("-")[-1]) # we lowered in MovieLens as well df_IMDb_movies = df_IMDb_movies.dropna(subset=["title"]) df_IMDb_movies["title"] = df_IMDb_movies["title"].apply(lambda x: x.lower()) # drop rows where movie starts with brackets, those are some strange names... df_IMDb_movies = df_IMDb_movies[~df_IMDb_movies.title.str.startswith("(")] # handle seven (se7en) movies, creating new rows containing the content of brackets _df = df_IMDb_movies[df_IMDb_movies.title.str.contains("(", regex=False)] _df.title = _df.title.apply(lambda x: re.search(r'\((.*?)\)', x).group(1).strip() if re.search(r'\((.*?)\)', x) else x.strip()) df_IMDb_movies = df_IMDb_movies.append(_df) print(df_IMDb_movies.dtypes) print(df_IMDb_movies.shape) df_IMDb_movies.head() # + column_movie_keyword = ["mkid", "movie_id", "keyword_id"] df_movie_keywords = pd.read_csv('data/original/movie_keyword.csv', delimiter=',', names=column_movie_keyword, encoding = "ISO-8859-1") print(df_movie_keywords.dtypes) print(df_movie_keywords.shape) df_movie_keywords = df_movie_keywords.drop(columns=["mkid"]) df_movie_keywords.head() # + column_movie_companies = ["mcid", "movie_id", "company_id", "ctype", "note"] df_movie_companies = pd.read_csv('data/original/movie_companies.csv', delimiter=',', names=column_movie_companies, encoding = "ISO-8859-1") print(df_movie_companies.dtypes) print(df_movie_companies.shape) df_movie_companies = df_movie_companies.drop(columns=["mcid", "ctype"]) df_movie_companies.head() # + column_companies = ["company_id", "name", "country", "imdb_id", "name_nf", "name_sf", "md5"] df_companies = pd.read_csv('data/original/company_name.csv', delimiter=',', names=column_companies, encoding = "ISO-8859-1", low_memory=False) print(df_companies.dtypes) print(df_companies.shape) df_companies = df_companies.drop(columns=["imdb_id", "name_nf", "name_sf", "md5"]) df_companies.head() # + column_keyword = ["keyword_id", "keyword", "phonetic"] df_keywords = pd.read_csv('data/original/keyword.csv', delimiter=',', names=column_keyword, encoding = "ISO-8859-1") print(df_keywords.dtypes) print(df_keywords.shape) df_keywords = df_keywords.drop(columns=["phonetic"]) df_keywords.head() # + columns_roles = ["role_id", "cast_role"] df_roles = pd.read_csv('data/original/role_type.csv', delimiter=',', names=columns_roles, encoding = "ISO-8859-1") print(df_roles.dtypes) print(df_roles.shape) df_roles.head() # - # --- # # Merge IMDb and MovieLens pd.options.display.max_columns = 100 df_movies = pd.merge(df_ML_movies, df_IMDb_movies, on=["title", "release"]) movie_ids = list(df_movies.movie_id.unique()) # ### Create separate DFs # + df_movie = pd.merge(df_movies, df_movie_keywords, on="movie_id") df_movie = pd.merge(df_movie, df_keywords, on="keyword_id") # drop excess info df_movie = df_movie.drop(columns=["movie_id_ml", "keyword_id"]) # + df_cast_people = pd.merge(df_cast, df_people, on="person_id") df_cast_people = pd.merge(df_cast_people, df_roles, on="role_id") # drop excess info df_cast_people = df_cast_people.drop(columns=["role_id"]) # - df_movie_company = pd.merge(df_movie_companies, df_companies, on="company_id") # ##### Store DFs df_movie.to_csv("data/movies.csv", sep=',') df_cast_people.to_csv("data/cast.csv", sep=',') df_movie_company.to_csv("data/companies.csv", sep=',') df_ratings.to_csv("data/ratings.csv", sep=',') df_users.to_csv("data/users.csv", sep=',') # ### Create unique DF (`df`) with everything # ##### Keywords df_movie_keyword = pd.merge(df_movie_keywords[df_movie_keywords.movie_id.isin(movie_ids)], df_keywords, on="keyword_id") df_movie_keyword = df_movie_keyword.groupby("movie_id")["keyword"].apply(list).reset_index() df_movie_keyword.tail() # ##### Cast df_movie_cast = pd.merge(df_cast[df_cast.movie_id.isin(movie_ids)], df_people, on="person_id") df_movie_cast = pd.merge(df_movie_cast, df_roles, on="role_id") df_movie_cast.head() df_movie_cast = df_movie_cast.groupby("movie_id")[["cast_id", "person_id", "cast_name", "cast_gender", "cast_role"]].apply(lambda x: json.dumps(list(x.T.to_dict().values()))).reset_index() df_movie_cast.rename(columns={0: "cast"}, inplace=True) df_movie_cast.tail() # ##### Companies # + # df_movie_companies, df_companies df_movie_company = pd.merge(df_movie_companies[df_movie_companies.movie_id.isin(movie_ids)], df_companies, on="company_id") df_movie_company = df_movie_company.groupby("movie_id")[["company_id", "name", "country", "note"]].apply(lambda x: json.dumps(list(x.T.to_dict().values()))).reset_index() df_movie_company.rename(columns={0: "company"}, inplace=True) df_movie_company.tail() # - # ### Merge 3 above DFs into main movie DF df = pd.merge(df_movies, df_movie_keyword, on="movie_id") print(df.shape) df = pd.merge(df, df_movie_cast, on="movie_id") print(df.shape) df = pd.merge(df, df_movie_company, on="movie_id") df.head() # ##### Store new DFs df.to_csv("data/movies_cast_company.csv", encoding="utf8") # --- # # Read new DFs import pandas as pd df_movies_all = pd.read_csv("data/movies.csv", sep=',') df_cast_people = pd.read_csv("data/cast.csv", sep=',') df_movie_companies = pd.read_csv("data/companies.csv", sep=',') df_ratings = pd.read_csv("data/ratings.csv", sep=',') df_users = pd.read_csv("data/users.csv", sep=',') import pandas_profiling profile_movies = df_movies_all.profile_report(title='Movies Report') profile_movies.to_file(output_file="data/movies_report.html") profile_cast = df_cast_people.profile_report(title='Cast Report') profile_cast.to_file(output_file="data/cast_report.html") profile_companies = df_movie_companies.profile_report(title='Companies Report') profile_companies.to_file(output_file="data/companies_report.html") profile_ratings = df_ratings.profile_report(title='Ratings Report') profile_ratings.to_file(output_file="data/ratings_report.html") profile_users = df_users.profile_report(title='Users Report') profile_users.to_file(output_file="data/users_report.html")
data_analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="Irpquiv8t2D0" colab_type="text" # ## Setup # + id="8ZbuY9PvnRJ6" colab_type="code" outputId="868bf3d7-bd31-40df-cdaf-ce4af3a728d6" executionInfo={"status": "ok", "timestamp": 1578223318662, "user_tz": -480, "elapsed": 9783, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 0} # !pip uninstall tensorflow -yq # !pip install tensorflow-gpu gpustat -Uq # !gpustat # + id="A_sba-HlvTO0" colab_type="code" colab={} import numpy as np import re, sys, csv, pickle from sklearn.model_selection import train_test_split import tensorflow.compat.v2 as tf from tensorflow.keras import layers # + id="eoXJplXxuV_T" colab_type="code" colab={} import matplotlib.pyplot as plt # %matplotlib inline # %config InlineBackend.figure_format = "retina" def plot_confusion_matrix(cm, labels, normalize=True, title='Confusion Matrix (Validation Set)', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.style.use('seaborn-dark') if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] #print("Normalized confusion matrix") else: #print('Confusion matrix, without normalization') pass #print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(labels)) plt.xticks(tick_marks, labels, rotation=45) plt.yticks(tick_marks, labels) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') # + [markdown] id="S002CfXLvTOv" colab_type="text" # # CNN for Text Classification # # In this notebook, we are going to do an end-to-end implemention of *Convolutional Neural Networks for Sentence Classification* (<NAME>, 2014). # # In his [paper](https://arxiv.org/abs/1408.5882), <NAME> proposed several techniques to achieve good text classification accuracy with minimal hyper-parameter tuning. # # This notebook consist of 4 main sections: # # 1. Preparing the data # 2. Implementing Yoon Kim's CNN model # 3. Training the model # 4. Evaluating the model # + id="g3iYrNFTvTOx" colab_type="code" colab={} MAX_NB_WORDS = 100000 # max no. of words for tokenizer MAX_SEQUENCE_LENGTH = 30 # max length of each entry (sentence), including padding VALIDATION_SPLIT = 0.2 # data for validation (not used in training) EMBEDDING_DIM = 100 # embedding dimensions for word vectors (word2vec/GloVe) # + [markdown] id="RNUCog3EvTO3" colab_type="text" # ## Prepare the data # + [markdown] id="6Myn_MFat0QR" colab_type="text" # ### Load Dataset # + id="7E6wD7OEvTO4" colab_type="code" outputId="70300ac9-679b-4443-a672-f2ca9c29c694" executionInfo={"status": "ok", "timestamp": 1578223323913, "user_tz": -480, "elapsed": 14957, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 35} # download pre-trained GloVe vectors GLOVE_URL = "https://github.com/OpenSUTD/machine-learning-workshop/releases/download/v0.0.01/glove.6B.100d.txt.zip" GLOVE_DIR = tf.keras.utils.get_file("glove.6B.100d.txt.zip", GLOVE_URL, cache_subdir='datasets', extract=True) print("GloVe data present at", GLOVE_DIR) GLOVE_DIR = GLOVE_DIR.replace(".zip", "") # + id="bnyH6DLsvTO6" colab_type="code" colab={} def clean_text(text): text = str(text).replace("\n", "") text = re.sub(r'[^\w\s]','',text).lower() return text.strip().replace(" ", " ") # + id="A8UF0K6ovTO8" colab_type="code" outputId="297376e9-c5a9-4f26-c234-b58f5dd9709e" executionInfo={"status": "ok", "timestamp": 1578223324530, "user_tz": -480, "elapsed": 15553, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 35} DATA_URL = "https://github.com/OpenSUTD/machine-learning-workshop/releases/download/v0.0.01/stanford_movie.zip" DATA_DIR = tf.keras.utils.get_file("stanford_movie.zip", DATA_URL, cache_subdir='datasets', extract=True) print("Dataset present at", DATA_DIR) DATA_DIR = DATA_DIR.replace(".zip", "") # + id="hauprCXtvTO-" colab_type="code" colab={} texts, labels = [], [] # empty lists for the sentences and labels data_neg = open(DATA_DIR+"/stanford_movie_neg.txt", "r", encoding="latin-1") for line in data_neg: texts.append(clean_text(line)) labels.append(int(0)) # + id="pQHaUCVQvTPA" colab_type="code" colab={} data_pos = open(DATA_DIR+"/stanford_movie_pos.txt", "r", encoding="latin-1") for line in data_pos: texts.append(clean_text(line)) labels.append(int(1)) # + id="VMOCwQeMvTPC" colab_type="code" outputId="c8d3a106-9214-4720-ddf7-4fee9707f5e0" executionInfo={"status": "ok", "timestamp": 1578223324533, "user_tz": -480, "elapsed": 15529, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 53} print("Sample negative:", texts[0], labels[0]) print("Sample positive:", texts[-1], labels[-1]) # + [markdown] id="tvMPsIBZvTPE" colab_type="text" # ### Create Word Tokenizer # + id="P49WuzeWvTPE" colab_type="code" outputId="6b020e82-4093-4dc6-96d0-e6dd5b2d6a85" executionInfo={"status": "ok", "timestamp": 1578223324533, "user_tz": -480, "elapsed": 15520, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 35} try: with open('tokenizer.pickle', 'rb') as f: tokenizer = pickle.load(f) print("Using cached tokenizer") except Exception as e: print(e) print("Creating new tokenizer") tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=MAX_NB_WORDS) tokenizer.fit_on_texts(texts) with open('tokenizer.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) print("[i] Saved word tokenizer to file: tokenizer.pickle") # + [markdown] id="SlOdO6_VvTPH" colab_type="text" # **Generate the array of sequences from dataset** # + id="PhOzOvw_vTPH" colab_type="code" outputId="2a74d120-ac92-43af-a394-ca97aa52e19d" executionInfo={"status": "ok", "timestamp": 1578223325144, "user_tz": -480, "elapsed": 16120, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 35} sequences = tokenizer.texts_to_sequences(texts) word_index = tokenizer.word_index print('[i] Vocabulary size:', len(word_index)) # pad on both ends data_int = tf.keras.preprocessing.sequence.pad_sequences(sequences, padding='pre', maxlen=(MAX_SEQUENCE_LENGTH-5)) data = tf.keras.preprocessing.sequence.pad_sequences(data_int, padding='post', maxlen=(MAX_SEQUENCE_LENGTH)) # + [markdown] id="8opaBJWtvTPJ" colab_type="text" # ### Train-Validation split # + id="wjlaCdoPvTPJ" colab_type="code" outputId="5ad5d494-3b8b-4b91-becd-04fb11331f3a" executionInfo={"status": "ok", "timestamp": 1578223325144, "user_tz": -480, "elapsed": 16108, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 107} # convert the category label to one-hot encoding labels = tf.keras.utils.to_categorical(np.asarray(labels)) print('[i] Shape of data tensor:', data.shape) print('[i] Shape of label tensor:', labels.shape) x_train, x_val, y_train, y_val = train_test_split(data, labels, test_size=VALIDATION_SPLIT) print('[i] Number of entries in each category:') print("[+] Training:", y_train.sum(axis=0)) print("[+] Validation:", y_val.sum(axis=0)) # + [markdown] id="9ERTcDlRvTPL" colab_type="text" # ### Inspecting the data # + id="2btHtPfHvTPM" colab_type="code" outputId="15e19b67-c939-4aea-b345-3df641ffa464" executionInfo={"status": "ok", "timestamp": 1578223325145, "user_tz": -480, "elapsed": 16099, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 143} print("Tokenized sequence:\n", data[0]) print("") print("One-hot label:\n", labels[0]) # + [markdown] id="HrMfVDf1vTPN" colab_type="text" # ## Create the Model # # Yoon Kim's model has several notable features: # # * two sets of word embeddings for what he terms a **"multi-channel" approach**. # * One of the word embeddings will be frozen (**"static channel"**), and one will be modified during the training process (**"non-static channel"**). # * multiple convolutional kernel sizes # # We will now start to create the model in Tensorflow 2.0 using `tf.keras`. # + [markdown] id="RmFWnm0WvTPO" colab_type="text" # **Load word embeddings into an `embeddings_index`** # Create an index of words mapped to known embeddings, by parsing the data dump of pre-trained embeddings. # # We use a set from [pre-trained GloVe vectors from Stanford](https://nlp.stanford.edu/projects/glove/). # + id="_YTYHeYFvTPO" colab_type="code" outputId="37c0c36e-909f-4101-f742-1685a7434c78" executionInfo={"status": "ok", "timestamp": 1578223336200, "user_tz": -480, "elapsed": 27144, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 53} embeddings_index = {} f = open(GLOVE_DIR) print("[i] (long) Loading GloVe from:",GLOVE_DIR,"...",end="") for line in f: values = line.split() word = values[0] embeddings_index[word] = np.asarray(values[1:], dtype='float32') f.close() print("Done.\n[+] Proceeding with Embedding Matrix...", end="") embedding_matrix = np.random.random((len(word_index) + 1, EMBEDDING_DIM)) for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector print(" Completed!") # + id="5DnIZmXZvTPQ" colab_type="code" colab={} # second embedding matrix for non-static channel embedding_matrix_ns = np.random.random((len(word_index) + 1, EMBEDDING_DIM)) for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix_ns[i] = embedding_vector # + [markdown] id="9EFnEi8wvTPS" colab_type="text" # **Create the `Embedding` layers** # + id="X-ZiPl6MvTPS" colab_type="code" colab={} sequence_input = layers.Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') # input to the model # static channel embedding_layer_frozen = layers.Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, mask_zero=True, trainable=False) embedded_sequences_frozen = embedding_layer_frozen(sequence_input) # non-static channel embedding_layer_train = layers.Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix_ns], input_length=MAX_SEQUENCE_LENGTH, mask_zero=True, trainable=True) embedded_sequences_train = embedding_layer_train(sequence_input) l_embed = layers.Concatenate(axis=1)([embedded_sequences_frozen, embedded_sequences_train]) # + [markdown] id="bV9amYH4vTPU" colab_type="text" # **Create the CNN layer with multiple kernel (filter) sizes** # + id="dasUnnytvTPV" colab_type="code" colab={} l_conv_3 = layers.Conv1D(filters=32,kernel_size=3,activation='relu')(l_embed) l_conv_4 = layers.Conv1D(filters=32,kernel_size=4,activation='relu')(l_embed) l_conv_5 = layers.Conv1D(filters=32,kernel_size=5,activation='relu')(l_embed) l_conv = layers.Concatenate(axis=1)([l_conv_3, l_conv_4, l_conv_5]) # + [markdown] id="EAhAWor8vTPW" colab_type="text" # Followed by the rest of the model (boring!!) # + id="V_xcWGw3vTPX" colab_type="code" colab={} l_pool = layers.MaxPooling1D(4)(l_conv) l_drop = layers.Dropout(0.5)(l_pool) l_flat = layers.Flatten()(l_drop) l_dense = layers.Dense(16, activation='relu')(l_flat) preds = layers.Dense(2, activation='softmax')(l_dense) #follows the number of classes # + [markdown] id="l-pEzKiRvTPa" colab_type="text" # **Compile the model into a static graph for training** # + id="a9i0hhxvvTPb" colab_type="code" outputId="91b2ecd1-1bf4-4ebc-aeba-69a7a7045325" executionInfo={"status": "ok", "timestamp": 1578223337881, "user_tz": -480, "elapsed": 28784, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 683} model = tf.keras.models.Model(sequence_input, preds) model.compile(loss='binary_crossentropy', optimizer="adam", metrics=["acc"]) model.summary() # + [markdown] id="oaefPOSmvTPe" colab_type="text" # ### Model Visualisation # + id="GWXK9tvlvTPe" colab_type="code" outputId="f24da5f1-49c5-45f3-ae45-ae3e71ad2ef5" executionInfo={"status": "ok", "timestamp": 1578223337881, "user_tz": -480, "elapsed": 28773, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 1000} tf.keras.utils.plot_model( model, show_shapes=True, show_layer_names=True, ) # + [markdown] id="YfDZuRWavTPg" colab_type="text" # ## Train the Model # + id="vd1pLOtowr0H" colab_type="code" colab={} model_checkpoint = tf.keras.callbacks.ModelCheckpoint("best_weights.h5", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True,) # + id="CL_WYbgfvTPg" colab_type="code" outputId="29e13400-53b0-491d-e786-97066c680593" executionInfo={"status": "ok", "timestamp": 1578223382577, "user_tz": -480, "elapsed": 73425, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 773} print("Training Progress:") model_log = model.fit(x_train, y_train, validation_data=(x_val, y_val), callbacks=[model_checkpoint], epochs=10, batch_size=64) # + id="C08trVXvvTPi" colab_type="code" colab={} model.load_weights("best_weights.h5") # + [markdown] id="Wh9vMTIyvTPl" colab_type="text" # ## Evaluate the Model # + id="UECDY83VvTPl" colab_type="code" outputId="06db11bd-f7a5-4af0-d45c-da6af29e81ee" executionInfo={"status": "ok", "timestamp": 1578223383910, "user_tz": -480, "elapsed": 74729, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 571} plt.plot(model_log.history['acc']) plt.plot(model_log.history['val_acc']) plt.title('Accuracy (Higher Better)') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() plt.plot(model_log.history['loss']) plt.plot(model_log.history['val_loss']) plt.title('Loss (Lower Better)') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() # + id="wV1S4vlnvTPn" colab_type="code" colab={} from sklearn.metrics import classification_report, confusion_matrix import itertools, pickle classes = ["negative", "positive"] # + id="QU9-RgsVvTPo" colab_type="code" outputId="c39c4442-2e51-4710-d3c7-7bc8b4a7cc54" executionInfo={"status": "ok", "timestamp": 1578223384198, "user_tz": -480, "elapsed": 74991, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 179} Y_test = np.argmax(y_val, axis=1) # Convert one-hot to index y_pred = model.predict(x_val) y_pred_class = np.argmax(y_pred,axis=1) print(classification_report(Y_test, y_pred_class, target_names=classes)) # + id="blyeo-U-vTPq" colab_type="code" outputId="e099c02a-aa7c-4c32-8f54-1f0f9bcc8dbc" executionInfo={"status": "ok", "timestamp": 1578223385140, "user_tz": -480, "elapsed": 75920, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} colab={"base_uri": "https://localhost:8080/", "height": 526} plt.figure(figsize=(14,7)) cnf_matrix = confusion_matrix(Y_test, y_pred_class) cnf_matrix = confusion_matrix(Y_test, y_pred_class) plot_confusion_matrix(cnf_matrix, labels=classes) # + [markdown] id="PyEJeB1ob9QY" colab_type="text" # ## Interprete the Model # + id="-zoGBb4LyCn1" colab_type="code" colab={} from IPython.core.display import display, HTML model.layers[1].trainable = True def export_html(result, max_activation): output = "" max_activation += 1e-8 for line in result: word, activation = line if activation>0: activation = activation/max_activation colour = str(int(255 - activation*255)) tag_open = "<span style='background-color: rgb(255,"+colour+","+colour+");'>" else: activation = -1 * activation/max_activation colour = str(int(255 - activation*255)) tag_open = "<span style='background-color: rgb("+colour+","+colour+",255);'>" tag_close = "</span>" tag = " ".join([tag_open, word, tag_close]) output = output + tag output = output + "" return output grads = None def plot_dependency(input_text, label): global grads input_tokens = tokenizer.texts_to_sequences([input_text]) input_tokens = tf.keras.preprocessing.sequence.pad_sequences(input_tokens, padding='pre', maxlen=(MAX_SEQUENCE_LENGTH-5)) input_tokens = tf.keras.preprocessing.sequence.pad_sequences(input_tokens, padding='post', maxlen=(MAX_SEQUENCE_LENGTH)) loss = tf.keras.losses.binary_crossentropy x = tf.convert_to_tensor(input_tokens, dtype=tf.float32) y_true = tf.convert_to_tensor(label, dtype=tf.float32) with tf.GradientTape() as g: g.watch(x) y = model(x) loss_value = loss(y_true, y) while loss_value < 1e-3: loss_value *= 1e2 grads = g.gradient(loss_value, model.trainable_weights) input_grads = grads[0].values.numpy()**2 + grads[1].values.numpy()**2 input_grads = np.sum(input_grads, axis=-1).tolist() input_tokens = input_tokens.reshape(MAX_SEQUENCE_LENGTH).tolist() nopad_grads = [] for n in range(MAX_SEQUENCE_LENGTH): if input_tokens[n] > 0: nopad_grads.append(input_grads[n]) nopad_grads = np.asarray(nopad_grads) result = zip(input_text.split(" "), nopad_grads) output = export_html(result, max(nopad_grads)) output = "<tt>" + output + "</tt>" display(HTML(output)) # + id="7U32UbHAGlt0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="c0152522-f0f5-41c9-f613-65b88265e2a0" executionInfo={"status": "ok", "timestamp": 1578223607186, "user_tz": -480, "elapsed": 2117, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCS8LwI0k0t2vkujQUBYfPPAo7627gWEnmKxe1ocA=s64", "userId": "03413426750796061565"}} for n in range(20): test_text = tokenizer.sequences_to_texts([x_train[n]])[0] pred = model.predict(x_train[n:n+1])[0] test_label = [y_train[n]] print("True:", classes[np.argmax(test_label)], "/ Pred:", classes[np.argmax(pred)]) plot_dependency(test_text, test_label) print(" ") # + id="QNW124c4dRTG" colab_type="code" colab={}
labs/text_classification_cnn.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Chemical Synapse Model import numpy as np import matplotlib.pyplot as plt S0 = 1000 S_max = 100000 V_Deg = 100 V_Uptake = 1000 U0 = -70 U_spike = 30 U_R_2 = 0.05 U_R_3 = 0.1 U_R_4 = 0.13 P_R_2 = 0.6 P_R_3 = 0.71 P_R_4 = 0.97 T = 10 R_abs = 1500 # ## Model class Model: def __init__(self, v_rel, xyz, max_t=(T * (10 ** 3)), step=5): self.v_rel = v_rel if abs(sum(xyz)) != R_abs: raise ValueError('`xyz` should sum up to `R_abs` in absolute value.') self.x, self.y, self.z = xyz u, data = U0, [] for t in range(0, max_t, step): values_t = self._step(u, t, step) values_t['t'] = t if values_t['u'] >= U_spike: values_t['f_activation'] = 1 u = U0 else: values_t['f_activation'] = 0 u = values_t['u'] data.append(values_t) self.data = data def _step(self, u, t, step): s = S0 + (self.v_rel - V_Deg - V_Uptake) * t s = max(0, min(S_max, s)) q_r_2 = np.random.binomial(self.x, s * P_R_2 / S_max) q_r_3 = np.random.binomial(self.y, s * P_R_3 / S_max) q_r_4 = np.random.binomial(self.z, s * P_R_4 / S_max) u = u + step * (U_R_2 * q_r_2 + U_R_3 * q_r_3 + U_R_4 * q_r_4) return { 's': s, 'q_r_2': q_r_2, 'q_r_3': q_r_3, 'q_r_4': q_r_4, 'u': u, } def __len__(self): return len(self.data) def __getitem__(self, index): if isinstance(index, int): return self.data[index] elif isinstance(index, str): return np.array([step[index] for step in self.data], dtype=np.float32) else: raise ValueError('Invalid index for getter.') def __getattr__(self, index): return self[index] @property def max_seq_spikes(self): cur_seq, max_seq = 0, 0 for a in model.f_activation: if np.isclose(a, 1.0): cur_seq += 1 else: cur_seq = 0 max_seq = max(max_seq, cur_seq) return max_seq def plot(model): plt.figure(figsize=(15, 20)) plt.subplot(5, 1, 1) plt.xlabel('t') plt.ylabel('s') plt.plot(model.t, model.s) plt.subplot(5, 1, 2) plt.xlabel('t') plt.ylabel('u') plt.plot(model.t, model.u) plt.subplot(5, 1, 3) plt.xlabel('t') plt.ylabel('Q_R_2') plt.plot(model.t, model.q_r_2) plt.subplot(5, 1, 4) plt.xlabel('t') plt.ylabel('Q_R_3') plt.plot(model.t, model.q_r_3) plt.subplot(5, 1, 5) plt.xlabel('t') plt.ylabel('Q_R_4') plt.plot(model.t, model.q_r_4) model = Model( v_rel=V_Deg + V_Uptake, xyz=(1500, 0, 0), ) plot(model) # + [markdown] heading_collapsed=true # ## Task 1 # + hidden=true model = Model( v_rel=V_Deg + V_Uptake + 5, xyz=(1500, 0, 0), ) assert model.max_seq_spikes >= 10 plot(model) # + [markdown] heading_collapsed=true # ## Task 2 # + hidden=true model = Model( v_rel=V_Deg + V_Uptake + 5, xyz=(500, 500, 500), ) assert model.max_seq_spikes >= 50 plot(model) # - # ## Deadline Task # Optimization algorithm: brute force with step increased. for x in range(0, 1501, 25): for y in range(0, 1501 - x, 25): z = 1500 - x - y model = Model( v_rel=V_Deg + V_Uptake + 4, # "+5" gives too good results. xyz=(x, y, z), ) if 10 <= model.max_seq_spikes <= 15: print('SUCCES: ', x, y, z, model.max_seq_spikes) model = Model( v_rel=V_Deg + V_Uptake + 4, xyz=(1425, 25, 50), ) assert 10 <= model.max_seq_spikes <= 15 plot(model)
task02/task02.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:fast_tabnet] # language: python # name: conda-env-fast_tabnet-py # --- from fastai.basics import * from fastai.tabular.all import * from fast_tabnet.core import * import wget, gzip, shutil np.random.seed(0) # # Forest Cover Type dataset BASE_DIR = Path.home().joinpath('data/tabnet') datafile = BASE_DIR.joinpath('covtype.data.gz') datafile.parent.mkdir(parents=True, exist_ok=True) url = "https://archive.ics.uci.edu/ml/machine-learning-databases/covtype/covtype.data.gz" if not datafile.exists(): wget.download(url, datafile.as_posix()) # + target = "Covertype" cat_names = [ "Wilderness_Area1", "Wilderness_Area2", "Wilderness_Area3", "Wilderness_Area4", "Soil_Type1", "Soil_Type2", "Soil_Type3", "Soil_Type4", "Soil_Type5", "Soil_Type6", "Soil_Type7", "Soil_Type8", "Soil_Type9", "Soil_Type10", "Soil_Type11", "Soil_Type12", "Soil_Type13", "Soil_Type14", "Soil_Type15", "Soil_Type16", "Soil_Type17", "Soil_Type18", "Soil_Type19", "Soil_Type20", "Soil_Type21", "Soil_Type22", "Soil_Type23", "Soil_Type24", "Soil_Type25", "Soil_Type26", "Soil_Type27", "Soil_Type28", "Soil_Type29", "Soil_Type30", "Soil_Type31", "Soil_Type32", "Soil_Type33", "Soil_Type34", "Soil_Type35", "Soil_Type36", "Soil_Type37", "Soil_Type38", "Soil_Type39", "Soil_Type40" ] cont_names = [ "Elevation", "Aspect", "Slope", "Horizontal_Distance_To_Hydrology", "Vertical_Distance_To_Hydrology", "Horizontal_Distance_To_Roadways", "Hillshade_9am", "Hillshade_Noon", "Hillshade_3pm", "Horizontal_Distance_To_Fire_Points" ] feature_columns = ( cont_names + cat_names + [target]) # - df = pd.read_csv(datafile, header=None, names=feature_columns) df.head() procs = [Categorify, FillMissing, Normalize] splits = RandomSplitter(0.05)(range_of(df)) to = TabularPandas(df, procs, cat_names, cont_names, y_names=target, y_block = CategoryBlock(), splits=splits) dls = to.dataloaders(bs=64*64*4) model = TabNetModel(get_emb_sz(to), len(to.cont_names), dls.c, n_d=64, n_a=64, n_steps=5, virtual_batch_size=256) opt_func = partial(Adam, wd=0.01, eps=1e-5) learn = Learner(dls, model, CrossEntropyLossFlat(), opt_func=opt_func, lr=3e-2, metrics=[accuracy]) model.size() learn.fit_one_cycle(10) # # Poker hand # https://www.kaggle.com/c/poker-rule-induction BASE_DIR = Path.home().joinpath('data/tabnet/poker') df = pd.read_csv(BASE_DIR.joinpath('train.csv')) df.head() cat_names = ['S1', 'S2', 'S3', 'S4', 'S5', 'C1', 'C2', 'C3', 'C4', 'C5'] cont_names = [] target = ['hand'] procs = [Categorify, Normalize] splits = RandomSplitter(0.05)(range_of(df)) to = TabularPandas(df, procs, cat_names, cont_names, y_names=target, y_block = CategoryBlock(), splits=splits) dls = to.dataloaders(bs=64*4) model = TabNetModel(get_emb_sz(to), len(to.cont_names), dls.c, n_d=16, n_a=16, n_steps=5, virtual_batch_size=256, gamma=1.5) opt_func = partial(Adam, eps=1e-5) learn = Learner(dls, model, CrossEntropyLossFlat(), opt_func=opt_func, lr=3e-2, metrics=[accuracy]) learn.lr_find() learn.fit_one_cycle(1000) # # Sarcos Robotics Arm Inverse Dynamics # http://www.gaussianprocess.org/gpml/data/ BASE_DIR = Path.home().joinpath('data/tabnet/sarcos') from mat4py import * wget.download('http://www.gaussianprocess.org/gpml/data/sarcos_inv.mat', BASE_DIR.as_posix()) wget.download('http://www.gaussianprocess.org/gpml/data/sarcos_inv_test.mat', BASE_DIR.as_posix()) data = loadmat(BASE_DIR.joinpath('sarcos_inv.mat').as_posix()) df = pd.DataFrame(data['sarcos_inv']) df.head() data = loadmat(BASE_DIR.joinpath('sarcos_inv_test.mat').as_posix()) test_df = pd.DataFrame(data['sarcos_inv_test']) splits = RandomSplitter()(df) procs = [Normalize] to = TabularPandas(df, procs, cat_names=[], cont_names=list(range(0,27)), y_names=27, splits=splits, y_block=TransformBlock()) dls = to.dataloaders(bs=512) model = TabNetModel([], len(to.cont_names), 1, n_d=64, n_a=64, n_steps=5, virtual_batch_size=256) opt_func = partial(Adam, wd=0.01, eps=1e-5) learn = Learner(dls, model, MSELossFlat(), opt_func=opt_func, lr=1e-2) model.size() learn.lr_find() learn.fit_one_cycle(1000) dl = learn.dls.test_dl(test_df) learn.validate(dl=dl) # # <NAME> BASE_DIR = Path.home().joinpath('data/tabnet/higgs') datafile = BASE_DIR.joinpath('HIGGS.csv.gz') datafile.parent.mkdir(parents=True, exist_ok=True) url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00280/HIGGS.csv.gz' if not datafile.exists(): wget.download(url, datafile.as_posix()) feature_columns = ['label', 'lepton pT', 'lepton eta', 'lepton phi', 'missing energy magnitude', 'missing energy phi', 'jet 1 pt', 'jet 1 eta', 'jet 1 phi', 'jet 1 b-tag', 'jet 2 pt', 'jet 2 eta', 'jet 2 phi', 'jet 2 b-tag', 'jet 3 pt', 'jet 3 eta', 'jet 3 phi', 'jet 3 b-tag', 'jet 4 pt', 'jet 4 eta', 'jet 4 phi', 'jet 4 b-tag', 'm_jj', 'm_jjj', 'm_lv', 'm_jlv', 'm_bb', 'm_wbb', 'm_wwbb'] df = pd.read_csv(datafile, header=None, names=feature_columns) df.head() df['label'] = df['label'].astype(int) df.replace({'label': {1.0:'yes',0.0:'no'}}, inplace=True) splits = IndexSplitter(range(len(df)-500000, len(df)))(df) procs = [Normalize] to = TabularPandas(df, procs, cat_names=[], cont_names=feature_columns[1:], y_names='label', splits=splits) dls = to.dataloaders(bs=64*64*4) model = TabNetModel([], len(to.cont_names), dls.c, n_d=64, n_a=64, n_steps=5, virtual_batch_size=256) opt_func = partial(Adam, wd=0.01, eps=1e-5) learn = Learner(dls, model, CrossEntropyLossFlat(), opt_func=opt_func, lr=3e-2, metrics=[accuracy]) model.size() learn.lr_find() learn.fit_one_cycle(10)
01_examples.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import os import matplotlib import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd import numpy as np import datetime import seaborn as sns import peakutils from peakutils.plot import plot as pplot # %matplotlib inline SMALL_SIZE = 8 MEDIUM_SIZE = 8 BIGGER_SIZE = 10 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title # + mut_og = pd.read_csv('./TDR_soil_moisture/TDR_MUT.csv', index_col='date', parse_dates=True, header=0,dtype=np.float64,na_values=' NaN', names=['date',0.0,0.3,0.5,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]) k04_og = pd.read_csv('./TDR_soil_moisture/TDR_K04.csv', index_col='date', parse_dates=True, header=0,dtype=np.float64,na_values=' NaN', names=['date',0.0,0.3,0.5,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]) # + kj_kcl = pd.read_excel('./ch4_data_archive.xlsx', sheet_name='Jankowski_KClext',na_values='') kj_kcl_stats = kj_kcl.groupby(['Landuse','depth_m']).describe() soil = pd.read_excel('./ch4_data_archive.xlsx',sheet_name='physical_props') soil_dry = pd.concat([soil['sample'],soil['dry_mass_kg'],soil['GWC']],axis=1) ion_kcl = pd.read_excel('./ch4_data_archive.xlsx',sheet_name='KCl_extract_data',na_values='#NA') ion_kcl = ion_kcl.merge(soil_dry, on='sample') # 0.05 L is the volume of extractant we used ion_kcl['nitrate_mmolkg'] = (ion_kcl['nitrate_mM'] * 0.05) / ion_kcl['dry_mass_kg'] ion_kcl['sample'] = ion_kcl['sample'].str.split('-') for i in ion_kcl.index: ion_kcl.loc[i,'location'] = ion_kcl.loc[i,'sample'][0] ion_kcl.loc[i,'hole'] = ion_kcl.loc[i,'sample'][1] ion_kcl.loc[i,'depth'] = float(ion_kcl.loc[i,'sample'][2]) kcl_group = ion_kcl.groupby(['landuse','depth']) kcl_stats = kcl_group.describe() # - # ## Figures def storage(df): storage = df.copy() layers = [10.] * 12 # 10 cm thickness around each TDR probe for l,c in zip(layers,df.columns): storage[c] = df[c] * l return storage # + mut_stor = storage(mut_og) k04_stor = storage(k04_og) bottoms = np.array([15, 25, 35, 75, 100, 100, 100, 100, 100, 100, 100, 100], dtype='float64').cumsum() # + mut_diff = (mut_stor.diff() / 6) * 10 # divide by six for the 6 hr interval, times 10 for cm-->mm mut_diff.mask(mut_diff >= 0.000, np.nan, inplace=True) mut_n = mut_diff.describe().loc['count',:] k04_diff = (k04_stor.diff() / 6) * 10 # divide by six for the 6 hr interval k04_diff.mask(k04_diff >= 0.000, np.nan, inplace=True) k04_n = k04_diff.describe().loc['count',:] # + fig, [ax1,ax2] = plt.subplots(2,1, figsize=(3,6),dpi=300,sharey=True,sharex=True) data = mut_diff sns.boxplot(data=-data, palette='gray_r', orient='h', whis=(10,90), showfliers=False, linewidth=1, ax=ax1) sns.stripplot( data=-data, jitter=True, dodge=True, marker='o', size=3, alpha=0.3, color='gray', orient='h', ax=ax1 ) data = k04_diff sns.boxplot(data=-data, palette='gray_r', orient='h', whis=(10,90), showfliers=False, linewidth=1, ax=ax2) sns.stripplot( data=-data, jitter=True, dodge=True, marker='o', size=3, alpha=0.3, color='gray', orient='h', ax=ax2 ) # assume that ET varies linearly over first 1 meter, see Notability for using trig to calculate for_evap_yr = [512.5, 358.75, 256.25] soy_evap_yr = [339.5, 237.65, 169.75] for_evap_hr_halfYr = [x/182.5/24 for x in for_evap_yr] # assume most ET occurs during half of year... soy_evap_hr_halfYr = [x/182.5/24 for x in soy_evap_yr] # assume most ET occurs during half of year... for_evap_hr_fullYr = [x/365/24 for x in for_evap_yr] # even ET all year soy_evap_hr_fullYr = [x/365/24 for x in soy_evap_yr] # even ET all year width=2 ax1.axvline(soy_evap_hr_fullYr[0],lw=width,ls='--',color='r',alpha=.75,ymin=.92,zorder=3) ax1.axvline(soy_evap_hr_fullYr[1],lw=width,ls='--',color='r',alpha=.75,ymax=.92,ymin=.83,zorder=3) ax1.axvline(soy_evap_hr_fullYr[2],lw=width,ls='--',color='r',alpha=.75,ymax=.83,ymin=.75,zorder=3) ax2.axvline(for_evap_hr_fullYr[0],lw=width,ls='--',color='r',alpha=.75,ymin=.92,zorder=3) ax2.axvline(for_evap_hr_fullYr[1],lw=width,ls='--',color='r',alpha=.75,ymax=.92,ymin=.83,zorder=3) ax2.axvline(for_evap_hr_fullYr[2],lw=width,ls='--',color='r',alpha=.75,ymax=.83,ymin=.75,zorder=3) ax1.set_xscale('log') ax1.set_xlim(10**-2,10**0) ax1.set_title('Ag-2') ax2.set_title('Fr-2') ax2.set_xlabel('Water flux out of layer (mm/hr)') for ax in (ax1,ax2): ax.set_ylabel('Depth (m)') if ax1.get_xscale() == 'log': ax.xaxis.set_major_formatter( matplotlib.ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(y),0)))).format(y))) for i,n in enumerate(mut_n): ax1.annotate('({})'.format(round(n)),xy=(.9,i),fontsize=6,va='center',ha='right') for i,n in enumerate(k04_n): ax2.annotate('({})'.format(round(n)),xy=(.9,i),fontsize=6,va='center',ha='right') ax1.tick_params(axis='both',which='both',direction='in',top=True,right=True) ax2.tick_params(axis='both',which='both',direction='in',top=True,right=True) fig.tight_layout() fig.patch.set_facecolor('w') # + q = 0.1 lw = 1 fig,ax = plt.subplots(1,2,figsize=(6,4),dpi=300,sharex=True,sharey=True) df=mut_diff n = len(df) ax[0].plot(-df.quantile(q).values,df.columns.values,'--o',color='k', linewidth=lw, markerfacecolor='w', label='{} percentile'.format(1-q)) # ax[0].plot(-df.quantile(q).values,df.columns.values,alpha=0.7,facecolor='k',edgecolor='k', # label='{} percentile'.format(1-q)) # ax[0].scatter(x=df.min().values,y=df.columns.values,marker='+',color='k',label='Max') df=k04_diff n = len(df) ax[1].plot(-df.quantile(q).values,df.columns.values,'--o',color='k', linewidth=lw, markerfacecolor='w', label='{} percentile'.format(1-q)) # ax[1].scatter(-df.quantile(q).values,df.columns.values,alpha=0.7,facecolor='k',edgecolor='k', # label='{} percentile'.format(1-q)) # ax[1].scatter(x=df.min().values,y=df.columns.values,marker='+',color='k',label='Max') ax[0].set_yticks(np.arange(0,10,1)) ax[0].set_ylim(8.1,-0.1) ax[0].set_xlim(.01,0.085) ax[0].set_xlabel('Water flux - 90th percentile (mm/hr)',color='k') ax[1].set_xlabel('Water flux - 90th percentile (mm/hr)',color='k') ax[0].tick_params(axis='x',labelcolor='k') ax[1].tick_params(axis='x',labelcolor='k') ax[0].set_ylabel('Depth (m)') # ax[1].set_ylabel('Depth (m)') # ax[0].legend(loc='lower right') # ax[1].legend(loc='lower right') ax[0].tick_params('both',direction='in',right=True) ax[1].tick_params('both',direction='in',right=True) ax[0].set_title('Soy',size=10) ax[1].set_title('Forest',size=10) # plot nitrate data df = kj_kcl_stats.loc['soybean'] x = df['nitrate_mmolkg']['mean']*1000 xerr = df['nitrate_mmolkg']['std']*1000 / np.sqrt(df['nitrate_mmolkg']['count']) ax2 = ax[0].twiny() ax2.errorbar(x=x,y=df.index,xerr=xerr,label='2015', fmt='s-',linewidth=lw,elinewidth=0.5,capsize=2,color='gray',markerfacecolor='w') df = kj_kcl_stats.loc['forest'] x = df['nitrate_mmolkg']['mean']*1000 xerr = df['nitrate_mmolkg']['std']*1000 / np.sqrt(df['nitrate_mmolkg']['count']) ax3 = ax[1].twiny() ax3.errorbar(x=x,y=df.index,xerr=xerr,label='2015', fmt='s-',linewidth=lw,elinewidth=.5,capsize=2,color='gray',markerfacecolor='w') # df = kcl_stats.loc['soybean'] # ax2.errorbar(x=df['nitrate_mmolkg']['mean'],y=df.index,xerr=df['nitrate_mmolkg']['std'],label='2019', # fmt='^-',linewidth=lw,elinewidth=0.5,capsize=2,color='k',markerfacecolor='None') # df = kcl_stats.loc['forest'] # ax3.errorbar(x=df['nitrate_mmolkg']['mean'],y=df.index,xerr=df['nitrate_mmolkg']['std'],label='2019', # fmt='^-',linewidth=lw,elinewidth=.5,capsize=2,color='k',markerfacecolor='None') ax2.set_xlim(0,1300) ax3.set_xlim(0,1300) # ax[0].fill_between((0,1),1,2,alpha=.2,zorder=-1,facecolor='k',edgecolor='None') # ax[1].fill_between((0,1),1,1.5,alpha=.2,zorder=-1,facecolor='k',edgecolor='None') ax2.set_xlabel('KCl-extractable NO$_3$ (μmol/kg dry soil)',color='gray') ax3.set_xlabel('KCl-extractable NO$_3$ (μmol/kg dry soil)',color='gray') ax2.tick_params(axis='x',labelcolor='gray') ax2.tick_params(direction='in',top=True) ax3.tick_params(axis='x',labelcolor='gray') ax3.tick_params(direction='in',top=True) # ax[0].annotate(xy=(),) ax[0].fill_between((0,1),1.,2,alpha=.2,zorder=-1,facecolor='tab:blue',edgecolor=None) ax[1].fill_between((0,1),.5,1.5,alpha=.2,zorder=-1,facecolor='tab:blue',edgecolor=None) fig.tight_layout() fig.patch.set_facecolor('w') # -
TDR_KCl_archive.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ![MIT Deep Learning](https://deeplearning.mit.edu/files/images/github/mit_deep_learning.png) # + [markdown] colab_type="text" id="" # <table align="center"> # <td align="center"><a target="_blank" href="https://deeplearning.mit.edu"> # <img src="https://deeplearning.mit.edu/files/images/github/icon_mit.png" style="padding-bottom:5px;" /> # Visit MIT Deep Learning</a></td> # <td align="center"><a target="_blank" href="http://colab.research.google.com/github/lexfridman/mit-deep-learning/blob/master/tutorial_deep_learning_basics/deep_learning_basics.ipynb"> # <img src="https://deeplearning.mit.edu/files/images/github/icon_google_colab.png" style="padding-bottom:5px;" />Run in Google Colab</a></td> # <td align="center"><a target="_blank" href="https://github.com/lexfridman/mit-deep-learning/blob/master/tutorial_deep_learning_basics/deep_learning_basics.ipynb"> # <img src="https://deeplearning.mit.edu/files/images/github/icon_github.png" style="padding-bottom:5px;" />View Source on GitHub</a></td> # <td align="center"><a target="_blank" align="center" href="https://www.youtube.com/watch?v=O5xeyoRL95U&list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf"> # <img src="https://deeplearning.mit.edu/files/images/github/icon_youtube.png" style="padding-bottom:5px;" />Watch YouTube Videos</a></td> # <!-- <td><a target="_blank" href="link"> # <img src="image" />text</a></td> --> # </table> # + [markdown] colab_type="text" id="" # # Deep Learning Basics # # This tutorial accompanies the [lecture on Deep Learning Basics](https://www.youtube.com/watch?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf&v=O5xeyoRL95U) given as part of [MIT Deep Learning](https://deeplearning.mit.edu). Acknowledgement to amazing people involved is provided throughout the tutorial and at the end. You can watch the video on YouTube: # # [![Deep Learning Basics](https://i.imgur.com/FfQVV8q.png)](https://www.youtube.com/watch?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf&v=O5xeyoRL95U) # # In this tutorial, we mention seven important types/concepts/approaches in deep learning, introducing the first 2 and providing pointers to tutorials on the others. Here is a visual representation of the seven: # # ![Deep learning concepts](https://i.imgur.com/EAl47rp.png) # # At a high-level, neural networks are either encoders, decoders, or a combination of both. Encoders find patterns in raw data to form compact, useful representations. Decoders generate new data or high-resolution useful infomation from those representations. As the lecture describes, deep learning discovers ways to **represent** the world so that we can reason about it. The rest is clever methods that help use deal effectively with visual information, language, sound (#1-6) and even act in a world based on this information and occasional rewards (#7). # # 1. **Feed Forward Neural Networks (FFNNs)** - classification and regression based on features. See [Part 1](#Part-1:-Boston-Housing-Price-Prediction-with-Feed-Forward-Neural-Networks) of this tutorial for an example. # 2. **Convolutional Neural Networks (CNNs)** - image classification, object detection, video action recognition, etc. See [Part 2](#Part-2:-Classification-of-MNIST-Dreams-with-Convolution-Neural-Networks) of this tutorial for an example. # 3. **Recurrent Neural Networks (RNNs)** - language modeling, speech recognition/generation, etc. See [this TF tutorial on text generation](https://www.tensorflow.org/tutorials/sequences/text_generation) for an example. # 4. **Encoder Decoder Architectures** - semantic segmentation, machine translation, etc. See [our tutorial on semantic segmentation](https://github.com/lexfridman/mit-deep-learning/blob/master/tutorial_driving_scene_segmentation/tutorial_driving_scene_segmentation.ipynb) for an example. # 5. **Autoencoder** - unsupervised embeddings, denoising, etc. # 6. **Generative Adversarial Networks (GANs)** - unsupervised generation of realistic images, etc. See [this TF tutorial on DCGANs](https://github.com/tensorflow/tensorflow/blob/r1.11/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb) for an example. # 7. **Deep Reinforcement Learning** - game playing, robotics in simulation, self-play, neural arhitecture search, etc. We'll be releasing notebooks on this soon and will link them here. # # There are selective omissions and simplifications throughout these tutorials, hopefully without losing the essence of the underlying ideas. See Einstein quote... # - # ## Part 0: Prerequisites: # # We recommend that you run this this notebook in the cloud on Google Colab (see link with icon at the top) if you're not already doing so. It's the simplest way to get started. You can also [install TensorFlow locally](https://www.tensorflow.org/install/). But, again, simple is best (with caveats): # # ![Einstein](https://i.imgur.com/vfPDHGN.png) # # [tf.keras](https://www.tensorflow.org/guide/keras) is the simplest way to build and train neural network models in TensorFlow. So, that's what we'll stick with in this tutorial, unless the models neccessitate a lower-level API. # # Note that there's [tf.keras](https://www.tensorflow.org/guide/keras) (comes with TensorFlow) and there's [Keras](https://keras.io/) (standalone). You should be using [tf.keras](https://www.tensorflow.org/guide/keras) because (1) it comes with TensorFlow so you don't need to install anything extra and (2) it comes with powerful TensorFlow-specific features. # + id="" colab_type="code" colab={} # %tensorflow_version 1.x # + colab={} colab_type="code" id="" # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense # Commonly used modules import numpy as np import os import sys # Images, plots, display, and visualization import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import cv2 import IPython from six.moves import urllib print(tf.__version__) # - # ## Part 1: Boston Housing Price Prediction with Feed Forward Neural Networks # # Let's start with using a fully-connected neural network to do predict housing prices. The following image highlights the difference between regression and classification (see part 2). Given an observation as input, **regression** outputs a continuous value (e.g., exact temperature) and classificaiton outputs a class/category that the observation belongs to. # # <img src="https://i.imgur.com/vvSoAzg.jpg" alt="classification_regression" width="400"/> # # For the Boston housing dataset, we get 506 rows of data, with 13 features in each. Our task is to build a regression model that takes these 13 features as input and output a single value prediction of the "median value of owner-occupied homes (in $1000)." # # Now, we load the dataset. Loading the dataset returns four NumPy arrays: # # * The `train_images` and `train_labels` arrays are the *training set*—the data the model uses to learn. # * The model is tested against the *test set*, the `test_images`, and `test_labels` arrays. # + (train_features, train_labels), (test_features, test_labels) = keras.datasets.boston_housing.load_data() # get per-feature statistics (mean, standard deviation) from the training set to normalize by train_mean = np.mean(train_features, axis=0) train_std = np.std(train_features, axis=0) train_features = (train_features - train_mean) / train_std # + [markdown] colab_type="text" id="" # ### Build the model # # Building the neural network requires configuring the layers of the model, then compiling the model. First we stack a few layers together using `keras.Sequential`. Next we configure the loss function, optimizer, and metrics to monitor. These are added during the model's compile step: # # * *Loss function* - measures how accurate the model is during training, we want to minimize this with the optimizer. # * *Optimizer* - how the model is updated based on the data it sees and its loss function. # * *Metrics* - used to monitor the training and testing steps. # # Let's build a network with 1 hidden layer of 20 neurons, and use mean squared error (MSE) as the loss function (most common one for regression problems): # + colab={} colab_type="code" id="" def build_model(): model = keras.Sequential([ Dense(20, activation=tf.nn.relu, input_shape=[len(train_features[0])]), Dense(1) ]) model.compile(optimizer=tf.train.AdamOptimizer(), loss='mse', metrics=['mae', 'mse']) return model # + [markdown] colab_type="text" id="" # ### Train the model # # Training the neural network model requires the following steps: # # 1. Feed the training data to the model—in this example, the `train_features` and `train_labels` arrays. # 2. The model learns to associate features and labels. # 3. We ask the model to make predictions about a test set—in this example, the `test_features` array. We verify that the predictions match the labels from the `test_labels` array. # # To start training, call the `model.fit` method—the model is "fit" to the training data: # + colab={} colab_type="code" id="" # this helps makes our output less verbose but still shows progress class PrintDot(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs): if epoch % 100 == 0: print('') print('.', end='') model = build_model() early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=50) history = model.fit(train_features, train_labels, epochs=1000, verbose=0, validation_split = 0.1, callbacks=[early_stop, PrintDot()]) hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch # show RMSE measure to compare to Kaggle leaderboard on https://www.kaggle.com/c/boston-housing/leaderboard rmse_final = np.sqrt(float(hist['val_mean_squared_error'].tail(1))) print() print('Final Root Mean Square Error on validation set: {}'.format(round(rmse_final, 3))) # - # Now, let's plot the loss function measure on the training and validation sets. The validation set is used to prevent overfitting ([learn more about it here](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit)). However, because our network is small, the training convergence without noticeably overfitting the data as the plot shows. # + def plot_history(): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Square Error [Thousand Dollars$^2$]') plt.plot(hist['epoch'], hist['mean_squared_error'], label='Train Error') plt.plot(hist['epoch'], hist['val_mean_squared_error'], label = 'Val Error') plt.legend() plt.ylim([0,50]) plot_history() # + [markdown] colab_type="text" id="" # Next, compare how the model performs on the test dataset: # + colab={} colab_type="code" id="" test_features_norm = (test_features - train_mean) / train_std mse, _, _ = model.evaluate(test_features_norm, test_labels) rmse = np.sqrt(mse) print('Root Mean Square Error on test set: {}'.format(round(rmse, 3))) # + [markdown] colab_type="text" id="" # Compare the RMSE measure you get to the [Kaggle leaderboard](https://www.kaggle.com/c/boston-housing/leaderboard). An RMSE of 2.651 puts us in 5th place. # - # ## Part 2: Classification of MNIST Dreams with Convolutional Neural Networks # # Next, let's build a convolutional neural network (CNN) classifier to classify images of handwritten digits in the MNIST dataset with a twist where we test our classifier on high-resolution hand-written digits from outside the dataset. # Set common constants this_repo_url = 'https://github.com/lexfridman/mit-deep-learning/raw/master/' this_tutorial_url = this_repo_url + 'tutorial_deep_learning_basics' # + [markdown] colab_type="text" id="" # The MNIST dataset containss 70,000 grayscale images of handwritten digits at a resolution of 28 by 28 pixels. The task is to take one of these images as input and predict the most likely digit contained in the image (along with a relative confidence in this prediction): # # <img src="https://i.imgur.com/ITrm9x4.png" width="500px"> # # Now, we load the dataset. The images are 28x28 NumPy arrays, with pixel values ranging between 0 and 255. The *labels* are an array of integers, ranging from 0 to 9. # + colab={} colab_type="code" id="" (train_images, train_labels), (test_images, test_labels) = keras.datasets.mnist.load_data() # reshape images to specify that it's a single channel train_images = train_images.reshape(train_images.shape[0], 28, 28, 1) test_images = test_images.reshape(test_images.shape[0], 28, 28, 1) # + [markdown] colab_type="text" id="" # We scale these values to a range of 0 to 1 before feeding to the neural network model. For this, we divide the values by 255. It's important that the *training set* and the *testing set* are preprocessed in the same way: # + colab={} colab_type="code" id="" def preprocess_images(imgs): # should work for both a single image and multiple images sample_img = imgs if len(imgs.shape) == 2 else imgs[0] assert sample_img.shape in [(28, 28, 1), (28, 28)], sample_img.shape # make sure images are 28x28 and single-channel (grayscale) return imgs / 255.0 train_images = preprocess_images(train_images) test_images = preprocess_images(test_images) # + [markdown] colab_type="text" id="" # Display the first 5 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. # + colab={} colab_type="code" id="" plt.figure(figsize=(10,2)) for i in range(5): plt.subplot(1,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i].reshape(28, 28), cmap=plt.cm.binary) plt.xlabel(train_labels[i]) # + [markdown] colab_type="text" id="" # ### Build the model # # Building the neural network requires configuring the layers of the model, then compiling the model. In many cases, this can be reduced to simply stacking together layers: # + colab={} colab_type="code" id="" model = keras.Sequential() # 32 convolution filters used each of size 3x3 model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1))) # 64 convolution filters used each of size 3x3 model.add(Conv2D(64, (3, 3), activation='relu')) # choose the best features via pooling model.add(MaxPooling2D(pool_size=(2, 2))) # randomly turn neurons on and off to improve convergence model.add(Dropout(0.25)) # flatten since too many dimensions, we only want a classification output model.add(Flatten()) # fully connected to get all relevant data model.add(Dense(128, activation='relu')) # one more dropout model.add(Dropout(0.5)) # output a softmax to squash the matrix into output probabilities model.add(Dense(10, activation='softmax')) # + [markdown] colab_type="text" id="" # Before the model is ready for training, it needs a few more settings. These are added during the model's *compile* step: # # * *Loss function* - measures how accurate the model is during training, we want to minimize this with the optimizer. # * *Optimizer* - how the model is updated based on the data it sees and its loss function. # * *Metrics* - used to monitor the training and testing steps. "accuracy" is the fraction of images that are correctly classified. # + colab={} colab_type="code" id="" model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # + [markdown] colab_type="text" id="" # ### Train the model # # Training the neural network model requires the following steps: # # 1. Feed the training data to the model—in this example, the `train_images` and `train_labels` arrays. # 2. The model learns to associate images and labels. # 3. We ask the model to make predictions about a test set—in this example, the `test_images` array. We verify that the predictions match the labels from the `test_labels` array. # # To start training, call the `model.fit` method—the model is "fit" to the training data: # + colab={} colab_type="code" id="" history = model.fit(train_images, train_labels, epochs=5) # + [markdown] colab_type="text" id="" # As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 98.68% on the training data. # + [markdown] colab_type="text" id="" # ### Evaluate accuracy # # Next, compare how the model performs on the test dataset: # + colab={} colab_type="code" id="" print(test_images.shape) test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) # + [markdown] colab_type="text" id="" # Often times, the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy is an example of *overfitting*. In our case, the accuracy is better at 99.19%! This is, in part, due to successful regularization accomplished with the Dropout layers. # + [markdown] colab_type="text" id="" # ### Make predictions # # With the model trained, we can use it to make predictions about some images. Let's step outside the MNIST dataset for that and go with the beautiful high-resolution images generated by a mixture of CPPN, GAN, VAE. See [great blog post by hardmaru](http://blog.otoro.net/2016/04/01/generating-large-images-from-latent-vectors/) for the source data and a description of how these morphed animations are generated: # # ![MNIST dream](https://i.imgur.com/OrUJs9V.gif) # + colab={} colab_type="code" id="" mnist_dream_path = 'images/mnist_dream.mp4' mnist_prediction_path = 'images/mnist_dream_predicted.mp4' # download the video if running in Colab if not os.path.isfile(mnist_dream_path): print('downloading the sample video...') vid_url = this_tutorial_url + '/' + mnist_dream_path mnist_dream_path = urllib.request.urlretrieve(vid_url)[0] def cv2_imshow(img): ret = cv2.imencode('.png', img)[1].tobytes() img_ip = IPython.display.Image(data=ret) IPython.display.display(img_ip) cap = cv2.VideoCapture(mnist_dream_path) vw = None frame = -1 # counter for debugging (mostly), 0-indexed # go through all the frames and run our classifier on the high res MNIST images as they morph from number to number while True: # should 481 frames frame += 1 ret, img = cap.read() if not ret: break assert img.shape[0] == img.shape[1] # should be a square if img.shape[0] != 720: img = cv2.resize(img, (720, 720)) #preprocess the image for prediction img_proc = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_proc = cv2.resize(img_proc, (28, 28)) img_proc = preprocess_images(img_proc) img_proc = 1 - img_proc # inverse since training dataset is white text with black background net_in = np.expand_dims(img_proc, axis=0) # expand dimension to specify batch size of 1 net_in = np.expand_dims(net_in, axis=3) # expand dimension to specify number of channels preds = model.predict(net_in)[0] guess = np.argmax(preds) perc = np.rint(preds * 100).astype(int) img = 255 - img pad_color = 0 img = np.pad(img, ((0,0), (0,1280-720), (0,0)), mode='constant', constant_values=(pad_color)) line_type = cv2.LINE_AA font_face = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1.3 thickness = 2 x, y = 740, 60 color = (255, 255, 255) text = "Neural Network Output:" cv2.putText(img, text=text, org=(x, y), fontScale=font_scale, fontFace=font_face, thickness=thickness, color=color, lineType=line_type) text = "Input:" cv2.putText(img, text=text, org=(30, y), fontScale=font_scale, fontFace=font_face, thickness=thickness, color=color, lineType=line_type) y = 130 for i, p in enumerate(perc): if i == guess: color = (255, 218, 158) else: color = (100, 100, 100) rect_width = 0 if p > 0: rect_width = int(p * 3.3) rect_start = 180 cv2.rectangle(img, (x+rect_start, y-5), (x+rect_start+rect_width, y-20), color, -1) text = '{}: {:>3}%'.format(i, int(p)) cv2.putText(img, text=text, org=(x, y), fontScale=font_scale, fontFace=font_face, thickness=thickness, color=color, lineType=line_type) y += 60 # if you don't want to save the output as a video, set this to False save_video = True if save_video: if vw is None: codec = cv2.VideoWriter_fourcc(*'DIVX') vid_width_height = img.shape[1], img.shape[0] vw = cv2.VideoWriter(mnist_prediction_path, codec, 30, vid_width_height) # 15 fps above doesn't work robustly so we right frame twice at 30 fps vw.write(img) vw.write(img) # scale down image for display img_disp = cv2.resize(img, (0,0), fx=0.5, fy=0.5) cv2_imshow(img_disp) IPython.display.clear_output(wait=True) cap.release() if vw is not None: vw.release() # + [markdown] colab_type="text" id="" # The above shows the prediction of the network by choosing the neuron with the highest output. While the output layer values add 1 to one, these do not reflect well-calibrated measures of "uncertainty". Often, the network is overly confident about the top choice that does not reflect a learned measure of probability. If everything ran correctly you should get an animation like this: # # ![MNIST dream predictions](https://i.imgur.com/eMF9FOG.gif) # - # ## Acknowledgements # # The contents of this tutorial is based on and inspired by the work of [TensorFlow team](https://www.tensorflow.org) (see their [Colab notebooks](https://www.tensorflow.org/tutorials/)), our [MIT Human-Centered AI team](https://hcai.mit.edu), and individual pieces referenced in the [MIT Deep Learning](https://deeplearning.mit.edu) course slides.
tutorial_deep_learning_basics/deep_learning_basics.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # default_exp special_tokens # %load_ext autoreload # %autoreload 2 # # Special Tokens # # export BOS_TOKEN = '[<PASSWORD>]' EOS_TOKEN = '[<PASSWORD>]' CLS_TOKEN = '[CLS]' SPACE_TOKEN = '[unused1]' UNK_TOKEN = '[UNK]' SPECIAL_TOKENS = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN] TRAIN = 'train' EVAL = 'eval' PREDICT = 'infer' MODAL_LIST = ['image', 'others']
source_nbs/02_special_tokens.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import binascii cipher1 = "<KEY>" cipher2 = "<KEY>" cipher3 = "32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb" cipher4 = "32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa" cipher5 = "3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070" cipher6 = "32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4" cipher7 = "32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce" cipher8 = "315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3" cipher9 = "271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027" cipher10 = "466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83" target = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904" ciphers = [cipher1,cipher2,cipher3,cipher4,cipher5,cipher6,cipher7,cipher8,cipher9, cipher10] ciphers = [binascii.unhexlify(c) for c in ciphers] target = binascii.unhexlify(target) def strxor(a, b): # xor two strings of different lengths return bytes([x ^ y for (x, y) in zip(a, b)]) # - # + keystream = [0] * 150 known_positions = set() for index, cipher in enumerate(ciphers): # Loop over the ciphertexts alphanum_pos = {} for i, cipher2 in enumerate(ciphers): # Loop over the ciphertext again. The goal is to get c1 ^ c2 = m1 ^ m2 if i == index: # Do not xor ciphertexts with themselves continue combined_ciphers = strxor(cipher, cipher2) for msg_i, msg_xor in enumerate(combined_ciphers): # Enumerate over the plaintext xors if chr(msg_xor) not in string.printable: continue if not chr(msg_xor).isalpha(): continue if msg_i not in alphanum_pos: alphanum_pos[msg_i] = 0 else: alphanum_pos[msg_i] += 1 xor_with_spaces = strxor(cipher, [32] * 150) for j, character in enumerate(xor_with_spaces): if j not in alphanum_pos or j >= 150: continue if alphanum_pos[j] < 7: continue keystream[j] = character known_positions.add(j) def show_result(stream): keystream = bytes(stream) print(keystream) print() print("Plaintext") print() message = strxor(keystream, target) print("".join([chr(x) if ind in known_positions else "*" for ind, x in enumerate(message)])) print("\n\n==========Seperator============\n\n") show_result(keystream) secret_message = "The secret message is: When using a stream cipher, never use the key more than once" secret_bytes = bytes([ord(x) for x in secret_message]) key = strxor(secret_bytes, target) print("\n\n==========Seperator============\n\n") print("Actual message:\n {0}".format(secret_message)) print("Actual key:\n {0}".format(key)) print("All the hidden message: \n") [print(strxor(key, cipher)) for cipher in ciphers] # + # -
py/TwoTimePads.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Download this page as a jupyter notebook at [Lesson 0](http://172.16.17.32/engr-1330-webroot/1-Lessons/Lesson00/ENGR-1330-Lesson00.ipynb) # <div class="alert alert-block alert-info"> # <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b> # </div> # # Copyright © 2021 <NAME> and <NAME> # # Last GitHub Commit Date: 13 July 2021 # ## Lesson 0 Introduction to Computational Thinking with Data Science: # - Introduction to Course and Web-enabled content # - Computational thinking concepts # - Data science and practices # - JupyterLab Environment for ENGR 1330 # ## Computational Thinking Concepts # # Computational thinking (CT) refers to the thought processes involved in expressing solutions as computational steps or algorithms that can be carried out by a computer. # # Much of what follows is borrowed from (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2696102/). # # Computational thinking is taking an approach to solving problems, designing systems and understanding human behaviour that draws on concepts fundamental to computing (http://www.cs.cmu.edu/~15110-s13/Wing06-ct.pdf). # # Computational thinking is a kind of analytical thinking: # # - It shares with mathematical thinking in the general ways in which we might approach solving a problem. # - It shares with engineering thinking in the general ways in which we might approach designing and evaluating a large, complex system that operates within the constraints of the real world. - It shares with scientific thinking in the general ways in which we might approach understanding computability, intelligence, the mind and human behaviour. # # The essence of computational thinking is **abstraction** and **automation**. # In computing, we abstract notions beyond the physical dimensions of time and space. Our abstractions are extremely general because they are symbolic, where numeric abstractions are just a special case. # # ### CT Foundations # # CT is literally a process for breaking down a problem into smaller parts, looking for patterns in the problems, identifying what kind of information is needed, developing a step-by-step solution, and implementing that solution. # # 1. Decomposition # 2. Pattern Recognition # 3. Abstraction # 4. Algorithms # 5. System Integration (implementation) # # #### Decomposition # Decomposition is the process of taking a complex problem and breaking it into more manageable sub-problems. Examples include: # - Writing a paper: # - Introduction # - Body # - Conclusion # # - Wide-viewed (Panorama) image: # - Taking multiple overlapped photos # - Stitch them # # Decomposition often leaves a **framework** of sub-problems that later have to be **assembled (system integration)** to produce a desired solution. # # #### Pattern Recognition # Refers to finding similarities, or shared characteristics of problems. Allows a complex problem to become easier to solve. Allows use of same solution method for each occurrence of the pattern. # # Pattern recognition allows use of **automation** to process things - its a fundamental drilled shaft of CT. It also provides a way to use analogs from old problems to address new situations; it also will require **assembly (system integration)** to produce a desired solution. # # #### Abstraction # # Determine important characteristics of the problem and ignore characteristics that are not important. Use these characteristics to create a representation of what we are trying to solve. # # Books in an online bookstore # # |Important| NOT important| # |:--------|:-------------| # |title | Cover color | # |ISBN |Author’s hometown| # |Authors | ... | # |... | ... | # # # #### Algorithms # Step-by-step instructions of how to solve a problem (https://en.wikipedia.org/wiki/Algorithm). # Identifies what is to be done, and the order in which they should be done. # # ![](https://172.16.31.10/engr-1330-webroot/1-Lessons/Lesson00/algorithm.png) # <!-- ![](algorithm.png) --> # # ||Image from https://www.newyorker.com/magazine/2021/01/18/whats-wrong-with-the-way-we-work?utm_source=pocket-newtab|| # |---|------------|---| # # An algorithm is a **finite** sequence of defined, instructions, typically to solve a class of problems or to perform a computation. Algorithms are unambiguous and are used as specifications for performing calculations, data processing, automated reasoning, and other tasks. Starting from an initial state and initial input (perhaps empty), the instructions describe a computation that, when executed, proceeds through a finite number of defined successive states, eventually producing "output" and terminating at a final ending state. The transition from one state to the next is not necessarily deterministic; some algorithms, known as randomized algorithms, can incorporate random input. # # #### System Integration (implementation) # # System integration is the assembly of the parts above into the complete (integrated) solution. Integration combines parts into a program which is the realization of an algorithm using a syntax that the computer can understand. # ## Data Science and Practice # # Data science is leveraging existing data sources, to create new ones as needed in order to extract meaningful information and actionable insights through business domain expertise, effective communication and results interpretation. Data science uses relevant statistical techniques, programming languages, software packages and libraries, and data infrastructure; The insights are used to drive business decisions and take actions intended to achieve business goals. # # Why is this important for engineers? Because engineering is a business! # # A list of typical skills (https://elitedatascience.com/data-science-resources): # # - Foundational Skills # - **Programming and Data Manipulation** # - **Statistics and Probability** # - Technical Skills # - Data Collection # - SQL # - **Data Visualization** # - **Applied Machine Learning** # - Business Skills # - **Communication** # - Creativity and Innovation # - Operations and Strategy # - Business Analytics # - Supplementary Skills # - Natural Language Processing # - Recommendation Systems # - **Time Series Analysis** # - Practice # - **Projects** # - Competitions # - Problem Solving Challenges # # # ## JupyterLab (iPython) Environment # # ### The tools: # **JupyterLab** (https://jupyter.org/) is a web-based interactive development environment for Jupyter notebooks, code, and data. # # **Jupyter Notebook** is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data organizing and transformation, numerical simulation, statistical modeling, visualization, machine learning, and other similar types of uses. # # **JupyterHub** (https://github.com/jupyterhub/jupyterhub) is a multi-user Hub that spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. # # All these tools allow use of various coding languages; Python is the choice for ENGR 1330. Installing JupyterLab on your own computer is relatively straightforward if it is an Intel-based Linux, Macintosh, or Windows machine - simply use Anaconda (https://www.anaconda.com/) as the installer. # # Installing onto an ARM-based machine is more difficult, but possible (this notebook was created on a Raspberry Pi). With both Apple and Microsoft abandoning Intel you can expect Anaconda builds for aarch64 (ARM) in the future. # # ### This course: # # You will create and use Jupyter Notebooks that use the **ipython** kernel, the notebook files will look like `filename.ipynb`; these are ASCII files that the JupyterLab interprets and runs. # ## Python # # The programming language we will use is Python (actually iPython). Python is an example of a high-level language; other high-level languages include C, C++, PHP, FORTRAN, ADA, Pascal, Go, Java, etc (there are a lot). # # As you might infer from the name high-level language, there are also low-level languages, sometimes referred to as machine languages or assembly languages. Machine language is the encoding of instructions in binary so that they can be directly executed by the computer. Assembly language uses a slightly easier format to refer to the low level instructions. Loosely speaking, computers can only execute programs written in low-level languages. To be exact, computers can actually only execute programs written in machine language. Thus, programs written in a high-level language (and even those in assembly language) have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages. However, the advantages to high-level languages are enormous. # # First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another. # # Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications, and for device drivers. # # Two kinds of programs process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. # # ![](https://172.16.31.10/engr-1330-webroot/1-Lessons/Lesson00/interpreter.png) # <!-- ![](interpreter.png) --> # # ||Interpreted Program. Image from (https://runestone.academy/runestone/books/published/thinkcspy/GeneralIntro/ThePythonProgrammingLanguage.html)|| # |---|------------|---| # # A compiler reads the program and translates it completely before the program starts running. In this case, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. # # ![](https://172.16.31.10/engr-1330-webroot/1-Lessons/Lesson00/compiler.png) # <!-- ![](compiler.png) --> # # ||Compiled Program. Image from: (https://runestone.academy/runestone/books/published/thinkcspy/GeneralIntro/ThePythonProgrammingLanguage.html)|| # |---|------------|---| # # Many modern languages use both processes. They are first compiled into a lower level language, called byte code, and then interpreted by a program called a virtual machine. Python uses both processes, but because of the way programmers interact with it, it is usually considered an interpreted language. # # As a language, python is a formal language that has certain requirements and structure called "syntax." # # Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. Programming languages are formal languages that have been designed to express computations. # # Formal languages have strict rules about syntax. For example, 3+3=6 is a syntactically correct mathematical statement, but 3=+6& is not. # # Syntax rules come in two flavors, pertaining to **tokens** and **structure**. **Tokens** are the basic elements of the language, such as words, numbers, and chemical elements. One of the problems with 3=+6& is that & is not a legal token in mathematics (at least as far as we know). # # The second type of syntax rule pertains to the structure of a statement— that is, the way the tokens are arranged. The statement 3=+6& is structurally illegal (in mathematics) because you don’t place a plus sign immediately after an equal sign (of course we will in python!). # # When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is; This process is called **parsing**. # # For example, when you hear the sentence, “The other shoe fell”, you understand that the other shoe is the subject and fell is the verb. Once you have parsed a sentence, you can figure out what it means, or the semantics of the sentence. Assuming that you know what a shoe is and what it means to fall, you will understand the general implication of this sentence. # ## Readings # # Computational and Inferential Thinking <NAME> and <NAME>, Computational and Inferential Thinking, The Foundations of Data Science, Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND) Chapter 1 https://www.inferentialthinking.com/chapters/01/what-is-data-science.html # # Learn Python the Hard Way (Online Book) (https://learnpythonthehardway.org/book/) Recommended for beginners who want a complete course in programming with Python. # # LearnPython.org (Interactive Tutorial) (https://www.learnpython.org/) Short, interactive tutorial for those who just need a quick way to pick up Python syntax. # # How to Think Like a Computer Scientist (Interactive Book) (https://runestone.academy/runestone/books/published/thinkcspy/index.html) Interactive "CS 101" course taught in Python that really focuses on the art of problem solving. # # How to Learn Python for Data Science, The Self-Starter Way (https://elitedatascience.com/learn-python-for-data-science) # # <NAME>, <NAME>, <NAME>, <NAME> (Batu), <NAME>, <NAME>, and <NAME>. (2021) Computational Thinking and Data Science: A WebBook to Accompany ENGR 1330 at TTU, Whitacre College of Engineering, DOI (pending)[http://172.16.17.32/engr-1330-webroot/engr-1330-webbook/ctds-psuedocourse/site/](http://172.16.17.32/engr-1330-webroot/engr-1330-webbook/ctds-psuedocourse/site/)
1-Lessons/Lesson00/ENGR-1330-Lesson00.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + id="H9EU0e8yzFOm" colab_type="code" outputId="c14c62d4-eab7-4cd8-d666-0fba45072b47" executionInfo={"status": "ok", "timestamp": 1573660586513, "user_tz": -330, "elapsed": 1175, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} colab={"base_uri": "https://localhost:8080/", "height": 68} # Credits: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py # %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings("ignore") from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K batch_size = 128 num_classes = 10 epochs = 10 # input image dimensions img_rows, img_cols = 28, 28 # the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) # + id="zpTbV5hmAhli" colab_type="code" colab={} import numpy as np import time # https://gist.github.com/greydanus/f6eee59eaf1d90fcb3b534a25362cea4 # https://stackoverflow.com/a/14434334 # this function is used to update the plots for each epoch and error def plt_dynamic(x, vy, ty, fig, ax, colors=['b']): ax.plot(x, vy, 'b', label="Validation Loss") ax.plot(x, ty, 'r', label="Train Loss") plt.legend() plt.grid() fig.canvas.draw() # + id="niCdh2TUQKce" colab_type="code" colab={} def loss_plot(model_name): score = model_name.evaluate(x_test, y_test, verbose=0) print('Test score:', score[0]) print('Test accuracy:', score[1]) fig, ax = plt.subplots(1,1, figsize=(10,6)) ax.set_xlabel('epoch') ; ax.set_ylabel('Categorical Crossentropy Loss') ax.set_title('Variation of Loss with epochs') # list of epoch numbers x = list(range(1,epochs+1)) # print(history.history.keys()) # dict_keys(['val_loss', 'val_acc', 'loss', 'acc']) # history = model_drop.fit(X_train, Y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_data=(X_test, Y_test)) # we will get val_loss and val_acc only when you pass the paramter validation_data # val_loss : validation loss # val_acc : validation accuracy # loss : training loss # acc : train accuracy # for each key in histrory.histrory we will have a list of length equal to number of epochs vy = history.history['val_loss'] ty = history.history['loss'] plt_dynamic(x, vy, ty, fig, ax) # + id="PDtptoSnQKcf" colab_type="code" colab={} def weight_plot(model_name): w_after = model_name.get_weights() h1_w = w_after[0].flatten().reshape(-1,1) h2_w = w_after[2].flatten().reshape(-1,1) out_w = w_after[4].flatten().reshape(-1,1) fig = plt.figure(figsize=(15,7)) fig.suptitle("Weight matrices after model trained") plt.subplot(1, 3, 1) ax = sns.violinplot(y=h1_w,color='b') plt.xlabel('Hidden Layer 1') plt.subplot(1, 3, 2) ax = sns.violinplot(y=h2_w, color='r') plt.xlabel('Hidden Layer 2 ') plt.subplot(1, 3, 3) ax = sns.violinplot(y=out_w,color='y') plt.xlabel('Output Layer ') plt.show() # + [markdown] id="tt1YCsHCvjpy" colab_type="text" # ## Architecture 1: # no. of Layers = 3; Kernel_size = 3x3 # + id="BR1dCIQhvh0V" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 901} outputId="a0e1208b-60d7-48cd-ced3-0975fdcd4f50" executionInfo={"status": "ok", "timestamp": 1573660926126, "user_tz": -330, "elapsed": 45665, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} model1 = Sequential() #Layer 1 model1.add(Conv2D(48, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) #Layer 2 model1.add(Conv2D(64, (3, 3), activation='relu')) model1.add(MaxPooling2D(pool_size=(2, 2))) model1.add(Dropout(0.5)) #Layer 3 model1.add(Conv2D(50, (3, 3), activation='relu')) model1.add(MaxPooling2D(pool_size=(2, 2))) model1.add(Dropout(0.5)) model1.add(Flatten()) model1.add(Dense(128, activation='relu')) model1.add(Dropout(0.5)) model1.add(Dense(num_classes, activation='softmax')) print(model1.summary()) model1.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) history = model1.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) # + id="cIw5CEKF_1fC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 904} outputId="a34d93a4-052e-487c-e998-b4379a6af659" executionInfo={"status": "ok", "timestamp": 1573660933168, "user_tz": -330, "elapsed": 3296, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} loss_plot(model1) weight_plot(model1) # + [markdown] colab_type="text" id="YVQ18RLgBQD7" # ## Architecture 2: # no. of Layers = 5; Kernel_size = 5x5 # + colab_type="code" outputId="dfd7efbf-a10c-486d-f2ca-f91d394e84b1" executionInfo={"status": "ok", "timestamp": 1573663311228, "user_tz": -330, "elapsed": 74158, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} id="5f8FEpsOBQEA" colab={"base_uri": "https://localhost:8080/", "height": 1000} model2 = Sequential() #Layer 1 model2.add(Conv2D(50, kernel_size=(5, 5), padding='same', activation='relu', input_shape=input_shape)) #Layer 2 model2.add(Conv2D(50, (5, 5), padding='same', activation='relu')) model2.add(MaxPooling2D(pool_size=(2, 2))) model2.add(Dropout(0.5)) #Layer 3 model2.add(Conv2D(60, (5, 5), padding='same', activation='relu')) model2.add(Dropout(0.5)) #Layer 4 model2.add(Conv2D(40, (5, 5), padding='same', activation='relu')) model2.add(MaxPooling2D(pool_size=(3, 3), padding='same')) model2.add(Dropout(0.5)) #Layer 5 model2.add(Conv2D(30, (5, 5), padding='same', activation='relu')) model2.add(Dropout(0.5)) model2.add(Flatten()) model2.add(Dense(128, activation='relu')) model2.add(Dropout(0.5)) model2.add(Dense(num_classes, activation='softmax')) print(model2.summary()) model2.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) history = model2.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) # + colab_type="code" outputId="a07cc832-0de5-4b84-a8fb-df521ea3bd94" executionInfo={"status": "ok", "timestamp": 1573663316844, "user_tz": -330, "elapsed": 2226, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} id="XcLXIugZBQEG" colab={"base_uri": "https://localhost:8080/", "height": 438} loss_plot(model2) # + [markdown] colab_type="text" id="3ii4E_yCwmWL" # ## Architecture 3: # no. of Layers = 7; Kernel_size = 6x6 # # along with Batch Normalization and Dropout layers # + colab_type="code" outputId="9be6bb4e-d3da-408d-e1ec-dbdcbdbc4f56" executionInfo={"status": "ok", "timestamp": 1573663122613, "user_tz": -330, "elapsed": 185845, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} id="dgo7rOmVwmWS" colab={"base_uri": "https://localhost:8080/", "height": 1000} from keras.layers.normalization import BatchNormalization model3 = Sequential() #Layer 1 model3.add(Conv2D(70, kernel_size=(6, 6), padding='same', activation='relu', input_shape=input_shape)) model3.add(BatchNormalization()) #Layer 2 model3.add(Conv2D(80, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(MaxPooling2D(pool_size=(2, 2), padding='same')) model3.add(Dropout(0.5)) #Layer 3 model3.add(Conv2D(60, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(Dropout(0.5)) #Layer 4 model3.add(Conv2D(50, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(MaxPooling2D(pool_size=(2, 2), padding='same')) model3.add(Dropout(0.5)) #Layer 5 model3.add(Conv2D(48, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(Dropout(0.5)) #Layer 6 model3.add(Conv2D(36, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(Dropout(0.5)) #Layer 7 model3.add(Conv2D(24, (6, 6), padding='same', activation='relu')) model3.add(BatchNormalization()) model3.add(MaxPooling2D(pool_size=(2, 2), padding='same')) model3.add(Dropout(0.5)) model3.add(Flatten()) model3.add(Dense(128, activation='relu')) model3.add(Dropout(0.5)) model3.add(Dense(num_classes, activation='softmax')) print(model3.summary()) model3.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) history = model3.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) # + colab_type="code" outputId="d4825cec-664a-4b9b-ed40-93e69b1fb25a" executionInfo={"status": "ok", "timestamp": 1573663131573, "user_tz": -330, "elapsed": 3158, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} id="WvFewspdwmWa" colab={"base_uri": "https://localhost:8080/", "height": 438} loss_plot(model3) # + [markdown] id="lMIlh_Yop1vF" colab_type="text" # ## Summary # + id="q4p6EEQpp0U4" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 187} outputId="660b0c89-60a4-45cf-c6bf-5bd945e612a9" executionInfo={"status": "ok", "timestamp": 1573665183228, "user_tz": -330, "elapsed": 1262, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCor_--txtvi2-PleuyDCIq91JPepRDrHQih0jh=s64", "userId": "01425536422013553450"}} # Please compare all your models using Prettytable library from prettytable import PrettyTable x = PrettyTable() print('\nResults : CNN on MNIST data') print(40*'=') x.field_names = ["Hidden layers", "Kernel size", "Padding", "Max pooling", "epochs", "Train error", "Train accuracey", "Test error", "Test accuracy"] x.add_row([3, '3X3', 'valid', '(2,2)', 10, 0.0623, '98.18 %', 0.0207, '99.35 %']) x.add_row([5, '5X5', 'same', '(2,2)', 10, 0.0511, '98.60 %', 0.0194, '99.40 %']) x.add_row([7, '6X6', 'same', '(2,2)', 10, 0.0326, '99.14 %', 0.0277, '99.45 %']) print(x)
CNN_MNIST.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Geometry tools: example usage # # First, import the relevant packages. The `hyperbolic` package handles the computations in hyperbolic space, while the `drawtools` package provides a bunch of convenient tools for drawing pictures in the hyperbolic plane. from geometry_tools import hyperbolic, drawtools # We create an object to represent a copy of hyperbolic space. Every hyperbolic object we create lives in this copy of H^2. # + plane = hyperbolic.HyperbolicPlane() # this is equivalent to: # plane = hyperbolic.HyperbolicSpace(2) # - # We can do some basic coordinate transformations in the different models. # + point = plane.get_point((0., 0.1), model="klein") point.coords("poincare"), point.coords("halfplane") # + # we can also construct the point directly: point2 = hyperbolic.Point(plane, (0.1, 0.3), model="klein") point2.coords("projective"), point.coords("hyperboloid") # - # ## Using drawtools to draw some points # # This is based around a HyperbolicDrawing object # + # supported drawing models are: Model.KLEIN, Model.POINCARE, and Model.HALFPLANE figure = drawtools.HyperbolicDrawing(model="klein") figure.draw_plane() figure.draw_point(point, color="blue") figure.draw_point(point2, color="red") # + # and now in the poincare model: figure = drawtools.HyperbolicDrawing(model="poincare") figure.draw_plane() figure.draw_point(point, color="blue") figure.draw_point(point2, color="red") # + # and now in the poincare model: figure = drawtools.HyperbolicDrawing(model="halfspace") figure.draw_plane() figure.draw_point(point, color="blue") figure.draw_point(point2, color="red") # - # ## Drawing segments and polygons # # We can build segments and polygons using arrays of points. # + # first pick some points in Klein coordinates p1 = plane.get_point((0.1, 0.8), model="klein") p2 = plane.get_point((-0.6, 0.2), model="klein") p3 = plane.get_point((0., -0.1), model="klein") p4 = plane.get_point((-0.2, -0.3)) p5 = plane.get_point((0.3, -0.4)) # make a triangle and an arc out of these points triangle = hyperbolic.Polygon(plane, [p1, p2, p3]) arc = hyperbolic.Segment(plane, [p4, p5]) # draw using drawtools figure = drawtools.HyperbolicDrawing(model="klein") figure.draw_plane() figure.draw_polygon(triangle, facecolor="lightblue") figure.draw_geodesic(arc, edgecolor="darkred") # - # And now the same figure, in Poincare and halfplane coordinates: # + figure = drawtools.HyperbolicDrawing(model="poincare") figure.draw_plane() figure.draw_polygon(triangle, facecolor="lightblue") figure.draw_geodesic(arc, edgecolor="darkred", linestyle="-") # + figure = drawtools.HyperbolicDrawing(model="halfplane") figure.draw_plane() figure.draw_polygon(triangle, facecolor="lightblue") figure.draw_geodesic(arc, edgecolor="darkred") # - # ## Translating by isometries # # This is the main feature of geometry_tools: the ability to quickly translate around objects in hyperbolic space by an array of many isometries. # # There are a handful of built-in ways to construct isometries, but for starters let's use the action of PSL(2, R). # + lox_param = 2.0 # make a loxodromic isometry iso = plane.sl2r_iso([[lox_param, 0.], [0., 1 / lox_param]]) figure = drawtools.HyperbolicDrawing(model="poincare") figure.draw_plane() # draw 4 copies of the triangle, translated by this isometry figure.draw_polygon(triangle, facecolor="pink") figure.draw_polygon(iso @ triangle, facecolor="pink") figure.draw_polygon(iso.inv() @ triangle, facecolor="pink") figure.draw_polygon(iso @ iso @ triangle, facecolor="pink") # - # ## Translating by free group orbits # # To quickly build a lot of isometries, we can build a representation of a free group, and then translate by the images of group elements up to a given length. # + # first we need pi! import numpy as np pi = np.pi rep = hyperbolic.HyperbolicRepresentation(plane) # we take the free group generated by a loxodromic isometry, # and a conjugate of it with a perpendicular axis param = 3.5 rot = plane.get_standard_rotation(pi / 2) lox = plane.get_standard_loxodromic(param) rep["a"] = lox rep["b"] = rot @ lox @ rot.inv() # + isometries = rep.isometries(rep.free_words_less_than(4)) figure = drawtools.HyperbolicDrawing(model="poincare") figure.draw_plane() figure.draw_polygon(isometries @ triangle, facecolor="limegreen", edgecolor="darkgreen", linewidth=1) # -
examples/geometry_drawing_tools.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %load_ext sparkmagic.magics # %spark add -s my_session -l python -u http://192.168.0.200:8998 spark # %manage_spark # # Pyspark # + magic_args="-s kjh-session" language="spark" # numbers = sc.parallelize([1, 2, 3, 4]) # print('First element of numbers is {} and its description is:\n{}'.format(numbers.first(), numbers.toDebugString())) # - # %spark -s kjh-session logs # # SparkSQL # + magic_args="-s kjh-session" language="spark" # df = spark.read.json("hdfs:///people.json") # df.createOrReplaceTempView("people") # + magic_args="-s kjh-session -c sql" language="spark" # SHOW TABLES # + magic_args="-s kjh-session -c sql -o df_people --maxrows 10" language="spark" # SELECT * FROM people # - df_people.head() from autovizwidget.widget.utils import display_dataframe display_dataframe(df_people) # + magic_args="-s kjh-session" language="spark" # import matplotlib.pyplot as plt # ax = df.toPandas().plot.bar(x='name',y='age') # - import numpy as np import pandas as pd from sklearn import datasets import ipywidgets as widgets from ipywidgets import interact, interact_manual import cufflinks as cf cf.go_offline(connected=True) df = pd.DataFrame(np.random.random([100,3]) * 10) df.columns = ['Feature1','Feature2','Feature3'] df.head() @interact def show_data_more_than(column=['Feature2','Feature3'], x=(0,10,1)): return df.loc[df[column] > x] # !conda install -c conda-forge python-cufflinks -y @interact def scatter_plot(x=list(df.select_dtypes('number').columns), y=list(df.select_dtypes('number').columns), theme=list(cf.themes.THEMES.keys()), colorscale=list(cf.colors._scales_names.keys())): if x.title() == y.title(): print('Can Not Use Same Value') else: title=f'{y.title()} vs {x.title()}' df.iplot(kind='scatter', x=x, y=y, mode='markers', xTitle=x.title(), yTitle=y.title(), #text='title', title=f'{y.title()} vs {x.title()}', theme=theme, colorscale=colorscale) # + magic_args="-s my-scala" language="spark" # val hvacText = sc.parallelize(Array(1, 2, 3, 4)) # hvacText.first() # + magic_args="-s my-scala" language="spark" # val df = spark.read.json("hdfs:///people.json") # df.createOrReplaceTempView("people") # + magic_args="-s my-scala -c sql -o my_df_from_scala --maxrows 10" language="spark" # SELECT * FROM people # - # %manage_spark
lecture_source/big_data/pyspark_01.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Load data files import pandas as pd from sklearn.metrics import * binary = False n_logits = 2 if binary else 3 for data_format in ['token', 'morph']: train_df = pd.read_csv(f'../{data_format}_train.tsv', sep='\t', header=None, names=['comment', 'label']) train_df['is_valid'] = False test_df = pd.read_csv(f'../{data_format}_test.tsv', sep='\t', header=None, names=['comment', 'label']) test_df['is_valid'] = True df = pd.concat([train_df,test_df], sort=False) df = df.drop_duplicates('comment') if binary: df = df[df.label != 2] train_df = df[df.is_valid == False].drop('is_valid', axis=1) test_df = df[df.is_valid == True].drop('is_valid', axis=1) train_df.to_csv(f'../{data_format}_train_clean.tsv', sep='\t', header=None, index=False) test_df.to_csv(f'../{data_format}_test_clean.tsv', sep='\t', header=None, index=False) # + import codecs import re from keras.utils.np_utils import to_categorical import numpy as np import warnings warnings.filterwarnings('ignore') def load_data(filename): data = pd.read_csv(filename, sep='\t', header=None, names=['comment', 'label']) x, y = data.comment, data.label x = np.asarray(list(x)) # Reducing any char-acter sequence of more than 3 consecutive repetitions to a respective 3-character sequence # (e.g. “!!!!!!!!”turns to “!!!”) # x = [re.sub(r'((.)\2{3,})', r'\2\2\2', i) for i in x] y = to_categorical(y, n_logits) return x, y version = '_clean' x_token_train, y_token_train = load_data(f'../token_train{version}.tsv') x_token_test, y_token_test = load_data(f'../token_test{version}.tsv') x_morph_train, y_morph_train = load_data(f'../morph_train{version}.tsv') x_morph_test, y_morph_test = load_data(f'../morph_test{version}.tsv') print('X token train shape: {}'.format(x_token_train.shape)) print('X token test shape: {}'.format(x_token_test.shape)) print('X morph train shape: {}'.format(x_morph_train.shape)) print('X morph test shape: {}'.format(x_morph_test.shape)) # - print(x_token_train[:5]) print(x_token_test[:5]) print(x_morph_train[:5]) print(x_morph_test[:5]) # ## Prepare # Convert text (train & test) to sequences and pad to requested document length # + from keras.preprocessing import text, sequence def tokenizer(x_train, x_test, vocabulary_size, char_level): tokenize = text.Tokenizer(num_words=vocabulary_size, char_level=char_level, filters='', oov_token='UNK') tokenize.fit_on_texts(x_train) # only fit on train print('UNK index: {}'.format(tokenize.word_index['UNK'])) x_train = tokenize.texts_to_sequences(x_train) x_test = tokenize.texts_to_sequences(x_test) return x_train, x_test def pad(x_train, x_test, max_document_length): x_train = sequence.pad_sequences(x_train, maxlen=max_document_length, padding='post', truncating='post') x_test = sequence.pad_sequences(x_test, maxlen=max_document_length, padding='post', truncating='post') return x_train, x_test vocabulary_size = 5000 x_token_train, x_token_test = tokenizer(x_token_train, x_token_test, vocabulary_size, False) x_morph_train, x_morph_test = tokenizer(x_morph_train, x_morph_test, vocabulary_size, False) max_document_length = 100 x_token_train, x_token_test = pad(x_token_train, x_token_test, max_document_length) x_morph_train, x_morph_test = pad(x_morph_train, x_morph_test, max_document_length) print('X token train shape: {}'.format(x_token_train.shape)) print('X token test shape: {}'.format(x_token_test.shape)) print('X morph train shape: {}'.format(x_morph_train.shape)) print('X morph test shape: {}'.format(x_morph_test.shape)) # - # ## Plot function # + import matplotlib.pyplot as plt def plot_loss_and_accuracy(history): fig, axs = plt.subplots(1, 2, sharex=True) axs[0].plot(history.history['loss']) axs[0].plot(history.history['val_loss']) axs[0].set_title('Model Loss') axs[0].legend(['Train', 'Validation'], loc='upper left') axs[1].plot(history.history['accuracy']) axs[1].plot(history.history['val_accuracy']) axs[1].set_title('Model Accuracy') axs[1].legend(['Train', 'Validation'], loc='upper left') fig.tight_layout() plt.show() # - # ## Import required modules from Keras from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Activation, Flatten, Input, Concatenate from keras.layers import Embedding from keras.layers import LSTM, Bidirectional from keras.layers.convolutional import Conv1D from keras.layers.pooling import MaxPool1D from keras.layers import BatchNormalization from keras import optimizers from keras import metrics from keras import backend as K # ## Default Parameters dropout_keep_prob = 0.5 embedding_size = 300 batch_size = 50 lr = 1e-4 dev_size = 0.2 loss = 'categorical_crossentropy' # ## Linear - Token # + num_epochs = 10 # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Dense(100)(text_input) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss=loss, optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_token_train, y_token_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_token_test, y_token_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.4f}'.format(scores[1])) # Save the model #model.save('word_saved_models/Linear-Token-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_token_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_token_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## Linear - Morph # + # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Dense(100)(text_input) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss=loss, optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_morph_train, y_morph_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_morph_test, y_morph_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.4f}'.format(scores[1])) # Save the model # model.save('word_saved_models/Linear-Morph-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_morph_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_morph_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## CNN - Token # + num_epochs = 5 # Create new TF graph K.clear_session() # Construct model convs = [] text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) for fsz in [3, 8]: conv = Conv1D(128, fsz, padding='valid', activation='relu')(x) pool = MaxPool1D()(conv) convs.append(pool) x = Concatenate(axis=1)(convs) x = Flatten()(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss=loss, optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_token_train, y_token_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_token_test, y_token_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/CNN-Token-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_token_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_token_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## CNN - Morph # + # Create new TF graph K.clear_session() # Construct model convs = [] text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) for fsz in [3, 8]: conv = Conv1D(128, fsz, padding='valid', activation='relu')(x) pool = MaxPool1D()(conv) convs.append(pool) x = Concatenate(axis=1)(convs) x = Flatten()(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_morph_train, y_morph_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_morph_test, y_morph_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.4f}'.format(scores[1])) # Save the model # model.save('word_saved_models/CNN-Morph-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_morph_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_morph_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## LSTM - Token # + num_epochs = 7 lstm_units = 93 # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = LSTM(units=lstm_units, return_sequences=True)(x) x = LSTM(units=lstm_units)(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_token_train, y_token_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_token_test, y_token_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/LSTM-Token-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_token_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_token_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## LSTM - Morph # + num_epochs = 7 # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = LSTM(units=lstm_units, return_sequences=True)(x) x = LSTM(units=lstm_units)(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_morph_train, y_morph_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_morph_test, y_morph_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/LSTM-Morph-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_morph_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_morph_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## BiLSTM - Token # + num_epochs = 3 # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = Bidirectional(LSTM(units=lstm_units, return_sequences=True))(x) x = Bidirectional(LSTM(units=lstm_units))(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_token_train, y_token_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_token_test, y_token_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/BiLSTM-Token-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_token_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_token_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## BiLSTM - Morph # + # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = Bidirectional(LSTM(units=lstm_units, return_sequences=True))(x) x = Bidirectional(LSTM(units=lstm_units))(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_morph_train, y_morph_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_morph_test, y_morph_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/BiLSTM-Morph-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_morph_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_morph_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## MLP - Token # + num_epochs = 6 # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = Flatten()(x) x = Dense(256, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) x = Dense(64, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_token_train, y_token_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_token_test, y_token_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/MLP-Token-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_token_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_token_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds) # ## MLP - Morph # + # Create new TF graph K.clear_session() # Construct model text_input = Input(shape=(max_document_length,)) x = Embedding(vocabulary_size, embedding_size)(text_input) x = Flatten()(x) x = Dense(256, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) x = Dense(128, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) x = Dense(64, activation='relu')(x) x = Dropout(dropout_keep_prob)(x) preds = Dense(n_logits, activation='softmax')(x) model = Model(text_input, preds) adam = optimizers.Adam(lr=lr) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # Train the model history = model.fit(x_morph_train, y_morph_train, batch_size=batch_size, epochs=num_epochs, verbose=1, validation_split=dev_size) # Plot training accuracy and loss plot_loss_and_accuracy(history) # Evaluate the model scores = model.evaluate(x_morph_test, y_morph_test, batch_size=batch_size, verbose=1) print('\nAccurancy: {:.3f}'.format(scores[1])) # Save the model # model.save('word_saved_models/MLP-Morph-{:.3f}.h5'.format((scores[1] * 100))) # - preds = model.predict(x_morph_test, batch_size=batch_size, verbose=1) preds = preds.argmax(1) ys = y_morph_test.argmax(1) accuracy_score(ys, preds), f1_score(ys, preds, average='macro'), matthews_corrcoef(ys, preds)
replication/replication_word-based_dedup.ipynb
# # 6 Decorators # ### 6.1 Decorators Simplified # Conceptually a decorator changes or adds to the functionality of a # function either by modifying its arguments before the function is # called, or changing its return values afterwards, or both. def add(first, second): return first + second # add(2, 3) # Let's look at a simple example of a function that returns another function. def create_adder(first): def adder(second): return add(first, second) return adder add_to_2 = create_adder(2) add_to_2(3) # Next let's look at a function that receives a function as an argument. def trace_function(f): """Add tracing before and after a function""" def new_f(*args): """The new function""" print( 'Called {}({!r})' .format(f, *args)) result = f(*args) print('Returning', result) return result return new_f # This `trace_function` wraps the functionality of whatever existing # function is passed to it by returning a new function which calls the # original function, but prints some trace information before and # after. traced_add = trace_function(add) traced_add(2, 3) # We could instead reassign the original name. add = trace_function(add) add(2, 3) # Or we can use the decorator syntax to do that for us: @trace_function def add(first, second): """Return the sum of two arguments.""" return first + second add(2, 3) # add add.__qualname__ add.__doc__ # Use `@wraps` to update the metadata of the returned function and make it more useful. import functools def trace_function(f): """Add tracing before and after a function""" @functools.wraps(f) # <-- Added def new_f(*args): """The new function""" print( 'Called {}({!r})' .format(f, *args)) result = f(*args) print('Returning', result) return result return new_f # @trace_function def add(first, second): """Return the sum of two arguments.""" return first + second add add.__qualname__ add.__doc__ # To write a decorator that takes parameters, just write a function that returns a decorator. def better_trace_function(uppercase=False): def trace_function(f): """Add tracing before and after a function""" @functools.wraps(f) # <-- Added def new_f(*args): """The new function""" print( 'Called {}({!r})' .format(f, *args)) result = f(*args) print('Returning', result) if uppercase: # Two new return result.upper() # lines return result return new_f return trace_function # @better_trace_function(uppercase=False) def concat(s, t): return s + t concat('spam', 'eggs') # @better_trace_function(uppercase=True) def concat(s, t): return s + t concat('spam', 'eggs') # Here's another common example of the utility of # decorators. *Memoization* is "an optimization technique... storing # the results of expensive function calls and returning the cached # result when the same inputs occur again." -- # https://en.wikipedia.org/wiki/Memoization def memoize(f): print('Called memoize({!r})'.format(f)) cache = {} @functools.wraps(f) def memoized_f(*args): print('Called memoized_f({!r})'.format(args)) if args in cache: print('Cache hit!') return cache[args] if args not in cache: result = f(*args) cache[args] = result return result return memoized_f # @memoize def add(first, second): """Return the sum of two arguments.""" return first + second add(2, 3) add(4, 5) add(2, 3) # Note that this not a full treatment of decorators, only an # introduction, and primarily from the perspective of how they # intervene in the namespace operation of function definition. For # example it leaves out entirely how to handle decorators that take # more than one argument. # ### 6.2 Exercises: Decorators # A decorator is a function that takes a function as an argument # and *typically* returns a new function, but it can return anything. # The following code misuses decorators to help you focus on their # mechanics, which are really quite simple. del x def return_spam(f): print('Called return_spam({!r})'.format(f)) return 'spam' def x(): pass x x = return_spam(x) # What object will `x` be bound to now? x # Now try this `@decorator` syntax: @return_spam def x(): pass x
speakers/Stuart Williams/PyCon-2016-Python-Epiphanies/Python-Epiphanies-06-6-Decorators.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <h1 style="font-size:42px; text-align:center; margin-bottom:30px;"><span style="color:SteelBlue">Module 4:</span> The Big Picture</h1> # <hr> # Welcome to the **Companion Workbook** for <span style="color:royalblue">Module 4: The Big Picture</span>. # # # ### Instructions # # As you go through the online lessons, follow along here to run the lesson code for yourself. We recommend reading the lesson first, then completing its accompanying section in the workbook. # # While there are no exercises in this module, we strongly recommend recreating the lesson code and playing around with it. # # <br><hr id="toc"> # # ### Table of Contents # # 1. [Model complexity](#complexity) # * [Toy example: noisy sine wave](#sine) # * [Mean model](#mean) # * [Linear regression](#linear) # * [Polynomial linear regression](#polynomial) # * [Decision trees](#tree) # # **Tip:** Each section builds on the previous ones. # # <br><hr> # <br> # ### First, let's import the libraries we'll need. # # Before we do anything else, let's import the <code style="color:steelblue">print()</code> function from the future to ensure our code is compatible with Python 3. from __future__ import print_function # Compatability with Python 3 print( 'Print function ready to serve.' ) # Next, let's import Pandas and NumPy. import numpy as np import pandas as pd # Finally, let's import our **data visualization** libraries. # * <code style="color:steelblue">matplotlib</code> is a flexible and powerful tool for visualizing data. # * From it, we import the <code style="color:steelblue">pyplot</code> submodule and give it the alias <code style="color:steelblue">plt</code>. # * <code style="color:steelblue">%matplotlib inline</code> tells Jupyter Notebook to plot the charts inside this notebook directly. # * <code style="color:steelblue">seaborn</code> provides convenient wrappers on top of matplotlib. It also provides nice styles and themes for our charts. # * We give it the alias <code style="color:steelblue">sns</code> # + from matplotlib import pyplot as plt # %matplotlib inline import seaborn as sns # - # This is the first time we'll use these libraries, so this module will also be a gentle introduction to plotting. # <br id="complexity"> # # 1. Model complexity # # No code to run. # <br id="sine"> # # 2. - Toy example: noisy sine wave # # For the rest of this module, we're going to switch over to a toy example. # * Remember, the relevant code is all included in the online lesson. # First, create the dataset for the noisy sine wave: # + # input feature x = np.linspace(0, 2*np.pi, 100) # noise np.random.seed(321) noise = np.random.normal(0, .5, 100) # target variable y = np.sin(x) + noise # - # For convenience, let's throw $x$ and $y$ into a Pandas DataFrame. # Create DataFrame with x and y df = pd.DataFrame({'x' : x, 'y': y}) df.head() # Before moving on, let's plot that dataset first. # + # Scatterplot of x and y plt.scatter(df.x, df.y) # Overlay the sine wave plt.plot(df.x, np.sin(df.x), color='k') # - # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div> # <br id="mean"> # # 3 - Mean model # # Now it's time to start building some models. Let's start with a **very simple** model. # Build the mean model with 1 line of code. # Build model p = np.mean(df.y) # Print the prediction, for any value of x. # Display predictions for any value of x p # Let's see how that model "fits" the training data. # * First, we will use <code style="color:steelblue">plt.scatter()</code> again to plot the dataset. # * Then, we will use <code style="color:steelblue">plt.plot()</code> again, but this time print the predictions from our <span style="color:royalblue;">mean model</span> as a dotted black line. # + # Scatterplot of x and y plt.scatter(df.x, df.y) # Overlay horizontal line for the prediction plt.plot(df.x, [p]*len(df.x), 'k--') # - # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div> # <br id="linear"> # # 4. Linear regression # # Next, let's introduce linear regression. # First, let's import <code style="color:steelblue">LinearRegression</code> from Scikit-Learn. # * Scikit-Learn comes with implementations of many popular model types. # * We'll explore many of them throughout the course. # Import LinearRegression from Scikit-Learn from sklearn.linear_model import LinearRegression # Next, let's build a linear model for our example dataset. # + # Initialize instance of linear regression linmod = LinearRegression() # Separate our input features and target variable feat = df.drop('y', axis=1) target = df.y # Fit model to the data linmod.fit(feat, target) # - # Let's display the intercept ($\beta_0$) and coefficient ($\beta_1$) that were estimated from the dataset. # Print intercept and coefficient print( linmod.intercept_ ) print( linmod.coef_ ) # Finally, let's plot that line. # * Note that we are passing in the predicted values of $y$, or <code style="color:steelblue">lm.predict(features)</code>, as the second argument into <code style="color:steelblue">plt.plot()</code>. # + # Plot original points plt.scatter(df.x, df.y) # Plot predicted values of y plt.plot(df.x, linmod.predict(feat), 'k--') # - # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div> # <br id="polynomial"> # # 5 - Polynomial linear regression # # Next, we'll take a look at polynomial linear regression. # Let's quickly write a couple helper functions that will make building these models easier. # # First, we'll write a <code style="color:steelblue">fit_and_plot_fitted_model()</code> function that performs exactly what we did for the <span style="color:royalblue">linear regression</span> earlier, except for any model and any set of features. # * Splits input features from target variable # * Fits the model # * Plots the dataset # * Overlays the predicted values for $y$ # + # fit_and_plot_model helper function def fit_and_plot_model(df, model): features = df.drop('y', axis=1) target = df.y model.fit(features, target) plt.scatter(df.x, df.y) plt.plot(df.x, model.predict(features), 'k--') # - # Then, we'll write a <code style="color:steelblue">fit_polynomial_model()</code> function that creates powers of $x$ up to a maximum polynomial (a.k.a. the "order" of the model). # * If the "order" is 1, then we'll just fit and plot the model directly. # * If the "order" is greater than 1, then we'll create the polynomial terms: $x^2$, $x^3$, etc. # fit_and_plot_polynomial_model function def fit_and_plot_polynomial_model(df, model, max_polynomial=1): df_copy = df.copy() # If max_polynomial is 1, then just fit the model directly if max_polynomial == 1: fit_and_plot_model(df_copy, model) # Else create polynomial terms for x else: for power in range(2, max_polynomial + 1): df_copy[f'x{power}'] = np.power(x, power) fit_and_plot_model(df_copy, model) # Now, let's fit and plot the <span style="color:royalblue">second-order polynomial linear regression using our helper functions: # Fit and plot 2nd-order polynomial linear regression fit_and_plot_polynomial_model(df, LinearRegression(), 2) # Let's fit and plot a <span style="color:royalblue">third-order polynomial linear regression</span>: # Fit and plot 3rd-order polynomial linear regression fit_and_plot_polynomial_model(df, LinearRegression(), 3) # Now, just to illustrate a point, let's fit and plot a <span style="color:royalblue">10th-order polynomial linear regression</span>: # Fit and plot 10th-order polynomial linear regression fit_and_plot_polynomial_model(df, LinearRegression(), 10) # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div> # <br id="tree"> # # 6. Decision trees # # Just for fun, let's see what happens when you crank model complexity way up. # First, let's import <code style="color:steelblue">DecisionTreeRegressor</code> from Scikit-Learn. # Import DecisionTreeRegressor from sklearn.tree import DecisionTreeRegressor # Next, we can use our helper function, <code style="color:steelblue">fit_and_plot_model()</code>, to fit and plot an **unconstrained** decision tree: # fit and plot unconstrained decision tree fit_and_plot_model(df, DecisionTreeRegressor()) # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div> # <br> # ## Next Steps # # First, a huge congrats on finishing the first project! # # # Here are a few of things you did in this final module: # * You learned about one of the most important concepts in machine learning: model complexity. # * You generated an artificial dataset from a noisy sine wave. # * You fit and plotted mean, linear regression, polynomial linear, and decision tree models. # * And you compared their results against the "true underlying relationship" in the artificial dataset. # # In the next project, <span style="color:royalblue">Project 2: Real-Estate Tycoon</span>, we will dive deeper into these concepts, plus many others. You will get to practice the entire **machine learning workflow** from end to end! # # <div style="text-align:center; margin: 40px 0 40px 0;"> # [**Back to Contents**](#toc) # </div>
Project 1 Workbook Bundle/Module 4 - The Big Picture.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] hideCode=false hidePrompt=false # ## Twitter Sentiment Analysis # # # * Data Source: https://www.kaggle.com/kazanova/sentiment140 # # This is the sentiment140 dataset. It contains 1,600,000 tweets extracted using the twitter api . The tweets have been annotated (0 = negative, 4 = positive) and they can be used to detect sentiment. # # Content # # * It contains the following 6 fields: # # * target: the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive) # * ids: The id of the tweet ( 2087) # * date: the date of the tweet (Sat May 16 23:58:44 UTC 2009) # * flag: The query (lyx). If there is no query, then this value is NO_QUERY. # * user: the user that tweeted (robotickilldozr) # * text: the text of the tweet (Lyx is cool) # # # #### Imports # # * The main python packages that are used are: # * `NLTK` and regular expresions for input text manipulations # * Classifiers and metrics for evaluation from `Sklearn` # * `Pandas` and `Matplotlib` to depict results # * `Keras` as a neural-network library # + hideCode=false hidePrompt=false import numpy as np import pandas as pd from collections import Counter import nltk nltk.download('stopwords') nltk.download('wordnet') from nltk.corpus import stopwords import re from nltk.stem import WordNetLemmatizer stemmer = WordNetLemmatizer() from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # %matplotlib inline # + hideCode=false hidePrompt=false # Load data file = "training.1600000.processed.noemoticon.csv" cols = ['target','id','date','flag','user','text'] df = pd.read_csv(file,encoding = "ISO-8859-1",header=None, names=cols) # 0 for positive / 1 for negative df['target'] = (df['target']==4).astype(int) y = np.array(df.target) X = list(df.text) # + hideCode=false hidePrompt=false # Count the number of entities in each category target_cnt = Counter(df.target) plt.figure(figsize=(6,4)) plt.bar(target_cnt.keys(), target_cnt.values(),tick_label =('Negative', 'Positive'),color=['r','g']) plt.title("Dataset labels distribuition") plt.show() # + [markdown] hideCode=false hidePrompt=false # * From the above plot it can be seen that the dataset is balanced. We have 800,000 positive and and negative tweets. # # Each tweet has the following format: # + hideCode=false hidePrompt=false df.text[45] # + [markdown] hideCode=false hidePrompt=false # #### Preprocessing # # * We will remove from each tweet special characters, single characters, multiple spaces and prefixed letters and prefix such as '@nickname'. # * Everything will be converted to Lowercase. # * Using the WordNet Lemmatizer we will keep the stem of each word (only for words in the WordNet). # + hideCode=false hidePrompt=false tweets = [] for i in range(len(X)): tweet = re.sub(r"@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+", ' ', str(X[i])) # remove all single characters tweet = re.sub(r'\s+[a-zA-Z]\s+', ' ', tweet) # Substituting multiple spaces with single space tweet = re.sub(r'\s+', ' ', tweet, flags=re.I) # Converting to Lowercase tweet = tweet.lower() # Lemmatization tweet = tweet.split() tweet = [stemmer.lemmatize(word) for word in tweet] tweet = ' '.join(tweet) tweets.append(tweet) # + [markdown] hideCode=false hidePrompt=false # After preprocessing the above tweet is transformed into: # + hideCode=false hidePrompt=false tweets[45] # + [markdown] hideCode=false hidePrompt=false # #### Split dataset into train (70%) & development(10%) & test (30%) # # * Due to the large number of available data (1,600,000) we will do our analysis in a random 10% sample, in order to speed up computations. (Use of all the data did not impove the accuracy of the classifier) # + hideCode=false hidePrompt=false X_train, X_test, y_train, y_test = train_test_split(tweets, y, test_size=0.3, random_state=23828748) # keep only the 20% X_train,X_dev, X_test, y_train,y_dev, y_test = X_train[:160000],X_test[:32000], X_test[32000:96000], y_train[:160000], y_test[:32000],y_test[32000:96000] # + [markdown] hideCode=false hidePrompt=false # #### Feature extraction (Tf*IDF n-gram features) # # * In order to perform the classification (positive/negative) among the tweets, we represent them as `bags of words/ngrams`. # * We build features using the TF*IDF score of single words and bigrams. # # * TF: how frequent each vocabulary word is in the given tweet. # * IDF: how rare each word of an tweet is in the language. # # * Each tweet is transformed in a TF*IDF vector with length same as the number of the features. Thus, most values of this vector will be 0, as only a few of all the features will be present in a given tweet. # # * After removing the stop-words, we extract as features the 10000 words/bigrams with the highest frequency across the corpus. # + hideCode=false hidePrompt=false #Use unigram & bi-gram tf*idf features vectorizer = TfidfVectorizer(max_features=10000,stop_words=stopwords.words('english')) x_train = vectorizer.fit_transform(X_train) x_dev = vectorizer.transform(X_dev) x_test = vectorizer.transform(X_test) # + [markdown] hideCode=false hidePrompt=false # #### Define evaluation metrics # + hideCode=false hidePrompt=false def recall(y_true, y_pred): """ Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): """ Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. Source ------ https://github.com/fchollet/keras/issues/5400#issuecomment-314747992 """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1(y_true, y_pred): """Calculate the F1 score.""" p = precision(y_true, y_pred) r = recall(y_true, y_pred) return 2 * ((p * r) / (p + r)) def accuracy(y_true, y_pred): return K.mean(K.equal(y_true, K.round(y_pred)), axis=1) # + [markdown] hideCode=false hidePrompt=false # ### MLP classifier in Keras using tf*idf features # + hideCode=false hidePrompt=false # !pip install keras-tqdm # + hideCode=false hidePrompt=false # to run tensorflow on mac import os os.environ['KMP_DUPLICATE_LIB_OK']='True' # + hideCode=false hidePrompt=false import warnings import sklearn.exceptions warnings.filterwarnings("ignore", category=sklearn.exceptions.UndefinedMetricWarning) warnings.simplefilter(action='ignore', category=FutureWarning) from keras.callbacks import ModelCheckpoint,EarlyStopping from keras_tqdm import TQDMNotebookCallback from keras.models import Sequential from keras.layers.core import Dense, Dropout from keras.optimizers import Adam from keras import backend as K model = Sequential() model.add(Dense(64, input_dim=x_train.shape[1] , activation='relu')) model.add(Dropout(0.3)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.3)) model.add(Dense(1, activation='sigmoid')) print(model.summary()) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001), metrics=[precision, recall, f1, accuracy]) checkpoint = ModelCheckpoint('keras_tf_idf_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max') earlystopping=EarlyStopping(monitor='val_f1', patience=2, verbose=1) history = model.fit(x_train, y_train, batch_size=32, epochs=3, verbose = 0, callbacks=[checkpoint,earlystopping,TQDMNotebookCallback()], validation_data=(x_dev, y_dev), shuffle=True) # + [markdown] hideCode=false hidePrompt=false # ## Visualize Model Training History # + hideCode=false hidePrompt=false clf = SGDClassifier(loss="log", penalty="l2", tol=0.0001) clf.fit(x_train, y_train) predictions = clf.predict(x_train) score = f1_score(y_train,predictions) print("Train f1-score: %.2f%%"%(score*100)) predictions_test = clf.predict(x_test) score = f1_score(y_test, predictions_test) print("Test f1-score: %.2f%%"%(score*100)) print() print("Test data confusion matrix") y_true = pd.Series(y_test, name='True') y_pred = pd.Series(predictions_test, name='Predicted') pd.crosstab(y_true, y_pred) # + hideCode=false hidePrompt=false # summarize history for f1 plt.plot(history.history['f1']) plt.plot(history.history['val_f1']) plt.title('model f1') plt.ylabel('f1-score') plt.xlabel('epoch') plt.legend(['train', 'dev'], loc='upper left') plt.show() # summarize history for loss plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'dev'], loc='upper right') plt.show() # + [markdown] hideCode=false hidePrompt=false # * From the above results it can be seen that our model learns the weights of the network very quickly, resulting to overfitting after the 2nd epoch. # # ## Evaluate performance of tf-idf MLP model # + hideCode=false hidePrompt=false model = Sequential() model.add(Dense(64, input_dim=x_train.shape[1] , activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(1, activation='sigmoid')) #load weights from the pre-trained model model.load_weights("keras_tf_idf_model") model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001), metrics=[precision, recall, f1, accuracy]) score = model.evaluate( x_test, y_test, batch_size=32, verbose=1) print('\nTest Binary_cross_entropy: %.4f' % (score[0])) print('\nTest precision: %.4f' % (score[1])) print('\nTest recall: %.4f' % (score[2])) print('\nTest f1: %.4f' % (score[3])) print('\nTest accuracy: %.4f'% (score[4])) # + hideCode=false hidePrompt=false predictions = model.predict(x_test) predictions = predictions.reshape(len(predictions),) for i in range(len(predictions)): if predictions[i]<0.5: predictions[i]=0 else: predictions[i]=1 y_true = pd.Series(y_test, name='True') y_pred = pd.Series(predictions, name='Predicted') pd.crosstab(y_true, y_pred) # + [markdown] hideCode=false hidePrompt=false # ### Types of mistakes that MLP classifier makes. # + hideCode=false hidePrompt=false for i in range(40): if y_true[i]!= y_pred[i]: print("Preprocessed Tweet:",X_test[i] ) print("Predicted probability:",model.predict(x_test[i])) print("------------------------------------------------") # + [markdown] hideCode=false hidePrompt=false # ### Hyperparameter fine-tuning # # * We fine-tune only a fews parameters of the MLP classifier due to lack of computational resources. Those parameters are: # * layers = [2, 3] # * nodes = [64, 128, 256] # * dropout = 0.3 # * epochs = 4 # + hideCode=false hidePrompt=false nodes = [64, 128, 256] dropout = 0.3 epochs = 4 history_list1 = [] history_list2 = [] for node1 in nodes: for node2 in nodes: if node1>=node2: model = Sequential() model.add(Dense(node1, input_dim=x_train.shape[1] , activation='relu')) model.add(Dropout(dropout)) model.add(Dense(node2, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(1, activation='sigmoid')) print(model.summary()) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001), metrics=[precision, recall, f1, accuracy]) checkpoint = ModelCheckpoint('keras_tf_idf_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max') earlystopping=EarlyStopping(monitor='val_f1', patience=2, verbose=1) history = model.fit(x_train, y_train, batch_size=32, epochs=epochs, verbose = 0, callbacks=[checkpoint,earlystopping,TQDMNotebookCallback()], validation_data=(x_dev, y_dev), shuffle=True) history_list1.append([node1, node2, history.history['val_f1']]) for node1 in nodes: for node2 in nodes: for node3 in nodes: if node1>=node2 and node2>=node3: model = Sequential() model.add(Dense(node1, input_dim=x_train.shape[1] , activation='relu')) model.add(Dropout(dropout)) model.add(Dense(node2, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(node3, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(1, activation='sigmoid')) print(model.summary()) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.001), metrics=[precision, recall, f1, accuracy]) checkpoint = ModelCheckpoint('keras_tf_idf_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max') history = model.fit(x_train, y_train, batch_size=32, epochs=epochs, verbose = 0, callbacks=[checkpoint,TQDMNotebookCallback()], validation_data=(x_dev, y_dev), shuffle=True) history_list2.append([node1, node2, node3, history.history['val_f1']]) # + [markdown] hideCode=false hidePrompt=false # ### Visualize Tuning Results # + hideCode=false hidePrompt=false legends = [] plt.figure(figsize=(6,5)) for i in range(len(history_list1)): plt.plot(np.arange(1,epochs+1), history_list1[i][2]) legends.append('node1: ' + str(history_list1[i][0]) + ', node2: ' + str(history_list1[i][1])) plt.title('Evaluation f1-scores for 2-layer MLP') plt.ylabel('f1-score') plt.xlabel('epoch') plt.ylim(bottom=0.73) plt.legend(legends) plt.show() legends = [] plt.figure(figsize=(6,6)) for i in range(len(history_list2)): plt.plot(np.arange(1,epochs+1), history_list2[i][3]) legends.append('node1: ' + str(history_list2[i][0]) + ', node2: ' + str(history_list2[i][1]) + ', node3: ' + str(history_list2[i][2])) plt.title('Evaluation f1-scores for 3-layer MLP') plt.ylabel('f1-score') plt.xlabel('epoch') plt.ylim(bottom=0.72) plt.legend(legends) plt.show() # + [markdown] hideCode=false hidePrompt=false # * We see that the best results (F1-Score:77.30%) are obtained for a 3-layer percepton with 256 nodes per layer and dropout=0.3 trained for 2 epochs. # # ## Compare MLP Models's results with the must simpler and quicker SGDClassifier # # # + hideCode=false hidePrompt=false from sklearn.linear_model import SGDClassifier from sklearn.metrics import f1_score clf = SGDClassifier(loss="log", penalty="l2", tol=0.0001) clf.fit(x_train, y_train) predictions = clf.predict(x_train) score = f1_score(y_train,predictions) print("SGD Classifier") print('---------------') print("Train f1-score: %.2f%%"%(score*100)) predictions = clf.predict(x_dev) score = f1_score(y_dev, predictions) print("Development f1-score: %.2f%%"%(score*100)) print() print("Developmen data confusion matrix") y_true = pd.Series(y_dev, name='True') y_pred = pd.Series(predictions, name='Predicted') pd.crosstab(y_true, y_pred) # + [markdown] hideCode=false hidePrompt=false # * It can be seen that the NN performs shlitly better (1.13%) than the SGD Classifier. This means that may be better to use a simpler model for this classification task. # -
Twitter-Sentiment-Analysis.ipynb
// -*- coding: utf-8 -*- // --- // jupyter: // jupytext: // text_representation: // extension: .cs // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: .NET (C#) // language: C# // name: .net-csharp // --- // + [markdown] dotnet_interactive={"language": "csharp"} // # .Net Reflections and MetaProgramming Quickly Beginning // // - The basic principles of object-oriented programming (OOP) are understood by // most software developers these days. For example, you probably understand how // encapsulation and implementation-hiding can increase the cohesion of classes. // Languages like C# and Visual Basic are excellent for creating so-called coarsely // // > Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Attributes. // // ![](PICS/WHICHONEYOUGONNAUSE.png) // // - We recognize simplicity when we see it. Our challenge as programmers is in // seeing the opportunities for simplicity in the systems we develop. Language features // like encapsulation, abstraction, inheritance, data-hiding, and polymorphism are great, // but they only take you part of the way there // // - Seems like I in SOLID // // - "MetaProgram" = “a computer program that writes new computer programs.” // // - This sounds a lot like the definition of a compiler. A compiler for a // programming language like C# could be thought of as the ultimate metaprogram, // because its only job is to produce other programs from source code. // // - In the near future, that will be changing with the release of Microsoft’s Roslyn (code name) tools. Roslyn opens the black // box of the C# and VB compilers to make them available before, during, and after the // deployment of your applications. When that happens, we expect to see Microsoft’s // compilers used in many metaprogramming scenarios. // // - Each time you see the word metaprogramming in this // book, try to think of it as after-programming or beside-programming. The // Greek prefix meta allows for both of those definitions to be correct. // + dotnet_interactive={"language": "csharp"} vscode={"languageId": "dotnet-interactive.csharp"} foreach (var ci in System.CodeDom.Compiler.CodeDomProvider.GetAllCompilerInfo()) { foreach (string language in ci.GetLanguages()) System.Console.Write("{0} ", language); System.Console.WriteLine(); } // + dotnet_interactive={"language": "csharp"} vscode={"languageId": "dotnet-interactive.csharp"} using System; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; partial class HelloWorldCodeDOM { public static void GenerateCode() { CodeNamespace prgNamespace = BuildProgram(); var compilerOptions = new CodeGeneratorOptions() { IndentString = " ", BracingStyle = "C", BlankLinesBetweenMembers = false }; var codeText = new StringBuilder(); using (var codeWriter = new StringWriter(codeText)) { CodeDomProvider.CreateProvider("c#") .GenerateCodeFromNamespace( prgNamespace, codeWriter, compilerOptions); } var script = codeText.ToString(); Console.WriteLine(script); } public static CodeNamespace BuildProgram() { var ns = new CodeNamespace("MetaWorld"); var systemImport = new CodeNamespaceImport("System"); ns.Imports.Add(systemImport); var programClass = new CodeTypeDeclaration("Program"); ns.Types.Add(programClass); var methodMain = new CodeMemberMethod { Attributes = MemberAttributes.Static , Name = "Main" }; methodMain.Statements.Add( new CodeMethodInvokeExpression( new CodeSnippetExpression("Console") , "WriteLine" , new CodePrimitiveExpression("Hello, world!") ) ); programClass.Members.Add(methodMain); return ns; } } HelloWorldCodeDOM.GenerateCode(); // + dotnet_interactive={"language": "csharp"} vscode={"languageId": "dotnet-interactive.csharp"} // - // // // // + dotnet_interactive={"language": "csharp"} vscode={"languageId": "dotnet-interactive.csharp"} // - //
Module 16 C#/Reflections/Reflections.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="vkdnLiKk71g-" # ##### Copyright 2021 The TensorFlow Authors. # + cellView="form" id="0asMuNro71hA" #@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. # + [markdown] id="iPFgLeZIsZ3Q" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/federated/tutorials/federated_select"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/federated/blob/main/docs/tutorials/federated_select.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/federated/blob/main/docs/tutorials/federated_select.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/federated/docs/tutorials/federated_select.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> # </td> # </table> # + [markdown] id="T94owwmP-41H" # # Sending Different Data To Particular Clients With tff.federated_select # + [markdown] id="2K2GBCD2G6P8" # This tutorial demonstrates how to implement custom federated algorithms in TFF that require sending different data to different clients. You may already be familiar with `tff.federated_broadcast` which sends a single server-placed value to all clients. This tutorial focuses on cases where different parts of a server-based value are sent to different clients. This may be useful for dividing up parts of a model across different clients in order to avoid sending the whole model to any single client. # # Let's get started by importing both `tensorflow` and `tensorflow_federated`. # + id="9LcC1AwjoqfR" #@test {"skip": true} # !pip install --quiet --upgrade tensorflow-federated-nightly # !pip install --quiet --upgrade nest-asyncio import nest_asyncio nest_asyncio.apply() # + id="YVyimqc7qHCn" import tensorflow as tf import tensorflow_federated as tff # + [markdown] id="v35NnHqL_Zci" # ## Sending Different Values Based On Client Data # + [markdown] id="S169M4-qH9Y9" # Consider the case where we have some server-placed list from which we want to send a few elements to each client based on some client-placed data. For example, a list of strings on the server, and on the clients, a comma-separated list of indices to download. We can implement that as follows: # + id="Rc_XhL7h_vQC" list_of_strings_type = tff.TensorType(tf.string, [None]) # We only ever send exactly two values to each client. The number of keys per # client must be a fixed number across all clients. number_of_keys_per_client = 2 keys_type = tff.TensorType(tf.int32, [number_of_keys_per_client]) get_size = tff.tf_computation(lambda x: tf.size(x)) select_fn = tff.tf_computation(lambda val, index: tf.gather(val, index)) client_data_type = tf.string # A function from our client data to the indices of the values we'd like to # select from the server. @tff.tf_computation(client_data_type) @tff.check_returns_type(keys_type) def keys_for_client(client_string): # We assume our client data is a single string consisting of exactly three # comma-separated integers indicating which values to grab from the server. split = tf.strings.split([client_string], sep=',')[0] return tf.strings.to_number([split[0], split[1]], tf.int32) @tff.tf_computation(tff.SequenceType(tf.string)) @tff.check_returns_type(tf.string) def concatenate(values): def reduce_fn(acc, item): return tf.cond(tf.math.equal(acc, ''), lambda: item, lambda: tf.strings.join([acc, item], ',')) return values.reduce('', reduce_fn) @tff.federated_computation(tff.type_at_server(list_of_strings_type), tff.type_at_clients(client_data_type)) def broadcast_based_on_client_data(list_of_strings_at_server, client_data): keys_at_clients = tff.federated_map(keys_for_client, client_data) max_key = tff.federated_map(get_size, list_of_strings_at_server) values_at_clients = tff.federated_select(keys_at_clients, max_key, list_of_strings_at_server, select_fn) value_at_clients = tff.federated_map(concatenate, values_at_clients) return value_at_clients # + [markdown] id="QpdKyL77JKea" # Then we can simulate our computation by providing the server-placed list of strings as well as string data for each client: # + id="aneU54u0F6al" client_data = ['0,1', '1,2', '2,0'] broadcast_based_on_client_data(['a', 'b', 'c'], client_data) # + [markdown] id="TeLPCh8z_BJJ" # ## Sending A Randomized Element To Each Client # + [markdown] id="ADjD0poWJkIj" # Alternatively, it may be useful to send a random portion of the server data to each client. We can implement that by first generating a random key on each client and then following a similar selection process to the one used above: # + id="texCnO6Erds4" @tff.tf_computation(tf.int32) @tff.check_returns_type(tff.TensorType(tf.int32, [1])) def get_random_key(max_key): return tf.random.uniform(shape=[1], minval=0, maxval=max_key, dtype=tf.int32) list_of_strings_type = tff.TensorType(tf.string, [None]) get_size = tff.tf_computation(lambda x: tf.size(x)) select_fn = tff.tf_computation(lambda val, index: tf.gather(val, index)) @tff.tf_computation(tff.SequenceType(tf.string)) @tff.check_returns_type(tf.string) def get_last_element(sequence): return sequence.reduce('', lambda _initial_state, val: val) @tff.federated_computation(tff.type_at_server(list_of_strings_type)) def broadcast_random_element(list_of_strings_at_server): max_key_at_server = tff.federated_map(get_size, list_of_strings_at_server) max_key_at_clients = tff.federated_broadcast(max_key_at_server) key_at_clients = tff.federated_map(get_random_key, max_key_at_clients) random_string_sequence_at_clients = tff.federated_select( key_at_clients, max_key_at_server, list_of_strings_at_server, select_fn) # Even though we only passed in a single key, `federated_select` returns a # sequence for each client. We only care about the last (and only) element. random_string_at_clients = tff.federated_map(get_last_element, random_string_sequence_at_clients) return random_string_at_clients # + [markdown] id="eCgbnWznJxVq" # Since our `broadcast_random_element` function doesn't take in any client-placed data, we have to configure the TFF Simulation Runtime with a default number of clients to use: # + id="N70yh3i6vYoy" tff.backends.native.set_local_python_execution_context(default_num_clients=3) # + [markdown] id="TF1OttS2J9b4" # Then we can simulate the selection. We can change `default_num_clients` above and the list of strings below to generate different results, or simply re-run the computation to generate different random outputs. # + id="lowrkwE09mIe" broadcast_random_element(tf.convert_to_tensor(['foo', 'bar', 'baz']))
docs/tutorials/federated_select.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import exmp import os.path import qiime2 import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from qiime2.plugins.diversity.actions import filter_distance_matrix from qiime2.plugins.longitudinal.actions import first_distances import scipy.stats from statsmodels.stats.multitest import multipletests # + def microbiome_performance_correlations(project, time_column, baseline_time_value, performance_metrics, week, sample_metadata, data_dir, output_dir, gender=None): results = [] uu = ("unweighted UniFrac", os.path.join(data_dir, "unweighted_unifrac_distance_matrix.qza")) wu = ("weighted UniFrac", os.path.join(data_dir, "weighted_unifrac_distance_matrix.qza")) bc = ("Bray-Curtis", os.path.join(data_dir, "bray_curtis_distance_matrix.qza")) bj = ("Jaccard", os.path.join(data_dir, "jaccard_distance_matrix.qza")) where = "[project]='%s' and [exclude]='no'" % project if gender is not None: where = "%s and [gender]='%s'" % (where, gender) else: gender = 'mf' ids_to_keep = sample_metadata.get_ids(where=where) sample_metadata = sample_metadata.filter_ids(ids_to_keep=ids_to_keep) metadata_to_merge = [] distance_columns = [] for metric, dm_fp in [uu, wu, bc, bj]: dm = qiime2.Artifact.load(dm_fp) dm = filter_distance_matrix(dm, metadata=sample_metadata).filtered_distance_matrix # add distances to baseline to sample metadata dists_to_baselines = first_distances(distance_matrix=dm, metadata=sample_metadata, state_column=time_column, individual_id_column='subject-id', baseline=baseline_time_value, replicate_handling='random').first_distances dists_to_baselines = dists_to_baselines.view(qiime2.Metadata).get_column('Distance').to_dataframe() column_name = '%s distance (%s %d to %s)' % (metric, time_column, baseline_time_value, week) dists_to_baselines = dists_to_baselines.rename(columns = {'Distance' : column_name}) metadata_to_merge.append(qiime2.Metadata(dists_to_baselines)) distance_columns.append(column_name) for e in metadata_to_merge: sample_metadata = sample_metadata.merge(e) data = sample_metadata.to_dataframe() for distance_column in distance_columns: for performance_metric in performance_metrics: where = "[%s]='%s'" % (time_column, week) ids_to_keep = sample_metadata.get_ids(where=where) sample_metadata_subsample = sample_metadata.filter_ids(ids_to_keep=ids_to_keep).to_dataframe() sample_metadata_subsample = sample_metadata_subsample[[distance_column, performance_metric]].dropna().astype(np.float) tau, p = scipy.stats.kendalltau(sample_metadata_subsample[[distance_column, performance_metric]]) results.append((project, distance_column, performance_metric, tau, p, sample_metadata_subsample.shape[0])) fig_fn = '%s-%s-%s-%s.pdf' % (project, distance_column, performance_metric, gender) fig_fp = '%s/%s' % (output_dir, fig_fn) sns.scatterplot(sample_metadata_subsample[distance_column], sample_metadata_subsample[performance_metric]).get_figure().savefig(fig_fp) plt.clf() df = pd.DataFrame(results, columns=['project', 'distance', 'performance metric', 'Spearman rho', 'p-value', 'sample size']) df['q-value'] = multipletests(df['p-value'])[1] output_fn = '%s-%s-%s.csv' % (project, week, gender) df.to_csv('%s/%s' % (output_dir, output_fn)) return df # + output_dir = '../data/exmp1-and-exmp2/cm/microbiome-performance-correlations/' df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir) df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir) df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir) df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir) df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='m') df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='m') df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='m') df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='m') df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='f') df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '5.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='f') df_exmp1 = microbiome_performance_correlations( 'exmp1', 'week', 1.0, ['RER-change', 'VO2max-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='f') df_exmp2 = microbiome_performance_correlations( 'exmp2', 'week', 1.0, ['bench-press-change', 'row-change', '3RM-squat-change'], '6.0', exmp.load_sample_metadata(), exmp.cm_path, output_dir, gender='f') # -
code/microbiome-change-exercise-change-correlation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np import re df=pd.read_csv("../input/folds/train_folds_score_5.csv") df.head(5) # - np.mean(df.comment_text.str.len()) def pre_process_text(text): emoticons = [':-)', ':)', '(:', '(-:', ':))', '((:', ':-D', ':D', 'X-D', 'XD', 'xD', 'xD', '<3', '</3', ':\*', ';-)', ';)', ';-D', ';D', '(;', '(-;', ':-(', ':(', '(:', '(-:', ':,(', ':\'(', ':"(', ':((', ':D', '=D', '=)', '(=', '=(', ')=', '=-O', 'O-=', ':o', 'o:', 'O:', 'O:', ':-o', 'o-:', ':P', ':p', ':S', ':s', ':@', ':>', ':<', '^_^', '^.^', '>.>', 'T_T', 'T-T', '-.-', '*.*', '~.~', ':*', ':-*', 'xP', 'XP', 'XP', 'Xp', ':-|', ':->', ':-<', '$_$', '8-)', ':-P', ':-p', '=P', '=p', ':*)', '*-*', 'B-)', 'O.o', 'X-(', ')-X'] text = text.replace(".", " ").lower() text = re.sub(r"[^a-zA-Z?.!,¿]+", " ", text) users = re.findall("[@]\w+", text) for user in users: text = text.replace(user, "<user>") urls = re.findall(r'(https?://[^\s]+)', text) if len(urls) != 0: for url in urls: text = text.replace(url, "<url >") for emo in text: if emo in emoji.UNICODE_EMOJI: text = text.replace(emo, "<emoticon >") for emo in emoticons: text = text.replace(emo, "<emoticon >") numbers = re.findall('[0-9]+', text) for number in numbers: text = text.replace(number, "<number >") text = text.replace('#', "<hashtag >") text = re.sub(r"([?.!,¿])", r" ", text) text = "".join(l for l in text if l not in string.punctuation) text = re.sub(r'[" "]+', " ", text) return text # + from spacy.lang.en import English #tokenization tok=English() def tokenize(text): return [token.text for token in tok.tokenizer(pre_process_text(text))] # - from collections import Counter import emoji, string counts = Counter() for index, row in df.iterrows(): counts.update(tokenize(row['comment_text'])) #deleting infrequent words print("num_words before:",len(counts.keys())) for word in list(counts): if counts[word] < 2: del counts[word] print("num_words after:",len(counts.keys())) import json vocab2index = {"":0, "UNK":1} words = ["", "UNK"] for word in counts: vocab2index[word] = len(words) words.append(word) with open('../input/vocab2index.txt', 'w') as convert_file: convert_file.write(json.dumps(vocab2index)) def encode_sentence(text, vocab2index, N=70): tokenized = tokenize(text) encoded = np.zeros(N, dtype=int) enc1 = np.array([vocab2index.get(word, vocab2index["UNK"]) for word in tokenized]) length = min(N, len(enc1)) encoded[:length] = enc1[:length] return encoded, length df['encoded'] = df['comment_text'].apply(lambda x: np.array(encode_sentence(x,vocab2index ))) df.head() df=df[['encoded','y','kfold']] df.to_csv("../input/folds/train_folds_score_5.csv") df.head() print(len(words)) import torch torch.from_numpy(df.loc[0]['encoded'][0].astype(np.int32)) def pre_process_text(text,vocab2index): emoticons = [':-)', ':)', '(:', '(-:', ':))', '((:', ':-D', ':D', 'X-D', 'XD', 'xD', 'xD', '<3', '</3', ':\*', ';-)', ';)', ';-D', ';D', '(;', '(-;', ':-(', ':(', '(:', '(-:', ':,(', ':\'(', ':"(', ':((', ':D', '=D', '=)', '(=', '=(', ')=', '=-O', 'O-=', ':o', 'o:', 'O:', 'O:', ':-o', 'o-:', ':P', ':p', ':S', ':s', ':@', ':>', ':<', '^_^', '^.^', '>.>', 'T_T', 'T-T', '-.-', '*.*', '~.~', ':*', ':-*', 'xP', 'XP', 'XP', 'Xp', ':-|', ':->', ':-<', '$_$', '8-)', ':-P', ':-p', '=P', '=p', ':*)', '*-*', 'B-)', 'O.o', 'X-(', ')-X'] text = text.replace(".", " ").lower() text = re.sub(r"[^a-zA-Z?.!,¿]+", " ", text) users = re.findall("[@]\w+", text) for user in users: text = text.replace(user, "<user>") urls = re.findall(r'(https?://[^\s]+)', text) if len(urls) != 0: for url in urls: text = text.replace(url, "<url >") for emo in text: if emo in emoji.UNICODE_EMOJI: text = text.replace(emo, "<emoticon >") for emo in emoticons: text = text.replace(emo, "<emoticon >") numbers = re.findall('[0-9]+', text) for number in numbers: text = text.replace(number, "<number >") text = text.replace('#', "<hashtag >") text = re.sub(r"([?.!,¿])", r" ", text) text = "".join(l for l in text if l not in string.punctuation) text = re.sub(r'[" "]+', " ", text) tok=English() def tokenize(text): return [token.text for token in tok.tokenizer(text)] N=70 tokenized = tokenize(text) encoded = np.zeros(N, dtype=int) enc1 = np.array([vocab2index.get(word, vocab2index["UNK"]) for word in tokenized]) length = min(N, len(enc1)) encoded[:length] = enc1[:length] return " ".join(encoded) import ast df = pd.read_csv("../input/folds/train_folds_score_5.csv") file = open("../input/vocab2index.txt", "r") contents = file.read() vocab2index = ast.literal_eval(contents) df['encoded'] = df['comment_text'].apply(lambda x: pre_process_text(x,vocab2index)) df.head()
src/.ipynb_checkpoints/Untitled1-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### Scenario # Alice is competing in Kaggle's Titanic competitions. Following the advice from an internet article, she tried heavy feature engineering and a simple classifying model. However, she found that the model did not perform as well as what the original article claimed. She wondered what went wrong, but couldn't find the problem despite much effort. **Could you help her find problems in her notebook and improve the model's performance?** # # ### Instruction # + You are free to use the Internet to search for any problems you might encounter. # + You overall goal is to improve the model's performance, but you might prioritize finding the underlying problems in the notebook. # # + # %matplotlib inline import warnings warnings.filterwarnings('ignore') warnings.filterwarnings('ignore', category=DeprecationWarning) import pandas as pd pd.options.display.max_columns = 100 from matplotlib import pyplot as plt import numpy as np # - # # II - Feature engineering # first, let's define a print function that asserts whether or not a feature has been processed. def status(feature): print('Processing', feature, ': ok') # ### Loading the data # # One trick when starting a machine learning problem is to append the training set to the test set together. # # We'll engineer new features using the train set to prevent information leakage. Then we'll add these variables to the test set. # # Let's load the train and test sets and append them together. # + # reading train data train = pd.read_csv('./data/train.csv') train_len = len(train) # reading test data test = pd.read_csv('./data/test.csv') # extracting and then removing the targets from the training data targets = train.Survived train.drop(['Survived'], 1, inplace=True) # merging train data and test data for future feature engineering # we'll also remove the PassengerID since this is not an informative feature combined = train.append(test) combined.reset_index(inplace=True) combined.drop(['index', 'PassengerId'], inplace=True, axis=1) # - # ### Processing Title # This function parses the names and extract the titles. Then, it maps the titles to categories of titles. titles = set() for name in combined['Name']: titles.add(name.split(',')[1].split('.')[0].strip()) # + Title_Dictionary = { "Capt": "Officer", "Col": "Officer", "Major": "Officer", "Jonkheer": "Royalty", "Don": "Royalty", "Sir" : "Royalty", "Dr": "Officer", "Rev": "Officer", "the Countess":"Royalty", "Mme": "Mrs", "Mlle": "Miss", "Ms": "Mrs", "Mr" : "Mr", "Mrs" : "Mrs", "Miss" : "Miss", "Master" : "Master", "Lady" : "Royalty" } # we extract the title from each name combined['Title'] = combined['Name'].map(lambda name:name.split('.')[0].strip()) # a map of more aggregated title # we map each title combined['Title'] = combined.Title.map(Title_Dictionary) status('Title') # - # some names not in dict are mapped to "Royalty" combined[combined['Title'].isnull()] combined.at[combined['Title'].isnull(), "Title"] = "Royalty" # ### Processing Ages # Let's create a function that fills in the missing age in combined based on these different attributes. grouped_train = combined.iloc[:train_len].groupby(['Sex','Pclass','Title']) grouped_median_train = grouped_train.median() grouped_median_train = grouped_median_train.reset_index()[['Sex', 'Pclass', 'Title', 'Age']] # + def fill_age(row): condition = ( (grouped_median_train['Sex'] == row['Sex']) & (grouped_median_train['Title'] == row['Title']) & (grouped_median_train['Pclass'] == row['Pclass']) ) return grouped_median_train[condition]['Age'].values[0] combined['Age'] = combined.apply(lambda row: fill_age(row), axis=1) status('age') # - # Let's now process the names. # + # we clean the Name variable combined.drop('Name', axis=1, inplace=True) # encoding in dummy variable titles_dummies = pd.get_dummies(combined['Title'], prefix='Title') combined = pd.concat([combined, titles_dummies], axis=1) # removing the title variable combined.drop('Title', axis=1, inplace=True) status('names') # - # ### Processing Fare # there's one missing fare value - replacing it with the mean. combined.Fare.fillna(combined.iloc[:train_len].Fare.mean(), inplace=True) status('fare') # ### Processing Embarked # two missing embarked values - filling them with the most frequent one in the train set(S) combined.Embarked.fillna('S', inplace=True) # dummy encoding embarked_dummies = pd.get_dummies(combined['Embarked'], prefix='Embarked') combined = pd.concat([combined, embarked_dummies], axis=1) combined.drop('Embarked', axis=1, inplace=True) status('embarked') combined.Cabin # ### Processing Cabin # + # replacing missing cabins with U (for Uknown) combined.Cabin.fillna('U', inplace=True) # mapping each Cabin value with the cabin letter combined['Cabin'] = combined['Cabin'].map(lambda c: c[0]) # dummy encoding ... cabin_dummies = pd.get_dummies(combined['Cabin'], prefix='Cabin') combined = pd.concat([combined, cabin_dummies], axis=1) combined.drop('Cabin', axis=1, inplace=True) status('cabin') # - # This function replaces NaN values with U (for <i>Unknow</i>). It then maps each Cabin value to the first letter. # Then it encodes the cabin values using dummy encoding again. # ### Processing Sex # mapping string values to numerical one combined['Sex'] = combined['Sex'].map({'male':1, 'female':0}) status('Sex') # This function maps the string values male and female to 1 and 0 respectively. # ### Processing Pclass # + # encoding into 3 categories: pclass_dummies = pd.get_dummies(combined['Pclass'], prefix="Pclass") # adding dummy variable combined = pd.concat([combined, pclass_dummies],axis=1) # removing "Pclass" combined.drop('Pclass',axis=1,inplace=True) status('Pclass') # - # This function encodes the values of Pclass (1,2,3) using a dummy encoding. # ### Processing Ticket # + # a function that extracts each prefix of the ticket, returns 'XXX' if no prefix (i.e the ticket is a digit) def cleanTicket(ticket): ticket = ticket.replace('.','') ticket = ticket.replace('/','') ticket = ticket.split() ticket = map(lambda t : t.strip(), ticket) ticket = list(filter(lambda t : not t.isdigit(), ticket)) if len(ticket) > 0: return ticket[0] else: return 'XXX' # Extracting dummy variables from tickets: combined['Ticket'] = combined['Ticket'].map(cleanTicket) tickets_dummies = pd.get_dummies(combined['Ticket'], prefix='Ticket') combined = pd.concat([combined, tickets_dummies], axis=1) combined.drop('Ticket', inplace=True, axis=1) status('Ticket') # - # ### Processing Family # + # introducing a new feature : the size of families (including the passenger) combined['FamilySize'] = combined['Parch'] + combined['SibSp'] + 1 # introducing other features based on the family size combined['Singleton'] = combined['FamilySize'].map(lambda s: 1 if s == 1 else 0) combined['SmallFamily'] = combined['FamilySize'].map(lambda s: 1 if 2 <= s <= 4 else 0) combined['LargeFamily'] = combined['FamilySize'].map(lambda s: 1 if 5 <= s else 0) status('family') # - # # III - Modeling from sklearn.pipeline import make_pipeline from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble.gradient_boosting import GradientBoostingClassifier from sklearn.feature_selection import SelectKBest from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_score from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LogisticRegression, LogisticRegressionCV def compute_score(clf, X, y, scoring='accuracy'): xval = cross_val_score(clf, X, y, cv = 5, scoring=scoring) return np.mean(xval) # Recovering the train set and the test set from the combined dataset is an easy task. targets = pd.read_csv('./data/train.csv', usecols=['Survived'])['Survived'].values train = combined.iloc[:train_len] test = combined.iloc[train_len:] # ## Feature selection clf = RandomForestClassifier(n_estimators=50, max_features='sqrt') clf = clf.fit(train, targets) # + features = pd.DataFrame() features['feature'] = train.columns features['importance'] = clf.feature_importances_ features.sort_values(by=['importance'], ascending=True, inplace=True) features.set_index('feature', inplace=True) features.plot(kind='barh', figsize=(25, 25)) # - model = SelectFromModel(clf, prefit=True) train_reduced = model.transform(train) test_reduced = model.transform(test) # ### Let's try a simple model model = RandomForestClassifier() print('Cross-validation of : {0}'.format(model.__class__)) score = compute_score(clf=model, X=train_reduced, y=targets, scoring='accuracy') print('CV score = {0}'.format(score))
debug_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # #Lesson 3 # # This lesson will review **linear equations**, briefly discuss **kinematics** and see how we can write **functions** in python to reuse code. # ##Linear Equations # # Recall the definition of a line is $y(x) = mx + c$. Where $m$ is the **slope** of the line and $c$ is the **y-intercept**. See if you can find the equation of the line below. # # <img src="ygraph.png" alt="Drawing" style="width: 300px;"/> # # The slope of the line is $2$ and the y-intercept is $4$, so the equation is $y(x) = 2x+4$. If we are told that a line goes through two points $(x_1, y_1)$ and $(x_2,y_2)$, we can also find the equation of the line. We know that since the slope is defined as **rise over run**: $m = \frac{y_2-y_1}{x_2-x_1}$. Now that we have found the slope of the line, how can we find the y-interccept? The line goes through $(x_1, y_1)$ so $y_1 = m*x_1 + c$ and hence $c = y_1-m*x_1$. Alternatively, we also know that the line goes through $(x_2, y_2)$ so $y_2 = m*x_2 + c$ and $c = y_2 - m*x_2$. Now we have found both $m$ and $c$ so we know the equation of the line! # # Example Problems # 1. What is the slope of the line that goes through the points $(1,2)$ and $(3,4)$? # 2. What is the y-intercept of the line that goes through $(1,2)$ and $(3,4)$? # 3. What is the equation of the line that goes through the points $(1,2)$ and $(3,4)$? # #Basic Kinematics # # **Kinematics** is defined as the study of motion and one branch of it looks at the relationships between **position**, **speed**, and **time**. # # The position of an object is where it is **relative** to an origin at a specific moment in time. If your school is two miles away from home, then at this moment your position, relative to your home, is two miles. When you leave school and decide to go home, your position will slowly decrease as you walk home until it reaches zero miles. # # The speed of an object is how fast it is moving at a specific moment in time. If you walk from your house to school in one hour, then your speed would have been two **miles per hour**. If, instead, you decided to bike from home to school and it only took you half an hour, your speed would have been four **miles per hour**. # # If you decide to skip school (please don't) to go the new arcade four miles away from your house, it will take you twice as long because you have to travel twice the distance. If you decide to walk there, it will take you two **hours** and if you bike there, it will take you one **hour**. # # In general we have the following relationship $position = speed \times time$ or $p(t) = st$. But wait, doesn't this look really similar to our linear equation above? $p(t) = st + 0$ and $y(x) = mx + c$. Its just a linear line with a y-intercept of zero! The same properties hold as well. Since $s$ is the "slope" of this graph, we can calculate $s$ by taking the **rise over run** of the graph or **the change in position divided by the change in time**. The time it takes to travel from one one position to another is the **change in position divided by the speed**. # # The equations are summarized below. $\Delta$ is the shorthand notation for "change in". # 1. $p(t) = st$ # 2. $s = \frac{\Delta p}{\Delta t}$ # 3. $t = \frac{\Delta p}{\Delta s}$ # Suppose your friend lives four miles away from school, but in the opposite direction. If he walks just as quickly as you, how long will it take him to get home? # # <img src="school.png" alt="Drawing" style="width: 750px;"/> # # Because he lives four miles away and walks at two miles per hour, it will take him $\frac{4}{2} = 2$ hours. This is one hour after you arrive at your home (it takes you one hour to get home by foot). We define this as the **time difference of arrival**. However, if you lived four miles away and your friend lived two miles away, he would have gotten home one hour _before_ you have, and the time difference of arrival would be negative (-1 hours). Notice that the time difference of arrival is also how much more distance your friend has to travel over his speed. # # # **Problem** # # What would be the time difference of arrival if you lived 3 miles away from school and your friend also lived 3 miles away from school? # #Functions in Python # # In programming, a function refers to a procedure that does something for you! Much like how in mathematics a function takes in an "input" and returns an "output" after performing some operations on the inputs. # Below is a function that returns the double of an input; def double(x): return(2*x); # Look at some sample outputs below print double(1); print double(2); print double(3); # We can define a function in python by the **def** keyword, followed by the name of the function, a set of parenthesis with its inputs or **paramaters** and a **:**. The code that modifies our inputs is in the lines that follow. It has the general format of # ```python # def name(parameters): # code; # ``` # Look at our definition of double again and notice that we **return** the value $2x$. We then print out double(1) which prints out the return value $2 \times 1$. However, it is not required for a function to return anything! A function is still valid even it doesn't explicitly return anything. An example is shown below. def print_double(x): print(2*x); # Whenever we call print_double, we ask the function to print $2x$ so we don't have to. print_double(1); print_double(2); print_double(3); # A function can also have multiple parameters, or no parameters at all. Remember, the parameters are the things that go in between the paranthesis. Suppose that we want a function that takes in _zero_ parameters and always returns $1337$, we just leave the parameter section blank. def leet(): return 1337; # What do you think will happen if we run # # ```python # print leet(); # ``` # # Try it below! # + #Try what "print leet()" does. #Enter your code here: # - # Recall that the slope of a line that goes through $(x_1, y_1)$ and $(x_2, y_2)$ is $\frac{y_2-y_1}{x_2-x_1}$. Write a function that takes in four parameters x1,y1,x2,y2 and finds the slope of the line that goes through the two points. Call it find_Slope. # + #Write your function here #Solution def find_Slope(x1,y1,x2,y2): return (y2-y1)/(x2-x1); # - # Recall the example of you and your friend walking home from school. Now we will write a function that will calculate the time difference of arrival for an abstract sense. If your friend lives a distance $a$ miles away from you and you both decide to hang out at a location $x$ during the weekend, what will be the time difference of arrival of you and your friend getting home? Both of you walk with the same speed $s$. Answer the questions below to help find the TDOA. # # 1. How far do you have to walk home? # 2. How long does it take for you to walk home? # 3. How far does your friend have to walk home? # 4. How long will it take him to walk home? # 5. What is the difference in these two times? # # Write a python function below that takes in $a$ (friends house), $x$ (hangout location) and $s$ (the speed you two walk) and returns the TDOA. The function declaration should be # # ```python # def TDOA(a, x, s): # ``` # + #Write your function here #Solution def TDOA(a, x, s): return (a-2.0*x)/s; # - # Now we have a function that given a position finds the time difference of arrival. What if we want to find the position of your hangout spot given the TDOA? Write a function called ```find_position``` that takes in the position of your friend's house $a$, a time difference of arrival ($t$), and speed ($s$) and returns the position of your hangout location. # + #Write your function here #Solution def find_position(a, t, s): return (a-s*t)/2.0; # - # The ```find_position``` function you've defined will be vital in the final step of this project. # # Problems # # 1. What is the TDOA if you decide to hang out at a location to the LEFT of your house? # 2. Will your functions still work if this is the case?
Lessons/Lesson 3/Lesson 3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import cv2 as cv from tensorflow.keras.models import load_model model=load_model('C:/Users/kuwar/Downloads/sign_images (3).h5',compile=False) model.summary() # + import tensorflow as tf class_names=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','del','nothing','space'] import cv2 as cv inp=cv.VideoCapture(0) while(True): ret,frame=inp.read() fram=frame.copy() frame = frame[100:400, 320:620] frame = cv.resize(frame,(224,224),interpolation = cv.INTER_AREA) img=tf.expand_dims(frame,axis=0) prd = model.predict(img) index = prd.argmax() label=class_names[index] cv.putText(frame,label,(100,100),4,1,250,4) cv.rectangle(fram,(320,100),(620,400),(0,0,255),4) cv.imshow('frame',frame) cv.imshow('frame1',fram) if cv.waitKey(1) & 0xFF ==ord('q'): break inp.release() cv.destroyAllWindows() # -
prediction.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Please Follow this Docker container installation process in your MacBook/Laptop before running this Python+R Notebook below. # # - Installation setup of environment where this notebook runs can be found i # Container with Jupyter+H2o.ai+Python3+R+Spark in this [link_here](https://github.com/jpacerqueira/project_lost_saturn) # # Also : # - You need a Strong bandwith the install the Container environment it takes about 10-11 minutes to finish. # # - Good Luck, stay safe! But investigate Corona virus(covid-19 or SARS-Cov-2) in your area and give the information back to the comunity! # # + [markdown] colab_type="text" id="f1S90bdBVIaK" # # CoronaVirus Prediction # - # ### Number of Day to Predict 1 num_days_R_prediction=1 # #!pip install rpy2 import rpy2 # %load_ext rpy2.ipython # %Rpush num_days_R_prediction # + language="R" # max_days_prediction<-num_days_R_prediction # - bypass_weather=1 # =1 bypass weather_pi api calls # number_past_days_training=27 # =(6/14) * num_days_R_prediction # Number of Past days on training # max to be on 6.Feb.2020 # max_countries_map=51 # ## DROP_N=15 => 06/02 ## DROP_N=45 => 08/03 ## DROP_N=75 => 07/04 ## DROP_N=145 => 08/06 # drop_n_dataset_days=15 # # ## Regression - 1 Day Prediction # #!pip install h2o import h2o from h2o.estimators import H2ORandomForestEstimator from h2o.estimators.glm import H2OGeneralizedLinearEstimator from h2o.grid.grid_search import H2OGridSearch h2o.init(min_mem_size='3G') import numpy as np from sklearn.linear_model import LinearRegression # ### Load Data from Github - John Hopkins Institute # + # Get data from Github import numpy as np from math import sqrt from sklearn.metrics import mean_squared_error import pandas as pd #url_1 = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv' url_1 = 'https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv' confirmed = pd.read_csv(url_1, error_bad_lines=False) #url_2 = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv' url_2 = 'https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv' death = pd.read_csv(url_2, error_bad_lines=False) #url_3 = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv' url_3 = 'https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv' recover = pd.read_csv(url_3, error_bad_lines=False) # fix region names confirmed['Country/Region']= confirmed['Country/Region'].str.replace("Mainland China", "China") confirmed['Country/Region']= confirmed['Country/Region'].str.replace("US", "United States") death['Country/Region']= death['Country/Region'].str.replace("Mainland China", "China") death['Country/Region']= death['Country/Region'].str.replace("US", "United States") recover['Country/Region']= recover['Country/Region'].str.replace("Mainland China", "China") recover['Country/Region']= recover['Country/Region'].str.replace("US", "United States") # - confirmed.iloc[:,:] # + [markdown] colab_type="text" id="Vvb-N49UipcR" # ## Get Population # + colab={} colab_type="code" id="2h7I0zT9kmFS" population=pd.read_csv('/home/notebookuser/notebooks/covid19/data/population.csv', sep=',', encoding='latin1') confirmed=pd.merge(confirmed, population,how='left' ,on=['Province/State','Country/Region']) death=pd.merge(death, population,how='left' ,on=['Province/State','Country/Region']) recover=pd.merge(recover, population,how='left' ,on=['Province/State','Country/Region']) # + colab={"base_uri": "https://localhost:8080/", "height": 224} colab_type="code" executionInfo={"elapsed": 906, "status": "ok", "timestamp": 1582444047902, "user": {"displayName": "Ran Kremer", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB2_ZiPPU7rQBIvIt172EuazLz5955iIqYS5NAMAQ=s64", "userId": "05457805718113099013"}, "user_tz": -120} id="4_P8_F9poBQk" outputId="28901cce-a647-4d3c-afd2-5ccfaa18fd9d" # merge region confirmed + death + recover confirmed['region']=confirmed['Country/Region'].map(str)+'_'+confirmed['Province/State'].map(str) death['region']=death['Country/Region'].map(str)+'_'+death['Province/State'].map(str) recover['region']=recover['Country/Region'].map(str)+'_'+recover['Province/State'].map(str) confirmed.iloc[:,:] # - # merge region death death.iloc[185:195,:] # merge region recover recover.iloc[175:185,:] confirmed.iloc[185:195,:] confirmed.iloc[220:230,:] # + [markdown] colab_type="text" id="2dJhgqRCVgBV" # ## Create Time Series + Plots # + colab={} colab_type="code" id="V21PYZNdlf5m" def create_ts(df): ts=df ts=ts.drop(['Province/State', 'Country/Region','Lat', 'Long',' Population '], axis=1) ts.set_index('region') ts=ts.T ts.columns=ts.loc['region'] ts=ts.drop('region') ts=ts.fillna(0) ts=ts.reindex(sorted(ts.columns), axis=1) return (ts) # + colab={} colab_type="code" id="7XmTDuNDlx-k" ## JOAO - Fix - Drop Duplicates # Keep Last # Issue With Data source Change from John Hopkins institute # ts=create_ts(confirmed.drop_duplicates(subset=['region'], keep='last', inplace=False) ) ts_d=create_ts(death.drop_duplicates(subset=['region'], keep='last', inplace=False) ) ts_rec=create_ts(recover.drop_duplicates(subset=['region'], keep='last', inplace=False) ) # - # JOAO - FIX - Automation WarmUp of Plot Library import matplotlib.pyplot as plt import time plt.legend(loc = 'upper left') plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" executionInfo={"elapsed": 2666, "status": "ok", "timestamp": 1582444057086, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB2_ZiPPU7rQBIvIt172EuazLz5955iIqYS5NAMAQ=s64", "userId": "05457805718113099013"}, "user_tz": -120} id="jOOwU-KzPssI" outputId="19b97499-f8c5-460e-f173-aa44515444ec" # p=ts.reindex(ts.max().sort_values(ascending=False).index, axis=1) p.iloc[:,0:3].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Confirmed - Top_3 World Region ',fontdict={'fontsize': 22}) p.iloc[:,3:25].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Confirmed - Major_4,25 2nd Areas',fontdict={'fontsize': 22}) p_d=ts_d.reindex(ts_d.max().sort_values(ascending=False).index, axis=1) p_d.iloc[:,0:3].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Deaths - Top_3 World Region',fontdict={'fontsize': 22}) p_d.iloc[:,3:25].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Deaths - Major_4,25 2nd Areas',fontdict={'fontsize': 22}) p_r=ts_rec.reindex(ts_rec.max().sort_values(ascending=False).index, axis=1) p_r.iloc[:,0:3].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Recovered - Top_3 World Region',fontdict={'fontsize': 22}) p_r.iloc[:,3:25].plot(marker='*',figsize=(20,12)).set_title('Daily Update - Total Recovered - Major_4,25 2nd Areas',fontdict={'fontsize': 22}) # + [markdown] colab_type="text" id="EsVRIFMLoV_3" # ### Extract Weather Data # + colab={} colab_type="code" id="LwxsJMRHoQKS" # #!pip install pyweatherbit # from weatherbit.api import Api import json import pandas as pd from pandas.io.json import json_normalize ### API - Joao from datetime import datetime # #api_key="<KEY>" # <EMAIL> api_key="<KEY>" # <EMAIL> # api = Api(api_key) api.set_granularity('daily') # # Set the granularity of the API - Options: ['daily','hourly','3hourly'] # # Will only affect forecast requests. #api.get_forecast(lat='Lat', lon='Lon') #my_end_date=datetime.today().strftime('%Y-%m-%d') #### United Kingdom #lat1='55.378100' #lon1='-3.436000' #api.get_history(lat=lat1,lon=lon1, start_date='2020-03-29',end_date=my_end_date) # - ## #### My List of Countries and Regions to train and represent data my_train_list=[ ### JOAO - LIST of Countries - Start here # 'Andorra_nan', 'United States_nan', 'United Kingdom_nan', 'Italy_nan', 'Spain_nan', 'Netherlands_nan', 'France_nan', 'Belgium_nan', 'Portugal_nan', 'Switzerland_nan', 'Germany_nan', 'Japan_nan', 'Poland_nan', ### JOAO - LIST of Countries - Finish here 'Korea, South_nan', 'China_Hubei', 'China_Beijing', 'China_Guangdong', 'China_Shanghai', # 'China_Shanxi', # 'China_Sichuan', 'China_Xinjiang', # 'China_Yunnan', 'China_Zhejiang', # 'China_Anhui', 'China_Beijing', # 'China_Chongqing', 'China_Fujian', 'China_Gansu', # 'China_Guangdong', 'China_Guangxi', 'China_Guizhou', # 'China_Hainan', 'China_Hebei', 'China_Heilongjiang', 'China_Henan', # 'China_Hubei', 'China_Hunan', 'China_Inner Mongolia', # 'China_Jiangsu', 'China_Jiangxi', 'China_Jilin', 'China_Liaoning', # 'China_Ningxia', 'China_Qinghai', 'China_Shaanxi', # 'China_Shandong', 'China_Shanghai', 'China_Shanxi', # 'China_Sichuan', 'China_Tianjin', 'China_Tibet', 'China_Xinjiang', # 'China_Yunnan', 'China_Zhejiang', # 'Morocco_nan', 'Australia_New South Wales', # 'Australia_Queensland', # 'Australia_South Australia', 'Australia_Victoria', 'Brazil_nan', # 'Cambodia_nan', # 'Canada_British Columbia', 'Canada_Ontario', 'Canada_Quebec', # 'Egypt_nan', 'China_Hong Kong', 'China_Macau', 'Finland_nan', 'India_nan', 'Iran_nan', 'Malaysia_nan', # 'Nepal_nan', 'Norway_nan', 'Philippines_nan', 'Russia_nan', 'Singapore_nan', # 'Sri Lanka_nan', 'Thailand_nan', 'United Arab Emirates_nan', 'Sweden_nan', 'Austria_nan', # 'Taiwan*_nan', # 'Vietnam_nan', 'Turkey_nan', 'Peru_nan', 'Chile_nan', 'Mexico_nan' ] # # + [markdown] colab_type="text" id="6BthA7XNoBnx" # #### Weather History # + colab={} colab_type="code" id="eEriYmKdoFaN" # ################## already done since API is limited to 500 call per day ## consume Wether data From 15/03/2020 forward to end_date=30/03/2020 # ### Location in confirmed array to start in pos 1='Albania_nan' 61 = 'China_Hong Kong' ### Only run for Countries in above : my_train_list vpos=len(confirmed.iloc[1])-1 #90# 89 #88 #87 #86 #85 #84 #83 #82 #81 #80 #79 #78 #77 #76 #75 #74 #1 #73 print('xcountry_region='+confirmed.iloc[1,vpos]) my_weather_fetch_list= my_train_list # ['Canada_Quebec'] # ['Iran_nan'] #['Brazil_nan'] # start_date_init=pd.to_datetime('today').strftime('%Y/%m/%d') # '2020-04-18' print('start_date_init=',start_date_init) offset_days=-1 # -1 to start yesterday pick today # API free-tier just picks one per api call! max_days=1 #1 w=pd.DataFrame(columns=['date','region','min','max']) if bypass_weather != 1 : for h in range(0,max_days): offset_days=h start_date=pd.to_datetime(start_date_init) # end_date=(start_date+pd.DateOffset(days=offset_days+1)).strftime('%Y-%m-%d') start_date=(start_date+pd.DateOffset(days=offset_days)).strftime('%Y-%m-%d') prnt_start_date=pd.to_datetime(start_date).strftime('%Y/%m/%d') prnt_end_date=pd.to_datetime(end_date).strftime('%Y/%m/%d') # for i in range (1,len(confirmed)): if confirmed.iloc[i,vpos] not in my_weather_fetch_list: continue if confirmed.iloc[i,vpos] in my_weather_fetch_list: # # Clean JSON structure return from API Call jas="" jas=api.get_history(lat=confirmed.iloc[i,2], lon=confirmed.iloc[i,3], start_date=start_date,end_date=end_date).json if (((json_normalize(jas['data'])['min_temp'].values[0])=='') or (np.isnan((json_normalize(jas['data'])['min_temp'].values[0])) == True )): continue try: w=w.append({'date':prnt_end_date,'region':confirmed.iloc[i,vpos] ,'min':json_normalize(jas['data'])['min_temp'].values[0],'max':json_normalize(jas['data'])['max_temp'].values[0]}, ignore_index=True) except Exception: w=w.append({'date':prnt_end_date,'region':confirmed.iloc[i,vpos] ,'min':None,'max':None}, ignore_index=True) # # table_columns=['date','region','min','max'] w = w[w.columns.intersection(table_columns)] # - w.to_csv('data/w_v2_v227.csv', index = False, header=True) w[:] # + [markdown] colab_type="text" id="DP96GEhbXKL1" # ## Kalman Filter With R # + # Joao - FIX - Improve Performance ### Drop the Months of Jan, Feb < 06/02 as ### they are too in the Past and model no longuer trains in China Hubei only! # ## DROP_N=75 => 07/04 drop_n=drop_n_dataset_days ts=ts[drop_n:] ts_d=ts_d[drop_n:] ts_rec=ts_rec[drop_n:] # - ts[:3] ts[-4:] # + colab={} colab_type="code" id="ie1YVvCXgybm" # Create data for R script ts_conf=ts.reset_index() ts_conf=ts_conf.rename(columns = {'index':'date'}) ts_conf['date']=pd.to_datetime(ts_conf['date'] ,errors ='coerce') ts_conf.to_csv(r'/home/notebookuser/notebooks/covid19/data/ts_conf_r.csv') ts_rec=ts_rec.reset_index() ts_rec=ts_rec.rename(columns = {'index':'date'}) ts_rec['date']=pd.to_datetime(ts_rec['date'] ,errors ='coerce') ts_rec.to_csv(r'/home/notebookuser/notebooks/covid19/data/ts_rec_r.csv') ts_d=ts_d.reset_index() ts_d=ts_d.rename(columns = {'index':'date'}) ts_d['date']=pd.to_datetime(ts_d['date'] ,errors ='coerce') ts_d.to_csv(r'/home/notebookuser/notebooks/covid19/data/ts_d_r.csv') # + colab={"base_uri": "https://localhost:8080/", "height": 629} colab_type="code" executionInfo={"elapsed": 19024, "status": "ok", "timestamp": 1582444082482, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB2_ZiPPU7rQBIvIt172EuazLz5955iIqYS5NAMAQ=s64", "userId": "05457805718113099013"}, "user_tz": -120} id="ngrkbpXcprcN" outputId="b79bf710-1544-449f-9d07-411cc2efcda5" language="R" # # #install.packages('pracma') # #install.packages('Metrics') # #install.packages('readr') # #install.packages('reshape') # # Sys.setenv(TZ='GMT') # Sys.timezone() # + colab={"base_uri": "https://localhost:8080/", "height": 238} colab_type="code" executionInfo={"elapsed": 2026, "status": "ok", "timestamp": 1582444084537, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mB2_ZiPPU7rQBIvIt172EuazLz5955iIqYS5NAMAQ=s64", "userId": "05457805718113099013"}, "user_tz": -120} id="mcIMrc3AW-Km" outputId="31c140e2-1428-44fb-b669-97c0ba6b6321" language="R" # require(pracma) # require(Metrics) # require(readr) # all<- read_csv("/home/notebookuser/notebooks/covid19/data/ts_conf_r.csv") # all$X1<-NULL # date<-all[,1] # date[nrow(date) + 1,1] <-all[nrow(all),1]+1 # pred_all<-NULL # for (n in 2:ncol(all)-1) { # Y<-ts(data = all[n+1], start = 1, end =nrow(all)+1) # sig_w<-0.01 # w<-sig_w*randn(1,100) # acceleration which denotes the fluctuation (Q/R) rnorm(100, mean = 0, sd = 1) # sig_v<-0.01 # v<-sig_v*randn(1,100) # t<-0.45 # phi<-matrix(c(1,0,t,1),2,2) # gama<-matrix(c(0.5*t^2,t),2,1) # H<-matrix(c(1,0),1,2) # #Kalman # x0_0<-p0_0<-matrix(c(0,0),2,1) # p0_0<-matrix(c(1,0,0,1),2,2) # Q<-0.01 # R<-0.01 # X<-NULL # X2<-NULL # pred<-NULL # for (i in 0:nrow(all)) { # namp <-paste("p", i+1,"_",i, sep = "") # assign(namp, phi%*%(get(paste("p", i,"_",i, sep = "")))%*%t(phi)+gama%*%Q%*%t(gama)) # namk <- paste("k", i+1, sep = "") # assign(namk,get(paste("p", i+1,"_",i, sep = ""))%*%t(H)%*%(1/(H%*%get(paste("p", i+1,"_",i, sep = ""))%*%t(H)+R))) # namx <- paste("x", i+1,"_",i, sep = "") # assign(namx,phi%*%get(paste("x", i,"_",i, sep = ""))) # namE <- paste("E", i+1, sep = "") # assign(namE,Y[i+1]-H%*%get(paste("x", i+1,"_",i, sep = ""))) # namx2 <- paste("x", i+1,"_",i+1, sep = "") # assign(namx2,get(paste("x", i+1,"_",i, sep = ""))+get(paste("k", i+1, sep = ""))%*%get(paste("E", i+1, sep = ""))) # namp2 <- paste("p", i+1,"_",i+1, sep = "") # assign(namp2,(p0_0-get(paste("k", i+1, sep = ""))%*%H)%*%get(paste("p", i+1,"_",i, sep = ""))) # X<-rbind(X,get(paste("x", i+1,"_",i,sep = ""))[1]) # X2<-rbind(X2,get(paste("x", i+1,"_",i,sep = ""))[2]) # if(i>2){ # remove(list=(paste("p", i-1,"_",i-2, sep = ""))) # remove(list=(paste("k", i-1, sep = ""))) # remove(list=(paste("E", i-1, sep = ""))) # remove(list=(paste("p", i-2,"_",i-2, sep = ""))) # remove(list=(paste("x", i-1,"_",i-2, sep = ""))) # remove(list=(paste("x", i-2,"_",i-2, sep = "")))} # } # pred<-NULL # pred<-cbind(Y,X,round(X2,4)) # pred<-as.data.frame(pred) # pred$region<-colnames(all[,n+1]) # pred$date<-date$date # pred$actual<-rbind(0,(cbind(pred[2:nrow(pred),1])/pred[1:nrow(pred)-1,1]-1)*100) # pred$predict<-rbind(0,(cbind(pred[2:nrow(pred),2])/pred[1:nrow(pred)-1,2]-1)*100) # pred$pred_rate<-(pred$X/pred$Y-1)*100 # pred$X2_change<-rbind(0,(cbind(pred[2:nrow(pred),3]-pred[1:nrow(pred)-1,3]))) # pred_all<-rbind(pred_all,pred) # } # pred_all<-cbind(pred_all[,4:5],pred_all[,1:3]) # names(pred_all)[5]<-"X2" # pred_all=pred_all[with( pred_all, order(region, date)), ] # pred_all<-pred_all[,3:5] # - # p=%R pred_all # + colab={} colab_type="code" id="j8ZrF8iJUcKq" ############ Merge R output due to package problem ### Joao FIX - # t=ts_d - deaths # t=ts_rec - recovered # t=ts - confirmed t=ts t=t.stack().reset_index(name='confirmed') t.columns=['date', 'region','confirmed'] t['date']=pd.to_datetime(t['date'] ,errors ='coerce') t=t.sort_values(['region', 'date']) temp=t.iloc[:,:3] temp=temp.reset_index(drop=True) for i in range(1,len(t)+1): if(temp.iloc[i,1] is not temp.iloc[i-1,1]): temp.loc[len(temp)+1] = [temp.iloc[i-1,0]+ pd.DateOffset(1),temp.iloc[i-1,1], 0] temp=temp.sort_values(['region', 'date']) temp=temp.reset_index(drop=True) temp['Y']=p['Y'] temp['X']=p['X'] temp['X2']=p['X2'] # JOAO - FIX - temp fixed # Y,X,X2 nan issue from p revolved p_pd=pd.DataFrame(p,columns=['Y','X','X2']) p_pd['nindex'] = range(1, 1+len(p_pd)) temp['nindex']= range(1,1+len(temp)) #temp_1 = temp.join(p_pd) temp_1 = temp.merge(p_pd, on='nindex', how='inner', suffixes=('_1', '_2')).rename(columns={"Y_2": "Y", "X_2": "X", "X2_2" : "X2"}) temp_1 = temp_1.drop(columns=['Y_1', 'X_1','X2_1','nindex']) temp=temp_1 temp.to_csv(r'/home/notebookuser/notebooks/covid19/data/temp.csv') # + [markdown] colab_type="text" id="a7vUr36bVvOb" # ## Pre Proccessing Data for ML Model # + [markdown] colab_type="text" id="PTerYYnPq2X7" # ### Extract Weather Forecast Data # + colab={} colab_type="code" id="M4XJBLT2-quk" # ### Joao - Test Later Weather from new file : w_v2.csv and w_v2_v2.csv w_v2=pd.read_csv('data/w_v2.csv', sep=',', encoding='latin1') w_v2['date']=pd.to_datetime(w_v2['date'],format='%Y/%m/%d') w_v2_v2=pd.read_csv('data/w_v2_v2.csv', sep=',', encoding='latin1') w_v2_v2['date']=pd.to_datetime(w_v2_v2['date'],format='%Y/%m/%d') w_v2_v227=pd.read_csv('data/w_v2_v227.csv', sep=',', encoding='latin1') w_v2_v227['date']=pd.to_datetime(w_v2_v227['date'],format='%Y/%m/%d') w=pd.read_csv('data/w.csv', sep=',', encoding='latin1') w['date']=pd.to_datetime(w['date'],format='%d/%m/%Y') w_forecast=pd.read_csv('data/w_forecast.csv', sep=',', encoding='latin1') w_forecast['date']=pd.to_datetime(w_forecast['date'],format='%d/%m/%Y') ### Append Weather fetched now to file w_v2_v2 w_n_forward=w_v2_v2.append(w_v2_v227) w_n_forward=w_n_forward.drop_duplicates(subset=['date','region'], keep='last', inplace=False) w_n_forward=w_n_forward.sort_values(by=['region','date'], ascending=True) w_n_forward.to_csv(r'data/w_v2_v2.csv', index = False, header=True) # + w_total=pd.DataFrame(columns=['date','region','min','max']) w_total=w.append(w_forecast).append(w_v2).append(w_v2_v2).append(w_v2_v227) w_total=w_total.drop_duplicates(subset=['date','region'], keep='last', inplace=False) w_total=w_total.sort_values(by=['region','date'], ascending=True) w_total.to_csv(r'data/w_total.csv', index = False, header=True) # - w_in_model=pd.read_csv('data/w_total.csv', sep=',', encoding='latin1') # w_in_model['date']=pd.to_datetime(w_in_model['date'],format='%Y/%m/%d') w_in_model.to_csv(r'data/w_in_model.csv', index = False, header=True) w_in_model.tail(2) # + [markdown] colab_type="text" id="2vIZPBkfoqHe" # ### Build Train Set Data Structure # + colab={} colab_type="code" id="YPMRge7kQA8t" ### JOAO - Fix - ## t=ts confirmed t=ts t=t.stack().reset_index(name='confirmed') t.columns=['date', 'region','confirmed'] t['date']=pd.to_datetime(t['date'] ,errors ='coerce') t=t.sort_values(['region', 'date']) # Add 1 Future day for prediction t=t.reset_index(drop=True) for i in range(1,len(t)+1): if(t.iloc[i,1] is not t.iloc[i-1,1]): t.loc[len(t)+1] = [t.iloc[i-1,0]+ pd.DateOffset(1),t.iloc[i-1,1], 0] t=t.sort_values(['region', 'date']) t=t.reset_index(drop=True) # + ### JOAO - Fix - t['1_day_change']=t['3_day_change']=t['7_day_change']=t['1_day_change_rate']=t['3_day_change_rate']=t['7_day_change_rate']=t['last_day']=0 # ### JOAO - Fix - ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars for i in range(1,len(t)): if(t.iloc[i,1] is t.iloc[i-2,1]): t.iloc[i,3]=t.iloc[i-1,2]-t.iloc[i-2,2] t.iloc[i,6]=((t.iloc[i-1,2]*100 +1)/(t.iloc[i-2,2]*100 -1 +1))*100 t.iloc[i,9]=t.iloc[i-1,2] if(t.iloc[i,1] is t.iloc[i-4,1]): t.iloc[i,4]=t.iloc[i-1,2]-t.iloc[i-4,2] t.iloc[i,7]=((t.iloc[i-1,2]*100 +1)/(t.iloc[i-4,2]*100 -1 +1))*100 if(t.iloc[i,1] is t.iloc[i-8,1]): t.iloc[i,5]=t.iloc[i-1,2]-t.iloc[i-8,2] t.iloc[i,8]=((t.iloc[i-1,2]*100 +1)/(t.iloc[i-8,2]*100 -1 +1))*100 t=t.fillna(0) t=t.merge(temp[['date','region', 'X']],how='left',on=['date','region']) t=t.rename(columns = {'X':'kalman_prediction'}) t=t.replace([np.inf, -np.inf], 0) ### Joao - Fix NaN Kalman_Filter t['kalman_prediction']=np.nan_to_num(t['kalman_prediction']) t['kalman_prediction']=round(t['kalman_prediction']) # train=t.merge(confirmed[['region',' Population ']],how='left',on='region') train=train.rename(columns = {' Population ':'population'}) train['population']=train['population'].str.replace(r" ", '') train['population']=train['population'].str.replace(r",", '') train['population']=train['population'].fillna(10000000) ### Fill 10M if nan train['population']=train['population'].astype('int32') ### JOAO - Fix - ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars # train['infected_rate']=train['last_day']/train['population']*10000 train['infected_rate']=(((train['last_day'] +1)*100)/((train['population'] +1)*100000) *10) # *100 - % converter # #### Joao , merge w weather only !?! ##train=train.merge(w,how='left',on=['date','region']) train=train.merge(w_in_model,how='left',on=['date','region']) # train=train.sort_values(['region', 'date']) ### fill missing weather for i in range(0,len(train)): if(np.isnan(train.iloc[i,13])): if(train.iloc[i,1] is train.iloc[i-1,1]): train.iloc[i,13]=train.iloc[i-1,13] train.iloc[i,14]=train.iloc[i-1,14] # - # Joao - Fix - Nulls are an issue train_notnull=train[train['kalman_prediction'] != 0.0 ] #.any(axis=1)] train_notnull[:] # Joao - Fix - Nulls are an issue train_nulls=train[train['kalman_prediction'].isnull() ] #.any(axis=1)] train_nulls[:] # + # Joao - Fix - Nulls are an issue train_nulls=train[train.isnull().any(axis=1)] train_nulls[:] train[-1:] # + train.to_csv(r'data/train.csv', index = False, header=True) ##Shared -- Ratio in Confirmed - 21Day Forecast -- train 25April2020 - I ratiod=pd.read_csv('data/train.csv', sep=',', encoding='latin1') todayd=datetime.today().strftime('%Y-%m-%d') ratiofn="World v2 -- Confirmed - "+str(num_days_R_prediction)+"Day Forecast -- train "+todayd+".csv" ratiod['population_percentage : infected_rate confirmed']=ratiod['infected_rate']*100 ratiod['population_percentage : factor 9/10 infected_rate confirmed']=ratiod['infected_rate']*1000 ratiod['delta : new_cases']=ratiod['kalman_prediction']-ratiod['last_day'] ratiod['delta : new_cases per 1M hab']=ratiod['delta : new_cases']/ratiod['population']*1000000 ### roling 7day_AVG ratiod['delta : roling 7day AVG']=ratiod['7_day_change']/7 ratiod['delta : aprox 14-day case notification rate per 100k hab']=(ratiod['7_day_change']*2)/ratiod['population']*100000 ### ratiod=ratiod.rename(columns={'kalman_prediction': 'confirmed_prediction', 'last_day': 'confirmed_yesterday'}) ratiod.to_csv(r'data/'+ratiofn, index = False, header=True) ratiod[-3:] # + [markdown] colab_type="text" id="YekOqU6Xr-qZ" # ## Kalman 1 day Prediction with Evaluation # + # Select region region='United States_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Russia_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Brazil_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Mexico_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='United Kingdom_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='France_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Italy_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Portugal_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + # Select region region='Spain_nan' evaluation=pd.DataFrame(columns=['region','mse','rmse','mae']) place=0 for i in range(1,len(t)): if(t.iloc[i,1] is not t.iloc[i-1,1]): ex=np.array(t.iloc[i-len(ts):i,10]) pred=np.array(t.iloc[i-len(ts):i,2]) evaluation=evaluation.append({'region': t.iloc[i-1,1], 'mse': np.power((ex - pred),2).mean(),'rmse':sqrt(mean_squared_error(ex,pred)),'mae': (abs(ex - pred)).mean()}, ignore_index=True) p=t[t['region']==region][['date','region','confirmed','kalman_prediction']] #p=p.rename(columns = {'confirmed':'recoverd'}) p.iloc[len(p)-1,2]=None p=p.set_index(['date']) p.iloc[:,1:].plot(marker='o',figsize=(16,8)).set_title('Kalman Prediction - Select Region to Change - {}'.format(p.iloc[0,0])) print(evaluation[evaluation['region']==p.iloc[0,0]]) # + [markdown] colab_type="text" id="8fjvSTMetENY" # ## Regression - 1 Day Prediction # - print("Light version 1day for display purpose at https://FuelBigData.com/blog ") # + colab={} colab_type="code" id="15zSGQ9xZ2Qy" exit() # -
notebooks/covid19/archive/.ipynb_checkpoints/MY_COVID19-Prediction_2020-10-18-1dayForecast-data-output-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # In looking at the flux results, I had a hunch that something was off. The flux was correct on my test flow fields, so I speculated the problem was in the flow approximations of the calcium. So I've been to digging into the idiosyncrasies of the flow calculations and I have found what I believe to an issue, hopefully THE issue. # # --- # # Take frames 79 and 80 from the TSeries-01292015-1540_site3_0.75ISO_AL_VDNstd3 data set... (Frame 79 on left, frame 80 on right) # # <img src="files/media/issues_with_flow/frames79and80.png" height="90%" width="90%"> # We can clearly see from this raw data that there appears to be inward calcium movement in the top process. So I began to examine how accurately the optical flow algorithm captures this. From our discussions, the implementation that I WAS using went as follows # # ```python # # ... # data = loadData(dataPath) # Load the data # f0 = percentile(data, 10.0, axis=0) # Used for calculating relative fluorescence # relData = (data-f0)/f0 # Reletive fluorescence # blurData = gauss(relData, (1.2,0.75,0.75)) # Blurring stds are (time,y,x) # # ---- Then calculate the optical flow ---- # # ... # prev = blurData[0] # for i,curr in enumerate(blurData[1:]): # flow = optFlow(prev, curr, pyr_scale, levels, winSz, itrs, polyN, polyS, flg) # xflow[i] = flow[:,:,0] # yflow[i] = flow[:,:,1] # prev = curr # ``` # So we see here that the flow is calculated using the blurred relative fluorescence. Below I show frames 79 and 80 from the blurred relative fluorescence data set, `blurData`. # # <img src="files/media/issues_with_flow/rcframes79and80.png" height="92%" width="92%"> # We see a very poor representation of the movement of calcium in the top process as compared with the original data. This can be seen from the flow approximations between these two frames. If you examine the flow more closely (I went back and forth between overlayed flows and images to see) you can see that the apparent inward flow in the top process is not aligned on top of the process and it is not at what visually appears to be the right angle. This is made more clear with the following data # # <img src="files/media/issues_with_flow/rc_based_raw_flow.png" height="96%" width="96%"> # So I decided to try the calculations again on the regular blurred fluorescence images. i.e. I simply removed the relative fluorescence calculation. The two blurred raw frames 79 and 80 are shown below... # # <img src="files/media/issues_with_flow/rawframes79and80.png" height="92%" width="92%"> # If I didn't save the image all goofy then it would be pretty clear that this better represents the calcium movement in the top process. (I am emailing you all of the figures so you can examine and compare them at your leisure) So, I was hoping that the flow calculations would be much better, however, they were not. Below is the flow approximation. # # <img src="files/media/issues_with_flow/raw_flow.png" height="96%" width="96%"> # # After I carefully examined this it seemed to me that all of the alleged "correct" flows are in here, however there is also much more garbage. This is because the flow calculations look for displacement and ignore magnitude. So the seemingly strong flows around the periphery are allegedly the dynamics of the faint calcium fluorescence. So I remembered my previous idea of incorporating the original data set into the flux, and thought I could incorporate the original dataset into the flow calculations instead. So, I compared the results between scaling the flow by original blurred calcium intensities and via scaling it by the blurred relative calcium intensities. The idea here is that the "strong" flows around the periphery would be smothered by the low amplitude of the calcium underneath while the strong calcium movements would be accentuated. It turns out that this was the case... # # <img src="files/media/issues_with_flow/flow_scaled_by_calcium.png" height="96%" width="96%"> # <img src="files/media/issues_with_flow/flow_scaled_by_relative_calcium.png" height="96%" width="96%"> # # So I see that the scaling via the regular calcium seems to "sharpen" the flow within the processes and capture activity in the soma, while scaling via the relative fluorescence broadens the flow around the processes and silences the flow in the soma. Given our objective of measuring "flow" in the processes, off hand I think calculating the flow from the regular data and scaling it with the regular data produces the best results. Or perhaps I need to choose a better f0 to calculate the relative fluorescnece. What do you think? # # P.S. I also tried scaling the flow determined from the relative fluorescence data as well. The results weren't helpful so I am not including them here. I did send the flow figures to you though.
.ipynb_checkpoints/Issues with Flow-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # [View in Colaboratory](https://colab.research.google.com/github/scumabo/Deep-Learning-with-tf.keras/blob/master/3_MNIST_classification_fully_connected_neural_networks_(tf_keras).ipynb) # + id="aNAb4KwP5VvW" colab_type="code" colab={} import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # %matplotlib inline # + id="_hO5jard9yV2" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 67} outputId="ac7bc7a5-ecb2-46c4-c989-8ab425042152" data = pd.read_csv("MNIST_train.csv").values X_data = data[:, 1:] Y_data = data[:, [0]] # Simple normalization X_data = X_data / 255 X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, random_state = 0) print("Number of training examples = " + str(X_train.shape[0]) ) print("Number of testing examples = " + str(X_test.shape[0]) ) print("Number of features = " + str(X_train.shape[1]) ) # + id="N0yKt0dk92Sk" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 297} outputId="06eb0c94-7e70-41e2-a818-b7964fa8d15c" index = 20 sampleImg = np.reshape(X_train[index, :], [28, 28]) ax = plt.imshow(sampleImg) plt.title("label is " + str(Y_train[index, :])) # + id="S98sGk-h-MVT" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1959} outputId="c98e5836-2ffa-4d42-c494-bb110cfbcb5d" tf.set_random_seed(1) model = tf.keras.Sequential([ tf.keras.layers.Dense(50, activation = "relu"), tf.keras.layers.Dense(40, activation = "relu"), tf.keras.layers.Dense(30, activation = "relu"), tf.keras.layers.Dense(10, activation = "softmax") ]) model.compile(optimizer = "adam", loss = "sparse_categorical_crossentropy", metrics = ["accuracy"]) History = model.fit(X_train, Y_train, epochs = 50) plt.plot(History.history["loss"]) plt.xlabel("epoch") plt.ylabel("loss") plt.show() # + id="DHKr_elcFboH" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 50} outputId="472a0a5f-b301-4197-ee0a-535368abd899" model.evaluate(X_test, Y_test) # + [markdown] id="azSJJUnZFkId" colab_type="text" # The test accuracy is 96 $\%$ and the training accuracy is 99.71 $\%$. Let's add dropout regularizers.
3_MNIST_classification_fully_connected_neural_networks_(tf_keras).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import open3d as o3d import os import sys # monkey patches visualization and provides helpers to load geometries sys.path.append('..') import open3d_tutorial as o3dtut # change to True if you want to interact with the visualization windows o3dtut.interactive = not "CI" in os.environ # - # # Half Edge Mesh # # This tutorial outlines the following: # 1. How to use `mesh_show_back_face` to render the backface of a mesh. # 2. How to use `geometry.AxisAlignedBoundingBox` to crop a mesh. # 3. How to use `utility.Vector3dVector` to colorize boundary vertices of a mesh to red. # ## Render the backface of a Mesh # # In order to render the backface of a mesh `visualization.draw_geometries()` is called with the flag `mesh_show_back_face` set to `True`. # Initialize a HalfEdgeTriangleMesh from TriangleMesh mesh = o3d.geometry.TriangleMesh.create_sphere() bbox = o3d.geometry.AxisAlignedBoundingBox() bbox.min_bound = [-1, -1, -1] bbox.max_bound = [1, 0.6, 1] mesh = mesh.crop(bbox) het_mesh = o3d.geometry.HalfEdgeTriangleMesh.create_from_triangle_mesh(mesh) o3d.visualization.draw_geometries([het_mesh], mesh_show_back_face=True) # ## Cropping a Mesh # # `geometry.AxisAlignedBoundingBox` is used to create an axis aligned box. The parameters `min_bound` and `max_bound` take an array of cartesian coordinates (x,y,z) and define the size of the bounding box. The bounds are set such that the y-axis of the sphere mesh is cut by a call to `crop`. # Colorize boundary vertices to red vertex_colors = 0.75 * np.ones((len(het_mesh.vertices), 3)) for boundary in het_mesh.get_boundaries(): for vertex_id in boundary: vertex_colors[vertex_id] = [1, 0, 0] het_mesh.vertex_colors = o3d.utility.Vector3dVector(vertex_colors) o3d.visualization.draw_geometries([het_mesh], mesh_show_back_face=True) # ## Colorize the Boundaries of a Mesh # # A call to `geometry.TriangleMesh.get_boundaries` returns a vector of boundaries, where each boundary is a vector of vertices. Each vertex color is represented by an RBG array and `Vector3dVector` is used to convert `vertex_colors` of shape (n, 3) to Open3D format. Finally, the vertex colors are set on the mesh.
docs/jupyter/geometry/half_edge_mesh.ipynb