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 # language: python # name: python3 # --- # # 4. Record linkage # **Record linkage is a powerful technique used to merge multiple datasets together, used when values have typos or different spellings. In this chapter, you'll learn how to link records by calculating the similarity between stringsโ€”youโ€™ll then use your new skills to join two restaurant review datasets into one clean master dataset.** # ## Comparing strings # Welcome to the final chapter of this course, where we'll discover the world of record linkage. But before we get deep dive into record linkage, let's sharpen our understanding of string similarity and minimum edit distance. # # ### Minimum edit distance # Minimum edit distance is a systematic way to identify how close 2 strings are. # # For example, let's take a look at the following two words: *intention*, and *execution*. # # The minimum edit distance between them is the least possible amount of steps, that could get us from the word intention to execution, with the available operations being inserting new characters, deleting them, substituting them, and transposing consecutive characters. # # To get from *intention* to *execution*, We first start off by deleting `I` from *intention*, and adding `C` between `E` and `N`. Our minimum edit distance so far is **2**, since these are two operations. Then we substitute the first `N` with `E`, `T` with `X`, and `N` with `U`, leading us to execution! With the minimum edit distance being **5**. # # The lower the edit distance, the closer two words are. For example, the two different typos of *reading*, '*reeding*' and '*redaing*', have a minimum edit distance of **1** between them and reading. # ### Minimum edit distance algorithm # There's a variety of algorithms based on edit distance that differ on which operations they use, how much weight attributed to each operation, which type of strings they're suited for and more, with a variety of packages to get each similarity. # # For this lesson, we'll be comparing strings using Levenshtein distance since it's the most general form of string matching by using the fuzzywuzzy package. # # Algorithm | Operations # :---|:--- # Danerau-Levenshtein | insertion, substitution, deletion, transposition # ***Levenshtein*** | ***insertion, substitution, deletion*** # Hamming | substitution only # Jaro distance | transpostion only # ... | ... # # **possible packages**: `nltk`, `fuzzywuzzy`, `textdistance`, ... # ### Simple string comparison # ***Fuzzywuzzy*** is a simple to use package to perform string comparison. We first import fuzz from fuzzywuzzy, which allow us to compare between single strings. # # Here we use fuzz's WRatio function to compute the similarity between reading and its typo, inputting each string as an argument. For any comparison function using fuzzywuzzy, our output is a score from 0 to 100 with 0 being not similar at all, 100 being an exact match. # # ```python # # Compare between two strings # from fuzzywuzzy import fuzz # # # Compare reeding vs reading # fuzz.WRatio('Reeding', 'Reading') # ``` # # ``` # 86 # ``` # # Do not confuse this with the minimum edit distance score earlier, where a lower minimum edit distance means a closer match. # ### Partial strings and different orderings # The WRatio function is highly robust against partial string comparison with different orderings. # # For example here we compare the strings Houston Rockets and Rockets, and still receive a high similarity score. # ```python # # Partial string comparison # fuzz.WRatio('Houston Rockets', 'Rockets') # ``` # ``` # 90 # ``` # # The same can be said for the strings Houston Rockets vs Los Angeles Lakers and Lakers vs Rockets, where the team names are only partial and they are differently ordered. # ```python # # Partial string comparison # fuzz.WRatio('Houston Rockets vs Los Angeles Lakers', 'Lakers vs Rockets') # ``` # ``` # 86 # ``` # ### Comparison with arrays # We can also compare a string with an array of strings by using the extract function from the process module from fuzzy wuzzy. # ```python # # Import precess # from fuzzywuzzy import process # # # Define string and array of possible matches # string = 'Houston Rockets vs Los Angeles Lakers' # choices = pd.Series(['Rockets vs Lakers', 'Lakers vs Rockets', # 'Houston vs Los Angeles', 'Heat vs Bulls']) # # process.extract(string, choices, limit = 2) # ``` # ``` # [('Rockets vs Lakers', 86, 0), ('Lakers vs Rockets', 86, 1)] # ``` # Extract takes in a string, an array of strings, and the number of possible matches to return ranked from highest to lowest. It returns a list of tuples with 3 elements, the first one being the matching string being returned, the second one being its similarity score, and the third one being its index in the array. # ### Collapsing categories with string similarity # **Chapter 2** # # Use `.replace()` to collapse `'eur` into `Europe` # # In chapter 2, we learned that collapsing data into categories is an essential aspect of working with categorical and text data, and we saw how to manually replace categories in a column of a DataFrame. # # *What if there are too many variations?* # # `'EU`, `'eur`, `'Europe'`, `'Europa'`, `'Erope'`, `'Evropa'` ... # # But what if we had so many inconsistent categories that a manual replacement is simply not feasible? We can easily do that with string similarity! # # Say we have DataFrame named survey containing answers from respondents from the state of New York and California asking them how likely are you to move on a scale of 0 to 5. # # ```python # print(survey['state'].unique()) # ``` # ``` # id state # 0 California # 1 Cali # 2 Calefornia # 3 Calefornie # 4 Californie # 5 Calfornia # 6 Calefernia # 7 New York # 8 New York City # ``` # # The state field was free text and contains hundreds of typos. Remapping them manually would take a huge amount of time. Instead, we'll use string similarity. # # ```python # catefories # ``` # ``` # state # 0 California # 1 New York # ``` # # We also have a category DataFrame containing the correct categories for each state. # # Let's collapse the incorrect categories with string matching! # ### Collapsing all of the state # # ```python # # For each correct category # for state in categories['state']: # # Find potential matches in states with typoes # matches = process.extract(state, survey['state'], # limit=survey.shape[0]) # # For each potential_match match # for potential_match in matches: # # If high similarity score # if potential_match[1] >= 80: # # Replace type with correct category # survey.loc[survey['state'] == potential_match[0], 'state'] = state # ``` # # We first create a for loop iterating over each correctly typed state in the categories DataFrame. # # For each state, we find its matches in the state column of the survey DataFrame, returning all possible matches by setting the limit argument of extract to the length of the survey DataFrame. # # Then we iterate over each potential match, isolating the ones only with a similarity score higher or equal than 80 with an if statement. # # Then for each of those returned strings, we replace it with the correct state using the loc method. # # ### Record linkage # Record linkage attempts to join data sources that have similarly fuzzy duplicate values, so that we end up with a final DataFrame with no duplicates by using string similarity # ### Minimum edit distance # Minimum edit distance is the minimum number of steps needed to reach from String A to String B, with the operations available being: # # **Insertion** of a new character. # **Deletion** of an existing character. # **Substitution** of an existing character. # **Transposition** of two existing consecutive characters. # # *What is the minimum edit distance from `'sign'` to `'sing'`, and which operation(s) gets you there?* # # 1. ~2 by substituting `'g'` with `'n'` and `'n'` with `'g'`.~ # 2. **1 by transposing `'g'` with `'n'`.** # 3. ~1 by substituting `'g'` with `'n'`.~ # 4. ~2 by deleting `'g'` and inserting a new `'g'` at the end.~ # # **Answer: 2.** Transposing the last two letters of `'sign'` is the easiest way to get to `'sing'` # # # # ## The cutoff point # The ultimate goal is to create a restaurant recommendation engine, but you need to first clean your data. # # This version of the `restaurants` DataFrame has been collected from many sources, where the `cuisine_type` column is riddled with typos, and should contain only `italian`, `american` and `asian` cuisine types. There are so many unique categories that remapping them manually isn't scalable, and it's best to use string similarity instead. # # Before doing so, you want to establish the cutoff point for the similarity score using the `fuzzywuzzy`'s `process.extract()` function by finding the similarity score of the most *distant* typo of each category. # + import pandas as pd restaurants = pd.read_csv('restaurants.csv') # - restaurants.head() # - Import `process` from `fuzzywuzzy`. # - Store the unique `cuisine_types` into `unique_types`. # - Calculate the similarity of `'asian'`, `'american'`, and `'italian'` to all possible `cuisine_types` using `process.extract()`, while returning all possible matches. # Import process from fuzzywuzzy from fuzzywuzzy import process # + jupyter={"outputs_hidden": true, "source_hidden": true} tags=[] # Store the unique values of cuisine_type in unique_types unique_types = restaurants['type'].unique() # Calculate similarity of 'asian' to all values of unique_types print(process.extract('asian', unique_types, limit = len(unique_types)), '\n') # Calculate similarity of 'american' to all values of unique_types print(process.extract('american', unique_types, limit=len(unique_types)), '\n') # Calculate similarity of 'italian' to all values of unique_types print(process.extract('italian', unique_types, limit=len(unique_types))) # + # Store the unique values of cuisine_type in unique_types unique_types = restaurants['cuisine_type'].unique() # Calculate similarity of 'asian' to all values of unique_types print(process.extract('asian', unique_types, limit = len(unique_types)), '\n') # Calculate similarity of 'american' to all values of unique_types print(process.extract('american', unique_types, limit=len(unique_types)), '\n') # Calculate similarity of 'italian' to all values of unique_types print(process.extract('italian', unique_types, limit=len(unique_types))) # - # output: # ``` # [('asian', 100), ('asiane', 91), ('asiann', 91), ('asiian', 91), ('asiaan', 91), ('asianne', 83), ('asiat', 80), ('italiann', 72), ('italiano', 72), ('italianne', 72), ('italian', 67), ('amurican', 62), ('american', 62), ('italiaan', 62), ('italiian', 62), ('itallian', 62), ('americann', 57), ('americano', 57), ('ameerican', 57), ('aamerican', 57), ('ameriican', 57), ('amerrican', 57), ('ammericann', 54), ('ameerrican', 54), ('ammereican', 54), ('america', 50), ('merican', 50), ('murican', 50), ('italien', 50), ('americen', 46), ('americin', 46), ('amerycan', 46), ('itali', 40)] # # [('american', 100), ('americann', 94), ('americano', 94), ('ameerican', 94), ('aamerican', 94), ('ameriican', 94), ('amerrican', 94), ('america', 93), ('merican', 93), ('ammericann', 89), ('ameerrican', 89), ('ammereican', 89), ('amurican', 88), ('americen', 88), ('americin', 88), ('amerycan', 88), ('murican', 80), ('asian', 62), ('asiane', 57), ('asiann', 57), ('asiian', 57), ('asiaan', 57), ('italian', 53), ('asianne', 53), ('italiann', 50), ('italiano', 50), ('italiaan', 50), ('italiian', 50), ('itallian', 50), ('italianne', 47), ('asiat', 46), ('itali', 40), ('italien', 40)] # # [('italian', 100), ('italiann', 93), ('italiano', 93), ('italiaan', 93), ('italiian', 93), ('itallian', 93), ('italianne', 88), ('italien', 86), ('itali', 83), ('asian', 67), ('asiane', 62), ('asiann', 62), ('asiian', 62), ('asiaan', 62), ('asianne', 57), ('amurican', 53), ('american', 53), ('americann', 50), ('asiat', 50), ('americano', 50), ('ameerican', 50), ('aamerican', 50), ('ameriican', 50), ('amerrican', 50), ('ammericann', 47), ('ameerrican', 47), ('ammereican', 47), ('america', 43), ('merican', 43), ('murican', 43), ('americen', 40), ('americin', 40), ('amerycan', 40)] # ``` # ### Question # Take a look at the output, what do you think should be the similarity cutoff point when remapping categories? # # 1. **80** # 2. ~70~ - (*Not quite, `'asian'` and `'italiann'` have a similarity score of ***72***, meaning `'italiann'` would be converted to `'asian'`.*) # 3. ~60~ - (*That's too low, and you risk converting a lot more categories than you should.*) # # **Answer: 1.** **80** is that sweet spot where you convert all incorrect typos without remapping incorrect categories. # ## Remapping categories II # In the last exercise, you determined that the distance cutoff point for remapping typos of `'american'`, `'asian'`, and `'italian'` cuisine types stored in the `cuisine_type` column should be **80**. # # In this exercise, you're going to put it all together by finding matches with similarity scores equal to or higher than 80 by using `fuzywuzzy.process`'s `extract()` function, for each correct cuisine type, and replacing these matches with it. Remember, when comparing a string with an array of strings using `process.extract()`, the output is a list of tuples where each is formatted like: # ``` # (closest match, similarity score, index of match) # ``` # - Return all of the unique values in the `cuisine_type` column of `restaurants`. # + jupyter={"outputs_hidden": true, "source_hidden": true} tags=[] # Inspect the unique values of the cuisine_type column print(restaurants['type'].unique()) # - # Inspect the unique values of the cuisine_type column print(restaurants['cuisine_type'].unique()) # ``` # ['america' 'merican' 'amurican' 'americen' 'americann' 'asiane' 'itali' 'asiann' 'murican' 'italien' 'italian' 'asiat' 'american' 'americano' 'italiann' 'ameerican' 'asianne' 'italiano' 'americin' 'ammericann' 'amerycan' 'aamerican' 'ameriican' 'italiaan' 'asiian' 'asiaan' 'amerrican' 'ameerrican' 'ammereican' 'asian' 'italianne' 'italiian' 'itallian'] # ``` # Looks like you will need to use some string matching to correct these misspellings. # # - As a first step, create a list of all possible `matches`, comparing `'italian'` with the restaurant types listed in the `cuisine_type` column. # + jupyter={"outputs_hidden": true, "source_hidden": true} tags=[] # Create a list of matches, comparing 'italian' with the cuisine_type column matches = process.extract('italian', restaurants['type'], limit=len(restaurants.type)) # Inspect the first 5 matches print(matches[0:5]) # + # Create a list of matches, comparing 'italian' with the cuisine_type column matches = process.extract('italian', restaurants['cuisine_type'], limit=len(restaurants.cuisine_type)) # Inspect the first 5 matches print(matches[0:5]) # - # ``` # [('italian', 100, 11), ('italian', 100, 25), ('italian', 100, 41), ('italian', 100, 47), ('italian', 100, 49)] # ``` # Now you're getting somewhere! Now you can iterate through `matches` to reassign similar entries. # # - Within the `for` loop, use an `if` statement to check whether the similarity score in each `match` is greater than or equal to 80. # - If it is, use `.loc` to select rows where `cuisine_type` in `restaurants` is equal to the current match (which is the first element of `match`), and reassign them to be `'italian'`. # Iterate through the list of matches to italian for match in matches: # Check whether the similarity score is greater than or equal to 80 if match[1] >= 80: # Select all rows where the cuisine_type is spelled this way, and set them to the correct cuisine restaurants.loc[restaurants['type'] == match[0]] = 'italian' # Finally, you'll adapt your code to work with every restaurant type in `categories`. # # - Using the variable `cuisine` to iterate through `categories`, embed your code from the previous step in an outer `for` loop. # - Inspect the final result. categories = ['italian', 'asian', 'american'] # + jupyter={"outputs_hidden": true, "source_hidden": true} tags=[] # Iterate through categories for cuisine in categories: # Create a list of matches, comparing cuisine with the cuisine_type column matches = process.extract(cuisine, restaurants['type'], limit=len(restaurants.type)) # Iterate through the list of matches for match in matches: # Check whether the similarity score is greater than or equal to 80 if match[1] >= 80: # If it is, select all rows where the cuisine_type is spelled this way, and set them to the correct cuisine restaurants.loc[restaurants['type'] == match[0]] = cuisine # Inspect the final result print(restaurants['type'].unique()) # + # Iterate through categories for cuisine in categories: # Create a list of matches, comparing cuisine with the cuisine_type column matches = process.extract(cuisine, restaurants['cuisine_type'], limit=len(restaurants.cuisine_type)) # Iterate through the list of matches for match in matches: # Check whether the similarity score is greater than or equal to 80 if match[1] >= 80: # If it is, select all rows where the cuisine_type is spelled this way, and set them to the correct cuisine restaurants.loc[restaurants['cuisine_type'] == match[0]] = cuisine # Inspect the final result print(restaurants['cuisine_type'].unique()) # - # output: # ``` # ['american' 'asian' 'italian'] # ``` # *All your cuisine types are properly mapped. Now you'll build on string similarity, by jumping into record linkage.* # --- # ## Generating pairs # ### Record linkage # Record linkage is the act of linking data from different sources regarding the same entity. Generally, we clean two or more DataFrames, generate pairs of potentially matching records, score these pairs according to string similarity and other similarity metrics, and link them. All of these steps can be achieved with the `recordlinkage` package. # # ### DataFrames # There are two DataFrames, census_A, and census_B, containing data on individuals throughout the states. # ```python # census_A # ``` # ``` # given_name surname date_of_birth suburb state address_1 # rec_id # rec-1070-org michaela neumann 19151111 <NAME> cal stanley street # rec-1016-org courtney painter 19161214 richlands txs pinkerton circuit # ``` # ```python # census_B # ``` # ``` # given_name surname date_of_birth suburb state address_1 # rec_id # rec-561-dup-0 elton NaN 19651013 windermere ny light setreet # rec-2642-dup-0 mitchell maxon 19390212 north ryde cal edkins street # ``` # # We want to merge them while avoiding duplication using record linkage, since they are collected manually and are prone to typos, there are no consistent IDs between them. # ### Generating pairs # We first want to generate pairs between both DataFrames. Ideally, we want to generate all possible pairs between our DataFrames, but what if we had big DataFrames and ended up having to generate millions if not billions of pairs? It wouldn't prove scalable and could seriously hamper development time. # # ### Blocking # This is where we apply what we call blocking, which creates pairs based on a matching column, which is in this case, the state column, reducing the number of possible pairs. # # ### Generating pairs # To do this, we first start off by importing recordlinkage. We then use the recordlinkage dot Index function, to create an indexing object. This essentially is an object we can use to generate pairs from our DataFrames. To generate pairs blocked on state, we use the block method, inputting the state column as input. # ```python # # Import recordlinkage # import recordlinkage # # # Create indexing object # indexer = recordlinkage.Index() # # # Generate pairs blocked on state # indexer.block('state') # pairs = indexer.index(census_A, census_B) # ``` # # Once the indexer object has been initialized, we generate our pairs using the dot index method, which takes in the two dataframes. # # ```python # print(pairs) # ``` # ``` # MultiIndex(levels=[['rec-1007-org', 'rec-1016-org', 'rec-1054-org', 'rec-1066-org', 'rec-1070-org', 'rec-1075-org', 'rec-1080-org', 'rec-110-org', 'rec-1146-org', 'rec-1157-org', 'rec-1165-org', 'rec-1185-org', 'rec-1234-org', 'rec-1271-org', 'rec-1280-org', ...... # 66, 14, 13, 18, 34, 39, 0, 16, 80, 50, 20, 69, 28, 25, 49, 77, 51, 85, 52, 63, 74, 61, 83, 91, 22, 26, 55, 84, 11, 81, 97, 56, 27, 48, 2, 64, 5, 17, 29, 60, 72, 47, 92, 12, 95, 15, 19, 57, 37, 70, 94]], names=['rec_id_1', 'rec_id_2']) # ``` # # The resulting object, is a pandas multi index object containing pairs of row indices from both DataFrames, which is a fancy way to say it is an array containing possible pairs of indices that makes it much easier to subset DataFrames on. # ### Comparing the DataFrames # Since we've already generated our pairs, it's time to find potential matches. # # ```python # # Generate the pairs # pairs = indexer.index(census_A, census_B) # # Create a Compare object # compare_cl = recordlinkage.Compare() # # # Find exact matches for pairs of date_of_birth and state # compare_cl.exact('date_of_birth', 'date_of_birth', label='date_of_birth') # compare_cl.exacy('state', 'state', label='state') # # Find similar matches for pairs of surname and address_1 using string similarity # compare_cl.string('surname', 'surname', threshold=0.85, label='surname') # compare_cl.string('address_1', 'address_1', threshold=0.85, label='address_1') # # # Find matches # potential_matches = compare_cl.compute(pairs, census_A, census_B) # ``` # # We first start by creating a comparison object using the recordlinkage dot compare function. This is similar to the indexing object we created while generating pairs, but this one is responsible for assigning different comparison procedures for pairs. Let's say there are columns for which we want exact matches between the pairs. # # To do that, we use the exact method. It takes in the column name in question for each DataFrame, which is in this case date_of_birth and state, and a label argument which lets us set the column name in the resulting DataFrame. # # Now in order to compute string similarities between pairs of rows for columns that have fuzzy values, we use the dot string method, which also takes in the column names in question, the similarity cutoff point in the threshold argument, which takes in a value between 0 and 1, which we here set to 0.85. # # Finally to compute the matches, we use the compute function, which takes in the possible pairs, and the two DataFrames in question. # # Note that you need to always have the same order of DataFrames when inserting them as arguments when generating pairs, comparing between columns, and computing comparisons. # ### Finding matching pairs # The output is a multi index DataFrame, where the first index is the row index from the first DataFrame, or census A, and the second index is a list of all row indices in census B. The columns are the columns being compared, with values being 1 for a match, and 0 for not a match. # # ```python # print(potential_matches) # ``` # ``` # date_of_birth state surname address_1 # rec_id_1 rec_id_2 # rec-1070-org rec-561-dup-0 0 1 0.0 0.0 # rec-2642-dup-0 0 1 0.0 0.0 # rec-608-dup-0 0 1 0.0 0.0 # ... # rec-1631-org rec-4070-dup-0 0 1 0.0 0.0 # rec-4862-dup-0 0 1 0.0 0.0 # rec-629-dup-0 0 1 0.0 0.0 # ... # ``` # # To find potential matches, we just filter for rows where the sum of row values is higher than a certain threshold. Which in this case higher or equal to 2. But we'll dig deeper into these matches and see how to use them to link our census DataFrames in the next lesson. # ```python # potential_matches[pontential_matches.sum(axis = 1) => 2] # ``` # ``` # date_of_birth state surname address_1 # rec_id_1 rec_id_2 # rec-4878-org rec-4878-dup-0 1 1 1.0 0.0 # rec-417-org rec-2867-dup-0 0 1 0.0 1.0 # rec-3967-org rec-394-dup-0 0 1 1.0 0.0 # rec-1373-org rec-4051-dup-0 0 1 1.0 0.0 # rec-802-dup-0 0 1 1.0 0.0 # rec-3540-org rec-470-dup-0 0 1 1.0 0.0 # ``` # # ## To link or not to link? # Similar to joins, record linkage is the act of linking data from different sources regarding the same entity. But unlike joins, record linkage does not require exact matches between different pairs of data, and instead can find close matches using string similarity. This is why record linkage is effective when there are no common unique keys between the data sources you can rely upon when linking data sources such as a unique identifier. # # In this exercise, you will classify each card whether it is a traditional join problem, or a record linkage one. # # - Classify each card into a problem that requires record linkage or regular joins. # # Record linkage | Regular joins # :---|:--- # Two customer DataFrames containing names and address, one with a unique identifier per customer, one without. | Two basketball DataFrames with a common unique identifier per game. # Using an `address` column to join two DataFrames, with the address in each DataFrame being formatted slightly differently. | Consolidationg two DataFrames containing details on the courses, with each course having its own unique indentifier. # Merging two basketball DataFrames, with columns `team_A`, `team_B`, and `time` and differently formatted team names between each DataFrame. | # # *Don't make things more complicated than they need to be: record linkage is a powerful tool, but it's more complex than using a traditional join.* # ## Pairs of restaurants # In the last lesson, you cleaned the `restaurants` dataset to make it ready for building a restaurants recommendation engine. You have a new DataFrame named `restaurants_new` with new restaurants to train your model on, that's been scraped from a new data source. # # You've already cleaned the `cuisine_type` and `city` columns using the techniques learned throughout the course. However you saw duplicates with typos in restaurants names that require record linkage instead of joins with `restaurants`. # # In this exercise, you will perform the first step in record linkage and generate possible pairs of rows between `restaurants` and `restaurants_new`. # # - Instantiate an indexing object by using the `Index()` function from `recordlinkage`. # - Block your pairing on `cuisine_type` by using `indexer`'s' `.block()` method. # - Generate pairs by indexing `restaurants` and `restaurants_new` in that order. import recordlinkage restaurants_new = pd.read_csv('restaurants_new.csv') restaurants_new.head() # + # Create an indexer and object and find possible pairs indexer = recordlinkage.Index() # Block pairing on cuisine_type indexer.block('type') # Generate pairs pairs = indexer.index(restaurants, restaurants_new) # - # ### Question # Now that you've generated your pairs, you've achieved the first step of record linkage. What are the steps remaining to link both restaurants DataFrames, and in what order? # # 1. **Compare between columns, score the comparison, then link the DataFrames.** # 2. ~Clean the data, compare between columns, link the DataFrames, then score the comparison.~ # 3. ~Clean the data, compare between columns, score the comparison, then link the DataFrames.~ # # **Answer: 1.** Cleaning data precedes the pair generation phase, and linking DataFrames is the final step. # ## Similar restaurants # In the last exercise, you generated pairs between `restaurants` and `restaurants_new` in an effort to cleanly merge both DataFrames using record linkage. # # When performing record linkage, there are different types of matching you can perform between different columns of your DataFrames, including exact matches, string similarities, and more. # # Now that your pairs have been generated and stored in `pairs`, you will find exact matches in the `city` and `cuisine_type` columns between each pair, and similar strings for each pair in the `rest_name` column. # # - Instantiate a comparison object using the `recordlinkage.Compare()` function. # Create a comparison object comp_cl = recordlinkage.Compare() # - Use the appropriate `comp_cl` method to find exact matches between the `city` and `cuisine_type` columns of both DataFrames. # - Use the appropriate `comp_cl` method to find similar strings with a `0.8` similarity threshold in the `rest_name` column of both DataFrames. # + # Create a comparison object comp_cl = recordlinkage.Compare() # Find exact matches on city, cuisine_types comp_cl.exact('city', 'city', label='city') comp_cl.exact('type', 'type', label='type') # Find similar matches of rest_name comp_cl.string('rest_name', 'rest_name', label='name', threshold=0.8) # - # - Compute the comparison of the pairs by using the `.compute()` method of `comp_cl`. # Get potential matches and print potential_matches = comp_cl.compute(pairs, restaurants, restaurants_new) print(potential_matches) # output: # ``` # city cuisine_type name # 0 0 0 1 0.0 # 1 0 1 0.0 # 7 0 1 0.0 # 12 0 1 0.0 # 13 0 1 0.0 # ... ... ... ... # 40 18 0 1 0.0 # 281 18 0 1 0.0 # 288 18 0 1 0.0 # 302 18 0 1 0.0 # 308 18 0 1 0.0 # # [3631 rows x 3 columns] # ``` # ### Question # Print out `potential_matches`, the columns are the columns being compared, with values being 1 for a match, and 0 for not a match for each pair of rows in your DataFrames. To find potential matches, you need to find rows with more than matching value in a column. You can find them with # ```python # potential_matches[potential_matches.sum(axis = 1) >= n] # ``` # # Where `n` is the minimum number of columns you want matching to ensure a proper duplicate find, what do you think should the value of `n` be? # # 1. **3 because I need to have matches in all my columns.** # 2. ~2 because matching on any of the 2 columns or more is enough to find potential duplicates.~ (If `n` is set to 2, then you will get duplicates for all restaurants with the same cuisine type in the same city.) # 3. ~1 because matching on just 1 column like the restaurant name is enough to find potential duplicates.~ (What if you had restaurants with the same name in different cities?) # # **Answer: 1.** For this example, tightening your selection criteria will ensure good duplicate finds. In the next lesson, you're gonna build on what you learned to link these two DataFrames. potential_matches[potential_matches.sum(axis = 1) >= 3] # output: # ``` # city cuisine_type name # 0 40 1 1 1.0 # 1 28 1 1 1.0 # 2 74 1 1 1.0 # 3 1 1 1 1.0 # 4 53 1 1 1.0 # 8 43 1 1 1.0 # 9 50 1 1 1.0 # 13 7 1 1 1.0 # 14 67 1 1 1.0 # 17 12 1 1 1.0 # 20 20 1 1 1.0 # 21 27 1 1 1.0 # 5 65 1 1 1.0 # 7 79 1 1 1.0 # 12 26 1 1 1.0 # 18 71 1 1 1.0 # 6 73 1 1 1.0 # 10 75 1 1 1.0 # 11 21 1 1 1.0 # 16 57 1 1 1.0 # 19 47 1 1 1.0 # 15 55 1 1 1.0 # ``` # --- # ## Linking DataFrames # ### Potential matches # Let's look closely at the potential matches. It is a multi-index DataFrame, where we have two index columns, record id 1, and record id 2. # ```python # potential_matches # ``` # ``` # date_of_birth state surname address_1 # rec_id_1 rec_id_2 # rec-1070-org rec-561-dup-0 0 1 0.0 0.0 # rec-2642-dup-0 0 1 0.0 0.0 # rec-608-dup-0 0 1 0.0 0.0 # ... ... ... ... ... # rec-1631-org rec-1697-dup-0 0 1 0.0 0.0 # rec-4404-dup-0 0 1 0.0 0.0 # rec-3780-dup-0 0 1 0.0 0.0 # ... ... ... ... ... # ``` # The first index column, stores indices from census A. The second index column, stores all possible indices from census_B, for each row index of census_A. The columns of our potential matches are the columns we chose to link both DataFrames on, where the value is 1 for a match, and 0 otherwise. # # ### Probable matches # The first step in linking DataFrames, is to isolate the potentially matching pairs to the ones we're pretty sure of. We saw how to do this in the previous lesson, by subsetting the rows where the row sum is above a certain number of columns, in this case 3. # ```python # matches = potential_matches[potential_matches.sum(axis = 1) >= 3] # ``` # ``` # date_of_birth state surname address_1 # rec_id_1 rec_id_2 # rec-2404-org rec-2404-dup-0 1 1 1.0 1.0 # rec-4178-org rec-4178-dup-0 1 1 1.0 1.0 # rec-1054-org rec-1054-dup-0 1 1 1.0 1.0 # ... ... ... ... ... # rec-1234-org rec-1234-dup-0 1 1 1.0 1.0 # rec-1271-org rec-1271-dup-0 1 1 1.0 1.0 # ``` # The output is row indices between census A and census B that are most likely duplicates. The next step is to extract the one of the index columns, and subsetting its associated DataFrame to filter for duplicates. # # Here we choose the second index column, which represents row indices of `census B`. We want to extract those indices, and subset `census_B` on them to remove duplicates with `census_A` before appending them together. # ### Get the indices # ```python # matches.index # ``` # ``` # MultiIndex(levels=[['rec-1007-org', 'rec-1016-org', 'rec-1054-org', 'rec-1066-org', 'rec-1070-org', 'rec-1075-org', 'rec-1080-org', 'rec-110-org', ... # ``` # We can access a DataFrame's index using the index attribute. Since this is a multi index DataFrame, it returns a multi index object containing pairs of row indices from `census_A` and `census_B` respectively. # ```python # # Get indices from census_B only # duplicate_rows = matches.index.get_level_values(1) # print(census_B_index) # ``` # ``` # MultiIndex(levels=[['rec-2404-dup-0', 'rec-4178-dup-0', 'rec-1054-dup-0', 'rec-4663-dup-0', 'rec-485-dup-0', 'rec-2950-dup-0', 'rec-1234-dup-0', ... 'rec-299-oduprg-0']) # ``` # We want to extract all `census_B` indices, so we chain it with the get_level_values method, which takes in which column index we want to extract its values. We can either input the index column's name, or its order, which is in this case 1. # ### Linking DataFrames # ```python # # Finding duplicates in census_B # census_B_duplicates = census_B[census_B.index.isin(duplicate_rows)] # # # Finding new rows in census_B # census_B_new = census_B[~census_B.index.isin(duplicate_rows)] # ``` # To find the duplicates in `census B`, we simply subset on all indices of `census_B`, with the ones found through record linkage. You can choose to examine them further for similarity with their duplicates in `census_A`, but if you're sure of your analysis, you can go ahead and find the non duplicates by repeating the exact same line of code, except by adding a tilde at the beginning of your subset. # # ```python # # Link the DataFrames # full_census = census_A.append(census_B_new) # ``` # Now that you have your non duplicates, all you need is a simple append using the DataFrame append method of census A, and you have your linked Data. # To recap, what we did was build on top of our previous work in generating pairs, comparing across columns and finding potential matches. # # We then isolated all possible matches, where there are matches across 3 columns or more, ensuring we tightened our search for duplicates across both DataFrames before we link them. # # Extracted the row indices of `census_B` where there are duplicates. Found rows of `census_B` where they are not duplicated with `census_A` by using the tilde symbol. And linked both DataFrames for full census results. # ```python # # Import recordlinkage and generate pairs and compare across columns # . . . # # Generate potential matches # potential_matches = compare_cl.compute(full_pairs, census_A, census_B) # # # Isolate matches with matching values for 3 or more columns # matches = potential_matches[potential_matches.sum(axis = 1) >= 3] # # # Get index for matching census_B rows only # duplicate_rows = matches.index.get_level_values(1) # # # Finding new rows in census_B # census_B_new = census_B[~census_B.index.isin(duplicate_rows)] # # # Link the DataFrame # full_census = census_A.append(census_B_new) # ``` # ## Getting the right index # Here's a DataFrame named `matches` containing potential matches between two DataFrames, `users_1` and `users_2`. Each DataFrame's row indices is stored in `uid_1` and `uid_2` respectively. # ``` # first_name address_1 address_2 marriage_status date_of_birth # uid_1 uid_2 # 0 3 1 1 1 1 0 # ... ... ... ... ... ... # ... ... ... ... ... ... # 1 3 1 1 1 1 0 # ... ... ... ... ... ... # ... ... ... ... ... ... # ``` # How do you extract all values of the `uid_1` index column? # # 1. **`matches.index.get_level_values(0)`** # 2. ~`matches.index.get_level_values(1)`~ # 3. **`matches.index.get_level_values('uid_1')`** # # **Answer: Both 1 and 3 are correct.** # ## Linking them together! # In the last lesson, you've finished the bulk of the work on your effort to link `restaurants` and `restaurants_new`. You've generated the different pairs of potentially matching rows, searched for exact matches between the `cuisine_type` and `city` columns, but compared for similar strings in the `rest_name` column. You stored the DataFrame containing the scores in `potential_matches`. # # Now it's finally time to link both DataFrames. You will do so by first extracting all row indices of `restaurants_new` that are matching across the columns mentioned above from `potential_matches`. Then you will subset `restaurants_new` on these indices, then append the non-duplicate values to restaurants. # # - Isolate instances of `potential_matches` where the row sum is above or equal to 3 by using the `.sum()` method. # - Extract the second column index from `matches`, which represents row indices of matching record from `restaurants_new` by using the `.get_level_values()` method. # - Subset `restaurants_new` for rows that are not in `matching_indices`. # - Append `non_dup` to `restaurants`. # + # Isolate potential matches with row sum >=3 matches = potential_matches[potential_matches.sum(axis = 1) >= 3] # Get values of second column index of matches matching_indices = matches.index.get_level_values(1) # Subset restaurants_new based on non-duplicate values non_dup = restaurants_new[~restaurants_new.index.isin(matching_indices)] # Append non_dup to restaurants full_restaurants = restaurants.append(non_dup) print(full_restaurants) # - # output: # ``` # rest_name rest_addr city phone cuisine_type # 0 arnie morton's of chicago 435 s. la cienega blv . los angeles 3102461501 american # 1 art's delicatessen 12224 ventura blvd. studio city 8187621221 american # 2 campanile 624 s. la brea ave. los angeles 2139381447 american # 3 fenix 8358 sunset blvd. west hollywood 2138486677 american # 4 grill on the alley 9560 dayton way los angeles 3102760615 american # .. ... ... ... ... ... # 76 don 1136 westwood blvd. westwood 3102091422 italian # 77 feast 1949 westwood blvd. west la 3104750400 chinese # 78 mulberry 17040 ventura blvd. encino 8189068881 pizza # 80 jiraffe 502 santa monica blvd santa monica 3109176671 californian # 81 martha's 22nd street grill 25 22nd st. hermosa beach 3103767786 american # # [396 rows x 5 columns] # ``` # *Linking the DataFrames is arguably the most straightforward step of record linkage. You are now ready to get started on that recommendation engine.* import re x = "123-456-789" # Is x a valid phone number? print(bool(re.compile("\d{3}-\d{3}-\d{4}").match(x)))
Data Analyst with Python/11_Cleaning_Data_in_Python/11_4_Record linkage.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 h5py import numpy as np import cartopy.crs as ccrs import numpy as np import matplotlib.pyplot as plt from utils import transform_coord from utils import make_grid from utils import mad_std from utils import spatial_filter from utils import interp2d from utils import tiffread from utils import binning from scipy.ndimage.filters import generic_filter import re import pyproj datapath='/home/jovyan/shared/surface_velocity/FIS_ATL06_small/processed_ATL06_20191129105346_09700511_003_01.h5' # !h5ls -r /home/jovyan/shared/surface_velocity/FIS_ATL06_small/processed_ATL06_20191129105346_09700511_003_01.h5 with h5py.File(datapath, 'r') as f: segment_id = f['/gt2l/land_ice_segments/segment_id'][:] print(segment_id) # /gt2l/land_ice_segments/segment_id def atl06_to_dict(filename, beam, field_dict=None, index=None, epsg=None): """ Read selected datasets from an ATL06 file Input arguments: filename: ATl06 file to read beam: a string specifying which beam is to be read (ex: gt1l, gt1r, gt2l, etc) field_dict: A dictinary describing the fields to be read keys give the group names to be read, entries are lists of datasets within the groups index: which entries in each field to read epsg: an EPSG code specifying a projection (see www.epsg.org). Good choices are: for Greenland, 3413 (polar stereographic projection, with Greenland along the Y axis) for Antarctica, 3031 (polar stereographic projection, centered on the Pouth Pole) Output argument: D6: dictionary containing ATL06 data. Each dataset in dataset_dict has its own entry in D6. Each dataset in D6 contains a numpy array containing the data """ if field_dict is None: field_dict={None:['latitude','longitude','h_li', 'atl06_quality_summary'],\ 'ground_track':['x_atc','y_atc'],\ 'fit_statistics':['dh_fit_dx', 'dh_fit_dy']} D={} file_re=re.compile('ATL06_(?P<date>\d+)_(?P<rgt>\d\d\d\d)(?P<cycle>\d\d)(?P<region>\d\d)_(?P<release>\d\d\d)_(?P<version>\d\d).h5') with h5py.File(filename,'r') as h5f: for key in field_dict: for ds in field_dict[key]: if key is not None: ds_name=beam+'/land_ice_segments/'+key+'/'+ds else: ds_name=beam+'/land_ice_segments/'+ds if index is not None: D[ds]=np.array(h5f[ds_name][index]) else: D[ds]=np.array(h5f[ds_name]) if '_FillValue' in h5f[ds_name].attrs: bad_vals=D[ds]==h5f[ds_name].attrs['_FillValue'] D[ds]=D[ds].astype(float) D[ds][bad_vals]=np.NaN D['data_start_utc'] = h5f['/ancillary_data/data_start_utc'][:] D['delta_time'] = h5f['/gt2l/land_ice_segments/delta_time'][:] if epsg is not None: xy=np.array(pyproj.proj.Proj(epsg)(D['longitude'], D['latitude'])) D['x']=xy[0,:].reshape(D['latitude'].shape) D['y']=xy[1,:].reshape(D['latitude'].shape) temp=file_re.search(filename) D['rgt']=int(temp['rgt']) D['cycle']=int(temp['cycle']) D['beam']=beam return D ATL06_track = atl06_to_dict(datapath, 'gt2l', epsg=3031) ATL06_track.keys() # + print(ATL06_track['delta_time']) print(ATL06_track['data_start_utc']) plt.plot(ATL06_track['delta_time'], ATL06_track['h_li']) # plt.scatter(ATL06_track['x'],ATL06_track['y'],1,ATL06_track['h_li']) # plt.colorbar() # - # Try fittopo.py timevector = ATL06_track['delta_time'] - ATL06_track['delta_time'][0] import datetime # logic: turn into decimal years, somehow # !python fittopo.py -h # t_year is decimal years # !python ./fittopo.py /home/jovyan/shared/surface_velocity/FIS_ATL06_small/processed_ATL06_20191129105346_09700511_003_01.h5 -d 1 1 -r 1.0 -q 3 -i 5 -z 10 -m 100 \ # -k 2 -t 2020 -j 3031 -v lon lat t_year h_li -s 10 -p
notebooks/remove_static_surface.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 # --- # ### Wigner function # # Wigner distribution function gives the phase space distribution of a function. <br> # The definition is as follows, as per Advances in Optics and Photonics 3, 272โ€“365 (2011) : <br><br> # # $W_{f}(p,q) = \left(\dfrac{|K|}{2\pi}\right)^{N}\int f^{*}\left(q-\dfrac{q^{'}}{2}\right) f\left(q+\dfrac{q^{'}}{2}\right)exp(-iKq^{'}.p)d^{N}q^{'}$<br><br> # # ### Implementation # This will be implemented in two steps. First the Ambiguity function will be calclualted.<br> # Now, the WDF is just the Fourier Transform of the AF (implemented via fft) import numpy as np import matplotlib.pyplot as plt import scipy.signal as scisig from tqdm import tqdm from numba import njit,prange N = 500 f = np.zeros(N,dtype=np.complex128) x = np.linspace(-1e-6,1e-6,N) f[:] = 1+1j*0 f[:int(N/4)]=0+1j*0 f[int(3*N/4):]=0+1j*0 plt.plot(x*1e6,np.abs(f),'b-') plt.plot(x*1e6,np.angle(f),'g*') plt.ylabel('f') plt.xlabel('x in um') plt.title('Signal') plt.show() scale_factor = 3 #Scale domain by this much # Assuming the domain is symmetrical, stretch on both sides domain_real = np.linspace(scale_factor*x[0],scale_factor*x[-1],scale_factor*N) # Test function to verify positive and negative shifting of the original signal # on a scaled domain def f1(f,f_,y,domain): i = int((y-domain[0])/(domain[1]-domain[0])) f_[:] = 0 N = len(f) f_[i-int(N/2):i+int(N/2)] = f return f_ z1 = np.zeros(scale_factor*N,dtype=np.complex128) z2 = np.zeros(scale_factor*N,dtype=np.complex128) q1 = x[0] q2 = x[-1] z1 = f1(f,z1,q1,domain_real) z2 = f1(f,z2,q2,domain_real) fig,ax1 = plt.subplots(1,1) ax1.plot(domain_real,np.abs(z1),'b') ax1.tick_params('y', colors='b') ax1.set_ylabel('z1') ax2 = ax1.twinx() ax2.plot(domain_real,np.abs(z2),'g') ax2.tick_params('y', colors='g') ax2.set_ylabel('z2') ax1.set_xlabel('domain') fig.suptitle('Shifted versions of the signal on the scaled domain') plt.show() # Computer the ambiguity function row by row. def fill_AF(af,sig,domain,scale_factor,N): q1_vals = np.linspace(domain[0],domain[-1],scale_factor*N) for i in prange(scale_factor*N): q1 = q1_vals[i] z1 = np.zeros(scale_factor*N,dtype=np.complex128) z2 = np.zeros(scale_factor*N,dtype=np.complex128) i = int((q1/2-domain[0])/(domain[1]-domain[0])) z1[:] = 0 z1[i-int(N/2):i+int(N/2)] = sig i = int((-q1/2-domain[0])/(domain[1]-domain[0])) z2[:] = 0 z2[i-int(N/2):i+int(N/2)] = sig af[:,i] = z1*z2 AF = np.zeros((scale_factor*N,scale_factor*N),dtype=np.complex128) fill_AF(AF,f,domain_real,scale_factor,N) WDF = np.fft.fftshift(np.fft.fft(AF),axes=1) plt.rcParams["figure.figsize"] = (8,8) N1 = int(scale_factor*N/2) n1 = 250 fig,(ax1,ax2) = plt.subplots(1,2) ax1.contour(np.abs(AF)[N1-n1:N1+n1,N1-n1:N1+n1],50) ax1.set_title('AF') ax2.contour(np.abs(WDF)[N1-n1:N1+n1,N1-n1:N1+n1],50) ax2.set_title('WDF') fig.suptitle('AF/WDF of the signal') plt.show() energy = 1000 wavel = (1240/energy)*10**(-9) pi = np.pi L_in = x[-1] - x[0] from xwp.spectral_1d import propTF z = 4e-6 sampling = L_in/N1 critical = (wavel*z/L_in) if sampling>critical: print('Use TF') else : print('Use IR/1FT') print('Fresnel Number :', (L_in**2)/(wavel*z)) out,L_out = propTF(f,L_in/N1,L_in,wavel,z) plt.plot(np.abs(out)) plt.show() AF = np.zeros((scale_factor*N,scale_factor*N),dtype=np.complex128) domain_real = np.linspace(-L_out/2*scale_factor,L_out/2*scale_factor,scale_factor*N,) fill_AF(AF,out,domain_real,scale_factor,N) WDF = np.fft.fftshift(np.fft.fft(AF),axes=1) N1 = int(scale_factor*N/2) n1 = 250 fig,(ax1,ax2) = plt.subplots(1,2) ax1.contour(np.abs(AF)[N1-n1:N1+n1,N1-n1:N1+n1],50) ax1.set_title('AF') ax2.contour(np.abs(WDF)[N1-n1:N1+n1,N1-n1:N1+n1],50) ax2.set_title('WDF') fig.suptitle('AF/WDF of Fourier transform of the signal') plt.show()
notebooks/wigner_function/wdf_fresnel_prop.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:herschelhelp_internal] # language: python # name: conda-env-herschelhelp_internal-py # --- # # Extended sources in SPIRE maps # # This notebook was originally written by <NAME> to investigate the possibility of using XID+ to get flux posterior distributions for resolved objects in the far infrared. This is to be done by using fitted profiles from optical images. # + import warnings from matplotlib.cbook import MatplotlibDeprecationWarning warnings.simplefilter('ignore', MatplotlibDeprecationWarning) warnings.simplefilter('ignore', UserWarning) warnings.simplefilter('ignore', RuntimeWarning) warnings.simplefilter('ignore',UnicodeWarning) #warnings.simplefilter('ignore',VisibleDeprecationWarning) import numpy as np import scipy.stats as st import pylab as plt from pymoc import MOC import xidplus from xidplus.stan_fit import SPIRE from xidplus import posterior_maps as postmaps from astropy.io import fits from astropy import wcs from astropy.table import Table from astropy.convolution import Gaussian2DKernel from astropy.convolution import convolve from astropy.coordinates import SkyCoord from astropy import units as u import pickle import seaborn as sns import pandas as pd sns.set(color_codes=True) # %matplotlib inline import aplpy # + hdulist_250=fits.open('./data/XMM-LSS-NEST_image_250_SMAP_v6.0.fits') im250phdu=hdulist_250[0].header im250hdu=hdulist_250[1].header im250=hdulist_250[1].data*1.0E3 nim250=hdulist_250[2].data*1.0E3 w_250 = wcs.WCS(hdulist_250[1].header) pixsize250=3600.0*w_250.wcs.cd[1,1] #pixel size (in arcseconds) #hdulist.close() hdulist_350=fits.open('./data/XMM-LSS-NEST_image_350_SMAP_v6.0.fits') im350phdu=hdulist_350[0].header im350hdu=hdulist_350[1].header im350=hdulist_350[1].data*1.0E3 nim350=hdulist_350[2].data*1.0E3 w_350 = wcs.WCS(hdulist_350[1].header) pixsize350=3600.0*w_350.wcs.cd[1,1] #pixel size (in arcseconds) #hdulist.close() hdulist_500=fits.open('./data/XMM-LSS-NEST_image_500_SMAP_v6.0.fits') im500phdu=hdulist_500[0].header im500hdu=hdulist_500[1].header im500=hdulist_500[1].data*1.0E3 nim500=hdulist_500[2].data*1.0E3 w_500 = wcs.WCS(hdulist_500[1].header) pixsize500=3600.0*w_500.wcs.cd[1,1] #pixel size (in arcseconds) #hdulist.close() # - source=Table.read('./data/extended_source_test.xml') IRAC_sources=Table.read('./data/UDS_PACSxID24_v1.fits') IRAC_sources WISE_sources=Table.read('./data/WXSC.phot.clean_all.fits') # + #Set some color info cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 # + c = SkyCoord(ra=ra_zoom, dec=dec_zoom) catalog = SkyCoord(ra=WISE_sources['ra'], dec=WISE_sources['dec']) idx, d2d, d3d = c.match_to_catalog_sky(catalog) # - WISE_sources[idx] def extended_source(beta,r_e,x_0,y_0,x,y): source_grid=np.exp(-beta*((x-x_0)**2+(y-y_0)**2)/r_e) return source_grid xx, yy = np.meshgrid(np.arange(0,101), np.arange(0,101), sparse=True) # The extended source as seen in optical, MIPS, WISE band 4, and the SPIRE bands source # + def sersic(alpha,beta,x_0,y_0,x,y): source_grid=np.exp(-1*((((x-x_0)**2+(y-y_0)**2)**0.5)/alpha)**(1/beta)) return source_grid def extended_source(beta,r_e,x_0,y_0,x,y): source_grid=np.exp(-beta*((x-x_0)**2+(y-y_0)**2)/r_e) return source_grid # - bulge=sersic(WISE_sources[idx]['scale_1a'],WISE_sources[idx]['beta_1a'],50,50,xx,yy) #Raphael added first 50 to make it run disc=sersic(WISE_sources[idx]['scale_1b'],WISE_sources[idx]['beta_1b'],50,50,xx,yy) plt.imshow(disc) plt.colorbar() # + #pixsize array (size of pixels in arcseconds) pixsize=np.array([pixsize250,pixsize350,pixsize500]) #point spread function for the three bands prfsize=np.array([18.15,25.15,36.3]) ##---------fit using Gaussian beam----------------------- prf250=Gaussian2DKernel(prfsize[0]/2.355,x_size=101,y_size=101) prf250.normalize(mode='peak') prf350=Gaussian2DKernel(prfsize[1]/2.355,x_size=101,y_size=101) prf350.normalize(mode='peak') prf500=Gaussian2DKernel(prfsize[2]/2.355,x_size=101,y_size=101) prf500.normalize(mode='peak') pind250=np.arange(0,101,1)*1.0/pixsize[0] #get 250 scale in terms of pixel scale of map pind350=np.arange(0,101,1)*1.0/pixsize[1] #get 350 scale in terms of pixel scale of map pind500=np.arange(0,101,1)*1.0/pixsize[2] #get 500 scale in terms of pixel scale of map #convolved250 = convolve(prf250)[::6,::6] # - fig=plt.figure(figsize=(30,10)) plt.subplot(2,1,1) plt.imshow(convolve(bulge,prf250.array)[::6,::6],interpolation='nearest') plt.colorbar() plt.subplot(2,1,2) plt.imshow(convolve(disc,prf250.array)[::6,::6],interpolation='nearest') plt.colorbar() w_250.wcs_world2pix(ra_zoom,dec_zoom,0) def radial_profile(data, center): x, y = np.indices((data.shape)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.bincount(r.ravel(), data.ravel()) nr = np.bincount(r.ravel()) radialprofile = tbin / nr return radialprofile # + rad_profile = radial_profile(hdulist_250[1].data,w_250.wcs_world2pix(ra_zoom,dec_zoom,0)) fig, ax = plt.subplots() plt.plot(rad_profile[0:22], 'x-') # - # # Fit extended source with XID+ RA=np.concatenate((IRAC_sources['RA'].__array__(),source['RAJ2000'].__array__())) Dec=np.concatenate((IRAC_sources['Dec'].__array__(),source['DEJ2000'].__array__())) source # + prior_cat='IRAC' #---prior250-------- prior250=xidplus.prior(im250,nim250,im250phdu,im250hdu)#Initialise with map, uncertianty map, wcs info and primary header prior250.prior_cat(RA,Dec,prior_cat)#Set input catalogue prior250.prior_bkg(-5.0,5)#Set prior on background (assumes Guassian pdf with mu and sigma) #---prior350-------- prior350=xidplus.prior(im350,nim350,im350phdu,im350hdu) prior350.prior_cat(RA,Dec,prior_cat) prior350.prior_bkg(-5.0,5) #---prior500-------- prior500=xidplus.prior(im500,nim500,im500phdu,im500hdu) prior500.prior_cat(RA,Dec,prior_cat) prior500.prior_bkg(-5.0,5) # + #pixsize array (size of pixels in arcseconds) pixsize=np.array([pixsize250,pixsize350,pixsize500]) #point response function for the three bands prfsize=np.array([18.15,25.15,36.3]) #use Gaussian2DKernel to create prf (requires stddev rather than fwhm hence pfwhm/2.355) from astropy.convolution import Gaussian2DKernel ##---------fit using Gaussian beam----------------------- prf250=Gaussian2DKernel(prfsize[0]/2.355,x_size=101,y_size=101) prf250.normalize(mode='peak') prf350=Gaussian2DKernel(prfsize[1]/2.355,x_size=101,y_size=101) prf350.normalize(mode='peak') prf500=Gaussian2DKernel(prfsize[2]/2.355,x_size=101,y_size=101) prf500.normalize(mode='peak') pind250=np.arange(0,101,1)*1.0/pixsize[0] #get 250 scale in terms of pixel scale of map pind350=np.arange(0,101,1)*1.0/pixsize[1] #get 350 scale in terms of pixel scale of map pind500=np.arange(0,101,1)*1.0/pixsize[2] #get 500 scale in terms of pixel scale of map prior250.set_prf(prf250.array,pind250,pind250)#requires psf as 2d grid, and x and y bins for grid (in pixel scale) prior350.set_prf(prf350.array,pind350,pind350) prior500.set_prf(prf500.array,pind500,pind500) # - print( 'fitting ' + str(prior250.nsrc)+' sources \n') print( 'using ' + str(prior250.snpix)+', '+ str(prior250.snpix)+' and '+ str(prior500.snpix)+' pixels') # + moc=MOC() moc.read('./data/extended_source_test_MOC_rad4.fits') prior250.set_tile(moc) prior350.set_tile(moc) prior500.set_tile(moc) # - print( 'fitting '+ str(prior250.nsrc)+' sources \n') print( 'using ' + str(prior250.snpix)+', '+ str(prior350.snpix)+' and '+ str(prior500.snpix)+' pixels') prior250.get_pointing_matrix() prior350.get_pointing_matrix() prior500.get_pointing_matrix() prior250.upper_lim_map() prior350.upper_lim_map() prior500.upper_lim_map() # + fit=SPIRE.all_bands(prior250,prior350,prior500,iter=1500) # - posterior=xidplus.posterior_stan(fit,[prior250,prior350,prior500]) # + hdurep_250=postmaps.make_fits_image(prior250,prior250.sim) hdurep_350=postmaps.make_fits_image(prior350,prior350.sim) hdurep_500=postmaps.make_fits_image(prior500,prior500.sim) # + rep_maps=postmaps.replicated_maps([prior250, prior350, prior500],posterior,nrep=1000) # - rep_maps mod_map_250 = rep_maps[0] mod_map_350 = rep_maps[1] mod_map_500 = rep_maps[2] mod_map_array_250 = rep_maps[0] mod_map_array_350 = rep_maps[1] mod_map_array_500 = rep_maps[2] # + pval_250=np.empty_like(prior250.sim) for i in range(0,prior250.snpix): ind=mod_map_array_250[i,:]<prior250.sim[i] pval_250[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_250.shape[1])) pval_250[np.isposinf(pval_250)]=6 pval_350=np.empty_like(prior350.sim) for i in range(0,prior350.snpix): ind=mod_map_array_350[i,:]<prior350.sim[i] pval_350[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_350.shape[1])) pval_350[np.isposinf(pval_350)]=6 pval_500=np.empty_like(prior500.sim) for i in range(0,prior500.snpix): ind=mod_map_array_500[i,:]<prior500.sim[i] pval_500[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_500.shape[1])) pval_500[np.isposinf(pval_500)]=6 # + cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 fig = plt.figure(figsize=(30,30)) cfhtls=aplpy.FITSFigure('./data/W1+1+2.U.11023_11534_3064_3575.fits',figure=fig,subplot=(3,3,1)) cfhtls.show_colorscale(vmin=-10,vmax=200,cmap=cmap) cfhtls.recenter(ra_zoom, dec_zoom, radius=radius) mips=aplpy.FITSFigure('./data/wp4_xmm-lss_mips24_map_v1.0.fits.gz',figure=fig,subplot=(3,3,2)) mips.show_colorscale(vmin=-0.001,vmax=5,cmap=cmap) mips.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4=aplpy.FITSFigure('./data/L3a-0349m061_ac51-0349m061_ac51-w4-int-3_ra35.401958_dec-5.5213939_asec600.000.fits',figure=fig,subplot=(3,3,3)) wise_band4.show_colorscale(vmin=202,vmax=204,cmap=cmap) wise_band4.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250 = aplpy.FITSFigure(hdulist_250[1],figure=fig,subplot=(3,3,4)) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.add_colorbar() #real_250.show_markers(WISE_sources['ra'],WISE_sources['dec'], edgecolor='red', facecolor='red', # marker='o', s=40, alpha=0.5) real_350 = aplpy.FITSFigure(hdulist_350[1],figure=fig,subplot=(3,3,5)) real_350.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) real_350.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) #real_350.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_350.recenter(ra_zoom, dec_zoom, radius=radius) real_500 = aplpy.FITSFigure(hdulist_500[1],figure=fig,subplot=(3,3,6)) real_500.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_500.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_500.recenter(ra_zoom, dec_zoom, radius=radius) real_500.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) vmin=-6 vmax=6 cmap=sns.diverging_palette(220, 20,as_cmap=True) res250=aplpy.FITSFigure(hdurep_250[1],figure=fig,subplot=(3,3,7)) res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250.recenter(ra_zoom, dec_zoom, radius=radius) res350=aplpy.FITSFigure(hdurep_350[1],figure=fig,subplot=(3,3,8)) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_markers(prior350.sra, prior350.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res350.recenter(ra_zoom, dec_zoom, radius=radius) res500=aplpy.FITSFigure(hdurep_500[1],figure=fig,subplot=(3,3,9)) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_markers(prior500.sra, prior500.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250._data[prior250.sy_pix-np.min(prior250.sy_pix)-1,prior250.sx_pix-np.min(prior250.sx_pix)-1]=pval_250 res350._data[prior350.sy_pix-np.min(prior350.sy_pix)-1,prior350.sx_pix-np.min(prior350.sx_pix)-1]=pval_350 res500._data[prior500.sy_pix-np.min(prior500.sy_pix)-1,prior500.sx_pix-np.min(prior500.sx_pix)-1]=pval_500 res500.recenter(ra_zoom, dec_zoom, radius=radius) #res500.tick_labels.set_xformat('dd.dd') #res500.tick_labels.set_yformat('dd.dd') res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.add_colorbar() res250.colorbar.set_location('top') res350.add_colorbar() res350.colorbar.set_location('top') res500.add_colorbar() res500.colorbar.set_location('top') # + def ellipse(x,y,x0,y0,angle,a,b): dx=x-x0 dy=y-y0 rad=((dx*np.cos(angle)-dy*np.sin(angle))/a)**2 + ((dx*np.sin(angle)+dy*np.cos(angle))/b)**2 rad[rad<1.0]=1.0 rad[rad>1.0]=0.0 return rad from astropy.modeling.models import Sersic2D mod = Sersic2D(amplitude = 1, r_eff = 25, n=4, x_0=50, y_0=50, ellip=.5, theta=-1) # - wcs_temp = wcs.WCS(prior250.imhdu) source_pix_x,source_pix_y=wcs_temp.all_world2pix(ra_zoom,dec_zoom,0) a=WISE_sources[idx]['Riso']/pixsize[0] b=WISE_sources[idx]['ba']*a xx, yy = np.meshgrid(np.arange(0,WISE_sources[idx]['Riso']*3), np.arange(0,WISE_sources[idx]['Riso']*3)) import scipy.signal as signal extended_source_SMAP=signal.convolve(ellipse(xx,yy,xx.shape[1]/2.0,yy.shape[0]/2.0,WISE_sources[idx]['pa']*np.pi/180.0,a*pixsize[0],b*pixsize[0]),prf250.array,mode='same') plt.imshow(extended_source_SMAP) # + from astropy.modeling.models import Ellipse2D from astropy.coordinates import Angle theta = Angle(-1*WISE_sources[idx]['pa'], 'deg') e = Ellipse2D(amplitude=100., x_0=xx.shape[1]/2.0,y_0=yy.shape[0]/2.0, a=a*pixsize[0], b=b*pixsize[0], theta=theta.radian) plt.imshow(signal.convolve(e(xx,yy),prf250.array,mode='same')) # + from astropy.modeling.models import Sersic2D mod = Sersic2D(amplitude = 1.0, r_eff = WISE_sources[idx]['scale_1b'], n=WISE_sources[idx]['beta_1b'] ,x_0=xx.shape[1]/2.0,y_0=yy.shape[0]/2.0, ellip=1.0-WISE_sources[idx]['ba'], theta=theta.radian) plt.imshow(signal.convolve(mod(xx,yy),prf250.array,mode='same')) # - pind250_source=np.arange(0,WISE_sources[idx]['Riso']*3)*1.0/pixsize[0] ipx=source_pix_x+xx*1.0/pixsize[0]-pind250_source[-1]/2 ipy=source_pix_y+yy*1.0/pixsize[0]-pind250_source[-1]/2 from scipy import interpolate atemp = interpolate.griddata((ipx.ravel(), ipy.ravel()),extended_source_SMAP.ravel(), (prior250.sx_pix,prior250.sy_pix), method='nearest') # + def add_sersic_source(prior,source_no,angle,scale,beta,ba): from astropy.modeling.models import Sersic2D from astropy.coordinates import Angle import scipy.signal as signal import scipy.signal as signal wcs_temp = wcs.WCS(prior.imhdu) source_pix_x=prior.sx[source_no] source_pix_y=prior.sy[source_no] pixsize=np.absolute(prior.imhdu['CD2_2']*3600.0) mesh_length=np.max([prior.pindx.size,scale*5]) xx, yy = np.meshgrid(np.arange(0,mesh_length), np.arange(0,mesh_length)) theta = Angle(-1*angle, 'deg') mod = Sersic2D(amplitude = 1.0, r_eff =scale, n=beta,x_0=xx.shape[1]/2.0,y_0=yy.shape[0]/2.0, ellip=1.0-ba, theta=theta.radian) extended_source_SMAP=signal.convolve(mod(xx,yy),prior.prf,mode='same') pind_source=np.arange(0,mesh_length)*1.0/pixsize ipx=source_pix_x+xx*1.0/pixsize-pind_source[-1]/2 ipy=source_pix_y+yy*1.0/pixsize-pind_source[-1]/2 from scipy import interpolate atemp = interpolate.griddata((ipx.ravel(), ipy.ravel()),extended_source_SMAP.ravel(), (prior.sx_pix,prior.sy_pix), method='nearest') ind=atemp>0.001 ind_not_prev=prior.amat_col != source_no prior.amat_data=np.append(prior.amat_data[ind_not_prev],atemp[ind]) prior.amat_col=np.append(prior.amat_col[ind_not_prev],np.full(ind.sum(),source_no)) prior.amat_row=np.append(prior.amat_row[ind_not_prev],np.arange(0,prior.snpix,dtype=int)[ind]) return prior def add_extended_source(prior,source_no,angle,semi_major,semi_minor): import scipy.signal as signal wcs_temp = wcs.WCS(prior.imhdu) source_pix_x=prior.sx[source_no] source_pix_y=prior.sy[source_no] pixsize=np.absolute(prior.imhdu['CD2_2']*3600.0) a=semi_major/pixsize b=semi_minor/pixsize xx, yy = np.meshgrid(np.arange(0,semi_major*2.5), np.arange(0,semi_major*2.5)) extended_source_SMAP=signal.convolve(ellipse(xx,yy,xx.shape[1]/2.0,yy.shape[0]/2.0,angle*np.pi/180.0,a*pixsize,b*pixsize),prior.prf,mode='same') pind_source=np.arange(0,semi_major*2.5)*1.0/pixsize ipx=source_pix_x+xx*1.0/pixsize-pind_source[-1]/2 ipy=source_pix_y+yy*1.0/pixsize-pind_source[-1]/2 from scipy import interpolate atemp = interpolate.griddata((ipx.ravel(), ipy.ravel()),extended_source_SMAP.ravel(), (prior.sx_pix,prior.sy_pix), method='nearest') ind=atemp>0.001 ind_not_prev=prior.amat_col != source_no prior.amat_data=np.append(prior.amat_data[ind_not_prev],atemp[ind]) prior.amat_col=np.append(prior.amat_col[ind_not_prev],np.full(ind.sum(),source_no)) prior.amat_row=np.append(prior.amat_row[ind_not_prev],np.arange(0,prior.snpix,dtype=int)[ind]) return prior # - prior250.pindx.size prior250.imhdu['CD2_2']*3600.0 extended_source_conv=postmaps.make_fits_image(prior250,atemp) # + vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) real_250 = aplpy.FITSFigure(extended_source_conv[1]) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) #real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.add_colorbar() # - prior250.amat_data # # Fit with disc and bulge #Concatenate the extended source twice, once for bulge once for disc RA=np.concatenate((np.concatenate((IRAC_sources['RA'].__array__(),source['RAJ2000'].__array__())),source['RAJ2000'].__array__())) Dec=np.concatenate((np.concatenate((IRAC_sources['DEC'].__array__(),source['DEJ2000'].__array__())),source['DEJ2000'].__array__())) # + prior_cat='IRAC' #---prior250-------- prior250=xidplus.prior(im250,nim250,im250phdu,im250hdu)#Initialise with map, uncertianty map, wcs info and primary header prior250.prior_cat(RA,Dec,prior_cat)#Set input catalogue prior250.prior_bkg(-5.0,5)#Set prior on background (assumes Guassian pdf with mu and sigma) #---prior350-------- prior350=xidplus.prior(im350,nim350,im350phdu,im350hdu) prior350.prior_cat(RA,Dec,prior_cat) prior350.prior_bkg(-5.0,5) #---prior500-------- prior500=xidplus.prior(im500,nim500,im500phdu,im500hdu) prior500.prior_cat(RA,Dec,prior_cat) prior500.prior_bkg(-5.0,5) # + #pixsize array (size of pixels in arcseconds) pixsize=np.array([pixsize250,pixsize350,pixsize500]) #point response function for the three bands prfsize=np.array([18.15,25.15,36.3]) #use Gaussian2DKernel to create prf (requires stddev rather than fwhm hence pfwhm/2.355) from astropy.convolution import Gaussian2DKernel ##---------fit using Gaussian beam----------------------- prf250=Gaussian2DKernel(prfsize[0]/2.355,x_size=101,y_size=101) prf250.normalize(mode='peak') prf350=Gaussian2DKernel(prfsize[1]/2.355,x_size=101,y_size=101) prf350.normalize(mode='peak') prf500=Gaussian2DKernel(prfsize[2]/2.355,x_size=101,y_size=101) prf500.normalize(mode='peak') pind250=np.arange(0,101,1)*1.0/pixsize[0] #get 250 scale in terms of pixel scale of map pind350=np.arange(0,101,1)*1.0/pixsize[1] #get 350 scale in terms of pixel scale of map pind500=np.arange(0,101,1)*1.0/pixsize[2] #get 500 scale in terms of pixel scale of map prior250.set_prf(prf250.array,pind250,pind250)#requires psf as 2d grid, and x and y bins for grid (in pixel scale) prior350.set_prf(prf350.array,pind350,pind350) prior500.set_prf(prf500.array,pind500,pind500) # - print 'fitting '+ str(prior250.nsrc)+' sources \n' print 'using ' + str(prior250.snpix)+', '+ str(prior250.snpix)+' and '+ str(prior500.snpix)+' pixels' from pymoc import MOC moc=MOC() moc.read('./data/extended_source_test_MOC_rad4.fits') prior250.set_tile(moc) prior350.set_tile(moc) prior500.set_tile(moc) prior250.get_pointing_matrix() prior350.get_pointing_matrix() prior500.get_pointing_matrix() print 'fitting '+ str(prior250.nsrc)+' sources \n' print 'using ' + str(prior250.snpix)+', '+ str(prior250.snpix)+' and '+ str(prior500.snpix)+' pixels' prior250.upper_lim_map() prior350.upper_lim_map() prior500.upper_lim_map() prior250=add_extended_source(prior250,419,source['Spa'],source['r_K20e'],source['r_K20e']*source['Kb_a']) prior250=add_extended_source(prior250,420,WISE_sources[idx]['pa'],WISE_sources[idx]['Riso'],WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']) prior350=add_extended_source(prior350,419,source['Spa'],source['r_K20e'],source['r_K20e']*source['Kb_a']) prior350=add_extended_source(prior350,420,WISE_sources[idx]['pa'],WISE_sources[idx]['Riso'],WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']) prior500=add_extended_source(prior500,419,source['Spa'],source['r_K20e'],source['r_K20e']*source['Kb_a']) prior500=add_extended_source(prior500,420,WISE_sources[idx]['pa'],WISE_sources[idx]['Riso'],WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']) # + prior250=add_sersic_source(prior250,419,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1a'],WISE_sources[idx]['beta_1a'],WISE_sources[idx]['ba']) prior250=add_sersic_source(prior250,420,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1b'],WISE_sources[idx]['beta_1b'],WISE_sources[idx]['ba']) prior350=add_sersic_source(prior350,419,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1a'],WISE_sources[idx]['beta_1a'],WISE_sources[idx]['ba']) prior350=add_sersic_source(prior350,420,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1b'],WISE_sources[idx]['beta_1b'],WISE_sources[idx]['ba']) prior500=add_sersic_source(prior500,419,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1a'],WISE_sources[idx]['beta_1a'],WISE_sources[idx]['ba']) prior500=add_sersic_source(prior500,420,WISE_sources[idx]['pa'],WISE_sources[idx]['scale_1b'],WISE_sources[idx]['beta_1b'],WISE_sources[idx]['ba']) # - SDSS=Table.read('./data/SDSS_extended_example.csv',format='ascii.csv') SDSS # + prior250=add_sersic_source(prior250,419,SDSS['expPhi_u'],SDSS['expRad_u'],1.0,SDSS['expAB_u']) prior350=add_sersic_source(prior350,419,SDSS['expPhi_u'],SDSS['expRad_u'],1.0,SDSS['expAB_u']) prior500=add_sersic_source(prior500,419,SDSS['expPhi_u'],SDSS['expRad_u'],1.0,SDSS['expAB_u']) # - from xidplus.stan_fit import SPIRE fit=SPIRE.all_bands(prior250,prior350,prior500,iter=1000) posterior=xidplus.posterior_stan(fit,[prior250,prior350,prior500]) # + from xidplus import posterior_maps as postmaps hdurep_250=postmaps.make_fits_image(prior250,prior250.sim) hdurep_350=postmaps.make_fits_image(prior350,prior350.sim) hdurep_500=postmaps.make_fits_image(prior500,prior500.sim) # + mod_map=np.full((hdurep_250[1].data.shape[1],hdurep_250[1].data.shape[0],500),np.nan) mod_map_array=np.empty((prior250.snpix,500)) for i in range(0,500): mod_map_array[:,i]= postmaps.ymod_map(prior250,posterior.stan_fit[i,0,0:prior250.nsrc]).reshape(-1)+posterior.stan_fit[i,0,prior250.nsrc]+np.random.normal(scale=np.sqrt(prior250.snim**2+posterior.stan_fit[i,0,(prior250.nsrc+1)*3]**2)) mod_map[prior250.sx_pix-np.min(prior250.sx_pix)-1,prior250.sy_pix-np.min(prior250.sy_pix)-1,i]=mod_map_array[:,i] # + mod_map_350=np.full((hdurep_350[1].data.shape[1],hdurep_350[1].data.shape[0],500),np.nan) mod_map_array_350=np.empty((prior350.snpix,500)) for i in range(0,500): mod_map_array_350[:,i]= postmaps.ymod_map(prior350,posterior.stan_fit[i,0,prior350.nsrc+1:2*prior350.nsrc+1]).reshape(-1)+posterior.stan_fit[i,0,2*prior350.nsrc+1]+np.random.normal(scale=np.sqrt(prior350.snim**2+posterior.stan_fit[i,0,1+(prior350.nsrc+1)*3]**2)) mod_map_350[prior350.sx_pix-np.min(prior350.sx_pix)-1,prior350.sy_pix-np.min(prior350.sy_pix)-1,i]=mod_map_array_350[:,i] # + mod_map_500=np.full((hdurep_500[1].data.shape[1],hdurep_500[1].data.shape[0],500),np.nan) mod_map_array_500=np.empty((prior500.snpix,500)) for i in range(0,500): mod_map_array_500[:,i]= postmaps.ymod_map(prior500,posterior.stan_fit[i,0,2*prior500.nsrc+2:3*prior350.nsrc+2]).reshape(-1)+posterior.stan_fit[i,0,3*prior500.nsrc+2]+np.random.normal(scale=np.sqrt(prior500.snim**2+posterior.stan_fit[i,0,2+(prior500.nsrc+1)*3]**2)) mod_map_500[prior500.sx_pix-np.min(prior500.sx_pix)-1,prior500.sy_pix-np.min(prior500.sy_pix)-1,i]=mod_map_array_500[:,i] # + import scipy.stats as st pval_250=np.empty_like(prior250.sim) for i in range(0,prior250.snpix): ind=mod_map_array[i,:]<prior250.sim[i] pval_250[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array.shape[1])) pval_250[np.isposinf(pval_250)]=6 pval_350=np.empty_like(prior350.sim) for i in range(0,prior350.snpix): ind=mod_map_array_350[i,:]<prior350.sim[i] pval_350[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_350.shape[1])) pval_350[np.isposinf(pval_350)]=6 pval_500=np.empty_like(prior500.sim) for i in range(0,prior500.snpix): ind=mod_map_array_500[i,:]<prior500.sim[i] pval_500[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_500.shape[1])) pval_500[np.isposinf(pval_500)]=6 # - # + cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 fig = plt.figure(figsize=(30,30)) cfhtls=aplpy.FITSFigure('./data/W1+1+2.U.11023_11534_3064_3575.fits',figure=fig,subplot=(3,3,1)) cfhtls.show_colorscale(vmin=-10,vmax=200,cmap=cmap) cfhtls.recenter(ra_zoom, dec_zoom, radius=radius) mips=aplpy.FITSFigure('./data/wp4_xmm-lss_mips24_map_v1.0.fits',figure=fig,subplot=(3,3,2)) mips.show_colorscale(vmin=-0.001,vmax=5,cmap=cmap) mips.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4=aplpy.FITSFigure('./data/L3a-0349m061_ac51-0349m061_ac51-w4-int-3_ra35.401958_dec-5.5213939_asec600.000.fits',figure=fig,subplot=(3,3,3)) wise_band4.show_colorscale(vmin=202,vmax=204,cmap=cmap) wise_band4.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250 = aplpy.FITSFigure(hdulist_250[1],figure=fig,subplot=(3,3,4)) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.add_colorbar() #real_250.show_markers(WISE_sources['ra'],WISE_sources['dec'], edgecolor='red', facecolor='red', # marker='o', s=40, alpha=0.5) real_350 = aplpy.FITSFigure(hdulist_350[1],figure=fig,subplot=(3,3,5)) real_350.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) real_350.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) #real_350.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_350.recenter(ra_zoom, dec_zoom, radius=radius) real_500 = aplpy.FITSFigure(hdulist_500[1],figure=fig,subplot=(3,3,6)) real_500.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_500.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_500.recenter(ra_zoom, dec_zoom, radius=radius) real_500.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) vmin=-6 vmax=6 cmap=sns.diverging_palette(220, 20,as_cmap=True) res250=aplpy.FITSFigure(hdurep_250[1],figure=fig,subplot=(3,3,7)) res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250.recenter(ra_zoom, dec_zoom, radius=radius) res350=aplpy.FITSFigure(hdurep_350[1],figure=fig,subplot=(3,3,8)) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_markers(prior350.sra, prior350.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res350.recenter(ra_zoom, dec_zoom, radius=radius) res500=aplpy.FITSFigure(hdurep_500[1],figure=fig,subplot=(3,3,9)) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_markers(prior500.sra, prior500.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250._data[prior250.sy_pix-np.min(prior250.sy_pix)-1,prior250.sx_pix-np.min(prior250.sx_pix)-1]=pval_250 res350._data[prior350.sy_pix-np.min(prior350.sy_pix)-1,prior350.sx_pix-np.min(prior350.sx_pix)-1]=pval_350 res500._data[prior500.sy_pix-np.min(prior500.sy_pix)-1,prior500.sx_pix-np.min(prior500.sx_pix)-1]=pval_500 res500.recenter(ra_zoom, dec_zoom, radius=radius) #res500.tick_labels.set_xformat('dd.dd') #res500.tick_labels.set_yformat('dd.dd') res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.add_colorbar() res250.colorbar.set_location('top') res350.add_colorbar() res350.colorbar.set_location('top') res500.add_colorbar() res500.colorbar.set_location('top') # - plt.imshow(mod_map[:,:,1],interpolation='nearest') plt.colorbar() plt.hist(posterior.stan_fit[:,:,420]) prior250.nsrc # + cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 fig = plt.figure(figsize=(30,30)) cfhtls=aplpy.FITSFigure('./data/W1+1+2.U.11023_11534_3064_3575.fits',figure=fig,subplot=(3,3,1)) cfhtls.show_colorscale(vmin=-10,vmax=200,cmap=cmap) cfhtls.recenter(ra_zoom, dec_zoom, radius=radius) mips=aplpy.FITSFigure('./data/wp4_xmm-lss_mips24_map_v1.0.fits',figure=fig,subplot=(3,3,2)) mips.show_colorscale(vmin=-0.001,vmax=5,cmap=cmap) mips.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4=aplpy.FITSFigure('./data/L3a-0349m061_ac51-0349m061_ac51-w4-int-3_ra35.401958_dec-5.5213939_asec600.000.fits',figure=fig,subplot=(3,3,3)) wise_band4.show_colorscale(vmin=202,vmax=204,cmap=cmap) wise_band4.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250 = aplpy.FITSFigure(hdulist_250[1],figure=fig,subplot=(3,3,4)) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.add_colorbar() #real_250.show_markers(WISE_sources['ra'],WISE_sources['dec'], edgecolor='red', facecolor='red', # marker='o', s=40, alpha=0.5) real_350 = aplpy.FITSFigure(hdulist_350[1],figure=fig,subplot=(3,3,5)) real_350.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') real_350.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) #real_350.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_350.recenter(ra_zoom, dec_zoom, radius=radius) real_500 = aplpy.FITSFigure(hdulist_500[1],figure=fig,subplot=(3,3,6)) real_500.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') #real_500.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_500.recenter(ra_zoom, dec_zoom, radius=radius) real_500.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) vmin=-1.7E1 vmax=800.0 #cmap=sns.diverging_palette(220, 20,as_cmap=True) res250=aplpy.FITSFigure(hdurep_250[1],figure=fig,subplot=(3,3,7)) res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res250.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250.recenter(ra_zoom, dec_zoom, radius=radius) res350=aplpy.FITSFigure(hdurep_350[1],figure=fig,subplot=(3,3,8)) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res350.show_markers(prior350.sra, prior350.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res350.recenter(ra_zoom, dec_zoom, radius=radius) res500=aplpy.FITSFigure(hdurep_500[1],figure=fig,subplot=(3,3,9)) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res500.show_markers(prior500.sra, prior500.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250._data[prior250.sy_pix-np.min(prior250.sy_pix)-1,prior250.sx_pix-np.min(prior250.sx_pix)-1]=mod_map_array[:,50] res350._data[prior350.sy_pix-np.min(prior350.sy_pix)-1,prior350.sx_pix-np.min(prior350.sx_pix)-1]=mod_map_array_350[:,50] res500._data[prior500.sy_pix-np.min(prior500.sy_pix)-1,prior500.sx_pix-np.min(prior500.sx_pix)-1]=mod_map_array_500[:,50] res500.recenter(ra_zoom, dec_zoom, radius=radius) #res500.tick_labels.set_xformat('dd.dd') #res500.tick_labels.set_yformat('dd.dd') res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res250.add_colorbar() res250.colorbar.set_location('top') res350.add_colorbar() res350.colorbar.set_location('top') res500.add_colorbar() res500.colorbar.set_location('top') # - plt.scatter(posterior.stan_fit[:,:,419].flatten(),posterior.stan_fit[:,:,420].flatten()) plt.hist(posterior.stan_fit[:,:,-4].flatten()) prior250 extended_source_conv=postmaps.make_fits_image(prior250,atemp) prior250.amat_col == 419 prior250.nsrc # + atemp=np.empty_like(prior250.sim) atemp[:]=0.0 ind=prior250.amat_col == 420 atemp[prior250.amat_row[ind]]=prior250.amat_data[ind] extended_source_conv=postmaps.make_fits_image(prior250,atemp) cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) real_250 = aplpy.FITSFigure(extended_source_conv[1]) real_250.show_colorscale(cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) #real_250.recenter(ra_zoom, dec_zoom, radius=radius) # - fit=SPIRE.all_bands(prior250,prior350,prior500,iter=1500) posterior=xidplus.posterior_stan(fit,[prior250,prior350,prior500]) # + from xidplus import posterior_maps as postmaps hdurep_250=postmaps.make_fits_image(prior250,prior250.sim) hdurep_350=postmaps.make_fits_image(prior350,prior350.sim) hdurep_500=postmaps.make_fits_image(prior500,prior500.sim) # + mod_map=np.full((hdurep_250[1].data.shape[1],hdurep_250[1].data.shape[0],500),np.nan) mod_map_array=np.empty((prior250.snpix,500)) for i in range(0,500): mod_map_array[:,i]= postmaps.ymod_map(prior250,posterior.stan_fit[i,0,0:prior250.nsrc]).reshape(-1)+posterior.stan_fit[i,0,prior250.nsrc]+np.random.normal(scale=np.sqrt(prior250.snim**2+posterior.stan_fit[i,0,(prior250.nsrc+1)*3]**2)) mod_map[prior250.sx_pix-np.min(prior250.sx_pix)-1,prior250.sy_pix-np.min(prior250.sy_pix)-1,i]=mod_map_array[:,i] # + mod_map_350=np.full((hdurep_350[1].data.shape[1],hdurep_350[1].data.shape[0],500),np.nan) mod_map_array_350=np.empty((prior350.snpix,500)) for i in range(0,500): mod_map_array_350[:,i]= postmaps.ymod_map(prior350,posterior.stan_fit[i,0,prior350.nsrc+1:2*prior350.nsrc+1]).reshape(-1)+posterior.stan_fit[i,0,2*prior350.nsrc+1]+np.random.normal(scale=np.sqrt(prior350.snim**2+posterior.stan_fit[i,0,1+(prior350.nsrc+1)*3]**2)) mod_map_350[prior350.sx_pix-np.min(prior350.sx_pix)-1,prior350.sy_pix-np.min(prior350.sy_pix)-1,i]=mod_map_array_350[:,i] # + mod_map_500=np.full((hdurep_500[1].data.shape[1],hdurep_500[1].data.shape[0],500),np.nan) mod_map_array_500=np.empty((prior500.snpix,500)) for i in range(0,500): mod_map_array_500[:,i]= postmaps.ymod_map(prior500,posterior.stan_fit[i,0,2*prior500.nsrc+2:3*prior350.nsrc+2]).reshape(-1)+posterior.stan_fit[i,0,3*prior500.nsrc+2]+np.random.normal(scale=np.sqrt(prior500.snim**2+posterior.stan_fit[i,0,2+(prior500.nsrc+1)*3]**2)) mod_map_500[prior500.sx_pix-np.min(prior500.sx_pix)-1,prior500.sy_pix-np.min(prior500.sy_pix)-1,i]=mod_map_array_500[:,i] # + import scipy.stats as st pval_250=np.empty_like(prior250.sim) for i in range(0,prior250.snpix): ind=mod_map_array[i,:]<prior250.sim[i] pval_250[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array.shape[1])) pval_250[np.isposinf(pval_250)]=6 pval_350=np.empty_like(prior350.sim) for i in range(0,prior350.snpix): ind=mod_map_array_350[i,:]<prior350.sim[i] pval_350[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_350.shape[1])) pval_350[np.isposinf(pval_350)]=6 pval_500=np.empty_like(prior500.sim) for i in range(0,prior500.snpix): ind=mod_map_array_500[i,:]<prior500.sim[i] pval_500[i]=st.norm.ppf(sum(ind)/np.float(mod_map_array_500.shape[1])) pval_500[np.isposinf(pval_500)]=6 # + cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 fig = plt.figure(figsize=(30,30)) cfhtls=aplpy.FITSFigure('./data/W1+1+2.U.11023_11534_3064_3575.fits',figure=fig,subplot=(3,3,1)) cfhtls.show_colorscale(vmin=-10,vmax=200,cmap=cmap) cfhtls.recenter(ra_zoom, dec_zoom, radius=radius) mips=aplpy.FITSFigure('./data/wp4_xmm-lss_mips24_map_v1.0.fits',figure=fig,subplot=(3,3,2)) mips.show_colorscale(vmin=-0.001,vmax=5,cmap=cmap) mips.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4=aplpy.FITSFigure('./data/L3a-0349m061_ac51-0349m061_ac51-w4-int-3_ra35.401958_dec-5.5213939_asec600.000.fits',figure=fig,subplot=(3,3,3)) wise_band4.show_colorscale(vmin=202,vmax=204,cmap=cmap) wise_band4.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250 = aplpy.FITSFigure(hdulist_250[1],figure=fig,subplot=(3,3,4)) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.add_colorbar() #real_250.show_markers(WISE_sources['ra'],WISE_sources['dec'], edgecolor='red', facecolor='red', # marker='o', s=40, alpha=0.5) real_350 = aplpy.FITSFigure(hdulist_350[1],figure=fig,subplot=(3,3,5)) real_350.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) real_350.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) #real_350.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_350.recenter(ra_zoom, dec_zoom, radius=radius) real_500 = aplpy.FITSFigure(hdulist_500[1],figure=fig,subplot=(3,3,6)) real_500.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap) #real_500.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_500.recenter(ra_zoom, dec_zoom, radius=radius) real_500.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) vmin=-6 vmax=6 cmap=sns.diverging_palette(220, 20,as_cmap=True) res250=aplpy.FITSFigure(hdurep_250[1],figure=fig,subplot=(3,3,7)) res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250.recenter(ra_zoom, dec_zoom, radius=radius) res350=aplpy.FITSFigure(hdurep_350[1],figure=fig,subplot=(3,3,8)) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_markers(prior350.sra, prior350.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res350.recenter(ra_zoom, dec_zoom, radius=radius) res500=aplpy.FITSFigure(hdurep_500[1],figure=fig,subplot=(3,3,9)) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_markers(prior500.sra, prior500.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250._data[prior250.sy_pix-np.min(prior250.sy_pix)-1,prior250.sx_pix-np.min(prior250.sx_pix)-1]=pval_250 res350._data[prior350.sy_pix-np.min(prior350.sy_pix)-1,prior350.sx_pix-np.min(prior350.sx_pix)-1]=pval_350 res500._data[prior500.sy_pix-np.min(prior500.sy_pix)-1,prior500.sx_pix-np.min(prior500.sx_pix)-1]=pval_500 res500.recenter(ra_zoom, dec_zoom, radius=radius) #res500.tick_labels.set_xformat('dd.dd') #res500.tick_labels.set_yformat('dd.dd') res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap) res250.add_colorbar() res250.colorbar.set_location('top') res350.add_colorbar() res350.colorbar.set_location('top') res500.add_colorbar() res500.colorbar.set_location('top') # + cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 ra_zoom=source['RAJ2000'] dec_zoom=source['DEJ2000'] radius=0.05 fig = plt.figure(figsize=(30,30)) cfhtls=aplpy.FITSFigure('./data/W1+1+2.U.11023_11534_3064_3575.fits',figure=fig,subplot=(3,3,1)) cfhtls.show_colorscale(vmin=-10,vmax=200,cmap=cmap) cfhtls.recenter(ra_zoom, dec_zoom, radius=radius) mips=aplpy.FITSFigure('./data/wp4_xmm-lss_mips24_map_v1.0.fits',figure=fig,subplot=(3,3,2)) mips.show_colorscale(vmin=-0.001,vmax=5,cmap=cmap) mips.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4=aplpy.FITSFigure('./data/L3a-0349m061_ac51-0349m061_ac51-w4-int-3_ra35.401958_dec-5.5213939_asec600.000.fits',figure=fig,subplot=(3,3,3)) wise_band4.show_colorscale(vmin=202,vmax=204,cmap=cmap) wise_band4.recenter(ra_zoom, dec_zoom, radius=radius) wise_band4.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250 = aplpy.FITSFigure(hdulist_250[1],figure=fig,subplot=(3,3,4)) real_250.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.add_colorbar() #real_250.show_markers(WISE_sources['ra'],WISE_sources['dec'], edgecolor='red', facecolor='red', # marker='o', s=40, alpha=0.5) real_350 = aplpy.FITSFigure(hdulist_350[1],figure=fig,subplot=(3,3,5)) real_350.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') real_350.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) #real_350.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_350.recenter(ra_zoom, dec_zoom, radius=radius) real_500 = aplpy.FITSFigure(hdulist_500[1],figure=fig,subplot=(3,3,6)) real_500.show_colorscale(vmin=vmin,vmax=0.8,cmap=cmap,stretch='arcsinh') #real_500.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', #marker='o', s=40, alpha=0.5) real_500.recenter(ra_zoom, dec_zoom, radius=radius) real_500.show_ellipses(ra_zoom, dec_zoom,2*source['r_K20e']/3600.0,2*source['r_K20e']*source['Kb_a']/3600.0, angle=360.0-source['Spa'],edgecolor='white',linewidth=2.0) vmin=-1.7E1 vmax=800.0 #cmap=sns.diverging_palette(220, 20,as_cmap=True) res250=aplpy.FITSFigure(hdurep_250[1],figure=fig,subplot=(3,3,7)) res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res250.show_markers(prior250.sra, prior250.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250.recenter(ra_zoom, dec_zoom, radius=radius) res350=aplpy.FITSFigure(hdurep_350[1],figure=fig,subplot=(3,3,8)) res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res350.show_markers(prior350.sra, prior350.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res350.recenter(ra_zoom, dec_zoom, radius=radius) res500=aplpy.FITSFigure(hdurep_500[1],figure=fig,subplot=(3,3,9)) res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res500.show_markers(prior500.sra, prior500.sdec, edgecolor='black', facecolor='black', marker='o', s=80, alpha=0.5) res250._data[prior250.sy_pix-np.min(prior250.sy_pix)-1,prior250.sx_pix-np.min(prior250.sx_pix)-1]=mod_map_array[:,50] res350._data[prior350.sy_pix-np.min(prior350.sy_pix)-1,prior350.sx_pix-np.min(prior350.sx_pix)-1]=mod_map_array_350[:,50] res500._data[prior500.sy_pix-np.min(prior500.sy_pix)-1,prior500.sx_pix-np.min(prior500.sx_pix)-1]=mod_map_array_500[:,50] res500.recenter(ra_zoom, dec_zoom, radius=radius) #res500.tick_labels.set_xformat('dd.dd') #res500.tick_labels.set_yformat('dd.dd') res250.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res350.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res500.show_colorscale(vmin=vmin,vmax=vmax,cmap=cmap,stretch='arcsinh') res250.add_colorbar() res250.colorbar.set_location('top') res350.add_colorbar() res350.colorbar.set_location('top') res500.add_colorbar() res500.colorbar.set_location('top') # - plt.scatter(posterior.stan_fit[:,:,421*2-1].flatten(),posterior.stan_fit[:,:,421*2].flatten()) # + vmin=-1.7E1/1.0E3 vmax=4.446e+01/1.0E3 cmap=sns.cubehelix_palette(8, start=.5, rot=-.75,as_cmap=True) real_250 = aplpy.FITSFigure(extended_source_conv[1]) real_250.show_colorscale(cmap=cmap) #real_250.show_markers(ra_list,dec_list, edgecolor='white', facecolor='white', #marker='o', s=40, alpha=0.5) real_250.show_ellipses(ra_zoom, dec_zoom,2*WISE_sources[idx]['Riso']/3600.0,2*WISE_sources[idx]['Riso']*WISE_sources[idx]['ba']/3600.0, angle=360.0-WISE_sources[idx]['pa'],edgecolor='white',linewidth=2.0) real_250.show_markers(IRAC_sources['RA'],IRAC_sources['DEC'], edgecolor='yellow', facecolor='yellow', marker='o', s=40, alpha=0.5) #real_250.recenter(ra_zoom, dec_zoom, radius=radius) real_250.add_colorbar() # -
examples/XID+Extended_sources_test.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="vDiVVG4FJsLY" pip install matplotlib # + id="ZZGJPZANJ9Zy" import matplotlib.pyplot as plt import numpy as np # + id="5yOM7xYoNae4" x=np.array([1,2,3,4,5,6,7,8,9,10]) y=np.array([1,4,9,16,25,36,49,64,81,100]) # + [markdown] id="ZoKwvs50Q1Ca" # # Simple Line Plot # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="B4cKriwrJ9cc" outputId="4d86d6b5-fafc-4b04-9252-a0da833b3c61" x=np.array([1,2,3,4,5,6,7,8,9,10]) y=np.array([1,4,9,16,25,36,49,64,81,100]) plt.plot(x,y) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="LXr_lbFUJ9e4" outputId="5f02e218-c989-44a9-8fc3-3f74a73d1618" #the general syntax is plt.plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs). #The [fmt] is a convenient way for defining basic formatting like color, marker and linestyle. #There are various line properties you can use. for more properties visit https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot x=np.array([1,2,3,4,5,6,7,8,9,10]) y=np.array([1,4,9,16,25,36,49,64,81,100]) plt.plot(x,y,color='green', marker='o', linestyle='dashed',linewidth=2, markersize=12) plt.show() # + [markdown] id="nsL_AJgTOjlU" # # # # Scatter Plot # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="R7XDiAR1MzsM" outputId="058b29d1-8e65-470f-fb73-3149b0f372bb" #This is a simple scatter plot without any modifictaion plt.scatter(x,y) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="Gxim0rhRNwRW" outputId="6f4d7232-f814-4ba4-b067-63da7865a31d" #You can modify the parameters to design the plot. #The s=area sets the size of marker points #The c=colors sets random colors in an array which is assigned randomly to the markers #The aplha=0.5 is the bleding value of graph, that is 0(Transperant) and 1(Opaque) X = np.random.rand(50) Y = np.random.rand(50) colors = np.random.rand(50) area = (30 * np.random.rand(50))**2 # 0 to 15 point radii plt.scatter(X, Y, s=area, c=colors, alpha=0.5) plt.show() # + [markdown] id="8g9iBwIrQxvP" # # Bar Plots # + colab={"base_uri": "https://localhost:8080/", "height": 285} id="ynL2s7NiOhSb" outputId="872cb4be-3eee-4b00-e418-204d50da1a87" #The parameters are, X the x values, Y the height of bars, width=0.6 the width of each bar,align='center' the position of bars) X = np.arange(1,25,dtype=int) Y = np.arange(1,25,dtype=int) plt.bar(X,Y,width=0.6,align='center') # + colab={"base_uri": "https://localhost:8080/", "height": 282} id="uGrP-z8AQ54X" outputId="188cf9cb-d1e2-4257-d921-f0b7d7cf53ba" #Horizontal Bar plot. plt.barh([2,5,7,3,1,0],[1,2,3,4,5,6],align='center') # + [markdown] id="qzjSLbg6Tgt7" # # Displaying Images using Matplotlib # + id="E2YS4ThrRe6z" #This module is used to manipulate images in various styles #read more about it here https://matplotlib.org/stable/tutorials/introductory/images.html#sphx-glr-tutorials-introductory-images-py import matplotlib.image as mpimg # + colab={"base_uri": "https://localhost:8080/"} id="VWS6FX-FSnvB" outputId="7a058bd4-44f3-4afa-e6bc-db5d784aaf63" img = mpimg.imread('/content/sample_data/Raw file.jpeg') print(img) # + colab={"base_uri": "https://localhost:8080/", "height": 240} id="rafS_GGGS4dB" outputId="67fb4e06-ab91-46d9-d248-f74fca87e26c" #Displaying the image using imshow() function imgplot = plt.imshow(img) # + colab={"base_uri": "https://localhost:8080/", "height": 257} id="IbpbRKJVS_Hg" outputId="2e52b322-c87a-419f-fcfc-c6b520acb473" lum_img = img[:, :, 0] # This is array slicing. You can read more in the `Numpy tutorial # <https://docs.scipy.org/doc/numpy/user/quickstart.html>`_. plt.imshow(lum_img) # + colab={"base_uri": "https://localhost:8080/", "height": 257} id="A7Qb1Ca-TBRi" outputId="bbb9d563-611d-42f5-b020-fb28b61fab79" plt.imshow(lum_img, cmap="hot") # + colab={"base_uri": "https://localhost:8080/", "height": 240} id="9uq29XTPTGQs" outputId="80d9f9ed-1c5b-456e-f549-f91e8037a31b" imgplot = plt.imshow(lum_img) imgplot.set_cmap('nipy_spectral') # + colab={"base_uri": "https://localhost:8080/", "height": 271} id="y0SJHarwTLFO" outputId="934ccbe9-5c78-4103-c4e2-8ff3ad192859" imgplot = plt.imshow(lum_img) plt.colorbar() # + colab={"base_uri": "https://localhost:8080/", "height": 240} id="Ma8Ndp88TQnK" outputId="58e9a9e5-e0bd-436e-d178-4e747fccbc78" imgplot = plt.imshow(lum_img, clim=(0.0, 0.7)) # + colab={"base_uri": "https://localhost:8080/", "height": 238} id="SKMLorRaTZxy" outputId="d2264f83-85f9-4755-9410-0fc2c7a23a4b" from PIL import Image img = Image.open('/content/sample_data/Raw file.jpeg') img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place imgplot = plt.imshow(img) # + [markdown] id="VSL45cMBU5vg" # # # # Contours # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="UnGruNDjUDsj" outputId="58184c53-2f64-4a34-e75a-847b2db74bc5" from matplotlib.colors import LogNorm Z = np.random.rand(20, 20) plt.pcolormesh(Z) plt.title('matplotlib.pyplot.pcolormesh() function Example', fontweight ="bold") plt.show() #The pcolormesh() function in pyplot module of matplotlib library is used to create a pseudocolor plot with a non-regular rectangular grid. # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="tU4VTjieVAgK" outputId="176e9a4c-3fb9-4985-ae32-a4d44391fc9e" xlist = np.linspace(-3.0, 3.0, 100) ylist = np.linspace(-3.0, 3.0, 100) X, Y = np.meshgrid(xlist, ylist) Z = np.sqrt(X**2 + Y**2) fig,ax=plt.subplots(1,1) cp = ax.contourf(X, Y, Z) fig.colorbar(cp) # Add a colorbar to a plot ax.set_title('Filled Contours Plot') #ax.set_xlabel('x (cm)') ax.set_ylabel('y (cm)') plt.show() #Contours are basically used for visualizing 3D graphs in a 2D plane. If you want to observe the change #of a variable Z as a function two input variable X and Y, then contour() is the best function available # + [markdown] id="qK02Vu999oIW" # # Histograms # + id="zerDCDrM4AKu" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="dd7ad053-0ba8-4d61-bc68-e5bf1a149c7c" #VErtical Histograms # Fixing random state for reproducibility np.random.seed(19680801) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data plt.hist(x,'auto',density=True, facecolor='g', alpha=0.75) plt.show() # + [markdown] id="nwhr_vsc89HH" # # Plotting Histograms with various bin values # ### The supported bin values are 'auto', 'fd', 'doane', 'scott', 'stone', 'rice', 'sturges', or 'sqrt'. # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="gfh64_Xx5Qo7" outputId="f9cf964b-62f9-4131-a682-d019e17a1b86" plt.hist(x,'fd',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'doane',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'scott',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'stone',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'rice',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'sturges',density=True, facecolor='g', alpha=0.75) plt.show() plt.hist(x,'sqrt',density=True, facecolor='g', alpha=0.75) plt.show() # + [markdown] id="X5A_JFkh-J8I" # # 2D Histogram # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="Yv3gDHTT9rGx" outputId="0add20d1-50a6-4384-ea53-049a57791c19" #Just Like 1D Histogram, 2D Histogram just takes one more parameter which is the y value which is an array of values np.random.seed(19680801) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) gamma,beta = 200,20 y= gamma + beta * np.random.randn(10000) plt.hist2d(x,y,50,density=True, facecolor='r', alpha=0.75) plt.show() # + [markdown] id="9BarBXHv_gwS" # # Pie Charts # + colab={"base_uri": "https://localhost:8080/", "height": 411} id="6izgZ7qy-exa" outputId="824d7c3d-45cc-400e-a319-47b521ac92cf" cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES'] data = [23, 17, 35, 29, 12, 41] explode = (0.0, 0.0, 0.2, 0.0, 0.0, 0.0) # Creating color parameters colors = ( "orange", "cyan", "brown", "grey", "indigo", "beige") # Creating plot fig = plt.figure(figsize =(10, 7)) plt.pie(data, labels = cars,explode=explode,colors=colors,shadow=True) # show plot plt.show() # + [markdown] id="EP4r0Q46JmP8" # # Fill between graphs # + id="Le0qEPFRBSnj" import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 1, 500) y = np.sin(4 * np.pi * x) * np.exp(-5 * x) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="6Kcy0yN6ITr3" outputId="c18b148e-954b-430d-b277-7192b50ee247" fig, ax = plt.subplots() #Filling between x and y values #zorder determines how close the points will be to the observer ax.fill(x, y, zorder=10) ax.grid(True, zorder=5) x = np.linspace(0, 2 * np.pi, 500) y1 = np.sin(x) y2 = np.cos(3 * x) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="W5wYacaqIcY3" outputId="73dbbca7-741b-492e-c904-af7fccb47849" #Plotting two sets of curves on the plot fig, ax = plt.subplots() ax.fill(x, y1, 'b', x, y2, 'r', alpha=0.3) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 441} id="_SaasNZyIt31" outputId="cf6ad102-8007-419f-c3b7-3781f45fe149" x = np.arange(0.0, 2, 0.01) y1 = np.sin(2 * np.pi * x) y2 = 0.8 * np.sin(4 * np.pi * x) fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(6, 6)) ax1.fill_between(x, y1) ax1.set_title('fill between y1 and 0') ax2.fill_between(x, y1, 1) ax2.set_title('fill between y1 and 1') ax3.fill_between(x, y1, y2) ax3.set_title('fill between y1 and y2') ax3.set_xlabel('x') fig.tight_layout() # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="wGHyDFkZJWUC" outputId="57129c5b-6336-4551-8444-62d518df2a33" N = 21 x = np.linspace(0, 10, 11) y = [3.9, 4.4, 10.8, 10.3, 11.2, 13.1, 14.1, 9.9, 13.9, 15.1, 12.5] # fit a linear curve an estimate its y-values and their error. a, b = np.polyfit(x, y, deg=1) y_est = a * x + b y_err = x.std() * np.sqrt(1/len(x) + (x - x.mean())**2 / np.sum((x - x.mean())**2)) fig, ax = plt.subplots() ax.plot(x, y_est, '-') ax.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2) ax.plot(x, y, 'o', color='tab:brown') # + [markdown] id="xuMFtvYPLGRZ" # # Subplots in a Graph # + colab={"base_uri": "https://localhost:8080/", "height": 320} id="a6mXxaK1KiRn" outputId="ac90076b-bf3b-4494-bb93-f921bd609f19" #Creating 4 subplots in a same graph np.random.seed(19680801) data = np.random.randn(2, 1000) fig, axs = plt.subplots(2, 2, figsize=(5, 5)) axs[0, 0].hist(data[0]) axs[1, 0].scatter(data[0], data[1]) axs[0, 1].plot(data[0], data[1]) axs[1, 1].hist2d(data[0], data[1]) plt.show() # + [markdown] id="O6JfnnUCLyrZ" # # Quiver Plot # + colab={"base_uri": "https://localhost:8080/", "height": 432} id="NAd0J2xfLp50" outputId="bc12549f-8d08-40b6-a634-c9297bdf9de0" #It is used to draw arrows in a graph. For example the Electric field diagrams # Creating arrow x_pos = [0, 0] y_pos = [0, 0] x_direct = [1, 0] y_direct = [1, -1] # Creating plot fig, ax = plt.subplots(figsize = (12, 7)) ax.quiver(x_pos, y_pos, x_direct, y_direct, scale = 5) ax.axis([-1.5, 1.5, -1.5, 1.5]) # show plot plt.show() # + [markdown] id="2vczNKGUPoT3" # # Step Plot # + colab={"base_uri": "https://localhost:8080/", "height": 761} id="uhCSDXVXL8OX" outputId="2f5585cd-b256-4ee4-a174-00593a178b78" x = np.array([1, 3, 4, 5, 7]) y = np.array([1, 9, 16, 25, 49]) plt.step(x, y, 'g^', where='pre') plt.show() plt.step(x, y, 'r*', where='post') plt.show() plt.step(x, y, 'cs', where='mid') plt.xlim(1, 9) plt.show() # + [markdown] id="pmZjNoF3PsMq" # # Box Plot # + colab={"base_uri": "https://localhost:8080/", "height": 552} id="ObraI24XPM99" outputId="b55dbac9-4521-489a-a288-4dfd28e21dde" #A Box Plot is also known as Whisker plot is created to display the summary of the #set of data values having properties like minimum, first quartile, median, third quartile and maximum np.random.seed(10) data_1 = np.random.normal(100, 10, 200) data_2 = np.random.normal(90, 20, 200) data_3 = np.random.normal(80, 30, 200) data_4 = np.random.normal(70, 40, 200) data = [data_1, data_2, data_3, data_4] fig = plt.figure(figsize =(10, 7)) # Creating axes instance ax = fig.add_axes([0, 0, 1, 1]) # Creating plot bp = ax.boxplot(data) # show plot plt.show() # + [markdown] id="ix9DTNccQqL-" # # Error Plot # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="X4SyROYzPzyW" outputId="fec1a628-7737-4061-8efc-b2d55b483bc3" #The errorbar() function in pyplot module of matplotlib library #is used to plot y versus x as lines and/or markers with attached errorbars. #The parameters used are #xval and yval are the set of data points to be plotted #xerr and yerr contain an array of positive values which determines the error in the xval and yval given as input xval = np.arange(0.1, 10, 0.5) yval = np.exp(xval) plt.errorbar(xval, yval, xerr = 0.3, yerr = 0.2) plt.title('matplotlib.pyplot.errorbar() function Example') plt.show() # + [markdown] id="5nJbD38LRb0k" # # Violin Plot # + colab={"base_uri": "https://localhost:8080/", "height": 336} id="T6AF1yXdQtA3" outputId="91edd496-e2f8-439b-b475-6cca85d12529" #Violin plots are similar to box plots, except that they also show the probability density of the data at different values. #These plots include a marker for the median of the data and a box indicating the interquartile range, #as in the standard box plots. np.random.seed(10) collectn_1 = np.random.normal(100, 90, 200) collectn_2 = np.random.normal(80, 30, 200) collectn_3 = np.random.normal(90, 20, 200) collectn_4 = np.random.normal(70, 25, 200) ## combine these different collections into a list data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4] # Create a figure instance fig = plt.figure() # Create an axes instance ax = fig.add_axes([0,0,1,1]) # Create the boxplot bp = ax.violinplot(data_to_plot) plt.show() # + [markdown] id="XKV2_e4yST3N" # # Barb Plots # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="RtroFxe0Rflv" outputId="aeff894e-49f9-477c-ddfb-f687c01b97f1" #Barbs are used majorly in meteorology to plot the speed and direction of winds #but can be used to plot any two-dimensional vector quantity. #Barbs are able to provide more precise and quantitative information about vector magnitude when compared to arrows. #The syntax is matplotlib.pyplot.barbs(x_coordinate, y_coordinate, x_direction, y_direction, [colour]) x = np.linspace(-10, 10, 5) X, Y = np.meshgrid(x, x) U, V = 12 * X, 12 * Y data = [(-1.5, .5, -6, -6), (1, -1, -46, 46), (-3, -1, 11, -11), (1, 1.5, 80, 80), (0.5, 0.25, 25, 15), (-1.5, -0.5, -5, 40)] data = np.array(data, dtype=[('x', np.float32), ('y', np.float32), ('u', np.float32), ('v', np.float32)]) plt.barbs(X, Y, U, V) # + [markdown] id="XJwwkMZ1UDVk" # # Event Plots # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="S34e8kStSWkB" outputId="2e061353-8b11-4f75-a53f-94888599b5f6" #These plots, in general, are used for representing neural events in neuroscience, where more often it is called spike raster #or dot raster or raster plot. #More often it is also used for showing the timing or positioning of multiple sets of different or discrete events. spike = 100*np.random.random(100) plt.eventplot(spike, orientation = 'vertical', linelengths = 0.8, color = [(0.5,0.5,0.8)]) #The parameters are #positions, which takes a 1D or 2D array where each value in the array represents an event #orientation, which determines the plot will be vertical or horizontal #linelenghts, which determines the length of the lines of the events # + [markdown] id="cW35U8FjU-Y2" # # Hexbin function # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="usbbOnUAUA4r" outputId="6336f59e-b5f3-4629-e567-6da702626106" #The hexbin() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y. np.random.seed(19680801) n = 100000 x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() hb = plt.hexbin(x, y, gridsize = 50, bins = z, cmap ='gist_rainbow_r') plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) cb = plt.colorbar(hb) cb.set_label(z) plt.title('matplotlib.pyplot.hexbin()\ Example') plt.show() #The parameters are #x,y- These parameter are the sequence of data. x and y must be of the same length #C- This parameter are the values which are accumulated in the bins. #gridsize - This parameter represents the number of hexagons in the x-direction or both direction. #cmap - The coloruing scheme for the hex plot # + colab={"base_uri": "https://localhost:8080/", "height": 148} id="z5Wj2I58VEpT" outputId="bef65cbd-f540-4591-e58a-06a8c9f79caa" #Cross Correlation #The correlation coefficient is a statistical measure of the strength of the relationship between #the relative movements of two variables. # float lists for cross # correlation x, y = np.random.randn(2, 100) # Plot graph fig = plt.figure() ax1 = fig.add_subplot(211) # cross correlation using xcorr() # function ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2) # adding grid to the graph ax1.grid(True) ax1.axhline(0, color='blue', lw=2) # show final plotted graph plt.show() #The Parameters are #x,y- A vector of real or complex floating point numbers used for cross correlation #usevlines- take bool value. If it is true it vertical lines are plotted from 0 to xcorr values #normed - takes bool value. If it is true it normalizes the input vectors to unit length #maxlags - Number of lags to show. If None, will return all 2 * len(x) โ€“ 1 lags. Optional parameter, default value is 10.
Various_Plots_in_Matplotlib.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 tmilib import * import csv import math def get_baseline2_accuracy(insession_only): testdata_filename = 'catdata_test_second_evaluation_v4.csv' #log_threshold = log(60*threshold_minutes) if insession_only: testdata_filename = 'catdata_test_insession_second_evaluation_v4.csv' #for line in csv.DictReader(sdir_open(testdata_filename)): csv_reader = csv.reader(sdir_open(testdata_filename)) headers = next(csv_reader) assert headers[0] == 'user' assert headers[2] == 'label' #assert headers[1] == 'time_sec' assert headers[3] == 'sinceprev' tp = 0 fn = 0 fp = 0 tn = 0 user_to_is_active_in_majority_of_sessions = get_username_to_is_active_in_majority_of_sessions() for line in csv_reader: user = line[0] label = line[2] ref = label == 'T' sinceprev = float(line[4]) # this is in log-seconds rec = user_to_is_active_in_majority_of_sessions[user] #rec = sinceprev < log_threshold if ref == True and rec == True: tp += 1 elif ref == True and rec == False: fn += 1 elif ref == False and rec == True: fp += 1 elif ref == False and rec == False: tn += 1 return { 'tp': tp, 'fn': fn, 'fp': fp, 'tn': tn } def print_binary_classification_stats(stats): tp = float(stats['tp']) fp = float(stats['fp']) fn = float(stats['fn']) tn = float(stats['tn']) precision = tp / (tp + fp) recall = tp / (tp + fn) f1 = 2*precision*recall / (precision+recall) accuracy = (tp + tn) / (tp + fp + fn + tn) print 'tp', tp print 'tn', tn print 'fp', fp print 'fn', fn print 'precision', precision print 'recall', recall print 'f1', f1 print 'accuracy', accuracy print 'insession stats for baseline2' cur_stats = get_baseline2_accuracy(True) print_binary_classification_stats(cur_stats) print 'all stats for baseline2' cur_stats = get_baseline2_accuracy(False) print_binary_classification_stats(cur_stats)
evaluate_baseline_timeactive_algorithms_v3_baseline2.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 # --- # # Playing with a qubit on a PewPew # Prototype quantum computers are now on the cloud and ready to be experimented with. Larger scale devices, capable of things that no supercomputer can match, are already on their way. The technology is coming out of the lab and into the hands of everyone. So let's use them for stuff! # # If you are like most people, there are probably still a couple of barriers between you and quantum awesomeness # * You don't know what quantum computers are, or how to program them; # * You wouldn't know what to do with them anyway. # # This workshop aims to fix this. You will learn everything there is to know about the basic building block of quantum computing: the qubit. You'll then be challenged to use your new knowledge in a simple and creative task: creating a map for a computer game. # # Once you finish this short workshop, you'll still be left with some important questions. Such as why large collections of qubits are hard to simulate, and how they can do things that even a planet-size supercomputer never could. To help you with this, we'll show you some resources to continue your quantum journey. But before that, your journey of a thousand quantum programs must begin with a single qubit. # ## Introduction to the PewPew # # The [PewPew](https://pewpew.readthedocs.io/en/latest/) is a handheld games console with 6 buttons and 64 pixels. # # <img src="images/pewpew.jpg" width="750"/> # # It provides a perfect environment for people to get their first taste of programming or game design. In this workshop we will also use it to get people started with quantum computing. # # ### How to run PewPew programs # # Every code cell in this notebook that begins with `import pew` is a standalone program. To run them, pick one of the following three options. # # * Run on an actual PewPew by connecting it to your computer, and then copying the program into the `main.py` file on the device. # # * Run it in conjugation with the Pygame-based emulator for the PewPew. You can do this by using a web-hosted service such as [this one](https://repl.it/@quantum_jim/pewpewtutorials) (Note that this is an external site, unaffiliated with Qiskit or IBM). You could also download all the files there. The `main.py` file is then were you put your programs, and run them on your own computer. # # * Run the cells in this notebook on your own computer to use a Matplotlib-based emulator. You'll first need to open and run [this notebook](controller.ipynb) to get the controller, and use both notebooks at the same time. # # If you are using the third option, start by firing up the matplotlib magic. # %matplotlib notebook # ### Your first PewPew program # # Let's start with the most minimal example of a program for the PewPew. We will simply light up one of the pixels. This is done with the command `screen.pixel(X,Y,B)`, where `X` and `Y` are the coordinates of the pixel (each a number from 0 to 7) and `B` is the brightness (0 for off, and then 1, 2 and 3 from dim to bright). # # Here is a program that lights up the pixel at position X=6, Y=6 with maximum brightness, and sets the rest to a medium brightness. # + import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with medium brightness pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) B = 3 # set brightness screen.pixel(6,6,B) # put a bright pixel at (6,6) pew.show(screen) # update screen to display the above changes pew.tick(5) # pause for 5 seconds before quitting # - # The PewPew's buttons allow you to interact with what is happening on screen. To implement this, we need a loop to allow the program to keep periodically checking for input. # # The input is described by `keys=pew.keys()`, which takes certain values depending on which button is being pressed. Pressing 'Up' gives the value described by `pew.K_UP`, and so on. Pressing multiple buttons will give a value that describes the combination. To filter out whether a given button is pressed we therefore use Python's `&` operation, such as `keys&pew.K_UP` to check for 'Up'. # # Using this information, we can construct `if`-`else` statements to control what the program does when a button is pressed. We'll simply use the 'Up' button (up arrow on a keyboard) to control whether the pixel at (6,6) is on or not. # + import pew # setting up tools for the pewpew pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with medium brightness pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) B = 3 # set initial brightness pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, increase brightness of pixel at at (6,6) B = min(B+1,3) if keys&pew.K_DOWN: # if DOWN is pressed, decrease brightness of pixel at at (6,6) B = max(B-1,0) if keys: pressing = True else: if not keys: pressing = False screen.pixel(6,6,B) # put a pixel at (6,6) with current brightness pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second # - # ## Introduction to MicroQiskit # # Qiskit is the largest, most feature rich and most well developed framework for quantum computing. This is obviously a good thing in general, but it can be overwhelming for those getting started. # # For that reason, we have created MicroQiskit: the smallest, least feature rich and least developed framework for quantum computing! It has everything you need to get to know single and two qubit circuits, and do so with the same syntax as Qiskit. By mastering MicroQiskit, you'll be well on your way to mastering Qiskit. # # MicroQiskit has also been designed to be able to work on microcontroller devices. This includes the PewPew, as well as many other devices used for education and hobbies. It is compatible with MicroPython and CircuitPython, both of which are minimal implementations of Python designed to run on microcontrollers. Many Python packages have minimal versions made to be compatible with these implementations. MicroQiskit is similarly the MicroPython-compatible version of Qiskit. # # ## Basics of MicroQiskit (and Qiskit) # # ### Quantum Circuits # # The heart of quantum computing is the circuit. In Qiskit and MicroQiskit, our circuit is represented by a Python object, known as the `QuantumCircuit` object. The following line creates such an object, and names it `qc`. # # ```python # qc = QuantumCircuit(n,n) # ``` # # Here the first `n` is the number of qubits, and the second `n` is the number of output bits. In Qiskit, these can be different numbers in general. However, they are often simply chosen to be equal. MicroQiskit restricts us to this standard case. MicroQiskit also retricts to `n` being either 1 or 2, as it cannot simulate larger numbers of qubits. Many interesting things can be done with just two qubits, so this will not hamper us. However, Qiskit supports any number of qubits. # # ### Quantum gates # # The gates that can be added to a quantum circuit are # # ```python # qc.x(j) # qc.h(j) # qc.rx(theta,j) # qc.rz(theta,j) # qc.ry(theta,j) # qc.cx(j,k) # ``` # # Here `j` is the number representing the qubit: `0` for a single qubit circuit, or `0` and `1` for a two qubit circuit. # # Other gates are also available in Qiskit. However, since everything can be built out of the basic operations we have here, nothing is lost in MicroQiskit by restricting to them. # # ### Measurements # # Measurement is the process of extracting an output from a qubit. These outputs take the form of normal bits. There are an infinite number of ways we can choose to do this, but normally we stick to just three. The most common is the *z measurement*, which is performed using the command # # ```python # # z measurement of qubit j # qc.measure(j,j) # ``` # # This measures qubit `j` and places the result in output bit `j`. In Qiskit, these two arguments do not neccessarily need to be equal: the labelling of a qubit and the bit used for its output can be different. However, they are often chosen to be the same. MicroQiskit only supports this standard case, so the two arguments must be equal. # # The other standard forms of measurement are the *x measurement*, which is performed using # # ```python # # x measurement of qubit j # qc.h(j) # qc.measure(j,j) # ``` # # and the *y measurement* # # ```python # # y measurement of qubit j # qc.rx(pi/2,j) # qc.measure(j,j) # ``` # # Measurements in Qiskit can be placed at any point in the circuit. The simulators of Qiskit will quite happily run such quantum programs. However, when running on current prototype quantum hardware, the only supported case is to have all measurements made at the very end. This is also only case supported by MicroQiskit, so no gates for a given qubit should be placed after its measurement. # # # # ### Simulating a Circuit # # In standard Qiskit, circuits can be run on various simulators as well as real quantum devices. # # Yes! That's what I said! Real prototype quantum processes are sitting on the cloud, waiting for you to experiment with. It's free and available to all. Check it out [here](https://quantum-computing.ibm.com/). # # Since there are many ways to run a quantum circuit with Qiskit, the procedure for running circuits and extracting results in Qiskit is designed to handle all these various use cases. # # In MicroQiskit, there is only one way to run a circuit: to simulate it on the MicroQiskit simulator. For this reason, running circuits is slightly easier in MicroQiskit. The process is implemented by a single function, called `simulate()`. This has an argument `shots`, which determines how many times you wish to repeatedly run the circuit to extract statistics. It also has an argument `get` which determines the form in which the results are given. # # For example, to get a list of `shots=5` output bit strings, use # # ```python # m = simulate(qc,shots=5,get='memory') # ``` # # The result will look something like `m = ['1','0','1','0','0']`. # # To get a dictionary detailing how many of `shots=1024` samples result in each output, use # # ```python # c = simulate(qc,shots=1024,get='counts') # ``` # # The result will look something like `c = {'0':502,'1':522}`. # # To get a state vector describing the state at output, no measurement gates or output bits are required. You are therefore able to initialize the circuit with # # ```python # qc = QuantumCircuit(n) # ``` # # The state vector is extracted with # # ```python # state = simulate(qc,shots=1024,get='statevector') # ``` # # The Qiskit equivalents of the commands listed above are very similar to their MicroQiskit counterparts. Specifically, they are # # ```python # m = execute(qc,backend,shots=5,memory=True).result().get_memory() # c = execute(qc,backend,shots=1024).result().get_counts() # state = execute(qc,backend,shots=1024).result().get_statevector() # ``` # # Note also that the format for complex numbers in the statevector is different in MicroQiskit. A complex number of the form $a + i b$ is represented by the list `[a,b]` in MicroQiskit, rather than `a + bj` as in Qiskit. A statevector composed only of real numbers can be initialized with a list of real numbers as normal. # # # # # ## A Qubit on the PewPew # # We will now use our quantum tools on the PewPew. To do this, take the file named 'MicroQiskit.py', included in this folder, and place it on your PewPew. You will then be able to run the program below. If you are running an emulator on your own device, make sure that 'MicroQiskit.py' is in the same folder as the 'Pew.py' file. # # The following program shows a simple example of using MicroQiskit. Two circuits are created # # ```python # qc = QuantumCircuit(1,1) # ``` # # and # # ```python # m_z = QuantumCircuit(1,1) # m_z.measure(0,0) # ``` # # The first is the main circuit that will hold our quantum program. The second simply provides the measurement needed at the end. The final circuit that is run is `qc+m_z`, which corresponds to the contents of `qc`, following by those of `m_z`. # # The end result of the circuit is used to set the brightness of the pixel at (6,6), with it going dark for the output `0`, and bright for `1`. # # The 'Up' and 'Down' buttons can be used to add gates to `qc`. The 'Up' button is used for `x`. This acts like a classical NOT gate by flipping between `0` and `1`. The 'Down' button adds `h`, a gate which will need a little explanation. But first, experiment for yourself. # + import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit full_circuit = qc + m_z bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 screen.pixel(6,6,B) # put a pixel at (6,1) with current brightness pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second # - # If you start with a qubit that is certain to output `0`, and then apply an `h`, you get a random result. But apply it again, and you are back to a certain `0`. Similarly, if you start with a certain output of `1`, a single `h` creates randomness. But another `h` gets you back to `1`. # # This shows us something important about `h`. Though it seems to create randomness, it does not do it in the same way as a dice roll or coin flip. The information about the initial state is not forgotten. It is just moved somewhere. But where? # # To answer this question, we'll use 'O' to change between making a z mesurement, and making an x measurement. The outcome for an x measurement will then be display on pixel (1,1). # + import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) basis = 'z' # set initial measurement basis pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys&pew.K_O: basis = (basis=='z')*'x' + (basis=='x')*'z' if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit if basis=='z': full_circuit = qc + m_z elif basis=='x': full_circuit = qc + m_x bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 if basis=='z': screen.pixel(6,6,B) screen.pixel(1,1,2) elif basis=='x': screen.pixel(6,6,2) screen.pixel(1,1,B) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second # - # Whenever the output of a one of these measurements is certain, the output for the other is random. The `h` gate simply swaps information between the two bases. # # Let's add in the y measurement too, as well as another gate. # + import pew # setting up tools for the pewpew from microqiskit import QuantumCircuit, simulate # setting up tools for quantum from math import pi pew.init() # initialize the game engine... screen = pew.Pix() # ...and the screen # fill the screen with dim pixels for X in range(8): for Y in range(8): screen.pixel(X,Y,2) pew.show(screen) # update screen to display the above changes qc = QuantumCircuit(1,1) # create an empty single qubit circuit # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) # create a circuit that measures the qubit in the y basis m_y = QuantumCircuit(1,1) m_y.rx(pi/2,0) m_y.measure(0,0) basis = 'z' # set initial measurement basis pressing = False while True: # loop which checks for user input and responds keys = pew.keys() # get current key presses if not pressing: if keys&pew.K_X: # pressing X turns off the program break if keys&pew.K_UP: # if UP is pressed, add an x gate qc.x(0) if keys&pew.K_DOWN: # if DOWN is pressed, add an h gate qc.h(0) if keys&pew.K_LEFT: # if LEFT is pressed, add a sqrt(x) gate qc.rx(pi/2,0) if keys&pew.K_O: basis = (basis=='z')*'x' + (basis=='x')*'y'+ (basis=='y')*'z' if keys: pressing = True else: if not keys: pressing = False # get the output from the current circuit if basis=='z': full_circuit = qc + m_z elif basis=='x': full_circuit = qc + m_x elif basis=='y': full_circuit = qc + m_y bit = simulate(full_circuit,shots=1,get='memory')[0] # set the brightness of 6,6 according to the output if bit=='1': B = 3 else: B = 0 if basis=='z': screen.pixel(6,6,B) screen.pixel(6,1,2) screen.pixel(1,1,2) elif basis=='x': screen.pixel(6,6,2) screen.pixel(6,1,2) screen.pixel(1,1,B) elif basis=='y': screen.pixel(6,6,2) screen.pixel(6,1,B) screen.pixel(1,1,2) pew.show(screen) # update screen to display the above changes pew.tick(1/6) # pause for a sixth of a second # - # The gate on the 'Left' button is `qc.rx(pi/2,0)`. There are two important things to note about its effects. # # Firstly, let's look at the effects of applying it once. This allows the output of the y measurement to be certain, and makes the other two random. # # With all the gates available, we will find that whenever the output for one measurement type is certain, the others are completely random. The gates allow us change the bit value, move it around. # # The reason that qubits behave in this way is that they are quantum objects, and are therefore bound to obey Heisenberg's uncertainty principle. # # Despite the multiple ways to extract a bit from a qubit, a qubit is only able to store a single bit. It has a single bit's worth of certainty that it shares among the x, y and z basis. When one is certain of what that bit is, the others must be completely uncertain. # # To explore this gate further, we need to look at the maths behind the single qubit. Fortunately, this is quite simple to visualize, but we'll need to leave the PewPew to do it. # ## Visualizing Qubit Rotations # We'll now use some tools from the full version of Qiskit to visualize single qubit circuits. # # Specifically, we set up the following function to take a quantum circuit as input and run it with each of the three types of measurment. The results are then collected in a from that can be plotted using the `plot_bloch_vector` tool from Qiskit. # # The easiest way to try this for yourself is to go to [this website](https://quantum-computing.ibm.com/jupyter), where Qiskit is already set up for you. If you don't already have a (free) account, you'll need to sign up first. # # You will need to click on the 'New Notebook' button. Then replace the contents of the first cell with the following and run it. # # If you are just running things in this notebook, simply run the cell here. # + # %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Set up tools for visualizing the Bloch sphere from math import pi def get_bloch(qc): # create a circuit that measures the qubit in the z basis m_z = QuantumCircuit(1,1) m_z.measure(0,0) # create a circuit that measures the qubit in the x basis m_x = QuantumCircuit(1,1) m_x.h(0) m_x.measure(0,0) # create a circuit that measures the qubit in the y basis m_y = QuantumCircuit(1,1) m_y.rx(pi/2,0) m_y.measure(0,0) shots = 2**14 # number of samples used for statistics bloch_vector = [] # look at each possible measurement for measure_circuit in [m_x, m_y, m_z]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 # the bloch vector needs the different between these values bloch_vector.append( probs['0'] - probs['1'] ) return bloch_vector # - # Let's first try it out on an empty circuit. qc = QuantumCircuit(1,1) # Remember that this circuit outputs a `0` with certainty for a z measurement, but is random for the others. plot_bloch_vector(get_bloch(qc)) # The state of the qubit is represented as a point in 3D space. The vertical axis corresponds to the probability of getting a `0` or a `1` for the z measurement. If the qubit is certain to output `0`, as we see here, the point lies at the top of the image. # # Now let's see what happens when the z measurement is certain to output `1`. # + qc = QuantumCircuit(1,1) qc.x(0) plot_bloch_vector(get_bloch(qc)) # - # Here the point is at the bottom. So the positions of these completely opposing outcomes are completely opposing points. # # We should also mention what is going on with the x and y axes. These correspond to the probability of the outputs for x and y measurements, respectively. Since these outputs are random, with no bias towards `0` or `1`, the points above lie in the middle of these axes. # # Now let's look at qubits that are certain of their outputs for the x measurement. First for `0`. # + qc = QuantumCircuit(1,1) qc.h(0) plot_bloch_vector(get_bloch(qc)) # - # Then for `1`. # + qc = QuantumCircuit(1,1) qc.x(0) qc.h(0) plot_bloch_vector(get_bloch(qc)) # - # Again, the states are represented by opposing points, this time represented as points along the x axis. # # The states with certain outcomes for the y measurement will hold no suprises. First `0` # + qc = QuantumCircuit(1,1) qc.rx(-pi/2,0) plot_bloch_vector(get_bloch(qc)) # - # And then `1`. # + qc = QuantumCircuit(1,1) qc.rx(pi/2,0) plot_bloch_vector(get_bloch(qc)) # - # So far we have mapped out six points. Now it's time to see why this visualization uses a sphere. For this we need to use some other gates. Specifically, let's try a few different numbers for the first argument of the `rx` gate. # # First, $1/8$ of what is required for an `x`. qc = QuantumCircuit(1,1) qc.rx(pi*1/8,0) plot_bloch_vector(get_bloch(qc)) # Then $2/8$. qc = QuantumCircuit(1,1) qc.rx(pi*2/8,0) plot_bloch_vector(get_bloch(qc)) # Now $3/8$. qc = QuantumCircuit(1,1) qc.rx(pi*3/8,0) plot_bloch_vector(get_bloch(qc)) # And finally $4/8=1/2$. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) plot_bloch_vector(get_bloch(qc)) # With this visualization, the `rx` gate can be understood as a rotation around the `x` axes, expressed in radians. A $\pi$ rotation flips the qubit on its head, flipping `0` to `1` and `1` to `0`, which is the effect we know from the `x` gate. Other angles explore other points along the way, but the qubit state always corresponds to somewhere on the surface of the sphere. This restriction is the form that Heisenberg's uncertainty principle takes for qubits: any point outside of the sphere is too certain of too many things. # # All other points on the sphere can also be reached, but this will require the gate `rz` as well. This is for rotations around the z axis. Starting from the same state as above, here is a $\pi/8$ rotation. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*1/8,0) plot_bloch_vector(get_bloch(qc)) # Now we add another $\pi/8$ rotation around the z axis. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*2/8,0) plot_bloch_vector(get_bloch(qc)) # And another. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*3/8,0) plot_bloch_vector(get_bloch(qc)) # And another. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*4/8,0) plot_bloch_vector(get_bloch(qc)) # You can similarly use `ry` for rotations around the y axes. Together, the world of the single qubit is under your control. qc = QuantumCircuit(1,1) qc.rx(pi*4/8,0) qc.rz(pi*4/8,0) qc.ry(-pi*1/8,0) plot_bloch_vector(get_bloch(qc)) # ## What next? # # Now you've done some learning, you might be eager to start actually doing something. If so, check out our idea for a mini [**Single qubit hackathon**](https://nbviewer.jupyter.org/github/quantumjim/MicroQiskit/blob/master/Terrain-Hackathon.ipynb). # # Also take a look at the [games people have made using quantum computing](https://mybinder.org/v2/gh/qiskit/qiskit-community-tutorials/master?filepath=ganes%2FHello_Qiskit.ipynb). These have game mechanics inspired by and implemented with qubits. Many of these use only the properties of a single qubit. So you are already ready to make quantum games! # # If you want to learn about more than one qubit, check out the [Qiskit Textbook](https://community.qiskit.org/textbook/). Chapter 1 starts off by giving a math-free taste of how quantum computers will work, and how qubits are unlike any variable in normal computers. Chapter 1 and Chapter 2 then go on to explain build up a mathematical description of qubits, which is then used in later chapters to explain how the devices can do useful things. # # Too stick with few qubits and no maths, check out [this puzzle game](http://ibm.biz/hello-qiskit). It visualizes and explains the inner workings of two qubits. # # [**Click here to return to the list of MicroQiskit resources**](https://github.com/quantumjim/MicroQiskit/blob/master/README.md)
PewPew-Qubit.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 # --- # ## Test GPT on Images # # After training minGPT using **TorchShard**, we test it on images. import numpy as np import torchvision import torch import torchshard as ts import matplotlib.pyplot as plt # %matplotlib inline # set up logging import logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) # make deterministic from mingpt.utils import set_seed set_seed(42) # pytorch helpfully makes it easy to download datasets, e.g. the common CIFAR-10 https://www.kaggle.com/c/cifar-10 root = './data' train_data = torchvision.datasets.CIFAR10(root, train=True, transform=None, target_transform=None, download=True) test_data = torchvision.datasets.CIFAR10(root, train=False, transform=None, target_transform=None, download=True) print(len(train_data), len(test_data)) # get random 5 pixels per image and stack them all up as rgb values to get half a million random pixels pluck_rgb = lambda x: torch.from_numpy(np.array(x)).view(32*32, 3)[torch.randperm(32*32)[:5], :] px = torch.cat([pluck_rgb(x) for x, y in train_data], dim=0).float() print(px.size()) # + # run kmeans to get our codebook # def kmeans(x, ncluster, niter=10): # N, D = x.size() # c = x[torch.randperm(N)[:ncluster]] # init clusters at random # for i in range(niter): # # assign all pixels to the closest codebook element # a = ((x[:, None, :] - c[None, :, :])**2).sum(-1).argmin(1) # # move each codebook element to be the mean of the pixels that assigned to it # c = torch.stack([x[a==k].mean(0) for k in range(ncluster)]) # # re-assign any poorly positioned codebook elements # nanix = torch.any(torch.isnan(c), dim=1) # ndead = nanix.sum().item() # print('done step %d/%d, re-initialized %d dead clusters' % (i+1, niter, ndead)) # c[nanix] = x[torch.randperm(N)[:ndead]] # re-init dead clusters # return c ncluster = 512 # with torch.no_grad(): # C = kmeans(px, ncluster, niter=8) # torch.save(C, 'c.pt') # assume we have saved C pt at the fisrt time # then we just load it after that C = torch.load('c.pt', map_location='cpu') print(C.size()) # - # encode the training examples with our codebook to visualize how much we've lost in the discretization n_samples = 16 ncol = 8 nrow = n_samples // ncol + 1 plt.figure(figsize=(20, 10)) for i in range(n_samples): # encode and decode random data x, y = train_data[np.random.randint(0, len(train_data))] xpt = torch.from_numpy(np.array(x)).float().view(32*32, 3) ix = ((xpt[:, None, :] - C[None, :, :])**2).sum(-1).argmin(1) # cluster assignments for each pixel # these images should look normal ideally plt.subplot(nrow, ncol, i+1) plt.imshow(C[ix].view(32, 32, 3).numpy().astype(np.uint8)) plt.axis('off') # The images above look relatively reasonable, so our 512-sized codebook is enough to reasonably re-represent RGB values. Ok cool. So now every image is just a 1024-long sequence of numbers between 0..511. Time to train a GPT. # + from torch.utils.data import Dataset class ImageDataset(Dataset): """ wrap up the pytorch CIFAR-10 dataset into our own, which will convert images into sequences of integers """ def __init__(self, pt_dataset, clusters, perm=None): self.pt_dataset = pt_dataset self.clusters = clusters self.perm = torch.arange(32*32) if perm is None else perm self.vocab_size = clusters.size(0) self.block_size = 32*32 - 1 def __len__(self): return len(self.pt_dataset) def __getitem__(self, idx): x, y = self.pt_dataset[idx] x = torch.from_numpy(np.array(x)).view(-1, 3) # flatten out all pixels x = x[self.perm].float() # reshuffle pixels with any fixed permutation and -> float a = ((x[:, None, :] - self.clusters[None, :, :])**2).sum(-1).argmin(1) # cluster assignments return a[:-1], a[1:] # always just predict the next one in the sequence train_dataset = ImageDataset(train_data, C) test_dataset = ImageDataset(test_data, C) train_dataset[0][0] # one example image flattened out into integers # - # # For reference, **iGPT-S** from the paper is: # - batch size of 128 and trained for 1M terations # - Adam lr 0.003 with betas = (0.9, 0.95) # - learning rate is warmed up for one epoch, then decays to 0 # - did not use weight decay or dropout # - `n_layer=24, n_head=8, n_embd=512` # # We will do something similar but smaller # + from mingpt.model import GPT, GPTConfig, GPT1Config # we'll do something a bit smaller mconf = GPTConfig(train_dataset.vocab_size, train_dataset.block_size, embd_pdrop=0.0, resid_pdrop=0.0, attn_pdrop=0.0, n_layer=12, n_head=8, n_embd=256, enable_model_parallel=False) model = GPT(mconf) # + from mingpt.trainer import Trainer, TrainerConfig """ Note that I am running on an 8-GPU V100 machine so each GPU has 32GB. If you don't have as many computational resources you have to bring down the batch_size until the model fits into your memory, and then you may also need to adjust the learning rate (e.g. decrease it a bit). Alternatively, you can use an even smaller model up above, bringing down the number of layers, number of heads, and the embedding size. """ tokens_per_epoch = len(train_data) * train_dataset.block_size train_epochs = 20 # todo run a bigger model and longer, this is tiny # initialize a trainer instance and kick off training tconf = TrainerConfig(max_epochs=train_epochs, batch_size=32, learning_rate=3e-3, betas = (0.9, 0.95), weight_decay=0, lr_decay=True, warmup_tokens=tokens_per_epoch, final_tokens=train_epochs*tokens_per_epoch, ckpt_path='cifar10_model.pt', num_workers=16) trainer = Trainer(model, train_dataset, test_dataset, tconf) # trainer.train() # skip training # - # to sample we also have to technically "train" a separate model for the first token in the sequence # we are going to do so below simply by calculating and normalizing the histogram of the first token counts = torch.ones(ncluster) # start counts as 1 not zero, this is called "smoothing" rp = torch.randperm(len(train_dataset)) nest = 5000 # how many images to use for the estimation for i in range(nest): a, _ = train_dataset[int(rp[i])] t = a[0].item() # index of first token in the sequence counts[t] += 1 prob = counts/counts.sum() # load the state of the best model we've seen based on early stopping checkpoint = torch.load('cifar10_model.pt') model.load_state_dict(checkpoint, strict=False) # + # %%time from mingpt.utils import sample n_samples = 32 start_pixel = np.random.choice(np.arange(C.size(0)), size=(n_samples, 1), replace=True, p=prob) start_pixel = torch.from_numpy(start_pixel).to(trainer.device) pixels = sample(model, start_pixel, 32*32-1, temperature=1.0, sample=True, top_k=100) # + # for visualization we have to invert the permutation used to produce the pixels iperm = torch.argsort(train_dataset.perm) ncol = 8 nrow = n_samples // ncol plt.figure(figsize=(16, 8)) for i in range(n_samples): pxi = pixels[i][iperm] # note: undo the encoding permutation plt.subplot(nrow, ncol, i+1) plt.imshow(C[pxi].view(32, 32, 3).numpy().astype(np.uint8)) plt.axis('off') # - # visualize some of the learned positional embeddings, maybe they contain structure plt.figure(figsize=(5, 5)) nsee = 8*8 ncol = 8 nrow = nsee // ncol for i in range(nsee): ci = model.pos_emb.data[0, :, i].cpu() zci = torch.cat((torch.tensor([0.0]), ci)) # pre-cat a zero rzci = zci[iperm] # undo the permutation to recover the pixel space of the image plt.subplot(nrow, ncol, i+1) plt.imshow(rzci.view(32, 32).numpy()) plt.axis('off') # + # huh, pretty cool! :P # TorchShard is not bad! :P # -
projects/minGPT/valid.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 # --- # # Revision history of Wikipedia articles # # ### Inspired by <NAME>'s "Who writes Wikipedia?" # # Work in progress... # + # Import classes used in this notebook import urllib.request import re import pandas as pd # %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn') # + def GetRevisions(pageTitle): # Format is xml because it's preferred for 'rvcontinue'. See https://www.mediawiki.org/wiki/API:Revisions url = "https://en.wikipedia.org/w/api.php?action=query&format=xml&prop=revisions&rvprop=timestamp|user|size&rvlimit=500&titles=" + pageTitle revisions = [] # list of all accumulated revisions next = '' # information for the next request while True: response = urllib.request.urlopen(url + next).read().decode('utf-8') # web request, error without .decode('utf-8') revisions += re.findall('<rev [^>]*>', response) # adds all revisions from the current request to the list cont = re.search('<continue rvcontinue="([^"]+)"', response) if not cont: # break the loop if 'continue' element missing break next = "&rvcontinue=" + cont.group(1) # gets the revision Id from which to start the next request return revisions; # Could the RegEx string parsing from result_to_dataframe() be incorporated into this already? # - # # Insert Wikipedia page title below # # Insert the article title of your choosing in the GetRevisions() function below. # # Check you have the corroct page title! It's case sensitive and spaces are underscores. You can take the title from the page URL. # # For example, for https://en.wikipedia.org/wiki/Aaron_Swartz the page title is "Aaron_Swartz". # # So to get the revisions history for the article put it into the function in the cell below in quotation marks like so: # # ```python # GetRevisions("Aaron_Swartz") # ``` # # Then run all subsequent cells or click 'Kernel' in the menu bar and select 'Restart Kernel and Run All Cells...' # # Depending on the article size it may take several seconds to gather all the data. # + revisions = GetRevisions("Diabetes_mellitus") # Wikipedia article titles are case sensitive and spaces are underscores # Make sure the title corresponds to Wikipedia's title - you can take it from the URL # e.g. "Diabetes" is actually "Diabetes_mellitus", "Diabetes" returns differnt results # - # ### Number of article revisions to date: # API returns a list of strings so the number of items in the list == number of revisions len(revisions) def result_to_dataframe(): """Loops over the the 'revisions' list and extracts user, timestamp, revision size values. Returns: pandas dataframe""" # Initiate an empty list of list for future dataframe data = [[],[],[]] # These will be column headers of the returned dataframe headers = ['user', 'time', 'size'] for i in revisions: # Find username to extract userMatch = re.search('user="(.+?)"', i) # Catch missing values throwing AttributeError if userMatch is not None: user = userMatch.group(1) else: user = "" # Add result to the first list of lists in 'data' data[0].append(user) # Find timestamp to extract timeMatch = re.search('timestamp="(.+?)"', i) # Catch missing values throwing AttributeError if timeMatch is not None: time = timeMatch.group(1) else: time = "" # how is this handled in the chart? # Add result to the second list of lists in 'data' data[1].append(time) # Find revision size to extract sizeMatch = re.search('size="(.+?)"', i) # Catch missing values throwing AttributeError if sizeMatch is not None: size = sizeMatch.group(1) else: size = "" # how to handle this is the chart? # Add result to the third list of lists in 'data' data[2].append(size) return pd.DataFrame(dict(zip(headers, data))) # NOTE: Alternative return: pd.DataFrame(data=data).T # But simply transposing the dataframe with the transpose method # would only work if we didn't assign the headers in the same step # therefore the (dict(zip(____,____))) is preferable here # Can this be incorporated into the 'return' in the function above? df = result_to_dataframe() df.set_index('time', inplace=True); df.index = pd.to_datetime(df.index, infer_datetime_format=True) df['size'] = pd.to_numeric(df['size']) # size is article length after revision, not size of revision df.sort_index(); df['edit'] = df['size'] - df['size'].shift(-1) # + # Just some formatting parameters plt.figure(figsize=(16,9)) # Increase the plot size to 16 x 9 plt.title('Article length over time - edit by edit', color='grey', size='xx-large') plt.xticks(size='large', color='grey') # Grey color to show on my dark theme and also white background plt.yticks(size='large', color='grey') # Units are bytes y = df['size'] x = df.index plt.plot(x,y); # + df2 = df.resample('A').max() plt.figure(figsize=(16,9)) # Increase the plot size to 16 x 9 plt.title('Article length over time - year by year', color='grey', size='xx-large') plt.xticks(size='large', color='grey') # Grey color to show on my dark theme and also white background plt.yticks(size='large', color='grey') # Units are bytes y2 = df2['size'] x2 = df2.index plt.plot(x2,y2); # Idea: Add four or more figures: actual, H, D, W, M, A # Or H to A in different colour lines in the same figure # - # ### Top ten vandalisms df.sort_values(by=['edit'],ascending=True, inplace=False).head(10) # ### Reversals of vandalisms df.sort_values(by=['edit'],ascending=False, inplace=False).head(10) # ### Top contributors v top editors (not bots, not vandalism reversals) # # TBC
MediaWikiAPIrevisions.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 # --- # # Beta Regression # # This example has been contributed by <NAME> ([\@tjburch](https://github.com/tjburch) on GitHub). import arviz as az import bambi as bmb import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as pm from scipy import stats from scipy.special import expit az.style.use("arviz-darkgrid") # In this example, we'll look at using the **Beta distribution** for regression models. The Beta distribution is a probability distribution bounded on the interval [0, 1], which makes it well-suited to model probabilities or proportions. In fact, in much of the Bayesian literature, the Beta distribution is introduced as a prior distribution for the probability $p$ parameter of the Binomial distribution (in fact, it's the conjugate prior for the Binomial distribution). # ## Simulated Beta Distribution # # To start getting an intuitive sense of the Beta distribution, we'll model coin flipping probabilities. Say we grab all the coins out of our pocket, we might have some fresh from the mint, but we might also have some old ones. Due to the variation, some may be slightly biased toward heads or tails, and our goal is to model distribution of the probabilities of flipping heads for the coins in our pocket. # # Since we trust the mint, we'll say the $\alpha$ and $\beta$ are both large, we'll use 1,000 for each, which gives a distribution spanning from 0.45 to 0.55. alpha = 1_000 beta = 1_000 p = np.random.beta(alpha, beta, size=10_000) az.plot_kde(p) plt.xlabel("$p$"); # Next, we'll use Bambi to try to recover the parameters of the Beta distribution. Since we have no predictors, we can do a intercept-only model to try to recover them. data = pd.DataFrame({"probabilities": p}) model = bmb.Model("probabilities ~ 1", data, family="beta") fitted = model.fit() az.plot_trace(fitted); az.summary(fitted) # The model fit, but clearly these parameters are not the ones that we used above. For Beta regression, we use a linear model for the mean, so we use the $\mu$ and $\sigma$ formulation. To link the two, we use # # $\alpha = \mu \kappa$ # # $\beta = (1-\mu)\kappa$ # # and $\kappa$ is a function of the mean and variance, # # $\kappa = \frac{\mu(1-\mu)}{\sigma^2} - 1$ # # Rather than $\sigma$, you'll note Bambi returns $\kappa$. We'll define a function to retrieve our original parameters. # + def mukappa_to_alphabeta(mu, kappa): # Calculate alpha and beta alpha = mu * kappa beta = (1 - mu) * kappa # Get mean values and 95% HDIs alpha_mean = alpha.mean(["chain", "draw"]).values alpha_hdi = az.hdi(alpha, hdi_prob=.95)["x"].values beta_mean = beta.mean(["chain", "draw"]).values beta_hdi = az.hdi(beta, hdi_prob=.95)["x"].values return alpha_mean, alpha_hdi, beta_mean, beta_hdi alpha, alpha_hdi, beta, beta_hdi = mukappa_to_alphabeta( expit(fitted.posterior["Intercept"]), fitted.posterior["probabilities_kappa"] ) print(f"Alpha - mean: {np.round(alpha)}, 95% HDI: {np.round(alpha_hdi[0])} - {np.round(alpha_hdi[1])}") print(f"Beta - mean: {np.round(beta)}, 95% HDI: {np.round(beta_hdi[0])} - {np.round(beta_hdi[1])}") # - # We've managed to recover our parameters with an intercept-only model. # ## Beta Regression with Predictors # Perhaps we have a little more information on the coins in our pocket. We notice that the coins have accumulated dirt on either side, which would shift the probability of getting a tails or heads. In reality, we would not know how much the dirt affects the probability distribution, we would like to recover that parameter. We'll construct this toy example by saying that each micron of dirt shifts the $\alpha$ parameter by 5.0. Further, the amount of dirt is distributed according to a Half Normal distribution with a standard deviation of 25 per side. # # We'll start by looking at the difference in probability for a coin with a lot of dirt on either side. # + effect_per_micron = 5.0 # Clean Coin alpha = 1_000 beta = 1_000 p = np.random.beta(alpha, beta, size=10_000) # Add two std to tails side (heads more likely) p_heads = np.random.beta(alpha + 50 * effect_per_micron, beta, size=10_000) # Add two std to heads side (tails more likely) p_tails = np.random.beta(alpha - 50 * effect_per_micron, beta, size=10_000) az.plot_kde(p, label="Clean Coin") az.plot_kde(p_heads, label="Biased toward heads", plot_kwargs={"color":"C1"}) az.plot_kde(p_tails, label="Biased toward tails", plot_kwargs={"color":"C2"}) plt.xlabel("$p$") plt.ylim(top=plt.ylim()[1]*1.25); # - # Next, we'll generate a toy dataset according to our specifications above. As an added foil, we will also assume that we're limited in our measuring equipment, that we can only measure correctly to the nearest integer micron. # + # Create amount of dirt on top and bottom heads_bias_dirt = stats.halfnorm(loc=0, scale=25).rvs(size=1_000) tails_bias_dirt = stats.halfnorm(loc=0, scale=25).rvs(size=1_000) # Create the probability per coin alpha = np.repeat(1_000, 1_000) alpha = alpha + effect_per_micron * heads_bias_dirt - effect_per_micron * tails_bias_dirt beta = np.repeat(1_000, 1_000) p = np.random.beta(alpha, beta) df = pd.DataFrame({ "p" : p, "heads_bias_dirt" : heads_bias_dirt.round(), "tails_bias_dirt" : tails_bias_dirt.round() }) df.head() # - # Taking a look at our new dataset: # + fig,ax = plt.subplots(1,3, figsize=(16,5)) df["p"].plot.kde(ax=ax[0]) ax[0].set_xlabel("$p$") df["heads_bias_dirt"].plot.hist(ax=ax[1], bins=np.arange(0,df["heads_bias_dirt"].max())) ax[1].set_xlabel("Measured Dirt Biasing Toward Heads ($\mu m$)") df["tails_bias_dirt"].plot.hist(ax=ax[2], bins=np.arange(0,df["tails_bias_dirt"].max())) ax[2].set_xlabel("Measured Dirt Biasing Toward Tails ($\mu m$)"); # - # Next we want to make a model to recover the effect per micron of dirt per side. So far, we've considered the biasing toward one side or another independently. A linear model might look something like this: # # $ p \text{ ~ Beta}(\mu, \sigma)$ # # $logit(\mu) = \text{ Normal}( \alpha + \beta_h d_h + \beta_t d_t)$ # # Where $d_h$ and $d_t$ are the measured dirt (in microns) biasing the probability toward heads and tails respectively, $\beta_h$ and $\beta_t$ are coefficients for how much a micron of dirt affects each independent side, and $\alpha$ is the intercept. Also note the logit link function used here, since our outcome is on the scale of 0-1, it makes sense that the link must also put our mean on that scale. Logit is the default link function, however Bambi supports the identity, probit, and cloglog links as well. # # In this toy example, we've constructed it such that dirt should not affect one side differently from another, so we can wrap those into one coefficient: $\beta = \beta_h = -\beta_t$. This makes the last line of the model: # # $logit(\mu) = \text{ Normal}( \alpha + \beta \Delta d)$ # # where # # $\Delta d = d_h - d_t$ # # Putting that into our dataset, then constructing this model in Bambi, df["delta_d"] = df["heads_bias_dirt"] - df["tails_bias_dirt"] dirt_model = bmb.Model("p ~ delta_d", df, family="beta") dirt_fitted = dirt_model.fit() dirt_model.predict(dirt_fitted, kind="pps", draws=1000) az.summary(dirt_fitted) az.plot_ppc(dirt_fitted); # Next, we'll see if we can in fact recover the effect on $\alpha$. Remember that in order to return to $\alpha$, $\beta$ space, the linear equation passes through an inverse logit transformation, so we must apply this to the coefficient on $\Delta d$ to get the effect on $\alpha$. The inverse logit is nicely defined in `scipy.special` as `expit`. mean_effect = expit(dirt_fitted.posterior.delta_d.mean()) hdi = az.hdi(dirt_fitted.posterior.delta_d, hdi_prob=.95) lower = expit(hdi.delta_d[0]) upper = expit(hdi.delta_d[1]) print(f"Mean effect: {mean_effect.item():.4f}") print(f"95% interval {lower.item():.4f} - {upper.item():.4f}") # The recovered effect is very close to the true effect of 0.5. # ## Example - Revisiting Baseball Data # In the [Hierarchical Logistic regression with Binomial family](https://bambinos.github.io/bambi/main/notebooks/hierarchical_binomial_bambi.html) notebook, we modeled baseball batting averages (times a player reached first via a hit per times at bat) via a Hierarchical Logisitic regression model. If we're interested in league-wide effects, we could look at a Beta regression. We work off the assumption that the league-wide batting average follows a Beta distribution, and that individual player's batting averages are samples from that distribtuion. # # First, load the Batting dataset again, and re-calculate batting average as hits/at-bat. In order to make sure that we have a sufficient sample, we'll require at least 100 at-bats in order consider a batter. Last, we'll focus on 1990-2018. batting = bmb.load_data("batting") batting["batting_avg"] = batting["H"] / batting["AB"] batting = batting[batting["AB"] > 100] df = batting[ (batting["yearID"] > 1990) & (batting["yearID"] < 2018) ] df.batting_avg.hist(bins=30) plt.xlabel("Batting Average") plt.ylabel("Count"); # If we're interested in modeling the distribution of batting averages, we can start with an intercept-only model. model_avg = bmb.Model("batting_avg ~ 1", df, family="beta") avg_fitted = model_avg.fit() az.summary(avg_fitted) # Looking at the posterior predictive, posterior_predictive = model_avg.predict(avg_fitted, kind="pps", draws=1000) az.plot_ppc(avg_fitted); # This appears to fit reasonably well. If, for example, we were interested in simulating players, we could sample from this distribution. # # However, we can take this further. Say we're interested in understanding how this distribution shifts if we know a player's batting average in a previous year. We can condition the model on a player's n-1 year, and use Beta regrssion to model that. Let's construct that variable, and for sake of ease, we will ignore players without previous seasons. # Add the player's batting average in the n-1 year batting["batting_avg_shift"] = np.where( batting["playerID"] == batting["playerID"].shift(), batting["batting_avg"].shift(), np.nan ) df_shift = batting[ (batting["yearID"] > 1990) & (batting["yearID"] < 2018) ] df_shift = df_shift[~df_shift["batting_avg_shift"].isna()] df_shift[["batting_avg_shift","batting_avg"]].corr() # There is a lot of variance in year-to-year batting averages, it's not known to be incredibly predictive, and we see that here. A correlation coefficient of 0.23 is only lightly predictive. However, we can still use it in our model to get a better understanding. We'll fit two models. First, we'll refit the previous, intercept-only, model using this updated dataset so we have an apples-to-apples comparison. Then, we'll fit a model using the previous year's batting average as a predictor. # + model_avg = bmb.Model("batting_avg ~ 1", df_shift, family="beta") avg_fitted = model_avg.fit() model_lag = bmb.Model("batting_avg ~ batting_avg_shift", df_shift, family="beta") lag_fitted = model_lag.fit() # - az.summary(lag_fitted) az.compare({ "intercept-only" : avg_fitted, "lag-model": lag_fitted }) # Adding the predictor results in a higher loo than the intercept-only model. ppc= model_lag.predict(lag_fitted, kind="pps", draws=1000) az.plot_ppc(lag_fitted); # The biggest question this helps us understand is, for each point of batting average in the previous year, how much better do we expect a player to be in the current year? # + mean_effect = lag_fitted.posterior.batting_avg_shift.values.mean() hdi = az.hdi(lag_fitted.posterior.batting_avg_shift, hdi_prob=.95) lower = expit(hdi.batting_avg_shift[0]).item() upper = expit(hdi.batting_avg_shift[1]).item() print(f"Mean effect: {expit(mean_effect):.4f}") print(f"95% interval {lower:.4f} - {upper:.4f}") # + az.plot_hdi(df_shift.batting_avg_shift, lag_fitted.posterior_predictive.batting_avg, hdi_prob=0.95, color="goldenrod", fill_kwargs={"alpha":0.8}) az.plot_hdi(df_shift.batting_avg_shift, lag_fitted.posterior_predictive.batting_avg, hdi_prob=.68, color="forestgreen", fill_kwargs={"alpha":0.8}) intercept = lag_fitted.posterior.Intercept.values.mean() x = np.linspace(df_shift.batting_avg_shift.min(), df_shift.batting_avg_shift.max(),100) linear = mean_effect * x + intercept plt.plot(x, expit(linear), c="black") plt.xlabel("Previous Year's Batting Average") plt.ylabel("Batting Average");
docs/notebooks/beta_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 # --- # # Soluzione 'The Maze Challenge' - <NAME> (prushh) # ## Engine # Al fine di risolvere le varie Quest รจ stato necessario capire il funzionamento dell'engine, messo a disposizione grazie ai tre file eseguibili (rispettivamente per Linux, MacOS o Windows) e come interagire con esso tramite il modulo **mazeClient**. # Al suo interno troviamo due classi (**Commands**, **\_MazeCommand**) e la funzione `send_command(command)` che ci permetterร  di: # * Ricavare informazioni su nodo corrente, *GET_STATE* # * { # "userX": 14, # "userY": 10, # "userVal": 32, # "Neighbors": [ # { # "x": 14, # "y": 9, # "val": 82 # }, # { # "x": 14, # "y": 11, # "val": 71 # } # ] # } # * Muovere il cursore tra i vari nodi # * (x, y+1), *MOVE_LEFT* # * (x, y-1), *MOVE_RIGHT* # * (x+1, y), *MOVE_UP* # * (x-1, y), *MOVE_DOWN* # * Terminare l'esecuzione dell'engine # * *EXIT* # # Selezionando la finestra del processo in esecuzione, รจ inoltre possibile usare le frecce direzionali per muoversi in maniera molto rapida tra le celle. # Modificando il file **seed.maze** si potranno ottenere ulteriori labirinti distinti. # ## Argparse # ``` # usage: main.py file_path [--no_stats] [-c] [-d] [-h] # # 'The Maze Challenge' by MircoT # Solution by prushh # ------------------------------------------------------------ # There are two modes of use: # - Classic maze solver with stats # - Controller mode (disable stats) # You must specify mazeEngine.ext path for parallel execution. # # # positional arguments: # file_path executable file to start engine # # optional arguments: # -h, --help show this help message and exit # -c, --controller controller mode for interact with engine # --no_stats hide statistical information # -d, --debug print debug information and more # # ``` # ## Quests # ### 1. Muoviti e raccogli statistiche sul labirinto # Questa รจ stata la Quest a mio parere piรน impegnativa, non tanto per la raccolta di alcuni dati statistici ma per la realizzazione di un algoritmo che funzionasse correttamente per tutti i seed.<br> # Avendo a disposizione per ogni nodo una lista contenente i vicini per tutte e 8 le direzioni (4 raggiungibili + 4 diagonali), ho pensato di adattare il problema della visita in profonditร  di un grafo (DFS), immaginando ogni cella come un vertice appartenente ad esso.<br> # Una prima implementazione iterativa comprendeva l'ausilio di una *Stack* ma ho avuto problemi nel tornare indietro ad ispezionare nuovamente i *Neighbors* e di conseguenza ad aggiornare l'interfaccia; cosรฌ ho optato per una soluzione ricorsiva: def explore(self, cur_node: dict, last_act: str): ''' Core for maze solver. It is a recursive function inspired to Depth-First-Search logic. ''' neighbors = cur_node['Neighbors'] for neighbor in neighbors: if neighbor in self.__get_valid_neighbors(cur_node): if neighbor not in self.visited: self.visited.append(neighbor) self.__increment_coord_color(neighbor) self.__increment_color(neighbor['val']) action = self.__get_action(cur_node, neighbor) new_node = to_dict(get_response(action)) if args.debug: print(action) sleep(0.5) self.explore(new_node, action) elif neighbor not in self.visited: self.known.append(neighbor) # There are not other valid near node, # reverse last action and go back reverse_act = self.__reverse_action(last_act) get_response(reverse_act) if args.debug: print(reverse_act) sleep(0.5) # - Per ogni vicino in *Neighbors* controllo se รจ raggiungibile, escludo quindi i nodi diagonali che andrรฒ a considerare nell'altro ramo di selezione # - Piรน internamente, se questo vicino non รจ stato giร  visitato: # - lo aggiungo alla lista dei visitati # - aggiorno le varie strutture per memorizzare dati statistici # - ricavo l'azione per raggiungerlo e sposto il cursore # - richiamo la funzione `explore()` con i nuovi parametri # - La chiamata ricorsiva รจ terminata, inverto l'ultima azione e torno indietro # # Infine, per avere tutti i nodi memorizzati in una sola struttura, รจ necessario richiamare la seguente funzione che aggiunge alla lista dei nodi visitati i nodi diagonali conosciuti durante il tragitto, ma non raggiungibili fisicamente. def __fix_known(self): ''' Add the known neighbors to the visited ones. ''' for neighbor in self.known: if neighbor not in self.visited: print(neighbor) self.visited.append(neighbor) self.__increment_coord_color(neighbor) self.__increment_color(neighbor['val']) # ### 2. Conta le celle totali nel labirinto (Bianche, Rosse, Blu, Verdi) # ### 3. Conta il numero di celle Rosse, Blu e Verdi # Come detto in precedenza la raccolta dei dati non รจ stata complicata, ho utilizzato un dizionario inizializzato nel modo seguente: # ```python # self.colors_count = { # 'white': 0, # 'blue': 0, # '#00ff00': 0, # 'red': 0 # } # ``` # Con l'ausilio di questa struttura posso andare direttamente ad incrementare il valore specificando la *key*, abbiamo visto perรฒ che il colore rappresentato da *userVal* viene fornito sotto forma di codice, bisogna quindi effettuare una conversione: def __get_color_name(self, color: int) -> str: ''' Returns color name specified by int code. ex: 32 -> white ''' colors_code = { 32: 'white', 66: 'blue', 71: '#00ff00', 82: 'red' } return colors_code[color] # Una volta ottenuta la stringa che rappresenta il colore si puรฒ provvedere ad aggiornare le frequenze: def __increment_color(self, color: int): ''' Update the frequency of colors find in the maze. ''' self.colors_count[self.__get_color_name(color)] += 1 # Da `self.colors_count` possiamo quindi facilmente ricavare: # * numero totale di celle, utilizzando `sum(self.colors_count.values())` # * numero di celle per ogni colore # # Per riprendere confidenza con i plot questi dati sono stati visualizzati graficamente, utilizzando la funzione `plt_colors_dist(dict_)` reperibile in **statistics.py** # ### 4. Traccia l'istogramma della distribuzione della frequenza di colore per le coordinate X e Y # Anche in questo caso รจ stato utilizzato un dizionario, con all'interno due *key* giร  presenti: # ```python # self.colors_xy = {'x': {}, 'y': {}} # ``` # L'idea รจ quella di aggiungere per ogni nodo ispezionato la propria coordinata x come *key* in `self.colors_xy['x']` ed equivalentemente per y in `self.colors_xy['y']`. Dato che non conosciamo a priori le *sub-key* e bisognerร  contare per ognuna di esse la frequenza con la quale si ripete un colore, si รจ pensato di usare la funzione `setdefault(keyname, value)` per l'inizializzazione di ogni coordinata nel seguente modo: def __increment_coord_color(self, node: dict): ''' Update the color frequency distribution for XY coordinates. ''' x = node['x'] y = node['y'] c_code = node['val'] dict_ = { 'white': 0, 'blue': 0, '#00ff00': 0, 'red': 0 } # If key does not exists create # and fill it with default value self.colors_xy['x'].setdefault(x, dict_) self.colors_xy['y'].setdefault(y, dict_) self.colors_xy['x'][x][self.__get_color_name(c_code)] += 1 self.colors_xy['y'][y][self.__get_color_name(c_code)] += 1 # Come espressamente richiesto questi dati sono stati visualizzati graficamente, utilizzando la funzione `plt_xy_dist(xy_freq, old_xy_freq)` reperibile in **statistics.py** def plt_xy_dist(xy_freq: dict, old_xy_freq: dict): ''' Plot the histogram of the color frequency distribution for X e Y coordinates. If old_freq is not empty, show the previous distribution. ''' # Prepares colors list and labels colors = xy_freq['x'][list(xy_freq['x'].keys())[0]].keys() title = 'Colors distribution for XY coordinates' title_x = 'X distribution' title_y = 'Y distribution' old_title_x = f'Old {title_x}' old_title_y = f'Old {title_y}' ylabel = 'Number of cells' # Creates pandas.DataFrame (more simple to manage) and sort them for index # Current maze information df_x = pd.DataFrame.from_dict(xy_freq['x'], orient='index').sort_index() df_y = pd.DataFrame.from_dict(xy_freq['y'], orient='index').sort_index() # Create subplot ad customize it fig, axes = _dark_subplots(nrows=2, ncols=2) fig.suptitle(title, fontsize=15) df_x.plot.bar(figsize=(12, 8), ax=axes[0][0], yticks=_get_max_tick(df_x), color=colors, legend=False) df_y.plot.bar(ax=axes[0][1], yticks=_get_max_tick(df_y), color=colors, legend=False) axes[0][0].set(title=title_x, ylabel=ylabel) axes[0][1].set(title=title_y) if len(old_xy_freq): # Old maze information old_df_x = pd.DataFrame.from_dict(old_xy_freq['x'], orient='index').sort_index() old_df_y = pd.DataFrame.from_dict(old_xy_freq['y'], orient='index').sort_index() # Create subplot ad customize it old_df_x.plot.bar(ax=axes[1][0], yticks=_get_max_tick(old_df_x), color=colors, legend=False) old_df_y.plot.bar(ax=axes[1][1], yticks=_get_max_tick(old_df_y), color=colors, legend=False) axes[1][0].set(title=old_title_x, ylabel=ylabel) axes[1][1].set(title=old_title_y) plt.show() # Nella *Quest7* verrร  commentata la possibilitร  di confrontare le vecchie distribuzioni della frequenza di colore per X ed Y. # ### 5. Traccia il labirinto esplorato come una mappa # Avendo a disposizione le coordinate *x* ed *y* per ogni nodo viene spontaneo pensare alla realizzazione di una matrice.<br> # Si รจ deciso di utilizzare la funzione `numpy.zeros(shape, dtype=float, order='C')` per creare un array 2D inizializzato a 0: le dimensioni di quest'ultimo saranno definite da una semplice operazione del tipo `max_coord - min_coord + 1` e verrร  specificato il parametro `dtype`.<br> # Per ricavare i valori massimi e minimi che ci occorrono, la lista dei nodi รจ stata convertita in **pandas.DataFrame** cosรฌ da effettuare questa operazione in maniera molto semplice. Si valorizzano poi le corrispettive celle della matrice con i valori *1, 2, 3, 4* a seconda del colore di ogni nodo.<br> # รˆ stata infine scelta la funzione `matshow(A, fignum=None, \**kwargs)` per visualizzare la matrice creata, la quale prende in input anche cmap, oggetto **Colormap** generato da una lista di colori. def plt_map(visited: list): ''' Plot the explored maze as a map. ''' title = 'Map of the explored maze' cmap = ListedColormap(['black', 'white', 'blue', '#00ff00', 'red']) colors_code = { 32: 1, 66: 2, 71: 3, 82: 4 } # Simple solution for max/min with pd.DataFrame df = pd.DataFrame(visited) min_x = df.x.min() min_y = df.y.min() max_x = df.x.max() max_y = df.y.max() # Returns a new 2-D array of int, filled with zeros matrix = np.zeros(_get_dimensions(max_x, min_x, max_y, min_y), dtype=int) for node in visited: x = max_x - node["x"] y = max_y - node["y"] # Fills matrix position with # the color_code converted matrix[x, y] = colors_code[node["val"]] # Create subplot ad customize it fig, ax = _dark_subplots() fig.suptitle(title, fontsize=15) ax.matshow(matrix, cmap=cmap) plt.xticks(_get_range(max_y, min_y), _get_range(max_y, min_y, True)) plt.yticks(_get_range(max_x, min_x), _get_range(max_x, min_x, True)) plt.show() # # Advanced Quests # ### 6. Prova a esplorare un labirinto con un seed diverso # Semplicemente per risolvere questa Quest รจ stato creato un file contenente una nuova 'chiave':<br> # `1594709668559390700`<br> # In fase di test รจ stato sostituito il contenuto del file **seed.maze**, per la memorizzazione รจ stato successivamente rinominato in **seed1.maze** # ### 7. Confronta la distribuzione dell'istogramma con il labirinto precedente # Come visto in precedenza nella *Quest4*, la funzione `plt_xy_dist(xy_freq, old_xy_freq)` ci permette di tracciare graficamente la distribuzione della frequenza di colore per X ed Y.<br> # Ogni volta che finisce l'esplorazione di un labirinto viene richiamata la seguente funzione, disponibile in **functions.py**, che svolge le seguenti operazioni: # * carica il file `previous_maze.pickle` se presente # * confronta la vecchia distribuzione con la nuova # * se sono uguali non viene aggiornato il file # * se non sono uguali procedo scaricando la nuova distribuzione su file def get_pickle_obj(colors_xy: dict) -> dict: ''' Check the old pickle file and compare it to the current color distribution. ''' old_data = {} name_file = 'previous_maze.pickle' try: with gzip.open(name_file, 'rb') as handle: old_data = pickle.load(handle) except FileNotFoundError: pass if old_data == colors_xy: old_data = {} print("Color frequency distribution not saved, same as the previous one...") else: print("Save XY color frequency distribution to pickle file...") with gzip.open(name_file, 'wb') as handle: pickle.dump(colors_xy, handle, protocol=pickle.HIGHEST_PROTOCOL) return old_data # Se la lunghezza del dizionaro *old_xy_freq* in `plt_xy_dist()` รจ maggiore di 0, si procede con la preparazione dei vecchi dati da confrontare, altrimenti verrร  visualizzata la distribuzione attuale con in basso due riquadri vuoti, ad indicare che non sono presenti cambiamenti. # ### 8. Crea un client che consente lo spostamento nel labirinto con le frecce direzionali # Dato che l'*Engine* supporta nativamente l'utilizzo delle frecce direzionali si รจ deciso di organizzare i tasti nel seguente modo: # * **WASD** per il movimento # * **F** per l'ispezione # * **E** per uscire # # In una prima implementazione, per catturare i tasti premuti, era stato utilizzata la funzione `getch()` del pacchetto **msvcrt**, vista la compatibilitร  con i soli sistemi *Windows* si รจ deciso di utilizzare l'oggetto **Listener** dal pacchetto **pynput.keyboard** che dovrebbe essere indipendente dal *SO* (non ho avuto modo di provare). class Controller: ''' Class that contains methods to use client controller. ''' def __init__(self, debug): ''' Initialize flag for prints debug information, creates act_map for key-action association. ''' self.debug = debug self.act_map = { 'w': command.MOVE_UP, 'a': command.MOVE_LEFT, 's': command.MOVE_DOWN, 'd': command.MOVE_RIGHT, 'f': command.GET_STATE, 'e': command.EXIT } def explore_maze(self): ''' Listen for keys pressed. ''' with Listener(on_press=self._on_press) as listener: listener.join() def _on_press(self, key): ''' Sends the action to do based on key pressed. ''' try: # Check if key correspond to an action if key.char in self.act_map.keys(): action = self.act_map[key.char] if self.debug: print(action) if key.char == 'e': return False tmp = get_response(action) if key.char == 'f': pprint(to_dict(tmp)) except AttributeError: # Cleans terminal after an illegal key self._flush_input() def _flush_input(self): ''' Flush the keyboard input buffer. ''' try: # Windows import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: # Linux, MacOS import sys import termios termios.tcflush(sys.stdin, termios.TCIOFLUSH)
mazeChallenge/davidepruscini/report.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] colab_type="text" id="t09eeeR5prIJ" # ##### Copyright 2018 The TensorFlow Authors. # + cellView="form" colab={} colab_type="code" id="GCCk8_dHpuNf" #@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] colab_type="text" id="xh8WkEwWpnm7" # # Automatic differentiation and gradient tape # + [markdown] colab_type="text" id="idv0bPeCp325" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/tutorials/eager/automatic_differentiation"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/eager/automatic_differentiation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/eager/automatic_differentiation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> # </td> # </table> # + [markdown] colab_type="text" id="vDJ4XzMqodTy" # In the previous tutorial we introduced `Tensor`s and operations on them. In this tutorial we will cover [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation), a key technique for optimizing machine learning models. # + [markdown] colab_type="text" id="GQJysDM__Qb0" # ## Setup # # + colab={} colab_type="code" id="OiMPZStlibBv" from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf tf.enable_eager_execution() # + [markdown] colab_type="text" id="1CLWJl0QliB0" # ## Gradient tapes # # TensorFlow provides the [tf.GradientTape](https://www.tensorflow.org/api_docs/python/tf/GradientTape) API for automatic differentiation - computing the gradient of a computation with respect to its input variables. Tensorflow "records" all operations executed inside the context of a `tf.GradientTape` onto a "tape". Tensorflow then uses that tape and the gradients associated with each recorded operation to compute the gradients of a "recorded" computation using [reverse mode differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). # # For example: # + colab={} colab_type="code" id="bAFeIE8EuVIq" x = tf.ones((2, 2)) with tf.GradientTape() as t: t.watch(x) y = tf.reduce_sum(x) z = tf.multiply(y, y) # Derivative of z with respect to the original input tensor x dz_dx = t.gradient(z, x) for i in [0, 1]: for j in [0, 1]: assert dz_dx[i][j].numpy() == 8.0 # + [markdown] colab_type="text" id="N4VlqKFzzGaC" # You can also request gradients of the output with respect to intermediate values computed during a "recorded" `tf.GradientTape` context. # + colab={} colab_type="code" id="7XaPRAwUyYms" x = tf.ones((2, 2)) with tf.GradientTape() as t: t.watch(x) y = tf.reduce_sum(x) z = tf.multiply(y, y) # Use the tape to compute the derivative of z with respect to the # intermediate value y. dz_dy = t.gradient(z, y) assert dz_dy.numpy() == 8.0 # + [markdown] colab_type="text" id="ISkXuY7YzIcS" # By default, the resources held by a GradientTape are released as soon as GradientTape.gradient() method is called. To compute multiple gradients over the same computation, create a `persistent` gradient tape. This allows multiple calls to the `gradient()` method. as resources are released when the tape object is garbage collected. For example: # + colab={} colab_type="code" id="zZaCm3-9zVCi" x = tf.constant(3.0) with tf.GradientTape(persistent=True) as t: t.watch(x) y = x * x z = y * y dz_dx = t.gradient(z, x) # 108.0 (4*x^3 at x = 3) dy_dx = t.gradient(y, x) # 6.0 del t # Drop the reference to the tape # + [markdown] colab_type="text" id="6kADybtQzYj4" # ### Recording control flow # # Because tapes record operations as they are executed, Python control flow (using `if`s and `while`s for example) is naturally handled: # + colab={} colab_type="code" id="9FViq92UX7P8" def f(x, y): output = 1.0 for i in range(y): if i > 1 and i < 5: output = tf.multiply(output, x) return output def grad(x, y): with tf.GradientTape() as t: t.watch(x) out = f(x, y) return t.gradient(out, x) x = tf.convert_to_tensor(2.0) assert grad(x, 6).numpy() == 12.0 assert grad(x, 5).numpy() == 12.0 assert grad(x, 4).numpy() == 4.0 # + [markdown] colab_type="text" id="DK05KXrAAld3" # ### Higher-order gradients # # Operations inside of the `GradientTape` context manager are recorded for automatic differentiation. If gradients are computed in that context, then the gradient computation is recorded as well. As a result, the exact same API works for higher-order gradients as well. For example: # + colab={} colab_type="code" id="cPQgthZ7ugRJ" x = tf.Variable(1.0) # Create a Tensorflow variable initialized to 1.0 with tf.GradientTape() as t: with tf.GradientTape() as t2: y = x * x * x # Compute the gradient inside the 't' context manager # which means the gradient computation is differentiable as well. dy_dx = t2.gradient(y, x) d2y_dx2 = t.gradient(dy_dx, x) assert dy_dx.numpy() == 3.0 assert d2y_dx2.numpy() == 6.0 # + [markdown] colab_type="text" id="4U1KKzUpNl58" # ## Next Steps # # In this tutorial we covered gradient computation in TensorFlow. With that we have enough of the primitives required to build and train neural networks.
site/en/tutorials/eager/automatic_differentiation.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 # # Deploy a Quantized Model on Cuda # ================================ # **Author**: `<NAME> <https://github.com/vinx13>`_ # # This article is an introductory tutorial of automatic quantization with TVM. # Automatic quantization is one of the quantization modes in TVM. More details on # the quantization story in TVM can be found # `here <https://discuss.tvm.apache.org/t/quantization-story/3920>`_. # In this tutorial, we will import a GluonCV pre-trained model on ImageNet to # Relay, quantize the Relay model and then perform the inference. # # # + import tvm from tvm import te from tvm import relay import mxnet as mx from tvm.contrib.download import download_testdata from mxnet import gluon import logging import os batch_size = 1 model_name = "resnet18_v1" target = "cuda" dev = tvm.device(target) # - # Prepare the Dataset # ------------------- # We will demonstrate how to prepare the calibration dataset for quantization. # We first download the validation set of ImageNet and pre-process the dataset. # # # + calibration_rec = download_testdata( "http://data.mxnet.io.s3-website-us-west-1.amazonaws.com/data/val_256_q90.rec", "val_256_q90.rec", ) def get_val_data(num_workers=4): mean_rgb = [123.68, 116.779, 103.939] std_rgb = [58.393, 57.12, 57.375] def batch_fn(batch): return batch.data[0].asnumpy(), batch.label[0].asnumpy() img_size = 299 if model_name == "inceptionv3" else 224 val_data = mx.io.ImageRecordIter( path_imgrec=calibration_rec, preprocess_threads=num_workers, shuffle=False, batch_size=batch_size, resize=256, data_shape=(3, img_size, img_size), mean_r=mean_rgb[0], mean_g=mean_rgb[1], mean_b=mean_rgb[2], std_r=std_rgb[0], std_g=std_rgb[1], std_b=std_rgb[2], ) return val_data, batch_fn # - # The calibration dataset should be an iterable object. We define the # calibration dataset as a generator object in Python. In this tutorial, we # only use a few samples for calibration. # # # + calibration_samples = 10 def calibrate_dataset(): val_data, batch_fn = get_val_data() val_data.reset() for i, batch in enumerate(val_data): if i * batch_size >= calibration_samples: break data, _ = batch_fn(batch) yield {"data": data} # - # Import the model # ---------------- # We use the Relay MxNet frontend to import a model from the Gluon model zoo. # # def get_model(): gluon_model = gluon.model_zoo.vision.get_model(model_name, pretrained=True) img_size = 299 if model_name == "inceptionv3" else 224 data_shape = (batch_size, 3, img_size, img_size) mod, params = relay.frontend.from_mxnet(gluon_model, {"data": data_shape}) return mod, params # Quantize the Model # ------------------ # In quantization, we need to find the scale for each weight and intermediate # feature map tensor of each layer. # # For weights, the scales are directly calculated based on the value of the # weights. Two modes are supported: `power2` and `max`. Both modes find the # maximum value within the weight tensor first. In `power2` mode, the maximum # is rounded down to power of two. If the scales of both weights and # intermediate feature maps are power of two, we can leverage bit shifting for # multiplications. This make it computationally more efficient. In `max` mode, # the maximum is used as the scale. Without rounding, `max` mode might have # better accuracy in some cases. When the scales are not powers of two, fixed # point multiplications will be used. # # For intermediate feature maps, we can find the scales with data-aware # quantization. Data-aware quantization takes a calibration dataset as the # input argument. Scales are calculated by minimizing the KL divergence between # distribution of activation before and after quantization. # Alternatively, we can also use pre-defined global scales. This saves the time # for calibration. But the accuracy might be impacted. # # def quantize(mod, params, data_aware): if data_aware: with relay.quantize.qconfig(calibrate_mode="kl_divergence", weight_scale="max"): mod = relay.quantize.quantize(mod, params, dataset=calibrate_dataset()) else: with relay.quantize.qconfig(calibrate_mode="global_scale", global_scale=8.0): mod = relay.quantize.quantize(mod, params) return mod # Run Inference # ------------- # We create a Relay VM to build and execute the model. # # # + def run_inference(mod): model = relay.create_executor("vm", mod, dev, target).evaluate() val_data, batch_fn = get_val_data() for i, batch in enumerate(val_data): data, label = batch_fn(batch) prediction = model(data) if i > 10: # only run inference on a few samples in this tutorial break def main(): mod, params = get_model() mod = quantize(mod, params, data_aware=True) run_inference(mod) if __name__ == "__main__": main()
_downloads/a269cb38341b190be980a0bd3ea8a625/deploy_quantized.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/sianlewis/energy_consumption/blob/master/team_high_energy_(previous).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="2URjf0_REx_A" colab_type="text" # # Import and Functions # + id="fbSICfxtFKAN" colab_type="code" outputId="25cca362-90e8-4050-ed4a-db8e0a0b1316" colab={"base_uri": "https://localhost:8080/", "height": 675} import pandas as pd import numpy as np import seaborn as sns import requests from bs4 import BeautifulSoup import pandas_profiling import sklearn import boto3 from boto3 import session from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV #from sklearn.cross_validation import cross_val_score, cross_val_predict, train_test_split, KFold, StratifiedKFold from sklearn import datasets, linear_model, metrics, preprocessing, pipeline from sklearn.pipeline import make_union, make_pipeline, Pipeline from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, BaggingClassifier from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_squared_error, classification_report, confusion_matrix, accuracy_score, r2_score from sklearn.neighbors import KNeighborsClassifier import scipy.stats as stats import statsmodels.api as sm import statsmodels.formula.api as smf import patsy import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns import plotly import re import sys import datetime as dt import time from time import sleep # !pip install fancyimpute import fancyimpute # documentation: https://pypi.org/project/fancyimpute/ # + id="50ktrb8_N-n4" colab_type="code" colab={} #Exploratory Data Analysis def get_variable_category(series): unique_count = series.nunique(dropna=False) total_count = len(series) if pd.api.types.is_numeric_dtype(series): return 'Numerical' elif pd.api.types.is_datetime64_dtype(series): return 'Date' elif unique_count==total_count: return 'Text (Unique)' else: return 'Categorical' def print_variable_categories(data): for column_name in data.columns: print(column_name, ': ', get_variable_category(data[column_name])) def datainspect(dataframe): '''Inspect data''' print('ROWS AND COLUMNS: \n', dataframe.shape,'\n') print('MISSING VALUES: \n', dataframe.isnull().sum(),'\n') print('DUPLICATE ROWS \n', dataframe.duplicated().sum(),'\n') print('DATA TYPES: \n', dataframe.dtypes,"\n") print('DATAFRAME DESCRIBE: \n \n', dataframe.describe(include='all'),'\n') print('UNIQUE VALUES:') for item in dataframe: print(item, dataframe[item].nunique()) print('\n') print('VARIABLE CATEGORIES:', '\n' ) print(print_variable_categories(dataframe)) # + id="1OqhjPt_Rkix" colab_type="code" outputId="983459e0-fbde-450f-e34a-31363e1ccef5" colab={"base_uri": "https://localhost:8080/", "height": 51} # Code to read csv file into Colaboratory: # !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # + [markdown] id="w32nHbmxnDjL" colab_type="text" # # + [markdown] id="KXs5HWRxbW2Q" colab_type="text" # **Datasets** # # # Historical Consumption: A selected time series of consumption data for over 200 buildings. # # List of Variables that are included in the multiple datasets: # # **Training Dataset Variables** # # * **obs_id** - An arbitrary ID for the observations # * **SiteId** - An arbitrary ID number for the building, matches across datasets # * **ForecastId** - An ID for a timeseries that is part of a forecast (can be matched with the submission file) # * **Timestamp** - The time of the measurement # * **Value** - A measure of consumption for that building # # # **Building Metadata Dataset**: Additional information about the included buildings. # # * **SiteId** - An arbitrary ID number for the building, matches across datasets # * **Surface** - The surface area of the building # * **Sampling** - The number of minutes between each observation for this site. The timestep size for each ForecastId can be found in the separate "Submission Forecast Period" file on the data download page. # * **BaseTemperature** - The base temperature for the building # * **[DAY_OF_WEEK]IsDayOff** - True if DAY_OF_WEEK is not a work day # Historical Weather Data # This dataset contains temperature data from several stations near each site. For each site several temperature measurements were retrieved from stations in a radius of 30 km if available. # # Note: Not all sites will have available weather data. # # Note: Weather data is available for test periods under the assumption that reasonably accurate forecasts will be available to algorithms that the time that we are attempting to make predictions about the future. # # **Weather Dataset Variables** # # * **SiteId** - An arbitrary ID number for the building, matches across datasets # * **Timestamp** - The time of the measurement # * **Temperature** - The temperature as measured at the weather station # * **Distance** - The distance in km from the weather station to the building in km # Public Holidays # Public holidays at the sites included in the dataset, which may be helpful for identifying days where consumption may be lower than expected. # # Note: Not all sites will have available public holiday data. # # **Holidays Dataset** # # * **SiteId** - An arbitrary ID number for the building, matches across datasets # * **Date** - The date of the holiday # * **Holiday** - The name of the holiday # + [markdown] id="3SJcZ9NUFnDm" colab_type="text" # # Submission Forecast Period (not using) # + [markdown] id="PyMTiS4hxHdY" colab_type="text" # **There are no days off for buildings Monday - Thursday** # **Minimal days off for friday, saturday, sunday # # + id="VL3bJa0TiBEv" colab_type="code" outputId="5c172a5d-6f39-4a87-e267-12cc756e0ad5" colab={"base_uri": "https://localhost:8080/", "height": 34} submission_forecast_period = 'https://drive.google.com/open?id=1S59Hrh4yduw3Ee_X5yHzHDlSbg-1PkUK' fluff, id = submission_forecast_period.split('=') print (id) # + id="xjoDOipriQz6" colab_type="code" outputId="deb7d2b7-c83f-46c3-9efa-80afdac760ad" colab={"base_uri": "https://localhost:8080/", "height": 195} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-submission-forecast-period.csv') submission_forecast_period = pd.read_csv('power-laws-forecasting-energy-consumption-submission-forecast-period.csv', sep = ';') submission_forecast_period.head() # + id="s_VO2XaSOmzb" colab_type="code" outputId="152b51b9-dcf7-4c73-d0ad-5c2ffb785e00" colab={"base_uri": "https://localhost:8080/", "height": 655} datainspect(submission_forecast_period) # + id="BO-xAs2Wz9v3" colab_type="code" outputId="b2631b2d-09ad-4e12-8bbb-abb596b8ad26" colab={"base_uri": "https://localhost:8080/", "height": 326} submission_forecast_period.plot(kind='scatter', x='ForecastId', y='ForecastPeriodNS'); # + id="M2IktXyw1hOv" colab_type="code" outputId="991efb3d-61ce-4aa4-f9b7-4b06cc7edfab" colab={"base_uri": "https://localhost:8080/", "height": 293} correlation = submission_forecast_period.corr() # correlation between ALL variables sns.heatmap(correlation, cmap='bwr') # + [markdown] id="pKmBwIWHFuAH" colab_type="text" # # Submission Format (not using) # + id="OdgrBxjrizZJ" colab_type="code" outputId="19431d6f-d846-47b7-8869-55de48474ed8" colab={"base_uri": "https://localhost:8080/", "height": 34} submission_format = 'https://drive.google.com/open?id=1B196PxseHWY4DTGgy1dUMqwtm7MFEw_r' fluff, id = submission_format.split('=') print (id) # + id="PDiFXBWJkb5H" colab_type="code" outputId="d1632ab6-1e87-4135-f7b9-066b40b3e23b" colab={"base_uri": "https://localhost:8080/", "height": 195} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-submission-format.csv') submission_format = pd.read_csv('power-laws-forecasting-energy-consumption-submission-format.csv', sep = ';') submission_format.head() # + id="kmj74_hgOwHC" colab_type="code" outputId="03a9a426-e7b4-437b-f44e-146f69da28e8" colab={"base_uri": "https://localhost:8080/", "height": 907} datainspect(submission_format) # + [markdown] id="TT8Nwt5REnIv" colab_type="text" # # Holidays # + id="0Hp5R7vIf-4C" colab_type="code" outputId="c8cf25ff-2bae-4758-b011-6f5f01e3670a" colab={"base_uri": "https://localhost:8080/", "height": 34} holidays = 'https://drive.google.com/open?id=1H0TqoTnei1_8DP-ttDsOsJyVkmytQZLG' fluff, id = holidays.split('=') print (id) # + id="nmsSxfjXgxVV" colab_type="code" outputId="a6a12b73-85b6-44a6-8496-5666fa81952f" colab={"base_uri": "https://localhost:8080/", "height": 204} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-holidays.csv') holidays = pd.read_csv('power-laws-forecasting-energy-consumption-holidays.csv', sep = ';') holidays.head() # + [markdown] id="kNj7G4_f4dj8" colab_type="text" # **Holidays Dataset** # # SiteId - An arbitrary ID number for the building, matches across datasets # # Date - The date of the holiday # # Holiday - The name of the holiday # # I'm thinking this dataset does not tell us much since we already have the days that the building is on and off so this may be redundant data. # # + id="hBxv-Zo_OUtn" colab_type="code" outputId="a515a0b3-484f-43cc-f6fb-796cf2790fbe" colab={"base_uri": "https://localhost:8080/", "height": 782} datainspect(holidays) # + id="VnYjTY17sX_l" colab_type="code" outputId="ab2d2385-a192-4a7c-ee05-5f22c1ca774d" colab={"base_uri": "https://localhost:8080/", "height": 119} holidays['Holiday'].value_counts().head() # + [markdown] id="SUfcXAWvEsn9" colab_type="text" # # Metadata # + id="aQAJsOn2g_pe" colab_type="code" outputId="90b1fb8e-0cb1-4271-9b1d-85185b6e3ea3" colab={"base_uri": "https://localhost:8080/", "height": 34} metadata = 'https://drive.google.com/open?id=1dpwWIs3EyLkaaOSN8ws8gMHgCFsRTYK3' fluff, id = metadata.split('=') print (id) # + id="h8Wq9SOhh70h" colab_type="code" outputId="e2c392f3-fc2b-43a0-ebb6-7d8dc12e9c0c" colab={"base_uri": "https://localhost:8080/", "height": 195} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-metadata.csv') metadata = pd.read_csv('power-laws-forecasting-energy-consumption-metadata.csv', sep = ';') metadata.head() # + id="QEszZ_3nOh_U" colab_type="code" outputId="b87a86c7-d607-495a-c8aa-eedd59ded69a" colab={"base_uri": "https://localhost:8080/", "height": 178} datainspect(metadata) # sampling and BaseTemperature do not tell us much about the energy consumption # + id="REyorFtJsz66" colab_type="code" outputId="02dbb683-e4f6-43d7-8c6e-dfb45440cfb1" colab={"base_uri": "https://localhost:8080/", "height": 50} metadata['MondayIsDayOff'].value_counts() # + id="RvVPSIUYwJGb" colab_type="code" colab={} def dayoff(dataframe): print('MONDAY IS A DAY OFF: \n', dataframe.MondayIsDayOff.value_counts(),'\n') print('TUESDAY IS A DAY OFF: \n', dataframe.TuesdayIsDayOff.value_counts(),'\n') print('WEDNESDAY IS A DAY OFF: \n', dataframe.WednesdayIsDayOff.value_counts(),'\n') print('THURSDAY IS A DAY OFF: \n', dataframe.ThursdayIsDayOff.value_counts(),'\n') print('FRIDAY IS A DAY OFF: \n', dataframe.FridayIsDayOff.value_counts(),'\n') print('SATURDAY IS A DAY OFF: \n', dataframe.SaturdayIsDayOff.value_counts(),'\n') print('SUNDAY IS A DAY OFF: \n', dataframe.SundayIsDayOff.value_counts(),'\n') # + id="RTaHRtJRwq1M" colab_type="code" outputId="232195cf-c83b-4030-f3e9-18da4cd93810" colab={"base_uri": "https://localhost:8080/", "height": 538} dayoff(metadata) # + id="rPdNNZpOxsIb" colab_type="code" outputId="48c0c52f-6b57-423c-c476-0703829208a1" colab={"base_uri": "https://localhost:8080/", "height": 316} metadata.plot(kind='scatter', x='Surface', y='BaseTemperature'); # + [markdown] id="OMg6fjCpF1Ku" colab_type="text" # # Training Data # + id="dU7eq3QvkiqI" colab_type="code" outputId="02aa8119-ba26-4688-b53f-b6806e464b5b" colab={"base_uri": "https://localhost:8080/", "height": 34} training_data = 'https://drive.google.com/open?id=1Ri9t0yrf2A99S8Lqy3DwvydP-jmsokeL' fluff, id = training_data.split('=') print (id) # + id="p8fBeuCllIW7" colab_type="code" outputId="3d3bdb29-d7e0-4ee9-c811-83797304ee7a" colab={"base_uri": "https://localhost:8080/", "height": 195} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-training-data.csv') training_data = pd.read_csv('power-laws-forecasting-energy-consumption-training-data.csv', sep = ';') training_data.head() # + id="-flb_7gaO-OM" colab_type="code" outputId="99508ee4-c443-4766-f45e-64f4812b4e4a" colab={"base_uri": "https://localhost:8080/", "height": 907} datainspect(training_data) # + id="tEZJCQao03Dw" colab_type="code" outputId="61534ab7-de19-4b0c-efdd-9729b397e8c0" colab={"base_uri": "https://localhost:8080/", "height": 326} training_data.plot(kind='scatter', x='ForecastId', y='Value'); # + id="XQNWOvFV1T_y" colab_type="code" outputId="aeb9ef14-a3ad-4bdc-a537-7448348a92ad" colab={"base_uri": "https://localhost:8080/", "height": 282} corr = training_data.corr() # correlation between ALL variables sns.heatmap(corr, cmap='bwr') # + [markdown] id="EVPmKIm91t8R" colab_type="text" # **Correlation Pot** # # # # * forecastId an SiteId are very correlated # # # + [markdown] id="wlmejkTgUjHS" colab_type="text" # **Inspecting the Training Data:** # # # * There are no missing values # * Multiple time-stamps for same Site-id # # # + [markdown] id="_TJ5RO3cF7ho" colab_type="text" # # Weather # + id="gmmjRn84lX5-" colab_type="code" outputId="0f16a4f7-1590-49f6-9b7b-053045a94443" colab={"base_uri": "https://localhost:8080/", "height": 34} weather = 'https://drive.google.com/open?id=1QZtFjz61NS0Ebbma42LrGtYZFRSsF3Ij' fluff, id = weather.split('=') print (id) # + id="UDtjURR6lv1g" colab_type="code" outputId="4e9a5bbd-8d61-4d80-9955-2ac7bde2b7eb" colab={"base_uri": "https://localhost:8080/", "height": 195} downloaded = drive.CreateFile({'id':id}) downloaded.GetContentFile('power-laws-forecasting-energy-consumption-weather.csv') weather = pd.read_csv('power-laws-forecasting-energy-consumption-weather.csv', sep = ';') weather.head() # + id="Ed94MmXMPUIS" colab_type="code" outputId="3860afc6-208a-4eb2-baa4-576a7ad86879" colab={"base_uri": "https://localhost:8080/", "height": 840} datainspect(weather) # + id="XdxFLZBb3Rvy" colab_type="code" outputId="c303aebe-0635-4bc8-fcb8-f3d7166b956c" colab={"base_uri": "https://localhost:8080/", "height": 286} corr2 = weather.corr() # correlation between ALL variables sns.heatmap(corr2, cmap='bwr') # + id="fVynhIcOl7Q-" colab_type="code" colab={} # Variables weather_distance = weather[['Distance']] weather_temp = weather[['Temperature']] training_data_value = training_data[['Value']] training_data_ts = training_data[['Timestamp']] metadata_basetemp = metadata[['BaseTemperature']] metadata_surface = metadata[['Surface']] # + id="o4Rta6CJ_qiN" colab_type="code" outputId="0f77fa1c-e1e5-49aa-c07c-bb093ebea7ef" colab={"base_uri": "https://localhost:8080/", "height": 282} plt.plot(metadata_basetemp) plt.plot(metadata_surface)
team_high_energy_(previous).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 # --- # + pycharm={"name": "#%%\n"} # %matplotlib inline import numpy as np from create_model import create_model from data_generator import DataGenerator from config import get_config # + pycharm={"name": "#%%\n"} conf = get_config() batch_size = 4 f = "bright_vs_dark" conf["features"] = [f] conf["model_name"] = f conf["valid_split"] = 0.0 data_gen = DataGenerator(conf, batch_size) # + pycharm={"name": "#%%\n"} model = create_model(conf) model.load_weights("checkpoints/bright_vs_dark_loss_0.9607_acc_0.61.h5") # + pycharm={"name": "#%%\n"} data = iter(data_gen.generator("train")) # + pycharm={"name": "#%%\n"} x, y = next(data) preds = model.predict(x) for index in range(0, batch_size): print("="*10) print(np.argmax(y[index]), np.argmax(preds[index])) # + pycharm={"name": "#%%\n"}
members/amit/clf/predictions.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] raw_mimetype="text/latex" # (c) <NAME> 2019. Thanks to Universidad EAFIT for support. This material is part of the course Introduction to Finite Element Analysis # - # # Interpolation in Two-Dimensional Domains # ## Introduction # Here we will extend the one-dimensional interpolation scheme studied previously to the more general case of a two-dimensional domain. From the geometric point of view we will also see that a **finite element** is just a canonical spatial domain described by nodal points and the corresponding set of interpolation (or **shape**) functions. Thus this will be the first formal definition of a finite element in the course. **After completing this notebook you should be able to:** # # * Recognize the problem of interpolation in two-dimensional domains as the application of the known one-dimensional scheme. # # * Formalize the concept of a finite element as a canonical interpolation space with prescribed interpolation functions. # # * Propose interpolation schemes for general two-dimensional domains. # ## Two-dimensional domain # Consider the two-dimensional square domain shown in the figure and where we want to approximate, via interpolation, a scalar (or vector) valued fuction $f=f(x,y)$. For that purpose the black-dots in the figure, represent nodal or sampling points where the function is assumed to be known. As discussed in the **Class Notes (Section 1.4)** the interpolating polynomial, in this case denoted by $p(x,y)$ is built like: # # $$p(x,y) = H^Q(x,y)f^Q$$ # # where $Q = 1,...,N$ for a *N*-noded domain and where $H^Q(x,y)$ are the interpolation polynomials which in the context of the finite element method are called **Shape Funtions**. # # To built the bi-dimensional interpolation functions $ H^Q(x,y)$ we actually perform an iterated one-dimensional interpolation as described next. # # Let $x^A$ and $x^B$ denote the x-coordinates of points A and B for the square domain, shown in the figure below and assume we would like to find the value of the function at point A. # <center><img src="img/element.png" alt="Element" style="width:300px"></center> # Point A has an arbitrary y-coordinate but a constant $x = x^A$ x-coordinate, thus for an arbitrary point A along the 1-4 direction (see figure below) the interpolation scheme is still one-dimensional with only y-dependence as indicated by the label $f(y , x= A)$ in the figure. Using known one-dimensional Lagrange polynomials this y-dependence can be captured by: # # $$f(x^A , y) = L^1(y)f^1 + L^4(y)f^4$$ # # <center><img src="img/inter1D.png" alt="1direction" style="width:300px"></center> # Proceeding similarly for an arbitrary point B along the 2-3 direction leads to: # # $$f(x^B , y) = L^2(y)f^2 + L^3(y)f^3.$$ # # With $f^A$ and $f^B$ known the x-dependence can now be captured like: # # $$f(x,y) = L^A(x) f(x^A,y) + L^B(x)f(x^B,y).$$ # # To arrive at the final 2D-shape functions we compute the polynomials $L^2(y)$, $L^3(y)$, $ L^A(x)$ and $ L^B(x)$ and replace them in the expressions above. In the case of an element of side 2.0 these functions take the form: # # \begin{align*} # H^1(x,y) & = L^1(x)L^1(y) \equiv \frac14(1-x)(1-y)\\ # H^2(x,y) & = L^2(x)L^1(y) \equiv \frac14(1+x)(1-y)\\ # H^3(x,y) & = L^2(x)L^2(y) \equiv \frac14(1+x)(1+y)\\ # H^4(x,y) & = L^1(x)L^2(y) \equiv \frac14(1-x)(1+y). # \end{align*} # # # Since along each line 1-4 or 2-3 one-dimensional interpolation is being used, the formulated element is termed a bi-linear element. # ### A Canonical Finite Element # # In the following subroutine we code the final form $H^Q(x,y)$ of the shape functions instead of directly computing the fundamental 1D-polynomials of the form $L^I(y)$ and computing the iterated interpolation. The subroutine, named here **sha4()** stores the functions in a matrix structure which depends on $x$ and $y$. Here we assume that the element is a perfect square of side $\mathcal l=2.0$ with nodal points at the corners thus allowing for linear interpolation along each face. # %matplotlib notebook import matplotlib.pyplot as plt import numpy as np import sympy as sym from scipy import interpolate def sha4(x,y): """ Compute the shape functions for bi-linear square element of size 2.0. """ sh=sym.zeros(4) sh[0] =(1.0/4.0)*(1 - x)*(1 - y) sh[1] =(1.0/4.0)*(1 + x)*(1 - y) sh[2] =(1.0/4.0)*(1 + x)*(1 + y) sh[3] =(1.0/4.0)*(1 - x)*(1 + y) # return sh # This square-element is a **canonical** or reference element where it is easy to conduct the interpolation operation. In an actual finite element discretization the resulting quadrilateral elements are expected to be distorted with respect to this canonical element. In these cases interpolation is still conducted in the space of the canonical element and geometry and functions are nicely transformed using simple mathematics. However, those details will be discussed later. # # The shape functions stored in the subroutine correspond to: # # $$H = \frac14\begin{bmatrix}(1-x)(1-y)&(1+x)(1-y)&(1+x)(1+y)&(1-x)(1+y)\end{bmatrix}$$ # # **Questions:** # # **(i) Write the element shape functions if the sub-domain is now the same squared element but now it also includes, in addition to the corner nodes, midside nodes to complete a total of 8 nodal points.** # # **(ii) Make a copy of the subroutine **sha4()** and modify it to compute the shape functions for an 8-noded element.** x , y= sym.symbols('x y') H = sha4(x , y) # ## Interpolation over a square element. # In this step we consider a square element conformed by 4-nodal points located at the corners and where nodal values of a function are assumed to be known. We use these values together with the shape functions to derive an interpolating polynomial. The resulting polynomial is used next to generate approximated values of the function along a set of points conforming a grid used to visualize the solution. The grid of observation points is generated using the function **mgrid** from **numpy**. # # Notice that the system of reference is placed at the center of the element thus $x\in\lbrack-1\;,\;1\rbrack$ and $y\in\lbrack-1\;,\;1\rbrack$. The 1D array **USOL[]** will store the value interpolated at each point of the grid. # # To conduct the interpolation we will assume known nodal values of the function at a given point $(x , y)$ so we can obtain the interpolated value like: # # $$u(x,y)\;=\;\left[H(x,y)\right]\left\{u\right\}$$ # # **(Add comments to clarify the relevant steps in the code below)**. li=-1.0 ls= 1.1 dl= 0.1 npts=int((ls-li)/dl) USOL = np.zeros((npts, npts, 1)) xx, yy = np.mgrid[li:ls:npts*1j, li:ls:npts*1j] #Try different values of the function at the nodal points u = sym.Matrix(4, 1, [-0.2 ,0.2 ,-0.2 , 0.2]) # for i in range(npts): for j in range(npts): NS =H.subs([(x, xx[i,j]), (y, yy[i,j])]) up = NS*u USOL[i, j, 0] = up[0] plt.figure(1) plt.contourf(xx , yy , USOL[:,:,0], cmap="RdYlBu") # ### Glossary of terms # # **Canonical finite element:** Undistorted constant size sub-domain with fixed shape functions. In a practical case the elements differ in size and level of distortion, however all of them are geometrically transformed to the canonical element. # # **Shape functions:** Interpolation functions formulated over a canonical element. # # **Mesh:** A set of finite elements covering a given computational domain. A mesh is refined when the characteristic element size reduces generating a larger number of elements to cover the same compuattional domain. # ### Class activity # **Problem 1** # # Extend the 2D interpolation scheme discussed above to the case of a vector valued function in the context of linear elasticity. For that purpose: # # * Assume that at each nodal point of the square domain the displacement vector with horizontal and vertical componentes denoted by $u$ and $v$ respectively is known. # * Using these nodal values compute the horizontal and vertical displacement components over the element. # * Using these same nodal values compute the strain field given by: # # $$\varepsilon_{xx}=\frac12\left(\frac{\partial u}{\partial x}\right)$$ # # $$\varepsilon_{yy}=\frac12\left(\frac{\partial v}{\partial y}\right)$$ # # $$\gamma_{yy}=\left(\frac{\partial u}{\partial y}+\frac{\partial v}{\partial x}\right)$$ # # * Store the shape function derivatives in a separate matrix $B$. # # **Problem 2** # # In a realistic finite element problem and due to geometric irregularities in the computational domain all the elements of the mesh would have different geometric paramters. These differences not only complicate the interpolation process but even create serious problems on coding a systematic approach. In practice every real (distorted) element is transformed to a canonical element in such a way that the interpolation process is conducted in the canonical space. The figure below shows the relation between these two spaces emphasizing the fact that there is a one to one connecion between a point in both spaces. The mathematical details of the transformation are provided in the **Class Notes.** # # <center><img src="img/isopar.png" alt="1direction" style="width:400px"></center> # # * Compute the transformation between the distorted and canonical element spaces required to conduct two-dimensional interpolation in a realistic case. from IPython.core.display import HTML def css_styling(): styles = open('./nb_style.css', 'r').read() return HTML(styles) css_styling()
notebooks/03_lagrange_2d.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python3-azureml # kernelspec: # display_name: PyCharm (drug-resistance-prediction-cambiohack) # language: python # name: pycharm-f27e5417 # --- # + gather={"logged": 1604307425503} import pandas as pd import warnings warnings.filterwarnings('ignore') import h2o h2o.init(min_mem_size='27G') # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604307447638} binarized_final_df = h2o.import_file("../data/processed/final.binarized_final_monolabel_df.tsv") binarized_final_df.head() # + gather={"logged": 1604307464844} train = h2o.import_file("../data/processed/final.train.tsv") train.head() # + gather={"logged": 1604307478044} test = h2o.import_file("../data/processed/final.test.tsv") test.head() # + gather={"logged": 1604307478173} # Identify predictors and response train_predictor_cols = train.columns train_response_col = "Resistance_Status" train_predictor_cols.remove('SampleID') train_predictor_cols.remove(train_response_col) print("train frame - predictor column: ", train_predictor_cols[0], train_predictor_cols[-1]) print("train frame - response column: ", train_response_col) # Identify predictors and response test_predictor_cols = test.columns test_response_col = "Resistance_Status" test_predictor_cols.remove('SampleID') test_predictor_cols.remove(test_response_col) print("test frame - predictor columns: ", test_predictor_cols[0], test_predictor_cols[-1]) print("test frame - response column: ", test_response_col) # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604307478223} # For binary classification, response should be a factor train[train_response_col] = train[train_response_col].asfactor() test[test_response_col] = test[test_response_col].asfactor() x = train_predictor_cols y = train_response_col # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604307479662} test.head() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604307481326} train.head() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604302962344} from h2o.estimators import H2OPrincipalComponentAnalysisEstimator my_pca = H2OPrincipalComponentAnalysisEstimator( k = 400, # pca_method = "gram_s_v_d", # use_all_factor_levels = True, # pca_method = "glrm", ) # TODO: Do PCA for the entire dataset, it doesn't make sense for test/train only my_pca.train(x=x, y=y, training_frame=binarized_final_df) # Try out with smaller test dataset first # my_pca.train(x=x, y=y, training_frame=test) # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300649929} # save the model model_path = h2o.save_model(model= my_pca, path="../models/my_pca_model", force=True) # print(model_path) # model_path = "../data/processed/my_rf_model/DRF_model_python_1601519217841_129" # load the model # my_rf = h2o.load_model(model_path) # download the model built above to your local machine # my_local_model = h2o.download_model(my_rf, path="../data/processed/my_rf_model") # upload the model that you just downloded above # to the H2O cluster # uploaded_model = h2o.upload_model(my_local_model) # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1603964997073} # Generate predictions on a test set (if neccessary) pred = my_pca.predict(binarized_final_df) pred # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300650178} my_pca.summary() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300650477} my_pca.show() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300657396} my_pca.model_performance(test) # + [markdown] nteract={"transient": {"deleting": false}} # # Save the PCA dataframe # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300671783} # Generate predictions train_pca = my_pca.predict(train) h2o.export_file(frame=train_pca, path="../data/processed/final.train.pca400.tsv", force=True) train_pca.head() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604300695079} # Generate predictions test_pca = my_pca.predict(test) h2o.export_file(frame=test_pca, path="../data/processed/final.test.pca400.tsv", force=True) test_pca.head() # + [markdown] nteract={"transient": {"deleting": false}} # # GLRM Model # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} from h2o.estimators import H2OGeneralizedLowRankEstimator my_glrm = H2OGeneralizedLowRankEstimator( # k=5, # loss="quadratic", # gamma_x=0.5, # gamma_y=0.5, # max_iterations=700, # recover_svd=True, # init="SVD", # transform="standardize" ) my_glrm.train(training_frame=test) # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}} gather={"logged": 1604250529998} h2o.shutdown() # + jupyter={"source_hidden": false, "outputs_hidden": false} nteract={"transient": {"deleting": false}}
notebooks/mono_resistance_pca_h2o.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 # --- # # <font color='blue'>Data Science Academy - Python Fundamentos - Capรญtulo 7</font> # # ## Download: http://github.com/dsacademybr # ## Missรฃo: Analisar o Comportamento de Compra de Consumidores. # ## Nรญvel de Dificuldade: Alto # Vocรช recebeu a tarefa de analisar os dados de compras de um web site! Os dados estรฃo no formato JSON e disponรญveis junto com este notebook. # # No site, cada usuรกrio efetua login usando sua conta pessoal e pode adquirir produtos ร  medida que navega pela lista de produtos oferecidos. Cada produto possui um valor de venda. Dados de idade e sexo de cada usuรกrio foram coletados e estรฃo fornecidos no arquivo JSON. # # Seu trabalho รฉ entregar uma anรกlise de comportamento de compra dos consumidores. Esse รฉ um tipo de atividade comum realizado por Cientistas de Dados e o resultado deste trabalho pode ser usado, por exemplo, para alimentar um modelo de Machine Learning e fazer previsรตes sobre comportamentos futuros. # # Mas nesta missรฃo vocรช vai analisar o comportamento de compra dos consumidores usando o pacote Pandas da linguagem Python e seu relatรณrio final deve incluir cada um dos seguintes itens: # # ** Contagem de Compradores ** # # * Nรบmero total de compradores # # # ** Anรกlise Geral de Compras ** # # * Nรบmero de itens exclusivos # * Preรงo mรฉdio de compra # * Nรบmero total de compras # * Rendimento total # # # ** Informaรงรตes Demogrรกficas Por Gรชnero ** # # * Porcentagem e contagem de compradores masculinos # * Porcentagem e contagem de compradores do sexo feminino # * Porcentagem e contagem de outros / nรฃo divulgados # # # ** Anรกlise de Compras Por Gรชnero ** # # * Nรบmero de compras # * Preรงo mรฉdio de compra # * Valor Total de Compra # * Compras for faixa etรกria # # # ** Identifique os 5 principais compradores pelo valor total de compra e, em seguida, liste (em uma tabela): ** # # * Login # * Nรบmero de compras # * Preรงo mรฉdio de compra # * Valor Total de Compra # * Itens mais populares # # # ** Identifique os 5 itens mais populares por contagem de compras e, em seguida, liste (em uma tabela): ** # # * ID do item # * Nome do item # * Nรบmero de compras # * Preรงo do item # * Valor Total de Compra # * Itens mais lucrativos # # # ** Identifique os 5 itens mais lucrativos pelo valor total de compra e, em seguida, liste (em uma tabela): ** # # * ID do item # * Nome do item # * Nรบmero de compras # * Preรงo do item # * Valor Total de Compra # # # ** Como consideraรงรตes finais: ** # # * Seu script deve funcionar para o conjunto de dados fornecido. # * Vocรช deve usar a Biblioteca Pandas e o Jupyter Notebook. # # Imports import pandas as pd import numpy as np # Carrega o arquivo load_file = "dados_compras.json" purchase_file = pd.read_json(load_file, orient = "records") purchase_file.head() # ## Informaรงรตes Sobre os Compradores player_demographics = purchase_file.loc[:, ["Sexo", "Login", "Idade"]] player_demographics.head() # Limpeza dos dados e remoรงรฃo de duplicatas player_demographics = player_demographics.drop_duplicates() player_count = player_demographics.count()[0] player_count # Converter saรญda para DF para uso posterior em anรกlise pd.DataFrame({"Total de Jogadores" : [player_count]}) # ## Anรกlise de Compra # + # Cรกlculos bรกsicos average_item_price = purchase_file["Valor"].mean() total_item_price = purchase_file["Valor"].sum() total_item_count = purchase_file["Valor"].count() item_id = len(purchase_file["Item ID"].unique()) # Dataframe para os resultados summary_calculations = pd.DataFrame({"Nรบmero de Itens รšnicos" : item_id, "Nรบmero de Compras" : total_item_count, "Total de Vendas" : total_item_price, "Preรงo Mรฉdio" : [average_item_price]}) # Data Munging summary_calculations = summary_calculations.round(2) summary_calculations ["Preรงo Mรฉdio"] = summary_calculations["Preรงo Mรฉdio"].map("${:,.2f}".format) summary_calculations ["Total de Vendas"] = summary_calculations["Total de Vendas"].map("${:,.2f}".format) summary_calculations = summary_calculations.loc[:, ["Nรบmero de Itens รšnicos", "Preรงo Mรฉdio", "Nรบmero de Compras", "Total de Vendas"]] summary_calculations # - purchase_file["Item ID"].unique() # ## Informaรงรตes Demogrรกficas # + # Cรกlculos bรกsicos gender_count = player_demographics["Sexo"].value_counts() gender_percent = (gender_count / player_count) * 100 # Dataframe para os resultados gender_demographics = pd.DataFrame({"Sexo" : gender_count, "%" : gender_percent}) # Data Munging gender_demographics = gender_demographics.round(2) gender_demographics ["%"] = gender_demographics["%"].map("{:,.1f}%".format) # - # Output Test gender_count # Output Test gender_percent # Output Test gender_demographics # ## Anรกlise de Compra Por Gรชnero # + # Agrupamentos gender_total_item_price = purchase_file.groupby(["Sexo"]).sum()["Valor"].rename("Total de Vendas") gender_average_item_price = purchase_file.groupby(["Sexo"]).mean()["Valor"].rename("Average Price") purchase_count = purchase_file.groupby(["Sexo"]).count()["Valor"].rename("Nรบmero de Compras") normalized_total = gender_total_item_price / gender_demographics["Sexo"] # Armazenando o resultado em um Dataframe gender_purchasing_analysis = pd.DataFrame({"Nรบmero de Compras" : purchase_count, "Valor Mรฉdio Por Item" : gender_average_item_price, "Total de Vendas" : gender_total_item_price, "Total Normalizado" : normalized_total}) # Data Munging gender_purchasing_analysis = gender_purchasing_analysis.round(2) gender_purchasing_analysis ["Valor Mรฉdio Por Item"] = gender_purchasing_analysis["Valor Mรฉdio Por Item"].map("${:,.2f}".format) gender_purchasing_analysis ["Total de Vendas"] = gender_purchasing_analysis["Total de Vendas"].map("${:,.2f}".format) gender_purchasing_analysis ["Total Normalizado"] = gender_purchasing_analysis["Total Normalizado"].map("${:,.2f}".format) # - # Resultado gender_total_item_price # Resultado gender_average_item_price # Resultado gender_purchasing_analysis # Resultado normalized_total # ## Anรกlise Demogrรกfica player_demographics # + # Cรกlculos bรกsicos age_bins = [0, 9.99, 14.99, 19.99, 24.99, 29.99, 34.99, 39.99, 999] age_bracket = ["Menos de 10", "10 a 14", "15 a 19", "20 a 24", "25 a 29", "30 a 34", "35 a 39", "Mais de 40"] purchase_file["Range de Idades"] = pd.cut(purchase_file["Idade"], age_bins, labels=age_bracket) # Cรกlculos bรกsicos age_demographics_count = purchase_file["Range de Idades"].value_counts() age_demographics_average_item_price = purchase_file.groupby(["Range de Idades"]).mean()["Valor"] age_demographics_total_item_price = purchase_file.groupby(["Range de Idades"]).sum()["Valor"] age_demographics_percent = (age_demographics_count / player_count) * 100 # Dataframe para os resultados age_demographics = pd.DataFrame({"Contagem": age_demographics_count, "%": age_demographics_percent, "Valor Unitario": age_demographics_average_item_price, "Valor Total de Compra": age_demographics_total_item_price}) # Data Munging age_demographics ["Valor Unitario"] = age_demographics["Valor Unitario"].map("${:,.2f}".format) age_demographics ["Valor Total de Compra"] = age_demographics["Valor Total de Compra"].map("${:,.2f}".format) age_demographics ["%"] = age_demographics["%"].map("{:,.2f}%".format) # - # Resultado player_demographics.head() # Resultado age_demographics = age_demographics.sort_index() age_demographics # ## Top Spenders # + # Cรกlculos bรกsicos user_total = purchase_file.groupby(["Login"]).sum()["Valor"].rename("Valor Total de Compra") user_average = purchase_file.groupby(["Login"]).mean()["Valor"].rename("Valor Mรฉdio de Compra") user_count = purchase_file.groupby(["Login"]).count()["Valor"].rename("Nรบmero de Compras") # Dataframe para os resultados user_data = pd.DataFrame({"Valor Total de Compra": user_total, "Valor Mรฉdio de Compra": user_average, "Nรบmero de Compras": user_count}) # Data Munging user_data ["Valor Total de Compra"] = user_data["Valor Total de Compra"].map("${:,.2f}".format) user_data ["Valor Mรฉdio de Compra"] = user_data["Valor Mรฉdio de Compra"].map("${:,.2f}".format) user_data.sort_values("Valor Total de Compra", ascending=False).head(5) # - # Resultado user_data # ## Itens Mais Populares # + # Cรกlculos bรกsicos user_total = purchase_file.groupby(["Nome do Item"]).sum()["Valor"].rename("Valor Total de Compra") user_average = purchase_file.groupby(["Nome do Item"]).mean()["Valor"].rename("Valor Mรฉdio de Compra") user_count = purchase_file.groupby(["Nome do Item"]).count()["Valor"].rename("Nรบmero de Compras") # Dataframe para os resultados user_data = pd.DataFrame({"Valor Total de Compra": user_total, "Valor Mรฉdio de Compra": user_average, "Nรบmero de Compras": user_count}) # Data Munging user_data ["Valor Total de Compra"] = user_data["Valor Total de Compra"].map("${:,.2f}".format) user_data ["Valor Mรฉdio de Compra"] = user_data["Valor Mรฉdio de Compra"].map("${:,.2f}".format) user_data.sort_values("Nรบmero de Compras", ascending=False).head(5) # - # ## Itens Mais Lucrativos # + # Cรกlculos bรกsicos user_total = purchase_file.groupby(["Nome do Item"]).sum()["Valor"].rename("Valor Total de Compra") user_average = purchase_file.groupby(["Nome do Item"]).mean()["Valor"].rename("Valor Mรฉdio de Compra") user_count = purchase_file.groupby(["Nome do Item"]).count()["Valor"].rename("Nรบmero de Compras") # Dataframe para os resultados user_data = pd.DataFrame({"Valor Total de Compra": user_total, "Valor Mรฉdio de Compra": user_average, \ "Nรบmero de Compras": user_count}) # Data Munging user_data ["Valor Total Compra"] = user_data["Valor Total de Compra"] user_data ["Valor Total de Compra"] = user_data["Valor Total de Compra"].map("${:,.2f}".format) user_data ["Valor Mรฉdio de Compra"] = user_data["Valor Mรฉdio de Compra"].map("${:,.2f}".format) display(user_data.sort_values("Valor Total Compra", ascending=False).head(5)[ \ ['Valor Total de Compra','Valor Mรฉdio de Compra','Nรบmero de Compras']]) # - # ## Fim # ### Obrigado - Data Science Academy - <a href="http://facebook.com/dsacademybr">facebook.com/dsacademybr</a>
scripts-python-solucoes-propostas/DesafioDSA_Solucao/Missao5/missao5_solucao.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 # --- # + # Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Basic word2vec example.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import collections import math import os import random import sys from tempfile import gettempdir import zipfile import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector data_index = 0 def word2vec_basic(log_dir): """Example of building, training and visualizing a word2vec model.""" # Create the directory for TensorBoard variables if there is not. if not os.path.exists(log_dir): os.makedirs(log_dir) # Step 1: Download the data. url = 'http://mattmahoney.net/dc/' # pylint: disable=redefined-outer-name def maybe_download(filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" local_filename = os.path.join(gettempdir(), filename) if not os.path.exists(local_filename): local_filename, _ = urllib.request.urlretrieve(url + filename, local_filename) statinfo = os.stat(local_filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: print(statinfo.st_size) raise Exception('Failed to verify ' + local_filename + '. Can you get to it with a browser?') return local_filename filename = maybe_download('text8.zip', 31344016) # Read the data into a list of strings. def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data vocabulary = read_data(filename) print('Data size', len(vocabulary)) # Step 2: Build the dictionary and replace rare words with UNK token. vocabulary_size = 50000 def build_dataset(words, n_words): """Process raw inputs into a dataset.""" count = [['UNK', -1]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = {} for word, _ in count: dictionary[word] = len(dictionary) data = [] unk_count = 0 for word in words: index = dictionary.get(word, 0) if index == 0: # dictionary['UNK'] unk_count += 1 data.append(index) count[0][1] = unk_count reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary # Filling 4 global variables: # data - list of codes (integers from 0 to vocabulary_size-1). # This is the original text but words are replaced by their codes # count - map of words(strings) to count of occurrences # dictionary - map of words(strings) to their codes(integers) # reverse_dictionary - maps codes(integers) to words(strings) data, count, unused_dictionary, reverse_dictionary = build_dataset( vocabulary, vocabulary_size) del vocabulary # Hint to reduce memory. print('Most common words (+UNK)', count[:5]) print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]]) # Step 3: Function to generate a training batch for the skip-gram model. def generate_batch(batch_size, num_skips, skip_window): global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window target skip_window ] buffer = collections.deque(maxlen=span) # pylint: disable=redefined-builtin if data_index + span > len(data): data_index = 0 buffer.extend(data[data_index:data_index + span]) data_index += span for i in range(batch_size // num_skips): context_words = [w for w in range(span) if w != skip_window] words_to_use = random.sample(context_words, num_skips) for j, context_word in enumerate(words_to_use): batch[i * num_skips + j] = buffer[skip_window] labels[i * num_skips + j, 0] = buffer[context_word] if data_index == len(data): buffer.extend(data[0:span]) data_index = span else: buffer.append(data[data_index]) data_index += 1 # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, labels batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1) for i in range(8): print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0], reverse_dictionary[labels[i, 0]]) # Step 4: Build and train a skip-gram model. batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. skip_window = 1 # How many words to consider left and right. num_skips = 2 # How many times to reuse an input to generate a label. num_sampled = 64 # Number of negative examples to sample. # We pick a random validation set to sample nearest neighbors. Here we limit # the validation samples to the words that have a low numeric ID, which by # construction are also the most frequent. These 3 variables are used only for # displaying model accuracy, they don't affect calculation. valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # Only pick dev samples in the head of the distribution. valid_examples = np.random.choice(valid_window, valid_size, replace=False) graph = tf.Graph() with graph.as_default(): # Input data. with tf.name_scope('inputs'): train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Ops and variables pinned to the CPU because of missing GPU implementation with tf.device('/cpu:0'): # Look up embeddings for inputs. with tf.name_scope('embeddings'): embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_inputs) # Construct the variables for the NCE loss with tf.name_scope('weights'): nce_weights = tf.Variable( tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) with tf.name_scope('biases'): nce_biases = tf.Variable(tf.zeros([vocabulary_size])) # Compute the average NCE loss for the batch. # tf.nce_loss automatically draws a new sample of the negative labels each # time we evaluate the loss. # Explanation of the meaning of NCE loss: # http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/ with tf.name_scope('loss'): loss = tf.reduce_mean( tf.nn.nce_loss( weights=nce_weights, biases=nce_biases, labels=train_labels, inputs=embed, num_sampled=num_sampled, num_classes=vocabulary_size)) # Add the loss value as a scalar to summary. tf.summary.scalar('loss', loss) # Construct the SGD optimizer using a learning rate of 1.0. with tf.name_scope('optimizer'): optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss) # Compute the cosine similarity between minibatch examples and all # embeddings. norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keepdims=True)) normalized_embeddings = embeddings / norm valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset) similarity = tf.matmul( valid_embeddings, normalized_embeddings, transpose_b=True) # Merge all summaries. merged = tf.summary.merge_all() # Add variable initializer. init = tf.global_variables_initializer() # Create a saver. saver = tf.train.Saver() # Step 5: Begin training. num_steps = 100001 with tf.compat.v1.Session(graph=graph) as session: # Open a writer to write summaries. writer = tf.summary.FileWriter(log_dir, session.graph) # We must initialize all variables before we use them. init.run() print('Initialized') average_loss = 0 for step in xrange(num_steps): batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window) feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels} # Define metadata variable. run_metadata = tf.RunMetadata() # We perform one update step by evaluating the optimizer op (including it # in the list of returned values for session.run() # Also, evaluate the merged op to get all summaries from the returned # "summary" variable. Feed metadata variable to session for visualizing # the graph in TensorBoard. _, summary, loss_val = session.run([optimizer, merged, loss], feed_dict=feed_dict, run_metadata=run_metadata) average_loss += loss_val # Add returned summaries to writer in each step. writer.add_summary(summary, step) # Add metadata to visualize the graph for the last run. if step == (num_steps - 1): writer.add_run_metadata(run_metadata, 'step%d' % step) if step % 2000 == 0: if step > 0: average_loss /= 2000 # The average loss is an estimate of the loss over the last 2000 # batches. print('Average loss at step ', step, ': ', average_loss) average_loss = 0 # Note that this is expensive (~20% slowdown if computed every 500 steps) if step % 10000 == 0: sim = similarity.eval() for i in xrange(valid_size): valid_word = reverse_dictionary[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k + 1] log_str = 'Nearest to %s:' % valid_word for k in xrange(top_k): close_word = reverse_dictionary[nearest[k]] log_str = '%s %s,' % (log_str, close_word) print(log_str) final_embeddings = normalized_embeddings.eval() # Write corresponding labels for the embeddings. with open(log_dir + '/metadata.tsv', 'w') as f: for i in xrange(vocabulary_size): f.write(reverse_dictionary[i] + '\n') # Save the model for checkpoints. saver.save(session, os.path.join(log_dir, 'model.ckpt')) # Create a configuration for visualizing embeddings with the labels in # TensorBoard. config = projector.ProjectorConfig() embedding_conf = config.embeddings.add() embedding_conf.tensor_name = embeddings.name embedding_conf.metadata_path = os.path.join(log_dir, 'metadata.tsv') projector.visualize_embeddings(writer, config) writer.close() # Step 6: Visualize the embeddings. # pylint: disable=missing-docstring # Function to draw visualization of distance between embeddings. def plot_with_labels(low_dim_embs, labels, filename): assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings' plt.figure(figsize=(18, 18)) # in inches for i, label in enumerate(labels): x, y = low_dim_embs[i, :] plt.scatter(x, y) plt.annotate( label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.savefig("Embeddings2D.png") try: # pylint: disable=g-import-not-at-top from sklearn.manifold import TSNE import matplotlib.pyplot as plt tsne = TSNE( perplexity=30, n_components=2, init='pca', n_iter=5000, method='exact') plot_only = 500 low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :]) labels = [reverse_dictionary[i] for i in xrange(plot_only)] plot_with_labels(low_dim_embs, labels, os.path.join(gettempdir(), 'tsne.png')) except ImportError as ex: print('Please install sklearn, matplotlib, and scipy to show embeddings.') print(ex) # All functionality is run after tf.compat.v1.app.run() (b/122547914). This # could be split up but the methods are laid sequentially with their usage for # clarity. def main(unused_argv): # Give a folder path as an argument with '--log_dir' to save # TensorBoard summaries. Default is a log folder in current directory. current_path = os.path.dirname(os.path.realpath(sys.argv[0])) parser = argparse.ArgumentParser() parser.add_argument( '--log_dir', type=str, default=os.path.join(current_path, 'log'), help='The log directory for TensorBoard summaries.') flags, unused_flags = parser.parse_known_args() word2vec_basic(flags.log_dir) if __name__ == '__main__': tf.app.run() # -
.ipynb_checkpoints/Word2VecTensorFlow-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: chicagotaxi # language: python # name: chicagotaxi # --- import csv import pandas as pd import numpy as np #from sklearn import from sklearn.linear_model import LinearRegression from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt import statsmodels.api as sm from scipy import stats # %matplotlib inline # ## Years to Load years = [15, 16] # + taxi_df = {} for i in years: taxi_df[i] = pd.read_csv("../dataset_4_02_modified/20" + str(i) \ + "lag.csv", sep = ",") # "2016" and before # taxi_df[15] = pd.concat([taxi_df[15], taxi_df[16]], axis = 0)\ # .reset_index().drop(columns = ['index']) # - y_df = {} X_raw_df = {} for i in years: y_df[i] = pd.DataFrame(taxi_df[i]['Count']) X_raw_df[i] = taxi_df[i].drop(columns = ['Pickup Community Area', \ 'Count', 'Trip Start Timestamp']) # + weekdays = ['0','1','2','3','4','5','6'] enc = OneHotEncoder(categories=[weekdays]) encoded_df = {} for i in years: enc.fit(X_raw_df[i].weekday.values.reshape(-1, 1)) encoded_df[i] = pd.DataFrame(enc.transform(X_raw_df[i].weekday.values.reshape(-1, 1))\ .toarray().astype(int))\ .rename(columns = {0: 'Monday', 1:'Tuesday', 2:'Wedneseday',\ 3:'Thursday', 4:'Friday', 5:'Saturday',\ 6:'Sunday'}) # - X_encode_df = {} for i in years: X_encode_df[i] = pd.concat([X_raw_df[i].drop(columns=['weekday']), encoded_df[i]], axis=1) X_mat = {} y_mat = {} for i in years: X_mat[i] = X_encode_df[i].values y_mat[i] = y_df[i].values reg = LinearRegression().fit(X_mat[15], y_mat[15]) reg.score(X_mat[16], y_mat[16]) X2 = sm.add_constant(X_mat[15]) est = sm.OLS(y_mat[15], X2) est2 = est.fit() print(est2.summary()) for i in range(0, len(reg.coef_[0])): print("{2} {0} {1}".format(X_encode_df[16].columns.values[i], round(reg.coef_[0][i], 2),i+1)) # # Add 2dg terms for lon and lat for i in years: X_encode_df[i]['lat_sq'] = round(X_encode_df[i].lat.pow(2),4) X_encode_df[i]['lon_sq'] = round(X_encode_df[i].lon.pow(2),4) X_encode_df[i]['latXlon'] = round(X_encode_df[i].lat*X_encode_df[i].lon, 4) X_mat = {} y_mat = {} for i in years: X_mat[i] = X_encode_df[i].values y_mat[i] = y_df[i].values reg2 = LinearRegression().fit(X_mat[15], y_mat[15]) # ## R^2 reg2.score(X_mat[16], y_mat[16]) X2 = sm.add_constant(X_mat[15]) est = sm.OLS(y_mat[15], X2) est2 = est.fit() print(est2.summary()) for i in range(0, len(reg2.coef_[0])): print("{2} {0} {1}".format(X_encode_df[16].columns.values[i], round(reg2.coef_[0][i], 2),i+1)) # ## Mean Square Error reg2_pred16 = reg2.predict(X_mat[16]) mean_squared_error(y_true = y_mat[16], y_pred = reg2_pred16) # ## Analyze error distribution plt.hist(x = (y_mat[17] - reg2_pred16).reshape(1,-1)[0]) # ## Results (ARIMA) # ### Original terms: # #### Train 2015, Test 2016: Test R^2 0.97, Test MSE 398 # ### Lon Lat Sq terms: # #### Train 2015, Test 2016: Test R^2 0.97, Test MSE 397
linear_model_ARIMA.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.0.3 # language: julia # name: julia-1.0 # --- # This brief notebook is to demonstrate how composition of polynomials can accelerate convergence. # + using Plots, LinearAlgebra chebnodes(N) = [ cos(j*ฯ€/N) for j = N:-1:0 ] function bary(f::Function, N, x) X = chebnodes(N) F = f.(X) return bary(F, x; X=X) end function bary(F::Vector, x; X = chebnodes(length(F)-1)) N = length(F)-1 p = 0.5 * ( F[1] ./ (x .- X[1]) + (-1)^N * F[N+1] ./(x .- X[N+1]) ) q = 0.5 * (1.0 ./ (x .- X[1]) + (-1)^N ./ (x .- X[N+1])) for n = 1:N-1 p += (-1)^n * F[n+1] ./ (x .- X[n+1]) q += (-1)^n ./ (x .- X[n+1]) end return p ./ q end plotgrid(Np) = range(-1+0.0123, stop=1-0.00321, length=Np) errgrid(Np) = range(-1+0.0123, stop=1-0.00321, length=Np) # - f(ฮฒ, x) = 1 / (1 + exp(ฮฒ*x)) ฮฒ = 100 xp = range(-1, stop=1, length=300) plot(xp, f.(ฮฒ, xp), lw=2) f(ฮฒ, x) = 1 / (1 + exp(ฮฒ*x)) ฮฒ = 100 f(x) = f(ฮฒ, x) Y(x) = (0.1*x + x^3) / 1.1 g(x) = f(Y(x)) xp = range(-1, stop=1, length=300) plot(xp, f.(ฮฒ, xp), lw=2, label="Fermi-dirac") plot!(xp, g.(xp), lw=2, label="transformed") xp = errgrid(1000) NN = 2:4:100 err_f = [ norm(f.(xp) - bary(f, N, xp), Inf) for N = NN] err_g = [ norm(g.(xp) - bary(g, N, xp), Inf) for N = NN] # pred = 1.5*exp.(-NN/5) plot(NN, [err_f, err_g], lw=2, m=:o, label=["err_f", "err_g"], yaxis = (:log,)) # The idea is we can first approximate $g_\beta(x) \approx p(x)$ and then evaluate $f_\beta(x) \approx p(Y^{-1}(x))$. This is fine as long as we have a cheap way to compute $Y^{-1}(x)$. But this involves roots which are just as difficult, if not more difficult to evaluate than $f_\beta$! The solution is to create a crude polynomial approximation to $Y^{-1}$. Or, alternatively, we can specify $Y^{1}$ directly first. # R(x) represents Y^{-1}(x) epsn = 0.001 R(x) = sign(x)*((abs(x)+epsn)^(1/3) - epsn^(1/3)) / ((1+epsn)^(1/3) - epsn^(1/3)) xx = plotgrid(500) # and p_xx is a polynomial approximation to Y^{-1}! p_xx = bary(R, 40, xx) plot(xx, [R.(xx), p_xx], lw = 2) # now we need to invert R(x) to get R^{-1}(x) ~ Y(x) using Roots RR = R.(chebnodes(40)) pp(x) = bary(RR, x) pp_inv(y) = (abs(y) == 1.0 ? y : fzero(x -> pp(x) - y, y^3, xatol = 1e-10)) ฮฒ = 100 f(x) = 1 / (1 + exp(ฮฒ*x)) g(x) = f(pp_inv(x)) xx = plotgrid(400) plot(xx, [f.(xx), g.(xx)], lw=2, label=["Fermi-Dirac", "Transformed"]) ## ERROR TEST xp = errgrid(1000) NN = 2:4:100 err_f = [ norm(f.(xp) - bary(f, N, xp), Inf) for N = NN] err_g = [ norm(g.(xp) - bary(g, N, xp), Inf) for N = NN] # pred = 1.5*exp.(-NN/5) plot(NN, [err_f, err_g], lw=2, m=:o, label=["err_f", "err_g"], yaxis = (:log,))
jl/Fermi-Transform.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 # --- # ## What is the optimal geometry for social distancing? # # Given the desire to position N people, in 2D space, while maintaing minimal distance of not closer then 2m, is there an optimal arragement? and if so, what is it, for N=2 to N=10 # + import numpy as np import math # sample point sets c3 = 2*math.sin(math.pi/3) c2 = 2*math.sin(math.pi/4) sample3 = np.array(((0, 0), (2, 0), (1, c3))) sample4 = np.array(((0, 0), (2, 0), (0, 2), (2, 2))) sample4_2 = np.array(((0, 0), (2, 0), (1, c3), (1, -c3))) sample5 = np.array(((0, 0), (2, 0), (-2, 0), (0, 2), (0, -2))) sample5_2 = np.array(((0, 0), (2, 0), (1, c3), (1, -c3), (-1, -c3))) sample5_3 = np.array(((0, 0), (c2, c2), (c2, -c2), (-c2, c2), (-c2, -c2))) sample5_4 = np.array(((0, 0), (-1, c3), (1, c3), (1, -c3), (-1, -c3))) sample7 = np.array(((0, 0), (2, 0), (1, c3), (1, -c3), (-2, 0), (-1, c3), (-1, -c3))) # calc average distance in array def avgdist(ar): sum = 0 for c in it.combinations(ar, 2): d = np.linalg.norm(c[0]-c[1]) if round(d, 8) < 2: return 0 sum += d trig = (ar.shape[0] * (ar.shape[0] - 1)) / 2 return sum / trig print("sample3: %s" % str(avgdist(sample3))) print("sample4: %s" % str(avgdist(sample4))) print("sample4_2: %s" % str(avgdist(sample4_2))) print("sample5: %s" % str(avgdist(sample5))) print("sample5_2: %s" % str(avgdist(sample5_2))) # + fig, axs = plt.subplots(2, 2) def showaxe(axe, ar): axe.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) axe.scatter(ar[:,0], ar[:,1], 400) axe.set_xlim(-3, 3) axe.set_ylim(-3, 3) axe.grid() fig.gca().set_aspect('equal', adjustable='box') fig.set_size_inches(8, 8) axe.set_title("N=%d, D=%f" % (ar.shape[0], avgdist(ar))) showaxe(axs[0][0], sample5_2) showaxe(axs[0][1], sample5_3) showaxe(axs[1][0], sample5_4) showaxe(axs[1][1], sample7) # -
notebooks/optimal-social-distancing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- # %load_ext load_style # %load_style talk.css # # Power Spectral Density # ## Introduction # # * Methods # # > This notebook consists of two methods to carry Spectral Analysis. # # > The first one is based on covariance called **pcovar**, which comes from Spectrum: a Spectral Analysis Library in Python. This library that contains tools to estimate Power Spectral Densities based on Fourier transform, Parametric methods or eigenvalues analysis. See more from http://pyspectrum.readthedocs.io/en/latest/index.html. # # > Install can be done ==> conda install spectrum # # > The second is the welch method that comes from the package of scipy.signal. The library also contains many kinds of method. See more from https://docs.scipy.org/doc/scipy/reference/signal.html. # # > In fact, both matplotlib.mlab and Spectrumalso implements the welch method. However, They do not appear flexible as one from scipy.signal. An common error looks like "*ValueError: The len(window) must be the same as the shape of x for the chosen axis*". # # * Data # # > The 30-years nino3 SSTA series from a previous notebook will be used as an example. # ## 1. Load basic libraries # + % matplotlib inline import warnings warnings.filterwarnings('ignore') import numpy as np from scipy import signal import matplotlib.pyplot as plt from matplotlib import mlab from spectrum import pcovar from pylab import rcParams rcParams['figure.figsize'] = 15, 6 # - # ## 2. Load nino3 SSTA series # # Please keep in mind that the nino3 SSTA series lies between 1970 and 1999 <br> # Recall ex2 # ### 2.1 Load data npzfile = np.load('data/ssta.nino3.30y.npz') npzfile.files ssta_series = npzfile['ssta_series'] ssta_series.shape # ### 2.2 Have a quick plot plt.plot(ssta_series) # ## 3. Estimates the power spectral density (PSD ) # ### 3.1 pcovar method # #### 3.1.1 Create PSD # + nw = 48 # order of an autoregressive prediction model for the signal, used in estimating the PSD. nfft = 256 # NFFT (int) โ€“ total length of the final data sets (padded with zero if needed fs = 1 # default value p = pcovar(ssta_series, nw, nfft, fs) # - # #### 3.1.2 Visualize using embeded plot p.plot(norm=True) #help(p.plot) # #### 3.1.3 Visualize by a customized way # # Access the data and properties of a object of pcovar # + # process frequencies and psd f0 = np.array(p.frequencies()) pxx0 = p.psd/np.max(p.psd) # noralize the psd values plt.plot(1.0/f0[1:47]/12, pxx0[1:47]) plt.title('NINO 3 Spectrum via pcovar'); plt.xlabel('Years') # - # ### 3.2 welch method # + n = 150 alpha = 0.5 noverlap = 75 nfft = 256 #default value fs = 1 #default value win = signal.tukey(n, alpha) ssta = ssta_series.reshape(360) # convert vector f1, pxx1 = signal.welch(ssta, nfft=nfft, fs=fs, window=win, noverlap=noverlap) # process frequencies and psd pxx1 = pxx1/np.max(pxx1) # noralize the psd values plt.plot(1.0/f1[1:47]/12, pxx1[1:47], label='welch') plt.title('NINO 3 Spectrum via welch'); plt.xlabel('Years') # - # ## 4. Have a comparison plt.plot(1.0/f0[1:47]/12, pxx0[1:47], label='pcov') plt.plot(1.0/f1[1:47]/12, pxx1[1:47], label='welch') plt.title('NINO 3 Spectrum'); plt.legend() plt.xlabel('Years') # ## References # # Bendat & Piersol โ€“ Random Data: Analysis and Measurement Procedures, <NAME> & Sons (1986) # # Matplotlib: A 2D Graphics Environment by <NAME> In Computing in Science & Engineering, Vol. 9, No. 3. (2007), pp. 90-95 # # <NAME>, <NAME>, <NAME>, et al. SciPy: Open Source Scientific Tools for Python, 2001-, http://www.scipy.org/
ex20-Power spectral density.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/cateto/python4NLP/blob/main/kMeans/sklearn_k_means_test.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="vd5oupp2PZPE" outputId="a11ecbec-42a3-43d0-8061-beabcec59dbb" from google.colab import drive drive.mount('/content/drive') # + id="7bWpQBjmPVXf" import pandas as pd save_path = "/content/drive/MyDrive/sentence_sim/sampling_data_แ„แ…ฉแ„…แ…ฉแ„‚แ…ก_5.json" # + id="UAFs2hFvPvlB" import json with open(save_path, 'r') as datafile: data = json.load(datafile) df = pd.DataFrame(data) # + id="F2HLAwwIQSXN" target_df = df # + id="0qeMTBaZQc1l" del df # + id="ExfeNtppRE7N" db_array = np.array(target_df['embedding'].to_list(), dtype=np.float32) # + id="M4CK-G1HQdU-" from sklearn.cluster import KMeans import time import numpy as np num_clusters = 4 # K means ๋ฅผ ์ •์˜ํ•˜๊ณ  ํ•™์Šต์‹œํ‚จ๋‹ค. kmeans_clustering = KMeans( n_clusters = num_clusters ) idx = kmeans_clustering.fit_predict( db_array ) target_df['topic'] = idx # + colab={"base_uri": "https://localhost:8080/", "height": 586} id="_fYCHAX-RGV_" outputId="8db4812b-13b0-4d55-82f9-31eab84c46b7" target_df[:10] # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="CnLI023MSOsg" outputId="e9f5be3e-5d50-4b6a-cb34-6f2d84557220" target_df['title'][5] # topic 0 # + colab={"base_uri": "https://localhost:8080/", "height": 52} id="jrzvx39USmGv" outputId="2372db59-ff91-4502-86bb-998a2907eafc" target_df['title'][6] # topic 1 # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="f7Z_8KIYSnLu" outputId="3b891179-bab5-4224-bcbc-a3d11dc3c1f4" target_df['title'][7] # topic 2 # + id="3sKAKM6eSn8A"
kMeans/sklearn_k_means_test.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 # --- # ## Learning Algorithms - Supervised Learning # # > Reminder: All supervised estimators in scikit-learn implement a `fit(X, y)` method to fit the model and a `predict(X)` method that, given unlabeled observations X, returns the predicted labels y. (direct quote from `sklearn` docs) # # * Given that Iris is a fairly small, labeled dataset with relatively few features...what algorithm would you start with and why? # > "Often the hardest part of solving a machine learning problem can be finding the right estimator for the job." # # > "Different estimators are better suited for different types of data and different problems." # # <a href = "http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html" style = "float: right">-Choosing the Right Estimator from sklearn docs</a> # # + # Imports for python 2/3 compatibility from __future__ import absolute_import, division, print_function, unicode_literals # For python 2, comment these out: # from builtins import range # - # <b>An estimator for recognizing a new iris from its measurements</b> # # > Or, in machine learning parlance, we <i>fit</i> an estimator on known samples of the iris measurements to <i>predict</i> the class to which an unseen iris belongs. # # Let's give it a try! (We are actually going to hold out a small percentage of the `iris` dataset and check our predictions against the labels) # + from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split # Let's load the iris dataset iris = load_iris() X, y = iris.data, iris.target # split data into training and test sets using the handy train_test_split func # in this split, we are "holding out" only one value and label (placed into X_test and y_test) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3) # + # Let's try a decision tree classification method from sklearn import tree t = tree.DecisionTreeClassifier(max_depth = 4, criterion = 'entropy', class_weight = 'balanced', random_state = 2) t.fit(X_train, y_train) t.score(X_test, y_test) # what performance metric is this? # + # What was the label associated with this test sample? ("held out" sample's original label) # Let's predict on our "held out" sample y_pred = t.predict(X_test) print(y_pred) # fill in the blank below # how did our prediction do for first sample in test dataset? print("Prediction: %d, Original label: %d" % (y_pred[0], ___)) # <-- fill in blank # + # Here's a nifty way to cross-validate (useful for quick model evaluation!) from sklearn import cross_validation t = tree.DecisionTreeClassifier(max_depth = 4, criterion = 'entropy', class_weight = 'balanced', random_state = 2) # splits, fits and predicts all in one with a score (does this multiple times) score = cross_validation.cross_val_score(t, X, y) score # - # QUESTIONS: What do these scores tell you? Are they too high or too low you think? If it's 1.0, what does that mean? # ### What does the graph look like for this decision tree? i.e. what are the "questions" and "decisions" for this tree... # * Note: You need both Graphviz app and the python package `graphviz` (It's worth it for this cool decision tree graph, I promise!) # * To install both on OS X: # ``` # sudo port install graphviz # sudo pip install graphviz # ``` # * For general Installation see [this guide](http://graphviz.readthedocs.org/en/latest/manual.html) # + from sklearn.tree import export_graphviz import graphviz # Let's rerun the decision tree classifier from sklearn import tree t = tree.DecisionTreeClassifier(max_depth = 4, criterion = 'entropy', class_weight = 'balanced', random_state = 2) t.fit(X_train, y_train) t.score(X_test, y_test) # what performance metric is this? export_graphviz(t, out_file="mytree.dot", feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True, special_characters=True) with open("mytree.dot") as f: dot_graph = f.read() graphviz.Source(dot_graph, format = 'png') # - # ### From Decision Tree to Random Forest # + from sklearn.datasets import load_iris import pandas as pd import numpy as np iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3) # + from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(max_depth=4, criterion = 'entropy', n_estimators = 100, class_weight = 'balanced', n_jobs = -1, random_state = 2) #forest = RandomForestClassifier() forest.fit(X_train, y_train) y_preds = iris.target_names[forest.predict(X_test)] forest.score(X_test, y_test) # + # Here's a nifty way to cross-validate (useful for model evaluation!) from sklearn import cross_validation # reinitialize classifier forest = RandomForestClassifier(max_depth=4, criterion = 'entropy', n_estimators = 100, class_weight = 'balanced', n_jobs = -1, random_state = 2) score = cross_validation.cross_val_score(forest, X, y) score # - # QUESTION: Comparing to the decision tree method, what do these accuracy scores tell you? Do they seem more reasonable? # ### Splitting into train and test set vs. cross-validation # <p>We can be explicit and use the `train_test_split` method in scikit-learn ( [train_test_split](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html) ) as in (and as shown above for `iris` data):<p> # # ```python # # Create some data by hand and place 70% into a training set and the rest into a test set # # Here we are using labeled features (X - feature data, y - labels) in our made-up data # import numpy as np # from sklearn import linear_model # from sklearn.cross_validation import train_test_split # X, y = np.arange(10).reshape((5, 2)), range(5) # X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.70) # clf = linear_model.LinearRegression() # clf.fit(X_train, y_train) # ``` # # OR # # Be more concise and # # ```python # import numpy as np # from sklearn import cross_validation, linear_model # X, y = np.arange(10).reshape((5, 2)), range(5) # clf = linear_model.LinearRegression() # score = cross_validation.cross_val_score(clf, X, y) # ``` # # <p>There is also a `cross_val_predict` method to create estimates rather than scores and is very useful for cross-validation to evaluate models ( [cross_val_predict](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.cross_val_predict.html) ) # Created by a Microsoft Employee. # # The MIT License (MIT)<br> # Copyright (c) 2016 <NAME>
04.Supervised Learning.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 # --- # ## Gaussian Process Latent Variable Model # The [Gaussian Process Latent Variable Model](https://en.wikipedia.org/wiki/Nonlinear_dimensionality_reduction#Gaussian_process_latent_variable_models) (GPLVM) is a dimensionality reduction method that uses a Gaussian process to learn a low-dimensional representation of (potentially) high-dimensional data. In the typical setting of Gaussian process regression, where we are given inputs $X$ and outputs $y$, we choose a kernel and learn hyperparameters that best describe the mapping from $X$ to $y$. In the GPLVM, we are not given $X$: we are only given $y$. So we need to learn $X$ along with the kernel hyperparameters. # We do not do maximum likelihood inference on $X$. Instead, we set a Gaussian prior for $X$ and learn the mean and variance of the approximate (gaussian) posterior $q(X|y)$. In this notebook, we show how this can be done using the `pyro.contrib.gp` module. In particular we reproduce a result described in [2]. # + import os import matplotlib.pyplot as plt import pandas as pd import torch from torch.nn import Parameter import pyro import pyro.contrib.gp as gp import pyro.distributions as dist import pyro.ops.stats as stats smoke_test = ('CI' in os.environ) # ignore; used to check code integrity in the Pyro repo assert pyro.__version__.startswith('0.4.0') pyro.enable_validation(True) # can help with debugging pyro.set_rng_seed(1) # - # ### Dataset # The data we are going to use consists of [single-cell](https://en.wikipedia.org/wiki/Single-cell_analysis) [qPCR](https://en.wikipedia.org/wiki/Real-time_polymerase_chain_reaction) data for 48 genes obtained from mice (Guo *et al.*, [1]). This data is available at the [Open Data Science repository](https://github.com/sods/ods). The data contains 48 columns, with each column corresponding to (normalized) measurements of each gene. Cells differentiate during their development and these data were obtained at various stages of development. The various stages are labelled from the 1-cell stage to the 64-cell stage. For the 32-cell stage, the data is further differentiated into 'trophectoderm' (TE) and 'inner cell mass' (ICM). ICM further differentiates into 'epiblast' (EPI) and 'primitive endoderm' (PE) at the 64-cell stage. Each of the rows in the dataset is labelled with one of these stages. # + # license: Copyright (c) 2014, the Open Data Science Initiative # license: https://www.elsevier.com/legal/elsevier-website-terms-and-conditions URL = "https://raw.githubusercontent.com/sods/ods/master/datasets/guo_qpcr.csv" df = pd.read_csv(URL, index_col=0) print("Data shape: {}\n{}\n".format(df.shape, "-" * 21)) print("Data labels: {}\n{}\n".format(df.index.unique().tolist(), "-" * 86)) print("Show a small subset of the data:") df.head() # - # ### Modelling # First, we need to define the output tensor $y$. To predict values for all $48$ genes, we need $48$ Gaussian processes. So the required shape for $y$ is `num_GPs x num_data = 48 x 437`. data = torch.tensor(df.values, dtype=torch.get_default_dtype()) # we need to transpose data to correct its shape y = data.t() # Now comes the most interesting part. We know that the observed data $y$ has latent structure: in particular different datapoints correspond to different cell stages. We would like our GPLVM to learn this structure in an unsupervised manner. In principle, if we do a good job of inference then we should be able to discover this structure---at least if we choose reasonable priors. First, we have to choose the dimension of our latent space $X$. We choose $dim(X)=2$, since we would like our model to disentangle 'capture time' ($1$, $2$, $4$, $8$, $16$, $32$, and $64$) from cell branching types (TE, ICM, PE, EPI). Next, when we set the mean of our prior over $X$, we set the first dimension to be equal to the observed capture time. This will help the GPLVM discover the structure we are interested in and will make it more likely that that structure will be axis-aligned in a way that is easier for us to interpret. # + capture_time = y.new_tensor([int(cell_name.split(" ")[0]) for cell_name in df.index.values]) # we scale the time into the interval [0, 1] time = capture_time.log2() / 6 # we setup the mean of our prior over X X_prior_mean = torch.zeros(y.size(1), 2) # shape: 437 x 2 X_prior_mean[:, 0] = time # - # We will use a sparse version of Gaussian process inference to make training faster. Remember that we also need to define $X$ as a `Parameter` so that we can set a prior and guide (variational distribution) for it. # + kernel = gp.kernels.RBF(input_dim=2, lengthscale=torch.ones(2)) # we clone here so that we don't change our prior during the course of training X = Parameter(X_prior_mean.clone()) # we will use SparseGPRegression model with num_inducing=32; # initial values for Xu are sampled randomly from X_prior_mean Xu = stats.resample(X_prior_mean.clone(), 32) gplvm = gp.models.SparseGPRegression(X, y, kernel, Xu, noise=torch.tensor(0.01), jitter=1e-5) # - # We will use the [set_prior()](http://docs.pyro.ai/en/dev/contrib.gp.html#pyro.contrib.gp.parameterized.Parameterized.set_prior) and [autoguide()](http://docs.pyro.ai/en/dev/contrib.gp.html#pyro.contrib.gp.parameterized.Parameterized.autoguide) methods from the [Parameterized](http://docs.pyro.ai/en/dev/contrib.gp.html#module-pyro.contrib.gp.parameterized) class to set a prior and guide for $X$. # we use `.to_event()` to tell Pyro that the prior distribution for X has no batch_shape gplvm.set_prior("X", dist.Normal(X_prior_mean, 0.1).to_event()) gplvm.autoguide("X", dist.Normal) # ### Inference # As mentioned in the [Gaussian Processes tutorial](gp.ipynb), we can use the helper function [gp.util.train](http://docs.pyro.ai/en/dev/contrib.gp.html#pyro.contrib.gp.util.train) to train a Pyro GP module. By default, this helper function uses the Adam optimizer with a learning rate of `0.01`. # + # note that training is expected to take a minute or so losses = gp.util.train(gplvm, num_steps=4000) # let's plot the loss curve after 4000 steps of training plt.plot(losses) plt.show() # - # After inference, the mean and standard deviation of the approximated posterior $q(X) \sim p(X | y)$ will be stored in the parameters `X_loc` and `X_scale`. To get a sample from $q(X)$, we need to set the `mode` of `gplvm` to `"guide"`. gplvm.mode = "guide" X = gplvm.X # ### Visualizing the result # Letโ€™s see what we got by applying GPLVM to our dataset. # + plt.figure(figsize=(8, 6)) colors = plt.get_cmap("tab10").colors[::-1] labels = df.index.unique() X = gplvm.X_loc.detach().numpy() for i, label in enumerate(labels): X_i = X[df.index == label] plt.scatter(X_i[:, 0], X_i[:, 1], c=colors[i], label=label) plt.legend() plt.xlabel("pseudotime", fontsize=14) plt.ylabel("branching", fontsize=14) plt.title("GPLVM on Single-Cell qPCR data", fontsize=16) plt.show() # - # We can see that the first dimension of the latent $X$ for each cell (horizontal axis) corresponds well with the observed capture time (colors). On the other hand, the 32 TE cell and 64 TE cell are clustered near each other. And the fact that ICM cells differentiate into PE and EPI can also be observed from the figure! # ### Remarks # # + The sparse version scales well (linearly) with the number of data points. So the GPLVM can be used with large datasets. Indeed in [2] the authors have applied GPLVM to a dataset with 68k peripheral blood mononuclear cells. # # + Much of the power of Gaussian Processes lies in the function prior defined by the kernel. We recommend users try out different combinations of kernels for different types of datasets! For example, if the data contains periodicities, it might make sense to use a [Periodic kernel](http://docs.pyro.ai/en/dev/contrib.gp.html#periodic). Other kernels can also be found in the [Pyro GP docs](http://docs.pyro.ai/en/dev/contrib.gp.html#module-pyro.contrib.gp.kernels). # ### References # # [1] `Resolution of Cell Fate Decisions Revealed by Single-Cell Gene Expression Analysis from Zygote to Blastocyst`,<br />&nbsp;&nbsp;&nbsp;&nbsp; # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # [2] `GrandPrix: Scaling up the Bayesian GPLVM for single-cell data`,<br />&nbsp;&nbsp;&nbsp;&nbsp; # <NAME>, <NAME>, <NAME> # # [3] `Bayesian Gaussian Process Latent Variable Model`,<br />&nbsp;&nbsp;&nbsp;&nbsp; # <NAME>, <NAME> # # [4] `A novel approach for resolving differences in single-cell gene expression patterns from zygote to blastocyst`,<br />&nbsp;&nbsp;&nbsp;&nbsp; # <NAME>, <NAME>
tutorial/source/gplvm.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- # # PERMANOVA analysis for recurrent mutation profiles # + # Housekeeping library(ggplot2) library(reshape2) library(RVAideMemoire) library(scales) library(vegan) # + # Read in data variants = read.table("../../../data/deep_seq/downsampled_multihit_nonsynonymous_variant_data.txt", sep = "\t", header = T) # - variants2 = dcast(variants, TIME + ANTIBIOTIC + IMMIGRATION + REPLICATE + SPECIES ~ GENE, value.var = "COUNT") head(variants2) rownames(variants2) = paste(variants2$TIME, variants2$ANTIBIOTIC, variants2$IMMIGRATION, variants2$REPLICATE, variants2$SPECIES, sep = "_") meta = variants2[,1:5] data = as.matrix(variants2[,-c(1:5)]) head(meta) head(data) # + # T8 for all data T8 = meta$TIME == 8 meta_T8 = meta[T8,] data_T8 = data[T8,] y = colSums(data_T8) > 0 D_T8 = vegdist(data_T8) M_T8 = adonis(D_T8 ~ IMMIGRATION*ANTIBIOTIC*SPECIES, data = meta_T8) M_T8 # + # T12 for all data T12 = meta$TIME == 12 meta_T12 = meta[T12,] data_T12 = data[T12,] y = colSums(data_T12) > 0 D_T12 = vegdist(data_T12) M_T12 = adonis(D_T12 ~ IMMIGRATION*ANTIBIOTIC*SPECIES, data = meta_T12) M_T12 # - # ##### Most of the nonsynonymous multi-hit genes occur in the same species across treatments (PERMANOVA species: p < 0.001, R2 > 0.8), likely representing adaptation to experimental conditions. When the presence of species is accounted for, antibiotic also has a significant effect (p < 0.001) on the genes mutated both during and after recovery from the antibiotic pulse. Notably, the effect size of antibiotic decreases when the community recovers (during antibiotic pulse: R2 = 0.028; after recovery: R2 = 0.014). After recovery, immigration also affects the profile of mutated genes for certain species (immigration: p < 0.001; R2 = 0.008; immigration * species: p = 0.041, R2 = 0.012). # # Differentially mutated genes # + AB0 = unique(variants$GENE[variants$ANTIBIOTIC == 0]) AB1 = unique(variants$GENE[variants$ANTIBIOTIC != 0]) IM0 = unique(variants$GENE[variants$IMMIGRATION == 0]) IM1 = unique(variants$GENE[variants$IMMIGRATION != 0]) AB0 AB1 IM0 IM1 # Use as input for Venny 2.1 (http://bioinfogp.cnb.csic.es/tools/venny/, accessed 2019-03-25) # - inters = intersect(AB0, AB1) inters AB1_unique = AB1[!(AB1 %in% inters)] AB1_unique length(unique(variants$GENE))
src/notebooks/deep_seq/.ipynb_checkpoints/3_downsampled_recurrent_mutation_profiles-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 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Scraping with BeautifulSoup # + html_doc = """ <html><head><title>The title is Demo for BeautifulSoup</title></head> <body> <h1 class="title"><b>The title headline is Demo for BeautifulSoup</b></p> <section class="main" id="all_plants"> <p class="article">There are three things to keep in mind: <a href="http://example.com/plant1" class="plants life" id="plant1">Plant 1</a>: <span class="cost">$10</span>, <a href="http://example.com/plant2" class="plants life" id="plant2">Plant 2</a>: <span class="cost">$20</span> and <a href="http://example.com/plant3" class="plants life" id="plant3">Plant 3</a> <span class="cost">$30</span>; </p> <strong>Don't forget to water these 3 plants.</strong> </section> <section class="main" id="all_animals"> <p class="article"> There are three animals in the barn: <a href="http://example.com/animal1" class="animals life" id="animal1">Animal 1</a>: <span class="cost">$500</span>, <a href="http://example.com/animal2" class="animals life" id="animal2">Animal 2</a>: <span class="cost">$600</span> and <a href="http://example.com/animal3" class="animals life" id="animal3">Animal 3</a>: <span class="cost">$700</span>; </p> <strong>Don't forget these feed these 3 animals.</strong> </section> <section> <p><span>Inanimate object 1</span></p> <p><span>Inanimate object 2</span></p> <p><span>Inanimate object 3</span></p> </section> """ print(html_doc) # - from bs4 import BeautifulSoup ## import library # ## Create a BeautifulSoup object # <img src="../support_files/bs-soup.png"> ## we add name of our file soup = BeautifulSoup(html_doc, 'html.parser') soup ## What type of file is it? print(type(soup)) ## get title of page soup.title # + ## What about the h1 tag with the class of title? ## How can we have two titles? soup("h1", class_="title") # - # ### string v. get_text() # # In most cases, our final step in a scrape is to convert everything to a string. We don't want all the html. # # We can use ```.string``` or ```get_text().``` # # - ```get_text()``` is far more powerful because you can add parameters to strip, specify separators, etc. # ## get text from soup soup.get_text() ## get the type print(type(soup.get_text())) ## string will only work on individual tags, not on the entire soup object. ##soup.string returns nothing soup.string print(type(soup.string)) ## return just a string of the tag: soup.title.string ## get only title text and not html soup.title.get_text() ## get all p tag text soup.p.get_text() ## get rid of weird characters soup.p.get_text(strip=True) # ## Finding ```class``` # # ### There are three ways ranging from simplicity to precision. # # ```find()``` returns the first occurence of any item you are searching for. # # ### 1. Simplicity # # Because ```find``` is one of the most popular functions in ```BeautifulSoup```, # you don't even have to write it. # # ```soup("tag_name", "class_name")``` # ## simple but without precision # find all p tags with class "article" soup("p","article") # ### 2. Clarity # # We want to be clear what we are writing so all team members can more easily understand it later. # # - Use ```find``` to know what function it is. # - Use ```soup.find(class_="class_name"``` to be clear what class we are looking for. # - ```class_``` is not Python or BeautifulSoup. It is simply there to tell us we are looking for a ```class```. Because ```class``` (a type of data) is a Python reserved word, we add the ```_``` to tell us we are referring to an ```HTML class```. # # find all tags in the first occurence class "article" soup.find(class_="article") # ### 3. Precision # # In the previous example, we could have run into trouble in case the ```class = "article"``` applied to multiple tags. # # - Use the tag name to add precision. # - ```soup.find("tag_name", class_="class_name")``` soup.find("p", class_="article") # ## ```find_all``` tags, classes # # - ```find_all``` is *the most widely* used BeautifulSoup command. # - Unlike ```find``` it returns *ALL* occurences of a class or tag. # - Remember ```find``` returns just the first occurence. # - It returns all occurences in a ```beautifulSoup object``` that is similiar to a ```list```. ## Return all p tags with class article soup.find_all("p",class_="article") ## What if you want only the second group of life forms? soup.find_all("p", class_="article")[1] ## SEARCH BY ID for "animal1" soup(id="animal1") ## SEARCH BY ID for "plant1" soup(id="plant1") # ## Storing values # # We haven't been saving in values in memory. # # If we want to move beyond a demo, we need to start saving them. ## save all lifeforms in a object called lifeforms lifeforms = soup.find_all("a", class_="life") lifeforms ## what kind of object it it? print(type(lifeforms)) # ### Print lifeforms. Does it look familiar? ## print lifeforms print(lifeforms) # + ## This breaks! ## You can't just get the text for the lifeforms. ## Why? Because you can't call .get_text() on a <class 'bs4.element.ResultSet'> # print(lifeforms.string) # print(lifeforms.get_text()) # + ## just the text, no html ## Using for loop lifeforms_list = [] for life in lifeforms: # life = life.string life = life.get_text() lifeforms_list.append(life) lifeforms_list # + ## just the text, no html ## Using for list comprehension lifeforms_lc = [life.get_text() for life in lifeforms] lifeforms_lc # - # ## Get the urls for each # + ## use for loop all_urls_fl = [] for link in lifeforms: url = link.get("href") all_urls_fl.append(url) all_urls_fl # + # using list comprehension all_urls_lc = [a.get("href") for a in lifeforms] all_urls_lc # - # ## Cost # # Let's grab the cost # # How do we target the cost? ## A wide target: cost = soup.find_all("span") cost ## narrow the target cost = soup.find_all("span", class_="cost") cost # + ## using for loop cost_list_fl = [] for amount in cost: # amount = amount.get_text() amount = amount.string cost_list_fl.append(amount) cost_list_fl # - ## using list comprehension cost_list_lc = [amount.get_text() for amount in cost] cost_list_lc # ## Prepare to Export # # You now have one list that holds the name of the lifeform and another that holds the related URL. # # Let's create a dict call ```life_dict```. # # Keys are name and url...values are the related values # # ### Pure Python life_dict_list = [] for (name, cost, url) in zip(lifeforms_lc, cost_list_lc, all_urls_fl): life_dict = {"life_form": name, "cost": cost, "link": url} life_dict_list.append(life_dict) print(life_dict_list) # ### Using Pandas ## import pandas import pandas as pd # + df1 = pd.DataFrame(list(zip(lifeforms_lc, cost_list_lc,all_urls_lc)), columns =['life_form', 'cost', 'link']) df1 # - # ## Export as CSV # # We'll use Pandas to export our data to an external file. # # We'll cover this in more detail soon, but for now here it is: # + ## use pandas to write to csv file filename = "test.csv" ## what are file name is df = pd.DataFrame(life_dict_list) ## we turn our life dict into a dataframe which we're call df df.to_csv(filename, encoding='utf-8', index=False) ## export to csv as utf-8 coding (it just has to be this) print(f"{filename} is in your project folder!") ## a print out that tells us the file is ready # - # # BeautifulSoup # # We covered some basic BeautifulSoup functionality: # # - Remember ```soup``` is just a term we use to store an entire webpage or file. We could call it anything we want. # - Searching by ```tags``` like ```title```, ```h1```, ```span``` etc. # - Searching by ```class``` or ```id``` # - Finding all occurences of an item using ```find_all()``` # - Finding the first occurence of an item using ```find()``` # - Removing the html and returning just the string by using ```.string``` or ```get_text()``` # - Grabbing just the URL(s) using ```get("href")``` # # These are the most frequently used BeautifulSoup functions. You can [find many more](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#) in the documentation. #
week_04/week-4-inclass-beautifulsoup_SOLUTIONS.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 # --- # + # Ejecuta el archivo de atp import subprocess import time import sys, os # Get the opperative system operativeSystem = sys.platform # get the working directory if operativeSystem == 'linux': working_dir = os.getcwd() + "/" + 'ATP' + "/" else: working_dir = os.getcwd() + "\\" + 'ATP' + "\\" fileName = 'estudio_v2.atp' file = working_dir + fileName subprocess.run([r"runAtp.exe" ,r'"' + file + '"']) # + # Carga los datos import pandas as pd filepath = r"C:\Users\jsacostas\Dropbox\Doctorado\ATP_archivos\Resultados\estudio_v2.txt" df = pd.read_csv(filepath, skiprows=3, delim_whitespace=True, header=-1) df2 = pd.read_csv(filepath, delim_whitespace=True, skiprows=1) df.columns = df2.columns df = df.loc[1:2000,:] #df.columns.values[0] = 't' df.head() # + # Plot % matplotlib inline|nbagg import numpy as np import matplotlib.pyplot as plt # %matplotlib inline t = df.loc[:,'in'] Vin = df.loc[:,'FA':'FC'] plt.plot(t,Vin) plt.show() #t.values.reshape([-1,1])
ATP/.ipynb_checkpoints/ATP-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 # --- # # Logistic regression using `statsmodels` # + import numpy as np import pandas as pd import seaborn as sns import statsmodels.api as sm import statsmodels.formula.api as smf # %matplotlib inline # - # Read in the [British Crime Survey 2007-2008](https://beta.ukdataservice.ac.uk/datacatalogue/studies/study?id=6561) dataset. bcs = pd.read_csv("datasets/bcs.csv") bcs.head() # Define predictors and response. predictors = ["sex", "age", "safety_walk_night"] response = "victim_last_yr" all_vars = predictors + [response] # Remove missing values. bcs.dropna(subset=all_vars, inplace=True) # ## EDA sns.boxplot(x="victim_last_yr", y="age", data=bcs) bcs.groupby("safety_walk_night")["victim_last_yr"].mean().plot.bar(color="darkblue") # ## Logistic regression bcs["victim_last_yr"] = bcs["victim_last_yr"].astype(int) # Recode as 0/1 model = smf.glm( "victim_last_yr ~ C(sex, Treatment(reference='M')) + age + C(safety_walk_night, Treatment(reference='Very safe'))", data=bcs, family=sm.families.Binomial() ).fit() model.summary() np.exp(model.params) np.exp(model.conf_int()) model.pvalues
02-data-analysis/notebooks/02-statsmodels.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.10 64-bit (''pyraug'': conda)' # name: python3 # --- # # Tutorial 2 # # In this tutorial, we will see how to use the built-in function of Pyraug to set upd our own configuration for the trainer, models and samplers. This follows the section ``Setting up your own configuations`` of the documentation # ## Link between `.json` and `dataclasses` # # In pyraug, the configurations of the models, trainers and samplers are stored and used as dataclasses.dataclass and all inherit from the BaseConfig. Hence, any configuration class has a classmethod from_json_file coming from BaseConfig allowing to directly load config from `.json` files into dataclasses or save dataclasses into a ``.json`` file. # ### Loading a configuration from a `.json` # Since all `ModelConfig` inherit from `BaseModelConfig` data class, any pyraug's model configuration can be loaded from a `.json` file with the `from_json_file` classmethod. Defining your own `model_config.json` may be useful when you decide to use the Pyraug's scripts which take as arguments paths to json files. # # **note:** Make sure the keys and types match the one expected in the `dataclass` or errors will be raised. Check documentation to find the expected types and keys # + # If you run this notebook on colab uncomment the following lines # #!pip install pyraug # #!git clone https://github.com/clementchadebec/pyraug.git #import os #path=os.path.join(os.getcwd(), 'pyraug/examples') #os.chdir(path) # - from pyraug.models.base.base_config import BaseModelConfig config = BaseModelConfig.from_json_file('_demo_data/configs/model_config.json') print(config) # Let's try with a `RHVAE` model from pyraug.models.rhvae import RHVAEConfig config = RHVAEConfig.from_json_file('_demo_data/configs/rhvae_config.json') print(config) # ### Saving a configuration to a `.json` # Conversely, you can save a `dataclass` quite easily using the `save_json` method coming form `BaseModelConfig` # + from pyraug.models.base.base_config import BaseModelConfig my_model_config = BaseModelConfig(latent_dim=11) print(my_model_config) # - # Save the `.json` file ... my_model_config.save_json(dir_path='_demo_data/configs', filename='my_model_config') # ... and reload it BaseModelConfig.from_json_file('_demo_data/configs/my_model_config.json') # The same can be done with a `TrainingConfig` or `SamplerConfig` from pyraug.trainers.training_config import TrainingConfig my_training_config = TrainingConfig(max_epochs=10, learning_rate=0.1) print(my_training_config) my_training_config.save_json(dir_path='_demo_data/configs', filename='my_training_config') TrainingConfig.from_json_file('_demo_data/configs/my_training_config.json') from pyraug.models.base.base_config import BaseSamplerConfig my_sampler_config = BaseSamplerConfig(batch_size=10, samples_per_save=100) print(my_sampler_config) my_sampler_config.save_json(dir_path='_demo_data/configs', filename='my_sampler_config') BaseSamplerConfig.from_json_file('_demo_data/configs/my_sampler_config.json') # ## Setting up configs in `Pipelines` # # Let's consider the example of Tutorial 1 import torch import torchvision.datasets as datasets import matplotlib.pyplot as plt import numpy as np mnist_trainset = datasets.MNIST(root='../data', train=True, download=True, transform=None) n_samples = 200 dataset_to_augment = mnist_trainset.data[:n_samples] dataset_to_augment.shape # ### Amending the model parameters # # Conversely to tutorial 1, we here first instantiate a model we want to train to avoid using the default on. Ths `Model` instance will then be passed to the `TrainingPipeline` for training. # Let's set up a custom model config and build the model # + from pyraug.models.rhvae import RHVAEConfig model_config = RHVAEConfig( input_dim=28*28, # This is needed since we do not provide any encoder, decoder and metric architecture latent_dim=9, eps_lf=0.0001, temperature=0.9 ) # + from pyraug.models import RHVAE model = RHVAE( model_config=model_config ) model.latent_dim, model.eps_lf, model.temperature # - # ### Amending training parameters # # In the meantime we can also amend the training parameter through the `TrainingConfig` instance # + from pyraug.trainers.training_config import TrainingConfig training_config = TrainingConfig( output_dir='my_model_with_custom_parameters', no_cuda=False, learning_rate=1e-3, batch_size=200, train_early_stopping=100, steps_saving=None, max_epochs=5) training_config # - # Now we only have to pass the model and the training config to the TrainingPipeline to perform training ! # + from pyraug.pipelines import TrainingPipeline torch.manual_seed(8) pipeline = TrainingPipeline( data_loader=None, data_processor=None, model=model, optimizer=None, training_config=training_config) # - pipeline( train_data=dataset_to_augment, log_output_dir='output_logs' ) # Now, the model and training parameters are saved in `json` files in `my_model_with_custom_parameters/training_YYYY-MM-DD_hh-mm-ss/final_model` and we can reload any of them. last_training = sorted(os.listdir('my_model_with_custom_parameters'))[-1] # Let's get the saved `Trainingconfig` ... TrainingConfig.from_json_file(os.path.join('my_model_with_custom_parameters', last_training, 'final_model/training_config.json')) # ... and rebuild the model model_rec = RHVAE.load_from_folder(os.path.join('my_model_with_custom_parameters', last_training, 'final_model')) model_rec.latent_dim, model_rec.eps_lf, model_rec.temperature # ### Amending the Sampler parameters # # Of course, we can also amend the sampler parameters that is used within the `GenerationPipeline` as well. Again, simpy, build a `ModelSampler` instance and pass it to the `GenerationPipeline` # + from pyraug.models.rhvae import RHVAESamplerConfig sampler_config = RHVAESamplerConfig( output_dir='my_generated_data_with_custom_parameters', mcmc_steps_nbr=100, batch_size=100, n_lf=5, eps_lf=0.01 ) # - # Build the sampler # + from pyraug.models.rhvae.rhvae_sampler import RHVAESampler sampler = RHVAESampler(model=model_rec, sampler_config=sampler_config) # - # At initialization, the sampler creates the folder where the generated data should be saved in case it does not exist. # Now we only have to pass the model and the sampler to the GenerationPipeline to perform generation ! # + from pyraug.pipelines import GenerationPipeline generation_pipe = GenerationPipeline( model=model_rec, sampler=sampler ) # - generation_pipe(5) # Now, the sampler parameters are saved in a `json` file in `my_generated_data_with_custom_parameters/training_YYYY-MM-DD_hh-mm-ss/final_model` and we can reload any it to check everything is ok . last_generation = sorted(os.listdir('my_generated_data_with_custom_parameters'))[-1] RHVAESamplerConfig.from_json_file(os.path.join('my_generated_data_with_custom_parameters', last_generation, 'sampler_config.json' ))
examples/playing_with_configs.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 # --- # + from keras import applications from keras.preprocessing.image import ImageDataGenerator from keras import optimizers from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense import tensorflow as tf import cv2 import imgaug.augmenters as iaa # path to the model weights files. weights_path = '../vgg16_weights.h5' top_model_weights_path = 'weights/fc_model.h5' # dimensions of our images. img_width, img_height = 216, 384 temp_aug = iaa.ChangeColorTemperature((4000, 9000)) def augment_color_temperature(image): return temp_aug.augment_image(image.astype("uint8")) # - def to_grayscale_then_rgb(img): gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) gray_rgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) return gray_rgb # + datagen = tf.keras.preprocessing.image.ImageDataGenerator( #width_shift_range=0.2, #height_shift_range=0.2, #zoom_range=0.15, #shear_range=0.15, #rotation_range = 5, #brightness_range = (0.05, 0.2), validation_split=0.2, #horizontal_flip = True, preprocessing_function=augment_color_temperature, ) valgen = tf.keras.preprocessing.image.ImageDataGenerator( #width_shift_range=0.2, #height_shift_range=0.2, #zoom_range=0.15, #shear_range=0.15, #rotation_range = 40, #brightness_range = (0.05, 0.2), validation_split=0.2, #horizontal_flip = True, #preprocessing_function=to_grayscale_then_rgb, ) # - class_names = ['wada banderoli', 'wada nakretki', 'prawidlowa', 'brak nakretki'] # + my_seed = 11123 TRAIN_DIR = "../../dataset/butelka_wyciete_przez_niego" #train_generator = datagen.flow_from_directory('processed_dataset/nowy', batch_size=32, class_mode='categorical', seed = 123, subset='training', classes=class_names, shuffle=True) train_generator = datagen.flow_from_directory(TRAIN_DIR, (img_height, img_width), batch_size=32, class_mode='categorical', seed = my_seed, subset='training', classes=class_names, shuffle=True) val_generator = valgen.flow_from_directory(TRAIN_DIR, (img_height, img_width), batch_size=32, class_mode='categorical', seed = my_seed, subset='validation', classes=class_names, shuffle=True) # + from collections import Counter print("Training") print(train_generator.class_indices) print(Counter(train_generator.classes)) print("Validation") print(val_generator.class_indices) print(Counter(val_generator.classes)) num_classes = len(class_names) # + import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(10, 10)) for gen in range(3): x,y = train_generator.next() for i in range(3): ax = plt.subplot(3, 3, gen * 3 + i + 1) plt.imshow(x[i].astype("uint8")) plt.title(class_names[np.argmax(y[i])]) plt.axis("off") plt.show() # - model = applications.vgg16.VGG16(weights='imagenet', include_top=False) print('Model loaded.') # + from keras.layers import Input from keras.models import Model # build a classifier model to put on top of the convolutional model input_tensor = Input(shape=(img_height, img_width,3)) #input_tensor = Input(shape=(150,150,3)) base_model = applications.vgg16.VGG16(weights='imagenet',include_top= False,input_tensor=input_tensor) top_model = Sequential() top_model.add(Flatten(input_shape=base_model.output_shape[1:])) top_model.add(Dense(256, activation='relu')) top_model.add(Dropout(0.5)) top_model.add(Dense(num_classes, activation='softmax')) # note that it is necessary to start with a fully-trained # classifier, including the top classifier, # in order to successfully do fine-tuning #top_model.load_weights(top_model_weights_path) # add the model on top of the convolutional base model = Model(base_model.input, top_model(base_model.output)) # - base_model.input base_model.output # + new_model = Sequential() for l in base_model.layers: new_model.add(l) for l in top_model.layers: new_model.add(l) # CONCATENATE THE TWO MODELS print(new_model.summary()) # - len(base_model.layers) for layer in new_model.layers[:len(base_model.layers) - 1]: layer.trainable = False new_model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics =['accuracy']) # + epochs = 5 my_callbacks = [ #tf.keras.callbacks.ModelCheckpoint(filepath='vgg_nowy.{epoch:02d}-{val_loss:.2f}.h5'), ] history=new_model.fit(train_generator, epochs=epochs, callbacks=my_callbacks, validation_data=val_generator) # - model.save('zlozonadosprawkanakretkizaug12.h5') # list all data in history print(history.history.keys()) # summarize history for accuracy plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], 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', 'test'], loc='upper left') plt.show()
notebook/Klasyfikacja_nakretek/transfer_learning_wycietych.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 torch class Mysoftmax(torch.autograd.Function): @staticmethod def forward(ctx, input): result = input - input.max() result = result.exp() result = result/result.sum() ctx.save_for_backward(result) return result @staticmethod def backward(ctx, grad_output): # grad_outputใซใฏforwardใฎinputใซๅ…ฅใฃใฆใ„ใ‚‹ๅค‰ๆ•ฐใฎๅ€คใŒๅ…ฅใฃใฆใ„ใ‚‹ใ€‚ result, = ctx.saved_tensors J = torch.zeros(result.size()[-1], result.size()[-1]) print(result) for i in range(result.size()[-1]): for j in range(result.size()[-1]): if i==j: J[i][j] = result[0][i]*(1-result[0][i]) else: J[i][j] = -result[0][i]*result[0][j] grad_output = torch.mm(grad_output, J) return grad_output # ใ“ใฎailiasใ‚’ใ‚„ใ‚‰ใชใ„ใจtensorใŒๅ‡บๅŠ›ใซใชใ‚‰ใชใ„ softmax = Mysoftmax.apply # - a = torch.tensor([[1.0,2.0,3.0]], dtype=torch.float32, requires_grad=True) b = softmax(a) print(b) b.backward(a) print(a.grad) x = torch.tensor([1.0,2.0,3.0], dtype=torch.float32, requires_grad=True) y = x - x.max() y = y.exp() result = y/y.sum() result.backward(x) print(x.grad) import torch import torch.nn.functional as F c_a = torch.tensor([[1.0,2.0,3.0]], dtype=torch.float32, requires_grad=True) c = F.softmax(c_a) print(c) c.backward(c_a) print(c_a.grad) c_a = torch.tensor([[1.0,2.0,3.0]], dtype=torch.float32, requires_grad=True) c = F.softmax(c_a, dim = 0) print(c) c.backward(c_a) print(c_a.grad) c_a = torch.tensor([[1.0,2.0,3.0]], dtype=torch.float32, requires_grad=True) c = F.softmax(c_a, dim=1) print(c) c.backward(c_a) print(c_a.grad) c_a = torch.tensor([[1.0,2.0,3.0]], dtype=torch.float32, requires_grad=True) c = F.softmax(c_a, dim=1) print(c) c.backward(c_a) print(c_a.grad) # + import torch import torch.nn.functional as F # ใƒ†ใƒณใ‚ฝใƒซใ‚’ไฝœๆˆ # requires_grad=Falseใ ใจๅพฎๅˆ†ใฎๅฏพ่ฑกใซใชใ‚‰ใšๅ‹พ้…ใฏNoneใŒ่ฟ”ใ‚‹ x = torch.tensor([0.0, 1.0, 4.0], requires_grad=True) # ่จˆ็ฎ—ใ‚ฐใƒฉใƒ•ใ‚’ๆง‹็ฏ‰ # y = 2 * x + 3 y = F.relu(x) # ๅ‹พ้…ใ‚’่จˆ็ฎ— y.backward(x) # ๅ‹พ้…ใ‚’่กจ็คบ print(x.grad) # dy/dx = w = 2 # - print(x.grad) # pytorch tutorialใ‹ใ‚‰ # + import torch # x = torch.ones(2, 2, requires_grad=True) x = torch.tensor([[1,2],[3,4]], requires_grad=True, dtype=torch.float32) print(x) y = x + 2 print(y) z = y * y * 3 # ใ“ใ‚Œใฏใ‚ขใƒ€ใƒžใƒผใƒซ็ฉ(่ฆ็ด ็ฉ๏ผŒใ€€่กŒๅˆ—ใฎๆŽ›ใ‘็ฎ—ใงใฏใชใ„) out = z.mean() print(z, out) out.backward() print(x.grad) # - # softmaxใฎใƒคใ‚ณใƒ“ใ‚ขใƒณใฎ่จˆ็ฎ— # # ๅ˜็ด”ใชๅฎŸ่ฃ… # + a = torch.tensor([1.0,2.0,3.0], dtype=torch.float32) # J = [a[i]*(1-a[i]) if i==j else -a[i]*a[j] for i in range(len(a)) for j in range(len(a))] J = [a[i]*(1-a[i]) for i in range(len(a))] # - print(J) a = torch.tensor([1.0,2.0,3.0], dtype=torch.float32) J = [] for i in range(len(a)): tmp = [] for j in range(len(a)): if i==j: tmp.append(a[i]*(1-a[i])) else: tmp.append(-a[i]*a[j]) J.append([tmp]) J = torch.tensor(J) print(J) # + import torch x = torch.tensor([1,2,3], dtype=torch.float32, requires_grad=True) print(len(x)) # - a = torch.randn(4, 4) print(a) print(torch.sum(a, 1)) print(torch.sum(a, 0)) # + a = torch.tensor([1.0,2.0,3.0], dtype=torch.float32) print(a[0].item()) # + import torch class Mysoftmax(torch.autograd.Function): @staticmethod def forward(ctx, x): y = x - max(x) y = y.exp() result = y/y.sum() ctx.save_for_backward(x, result) return result @staticmethod def backward(ctx, grad_output): x, result = ctx.saved_tensors #print(result,x) #""" J = [] for i in range(len(result)): tmp = [] for j in range(len(result)): if i==j: tmp.append(result[i].item()*(1-result[i].item())) else: tmp.append(-result[i].item()*result[j].item()) #J.append(torch.tensor(tmp)) J.append(tmp) J = torch.tensor(J) #print("J\n",J) grad_input = torch.mv(J, x) return grad_input # - # # cosine similarity # my cosine # + import torch class Mycossim(torch.autograd.Function): @staticmethod def forward(ctx, input, key_vec): #k_1 = k.view(-1) #x = x.view(x.size()[1], x.size()[2]) #y = [torch.dot(x/x.norm(), k/k.norm()) for x in x] #y = torch.tensor(y) """ z = [] for i in x: z.append(torch.dot(i/ torch.norm(i, dim=-1), k / torch.norm(k))) """ print("input", input) print("key", key_vec) #mem_k = (mem*key_vec).sum() input_norm = input.norm() key_vec_norm = key_vec.norm() #result = mem_k/(max(mem_norm*key_vec_norm, 1e-8)) result = (input*key_vec).sum()/(torch.max(input_norm*key_vec_norm, 1e-8)) ctx.save_for_backward(input, key_vec, result) return result @staticmethod def backward(ctx, grad_output): mem, key_vec, result = ctx.saved_tensors print("grad_output", grad_output) """print(m) print(torch.norm(m, dim=-1)) print(m.norm()) print(torch.norm(m, dim=-1)**2) print(m.pow(2).sum()) """ #print(result*k/k.pow(2).sum()) eps = torch.tensor([[1e-8]]) m = mem k = key_vec m_norm = torch.norm(m) k_norm = torch.norm(k) m_grad = k/max(m_norm*k_norm, eps) - result*m/max(m_norm.pow(2), eps) k_grad = m/max(m_norm*k_norm, eps) - result*k/max(k_norm.pow(2), eps) print(m_grad) print(k_grad) #m_norm = torch.abs(m) #k_norm = torch.abs(k) #m_grad = k/torch.sum(m_norm*k_norm) - result*m/torch.sum(m_norm.pow(2)) #k_grad = m/torch.sum(m_norm*k_norm) - result*k/torch.sum(k_norm.pow(2)) m_grad = m_grad*m k_grad = k_grad*k return m_grad, k_grad # + a = torch.tensor([[1.0, 2.0, 3.0]], requires_grad=True) b = torch.tensor([[-1.0,-2.0,-3.0]], requires_grad=True) #b = torch.tensor([[-3.0,-6.0,-2.0]], dtype=torch.float32, requires_grad=True) print("\nMy cosine") # ใ“ใฎailiasใ‚’ใ‚„ใ‚‰ใชใ„ใจtensorใŒๅ‡บๅŠ›ใซใชใ‚‰ใชใ„ cosine_similarity = Mycossim.apply c = cosine_similarity(a,b) print(c) c.backward(a) print("a grad:", a.grad) print("b grad:", b.grad) # ------------------ f_c = F.cosine_similarity(a,b, dim=-1) print(f_c) # aใซใคใ„ใฆ f_c.backward(a) print("a grad:", a.grad) print("b grad:", b.grad) # + import torch import torch.nn.functional as F a = torch.tensor([1.0,2.0,3.0], requires_grad=True) b = torch.tensor([-1.0,-2.0,-3.0], requires_grad=True) f_c = F.cosine_similarity(a,b, dim=-1) print(f_c) # aใซใคใ„ใฆ f_c.backward(b) print("a grad:", a.grad) print("b grad:", b.grad) # ---------- # ใ“ใฎailiasใ‚’ใ‚„ใ‚‰ใชใ„ใจtensorใŒๅ‡บๅŠ›ใซใชใ‚‰ใชใ„ cosine_similarity = Mycossim.apply c = cosine_similarity(a,b) print(c) c.backward(b) print("a grad:", a.grad) print("b grad:", b.grad) # - print(a*b) print(torch.dot(a, b)) print(a/b) print(torch.div(a, b)) # + import torch import torch.nn.functional as F m = torch.tensor([1.0,2.0,3.0], dtype=torch.float32, requires_grad=True) k = torch.tensor([1.0,2.0,3.0], dtype=torch.float32, requires_grad=True) m_k = torch.sum(m*k) m_norm = torch.norm(m) k_norm = torch.norm(k) result = m_k/(max(m_norm*k_norm, 1e-8)) result.backward(result) print("m.grad", m.grad) print("k.grad", k.grad) print("m_norm.grad", m_norm.grad) print("k_norm.grad", k_norm.grad) print("result", result.grad) m = torch.tensor([1.0,2.0,3.0], dtype=torch.float32, requires_grad=True) k = torch.tensor([1.0,2.0,3.0], dtype=torch.float32, requires_grad=True) c = F.cosine_similarity(m,k, dim=-1) c.backward(c) print("m_grad", m.grad) print("k_grad", k.grad) print(c.grad) # - m = torch.tensor([[[1.0,2.0,3.0],[4.0,5.0,6.0]]], dtype=torch.float32, requires_grad=True) torch.max(m) # + m = torch.tensor([[[1.0,2.0,3.0],[4.0,5.0,6.0]]], dtype=torch.float32, requires_grad=True) k = torch.tensor([1.0,2.0,3.0], requires_grad=True) eps = torch.tensor([[1e-8]]) print(m*k) print((m*k).sum(dim=-1)) print(m.norm(dim=-1)) print(k.norm(dim=-1)) print((m*k).sum(dim=-1)/torch.max(m.norm(dim=-1)*k.norm(dim=-1), eps)) print(F.cosine_similarity(m, k, dim=-1)) # - print(result)
.ipynb_checkpoints/test_myfunc-checkpoint.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:icesat2-hackweek] * # language: python # name: conda-env-icesat2-hackweek-py # --- # ## Accessing ICESat-2 Data # ### Data Query and Download Example Notebook # This notebook illustrates the use of icepyx for ICESat-2 data access and download from the NASA NSIDC DAAC (NASA National Snow and Ice Data Center Distributed Active Archive Center). # # #### Credits # * notebook by: <NAME> and <NAME> # # ### Import packages, including icepyx from icepyx import is2class as ipd import os import shutil # !pwd # ### Create an ICESat-2 data object with the desired search parameters # # There are three required inputs: # - `short_name` = the dataset of interest, known as its "short name". # See https://nsidc.org/data/icesat-2/data-sets for a list of the available datasets. # - `spatial extent` = a bounding box to search within. Given in decimal degrees for the lower left longitude, lower left latitude, upper right longitude, and upper right latitude. Future development will enable alternative spatial extent inputs, such as a poloygon. # - `date_range` = the date range for which you would like to search for results. Must be formatted as a set of 'YYYY-MM-DD' strings. short_name = 'ATL06' spatial_extent = [-64, 66, -55, 72] date_range = ['2019-02-22','2019-02-28'] # + region_a = ipd.Icesat2Data(short_name, spatial_extent, date_range) print(region_a.dataset) print(region_a.dates) print(region_a.start_time) print(region_a.end_time) print(region_a.dataset_version) print(region_a.spatial_extent) # - # There are also several optional inputs to allow the user finer control over their search. # - `start_time` = start time to search for data on the start date. If no input is given, this defaults to 00:00:00. # - `end_time` = end time for the end date of the temporal search parameter. If no input is given, this defaults to 23:59:59. Times must be input as 'HH:mm:ss' strings. # - `version` = What version of the dataset to use, input as a numerical string. If no input is given, this value defaults to the most recent version of the dataset specified in `short_name`. # + region_a = ipd.Icesat2Data(short_name, spatial_extent, date_range, \ start_time='03:30:00', end_time='21:30:00', version='001') print(region_a.dataset) print(region_a.dates) print(region_a.start_time) print(region_a.end_time) print(region_a.version) print(region_a.spatial_extent) # - # Alternatively, you can also just create the data object without creating named variables. region_a = ipd.Icesat2Data('ATL06',[-64, 66, -55, 72],['2019-02-22','2019-02-28'], \ start_time='00:00:00', end_time='23:59:59', version='002') # ### Built in methods allow us to get more information about our dataset # In addition to viewing the stored object information shown above (e.g. dataset, start and end date and time, version, etc.), we can also request summary information about the dataset itself or confirm that we have manually specified the latest version. print(region_a.about_dataset()) print(region_a.latest_version()) # ### Querying a dataset # In order to search the dataset collection for available data granules, we need to build our search parameters. These are formatted as a dictionary of key:value pairs according to the CMR documentation. region_a.build_CMR_params() #view the parameters that will be submitted in our query region_a.CMRparams # Now that our parameter dictionary is constructed, we can search the CMR database for the available granules. Granules returned by the search are automatically stored within the data object. #search for available granules region_a.avail_granules() #print the information about the returned search results region_a.granules # ### Downloading the found granules # In order to download any data from NSIDC, we must first authenticate ourselves using a valid Earthdata login. This will create a valid token to interface with the DAAC as well as start an active logged-in session to enable data download. The token is attached to the data object and stored, but the session must be passed to the download function. Passwords are entered but not shown or stored in plain text by the system (I think?) earthdata_uid = '' email = '' session=region_a.earthdata_login(earthdata_uid, email) # Once we have generated our session, we must build the required configuration parameters needed to actually download data. These will tell the system how we want to download the data. # - `page_size` = 10. This is the number of granules we will request per order. # - `page_num` = 1. Determine the number of pages based on page size and the number of granules available. If no page_num is specified, this calculation is done automatically to set page_num, which then provides the number of individual orders we will request given the number of granules. # - `request_mode` = 'async' # - `agent` = 'NO' # - `include_meta` = 'Y' # # #### More details about the configuration parameters # `request_mode` is "synchronous" by default, meaning that the request relies on a direct, continous connection between you and the API endpoint. Outputs are directly downloaded, or "streamed" to your working directory. For this tutorial, we will set the request mode to asynchronous, which will allow concurrent requests to be queued and processed without the need for a continuous connection. # # ** Use the streaming `request_mode` with caution: While it can be beneficial to stream outputs directly to your local directory, note that timeout errors can result depending on the size of the request, and your request will not be queued in the system if NSIDC is experiencing high request volume. For best performance, I recommend setting `page_size=1` to download individual outputs, which will eliminate extra time needed to zip outputs and will ensure faster processing times per request. An example streaming request loop is available at the bottom of the tutorial below. ** # # Recall that we queried the total number and volume of granules prior to applying customization services. `page_size` and `page_num` can be used to adjust the number of granules per request up to a limit of 2000 granules for asynchronous, and 100 granules for synchronous (streaming). For now, let's select 10 granules to be processed in each zipped request. For ATL06, the granule size can exceed 100 MB so we want to choose a granule count that provides us with a reasonable zipped download size. # # If no keyword inputs are entered into the build function for these parameters, default values will be used. We must also specify that we would like to build the required configuration parameters for downloading (versus those needed for a 'search'). region_a.build_reqconfig_params('download', page_size=9) region_a.reqparams # #### Place the order # Then, we can send the order to NSIDC by providing our active session to the order_granules function. Information about the granules ordered and their status will be printed automatically as well as emailed to the address provided. Additional information on the order, including request URLs, can be viewed by setting the optional keyword input 'verbose' to True. region_a.order_granules(session) #region_a.order_granules(session, verbose=True) #view a short list of order IDs region_a.orderIDs # #### Download the order # Finally, we can download our order to a specified directory (which needs to have a full path but doesn't have to point to an existing directory) and the download status will be printed as the program runs. Additional information is again available by using the optional boolean keyword 'verbose'. path = './downloads' region_a.download_granules(session, path) # #### Clean up the download folder by removing individual order folders: # + #Clean up Outputs folder by removing individual granule folders for root, dirs, files in os.walk(path, topdown=False): for file in files: try: shutil.move(os.path.join(root, file), path) except OSError: pass for root, dirs, files in os.walk(path): for name in dirs: os.rmdir(os.path.join(root, name)) # - # ## Elements to develop further/implement (and then include in the example, as in Amy's tutorial) # - customization: subsetting and reformatting (check for options and include with order) # - polygon visualization # - input of polygon (including simplification steps) instead of bounding box # - more information/details on the above steps for a novice user
doc/examples/ICESat-2_DAAC_DataAccess_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 # --- # # APPM 4650 Homework 0: plotting practice # This homework is not quired and is not graded # # Assignment: Plot these functions on the same graph and make them look nice: # $$ # f(x)= \cos(e^{-x} + x \cos (x)), \ \ \ \ g(x) = \arctan \left( \frac{x^2}{ \log (1+ |1+x^7|)} \right), # $$ # + import math import numpy as np import matplotlib.pyplot as plt # #%matplotlib notebook # interactive # %matplotlib inline # You can do math.cos or np.cos # The advantage of np.cos is that it is "vectorized" and can operate on a numpy array # If you do math.cos, then you need to use np.vectorize, but this is not efficient f = lambda x : np.cos( np.exp(-x) + x*np.cos(x) ) g = lambda x : np.arctan( x**2/np.log(1+abs(1+x**7)) ) # - # ## Basic plot x = np.arange(-2.0, 5.0, 0.05) # or np.linspace plt.figure() plt.plot(x, f(x), x, g(x) ); # ## Fancier plot # + import matplotlib as mpl mpl.rcParams['mathtext.fontset'] = 'cm' plt.style.use('seaborn-ticks') # default, seaborn, etc. are common # For very fancy tweaking, see # https://seaborn.pydata.org/tutorial/aesthetics.html plt.figure() #plt.set_cmap('Set1') fig, ax = plt.subplots() ax.plot(x, f(x),label=r'$\cos(e^{-x}+x\cos(x))$', linewidth=2.0) ax.plot(x, g(x),'--',label=r'$\arctan(x^2/\log(1+|1+x^7|))$',linewidth=2.0) plt.xlabel(r'$x$', fontsize=22) plt.ylabel(r'$y$', fontsize=22) plt.xticks(fontsize=18) plt.yticks(fontsize=18) ax.legend(fontsize=14,frameon=True,loc=9) # The bbox_inches fixes some cropping issues that chopped of the labels plt.savefig('WarmupPlot_python.pdf',bbox_inches='tight') # -
Homework/APPM4650_Fall20_Homework00_soln.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="S2dPTjE1EOcR" colab_type="code" outputId="5f599953-ec11-4432-8799-ebbb6e27df48" executionInfo={"status": "ok", "timestamp": 1549673780650, "user_tz": 480, "elapsed": 9360, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07278259258766517376"}} colab={"base_uri": "https://localhost:8080/", "height": 82} # http://pytorch.org/ from os.path import exists from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) # cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\.\([0-9]*\)\.\([0-9]*\)$/cu\1\2/' accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu' # #!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvision # !pip install torch # !pip install tqdm import torch # + [markdown] id="fjVU5rmg7Phz" colab_type="text" # # VAE kernels # Can we use VAE as a kernel for convolutional layer? The idea is that for each receptive field, VAE would find multinomial gaussian distribution shared across all instances of the receptive field. The resulting system would have features, feature value ranges and distributions at each receptive field, similar to neurons with various feature value preferences for each receptive field in the cortex. For example, a neuron may have a preference for horizontal lines, upward movement, slow speed movement. That would be equivalent to VAE finding 3 features with specific values for a given receptive field. A neuron can have preference for only one (or few) values of a given feature so a lot of neurons are needed to represent the domain of each feature with sufficient statistical redundency. But a VAE's output for a given receptive field, e.g. 0.3 for feature 1, 0.9 for feature 2 and 0.5 for feature 3 with low, high and medium variance, respectively, can represent 1000s of feature-value preferences and 100s of neurons (because a neuron can be selective to a different value for each feature). The similifying factor here is Laplace assumption. Maybe using an order of magnitude more # of features would result at least in mixture of gaussians because a feature would get duplicated and learn different modes of the distribution. # + [markdown] id="aU-YTik28sU6" colab_type="text" # ## Basics # + id="F_z2dpGjETHC" colab_type="code" colab={} import logging import numpy as np import os import random import torch import torch.utils.data import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from tqdm import tqdm, tqdm_notebook device = "cuda" if torch.cuda.is_available() else "cpu" # device = "cpu" logging.basicConfig( level=logging.ERROR, format='%(asctime)s.%(msecs)03d %(name)s:%(funcName)s %(levelname)s:%(message)s', datefmt="%M:%S") import matplotlib.pyplot as plt import matplotlib.ticker as ticker from skimage.draw import line_aa # %matplotlib inline plt.style.use('classic') def show_image(image, vmin=None, vmax=None, title=None, print_values=False, figsize=(4, 4)): #print("image ", image.shape) image = image.cpu().numpy() fig, ax1 = plt.subplots(figsize=figsize) if title: plt.title(title) #i = image.reshape((height, width)) #print("i ", i.shape) ax1.imshow(image, vmin=vmin, vmax=vmax, interpolation='none', cmap=plt.cm.plasma) plt.show() if print_values: print(image) def generate_bouncing_pixel(width, height, count=100): ball_width = 2 x = 3 #random.randint(0, width) y = 2 #random.randint(0, height) dx = -1 #random.randint(0, 2) - 1 dy = 1 #random.randint(0, 2) - 1 images = [] for _ in range(count): image = np.zeros((width, height)) image[x, y] = 1.0 image[x+1, y] = 1.0 image[x, y+1] = 1.0 image[x+1, y+1] = 1.0 #image=gaussian_filter(image, 0.5) images.append(image) x += dx y += dy if (x < 0 or x > width - 1 - (ball_width - 1)): dx *= -1 x += dx if (y < 0 or y > height - 1 - (ball_width - 1)): dy *= -1 y += dy return torch.as_tensor(images) def load_mnist(train=True, batch_size=64): kwargs = {'num_workers': 1, 'pin_memory': True} if device=="cuda" else {} loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=train, download=True, transform=transforms.Compose([ transforms.ToTensor(), ])), batch_size=batch_size, shuffle=True, **kwargs) return loader def convolve(image_width, image_height, kernel_width, kernel_height, stride): convolutions = [] for x in range(0, image_width - kernel_width + 1, stride): for y in range(0, image_height - kernel_height + 1, stride): convolutions.append([y, x, y + kernel_height, x + kernel_width]) return convolutions def conv_slice(images, image_width, image_height, kernel_width, kernel_height, stride): convolutions = convolve(image_width, image_height, kernel_width, kernel_height, stride) slices = [images[i, c[0]:c[2], c[1]:c[3]] for i in range(image_count) for c in convolutions] slices = torch.stack(slices).float() slices = slices.view(slices.shape[0], -1).to(device) return slices def conv_join(slices, image_count, image_width, image_height, kernel_width, kernel_height, stride): print("slices.shape", slices.shape) if len(slices.shape) == 2: slices = slices.view(image_count, int(slices.shape[0] / image_count), kernel_width, kernel_height) # slices is now (image count, convolutions, kernel size, kernel size) #print("slices.shape", slices.shape) convolutions = convolve(image_width, image_height, kernel_width, kernel_height, stride) assert len(convolutions) == slices.shape[1] buffer = torch.zeros((image_count, image_width, image_height)).to(device) #print("buffer", buffer.shape) for i in range(image_count): #if i == 0: # print("slices[i]", slices[i]) for x in range(image_width): for y in range(image_height): values = [] for c in range(len(convolutions)): convolution = convolutions[c] if x >= convolution[0] and x < convolution[2] and y >= convolution[1] and y < convolution[3]: value = slices[i, c, x - convolution[0], y - convolution[1]] values.append(value.item()) #if i == 0 and x == 3 and y == 3: # print(f"x {x}, y {y}, convolution {convolution}") # print(f"[{x - convolution[0]}, {y - convolution[1]}]", value) #if i == 0 and x == 3 and y == 3: # print(f"i {i}, x {x}, y {y}") # print("values", values) if len(values) > 0: value = np.average(values) #print("value", value) buffer[i, x, y] = value return buffer # + [markdown] id="QSSDHTtfG3tU" colab_type="text" # ## Network # # + id="efSLelurHIIY" colab_type="code" colab={} class VAE(nn.Module): def __init__(self, input_width, input_height, feature_count): super(VAE, self).__init__() self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.WARN) self.feature_count = feature_count self.encoder = nn.Sequential( nn.Linear(input_width * input_height , input_width * input_height * 2), #nn.BatchNorm1d(1), nn.LeakyReLU(0.2, inplace=True), nn.Linear(input_width * input_height * 2, input_width * input_height * 4), #nn.BatchNorm1d(1), nn.LeakyReLU(0.2, inplace=True), ) # self.e_l1 = nn.Linear(input_width * input_height , input_width * input_height * 2) # self.e_b1 = nn.BatchNorm1d(1) # self.e_r1 = nn.LeakyReLU(0.2, inplace=True) # self.e_l2 = nn.Linear(input_width * input_height * 2, input_width * input_height * 4) # self.e_b2 = nn.BatchNorm1d(1) # self.e_r2 = nn.LeakyReLU(0.2, inplace=True) self.decoder = nn.Sequential( nn.Linear(feature_count , input_width * input_height * 2), #nn.BatchNorm1d(1), nn.LeakyReLU(0.2, inplace=True), nn.Linear(input_width * input_height * 2, input_width * input_height), #nn.BatchNorm2d(1), nn.Sigmoid(), ) self.linear_mu = nn.Linear(input_width * input_height * 4, feature_count) self.linear_sigma = nn.Linear(input_width * input_height * 4, feature_count) self.lrelu = nn.LeakyReLU() self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() self.tanh = nn.Tanh() def encode(self, x): self.logger.debug(f"x {x.shape}") x = self.encoder(x) # x = self.e_l1(x) # #x = self.e_b1(x) # x = self.e_r1(x) # x = self.e_l2(x) # #x = self.e_b2(x) # x = self.e_r2(x) #return self.tanh(self.linear_mu(x)), self.tanh(self.linear_sigma(x)) return self.sigmoid(self.linear_mu(x)), self.linear_sigma(x) def decode(self, z): #z = z.view(-1, 1, 1, self.feature_count) self.logger.debug(f"z {z.shape}") return self.decoder(z) def reparametrize(self, mu, logvar): std = logvar.mul(0.5).exp_() eps = torch.FloatTensor(std.size()).normal_().to(device) eps = eps.mul(std).add_(mu) eps = torch.sigmoid(eps) self.logger.debug(f"eps {eps.shape}") return eps def decode_features(self, mu, logvar): z = self.reparametrize(mu, logvar) self.logger.debug(f"z {z.shape}") decoded = self.decode(z) self.logger.debug(f"decoded {decoded.shape}") return decoded, z def forward(self, x): self.logger.debug(f"x {x.shape}") mu, logvar = self.encode(x) self.logger.debug(f"mu {mu.shape}") self.logger.debug(f"logvar {logvar.shape}") decoded, z = self.decode_features(mu, logvar) return decoded, mu, logvar, z class Network(nn.Module): def __init__(self, image_width, image_height, kernel_width, kernel_height, stride, feature_count): super(Network, self).__init__() self.image_width = image_width self.image_height = image_height self.kernel_width = kernel_width self.kernel_height = kernel_height self.feature_count = feature_count self.stride = stride self.vae = VAE(kernel_width, kernel_height, feature_count) self.trained = False if os.path.exists(self.save_path()): self.load_state_dict(torch.load(self.save_path())) self.eval() self.trained = True def forward(self, x): return self.vae(x) def loss_function(self, recon_x, x, mu, logvar): # print(recon_x.size(), x.size()) BCE = F.binary_cross_entropy(recon_x.view(-1, self.kernel_width * self.kernel_height), x.view(-1, self.kernel_width * self.kernel_height), size_average=True) # see Appendix B from VAE paper: # <NAME>. Auto-Encoding Variational Bayes. ICLR, 2014 # https://arxiv.org/abs/1312.6114 # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) # return BCE + KLD BCE /= 0.00001 #print(BCE, KLD) return BCE + KLD def train(self, images, num_epochs=3000): if self.trained: return if isinstance(images, bool): return print("images", images.shape) input = conv_slice(images, self.image_width, self.image_height, self.kernel_width, self.kernel_height, self.stride) learning_rate = 1e-3 optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate, weight_decay=1e-5) done = False dataset = torch.utils.data.TensorDataset(input) data_loader = torch.utils.data.DataLoader(dataset, batch_size=128, shuffle=True) epoch = 0 with tqdm(total=num_epochs) as tqdm_epochs: for epoch in range(num_epochs): for i, batch in enumerate(data_loader): batch = batch[0].to(device) output, mu, logvar, z = self(batch) loss = self.loss_function(output, batch, mu, logvar) # ===================backward==================== optimizer.zero_grad() loss.backward() optimizer.step() if epoch % int(num_epochs / 10) == 0: output, mu, logvar, z = self(input[0].unsqueeze(dim=0)) tqdm_epochs.write('epoch [{}/{}], loss:{:.4f}' .format(epoch+1, num_epochs, loss.item())) show_image(output[0].view(self.kernel_height, self.kernel_width).detach(), title=f"output {0}", vmin=0, vmax=1) if (loss.item() < 0.001 and epoch > 1500) or epoch > num_epochs: break tqdm_epochs.update(1) torch.save(self.state_dict(), self.save_path()) def eval_data(self, images): input = conv_slice(images, self.image_width, self.image_height, self.kernel_width, self.kernel_height, self.stride) reconstructed_slices, mu, logvar, z = self(input) #reconstructed_slices = output[0] reconstructed_images = conv_join(reconstructed_slices, images.shape[0], self.image_width, self.image_height, self.kernel_width, self.kernel_height, self.stride) return reconstructed_images, reconstructed_slices, mu, logvar, z def save_path(self): return f"network.pt" # + [markdown] id="7S9Yqr8wbruT" colab_type="text" # ## Example # + id="XaYE0tslbzMQ" colab_type="code" outputId="637be429-d59e-4d05-fcfd-aa4397061272" executionInfo={"status": "error", "timestamp": 1549673795592, "user_tz": 480, "elapsed": 18117, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07278259258766517376"}} colab={"base_uri": "https://localhost:8080/", "height": 9406} if False: import os import glob files = glob.glob('./*.pt') for f in files: os.remove(f) image_height = image_width = 16 image_count = 20 kernel_size = 5 stride = 1 feature_count = 4 random.seed(0) np.random.seed(0) torch.manual_seed(0) # images = generate_bouncing_pixel(image_height, image_width, count=image_count) images = next(iter(load_mnist(batch_size=10)))[0].squeeze(dim=1) image_count, image_height, image_width = images.shape network = Network(image_width=image_width, image_height=image_height, kernel_width=kernel_size, kernel_height=kernel_size, stride=stride, feature_count=feature_count).to(device) # # %prun network.train(images, num_epochs=4000) reconstructed_images, reconstructed_slices, mu, logvar, z = network.eval_data(images) for i in range(20): print(f"------------------------- IMAGE {i} --------------------------") show_image(images[i].detach(), vmin=0, vmax=1, title=f"images image {i}") show_image(reconstructed_images[i].detach(), vmin=0, vmax=1, title=f"reconstructed_images {i}") show_image(images[i].float()-reconstructed_images[i].detach().cpu(), title=f"diff {i}") # + [markdown] id="XzbZHtcE8x3D" colab_type="text" # ## Explore latent space # + id="JnsfbBSPPZhH" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 2441} outputId="e62d3650-1c4a-4457-c8e3-ac0da4debbd9" executionInfo={"status": "ok", "timestamp": 1549674142143, "user_tz": 480, "elapsed": 52905, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07278259258766517376"}} image_grid_size = 6 ls = torch.linspace(0, 1, image_grid_size) test_mu = torch.stack([torch.tensor([ls[i1], ls[i2], ls[i3], ls[i4]]) for i1 in np.arange(image_grid_size) for i2 in np.arange(image_grid_size) for i3 in np.arange(image_grid_size) for i4 in np.arange(image_grid_size)]).to(device) test_logvar = torch.ones(test_mu.size()).mul(-10).to(device) output, _ = network.vae.decode_features(test_mu, test_logvar) output = output.view(-1, kernel_size, kernel_size) print(output.shape) def show_image_grid(images, vmin=0, vmax=1): s = images.shape assert len(s) == 3 image_grid_size = int(s[0] ** 0.5) fig, axs = plt.subplots(nrows=image_grid_size, ncols=image_grid_size, figsize=(30, 30), subplot_kw={'xticks': [], 'yticks': []}) fig.subplots_adjust(left=0.03, right=0.97, hspace=0, wspace=0) axs = axs.flat for i in np.arange(s[0]): axs[i].axis("off") axs[i].imshow(images[i].detach().cpu().numpy(), vmin=vmin, vmax=vmax, interpolation='none', cmap=plt.cm.plasma, aspect='auto') plt.tight_layout() plt.show() show_image_grid(output) # + [markdown] id="qYjvb7Yj84X9" colab_type="text" # ## Test images autoencoding # # + id="LjGjZ-3nPayf" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 9174} outputId="7bcd6cc7-0d79-4b07-f406-13342ddb6c70" executionInfo={"status": "ok", "timestamp": 1549677216922, "user_tz": 480, "elapsed": 13955, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "07278259258766517376"}} test_images = next(iter(load_mnist(batch_size=10)))[0].squeeze(dim=1) reconstructed_test_images, _, _, _, _ = network.eval_data(test_images) for i in range(10): print(f"------------------------- IMAGE {i} --------------------------") show_image(test_images[i].detach(), vmin=0, vmax=1, title=f"test_images {i}") show_image(reconstructed_test_images[i].detach(), vmin=0, vmax=1, title=f"reconstructed_test_images {i}") show_image(test_images[i].float()-reconstructed_test_images[i].detach().cpu(), title=f"diff {i}") # + id="QybNtPYZPf-A" colab_type="code" colab={}
Autoencoding kernel convolution/09 Autoencoding kernel convolution + mnist.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [tensor] # language: python # name: Python [tensor] # --- # + import pandas as pd import numpy as np import tensorflow as tf from sklearn.preprocessing import LabelEncoder from sklearn.cross_validation import StratifiedShuffleSplit train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') # + # Swiss army knife function to organize the data def encode(train, test): le = LabelEncoder().fit(train.species) labels = le.transform(train.species) # encode species strings classes = list(le.classes_) # save column names for submission test_ids = test.id # save test ids for submission train["label"] = labels train = train.drop(['species', 'id'], axis=1) test = test.drop(['id'], axis=1) return train, labels, test, test_ids, classes train, labels, test, test_ids, classes = encode(train, test) train.head() # + sss = StratifiedShuffleSplit(labels, 10, test_size=0.2, random_state=23) for train_index, test_index in sss: X_train, X_test = train.loc[train_index], train.loc[test_index] # - X_train.head() FEATURES = test.columns FEATURES feature_cols = [tf.contrib.layers.real_valued_column(k) for k in FEATURES] # + # #?tf.contrib.learn.DNNClassifier() # + dnn_classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_cols, hidden_units=[512, 256],n_classes=99) linear_classifier = tf.contrib.learn.LinearClassifier(feature_columns=feature_cols,n_classes=99) # - def input_fn(df): feature_cols = {k: tf.constant(df[k].values) for k in FEATURES} label = tf.constant(df["label"].values) return feature_cols, label dnn_classifier.fit(input_fn=lambda: input_fn(X_train), steps=2000) dnn_results = dnn_classifier.evaluate(input_fn=lambda: input_fn(X_test), steps=1) for key in sorted(dnn_results): print "%s: %s" %(key, dnn_results[key]) linear_classifier.fit(input_fn=lambda: input_fn(X_train), steps=10000) lin_results = linear_classifier.evaluate(input_fn=lambda:input_fn(X_test),steps=1) for key in sorted(lin_results): print "%s: %s" %(key, lin_results[key])
doc/tensorflow_kaggle_dcyang/kaggle_leaf/tf_kaggle_leaf_classification.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 # --- # + id="3fe94688" # %matplotlib inline from numpy import * from matplotlib.pyplot import * # + id="2yUETvkozE7b" # + [markdown] id="8184faab" # Consider the following one-dimensional PDE: # $$ # -u_{xx}(x) = f(x)\quad\mathrm{ in }\ \Omega = (0, \pi) # $$ # $$ # u(x) = 0, \quad\mathrm{ on }\ \partial\Omega = \{0, \pi\} # $$ # # Given the following $4^{th}$ order finite difference approximation of the second order derivative: # # $$u_{xx}(x_i) = \frac{-u_{i-2}+16u_{i-1}-30u_i+16u_{i+1}-u_{i+2}}{12h^2}$$ # # Implement a function that given the domain interval, the forcing function, the number of discretization points, the boundary conditions, returns the matrix $A$ and the the right hand side $b$. # + id="1c562f13" def finDif(omega,f,n,bc): h=(omega[1]-omega[0])/(n-1) coord=linspace(omega[0],omega[1],n) A=zeros((n,n),dtype=double);b=zeros(n,dtype=double) tmp=array([1,-16,30,-16,1]) A[1,:4]=array([-16,30,-16,1]) b[1]=f(coord[1]) for i in range(2,n-2): A[i,i-2:i+3]=tmp b[i]=f(coord[i]) A[-2,-4:]=array([1,-16,30,-16]) b[-2]=f(coord[-2]) #apply boundary condition A[0,:]=A[:,0]=A[-1,:]=A[:,-1]=0 A[0,0]=A[-1,-1]=1 b[0]=bc[0];b[-1]=bc[1] A=A/(12*(h**2)) # A=A*n**2/12 return A, b # + [markdown] id="c21bb21e" # Call the function using: # + id="23af8831" omega = [0,pi] f = lambda x : sin(x) n=8 bc = [0,0] A, b = finDif(omega, f, n, bc) # print(A) # + [markdown] id="4f8a7c6f" # Implement two functions that compute the LU and the Cholesky factorization of the system matrix $A$ # + id="47468a37" def LU(A): B=A.copy() n = B.shape[0] for i in range(n): factor = B[i+1:, i] / B[i, i] B[i+1:,i] = factor B[i+1:,i+1:] -= factor[:,newaxis]*B[i,i+1:] return tril(B,-1)+eye(n,dtype=double),triu(B) L, U = LU(A) # + id="193ebfed" def cholesky(A): n=A.shape[0] L=zeros((n,n)) for j in range(n): tmp_sum=sum(L[j,:j]*L[j,:j]) L[j,j]=sqrt(A[j,j]-tmp_sum) for i in range(j+1,n): tmp_sum=sum(L[i,:j]*L[j,:j]) L[i,j]=(1/L[j,j])*(A[i,j]-tmp_sum) return L,L.transpose() HT, H = cholesky(A) # + [markdown] id="41eb8436" # Implement forward and backward substitution functions to exploit the developed factorization methods to solve the derived linear system of equations. # + id="019cf0df" def L_solve(L,rhs): n=A.shape[0] sol=zeros(n) sol[0]=b[0]/L[0,0] for i in range(1,n): sol[i]=(1/L[i,i])*(rhs[i]-dot(L[i,:i],sol[:i])) return sol # + id="26ce17c4" def U_solve(U,rhs): n=A.shape[0] sol=zeros(n) sol[-1]=b[-1]/U[-1,-1] for i in range(n-2,-1,-1): sol[i]=(1/U[i,i])*(rhs[i]-dot(U[i,i:],sol[i:])) return sol # + [markdown] id="08ac9ba1" # Solve the derived linear system using the implemented functions and plot the computed solution: # + id="7c1de4f3" tmp=L_solve(L,b) sol_LU=U_solve(U,tmp) coords=linspace(omega[0],omega[1],n) tmp=L_solve(HT,b) sol_CH=U_solve(H,tmp) coords=linspace(omega[0],omega[1],n) title='Comparison LU and Cholesky solution' xlabel='x' ylabel='u(x)' plot(coords,sol_LU,'o-b',label='LU') plot(coords,sol_CH,'x-r',label='CH') legend(loc='best') # + [markdown] id="62cdfe65" # Considering the new domain $\Omega = (0,1)$ and the forcing term $f(x) = x(1-x)$ with B.C. $u(x) = 0$, on $\partial \Omega = {0,1}$ produce a plot and a table where you show the decay of the error w.r.t. the number of grid points. # (The analytical solution for the above problems is $u_{an} = \frac{x^4}{12} - \frac{x^3}{6} + \frac{x}{12}$) # + id="91212afb" #TODO omega = [0,1] ff = lambda x : x*(1-x) bc = [0,0] N=9 npoints=[100,200,300,400,500,600,800,900,1000] error=zeros((N,3)) u = lambda x : (x**4/12)-(x**3)/6+(x/12) for idx,i in enumerate(npoints): coords=linspace(omega[0],omega[1],i) A, b = finDif(omega, ff, i, bc) #solve with LU L, U = LU(A) tmp=L_solve(L,b) sol_LU=U_solve(U,tmp) #solved with CH HT, H = cholesky(A) tmp=L_solve(HT,b) sol_CH=U_solve(H,tmp) #linalg sol_alg=linalg.solve(A,b) #analitical solution true_sol=u(coords) #LU-CH-error error[idx,0]=linalg.norm(true_sol-sol_LU) error[idx,1]=linalg.norm(true_sol-sol_CH) error[idx,2]=linalg.norm(true_sol-sol_alg) print(error) title='Error' xlabel='# points' ylabel='error' plot(npoints,error[:,0],'o-b') plot(npoints,error[:,1],'x-r') plot(npoints,error[:,2],'x-r') # + [markdown] id="c8d5002f" # Exploit the derived LU factorizations to compute the condition number of the system's matrix $A$ using the original problem formulation. # + id="c25fc1fe" #Power Method def PM(A,z,tol=1e-5,nmax=20000): it = 0 err = tol + 1. while it < nmax and err > tol: q = z/linalg.norm(z,2) z = dot(A,q) l = dot(q.T,z) err = linalg.norm(z-l*q,2) it += 1 if(it==nmax): print("Attention: Power Method reached the maximum number of iterations,\ for a more accurate solution increase it.") else: print("Power method converged in %d iteration ",it) return l #Inverse power method def IPM(A,z0,tol=1e-5,nmax=1000): L,U=LU(A) q = z0/linalg.norm(z0,2) it=0 err = tol + 1. while it < nmax and err > tol: y=linalg.solve(L,q) #Also L_solve could be used, prefered scipy x=linalg.solve(U,y) #Also U_solve could be used, prefered scipy q=x/linalg.norm(x,2) z=dot(A,q) l=dot(q.T,z) err=linalg.norm(z-l*q,2) it+=1 if(it==nmax): print("Attention: Inverse Power Method reached the maximum number of iterations,\ for a more accurate solution increase it.") else: print("Inverse power method converged in %d iteration ",it) return l def condNumb(A): n=A.shape[0] z0=random.rand(n) max_eig=PM(A,z0) min_eig=IPM(A,z0) zz,vv=linalg.eig(A) print(min(zz),max(zz),max_eig,min_eig) return max_eig/min_eig omega = [0,pi] f = lambda x : sin(x) n=83 bc = [0,0] A, b = finDif(omega, f, n, bc) l_np, x_np = linalg.eig(A) print(linalg.cond(A),condNumb(A)) # + [markdown] id="2728b49a" # Implement a preconditioned Conjugant Gradient method to solve the original linear system of equations using an iterative method: # - def conjugate_gradient(A, b, P, nmax=len(A), eps=1e-10): n=A.shape[0] x=random.rand(n) r=b-dot(A,x) p=linalg.solve(P,r) res=1 it=0 while res>eps and it<nmax: v1=dot(A,p) alpha=dot(p,r)/dot(v1,p) x=x+alpha*p r=r-alpha*v1 z=linalg.solve(P,r) beta=dot(v1,z)/dot(p,v1) p=z-beta*p res=sqrt(dot(r,r)) it+=1 return x,it,res # + id="62b83aee" omega = [0,pi] f = lambda x : sin(x) n=1728 bc = [0,0] A, b = finDif(omega, f, n, bc) L,U=LU(A) P=L.dot(L.T) HT, H = cholesky(A) PH=HT.dot(HT.T) sol_pc,it,res=conjugate_gradient(A,b,P) sol_pc_2,it2,res2=conjugate_gradient(A,b,PH) sol_chek=linalg.solve(A,b) print('LU res ',res, ' iterations ',it) print('Cholesky res ',res2, ' iterations ',it2) for i in range(n): if(sol_pc[i]-sol_chek[i]>1e-10): print('Warning solution may not be correct',sol_pc[i]-sol_chek[i]) if(sol_pc_2[i]-sol_chek[i]>1e-10): print('Warning solution may not be correct',sol_pc[i]-sol_chek[i]) # + [markdown] id="8a4cfc02" # Consider the following time dependent variation of the PDE starting from the orginal problem formulation: # $$ # u'(t)-u_{xx} = \alpha(t)f(x) # $$ # # for $t\in [0,T]$, with $\alpha(t) = \cos(t)$ and $T = 6\pi$ # # Use the same finite difference scheme to derive the semi-discrete formulation and solve it using a forward Euler's method. # # Plot the time dependent solution solution at $x = \pi/2$, $x=1$, # $x=\pi$ # # + id="3ffe0689" T=[0,6*pi] omega = [0,pi] #space domain bc=[0,0] #dirichlet bc # ns=100 #number of spatial points # nt=400000 #number of time "points" ns=100 nt=100000 hs=(omega[1]-omega[0])/(ns-1) ht=(T[1]-T[0])/(nt-1) alpha=lambda t: cos(t)# Q2=zeros((A.shape[0],A.shape[0])) # for i in range(A.shape[0]): # Q2[:,i]=Q[:,i]/linalg.norm(Q[:,i]) f = lambda x : sin(x) #x*(1-x) #spatial coord coord=linspace(omega[0],omega[1],ns) #time coord times=linspace(T[0],T[1],nt) A=zeros((ns,ns),dtype=double) a=-ones((ns-2,),dtype=double) b=16*ones((ns-1,),dtype=double) c=-30*ones((ns,),dtype=double) A=diag(a,-2)+diag(b,-1)+diag(c)+diag(b,1)+diag(a,2) #boundary conditions A[0,:]=0 A[-1,:]=0 A=A/(12*(hs**2)) d0=zeros(6,dtype=int) def get_index(coord,val): for id,i in enumerate(coord): if(i>=val): return(id) break d0[0]=get_index(coord,1) if(d0[0]-1<1e-8): d0[1]=d0[0]-1 else: d0[1]=d0[0] d0[2]=get_index(coord,pi/2) if(d0[2]-(pi/2)<1e-8): d0[3]=d0[2]-1 else: d0[3]=d0[2] d0[4]=get_index(coord,pi) if(d0[4]-pi<1e-8): d0[5]=d0[4]-1 else: d0[5]=d0[4] print(d0[0],d0[1],d0[2]) print(coord[d0]) u0=zeros(ns) #supposing initial time solution sol=zeros((nt,3)) for id,t in enumerate(times): rhs=f(coord) rhs[0]=rhs[-1]=0 b=alpha(t)*rhs*(ht) I=eye(ns) I[0,:]=I[-1,:]=0 ut=dot(I+ht*A,u0)+b u0=ut sol[id,0]=(u0[d0[0]]+u0[d0[1]])/2 sol[id,1]=(u0[d0[2]]+u0[d0[3]])/2 sol[id,2]=(u0[d0[4]]+u0[d0[5]])/2 title="Time dependent solution" xlabel='t' ylabel='u(x,t)' plot(times,sol[:,0],label='1') plot(times,sol[:,1],label='pi/2') plot(times,sol[:,2],label='pi') legend(loc='best') grid(True) print(u0) # - # + [markdown] id="36936121" # Given the original $Au = b$ system, implement an algorithm to compute the eigenvalues and eigenvectors of the matrix $A$. Exploit the computed LU factorization # + id="622aadf4" omega = [0,pi] f = lambda x : sin(x) n=100 bc = [0,0] A, b = finDif(omega, f, n, bc) def eigenval(A,tol=1e-5,nmax=10000): T=A.copy() test=max(amax(abs(tril(A,-1)),axis=0)) it=0 while it<nmax and test>tol: L,U=LU(T) T=U@L it+=1 test=max(amax(abs(tril(T,-1)),axis=0)) if(it>=nmax): print('eigenvalues rich max iterations, nmax ',nmax,' tol ',test) return diag(T) def eigenvec(A,eig,n,nmax=500, eps=1e-5): evec=eye(n) for id, eval in enumerate(eig): if id!=0 and id!=n-1: # consideration boundary conditions L,U=LU(A-eval*eye(n)) it=0 evec[:,id]=evec[:,id]/linalg.norm(evec[:,id],2) while it<nmax : tmp=linalg.solve(L,evec[:,id]) evec[:,id]=linalg.solve(U,tmp) evec[:,id]=evec[:,id]/linalg.norm(evec[:,id],2) it+=1 else: evec[:,id]=0 evec[id,id]=1 return evec eig =eigenval(A) vals,v=linalg.eig(A) vec=eigenvec(A,eig,A.shape[0]) # print('computed eigenvalues',eig) # print('numpy eigenvalues',vals) # print('computed eigenvectors',eig[1],vec[:,1]) # print('numpy eigenvectors ',vals[0],v[:,0]) # + [markdown] id="85d5f64e" # Compute the inverse of the matrix A exploiting the derived LU factorization # + id="6ad7199f" omega = [0,pi] f = lambda x : sin(x) n=100 bc = [0,0] A, b = finDif(omega, f, n, bc) B=eye(n,dtype=double) AINV=zeros((n,n),dtype=double) L,U=LU(A) for i in range(n): tmp=linalg.solve(L,B[:,i]) AINV[:,i]=linalg.solve(U,tmp) # print(AINV) # print(linalg.inv(A)) B=linalg.inv(A) for i in range(n): for j in range(n): if(AINV[i,j]-B[i,j]>1e-15): print("wrong inverse") # + [markdown] id="cb22566e" # Consider the following Cauchy problem # $$ # \begin{cases} # y'= -ty^2 \quad 0\le t \le 2\\ # y(0) = 1 # \end{cases} # $$ # Implement a Backward Euler's method in a suitable function and solve the resulting non-linear equation using a Newton's method. # + id="3184e358" def newton(y0,t,h,toll=1e-6, nmax=100): it=0 y=y0 diff=1. while diff>=toll and it <nmax: y= y-(h*t*y**2+y-y0)/(1+2*h*t*y) diff=h*t*y**2+y-y0 it+=1 return y def be(y0,t0,tf,h): timesteps=arange(t0,tf+1e-10, h) sol = zeros_like(timesteps) sol[0] = y0 for i in range(1,len(sol)): sol[i]=newton(sol[i-1],timesteps[i],h) return sol,timesteps sol,time=be(1,0,2,0.1) y=1/(1+(time**2)/2) # print(y) # print(sol) title='Solution' plot(time,sol,'r', label='estimated') plot(time,y,'b',label='exact') xlabel='t' ylabel='y(t)' grid(True) legend(loc='best') # -
FinalProject_2021_2022.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 # --- # # # # Data Challenge 1: Employee Retention # # ## Goal: # Employee turnover is a very costly problem for companies. The cost of replacing an employee is often larger than 100K USD, taking into account the time spent to interview and find a replacement, placement fees, sign-on bonuses and the loss of productivity for several months. # # t is only natural then that data science has started being applied to this area. Understanding why and when employees are most likely to leave can lead to actions to improve employee retention as well as planning new hiring in advance. This application of DS is sometimes called people analytics or people data science (if you see a job title: people data scientist, this is your job). # # In this challenge, you have a data set with info about the employees and have to predict when employees are going to quit by understanding the main drivers of employee churn. # # ## Challenge Description # We got employee data from a few companies. We have data about all employees who joined from 2011/01/24 to 2015/12/13. For each employee, we also know if they are still at the company as of 2015/12/13 or they have quit. Beside that, we have general info about the employee, such as avg salary during her tenure, dept, and yrs of experience. # # As said above, the goal is to predict employee retention and understand its main drivers # # ## Hints: # - What are the main factors that drive employee churn? Do they make sense? Explain your findings. # - What might you be able to do for the company to address employee Churn, what would be follow-up actions? # - If you could add to this data set just one variable that could help explain employee churn, what would that be? # # Your output should be in the form a a jupyter notebook and pdf output of a jupyter notebook in which you specify your results and how you got them. # # # # # Preprocessing and feature engineering # # First we import a few libraries that we use later # + import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix # - # We then load the data and inspect its columns and entries df=pd.read_csv("employee_retention_data.csv") df.head() # Number of people who have quit df["quit_date"].isnull().sum() # Here we create a new column indicating whether the employee has quit or not. # We also create a new column for employment duration of the employee in days. # + # creating a column indicating whether the employee has quit (1) or not (0) df["quit"]=~df["quit_date"].isnull() df["quit"]=df["quit"].astype(int) # - # a function to calculate the duration of employment in days def emp_dur(join_date, quit_date, quit): if quit==0: quit_date="2015-12-13" years=list(map(int, quit_date.split("-")))[0]-list(map(int, join_date.split("-")))[0] months=list(map(int, quit_date.split("-")))[1]-list(map(int, join_date.split("-")))[1] days=list(map(int, quit_date.split("-")))[2]-list(map(int, join_date.split("-")))[2] return years*365+months*30+days # + # creating the new column for employment duration in days df["employment_duration"]=df.apply(lambda x: emp_dur(x['join_date'], x['quit_date'], x['quit']), axis=1) df.head() # - # Here, we remove two outliers in seniority who had 99 years of experience! # There are two outliers in seniority with 99 years of experience (probably wrong data). We drop them! # df[df["seniority"]>29].index df.drop(axis=0, index=df[df["seniority"]>29].index, inplace=True) # Here, we do a paitplot for numerical features of our dataset and distinguish them by whether the employee has quit or not # pairplot of numerical features i.e. ['company_id','seniority','salary','employment_duration'] with hue of whether they quit or not sns.pairplot(df,vars=['company_id','seniority','salary','employment_duration'], hue="quit",markers=["o", "s"]) # We also check the number of employees who are still with the companies or who have quit, over all departments. # + # comparison of churn rate in different departments plt.figure(figsize=(10,7)) sns.countplot(data=df, x="dept", hue="quit") # - # We also create a new feature as the joining month for each employee to capture any seasonality # + # capturing seasonality if any, by creating a new column for joining month for each employee df["join_month"]=df["join_date"].map(lambda x: x.split("-")[1]) # df["quit_month"]=df["quit_date"].map(lambda x: list(map(int, x.split("-")))[1]) # - # Here we create dummy variables for categorical features. This is needed for our classification models later on. # + # creating the dummy variables for categorical features: company ID, department, and joining month df["company_id_cat"]=df["company_id"].astype(str) df_cat = pd.get_dummies(df[["company_id_cat","dept","join_month"]],drop_first = True) # - df.head() df_cat.columns # df_cat.columns X=pd.concat([df[['seniority','salary','employment_duration']], df_cat], axis=1) y=df['quit'] # ## Modeling and validation: Classification # # - Below we train two different models namely, logistic regression and random forest for classification # - for both models, we split the data into train and split with ratio of 30:70 # # ### Performance # # - The trained logistic regression and random forest models below, have F-scores of 0.73 and 0.84 for predicting who quits # - Based on logistic regression, the top three informative features are: employment duration, seniority, department type # - Based on random forest, the top three informative features are: employment duration, salary, seniority # # ### Conclusion # # In general the available features are very limited and not very informative. Features on incentives such as bonuses and vacation # days could be helpful. But given that salary and employment duration are already two driving factors, I would choose salary growth rate if I wanted to add another feature. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101) lr=LogisticRegression() lr.fit(X_train, y_train) y_pred = lr.predict(X_test) print(classification_report(y_test, y_pred)) print(confusion_matrix(y_test, y_pred)) lr_feature_importance =pd.DataFrame(lr.coef_[0], index = X_train.columns, columns=['importance']).sort_values('importance',ascending=False) lr_feature_importance.head(5) rf=RandomForestClassifier(max_depth = 30, random_state = 42) rf.fit(X_train, y_train) y_pred_rf=rf.predict(X_test) print(classification_report(y_test, y_pred_rf)) print(confusion_matrix(y_test, y_pred_rf)) rf_feature_importance = pd.DataFrame(rf.feature_importances_, index = X_train.columns, columns=['importance']).sort_values('importance',ascending=False) rf_feature_importance.head(5)
others/Data_Challenge1/Ashkan_HajiHosseinloo_EmployeeRetention.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 # --- # # Universidad de Costa Rica # ## Centro de Investigaciones Espaciales - CINESPA # # Proyecto: Estudio de la radiaciรณn de microondas y rayos X como รญndicadores de la velocidad de propagaciรณn de CME's en el medio interplanetario. # # Coordinadores: <NAME> - # <NAME> # # Asistente: <NAME> # # Periodo: II ciclo- 2018 # # # # Manejo de archivos FITS usando la librerรญa Astropy # # Las imรกgenes solares, contenidas en archivos FITS, requieren ser manejadas por librerรญas especializadas para ello. Astropy es una librerรญa muy utilizada para lograr dicho objetivo. A continuaciรณn se describen funciones bรกsicas para el manejo de archivos FITS. # # Flexible Image Transport System (FITS) es un formato de archivo usado en astronomรญa. Los archivos se conforman de una lista de Header Data Unit (HDU) tambien llamado HDUList, cada HDU consta de un encabezado y un array de datos. El array de datos puede ser una imagen o una tabla. # # Se importan las librerรญas necesarias, entre la que se encuentra 'fits' de Astropy. Ademรกs se importan numpy y matplotlib. # from astropy.io import fits import numpy as np import matplotlib.pyplot as plt # Los archivos FITS se encuentran en la carpeta "ImageFITS" del repositorio. Para abrir un archivo FITS, se utiliza la funciรณn fits.open() sunImageFile = fits.open('ImageFITS/5.fits') sunImageFile.info() # Es posible obtener el HDUList del archivo FITS, con el mรฉtodo HDUList.info(). Es importante notar que la funciรณn fits.open(), retorna un objeto HDUList. # # Se observa que '5.fits' contiene solo un HDU llamado PRIMARY. El header contiene 248 datos, y el tamaรฑo de la imagen es de 2048x2048 pixeles. # # Cada HDU posee dos atributos, el header y el arreglo de datos. Se imprime el header del archivo '5.fits', sunImageFile[0].header # Para guardar algรบn card (datos que conforman el header) en una variable, se puede hacer de forma indexada o utilizando la etiqueta. Se obtiene e imprime la fecha de observaciรณn utilizando ambas formas. # + date1 = sunImageFile[0].header[5] date2 = sunImageFile[0].header['DATE-OBS'] print date1 print date2 # - # Se puede obtener el arreglo de datos del HDU de dos formas. Una es usando la funciรณn fits.getdata(), y la otra es accediendo al atributo data que posee cada objeto HDU. A continuaciรณn, se obtiene la imagen contenida en el archivo '5.fits' de las dos formas ya comentadas. Seguidamente se imprime la matriz que representa la imagen y dimensiรณn de la misma. # + image_data1 = fits.getdata('ImageFITS/5.fits', ext=0) image_data2 = sunImageFile[0].data print(image_data1) print(image_data1.shape) print('\n') print(image_data2) print(image_data2.shape) # - # Se desplega la imagen con la librerรญa matplotlib. Es posible guardar la imagen resultante usando la funciรณn plt.savefig(). # %matplotlib inline plt.figure() plt.imshow(image_data1) plt.colorbar() # ![title](outFitsImagePLT.png) # ![title](outFitsImageCV.png)
ManejoArchivosFITS.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PythonData # language: python # name: pythondata # --- # Import the dependencies. import pandas as pd import gmaps import requests # Import the API key. from config import g_key # Store the CSV you saved created in part one into a DataFrame. city_data_df = pd.read_csv("weather_data/cities.csv") city_data_df.head() # Configure gmaps to use your Google API key. gmaps.configure(api_key=g_key) # Get the maximum temperature. max_temp = city_data_df["Max Temp"] temps = [] for temp in max_temp: temps.append(max(temp, 0)) # Heatmap of temperature # Get the latitude and longitude. locations = city_data_df[["Lat", "Lng"]] # Get the maximum temperature. max_temp = city_data_df["Max Temp"] # Assign the figure variable. fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) # Assign the heatmap variable. heat_layer = gmaps.heatmap_layer(locations, weights=temps, dissipating=False, max_intensity=300, point_radius=4) # Add the heatmap layer. fig.add_layer(heat_layer) # Call the figure to plot the data. fig # + # Heatmap of percent humidity locations = city_data_df[["Lat", "Lng"]] humidity = city_data_df["Humidity"] fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) heat_layer = gmaps.heatmap_layer(locations, weights=humidity, dissipating=False, max_intensity=300, point_radius=4) fig.add_layer(heat_layer) # Call the figure to plot the data. fig # + # Heatmap of cloudiness locations = city_data_df[["Lat", "Lng"]] clouds = city_data_df["Cloudiness"] fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) heat_layer = gmaps.heatmap_layer(locations, weights=clouds, dissipating=False, max_intensity=300, point_radius=4) fig.add_layer(heat_layer) # Call the figure to plot the data. fig # + # Heatmap of wind speed locations = city_data_df[["Lat", "Lng"]] wind = city_data_df["Wind Speed"] fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) heat_layer = gmaps.heatmap_layer(locations, weights=wind, dissipating=False, max_intensity=300, point_radius=4) fig.add_layer(heat_layer) # Call the figure to plot the data. fig # - # Ask the customer to add a minimum and maximum temperature value. min_temp = float(input("What is the minimum temperature you would like for your trip? ")) max_temp = float(input("What is the maximum temperature you would like for your trip? ")) # Filter the dataset to find the cities that fit the criteria. preferred_cities_df = city_data_df.loc[(city_data_df["Max Temp"] <= max_temp) & \ (city_data_df["Max Temp"] >= min_temp)] preferred_cities_df.head(10) preferred_cities_df.count() # Create DataFrame called hotel_df to store hotel names along with city, country, max temp, and coordinates. hotel_df = preferred_cities_df[["City", "Country", "Max Temp", "Lat", "Lng"]].copy() hotel_df["Hotel Name"] = "" hotel_df.head(10) # Set parameters to search for a hotel. params = { "radius": 5000, "type": "lodging", "key": g_key, "location": "" } # Iterate through the DataFrame. for index, row in hotel_df.iterrows(): # Get the latitude and longitude. lat = row["Lat"] lng = row["Lng"] # Add the latitude and longitude to location key for the params dictionary. params["location"] = f"{lat},{lng}" # Use the search term: "lodging" and our latitude and longitude. base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" # Make request and get the JSON data from the search. hotels = requests.get(base_url, params=params).json() # Grab the first hotel from the results and store the name. try: hotel_df.loc[index, "Hotel Name"] = hotels["results"][0]["name"] except (IndexError): print("Hotel not found... skipping.") hotel_df # Add a heatmap of temperature for the vacation spots and marker for each city. locations = hotel_df[["Lat", "Lng"]] max_temp = hotel_df["Max Temp"] fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) heat_layer = gmaps.heatmap_layer(locations, weights=max_temp, dissipating=False, max_intensity=300, point_radius=4) marker_layer = gmaps.marker_layer(locations) fig.add_layer(heat_layer) fig.add_layer(marker_layer) # Call the figure to plot the data. fig info_box_template = """ <dl> <dt>Hotel Name</dt><dd>{Hotel Name}</dd> <dt>City</dt><dd>{City}</dd> <dt>Country</dt><dd>{Country}</dd> <dt>Max Temp</dt><dd>{Max Temp} ยฐF</dd> </dl> """ # Store the DataFrame Row. hotel_info = [info_box_template.format(**row) for index, row in hotel_df.iterrows()] # + # Add a heatmap of temperature for the vacation spots and a pop-up marker for each city. locations = hotel_df[["Lat", "Lng"]] max_temp = hotel_df["Max Temp"] fig = gmaps.figure(center=(30.0, 31.0), zoom_level=1.5) heat_layer = gmaps.heatmap_layer(locations, weights=max_temp,dissipating=False, max_intensity=300, point_radius=4) marker_layer = gmaps.marker_layer(locations, info_box_content=hotel_info) fig.add_layer(heat_layer) fig.add_layer(marker_layer) # Call the figure to plot the data. fig # -
VacationPy.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 # --- # # Cleaning Train Data import pandas as pd import xml.etree.ElementTree as ET from lxml import etree import sys from random import shuffle positive_file = '../data/train_data_raw/kitchen_housewares/reviews_positive.xml' negative_file = '../data/train_data_raw/kitchen_housewares/reviews_negative.xml' reviews_list = [] # + with open(positive_file, 'r') as pos_file: positive_xml_string = pos_file.read() pos_file.close() with open(negative_file, 'r') as neg_file: negative_xml_string = neg_file.read() neg_file.close() # - pos_parser = etree.XMLParser(encoding="UTF-8", recover = True) neg_parser = etree.XMLParser(encoding="UTF-8", recover = True) positive_root = etree.fromstring(positive_xml_string, parser=pos_parser) negative_root = etree.fromstring(negative_xml_string, parser=neg_parser) positive_reviews = positive_root.findall('review') negative_reviews = negative_root.findall('review') def helpful_conv(text): try: new_text = text.replace('of', '|') scores = new_text.split('|') helpful_score = (float(scores[0].replace("\n", "").replace("\t", "").replace(" ", "")) / float(scores[1].replace("\n", "").replace("\t", "").replace(" ", ""))) helpful_score *= 100 return int(helpful_score) except: return 0 def add_to_review_dict(review, sentiment): count = 0 while count < (len(review)-1): try: rev = review[count + 1] uniq_id = rev[0].text.strip() product_name = rev[2].text.strip() helpful = helpful_conv(rev[4].text) rating = int(float(rev[5].text.replace("\n", "").replace("\t", "").replace(" ", ""))) summary = rev[6].text.strip() review_text = rev[10].text.strip() reviewer = rev[8].text.strip() sentiment = sentiment reviews_list.append([uniq_id, product_name, summary, review_text, reviewer, helpful, rating, sentiment]) except: print("Unexpected error:", sys.exc_info()[0]) continue count += 1 add_to_review_dict(positive_reviews, "1") add_to_review_dict(negative_reviews, "0") len(reviews_list) shuffle(reviews_list) dataframe = pd.DataFrame(reviews_list, columns = ['uniq_id', 'product_name', 'summary', 'review_text', 'reviewer', 'helpful', 'rating', 'sentiment']) dataframe.head(4) dataframe.to_csv(r'data/full_data/clean_data_kitchen_housewares.csv') # # Cleaning Test Data import pandas as pd import xml.etree.ElementTree as ET from lxml import etree import sys from random import shuffle category = "electronics" file_name = '../data/test_data_raw/'+category+'.xml' with open(file_name, 'r') as file_data: data_xml_string = file_data.read() file_data.close() xmltree_parser = etree.XMLParser(encoding = "UTF-8", recover = True) data_root = etree.fromstring(data_xml_string, parser = xmltree_parser) review_data = data_root.findall('review') def helpful_conversion(text): try: new_text = text.replace('of', '|') scores = new_text.split('|') helpful_score = (float(scores[0].replace("\n", "").replace("\t", "").replace(" ", "")) / float(scores[1].replace("\n", "").replace("\t", "").replace(" ", ""))) helpful_score *= 100 return int(helpful_score) except: return 0 reviews = [] def add_to_review_dict(review): count = 0 while count < 100: try: rev = review[count + 1] uniq_id = rev[0].text.strip() product_name = rev[2].text.strip() helpful = helpful_conv(rev[4].text) summary = rev[6].text.strip() review_text = rev[10].text.strip() reviewer = rev[8].text.strip() reviews.append([uniq_id, product_name, summary, review_text, reviewer, helpful]) except: print("Unexpected error:", sys.exc_info()[0]) continue count += 1 add_to_review_dict(review_data) shuffle(reviews) dataframe = pd.DataFrame(reviews, columns = ['uniq_id', 'product_name', 'summary', 'review_text', 'reviewer', 'helpful']) dataframe.to_csv(r'data/test_data/test_'+category+'.csv') test_review = [] def test_data_results(review): count = 0 while count < 100: try: rev = review[count + 1] uniq_id = rev[0].text.strip() rating = int(float(rev[5].text.replace("\n", "").replace("\t", "").replace(" ", ""))) test_review.append([uniq_id, rating]) except: print("Unexpected error:", sys.exc_info()[0]) continue count += 1 test_data_results(review_data) shuffle(test_review) dataframe = pd.DataFrame(test_review, columns = ['uniq_id', 'rating']) dataframe.to_csv(r'data/solution_data/'+category+'.csv')
sentiment_analysis/python_jupyter_notebooks/DataCleaning.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 # --- # # Customizing Federated Computations # In this next part of the tutorial it will be up to you to customize the `BaseModelOwner` or the `BaseDataOwner` to implement a new way of computing the gradients and securely aggregating them. # ### Boilerplate # First up is the boilerplate code from the previous part. This includes configuring TF Encrypted and importing all of the dependencies. We've removed the `default_model_fn` and `secure_mean` functions as you'll write new version of those. # + import tensorflow as tf import tf_encrypted as tfe players = [ 'server0', 'server1', 'crypto-producer', 'model-owner', 'data-owner-0', 'data-owner-1', 'data-owner-2', ] config = tfe.EagerLocalConfig(players) tfe.set_config(config) tfe.set_protocol(tfe.protocol.Pond()) from players import BaseModelOwner, BaseDataOwner from func_lib import default_model_fn, secure_mean, evaluate_classifier from util import split_dataset from download import download_mnist NUM_DATA_OWNERS = 3 BATCH_SIZE = 256 DATA_ITEMS = 60000 BATCHES = DATA_ITEMS // NUM_DATA_OWNERS // BATCH_SIZE # - # ### Implementing Reptile Meta-Learning Algorithm # In this section you will use the information from the previous tutorial to help implement new functions for the `model_fn` and the `aggregator_fn`. We also recommend checking out the implementations of `default_model_fn` and `secure_mean` located in [func_lib.py](./func_lib.py) for some help figuring out where to start. # # We've done this with reptile and recommend following through with this but if you have another idea feel free to implement that! # # **TODO**: might need to add details to the below paragraph # # The reptile meta-learning algorithm computes k steps of SGD. When paired with the secure_aggregation aggregator_fn, this model_fn corresponds to using g_k as the outer gradient update. See the Reptile paper for more: https://arxiv.org/abs/1803.02999 # # **HINT**: For implementing reptile it'll help to take advantage of the already implemented `default_model_fn` and `secure_mean` to use inside of the functions below. def reptile_model_fn(data_owner, iterations=3, grad_fn=default_model_fn, **kwargs): #TODO return [var.read_value() for var in data_owner.model.trainable_variables] def secure_reptile(collected_inputs, model): # TODO return weights_deltas # ### Customize Base Classes class ModelOwner(BaseModelOwner): @classmethod def model_fn(cls, data_owner): # TODO @classmethod def aggregator_fn(cls, model_gradients, model): # TODO @classmethod def evaluator_fn(cls, model_owner): return evaluate_classifier(model_owner) # TODO its not super clear how DataOwner should come into the picture here when customizing ModelOwner is sufficient class DataOwner(BaseDataOwner): pass # ### Continue Boilerplate # In this section we continue the fill in some of the boilerplate code from the previous tutorial. # + download_mnist() split_dataset("./data", NUM_DATA_OWNERS, DATA_ITEMS) model = tf.keras.Sequential(( tf.keras.layers.Dense(512, input_shape=[None, 28 * 28], activation='relu'), tf.keras.layers.Dense(10), )) model.build() loss = tf.keras.losses.sparse_categorical_crossentropy opt = tf.keras.optimizers.Adam(LEARNING_RATE) model_owner = ModelOwner("model-owner", "{}/train.tfrecord".format("./data"), model, loss, optimizer=opt) # - # In this next part consider how you might use another learning rate to customize the reptile training loop. # Simplify this with a loop? data_owners = [DataOwner("data-owner-{}".format(i), "{}/train{}.tfrecord".format("./data", i), model, loss, optimizer=opt) for i in range(NUM_DATA_OWNERS)] # Now train! Remember we're using TensorFlow 2.0 so it should be easy to explore the computations and see the actual values being passed around in the computations. You can use this to help debug any problems run into while implementing the reptile meta-learning algorithm. # + model_owner.fit(data_owners, rounds=BATCHES, evaluate_every=10) print("\nDone training!!") # - # Check out the solution [here](./b%20-%20Customizing%20Federated%20Computations%20-%20Solution.ipynb) and compare it to what you've accomplished.
federated-learning/b - Customizing Federated Computations.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] toc=true # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#Setup" data-toc-modified-id="Setup-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Setup</a></span><ul class="toc-item"><li><span><a href="#QC-Thresholds" data-toc-modified-id="QC-Thresholds-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>QC Thresholds</a></span></li><li><span><a href="#Inputs" data-toc-modified-id="Inputs-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Inputs</a></span></li><li><span><a href="#Load-expression-data" data-toc-modified-id="Load-expression-data-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Load expression data</a></span></li><li><span><a href="#Load-QC-data" data-toc-modified-id="Load-QC-data-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Load QC data</a></span></li><li><span><a href="#Load-metadata" data-toc-modified-id="Load-metadata-1.5"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Load metadata</a></span></li><li><span><a href="#Remove-extra-sample-rows" data-toc-modified-id="Remove-extra-sample-rows-1.6"><span class="toc-item-num">1.6&nbsp;&nbsp;</span>Remove extra sample rows</a></span></li></ul></li><li><span><a href="#Check-statistics" data-toc-modified-id="Check-statistics-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Check statistics</a></span><ul class="toc-item"><li><span><a href="#FastQC-stats" data-toc-modified-id="FastQC-stats-2.1"><span class="toc-item-num">2.1&nbsp;&nbsp;</span>FastQC stats</a></span></li><li><span><a href="#Percent-of-reads-aligned-to-genome" data-toc-modified-id="Percent-of-reads-aligned-to-genome-2.2"><span class="toc-item-num">2.2&nbsp;&nbsp;</span>Percent of reads aligned to genome</a></span></li><li><span><a href="#Number-of-aligned-reads" data-toc-modified-id="Number-of-aligned-reads-2.3"><span class="toc-item-num">2.3&nbsp;&nbsp;</span>Number of aligned reads</a></span></li></ul></li><li><span><a href="#Examine-Global-Correlations" data-toc-modified-id="Examine-Global-Correlations-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Examine Global Correlations</a></span><ul class="toc-item"><li><span><a href="#Hierarchical-Clustering" data-toc-modified-id="Hierarchical-Clustering-3.1"><span class="toc-item-num">3.1&nbsp;&nbsp;</span>Hierarchical Clustering</a></span></li></ul></li><li><span><a href="#Remove-failed-samples" data-toc-modified-id="Remove-failed-samples-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Remove failed samples</a></span></li><li><span><a href="#Metadata-Curation" data-toc-modified-id="Metadata-Curation-5"><span class="toc-item-num">5&nbsp;&nbsp;</span>Metadata Curation</a></span><ul class="toc-item"><li><span><a href="#BioProject-counts-of-passing-metadata" data-toc-modified-id="BioProject-counts-of-passing-metadata-5.1"><span class="toc-item-num">5.1&nbsp;&nbsp;</span>BioProject counts of passing metadata</a></span></li><li><span><a href="#BioProject-counts-of-all-metadata" data-toc-modified-id="BioProject-counts-of-all-metadata-5.2"><span class="toc-item-num">5.2&nbsp;&nbsp;</span>BioProject counts of all metadata</a></span></li></ul></li><li><span><a href="#Correlations-between-replicates" data-toc-modified-id="Correlations-between-replicates-6"><span class="toc-item-num">6&nbsp;&nbsp;</span>Correlations between replicates</a></span><ul class="toc-item"><li><span><a href="#Compute-Pearson-R-Score" data-toc-modified-id="Compute-Pearson-R-Score-6.1"><span class="toc-item-num">6.1&nbsp;&nbsp;</span>Compute Pearson R Score</a></span></li><li><span><a href="#Drop-Samples-with-no-replicates" data-toc-modified-id="Drop-Samples-with-no-replicates-6.2"><span class="toc-item-num">6.2&nbsp;&nbsp;</span>Drop Samples with no replicates</a></span></li></ul></li><li><span><a href="#Remove-failed-samples" data-toc-modified-id="Remove-failed-samples-7"><span class="toc-item-num">7&nbsp;&nbsp;</span>Remove failed samples</a></span></li><li><span><a href="#Save-final-datasets" data-toc-modified-id="Save-final-datasets-8"><span class="toc-item-num">8&nbsp;&nbsp;</span>Save final datasets</a></span></li></ul></div> # - # <font size="4">This is a template notebook for performing preliminary quality control on your organism's expression data.</font> import os import pandas as pd from os import path import matplotlib.pyplot as plt import seaborn as sns import numpy as np #sns.set_style('ticks') sns.set_style('whitegrid') # # Setup # ## QC Thresholds min_pct_aligned = 40 # Minimum percent of reads aligned to genome min_mrna_reads = 5e5 # Minimum number of reads mapped to mRNA # ## Inputs # <font size="4">Enter organism name here</font> organism = "Synechococcus_elongatus" # <font size="4">Show files in the organism directory</font> org_dir = path.join('/home/tahani/Documents/github/modulome/data/organisms/',organism) os.listdir(org_dir) # <font size="4">Enter name of curated metadata file here</font> metadata_file = "0_Synechococcus_elongatus.tsv" # ## Load expression data DF_log_tpm = pd.read_csv(path.join(org_dir,'0_log_tpm.csv'),index_col=0).fillna(0) #DF_log_tpm = pd.read_csv('log_tpm.csv',index_col=0) print('Number of genes:',DF_log_tpm.shape[0]) print('Number of samples:',DF_log_tpm.shape[1]) DF_log_tpm.fillna(0,inplace=True) DF_log_tpm.head() # ## Load QC data # <font size="4">There may be some datasets that failed along the processing pipeline, so the number of samples with QC data may be higher than the number of samples with expression data.</font> DF_qc_stats = pd.read_csv(path.join(org_dir,'0_multiqc_stats.tsv'),index_col=0, sep='\t') print('Number of samples with QC data:',DF_qc_stats.shape[0]) DF_qc_stats.fillna(0,inplace=True) DF_qc_stats.head() # ## Load metadata DF_metadata = pd.read_csv(path.join(org_dir,metadata_file),index_col=0,sep='\t') print('Number of samples with metadata:',DF_metadata.shape[0]) DF_metadata.head() np.shape(DF_metadata) np.shape(DF_log_tpm) # ## Remove extra sample rows # Ensure that metadata and qc_stats data contain all log_tpm sample information assert(set(DF_log_tpm.columns) - set(DF_metadata.index) == set()) assert(set(DF_log_tpm.columns) - set(DF_qc_stats.index) == set()) DF_metadata = DF_metadata.loc[DF_log_tpm.columns] DF_qc_stats = DF_qc_stats.loc[DF_log_tpm.columns] # # Check statistics # <font size="4">From here, create a new spreadsheet where you can flag samples based on various QC statistics</font> # # ## FastQC stats fastqc_cols = ['per_base_sequence_quality', 'per_tile_sequence_quality', 'per_sequence_quality_scores', 'per_base_sequence_content', 'per_sequence_gc_content', 'per_base_n_content', 'sequence_length_distribution', 'sequence_duplication_levels', 'overrepresented_sequences', 'adapter_content'] DF_fastqc = DF_qc_stats[fastqc_cols] ax = sns.heatmap(DF_fastqc.replace('pass',1).replace('warn',0).replace('fail',-1), cmap='RdYlBu',vmax=1.3,vmin=-1.3) cbar = ax.collections[0].colorbar cbar.set_ticks([-1,0,1]) cbar.set_ticklabels(['fail','warn','pass']) # <font size="4">The following four categories are the most important: # - per_base_sequence_quality # - per_sequence_quality_scores # - per_base_n_content # - adapter_content # # If a sample does not pass any of these four categories, discard the sample # </font> fastqc_fail_cols = ['per_base_sequence_quality','per_sequence_quality_scores','per_base_n_content','adapter_content'] DF_failed_fastqc = DF_fastqc[fastqc_fail_cols][(DF_fastqc[fastqc_fail_cols] != 'pass').any(axis=1)] DF_failed_fastqc[fastqc_fail_cols] # <font size="4">Mark samples as failed.</font> DF_metadata['passed_fastqc'] = ~DF_metadata.index.isin(DF_failed_fastqc.index) DF_metadata['passed_fastqc'] # ## Percent of reads aligned to genome min_pct_aligned align_cols = ['mRNA-sense','mRNA-antisense','rRNA-sense','rRNA-antisense', 'tRNA-sense','tRNA-antisense','ncRNA-sense','ncRNA-antisense','unannotated'] total_alignment = DF_qc_stats[align_cols].sum(axis=1) percent_alignment = total_alignment.divide(DF_qc_stats['total-reads'])*100 fig,ax = plt.subplots() ax.hist(percent_alignment,bins=50,alpha=0.8) ymin,ymax = ax.get_ylim() ax.vlines(min_pct_aligned,ymin,ymax,color='r') ax.set_ylim((ymin,ymax)) ax.set_xlabel('% of reads mapped to genome',fontsize=14) ax.set_ylabel('# Samples',fontsize=14) ax.set_title('Histogram of Alignment Percentage',fontsize=16) DF_failed_mapping = DF_qc_stats[percent_alignment < min_pct_aligned] DF_failed_mapping DF_metadata['passed_pct_reads_mapped'] = ~DF_metadata.index.isin(DF_failed_mapping.index) DF_metadata['passed_pct_reads_mapped'] # ## Number of aligned reads # <font size="4">The following histogram shows how many reads map to coding sequences (i.e. mRNA). Too few aligned reads reduces the sensitivity of the resulting data.</font> min_mrna_reads fig,ax = plt.subplots() ax.hist(DF_qc_stats['mRNA-sense']/1e6,bins=50,alpha=0.8) ymin,ymax = ax.get_ylim() ax.vlines(min_mrna_reads/1e6,ymin,ymax,color='r') ax.set_ylim((ymin,ymax)) ax.set_xlabel('# Reads (M)',fontsize=14) ax.set_ylabel('# Samples',fontsize=14) ax.set_title('Number of reads mapped to CDS',fontsize=16) # <font size="4">Identify samples with poor read depth:</font> DF_failed_mrna = DF_qc_stats[DF_qc_stats['mRNA-sense'] < min_mrna_reads].sort_values('mRNA-sense') DF_failed_mrna.head() # <font size="4">Mark samples as failed.</font> DF_metadata['passed_reads_mapped_to_CDS'] = ~DF_metadata.index.isin(DF_failed_mrna.index) DF_metadata['passed_reads_mapped_to_CDS'] # # Examine Global Correlations # ## Hierarchical Clustering # <font size=4> A clustermap is a great way to visualize the global correlations between one sample and all others. The following code uses hierarchical clustering to identify specific clusters in the clustermap <font size=4> # # <font size=4> To increase the number of clusters, decrease the value of `thresh`. To decrease the number of clusters, increase the value of `thresh` <font size=4> # + import scipy.cluster.hierarchy as sch import matplotlib.patches as patches # change this to get different number of clusters thresh = .25 # retrieve clusters using fcluster corr = DF_log_tpm.corr() corr.fillna(0,inplace=True) dist = sch.distance.pdist(corr) link = sch.linkage(dist, method='complete') clst = pd.DataFrame(index=DF_log_tpm.columns) clst['cluster'] = sch.fcluster(link, thresh * dist.max(), 'distance') #get colors for each cluster cm = plt.cm.get_cmap('tab20') clr = dict(zip(clst.cluster.unique(), cm.colors)) clst['color'] = clst.cluster.map(clr) print('Number of cluster: ', len(clr)) # - # <font size="4">To view sample IDs in the clustermap, set `xticklabels` and `yticklabels` to `True`. You can increase the `size` variable to improve readability of sample IDs<font> # + size = 12 legend_TN = [patches.Patch(color=c, label=l) for l,c in clr.items()] sns.set(rc={'figure.facecolor':'white'}) g = sns.clustermap(DF_log_tpm.corr(), figsize=(size,size), row_linkage=link, col_linkage=link, col_colors=clst.color, yticklabels=False, xticklabels=False, vmin=0, vmax=1) l2=g.ax_heatmap.legend(loc='upper left', bbox_to_anchor=(1.01,0.85), handles=legend_TN,frameon=True) l2.set_title(title='Clusters',prop={'size':10}) # - # <font size="4">Select clusters to remove.</font> #indicate which clusters you want to remove remove_clst = [1,2] failed_global_corr = clst[clst.cluster.isin(remove_clst)].index failed_global_corr DF_metadata.loc['SRX2769875'] DF_metadata['passed_global_correlation'] = ~DF_metadata.index.isin(failed_global_corr) DF_metadata['passed_global_correlation'] DF_metadata.head() # # Remove failed samples qc_columns = ['passed_fastqc', 'passed_reads_mapped_to_CDS', 'passed_pct_reads_mapped', 'passed_global_correlation'] pass_qc = DF_metadata[qc_columns].all(axis=1) DF_metadata_passed = DF_metadata[pass_qc] DF_metadata_passed.shape pass_qc # + _,_,pcts = plt.pie(pass_qc.value_counts().sort_values(), labels = ['Failed','Passed'], colors=['tab:red','tab:blue'], autopct='%.0f%%',textprops={'size':16}); # Colors percents white for pct in pcts: pct.set_color('white') # - # # Save Metadata for Curation Process DF_metadata_passed.to_csv(os.path.join(org_dir,'metadata_passed_qc_part1.csv')) # # Metadata Curation # <font size=4>The following sections can only be run after metadata curation is complete. To enable metadata curation, the code in this section sorts data by BioProject. </font> # ## BioProject counts of passing metadata DF_metadata_passed.BioProject.value_counts().sort_values(ascending=False) # ## BioProject counts of all metadata DF_metadata.BioProject.value_counts().sort_values(ascending=False) # # Correlations between replicates # <font size=4> First, get a full sample name </font> # Turn off pesky warning pd.set_option('mode.chained_assignment', None) # + curated_metadata_file= "metadata_curated_project_spec.csv" DF_metadata_passed = pd.read_csv(path.join(org_dir,curated_metadata_file),index_col=0,sep=',') print('Number of samples with metadata:',DF_metadata.shape[0]) DF_metadata.head() # - DF_metadata_passed['full_name'] = DF_metadata_passed.loc[:,'project_name'].str.cat(DF_metadata_passed.loc[:,'condition_name'],sep=':') DF_metadata_passed['full_name'] # ## Compute Pearson R Score # <font size="4">Once you have updated your metadata files with the sample information, we can investigate correlations between biological replicates. We require biological replicates to have a Pearson R correlation above 0.95. For samples with more than 2 replicates, the replicates must have R >= 0.95 with at least one other replicate or it will be dropped. </font> from tqdm.notebook import tqdm import itertools from scipy import stats import numpy as np # + rep_corrs = {} rand_corrs = {} num_comparisons = len(DF_metadata_passed)*(len(DF_metadata_passed)-1)/2 for exp1,exp2 in tqdm(itertools.combinations(DF_metadata_passed.index,2),total=num_comparisons): if DF_metadata_passed.loc[exp1,'full_name'] == DF_metadata_passed.loc[exp2,'full_name']: rep_corrs[(exp1,exp2)] = stats.pearsonr(DF_log_tpm[exp1],DF_log_tpm[exp2])[0] else: rand_corrs[(exp1,exp2)] = stats.pearsonr(DF_log_tpm[exp1],DF_log_tpm[exp2])[0] # - len(DF_metadata_passed)*(len(DF_metadata_passed)-1)/2 sns.set_style('ticks') # + fig,ax = plt.subplots(figsize=(5,5)) ax2 = ax.twinx() ax2.hist(rep_corrs.values(),bins=50,range=(0.2,1),alpha=0.8,color='green',linewidth=0) ax.hist(rand_corrs.values(),bins=50,range=(0.2,1),alpha=0.8,color='blue',linewidth=0) ax.set_title('Pearson R correlation between experiments',fontsize=14) ax.set_xlabel('Pearson R correlation',fontsize=14) ax.set_ylabel('Different Conditions',fontsize=14) ax2.set_ylabel('Known Replicates',fontsize=14) med_corr = np.median([v for k,v in rep_corrs.items()]) print('Median Pearson R between replicates: {:85.2f}'.format(med_corr)) # + #pearson r cutoff for replicates rcutoff = 0.9 #for each sample get max correlation between replicates dissimilar = [] for idx, grp in DF_metadata_passed.groupby('full_name'): ident = np.identity(len(grp)) corrs = (DF_log_tpm[grp.index].corr() - ident).max() dissimilar.extend(corrs[corrs<rcutoff].index) len(dissimilar) # - DF_metadata['passed_replicate_corr'] = ~DF_metadata.index.isin(dissimilar) DF_metadata_passed['passed_similar_replicates'] = ~DF_metadata_passed.index.isin(dissimilar) DF_metadata_passed['passed_similar_replicates'] # ## Drop Samples with no replicates # + #cond_counts = DF_metadata_passed.full_name.value_counts() #drop_conds = cond_counts[cond_counts < 2].index #len(drop_conds) # + #DF_metadata_passed['passed_number_replicates'] = ~DF_metadata_passed.full_name.isin(drop_conds) # + # this will give the metadata file with all samples containing replicates #DF_metadata_passed = DF_metadata_passed[DF_metadata_passed['passed_number_replicates']] #DF_metadata_passed # + #^the above code was errased because Sugats code already removes samples with no replicates # - # # Remove failed samples qc_columns = ['passed_similar_replicates'] #,'passed_number_replicates'] DF_metadata_final = DF_metadata_passed[DF_metadata_passed[qc_columns].all(axis=1)] DF_metadata_final.shape DF_log_tpm_final = DF_log_tpm[DF_metadata_final.index] # # Save final datasets DF_log_tpm_final.to_csv(os.path.join(org_dir,'1_log_tpm_final.csv')) DF_metadata_final.to_csv(os.path.join(org_dir,'1_metadata_final.csv')) # + #Tahani 8/9/2020 time 11:30pm # -
Old/Notebooks/expression_QC_SOP.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="_1sPZ3CpAwny" # # Graph Neural Networks # # The biggest difficulty for deep learning with molecules is the choice and computation of "descriptors". Graph neural networks (GNNs) are a category of deep neural networks whose inputs are graphs and provide a way around the choice of descriptors. A GNN can take a molecule directly as input. # # As usual, they are composed of specific layers that input a graph and those layers are what we're interested in. You can find reviews of GNNs in Dwivedi *et al.*{cite}`dwivedi2020benchmarking`, Bronstein *et al.*{cite}`bronstein2017geometric`, and Wu *et al.*{cite}`wu2020comprehensive`. GNNs can be used for everything from coarse-grained molecular dynamics {cite}`li2020graph` to predicting NMR chemical shifts {cite}`yang2020predicting` to modeling dynamics of solids {cite}`xie2019graph`. Before we dive too deep into them, we must first understand how a graph is represented and how molecules are converted into graphs. # # You can find an interactive introductory article on graphs and graph neural networks at [distill.pub](https://distill.pub/2021/gnn-intro/) {cite}`sanchez-lengeling2021a`. # + [markdown] id="8x1xularAwnz" # ## Representing a Graph # # A graph $\mathbf{G}$ is a set of nodes $\mathbf{V}$ and edges $\mathbf{E}$. In our setting, node $i$ is defined by a vector $\vec{v}_i$, so that the set of nodes can be written as a rank 2 tensor. The edges can be represented as an adjacency matrix $\mathbf{E}$, where if $e_{ij} = 1$ then nodes $i$ and $j$ are connected by an edge. In many fields, graphs are often immediately simplified to be directed and acyclic, which simplifies things. Molecules are instead undirected and have cycles (rings). Thus, our adjacency matrices are always symmetric $e_{ij} = e_{ji}$. Often our edges themselves have features, so that $e_{ij}$ is itself a vector. Then the adjacency matrix becomes a rank 3 tensor. Examples of edge features might be covalent bond order or distance between two nodes. # # # ```{figure} ./methanol.jpg # ---- # name: methanol # width: 400px # ---- # Methanol with atoms numbered so that we can convert it to a graph. # ``` # # # Let's see how a graph can be constructed from a molecule. Consider methanol, shown in {numref}`methanol`. I've numbered the atoms so that we have an order for defining the nodes/edges. First, the node features. You can use anything for node features, but often we'll begin with one-hot encoded feature vectors: # # | Node | C | H | O | # |:-----|----|----|---:| # | 1 | 0 | 1 | 0 | # | 2 | 0 | 1 | 0 | # | 3 | 0 | 1 | 0 | # | 4 | 1 | 0 | 0 | # | 5 | 0 | 0 | 1 | # | 6 | 0 | 1 | 0 | # # $\mathbf{V}$ will be the combined feature vectors of these nodes. The adjacency matrix $\mathbf{E}$ will look like: # # # | | 1 | 2 | 3 | 4 | 5 | 6 | # |:---|----|----|----|----|----|---:| # | 1 | 0 | 0 | 0 | 1 | 0 | 0 | # | 2 | 0 | 0 | 0 | 1 | 0 | 0 | # | 3 | 0 | 0 | 0 | 1 | 0 | 0 | # | 4 | 1 | 1 | 1 | 0 | 1 | 0 | # | 5 | 0 | 0 | 0 | 1 | 0 | 1 | # | 6 | 0 | 0 | 0 | 0 | 1 | 0 | # # # Take a moment to understand these two. For example, notice that rows 1, 2, and 3 only have the 4th column as non-zero. That's because atoms 1-3 are bonded only to carbon (atom 4). Also, the diagonal is always 0 because atoms cannot be bonded with themselves. # # You can find a similar process for converting crystals into graphs in Xie et al. {cite}`Xie2018Crystal`. We'll now begin with a function which can convert a smiles string into this representation. # + [markdown] id="rsyJAAvrAwn0" # ## Running This Notebook # # # Click the &nbsp;<i aria-label="Launch interactive content" class="fas fa-rocket"></i>&nbsp; above to launch this page as an interactive Google Colab. See details below on installing packages, either on your own environment or on Google Colab # # ````{tip} My title # :class: dropdown # To install packages, execute this code in a new cell # ``` # # # !pip install jupyter-book matplotlib numpy tensorflow pydot seaborn Pillow rdkit-pypi # ``` # # ```` # + tags=["hide-cell"] id="6tMyUYUjAwn2" import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl import numpy as np import tensorflow as tf import warnings import pandas as pd import rdkit, rdkit.Chem, rdkit.Chem.rdDepictor, rdkit.Chem.Draw import networkx as nx warnings.filterwarnings("ignore") sns.set_context("notebook") sns.set_style( "dark", { "xtick.bottom": True, "ytick.left": True, "xtick.color": "#666666", "ytick.color": "#666666", "axes.edgecolor": "#666666", "axes.linewidth": 0.8, "figure.dpi": 300, }, ) color_cycle = ["#1BBC9B", "#F06060", "#5C4B51", "#F3B562", "#6e5687"] mpl.rcParams["axes.prop_cycle"] = mpl.cycler(color=color_cycle) # soldata = pd.read_csv('https://dataverse.harvard.edu/api/access/datafile/3407241?format=original&gbrecs=true') # had to rehost because dataverse isn't reliable soldata = pd.read_csv( "https://github.com/whitead/dmol-book/raw/master/data/curated-solubility-dataset.csv" ) np.random.seed(0) my_elements = {6: "C", 8: "O", 1: "H"} # + [markdown] id="Jfet-OZuAwn3" # The hidden cell below defines our function `smiles2graph`. This creates one-hot node feature vectors for the element C, H, and O. It also creates an adjacency tensor with one-hot bond order being the feature vector. # + tags=["hide-cell"] id="gze3Vw00Awn3" def smiles2graph(sml): """Argument for the RD2NX function should be a valid SMILES sequence returns: the graph """ m = rdkit.Chem.MolFromSmiles(sml) m = rdkit.Chem.AddHs(m) order_string = { rdkit.Chem.rdchem.BondType.SINGLE: 1, rdkit.Chem.rdchem.BondType.DOUBLE: 2, rdkit.Chem.rdchem.BondType.TRIPLE: 3, rdkit.Chem.rdchem.BondType.AROMATIC: 4, } N = len(list(m.GetAtoms())) nodes = np.zeros((N, len(my_elements))) lookup = list(my_elements.keys()) for i in m.GetAtoms(): nodes[i.GetIdx(), lookup.index(i.GetAtomicNum())] = 1 adj = np.zeros((N, N, 5)) for j in m.GetBonds(): u = min(j.GetBeginAtomIdx(), j.GetEndAtomIdx()) v = max(j.GetBeginAtomIdx(), j.GetEndAtomIdx()) order = j.GetBondType() if order in order_string: order = order_string[order] else: raise Warning("Ignoring bond order" + order) adj[u, v, order] = 1 adj[v, u, order] = 1 return nodes, adj # + id="ASYUMhwEAwn4" nodes, adj = smiles2graph("CO") nodes # + [markdown] id="Ux8vA5kcAwn4" # ## A Graph Neural Network # # A graph neural network (GNN) is a neural network with two defining attributes: # # 1. It's input is a graph # 2. It's output is permutation invariant # # We can understand clearly the first point. Here, a graph permutation means re-ordering our nodes. In our methanol example above, we could have easily made the carbon be atom 1 instead of atom 4. Our new adjacency matrix would then be: # # | | 1 | 2 | 3 | 4 | 5 | 6 | # |:---|----|----|----|----|----|---:| # | 1 | 0 | 1 | 1 | 1 | 1 | 0 | # | 2 | 1 | 0 | 0 | 0 | 0 | 0 | # | 3 | 1 | 0 | 0 | 0 | 0 | 0 | # | 4 | 1 | 0 | 0 | 0 | 1 | 0 | # | 5 | 1 | 0 | 0 | 0 | 0 | 1 | # | 6 | 0 | 0 | 0 | 0 | 1 | 0 | # # # ```{margin} # Ok, so technically we might want our GNN to be permutation *equivariant*. If our GNN outputs per-node features, then obviously if we swap the node order of input, we want our per-node output to swap. # ``` # # A GNN is permutation invariant if the output is insensitive to these kind of exchanges. Of course, there may exist GNNs out there which are not permutation invariant, especially if they are for trees where it is possible to deterministically order all nodes. Yet all the GNNs used in chemistry and most of the deep learning work is concerned with GNNs that are permutation invariant. # + [markdown] id="N_UEUDHoAwn5" # ### A simple GNN # # We will often mention a GNN when we really mean a layer from a GNN. Most GNNs implement a specific layer that can deal with graphs, and so usually we are only concerned with this layer. Let's see an example of a simple layer for a GNN: # # \begin{equation} # f_k = \sigma\left( \sum_i \sum_j v_{ij}w_{jk} \right) # \end{equation} # # This equation shows that we first multiply every node feature by trainable weights $w_{jk}$, sum over all node features, and then apply an activation. This will yield a single feature vector for the graph. Is this equation permutation invariant? Yes, because the node index in our expression is index $i$ which can be re-ordered without affecting the output. # # Let's see an example that is similar, but not permutation invariant: # # \begin{equation} # f_k = \sigma\left( \sum_i v_{ij}w_{ik} \right) # \end{equation} # # This is a small change. We have one weight vector per node now. This makes the trainable weights depend on the ordering of the nodes. Then if we swap the node ordering, our weights will no longer align. So if we were to input two methanol molecules, which should have the same output, but we switched two atom numbers, we would get different answers. These simple examples differ from real GNNs in two important ways: (i) they give a single feature vector output, which throws away per-node information, and (ii) they do not use the adjacency matrix. Let's see a real GNN that has these properties while maintaining permutation invariance. # + [markdown] id="FoHeANFgAwn6" # ## Kipf & Welling GCN # # One of the first popular GNNs was the Kipf & Welling graph convolutional network (GCN) {cite}`kipf2016semi`. Although some people consider GCNs to be a broad class of GNNs, we'll use GCNs to refer specifically the Kipf & Welling GCN. # <NAME> has written an [excellent article introducing the GCN](https://tkipf.github.io/graph-convolutional-networks/). I will not repeat this article, so please take a look at it. # # The input to a GCN layer is $\mathbf{V}$, $\mathbf{E}$ and it outputs an updated $\mathbf{V}'$. Each node feature vector is updated. The way it updates a node feature vector is by averaging the feature vectors of its neighbors, as determined by $\mathbf{E}$. The choice of averaging over neighbors is what makes a GCN layer permutation invariant. Averaging over neighbors is not trainable, so we must add trainable parameters. We multiply the neighbor features by a trainable matrix before the averaging, which gives the GCN the ability to learn. In Einstein notation, this process is: # # \begin{equation} # v_{il} = \sigma\left(\frac{1}{d_i}e_{ij}v_{jk}w_{lk}\right) # \end{equation} # # where $i$ is the node we're considering, $j$ is the neighbor index, $k$ is the node input feature, $l$ is the output node feature, $d_i$ is the degree of node i (which makes it an average instead of sum), $e_{ij}$ isolates neighbors so that all non-neighbor $v_{jk}$s are zero, $\sigma$ is our activation, and $w_{lk}$ is the trainable weights. This equation is a mouthful, but it truly just is the average over neighbors with a trainable matrix thrown in. One common modification is to make all nodes neighbors of themselves. This is so that the output node features $v_{il}$ depends on the input features $v_{ik}$. We do not need to change our equation, just make the adjacency matrix have $1$s on the diagonal instead of $0$ by adding the identity matrix during pre-processing. # # Building understanding about the GCN is important for understanding other GNNs. You can view the GCN layer as a way to "communicate" between a node and its neighbors. The output for node $i$ will depend only on its immediate neighbors. For chemistry, this is not satisfactory. You can stack multiple layers though. If you have two layers, the output for node $i$ will include information about node $i$'s neighbors' neighbors. Another important detail to understand in GCNs is that the averaging procedure accomplishes two goals: (i) it gives permutation invariance by removing the effect of neighbor order and (ii) it prevents a change in magnitude in node features. A sum would accomplish (i) but would cause the magnitude of the node features to grow after each layer. Of course, you could ad-hoc put a batch normalization layer after each GCN layer to keep output magnitudes stable but averaging is easy. # + tags=["remove-cell"] id="cCYdqzvVAwn6" # THIS CELL IS USED TO GENERATE A FIGURE # AND NOT RELATED TO CHAPTER # YOU CAN SKIP IT from myst_nb import glue from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage def draw_vector(x, y, s, v, ax, cmap, **kwargs): x += s / 2 y += s / 2 for vi in v: if cmap is not None: ax.add_patch( mpl.patches.Rectangle((x, y), s * 1.5, s, facecolor=cmap(vi), **kwargs) ) else: ax.add_patch( mpl.patches.Rectangle( (x, y), s * 1.5, s, facecolor="#FFF", edgecolor="#333", **kwargs ) ) ax.text( x + s * 1.5 / 2, y + s / 2, "{:.2f}".format(vi), verticalalignment="center", horizontalalignment="center", ) y += s def draw_key(x, y, s, v, ax, cmap, **kwargs): x += s / 2 y += s / 2 for vi in v: ax.add_patch( mpl.patches.Rectangle((x, y), s * 1.5, s, facecolor=cmap(1.0), **kwargs) ) ax.text( x + s * 1.5 / 2, y + s / 2, vi, verticalalignment="center", horizontalalignment="center", ) y += s ax.text( x, y + s / 2, "Key:", verticalalignment="center", horizontalalignment="left" ) def draw( nodes, adj, ax, highlight=None, key=False, labels=None, mask=None, draw_nodes=None ): G = nx.Graph() for i in range(adj.shape[0]): for j in range(adj.shape[0]): if np.any(adj[i, j]): G.add_edge(i, j) if mask is None: mask = [True] * len(G) if draw_nodes is None: draw_nodes = nodes # go from atomic number to element elements = np.argmax(draw_nodes, axis=-1) el_labels = {i: list(my_elements.values())[e] for i, e in enumerate(elements)} pos = nx.nx_agraph.graphviz_layout(G, prog="sfdp") pos = nx.rescale_layout_dict(pos) c = ["white"] * len(G) all_h = [] if highlight is not None: for i, h in enumerate(highlight): for hj in h: c[hj] = "C{}".format(i) all_h.append(hj) nx.draw(G, ax=ax, pos=pos, labels=el_labels, node_size=700, node_color=c) cmap = plt.get_cmap("Wistia") for i in range(len(G)): if not mask[i]: continue if i in all_h: draw_vector(*pos[i], 0.15, nodes[i], ax, cmap) else: draw_vector(*pos[i], 0.15, nodes[i], ax, None) if key: draw_key(-1, -1, 0.15, my_elements.values(), ax, cmap) if labels is not None: legend_elements = [] for i, l in enumerate(labels): p = mpl.lines.Line2D( [0], [0], marker="o", color="C{}".format(i), label=l, markersize=15 ) legend_elements.append(p) ax.legend(handles=legend_elements) ax.set_xlim(-1.2, 1.2) ax.set_ylim(-1.2, 1.2) plt.figure() draw(nodes, adj, plt.gca(), highlight=[[1], [5, 0]], labels=["center", "neighbors"]) glue("dframe", plt.gcf(), display=False) # + tags=["remove-cell"] id="2WECOhDMAwn7" # THIS CELL IS USED TO GENERATE A FIGURE # AND NOT RELATED TO CHAPTER # YOU CAN SKIP IT fig, axs = plt.subplots(1, 2, squeeze=True, figsize=(12, 4)) order = [5, 1, 0, 2, 3, 4] time_per_node = 2 last_layer = [0] layers = 2 input_nodes = np.copy(nodes) def make_frame(t): axs[0].clear() axs[1].clear() layer_i = int(t / (time_per_node * len(order))) axs[0].set_title(f"Layer {layer_i + 1} Input") axs[1].set_title(f"Layer {layer_i + 1} Output") flat_adj = np.sum(adj, axis=-1) out_nodes = np.einsum( "i,ij,jk->ik", 1 / (np.sum(flat_adj, axis=1) + 1), flat_adj + np.eye(*flat_adj.shape), nodes, ) if last_layer[0] != layer_i: print("recomputing") nodes[:] = out_nodes last_layer[0] = layer_i t -= layer_i * time_per_node * len(order) i = order[int(t / time_per_node)] print(last_layer, layer_i, i, t) mask = [False] * nodes.shape[0] for j in order[: int(t / time_per_node) + 1]: mask[j] = True print(mask, i) neighs = list(np.where(adj[i])[0]) if (t - int(t / time_per_node) * time_per_node) >= time_per_node / 4: draw( nodes, adj, axs[0], highlight=[[i], neighs], labels=["center", "neighbors"], draw_nodes=input_nodes, ) else: draw( nodes, adj, axs[0], highlight=[[i]], labels=["center", "neighbors"], draw_nodes=input_nodes, ) if (t - int(t / time_per_node) * time_per_node) < time_per_node / 2: mask[j] = False draw( out_nodes, adj, axs[1], highlight=[[i]], key=True, mask=mask, draw_nodes=input_nodes, ) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=time_per_node * nodes.shape[0] * layers) animation.write_gif("../_static/images/gcn.gif", fps=2) # + [markdown] id="lQ9-r0QwAwn7" # ```{glue:figure} dframe # ---- # name: dframe # ---- # Intermediate step of the graph convolution layer. The center node is being updated by averaging its neighbors features. # ``` # # # ```{figure} ../_static/images/gcn.gif # ---- # name: gcnanim # ---- # Animation of the graph convolution layer. The left is input, right is output node features. Note that two layers are shown (see title change). # ``` # # To help understand the GCN layer, look at {numref}`dframe`. It shows an intermediate step of the GCN layer. Each node feature is represented here as a one-hot encoded vector at input. The animation in {numref}`gcnanim` shows the averaging process over neighbor features. To make this animation easy to follow, the trainable weights and activation functions are not considered. Note that the animation repeats for a second layer. Watch how the "information" about there being an oxygen atom in the molecule is propagated only after two layers to each atom. All GNNs operate with similar approaches, so try to understand how this animation works. # # # ### GCN Implementation # # Let's now create a tensor implementation of the GCN. We'll skip the activation and trainable weights for now. # We must first compute our rank 2 adjacency matrix. The `smiles2graph` code above computes an adjacency tensor with feature vectors. We can fix that with a simple reduction and add the identity at the same time # # + id="WszSYUjVAwn8" nodes, adj = smiles2graph("CO") adj_mat = np.sum(adj, axis=-1) + np.eye(adj.shape[0]) adj_mat # + [markdown] id="bdyLskCWAwn8" # To compute degree of each node, we can do another reduction: # + id="5dTdOfenAwn8" degree = np.sum(adj_mat, axis=-1) degree # + [markdown] id="lFw3QuYKAwn8" # Now we can put all these pieces together into the Einstein equation # + id="Yd5HcbJvAwn9" print(nodes[0]) # note to divide by degree, make the input 1 / degree new_nodes = np.einsum("i,ij,jk->ik", 1 / degree, adj_mat, nodes) print(new_nodes[0]) # + [markdown] id="BhhKhyB0Awn9" # To now implement this as a layer in Keras, we must put this code above into a new Layer subclass. The code is relatively straightforward, but you can read-up on the function names and Layer class in [this tutorial](https://keras.io/guides/making_new_layers_and_models_via_subclassing/). The three main changes are that we create trainable parameters `self.w` and use them in the {obj}`tf.einsum`, we use an activation `self.activation`, and we output both our new node features and the adjacency matrix. The reason to output the adjacency matrix is so that we can stack multiple GCN layers without having to pass the adjacency matrix each time. # + id="_PFfU9wxAwn9" class GCNLayer(tf.keras.layers.Layer): """Implementation of GCN as layer""" def __init__(self, activation=None, **kwargs): # constructor, which just calls super constructor # and turns requested activation into a callable function super(GCNLayer, self).__init__(**kwargs) self.activation = tf.keras.activations.get(activation) def build(self, input_shape): # create trainable weights node_shape, adj_shape = input_shape self.w = self.add_weight(shape=(node_shape[2], node_shape[2]), name="w") def call(self, inputs): # split input into nodes, adj nodes, adj = inputs # compute degree degree = tf.reduce_sum(adj, axis=-1) # GCN equation new_nodes = tf.einsum("bi,bij,bjk,kl->bil", 1 / degree, adj, nodes, self.w) out = self.activation(new_nodes) return out, adj # + [markdown] id="eJo2efloAwn9" # We can now try our layer: # + id="pBpu_5oYAwn9" gcnlayer = GCNLayer("relu") # we insert a batch axis here gcnlayer((nodes[np.newaxis, ...], adj_mat[np.newaxis, ...])) # + [markdown] id="crzT2aSRAwn-" # It outputs (1) the new node features and (2) the adjacency matrix. Let's make sure we can stack these and apply the GCN multiple times # + id="jWQQZPb6Awn-" x = (nodes[np.newaxis, ...], adj_mat[np.newaxis, ...]) for i in range(2): x = gcnlayer(x) x # + [markdown] id="54pU1WHfAwn-" # It works! Why do we see zeros though? Probably because we had negative numbers that were removed by our ReLU activation. This will be solved by training and increasing our dimension number. # + [markdown] id="oBNnUZ9UAwn-" # ## Solubility Example # # We'll now revisit predicting solubility with GCNs. Remember before that we used the features included with the dataset. Now we can use the molecular structures directly. Our GCN layer outputs node-level features. To predict solubility, we need to get a graph-level feature. We'll see later how to be more sophisticated in this process, but for now let's just take the average over all node features after our GCN layers. This is simple, permutation invariant, and gets us from node-level to graph level. Here's an implementation of this # + id="xnPBnidtAwn-" class GRLayer(tf.keras.layers.Layer): """A GNN layer that computes average over all node features""" def __init__(self, name="GRLayer", **kwargs): super(GRLayer, self).__init__(name=name, **kwargs) def call(self, inputs): nodes, adj = inputs reduction = tf.reduce_mean(nodes, axis=1) return reduction # + [markdown] id="r7FYHwFYAwn_" # To complete our deep solubility predictor, we can add some dense layers and make sure we have a single-output without activation since we're doing regression. Note this model is defined using the [Keras functional API](https://keras.io/guides/functional_api/) which is necessary when you have multiple inputs. # + id="waFjwubcAwn_" ninput = tf.keras.Input( ( None, 100, ) ) ainput = tf.keras.Input( ( None, None, ) ) # GCN block x = GCNLayer("relu")([ninput, ainput]) x = GCNLayer("relu")(x) x = GCNLayer("relu")(x) x = GCNLayer("relu")(x) # reduce to graph features x = GRLayer()(x) # standard layers (the readout) x = tf.keras.layers.Dense(16, "tanh")(x) x = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs=(ninput, ainput), outputs=x) # + [markdown] id="54hJLJS3Awn_" # where does the 100 come from? Well, this dataset has lots of elements so we cannot use our size 3 one-hot encodings because we'll have more than 3 unique elements. We previously only had C, H and O. This is a good time to update our `smiles2graph` function to deal with this. # + tags=["hidden-cell"] id="zkHWGgRsAwn_" def gen_smiles2graph(sml): """Argument for the RD2NX function should be a valid SMILES sequence returns: the graph """ m = rdkit.Chem.MolFromSmiles(sml) m = rdkit.Chem.AddHs(m) order_string = { rdkit.Chem.rdchem.BondType.SINGLE: 1, rdkit.Chem.rdchem.BondType.DOUBLE: 2, rdkit.Chem.rdchem.BondType.TRIPLE: 3, rdkit.Chem.rdchem.BondType.AROMATIC: 4, } N = len(list(m.GetAtoms())) nodes = np.zeros((N, 100)) for i in m.GetAtoms(): nodes[i.GetIdx(), i.GetAtomicNum()] = 1 adj = np.zeros((N, N)) for j in m.GetBonds(): u = min(j.GetBeginAtomIdx(), j.GetEndAtomIdx()) v = max(j.GetBeginAtomIdx(), j.GetEndAtomIdx()) order = j.GetBondType() if order in order_string: order = order_string[order] else: raise Warning("Ignoring bond order" + order) adj[u, v] = 1 adj[v, u] = 1 adj += np.eye(N) return nodes, adj # + id="QgasqU7GAwn_" nodes, adj = gen_smiles2graph("CO") model((nodes[np.newaxis, ...], adj_mat[np.newaxis, ...])) # + [markdown] id="EPx37s4rAwn_" # ```{margin} # We have switched from adjacency tensor to matrix only because a GCN cannot use edge features. Other architectures though can. # ``` # It outputs one number! That's always nice to have. Now we need to do some work to get a trainable dataset. Our dataset is a little bit complex because our features are tuples of tensors($\mathbf{V}, \mathbf{E}$) so that our dataset is a tuple of tuples: $\left((\mathbf{V}, \mathbf{E}), y\right)$. We use a **generator**, which is just a python function that can return multiple times. Our function returns once for every training example. Then we have to pass it to the `from_generator` {obj}`tf.data.Dataset` constructor which requires explicit declaration of the shapes of these examples. # + id="xzSUN5esAwoA" def example(): for i in range(len(soldata)): graph = gen_smiles2graph(soldata.SMILES[i]) sol = soldata.Solubility[i] yield graph, sol data = tf.data.Dataset.from_generator( example, output_types=((tf.float32, tf.float32), tf.float32), output_shapes=( (tf.TensorShape([None, 100]), tf.TensorShape([None, None])), tf.TensorShape([]), ), ) # + [markdown] id="_hccGPSBAwoA" # Whew, that's a lot. Now we can do our usual splitting of the dataset. # + id="FdX8YIYdAwoA" test_data = data.take(200) val_data = data.skip(200).take(200) train_data = data.skip(400) # + [markdown] id="nXM9rarLAwoA" # And finally, time to train. # + tags=["remove-output"] id="X8TnKEUeAwoA" model.compile("adam", loss="mean_squared_error") result = model.fit( train_data.batch(1), validation_data=val_data.batch(1), epochs=20, verbose=0 ) # + id="KuluLpeEAwoA" plt.plot(result.history["loss"], label="training") plt.plot(result.history["val_loss"], label="validation") plt.legend() plt.xlabel("Epoch") plt.ylabel("Loss") plt.show() # + [markdown] id="m-zUB18dAwoB" # This model is definitely underfit. One reason is that our batch size is 1. This is a side-effect of making the number of atoms variable and then Keras/tensorflow has trouble batching together our data if there are two unknown dimensions. You can fix this by manually batching or padding all molecules to have as many atoms as the one with the max. In any case, this example shows how to use GCN layers in a complete model. # + [markdown] id="r7zXMJcZAwoB" # ## Message Passing Viewpoint # # One way to more broadly view a GCN layer is that it is a kind of "message-passing" layer. You first compute a message coming from each neighboring node: # # \begin{equation} # \vec{e}_{{s_i}j} = \vec{v}_{{s_i}j} \mathbf{W} # \end{equation} # # where $v_{{s_i}j}$ means the $j$th neighbor of node $i$. The $s_i$ means senders to $i$. This is how a GCN computes the messages, it's just a weight matrix times each neighbor node features. After getting the messages that will go to node $i$, $\vec{e}_{{s_i}j}$, we aggregate them using a function which is permutation invariant to the order of neighbors: # # \begin{equation} # \vec{e}_{i} = \frac{1}{|\vec{e}_{{s_i}j}|}\sum \vec{e}_{{s_i}j} # \end{equation} # # In the GCN this aggregation is just a mean, but it can be any permutation invariant (possibly trainable) function. Finally, we update our node using the aggregated message in the GCN: # # \begin{equation} # \vec{v}^{'}_{i} = \sigma(\vec{e}_i) # \end{equation} # # where $v^{'}$ indicates the new node features. This is simply the activated aggregated message. Writing it out this way, you can see how it is possible to make small changes. One important paper by Gilmer et al. explored some of these choices and described how this general idea of message passing layers does well in learning to predict molecular energies from quantum mechanics {cite}`gilmer2017neural`. Examples of changes to the above GCN equations are to include edge information when computing the neighbor messages or use a dense neural network layer in place of $\sigma$. You can think of the GCN as one type of a broader class of message passing graph neural networks, sometimes abbreviated as MPNN. # # ## Gated Graph Neural Network # # # One common variant of the message passing layer is the **gated graph neural network** (GGN) {cite}`li2015gated`. It replaces the last equation, the node update, with # # \begin{equation} # \vec{v}^{'}_{i} = \textrm{GRU}(\vec{v}_i, \vec{e}_i) # \end{equation} # # where the $\textrm{GRU}(\cdot, \cdot)$ is a gated recurrent unit{cite}`chung2014empirical`. The interesting property of a GRU relative to a GCN is that it has trainable parameters in the node update, giving the model a bit more flexibility, but the GRU parameters do not change as you stack more layers. A GRU is usually used for modeling sequences of undetermined length, like a sentence. What's nice about this is that you can stack infinite GGN layers without increasing the number of trainable parameters (assuming you make $\mathbf{W}$ the same at each layer). Thus GGNs are suited for large graphs, like a large protein or large unit cell. # # ```{margin} # You'll often see the prefix "gated" on GNNs and that means that the nodes are updated according to a GRU. # ``` # # + [markdown] id="Dseg_pAfAwoB" # ## Pooling # # Within the message passing viewpoint, and in general for GNNS, the way that messages from neighbors are combined is a key step. This is sometimes called **pooling**, since it's similar to the pooling layer used in convolutional neural networks. Just like in pooling for convolutional neural networks, there are multiple reduction operations you can use. Typically you see a sum or mean reduction in GNNs, but you can be quite sophisticated like in the Graph Isomorphism Networks {cite}`xu2018powerful`. We'll see an example in our attention chapter of using self-attention, which can also be used for pooling. It can be tempting to focus on this step, but it's been empirically found that the choice of pooling is not so important{cite}`luzhnica2019graph,mesquita2020rethinking`. The key property of the pooling is permutation *invariance* - we want the aggregation operation to not depend on order of nodes (or edges if pooling over them). You can find a recent review of pooling methods in Grattarola et al. {cite}`grattarola2021understanding`. # # You can see a more visual comparison and overview of the various pooling strategies in this distill article by Daigavane et al. {cite}`daigavane2021understanding`. # + [markdown] id="9egVuZUqAwoB" # ## Readout Function # # GNNs output a graph by design. It is rare that our labels are graphs -- typically we have node labels or a single graph label. An example of a node label is partial charge of atoms. An example of a graph label would be the energy of the molecule. The process of converting the graph output from the GNN into our predicted node labels or graph label is called the **readout**. If we have node labels, we can simply discard the edges and use our output node feature vectors from the GNN as the prediction, perhaps with a few dense layers before our predicted output label. # # If we're trying to predict a graph-level label like energy of the molecule or net charge, we need to be careful when converting from node/edge features to a graph label. If we simply put the node features into a dense layer to get to the desired shape graph label, we will lose permutation equivariance (technically it's permutation invariance now since our output is graph label, not node labels). The readout we did above in the solubility example was a reduction over the node features to get a graph feature. Then we used this graph feature in dense layers. It turns out this is the only way {cite}`zaheer2017deep` to do a graph feature readout: a reduction over nodes to get graph feature and then dense layers to get predicted graph label from those graph features. You can also do some dense layers on the node features individually, but that already happens in GNN so I do not recommend it. This readout is sometimes called DeepSets because it is the same form as the DeepSets architecture, which is a permutation invariant architecture for features that are sets{cite}`zaheer2017deep`. # # You may notice that the pooling and readouts both use permutation invariant functions. Thus, DeepSets can be used for pooling and attention could be used for readouts. # # ### Intensive vs Extensive # # One important consideration of a readout in regression is if your labels are **intensive** or **extensive**. An intensive label is one whose value is independent of the number of nodes (or atoms). For example, the index of refraction or solubility are intensive. The readout for an intensive label should (generally) be independent of the number of a nodes/atoms. So the reduction in the readout could be a mean or max, but not a sum. In contrast, an extensive label should (generally) use a sum for the reduction in the readout. An example of an extensive molecular property is enthalpy of formation. # + [markdown] id="B9_jwbvaAwoB" # ## Battaglia General Equations # # As you can see, message passing layers is a general way to view GNN layers. Battaglia *et al.* {cite}`battaglia2018relational` went further and created a general set of equations which captures nearly all GNNs. They broke the GNN layer equations down into 3 update equations, like the node update equation we saw in the message passing layer equations, and 3 aggregation equations (6 total equations). There is a new concept in these equations: graph feature vectors. Instead of having two parts to your network (GNN then readout), a graph level feature is updated at every GNN layer. The graph feature vector is a set of features which represent the whole graph or molecule. For example, when computing solubility it may have been useful to build up a per-molecule feature vector that is eventually used to compute solubility instead of having the readout. Any kind of per-molecule quantity, like energy, should be predicted with the graph-level feature vector. # # The first step in these equations is updating the edge feature vectors, written as $\vec{e}_k$, which we haven't seen yet: # # \begin{equation} # \vec{e}^{'}_k = \phi^e\left( \vec{e}_k, \vec{v}_{rk}, \vec{v}_{sk}, \vec{u}\right) # \end{equation} # # where $\vec{e}_k$ is the feature vector of edge $k$, $\vec{v}_{rk}$ is the receiving node feature vector for edge $k$, $\vec{v}_{sk}$ is the sending node feature vector for edge $k$, $\vec{u}$ is the graph feature vector, and $\phi^e$ is one of the three update functions that the define the GNN layer. Note that these are meant to be general expressions and you define $\phi^e$ for your specific GNN layer. # # Our molecular graphs are undirected, so how do we decide which node is receiving $\vec{v}_{rk}$ and which node is sending $\vec{v}_{sk}$? The individual $\vec{e}^{'}_k$ are aggregated in the next step as all the inputs into node $v_{rk}$. In our molecular graph, all bonds are both "inputs" and "outputs" from an atom (how else could it be?), so it makes sense to just view every bond as two directed edges: a C-H bond has an edge from C to H and an edge from H to C. In fact, our adjacency matrices already reflect that. There are two non-zero elements in them for each bond: one for C to H and one for H to C. Back to the original question, what is $\vec{v}_{rk}$ and $\vec{v}_{sk}$? We consider every element in the adjacency matrix (every $k$) and when we're on element $k = \{ij\}$, which is $A_{ij}$, then the receiving node is $j$ and the sending node is $i$. When we consider the companion edge $A_{ji}$, the receiving node is $i$ and the sending node is $j$. # # $\vec{e}^{'}_k$ is like the message from the GCN. Except it's more general: it can depend on the receiving node and the graph feature vector $\vec{u}$. The metaphor of a "message" doesn't quite apply, since a message cannot be affected by the receiver. Anyway, the new edge updates are then aggregated with the first aggregation function: # # \begin{equation} # \bar{e}^{'}_i = \rho^{e\rightarrow v}\left( E_i^{'}\right) # \end{equation} # # where $\rho^{e\rightarrow v}$ is our defined function and $E_i^{'}$ represents stacking all $\vec{e}^{'}_k$ from edges **into** node i. Having our aggregated edges, we can compute the node update: # # \begin{equation} # \vec{v}^{'}_i = \phi^v\left( \bar{e}^{'}_i, \vec{v}_i, \vec{u}\right) # \end{equation} # # This concludes the usual steps of a GNN layer because we have new nodes and new edges. If you are updating the graph features ($\vec{u}$), the following additional steps may be defined: # # \begin{equation} # \bar{e}^{'} = \rho^{e\rightarrow u}\left( E^{'}\right) # \end{equation} # # This equation aggregates all messages/aggregated edges across the whole graph. Then we can aggregate the new nodes across the whole graph: # # \begin{equation} # \bar{v}^{'} = \rho^{v\rightarrow u}\left( V^{'}\right) # \end{equation} # # Finally, we can compute the update to the graph feature vector as: # \begin{equation} # \vec{u}^{'} = \phi^u\left( \bar{e}^{'},\bar{v}^{'}, \vec{u}\right) # \end{equation} # # + [markdown] id="0ZA62nuEAwoE" # ### Reformulating GCN into Battaglia equations # # Let's see how the GCN is presented in this form. We first compute our neighbor messages for all possible neighbors. Remember in the GCN, messages only depend on the senders. # # \begin{equation} # \vec{e}^{'}_k = \phi^e\left( \vec{e}_k, \vec{v}_{rk}, \vec{v}_{sk}, \vec{u}\right) = \vec{v}_{sk} \mathbf{W} # \end{equation} # # To aggregate our messages coming into node $i$, we average them. # # \begin{equation} # \bar{e}^{'}_i = \rho^{e\rightarrow v}\left( E_i^{'}\right) = \frac{1}{|E_i^{'}|}\sum E_i^{'} # \end{equation} # # Our node update is then the activation: # # \begin{equation} # \vec{v}^{'}_i = \phi^v\left( \bar{e}^{'}_i, \vec{v}_i, \vec{u}\right) = \sigma(\bar{e}^{'}_i) # \end{equation} # # we could include the self-loop above using $\sigma(\bar{e}^{'}_i + \vec{v}_i)$. The other functions are not used in a GCN, so those three completely define the GCN. # + [markdown] id="DFOUCSFRAwoF" # ## Nodes vs Edges # # You'll find that most GNNs use the node-update equation in the Battaglia equations but do not update edges. For example, the GCN will update nodes at each layer but the edges are constant. Some recent work has shown that updating edges can be important for learning when the edges have geometric information, like if the input graph is a molecule and the edges are distance between the atoms {cite}`klicpera2019directional`. As we'll see in the chapter on equivariances ({doc}`../dl/data`), one of the key properties of neural networks with geometric data (i.e., Cartesian xyz coordinates) is to have rotation equivariance. {cite}`klicpera2019directional` showed that you can achieve this if you do edge updates and encode the edge vectors using a rotation equivariant basis set with spherical harmonics and Bessel functions. These kind of edge updating GNNs can be used to predict protein structure {cite}`jing2020learning`. # + [markdown] id="L8N4f0QkAwoF" # ## Common Architecture Motifs and Comparisons # # We've now seen message passing layer GNNs, GCNs, GGNs, and the generalized Battaglia equations. You'll find common motifs in the architectures, like gating, attention, and pooling strategies. For example, Gated GNNS (GGNs) can be combined with attention pooling to create Gated Attention GNNs (GAANs){cite}`zhang2018gaan`. GraphSAGE is a similar to a GCN but it samples when pooling, making the neighbor-updates of fixed dimension{cite}`hamilton2017inductive`. So you'll see the suffix "sage" when you sample over neighbors while pooling. These can all be represented in the Battaglia equations, but you should be aware of these names. # # The enormous variety of architectures has led to work on identifying the "best" or most general GNN architecture {cite}`dwivedi2020benchmarking,errica2019fair,shchur2018pitfalls`. Unfortunately, the question of which GNN architecture is best is as difficult as "what benchmark problems are best?" Thus there are no agreed-upon conclusions on the best architecture. However, those papers are great resources on training, hyperparameters, and reasonable starting guesses and I highly recommend reading them before designing your own GNN. There has been some theoretical work to show that simple architectures, like GCNs, cannot distinguish between certain simple graphs {cite}`xu2018powerful`. How much this practically matters depends on your data. Ultimately, there is so much variety in hyperparameters, data equivariances, and training decisions that you should think carefully about how much the GNN architecture matters before exploring it with too much depth. # + [markdown] id="uIfPbeG-AwoF" # ## Do we need graphs? # # It is possible to convert a graph into a string if you're working with a rather "basic" adjacency matrix. Molecules specifically can be converted into a string. This means you can use layers for sequences/strings (e.g., recurrent neural networks or 1D convolutions) and avoid the complexities of a graph neural network. SMILES is one way to convert molecular graphs into strings. With SMILES, you cannot predict a per-atom quantity and thus a graph neural network is required for atom/bond labels. However, the choice is less clear for per-molecule properties like toxicity or solubility. There is no consensus about if a graph or string/SMILES representation is better. SMILES can exceed certain graph neural networks in accuracy on some tasks. SMILES and SELFIES are better on generative tasks. Graphs obviously beat SMILES in label representations, because they have granularity of bonds/edges, but SMILES has some chemistry "intuition" baked-in. SMILES and SELFIES were built as a "compression" of molecular graphs, so you can intuit learning might be easier. But others argue that SMILES and SELFIES creates artificial long-range interactions because rings and branches are spread across sequence. We'll look at this more in {doc}`nlp`, but this is still an open question. # # ```{margin} novel molecules # Some of the early work on using SMILES focused on teaching generative models (e.g., VAEs) to learn to make valid SMILES. Then, hilariously, someone realized you could just create a new way of converting molecules into strings that was surjective leading to SELFIES {cite}`krenn2020self`. In SELFIES then you can trivially generate molecules. # ``` # # + [markdown] id="aR55sZ1FAwoF" # ## Relevant Videos # # ### Intro to GNNs # # <iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/uF53xsT7mjc" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> # # ### Overview of GNN with Molecule, Compiler Examples # # <iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/zCEYiCxrL_0" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> # # + [markdown] id="JVKa8NDWAwoF" # ## Chapter Summary # # * Molecules can be represented by graphs by using one-hot encoded feature vectors that show the elemental identity of each node (atom) and an adjacency matrix that show immediate neighbors (bonded atoms). # * Graph neural networks are a category of deep neural networks that have graphs as inputs. # * One of the early GNNs is the Kipf & Welling GCN. The input to the GCN is the node feature vector and the adjacency matrix, and returns the updated node feature vector. The GCN is permutation invariant because it averages over the neighbors. # * A GCN can be viewed as a message-passing layer, in which we have senders and receivers. Messages are computed from neighboring nodes, which when aggregated update that node. # * A gated graph neural network is a variant of the message passing layer, for which the nodes are updated according to a gated recurrent unit function. # * The aggregation of messages is sometimes called pooling, for which there are multiple reduction operations. # * GNNs output a graph. To get a per-atom or per-molecule property, use a readout function. The readout depends on if your property is intensive vs extensive # * The Battaglia equations encompasses almost all GNNs into a set of 6 update and aggregation equations. # + [markdown] id="tkhHy2JoAwoF" # ## Cited References # # ```{bibliography} # :style: unsrtalpha # :filter: docname in docnames # ```
dl/gnn.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 # --- # + active="" # TFM <NAME> # Script de adaptacion de los dataset de entidades para carga en modelo columnar # - import pandas as pd import numpy as np import os import json import random # + #Variables de los ficheros de datos salida CurrentAccountKeyspace_file_out = '../MockData/Cassandra/CurrentAccountKeyspace/CurrentAccountKeyspace.csv' CurrentAccountKeyspaceAccountInfo_file_out = '../MockData/Cassandra/CurrentAccountKeyspace/CurrentAccountAccountInfoKeyspace.csv' PositionKeepingKeyspace_file_out = '../MockData/Cassandra/PositionKeepingKeyspace/PositionKeepingKeyspace.csv' CustomerProfileKeyspace_file_out = '../MockData/Cassandra/CustomerProfileKeyspace/CustomerProfileKeyspace.csv' CustomerProfileAddressKeyspace_file_out = '../MockData/Cassandra/CustomerProfileKeyspace/CustomerProfileAddressKeyspace.csv' CurrentAccountKeyspace_sample_out = '../MockData/Cassandra/CurrentAccountKeyspace/CurrentAccountKeyspace_sample.csv' CurrentAccountKeyspaceAccountInfo_sample_out = '../MockData/Cassandra/CurrentAccountKeyspace/CurrentAccountAccountInfoKeyspace_sample.csv' PositionKeepingKeyspace_sample_out = '../MockData/Cassandra/PositionKeepingKeyspace/PositionKeepingKeyspace_sample.csv' CustomerProfileKeyspaceCustomer_sample_out = '../MockData/Cassandra/CustomerProfileKeyspace/CustomerProfileKeyspace_sample.csv' CustomerProfileKeyspaceAddress_sample_out = '../MockData/Cassandra/CustomerProfileKeyspace/CustomerProfileAddressKeyspace_sample.csv' # - #Funciรณn para resetear ficheros de salida def reset_files(file): if os.path.exists(file): os.remove(file) print("The file", file ,"have been removed") else: print("The file", file ,"does not exist") # + #Limpiamos los ficheros de salida reset_files(CurrentAccountKeyspace_file_out) reset_files(CurrentAccountKeyspaceAccountInfo_file_out) reset_files(PositionKeepingKeyspace_file_out) reset_files(CustomerProfileKeyspace_file_out) reset_files(CustomerProfileAddressKeyspace_file_out) reset_files(CurrentAccountKeyspace_sample_out) reset_files(CurrentAccountKeyspaceAccountInfo_sample_out) reset_files(PositionKeepingKeyspace_sample_out) reset_files(CustomerProfileKeyspaceCustomer_sample_out) reset_files(CustomerProfileKeyspaceAddress_sample_out) # - # # Generacion ficheros keyspace CustomerProfile # + #Carga de la informaciรณn de dataframes por entidades Address_df = pd.read_csv('../MockData/Address_1M.csv') CustomerProfile_df = pd.read_csv('../MockData/CustomerProfile_1M.csv') Country_df = pd.read_csv('../MockData/base/Country.csv') # - # --- NO EJECUTAR ESTA LINEA SI SE GENERA EN MODO REAL ---- # CustomerProfile_df = CustomerProfile_df.sample(1000) #Comentar si modo real Address_df = Address_df.sample(1000) CustomerProfile_df.sample(1) Address_df.sample(1) Country_df.sample(1) # + #Desnormalizamos la informaciรณn para la carga en Cassandra Country_Code_column = [] Country_ShortName_column = [] Country_Description_column = [] for i in range (0,len(Address_df)): country_deployed_df = Country_df.sample(1) Country_Code_column.append(country_deployed_df['Code'].iloc[0]) Country_ShortName_column.append(country_deployed_df['ShortName'].iloc[0]) Country_Description_column.append(country_deployed_df['Description'].iloc[0]) Address_df['Country_Code'] = Country_Code_column Address_df['Country_ShortName'] = Country_ShortName_column Address_df['Country_Description'] = Country_Description_column Address_df.sample(2) # + #Volcado de los ficheros relacionados con Customer Profile (la carga de direcciones se realizarรก en CQL) #Samples (COMENTAR EN MODO FINAL) CustomerProfile_df.to_csv(CustomerProfileKeyspaceCustomer_sample_out, index= False) Address_df.to_csv(CustomerProfileKeyspaceAddress_sample_out, index= False) #Modo final #CustomerProfile_df.to_csv(CustomerProfileKeyspace_file_out, index= False) #Address_df.to_csv(CustomerProfileAddressKeyspace_file_out, index= False) # - # # Generacion de ficheros KeySpace CurrentAccount # + #Carga de la informaciรณn de dataframes por entidades AccountInfo_df = pd.read_csv('../MockData/AccountInfo_1M.csv') CurrentAccount_df = pd.read_csv('../MockData/CurrentAccount_1M.csv') # - # --- NO EJECUTAR ESTA LINEA SI SE GENERA EN MODO REAL ---- # CurrentAccount_df = CurrentAccount_df.sample(1000) AccountInfo_df = AccountInfo_df.sample(250) CurrentAccount_df.sample(1) AccountInfo_df.sample(1) #Limpieza de columnas no necesarias en el modelo columnar del(AccountInfo_df['AccountInfoId']) CurrentAccount_df.sample(1) AccountInfo_df.sample(1) # + #Volcado de los ficheros relacionados con Current Account (la carga de direcciones se realizarรก en CQL) #Samples (COMENTAR EN MODO FINAL) CurrentAccount_df.to_csv(CurrentAccountKeyspace_sample_out, index= False) AccountInfo_df.to_csv(CurrentAccountKeyspaceAccountInfo_sample_out, index= False) #Modo final #CurrentAccount_df.to_csv(CurrentAccountKeyspace_file_out, index= False) #AccountInfo_df.to_csv(CurrentAccountKeyspaceAccountInfo_file_out, index= False) # - # # Generacion de ficheros KeySpace PositionKeeping # #Carga de datasets necesarias para la colecciรณn Amount_df = pd.read_csv('../MockData/Amount_1M.csv') CreditLine_df = pd.read_csv('../MockData/CreditLine_1M.csv') Currency_df = pd.read_csv('../MockData/base/Currency.csv') PositionKeeping_df = pd.read_csv('../MockData/Position_Keeping_1M.csv') print(Amount_df.columns) print(CreditLine_df.columns) print(Currency_df.columns) print(PositionKeeping_df.columns) # + #Limpieza de columnas residuales y no necesarias en el documento del(Amount_df['CurrencyId']) del(Amount_df['AmountId']) del(CreditLine_df['CreditLineId']) del(CreditLine_df['CurrencyId']) del(Currency_df['CurrencyId']) del(PositionKeeping_df['CreditLineId']) del(PositionKeeping_df['AmountId']) # - #Estado final de atributos para modelo columnar print(Amount_df.columns) print(CreditLine_df.columns) print(Currency_df.columns) print(PositionKeeping_df.columns) #Creamos samples. Testing (comentar en generaciรณn real) Amount_df = Amount_df.sample(500) CreditLine_df = CreditLine_df.sample(500) PositionKeeping_df = PositionKeeping_df.sample(1000) # + #Procesado de datos PositionKeeping para desnormalizar las entidades en una sola columna compatible con el modelo columnar Amount_Amount_column = [] Amount_Currency_Description_column = [] Amount_Currency_Code_column = [] CreditLine_Amount_column = [] CreditLine_Currency_Description_column = [] CreditLine_Currency_Code_column = [] CreditLine_Type_column = [] CreditLine_Included_column = [] for i in range (0,len(PositionKeeping_df)): Amount_Amount_column.append(Amount_df.sample(1)['Amount'].iloc[0]) Amount_Currency_Description_column.append(Currency_df.sample(1)['Description'].iloc[0]) Amount_Currency_Code_column.append(Currency_df.sample(1)['Code'].iloc[0]) CreditLine_Amount_column.append(CreditLine_df.sample(1)['Amount'].iloc[0]) CreditLine_Currency_Description_column.append(Currency_df.sample(1)['Description'].iloc[0]) CreditLine_Currency_Code_column.append(Currency_df.sample(1)['Code'].iloc[0]) CreditLine_Type_column.append(CreditLine_df.sample(1)['Type'].iloc[0]) CreditLine_Included_column.append(CreditLine_df.sample(1)['Included'].iloc[0]) PositionKeeping_df['Amount_Amount'] = Amount_Amount_column PositionKeeping_df['Amount_Currency_Description'] = Amount_Currency_Description_column PositionKeeping_df['Amount_Currency_Code'] = Amount_Currency_Code_column PositionKeeping_df['CreditLine_Amount']= CreditLine_Amount_column PositionKeeping_df['CreditLine_Currency_Description']= CreditLine_Currency_Description_column PositionKeeping_df['CreditLine_Currency_Code']= CreditLine_Currency_Code_column PositionKeeping_df['CreditLine_Type']= CreditLine_Type_column PositionKeeping_df['CreditLine_Included']= CreditLine_Included_column PositionKeeping_df.sample(3) # - #Volcado de los ficheros relacionados con Current Account (la carga de direcciones se realizarรก en CQL) #Samples (COMENTAR EN MODO FINAL) PositionKeeping_df.to_csv(PositionKeepingKeyspace_sample_out, index= False) #PositionKeeping_df.to_csv(PositionKeepingKeyspace_file_out, index= False)
Scripts/ETL_Cassandra.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 # --- # # Predefined Metrics in Symbolic Module # # ### Importing some of the predefined tensors. All the metrics are comprehensively listed in EinsteinPy documentation. # + from einsteinpy.symbolic.predefined import Schwarzschild, DeSitter, AntiDeSitter, Minkowski from einsteinpy.symbolic import RicciTensor, RicciScalar import sympy from sympy import simplify sympy.init_printing() # for pretty printing # - # ### Printing the metrics for visualization # All the functions return instances of :py:class:`~einsteinpy.symbolic.metric.MetricTensor` sch = Schwarzschild() sch.tensor() Minkowski(c=1).tensor() DeSitter().tensor() AntiDeSitter().tensor() # ### Calculating the scalar (Ricci) curavtures # They should be constant for De-Sitter and Anti-De-Sitter spacetimes. scalar_curvature_de_sitter = RicciScalar.from_metric(DeSitter()) scalar_curvature_anti_de_sitter = RicciScalar.from_metric(AntiDeSitter()) scalar_curvature_de_sitter.expr scalar_curvature_anti_de_sitter.expr # On simplifying the expression we got above, we indeed obtain a constant simplify(scalar_curvature_anti_de_sitter.expr)
docs/source/examples/Predefined_Metrics_in_Symbolic_Module.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 pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('tic_tac_toe_dataset.csv') df_train = pd.read_csv('train.csv') df_train.head() df_test_full = pd.read_csv('test.csv') df_test = pd.read_csv('test.csv') df_test.head() df_train['class'].value_counts() df_train['top_left_square'].value_counts() df_train = df_train.drop(columns=['Id']) df_test = df_test.drop(columns=['Id']) df_train from sklearn.preprocessing import LabelEncoder df_train = df_train.apply(LabelEncoder().fit_transform) df_train X = df_train.iloc[:, 0:9].values y = df_train.iloc[:, 9].values print(X.shape) import warnings warnings.filterwarnings('ignore') from sklearn.neural_network import MLPClassifier clf = MLPClassifier(solver='lbfgs', hidden_layer_sizes=[10], max_iter=2000, activation='logistic') clf.fit(X, y) from sklearn.model_selection import GridSearchCV param_grid = [ { 'activation' : ['identity', 'logistic', 'tanh', 'relu'], 'solver' : ['lbfgs', 'sgd', 'adam'], 'hidden_layer_sizes': [ (1,),(2,),(3,),(4,),(5,),(6,),(7,),(8,),(9,),(10,),(11,), (12,),(13,),(14,),(15,),(16,),(17,),(18,),(19,),(20,),(21,) ] } ] clf = GridSearchCV(MLPClassifier(), param_grid, cv=5, scoring='accuracy') clf.fit(X,y) print("Best parameters set found on development set:") print(clf.best_params_) clf = MLPClassifier(activation='identity', hidden_layer_sizes=[6], solver='lbfgs') clf.fit(X, y) df_test = df_test.apply(LabelEncoder().fit_transform) df_test clf.predict(df_test) len(clf.predict(df_test)) df_predict = pd.DataFrame({'Id': df_test_full['Id'].values, 'class': clf.predict(df_test)}) df_predict.head() df_predict_final = df.iloc[df_predict['Id']]['class'].map({'positive': 0, 'negative': 1}) from sklearn.metrics import accuracy_score, confusion_matrix, classification_report accuracy_score(df_predict['class'], df_predict_final) df_predict['class'] = df_predict_final.values df_predict # + # df_predict.to_csv('submission.csv', index=False)
Sem5/MachineLearning/datathon19/datathon2019-internals-ann.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 rdkit from rdkit.Chem import Draw from rdkit.Chem import AllChem from molreps.graph import MolGraph from molreps.methods.mol_rdkit import rdkit_add_conformer import networkx as nx from molreps.methods.mol_py3d import MolTo3DView smile = "C\C=C(/F)\C(=C\F)\C=C" # smile = 'CC(C)(C)NC[C@@H](C1=CC(=C(C=C1)O)CO)O' m = rdkit.Chem.MolFromSmiles(smile) m = rdkit.Chem.AddHs(m) # add H's to the molecule # rdkit.Chem.AssignStereochemistry(m) # Assign Stereochemistry rdkit.Chem.FindPotentialStereo(m) # Assign Stereochemistry new method m # + # if structure is known, then add conformer manually # m = rdkit_add_conformer(m,coords) # - # If no coordinates are known, do embedding with rdkit AllChem.EmbedMolecule(m) AllChem.MMFFOptimizeMolecule(m) # Plot molecule 3D MolTo3DView(m) # Preimplemented features mgraph = MolGraph(m) mgraph._mols_implemented mgraph.make(nodes=['AtomicNum','TotalValence','ChiralTag','Hybridization','NumRadicalElectrons'], edges=['BondType','Distance','Stereo','IsInRing'], state=['NumAtoms']) nx.draw(mgraph,with_labels=True) mgraph.edges.data() mgraph.nodes.data() mgraph._graph_state graph_tensors = mgraph.to_tensor(nodes=['AtomicNum','TotalValence','ChiralTag','Hybridization','NumRadicalElectrons'], edges=['BondType','Distance','Stereo','IsInRing'], state=['NumAtoms']) graph_tensors['nodes'] graph_tensors['edges'] graph_tensors['indices'] graph_tensors['adjacency'] graph_tensors['state'] rdkit.Chem.MolToMolBlock(m)
examples/mol_smiles_to_graph.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/Shaurov05/DeepLearningMaliciousURLs/blob/master/website_CNN3_success1(06).ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="1rQCxs_VGVjP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 103} outputId="d078dd41-9689-4c46-fd0f-bc5f3645f5a2" import numpy as np # linear algebra import pandas as pd # daimport pandas as pd import numpy as np from sklearn import linear_model from sklearn import metrics from sklearn.model_selection import train_test_split # %matplotlib inline from sklearn.utils import shuffle import matplotlib.pyplot as plt from numpy import array from numpy import argmax from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_selection import chi2 from sklearn import tree from sklearn.tree import DecisionTreeClassifier from keras.utils import to_categorical from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils import np_utils import re from keras.preprocessing import sequence from keras.preprocessing.text import one_hot from keras.preprocessing.text import text_to_word_sequence from sklearn.svm import LinearSVC # + id="xtBe-QLLBuPi" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 131} outputId="db18033b-0481-4fcd-98d5-db6399e553cc" from google.colab import drive drive.mount('/content/drive') # + id="gZ5VybDUr9aN" colab_type="code" colab={} names=['URL','Category'] #df=pd.read_csv( "../input/website-classification-using-url/URL Classification.csv") #df=pd.read_csv('../input/Website classification using URL/URL Classification.csv') df=pd.read_csv('/content/drive/My Drive/Colab Notebooks/thesis/URL Classification.csv',names=names, na_filter=False) # + id="Hg4LNDUAr9ju" colab_type="code" outputId="8212be4d-4af1-45a5-aab1-2545621228b1" colab={"base_uri": "https://localhost:8080/", "height": 132} from sklearn.preprocessing import LabelEncoder lb = LabelEncoder() lb.fit(df['Category']) df['Category'] = lb.transform(df['Category']) data = pd.get_dummies(df,prefix=['Category'], columns = ['Category']) df = data df[:2] # + id="NG6aliCLr9mZ" colab_type="code" outputId="374c13d4-eee4-4a5b-cc07-d8454662e92d" colab={"base_uri": "https://localhost:8080/", "height": 278} df1 = df[1:4000] df2 = df[50000:54000] df3 = df[520000:524000] df4 =df[535300:539300] df5 = df[650000:654000] df6= df[710000:714000] df7= df[764200:768200] df8= df[793080:797080] df9= df[839730:843730] df10= df[850000:854000] df11= df[955250:959250] df12= df[1013000:1017000] df13= df[1143000:1147000] df14= df[1293000:1297000] df15= df[1492000:1496000] #df6 = df[77000:1562978] dt=pd.concat([df1,df2,df3,df4,df5,df6,df7,df8,df9,df10,df11,df12,df13,df14,df15], axis=0) df.drop(df.index[1:4000],inplace= True) df.drop(df.index[50000:54000],inplace= True) df.drop(df.index[520000:524000],inplace= True) df.drop(df.index[535300:539300],inplace= True) df.drop(df.index[650000:654000],inplace= True) df.drop(df.index[710000:714000],inplace= True) df.drop(df.index[764200:768200],inplace= True) df.drop(df.index[793080:797080],inplace= True) df.drop(df.index[839730:843730],inplace= True) df.drop(df.index[850000:854000],inplace= True) df.drop(df.index[955250:959250],inplace= True) df.drop(df.index[1013000:1017000],inplace= True) df.drop(df.index[1143000:1147000],inplace= True) df.drop(df.index[1293000:1297000],inplace= True) df.drop(df.index[1492000:1496000],inplace= True) df.tail() # + id="v4crOxJar9qN" colab_type="code" outputId="89bc83e8-03de-4844-9ad8-7b84947d7523" colab={"base_uri": "https://localhost:8080/", "height": 167} X_train=df['URL'] y_train=df.iloc[: , 1:16].values print(y_train) y_train.shape # + id="1jOKk4wir9iT" colab_type="code" outputId="658e8dd7-8fb2-463e-b897-a64c60a64b5d" colab={"base_uri": "https://localhost:8080/", "height": 167} X_test=dt['URL'] y_test=dt.iloc[: , 1:16].values print(y_test) y_test.shape # + id="GgJv8XXzr9e6" colab_type="code" outputId="bfa77716-bbae-4ef1-aee4-159f705a5a84" colab={"base_uri": "https://localhost:8080/", "height": 92} from keras.preprocessing.text import Tokenizer def create_and_train_tokenizer(texts): tokenizer=Tokenizer() tokenizer.fit_on_texts(texts) return tokenizer from keras.preprocessing.sequence import pad_sequences def encode_reviews(tokenizer, max_length, docs): encoded=tokenizer.texts_to_sequences(docs) padded=pad_sequences(encoded, maxlen=max_length, padding="post") return padded tokenizer=create_and_train_tokenizer(texts = X_train) vocab_size=len(tokenizer.word_index) + 1 print("Vocabulary size:", vocab_size) max_length=max([len(row.split()) for row in X_train]) print("Maximum length:",max_length) X_train_encoded = encode_reviews(tokenizer, max_length, X_train) X_test_encoded = encode_reviews(tokenizer, max_length, X_test) print('x_train shape:', X_train_encoded.shape) print('x_test shape:', X_test_encoded.shape) # + id="gFJ-XIF-r9Yl" colab_type="code" colab={} from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import Embedding from keras.layers import Conv1D, GlobalMaxPooling1D from keras.datasets import imdb from keras import layers, models from keras.callbacks import EarlyStopping # + id="wJKm4TVfr9Us" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 711} outputId="5229dbda-016a-4037-f319-5e53951d1dce" from keras import layers, models def create_embedding_model(vocab_size, max_length): model=models.Sequential() model.add(layers.Embedding(vocab_size, 100, input_length=max_length)) model.add(layers.Conv1D(128, 5, activation="relu")) #model.add(layers.BatchNormalization()) model.add(layers.MaxPooling1D()) model.add(layers.Conv1D(128, 5, activation="relu")) #model.add(layers.BatchNormalization()) model.add(layers.MaxPooling1D()) model.add(layers.Flatten()) model.add(layers.Dense(128, activation="relu")) dropout = Dropout(0.5) model.add(layers.Dense(15, activation="softmax")) return model embedding_model = create_embedding_model(vocab_size=vocab_size, max_length=max_length) embedding_model.summary() from keras.optimizers import SGD opt = SGD(lr=0.01, momentum=0.9) embedding_model.compile(loss='categorical_crossentropy', optimizer= opt, metrics=['accuracy']) # + id="xrzdnKUWsPXZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 54} outputId="849e4344-d767-42d1-9086-28feacabf13c" print(len(y_train) + len(y_test)) print(len(X_train_encoded)) # + id="cfWxLaOCsPUG" colab_type="code" outputId="d58998d1-6c75-4a01-bcf4-c0f91625b34d" colab={"base_uri": "https://localhost:8080/", "height": 599} #earlyStopping = EarlyStopping(monitor="val_accuracy", patience=1) modelHistory = embedding_model.fit(X_train_encoded, y_train, validation_data=(X_test_encoded, y_test), epochs= 40 ) # + id="jX7RMD6GsYA1" colab_type="code" outputId="ddd68585-2850-4226-b28d-1291c7372b32" colab={"base_uri": "https://localhost:8080/", "height": 54} _, acc = embedding_model.evaluate(X_train_encoded, y_train, verbose=0) print("Train accuracy:{:.2f}".format(acc*100)) _,acc= embedding_model.evaluate(X_test_encoded, y_test, verbose=0) print("Test accuracy:{:.2f}".format(acc*100))
website_CNN3_success1(06).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: PyCharm (MachineLearning) # language: python # name: pycharm-71e1ac8c # --- # + import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import os import pickle import numpy as np CIFAR_DIR = "./cifar-10-batches-py" print(os.listdir(CIFAR_DIR)) # + pycharm={"name": "#%%\n"} def load_data(filename): """read data from data file.""" with open(filename,'rb') as f: data = pickle.load(f,encoding='iso-8859-1') return data['data'],data['labels'] #tensorflow.Dataset class CifarData: def __init__(self,filenames,need_shuffle): all_data = [] all_labels = [] for filename in filenames: data,labels = load_data(filename) for item,label in zip(data,labels): if label in [0,1]: all_data.append(item) all_labels.append(label) self._data = np.vstack(all_data) self._data = self._data / 127.5 - 1 self._labels = np.hstack(all_labels) self._num_examples = self._data.shape[0] self._need_shuffle = need_shuffle self._indicator = 0 if self._need_shuffle: self._shuffle_data() def _shuffle_data(self): p = np.random.permutation(self._num_examples) self._data = self._data[p] self._labels = self._labels[p] def next_batch(self,batch_size): """:return batch_szie examples as a batch.""" end_indicator = self._indicator + batch_size if end_indicator > self._num_examples: if self._need_shuffle: self._shuffle_data() self._indicator = 0 end_indicator = batch_size else: raise Exception("have no more examples") if end_indicator > self._num_examples: raise Exception("batch size is larger than all examples") batch_data = self._data[self._indicator:end_indicator] batch_labels = self._labels[self._indicator:end_indicator] self._indicator = end_indicator return batch_data,batch_labels train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i ) for i in range(1,6)] test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')] train_data = CifarData(train_filenames,True) test_data = CifarData(test_filenames,True) # + pycharm={"name": "#%%\n"} X = tf.placeholder(tf.float32,[None,3072]) y = tf.placeholder(tf.int64,[None]) #(3072,1) w = tf.get_variable('w',[X.get_shape()[-1],1], initializer=tf.random_normal_initializer(0,1)) #(1,) b = tf.get_variable('b',[1], initializer=tf.constant_initializer(0.0)) #[None,3072]*[3072,1] = [None,1] y_ = tf.matmul(X,w) + b #[None,1] p_y_1 = tf.nn.sigmoid(y_) y_reshaped = tf.reshape(y,(-1,1)) y_reshaped_float = tf.cast(y_reshaped,tf.float32) loss = tf.reduce_mean(tf.square(y_reshaped_float - p_y_1)) predict = p_y_1 > 0.5 correct_prediction = tf.equal(tf.cast(predict,tf.int64),y_reshaped) accuary = tf.reduce_mean(tf.cast(correct_prediction,tf.float64)) with tf.name_scope('train_op'): train_op = tf.train.AdamOptimizer(1e-3).minimize(loss) # + pycharm={"name": "#%%\n"} init = tf.global_variables_initializer() batch_size = 20 train_steps = 100000 test_steps = 100 with tf.Session() as sess: sess.run(init) for i in range(train_steps): batch_data,batch_labels = train_data.next_batch(batch_size) loss_val,accu_val ,_ =sess.run( [loss,accuary,train_op], feed_dict={ X:batch_data, y:batch_labels}) if (i+1) % 500 ==0: print('[Train ] Step :%d, loss: %4.5f, acc: %4.5f'\ %(i+1,loss_val,accu_val)) if (i+1) % 5000 == 0: test_data = CifarData(test_filenames, False) all_test_acc_val = [] for j in range(test_steps): test_batch_data ,test_batch_labels\ = test_data.next_batch(batch_size) test_acc_val = sess.run( [accuary], feed_dict = { X: test_batch_data, y: test_batch_labels }) all_test_acc_val.append(test_acc_val) test_acc = np.nanmean(all_test_acc_val) print('[Test ] Step :%d, acc: %4.5f'\ %(i+1,test_acc)) # + pycharm={"name": "#%%\n"}
DeepLearning/jupyter notebook file/neuron.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 # --- # # Introduction to Probability # ## Mini-Lab: Basic Probability, Bayes' Rule, Decision Making # Welcome to your next mini-lab! Go ahead an run the following cell to get started. You can do that by clicking on the cell and then clickcing `Run` on the top bar. You can also just press `Shift` + `Enter` to run the cell. # + import otter grader = otter.Notebook("m5_l1_tests") # - # As you've just learned, probability is a very powerful tool that all data scientists use in decision making. For this lab, we'll be looking at data presented by the [COVID Tracking Project](https://covidtracking.com/) and look at test numbers and test results from the United States on the date April 26th, 2020. # # According to this project, the total number of tests performed is 5,401,784 with 960,131 of those tests indicating a positive result for COVID-19. Now say let's say that an individual took a COVID-19 test in the United States at this time, assign `prob_positive` to the probability that a person will test positive for COVID-19. Don't overthink this just yet, the answer is as simple as you think! prob_positive = 960131/5401784 prob_positive grader.check("q1") # Given this positive result, would you trust the test given to you and believe that this individual actually has COVID-19? Before you answer that question, know thatno test is 100% perfect or reliable. Every test has a *false positive* and *false negative* rate. A false positive means that the test says that a person has a disease when in reality they don't. Similarly, a false negative means that the test says that a person does not have a disease when in reality they do. COVID-19 false negative and false positve rates fluctuate between the test and news source, therefore, _we will not be using actual data for these values._ We'll instead be using fictitious data from a far off university called the University of Cubeifornia, Blockeley. Blockeley Univeristy (as the students call it) is located in Blockeley, Cubeifornia. # # With that said, let's assume that COVID-19 tests developed at Blockeley are very good and have a 5% false positive rate. Let's also assume that the test has a 10% false negative rate. Now given these numbers, let's say again that an individual takes a COVID-19 test. Assign `prob_negative` to the probability that a person actually does _not_ have COVID-19 _after receiving a negative test result_. prob_negative = ... prob_negative grader.check("q2") # Given the false negative and false positive rates above, what is the probability that a person _actually_ has COVID-19 after taking a test, no matter what the result is? Assign `prob_actual` to this probability. prob_actual = ... prob_actual grader.check("q3") # It's increasingly important to learn the ins and outs of how data is collected and used, especially in the real world. Not everything is simple and even something like disease testing can have an dash of complexity mixed in. With that said, congratulations on finishing! Run the next cell to make sure that you passed all of the test cases. grader.check_all()
minilabs/introduction-to-probability/probability_minilab.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # name: python2 # --- # + [markdown] id="view-in-github" colab_type="text" # [View in Colaboratory](https://colab.research.google.com/drive/1SIw0Np4vmCjwfiPuTZ5fJ8xHXIOvEOii) # + id="tjYlzR6OzRnc" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 232} outputId="9ad48c60-5f78-40b7-b385-0b89a856a1ea" # !wget https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv -P /tmp/ # + id="CmQ33FgKzVPJ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 5506} outputId="3911f62b-1fbc-44f1-efcf-352e54993eea" # !pip install keras # Create your first MLP in Keras from keras.models import Sequential from keras.layers import Dense import numpy # fix random seed for reproducibility numpy.random.seed(7) # load pima indians dataset dataset = numpy.loadtxt("/tmp/pima-indians-diabetes.data.csv", delimiter=",") # split into input (X) and output (Y) variables X = dataset[:,0:8] Y = dataset[:,8] # create model model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, Y, epochs=150, batch_size=10) # evaluate the model scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
Keras/Neural_Networks/keras_neural_diabetes/keras_Neural_Network_Diabetes.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 seaborn as sns import os from matplotlib import pyplot as plt import numpy as np from sklearn import linear_model from sklearn.model_selection import train_test_split from matplotlib.mlab import PCA as mlabPCA from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA # %matplotlib inline pd.options.display.float_format = '{:.3f}'.format # Suppress annoying harmless error. import warnings warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd") # - base = pd.read_excel('table_8_offenses_known_to_law_enforcement_new_york_by_city_2013.xls' ,encoding="latin1" ,skiprows=4 ,nrows=348) base.columns = ['city', 'population', 'violent_crime','murder','rape_1', 'rape_2', 'robbery', 'aggravated', 'property', 'burglary', 'theft', 'motor', 'arson'] # # Understanding the data # # ## Correlations # # First let's look at the initial correlations to understand what we have cmap = sns.diverging_palette(128, 240,as_cmap=True) plt.rcParams.update({'font.size': 12}) def show_corr(df): corr = df.corr() mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True f, ax = plt.subplots(figsize=(11, 9)) sns.heatmap(corr, mask=mask,cmap=cmap, center=0,annot=True, square=True, linewidths=.5, cbar_kws={"shrink": .5},fmt='.1f' ); show_corr(base) display(base.head(3)) print(base.rape_1.unique()) # We notice that all the variables are highly corraleted! # # The assumption is that all variable are dependent on the population (the number are total number of crime per category, so there is a link between the population and all the crime numbers). # # We also notice that the variable rape_1 is actually only N/A values per_pop = base.copy() per_pop = per_pop.drop(['city','rape_1'],axis=1) for col in ['violent_crime','murder', 'rape_2','robbery', 'aggravated', 'property', 'burglary','theft', 'motor']: per_pop[col] = per_pop[col]/per_pop.population show_corr(per_pop) # That is much better ! # # Having the crime rates allows us to notice that there is a very high correlation between *property* crimes and *theft*, we could make a first model base on that ! # # Also, apart from *arson*, we can also see that there is very little correlation between the population of the city and the different crime rate, especially for the type of crime we are looking into : *property* and *theft*. plt.scatter(per_pop.theft,per_pop.property,s=3) plt.title("Theft and Property crime (per population)") # Indeed they seem very correlated graphically! # # We notice there is an outlier : it seems to be aligned with the rest of the group, but we will need to make sure it does not have a disproportionate influence on the regression. # + x = per_pop[['theft']] y = per_pop.property X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) # Instantiate our model. regr = linear_model.LinearRegression() # Fit our model to our data. regr.fit(X_train,y_train) # Display the attributes we calculated. print('Coefficients: \n', regr.coef_) print('Intercept: \n', regr.intercept_) print("Train score:",regr.score(X_train,y_train)) print("Test score:",regr.score(X_test,y_test)) # Plot outputs plt.scatter(X_test,y_test, color='black',s=2,label="Test values") plt.scatter(X_test, regr.predict(X_test), color='red',s=1,label="Predicted values") plt.legend() plt.show() # - predicted = regr.predict(x) residual = y - predicted plt.hist(residual,bins=30); plt.title("Residual histogram") plt.scatter(predicted, residual) plt.xlabel('Predicted') plt.ylabel('Residual') plt.axhline(y=0) plt.title('Residual vs. Predicted') plt.show() from sklearn.model_selection import cross_val_score cross_val_score(regr, x, y, cv=10) # # First regression discussion # # Indeed we are able to explain around 95% of the value of the Property crime per population. # # The residual is almost normally distributed, but they are a couple of errors that are higher than expected further from 0. # # Also the plot of the residual and expected show some heteroscedasticity. # # As this is only our first regression with one variable, we will try to improve it with the other variables. # # We also notice the outlier variable is visible on the graph and present a higher than expected error : this seems like it is related to the population, looking at the distribution of population there is only one city of more than 1 million inhabitant : this outlier might have a disproportionnate influence on the regression so we will take it out. # # Also, **Arson** behave in a strange manner, with N/A that is linked to the way the crime are reported. The median value in 0, so we can safely replace N/A by 0, but we will recorded the value that are N/A with a categorical value. # # Second regression # # As there are not many variable, and we already have a very good prediction with theft, let's look iteratively at the features, using the minimum of the cross validation test score. # + for_reg = per_pop.sort_values("population").reset_index().fillna(0) y = for_reg[["property"]] for col in ['population', 'violent_crime', 'murder', 'rape_2', 'robbery', 'aggravated', 'motor', 'arson',]: x = for_reg[['theft', 'burglary', col]] print(col,min(cross_val_score(regr, x, y, cv=15))) # - x = for_reg[['theft', 'burglary', 'motor']] cross_val_score(regr, x, y, cv=35) # + y = for_reg[["property"]] x = for_reg[['theft', 'burglary',"motor"]] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.10) # Instantiate our model. regr = linear_model.LinearRegression() # Fit our model to our data. regr.fit(X_train,y_train) # Display the attributes we calculated. print('Coefficients: \n', regr.coef_) print('Intercept: \n', regr.intercept_) print("Train score:",regr.score(X_train,y_train)) print("Test score:",regr.score(X_test,y_test)) # Plot outputs plt.scatter(X_test.theft,y_test, color='black',s=2,label="Test values") plt.scatter(X_test.theft, regr.predict(X_test), color='red',s=1,label="Predicted values") plt.legend() plt.show() # - # # Getting the R2 score for the **Property Crime** # # The regression was on the property crime per population, let's check the R2 for the actual R2 value. from sklearn.metrics import r2_score for_r2 = X_test.merge(for_reg[["population"]],left_index=True, right_index=True) #r2_score((for_r2.population*y_test.T).T, for_r2.population*[x[0] for x in regr.predict(X_test)], multioutput='variance_weighted') # # Second regression conclusion # # This result is very surprising, it really looks like a data leak ! It seems that Property = Theft + Burglary + Motor # # To make it a little more interesting, let's look at the data without those 3 values and try to find a good prediction. # # # # Doing some PCA... per_pop = base.copy() per_pop = per_pop.drop(['city','rape_1'],axis=1) for col in ['violent_crime','murder', 'rape_2','robbery', 'aggravated', 'property', 'burglary','theft', 'motor']: per_pop[col] = per_pop[col]/per_pop.population crime_pca = per_pop[['violent_crime','murder', 'rape_2','robbery', 'aggravated']].copy() sklearn_pca = PCA(n_components=5) X = StandardScaler().fit_transform(crime_pca) Y_sklearn = sklearn_pca.fit_transform(X) display(sklearn_pca.components_) display(sklearn_pca.explained_variance_) sum(sklearn_pca.explained_variance_ratio_[:3]) # + for i in range(5): per_pop[f"pca_{i}"] = Y_sklearn[:,i] per_pop["is_arson"] = per_pop.arson.isna() per_pop = per_pop.fillna(0) #per_pop = per_pop.drop(['theft', 'burglary',"motor"],axis=1) # - show_corr(per_pop) # # Third regression # # # # ## Very bad fit ! # + for_reg = per_pop[per_pop.population<1000000].sort_values("population").reset_index() #for_reg = per_pop[~per_pop.arson.isna()].sort_values("population").reset_index() y = for_reg[["property"]] x = for_reg[['pca_0', 'pca_1', 'pca_2','is_arson','arson']] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.40) # Instantiate our model. regr = linear_model.LinearRegression() # Fit our model to our data. regr.fit(X_train,y_train) # Display the attributes we calculated. print('Coefficients: \n', regr.coef_) print('Intercept: \n', regr.intercept_) print("Train score:",regr.score(X_train,y_train)) print("Test score:",regr.score(X_test,y_test)) # Plot outputs #plt.scatter(X_test.pca_0,y_test, color='black',s=2,label="Test values") #plt.scatter(X_test.pca_0, regr.predict(X_test), color='red',s=1,label="Predicted values") #plt.legend() #plt.show() # + predicted_test = regr.predict(X_test) predicted_train = regr.predict(X_train) residual_test = y_test - predicted_test residual_train = y_train - predicted_train _,bins,_ = plt.hist(residual_test.property,color="red",bins=15,alpha=0.6,density=True,label="Test residual"); plt.hist(residual_train.property,color="green",bins=bins,alpha=0.3,density=True,label="Train residual"); plt.legend() plt.title("Residual histogram"); # + plt.scatter(predicted_test, residual_test.property,s=10,label="Test") plt.scatter(predicted_train, residual_train.property,s=15,alpha=0.5,label="Train") plt.xlabel('Predicted') plt.ylabel('Residual') plt.axhline(y=0,color="red") plt.title('Residual vs. Predicted') plt.legend() plt.show() # - from sklearn.metrics import r2_score for_r2 = X_test.merge(for_reg[["population"]],left_index=True, right_index=True) r2_score((for_r2.population*y_test.T).T, for_r2.population*[x[0] for x in regr.predict(X_test)], multioutput='variance_weighted') # Eventhoug we get a very bad score for the property crim rate, we still end up with a very high score for the number of property crime as it is dependant on the population mostly. # # But looking at the test and train, we realize that the train has no 'is_arson', when the rest of the values are comparable. sum(X_train.is_arson) _,bins,_ = plt.hist(X_train.arson,density=True,alpha=0.5) _,bins,_ = plt.hist(X_test.arson,bins=bins,density=True,alpha=0.5) per_pop.is_arson.unique() _,bins,_ = plt.hist(per_pop[per_pop.is_arson==True].pca_0,bins=20,density=True,alpha=0.5,color="blue"); plt.hist(per_pop[per_pop.is_arson==False].pca_0,bins=bins,density=True,alpha=0.5,color="red"); _,bins,_ = plt.hist(per_pop[per_pop.is_arson==True].pca_1,bins=20,density=True,alpha=0.5,color="blue"); plt.hist(per_pop[per_pop.is_arson==False].pca_1,bins=bins,density=True,alpha=0.5,color="red"); # ## Controling the train and test are comparable # # There is an overal difference between cities that report arson correctly and the others, we need to make sure the number of 'is_arson' is almost the same in train and test. # + for_reg = per_pop[per_pop.population<1000000].sort_values("population").reset_index() #for_reg = per_pop[~per_pop.arson.isna()].sort_values("population").reset_index() y = for_reg[["property"]] x = for_reg[['pca_0', 'pca_1',"pca_2"]] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.10) # Instantiate our model. regr = linear_model.LinearRegression() # Fit our model to our data. regr.fit(X_train,y_train) # Display the attributes we calculated. print('Coefficients: \n', regr.coef_) print('Intercept: \n', regr.intercept_) print("Train score:",regr.score(X_train,y_train)) print("Test score:",regr.score(X_test,y_test)) # Plot outputs #plt.scatter(X_test.pca_0,y_test, color='black',s=2,label="Test values") #plt.scatter(X_test.pca_0, regr.predict(X_test), color='red',s=1,label="Predicted values") #plt.legend() #plt.show() test_arson = X_test.merge(for_reg[["is_arson"]],left_index=True, right_index=True) train_arson = X_train.merge(for_reg[["is_arson"]],left_index=True, right_index=True) print("Check Arson train",sum(train_arson.is_arson)/train_arson.shape[0]) print("Check Arson test",sum(test_arson.is_arson)/test_arson.shape[0]) # + predicted_test = regr.predict(X_test) predicted_train = regr.predict(X_train) residual_test = y_test - predicted_test residual_train = y_train - predicted_train _,bins,_ = plt.hist(residual_test.property,color="red",bins=15,alpha=0.6,density=True,label="Test residual"); plt.hist(residual_train.property,color="green",bins=bins,alpha=0.3,density=True,label="Train residual"); plt.legend() plt.title("Residual histogram"); # + plt.scatter(predicted_test, residual_test.property,s=10,label="Test") plt.scatter(predicted_train, residual_train.property,s=15,alpha=0.5,label="Train") plt.xlabel('Predicted') plt.ylabel('Residual') plt.axhline(y=0,color="red") plt.title('Residual vs. Predicted') plt.legend() plt.show() # - plt.scatter(x.pca_0,y.property) plt.scatter(x.pca_1,y.property) plt.scatter(x.pca_2,y.property) cross_val_score(regr, x, y, cv=5) from sklearn.metrics import r2_score for_r2 = X_test.merge(for_reg[["population"]],left_index=True, right_index=True) r2_score((for_r2.population*y_test.T).T, for_r2.population*[x[0] for x in regr.predict(X_test)], multioutput='variance_weighted') # In the this final regression, we still have some outliers. import statsmodels.formula.api as smf from statsmodels.sandbox.regression.predstd import wls_prediction_std per_pop.columns #per_pop = base.copy() #per_pop = per_pop.drop(['city','rape_1'],axis=1) for col in ['violent_crime','murder', 'rape_2','robbery', 'aggravated', 'property', 'burglary','theft', 'motor']: base[col+"_per_pop"] = base[col]/base.population base.columns # + linear_formula = 'property_per_pop ~ violent_crime_per_pop+rape_2_per_pop' # Fit the model to our data using the formula. lm = smf.ols(formula=linear_formula, data=base).fit() # - lm.params lm.pvalues lm.rsquared
NY_city_offense_2013.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:deep-learning] # language: python # name: conda-env-deep-learning-py # --- # + #importing utilities import os import sys from datetime import datetime #importing pytorch libraries import torch from numpy.core.setup_common import fname2def from torch import nn from torch.nn import init from torch import autograd from torch.utils.data import DataLoader import torch.nn.functional as F #importing data science libraries including pandas import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import matplotlib.gridspec as gridspec import pdb # + df_torch = pd.read_csv("./creditcard.csv") x = df_torch.Class.value_counts() #df_torch = df.drop('Class', axis=1) print(x) print(df_torch.shape) numeric_attr_names = ['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class'] numeric_attr = df_torch[numeric_attr_names] + 1e-3 df_torch_normalized = (numeric_attr - numeric_attr.min()) / (numeric_attr.max() - numeric_attr.min()) # print(df_torch_normalized) Class = df_torch_normalized.Class.values print(Class) # - # conclusion: Dataset is highly unbalanced # Here we want to check, how explanatory variables are affecting response variable(type of class) print("Fraud") # only 492 counts for fraudulant cases print(df_torch_normalized.Time[df_torch_normalized.Class==1].describe()) print() print("Normal") # large number of counts for non-fraudulant cases print(df_torch_normalized.Time[df_torch_normalized.Class==0].describe()) # + # returns a figure and two subplots stored in ax1 and ax2, respectively f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15,4)) bins = 65 ax1.hist(df_torch_normalized.Time[df_torch_normalized.Class==1], bins = bins) ax1.set_title('Fraud') ax2.hist(df_torch_normalized.Time[df_torch_normalized.Class==0], bins = bins) ax2.set_title('Normal') plt.xlabel('Time (in Seconds)') plt.ylabel('Number of Transactions') plt.tight_layout() plt.show() # + # returns a figure and two subplots stored in ax1 and ax2, respectively f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15,4)) bins = 30 ax1.hist(df_torch_normalized.Amount[df_torch_normalized.Class==1], bins = bins) ax1.set_title('Fraud') ax2.hist(df_torch_normalized.Amount[df_torch_normalized.Class==0], bins = bins) ax2.set_title('Normal') plt.xlabel('Amount') plt.ylabel('Number of Transactions') # takes the value between (-1,1). # log or ln because when a variable spans several orders of magnitude, # it is often easier on the eyes (and more informative) to visualize it on the log scale. plt.yscale('symlog') plt.tight_layout() plt.show() # + #compare Time with Amount for both the cases f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15,6)) ax1.scatter(df_torch_normalized.Time[df_torch_normalized.Class == 1], df_torch_normalized.Amount[df_torch_normalized.Class == 1]) ax1.set_title('Fraud') ax2.scatter(df_torch_normalized.Time[df_torch_normalized.Class == 0], df_torch_normalized.Amount[df_torch_normalized.Class == 0]) ax2.set_title('Normal') plt.xlabel('Time (in Seconds)') plt.ylabel('Amount') plt.tight_layout() plt.show() #somehow not too useful seeing from the distribution of data points # + # let's plot each of the feature to analyse even further plt.figure(figsize=(12,28*3)) gs = gridspec.GridSpec(31, 1) # creating grid with row = 28 for each feature, column = 1 # i = index, cn = to track the elements in list consisting column names for i, cn in enumerate(df_torch_normalized[numeric_attr_names]): ax = plt.subplot(gs[i]) # Plot a historgram and kernel density estimate sns.distplot(df_torch_normalized[cn][df_torch_normalized.Class == 1], bins=100, color='b') # e.g, Class==1 in feature = V1, so on.. sns.distplot(df_torch_normalized[cn][df_torch_normalized.Class == 0], bins=100, color='r') # e.g, Class==0 in feature = V1, so on.. ax.set_xlabel('') ax.set_title('histogram of feature: ' + str(cn)) plt.tight_layout() plt.show() # #Drop all of the features that have very similar distributions between the two types of transactions # df = df.drop(['V28','V27','V26','V25','V24','V23','V22','V20','V15','V13','V8', 'Amount', 'Time', 'Class'], axis = 1) # - # append 'Class' numeric_attr_vis = df_torch_normalized.copy() numeric_attr_vis['Class'] = Class # + USE_CUDA = False # setting up the seed seed_value = 1234 if (torch.backends.cudnn.version() != None and USE_CUDA == True): torch.cuda.manual_seed(seed_value) # set pytorch seed GPU # implementation of the encoder class encoder(nn.Module): def __init__(self): super(encoder, self).__init__() # layer 1 - in 17, out 14 self.encoder_L1 = nn.Linear(in_features=31, out_features=25, bias=True) # adding linearity nn.init.xavier_uniform(self.encoder_L1.weight) #initialize weights self.encoder_activation_L1 = nn.ReLU() # layer 2 - in 14, out 10 self.encoder_L2 = nn.Linear(25, 20, bias=True) nn.init.xavier_uniform(self.encoder_L2.weight) self.encoder_activation_L2 = nn.Tanh() # layer 3 - in 10, out 5 self.encoder_L3 = nn.Linear(20, 15, bias=True) nn.init.xavier_uniform(self.encoder_L3.weight) self.encoder_activation_L3 = nn.Tanh() # layer 4 - in 5, out 3 self.encoder_L4 = nn.Linear(15, 10, bias=True) nn.init.xavier_uniform(self.encoder_L4.weight) self.encoder_activation_L4 = nn.Tanh() # layer 5 - in 5, out 3 self.encoder_L5 = nn.Linear(10, 5, bias = True) # adding linearity nn.init.xavier_uniform(self.encoder_L5.weight) #initialize weights self.encoder_activation_L5 = nn.Tanh() # init dropout layer with probability p # self.dropout = nn.Dropout(p=0.4, inplace=True) def forward(self, x): # define forward pass x = self.encoder_activation_L1((self.encoder_L1(x))) x = self.encoder_activation_L2((self.encoder_L2(x))) x = self.encoder_activation_L3((self.encoder_L3(x))) x = self.encoder_activation_L4((self.encoder_L4(x))) x = self.encoder_activation_L5(self.encoder_L5(x)) return x # init training network classes / architectures encoder_train = encoder() # print the initialized architectures now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") print('[LOG {}] encoder architecture:\n\n{}\n'.format(now, encoder_train)) # + # implementation of the encoder class decoder(nn.Module): def __init__(self): super(decoder, self).__init__() # layer 1 - in 3, out 5 self.decoder_L1 = nn.Linear(in_features=5, out_features=10, bias=True) # adding linearity nn.init.xavier_uniform(self.decoder_L1.weight) #initialize weights self.decoder_activation_L1 = nn.Tanh() # layer 2 - in 5, out 10 self.decoder_L2 = nn.Linear(10, 15, bias=True) nn.init.xavier_uniform(self.decoder_L2.weight) self.decoder_activation_L2 = nn.Tanh() # layer 3 - in 10, out 14 self.decoder_L3 = nn.Linear(15, 20, bias=True) nn.init.xavier_uniform(self.decoder_L3.weight) self.decoder_activation_L3 = nn.Tanh() # layer 4 - in 14, out 17 self.decoder_L4 = nn.Linear(20, 25, bias=True) nn.init.xavier_uniform(self.decoder_L4.weight) self.decoder_activation_L4 = nn.Tanh() # layer 5 - in 15, out 20 self.decoder_L5 = nn.Linear(25, 31, bias = True) # adding linearity nn.init.xavier_uniform(self.decoder_L5.weight) #initialize weights self.decoder_activation_L5 = nn.Tanh() # init dropout layer with probability p # self.dropout = nn.Dropout(p=0.4, inplace=True) def forward(self, x): # define forward pass x = self.decoder_activation_L1((self.decoder_L1(x))) x = self.decoder_activation_L2((self.decoder_L2(x))) x = self.decoder_activation_L3((self.decoder_L3(x))) x = self.decoder_activation_L4((self.decoder_L4(x))) x = self.decoder_activation_L5(self.decoder_L5(x)) return x # init training network classes / architectures decoder_train = decoder() # print the initialized architectures now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") print('[LOG {}] decoder architecture:\n\n{}\n'.format(now, decoder_train)) # + # define the optimization criterion or loss function loss_function = nn.MSELoss(size_average=True) # define learning rate, optimization strategy learning_rate = .0001 encoder_optimizer = torch.optim.Adam(encoder_train.parameters(), lr=learning_rate) decoder_optimizer = torch.optim.Adam(decoder_train.parameters(), lr=learning_rate) # + # specify training parameters num_epochs = 50 mini_batch_size = 150 # convert pre-processed data --> pytorch tensor df_torch= torch.from_numpy(df_torch_normalized.values).float() # convert to pytorch tensor - none cuda enabled dataloader = DataLoader(df_torch, batch_size=mini_batch_size, shuffle=True, num_workers=0) # num_workers to zero to retrieve deterministic results # determine if CUDA is available at compute node if (torch.backends.cudnn.version() != None) and (USE_CUDA == True): dataloader = DataLoader(df_torch.cuda(), batch_size=mini_batch_size, shuffle=True) # init collection of mini-batch losses losses = [] # convert encoded transactional data to torch Variable data = autograd.Variable(df_torch) # train autoencoder model for epoch in range(num_epochs): # init mini batch counter mini_batch_count = 0 # determine if CUDA is available at compute node if(torch.backends.cudnn.version() != None) and (USE_CUDA == True): None # set networks / models in GPU mode encoder_train.cuda() decoder_train.cuda() # set networks in training mode (apply dropout when needed) encoder_train.train() decoder_train.train() # start timer start_time = datetime.now() #mini_batch_losses = [] # iterate over all mini-batches for mini_batch_data in dataloader: # increase mini batch counter mini_batch_count += 1 # convert mini batch --> torch variable mini_batch_torch = autograd.Variable(mini_batch_data) # =================== (1) forward pass =================================== # run forward pass z_representation = encoder_train(mini_batch_torch) # encode mini-batch data mini_batch_reconstruction = decoder_train(z_representation) # decode mini-batch data # =================== (2) compute reconstruction loss ==================== # determine reconstruction loss reconstruction_loss = loss_function(mini_batch_reconstruction, mini_batch_torch) # =================== (3) backward pass ================================== # reset graph gradients decoder_optimizer.zero_grad() encoder_optimizer.zero_grad() # run backward pass reconstruction_loss.backward() # =================== (4) update model parameters ======================== # update network parameters decoder_optimizer.step() encoder_optimizer.step() # =================== monitor training progress ========================== # print training progress each 1000 mini-batches if mini_batch_count % 1000 == 0: # print the training mode: either on GPU or CPU #mode = 'GPU' if (torch.backends.cudnn.version() != None) and (USE_CUDA == True) else 'CPU' mode = 'CPU' # print mini batch reconstuction results now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") end_time = datetime.now() - start_time # mini_batch_losses.extend([reconstruction_loss.data[0]]) # print(mini_batch_losses) print('[LOG {}] training status, epoch: [{:04}/{:04}], batch: {:04}, mode: {}, time required: {}' .format(now, (epoch+1), num_epochs, mini_batch_count, mode, end_time)) # reset timer start_time = datetime.now() # =================== evaluate model performance ============================= # set networks in training mode (don't apply dropout) encoder_train.cpu().eval() decoder_train.cpu().eval() # reconstruct encoded transactional data reconstruction = decoder_train(encoder_train(data)) # determine reconstruction loss - all transactions reconstruction_loss_all = loss_function(reconstruction, data) # collect reconstruction loss losses.extend([reconstruction_loss.data[0]]) # print reconstruction loss results now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") print('[LOG {}] training status, epoch: [{:04}/{:04}], loss: {:.10f}'.format(now, (epoch+1), num_epochs, reconstruction_loss.data[0])) # =================== save model snapshot to disk ============================ # save trained encoder model file to disk now = datetime.utcnow().strftime("%Y%m%d-%H_%M_%S") encoder_model_name = "{}_ep_{}_encoder_model.pth".format(now, (epoch+1)) torch.save(encoder_train.state_dict(), os.path.join("./models", encoder_model_name)) # save trained decoder model file to disk decoder_model_name = "{}_ep_{}_decoder_model.pth".format(now, (epoch+1)) torch.save(decoder_train.state_dict(), os.path.join("./models", decoder_model_name)) # + # plot the training progress plt.plot(range(0, len(losses)), losses) plt.xlabel('[training epoch]') plt.xlim([0, len(losses)]) plt.ylabel('[reconstruction-error]') # plt.ylim([0.0, 1.0]) plt.title('AAEN training performance') plt.tight_layout() plt.show() # mini_batch_losses.extend([reconstruction_loss.data[0]]) # plt.plot(range(0, len(mini_batch_losses)), mini_batch_losses) # plt.xlim([0, len(mini_batch_losses)]) # plt.show() # print(mini_batch_losses) # + # restore pretrained model checkpoint encoder_model_name = "20180319-14_49_18_ep_20_encoder_model.pth" decoder_model_name = "20180319-14_49_18_ep_20_decoder_model.pth" # init training network classes / architectures encoder_eval = encoder() decoder_eval = decoder() # load trained models encoder_eval.load_state_dict(torch.load(os.path.join("models", encoder_model_name))) decoder_eval.load_state_dict(torch.load(os.path.join("models", decoder_model_name))) # convert encoded transactional data to torch Variable data = autograd.Variable(df_torch) # set networks in training mode encoder_eval.eval() decoder_eval.eval() # reconstruct encoded transactional data reconstruction = decoder_eval(encoder_eval(data)) print(reconstruction.size()) # determine reconstruction loss - all transactions reconstruction_loss_all = loss_function(reconstruction, data) # print reconstruction loss - all transactions now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") print('[LOG {}] collected reconstruction loss of: {:06}/{:06} transactions'.format(now, reconstruction.size()[0], reconstruction.size()[0])) print('[LOG {}] reconstruction loss: {:.10f}'.format(now, reconstruction_loss_all.data[0])) # + # init binary cross entropy errors reconstruction_loss_transaction = np.zeros(reconstruction.size()[0]) #print(reconstruction_loss_transaction) #print(reconstruction.size()[0]) # iterate over all detailed reconstructions for i in range(0, reconstruction.size()[0]): # iterate over 0 to 284807 transactions # determine reconstruction loss - individual transactions reconstruction_loss_transaction[i] = loss_function(reconstruction[i], data[i]).data[0] # print(reconstruction_loss_transaction[i]) if(i % 100000 == 0): ### print conversion summary now = datetime.utcnow().strftime("%Y%m%d-%H:%M:%S") print('[LOG {}] collected individual reconstruction loss of: {:05}/{:05} transactions'.format(now, i, reconstruction.size()[0])) # prepare plot fig = plt.figure() ax = fig.add_subplot(111) # assign unique id to transactions plot_data = np.column_stack((np.arange(len(reconstruction_loss_transaction)), reconstruction_loss_transaction)) # print(plot_data) # obtain regular transactions as well as anomalies regular_data = plot_data[[Class == 0]] # print(regular_data) # print('regular_data:', regular_data) anomalous_data = plot_data[[Class == 1]] # print('anomalous_data:', anomalous_data) # plot reconstruction error scatter plot ax.scatter(regular_data[:, 0], regular_data[:, 1], c='C0', alpha=0.4, marker="o", label='regular') # plot regular transactions ax.scatter(anomalous_data[:, 0], anomalous_data[:, 1], c='C1', marker="^", label='anomolous') # plot anomolous transactions # add plot legend of transaction classes ax.legend(loc='best') filename = 'test_' + str(i) + '.png' fig.savefig(fname=filename) plt.tight_layout() plt.show() # -
FraudDetection-CreditCard/AE-CC_Notebook.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 Resturants = pd.read_excel(r"C:\Users\<NAME>\Google Drive\FYP\Sentimental Analysis\Sentimental_Burpple.xlsx") AllNames = Resturants.groupby('Cafรฉ_Names', sort=False, as_index=False).Title.count().reset_index(drop=True) NoR = AllNames['Title'].tolist() #for Negative reviews NegativeReviews = pd.read_excel(r"C:\Users\<NAME>\Google Drive\FYP\Sentimental Analysis\Burpple_Negative_Reviews.xlsx") NegNames = NegativeReviews.groupby('Cafรฉ_Names', sort=False, as_index=False).Title.count().reset_index(drop=True) NoRNeg = NegNames['Title'].tolist() NegReviews = [] maxNo = 0 polarity = NegativeReviews['polarity'].tolist() Negcafename = NegativeReviews['Cafรฉ_Names'].tolist() names = AllNames['Cafรฉ_Names'].tolist() rev = NegativeReviews['Review'].tolist() num = len(NoRNeg) pos = 0 poss = 0 for i in names: if i in Negcafename: NegReviews.append("Yes") else: NegReviews.append("") num1 = len(NegReviews) NegReviews1 = [] counta = 0 pos1 = 0 poss1 = 0 for i in range(0, num1): if NegReviews[i] == "Yes": pos1 = pos1 + NoRNeg[counta] for x in range (poss1, pos1): if abs(polarity[x]) > maxNo: maxNo = abs(polarity[x]) NegReviews1.append(rev[x]) poss1 = pos1 counta = counta +1 else: NegReviews1.append("") NegReviews2 = pd.Series(NegReviews1) AllNames['Negative_Review'] = NegReviews2.values #Neutral Reviews NeutralReviews = pd.read_excel(r"C:\Users\<NAME>\Google Drive\FYP\Sentimental Analysis\Burpple_Neutral_Reviews.xlsx") NeuNames = NeutralReviews.groupby('Cafรฉ_Names', sort=False, as_index=False).Title.count().reset_index(drop=True) NoRNeu = NeuNames['Title'].tolist() NeuReviews = [] minNo = 1 polarity = NeutralReviews['polarity'].tolist() Neucafename = NeutralReviews['Cafรฉ_Names'].tolist() names = AllNames['Cafรฉ_Names'].tolist() rev = NeutralReviews['Review'].tolist() num = len(NoRNeu) pos = 0 poss = 0 for i in names: if i in Neucafename: NeuReviews.append("Yes") else: NeuReviews.append("") num1 = len(NeuReviews) NeuReviews1 = [] counta = 0 pos1 = 0 poss1 = 0 for i in range(0, num1): if NeuReviews[i] == "Yes": pos1 = pos1 + NoRNeu[counta] for x in range (poss1, pos1): if abs(polarity[x]) < minNo: minNo = abs(polarity[x]) NeuReviews1.append(rev[x]) poss1 = pos1 counta = counta +1 else: NeuReviews1.append("") NeuReviews2 = pd.Series(NeuReviews1) AllNames['Neutral_Review'] = NeuReviews2.values #Positive Reviews PositiveReviews = pd.read_excel(r"C:\Users\<NAME>\Google Drive\FYP\Sentimental Analysis\Burpple_Positive_Reviews.xlsx") PovNames = PositiveReviews.groupby('Cafรฉ_Names', sort=False, as_index=False).Title.count().reset_index(drop=True) NoRPov = PovNames['Title'].tolist() PovReviews = [] maxNo = 1 polarity = PositiveReviews['polarity'].tolist() Povcafename = PositiveReviews['Cafรฉ_Names'].tolist() names = AllNames['Cafรฉ_Names'].tolist() rev = PositiveReviews['Review'].tolist() num = len(NoRPov) pos = 0 poss = 0 for i in names: if i in Povcafename: PovReviews.append("Yes") else: PovReviews.append("") num1 = len(PovReviews) PovReviews1 = [] counta = 0 pos1 = 0 poss1 = 0 for i in range(0, num1): if PovReviews[i] == "Yes": pos1 = pos1 + NoRPov[counta] for x in range (poss1, pos1): if abs(polarity[x]) > maxNo: maxNo = abs(polarity[x]) PovReviews1.append(rev[x]) poss1 = pos1 counta = counta +1 else: PovReviews1.append("") PovReviews2 = pd.Series(PovReviews1) AllNames['Positive_Review'] = PovReviews2.values #Positive Reviews PositiveReviews = pd.read_excel(r"C:\Users\<NAME>\Google Drive\FYP\Sentimental Analysis\Burpple_Positive_Reviews.xlsx") PovNames = PositiveReviews.groupby('Cafรฉ_Names', sort=False, as_index=False).Title.count().reset_index(drop=True) NoRPov = PovNames['Title'].tolist() PovReviews = [] maxNo = 1 polarity = PositiveReviews['polarity'].tolist() Povcafename = PositiveReviews['Cafรฉ_Names'].tolist() names = AllNames['Cafรฉ_Names'].tolist() rev = PositiveReviews['Review'].tolist() num = len(NoRPov) pos = 0 poss = 0 for i in names: if i in Povcafename: PovReviews.append("Yes") else: PovReviews.append("") num1 = len(PovReviews) PovReviews1 = [] counta = 0 pos1 = 0 poss1 = 0 for i in range(0, num1): if PovReviews[i] == "Yes": pos1 = pos1 + NoRPov[counta] for x in range (poss1, pos1): if abs(polarity[x]) > maxNo: maxNo = abs(polarity[x]) PovReviews1.append(rev[x]) poss1 = pos1 counta = counta +1 else: PovReviews1.append("") PovReviews2 = pd.Series(PovReviews1) AllNames['Positive_Review'] = PovReviews2.values AllNames.columns = ['Cafรฉ_Names', 'Count', 'Negative_Review', 'Neutral_Review','Positive_Review'] ex = pd.ExcelWriter('Example_Reviews.xlsx', options={'encoding':'utf-8'}) AllNames.to_excel(ex, 'Data', index=False) # - AllNames
Sentimental Analysis/Misc/All Reviews/Finding Example Reviews.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: tfcomb_env # language: python # name: tfcomb_env # --- # # Analyse: comparison between HL60 cells and NB4 cells (acute promyelocytic leukemia cell lines) # # ### HL60 cells # The HL-60 cell line is a human leukemia cell line that has been used for laboratory research on blood cell formation and physiology. The cell line was derived from a 36-year-old woman who was originally reported to have acute promyelocytic leukemia at the MD Anderson Cancer Center. HL-60 cells predominantly show neutrophilic promyelocytic morphology. HL-60 cells predominantly show neutrophilic promyelocytic morphology. # ### NB4 cells # # acute promyelocytic leukemia.established from the bone marrow of a 23-year-old woman with acute promyelocytic leukemia (APL = AML FAB M3) in second relapse in 1989; patented cell line; cells carry the t(15;17) PML-RARA fusion gene. NB4 cells, an acute promyelocytic leukemia cell line, have the t(15;17) translocation and differentiate in response to ATRA, whereas HL-60 cells lack this chromosomal translocation, even after differentiation by ATRA. Die hรคufigste Ursache fรผr acute promyelocytic leukemia ist eine t(15;17)-Translokation, die in einer Fusion der beiden fรผr die Transkriptionsfaktoren Promyelocytic Leukemia Protein (PML) und Retinsรคurerezeptor-ฮฑ (RARฮฑ) codierenden Gene resultiert. from tfcomb import CombObj genome_path="../testdaten/hg19_masked.fa" motif_path="../testdaten/HOCOMOCOv11_HUMAN_motifs.txt" result_path="./results/" # Using saved objects from market basket analysis from pkl files for liver and hepG2 cells using complete results of TF. Saving results from market basket analysis in objects. # + HL60_object= CombObj().from_pickle(f"{result_path}HL-60_enhancers_complete.pkl") HL60_object.prefix = "HL-60" NB4_object = CombObj().from_pickle(f"{result_path}NB4_enhancers_complete.pkl") NB4_object.prefix = "NB4" # - # Showing found rules of TF in each cell line print(f"HL-60: {HL60_object}") print(f"NB4: {NB4_object}") # Comparing rules of TF of cell line objects compare_objHL60_NB4 = HL60_object.compare(NB4_object) # ## Results Differential analysis of HL60 cells and NB4 cells # Results of differential analysis are found in compare_objHL60_NB4.rules. The table shows the rules of TF that distinguish strongly in occurence. The duplicates in the results are removed with simplify rules compare_objHL60_NB4.simplify_rules() compare_objHL60_NB4.rules compare_objHL60_NB4.plot_heatmap() selectionHL60_NB4 = compare_objHL60_NB4.select_rules(measure_threshold_percent=0.00025) selectionHL60_NB4.plot_network() selectionHL60_NB4.rules.head(10) selectionHL60_NB4.rules.tail(10) # ## Biological meaning # .. nothing to be found special to the tfs co occurences
wp6/analyse/backup_old/sl_enhancer_analyses_hl60_NB4.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 # --- # # Full Grade Notebook # This notebook contains code that gets a student full marks on the assignment. There are two very simple test cases. # ## This cell loads Gofer from gofer.ok import check # # Question 1: Does `defined_variable` equal 100? defined_variable = 100 check('tests/q_1.py') # # Question 2: Does `another_defined_variable` equal 200? another_defined_variable = 200 check('tests/q_2.py') # # Almost done! (optional) Run all tests sequentially # This is a convenient cell for users to run all their tests in order. # It also shows how the grader will see their code for the above tests from gofer.ok import grade_notebook from glob import glob grade_notebook('full-grade.ipynb', glob("tests/q*.py")) # Side note: grades are out of 1 so instructors can do their own weighting of assignments # # _Important_ Last step: Submit! # ## Hit the check mark at the end of the toolbar to submit your assignment
tests/notebooks/grading/full-grade.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 # --- # # Tutorial 3 # # ## Monte Carlo Tree Search # # In this mini project we will implement a recently developed planning method called monte carlo tree search. This algorithm combines the strengths of a structured tree search with the exploratory behavior of random "rollouts" to focus on promising parts of the state space, and has been particularly successful with perfect information games using a large state space (such as go). Similarly to RL, planning has to balance exploration and exploitation and MCTS employs a number of heuristics to try to do it. # # # # As you can see from the pseudocode, the algorithm has three key components: a tree policy (for action selection within the search tree), a default policy (for rollouts outside the search tree), and a backup function for backing up accumulated rewards over the simulated episode. We will first implement an example for each of these, and then put them together into the complete algorithm. # # A version in the algorithm is summerized in the following pseudocode: # # <img src="mcts_pseudocode.png",width='500'> # # # # You can import a generic graph structure with state nodes and action nodes, and implement a set of classes defining corresponding states and actions using the code below, aimed to integrate RL worlds from module 2 (in this case the windy cliff world). State nodes have these state objects as attributes, which in turn have position attribute returning the location in the maze. # # Action objects have the attribute move, which tell you the direction (0 to 3) corresponding to that action. You can change, and extend the reward function later to better solve the task. Please study the code below and graph.py for more details. # # # + import numpy as np import RL_worlds from RL_worlds import windy_cliff_grid_2 from graph import * import random import utils class MazeAction(object): def __init__(self, move): self.move = np.asarray(move) def __eq__(self, other): return self.move == other.move class MazeState(object): def __init__(self, pos): self.pos = np.asarray(pos) self.actions = [MazeAction(0), MazeAction(1), MazeAction(2), MazeAction(3)] def perform(self, action): pos,r = wd.get_outcome(self.pos,action.move) return MazeState(pos) def reward(self, parent, action): if self.pos in [53,131]: return 10000 elif self.pos in [2,3,4,28,42,56,70]: return -10000 elif self.pos in rstates[len(rstates)-5:]:#== parent.pos: return -200 return -10 def is_terminal(self): if (self.pos in [2,3,4, 53,131,28,42,56,70]): return True else: return False # - # Once you created a search tree, you can navigate around it using the following syntax (which we highlight with a list of examples): # To see the maze location corresponding to a node: node.state.pos # To see the visitation counts: node.n # The possible actions from a state node are the children nodes node.children.values() # So to see how many times during the rollouts from that particular root you took action 0 in the first step (from the root node): root.children.values()[0].n # # Exercise 1 # # # Write a function called ucbt to execute the UCB (upper confidence bound) tree poilcy. In particular write a function that takes as input an action-node, and returns the ucb value, $Q(s,a)_{ucb}=Q(s,a)+c * \sqrt {\frac{\log n(s)}{n(s,a)}}$, where n() denotes the number of visitations to the state, or action node. UCB uses optimism in the face of uncertainty, and chooses the action that could potentially be the best, given the remaining uncertainty about its value (specified in terms of the number of previous visitations). In this sense it's a bandit algorithm with Bayesian inspiration. # # Write a default policy function that performs a k-step random rollout (picking a random action at each step for k steps), but stops if a state is terminal. The function should return the total accumulated discounted reward. # # Write a backup function, that takes as input the terminal node and adjusts the value of all nodes (state and action) visited in the episode (this just means walking up the search tree). You can assume that the result of the rollout from the terminal node has been stored in node.reward. The rewards for actions taken while in the search tree can either be computed inside the backup function, or stored during the tree traversal during the episode. # # # # We will now write the core algorithm for MCTS. # <img src="basic_algorithm.png",width='600'> # # We can write three helper functions: # # best_child should return, given a state node and the tree policy, a successor state when taking the maximum value action. # # expand should return ,given a state node as input, a successor state after randomly taking one of the untried actions. # # Finally get_next_node should take as input a state node and the tree policy, and return a successor state node using best_child while inside the search tree (no untried actions), or using expand when reaching a leaf of the search tree (The state node has untried actions.) # # # These helper functions can then be integrated into a callable Tree search object (MCTS here), where you assign you should input your own tree policy, default policy and backup functions at the time of initialization. utils.rand_max is provided to randomly choose between possible actions of equal value. # class MCTS(object): def __init__(self, tree_policy, default_policy, backup): self.tree_policy = tree_policy self.default_policy = default_policy self.backup = backup def __call__(self, root, n=500): depth=0 if root.parent is not None: raise ValueError("Root's parent must be None.") for _ in range(n): node = get_next_node(root, self.tree_policy) node.reward = self.default_policy(node) self.backup(node,depth) return utils.rand_max(root.children.values(), key=lambda x: x.q).action # Run your tree search on the windy cliff world problem. There are many moving parts you can adjust, including the reward structure (though you are not supposed to introduce new location specific rewards), any discounting you introduce, the constant for the UCB algorithm. You can also vary how the backup is performed. # # Try to tune your algorithm so it can reach one of the gold states from any starting state. # # AS a reminder, to create a root node using a particular state, you can write # root=StateNode(None,MazeState(start_state)) # # to make a real move in the windy cliff world: # wd=windy_cliff_grid_2() # new_state,rreward=wd.get_outcome(root.state.pos,best_action.move)
module4/miniprojects/MCTS.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 # --- # # StarDistLite without distance map extension # # Modification of model.predict function to make it lighter from stardist.models.base import StarDistBase class StarDistBaseLite(StarDistBase): def __init__(self, config, name=None, basedir='.'): super().__init__(config=config, name=name, basedir=basedir) def predict_prob(self, img, axes=None, normalizer=None, n_tiles=None, show_tile_progress=True, **predict_kwargs): x, axes, axes_net, axes_net_div_by, _permute_axes, resizer, n_tiles, grid, grid_dict, channel, predict_direct, tiling_setup = \ self._predict_setup(img, axes, normalizer, n_tiles, show_tile_progress, predict_kwargs) if np.prod(n_tiles) > 1: tile_generator, output_shape, create_empty_output = tiling_setup() prob = create_empty_output(1) if self._is_multiclass(): prob_class = create_empty_output(self.config.n_classes+1) result = (prob, prob_class) else: result = (prob) for tile, s_src, s_dst in tile_generator: # predict_direct -> prob, dist, [prob_class if multi_class] result_tile = predict_direct(tile) # account for grid s_src = [slice(s.start//grid_dict.get(a,1),s.stop//grid_dict.get(a,1)) for s,a in zip(s_src,axes_net)] s_dst = s_src # prob and dist have different channel dimensionality than image x s_src[channel] = slice(None) s_dst[channel] = slice(None) s_src, s_dst = tuple(s_src), tuple(s_dst) # print(s_src,s_dst) for part, part_tile in zip(result, result_tile): part[s_dst] = part_tile[s_src] else: # predict_direct -> prob, dist, [prob_class if multi_class] result = predict_direct(x) result = [resizer.after(part, axes_net) for part in result] # prob result[0] = np.take(result[0],0,axis=channel) if self._is_multiclass(): # prob_class result[1] = np.moveaxis(result[1],channel,-1) return tuple(result) #
examples/Predict/StarDistLite.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="YtasH2tBWrTK" # # Simple Recurrent Language Model # # Predicting the next token. # + [markdown] id="z225dbwoaygs" # # Imports and Setup # # Common imports and standardized code for importing the relevant data, models, etc., in order to minimize copy-paste/typo errors. # + [markdown] id="cBD3U5YCt7-s" # # Set the relevant text field (`'abstract'` or `'title'`) and whether we are working with `'one-hot'` or `'tokenized'` text. # + id="7N6wzc1S1f91" executionInfo={"status": "ok", "timestamp": 1642476865347, "user_tz": 300, "elapsed": 17, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} TEXT_FIELD = 'abstract' TEXT_ENCODING = 'one-hot' assert TEXT_FIELD in ('abstract', 'title'), 'TEXT_FIELD must be one of "title" or "abstract".' assert TEXT_ENCODING in ('one-hot', 'tokenized'), 'TEXT_ENCODING must be one of "one-hot" or "tokenized".' # The above choices determine the relevant sequence length of the data. SEQ_LEN = 512 if TEXT_ENCODING == 'tokenized' else 1024 # + [markdown] id="tfUISDFhbmZB" # Imports and colab setup # + id="beaGM0OZDGBe" executionInfo={"status": "ok", "timestamp": 1642476900761, "user_tz": 300, "elapsed": 35426, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} # %%capture import_capture --no-stder # Jupyter magic methods # For auto-reloading when external modules are changed # %load_ext autoreload # %autoreload 2 # For showing plots inline # %matplotlib inline # pip installs needed in Colab for arxiv_vixra_models # !pip install wandb # !pip install pytorch-lightning # !pip install unidecode # Update sklearn # !pip uninstall scikit-learn -y # !pip install -U scikit-learn from copy import deepcopy import matplotlib.pyplot as plt import numpy as np import pandas as pd pd.set_option(u'float_format', '{:f}'.format) from pytorch_lightning import Trainer from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks.early_stopping import EarlyStopping import seaborn as sns import torch import wandb # + [markdown] id="dmuHdurUyvjK" # `wandb` log in: # + id="3DfWm5EfyyV-" colab={"base_uri": "https://localhost:8080/", "height": 68} executionInfo={"status": "ok", "timestamp": 1642476906085, "user_tz": 300, "elapsed": 5340, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="3696682f-fa2c-49a7-b339-a825e166f4f8" wandb.login() # + [markdown] id="kamviAnIb068" # Google drive access # + id="Q2rHoHQkVKqH" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642476929169, "user_tz": 300, "elapsed": 23108, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="c9d33d1b-c0e8-48a5-ae73-5bfde1f6097a" from google.colab import drive drive.mount("/content/drive", force_remount=True) # Enter the relevant foldername FOLDERNAME = '/content/drive/My Drive/ML/arxiv_vixra' assert FOLDERNAME is not None, "[!] Enter the foldername." # For importing modules stored in FOLDERNAME or a subdirectory thereof: import sys sys.path.append(FOLDERNAME) # + [markdown] id="K9ga5ia9cFRw" # Import my models, loaders, and utility functions: # + id="j8U3Ki7mbcw7" executionInfo={"status": "ok", "timestamp": 1642476936150, "user_tz": 300, "elapsed": 6985, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} import arxiv_vixra_models as avm # + [markdown] id="CXP2Q2FoaryB" # Set the model, datamodule, and text utils to be instantianted in the notebook # + id="UZfn8eELa0sg" executionInfo={"status": "ok", "timestamp": 1642476936152, "user_tz": 300, "elapsed": 8, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} notebook_model = avm.LitOneHotCharRNNNextLM notebook_datamodule = avm.OneHotCharDataModuleNextLM notebook_encoder = avm.str_to_one_hot notebook_decoder = avm.one_hot_to_str notebook_wandb_callback = avm.WandbTextGenerationCallback # + [markdown] id="HAjCZ39tcQ1Y" # Copy data to cwd for speed. # + id="V4b1KZSYV8rP" executionInfo={"status": "ok", "timestamp": 1642476964765, "user_tz": 300, "elapsed": 28619, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} train_data_file_name = 'large_filtered_normalized_data_train.feather' val_data_file_name = 'balanced_filtered_normalized_data_validation.feather' SUBDIR = '/data/data_splits/' train_data_path = FOLDERNAME + SUBDIR + train_data_file_name val_data_path = FOLDERNAME + SUBDIR + val_data_file_name if TEXT_ENCODING == 'one-hot': tokens_file_name = 'normalized_char_set.feather' else: tokens_file_name = 'balanced_title_normalized_vocab.feather' tokens_path = FOLDERNAME + SUBDIR + tokens_file_name # !cp '{train_data_path}' . # !cp '{val_data_path}' . # !cp '{tokens_path}' . train_data_df = pd.read_feather(train_data_file_name) val_data_df = pd.read_feather(val_data_file_name) tokens_df = pd.read_feather(tokens_file_name) if TEXT_ENCODING == 'one-hot': text_to_idx = dict(zip(tokens_df.char.values, np.arange(len(tokens_df)))) else: # 0 and 1 are reserved for padding and <UNK> for embeddings and not included # in tokens_df text_to_idx = dict(zip(tokens_df.word.values, np.arange(2, len(tokens_df) + 2))) text_to_idx['<PAD>'] = 0 text_to_idx['<UNK>'] = 1 idx_to_text = {val: key for key, val in text_to_idx.items()} if TEXT_FIELD == 'title': train_text_file_name = 'concatenated_large_normalized_train_title.txt' val_text_file_name = 'concatenated_balanced_normalized_validation_title.txt' else: train_text_file_name = 'concatenated_large_normalized_train_abstract.txt' val_text_file_name = 'concatenated_balanced_normalized_validation_abstract.txt' with open(FOLDERNAME + SUBDIR + train_text_file_name, 'r') as f: train_text = f.read().strip() with open(FOLDERNAME + SUBDIR + val_text_file_name, 'r') as f: val_text = f.read().strip() # + [markdown] id="xRfQtriZWa1P" # Computing specs. Save the number of processors to pass as `num_workers` into the Datamodule and cuda availability for other flags. # + id="yuUpH52TUAG7" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642476965174, "user_tz": 300, "elapsed": 426, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="ce03fd58-e30d-4cb4-aa96-fa581bda5966" # GPU. Save availability to IS_CUDA_AVAILABLE. # gpu_info= !nvidia-smi gpu_info = '\n'.join(gpu_info) if gpu_info.find('failed') >= 0: print('Not connected to a GPU') IS_CUDA_AVAILABLE = False else: print(f"GPU\n{50 * '-'}\n", gpu_info, '\n') IS_CUDA_AVAILABLE = True # Memory. from psutil import virtual_memory, cpu_count ram_gb = virtual_memory().total / 1e9 print(f"Memory\n{50 * '-'}\n", 'Your runtime has {:.1f} gigabytes of available RAM\n'.format(ram_gb), '\n') # CPU. print(f"CPU\n{50 * '-'}\n", f'CPU Processors: {cpu_count()}') # Determine the number of workers to use in the datamodule NUM_PROCESSORS = cpu_count() # + [markdown] id="yP-xjLY4cEEL" # Use notebook name as `wandb` `project` string. Remove the file extension and any "Copy of" or "Kopie van" text which arises from copying notebooks and running in parallel. The `entity` needed for various `wandb` calls is just the `wandb` user name. # + id="yy8UZlYodrhO" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642476965175, "user_tz": 300, "elapsed": 9, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="f9e38dcd-9687-49da-da83-c65ec1ef7b63" from requests import get PROJECT = get('http://172.28.0.2:9000/api/sessions').json()[0]['name'] PROJECT = PROJECT.replace('.ipynb', '').replace('Kopie%20van%20', '').replace('Copy%20of%20', '') print(PROJECT) ENTITY = 'garrett361' # + [markdown] id="2HVB4e-xchSi" # # Model Testing # # Setting hyperparameters and performing a small test run. # + [markdown] id="E0e7seomcjud" # Dictionary args for model and datamodule. # + id="GLg5mLHchpqp" executionInfo={"status": "ok", "timestamp": 1642476965176, "user_tz": 300, "elapsed": 7, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} model_args_dict = {'seq_len': SEQ_LEN, 'tokens': tokens_df, 'num_layers': 2, 'hidden_size': 512, 'rnn_type': 'GRU', 'fc_dims': None, 'zero_fc_bias_init': True, 'truncated_bptt_steps': 128 } data_args_dict = {'seq_len': SEQ_LEN, 'train_text': train_text, 'val_text': val_text, 'tokens': tokens_df, 'num_workers': NUM_PROCESSORS, 'batch_size': 128, 'pin_memory': IS_CUDA_AVAILABLE, 'persistent_workers': True, } # + [markdown] id="okEcWXWWxYb0" # Small test run. # + id="qhOY0cnMvnX-" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642476989055, "user_tz": 300, "elapsed": 23885, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="185532c5-3e15-45ce-fc79-ef5f71ffad8b" small_data_module = notebook_datamodule(**data_args_dict) small_data_module.setup() small_loader = small_data_module.train_dataloader() small_inputs, small_targets = next(iter(small_loader)) # Print the first few input texts for input, target in zip(small_inputs[:3], small_targets[:3]): sample_text = notebook_decoder(input, idx_to_text) sample_target = ''.join(idx_to_text[ch.item()] for ch in target) print(f"input text: {sample_text}", f"target text: {sample_target}", f'input, target lens: {len(sample_text), len(sample_target)}', sep='\n') small_model = notebook_model(**model_args_dict) print('Model layers:', small_model) small_preds, small_losses, _ = small_model.scores_loss_hiddens(small_inputs, small_targets) print('\npreds shape:', small_preds.shape) print('\nactual loss:', small_losses.item()) print('\nexpected approx loss', np.log(len(tokens_df))) # + id="lLdlEdmO83mU" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642476989059, "user_tz": 300, "elapsed": 39, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="b19a787d-ff0e-41f1-f1db-a36e6f68f9f5" # pl implements gradient clipping through the Trainer. small_trainer = Trainer(gpus=-1 if IS_CUDA_AVAILABLE else 0, max_epochs=1, gradient_clip_val=1 ) # + [markdown] id="97-nbRSP87fY" # A `LR finder stopped early due to diverging loss.` here may be due to having too large a batch size, i.e., not enough samples from the datamodule; [see this github discussion](https://github.com/PyTorchLightning/pytorch-lightning/issues/5044) # + id="wE0laRH4samb" executionInfo={"status": "ok", "timestamp": 1642476989060, "user_tz": 300, "elapsed": 24, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} # small_trainer_lr_finder = small_trainer.tuner.lr_find(small_model, datamodule=small_data_module, min_lr=1e-6, max_lr=1e-1) # small_trainer_lr_finder_plot = small_trainer_lr_finder.plot(suggest=True) # small_trainer_suggested_lr = small_trainer_lr_finder.suggestion() # print(f'Suggested lr: {small_trainer_suggested_lr}') # + [markdown] id="b7DPjsjTnlso" # # Training # + id="OjBi9bSrYa4b" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642504769672, "user_tz": 300, "elapsed": 271, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="8fd47d1a-01d8-49c9-df01-892462da45bb" cyclic_lr_scheduler_args = {'base_lr': 5e-5, 'max_lr': 5e-3, 'step_size_up': 2048, 'mode': 'triangular2', 'cycle_momentum': False} plateau_lr_scheduler_args = {'verbose': True, 'patience': 512, 'factor': .5, 'mode': 'min'} model_args_dict['save_models_to_wandb'] =True model_args_dict['lr'] = 5e-3 model_args_dict['lr_scheduler'] = 'cyclic' model_args_dict['lr_scheduler_args'] = cyclic_lr_scheduler_args model_args_dict['lr_scheduler_monitor'] = 'train_batch_loss' model = notebook_model(**model_args_dict) data_args_dict['batch_size'] = 1024 datamodule = notebook_datamodule(**data_args_dict) # + [markdown] id="R2nS87PG92Aw" # Training: # + colab={"base_uri": "https://localhost:8080/", "height": 1000, "referenced_widgets": ["ec7165fa25bb48bbb3aba56d3d58fcb7", "9be25033647340c786fa4b25b1426a16", "3b61fe00579640cb8a8d4255d9b8f171", "<KEY>", "<KEY>", "<KEY>", "924a31ebb28d4659aded1114cc970b1e", "5666a2dae0894c0f811a6097793d2882", "<KEY>", "9ce4efa1799f4fdaae6fbb8a471036c0", "ecaed41dd36545ea9901de65fed7ae1b", "bcfde22851524d8a976b5a3e2d02bcca", "84f1d9dce7b44b84abc624c0ced99247", "7638a99799f34dac99944ac28dcc7787", "<KEY>", "<KEY>", "<KEY>", "09125d5a1e73465494a78de860d6aeb9", "654628691b5c4ea2aeae29ea610bbe84", "<KEY>", "<KEY>", "b375a06db97f4694a2133e13d8432b35", "54a4d2adc67a4ca39805e4f2ab88fc68", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "5298e1587a9143a0813bf2e083dc2a4d", "12863709f3f54def8b095d1e04c735c1", "3df8aa09da9f4834b30761d0838e89e8", "74c5394f20e042f6ac5e8147deba9f3c", "412d89304c4c4d5c9e94b961609809ea", "<KEY>", "<KEY>", "39ccdf14f87a485ca1273481f089b3e6", "4a05ffa40a9f4f969669f68c196dca8d", "39c342e5e94b41269e2395c1761cb59a", "58639307f2494af98a82fb02c4850e8e", "7ad3ba8a75bb4da39cd6ac3539ac8c67", "1a9e80d65fad4880abb007d94d35aeba", "<KEY>", "<KEY>", "<KEY>", "2809307f18eb4952912271a6441e0e1e", "a6adcafac9de42688f31be85a88354c2", "974d848a45da41ec89c19695c4ac100b", "<KEY>", "a73dd7763fb545ad867acbfb0275b7ec", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "0546ff50f3c947b8ab9c623089efa2df", "d4002a26db63472c8a8c6c2a4265a3f3", "<KEY>", "<KEY>", "7b57b03e0f854f1aab1b1ce27cf8f161", "<KEY>", "8f473d05a0584091b2934752b3ad4591", "a7ee4c1813ab4b6b83a35d6cf26e1dfb", "759b09dd1d10448fa94b251ee7d7b7b6", "881e3157abe6439282316f6747d98b3b", "<KEY>", "<KEY>", "<KEY>", "e7367df801004074801638c037a518e8", "<KEY>", "45f6023223404f52a9dd3bd594ec5951", "<KEY>", "ac21a121836a4accaf9d4ee937c03959", "<KEY>", "53ed01e0556e43e1be974a0b45dc007e", "91dc4ed9def54838ace41acc124ce925", "321bc70ea6ad42ac97b1fc8ec6876beb", "4ea02a7f77de4ffc9cfc31f425827bac", "a424761466df409daf4027824cf61fe5"]} id="cJU6yv3wRW8j" outputId="501f3c70-8bff-4abd-e165-58392820b325" # We accumulate gradients in batches to help smooth out the loss-curve. trainer = Trainer(logger=WandbLogger(), gpus=-1 if IS_CUDA_AVAILABLE else 0, log_every_n_steps=1, callbacks=[notebook_wandb_callback()], gradient_clip_val=1, ) with wandb.init(project=PROJECT) as run: run.name = f"lr_{model.hparams['lr']}_scheduler_{model_args_dict.get('lr_scheduler', None)}"[:128] trainer.fit(model, datamodule=datamodule) plt.close("all") # + [markdown] id="VGAXPFMzg2QT" # # Loading Best Models # + id="KmzGOAg7g40x" colab={"base_uri": "https://localhost:8080/", "height": 204} executionInfo={"status": "ok", "timestamp": 1642504757376, "user_tz": 300, "elapsed": 831, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="624df3eb-41a3-46c2-ffad-c1bf124b30ff" wandb_api = wandb.Api() notebook_runs = wandb_api.runs(ENTITY + "/" + PROJECT) run_cats = ('best_val_acc','config', 'name', 'wandb_path') notebook_runs_dict = {key: [] for key in run_cats} for run in notebook_runs: run_json = run.summary._json_dict if 'best_val_acc' in run_json: notebook_runs_dict['best_val_acc'].append(run_json['best_val_acc']) notebook_runs_dict['config'].append({key: val for key, val in run.config.items()}) notebook_runs_dict['name'].append(run.name) notebook_runs_dict['wandb_path'].append('/'.join(run.path)) notebook_runs_df = pd.DataFrame(notebook_runs_dict).sort_values(by='best_val_acc', ascending=False).reset_index(drop=True) notebook_runs_df.head() # + id="4vKX8-YSnnJV" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642504757378, "user_tz": 300, "elapsed": 14, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="fd3a2b43-c6ff-47dc-973c-f1e99d3a3aeb" best_model_df = notebook_runs_df.iloc[notebook_runs_df['best_val_acc'].argmax()] print(best_model_df) # + [markdown] id="JWHtDEyrnnJY" # Save the state dicts locally and rebuild the corresponding models. # + id="j8uEeZcLnnJZ" executionInfo={"status": "ok", "timestamp": 1642504760316, "user_tz": 300, "elapsed": 2945, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} # wandb stores None values in the config dict as a string literal. Need to # fix these entries, annoyingly. for key, val in best_model_df.config.items(): if val == 'None': best_model_df.config[key] = None # Write to disk best_model_file_name = f"model_best_val_acc.pt" wandb.restore(best_model_file_name, run_path=best_model_df.wandb_path, replace=True) best_model_file_name_suffix = '_'.join(best_model_file_name.split('_')[-2:]) # Also copy to the final_models folder # !cp '{best_model_file_name}' "{FOLDERNAME + '/final_models/' + PROJECT + '_' + best_model_file_name_suffix}" # + id="stPhRPeBnnJd" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1642504760318, "user_tz": 300, "elapsed": 25, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="137ffc0d-e323-4677-c98a-163b1febc8a5" best_model = notebook_model(**{**best_model_df.config, **{'tokens': tokens_df}}) best_model.load_state_dict(torch.load(best_model_file_name)) # + [markdown] id="GdWSVBrOMJ2X" # # Visualize # + id="q_46Qh7dk8IJ" colab={"base_uri": "https://localhost:8080/", "height": 197} executionInfo={"status": "error", "timestamp": 1642504761360, "user_tz": 300, "elapsed": 1058, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} outputId="59d7dd4e-bc1a-4c4c-e52d-1229f79592c2" heatmap = avm.embedding_cosine_heatmap(model=best_model, words=heatmap_words, word_to_idx=title_word_to_idx) # + id="5piTr2-CmjHa" executionInfo={"status": "aborted", "timestamp": 1642504761059, "user_tz": 300, "elapsed": 425, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} pca = avm.pca_3d_embedding_plotter_topk(model=best_model, words=pca_words, word_to_idx=title_word_to_idx, idx_to_word=title_idx_to_word, title='PCA', k=5) # + id="9T6h2Pv-mwyG" executionInfo={"status": "aborted", "timestamp": 1642504761061, "user_tz": 300, "elapsed": 426, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} tsne = avm.tsne_3d_embedding_plotter_topk(model=best_model, words=tsne_words, word_to_idx=title_word_to_idx, idx_to_word=title_idx_to_word, title='t-SNE', k=5) # + id="sJziDqL2SV9u" executionInfo={"status": "aborted", "timestamp": 1642504761062, "user_tz": 300, "elapsed": 427, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} pca.show() # + id="8AIsi4-dJBUk" executionInfo={"status": "aborted", "timestamp": 1642504761063, "user_tz": 300, "elapsed": 427, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} tsne.show() # + id="XHyd8lx3pZJR" executionInfo={"status": "aborted", "timestamp": 1642504761064, "user_tz": 300, "elapsed": 427, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GjiiYFf8nm-IpkI8yUgW_CqJJ76xMZhUUU94FCJabg=s64", "userId": "15364959356591490410"}} avm.embedding_utils.topk_analogies_df(best_model, 'newton mechanics heisenberg'.split(), title_word_to_idx, title_idx_to_word)
simple_language_models/Kopie van Kopie van large_abstract_recurrent_one_hot_next_language_model.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 # --- # ### Use logistic regression to analyse customer churn problem import findspark findspark.init('/home/bowen/spark-2.4.4-bin-hadoop2.7/') from pyspark.sql import SparkSession spark = SparkSession.builder.appName('customer_churn').getOrCreate() fn = './customer_churn.csv' df = spark.read.csv(fn, inferSchema=True, header=True) df.printSchema() df.head(1) df.describe().show() #all counts are 900, no missing data from pyspark.ml.feature import VectorAssembler from pyspark.ml.classification import LogisticRegression vc_assembler = VectorAssembler(inputCols=['Age', 'Total_Purchase', 'Years', 'Num_Sites'], outputCol='features') features_df = vc_assembler.transform(df).select('features', 'churn') train_set, test_set = features_df.randomSplit([0.7,0.3]) reg_churn = LogisticRegression(labelCol='churn', maxIter=100) churn_model = reg_churn.fit(train_set) churn_model.summary.areaUnderROC from pyspark.ml.evaluation import BinaryClassificationEvaluator results = churn_model.evaluate(test_set) results.predictions.show() churn_eval = BinaryClassificationEvaluator(rawPredictionCol='prediction', labelCol='churn') auc = churn_eval.evaluate(results.predictions, {churn_eval.metricName: "areaUnderROC"}) print (auc) new_customer_df = spark.read.csv('new_customers.csv', inferSchema=True, header=True) test_new_customer_features = vc_assembler.transform(new_customer_df) test_new_customer_features.printSchema() predicted_results = churn_model.transform(test_new_customer_features) predicted_results.select('Names', 'Company', 'prediction').show()
Customer_churn_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 # --- # # Glass Ceiling - A Perspective on Women ocupation on informal work places. # ## Objective: # To demonstrate the position of women on informal work places, how does this affects their glass ceiling and if we can infer their current position as working force for Mexico.<br /> After our data exploration, we just came down to three data sources which are: # * Population by gender and earned salary. # * **Busy population by formality under economical activity** # + import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # - # ## Cleaning Sources # ### Population working under informality # The further analysis will try to make a statment about the representation of women on informal workplaces. informal_eco=pd.read_csv('Poblacion_Ocupada_Condicion_Informalidad.csv') # We'll look if dtypes are set up correctly: informal_eco.info() # Since our fields are categorical but the count of people; let's: # * Convert to datetime the period # * Let's check if there's any null values we need to remove: informal_eco informal_eco['Periodo'] = pd.to_datetime(informal_eco['Periodo'],format='%Y%m%d') informal_eco.head() # Since this is an analysis on a very general POV; let's select `Nacional` as our location to work with, since the data is already loaded, after that, we'll look for Null values. informal_eco=informal_eco.loc[informal_eco['Entidad_Federativa']=='Nacional'] informal_eco # Could we segregate more the data for the Null Values Cleanse? informal_eco['Grupo_edad'].unique() informal_eco.loc[informal_eco['Grupo_edad']=='NO ESPECIFICADO'].count() informal_eco.loc[informal_eco['Grupo_edad']=='NO ESPECIFICADO'].count() 36/180 # Since the Null values are almost 20% of the sample, we can't infere with which values to replace and if dropping them, we would lose a significant amount of data from the already narrow dataset informal_eco['Periodo'].unique() # As per dates, we don't have very significant data to conclude anything, so let's explore this dataframe to see how in 2020 and 2021 the formal and informal work occupation affected women. # * Percentage of women vs men during 2020 on informal jobs vs formal jobs. # * Percentage of women vs men during 2021 on informal jobs vs formal jobs. # In order to group, we need to have period as Object rather than numeric: informal_eco['Periodo'].map(str) informal_eco=informal_eco.astype({'Periodo': str}) informal_eco['Periodo']=informal_eco['Periodo'].str[:10] informal_eco # Due to ease of tools and lack of time, will define 4 dataframes, no considering age category to group by formality status and gender. # + # grafiquemos genero a genero, por categoria de edad por ambos aรฑos - formalidad para 2020 a1 = informal_eco.loc[( (informal_eco['Periodo'].str[3].isin(['0'])) & (informal_eco['Condicion_informalidad'] == 'Formal')) ].groupby(['Sexo','Grupo_edad']).sum()['Numero_personas'].unstack() a1.plot(kind="barh",colormap='PiYG',edgecolor='Black',figsize=(15,5),title='Formal labour occupation by 2020') # grafiquemos genero a genero, por categoria de edad por ambos aรฑos - informalidad para 2020 a2 = informal_eco.loc[( (informal_eco['Periodo'].str[3].isin(['0'])) & (informal_eco['Condicion_informalidad'] == 'Informal')) ].groupby(['Sexo','Grupo_edad']).sum()['Numero_personas'].unstack() a2.plot(kind="barh",colormap='tab10',edgecolor='Black',figsize=(15,5),title='Informal labour occupation by 2020') # + # grafiquemos genero a genero, por categoria de edad por ambos aรฑos - formalidad para 2021 a3 = informal_eco.loc[( (informal_eco['Periodo'].str[3].isin(['1'])) & (informal_eco['Condicion_informalidad'] == 'Formal')) ].groupby(['Sexo','Grupo_edad']).sum()['Numero_personas'].unstack() a3.plot(kind="barh",colormap='PiYG',edgecolor='Black',figsize=(15,5),title='Formal labour occupation by 2021') # grafiquemos genero a genero, por categoria de edad por ambos aรฑos - informalidad para 2021 a4 = informal_eco.loc[( (informal_eco['Periodo'].str[3].isin(['1'])) & (informal_eco['Condicion_informalidad'] == 'Informal')) ].groupby(['Sexo','Grupo_edad']).sum()['Numero_personas'].unstack() a4.plot(kind="barh",colormap='tab10',edgecolor='Black',figsize=(15,5),title='Informal labour occupation by 2021') # - # ##### Gender by Formality Status ecoMF = ( informal_eco.loc[ ((informal_eco['Sexo'] == 'Mujer') & (informal_eco['Condicion_informalidad'] == 'Formal'))] .groupby('Periodo') .agg({'Numero_personas':'sum'}) .reset_index() ) ecoMF=ecoMF.rename(columns = {'Numero_personas':'Mujeres_Formalidad'}) ecoMF ecoHF = ( informal_eco.loc[ ((informal_eco['Sexo'] == 'Hombre') & (informal_eco['Condicion_informalidad'] == 'Formal'))] .groupby('Periodo') .agg({'Numero_personas':'sum'}) .reset_index() ) ecoHF=ecoHF.rename(columns = {'Numero_personas':'Hombres_Formalidad'}) ecoHF # ##### Gender by Informality Status ecoMI = ( informal_eco.loc[ ((informal_eco['Sexo'] == 'Mujer') & (informal_eco['Condicion_informalidad'] == 'Informal'))] .groupby('Periodo') .agg({'Numero_personas':'sum'}) .reset_index() ) ecoMI=ecoMI.rename(columns = {'Numero_personas':'Mujeres_Informalidad'}) ecoMI ecoHI = ( informal_eco.loc[ ((informal_eco['Sexo'] == 'Hombre') & (informal_eco['Condicion_informalidad'] == 'Informal'))] .groupby('Periodo') .agg({'Numero_personas':'sum'}) .reset_index() ) ecoHI=ecoHI.rename(columns = {'Numero_personas':'Hombres_Informalidad'}) ecoHI formalJ=pd.merge(ecoMF, ecoHF, on ='Periodo', how ="inner") informalJ=pd.merge(ecoMI, ecoHI, on ='Periodo', how ="inner") finalJ=pd.merge(formalJ,informalJ, on='Periodo',how='inner') finalJ finalJ.set_index('Periodo') # + plt.figure(figsize=(12, 6)) plt.title('Amount of work force by gender and formality') x=finalJ['Periodo'] y1=finalJ['Mujeres_Formalidad'] y2=finalJ['Hombres_Formalidad'] y3=finalJ['Mujeres_Informalidad'] y4=finalJ['Hombres_Informalidad'] plt.plot(x,y1,color='red', linewidth=1,marker='o', markersize=8, label='Women under formal jobs') plt.plot(x,y2,color='orange', linewidth=1,marker='v', markersize=8, label='Men under formal jobs') plt.plot(x,y3,color='pink', linewidth=1,marker='1', markersize=8, label='Women under informal jobs') plt.plot(x,y4,color='purple', linewidth=1,marker='s', markersize=8, label='Men under informal jobs') plt.legend() # - # As per below results, knowing about the salary data we have previously; we can partialy confirm (since we only have 2 years data) that even though women are proportionally present as work force, they're still on positions of lower power and really underpaid; since as we show, they represent only 30% of earning population and from that, over 60% earn barely 3 minimum wages. # With this brief analysis, we see that there's still a long way mexican woman and institutions will need to go in order to show true equality between genders and pay gap. # Q.E.D. - IZ
Documentation/EconomicalActivitiesPerFormality_GenderPerYear.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: orchest-kernel-4e3e3b13-882e-47db-b8f2-03a87620ea0d # --- import orchest from catboost import CatBoostClassifier from sklearn.metrics import roc_auc_score data = orchest.get_inputs() X_train, y_train, X_test, y_test = data["training_data"] # + cat = CatBoostClassifier( iterations=250, od_type="Iter", l2_leaf_reg=5, learning_rate=0.95, verbose=0, depth=10,) cat.fit(X_train, y_train) cat_pred = cat.predict(X_test) print("AUC score :", roc_auc_score(cat_pred, y_test)) # - orchest.output((cat,cat_pred), name="catboost")
CatBoost.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 # --- # # 8 import numpy as np from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original') X = mnist['data'].astype(np.float32) y = mnist['target'].astype(np.int32) from sklearn.decomposition import PCA pca = PCA(n_components=0.7) X_trans = pca.fit_transform(X) train = 4000 val = 5000 test = 6000 m, n = X_trans.shape np.random.seed(42) shuffle_idx = np.random.permutation(m) X_trans = X_trans[shuffle_idx] y = y[shuffle_idx] X_train, y_train = X_trans[:train], y[:train] X_val, y_val = X_trans[train:val], y[train:val] X_test, y_test = X_trans[val:test], y[val:test] from sklearn.ensemble import VotingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score rnd_clf = RandomForestClassifier(max_depth=2, n_estimators=400) ext_clf = ExtraTreesClassifier(max_depth=2, n_estimators=500) svm_clf = SVC() vote_clf = VotingClassifier( estimators=[('rnd_clf', rnd_clf), ('ext_clf', ext_clf), ('svm_clf', svm_clf)], voting='hard' ) for clf in (rnd_clf, ext_clf, svm_clf, vote_clf): clf.fit(X_train, y_train) y_pred = clf.predict(X_val) print(clf.__class__.__name__, accuracy_score(y_pred, y_val))
Hand-on-Machine-Learning-with-Scikit-learning-and-Tensorflow/Chapter07/Exercise.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 # --- # Output of this script can be loaded from pickle file (predicted_TFBS_normalized_final10_low.pkl) by executing the last cell. # __________________________________ # This code requires the DeepSEA output files to be present in a subdirectory called 'deepsea-results/', or else a FileNotFound Error will occur. Please contact <EMAIL> for the DeepSEA output files (7.5GB). import math import pandas as pd from TF import * # + finalResults = pd.DataFrame() for i in range(10): print('Reading file ', i+1, 'of 10') data = pd.read_csv('deepsea-results/'+str(i)+'-infile.bed.out', header=0, index_col=0) results = data.iloc[:,0:3] for TF in TFsSlash: results = results.join(data.filter(regex=TF).iloc[:,0]) if i == 0: finalResults = results else: finalResults = finalResults.append(results, ignore_index=True) finalResults.head(-1) # - # Normalize the probabilities to take into account each TF's positive rate. # positive proportion given by experimental data posRate = pd.read_csv('positiveProportion.txt', header=0, delimiter='\t') TFposRate = [] TFposRate.append(posRate[(posRate['Cell Type'] == 'GM12878') & (posRate['TF/DNase/HistoneMark'] == 'BRCA1') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'GM12801') & (posRate['TF/DNase/HistoneMark'] == 'CTCF') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'HepG2') & (posRate['TF/DNase/HistoneMark'] == 'Nrf1') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'K562') & (posRate['TF/DNase/HistoneMark'] == 'E2F4') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'GM12878') & (posRate['TF/DNase/HistoneMark'] == 'c-Fos') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'HeLa-S3') & (posRate['TF/DNase/HistoneMark'] == 'IRF3') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'H1-hESC') & (posRate['TF/DNase/HistoneMark'] == 'SP4') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'GM12891') & (posRate['TF/DNase/HistoneMark'] == 'TAF1') & (posRate['Treatment'] == 'None')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'K562') & (posRate['TF/DNase/HistoneMark'] == 'STAT2') & (posRate['Treatment'] == 'IFNa6h')]['Positive Proportion'].item()) TFposRate.append(posRate[(posRate['Cell Type'] == 'K562') & (posRate['TF/DNase/HistoneMark'] == 'ZNF274') & (posRate['Treatment'] == 'None')]['Positive Proportion'].tolist()[0]) TFposRate = pd.DataFrame(TFposRate, columns=['Positive Rate'], index=TFs) TFposRate.head(10) # normalizing as a function of positive proportion in experimental data for i, index in enumerate(TFposRate.index): print('Normalizing data for TF ', index, ' (', i+1,'/10)') myitem = TFposRate.iloc[i].item() # finalResults[index] = finalResults[index].map(lambda P:1/(1+math.exp(-(math.log(P/(1-P))+math.log(0.05/(1-0.05))-math.log(TFposRate.iloc[i].item()/(1-TFposRate.iloc[i].item())))))) finalResults[index] = finalResults[index].map(lambda P:1/(1+math.exp(-(math.log(P/(1-P))+math.log(0.05/(1-0.05))-math.log(myitem/(1-myitem)))))) finalResults.head(-1) # + # save the resulting table to a pickle file # finalResults.to_pickle('predicted_TFBS_normalized_new.pkl') # - # load results from pickle file finalResults = pd.read_pickle('predicted_TFBS_normalized_0-9_final10_low.pkl') finalResults.head(-1)
analyzeResults.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 # --- # + id="ur8xi4C7S06n" # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] id="title:generic,gcp" # # E2E ML on GCP: MLOps stage 6 : Get started with TensorFlow serving functions with Vertex AI Raw Prediction # # <table align="left"> # <td> # <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage6/get_started_with_vertex_raw_predict.ipynb"> # <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab # </a> # </td> # <td> # <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage6/get_started_with_vertex_raw_predict.ipynb"> # <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> # View on GitHub # </a> # </td> # <td> # <a href="https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/stage6/get_started_with_vertex_raw_predict.ipynb"> # <img src="https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32" alt="Vertex AI logo"> # Open in Vertex AI Workbench # </a> # </td> # </table> # <br/><br/><br/> # + [markdown] id="tvgnzT1CKxrO" # ## Overview # # This tutorial demonstrates how use `Vertex AI Raw Prediction` to send raw HTTP content directly to a model deployed to a `Vertex AI Endpoint`. # # For example, the HTTP server for pre-built `Vertex AI` deployment containers does not support the HTTP request body for TensorFlow 1.x estimators. Using raw predict, one can send raw content through the HTTP server that is presented to the model input as-is -- no canonical processing. # + [markdown] id="c9402cfbdc2d" # ### Objective # # In this tutorial, you learn how to use `Vertex AI Raw Prediction` on a `Vertex AI Endpoint` resource. # # This tutorial uses the following Google Cloud ML services and resources: # # - `Vertex AI Raw Prediction` # - `Vertex AI Models` # - `Vertex AI Endpoints` # # The steps performed include: # # - Download a pretrained tabular classification model artifacts for a TensorFlow 1.x estimator. # - Upload the TensorFlow estimator model as a `Vertex AI Model` resource. # - Creating an `Endpoint` resource. # - Deploying the `Model` resource to an `Endpoint` resource. # - Make an online raw prediction to the `Model` resource instance deployed to the `Endpoint` resource. # + [markdown] id="dataset:iris,lcn" # ### Dataset # # This tutorial uses a pre-trained tabular classification model from a public Cloud Storage bucket, which is trained on the Penguins dataset (https://cloud.google.com/bigquery/public-data). The version of the dataset predicts the species. # + [markdown] id="costs" # ### Costs # # This tutorial uses billable components of Google Cloud: # # * Vertex AI # * Cloud Storage # # Learn about [Vertex AI # pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage # pricing](https://cloud.google.com/storage/pricing), and use the [Pricing # Calculator](https://cloud.google.com/products/calculator/) # to generate a cost estimate based on your projected usage. # + [markdown] id="install_aip" # ## Installation # # Install the following packages to execute this notebook. # + id="install_aip" import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_WORKBENCH_NOTEBOOK: USER_FLAG = "--user" # ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG -q # ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG -q # ! pip3 install tensorflow-hub $USER_FLAG -q # + [markdown] id="hhq5zEbGg0XX" # ### Restart the kernel # # After you install the additional packages, you need to restart the notebook kernel so it can find the packages. # + id="EzrelQZ22IZj" # Automatically restart kernel after installs import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) # + [markdown] id="before_you_begin" # ## Before you begin # # ### GPU runtime # # *Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU** # # ### Set up your Google Cloud project # # **The following steps are required, regardless of your notebook environment.** # # 1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs. # # 2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project) # # 3. [Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage.](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com,compute_component,storage-component.googleapis.com) # # 4. If you are running this notebook locally, you will need to install the [Cloud SDK]((https://cloud.google.com/sdk)). # # 5. Enter your project ID in the cell below. Then run the cell to make sure the # Cloud SDK uses the right project for all the commands in this notebook. # # **Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$`. # + [markdown] id="project_id" # #### Set your project ID # # **If you don't know your project ID**, you may be able to get your project ID using `gcloud`. # + id="set_project_id" PROJECT_ID = "[your-project-id]" # @param {type:"string"} # + id="autoset_project_id" if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) # + id="set_gcloud_project_id" # ! gcloud config set project $PROJECT_ID # + [markdown] id="region" # #### Region # # You can also change the `REGION` variable, which is used for operations # throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. # # - Americas: `us-central1` # - Europe: `europe-west4` # - Asia Pacific: `asia-east1` # # You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services. # # Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations). # + id="region" REGION = "[your-region]" # @param {type: "string"} if REGION == "[your-region]": REGION = "us-central1" # + [markdown] id="timestamp" # #### Timestamp # # If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial. # + id="timestamp" from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") # + [markdown] id="gcp_authenticate" # ### Authenticate your Google Cloud account # # **If you are using Vertex AI Workbench Notebooks**, your environment is already authenticated. Skip this step. # # **If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. # # **Otherwise**, follow these steps: # # In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page. # # **Click Create service account**. # # In the **Service account name** field, enter a name, and click **Create**. # # In the **Grant this service account access to project** section, click the Role drop-down list. Type "Vertex" into the filter box, and select **Vertex Administrator**. Type "Storage Object Admin" into the filter box, and select **Storage Object Admin**. # # Click Create. A JSON file that contains your key downloads to your local environment. # # Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. # + id="gcp_authenticate" # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. import os import sys # If on Vertex AI Workbench, then don't execute this code IS_COLAB = False if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv( "DL_ANACONDA_HOME" ): if "google.colab" in sys.modules: IS_COLAB = True from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): # %env GOOGLE_APPLICATION_CREDENTIALS '' # + [markdown] id="bucket:mbsdk" # ### Create a Cloud Storage bucket # # **The following steps are required, regardless of your notebook environment.** # # When you initialize the Vertex AI SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. # # Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. # + id="bucket" BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"} BUCKET_URI = f"gs://{BUCKET_NAME}" # + id="autoset_bucket" if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]": BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP BUCKET_URI = "gs://" + BUCKET_NAME # + [markdown] id="create_bucket" # **Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket. # + id="create_bucket" # ! gsutil mb -l $REGION $BUCKET_URI # + [markdown] id="validate_bucket" # Finally, validate access to your Cloud Storage bucket by examining its contents: # + id="validate_bucket" # ! gsutil ls -al $BUCKET_URI # + [markdown] id="setup_vars" # ### Set up variables # # Next, set up some variables used throughout the tutorial. # ### Import libraries and define constants # + id="import_aip:mbsdk" import google.cloud.aiplatform as aip import tensorflow as tf # + [markdown] id="init_aip:mbsdk" # ### Initialize Vertex AI SDK for Python # # Initialize the Vertex AI SDK for Python for your project and corresponding bucket. # + id="init_aip:mbsdk" aip.init(project=PROJECT_ID, staging_bucket=BUCKET_URI) # + [markdown] id="accelerators:training,cpu,prediction,cpu,mbsdk" # #### Set hardware accelerators # # You can set hardware accelerators for training and prediction. # # Set the variables `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocated to each VM, you would specify: # # (aip.AcceleratorType.NVIDIA_TESLA_K80, 4) # # # Otherwise specify `(None, None)` to use a container image to run on a CPU. # # Learn more about [hardware accelerator support for your region](https://cloud.google.com/vertex-ai/docs/general/locations#accelerators). # # *Note*: TF releases before 2.3 for GPU support will fail to load the custom model in this tutorial. It is a known issue and fixed in TF 2.3. This is caused by static graph ops that are generated in the serving function. If you encounter this issue on your own custom models, use a container image for TF 2.3 with GPU support. # + id="accelerators:training,cpu,prediction,cpu,mbsdk" if os.getenv("IS_TESTING_DEPLOY_GPU"): DEPLOY_GPU, DEPLOY_NGPU = ( aip.gapic.AcceleratorType.NVIDIA_TESLA_K80, int(os.getenv("IS_TESTING_DEPLOY_GPU")), ) else: DEPLOY_GPU, DEPLOY_NGPU = (None, None) # + [markdown] id="container:training,prediction" # #### Set pre-built containers # # Set the pre-built Docker container image for prediction. # # # For the latest list, see [Pre-built containers for prediction](https://cloud.google.com/ai-platform-unified/docs/predictions/pre-built-containers). # + id="container:training,prediction" if os.getenv("IS_TESTING_TF"): TF = os.getenv("IS_TESTING_TF") else: TF = "2.5".replace(".", "-") if TF[0] == "2": if DEPLOY_GPU: DEPLOY_VERSION = "tf2-gpu.{}".format(TF) else: DEPLOY_VERSION = "tf2-cpu.{}".format(TF) else: if DEPLOY_GPU: DEPLOY_VERSION = "tf-gpu.{}".format(TF) else: DEPLOY_VERSION = "tf-cpu.{}".format(TF) DEPLOY_IMAGE = "{}-docker.pkg.dev/vertex-ai/prediction/{}:latest".format( REGION.split("-")[0], DEPLOY_VERSION ) print("Deployment:", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU) # + [markdown] id="machine:training" # #### Set machine type # # Next, set the machine type to use for prediction. # # - Set the variable `DEPLOY_COMPUTE` to configure the compute resources for the VMs you will use for for prediction. # - `machine type` # - `n1-standard`: 3.75GB of memory per vCPU. # - `n1-highmem`: 6.5GB of memory per vCPU # - `n1-highcpu`: 0.9 GB of memory per vCPU # - `vCPUs`: number of \[2, 4, 8, 16, 32, 64, 96 \] # # *Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*. # + id="machine:training" if os.getenv("IS_TESTING_DEPLOY_MACHINE"): MACHINE_TYPE = os.getenv("IS_TESTING_DEPLOY_MACHINE") else: MACHINE_TYPE = "n1-standard" VCPU = "4" DEPLOY_COMPUTE = MACHINE_TYPE + "-" + VCPU print("Train machine type", DEPLOY_COMPUTE) # + [markdown] id="d8128b8ff025" # ## Get pretrained model from the public Cloud Storage location # # For demonstration purposes, this tutorial uses a pretrained model TensorFlow 1.x estimator tabular classification Model, which is then uploaded to a `Vertex AI Model` resource. Once you have a `Vertex AI Model` resource, the model can be deployed to a `Vertex AI Endpoint` resource. # # ### Download the pretrained model # # Download the pretrained TensorFlow estimator model artifacts from the public Cloud Storage, and then upload the model artifacts to your own Cloud Storage bucket. # + id="c55fa4c826f7" MODEL_DIR = BUCKET_URI + "/model" # ! gsutil cp -r gs://cloud-samples-data/vertex-ai/google-cloud-aiplatform-ci-artifacts/models/penguins/estimator/ {MODEL_DIR} # + [markdown] id="e8ce91147c93" # ## Upload the TensorFlow estimator model to a `Vertex AI Model` resource # # Finally, you upload the model artifacts from the TFHub model and serving function into a `Vertex AI Model` resource. # # *Note:* When you upload the model artifacts to a `Vertex AI Model` resource, you specify the corresponding deployment container image. # + id="ad61e1429512" model = aip.Model.upload( display_name="example_" + TIMESTAMP, artifact_uri=MODEL_DIR, serving_container_image_uri=DEPLOY_IMAGE, ) print(model) # + [markdown] id="628de0914ba1" # ## Creating an `Endpoint` resource # # You create an `Endpoint` resource using the `Endpoint.create()` method. At a minimum, you specify the display name for the endpoint. Optionally, you can specify the project and location (region); otherwise the settings are inherited by the values you set when you initialized the Vertex AI SDK with the `init()` method. # # In this example, the following parameters are specified: # # - `display_name`: A human readable name for the `Endpoint` resource. # - `project`: Your project ID. # - `location`: Your region. # - `labels`: (optional) User defined metadata for the `Endpoint` in the form of key/value pairs. # # This method returns an `Endpoint` object. # # Learn more about [Vertex AI Endpoints](https://cloud.google.com/vertex-ai/docs/predictions/deploy-model-api). # + id="0ea443f9593b" endpoint = aip.Endpoint.create( display_name="example_" + TIMESTAMP, project=PROJECT_ID, location=REGION, labels={"your_key": "your_value"}, ) print(endpoint) # + [markdown] id="ca3fa3f6a894" # ## Deploying `Model` resources to an `Endpoint` resource. # # You can deploy one of more `Vertex AI Model` resource instances to the same endpoint. Each `Vertex AI Model` resource that is deployed will have its own deployment container for the serving binary. # # In the next example, you deploy the `Vertex AI Model` resource to a `Vertex AI Endpoint` resource. The `Vertex AI Model` resource already has defined for it the deployment container image. To deploy, you specify the following additional configuration settings: # # - The machine type. # - The (if any) type and number of GPUs. # - Static, manual or auto-scaling of VM instances. # # In this example, you deploy the model with the minimal amount of specified parameters, as follows: # # - `model`: The `Model` resource. # - `deployed_model_displayed_name`: The human readable name for the deployed model instance. # - `machine_type`: The machine type for each VM instance. # # Do to the requirements to provision the resource, this may take upto a few minutes. # + id="4e93b034a72f" response = endpoint.deploy( model=model, deployed_model_display_name="example_" + TIMESTAMP, machine_type=DEPLOY_COMPUTE, ) print(endpoint) # + [markdown] id="make_test_items:bqml,penguins" # #### Make prediction instances # # Next, you prepare a prediction request using a synthetic example. In this example, the model format is a TensorFlow 1.x estimator format. This model format takes a request signature not supported by the HTTP server in the `Vertex AI` prebuilt TensorFlow serving containers. # # For this model format, you use the `raw_predict()` to pass as-is a request that matches directly the serving interfac of the model, with the following request format: # # http_body -> { # 'signature_name' : serving_signature, # 'instances': [ {instance_1}, {instance_2}, ... ] # } # # instance -> { 'feature_1': value_1, 'feature_2': value_2, ... } # # serving_signature -> "predict" # # + id="make_test_items:bqml,penguins" import json from google.api import httpbody_pb2 from google.cloud import aiplatform_v1 DATA = { "signature_name": "predict", "instances": [ { "island": "DREAM", "culmen_length_mm": 36.6, "culmen_depth_mm": 18.4, "flipper_length_mm": 184.0, "body_mass_g": 3475.0, "sex": "FEMALE", } ], } http_body = httpbody_pb2.HttpBody( data=json.dumps(DATA).encode("utf-8"), content_type="application/json", ) req = aiplatform_v1.RawPredictRequest( http_body=http_body, endpoint=endpoint.resource_name ) # + [markdown] id="endpoint_predict:mbsdk" # ### Make a prediction # # Finally, you make the prediction request using Vertex AI Prediction service. # + id="endpoint_predict:mbsdk" API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION) client_options = {"api_endpoint": API_ENDPOINT} pred_client = aip.gapic.PredictionServiceClient(client_options=client_options) response = pred_client.raw_predict(req) print(response) # + [markdown] id="TpV-iwP9qw9c" # ## Cleaning up # # To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud # project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial. # # Otherwise, you can delete the individual resources you created in this tutorial: # + id="sx_vKniMq9ZX" delete_bucket = False delete_model = True delete_endpoint = True if delete_endpoint: try: endpoint.undeploy_all() endpoint.delete() except Exception as e: print(e) if delete_model: try: model.delete() except Exception as e: print(e) if delete_bucket or os.getenv("IS_TESTING"): # ! gsutil rm -rf {BUCKET_URI}
notebooks/community/ml_ops/stage6/get_started_with_raw_predict.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 # --- # # An Analysis of COVID-19 Data in Ireland # ## Created by <NAME> # ![Ireland](https://www.kilts-n-stuff.com/wp-content/uploads/ireland-flying.jpg) # ## Data Source # The data used in this analysis is dowloaded from [European Centre for Disease Prevention and Control](https://www.ecdc.europa.eu/en/publications-data/download-todays-data-geographic-distribution-covid-19-cases-worldwide). # %matplotlib inline import pandas # ## Background on COVID-19 # COVID-19 is an infectious disease that is caused by the SARS-CoV-2 virus. Typically, those infected will experience mild to moderate respiratory illness and will be able to recover. However, some have become seriously ill and have died from the virus. While this typically happens to older people or those with compromised immune systems, anyone can die from COVID-19. Since it is relatively new, COVID-19 has continued to mutate. Scientists are conducting research in order to learn more about this virus and ensure that vaccines remain effective. [(World Health Organization)](https://www.who.int/health-topics/coronavirus#tab=tab_1). # ## An Overview of Ireland's COVID-19 Data df = pandas.read_excel('s3://ia241-2-spring2022-tewksbury/covid_data.xls') ireland_data=df.loc[df['countriesAndTerritories']=='Ireland'] ireland_data[:] # ## Question 1: What is the trend of confirmed COVID-19 cases in Ireland from January 2020 to December 2020? ireland_cases=ireland_data.groupby('month').sum()['cases'] ireland_cases.plot() # ### Explanation of Calculations # I used a line graph in order to convey the trend of COVID-19 cases in 2020. I found it easiest to to this by each month, so the x-axis has January to December (1 to 12). The y-axis has the total number of cases, and the line represents the total number of cases per month. The cases range from 0 to 25,000. # ### Interpretation of Visualizations # In this line graph, April and October were the months with the highest COVID-19 cases in Ireland because the line peaks at both of these points. January, February, July, June, and December all had a low number of cases. October had around 25,000 cases, and April had almost 20,000. January and Feburary both had zero reported cases of COVID-19. COVID-19 cases appear to have peaked twice in 2020, and these peaks were 6 months apart. # ## Question 2: Which month in 2020 had the highest number of COVID-19 deaths in Ireland? ireland_cases=ireland_data.groupby('month').sum()['deaths'] ireland_cases.nlargest(12).plot.bar() # ### Explanation of Calculations # I used a bar chart in order to clearly indicate which month had the highest COVID-19 deaths. I also ordered them from largest to smallest starting from left to right. This helps readers to clearly see the ranking of each month according to the number of COVID-19 deaths. The y-axis represents the number of deaths, which range from zero to almost 1,200. # ### Interpretation of Visualizations # The month of April in 2020 had over 1,000 COVID-19 deaths, while all of the others had 500 or less. January and February had no recorded COVID-19 deaths, which makes sense because the pandemic began in March. Many of the months had 200 deaths or less. April and May had the most deaths. It is interesting that October had the most COVID-19 cases but did not have nearly as many deaths as April. # ## Question 3: How are the number of deaths related to the number of cases in Ireland? ireland_data.plot.scatter(x='cases',y='deaths', c='month') # ### Explanation of Calculations # I used a scatterplot in order to show the relationship between COVID-19 deaths and cases in Ireland. The darker dots represent later months, and the lighter dots are earlier months. The x-axis represents the number of COVID-19 cases, and the y-axis represents the deaths. I included the months because there was an outlier, and I wanted to note that it took place during the month of April. # ### Interpretation of Visualizations # The scatterplot appears very flat due to an outlier. On April 26, 2020, there were 234 recorded deaths from COVID-19. Every other day had less than 100 deaths. Without this outlier, the scatterplot would be more evenly distributed. It also appears that the earlier months had more deaths in comparison with the later months, although the later months still had a high number of COVID-19 cases. Overall, there does not appear to be a very strong correlation between the number of COVID-19 cases and the number of deaths in Ireland during 2020. # ## Conclusion, Limitations, & Improvements # The goal of this project was to use the COVID-19 data from the European Centre for Disease Prevention and Control in order to understand how COVID-19 affected Ireland. I was able to portray the trend in cases, the months with the most deaths, and the relationship between COVID-19 cases and deaths for the year of 2020. # # One limitation present within this assessment was that the data only covered half of December. After December 14, there is no more data; therefore, the December COVID-19 cases and deaths are likely understated. Another limitation was that I did not have a lot of experience in Python. If I had more, I could have done more with the data and made the scatterplot easier to read. # # An improvement that could have been made to this project would have been to analyze COVID-19 data from both 2020 and 2021 and to compare the two years in terms of cases and deaths for Ireland. Since the vaccine was distributed in 2021, it would have been interesting to see how the two years differed. One other improvement would be to compare Ireland to another country, such as Norway. The two countries have similar population sizes and are both in Europe, so it would have been interesting to see how their COVID-19 cases and deaths compared.
Final 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.9.7 64-bit (''mmlab'': conda)' # language: python # name: python3 # --- # + """ๆœฌๆจกๅ—็”จไบŽๅˆ’ๅˆ†่ฎญ็ปƒ้›†ๅ’Œ้ชŒ่ฏ้›†,ๅคงๆฆ‚ๆฏ”ไพ‹7:3""" import shutil import os import random import glob def move_file(raw_path, imgs, new_path): '''่ฟ™ไธชๅ‡ฝๆ•ฐๆ˜ฏ็”จๆฅ็งปๅŠจๅ›พ็‰‡ๅ’Œ็›ธๅบ”็š„jsonๆ–‡ไปถ''' print(raw_path) print(new_path) # filelist = os.listdir(old_path) #ๅˆ—ๅ‡บ่ฏฅ็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ,listdir่ฟ”ๅ›ž็š„ๆ–‡ไปถๅˆ—่กจๆ˜ฏไธๅŒ…ๅซ่ทฏๅพ„็š„,ๅชๆ˜ฏๅฐ†ๅฝ“้ข็›ฎๅฝ•ไธ‹็š„ๆ‰€ๆœ‰ๆ–‡ไปถ็š„ๆ–‡ไปถๅไปฅๅญ—็ฌฆไธฒ็š„ๅฝขๅผๅญ˜ๅ…ฅlistไธญ filelist = imgs print(filelist) for file in filelist: src = os.path.join(raw_path, file[len("/home/gyf/data/sockets/raw_sockets/"):]) dst = os.path.join(new_path, file[len("/home/gyf/data/sockets/raw_sockets/"):]) src_jpg = os.path.join(raw_path, file[len("/home/gyf/data/sockets/raw_sockets/"):-5] + '.jpg') dst_jpg = os.path.join(new_path, file[len("/home/gyf/data/sockets/raw_sockets/"):-5] + '.jpg') print('src:', src) print('dst:', dst) shutil.move(src, dst) shutil.move(src_jpg, dst_jpg) raw_path = "/home/gyf/data/sockets/raw_sockets" new_train = "/home/gyf/data/sockets/train" new_val = "/home/gyf/data/sockets/val" pics = glob.glob("/home/gyf/data/sockets/raw_sockets/*.json") # globๅ’Œos.listdir็š„ๅŒบๅˆซๅœจไบŽglob้ๅކๆŒ‡ๅฎš่ทฏๅพ„ไธ‹ๆ–‡ไปถ็š„ๆ—ถๅ€™้ๅކๅฎŒ็š„pics็š„ๆฏไธชๆ–‡ไปถๅฏนๅบ”ๅญ—็ฌฆไธฒๅๅญ—ๆ˜ฏๅŒ…ๅซ่ทฏๅพ„็š„ print("divising....") move_file(raw_path, pics[:133], new_train) print("divising train end!") print("divising...") move_file(raw_path, pics[133:], new_val) print("divising validation end!")
gyf/division_data.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 math import scipy from scipy import stats def z_and_p(x1,x2,sigma1,sigma2,n1,n2): z=(x1-x2)/(math.sqrt(((sigma1**2)/n1)+((sigma2**2)/n2))) if(z<0): p=stats.norm.cf(z) else: p=1-stats.norm.cdf(z) print(z,p) z_and_p(121,112,8,8,10,10) b=[89.19,90.95,90.46,93.21,97.19,97.04,91.07,92.75] a=[91.5,94.18,92.18,95.39,91.79,89.07,94.72,89.21] stats.ttest_ind(a,b,equal_var=True) stats.t.ppf(0.025,14)
Week 4 Two Sample Test.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 # --- # # 4. Quantum computation # # Quantum computation is a new way of doing computation which differs from the classical way. Classical computations can be implemented in several ways, the most successful one today is the circuit model of computation. This is how elements in modern computers are designed. In the circuit model, a computation is made by taking a string of bits as inputs, doing certain operations on them and giving a new string of bits as output. In the current paradigm, these operations are logical operations that follow Boole's logic. It was proved that one needs to be able to carry out a limited set of operation (namely "NOT gate", and "AND gate") in order to implement any operation (addition, multiplication, division, ... ) by a combination of operation from this set. This fundamental set of gates is called an "elementary set of gates" and is all that is required to be able to do any computation. Similarly to classical computation, quantum computation can be done using the circuit model of computation. In this case, bits are replaced by qubits and logic gates must be substituted with quantum gates which can operate on qubits while keeping intact their special quantum properties. Quantum circuits must be reversible due to the reversibility inherent in the laws of quantum mechanics. # A reversible circuit allows you to run the computation backwards and retrieve the inputs given the outputs. Classical computation can also be implemented using reversible gates but there are disadvantages with regards to the circuit size and complexity. Thus, modern computer are built with "irreversible" logic (which means it's impossible to run the computation backwards, see truth table of the "AND" gate for example) and this is the reason why the generate heat! In order to have reversible quantum gates, one must implement these gates using, what is called a "unitary operation", that is an operation which preserve the sum of the probabilities of seeing each of the measurable values of the qubits. Although, the probability of seeing any single outcome can change, their sum will always add up to one. # # ## 4.1 The qubit # # # In quantum computation the objects of the computation are quantum objects called qubits. Similarly to bits, when qubits are measured they can only take two values: $\lvert 0 \rangle$, $\lvert 1 \rangle $. # Where the brackets around the number points to the fact that these are quantum objects (see Dirac's notation). # In linear algebra representation, the state of a qubit is a vector in a two-dimensional Hilbert space. One of the possible basis for this space is the so-called computational basis which is formed by the eigenvector of the Pauli Z matrix (more details below), the $\lvert 0 \rangle$ and $\lvert 1 \rangle $ states. In matrix form, they can be written as # # $$ # \lvert 0 \rangle = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} # $$ # # $$ # \lvert 1 \rangle = # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} # $$ # # A generic vector $\lvert \psi \rangle $ in the Hilbert space can then be constructed as a linear combination of the basis vectors # # $$ # \lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle = # \begin{pmatrix} # \alpha \\ # \beta # \end{pmatrix} # $$ # # where $\alpha$ and $\beta$ are two complex numbers. # # # ### Superposition # # Differently from the regular bits stored in a computer, which can either take the value of $"0"$ or $"1"$, during a computation qubits can be in a state $\lvert \psi \rangle$ which is a superposition of $\lvert 0 \rangle$ and $\lvert 1 \rangle$: # # \begin{equation} # \lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle , # \end{equation} # # # where $\alpha$ and $\beta$ are related to the probability of obtaining the corresponding outcome $\lvert 0 \rangle$ or $\lvert 1 \rangle$ when the qubit is measured to learn its value. # # \begin{eqnarray} # \text{P}(\text{qubit state} = 0) = \lvert \alpha \rvert^{2} \\ \notag # \text{P}(\text{qubit state} = 1) = \lvert \beta \rvert^{2} # \end{eqnarray} # # Which means that the value of the qubit is not determined until it is measured. This is a counter-intuitive property of quantum mechanical objects. A qubit in a superposition of different states will behave as if it possess properties of all the states in the superposition. However, when measured, the qubit will be in one of the states of the superposition, with a probability given by the modulo square of the coefficient of the corresponding state. # # # ### Multi-qubit state # # In quantum computation, one is generally interested in doing operations on a qubit register which contains a collection of qubits. To denote the state of an $n$ qubit register, one of the following equivalent notations is used: # # \begin{equation} # \lvert 0 \rangle_1 \otimes \lvert 1 \rangle_2 \otimes ... \otimes \lvert 0 \rangle_n \equiv \lvert 0, 1, ..., 0 \rangle \equiv \lvert 01...0 \rangle # \end{equation} # # Where each of the zeros or ones correspond to the state of one of the qubit in the register and the index counts the qubit's number. The linear algebra meaning of all these notations (although less and less explicit going from left to right) is that the Hilbert space containing the state of the multi-qubit system is a tensor product $\otimes$ of the Hilbert spaces of the single qubits and the state of the system is a Dirac ket vector in this tensor product space. That is, the state of the system is a tensor product of the state of the single qubits. So, if the Hilbert space of one qubit has dimension $2$, the Hilbert space of an $n$-qubit register has dimension $2^n$ # # As an example, let us consider the case of $n=2$ qubits. The matrix form of the basis of the 4-dimensional Hilbert space is given by the tensor product of the basis vectors of each of the single qubit spaces. # From the definition of tensor product between vectors given in Chapter 2, we have # # $$ # \lvert 00 \rangle = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} \otimes # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 1 \cdot 1 \\ # 1 \cdot 0 \\ # 0 \cdot 1 \\ # 0 \cdot 0 # \end{pmatrix} = # \begin{pmatrix} # 1 \\ # 0 \\ # 0 \\ # 0 # \end{pmatrix} # $$ # # $$ # \lvert 01 \rangle = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} \otimes # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 1 \cdot 0 \\ # 1 \cdot 1 \\ # 0 \cdot 0 \\ # 0 \cdot 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 1 \\ # 0 \\ # 0 # \end{pmatrix} # $$ # # $$ # \lvert 10 \rangle = # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} \otimes # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \cdot 1 \\ # 0 \cdot 0 \\ # 1 \cdot 1 \\ # 1 \cdot 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 0 \\ # 1 \\ # 0 # \end{pmatrix} # $$ # # $$ # \lvert 11 \rangle = # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} \otimes # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \cdot 0 \\ # 0 \cdot 1 \\ # 1 \cdot 0 \\ # 1 \cdot 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 0 \\ # 0 \\ # 1 # \end{pmatrix} # $$ # # The extension to $n$ qubits is then straightforward, although tedious. # # ### Entanglement # # Another interesting property of qubits, which departs from the classical world, is that they can be entangled. If qubits are entangled with each other, the value taken by each of them is strictly related to the value taken by the other. The correlations between the values of entangled qubits is so strong that it cannot be described by classical probability theory. This is one of the most peculiar features of quantum mechanics. # In a way, entangled qubits lose their identity as individual objects, as their properties now depend on the properties of the other qubits with which they are entangled. It's not possible to separate an entangled system in independent parts and it must be treated as a new unit (in quantum mechanical terms, the state of the whole system is not separable, it cannot be factorized as product state of the state of individual systems). # To see the difference between an entangled state and a non-entangle state, consider the following two possibilities for a two-qubit state: # <ol> # <li> $\frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_1 \otimes \lvert 0 \rangle_2 \right) + \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_1 \otimes \lvert 1 \rangle_2 \right) $ </li> # # <li> $\frac{1}{2} \left( \lvert 0 \rangle_1 \otimes \lvert 0 \rangle_2 \right) + \frac{1}{2} \left( \lvert 1 \rangle_1 \otimes \lvert 1 \rangle_2 \right)$ </li> # </ol> # # The state shown in 1. can be manipulated so that it will look like the tensor product of the state of the first qubit and the state of the second qubit. In fact, we can rewrite 1. as: $ \lvert 0 \rangle_1 \otimes \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle_2 + \lvert 1 \rangle_2 \right) $. Thus, we can say that the first qubit is in the state $\lvert 0 \rangle_1$ and the second qubit is in an equal superposition of $\lvert 0 \rangle_2$ and $\lvert 1 \rangle_2$. # The same procedure cannot be done on the two-qubit state shown in 2. which cannot be manipulated so that the two-qubit state looks like a tensor product of the state of the first qubit and the state of the second qubit. Therefore, one cannot say anything about the state of a single qubit in state 2. but one has always to talk about the joint state of the two qubits. If one of them has value $"0"$ the other one will have value $"0"$ as well, and if one qubit has value $"1"$, the other qubit will have value $"1"$ too. This purely quantum correlation between the states of a system is what is called quantum entanglement. # ## 4.2 Quantum gates # # # Quantum gates implement operations on qubits by keeping intact their quantum properties. They correspond to operators acting on the qubit register. Furthermore, they allow some of those properties to arise, for example by putting qubits in a superposition of states or entangling them with each other. # It was shown that, similarly to the classical case, it is only really necessary to be able to perform a finite set of quantum gates on the qubits to implement any possible operation on them by combining these particular quantum gates. The minimum set of quantum gates needed for computation is then called a "universal set of quantum gates". # # Let's see some quantum gates: # # ### 4.2.1 One-qubit gates # # These gates act on one of the qubits in the qubit register, leaving all other qubits unaffected. # # #### Identity gate # The identity gate I leaves the state of a qubit unchanged. In matrix form this is just the identity matrix in a two-dimensional vector space # # <img src="figures/4/I1.jpeg" width="150"> # $$\text{1. Identity gate.}$$ # # $$ # \hat{I} = # \begin{pmatrix} # 1 & 0\\ # 0 & 1 # \end{pmatrix} # $$ # # and its action on the state of a qubit is # # $$ # \hat{I} \lvert 0 \rangle = # \begin{pmatrix} # 1 & 0\\ # 0 & 1 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = \lvert 0 \rangle # $$ # # $$ # \hat{I} \lvert 1 \rangle = # \begin{pmatrix} # 1 & 0\\ # 0 & 1 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = \lvert 1 \rangle # $$ # # #### Pauli X gate # The X gate flips the state of a qubit from $\lvert 0 \rangle \rightarrow \lvert 1 \rangle $ and $\lvert 1 \rangle \rightarrow \lvert 0 \rangle $. It is the quantum analog of the NOT gate and it is sometimes referred to as the "bit-flip gate". When considering the Bloch sphere representation of a qubit, the X gate correspond to a $\pi$ rotation around the y-axis. # # <img src="figures/4/X1.jpeg" width="150"> # $$\text{2. X gate.}$$ # # # In matrix representation, the X gate is # # $$ # \hat{X} = # \begin{pmatrix} # 0 & 1\\ # 1 & 0 # \end{pmatrix} # $$ # # Its action on a qubit is # # $$ # \hat{X} \lvert 0 \rangle = # \begin{pmatrix} # 0 & 1\\ # 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = \lvert 1 \rangle # $$ # # $$ # \hat{X} \lvert 1 \rangle = # \begin{pmatrix} # 0 & 1\\ # 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = \lvert 0 \rangle # $$ # # # # #### Pauli Z gate # The Z gate flips the phase of a qubit if it is in the $\lvert 1 \rangle$ state. This correspond to a $\pi$ rotation around the z-axis. # # <img src="figures/4/Z1.jpeg" width="150"> # $$\text{3. Z gate.}$$ # # In matrix representation, the Z gate is # # $$ # \hat{Z} = # \begin{pmatrix} # 1 & 0\\ # 0 & -1 # \end{pmatrix} # $$ # # The effect on the state of a qubit is # # $$ # \hat{Z} \lvert 0 \rangle = # \begin{pmatrix} # 1 & 0\\ # 0 & -1 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = \lvert 0 \rangle # $$ # # $$ # \hat{Z} \lvert 1 \rangle = # \begin{pmatrix} # 1 & 0\\ # 0 & -1 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # -1 # \end{pmatrix} = - \lvert 1 \rangle # $$ # # #### Pauli Y gate # The Y gate flips the state of a qubit and its phase and is sometimes called the " bit- and phase-flip gate". # # <img src="figures/4/Y1.jpeg" width="150"> # $$\text{4. Y gate.}$$ # # The definition of the Y gate in matrix form is # # $$ # \hat{Y} = # \begin{pmatrix} # 0 & -i\\ # i & 0 # \end{pmatrix} # $$ # # The effect of the Y gate on the state of a qubit is # # $$ # \hat{Y} \lvert 0 \rangle = # \begin{pmatrix} # 0 & -i\\ # i & 0 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # i # \end{pmatrix} = i \lvert 1 \rangle # $$ # # $$ # \hat{Y} \lvert 1 \rangle = # \begin{pmatrix} # 0 & -i\\ # i & 0 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # -i \\ # 0 # \end{pmatrix} = -i \lvert 0 \rangle # $$ # # As the name of the Y gate suggest, the Y gate itself is not an independent gate but it is the combination of the X and Z gate. In particular, let us consider # # $$ # i\hat{X}\hat{Z} = # i \begin{pmatrix} # 0 & 1\\ # 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 1 & 0\\ # 0 & -1 # \end{pmatrix} = # i \begin{pmatrix} # 0 & -1\\ # 1 & 0 # \end{pmatrix} = # \begin{pmatrix} # 0 & -i\\ # i & 0 # \end{pmatrix} = Y # $$ # # # # #### Hadamard gate # The Hadamard gate H puts a qubit in an equal superposition of $\lvert 0 \rangle$ and $\lvert 1 \rangle$. # # <img src="figures/4/H1.jpeg" width="150"> # $$\text{5. Hadamard gate.}$$ # # Its matrix representation is # # $$ # \hat{H} = # \frac{1}{\sqrt{2}} # \begin{pmatrix} # 1 & 1\\ # 1 & -1 # \end{pmatrix} # $$ # # Acting with the Hadamard gate on a qubit gives # # $$ # \hat{H} \lvert 0 \rangle = # \frac{1}{\sqrt{2}} # \begin{pmatrix} # 1 & 1\\ # 1 & -1 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 # \end{pmatrix} = # \frac{1}{\sqrt{2}} \begin{pmatrix} # 1 \\ # 1 # \end{pmatrix} = \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle + \lvert 1 \rangle \right) # $$ # # $$ # \hat{H} \lvert 1 \rangle = # \frac{1}{\sqrt{2}} # \begin{pmatrix} # 1 & 1\\ # 1 & -1 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 # \end{pmatrix} = # \frac{1}{\sqrt{2}} \begin{pmatrix} # 1 \\ # -1 # \end{pmatrix} = \frac{1}{\sqrt{2}} \left( \lvert 0 \rangle - \lvert 1 \rangle \right) # $$ # # #### Rotations # Rotations around an axis ($R_x, R_y, R_z$): Rotates qubit state $\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle $, by changing the coefficients $\alpha, \beta$ in a way that depends on the angle of rotation. # # <img src="figures/4/R1.jpeg" width="300"> # $$\text{6. Rotation gate around the $x$, $y$ and $z$ axis.}$$ # # In matrix form # # $$ # \hat{R}_x(\theta) = # \begin{pmatrix} # \cos(\theta/2) & -i\sin(\theta/2)\\ # -i\sin(\theta/2) & \cos(\theta/2) # \end{pmatrix} # $$ # # # $$ # \hat{R}_y(\theta) = # \begin{pmatrix} # \cos(\theta/2) & \sin(\theta/2)\\ # \sin(\theta/2) & \cos(\theta/2) # \end{pmatrix} # $$ # # # $$ # \hat{R}_z(\theta) = # \begin{pmatrix} # 1 & 0 \\ # 0 & e^{i \theta} # \end{pmatrix} # $$ # # Their action is # # $$ \hat{R}_x(\theta) \lvert \psi \rangle = # \begin{pmatrix} # \cos(\theta/2) & -i\sin(\theta/2)\\ # -i\sin(\theta/2) & \cos(\theta/2) # \end{pmatrix} # \begin{pmatrix} # \alpha \\ # \beta # \end{pmatrix} = # \begin{pmatrix} # \cos(\theta/2) \alpha -i\sin(\theta/2) \beta\\ # -i\sin(\theta/2) \alpha + \cos(\theta/2) \beta # \end{pmatrix} = \left( \cos(\theta/2) \alpha -i\sin(\theta/2) \right) \lvert 0 \rangle + \left( -i\sin(\theta/2) \alpha + \cos(\theta/2) \beta \right) \lvert 1 \rangle$$ # # $$ \hat{R}_y(\theta) \lvert \psi \rangle = # \begin{pmatrix} # \cos(\theta/2) & \sin(\theta/2)\\ # \sin(\theta/2) & \cos(\theta/2) # \end{pmatrix} # \begin{pmatrix} # \alpha \\ # \beta # \end{pmatrix} = # \begin{pmatrix} # \cos(\theta/2) \alpha + \sin(\theta/2) \beta\\ # \sin(\theta/2) \alpha + \cos(\theta/2) \beta # \end{pmatrix} = \left( \cos(\theta/2) \alpha + \sin(\theta/2) \right) \lvert 0 \rangle + \left( \sin(\theta/2) \alpha + \cos(\theta/2) \beta \right) \lvert 1 \rangle$$ # # # $$ \hat{R}_z(\theta) \lvert \psi \rangle = # \begin{pmatrix} # 1 & 0 \\ # 0 & e^{i \theta} # \end{pmatrix} # \begin{pmatrix} # \alpha \\ # \beta # \end{pmatrix} = # \begin{pmatrix} # \alpha \\ # e^{i \theta} \beta # \end{pmatrix} = \alpha \lvert 0 \rangle + e^{i \theta} \beta \lvert 1 \rangle $$ # # # ### 4.2.2 Multi-qubit gates # # <img src="figures/4/multi_qubit1.jpeg" width="150"> # $$\text{7. Two single-qubit gates. $X$ on the first qubit and $I$ on the second qubit.}$$ # # If we are dealing with a qubit register that contains more than a single qubit, the operators on the whole register can be obtained by taking the tensor product of the operators acting on each qubit. To avoid lengthy calculations, we work out a few examples for a two-qubit register. We have shown above the form of the basis vector of a two-qubit register. # As an example, consider the matrix representation of the X gate on the first qubit is # # $$ # \hat{X} \otimes \hat{I} = # \begin{pmatrix} # 0 & 1 \\ # 1 & 0 # \end{pmatrix} \otimes # \begin{pmatrix} # 1 & 0 \\ # 0 & 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \cdot 1 & 0 \cdot 0 & 1 \cdot 1 & 1 \cdot 0 \\ # 0 \cdot 0 & 0 \cdot 1 & 1 \cdot 0 & 1 \cdot 1 \\ # 1 \cdot 1 & 1 \cdot 0 & 0 \cdot 1 & 0 \cdot 0 \\ # 1 \cdot 0 & 1 \cdot 1 & 0 \cdot 0 & 0 \cdot 1 # \end{pmatrix} = # \begin{pmatrix} # 0 & 0 & 1 & 0\\ # 0 & 0 & 0 & 1\\ # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0 # \end{pmatrix} # $$ # # The action of this operator on a two-qubit register will be # # $$ # \left( \hat{X} \otimes \hat{I} \right) \lvert 00 \rangle = # \begin{pmatrix} # 0 & 0 & 1 & 0\\ # 0 & 0 & 0 & 1\\ # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0\\ # 0\\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 0\\ # 1\\ # 0 # \end{pmatrix} = # \lvert 10 \rangle # $$ # # Exactly as expected. If we now want to combine different type of single qubit gates, acting on the two-qubit register, we only need to calculate the tensor product between these operators to find what is their matrix representation. # # # # ### 4.2.3 Two-qubit gates # # #### Control-NOT gate # # The most reknown two-qubit gate is the control-not gate or CNOT (CX) gate. The CX gate flips the state of a qubit (called $target$) conditionally on the state of another qubit (called $control$). # # <img src="figures/4/CX1.jpeg" width="150"> # $$\text{8. CNOT gate. The first qubit is the control and the second is the target.}$$ # # The matrix representation of the CX gate is the following # # $$ # \hat{C}X_{12} = # \begin{pmatrix} # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0\\ # 0 & 0 & 0 & 1\\ # 0 & 0 & 1 & 0 # \end{pmatrix} # $$ # # Let us see the effect of acting with the CX gate on a two-qubit register. In the matrix form shown above, the first qubit will be the control qubit and the second qubit will be the target qubit. # If the control qubit is in the state $\lvert 0 \rangle$, nothing is done to the target qubit. If the control qubit is in state $\lvert 1 \rangle$, the X gate (bit-flip) is applied to the target qubit. # # # $$ # \hat{C}X_{12} \lvert 00 \rangle = # \begin{pmatrix} # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0\\ # 0 & 0 & 0 & 1\\ # 0 & 0 & 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 1 \\ # 0 \\ # 0 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 1 \\ # 0 \\ # 0 \\ # 0 # \end{pmatrix} = \lvert 00 \rangle # $$ # # $$ # \hat{C}X_{12} \lvert 01 \rangle = # \begin{pmatrix} # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0\\ # 0 & 0 & 0 & 1\\ # 0 & 0 & 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 1 \\ # 0 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 1 \\ # 0 \\ # 0 # \end{pmatrix} = \lvert 01 \rangle # $$ # # $$ # \hat{C}X_{12} \lvert 10 \rangle = # \begin{pmatrix} # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0\\ # 0 & 0 & 0 & 1\\ # 0 & 0 & 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 0 \\ # 1 \\ # 0 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 0 \\ # 0 \\ # 1 # \end{pmatrix} = \lvert 11 \rangle # $$ # # $$ # \hat{C}X_{12} \lvert 11 \rangle = # \begin{pmatrix} # 1 & 0 & 0 & 0\\ # 0 & 1 & 0 & 0\\ # 0 & 0 & 0 & 1\\ # 0 & 0 & 1 & 0 # \end{pmatrix} # \begin{pmatrix} # 0 \\ # 0 \\ # 0 \\ # 1 # \end{pmatrix} = # \begin{pmatrix} # 0 \\ # 0 \\ # 1 \\ # 0 # \end{pmatrix} = \lvert 10 \rangle # $$ # # There is also another way to write the action of the CNOT gate in Dirac's notation: # # $$\hat{C}X_{12} \lvert x, y \rangle = \lvert x, x \oplus y \rangle $$ # # where $x,y= \{ 0,1 \}$. So that: # # # $$\hat{C}X_{12} \lvert 0, 0 \rangle = \lvert 0, 0 \oplus 0 \rangle = \lvert 0, 0 \rangle $$ # # $$\hat{C}X_{12} \lvert 0, 1 \rangle = \lvert 0, 1 \oplus 0 \rangle = \lvert 0, 1 \rangle $$ # # $$\hat{C}X_{12} \lvert 1, 0 \rangle = \lvert 0, 0 \oplus 1 \rangle = \lvert 1, 1 \rangle$$ # # $$\hat{C}X_{12} \lvert 1, 1 \rangle = \lvert 1, 1 \oplus 1 \rangle = \lvert 1, 0 \rangle $$ # ## Problems # # # <ol> # # <li> # Consider the generic state of a qubit $\lvert \psi \rangle = \alpha \lvert 0 \rangle + \beta \lvert 1 \rangle $. Give the values of $\alpha$ and $\beta$ (normalized to $\lvert \alpha \rvert^2 + \lvert \beta \rvert^2 = 1$) to represent the following ket-vectors # <ol> # <li> # $ \lvert 0 \rangle $ # </li> # # <li> # $ \lvert 1 \rangle $ # </li> # # <li> # equal superposition of $\lvert 0 \rangle $ and $\lvert 1 \rangle$ # </li> # </ol> # </li> # # # <li> # Find the basis for the Hilbert space of three qubits (it has dimension 8) using the tensor product of the computational basis of the Hilbert space of a qubit. # </li> # # # <li> # Given a qubit in the state $\lvert \psi \rangle = \frac{\sqrt{2}}{\sqrt{6}} \lvert 0 \rangle + \frac{\sqrt{4}}{\sqrt{6}} \lvert 1 \rangle$, Calculate: # # <ol> # <li> # $ \hat{X} \lvert \psi \rangle $ # </li> # # <li> # $\hat{Z} \lvert \psi \rangle$ # </li> # # <li> # $\hat{X} \lvert \psi \rangle$ # </li> # # <li> # $\hat{Y} \lvert \psi \rangle$ # </li> # # <li> # $\hat{H} \lvert \psi \rangle$ # </li> # # </ol> # </li> # # # <li> # Calculate the following multi-qubit operators in matrix form # # <ol> # <li> # $ X \otimes X $ # </li> # # <li> # $ H \otimes H $ # </li> # # <li> # $ H \otimes Z $ # </li> # </ol> # </li> # # # <li> # Given a qubit in the state $\lvert \psi \rangle = \frac{\sqrt{2}}{\sqrt{6}} \lvert 00 \rangle + \frac{\sqrt{2}}{\sqrt{6}} \lvert 01 \rangle + \frac{\sqrt{i}}{\sqrt{6}} \lvert 10 \rangle + \frac{\sqrt{1}}{\sqrt{6}} \lvert 11 \rangle$, Calculate $\hat{C}X_{12} \lvert \psi \rangle$, where the first qubit is the control qubit and the second qubit is the target qubit. # </li> # # # </ol> # # ## References # # [1] <NAME>, Simulating Physics with Computers, International Journal of Theoretical # Physics, Vol. 21, nos. 6/7, pp. 467{488 (1982). # # [2] <NAME>, and <NAME>, 2000, Quantum Computation # and Quantum Information (Cambridge University Press, Cambridge). # # [3] <NAME> al., Phys. Rev. A 52, 3457 (1995).
4.Quantum computation.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/Abhijit-2592/visualizing_cnns/blob/master/saliency_map.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + id="20X8rT5XtspT" colab_type="code" outputId="3b8b98f7-1fea-4d72-ed36-7631a97d7a89" colab={"base_uri": "https://localhost:8080/", "height": 34} # %tensorflow_version 2.x # + [markdown] id="yoeV2dyW6MMl" colab_type="text" # In this and the activation_maximization.ipynb notebooks we will try to understand the visualization technique presented in the following paper: # # # [Deep Inside Convolutional Networks: Visualising # Image Classification Models and Saliency Maps](https://arxiv.org/pdf/1312.6034.pdf). # # Here we are trying to find the regions of image which are mostly responsible for a specific class prediction # # ## NOTE: # # In the paper under section 3, the authors approximate the linear scoring function by using the 1st order term from the Tailor expansion of the softmax function (See equations 2 and 3). Instead of taking the 1st order term from the Tailor expansion we can do another trick to approximate a Linear scoring function: Just Swap the Softmax activation to a Linear/Identity activation in the output. # # + id="NxQWMKiMt57A" colab_type="code" colab={} import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import cv2 # + id="FvPjXhCvuDCw" colab_type="code" outputId="10ec003a-dd57-4199-cb32-596ce8e0a8df" colab={"base_uri": "https://localhost:8080/", "height": 50} model = tf.keras.applications.vgg16.VGG16(include_top=True, weights="imagenet") # + id="oPYD-JYBuInQ" colab_type="code" outputId="563f59a2-748d-4c8e-9dc2-9adca15e0d90" colab={"base_uri": "https://localhost:8080/", "height": 924} model.summary() # + id="l7ufbMP5uKjO" colab_type="code" outputId="bae1cd8b-453e-472b-e091-d40359326bef" colab={"base_uri": "https://localhost:8080/", "height": 269} image = np.array(tf.keras.preprocessing.image.load_img(path="./images/labrador.jpeg",target_size=(224,224))) plt.imshow(image) plt.show() # + id="XVNhQqCZuX8e" colab_type="code" colab={} preprocessed_image = tf.keras.applications.vgg16.preprocess_input(image.astype(np.float32)) preprocessed_image = np.expand_dims(preprocessed_image, axis=0) # reshape it to (1,224,224,3), # + id="dFAiP33cuc82" colab_type="code" colab={} # trick to get optimal visualizations swap softmax with linear model.get_layer("predictions").activation = None # + id="Wedhb1LOuf8R" colab_type="code" colab={} def get_gradients(model, image, class_index): image_tensor = tf.convert_to_tensor(image, dtype="float32") with tf.GradientTape() as tape: tape.watch(image_tensor) output = model(image_tensor) loss = tf.reduce_mean(output[:, class_index]) grads = tape.gradient(loss, image_tensor) return grads # + id="PaosSaDsuiXm" colab_type="code" colab={} class_index = 208 # labrador grads = get_gradients(model, preprocessed_image, class_index=class_index) # + id="UpCPKwKyukxo" colab_type="code" colab={} gradient_image = grads.numpy()[0] # + id="04TfaRLjuqpo" colab_type="code" outputId="a4384670-fd9e-49d4-db91-90043ab7b194" colab={"base_uri": "https://localhost:8080/", "height": 34} gradient_image.shape # + id="jihsw5FnutVE" colab_type="code" colab={} saliency_map = np.max(np.abs(gradient_image), axis=2) # + id="h3V_-0fEuvjB" colab_type="code" outputId="d6dad0d7-b739-4394-fe64-8b7b978b7920" colab={"base_uri": "https://localhost:8080/", "height": 34} saliency_map.shape # + id="HSqnvzceuxzd" colab_type="code" outputId="e744ab13-bb57-4399-afd2-3825075683bb" colab={"base_uri": "https://localhost:8080/", "height": 269} plt.imshow(saliency_map) plt.show() # + [markdown] id="XC1LvGl06sv9" colab_type="text" # The visualized saliency maps are a bit noisy. We can get better saliency maps by doing guided backprop: see slide 25 from [Andrej's lecture](http://cs231n.stanford.edu/slides/2016/winter1516_lecture9.pdf)
saliency_map.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.8.0 64-bit # language: python # name: python3 # --- import pandas as pd import numpy as np from matplotlib import pyplot as plt # ### Survay losss # + state = 'w' ansatz = 'linear_ansatz_' path = "../../experiments/" + ansatz + state + "/" + str(3) + '/fidelities_sgd.csv' fidelities1 = pd.read_csv(path, sep=",", header=None) fidelities1 = fidelities1.applymap(lambda s: complex(s.replace('i', 'j'))).values path = "../../experiments/" + ansatz + state + "/" + str(3) + '/fidelities_adam.csv' fidelities2 = pd.read_csv(path, sep=",", header=None) fidelities2 = fidelities2.applymap(lambda s: complex(s.replace('i', 'j'))).values path = "../../experiments/" + ansatz + state + "/" + str(3) + '/fidelities_qng.csv' fidelities3 = pd.read_csv(path, sep=",", header=None) fidelities3 = fidelities3.applymap(lambda s: complex(s.replace('i', 'j'))).values plt.ylim(0, 1.1) plt.plot(fidelities1, label = 'SGD') plt.plot(fidelities2, label = 'Adam') plt.plot(fidelities3, label = 'QNG') # plt.savefig(state.upper() + ' state - ' + ansatz + '.eps', dpi = 1000) plt.legend() # - state = 'ghz' ansatz = 'linear_ansatz_' path = "../../experiments/" + ansatz + state + "/" + str(3) + '/loss_values_sgd.csv' loss1 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "../../experiments/" + ansatz + state + "/" + str(3) + '/loss_values_adam.csv' loss2 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "../../experiments/" + ansatz + state + "/" + str(3) + '/loss_values_qng.csv' loss3 = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss1, label = 'SGD') plt.plot(loss2, label = 'Adam') plt.plot(loss3, label = 'QNG') plt.savefig(state.upper() + ' state - ' + ansatz + '.eps', dpi = 1000) plt.legend() # + losss = [] for i in range(2, 11): path = "../experiments/linear_ansatz_w/" + str(i) + '/loss_values_qng.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss, label = str(i) + ' qubits') plt.legend() plt.show() # + losss = [] for i in range(2, 7): path = "../experiments/star_ansatz_ghz/" + str(i) + '/loss_values_sgd.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss, label = str(i) + ' qubits') plt.xlabel('Iteration') plt.ylim((0,0.2)) plt.yticks(np.arange(0, 0.25, 0.05)) plt.ylabel('Value') plt.title('Loss') plt.legend() plt.show() # + qubits = range(2, 7) star_ansatz = [] for i in qubits: path = "../experiments/star_ansatz_" + 'ghz' + "/" + str(i) + '/loss_values_' + 'sgd' + '.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() star_ansatz.append((loss[-1])) plt.ylim((0,0.2)) plt.xticks(np.arange(0, 7, 1)) plt.yticks(np.arange(0, 0.2, 0.05)) plt.plot(qubits, star_ansatz, marker='s', label = 'Star ansatz') # + def get_loss(reconstruted_state, optimizer): losss_linear, losss_star, losss_polygon = [], [], [] qubits = range(2, 11) for i in qubits: path = "../experiments/linear_ansatz_" + reconstruted_state + "/" + str(i) + '/loss_values_' + optimizer + '.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_linear.append(np.min(loss)) for i in qubits: path = "../experiments/star_ansatz_" + reconstruted_state + "/" + str(i) + '/loss_values_' + optimizer + '.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star.append(np.min(loss)) for i in qubits: path = "../experiments/polygon_ansatz_" + reconstruted_state + "/" + str(i) + '/loss_values_' + optimizer + '.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_polygon.append(np.min(loss)) plt.plot(qubits, losss_linear, marker='o', color = 'blue', label = 'Linear ansatz') plt.plot(qubits, losss_star, marker='s', color = 'orange', label = 'Star ansatz') plt.plot(qubits, losss_polygon, marker='^', color = 'green', label = 'Polygon ansatz') plt.xlabel('Number of qubits') plt.yticks(np.arange(0, 1.2, 0.2)) plt.ylabel('Fubini-study loss') # plt.text(3.5, 0.5, optimizer.upper()) plt.title(reconstruted_state.upper() + ' state preparation') plt.legend() plt.savefig(reconstruted_state.upper() + ' state - ' + optimizer.upper() + ' optimizer.eps', dpi = 1000) plt.show() # get_loss('ghz', 'qng') # - get_loss('ghz', 'adam') get_loss('ghz', 'sgd') get_loss('w', 'adam') # + def get_loss(reconstruted_state, optimizer): losss_linear, losss_star, losss_polygon = [], [], [] qubits = range(2, 11) for i in qubits: path = "../experiments/star_ansatz_" + reconstruted_state + "/" + str(i) + '/loss_values_' + optimizer + '.csv' loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star.append(np.min(loss)) plt.plot(qubits, losss_star, label = reconstruted_state) plt.xlabel('Number of qubits') plt.yticks(np.arange(0, 1.4, 0.2)) plt.ylabel('Fubini-study loss') # plt.title(reconstruted_state.upper() + ' state - ' + optimizer.upper() + ' optimizer') plt.legend() get_loss('ghz', 'sgd') get_loss('w', 'sgd') plt.show() # - num_layers = range(2, 6) for i in num_layers: if i == 2: path = "../experiments/star_ansatz_ghz/7/loss_values_qng.csv" else: path = "../experiments/star_ansatz_ghz/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss, label = i) plt.legend() num_layers = range(2, 6) for i in num_layers: if i == 2: path = "../experiments/polygon_ansatz_w/7/loss_values_qng.csv" else: path = "../experiments/polygon_ansatz_w/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy()[:100] plt.plot(loss, label = i) plt.legend() # ### <NAME> # + losss_polygon_ghz, losss_polygon_w, losss_star_ghz, losss_star_w, losss_linear_ghz, losss_linear_w = [], [], [], [], [], [] num_layers = range(2, 6) for i in num_layers: if i == 2: path = "../experiments/polygon_ansatz_w/7/loss_values_qng.csv" else: path = "../experiments/polygon_ansatz_w/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_polygon_w.append(np.min(loss)) for i in num_layers: if i == 2: path = "../experiments/polygon_ansatz_ghz/7/loss_values_qng.csv" else: path = "../experiments/polygon_ansatz_ghz/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_polygon_ghz.append(np.min(loss)) for i in num_layers: if i == 2: path = "../experiments/star_ansatz_ghz/7/loss_values_qng.csv" else: path = "../experiments/star_ansatz_ghz/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz.append(np.min(loss)) for i in num_layers: if i == 2: path = "../experiments/star_ansatz_w/7/loss_values_qng.csv" else: path = "../experiments/star_ansatz_w/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_w.append(np.min(loss)) for i in num_layers: if i == 2: path = "../experiments/linear_ansatz_ghz/7/loss_values_qng.csv" else: path = "../experiments/linear_ansatz_ghz/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_linear_ghz.append(np.min(loss)) for i in num_layers: if i == 2: path = "../experiments/linear_ansatz_w/7/loss_values_qng.csv" else: path = "../experiments/linear_ansatz_w/7/loss_values_qng" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_linear_w.append(np.min(loss)) plt.plot(num_layers, losss_linear_ghz, marker='o', color='blue', label = 'Linear ansatz - GHZ state') plt.plot(num_layers, losss_linear_w, marker='o', color='orange', label = 'Linear ansatz - W state') plt.plot(num_layers, losss_star_ghz, marker='^', color='blue', label = 'Star ansatz - GHZ state') plt.plot(num_layers, losss_star_w, marker='^', color='orange',label = 'Star ansatz - W state') plt.plot(num_layers, losss_polygon_ghz, marker='v', color='blue', label = 'Polygon ansatz - GHZ state') plt.plot(num_layers, losss_polygon_w, marker='v', color='orange', label = 'Polygon ansatz - W state') plt.xlabel('Number of layers') plt.xticks(np.arange(2, 6, 1)) plt.yticks(np.arange(0, 1.2, 0.2)) plt.ylabel('Fubini-study loss') # plt.title(reconstruted_state.upper() + ' state - ' + optimizer.upper() + ' optimizer') plt.legend() plt.savefig('compare_layer.eps', format = 'eps', dpi = 1000) # - # ### Adding noise losss_star_ghz_1, losss_star_ghz_2 = [], [] losss_star_ghz_3, losss_star_ghz_4, losss_star_ghz_5 = [], [], [] num_noise = [0.0, 0.001, 0.005, 0.01, 0.015, 0.02, 0.025, 0.03, 0.035] for i in num_noise: path = "../experiments/star_ansatz_ghz/7/loss_values_qng1_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_1.append(np.min(loss)) for i in num_noise: path = "../experiments/star_ansatz_ghz/7/loss_values_qng2_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_2.append(np.min(loss)) for i in num_noise: path = "../experiments/star_ansatz_ghz/7/loss_values_qng3_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_3.append(np.min(loss)) for i in num_noise: path = "../experiments/star_ansatz_ghz/7/loss_values_qng4_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_4.append(np.min(loss)) for i in num_noise: path = "../experiments/star_ansatz_ghz/7/loss_values_qng5_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_5.append(np.min(loss)) plt.plot(num_noise, losss_star_ghz_1, marker='o', color='blue', label = '1 layer') plt.plot(num_noise, losss_star_ghz_2, marker='o', color='orange', label = '2 layers') plt.plot(num_noise, losss_star_ghz_3, marker='o', color='green', label = '3 layers') plt.plot(num_noise, losss_star_ghz_4, marker='o', color='red', label = '4 layers') plt.plot(num_noise, losss_star_ghz_5, marker='o', color='brown', label = '5 layers') plt.xlabel('Prob noise') plt.xticks(np.arange(0, 0.1, 0.01)) plt.yticks(np.arange(0, 1.2, 0.2)) plt.ylabel('Fubini-study loss') plt.title('Star ansatz - GHZ state') # plt.title(reconstruted_state.upper() + ' state - ' + optimizer.upper() + ' optimizer') plt.legend() # + losss_star_ghz_mitigating, losss_star_ghz_nomitigating = [], [] num_noise = [0.00, 0.01, 0.02, 0.03, 0.04] for i in num_noise: path = "./loss_values_qngm2_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_mitigating.append(np.min(loss)) print(np.min(loss)) for i in num_noise: path = "./loss_values_qngnm2_" + str(i) + ".csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() losss_star_ghz_nomitigating.append(np.min(loss)) plt.plot(num_noise, losss_star_ghz_mitigating, marker='o', color='red', label = 'Mitigated') plt.plot(num_noise, losss_star_ghz_nomitigating, marker='o', color='brown', label = 'Not mitigated') plt.xlabel('Prob noise') plt.xticks(np.arange(0, 0.06, 0.01)) plt.yticks(np.arange(0, 0.7, 0.2)) plt.ylabel('Fubini-study distance') plt.title('Star ansatz - GHZ state') # plt.title(reconstruted_state.upper() + ' state - ' + optimizer.upper() + ' optimizer') plt.legend() plt.savefig('compare_mitigating2.eps', format = 'eps', dpi = 1000) # + path = "./loss_values_qngm2_0.04.csv" loss = pd.read_csv(path, sep=",", header=None).to_numpy() thetass = pd.read_csv("./thetass_qngm2_0.04.csv", sep=",", header=None).to_numpy() imin = np.argmin(loss) thetas = thetass[imin] import qiskit, qtm.ansatz num_qubits = 5 num_layers = 2 qc = qiskit.QuantumCircuit(num_qubits, num_qubits) qc = qtm.ansatz.create_star2graph_state(qc, thetas, num_layers) psi = qiskit.quantum_info.Statevector.from_instruction(qc) rho_psi = qiskit.quantum_info.DensityMatrix(psi) print(psi) # + path = "./loss_values_qngnm2_0.01.csv" loss1 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngnm2_0.02.csv" loss2 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngnm2_0.03.csv" loss3 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngnm2_0.04.csv" loss4 = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss1, ':', color = 'orange', label = 'no mitigating ' + str(i)) plt.plot(loss2, ':', color = 'blue', label = 'no mitigating ' + str(i)) plt.plot(loss3, ':', color = 'green', label = 'no mitigating ' + str(i)) plt.plot(loss4, ':', color = 'red', label = 'no mitigating ' + str(i)) path = "./loss_values_qngm2_0.01.csv" loss1 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.02.csv" loss2 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.03.csv" loss3 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.04.csv" loss4 = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss1, color = 'orange', label = 'mitigating ' + str(i)) plt.plot(loss2, color = 'blue', label = 'mitigating ' + str(i)) plt.plot(loss3, color = 'green', label = 'mitigating ' + str(i)) plt.plot(loss4, color = 'red', label = 'mitigating ' + str(i)) plt.legend() plt.savefig('compare_mitigating.eps', format = 'eps', dpi = 1000) # - path = "./loss_values_qngm2_0.01.csv" loss1 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.02.csv" loss2 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.03.csv" loss3 = pd.read_csv(path, sep=",", header=None).to_numpy() path = "./loss_values_qngm2_0.04.csv" loss4 = pd.read_csv(path, sep=",", header=None).to_numpy() plt.plot(loss1, color = 'orange', label = 'mitigating ' + str(i)) plt.plot(loss2, color = 'blue', label = 'mitigating ' + str(i)) plt.plot(loss3, color = 'green', label = 'mitigating ' + str(i)) plt.plot(loss4, color = 'red', label = 'mitigating ' + str(i)) plt.ylim(0, 0.2) plt.legend()
codes/graph_ansatz/plot_compare_ansatz.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 demonstrates some basic post-processing tasks that can be performed with the Python API, such as plotting a 2D mesh tally and plotting neutron source sites from an eigenvalue calculation. The problem we will use is a simple reflected pin-cell. # + # %matplotlib inline from IPython.display import Image import numpy as np import matplotlib.pyplot as plt import openmc # - # ## Generate Input Files # First we need to define materials that will be used in the problem. Before defining a material, we must create nuclides that are used in the material. # Instantiate some Nuclides h1 = openmc.Nuclide('H-1') b10 = openmc.Nuclide('B-10') o16 = openmc.Nuclide('O-16') u235 = openmc.Nuclide('U-235') u238 = openmc.Nuclide('U-238') zr90 = openmc.Nuclide('Zr-90') # With the nuclides we defined, we will now create three materials for the fuel, water, and cladding of the fuel pin. # + # 1.6 enriched fuel fuel = openmc.Material(name='1.6% Fuel') fuel.set_density('g/cm3', 10.31341) fuel.add_nuclide(u235, 3.7503e-4) fuel.add_nuclide(u238, 2.2625e-2) fuel.add_nuclide(o16, 4.6007e-2) # borated water water = openmc.Material(name='Borated Water') water.set_density('g/cm3', 0.740582) water.add_nuclide(h1, 4.9457e-2) water.add_nuclide(o16, 2.4732e-2) water.add_nuclide(b10, 8.0042e-6) # zircaloy zircaloy = openmc.Material(name='Zircaloy') zircaloy.set_density('g/cm3', 6.55) zircaloy.add_nuclide(zr90, 7.2758e-3) # - # With our three materials, we can now create a materials file object that can be exported to an actual XML file. # + # Instantiate a Materials collection materials_file = openmc.Materials((fuel, water, zircaloy)) materials_file.default_xs = '71c' # Export to "materials.xml" materials_file.export_to_xml() # - # Now let's move on to the geometry. Our problem will have three regions for the fuel, the clad, and the surrounding coolant. The first step is to create the bounding surfaces -- in this case two cylinders and six reflective planes. # + # Create cylinders for the fuel and clad fuel_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.39218) clad_outer_radius = openmc.ZCylinder(x0=0.0, y0=0.0, R=0.45720) # Create boundary planes to surround the geometry # Use both reflective and vacuum boundaries to make life interesting min_x = openmc.XPlane(x0=-0.63, boundary_type='reflective') max_x = openmc.XPlane(x0=+0.63, boundary_type='reflective') min_y = openmc.YPlane(y0=-0.63, boundary_type='reflective') max_y = openmc.YPlane(y0=+0.63, boundary_type='reflective') min_z = openmc.ZPlane(z0=-0.63, boundary_type='reflective') max_z = openmc.ZPlane(z0=+0.63, boundary_type='reflective') # - # With the surfaces defined, we can now create cells that are defined by intersections of half-spaces created by the surfaces. # + # Create a Universe to encapsulate a fuel pin pin_cell_universe = openmc.Universe(name='1.6% Fuel Pin') # Create fuel Cell fuel_cell = openmc.Cell(name='1.6% Fuel') fuel_cell.fill = fuel fuel_cell.region = -fuel_outer_radius pin_cell_universe.add_cell(fuel_cell) # Create a clad Cell clad_cell = openmc.Cell(name='1.6% Clad') clad_cell.fill = zircaloy clad_cell.region = +fuel_outer_radius & -clad_outer_radius pin_cell_universe.add_cell(clad_cell) # Create a moderator Cell moderator_cell = openmc.Cell(name='1.6% Moderator') moderator_cell.fill = water moderator_cell.region = +clad_outer_radius pin_cell_universe.add_cell(moderator_cell) # - # OpenMC requires that there is a "root" universe. Let us create a root cell that is filled by the pin cell universe and then assign it to the root universe. # + # Create root Cell root_cell = openmc.Cell(name='root cell') root_cell.fill = pin_cell_universe # Add boundary planes root_cell.region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z # Create root Universe root_universe = openmc.Universe(universe_id=0, name='root universe') root_universe.add_cell(root_cell) # - # We now must create a geometry that is assigned a root universe, put the geometry into a geometry file, and export it to XML. # Create Geometry and set root Universe geometry = openmc.Geometry() geometry.root_universe = root_universe # Export to "geometry.xml" geometry.export_to_xml() # With the geometry and materials finished, we now just need to define simulation parameters. In this case, we will use 10 inactive batches and 90 active batches each with 5000 particles. # + # OpenMC simulation parameters batches = 100 inactive = 10 particles = 5000 # Instantiate a Settings object settings_file = openmc.Settings() settings_file.batches = batches settings_file.inactive = inactive settings_file.particles = particles # Create an initial uniform spatial source distribution over fissionable zones bounds = [-0.63, -0.63, -0.63, 0.63, 0.63, 0.63] uniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True) settings_file.source = openmc.source.Source(space=uniform_dist) # Export to "settings.xml" settings_file.export_to_xml() # - # Let us also create a plot file that we can use to verify that our pin cell geometry was created successfully. # + # Instantiate a Plot plot = openmc.Plot(plot_id=1) plot.filename = 'materials-xy' plot.origin = [0, 0, 0] plot.width = [1.26, 1.26] plot.pixels = [250, 250] plot.color = 'mat' # Instantiate a Plots collection and export to "plots.xml" plot_file = openmc.Plots([plot]) plot_file.export_to_xml() # - # With the plots.xml file, we can now generate and view the plot. OpenMC outputs plots in .ppm format, which can be converted into a compressed format like .png with the convert utility. # Run openmc in plotting mode openmc.plot_geometry(output=False) # + # Convert OpenMC's funky ppm to png # !convert materials-xy.ppm materials-xy.png # Display the materials plot inline Image(filename='materials-xy.png') # - # As we can see from the plot, we have a nice pin cell with fuel, cladding, and water! Before we run our simulation, we need to tell the code what we want to tally. The following code shows how to create a 2D mesh tally. # Instantiate an empty Tallies object tallies_file = openmc.Tallies() # + # Create mesh which will be used for tally mesh = openmc.Mesh() mesh.dimension = [100, 100] mesh.lower_left = [-0.63, -0.63] mesh.upper_right = [0.63, 0.63] # Create mesh filter for tally mesh_filter = openmc.Filter(type='mesh') mesh_filter.mesh = mesh # Create mesh tally to score flux and fission rate tally = openmc.Tally(name='flux') tally.filters = [mesh_filter] tally.scores = ['flux', 'fission'] tallies_file.append(tally) # - # Export to "tallies.xml" tallies_file.export_to_xml() # Now we a have a complete set of inputs, so we can go ahead and run our simulation. # Run OpenMC! openmc.run() # ## Tally Data Processing # Our simulation ran successfully and created a statepoint file with all the tally data in it. We begin our analysis here loading the statepoint file and 'reading' the results. By default, data from the statepoint file is only read into memory when it is requested. This helps keep the memory use to a minimum even when a statepoint file may be huge. # Load the statepoint file sp = openmc.StatePoint('statepoint.100.h5') # Next we need to get the tally, which can be done with the ``StatePoint.get_tally(...)`` method. tally = sp.get_tally(scores=['flux']) print(tally) # The statepoint file actually stores the sum and sum-of-squares for each tally bin from which the mean and variance can be calculated as described [here](http://mit-crpg.github.io/openmc/methods/tallies.html#variance). The sum and sum-of-squares can be accessed using the ``sum`` and ``sum_sq`` properties: tally.sum # However, the mean and standard deviation of the mean are usually what you are more interested in. The Tally class also has properties ``mean`` and ``std_dev`` which automatically calculate these statistics on-the-fly. print(tally.mean.shape) (tally.mean, tally.std_dev) # The tally data has three dimensions: one for filter combinations, one for nuclides, and one for scores. We see that there are 10000 filter combinations (corresponding to the 100 x 100 mesh bins), a single nuclide (since none was specified), and two scores. If we only want to look at a single score, we can use the ``get_slice(...)`` method as follows. flux = tally.get_slice(scores=['flux']) fission = tally.get_slice(scores=['fission']) print(flux) # To get the bins into a form that we can plot, we can simply change the shape of the array since it is a numpy array. flux.std_dev.shape = (100, 100) flux.mean.shape = (100, 100) fission.std_dev.shape = (100, 100) fission.mean.shape = (100, 100) fig = plt.subplot(121) fig.imshow(flux.mean) fig2 = plt.subplot(122) fig2.imshow(fission.mean) # Now let's say we want to look at the distribution of relative errors of our tally bins for flux. First we create a new variable called ``relative_error`` and set it to the ratio of the standard deviation and the mean, being careful not to divide by zero in case some bins were never scored to. # + # Determine relative error relative_error = np.zeros_like(flux.std_dev) nonzero = flux.mean > 0 relative_error[nonzero] = flux.std_dev[nonzero] / flux.mean[nonzero] # distribution of relative errors ret = plt.hist(relative_error[nonzero], bins=50) # - # ## Source Sites # Source sites can be accessed from the ``source`` property. As shown below, the source sites are represented as a numpy array with a structured datatype. sp.source # If we want, say, only the energies from the source sites, we can simply index the source array with the name of the field: sp.source['E'] # Now, we can look at things like the energy distribution of source sites. Note that we don't directly use the ``matplotlib.pyplot.hist`` method since our binning is logarithmic. # + # Create log-spaced energy bins from 1 keV to 100 MeV energy_bins = np.logspace(-3,1) # Calculate pdf for source energies probability, bin_edges = np.histogram(sp.source['E'], energy_bins, density=True) # Make sure integrating the PDF gives us unity print(sum(probability*np.diff(energy_bins))) # Plot source energy PDF plt.semilogx(energy_bins[:-1], probability*np.diff(energy_bins), linestyle='steps') plt.xlabel('Energy (MeV)') plt.ylabel('Probability/MeV') # - # Let's also look at the spatial distribution of the sites. To make the plot a little more interesting, we can also include the direction of the particle emitted from the source and color each source by the logarithm of its energy. plt.quiver(sp.source['xyz'][:,0], sp.source['xyz'][:,1], sp.source['uvw'][:,0], sp.source['uvw'][:,1], np.log(sp.source['E']), cmap='jet', scale=20.0) plt.colorbar() plt.xlim((-0.5,0.5)) plt.ylim((-0.5,0.5))
docs/source/pythonapi/examples/post-processing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: ibm # language: python # name: ibm # --- # # Machine Learning Foundation # # ## Course 2, Part b: Regression Setup, Train-test Split LAB # + [markdown] run_control={"marked": true} # ## Introduction # # We will be working with a data set based on [housing prices in Ames, Iowa](https://www.kaggle.com/c/house-prices-advanced-regression-techniques). It was compiled for educational use to be a modernized and expanded alternative to the well-known Boston Housing dataset. This version of the data set has had some missing values filled for convenience. # # There are an extensive number of features, so they've been described in the table below. # # ### Predictor # # * SalePrice: The property's sale price in dollars. # # ### Features # # * MoSold: Month Sold # * YrSold: Year Sold # * SaleType: Type of sale # * SaleCondition: Condition of sale # * MSSubClass: The building class # * MSZoning: The general zoning classification # * ... # + run_control={"marked": true} import os data_path = ['data'] # + [markdown] run_control={"marked": true} # ## Question 1 # # * Import the data using Pandas and examine the shape. There are 79 feature columns plus the predictor, the sale price (`SalePrice`). # * There are three different types: integers (`int64`), floats (`float64`), and strings (`object`, categoricals). Examine how many there are of each data type. # + jupyter={"outputs_hidden": false} run_control={"marked": true} import pandas as pd import numpy as np # Import the data using the file path filepath = os.sep.join(data_path + ['Ames_Housing_Sales.csv']) data = pd.read_csv(filepath, sep=',') print(data.shape) # + jupyter={"outputs_hidden": false} run_control={"marked": true} data.dtypes.value_counts() # + [markdown] run_control={"marked": true} # ## Question 2 # # A significant challenge, particularly when dealing with data that have many columns, is ensuring each column gets encoded correctly. # # This is particularly true with data columns that are ordered categoricals (ordinals) vs unordered categoricals. Unordered categoricals should be one-hot encoded, however this can significantly increase the number of features and creates features that are highly correlated with each other. # # Determine how many total features would be present, relative to what currently exists, if all string (object) features are one-hot encoded. Recall that the total number of one-hot encoded columns is `n-1`, where `n` is the number of categories. # + jupyter={"outputs_hidden": false} run_control={"marked": true} # Select the object (string) columns mask = data.dtypes == np.object categorical_cols = data.columns[mask] # + jupyter={"outputs_hidden": false} run_control={"marked": true} # Determine how many extra columns would be created num_ohc_cols = (data[categorical_cols] .apply(lambda x: x.nunique()) .sort_values(ascending=False)) # No need to encode if there is only one value small_num_ohc_cols = num_ohc_cols.loc[num_ohc_cols>1] # Number of one-hot columns is one less than the number of categories small_num_ohc_cols -= 1 # This is 215 columns, assuming the original ones are dropped. # This is quite a few extra columns! small_num_ohc_cols.sum() # + [markdown] run_control={"marked": true} # ## Question 3 # # Let's create a new data set where all of the above categorical features will be one-hot encoded. We can fit this data and see how it affects the results. # # * Used the dataframe `.copy()` method to create a completely separate copy of the dataframe for one-hot encoding # * On this new dataframe, one-hot encode each of the appropriate columns and add it back to the dataframe. Be sure to drop the original column. # * For the data that are not one-hot encoded, drop the columns that are string categoricals. # # For the first step, numerically encoding the string categoricals, either Scikit-learn;s `LabelEncoder` or `DictVectorizer` can be used. However, the former is probably easier since it doesn't require specifying a numerical value for each category, and we are going to one-hot encode all of the numerical values anyway. (Can you think of a time when `DictVectorizer` might be preferred?) # - num_ohc_cols.index # + jupyter={"outputs_hidden": false} run_control={"marked": true} from sklearn.preprocessing import OneHotEncoder, LabelEncoder # Copy of the data data_ohc = data.copy() # The encoders le = LabelEncoder() ohc = OneHotEncoder() for col in num_ohc_cols.index: # Integer encode the string categories dat = le.fit_transform(data_ohc[col]).astype(np.int) # Remove the original column from the dataframe data_ohc = data_ohc.drop(col, axis=1) # One hot encode the data--this returns a sparse array new_dat = ohc.fit_transform(dat.reshape(-1,1)) # Create unique column names n_cols = new_dat.shape[1] col_names = ['_'.join([col, str(x)]) for x in range(n_cols)] # Create the new dataframe new_df = pd.DataFrame(new_dat.toarray(), index=data_ohc.index, columns=col_names) # Append the new data to the dataframe data_ohc = pd.concat([data_ohc, new_df], axis=1) # + jupyter={"outputs_hidden": false} run_control={"marked": true} # Column difference is as calculated above data_ohc.shape[1] - data.shape[1] # + jupyter={"outputs_hidden": false} run_control={"marked": true} print(data.shape[1]) # Remove the string columns from the dataframe data = data.drop(num_ohc_cols.index, axis=1) print(data.shape[1]) # + [markdown] run_control={"marked": true} # ## Question 4 # # * Create train and test splits of both data sets. To ensure the data gets split the same way, use the same `random_state` in each of the two splits. # * For each data set, fit a basic linear regression model on the training data. # * Calculate the mean squared error on both the train and test sets for the respective models. Which model produces smaller error on the test data and why? # + jupyter={"outputs_hidden": false} run_control={"marked": true} from sklearn.model_selection import train_test_split y_col = 'SalePrice' # Split the data that is not one-hot encoded feature_cols = [x for x in data.columns if x != y_col] X_data = data[feature_cols] y_data = data[y_col] X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.3, random_state=42) # Split the data that is one-hot encoded feature_cols = [x for x in data_ohc.columns if x != y_col] X_data_ohc = data_ohc[feature_cols] y_data_ohc = data_ohc[y_col] X_train_ohc, X_test_ohc, y_train_ohc, y_test_ohc = train_test_split(X_data_ohc, y_data_ohc, test_size=0.3, random_state=42) # + jupyter={"outputs_hidden": false} run_control={"marked": true} # Compare the indices to ensure they are identical (X_train_ohc.index == X_train.index).all() # + jupyter={"outputs_hidden": false} run_control={"marked": true} from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error LR = LinearRegression() # Storage for error values error_df = list() # Data that have not been one-hot encoded LR = LR.fit(X_train, y_train) y_train_pred = LR.predict(X_train) y_test_pred = LR.predict(X_test) error_df.append(pd.Series({'train': mean_squared_error(y_train, y_train_pred), 'test' : mean_squared_error(y_test, y_test_pred)}, name='no enc')) # Data that have been one-hot encoded LR = LR.fit(X_train_ohc, y_train_ohc) y_train_ohc_pred = LR.predict(X_train_ohc) y_test_ohc_pred = LR.predict(X_test_ohc) error_df.append(pd.Series({'train': mean_squared_error(y_train_ohc, y_train_ohc_pred), 'test' : mean_squared_error(y_test_ohc, y_test_ohc_pred)}, name='one-hot enc')) # Assemble the results error_df = pd.concat(error_df, axis=1) error_df # + [markdown] run_control={"marked": true} # Note that the error values on the one-hot encoded data are very different for the train and test data. In particular, the errors on the test data are much higher. Based on the lecture, this is because the one-hot encoded model is overfitting the data. We will learn how to deal with issues like this in the next lesson. # + [markdown] run_control={"marked": true} # ## Question 5 # # For each of the data sets (one-hot encoded and not encoded): # # * Scale the all the non-hot encoded values using one of the following: `StandardScaler`, `MinMaxScaler`, `MaxAbsScaler`. # * Compare the error calculated on the test sets # # Be sure to calculate the skew (to decide if a transformation should be done) and fit the scaler on *ONLY* the training data, but then apply it to both the train and test data identically. # - # Mute the setting wtih a copy warnings pd.options.mode.chained_assignment = None # + jupyter={"outputs_hidden": false} from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler scalers = {'standard': StandardScaler(), 'minmax': MinMaxScaler(), 'maxabs': MaxAbsScaler()} training_test_sets = { 'not_encoded': (X_train, y_train, X_test, y_test), 'one_hot_encoded': (X_train_ohc, y_train_ohc, X_test_ohc, y_test_ohc)} # Get the list of float columns, and the float data # so that we don't scale something we already scaled. # We're supposed to scale the original data each time mask = X_train.dtypes == np.float float_columns = X_train.columns[mask] # initialize model LR = LinearRegression() # iterate over all possible combinations and get the errors errors = {} for encoding_label, (_X_train, _y_train, _X_test, _y_test) in training_test_sets.items(): for scaler_label, scaler in scalers.items(): trainingset = _X_train.copy() # copy because we dont want to scale this more than once. testset = _X_test.copy() trainingset[float_columns] = scaler.fit_transform(trainingset[float_columns]) testset[float_columns] = scaler.transform(testset[float_columns]) LR.fit(trainingset, _y_train) predictions = LR.predict(testset) key = encoding_label + ' - ' + scaler_label + 'scaling' errors[key] = mean_squared_error(_y_test, predictions) errors = pd.Series(errors) print(errors.to_string()) print('-' * 80) for key, error_val in errors.items(): print(key, error_val) # + [markdown] run_control={"marked": true} # ## Question 6 # # Plot predictions vs actual for one of the models. # + jupyter={"outputs_hidden": false} run_control={"marked": true} import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline sns.set_context('talk') sns.set_style('ticks') sns.set_palette('dark') ax = plt.axes() # we are going to use y_test, y_test_pred ax.scatter(y_test, y_test_pred, alpha=.5) ax.set(xlabel='Ground truth', ylabel='Predictions', title='Ames, Iowa House Price Predictions vs Truth, using Linear Regression'); # - # --- # ### Machine Learning Foundation (C) 2020 IBM Corporation
02 - Supervised Learning - Regression/02b_LAB_Regression_Train_Test_Split.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="w7C_Q2UbkGas" # ## Stochastic Optimization # + id="nLnz0sRrSjOg" import numpy as np import matplotlib import matplotlib.pyplot as plt, mpld3 from pydrake.all import ( BaseField, Evaluate, Fields, PointCloud, Rgba, RigidTransform, Sphere, Variable ) from manipulation.meshcat_cpp_utils import StartMeshcat from manipulation import running_as_notebook if running_as_notebook: mpld3.enable_notebook() def loss(theta): x = theta[0] y = theta[1] eval = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2 return 0.25 * eval def generate_color_mat(color_vec, shape): color_mat = np.tile(np.array(color_vec).astype(np.float32).reshape(3,1), (1, shape[1])) return color_mat def visualize_loss(meshcat, loss, colormap='viridis', spacing=0.01, clip_min=None, clip_max=None): # Create a grid of thetas and evaluate losses. points = [] for i in np.arange(-3, 3, spacing): for j in np.arange(-3, 3, spacing): points.append([i,j,loss(np.array([i,j]))]) points = np.array(points) # Normalize losses and color them according to colormap. cmap = matplotlib.cm.get_cmap(colormap) min_loss = np.min(points[:,2]) if clip_min == None else clip_min max_loss = np.max(points[:,2]) if clip_max == None else clip_max colors = [] for i in range(points.shape[0]): normalized_loss = (points[i,2] - min_loss) / (max_loss - min_loss) colors.append(list(cmap(normalized_loss))[0:3]) cloud = PointCloud(points.shape[0], Fields(BaseField.kXYZs | BaseField.kRGBs)) cloud.mutable_xyzs()[:] = points.T cloud.mutable_rgbs()[:] = 255 * np.array(colors).T meshcat.Delete() meshcat.SetProperty("/Background", 'visible', False) meshcat.SetObject("/loss", cloud, point_size=0.03) def visualize_trajectory(trajectory): points = PointCloud(trajectory.shape[0]) points.mutable_xyzs()[:] = trajectory.T meshcat.SetObject("/traj", points, rgba=Rgba(1, 0, 0), point_size=0.03) meshcat.SetLine("/traj_line", trajectory.T, rgba=Rgba(1, 0, 0)) # Visualize the initial guess. meshcat.SetObject("/traj_initial", Sphere(0.05), Rgba(1, 0, 0)) meshcat.SetTransform("/traj_initial", RigidTransform(trajectory[0,:])) # Visualize the final point of the iteration. meshcat.SetObject("/traj_final", Sphere(0.05), Rgba(0, 1, 0)) meshcat.SetTransform("/traj_final", RigidTransform(trajectory[-1,:])) # - # Start the visualizer. meshcat = StartMeshcat() # + [markdown] id="cUTNJkCK1IDH" # ## The Three Hump Camel # In this exercise, we'll implement our own versions of gradient descent and stochastic gradient descent! # # Our goal is to find the minima of the following function: # # $$l(x)=\frac{1}{4}\bigg(2x_1^2-1.05x_1^4+\frac{x_1^6}{6}+x_1x_2+x_2^2\bigg)$$ # # Note that you can access this function using `loss(x)`. # # We have visualized the landscape of this function in meshcat if you run the cell below! You will notice the following things: # # 1. This function has 3 local minima (hence, the name 'three hump camel') # 2. The global minima is located at $f([0,0])=0$. # + colab={"base_uri": "https://localhost:8080/"} id="U1GCQpPf1HwO" outputId="04be0d22-a216-4ee5-b7df-261b10f3320b" # The parameters are optimized for best visualization in meshcat. # For faster visualization, try increasing spacing. visualize_loss(meshcat, loss, colormap = 'viridis', spacing=0.02, clip_max=2.0) # + [markdown] id="-nBpUQcfOcwF" # ## Gradient Descent # # As we saw in the lecture, one way of trying to find the minimum of $l(x)$ is to use explicit gradients and do gradient descent. # # $$x \leftarrow x - \eta\bigg(\frac{\partial l(x)}{\partial x}\bigg)^T$$ # # We've set up a basic outline of the gradient descent algoritm for you. Take a look at the following function `gradient_descent` that implements the following steps: # # 1. Initialize $x\in\mathbb{R}^2$ at random from some bounded region. # 2. Until maximum iteration, update $x$ according to the rule. # + id="pH6DEMMA9cXP" def gradient_descent(rate, update_rule, initial_x=None, iter=1000): """gradient descent algorithm @params: - rate (float): eta variable of gradient descent. - update_rule: a function with a signature update_rule(x, rate). - initial_x: initial position for gradient descent. - iter: number of iterations to run gradient descent for. """ # If no initial guess is supplied, then randomly choose one. if initial_x is None: x = -3 + 6.0 * np.random.rand(2) else: x = initial_x # Compute loss for first parameter for visualization. x_list = [] x_list.append([x[0], x[1], loss(x)]) # Loop through with gradient descent. for i in range(iter): # Update the parameters using update rule. x = update_rule(x, rate) x_list.append([x[0], x[1], loss(x)]) return np.array(x_list) # + [markdown] id="tcIyb-iJRGHg" # ## Determinisitc Exact Gradients # # **Problem 9.1.a** [2 pts]: Let's first use the vanilla gradient descent algorithm with exact gradients. Below, you must implement the simple update function: # # $$x \leftarrow x - \eta\bigg(\frac{\partial l(x)}{\partial x}\bigg)^T$$ # # HINT: You can write down the gradient yourself, but remember you can also use drake's symbolic differentiation! # # + id="kO7h13kCUc1a" def exact_gradient(x, rate): """ Update rule. Receive theta and update it with the next theta. @params - x: input variable x. - rate: rate of descent, variable "eta". @returns: - updated variable x. """ return x # + [markdown] id="LT1PCqWPTTy2" # When you've completed the function, you can run the below cell to check the visualization! For this problem, the visualization has the following convention: # - Red sphere is the initial guess # - Green sphere is the final point after `iter` iterations. # - Every updated parameter is drawn as smaller red cubes. # + id="rEG6dKaxTbie" # Compute the trajectory. trajectory = gradient_descent(0.1, exact_gradient) visualize_trajectory(trajectory) # + [markdown] id="QT4O4yL7iuNg" # If you've implemented it correctly, run the cell multiple times to see the behavior of gradient descent from different initial conditions. You should note that depending on where you started, you are deterministically stuck in the local minima that corresponds to its attraction region. # + [markdown] id="2V8LydfhVMdJ" # ## Stochastic Approximation to Gradients # # **Problem 9.1.b** [2 pts]: One of the mindblowing facts we learned from the lecture was that we can actually do gradient descent without ever having true gradients of the loss function $l(x)$! # # Your job is to write down the following update function for gradient descent: # # $$x \leftarrow x - \eta\big[l(x+w)-l(x)\big]w$$ # # where $w\in\mathbb{R}^2$ drawn from a Gaussian distribution, $w\sim\mathcal{N}(0,\sigma^2=0.25)$. You can use `np.random.normal()` to draw from this distribution. # + id="leVxvWu3lLYd" def approximated_gradient(x, rate): """ Update rule. Receive theta and update it with the next theta. @params - x: input variable x. - rate: rate of descent, variable "eta". @returns: - updated varaible x. """ return x # + [markdown] id="Tg3ek5nz1ioL" # Again, once you've implemented the function, run the below cell to visualize the trajectory. # + id="yku6xDTQQtAt" trajectory = gradient_descent(0.01, approximated_gradient, iter=10000) visualize_trajectory(trajectory) # + [markdown] id="eTEL3_ENl1oI" # If you've implemented it correctly, take a moment to run it from multiple different conditions - the results are somewhat shocking. # - With the right parameters ($\sigma,\eta$), this version of gradient descent is much better than the deterministic exact version at converging to global minima. (In fact, you'll sometimes see it hop out of one of the local minimas and converge to a global minima?) # - But we never explicitly took derivatives! # - (Side note): does this mean this way approximating gradients is the magical tool to everything? not quite. This version can be prone to getting stuck in saddle points! # + [markdown] id="NNRWAjIjmiVV" # ## Baselines # # **Problem 9.1.c** [4 pts]: We don't necessarily have to take finite differences to estimate the gradient. In fact, we could have subtracted our perturbed estimate from any function, as long as it is not a function of $w$! # # $$x \leftarrow x - \eta\big[l(x+w)-b(x)\big]w$$ # # As a written problem, the problem is as follows: prove that on average, the difference in the updates (call it $\mathbb{E}_w[\Delta x$]) is approximately equal to the true analytical gradient. # # HINT: Use first-order taylor approximation of $l(x+w)$ (i.e. you may assume $w$ is quite small) # + [markdown] id="zdJXocpw3OTb" # **Problem 9.1.d** [1 pts]: Finally, implement the update law above. The update rule is almost identical to 9.1.b except for the implementation of the baseline, so this is like a bonus question. # + id="4vjty4Tc9bZw" def approximated_gradient_with_baseline(x, rate, baseline): """ Update rule. Receive theta and update it with the next theta. @params - x: input variable x. - rate: rate of descent, variable "eta". - baseline: float for baseline. @returns: - updated varaible x. """ return x # + [markdown] id="9N1BgRG29jNV" # As you proved in 9.1.c, adding a baseline does not change the mean of the update. However, it does change the variance! # # In the below code, you can play around with different values of the baseline to see what happens. Remember that the optimal value (smallest variance) of the baseline is $l(x)$. # # You should see that if the baseline is close to `loss(x)` (e.g. baseline is uniformly zero), there is no big difference with the solution you wrote on 9.1.b. However, when the baseline is far from `loss(x)` (e.g. baseline is uniformly 5), our path starts to look more like a random walk due to high variance. # + id="0IKbIy1P6a4k" def baseline(x): return 5 # feel free to modify here! def reduced_function(x, rate): return approximated_gradient_with_baseline(x, rate, baseline) trajectory = gradient_descent(0.01, reduced_function, iter=10000) visualize_trajectory(trajectory) # + [markdown] id="MwE8yNg58VQN" # ## How will this notebook be Graded? # # If you are enrolled in the class, this notebook will be graded using [Gradescope](www.gradescope.com). You should have gotten the enrollement code on our announcement in Piazza. # # For submission of this assignment, you must do two things. # - Download and submit the notebook `stochastic_optimization.ipynb` to Gradescope's notebook submission section, along with your notebook for the other problems. # - Write down your answers to 9.1.c in your PDF submission to Gradescope. # # We will evaluate the local functions in the notebook to see if the function behaves as we have expected. For this exercise, the rubric is as follows: # - [2 pts] 9.1.a must be implemented correctly. # - [2 pts] 9.1.b must be implemented correctly. # - [4 pts] 9.1.c is answered correctly. # - [1 pts] 9.1.d must be implemented correctly. # + colab={"base_uri": "https://localhost:8080/", "height": 389} id="pQISVdEG9NoN" outputId="8ecd274d-3fd8-4d2f-9fe3-fc530e8207b0" from manipulation.exercises.rl.test_stochastic_optimization import TestStochasticOptimization from manipulation.exercises.grader import Grader Grader.grade_output([TestStochasticOptimization], [locals()], 'results.json') Grader.print_test_results('results.json') # -
exercises/rl/stochastic_optimization.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 # --- # # Une transformation rรฉussie # # ร€ partir du fichier [*bbt.xml*](./files/xml/bbt.xml), produisez une page HTML comme ci-dessous : # # ```html # <!DOCTYPE html> # <html lang="fr" xmlns="http://www.w3.org/1999/xhtml"> # <head> # <meta charset="utf-8" /> # <title>The Big Bang Theory</title> # </head> # <body> # <h1>The Big Bang Theory</h1> # <p>La sรฉrie se focalise sur cinq personnages qui vivent ร  Pasadena, en Californie : <NAME> et <NAME>, colocataires et tous deux physiciens ร  Caltech ; Penny, une serveuse qui vit de lโ€™autre cรดtรฉ du palier et qui aspire ร  devenir actrice ; et les amis et collรจgues de Leonard et Sheldon, tout autant geeks et inadaptรฉs ร  la vie en sociรฉtรฉ, <NAME>, ingรฉnieur dans lโ€™aรฉrospatiale, et lโ€™astrophysicien <NAME>. Avec le temps, des personnages qui leur donnaient la rรฉplique ont รฉtรฉ promus aux rรดles principaux, comme la neurologue <NAME>, la microbiologiste <NAME>, la physicienne <NAME> et le propriรฉtaire dโ€™une boutique de BD, <NAME>.</p> # <h2>Les personnages</h2> # <ul> # <li>Penny</li> # <li><NAME></li> # <li>โ€ฆ</li> # </ul> # </body> # </html> # ``` # # Dans un second temps, essayez de mettre entre parenthรจses le nom des acteurs ร  cรดtรฉ des personnages quโ€™ils incarnent : # # ```html # <ul> # <li>Penny (<NAME>)</li> # <li><NAME> (<NAME>)</li> # <li>โ€ฆ</li> # </ul> # ``` # + # your code here from lxml import etree tree = etree.parse('../files/xml/bbt.xml') xslt = etree.parse('../files/xslt/bbt-to-html-full.xsl') processor = etree.XSLT(xslt) html = processor(tree) html.write('../files/xml/big-bang-theory.html')
6.xslt/answers/1.a-famous-show.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 # Interval = [a,b] a = 0 b = 1 Nplots = 1025 # 2^10 + 1, 1/2^10 size interval each, number of points where I want to plot N = 3 # degree of the polinomial space x = linspace(a, b, Nplots) q = linspace(a,b, N) # Points of interpolation print(x.shape, q.shape) # The function takes a function as a parameter and returns the plot of the points of interpolation and the function def plot_function(f, plot_points=x, interpolation_points=q): plot(interpolation_points, f(interpolation_points), 'or') # or stands for red circles plot(plot_points, f(plot_points)) plot_function(sin) # Increasing the power of the function make them look more and more similar to each other # The j-th column in the Lagrangian Matrix are going to be more and more similar to each other, # making the matrix ill-conditioned for i in range(10): plot(x, x**i) B = zeros((N,N)) print(B) # + #Fill B with vj evaluated at qi where vj is the function evaluation # - for i in range(N): B[:,i] = q**(i) print(B) # + #Same but faster than #for i in range(N): # for j in range(N): # B[i,j] = q[i]**j # - # For the N = 5 case # # Broadcasting between $\begin{bmatrix} 0 \\ 0.25 \\ 0.50 \\ 0.75 \\ 1 \end{bmatrix}$ and power vector $\begin{bmatrix} 0 & 1 & 2 & 3 & 4\end{bmatrix} = # \begin{bmatrix} # 0^{0} & 0^{1} & 0^{2} & 0^{3} & 0^{4} \\ # 0.25^{0} & 0.25^{1} & 0.25^{2} & 0.25^{3} & 0.25^{4} \\ # 0.50^{0} & 0.5^{1} & 0.5^{2} & 0.5^{3} & 0.5^{4} \\ # 0.75^{0} & 0.75^{1} & 0.75^{2} & 0.75^{3} & 0.75^{4} \\ # 1^{0} & 1^{1} & 1^{2} & 1^{3} & 1^{4} \\ # \end{bmatrix}$ #right way to write it in Python with numpy B = q.reshape((N,1))**arange(N) print(B) I = arange(N) c = inv(B) cond(B) # Multiplying the vector of all the points that define our function (x in the example, 1025) by the exposants (N in the example, 3). We get a matrix where a row represent all the powers of a single point Xvec = x.reshape((-1, 1)) # A vector of all the points of x Xvec = Xvec**I Xvec.shape # Plot 1 + 2*x + 3*x^2 p = array([1, 1, 1]) plot(Xvec, Xvec.dot(p)) def myfun(x): return sin(2*pi*x) # + # Compute the polynomial that interpolates myfun on q p = inv(B).dot(myfun(q)) p # - plot(x, Xvec.dot(p)) def interpolation(fun, q, x): """ Returns the polynomial interpolation of fun at the points q, evaluated at the points x. you can plot this by calling plot(x, interpolation(myfun, q, x)) """ N = len(q) I = arange(N) q_vec = q.reshape((-1,1)) # Reshapes q to be a value vector x_vec = x.reshape((-1,1)) B = q_vec**I V = x_vec**I # Contain the basis function evaluated at x - V_{i}(x) p = V.dot(inv(B).dot(fun(q))) # Vij dot Bij dot func(xj) return p # + myf = lambda x : 1./(1 + 50*(x - .5)**2) # Same as writing #def myf: # return 1./(1 + 50*(x - .5)**2) # - q = linspace(0,1,15) y = interpolation(myf, q, x) plot(x, y) plot(q, myf(q), 'ro') plot(x, myf(x)) def lagrange_basis(q, x): """ Returns the Lagrange basis function evaluated at the points x. you can plot this by calling plot(x, interpolation(myfun, q, x)) """ N = len(q) I = arange(N) q_vec = q.reshape((-1,1)) # Reshapes q to be a value vector x_vec = x.reshape((-1,1)) B = q_vec**I V = x_vec**I # Contain the basis function evaluated at x - V_{i}(x) p = V.dot(inv(B)) # Since it has the identity matrix, the inverse of B times the power of basis (delta) return p # 1 at a point, 0 at the others q = linspace(0,1,5) L = lagrange_basis(q, x) _ = plot(x, L) _ = plot(q, 0*q+1, 'ro') _ = plot(q, 0*q, 'ro') # **The Jupyter Notebook provided contains a more efficient way of computing the Lagrange basis**
gsarti_notes/lesson_7.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 cv2 import csv import pandas as pd from matplotlib import pyplot import tensorflow import keras keras.__version__ # !pip3 uninstall mask-rcnn --y csv_path = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/03-models/ob_model/workspace/trainig_demo/annotations/test.csv' def read_csv(path): csv_list = list() with open(path, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: csv_list.append(row) return csv_list[1:] read_csv(csv_path)[0] # training dataset anns = pd.read_csv(csv_path) anns.head() from os import listdir from xml.etree import ElementTree from numpy import zeros from numpy import asarray from mrcnn.utils import Dataset from mrcnn.visualize import display_instances from mrcnn.utils import extract_bboxes from mrcnn.config import Config from mrcnn.model import MaskRCNN import tensorflow.compat.v1 as tf tf.disable_v2_behavior() # + class ClickableConfig(Config): # Give the configuration a recognizable name NAME = "clickable" # We use a GPU with 12GB memory, which can fit two images. # Adjust down if you use a smaller GPU. # Number of classes (including background) NUM_CLASSES = 1 + 1 # background + steel defects # Number of training steps per epoch STEPS_PER_EPOCH = 10 # instantiating clickable_config = ClickableConfig() # + # display image with masks and bounding boxes # class that defines and loads the kangaroo dataset class ClickableDataset(Dataset): def __init__(self, path): super().__init__(self) self.data_path = path def read_csv(self): csv_list = list() with open(self.data_path, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: csv_list.append(row) return csv_list[1:] # load the dataset definitions # Override def load_dataset(self, is_train=True): # define one class self.add_class("", 1, "clickable") # define data locations img_list = self.read_csv() # find all images for img_info in img_list: image_id = img_info[0].split('/')[-2] + '_' + img_info[0].split('/')[-1] img_path = img_info[0] width = img_info[2] height = img_info[1] annot = img_info[4:7] self.add_image('dataset', image_id=image_id, width = width, height = height, path=img_path, annotation=img_info) def load_image(self, image_id): info = self.image_info[image_id] img_path = info['path'] img = cv2.imread(img_path) return img # extract bounding boxes from an annotation file def extract_boxes(self, filename): # load and parse the file tree = ElementTree.parse(filename) # get the root of the document root = tree.getroot() # extract each bounding box boxes = list() for box in root.findall('.//bndbox'): xmin = int(box.find('xmin').text) ymin = int(box.find('ymin').text) xmax = int(box.find('xmax').text) ymax = int(box.find('ymax').text) coors = [xmin, ymin, xmax, ymax] boxes.append(coors) # extract image dimensions width = int(root.find('.//size/width').text) height = int(root.find('.//size/height').text) return boxes, width, height # load the masks for an image # Override def load_mask(self, image_id): # get details of image info = self.image_info[image_id] # define box file location info_list = info['annotation'] height = int(info['height']) width = int(info['width']) box = info_list[4:] # load XML # create one array for all masks, each on a different channel masks = zeros([height, width, 1], dtype='uint8') # create masks class_ids = list() row_s, row_e = int(box[1]), int(box[3]) col_s, col_e = int(box[0]), int(box[2]) masks[row_s:row_e, col_s:col_e, 0] = 1 class_ids.append(self.class_names.index('clickable')) return masks, asarray(class_ids, dtype='int32') # load an image reference # Override def image_reference(self, image_id): info = self.image_info[image_id] return info['path'] # + # train set train_path = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/03-models/ob_model/workspace/trainig_demo/annotations/train_r.csv' train_set = ClickableDataset(train_path) train_set.load_dataset('train') train_set.prepare() # validation set validation_path = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/03-models/ob_model/workspace/trainig_demo/annotations/test.csv' validation_set = ClickableDataset(validation_path) validation_set.load_dataset('val') validation_set.prepare() # - image_id = 'com.google.android.apps.docs.editors.docs_2.png' image = train_set.load_image(100) print(image.shape) mask, class_ids = train_set.load_mask(100) pyplot.imshow(image) pyplot.imshow(mask[:, :, 0], cmap='gray', alpha=0.5) pyplot.show() # plot first few images for i in range(9): # define subplot pyplot.subplot(330 + 1 + i) # plot raw pixel data image = train_set.load_image(i) pyplot.imshow(image) # plot all masks mask, _ = train_set.load_mask(i) for j in range(mask.shape[2]): pyplot.imshow(mask[:, :, j], cmap='gray', alpha=0.3) # show the figure pyplot.show() # define image id image_id = 1 # load the image image = train_set.load_image(image_id) # load the masks and the class ids mask, class_ids = train_set.load_mask(image_id) # extract bounding boxes from the masks bbox = extract_bboxes(mask) # display image with masks and bounding boxes display_instances(image, bbox, mask, class_ids, train_set.class_names) # + model_path = '/home/kimsoohyun/00-Research/02-Graph/02-image_detection/04-clickable/dataset/04-maskRCNN/model' model = MaskRCNN(mode='training', model_dir=model_path, config=clickable_config) # - model.train(train_set, validation_set, learning_rate=clickable_config.LEARNING_RATE, epochs=5, layers='heads')
02-image_detection/04-clickable/ipynb/MaskRCNN.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 # --- # # Files I/O # Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object. # ### The open Function fo = open("foo.txt", "wb") print "Name of the file: ", fo.name print "Closed or not : ", fo.closed print "Opening mode : ", fo.mode print "Softspace flag : ", fo.softspace # ### The write() Method fo.write( "I have opened a file using Python. \n And I'm writing to it"); # ### The close() Method fo.close() # ### The read() Method fo = open("foo.txt", "r+") str = fo.read(10); print "Read String is : ", str # Close opend file fo.close() # ### File Positions with open("foo.txt", "r+") as fo: pass str = fo.read(15) print "String is : ", str # + fo = open("foo.txt", "r+") str = fo.read(15) print "String is : ", str position = fo.tell(); print "Current file position : ", position position = fo.seek(5, 0); str = fo.read(15); print "String is : ", str fo.close() # - # # Python Databases # ## Python sqlite3 # It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards. # Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. We will cover these modules in detail with example. # ## Connect To Database # + import sqlite3 conn = sqlite3.connect('test.db') # - # ## Create a Table conn.execute('''CREATE TABLE WORKSHOP (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, CITY CHAR(50));''') # ## INSERT Operation # + conn.execute("INSERT INTO WORKSHOP (ID,NAME,AGE,CITY) \ VALUES (1, 'Rajat', 20, 'Mangalore')"); conn.execute("INSERT INTO WORKSHOP (ID,NAME,AGE,CITY) \ VALUES (2, 'Jude', 22, 'Chennai')"); conn.execute("INSERT INTO WORKSHOP (ID,NAME,AGE,CITY) \ VALUES (3, 'Sherin', 23, 'Bangalore')"); conn.execute("INSERT INTO WORKSHOP (ID,NAME,AGE,CITY) \ VALUES (4, 'Ajay', 21, 'Panjab')"); conn.commit() # - # ## SELECT Operation # + cursor = conn.execute("SELECT id, name, city from WORKSHOP") for row in cursor: print (type(row)) print "ID = ", row[0] print "NAME = ", row[1] print "CITY = ", row[2], "\n" c = conn.execute("SELECT MAX(id) from WORKSHOP") print (c.fetchone()[0]) # - # ## UPDATE Operation conn.execute("UPDATE WORKSHOP set CITY = 'Mumbai' where ID = 1") conn.commit() cursor = conn.execute("SELECT id, name, city from WORKSHOP where ID = 1") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "CITY = ", row[2], "\n" # ## DELETE Operation conn.execute("DELETE from WORKSHOP where ID = 2;") conn.commit() cursor = conn.execute("SELECT id, name, city from WORKSHOP") for row in cursor: print "ID = ", row[0] print "NAME = ", row[1] print "CITY = ", row[2], "\n"
Intro-to-Python/08.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="qVMCjEV1IEC7" colab_type="text" # # Homework: Spark SQL # # In this homework you will gain a mastery of using Spark SQL. By the end, you'll be a star (not that you aren't already one). Over the next few days you will be using an EMR cluster to use Spark to manipulate the entire `linkedin.json` dataset as well as a new data set, `stock_prices.csv`. # # The goal of the homework will be to create a training dataset for a Random Forest Machine learning model. The training data set will contain the monthly number of employees hired by companies in `linkedin.json` and their corresponding closing stock prices over a 10 year period (2000-2011). We will try and predict, based on this data, if the company will have a positive or negative growth in stock in the first quarter of the next year. Who's ready to make some money? # # ## The Noteworthy Notes # Before we begin here are some important notes to keep in mind, # # # 1. **IMPORTANT!** I said it twice, it's really important. In this homework, we will be using AWS resources. You are given a quota ($150) to use for the entirety of the homework. There is a small chance you will use all this money, however it is important that at the end of every session, you **shut down your EMR cluster**. # 2. **You can only use Google Colab for this Homework** since we must connect to the EMR cluster and Jupyter doesn't do that. Using a Google Colab Notebook with an EMR cluster has two important abnormalities: # * The first line of any cell in which you will use the spark session must be `%%spark`. Notice that all cells below have this. # * You will, unfortunately, not be able to stop a cell while it is running. If you wish to do so, you will need to restart your cluster. See the Setup EMR Document for reference. # 3. You are **required** to use Spark SQL queries to handle the data in the assignment. Mastering SQL is more beneficial than being able to use Spark commands (functions) as it will show up in more areas of programming and data science/analytics than just Spark. Use the following [function list](https://spark.apache.org/docs/latest/api/sql/index.html#) to see all the SQL functions avaliable in Spark. # 4. There are portions of this homework that are _very_ challenging. # # With that said, let's dive in. # # # # + [markdown] id="7XEqGpEGBWs5" colab_type="text" # ## Step 0: Set up EMR # # Your first task is to create an EMR cluster your AWS Educate Accounts. Please see the [attached document](https://drive.google.com/open?id=1_8NB_3QXfQKm5Vyu7XyxU2mnH5HnGM-F) for detailed instructions. Move on to Step 0.1 after you have completed all the steps in the document. # + [markdown] id="5iBPXxgAdXkv" colab_type="text" # ### Step 0.1: The Superfluous Setup # # Run the following two cells. These will allow your colab notebook to connect to an use your EMR. # + id="pvkEbVaaAQ1e" colab_type="code" colab={} # %%capture # !apt update # !apt install gcc python-dev libkrb5-dev # !pip install sparkmagic # !pip install pyspark # + id="6WAJmQ8IAbRs" colab_type="code" colab={} # %%capture # %load_ext sparkmagic.magics # + id="IAvEMpzqqHeY" colab_type="code" colab={} from pyspark.sql.types import * import json import urllib.request from datetime import datetime # + [markdown] id="CL6n768EPt9E" colab_type="text" # ### Step 0.2: The Succulent Spark # # Now, connect your notebook to the EMR cluster you created. In the first cell, copy the link to the Master Public DNS specified in the setup document. You will need to add `http://` to the beginning of the address and the port to the end. The final format should be, # # `http://<your-DNS-link>:8998` # # For example, if my DNS (directly from the AWS EMR console) is `ec2-3-15-237-211.us-east-2.compute.amazonaws.com` my address would be, # # `http://ec2-3-15-237-211.us-east-2.compute.amazonaws.com:8998` # # Insert this in the `# TODO # below`. For our example, the cell would read, # # # # ``` # # # %spark add -s spark_session -l python -u http://ec2-3-15-237-211.us-east-2.compute.amazonaws.com:8998 # ``` # + id="R9XWNkCEAeWP" colab_type="code" outputId="63ed2476-09a2-4242-9c13-327feedcf230" executionInfo={"status": "ok", "timestamp": 1575582618079, "user_tz": 300, "elapsed": 27719, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 92, "referenced_widgets": ["0ec3bf246d6241e38d2b68f478bccb36", "f848b820820f462f9bd7788a206c6197", "c81f5783e51f450f8335631023d58bec"]} # TODO: Enter your Master Public DNS with the proper formatting and host # %spark add -s spark_session -l python -u http://ec2-34-205-85-50.compute-1.amazonaws.com:8998 # + id="DSALdzFWgKuV" colab_type="code" colab={} # To delte a session. # # %spark delete -s spark_session_name # + [markdown] id="Bfs-EQZUzF4j" colab_type="text" # _Note_: Since we are using an EMR cluster we will not have access to the several modules that exist for python, e.g. `pandas`, `numpy`, etc. We have written the entire homework such that the solution does not require any of these. Don't try to import them. It won't work. # + [markdown] id="Nf_ADEXnIK0b" colab_type="text" # ## Step 1: Data Cleaning and Shaping # # The data you will use is stored in an S3 bucket, a cloud storage service. You now need to download it onto the nodes of your [EMR cluster](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html). # # ### Step 1.1: The Stupendous Schema # # When loading data, Spark will try to infer it's structure on it's own. This process is faulty because it will sometimes infer the type incorrectly. JSON documents, like the one we will use, can have nested types, such as: arrays, arrays of dictionaries, dictionaries of dictionaries, etc. Spark's ability to determine these nested types is not reliable, thus you will define a schema for `linkedin.json`. # # A schema is a description of the structure of data. You will be defining an explicit schema for `linkedin.json`. In Spark, schema's are defined using a `StructType` object. This is a collection of data types, termed `StructField`'s, that specify the structure and variable type of each component of the dataset. For example, suppose we have the following simple JSON object, # # # ``` # { # "student_name": "<NAME>", # "GPA": 1.4, # "courses": [ # {"department": "Computer and Information Science", # "course_id": "CIS 545", # "semester": "Fall 2018"}, # {"department": "Computer and Information Science", # "course_id": "CIS 520", # "semester": "Fall 2018"}, # {"department": "Electrical and Systems Engineering", # "course_id": "ESE 650", # "semester": "Spring 2018"} # ], # "grad_year": 2019 # } # ``` # # We would define it's schema as follows, # # ``` # schema = StructType([ # StructField("student_name", StringType(), nullable=True), # StructField("GPA", FloatType(), nullable=True), # StructField("courses", ArrayType( # StructType([ # StructField("department", StringType(), nullable=True), # StructField("course_id", StringType(), nullable=True), # StructField("semester", StringType(), nullable=True) # ]) # ), nullable=True), # StructField("grad_year", IntegerType(), nullable=True) # ]) # ``` # # # Each `StructField` has the following structure: `(name, type, nullable)`. The `nullable` flag defines that the specified field may be empty. Your first task is to define the `schema` of `linkedin.json`. A sample JSON object for the dataset can be found [here](http://oneclickpaste.com/194048/). # # _Note_: In `linkedin.json` the field `specilities` is spelled incorrectly. This is **not** a typo. # # # + id="pL-Ps4KWIJ9e" colab_type="code" outputId="452c5671-7852-4905-ee6d-c26f8ad23ea0" executionInfo={"status": "ok", "timestamp": 1575583353855, "user_tz": 300, "elapsed": 402, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["8b3b2f26485c413881059c5affd2055e", "0f816c10fa484f01b4a14190ade37768", "b2af543a4da04a53a7080b43eea45486"]} language="spark" # # # TODO: Define [linkedin.json] schema # # YOUR CODE HERE # # + [markdown] id="2Su604X9ggc2" colab_type="text" # ### Step 1.2: The Laudable Loading # # Load the `linkedin.json` dataset from your S3 bucket into a Spark dataframe (sdf) called `raw_data_sdf`. If you have constructed `schema` correctly `spark.read.json()` will read in the dataset. ***You do not need to edit this cell***. # + id="ji-KW2sAiB6r" colab_type="code" outputId="e58668c0-67a8-4e2c-d602-18d70266da27" executionInfo={"status": "ok", "timestamp": 1575584115692, "user_tz": 300, "elapsed": 2733, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["10e9bda7da7e48d0845b749ab8e9e9ee", "d1a222beb845430abec998d9c6f175ea", "3747c90befbe4e7094faa212b6512361"]} language="spark" # # TODO: modify the location to the place where you have the data. # raw_data_sdf = spark.read.json("s3a://opends4allhw3/linkedin.json", schema=schema) # # raw_data_sdf = spark.read.json('linkedin.json', schema=schema) # + [markdown] id="jMVCVotcE1wv" colab_type="text" # The cell below shows how to run SQL commands on Spark tables. Use this as a template for all your SQL queries in this notebook. ***You do not need to edit this cell***. # + id="NJSVWeGiEO5c" colab_type="code" outputId="ec70a7ff-43ae-42e6-93b2-917f2fe11de2" executionInfo={"status": "ok", "timestamp": 1575584235649, "user_tz": 300, "elapsed": 12066, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 289, "referenced_widgets": ["fc9a5ea9104f4def9166d3a62dff697a", "8d520961230c4509820ffc9e698c6cdc", "<KEY>"]} language="spark" # # # Create SQL-accesible table # raw_data_sdf.createOrReplaceTempView("raw_data") # # # Declare SQL query to be excecuted # query = '''SELECT * # FROM raw_data''' # # # Save the output sdf of spark.sql() as answer_sdf # answer_sdf = spark.sql(query) # # # Display the first 10 rows # answer_sdf.show(10) # + [markdown] id="svOO4iLPist4" colab_type="text" # ### Step 1.3: The Extravagent Extraction # # In our training model, we are interested in when individuals began working at a company. From creating the schema, you should notice that the collection of companies inviduals worked at are contained in the `experience` field as an array of dictionaries. You should use the `org` for the company name and `start` for the start date. Here is an example of an `experience` field, # # ``` # { # "experience": [ # { # "org": "The Walt Disney Company", # "title" : "Mickey Mouse", # "end" : "Present", # "start": "November 1928", # "desc": "Sailed a boat." # }, # { # "org": "Walt Disney World Resort", # "title": "Mickey Mouse Mascot", # "start": "January 2005", # "desc": "Took pictures with kids." # } # ] # } # ``` # # Your task is to extract each pair of company and start date from these arrays. In Spark, this is known as "exploding" a row. An explode will seperate the elements of an array into multiple rows. # # Create an sdf called `raw_start_dates_sdf` that contains the company and start date for every experience of every individual in `raw_data_sdf`. Drop any row that contains a `null` in either column with `dropna()`. You can sort the elements however you wish (you don't need to if you don't want to). The sdf should look as follows: # # ``` # # +--------------------------+---------------+ # |org |start_date | # # +--------------------------+---------------+ # |Walt Disney World Resort |January 2005 | # |The Walt Disney Company |November 1928 | # |... |... | # # +--------------------------+---------------+ # ``` # # _Hint_: You may want to do two seperate explodes for `org` and `start`. In an explode, the position of the element in the array can be extracted as well, and used to merge two seperate explodes. Reference the [function list](https://spark.apache.org/docs/2.3.0/api/sql/index.html). # # _Note_: Some of the entires in `org` are "weird", i.e. made up of non-english letters and characters. Keep them. **DO NOT** edit any name in the original dataframe unless we specify. **DO NOT** drop any row unless there is a `null` value as stated before. This goes for the rest of the homework as well, unless otherwise specified. # + id="Kt16tyP0klQX" colab_type="code" outputId="4bb1d270-0215-44b6-d3b0-4cfcf2a3027b" executionInfo={"status": "ok", "timestamp": 1575584587756, "user_tz": 300, "elapsed": 36859, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["cfecaa14eb514313a5f15ed03ef6789d", "5bea45fa7fc54ebebad0a57be6310c65", "472c58675e1e4d2eab714bd7ce9f0df3"]} language="spark" # # # TODO: Create [raw_start_dates_sdf] # # # YOUR CODE HERE # # + id="-a3xLDEYCcwl" colab_type="code" outputId="6735732d-912e-4823-c8a2-59daf4f41d58" executionInfo={"status": "ok", "timestamp": 1575584659737, "user_tz": 300, "elapsed": 108829, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 168, "referenced_widgets": ["dc7c0513d85b4643bdbfc7bf8702e856", "2056868703734a26b1db0e3ffec7699d", "66aaa398ce5e401b9e1a1d87988e5487"]} language="spark" # raw_start_dates_sdf.show(4) # + [markdown] id="zSbb0t-d-VFt" colab_type="text" # ### Step 1.4: The Fortuitous Formatting # # There are two issues with the values in our `date` column. First, the values are saved as strings, not datetime types. This halts us from running functions such as `ORDER BY` or `GROUP BY` on common months or years. Second, some values do not have both month and year information or are in other languages. Your task is to filter out and clean the `date` column. We are interested in only those rows that have date in the following format "(month_name) (year)", e.g. "October 2010". # # Create an sdf called `filtered_start_dates_sdf` from `raw_start_dates_sdf` with the `date` column filtered in the manner above. Keep only those rows with a start date between January 2000 to December 2011, inclusive. Ensure that any dates that are not in our desired format are ommitted. Drop any row that contains a `null` in either column. The format of the sdf is shown below: # ``` # # +--------------------------+---------------+ # |org |start_date | # # +--------------------------+---------------+ # |Walt Disney World Resort |2005-01-01 | # |... |... | # # +--------------------------+---------------+ # ``` # _Hint_: Refer to the [function list](https://spark.apache.org/docs/2.3.0/api/sql/index.html) to format the `date` column. In Spark SQL the date format we are interested in is `"MMM y"`. # # _Note_: Spark will return the date in the format above, with the day as `01`. This is ok, since we are interested in the month and year each individual began working and all dates will have `01` as their day. # + id="eelgTtOc_MBM" colab_type="code" outputId="49854f5c-074a-4611-fc23-0acb2df64963" executionInfo={"status": "ok", "timestamp": 1575584734608, "user_tz": 300, "elapsed": 183678, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["52815494440f4161b01b6eebb60b999d", "91880f7960e5464da7893d80df72d483", "8ece5c44cc2c4a25b4fcc641882667a4"]} language="spark" # # # TODO: Create [filtered_start_dates_sdf] # # + [markdown] id="LXYYQn2_GYwZ" colab_type="text" # ### Step 1.5 The Gregarious Grouping # # We now want to collect the number of individuals that started in the same month and year for each company. Create an sdf called `start_dates_sdf` that has the total number of employees who began working at the same company on the same start date. The format of the sdf is shown below: # # ``` # # +--------------------------+---------------+---------------+ # |org |start_date |num_employees | # # +--------------------------+---------------+---------------+ # |Walt Disney World Resort |2005-01-01 |1 | # |... |... |... | # # +--------------------------+---------------+---------------+ # ``` # + id="CxVIyc1CHooV" colab_type="code" outputId="0a2c79d4-0749-403a-e007-0173cffe006e" executionInfo={"status": "ok", "timestamp": 1575584854127, "user_tz": 300, "elapsed": 303177, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["f52ae0051fc24086995d05461b02229d", "defbbe69eeb44fcbba983d981a4521fe", "5647e8443a5a4d7a9d775c8a2bea87c6"]} language="spark" # # # TODO: Create [start_dates_sdf] # # YOUR CODE HERE # # + [markdown] id="QYScM3FwJnUz" colab_type="text" # ## Step 2: Hiring Trends Analysis # # Now we will analyze `start_dates_sdf` to find monthly and annual hiring trends. # # ### Step 2.1: The Marvelous Months # # Your task is to answer the question: "On average, what month do most employees start working?" Create an sdf called `monthly_hires_sdf` which contains the total number of employees that started working on a specific month, at any company and on any year. The `month` column should be of type `int`, i.e. 1-12. The format of the sdf is shown below: # # ``` # # +---------------+---------------+ # |month |num_employees | # # +---------------+---------------+ # |1 |... | # |2 |... | # |3 |... | # |... |... | # # +---------------+---------------+ # ``` # # Find the month in which the most employees start working and save it's number as an integer to the variable `most_common_month`. # # _Hint_: Be careful. The starts dates we have right now have both month and year. We only want the common months. See if you can find something in the [function list](https://spark.apache.org/docs/2.3.0/api/sql/index.html) that will help you do this. # + id="vLTmvD9WNQH3" colab_type="code" outputId="4463575e-90d3-4050-ef97-b8d1155f5a4d" executionInfo={"status": "ok", "timestamp": 1575584971691, "user_tz": 300, "elapsed": 420722, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["00c647594bdf4e86aebd273fffcbcc85", "8de371ef2a1749558e1a7fe53363d060", "3e73d2733d814879bfb767f462570743"]} language="spark" # # # TODO: Create [monthly_hire_sdf] and find the most common month people were # # hired. Save its number as an integer to [most_common_month] # # + [markdown] id="CUtVHRcMUoWp" colab_type="text" # ### Step 2.2: The Preposterous Percentages # # The next question we will answer is "What is the percentage change in hires between 2010 and 2011 for each company?" Create an sdf called `percentage_change_sdf` that has the percentage change between 2010 and 2011 for each company. The sdf should look as follows: # # ``` # # +---------------------------+--------------------+ # |org |percentage_change | # # +---------------------------+--------------------+ # |Walt Disney World Resort |12.3 | # |... |... | # # +---------------------------+--------------------+ # ``` # # _Note_: A percentage change can be positive or negative depending # on the difference between the two years.The formula for percent change is given below, # # $$\text{% change} = \frac{P_f-P_i}{P_f} \times 100$$ # # Here, $P_f$ is the final element (in this case the number of hires in 2011) and $P_i$ is initial element (the number of hires in 2010). # # _Hint_: This is a **difficult** question. We recommend using a combination of `GROUP BY` and `JOIN`. Keep in mind that operations between columns in SQL dataframes are often easier than those between rows. # + id="_AhhfLXpWq7y" colab_type="code" outputId="e2e04149-cade-4ffc-d4bb-4e655228b109" executionInfo={"status": "ok", "timestamp": 1575585089273, "user_tz": 300, "elapsed": 538283, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["6bd5845756c84761a22c4fca0c27e091", "18c3f006e61b466abea135b15d4fe624", "637bd902d20544569334d56244bca5d3"]} language="spark" # # # TODO: Create [percentage_change_sdf] # # YOUR CODE HERE # # + [markdown] id="QkF2RfLSXO0u" colab_type="text" # ## Step 3: Formatting the Training Data # # # Our overaching goal is to train a machine learning (ML) model that will use the monthly hiring trends of a company to predict a positive or negative gain in the company's stock in the first quarter of the following year. A ML model is trained on a set of observations. Each observation contains a set of features, `X`, and a label, `y`. The goal of the ML model is to create a function that takes any `X` as an input and outputs a predicted `y`. # # The machine learning model we will use is a [Random Forest Classifier](https://builtin.com/data-science/random-forest-algorithm). Each observation we will pass in will have 24 features (columns). These are the number of people hired from Jan to Dec and the company stock price on the last day of each month. The label will be the direction of the company's stock percentage change (positive, `1`, or negative, `-1`) in the first quarter of the following year. Each observation will correspond to a specified company's trends on a specified year. The format of our final training sdf is shown below. The first 26 columns define our observations, `X`, and the last column the label, `y`. # ``` # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # |org |year |jan_hired | ... |dec_hired |jan_stock | ... |dec_stock |stock_result | # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # |IBM |2008 |... | ... |... |... | ... |... |1 | # |IBM |2009 |... | ... |... |... | ... |... |-1 | # |... |... |... | ... |... |... | ... |... |... | # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # ``` # # _Note_: We will use the first three letters of each month in naming, i.e. `jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec` # # # # ### Step 3.1: The Harmonious Hires # # Your first task is to create the first half of the training table, i.e. the `jan_hired` through `dec_hired` columns. This will involve reshaping `start_dates_sdf`. Currently, `start_dates_sdf` has columns `org`, `start_date`, and `num_employees`. We want to group the rows together based on common `org` and years and create new columns for the number of employees that started working in each month of that year. # # Create an sdf called `raw_hirings_for_training_sdf` that has for a single company and a single year, the number of hires in Jan through Dec, and the total number of hires that year. Note that for each company you will have several rows corresponding to years between 2000 and 2011. It is ok if for a given company you don't have a given year. However, ensure that for a given company and given year, each month column has an entry, i.e. if no one was hired the value should be `0`. The format of the sdf is shown below: # ``` # # +----+-----+----------+---------+----------+----------+ # |org |year |jan_hired | ... |dec_hired |total_num | # # +----+-----+----------+---------+----------+----------+ # |IBM |2008 |... | ... |... |... | # |IBM |2009 |... | ... |... |... | # |... |... |... | ... |... |... | # # +----+-----+----------+---------+----------+----------+ # ``` # _Hint_: This is a **difficult** question. The tricky part is creating the additional columns of monthly hires, specifically when there are missing dates. In our dataset, if a company did not hire anybody in a given date, it will not appear in `start_dates_sdf`. We suggest you look into `CASE` and `WHEN` statements in the [function list](https://spark.apache.org/docs/2.3.0/api/sql/index.html). # + id="btp2wboHqg2J" colab_type="code" outputId="f3561d40-c00d-497f-c487-3c58747b08dc" executionInfo={"status": "ok", "timestamp": 1575585305365, "user_tz": 300, "elapsed": 754324, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["277806ae13be4bd2a7e17019f477a79e", "0f19d766cf624efc9a417c72f607368e", "cc5799297d594e738a34ed4b83a16fec"]} language="spark" # # # TODO: Create [raw_hire_train_sdf] # # YOUR CODE HERE # # + [markdown] id="IkXyet6rrczK" colab_type="text" # ### Step 3.2: The Formidable Filters # # Create an sdf called `hire_train_sdf` that contains all the observations in `raw_hire_train_sdf` with `total_num` greater than or equal to 10. The format of the sdf is shown below: # # ``` # # +----+-----+----------+---------+----------+----------+ # |org |year |jan_hired | ... |dec_hired |total_num | # # +----+-----+----------+---------+----------+----------+ # |IBM |2008 |... | ... |... |... | # |IBM |2009 |... | ... |... |... | # |... |... |... | ... |... |... | # # +----+-----+----------+---------+----------+----------+ # ``` # # + id="dCH4mbNcshq9" colab_type="code" outputId="2a546db3-3a2e-4e16-e598-3cfd828c9e2f" executionInfo={"status": "ok", "timestamp": 1575585416723, "user_tz": 300, "elapsed": 865658, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["0b0cf2113c5d46079b10ee9291d81ca2", "e904164016e649b39ae675c5316f3718", "b2deaafff8174b3cab34294d58e1e27e"]} language="spark" # # # TODO: Create [hire_train_sdf] # # YOUR CODE HERE # # + [markdown] id="MN4ik70Hta01" colab_type="text" # ### Step 3.3: The Stupendous Stocks # # Now we are ready for the stock data. The stock data we will use is saved in the same S3 bucket as `linkedin.json`. Load the data into the EMR cluster. Run the cell below. ***You do not need to edit this cell, except changing dataset url***. # + id="APv4BxKw643q" colab_type="code" outputId="1de29e91-11be-40ca-9c02-5491aee6ff10" executionInfo={"status": "ok", "timestamp": 1575585524960, "user_tz": 300, "elapsed": 973879, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 269, "referenced_widgets": ["25c499f20e694a60bd3fc36ab3287402", "a27a5af9ab1e47449f2cb01f298ab010", "e2efaeed796f491dac1e80de28d71575"]} language="spark" # # TODO: modify the location to the place that you have the data. # # Load stock data # raw_stocks_sdf = spark.read.format("csv") \ # .option("header", "true") \ # .load("s3a://xxx/stock_prices.csv") # # # Creates SQL-accesible table # raw_stocks_sdf.createOrReplaceTempView('raw_stocks') # # # Display the first 10 rows # query = '''SELECT * # FROM raw_stocks''' # spark.sql(query).show(10) # # + [markdown] id="JUCdr3zDUAFH" colab_type="text" # Run the cell below to see the types of the columns in our data frame. These are not correct. We could have defined a schema when reading in data but we will handle this issue in another manner. You will do this in Step 3.4.2. # + id="oNTGEfxsisqs" colab_type="code" outputId="c62fe3de-796e-4c7a-d030-fe67f6710e81" executionInfo={"status": "ok", "timestamp": 1575585524961, "user_tz": 300, "elapsed": 973871, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 34, "referenced_widgets": ["664d2f8b41e8447ba797bbd586cf7442", "14f008c6d70a41de96a66a9255d28c91", "cac27272dfa64b55b8ac984c8f2e83e7"]} language="spark" # # # Print types of SDF # raw_stocks_sdf.dtypes # + [markdown] id="0DdnoFkP7mxz" colab_type="text" # ### Step 3.4 The Clairvoyant Cleaning # # We now want to format the stock data set into the second half of the training table. We will then merge it with `hire_train` based off the common `org` and `year` fields. The formatting will consist of 4 steps. Actually, it is 5. # # #### Step 3.4.1 The Ubiquitous UDF # # The companies in our stock dataset are defined by their stock tickers. Thus, we would not be able to merge it with the `org` field in `hire_train_sdf`. We must convert them to that format. Often times when using Spark, there may not be a built-in SQL function that can do the operation we desired. Instead, we can create one on our own with a user-defined function (udf). # # A udf is defined as a normal Python function and then registered to be used as a Spark SQL function. Your task is to create a udf, `TICKER_TO_NAME()` that will convert the ticker field in `raw_stocks` to the company's name. This will be done using the provided `ticker_to_name_dict` dictionary. We are only interested in the companies in that dictionary. # # Fill out the function `ticker_to_name()` below. Then use `spark.udf.register()` to register it as a SQL function. The command is provided. ***You do not need to edit it***. Note, we have defined the udf as returning `StringType()`. Ensure that your function returns this. You must also deal with any potential `null` cases. # + id="P4cJWZsr8iNC" colab_type="code" outputId="101ca7f2-f6a8-443b-e138-365d49241567" executionInfo={"status": "ok", "timestamp": 1575585525098, "user_tz": 300, "elapsed": 974000, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 34, "referenced_widgets": ["90d37ecc6c6e42d8a7867fcce3980831", "5b6f6a0b7f8a45949f82869fcae374cb", "3e9b9186606b4aa28ddeee3a5112ab20"]} language="spark" # # # TODO: Fill out [ticker_to_name()] and register it as a udf. # # YOUR CODE HERE # # def ticker_to_name(ticker): # # # Register udf as a SQL function. DO NOT EDIT # spark.udf.register("TICKER_TO_NAME", ticker_to_name, StringType()) # # + [markdown] id="u9YOYO9L-_GS" colab_type="text" # #### Step 3.4.2: The Fastidious Filters # # With our new `TICKER_TO_NAME()` function we will begin to wrangle `raw_stocks_sdf`. # # Create an sdf called `filter_1_stocks_sdf` as follows. Convert all the ticker names in `raw_stocks_sdf` to the company names and save it as `org`. Next, convert the `date` field to a datetime type. As explained before this will help order and group the rows in future steps. Then, convert the type of the values in `closing_price` to `float`. This will take care of the `dtypes` issue we saw in Step 3.3. # # Drop any company names that do not appear in `ticker_to_name_dict`. Keep any date between January 1st 2001 and December 4th 2012 inclusive, in the format shown below (note this is a datetime object not a string): # # ``` # # +----+------------+--------------+ # |org |date |closing_price | # # +----+------------+--------------+ # |IBM |2000-01-03 |... | # |... |... |... | # # +----+------------+--------------+ # ``` # _Hint_: You will use a similar function to filter the dates as in Step 1.4. In Spark SQL the format for the `date` field in `raw_stocks_sdf` is `"yyyy-MM-dd"`. # + id="RuiitnWlBYJ7" colab_type="code" outputId="dc6a7b77-34e5-4634-84b8-ca9114fa4c2f" executionInfo={"status": "ok", "timestamp": 1575585525577, "user_tz": 300, "elapsed": 974459, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["9b53a3b6b43e46b48004eab3188f52cc", "375176dbd9eb42a29fd34152142f70b3", "72ed66a0fe4d476ab6c55a255ae0cad0"]} language="spark" # # # TODO: Create [filter_1_stocks_sdf] # # YOUR CODE HERE # # + [markdown] id="Ne5NaT-6CLns" colab_type="text" # #### Step 3.4.3: The Magnanimous Months # # The data in `filter_1_stocks_sdf` gives closing prices on a daily basis. Since we are interested in monthly trends, we will only keep the closing price on the **last trading day of each month**. # # Create an sdf `filter_2_stocks_sdf` that contains only the closing prices for the last trading day of each month. Note that a trading day is not simply the last day of each month, as this could be on a weekend when the market is closed . The format of the sdf is shown below: # # ``` # # +----+------------+--------------+ # |org |date |closing_price | # # +----+------------+--------------+ # |IBM |2000-01-31 |... | # |... |... |... | # # +----+------------+--------------+ # ``` # # _Hint_: This is a **difficult** question. But if you made it this far, you're a star by now. It may be helpful to create an intermediate dataframe that will help you filter out the specific dates you desire. # + id="AIx5LUuDD4q_" colab_type="code" outputId="3c69ac55-3b2e-4724-b5b8-783e0a4e737c" executionInfo={"status": "ok", "timestamp": 1575585560088, "user_tz": 300, "elapsed": 1008953, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["06d34ff02a2f40acb420053db30d1ce6", "8f3ed02d295449deb1a410e319457366", "da5370dcfa9e484ebec2232b753f9126"]} language="spark" # # # TODO: Create [filter_2_stocks_sdf] # # YOUR CODE HERE # # + [markdown] id="AG4bACKKEQNl" colab_type="text" # #### Step 3.4.4: The Rambunctious Reshape # # Now, we will begin to shape our dataframe into the format of the final training sdf. # # Create an sdf `filter_3_stocks_sdf` that has for a single company and a single year, the closing stock price for the last trading day of each month in that year. This is similar to the table you created in Step 3.1. In this case since we cannot make a proxy for the closing price if the data is not avaliable, drop any rows containing any `null` values, in any column. The format of the sdf is shown below: # # ``` # # +----+-----+----------+---------+----------+ # |org |year |jan_stock | ... |dec_stock | # # +----+-----+----------+---------+----------+ # |IBM |2008 |... | ... |... | # |IBM |2009 |... | ... |... | # |... |... |... | ... |... | # # +----+-----+----------+---------+----------+ # ``` # # + id="AucLEgvwIr_0" colab_type="code" outputId="d40ca836-d8d6-4b6e-d6e6-e2a6eb604cd9" executionInfo={"status": "ok", "timestamp": 1575585622883, "user_tz": 300, "elapsed": 1071728, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["09bfe3c82da54132bc0b1de3698f5041", "bdf094cb30f741778998082741862013", "c6e2b881ee2e4982bb3781c81e46fda5"]} language="spark" # # # TODO: Create [filter_3_stocks_sdf] # # YOUR CODE HERE # # # + [markdown] id="82OQKp-nIulq" colab_type="text" # #### Step 3.4.5: The Decisive Direction # # The final element in our training set is the binary output for each case, i.e. the `y` label. # # Create an sdf `stocks_train_sdf` from `filter_3_stocks_sdf` with an additional column `direction`. This should be the direction of percentage change in the closing stock price, i.e. `1` for positive or `-1` for negative, in the first quarter of a given year. The quarter of a year begins in January and ends in April, inclusive. We want to know the percent change between these two months. Reference Step 2.2 for the percent change formula. The format of the sdf is shown below: # # ``` # # +----+-----+----------+---------+----------+-------------+ # |org |year |jan_stock | ... |dec_stock |direction | # # +----+-----+----------+---------+----------+-------------+ # |IBM |2008 |... | ... |... |1.0 | # |IBM |2009 |... | ... |... |-1.0 | # |... |... |... | ... |... |... | # # +----+-----+----------+---------+----------+-------------+ # ``` # + id="yEFJIfyZKf7B" colab_type="code" outputId="f24e6eae-c8f3-4336-a5ea-088b5f275dd3" executionInfo={"status": "ok", "timestamp": 1575585685404, "user_tz": 300, "elapsed": 1134227, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["3f7baced569340eb9e13bcce2d6e7834", "<KEY>", "293e6a8149074fa297336901798a3c5a"]} language="spark" # # # TODO: Create [stocks_train_sdf] # # YOUR CODE HERE # # + [markdown] id="Fd2nviNpM2dF" colab_type="text" # ### Step 3.5: The Capricious Combination # # Now that we have individually created the two halfs of our training data we will merge them together to create the final training sdf we showed in the beginning of Step 3. # # Create an sdf called `training_sdf` in the format of the one shown at the beginning of Step 3. Note that in our definition for the `stock_result` column, the `stock_result` value for a particular year corresponds to the direction of the stock percentage change in the **following** year. For example, the stock_result in the `2008` row for `IBM` will contain the direction of IBM's stock in the first quarter of 2009. The format of the sdf is shown below: # ``` # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # |org |year |jan_hired | ... |dec_hired |jan_stock | ... |dec_stock |stock_result | # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # |IBM |2008 |... | ... |... |... | ... |... |-1.0 | # |IBM |2009 |... | ... |... |... | ... |... |1.0 | # |... |... |... | ... |... |... | ... |... |... | # # +----+-----+----------+---------+----------+----------+---------+----------+-------------+ # ``` # + id="8ZIb6QkcO5RB" colab_type="code" outputId="824edeb5-3b1f-4282-fc90-3709e6f214cd" executionInfo={"status": "ok", "timestamp": 1575585746267, "user_tz": 300, "elapsed": 1195073, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "00573172153387237137"}} colab={"base_uri": "https://localhost:8080/", "height": 17, "referenced_widgets": ["60381de0cb0f4bcbb03a3f077896433a", "183ce4cf310845d29208c2565450ead1", "745dc77db2ac4dd6838be8dab0a5f66c"]} language="spark" # # # TODO: Create [training_sdf] # # YOUR CODE HERE #
opends4all-resources/opends4all-scalable-data-processing/CLUSTER-DATA-PROCESSING-Homework-Cloud.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 # --- # # Understanding the Prevalence of Decentralised Gambling Applications import gamba as gb raw_data = gb.read_csv('/home/ojs/Desktop/raw_matched_data.csv', ['bet_time','payout_time','duration']) raw_data.sort_values(['bet_time'], inplace=True) gb.summarise_app(raw_data) fck = raw_data[raw_data['provider'] == 'fck'] eroll = raw_data[raw_data['provider'] == 'etheroll'] d2w = raw_data[raw_data['provider'] == 'dice2win'] # + import matplotlib.dates as mdates dfs = [d2w, eroll, fck] labels = ['dice2.win', 'etheroll.com','fck.com'] unique_addresses = [] cumulative_expenditures = [] all_repeat_users = [] # repeat users differenceIn # fourth axis with shared y from tqdm import tqdm for i, df in enumerate(dfs): # for application in applications unique_users = [] unique_users_count = [] repeat_users = [] repeat_users_count = [] for player_id in tqdm(df['player_id'].values): # for every bet in the data #for player_id in df['player_id'].values: if player_id not in unique_users: unique_users.append(player_id) player_bets = df[df['player_id'] == player_id] player_duration = gb.duration(player_bets) if (player_duration >= 2) and (player_id not in repeat_users): repeat_users.append(player_id) unique_users_count.append(len(unique_users)) repeat_users_count.append(len(repeat_users)) unique_addresses.append(unique_users_count) all_repeat_users.append(repeat_users_count) cumulative_bet_values = df['bet_size'].cumsum() cumulative_expenditures.append(cumulative_bet_values) # + import numpy as np, datetime, matplotlib.pyplot as plt def plot_unique_players(dgapp_unique_addresses): plt.figure() for i, values in enumerate(dgapp_unique_addresses): plt.plot(dfs[i]['bet_time'], np.array(values)/ 1000, label=labels[i]) plt.ylim(0, 15) plt.ylabel('Unique Addresses (x1000), n') ax = plt.gca() months = mdates.MonthLocator((1,4,7,10)) ax.xaxis.set_major_locator(months) # ticks on first day of each month ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # format of only month (3 letter abbr) ax.legend(loc=1) return plt def plot_cumulative_expenditure(dgapp_cumulative_expenditures): plt.figure() for i, s in enumerate(dgapp_cumulative_expenditures): plt.plot(dfs[i]['bet_time'], np.array(s), label=labels[i]) plt.ylabel('Cumulative Amount Bet (ETH), v') plt.ylim(0) ax = plt.gca() months = mdates.MonthLocator((1,4,7,10)) ax.xaxis.set_major_locator(months) # ticks on first day of each month ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) # format of only month (3 letter abbr) ax.legend(loc=0) return plt fig1 = plot_unique_players(unique_addresses) fig1.savefig('fig1.pdf', bbox_inches='tight') fig1.show() plot_unique_players(all_repeat_users) fig2 = plot_cumulative_expenditure(cumulative_expenditures) fig2.savefig('fig2.pdf', bbox_inches='tight') fig2.show() # + import warnings, pandas as pd warnings.filterwarnings("ignore") def plot_weekly_users(dgapp_unique_addresses, extra_data=None): fig, ax = plt.subplots(nrows=3, sharex=True, figsize=[8,6]) colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] for i, addresses in enumerate(dgapp_unique_addresses): series = pd.Series(addresses, index=dfs[i]['bet_time']) weekly = series.resample('W').max().diff()[:-1] weekly.plot(ax = ax[i], color=colors[i], label=labels[i]) if extra_data != None: repeat_series = pd.Series(extra_data[i], index=dfs[i]['bet_time']) repeat_weekly = repeat_series.resample('W').max().diff()[:-1] repeat_weekly.plot(ax = ax[i], alpha=0.3, color=colors[i], label='repeat users') ax[i].legend() plt.xlim(raw_data['bet_time'].min(), raw_data['bet_time'].max()) return plt fig3 = plot_weekly_users(unique_addresses, extra_data = all_repeat_users) fig3.savefig('fig3.pdf', bbox_inches='tight') fig3.show() # - plt.rcParams["font.family"] = "monospace" plt.rcParams["font.size"] = 11 plt.rcParams['font.monospace'] = ['Roboto Mono'] plt.rcParams['figure.figsize'] = [8.0, 4.0] plt.rcParams['axes.grid'] = True
docs/research/new/Scholten_2020b/scholten_2020b.ipynb
# ##### Copyright 2021 Google LLC. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # crypto # <table align="left"> # <td> # <a href="https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/contrib/crypto.ipynb"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png"/>Run in Google Colab</a> # </td> # <td> # <a href="https://github.com/google/or-tools/blob/master/examples/contrib/crypto.py"><img src="https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png"/>View source on GitHub</a> # </td> # </table> # First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab. # !pip install ortools # + # Copyright 2010 <NAME> <EMAIL> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Crypto problem in Google CP Solver. Prolog benchmark problem GNU Prolog (crypta.pl) ''' Name : crypta.pl Title : crypt-arithmetic Original Source: P. <NAME>'s book Adapted by : <NAME> - INRIA France Date : September 1992 Solve the operation: B A I J J A J I I A H F C F E B B J E A + D H F G A B C D I D B I F F A G F E J E ----------------------------------------- = G J E G A C D D H F A F J B F I H E E F ''' Compare with the following models: * MiniZinc: http://www.hakank.org/minizinc/crypta.mzn * Comet : http://www.hakank.org/comet/crypta.co * ECLiPSe : http://www.hakank.org/eclipse/crypta.ecl * SICStus : http://hakank.org/sicstus/crypta.pl This model was created by <NAME> (<EMAIL>) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ """ from ortools.constraint_solver import pywrapcp # Create the solver. solver = pywrapcp.Solver("Crypto problem") # # data # num_letters = 26 BALLET = 45 CELLO = 43 CONCERT = 74 FLUTE = 30 FUGUE = 50 GLEE = 66 JAZZ = 58 LYRE = 47 OBOE = 53 OPERA = 65 POLKA = 59 QUARTET = 50 SAXOPHONE = 134 SCALE = 51 SOLO = 37 SONG = 61 SOPRANO = 82 THEME = 72 VIOLIN = 100 WALTZ = 34 # # variables # LD = [solver.IntVar(1, num_letters, "LD[%i]" % i) for i in range(num_letters)] 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 = LD # # constraints # solver.Add(solver.AllDifferent(LD)) solver.Add(B + A + L + L + E + T == BALLET) solver.Add(C + E + L + L + O == CELLO) solver.Add(C + O + N + C + E + R + T == CONCERT) solver.Add(F + L + U + T + E == FLUTE) solver.Add(F + U + G + U + E == FUGUE) solver.Add(G + L + E + E == GLEE) solver.Add(J + A + Z + Z == JAZZ) solver.Add(L + Y + R + E == LYRE) solver.Add(O + B + O + E == OBOE) solver.Add(O + P + E + R + A == OPERA) solver.Add(P + O + L + K + A == POLKA) solver.Add(Q + U + A + R + T + E + T == QUARTET) solver.Add(S + A + X + O + P + H + O + N + E == SAXOPHONE) solver.Add(S + C + A + L + E == SCALE) solver.Add(S + O + L + O == SOLO) solver.Add(S + O + N + G == SONG) solver.Add(S + O + P + R + A + N + O == SOPRANO) solver.Add(T + H + E + M + E == THEME) solver.Add(V + I + O + L + I + N == VIOLIN) solver.Add(W + A + L + T + Z == WALTZ) # # search and result # db = solver.Phase(LD, solver.CHOOSE_MIN_SIZE_LOWEST_MIN, solver.ASSIGN_CENTER_VALUE) solver.NewSearch(db) num_solutions = 0 str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while solver.NextSolution(): num_solutions += 1 for (letter, val) in [(str[i], LD[i].Value()) for i in range(num_letters)]: print("%s: %i" % (letter, val)) print() solver.EndSearch() print() print("num_solutions:", num_solutions) print("failures:", solver.Failures()) print("branches:", solver.Branches()) print("WallTime:", solver.WallTime())
examples/notebook/contrib/crypto.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 # --- # %%capture # !pip3 install penngrader --upgrade from penngrader.grader import * # ## Autograder Setup # Enter your 8-digit PennID below: STUDENT_ID = 99999999 # Run the following cell to initialize the autograder. This autograder will let you submit your code directly from this notebook and immidiately get a score. # # **NOTE:** Remember we store your submissions and check against other student's submissions... so, not that you would, but no cheating. grader = PennGrader(course_id = 'CIS545_Spring_2019', homework_id = 'CIS545_Spring_2019_HW1', student_id = STUDENT_ID) # ## Question 1: Write an addition function! # Fill in the function body of `addition_function` that takes in two numbers and returns their sum. def addition_function(x,y): return x + y # Run the following cell to grade this question. grader.grade(test_case_id = 'test_case_1', answer = addition_function) # ## Question 2: Now write a Class! # Add two class functions: `add_course` and `remove_course` that both take in a string representing a course ID. class Student: def __init__(self, name = 'John', email = '<EMAIL>', courses = []): self.name = name self.email = email self.courses = courses def get_coures(self): return self.courses def add_course(self, course): self.courses.append(course) def remove_course(self, course): self.courses.remove(course) grader.grade(test_case_id = 'test_case_2', answer = Student) # ## Question 3: Finally, let's do some Pandas stuff! # # Run the following cell to load the dataset... # + import pandas as pd students_df = pd.DataFrame([['Leonardo_Murri',100],['Akshay_Grewal',65]], columns = ['first_last_name','grade']) students_df # - # Use `.apply(...)` to keep only the last name in the `first_last_name` column. students_df['first_last_name'] = students_df['first_last_name'].apply(lambda x: x.split('_')[0]) students_df # Now, rename the `first_last_name` column to `first_name`. Make sure your final dataframe is called `student_df`. students_df = students_df.rename(columns = {'first_last_name':'first_name'}) students_df # Run the following cell to grade this question. # Autograder cell: Test case #3 grader.grade(test_case_id = 'test_case_3', answer = students_df) # ## View your score! # You made it this far, run the following cell to double check we stored all your scores correctly. grader.view_score()
Test Client Notebook/PennGrader_Homework_Template.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 # --- # # 1. Make OpenAI Gym like environment # - This example uses DDPG(Deep Deterministic Policy Gradient) with pybullet_env # - pybullet_env prerequisites: Open AI Gym, pybullet. # # pip install gym # # pip install pybullet import gym import pybullet_envs import time env = gym.make("InvertedPendulumBulletEnv-v0") env.render(mode="human") print('action space:',env.action_space) print('action space high,low :',env.action_space.high,env.action_space.low) print('state space:',env.observation_space) print('state space high,low :',env.observation_space.high,env.observation_space.low) # # 2. Import RL Algorithm # # Base agent needs core agent and an environment to interact. from rlagent.agents import ExperienceReplayAgent from rlagent.algorithms import DDPG state_shape = env.observation_space.shape action_shape = env.action_space.shape ddpg = DDPG(state_shape, action_shape, tau=0.01, actor_lr=0.0001, critic_lr=0.001, action_noise=True, add_memory=True) tf_agent = ExperienceReplayAgent(agent=ddpg, env=env, save_steps=10000, model_dir='model') tf_agent.agent.summary() # # 3. Train tf_agent.train(max_training_steps=20000) # # 4. Check Trained Model import gym import pybullet_envs env = gym.make("InvertedPendulumBulletEnv-v0") env.render(mode="human") # + from rlagent.agents import ExperienceReplayAgent from rlagent.algorithms import DDPG state_shape = env.observation_space.shape action_shape = env.action_space.shape ddpg = DDPG(state_shape, action_shape, tau=0.01, actor_lr=0.0001, critic_lr=0.001, action_noise=False, add_memory=False) tf_agent = ExperienceReplayAgent(agent=ddpg, env=env, save_steps=10000, model_dir='model') tf_agent.load_model(model_path='model/model-19999') # - tf_agent.act()
tutorial/rlagent_tutorial_1_getting_started.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 matplotlib.pyplot as plt import pandas as pd # you will likely need to add some imports here # %matplotlib inline # - # ### K-means clustering harvard = pd.read_csv('https://raw.githubusercontent.com/UWDIRECT/UWDIRECT.github.io/master/Wi18_content/DSMCER/HCEPD_100K.csv') # Perform k-means clustering on the harvard data. Vary the `k` from 5 to 50 in increments of 5. Run the `k-means` using a loop. # # Be sure to use standard scalar normalization! # `StandardScaler().fit_transform(dataArray)` # Use [silhouette](http://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html) analysis to pick a good k. # ### PCA and plotting # # The functions below may be helpful but they aren't tested in this notebook. # + def make_pca(array, components): pca = PCA(n_components=components, svd_solver='full') pca.fit(array) return pca def plot_pca(pca, array, outplt, x_axis, y_axis, colorList=None): markers = pca.transform(array) plt.scatter(markers[:, x_axis], markers[:, y_axis], color='c') if colorList is not None: x_markers = [markers[i, x_axis] for i in colorList] y_markers = [markers[i, y_axis] for i in colorList] plt.scatter(x_markers, y_markers, color='m') plt.xlabel("Component 1 ({}%)".format(pca.explained_variance_ratio_[x_axis]* 100)) plt.ylabel("Component 2 ({}%)".format(pca.explained_variance_ratio_[y_axis]* 100)) plt.tight_layout() plt.savefig(outplt) def plot_clusters(pca, array, outplt, x_axis, y_axis, colorList=None): xkcd = [x.rstrip("\n") for x in open("xkcd_colors.txt")] markers = pca.transform(array) if colorList is not None: colors = [xkcd[i] for i in colorList] else: colors = ['c' for i in range(len(markers))] plt.scatter(markers[:, x_axis], markers[:, y_axis], color=colors) plt.xlabel("Component {0} ({1:.2f}%)".format((x_axis+1), pca.explained_varia nce_ratio_[x_axis]*100)) plt.ylabel("Component {0} ({1:.2f}%)".format((y_axis+1), pca.explained_varia nce_ratio_[y_axis]*100)) plt.tight_layout() plt.savefig(outplt) data = pd_to_np(df) pca = make_pca(data, args.n_components) print(pca.explained_variance_ratio_) # - # ### Self organizing map # https://github.com/sevamoo/SOMPY
Wi20_content/DSMCER/L11_PCA_KMeans.ipynb
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.2 # language: julia # name: julia-1.5 # --- # # A Repair Problem # Ross, Simulation 5th edition, Section 7.7, p. 124-126 # ## Description # # A system needs $n$ working machines to be operational. To guard against machine breakdown, additional machines are kept available as spares. Whenever a machine breaks down it is immediately replaced by a spare and is itself sent to the repair facility, which consists of a single repairperson who repairs failed machines one at a time. Once a failed machine has been repaired it becomes available as a spare to be used when the need arises. All repair times are independent random variables having the common distribution function $G$. Each time a machine is put into use the amount of time it functions before breaking down is a random variable, independent of the past, having distribution function $F$. # # The system is said to โ€œcrashโ€ when a machine fails and no spares are available. Assuming that there are initially $n + s$ functional machines of which $n$ are put in use and $s$ are kept as spares, we are interested in simulating this system so as to approximate $E[T]$, where $T$ is the time at which the system crashes. # ## Needed Packages using Distributions using SimJulia using Plots using StatsPlots # ## Define constants # + const RUNS = 30 const N = 10 const S = 3 const LAMBDA = 100 const MU = 1 const F = Exponential(LAMBDA) const G = Exponential(MU); # - # ## Define the behaviour of a machine @resumable function machine(sim::Simulation, repair_facility::Resource, spares::Store{Process}) while true try @yield timeout(sim, Inf) catch end #println("At time $(now(sim)): $(active_process(sim)) starts working.") @yield timeout(sim, rand(F)) #println("At time $(now(sim)): $(active_process(sim)) stops working.") get_spare = get(spares) @yield get_spare | timeout(sim, 0.0) if state(get_spare) != SimJulia.idle interrupt(value(get_spare)) else throw(SimJulia.StopSimulation("No more spares!")) end @yield request(repair_facility) #println("At time $(now(sim)): $(active_process(sim)) repair starts.") @yield timeout(sim, rand(G)) @yield release(repair_facility) #println("At time $(now(sim)): $(active_process(sim)) is repaired.") @yield put(spares, active_process(sim)) end end # ## Startup procedure @resumable function start_sim(sim::Simulation, repair_facility::Resource, spares::Store{Process}) procs = Process[] for i=1:N push!(procs, @process machine(sim, repair_facility, spares)) end @yield timeout(sim, 0.0) for proc in procs interrupt(proc) end for i=1:S @yield put(spares, @process machine(sim, repair_facility, spares)) end end # ## One simulation run function sim_repair() sim = Simulation() repair_facility = Resource(sim) spares = Store{Process}(sim) @process start_sim(sim, repair_facility, spares) msg = run(sim) stop_time = now(sim) println("At time $stop_time: $msg") stop_time end sim_repair() # ## Multiple simulations results = Float64[] for i=1:RUNS push!(results, sim_repair()) end println("Average crash time: ", sum(results)/RUNS) # ## Plots boxplot(results)
Lectures_old/Lecture 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 # --- # + # Dependencies and Setup import pandas as pd import numpy as np import os # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_data = pd.read_csv(file_to_load) purchase_data.head() # + # making the vairs # Player Count totalNumPlayers = 0 # Purchasing (All) numOfUniqueItems = 0 avgPurPrice = 0.0 totalNumPur = 0 totalRev = 0.0 # Gender Demograph | m - male, f - female, o - other # Count countM = 0 countF = 0 countO = 0 # Percent percM = 0.0 percF = 0.0 percO = 0.0 # Total Rev of puchases tRevM = 0.0 tRevF = 0.0 tRevO = 0.0 # Average pur price avgPurM = 0.0 avgPurF = 0.0 avgPurO = 0.0 # Total Pur Value tPurValM = 0.0 tPurValF = 0.0 tPurValO = 0.0 # Average Purchase Total per Person by Gender avgPurTotM = 0.0 avgPurTotF = 0.0 avgPurTotO = 0.0 # - totalNumPlayers = purchase_data["SN"].nunique() totalNumPlayersDf = pd.DataFrame([{"Total Players" : totalNumPlayers}]) totalNumPlayersDf numOfUniqueItems = purchase_data["Item Name"].nunique() avgPurPrice = purchase_data['Price'].mean() totalNumPur = purchase_data['Purchase ID'].count() totalRev = purchase_data["Price"].sum() PurSumDF = pd.DataFrame([{"Number of Unique Items" : numOfUniqueItems, "Average Purchase Price" : avgPurPrice, "Total Number of Purchases" : totalNumPur, "Total Revenue" : totalRev}]) PurSumDF["Average Purchase Price"] = PurSumDF["Average Purchase Price"].map("${:.2f}".format) PurSumDF["Total Revenue"] = PurSumDF["Total Revenue"].map("${:.2f}".format) PurSumDF gender_df = purchase_data.loc[:, ["SN", "Gender",]] gender_df = gender_df.drop_duplicates(["SN"]) gender_df = gender_df.groupby(['Gender'], as_index=False).agg({'SN' : 'count'}) gender_df = gender_df.sort_values("SN", ascending=False).reset_index(drop=True) # The Hard Way # percM = (gender_df['SN'].loc[gender_df["Gender"] == 'Male'] / totalNumPlayers * 100).reset_index(drop=True) # percF = (gender_df['SN'].loc[gender_df["Gender"] == 'Female'] / totalNumPlayers * 100).reset_index(drop=True) # percO = (gender_df['SN'].loc[gender_df["Gender"] == 'Other / Non-Disclosed'] / totalNumPlayers * 100).reset_index(drop=True) # gender_percents = pd.DataFrame({'Percentage of Players' : [percM[0], percF[0], percO[0]]}) # gender_df['Percentage of Players'] = gender_percents # gender_df gender_df['Percentage of Players'] = (gender_df["SN"] / totalNumPlayers * 100).map("% {:.2f}".format) gender_df = gender_df.rename(columns={"SN": "Count"}) gender_df = gender_df.set_index("Gender") gender_df # + # I found a better way to do this down in the Age part. I'm leaving this here to show how much progress i made gender_purch_df = purchase_data.copy() gender_purch_df = gender_purch_df.drop(["Item Name" ,'Item ID' ,"Age" ,"Purchase ID"], axis=1) gender_purch_df = gender_purch_df.groupby(['Gender'], as_index=False).agg({'SN' : 'count', 'Price' : 'sum'}) # Calc Average Purchase Price temp_F = purchase_data.loc[purchase_data['Gender'] == 'Female'].mean() avgPurF = temp_F['Price'] temp_M = purchase_data.loc[purchase_data['Gender'] == 'Male'].mean() avgPurM = temp_M['Price'] temp_O = purchase_data.loc[purchase_data['Gender'] == 'Other / Non-Disclosed'].mean() avgPurO = temp_O['Price'] AvgPurPriceDict = pd.DataFrame({'Average Purchase Price' : [avgPurF, avgPurM, avgPurO]}) gender_purch_df["Average Purchase Price"] = AvgPurPriceDict # Calc Total Purchase cost temp_F = purchase_data.loc[purchase_data['Gender'] == 'Female'].sum() tRevF = temp_F['Price'] temp_M = purchase_data.loc[purchase_data['Gender'] == 'Male'].sum() tRevM = temp_M['Price'] temp_O = purchase_data.loc[purchase_data['Gender'] == 'Other / Non-Disclosed'].sum() tRevO = temp_O['Price'] TotalPurValGen = pd.DataFrame({'Total Purchase Value' : [tRevF, tRevM, tRevO]}) gender_purch_df["Total Purchase Value"] = TotalPurValGen # Calc Average Total Purchase Price Per Person gender_temp_df = purchase_data.loc[:, ["SN", "Gender","Price"]] female_avg_pur_pri_df = gender_temp_df.loc[gender_temp_df["Gender"] == "Female"] tPurValF = female_avg_pur_pri_df.groupby(['SN']).sum().mean() gender_temp_df = purchase_data.loc[:, ["SN", "Gender","Price"]] male_avg_pur_pri_df = gender_temp_df.loc[gender_temp_df["Gender"] == "Male"] tPurValM = male_avg_pur_pri_df.groupby(['SN']).sum().mean() gender_temp_df = purchase_data.loc[:, ["SN", "Gender","Price"]] other_avg_pur_pri_df = gender_temp_df.loc[gender_temp_df["Gender"] == "Other / Non-Disclosed"] tPurValO = other_avg_pur_pri_df.groupby(['SN']).sum().mean() TotalPurPerUsr = pd.DataFrame({'Average Total Purchase Per Person' : [tPurValF[0], tPurValM[0], tPurValO[0]]}) gender_purch_df["Average Total Purchase Per Person"] = TotalPurPerUsr # Clean up Data Sheet gender_purch_df = gender_purch_df.drop(['Price'], axis=1) gender_purch_df["Average Purchase Price"] = gender_purch_df["Average Purchase Price"].map("${:.2f}".format) gender_purch_df["Total Purchase Value"] = gender_purch_df["Total Purchase Value"].map("${:.2f}".format) gender_purch_df["Average Total Purchase Per Person"] = gender_purch_df["Average Total Purchase Per Person"].map("${:.2f}".format) gender_purch_df = gender_purch_df.rename(columns={"SN": "Purchase Count"}) gender_purch_df = gender_purch_df.set_index("Gender") gender_purch_df # - # Age bins = [0, 9, 14, 19, 24, 29, 34, 39, purchase_data['Age'].max()] binNames = ['<10', '10-14', '15-19', '20-24', '25-29', '30-34', '35-39', '40+'] age_base_df = purchase_data.copy() age_demo_df = age_base_df.drop(["Item Name" ,'Item ID' ,"Gender" ,"Purchase ID", 'Price'], axis=1) age_demo_df = age_demo_df.drop_duplicates(["SN"]) # df["Test Score Summary"] = pd.cut(df["Test Score"], bins, labels=group_names, include_lowest=True) age_demo_df["Age Bracket"] = pd.cut(age_demo_df['Age'], bins, labels=binNames, include_lowest=True) age_demo_df = age_demo_df.groupby(['Age Bracket']).agg({'SN' : 'count'}) age_demo_df['Percentage of Players'] = (age_demo_df["SN"] / totalNumPlayers * 100).map("{:.2f} %".format) age_demo_df = age_demo_df.rename(columns={"SN": "Count"}) age_demo_df # + age_pur_df = age_base_df age_pur_df = age_pur_df.drop(["Item Name" ,'Item ID' ,"Gender" ,"Purchase ID"], axis=1) age_pur_df["Age Bracket"] = pd.cut(age_pur_df['Age'], bins, labels=binNames, include_lowest=True) age_pur_df["Average Purchase Price"] = age_pur_df["Price"] age_pur_df["Total Purchase Value"] = age_pur_df["Price"] age_pur_df["Average Total Purchase per Person"] = age_pur_df["Price"] age_pur_grup_df = age_pur_df.groupby(['Age Bracket'], as_index=False).agg({'SN' : 'count', 'Average Purchase Price' : 'mean', 'Total Purchase Value' : 'sum', 'Average Total Purchase per Person' : 'sum'}).copy() age_avg_per_df = age_pur_df.copy() ageATPpP_list = [] for x in range(len(binNames)): age_temp_df = age_avg_per_df.loc[age_avg_per_df["Age Bracket"] == binNames[x]] bracket_age_avg = age_temp_df.groupby(['SN']).sum().mean() ageATPpP_list.append(bracket_age_avg["Average Total Purchase per Person"]) age_pur_grup_df['Average Total Purchase per Person'] = ageATPpP_list age_pur_grup_df["Average Purchase Price"] = age_pur_grup_df["Average Purchase Price"].map("${:.2f}".format) age_pur_grup_df["Total Purchase Value"] = age_pur_grup_df["Total Purchase Value"].map("${:.2f}".format) age_pur_grup_df["Average Total Purchase per Person"] = age_pur_grup_df["Average Total Purchase per Person"].map("${:.2f}".format) age_pur_grup_df = age_pur_grup_df.rename(columns={"SN": "Purchase Count"}) age_pur_grup_df = age_pur_grup_df.set_index("Age Bracket") age_pur_grup_df # + top_spender_base_df = purchase_data.copy() top_spend_temp_df = top_spender_base_df top_spend_temp_df['Avg'] = top_spender_base_df['Price'] top_spend_temp_df = top_spender_base_df.groupby(["SN"], as_index=False).agg({'Purchase ID' : 'count', 'Price' : 'sum', 'Avg' : 'mean'}) top_spenders = top_spend_temp_df.sort_values("Price", ascending=False).head() columns = [{'Name', 'Purchase Count', 'Average Purchase Price', 'Total Purchase Value'}] top_spenders = top_spenders.rename(columns={'SN' : 'Name', 'Purchase ID' : 'Purchase Count', 'Avg' : 'Average Purchase Price', 'Price' : 'Total Purchase Value'}) top_spenders['Average Purchase Price'] = top_spenders['Average Purchase Price'].map("${:.2f}".format) top_spenders['Total Purchase Value'] = top_spenders['Total Purchase Value'].map("${:.2f}".format) top_spenders = top_spenders.reset_index(drop=True).set_index("Name") top_spenders # + pop_items_base_df = purchase_data.copy() pop_items_df = pop_items_base_df.drop(['Purchase ID', 'SN', 'Age', 'Gender'], axis=1).copy() pop_items_df['Purchase Count'] = pop_items_base_df['Item ID'] pop_items_df['Total Purchase Value'] = pop_items_base_df['Price'] pop_items_df = pop_items_df.rename(columns={'Price' : 'Item Price'}) pop_grup_df = pop_items_df.groupby(['Item ID'], as_index=False).agg({'Item Name' : 'max', 'Item Price' : 'mean', 'Purchase Count' : 'count', 'Total Purchase Value' : 'sum'}) pop_sort_df = pop_grup_df.sort_values('Purchase Count', ascending=False) pop_final_df = pop_sort_df.head().copy() pop_final_df['Total Purchase Value'] = pop_final_df['Total Purchase Value'].map("${:.2f}".format) pop_final_df['Item Price'] = pop_final_df['Item Price'].map("${:.2f}".format) pop_final_df = pop_final_df.set_index(['Item ID', 'Item Name']) pop_final_df # + prof_items_base_df = purchase_data.copy() prof_items_df = prof_items_base_df.drop(['Purchase ID', 'SN', 'Age', 'Gender'], axis=1).copy() prof_items_df['Purchase Count'] = prof_items_base_df['Item ID'] prof_items_df['Total Purchase Value'] = prof_items_base_df['Price'] prof_items_df = prof_items_df.rename(columns={'Price' : 'Item Price'}) prof_grup_df = prof_items_df.groupby(['Item ID'], as_index=False).agg({'Item Name' : 'max', 'Item Price' : 'mean', 'Purchase Count' : 'count', 'Total Purchase Value' : 'sum'}) prof_sort_df = prof_grup_df.sort_values('Total Purchase Value', ascending=False) prof_final_df = prof_sort_df.head().copy() prof_final_df['Total Purchase Value'] = prof_final_df['Total Purchase Value'].map("${:.2f}".format) prof_final_df['Item Price'] = prof_final_df['Item Price'].map("${:.2f}".format) prof_final_df = prof_final_df.set_index(['Item ID', 'Item Name']) prof_final_df # + # Everything below is me expermenting with making a summary .txt file # This will output all the finished tables into a txt file dfStrings = [totalNumPlayersDf.to_string(justify='center', index=False), PurSumDF.to_string(justify='center', index=False), gender_df.to_string(justify='center'), gender_purch_df.to_string(justify='center'), age_demo_df.to_string(justify='center'), age_pur_grup_df.to_string(justify='center'), top_spenders.to_string(justify='center'), pop_final_df.to_string(justify='center'), prof_final_df.to_string(justify='center')] # + output_path = os.path.join("summary", "Heros_Data_Summary.txt") # Checks if the directory exists, if it dosen't it makes one. if not os.path.isdir("summary"): os.mkdir("summary") else: pass # Checks if path is valid. if it is, it creates a txt file containing the data # else it gives as os error try: with open(output_path, "w+") as dataOut: for df in dfStrings: dataOut.writelines(df + '\n\n\n') dataOut.writelines("------------------------------------------------------------------------------------------------------------\n") except OSError: print("Creation of txt file failed") else: pass # -
HeroesOfPymoli/HOP-Fonorow.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.path as osp import os from skimage import io import numpy as np import matplotlib.pyplot as plt # %matplotlib inline img = io.imread('/lab/data/spheroid/20190822-co-culture/raw/250kTcells-nopeptide/XY07/1_XY07_00016_Z007_CH3.tif') img.shape, img.dtype np.apply_over_axes(np.max, img, [0, 1]) plt.imshow(img) plt.imshow(img[..., 0])
analysis/spheroid/20190830-co-culture/eda.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- # # Data analysis portion import pandas as pd import numpy as np df = pd.read_csv("test.csv") df = df.replace("--",np.nan) df.head() # df.info() df["Greencard Processing Time"] = df["Greencard Processing Time"].astype(str) split_function = lambda x: x.split()[0] df["Greencard Processing Time"] = df["Greencard Processing Time"].apply(split_function) # df["Greencard Processing Time"] df["Greencard Processing Time"].astype(float).describe()
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 # --- # + colab={} colab_type="code" id="EA_xE6ARGnHQ" import tweepy import time import json access_token = "YOUR ACCESS TOKEN" access_token_secret = "YOUR TOKEN SECRET" consumer_key = "YOUR CONSUMER KEY" consumer_secret = "YOUR CONSUMER SECRET" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # + colab={"base_uri": "https://localhost:8080/", "height": 514, "resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY> "headers": [["content-type", "application/javascript"]], "ok": true, "status": 200, "status_text": ""}}} colab_type="code" id="u02FBv4-HDCQ" outputId="893f4b0d-531a-4005-aff1-ba1e6bfba9dc" from google.colab import files files.upload() # + colab={} colab_type="code" id="UP7G9gqvHb25" from joblib import load,dump districts = load('districts.pkl') states = load('states.pkl') placenames= districts + states commonWords = load('commonwords.pkl') pca = load('pca.joblib') vectorizer = load('vectorizer.joblib') classifier = load('classifier.joblib') patternNewCases = load('PatternNewCases.pkl') patternTotalCases = load('PatternTotalCases.pkl') placePattern = load('Placepatterns.pkl') # + colab={} colab_type="code" id="ELs_Em3CSXqT" districtPattern = [] for district in districts: wordPattern=[] district = district.strip() for word in district.split(" "): wordPattern.append({"lower":word}) districtPattern.append({"label":"district","pattern":wordPattern}) # + colab={} colab_type="code" id="HlJcdGEbTr-l" statePattern = [] for state in states: wordPattern=[] state = state.strip() for word in state.split(" "): wordPattern.append({"lower":word}) statePattern.append({"label":"state","pattern":wordPattern}) placePattern = statePattern + districtPattern dump(placePattern,'Placepattern.pkl') files.download('Placepattern.pkl') # + colab={} colab_type="code" id="WG3yD9mgIT9F" import re def removePunctuations(sentence): punctList = '''!()-[]{};:'"\,./?@#$%^&@*_~''' withoutPunctuation="" for character in sentence: if(character not in punctList): withoutPunctuation+=character return withoutPunctuation def cleanSentence(sentence): s = sentence.lower() s = [re.sub(r'http\S+','',s)] s = [re.sub(r'[^A-Za-z0-9 ]','', s[0])] s = [re.sub(' +', ' ', s[0])] s = removePunctuations(s[0]) s = [word for word in s.split(' ') if(word not in commonWords)] s = ' '.join(s) return s # + colab={"base_uri": "https://localhost:8080/", "height": 50} colab_type="code" id="ausxm6SEIeqt" outputId="c15c4bd3-67e2-4c84-c0b2-a6dc97979b5f" import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize from nltk.stem.snowball import SnowballStemmer def tokenize_and_stem_data(newData): tokenized_data = [] for sentence in newData: tokens = word_tokenize(sentence) tokenized_data.append(tokens) data = tokenized_data stemmer = SnowballStemmer('english') stemmedData = [] for sentence in data: wordArray = [] for word in sentence: # print(word) word = stemmer.stem(word) wordArray.append(word) stemmedData.append(' '.join(wordArray)) return stemmedData # + colab={} colab_type="code" id="OvMkjMlHIpJM" def transform_to_vectorize_pca(data): X = vectorizer.transform(data) X = pca.transform(X.toarray()) return X # + colab={} colab_type="code" id="fbH9Yl8WGp0m" import spacy nlp = spacy.load("en_core_web_sm") from spacy.matcher import Matcher from spacy.pipeline import EntityRuler ruler = EntityRuler(nlp) ruler.add_patterns(placePattern) nlp.add_pipe(ruler) placeMatcherPattern = [[{"TEXT":{"IN": placenames}}]] matcher = Matcher(nlp.vocab) matcher.add('PLACE',placeMatcherPattern) matcher.add('COUNT',patternNewCases) matcher.add('TOTAL',patternTotalCases) def extractInfo(tweet): tweet = tweet.lower() doc = nlp(tweet) detected={} for ent in doc.ents: if(ent.label_ == 'state' or ent.label_ == 'district'): if(ent.label_ == 'district'): if(not('district' in detected.keys())): detected['district'] = [] detected['district'].append(ent.text) else: detected[ent.label_] = ent.text matches = matcher(doc) for match_id, start, end in matches: rule_id = nlp.vocab.strings[match_id] span = doc[start : end] if(rule_id=='COUNT'): for word in span: if(word.pos_ == 'NUM' and word.text != 'covid19'): detected['caseCount'] = word.text elif(rule_id == 'PLACE'): if(str(span) in districts): if(not('district' in detected.keys())): detected['district'] = [] print(detected) detected['district'].append(str(span)) if(str(span) in states): detected['state'] = str(span) elif(rule_id == 'TOTAL'): for word in span: if(word.pos_ == 'NUM' and word.text != 'covid19'): detected['totalCaseCount'] = word.text return detected # + colab={} colab_type="code" id="3KWtC4YQI85f" ctr=0 def predictdata(unknownsample): cleanedSample = cleanSentence(unknownsample) cleanedSampleList = [cleanedSample] tokenize_and_stem_sample = tokenize_and_stem_data(cleanedSampleList) vectorized_pca_sample = transform_to_vectorize_pca(tokenize_and_stem_sample) prediction = classifier.predict(vectorized_pca_sample)[0] if(prediction == 1): #print(unknownsample) detected = extractInfo(cleanedSample) if('caseCount' in detected.keys() or 'totalCaseCount' in detected.keys()): return detected return None # + colab={} colab_type="code" id="pJEyqP8mGzub" predictedTweets=[] def processTweets(tweets): for tweet in tweets: time = tweet.created_at tweet_id = tweet.id full_text = tweet.full_text if (not tweet.retweeted) and ('RT @' not in full_text): detected = predictdata(full_text) if detected != None: print(detected,full_text) predictedTweets.append((tweet_id,time,detected,full_text)) # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="bVlP4JKNJuxn" outputId="68456d8d-dd1c-40c0-8b2d-c72ce2c081e4" accountName = 'PTI_News' try: for tweets in tweepy.Cursor(api.user_timeline, screen_name=accountName,tweet_mode='extended',exclude_replies=True,count = 200).pages(12): filteredTweets = processTweets(tweets) except tweepy.TweepError: time.sleep(60) # + colab={} colab_type="code" id="kj4OB32FJ5ZL" tweetid=[] tweettime=[] district = [] state = [] count = [] totalCases = [] tweetValue = [] tweetLink =[] for obj in predictedTweets: id = obj[0] time = obj[1] detected = obj[2] text = obj[3] link = text.split(" ")[-1] tweetVal = " ".join(text.split(" ")[:-1]) tweetValue.append(tweetVal) tweetLink.append(link) tweetid.append(id) tweettime.append(time) if('caseCount' in detected.keys()): count.append(detected['caseCount']) else: count.append(None) if('totalCaseCount' in detected.keys()): totalCases.append(detected['totalCaseCount']) else: totalCases.append(None) if('state' in detected.keys()): state.append(detected['state']) else: state.append(None) if('district' in detected.keys()): district.append(detected['district']) else: district.append('None') # + colab={"base_uri": "https://localhost:8080/", "height": 402} colab_type="code" id="kWSDeqI9Tglm" outputId="bad8ef7e-4a02-4c93-f060-5b7a4aa3752d" newDict = {"Id":tweetid, "Time":tweettime, "Tweet":tweetValue, "Count":count, "Total":totalCases, "District":district, "State":state, "Link":tweetLink} detectedDf = pd.DataFrame(newDict) detectedDf # + colab={} colab_type="code" id="hnNSY1NwMp7s" import pandas as pd df = pd.read_csv('Zones of India2 (1).csv') districts = df['District'].values.tolist() districts = [x.lower() for x in districts] states = df['State'].values.tolist() states = [x.lower() for x in states] dump(districts,'districts.pkl') dump(states,'states.pkl') files.download('districts.pkl') files.download('states.pkl') # + colab={} colab_type="code" id="RolzulX4RcgM" f = open('PredictedTweets.txt','w') f.write("\n".join(predictedTweets)) f.close() # + colab={} colab_type="code" id="8-Y7HIGSSJAj" files.download('PredictedTweets.txt') # + colab={"base_uri": "https://localhost:8080/", "height": 1000} colab_type="code" id="sccFghKzbCIo" outputId="f58002d3-618c-4f59-841f-5a9b9c90c277" placePattern # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="TaoEGeF9TuWj" outputId="8056c821-288d-42d0-b387-ed52f8dd1a07" states = [x.strip() for x in states] states = list(set(states)) dump(states,'states.pkl') # + colab={} colab_type="code" id="KbN16aZTUsgb" files.download('states.pkl') # + colab={} colab_type="code" id="phjMakcn3iev" districts = [x.strip() for x in districts] districts = list(set(districts)) dump(districts,'districts.pkl') files.download('districts.pkl') # + colab={} colab_type="code" id="SunYhBd8X10m" patternNewCases = [[{'LIKE_NUM': True}, {'LOWER': 'more'}, {'LOWER': 'covid19'}], [{'LIKE_NUM': True}, {'LOWER': 'more'}, {'LOWER': 'people'}, {'LOWER': 'test'}], [{'LIKE_NUM': True}, {'LOWER': 'more'}, {'LOWER': 'people'}], [{'LIKE_NUM': True}, {'LOWER': 'new'}, {'LOWER': 'covid19'}, {'LOWER': 'positive'}], [{'LIKE_NUM': True}, {'LOWER': 'new'}, {'LOWER': 'covid19'}], [{'LIKE_NUM': True}, {'LOWER': 'new'}, {'LOWER': 'covid19'}, {'LOWER': 'cases'}]] dump(patternNewCases,'PatternNewCases.pkl') files.download('PatternNewCases.pkl') # + colab={} colab_type="code" id="lxCYziRS8n-M" patternTotal = [[{'LOWER': 'number'}, {'LOWER': 'positive'}, {'LOWER': 'cases'}, {'LIKE_NUM': True}]] dump(patternTotal,'PatternTotalCases.pkl') files.download('PatternTotalCases.pkl') # + colab={"base_uri": "https://localhost:8080/", "height": 162} colab_type="code" id="Q80Ry3IxMhni" outputId="befc2e2e-4a05-4b18-be8f-b2ee9250da9c" placenames.index("ahmedabad") # + colab={} colab_type="code" id="yYOsOXSK1m9n"
TwitterPredict.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: visualization-curriculum-gF8wUgMm # language: python # name: visualization-curriculum-gf8wugmm # --- # + [markdown] papermill={"duration": 0.027896, "end_time": "2020-04-05T12:07:35.049517", "exception": false, "start_time": "2020-04-05T12:07:35.021621", "status": "completed"} tags=[] # # COVID-19 Exploratory Data Analysis # > (Almost) Everything You Want To Know About COVID-19. # # - author: <NAME> # - comments: true # - categories: [EDA] # - permalink: /corona-eda/ # - toc: true # - image: images/covid-eda-2-1.png # + [markdown] papermill={"duration": 0.022249, "end_time": "2020-04-05T12:07:35.094797", "exception": false, "start_time": "2020-04-05T12:07:35.072548", "status": "completed"} tags=[] # These visualizations were made by [<NAME>](https://twitter.com/imdevskp). Original notebook is [here](https://www.kaggle.com/imdevskp/covid-19-analysis-viz-prediction-comparisons). # + _cell_guid="b1076dfc-b9ad-4769-8c92-a6c4dae69d19" _kg_hide-input=true _kg_hide-output=true _uuid="8f2839f25d086af736a60e9eeb907d3b93b6e0e5" papermill={"duration": 1.673646, "end_time": "2020-04-05T12:07:36.790434", "exception": false, "start_time": "2020-04-05T12:07:35.116788", "status": "completed"} tags=[] #hide # essential libraries import json import random from urllib.request import urlopen # storing and anaysis import numpy as np import pandas as pd # visualization import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff import folium # color pallette cnf = '#393e46' # confirmed - grey dth = '#ff2e63' # death - red rec = '#21bf73' # recovered - cyan act = '#fe9801' # active case - yellow # converter from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() # hide warnings import warnings warnings.filterwarnings('ignore') # html embedding from IPython.display import Javascript from IPython.core.display import display, HTML # + _kg_hide-input=true papermill={"duration": 0.180382, "end_time": "2020-04-05T12:07:36.994099", "exception": false, "start_time": "2020-04-05T12:07:36.813717", "status": "completed"} tags=[] #hide # importing datasets url = 'https://raw.githubusercontent.com/imdevskp/covid_19_jhu_data_web_scrap_and_cleaning/master/new/complete_data_new_format.csv' full_table = pd.read_csv(url, parse_dates=['Date']) full_table.head() # + _kg_hide-input=true _kg_hide-output=true papermill={"duration": 0.038401, "end_time": "2020-04-05T12:07:37.055246", "exception": false, "start_time": "2020-04-05T12:07:37.016845", "status": "completed"} tags=[] #hide # cases cases = ['Confirmed', 'Deaths'] # replacing Mainland china with just China full_table['Country/Region'] = full_table['Country/Region'].replace('Mainland China', 'China') # filling missing values full_table[['Province/State']] = full_table[['Province/State']].fillna('') full_table[cases] = full_table[cases].fillna(0) # + _kg_hide-input=true papermill={"duration": 0.109768, "end_time": "2020-04-05T12:07:37.191143", "exception": false, "start_time": "2020-04-05T12:07:37.081375", "status": "completed"} tags=[] #hide # cases in the ships ship = full_table[full_table['Province/State'].str.contains('Grand Princess')|full_table['Province/State'].str.contains('Diamond Princess cruise ship')] # china and the row china = full_table[full_table['Country/Region']=='China'] row = full_table[full_table['Country/Region']!='China'] # latest full_latest = full_table[full_table['Date'] == max(full_table['Date'])].reset_index() china_latest = full_latest[full_latest['Country/Region']=='China'] row_latest = full_latest[full_latest['Country/Region']!='China'] # latest condensed full_latest_grouped = full_latest.groupby('Country/Region')['Confirmed', 'Deaths'].sum().reset_index() china_latest_grouped = china_latest.groupby('Province/State')['Confirmed', 'Deaths'].sum().reset_index() row_latest_grouped = row_latest.groupby('Country/Region')['Confirmed', 'Deaths'].sum().reset_index() # + [markdown] papermill={"duration": 0.027858, "end_time": "2020-04-05T12:07:37.241725", "exception": false, "start_time": "2020-04-05T12:07:37.213867", "status": "completed"} tags=[] # # World-Wide Totals # + _kg_hide-input=true papermill={"duration": 0.039153, "end_time": "2020-04-05T12:07:37.305385", "exception": false, "start_time": "2020-04-05T12:07:37.266232", "status": "completed"} tags=[] #hide temp = full_table.groupby(['Country/Region', 'Province/State'])['Confirmed', 'Deaths'].max() # temp.style.background_gradient(cmap='Reds') # + _kg_hide-input=true papermill={"duration": 0.099981, "end_time": "2020-04-05T12:07:37.428265", "exception": false, "start_time": "2020-04-05T12:07:37.328284", "status": "completed"} tags=[] #hide_input temp = full_table.groupby('Date')['Confirmed', 'Deaths'].sum().reset_index() temp = temp[temp['Date']==max(temp['Date'])].reset_index(drop=True) temp.style.background_gradient(cmap='Pastel1') # + [markdown] papermill={"duration": 0.023123, "end_time": "2020-04-05T12:07:37.475287", "exception": false, "start_time": "2020-04-05T12:07:37.452164", "status": "completed"} tags=[] # # Progression of Virus Over Time # + papermill={"duration": 0.031434, "end_time": "2020-04-05T12:07:37.530620", "exception": false, "start_time": "2020-04-05T12:07:37.499186", "status": "completed"} tags=[] #hide_input # https://app.flourish.studio/visualisation/1571387/edit HTML('''<div class="flourish-embed flourish-bar-chart-race" data-src="visualisation/1571387"><script src="https://public.flourish.studio/resources/embed.js"></script></div>''') # + [markdown] papermill={"duration": 0.023698, "end_time": "2020-04-05T12:07:37.577616", "exception": false, "start_time": "2020-04-05T12:07:37.553918", "status": "completed"} tags=[] # # Maps # + _kg_hide-input=true papermill={"duration": 3.801293, "end_time": "2020-04-05T12:07:41.401831", "exception": false, "start_time": "2020-04-05T12:07:37.600538", "status": "completed"} tags=[] #hide # Confirmed fig = px.choropleth(full_latest_grouped, locations="Country/Region", locationmode='country names', color="Confirmed", hover_name="Country/Region", range_color=[1,7000], color_continuous_scale="aggrnyl", title='Countries with Confirmed Cases') fig.update(layout_coloraxis_showscale=False) fig.write_image('covid-eda-1-1.png') # + _kg_hide-input=true papermill={"duration": 0.608395, "end_time": "2020-04-05T12:07:42.042911", "exception": false, "start_time": "2020-04-05T12:07:41.434516", "status": "completed"} tags=[] #hide # Deaths fig = px.choropleth(full_latest_grouped[full_latest_grouped['Deaths']>0], locations="Country/Region", locationmode='country names', color="Deaths", hover_name="Country/Region", range_color=[1,50], color_continuous_scale="agsunset", title='Countries with Deaths Reported') fig.update(layout_coloraxis_showscale=False) fig.write_image('covid-eda-1-2.png') # + [markdown] papermill={"duration": 0.024706, "end_time": "2020-04-05T12:07:42.091351", "exception": false, "start_time": "2020-04-05T12:07:42.066645", "status": "completed"} tags=[] # ![](covid-eda-1-1.png) # ![](covid-eda-1-2.png) # + [markdown] papermill={"duration": 0.024098, "end_time": "2020-04-05T12:07:42.139324", "exception": false, "start_time": "2020-04-05T12:07:42.115226", "status": "completed"} tags=[] # # Top 20 Countries # + _kg_hide-input=true _kg_hide-output=true papermill={"duration": 0.038035, "end_time": "2020-04-05T12:07:42.201445", "exception": false, "start_time": "2020-04-05T12:07:42.163410", "status": "completed"} tags=[] #hide flg = full_latest_grouped flg.head() # + _kg_hide-input=true papermill={"duration": 0.462427, "end_time": "2020-04-05T12:07:42.689046", "exception": false, "start_time": "2020-04-05T12:07:42.226619", "status": "completed"} tags=[] #hide fig = px.bar(flg.sort_values('Confirmed', ascending=False).head(20).sort_values('Confirmed', ascending=True), x="Confirmed", y="Country/Region", title='Confirmed Cases', text='Confirmed', orientation='h', width=700, height=700, range_x = [0, max(flg['Confirmed'])+10000]) fig.update_traces(marker_color=cnf, opacity=0.6, textposition='outside') fig.write_image('covid-eda-4-1.png') # + _kg_hide-input=true papermill={"duration": 0.548491, "end_time": "2020-04-05T12:07:43.261305", "exception": false, "start_time": "2020-04-05T12:07:42.712814", "status": "completed"} tags=[] #hide fig = px.bar(flg.sort_values('Deaths', ascending=False).head(20).sort_values('Deaths', ascending=True), x="Deaths", y="Country/Region", title='Deaths', text='Deaths', orientation='h', width=700, height=700, range_x = [0, max(flg['Deaths'])+500]) fig.update_traces(marker_color=dth, opacity=0.6, textposition='outside') fig.write_image('covid-eda-4-2.png') # + _kg_hide-input=true papermill={"duration": 0.412857, "end_time": "2020-04-05T12:07:43.698036", "exception": false, "start_time": "2020-04-05T12:07:43.285179", "status": "completed"} tags=[] #hide # (Only countries with more than 100 case are considered) flg['Mortality Rate'] = round((flg['Deaths']/flg['Confirmed'])*100, 2) temp = flg[flg['Confirmed']>100] temp = temp.sort_values('Mortality Rate', ascending=False) fig = px.bar(temp.sort_values('Mortality Rate', ascending=False).head(15).sort_values('Mortality Rate', ascending=True), x="Mortality Rate", y="Country/Region", text='Mortality Rate', orientation='h', width=700, height=600, range_x = [0, 8], title='No. of Deaths Per 100 Confirmed Case') fig.update_traces(marker_color=act, opacity=0.6, textposition='outside') fig.write_image('covid-eda-4-5.png') # + [markdown] papermill={"duration": 0.025008, "end_time": "2020-04-05T12:07:43.747318", "exception": false, "start_time": "2020-04-05T12:07:43.722310", "status": "completed"} tags=[] # ![](covid-eda-4-1.png) # ![](covid-eda-4-2.png) # ![](covid-eda-4-5.png) # + [markdown] papermill={"duration": 0.023922, "end_time": "2020-04-05T12:07:43.795203", "exception": false, "start_time": "2020-04-05T12:07:43.771281", "status": "completed"} tags=[] # # Composition of Cases # + _kg_hide-input=true papermill={"duration": 1.856362, "end_time": "2020-04-05T12:07:45.675318", "exception": false, "start_time": "2020-04-05T12:07:43.818956", "status": "completed"} tags=[] #hide_input fig = px.treemap(full_latest.sort_values(by='Confirmed', ascending=False).reset_index(drop=True), path=["Country/Region", "Province/State"], values="Confirmed", height=700, title='Number of Confirmed Cases', color_discrete_sequence = px.colors.qualitative.Prism) fig.data[0].textinfo = 'label+text+value' fig.write_image('covid-eda-8-1.png') fig = px.treemap(full_latest.sort_values(by='Deaths', ascending=False).reset_index(drop=True), path=["Country/Region", "Province/State"], values="Deaths", height=700, title='Number of Deaths reported', color_discrete_sequence = px.colors.qualitative.Prism) fig.data[0].textinfo = 'label+text+value' fig.write_image('covid-eda-8-2.png') # + [markdown] papermill={"duration": 0.023823, "end_time": "2020-04-05T12:07:45.728949", "exception": false, "start_time": "2020-04-05T12:07:45.705126", "status": "completed"} tags=[] # ![](covid-eda-8-1.png) # ![](covid-eda-8-2.png) # + [markdown] papermill={"duration": 0.023539, "end_time": "2020-04-05T12:07:45.775949", "exception": false, "start_time": "2020-04-05T12:07:45.752410", "status": "completed"} tags=[] # # Epidemic Span # + [markdown] papermill={"duration": 0.023108, "end_time": "2020-04-05T12:07:45.822740", "exception": false, "start_time": "2020-04-05T12:07:45.799632", "status": "completed"} tags=[] # Note : In the graph, last day is shown as one day after the last time a new confirmed cases reported in the Country / Region # + _kg_hide-input=true papermill={"duration": 2.840285, "end_time": "2020-04-05T12:07:48.686576", "exception": false, "start_time": "2020-04-05T12:07:45.846291", "status": "completed"} tags=[] #hide_input # first date # ---------- first_date = full_table[full_table['Confirmed']>0] first_date = first_date.groupby('Country/Region')['Date'].agg(['min']).reset_index() # first_date.head() from datetime import timedelta # last date # --------- last_date = full_table.groupby(['Country/Region', 'Date', ])['Confirmed', 'Deaths'] last_date = last_date.sum().diff().reset_index() mask = last_date['Country/Region'] != last_date['Country/Region'].shift(1) last_date.loc[mask, 'Confirmed'] = np.nan last_date.loc[mask, 'Deaths'] = np.nan last_date = last_date[last_date['Confirmed']>0] last_date = last_date.groupby('Country/Region')['Date'].agg(['max']).reset_index() # last_date.head() # first_last # ---------- first_last = pd.concat([first_date, last_date[['max']]], axis=1) # added 1 more day, which will show the next day as the day on which last case appeared first_last['max'] = first_last['max'] + timedelta(days=1) # no. of days first_last['Days'] = first_last['max'] - first_last['min'] # task column as country first_last['Task'] = first_last['Country/Region'] # rename columns first_last.columns = ['Country/Region', 'Start', 'Finish', 'Days', 'Task'] # sort by no. of days first_last = first_last.sort_values('Days') # first_last.head() # visualization # -------------- # produce random colors clr = ["#"+''.join([random.choice('0123456789ABC') for j in range(6)]) for i in range(len(first_last))] #plot fig = ff.create_gantt(first_last, index_col='Country/Region', colors=clr, show_colorbar=False, bar_width=0.2, showgrid_x=True, showgrid_y=True, height=1600, title=('Gantt Chart')) fig.write_image('covid-eda-9-1.png') # + [markdown] papermill={"duration": 0.025903, "end_time": "2020-04-05T12:07:48.744733", "exception": false, "start_time": "2020-04-05T12:07:48.718830", "status": "completed"} tags=[] # ![](covid-eda-9-1.png) # + [markdown] papermill={"duration": 0.026256, "end_time": "2020-04-05T12:07:48.794445", "exception": false, "start_time": "2020-04-05T12:07:48.768189", "status": "completed"} tags=[] # # China vs. Not China # + _kg_hide-input=true papermill={"duration": 0.999151, "end_time": "2020-04-05T12:07:49.817020", "exception": false, "start_time": "2020-04-05T12:07:48.817869", "status": "completed"} tags=[] #hide # In China temp = china.groupby('Date')['Confirmed', 'Deaths'].sum().diff() temp = temp.reset_index() temp = temp.melt(id_vars="Date", value_vars=['Confirmed', 'Deaths']) fig = px.bar(temp, x="Date", y="value", color='variable', title='In China', color_discrete_sequence=[cnf, dth, rec]) fig.update_layout(barmode='group') fig.write_image('covid-eda-10-1.png') #----------------------------------------------------------------------------- # ROW temp = row.groupby('Date')['Confirmed', 'Deaths'].sum().diff() temp = temp.reset_index() temp = temp.melt(id_vars="Date", value_vars=['Confirmed', 'Deaths']) fig = px.bar(temp, x="Date", y="value", color='variable', title='Outside China', color_discrete_sequence=[cnf, dth, rec]) fig.update_layout(barmode='group') fig.write_image('covid-eda-10-2.png') # + _kg_hide-input=true papermill={"duration": 1.502906, "end_time": "2020-04-05T12:07:51.347564", "exception": false, "start_time": "2020-04-05T12:07:49.844658", "status": "completed"} tags=[] #hide def from_china_or_not(row): if row['Country/Region']=='China': return 'From China' else: return 'Outside China' temp = full_table.copy() temp['Region'] = temp.apply(from_china_or_not, axis=1) temp = temp.groupby(['Region', 'Date'])['Confirmed', 'Deaths'] temp = temp.sum().diff().reset_index() mask = temp['Region'] != temp['Region'].shift(1) temp.loc[mask, 'Confirmed'] = np.nan temp.loc[mask, 'Deaths'] = np.nan fig = px.bar(temp, x='Date', y='Confirmed', color='Region', barmode='group', text='Confirmed', title='Confirmed', color_discrete_sequence= [cnf, dth, rec]) fig.update_traces(textposition='outside') fig.write_image('covid-eda-10-3.png') fig = px.bar(temp, x='Date', y='Deaths', color='Region', barmode='group', text='Confirmed', title='Deaths', color_discrete_sequence= [cnf, dth, rec]) fig.update_traces(textposition='outside') fig.update_traces(textangle=-90) fig.write_image('covid-eda-10-4.png') # + _kg_hide-input=true papermill={"duration": 0.860045, "end_time": "2020-04-05T12:07:52.231766", "exception": false, "start_time": "2020-04-05T12:07:51.371721", "status": "completed"} tags=[] #hide gdf = full_table.groupby(['Date', 'Country/Region'])['Confirmed', 'Deaths'].max() gdf = gdf.reset_index() temp = gdf[gdf['Country/Region']=='China'].reset_index() temp = temp.melt(id_vars='Date', value_vars=['Confirmed', 'Deaths'], var_name='Case', value_name='Count') fig = px.bar(temp, x="Date", y="Count", color='Case', facet_col="Case", title='China', color_discrete_sequence=[cnf, dth, rec]) fig.write_image('covid-eda-10-5.png') temp = gdf[gdf['Country/Region']!='China'].groupby('Date').sum().reset_index() temp = temp.melt(id_vars='Date', value_vars=['Confirmed', 'Deaths'], var_name='Case', value_name='Count') fig = px.bar(temp, x="Date", y="Count", color='Case', facet_col="Case", title='ROW', color_discrete_sequence=[cnf, dth, rec]) fig.write_image('covid-eda-10-6.png') # + [markdown] papermill={"duration": 0.02438, "end_time": "2020-04-05T12:07:52.280272", "exception": false, "start_time": "2020-04-05T12:07:52.255892", "status": "completed"} tags=[] # ![](covid-eda-10-1.png) # ![](covid-eda-10-2.png) # ![](covid-eda-10-3.png) # ![](covid-eda-10-4.png) # ![](covid-eda-10-5.png) # + [markdown] papermill={"duration": 0.02409, "end_time": "2020-04-05T12:07:52.327657", "exception": false, "start_time": "2020-04-05T12:07:52.303567", "status": "completed"} tags=[] # # Data By Country # + [markdown] papermill={"duration": 0.024538, "end_time": "2020-04-05T12:07:52.375561", "exception": false, "start_time": "2020-04-05T12:07:52.351023", "status": "completed"} tags=[] # ### Top 50 Countries By Confirmed Cases # + _kg_hide-input=true papermill={"duration": 0.10543, "end_time": "2020-04-05T12:07:52.505054", "exception": false, "start_time": "2020-04-05T12:07:52.399624", "status": "completed"} tags=[] #hide_input temp_f = full_latest_grouped.sort_values(by='Confirmed', ascending=False).head(50) temp_f = temp_f.reset_index(drop=True) temp_f.style.background_gradient(cmap='Reds') # + [markdown] papermill={"duration": 0.025769, "end_time": "2020-04-05T12:07:52.556526", "exception": false, "start_time": "2020-04-05T12:07:52.530757", "status": "completed"} tags=[] # ### Top 25 Countries By Deaths Reported # + _kg_hide-input=true papermill={"duration": 0.058598, "end_time": "2020-04-05T12:07:52.641828", "exception": false, "start_time": "2020-04-05T12:07:52.583230", "status": "completed"} tags=[] #hide_input temp_flg = temp_f[temp_f['Deaths']>0][['Country/Region', 'Deaths']].head(25) temp_flg.sort_values('Deaths', ascending=False).reset_index(drop=True).style.background_gradient(cmap='Reds') # + [markdown] papermill={"duration": 0.02739, "end_time": "2020-04-05T12:07:52.696035", "exception": false, "start_time": "2020-04-05T12:07:52.668645", "status": "completed"} tags=[] # ## Top 25 Chinese Provinces By Confirmed Cases # + _kg_hide-input=true papermill={"duration": 0.075388, "end_time": "2020-04-05T12:07:52.797711", "exception": false, "start_time": "2020-04-05T12:07:52.722323", "status": "completed"} tags=[] #hide_input temp_f = china_latest_grouped[['Province/State', 'Confirmed', 'Deaths']] temp_f = temp_f.sort_values(by='Confirmed', ascending=False) temp_f = temp_f.reset_index(drop=True) temp_f.style.background_gradient(cmap='Pastel1_r') # + [markdown] papermill={"duration": 0.027742, "end_time": "2020-04-05T12:07:52.852585", "exception": false, "start_time": "2020-04-05T12:07:52.824843", "status": "completed"} tags=[] # # Related Work # + [markdown] papermill={"duration": 0.027479, "end_time": "2020-04-05T12:07:52.906930", "exception": false, "start_time": "2020-04-05T12:07:52.879451", "status": "completed"} tags=[] # 1. https://www.kaggle.com/imdevskp/mers-outbreak-analysis # 2. https://www.kaggle.com/imdevskp/sars-2003-outbreak-analysis # 3. https://www.kaggle.com/imdevskp/western-africa-ebola-outbreak-analysis #
_notebooks/2020-03-13-EDA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: pySpark (Spark 2.0.0) # language: python # name: pyspark # --- # + from pyspark import SparkConf from pyspark.sql import SparkSession import sys conf = SparkConf() conf.set("spark.driver.memory", "100g") conf.set("spark.executor.memory", "100g") conf.set("spark.master", "local[30]") conf.set("spark.driver.maxResultSize", "100g") conf.set("spark.executor.heartbeatInterval","1000000000s") conf.set("spark.network.timeout","1000000000s") spark = SparkSession.builder.config(conf=conf).appName("convertProfile").getOrCreate() from pyspark.ml.feature import HashingTF, IDF, Tokenizer from pyspark.ml.feature import Tokenizer, RegexTokenizer, CountVectorizer from pyspark.sql.functions import col, udf from pyspark.sql.types import IntegerType from pyspark.ml.feature import StopWordsRemover from pyspark.sql import functions as F from pyspark.sql import types as T from pyspark.ml.linalg import SparseVector, DenseVector from pyspark.sql.types import * from pyspark.sql.functions import lit, col, regexp_replace from pyspark.sql.functions import split, explode from pyspark.ml.feature import HashingTF, IDF, Tokenizer from pyspark.ml.feature import Tokenizer, RegexTokenizer, CountVectorizer from pyspark.sql.functions import col, udf from pyspark.sql.types import IntegerType from pyspark.sql import functions as F from pyspark.sql import types as T from pyspark.ml.linalg import SparseVector, DenseVector from pyspark.sql.types import * from pyspark.sql.functions import lit, col, regexp_replace from pyspark.sql.functions import split, explode # + class PokeProfile(): def __init__(self): """ data can be downloaded at http://snap.stanford.edu/data/soc-Pokec.html or run: wget http://snap.stanford.edu/data/soc-pokec-relationships.txt.gz . wget http://snap.stanford.edu/data/soc-pokec-profiles.txt.gz . zcat soc-pokec-relationships.txt.gz > soc-pokec-relationships.txt zcat soc-pokec-profiles.txt.gz > soc-pokec-profiles.txt mkdir output # place to save output parquet mkdir vocabulary # place to save vocabulary (vector-word mapping) """ self.userFile = "data/seminar_year.csv" self.userFile = "data/policy_adoption.csv" def readProfile(self): """ read the profile data """ self.profiles_=spark.read.option("delimiter", ",").option("header","true").csv(self.userFile) self.profiles_ = self.profiles_.na.fill("") def formatHeaders(self, headers = [ "user_id","year","title"]): """ provide the headers of the data frame """ for c,n in zip(self.profiles_.columns,headers): self.profiles_ = self.profiles_.withColumnRenamed(c,n) def tokenize(self, inputColProfile = "I_am_working_in_field", vocSize = 40, minDF = 1.0): """ tokenize string column, count the occurence of words and then use the occurence of the top words as vector :type inputColProfile: str: column to extract the vector :type vocSize: int: number of words to count :type minDF: float: minimun document frequency of the word :rtype: None """ self.vocSize = vocSize self.minDF = minDF self.inputColProfile = inputColProfile self.outputColProfile = "{}_words".format(self.inputColProfile) self.outputColProfileStop = "{}_words_stp".format(self.inputColProfile) self.outputTokensColProfile = "{}_tokens".format(self.inputColProfile) self.outputTokensDenseColProfile = "{}_dense".format(self.inputColProfile) regexTokenizer = RegexTokenizer(inputCol=self.inputColProfile, outputCol=self.outputColProfile, pattern="\\W|\\d") self.profiles_ = regexTokenizer.transform(self.profiles_) remover = StopWordsRemover(inputCol=self.outputColProfile, outputCol=self.outputColProfileStop) self.profiles_ = remover.transform(self.profiles_) self.cv = CountVectorizer(inputCol=self.outputColProfileStop, outputCol=self.outputTokensColProfile, vocabSize=self.vocSize, minDF=self.minDF) try: self.model = self.cv.fit(self.profiles_) self.profiles_ = self.model.transform(self.profiles_) vector_udf = udf(lambda vector: vector.toArray().tolist(),ArrayType(DoubleType())) self.profiles_ = self.profiles_.withColumn(self.outputTokensDenseColProfile, vector_udf(self.outputTokensColProfile)) self.profiles_ = self.profiles_.drop(self.inputColProfile) self.profiles_ = self.profiles_.drop(self.outputColProfile) self.profiles_ = self.profiles_.drop(self.outputColProfileStop) self.profiles_ = self.profiles_.drop(self.outputTokensColProfile) except: print("Tokenizing {} Failed".format(self.inputColProfile)) self.profiles_ = self.profiles_.drop(self.outputColProfile) def flattenVectorColumns(self, selected_columns = ["user_id", "year"]): """ convert from col1=[0,1,2], col2=[0,1,2], col3=3, col4=0 to col1.0,col1.1,col1.2,col2.0, col2.1,col2.2, col3, col4 """ self.selected_columns = selected_columns stringColumns = self.listStringColumns(self.index, self.cnt_each, all_columns = self.all_columns) stringColumns = [column + "_dense" for column in stringColumns] self.newColumns = [self.profiles_[column][i] for column in stringColumns for i in range(self.vocSize)] self.nonstringColumns = [column for column in self.profiles_.columns if column not in stringColumns] self.profiles_flatten = self.profiles_.select(self.selected_columns + self.newColumns) # self.profiles_flatten = self.profiles_.select(self.nonstringColumns + self.newColumns) # self.profiles_flatten = self.profiles_flatten.drop("_c59") def saveVocabulary(self): """ save the vocabulary to a separate file; vocabulary can work as a look up table for the word given the index in the word vector """ import pandas as pd pd.DataFrame(self.model.vocabulary).to_csv("data/vocabulary/{}.txt".format(self.inputColProfile), sep='\t', encoding='utf-8', header=False) def listStringColumns(self, index = 0, cnt_each = 10, all_columns = ["title"]): """ list of string columns in the data """ self.index = index self.cnt_each = cnt_each self.all_columns = all_columns # "pets", "completed_level_of_education", "" # all_columns = ["title"] self.cnt_string = len(all_columns) start, end = index*cnt_each, (index+1)*cnt_each return all_columns[start:end] def saveOutput(self, data, outputfile = "soc-pokec-profiles-vector", save_format = "parquet"): """ save data as parquet """ if save_format == "parquet": data.repartition(1).write.parquet("{}.parquet".format(outputfile)) else: data.repartition(1).write.csv("{}.csv".format(outputfile)) from pyspark.sql.functions import array, col, explode, struct, lit df = sc.parallelize([(1, 0.0, 0.6), (1, 0.6, 0.7)]).toDF(["A", "col_1", "col_2"]) def to_long(df, by): # Filter dtypes and split into column names and type description cols, dtypes = zip(*((c, t) for (c, t) in df.dtypes if c not in by)) # Spark SQL supports only homogeneous columns assert len(set(dtypes)) == 1, "All columns have to be of the same type" # Create and explode an array of (column_name, column_value) structs kvs = explode(array([ struct(lit(c).alias("key"), col(c).alias("val")) for c in cols ])).alias("kvs") return df.select(by + [kvs]).select(by + ["kvs.key", "kvs.val"]) # - PP = PokeProfile() PP.readProfile() PP.formatHeaders() for i in range(1): print(i) for eachColumn in PP.listStringColumns(i, cnt_each = 1): PP.tokenize(inputColProfile = eachColumn, vocSize = 40) PP.saveVocabulary() PP.flattenVectorColumns() headers = ["user_id", "year"] + PP.model.vocabulary for c,n in zip(PP.profiles_flatten.columns,headers): PP.profiles_flatten = PP.profiles_flatten.withColumnRenamed(c,n) PP.profiles_flatten = to_long(PP.profiles_flatten, ["user_id", "year"]) PP.profiles_flatten = PP.profiles_flatten.repartition(1) PP.profiles_flatten.write.csv("data/scholar_top_{}.csv".format(PP.vocSize), header = False, mode="overwrite") PP = PokeProfile() PP.readProfile() PP.formatHeaders(headers=["policy_id","policy_name","policy_subject_id","policy_start","policy_end","policy_description","policy_lda_1","policy_lda_2","policy_lda_3"]) PP.profiles_ = PP.profiles_.filter(PP.profiles_.policy_start > 1995) PP.profiles_.head(3) for i in range(1): print(i) for eachColumn in PP.listStringColumns(i, cnt_each = 1, all_columns = ["policy_name"]): PP.tokenize(inputColProfile = eachColumn, vocSize = 30) PP.saveVocabulary() PP.flattenVectorColumns(selected_columns = ["policy_start", "policy_end", "policy_id"]) headers = PP.selected_columns + PP.model.vocabulary for c,n in zip(PP.profiles_flatten.columns,headers): PP.profiles_flatten = PP.profiles_flatten.withColumnRenamed(c,n) PP.profiles_flatten.head(1) PP.profiles_flatten = to_long(PP.profiles_flatten, PP.selected_columns) PP.profiles_flatten = PP.profiles_flatten.repartition(1) # PP.profiles_flatten.write.csv("data/policy_top_{}.csv".format(PP.vocSize), header = False, mode="overwrite") PP.profiles_flatten.head(3) PP.profiles_state=spark.read.option("delimiter", ",").option("header","true").csv("data/policy_adoption_state.csv") PP.profiles_state = PP.profiles_state.na.fill("") PP.profiles_state.head(3) PP.profiles_all = PP.profiles_state.join(PP.profiles_flatten, PP.profiles_state.policy_id == PP.profiles_flatten.policy_id)\ .select(PP.profiles_state["*"],PP.profiles_flatten["*"]).drop(PP.profiles_state.policy_id) PP.profiles_all.head(5) PP.profiles_all = PP.profiles_all.repartition(1) PP.profiles_all.write.csv("data/policy_top_{}.csv".format(PP.vocSize), header = True, mode="overwrite") # + # import pandas as pd # self = PP # picso = pd.read_csv("data/picso.csv", header=None) # picso.columns = ['member', 'year', 'keyword', 'value'] # # policy_group = policy.groupby(self.column)['adoption'].sum() # # policy_group1 = policy_group.unstack(fill_value=0).to_panel() # # self.hist = policy_group1.fillna(0).values
src/src/engine/readScholarProfiles.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 # --- # <h2 align=center>Data Visualization and Analysis of Worldwide Box Office Revenue (Part 1)</h2> # <img src="revenue.png"> # + [markdown] heading_collapsed=true # ### Libraries # + hidden=true import numpy as np import pandas as pd pd.set_option('max_columns', None) import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline plt.style.use('ggplot') import datetime from scipy import stats from scipy.sparse import hstack, csr_matrix from sklearn.model_selection import train_test_split, KFold from wordcloud import WordCloud from collections import Counter from nltk.corpus import stopwords from nltk.util import ngrams from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.preprocessing import StandardScaler import nltk nltk.download('stopwords') stop = set(stopwords.words('english')) import os import plotly.offline as py py.init_notebook_mode(connected=True) import plotly.graph_objs as go import plotly.tools as tls import json import ast from urllib.request import urlopen from PIL import Image # - # ### Task 1: Data Loading and Exploration # # # ### Task 2: Visualizing the Target Distribution # # ### Task 3: Relationship between Film Revenue and Budget # *** # Note: If you are starting the notebook from this task, you can run cells from all the previous tasks in the kernel by going to the top menu and Kernel > Restart and Run All # *** # # ### Task 4: Does having an Official Homepage Affect Revenue? # *** # Note: If you are starting the notebook from this task, you can run cells from all the previous tasks in the kernel by going to the top menu and Kernel > Restart and Run All # *** # # ### Task 5: Distribution of Languages in Film # *** # Note: If you are starting the notebook from this task, you can run cells from all the previous tasks in the kernel by going to the top menu and Kernel > Restart and Run All # *** # # ### Task 6: Frequent Words in Film Titles and Discriptions # *** # Note: If you are starting the notebook from this task, you can run cells from all the previous tasks in the kernel by going to the top menu and Kernel > Restart and Run All # *** # ### Task 7: Do Film Descriptions Impact Revenue? # *** # Note: If you are starting the notebook from this task, you can run cells from all the previous tasks in the kernel by going to the top menu and Kernel > Restart and Run All # ***
Part1/Task 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 # language: python # name: python3 # --- # + # importacion general de librerias y de visualizacion (matplotlib y seaborn) import pandas as pd import numpy as np import random import re import nltk import string import operator pd.options.display.float_format = '{:20,.2f}'.format # suprimimos la notacion cientifica en los outputs import warnings warnings.filterwarnings('ignore') # - df_train = pd.read_csv('~/Documents/Datos/DataSets/TP2/train.csv', dtype={'id': np.int16, 'target': np.int8}) df_test = pd.read_csv('~/Documents/Datos/DataSets/TP2/test.csv', dtype={'id': np.int16}) df_final = pd.read_csv('~/Documents/Datos/DataSets/TP2/socialmedia-disaster-tweets-DFE.csv', usecols=['text', 'choose_one'], encoding = "ISO-8859-1") df_final['target'] = 0 df_final.loc[df_final['choose_one'] == 'Relevant', 'target'] = 1 df_final.head() def relevant(text): return df_final[df_final['text'] == text]['target'].values[0] df_test['target'] = df_test['text'].map(relevant) df_test.to_csv('~/Documents/Datos/DataSets/TP2/test_with_targets.csv', index=False)
TP2/Alejo/Testing.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 # --- # + # # !wget https://raw.githubusercontent.com/huseinzol05/malay-dataset/master/knowledge-graph/kelm/download.txt # + # with open('download.txt') as fopen: # data = list(filter(None, fopen.read().split())) # len(data) # + # import os # for row in data: # os.system(f'wget {row}') # + from glob import glob kelm = glob('/home/husein/pure-text/knowledge-graph/kelm_generated_corpus.jsonl-*.translated') tekgen_train = glob('/home/husein/pure-text/splitted-quadruples-train.tsv0*.translated') tekgen_test = '/home/husein/pure-text/quadruples-test.tsv.translated' tekgen_validation = '/home/husein/pure-text/quadruples-validation.tsv.translated' # - len(kelm), len(tekgen_train) # + import re import json from unidecode import unidecode def cleaning(string): return re.sub(r'[ ]+', ' ', unidecode(string)).strip() # + train_left, train_right = [], [] for file in kelm: print(file) with open(file) as fopen: for line in fopen: try: l = json.loads(line) c_en = cleaning(l['en']['reference']) c_ms = cleaning(l['candidate-ms']) if len(c_en.split()) < 150 and len(c_ms.split()) < 150 and l['en']['score'] > 0.55: train_right.append(c_en) train_left.append(c_ms) except Exception as e: print(e) # - list(zip(train_left[:1000], train_right[:1000])) len(train_left) # + # for file in tekgen_train: # print(file) # with open(file) as fopen: # for line in fopen: # try: # l = json.loads(line) # c_en = cleaning(l['L-en']) # c_ms = cleaning(l['R-ms']) # if len(c_en.split()) < 150 and len(c_ms.split()) < 150: # train_right.append(c_en) # train_left.append(c_ms) # except Exception as e: # print(e) # + # with open(tekgen_validation) as fopen: # for line in fopen: # try: # l = json.loads(line) # c_en = cleaning(l['L-en']) # c_ms = cleaning(l['R-ms']) # if len(c_en.split()) < 120 and len(c_ms.split()) < 120: # train_right.append(c_en) # train_left.append(c_ms) # except Exception as e: # print(e) # + # test_left, test_right = [], [] # with open(tekgen_test) as fopen: # for line in fopen: # try: # l = json.loads(line) # c_en = cleaning(l['L-en']) # c_ms = cleaning(l['R-ms']) # if len(c_en.split()) < 120 and len(c_ms.split()) < 120: # test_right.append(c_en) # test_left.append(c_ms) # except Exception as e: # print(e) # - len(train_left), len(train_right) # + from tqdm import tqdm train_X, train_Y = [], [] for i in tqdm(range(len(train_left))): if len(train_left[i]) and len(train_right[i]): train_X.append(train_left[i]) train_Y.append(train_right[i]) # + # test_X, test_Y = [], [] # for i in tqdm(range(len(test_left))): # if len(test_left[i]) and len(test_right[i]): # test_X.append(test_left[i]) # test_Y.append(test_right[i]) # - len(train_X), len(train_Y) # !mkdir train # # !mkdir test # + with open('train/left.txt', 'w') as fopen: fopen.write('\n'.join(train_X)) with open('train/right.txt', 'w') as fopen: fopen.write('\n'.join(train_Y)) # with open('test/left.txt', 'w') as fopen: # fopen.write('\n'.join(test_X)) # with open('test/right.txt', 'w') as fopen: # fopen.write('\n'.join(test_Y))
session/knowledge-graph/t2t/prepare-dataset.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 gluoncv as gcv import mxnet as mx # mxnet NDarray from mxnet import nd # MXNet Gluon Neural network layers. from mxnet.gluon import nn # optional for displaying the image import matplotlib.pyplot as plt import numpy as np import os import math # - def build_rot_matrix(angle): # a b # c d # calculate terms a = math.cos(x) b = -math.sin(x) c = math.sin(x) d = math.cos(x) # print("a = ", a) # print("b = ", b) # print("c = ", c) # print("d = ", d) # build np array np_array = np.array([ [a,b], [c,d] ]) # build mx.nd array nd_array = mx.nd.array(np_array) return nd_array # + x=0.5*math.pi rotate_90 = build_rot_matrix(x) print('rotate by 90 nd array is ', rotate_90) # - # Input Image in_data_batch = nd.arange(9).reshape((1,3,3)) print('in_data_batch is ', in_data_batch) in_data = in_data_batch[0] print('in_data ', in_data) # Output Image # setup an ouptut array with all nines, so I can see overwrites with new values out_data = nd.ones(9).reshape((3,3))*9 # out_data also needs to be in batch form out_data_batch = nd.expand_dims(out_data, axis=0) print('out_data_batch', out_data_batch) print('out_data is ', out_data) # setup a rotation matrix rotate_data = rotate_90 print('rotate_90 ', rotate_data) # NDArrayIter(data, label=None, batch_size=1, shuffle=False, # last_batch_handle='pad', data_name='data', # label_name='softmax_label') # # Ignore the label parameter. dataiter = mx.io.NDArrayIter(in_data_batch, batch_size=1, shuffle=False, last_batch_handle='discard') #batch_index = [0] for batch in dataiter: print('loop entry - a single batch - a single image in batch.data[0] from what is in in_data') # Does this copy or get an alias to the input image? input_img = batch.data[0] #print ('input_img = ', input_img.asnumpy()) print ('input_img.shape = ', input_img.shape) # this will print the axis including the batch axis # print('indicies are ', mx.nd.contrib.index_array(entire_img) ) # this will print the x,y axis and ignore the batch input_img_indexes = mx.nd.contrib.index_array(input_img, axes=(1, 2)) print('indexes are: ', input_img_indexes) print ('input_img_indexes.shape = ', input_img_indexes.shape) # Try to assign input data to output data based upon indicies orig_indexes = mx.nd.reshape(input_img_indexes, shape=(9,2)) print('orig_indexes ', orig_indexes) orig_indexes = orig_indexes.astype("float32") # I've seen one variant where matrix-matrix multiply # is done with .T. why? new_indexes = nd.dot(orig_indexes, rotate_data) print('new_indexes = ', new_indexes) new_indexes = new_indexes.astype('int64') print('new_indexes = ', new_indexes) new_indexes = new_indexes + nd.array(nd.array([0, 2])).astype('int64') print('new_indexes after shift to positive', new_indexes) print('out_data ', out_data) print('out_data.shape ', out_data.shape) out_data = in_data[new_indexes[:,0],new_indexes[:,1]] print('out_data ', out_data) out_data = out_data.reshape(3,3) print('out_data ', out_data)
python/rotate_four.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="tOPTumVgsP33" import pandas as pd import ast import numpy as np from statistics import mean final_papers = pd.read_csv('papers1k.csv') final_authors = pd.read_csv('authors1k.csv') final_orgs = pd.read_csv('orgs1k.csv') # + id="TIDk9RfTsXQP" final_orgs['num_of_papers'] = "" final_orgs['max_H_index'] = 0 final_orgs['ave_H_index'] = 0 final_orgs['H_index'] = "" final_orgs['journal_publications'] = "" # + id="l6x3lJTIsaGe" final_orgs['num_of_papers'] = final_orgs['papers'].str.count(',')+1 final_orgs['authors'] = final_orgs.authors.apply(lambda x: list(map(np.int64, ast.literal_eval(x)))) final_orgs['H_index'] = final_orgs.authors.apply(lambda x: [final_authors.loc[final_authors['id'] == j]['H_index'].tolist()[0] for j in x]) final_orgs['max_H_index'] = final_orgs.H_index.apply(lambda x:max(x)) final_orgs['ave_H_index'] = final_orgs.H_index.apply(lambda x:mean(x)) final_orgs['papers'] = final_orgs.papers.apply(lambda x: list(map(np.int64, ast.literal_eval(x)))) final_orgs['journal_publications'] = final_orgs.papers.apply(lambda x:mean([final_papers.loc[final_papers['id'] == j]['year'].tolist()[0] for j in x])) final_orgs.to_csv('orgs1k.csv')
old_version/Organization Data processing.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 # --- # # Periodic Trends # Charting the Patterns of Elements # # #### Step 1 - Creating a Checkpoint # >Create a checkpoint by clicking <b>File</b> ==> <b>Save and Checkpoint</b>. If you make a major mistake, you can click <u>File</u> ==> <u>Revert to Checkpoint</u> to reset the Jupyter Notebook online on Binder.org. # Import modules that contain functions we need import pandas as pd import numpy as np # %matplotlib inline import matplotlib.pyplot as plt # ## Pre-Questions # >Using the coding block below and what you've learned in this unit, answer questions 1 & 2. In order to display different versions of the periodic table, add or remove the # in front of Image(url...). Only one image can be displayed at once. After adding/removing the #s, execute the cells using <b> Shift + Enter </b> to display another image. # # + # This code imports the image of the periodic table from the URL below #uncomment the image(url=... for the periodic table you would like to see. Be sure only one is uncommented at a time. from IPython.display import Image from IPython.core.display import HTML # The periodic table of elements with symbols, atomic numbers, and atomic masses Image(url= 'http://www.chem.qmul.ac.uk/iupac/AtWt/table.gif') # The periodic table of elements color-coded by type of element (metals, nonmetals, and metalloids) #Image(url= 'https://fthmb.tqn.com/I1J8fd6q-skC40aXr7LkJJN9Bew=/1500x1000/filters:fill(auto,1)/about/periodic-table-58ea5e0a5f9b58ef7ed0a788.jpg') # The periodic table of the elements with elemental families identified #Image(url= 'http://images.tutorcircle.com/cms/images/44/periodic-table11.PNG') # - # ## Importing the Data into your Jupyter Notebook # # >The next 3 blocks of code imports the data and displays what information can be found in the data set. # + # Read in data that will be used for the calculations. # The data needs to be in the same directory(folder) as the program # Using pandas read_csv method, we can create a data frame #data = pd.read_csv("./data/elements.csv") # If you're not using a Binder link, you can get the data with this instead: data = pd.read_csv("https://gist.githubusercontent.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee/raw/1d92663004489a5b6926e944c1b3d9ec5c40900e/Periodic%2520Table%2520of%2520Elements.csv") # - # displays a preview of the first several rows of the data set data.head(3) # shows you what data you can graph the names of all the columns in the dataset data.columns # ## PART 1: Trends Related to Atomic Number # # >Use and modify the section of code below to answer questions 3-5 in your coding booklet. ax = data.plot('AtomicNumber', 'AtomicMass', title="Trends Related to Atomic Number", legend=False) ax.set(xlabel="Atomic Number", ylabel="Comparison Factor") # ## PART 2: The Periodicity of Element Properties # # >Use and modify the section of code below to answer questions 6 & 7 in your coding booklet. ax = data.plot('AtomicNumber', 'BoilingPoint', title="Looking for Periodicity of Properties", legend=False) ax.set(xlabel="Atomic Number", ylabel="Comparison Factor") # ## PART 3: Unstructured Coding # # >Use and modify the section of code below to answer questions 8-11 in your coding booklet. data.Radioactive.count() # + # Set variables for scatter plot x = data.Group y = data.NumberofValence plt.scatter(x,y) plt.title('Looking For Patterns') plt.xlabel('x-axis') plt.ylabel('y-axis') #this sets the interval on the x-axis plt.xticks(np.arange(min(x), max(x)+1, 1.0)) # This actually shows the plot plt.show() # - data[['AtomicNumber', 'Element', 'Type']].sort_values(by='AtomicNumber') # >This data was modified from a data set that came from Data-Scientists [<NAME>](http://www.data-explorer.com/data). Thanks to UCF undergraduates <NAME>, for finding the data set, and <NAME>, for formatting it.
Periodic_Trends.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 # --- # + # ๊ทธ๋ž˜ํ”„, ์ˆ˜ํ•™ ๊ธฐ๋Šฅ ์ถ”๊ฐ€ # Add graph and math features import pylab as py import numpy as np import numpy.linalg as nl # ๊ธฐํ˜ธ ์—ฐ์‚ฐ ๊ธฐ๋Šฅ ์ถ”๊ฐ€ # Add symbolic operation capability import sympy as sy # + sy.init_printing() # - # # ์ƒ๋ฏธ๋ถ„๋ฐฉ์ •์‹์„ ์œ„ํ•œ ์˜ค์ผ๋Ÿฌ๋ฒ•<br>Euler Method for Ordinary Differntial Equation # # # [![Euler's method | Differential equations| AP Calculus BC | Khan Academy](https://i.ytimg.com/vi/q87L9R9v274/hqdefault.jpg)](https://www.youtube.com/watch?v=q87L9R9v274) # # # ## ์—ฌ๋Ÿฌ $(t, x)$ ์ง€์ ์—์„œ์˜ ๊ธฐ์šธ๊ธฐ<br>Slopes at $(t, x)$ points # # # ๋‹ค์‹œ ํ•œ๋ฒˆ ์ฃผ์–ด์ง„ ๋ฏธ๋ถ„ ๋ฐฉ์ •์‹์„ ์ƒ๊ฐํ•ด ๋ณด์ž.<br>Let's think about the first order differential equation again. # # # $$ # \left\{ # \begin{align} # a_0 \frac{d}{dt}x(t)+a_1 x(t)&=0 \\ # x(0)&=x_0 \\ # \end{align} # \right. # $$ # # # ๋ฏธ๋ถ„ํ•ญ์„ ๋‚จ๊ธฐ๊ณ  ๋‚˜๋จธ์ง€๋ฅผ ๋“ฑํ˜ธ์˜ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์˜ฎ๊ฒจ ๋ณด์ž.<br>Let's move terms except the differential to the right side of the equal sign. # # # $$ # a_0 \frac{d}{dt}x(t)=-a_1 x(t) # $$ # # # ์–‘๋ณ€์„ $a_0$๋กœ ๋‚˜๋ˆ„์–ด ๋ณด์ž.<br>Let's divide both sides with $a_0$. # # # $$ # \frac{d}{dt}x(t)=-\frac{a_1}{a_0} x(t) # $$ # # # ์ด ์‹์˜ ์˜๋ฏธ๋ฅผ ํ•œ๋ฒˆ ์ƒ๊ฐํ•ด ๋ณด์ž.<br>Let's think about the meaning of this equation. # # # ์œ„ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์„ ๋งŒ์กฑ์‹œํ‚ค๋Š” ์–ด๋–ค ํ•จ์ˆ˜ $x(t)$์˜ $t=t_i$, $x=x_j$ ์ ์—์„œ์˜ $t$์— ๋Œ€ํ•œ ๊ธฐ์šธ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์„ ๊ฒƒ์ด๋ผ๋Š” ์˜๋ฏธ์ด๋‹ค.<br> # This equation indicates that a function $x(t)$ satisfying the differential equation above would have a slope as follows at a point of $t=t_i$ and $x=x_j$. # # # $$ # \left.\frac{d}{dt}x\right|_{\left(t, x\right)=\left(t_i,x_j\right)}=-\frac{a_1}{a_0} x_j # $$ # # # ์ด๋Ÿฐ์‹์œผ๋กœ $t$์˜ ๋ณ€ํ™”์— ๋”ฐ๋ฅธ $x$์˜ ๊ธฐ์šธ๊ธฐ $\frac{d}{dt}x(t)$ ๋ฅผ ๋ชจ๋“  $(t, x)$ ์ ์—์„œ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.<br> # In this way, we can find all the $\frac{d}{dx}x(t)$, slopes of $x$ with respect to the change of $t$ at all $(t, x)$ points. # # # ## ๋ฐฉํ–ฅ์žฅ ๊ธฐ์šธ๊ธฐ ์‹œ๊ฐํ™”<br>Visualizing the slopes in the [Direction Field](https://en.wikipedia.org/wiki/Direction_field) # # # ๋‹ค์Œ ์˜ˆ๋ฅผ ์ƒ๊ฐํ•ด ๋ณด์ž.<br> # Let's think about an example as follows. # # # $$ # \left\{ # \begin{align} # 2 \frac{d}{dt}x(t)+ x(t)&=0 \\ # x(0)&=x_0 \\ # \end{align} # \right. # $$ # # # ๊ธฐ์šธ๊ธฐ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํŒŒ์ด์ฌ ํ•จ์ˆ˜๋ฅผ ์ƒ๊ฐํ•ด ๋ณด์ž.<br>Let's think about a python function calculating the slope. # # # + a_0, a_1 = 2.0, 1.0 def dx_dt(t, x): return - a_1 * x / a_0 # - # ์˜ˆ๋ฅผ ๋“ค์–ด $0 \le t \le 10$, $-6 \le x \le 6$ ์ธ ์˜์—ญ์—์„œ ๊ธฐ์šธ๊ธฐ๋ฅผ ๊ทธ๋ ค ๋ณด์ž.<br> # Let's plot slopes within the region of $0 \le t \le 10$ and $-6 \le x \le 6$. # # # + t_slope = py.linspace(0, 10) x_slope = py.linspace(-6, 6) # + import ode_plot ode_plot.ode_slope_1state(dx_dt, x_slope, t_slope) py.savefig('slopes_t_x.svg') # - # ์œ„์™€ ๊ฐ™์ด ๋ชจ๋“  ์ ์—์„œ์˜ ๊ธฐ์šธ๊ธฐ์˜ ๊ทธ๋ฆผ์„ **๋ฐฉํ–ฅ์žฅ** ๋˜๋Š” **๊ธฐ์šธ๊ธฐ์žฅ** ์ด๋ผ๊ณ  ํ•œ๋‹ค.<br> # As above, a plot of the slopes of all points is called a [**Direction Field**](https://en.wikipedia.org/wiki/Direction_field) or **Slope Field** # # # # ์—„๋ฐ€ํ•ด๋ฅผ ๊ฒน์ณ ๊ทธ๋ ค ๋ณด์ž<br>Let's overlap the curve of the exact solution. # # # $$x(t)=x_0 e^{-\frac{a_1}{a_0} t}$$ # # # + x_0 = 4.5 def exact(t): return x_0 * py.exp((-a_1 / a_0) * t) x_exact_array = exact(t_slope) ode_plot.plot_slope_fileds_and_exact_solution(dx_dt, t_slope, x_slope,) py.savefig('slopes_t_x_exact.svg') # - # $t=0$์—์„œ์˜ $x$์˜ ์ดˆ๊ธฐ๊ฐ’์— ๋”ฐ๋ผ ์—„๋ฐ€ํ•ด๊ฐ€ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ์Œ์„ ๊ธฐ์–ตํ•˜์ž.<br>Let's remember that the exact solution may vary depending on the initial value of $x$ at $t=0$. # # # ์ด๊ฒƒ์„ ์ด์šฉํ•ด์„œ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ํ•ด ๊ณก์„ ์„ ๊ตฌํ•ด๋ณผ ์ˆ˜ ์žˆ์„๊นŒ?<br>Using this, can we find solution curves of a differential equation? # # # ## ์˜ค์ผ๋Ÿฌ๋ฒ•<br>Euler Method # # # $\left(t,x\right) = \left(0, x_0\right)$ ์—์„œ์˜ $x(t)$์˜ ๊ธฐ์šธ๊ธฐ๋ฅผ ์ƒ๊ฐํ•ด ๋ณด์ž.<br> # Let's think about the slope of $x(t)$ at $\left(t,x\right) = \left(0, x_0\right)$. # # # $$ # \left.\frac{d}{dt}x\right|_{\left(t, x\right)=\left(0,x_0\right)}=-\frac{a_1}{a_0} x_0=s_0 # $$ # # # ๊ทธ๋ ‡๋‹ค๋ฉด, $(0, x_0)$์ ์„ ์ง€๋‚˜๊ณ  ๊ธฐ์šธ๊ธฐ๊ฐ€ $s_0=-\frac{a_1}{a_0} x_0$ ์ธ ์ง์„ ์„ ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ๋‹ค.<br> # Then, we can think about a line passing through $(0, x_0)$ with the slope of $s_0=-\frac{a_1}{a_0} x_0$. # # # $$ # x=-\frac{a_1}{a_0} x_0 \left(t - 0 \right) + x_0=s_0\left(t - 0 \right) + x_0 # $$ # # # ์ด ์ง์„ ์„ ๋”ฐ๋ผ $t_1$ ๊นŒ์ง€ ์ „์ง„ํ•ด ๋ณด์ž.<br> # Following this line, let's move forward to $t_1$. # # # $$ # t_1=t_0 + \Delta t = 0 + 0.5 # $$ # # # + # Initial point t_0 = 0 x_0 = 4.5 # time step delta_t = 0.5 # + # Slope at the initial point (t_0, x_0) point s_0 = dx_dt(t_0, x_0) # Straight line to next time step t_0_array = py.linspace(0, delta_t) x_0_array = s_0 * (t_0_array - t_0) + x_0 # (t_1, x_1) point t_1, x_1 = t_0_array[-1], x_0_array[-1] # + ode_plot.indicate_initial_point(t_0, x_0) ode_plot.plot_one_step(t_0_array, x_0_array, 0) ode_plot.format_incremental_plot() # - # $(t_1, x_1)$ ์—์„œ์˜ ๊ธฐ์šธ๊ธฐ $s_1$ ๊ณผ ๊ทธ๋Ÿฌํ•œ ๊ธฐ์šธ๊ธฐ๋ฅผ ๊ฐ€์ง€๊ณ  $\left(t_1, x_1\right)$ ์„ ์ง€๋‚˜๋Š” ์ง์„ ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.<br> # The slope $s_1$ at $\left(t_1, x_1\right)$ and another line with such slope and passing $\left(t_1, x_1\right)$ would be as follows. # # # $$ # \begin{align} # \left.\frac{d}{dt}x\right|_{\left(t, x\right) = \left(t_1,x_1\right)} &=-\frac{a_1}{a_0} x_1=s_1 \\ # x & = s_1\left(t - t_1 \right) + x_1 # \end{align} # $$ # # # + # Slope at (t_1, x_1) point s_1 = dx_dt(t_1, x_1) # Straight line to next time step t_1_array = py.linspace(t_1, t_1 + delta_t) x_1_array = s_1 * (t_1_array - t_1) + x_1 # (t_2, x_2) point t_2, x_2 = t_1_array[-1], x_1_array[-1] # + # Indicate the line from (t_0, x_0) with slope s_0 ode_plot.indicate_initial_point(t_0, x_0) ode_plot.plot_one_step(t_0_array, x_0_array, 0) # Indicate the line from (t_1, x_1) with slope s_1 ode_plot.plot_one_step(t_1_array, x_1_array, 1) ode_plot.format_incremental_plot() # - # ์—„๋ฐ€ํ•ด์™€ ๋น„๊ตํ•ด ๋ณด์ž.<br>Let's compare with the exact solution. # # # + # https://stackoverflow.com/a/9236970 t_array = py.concatenate([t_0_array.tolist(), t_1_array.tolist()], axis=None) exact = ode_plot.ExactPlotterFirstOrderODE(t_array) # + # Indicate the line segments ode_plot.indicate_initial_point(t_0, x_0) ode_plot.plot_one_step(t_0_array, x_0_array, 0) ode_plot.plot_one_step(t_1_array, x_1_array, 1) # plot exact solution exact.plot() ode_plot.format_incremental_plot() # - # $t$๊ฐ’์ด ์ปค ์ง์— ๋”ฐ๋ผ, ์—„๋ฐ€ํ•ด์™€ $x_1$์˜ ์˜ค์ฐจ ๋ณด๋‹ค ์—„๋ฐ€ํ•ด์™€ $x_2$ ์‚ฌ์ด์˜ ์˜ค์ฐจ๊ฐ€ ์ปค์ง€๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.<br> # As $t$ increases, the error between $x_2$ and the exact solution is larger than the error between $x_1$ and the exact solution. # # # ## ํ•จ์ˆ˜๋กœ ๋ณ€ํ™˜<br>Convert to a function # # # ์‚ฌ์šฉ์ƒ ํŽธ๋ฆฌ๋ฅผ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ๋ณด์ž.<br>To make it easier to use, let's make it a function. # # # + def euler(f, t_array, x_0): time_list = [t_array[0]] result_list = [x_0] x_i = x_0 for k, t_i in enumerate(t_array[:-1]): # time step delta_t = t_array[k+1] - t_array[k] # slope s_i = f(t_i, x_i) # x[i + 1] x_i_plus_1 = x_i + s_i * delta_t time_list.append(t_array[k+1]) result_list.append(x_i_plus_1) x_i = x_i_plus_1 return time_list, result_list # - # ๋‹ค์‹œ ๊ทธ๋ ค ๋ณด์ž.<br>Let's plot again. # # # + # Time step interval delta_t = 0.5 # Time array t_sec_array = np.arange(0, 1 + delta_t*0.5, delta_t) # Initial state x_0 = 4.5 # *** new function *** t_euler_out, x_euler_out = euler(dx_dt, t_sec_array, x_0) # *** new function *** py.plot(t_euler_out, x_euler_out, 'o-') for k in range(len(t_euler_out)): ode_plot.text_xy_k(t_euler_out[k], x_euler_out[k], k) # Indicate the exact solution exact.plot() ode_plot.format_incremental_plot() # - # ## $\Delta t$ ๊ฐ„๊ฒฉ์˜ ์˜ํ–ฅ<br>Influence of $\Delta t$ interval # # # ์˜ค์ฐจ๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋Š” ์ข‹์€ ๋ฐฉ๋ฒ•์ด ์—†์„๊นŒ?<br>Is there a good way to reduce the error? # # # $\Delta t=0.5$ ๋ฅผ $\Delta t=0.1$๋กœ ํ•œ๋ฒˆ ์ค„์—ฌ ๋ณด์ž.<br>Let's make $\Delta t=0.5$ to $\Delta t=0.1$. # # # + # Time step interval & Time array delta_t = 0.1 t_sec_array = np.arange(0, 1 + delta_t*0.5, delta_t) # Initial state x_0 = 4.5 # *** new function *** t_euler_out_01, x_euler_out_01 = euler(dx_dt, t_sec_array, x_0) # + py.plot(t_euler_out, x_euler_out, 'o-', label='$\Delta t=0.5$') py.plot(t_euler_out_01, x_euler_out_01, '.-', label='$\Delta t=0.1$') # Indicate the exact solution exact.plot() ode_plot.format_incremental_plot() # - # $\Delta t$ ๊ฐ„๊ฒฉ์„ ์ค„์ด๋ฉด ์˜ค์ฐจ์— ์–ด๋–ค ์˜ํ–ฅ์„ ๋ฏธ์ณค๋Š”๊ฐ€?<br>How did reducing $\Delta t$ interval influence the error? # # # ### ๊ทผ์‚ฌํ•ด์™€ ๋ฐฉํ–ฅ์žฅ<br>Approximate solutions and direction fields # # # ํ•ด๋ฅผ ๋ฐฉํ–ฅ์žฅ๊ณผ ๊ฒน์ณ ๊ทธ๋ ค ๋ณด์ž.<br> # Let's overlap the solutions and the direction field. # # # $t$์™€ $x$์˜ ๋ฒ”์œ„<br> # Ranges of $t$ and $x$ # # # + t_slopes = py.linspace(0, 6) x_slopes = py.linspace(0, 6) # - # ์ดˆ๊ธฐ๊ฐ’<br>Initial value<br> # $x(t_0)$ # # # + x_0 = 4.5 # - # $ # \Delta t = 0.5 # $ (sec) # # # + delta_t_05 = 0.5 t_05_sec = np.arange(t_slopes[0], t_slopes[-1] + delta_t_05*0.5, delta_t_05) t_out_05, x_out_05 = euler(dx_dt, t_05_sec, x_0) # - # $ # \Delta t = 0.1 # $ (sec) # # # + delta_t_01 = 0.1 t_01_sec = np.arange(t_slopes[0], t_slopes[-1] + delta_t_01*0.5, delta_t_01) t_out_01, x_out_01 = euler(dx_dt, t_01_sec, x_0) # - # ์ด์ œ ๊ทธ๋ ค ๋ณด์ž.<br>Now let's plot. # # # + # Slopes at each (t, x) points ode_plot.ode_slope_1state(dx_dt, x_slopes, t_slopes) py.plot(t_out_05, x_out_05, 'o-', label='$\Delta t=0.5$') py.plot(t_out_01, x_out_01, 'o-', label='$\Delta t=0.1$') # plot exact solution exact = ode_plot.ExactPlotterFirstOrderODE(t_slopes) exact.plot() # Aspect ratio py.axis('equal') # xy limits py.xlim(left=t_slopes[0], right=t_slopes[-1]) py.ylim(bottom=x_slopes[0], top=x_slopes[-1]) py.legend(loc=1, fontsize='xx-large'); # - # $i$๋ฒˆ์งธ ์ ๊ณผ $i+1$๋ฒˆ์งธ ์  ์‚ฌ์ด์—์„œ $\frac{d}{dt}x(t)$๋Š” ๊ณ„์† ๋ณ€ํ™”ํ•˜๊ณ  ์žˆ์œผ๋‚˜, ์˜ค์ผ๋Ÿฌ๋ฒ•์€ ํ•ด๋‹น ๊ตฌ๊ฐ„์—์„œ์˜ ๊ธฐ์šธ๊ธฐ๊ฐ€ $\frac{d}{dt}x(t_i)$์ธ ๊ฒƒ์œผ๋กœ ๊ฐ€์ •ํ•œ๋‹ค.<br> # Between the $i$th and $i+1$st points, $\frac{d}{dt}x(t)$ continuously changes. However, the Euler Method assumes that the slope is fixed at $\frac{d}{dt}x(t_1)$ within the interval. # # # ๊ทธ๋ ‡๋‹ค๋ฉด, $t_i \le t \le t_{i+1}$ ์‚ฌ์ด์—์„œ ๋Œ€ํ‘œ์ ์ธ $\frac{d}{dt}x$ ๊ฐ’์€ ์–ด๋–ค ๊ฐ’์ด ์ข‹์„ ๊ฒƒ์ธ๊ฐ€?<br> # If so, within $t_i \le t \le t_{i+1}$, which value of $\frac{d}{dt}x$ would be representative? # # # ## Scipy # # # ๊ณผํ•™๊ธฐ์ˆ  ๊ณ„์‚ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ธ ์‚ฌ์ดํŒŒ์ด `scipy` ์˜ `scipy.integrate` ๋ฅผ ํ†ตํ•ด์„œ ๋‹ค์ˆ˜์˜ ์ƒ๋ฏธ๋ถ„ ๋ฐฉ์ •์‹ ์†”๋ฒ„ solver ๋ฅผ ์ œ๊ณตํ•œ๋‹ค.<br> # As a scientific computation library, `scipy` has ODE solvers in `scipy.integrate`. # # # + import scipy.integrate as si # + sol = si.solve_ivp(dx_dt, (t_out_01[0], t_out_01[-1]), [x_0], t_eval=t_out_01) # - # ์—„๋ฐ€ํ•ด, ์˜ค์ผ๋Ÿฌ๋ฒ• ๊ฒฐ๊ณผ์™€ ๋น„๊ตํ•ด๋ณด์ž.<br> # Let's compare with the exact solution and the result of the Euler's method. # # # + py.plot(sol.t, sol.y[0, :], 'o', label='solve_ivp') py.plot(t_out_01, x_out_01, '.-', label='$\Delta t=0.1$') # plot exact solution exact = ode_plot.ExactPlotterFirstOrderODE(t_slopes) exact.plot() py.grid(True) py.xlabel('t(sec)') py.ylabel('y(t)') py.legend(loc=0); # - # ํŒ๋‹ค์Šค `pandas` ๋ฅผ ์ด์šฉํ•ด ํ‘œ ํ˜•ํƒœ๋กœ๋„ ์‚ดํŽด๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋‹ค.<br> # The `pandas`would enable observing in a table form. # # # + import pandas as pd df = pd.DataFrame( data={ 'euler':x_out_01, 'solve_ivp':sol.y[0, :], 'exact':exact.exact(py.array(t_out_01)) }, index=pd.Series(t_out_01, name='t(sec)'), columns=['exact', 'euler', 'solve_ivp'] ) # - # ์—ด ์—ฐ์‚ฐ์œผ๋กœ ์—„๋ฐ€ํ•ด์— ๋Œ€ํ•œ ์˜ค์ฐจ๋ฅผ ๊ตฌํ•ด๋ณด์ž.<br> # Let's calculate the error against the exact solution. # # # + df['euler_error'] = df.euler - df.exact df['solve_ivp_error'] = df.solve_ivp - df.exact # - # ํ‘œ ํ˜•ํƒœ<br>Table form # # # + pd.set_option('display.max_rows', 10) df # - # ๊ฐ์ข… ํ†ต๊ณ„<br>Statistics # # # + df.describe() # - # ์ด ๊ฒฝ์šฐ, ์˜ค์ผ๋Ÿฌ๋ฒ•์˜ ์˜ค์ฐจ์— ๋Œ€ํ•œ ์˜๊ฒฌ์€?<br> # In this case, what do you think about the error of the Euler method? # # # + import numpy.linalg as nl nl.norm(df.euler_error), nl.norm(df.solve_ivp_error), # - # ## ์—ฐ์Šต ๋ฌธ์ œ<br>Exercise # ๋„์ „๊ณผ์ œ 1: ๋‹ค์Œ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ํ•ด๊ณก์„ ์„ ์ „์ง„ ์˜ค์ผ๋Ÿฌ๋ฒ•์œผ๋กœ ๊ตฌํ•˜์‹œ์˜ค.<br> # Try This 1: Find a solution curve of the following differential equation using the forward Euler method. # # # $$ # \begin{cases} # \begin{align} # a_0\frac{d}{dt}x(t) + a_1 x(t) &= 0 \\ # x(0)&=x_0 # \end{align} # \end{cases} # $$ # ๋„์ „๊ณผ์ œ 2: ๋‹ค์Œ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ํ•ด๊ณก์„ ์„ ์ „์ง„ ์˜ค์ผ๋Ÿฌ๋ฒ•์œผ๋กœ ๊ตฌํ•˜์‹œ์˜ค.<br> # Try This 2: Find a solution curve of the following differential equation using the forward Euler method. # # # $$ # \begin{cases} # \begin{align} # a_0 \frac{d}{dt}x(t) + a_1 x(t) &= b_0 t \\ # x(0)&=0 # \end{align} # \end{cases} # $$ # ๋„์ „๊ณผ์ œ 3: ๋‹ค์Œ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ํ•ด๊ณก์„ ์„ ์ „์ง„ ์˜ค์ผ๋Ÿฌ๋ฒ•์œผ๋กœ ๊ตฌํ•˜์‹œ์˜ค.<br> # Try This 3: Find a solution curve of the following differential equation using the forward Euler method. # # # $$ # \begin{cases} # \begin{align} # a_0 \frac{d}{dt}x(t) + a_1 x(t) &= b_0 sin(t) \\ # x(0)&=x_0 # \end{align} # \end{cases} # $$ # ๋„์ „๊ณผ์ œ 4: ๋‹ค์Œ ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ํ•ด๊ณก์„ ์„ ์ „์ง„ ์˜ค์ผ๋Ÿฌ๋ฒ•์œผ๋กœ ๊ตฌํ•˜์‹œ์˜ค.<br> # Try This 4: Find a solution curve of the following differential equation using the forward Euler method. [[link](https://en.wikipedia.org/wiki/Bernoulli_differential_equation)]<br> # $1 \le x \le 10$ # # # $$ # \begin{cases} # \begin{align} # \frac{d}{dx}y(x) - \frac{2}{x}y(x) &= -x^2y^2 \\ # y(1)&=1 # \end{align} # \end{cases} # $$ # ## ์˜ˆ์ƒ ์ž๋ฃŒํ˜•<br>Type hints # # # References : [[1](https://docs.python.org/3/library/typing.html)], [[2](https://stackoverflow.com/a/54610845)] # # # ํƒ€์ž… ํžŒํŠธ๋Š” ๋ณ€์ˆ˜์˜ ์˜ˆ์ƒ ์ž๋ฃŒํ˜•์„ ์˜ˆ์‹œํ•˜์—ฌ (๊ฐœ๋ฐœ์ž ๋˜๋Š”) ๊ฐœ๋ฐœ์šฉ ์†Œํ”„ํŠธ์›จ์–ด ๋“ฑ์„ ๋•๊ธฐ ์œ„ํ•œ ๊ฒƒ์ด๋‹ค.<br> # Type hints are to present expected data types to help (developers or) development software. # # # + def dx_dt_type_hints(t:float, x:float) -> float: return - a_1 / a_0 * x # - # ์˜ˆ๋ฅผ ๋“ค์–ด ์œ„ ํ•จ์ˆ˜๋Š” ์‹ค์ˆ˜ํ˜• ๋งค๊ฐœ๋ณ€์ˆ˜ `t`, ์‹ค์ˆ˜ํ˜• ๋งค๊ฐœ๋ณ€์ˆ˜ `x` ๋ฅผ ๋ฐ›์•„๋“ค์—ฌ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ์‹ค์ˆ˜ํ˜•์œผ๋กœ ๋ฐ˜ํ™˜ํ•  ๊ฒƒ์ด๋ผ๋Š” ์˜๋ฏธ์ด๋‹ค.<br> # For example, the function above would accept two `float` arguments of `t` and `x` to return the calculated result in `float`. # # # ๋งค๊ฐœ๋ณ€์ˆ˜ `t` ๊ฐ€ ์‹ค์ˆ˜ํ˜• ๋˜๋Š” ์ •์ˆ˜ํ˜•์œผ๋กœ ์˜ˆ์ƒ๋œ๋‹ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด `typing` ๋ชจ๋“ˆ์˜ `Union`์œผ๋กœ ํ‘œ์‹œํ•  ์ˆ˜ ์žˆ๋‹ค.<br> # If the argument `t`is expected to be `float` or `int`, we can indicate as follows using `Union` of the `typing` module. # # # + import typing def dx_dt_type_hints(t:typing.Union[float, int], x:float) -> float: return - a_1 / a_0 * x # - # `euler( )`์™€ ๊ฐ™์ด ํ•จ์ˆ˜ ๋˜๋Š” list๋ฅผ ๋ฐ›์•„๋“ค์ด๋Š” ๊ฒฝ์šฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ‘œ์‹œํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋‹ค.<br> # If arguments are a function or a list as `euler( )`, following cell would be possible. # # # + import typing import numpy as np Scalar = typing.Union[float, int] Time = Scalar TimeList = typing.Union[typing.List[Time], typing.Tuple[Time]] State = typing.Union[Scalar, typing.List[Scalar], typing.Tuple[Scalar], np.ndarray] StateList = typing.Union[typing.List[State], typing.Tuple[State]] SlopeFunction = typing.Callable[[Time, State], State] def euler(f:SlopeFunction, t_array:TimeList, x_0, State) -> typing.Tuple[TimeList, StateList]: time_list = [t_array[0]] result_list = [x_0] x_i = x_0 for k, t_i in enumerate(t_array[:-1]): # time step delta_t = t_array[k+1] - t_array[k] # slope s_i = f(t_i, x_i) # x[i + 1] x_i_plus_1 = x_i + s_i * delta_t time_list.append(t_array[k+1]) result_list.append(x_i_plus_1) x_i = x_i_plus_1 return time_list, result_list # - # ## ์ค‘์ฒฉํ•จ์ˆ˜์™€ ํด๋กœ์ ธ<br>Nested function and Closure # # # ๋‚ด์žฅ ํ•จ์ˆ˜๋Š” ๋‹ค๋ฅธ ํ•จ์ˆ˜ ์•ˆ์— ์ •์˜๋œ ํ•จ์ˆ˜์ด๋‹ค.<br>A nested function is a function defined another function. # # # + def function_with_a_nested_function(t_list, x_list, a=0.5, b=2): def nested_function(t_i, x_i): return a * t_i + b * x_i y_list = [] for t_j, x_j in zip(t_list, x_list): y_list.append(nested_function(t_j, x_j)) return y_list # + t_list = [0, 1, 2] x_list = [0.1, 0.2, 0.3] function_with_a_nested_function(t_list, x_list) # - # **ํด๋กœ์ ธ**๋Š” ์ด๋Ÿฌํ•œ *๋‚ด์žฅ ํ•จ์ˆ˜๊ฐ€ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’*์ธ ๊ฒฝ์šฐ๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.<br> # A **closure** can be a nested function returned from a function. # # # + def function_returning_a_closure(a=0.5, b=2): def this_will_be_a_closure(t_i, x_i): return a * t_i + b * x_i return this_will_be_a_closure # no ( ) # + this_is_a_closure = function_returning_a_closure() t_list_closure = [0, 1, 2] x_list_closure = [0.1, 0.2, 0.3] y_list_closure = [] for t_j, x_j in zip(t_list_closure, x_list_closure): y_list_closure.append(this_is_a_closure(t_j, x_j)) y_list_closure # - # ์˜ˆ๋ฅผ ๋“ค์–ด ๋ฏธ๋ถ„๋ฐฉ์ •์‹์˜ ๊ธฐ์šธ๊ธฐ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ closure ๋กœ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅํ•  ๊ฒƒ์ด๋‹ค.<br> # For example, we may think about a function returning a closure calculating the slope for the differential equation. # # # + def get_slope_function_LODE1(a0, a1): minus_a1_over_a0 = -a1 / a0 def slope_LODE1(t, x): return minus_a1_over_a0 * x return slope_LODE1 # + dx_dt_closure = get_slope_function_LODE1(a_0, a_1) # + # Slopes at each (t, x) points ode_plot.ode_slope_1state(dx_dt, x_slopes, t_slopes) py.plot(t_out_05, x_out_05, 'o-', label='$\Delta t=0.5$') py.plot(t_out_01, x_out_01, 'o-', label='$\Delta t=0.1$') # plot exact solution exact = ode_plot.ExactPlotterFirstOrderODE(t_slopes) exact.plot() # Aspect ratio py.axis('equal') # xy limits py.xlim(left=t_slopes[0], right=t_slopes[-1]) py.ylim(bottom=x_slopes[0], top=x_slopes[-1]) py.legend(loc=1, fontsize='xx-large'); # - # ์•„๋ž˜ ์…€์€ ํ•จ์ˆ˜ `dx_dt()` ์™€ `dx_dt_closure()`์˜ ๊ฒฐ๊ณผ๋ฅผ ๋น„๊ตํ•œ๋‹ค.<br> # Following cell compares results from functions `dx_dt()` and `dx_dt_closure()` # # # + import numpy as np import numpy.testing as nt slope_dx_dt = np.array([dx_dt(t_k, x_k) for t_k, x_k in zip(t_out_01, x_out_01)]) slope_dx_dt_closure = np.array([dx_dt_closure(t_k, x_k) for t_k, x_k in zip(t_out_01, x_out_01)]) nt.assert_array_almost_equal(slope_dx_dt, slope_dx_dt_closure, err_msg="Closure results seem different.") # - # ## Final Bell<br>๋งˆ์ง€๋ง‰ ์ข… # # # + # stackoverfow.com/a/24634221 import os os.system("printf '\a'"); # -
10_Forward_Euler.ipynb