hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
cbe124020a3dae905bcbdeb8aaee4d8c089d4027
50,157
ipynb
Jupyter Notebook
web-server-related-tutorials/pandas-movie-recommender/movie-recommendation-system-scratch-master/movie-lens-recommendation-system-from-scratch.ipynb
djfedos/djfedos-boostrap
8a2fb1259c52134f6bcbda53821ab8f3b20e50e4
[ "Apache-2.0" ]
null
null
null
web-server-related-tutorials/pandas-movie-recommender/movie-recommendation-system-scratch-master/movie-lens-recommendation-system-from-scratch.ipynb
djfedos/djfedos-boostrap
8a2fb1259c52134f6bcbda53821ab8f3b20e50e4
[ "Apache-2.0" ]
9
2021-11-03T18:57:45.000Z
2022-03-26T06:29:38.000Z
web-server-related-tutorials/pandas-movie-recommender/movie-recommendation-system-scratch-master/movie-lens-recommendation-system-from-scratch.ipynb
djfedos/djfedos-boostrap
8a2fb1259c52134f6bcbda53821ab8f3b20e50e4
[ "Apache-2.0" ]
null
null
null
32.954665
640
0.427677
[ [ [ "# Coding Recommendation Engines Ground Up\n***\n## Overview\nRecommendation Engines are the programs which basically compute the similarities between two entities and on that basis, they give us the targeted output. If we look at the root level of the recommendation engines, they all are trying to find out the level of similarity between two entities. Then, the computed similarities can be used to calculate the various kinds of results.\n\n**Recommendation Engines are mostly based on the following concepts:**\n 1. Popularity Model\n 2. Collaborative Filtering Technique (Content Based / User Based)\n 3. Matrix Factorization Techniques. \n\n\n### Popularity Model\n***\nThe most basic form of a recommendation engine would be where the engine recommends the most popular items to all the customers. That would be generalised as everyone is getting the similar recommendations as we didn't personalize the recommendations. These kinds of recommendation engines are based on the **Popularity Model**. THe use case for this model would be the 'Top News' Section for the day on a news website where the most popular new for everyone is same irespective of the interests of every user because that makes a logical sense because News is a generalized thing and it has got nothing to do with your likeliness.\n\n\n\n### Collaborative Filtering Techniques\n***\n**User Based Collaborative Filetering**\n\nIn user based collaborative filtering, we find out the similarity score between the two users. On the basis of similarity score, we recommend the items bought/liked by one user to other user assuing that he might like these items on the basis of similarity. This will be more clear when we go ahead and implement this.\n\n\n**Content Based Filtering**\n\nIn user based filtering technique, we saw that we recommend items to a used based on the similarity score between two users where it does not matter whether the items were of a similar type. But, in this tehchnique out interest is in the content rather than the users. Here, if user 1 like watching movies of genre A (most of the movies he has watched/rated highly are of genre A), then we will recommend him more movies of the same genre. That's how this things works.\n\n\n\n### Matrix Factorization Techniques\n***\nIn this technique, our objective is to find out the latent features which we derive m*n matrix by taking the dot product of m*k and k*n matrices where k is out latent feature matrix. Here if we go by an example, if m is the row index of the users and n is column index of the items adn data is the rating provided by every user, then we start with m*k and k*n matrices by adjusting values such that they finally converge to ~ m*n matrix (not totally the same ofocurse). This is a very expensive approach but highly accurate.\n\n\n\n## Problem Statement\n***\nWe have a movie lens database and our objective is to apply various kinds of recommendation techniques from scratch and find out similarities between the users, most popular movies, and personalized recommendations for the targeted user based on user based collaborative filtering.", "_____no_output_____" ] ], [ [ "# Importing the required libraries.\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom math import pow, sqrt", "_____no_output_____" ], [ "# Reading users dataset into a pandas dataframe object.\nu_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']\nusers = pd.read_csv('data/users.dat', sep='::', names=u_cols,\n encoding='latin-1')", "/tmp/ipykernel_44083/484106584.py:3: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.\n users = pd.read_csv('data/users.dat', sep='::', names=u_cols,\n" ], [ "users.head(8)", "_____no_output_____" ], [ "# Reading ratings dataset into a pandas dataframe object.\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\nratings = pd.read_csv('data/ratings.dat', sep='::', names=r_cols,\n encoding='latin-1')", "/tmp/ipykernel_44083/1225598432.py:3: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.\n ratings = pd.read_csv('data/ratings.dat', sep='::', names=r_cols,\n" ], [ "ratings.head(8)", "_____no_output_____" ], [ "# Reading movies dataset into a pandas dataframe object.\nm_cols = ['movie_id', 'movie_title', 'genre']\nmovies = pd.read_csv('data/movies.dat', sep='::', names=m_cols, encoding='latin-1')", "/tmp/ipykernel_44083/3303852832.py:3: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.\n movies = pd.read_csv('data/movies.dat', sep='::', names=m_cols, encoding='latin-1')\n" ], [ "movies.head(8)", "_____no_output_____" ] ], [ [ "As seen in the above dataframe, the genre column has data with pipe separators which cannot be processed for recommendations as such. Hence, we need to genrate columns for every genre type such that if the movie belongs to that genre its value will be 1 otheriwse 0.(Sort of one hot encoding)", "_____no_output_____" ] ], [ [ "# Getting series of lists by applying split operation.\nmovies.genre = movies.genre.str.split('|')", "_____no_output_____" ], [ "# Getting distinct genre types for generating columns of genre type.\ngenre_columns = list(set([j for i in movies['genre'].tolist() for j in i]))", "_____no_output_____" ], [ "# Iterating over every list to create and fill values into columns.\nfor j in genre_columns:\n movies[j] = 0\nfor i in range(movies.shape[0]):\n for j in genre_columns:\n if(j in movies['genre'].iloc[i]):\n movies.loc[i,j] = 1", "_____no_output_____" ], [ "movies.head(7)", "_____no_output_____" ] ], [ [ "Also, we need to separate the year part of the 'movie_title' columns for better interpretability and processing. Hence, a columns named 'release_year' will be created using the below code.", "_____no_output_____" ] ], [ [ "# Separting movie title and year part using split function\nsplit_values = movies['movie_title'].str.split(\"(\", n = 1, expand = True) \n\n# setting 'movie_title' values to title part and creating 'release_year' column.\nmovies.movie_title = split_values[0]\nmovies['release_year'] = split_values[1]\n\n# Cleaning the release_year series and dropping 'genre' columns as it has already been one hot encoded.\nmovies['release_year'] = movies.release_year.str.replace(')','')\nmovies.drop('genre',axis=1,inplace=True)", "/tmp/ipykernel_44083/1326198417.py:9: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.\n movies['release_year'] = movies.release_year.str.replace(')','')\n" ] ], [ [ "Let's visualize all the dataframes after all the preprocessing we did.", "_____no_output_____" ] ], [ [ "movies[['movie_title', 'release_year']]", "_____no_output_____" ], [ "ratings.head()", "_____no_output_____" ], [ "users.head()", "_____no_output_____" ], [ "ratings.shape", "_____no_output_____" ] ], [ [ "### Writing generally used getter functions in the implementation\nHere, we have written down a few getters so that we do not need to write down them again adn again and it also increases readability and reusability of the code.", "_____no_output_____" ] ], [ [ "#Function to get the rating given by a user to a movie.\ndef get_rating_(userid,movieid):\n return (ratings.loc[(ratings.user_id==userid) & (ratings.movie_id == movieid),'rating'].iloc[0])\n\n# Function to get the list of all movie ids the specified user has rated.\ndef get_movieids_(userid):\n return (ratings.loc[(ratings.user_id==userid),'movie_id'].tolist())\n\n# Function to get the movie titles against the movie id.\ndef get_movie_title_(movieid):\n return (movies.loc[(movies.movie_id == movieid),'movie_title'].iloc[0])", "_____no_output_____" ] ], [ [ "## Similarity Scores\n***\nIn this implementation the similarity between the two users have been calculated on the basis of the distance between the two users (i.e. Euclidean distances) and by calculating Pearson Correlation between the two users.\n\nWe have written two functions.", "_____no_output_____" ] ], [ [ "def distance_similarity_score(user1,user2):\n '''\n user1 & user2 : user ids of two users between which similarity score is to be calculated.\n '''\n both_watch_count = 0\n both_watch_list = []\n for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist():\n if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist():\n both_watch_count += 1\n both_watch_list.append(element)\n if both_watch_count == 0 :\n return 0\n distance = []\n for element in both_watch_list:\n rating1 = get_rating_(user1,element)\n rating2 = get_rating_(user2,element)\n distance.append(pow(rating1 - rating2, 2))\n total_distance = sum(distance)\n return 1/(1+sqrt(total_distance))", "_____no_output_____" ], [ "distance_similarity_score(1,310)", "_____no_output_____" ], [ "distance_similarity_score(1,310)", "_____no_output_____" ] ], [ [ "Calculating Similarity Scores based on the distances have an inherent problem. We do not have a threshold to decide how much more distance between two users is to be considered for calculating whether the users are close enough or far enough. On the other side, this problem is resolved by pearson correlation method as it always returns a value between -1 & 1 which clearly provides us with the boundaries for closeness as we prefer.", "_____no_output_____" ] ], [ [ "def pearson_correlation_score(user1,user2):\n '''\n user1 & user2 : user ids of two users between which similarity score is to be calculated.\n '''\n both_watch_count = []\n for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist():\n if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist():\n both_watch_count.append(element)\n if len(both_watch_count) == 0 :\n return 0\n ratings_1 = [get_rating_(user1,element) for element in both_watch_count]\n ratings_2 = [get_rating_(user2,element) for element in both_watch_count]\n rating_sum_1 = sum(ratings_1)\n rating_sum_2 = sum(ratings_2)\n rating_squared_sum_1 = sum([pow(element,2) for element in ratings_1])\n rating_squared_sum_2 = sum([pow(element,2) for element in ratings_2])\n product_sum_rating = sum([get_rating_(user1,element) * get_rating_(user2,element) for element in both_watch_count])\n \n numerator = product_sum_rating - ((rating_sum_1 * rating_sum_2) / len(both_watch_count))\n denominator = sqrt((rating_squared_sum_1 - pow(rating_sum_1,2) / len(both_watch_count)) * (rating_squared_sum_2 - pow(rating_sum_2,2) / len(both_watch_count)))\n if denominator == 0:\n return 0\n return numerator/denominator", "_____no_output_____" ], [ "pearson_correlation_score(1,310)", "_____no_output_____" ], [ "pearson_correlation_score(1,310)", "_____no_output_____" ] ], [ [ "### Most Similar Users\n\nThe objective is to find out **Most Similar Users** to the targeted user. Here we have two metrics to find the score i.e. distance and correlation. ", "_____no_output_____" ] ], [ [ "def most_similar_users_(user1,number_of_users,metric='pearson'):\n '''\n user1 : Targeted User\n number_of_users : number of most similar users you want to user1.\n metric : metric to be used to calculate inter-user similarity score. ('pearson' or else)\n '''\n # Getting distinct user ids.\n user_ids = ratings.user_id.unique().tolist()\n \n # Getting similarity score between targeted and every other suer in the list(or subset of the list).\n if(metric == 'pearson'):\n similarity_score = [(pearson_correlation_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1]\n else:\n similarity_score = [(distance_similarity_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1]\n \n # Sorting in descending order.\n similarity_score.sort()\n similarity_score.reverse()\n \n # Returning the top most 'number_of_users' similar users. \n return similarity_score[:number_of_users]", "_____no_output_____" ] ], [ [ "\n\n## Getting Movie Recommendations for Targeted User\n***\nThe concept is very simple. First, we need to iterate over only those movies not watched(or rated) by the targeted user and the subsetting items based on the users highly correlated with targeted user. Here, we have used a weighted similarity approach where we have taken product of rating and score into account to make sure that the highly similar users affect the recommendations more than those less similar. Then, we have sorted the list on the basis of score along with movie ids and returned the movie titles against those movie ids.\n\n", "_____no_output_____" ] ], [ [ "def get_recommendation_(userid):\n user_ids = ratings.user_id.unique().tolist()\n total = {}\n similariy_sum = {}\n \n # Iterating over subset of user ids.\n for user in user_ids[:100]:\n \n # not comparing the user to itself (obviously!)\n if user == userid:\n continue\n \n # Getting similarity score between the users.\n score = pearson_correlation_score(userid,user)\n \n # not considering users having zero or less similarity score.\n if score <= 0:\n continue\n \n # Getting weighted similarity score and sum of similarities between both the users.\n for movieid in get_movieids_(user):\n # Only considering not watched/rated movies\n if movieid not in get_movieids_(userid) or get_rating_(userid,movieid) == 0:\n total[movieid] = 0\n total[movieid] += get_rating_(user,movieid) * score\n similariy_sum[movieid] = 0\n similariy_sum[movieid] += score\n \n # Normalizing ratings\n ranking = [(tot/similariy_sum[movieid],movieid) for movieid,tot in total.items()]\n ranking.sort()\n ranking.reverse()\n \n # Getting movie titles against the movie ids.\n recommendations = [get_movie_title_(movieid) for score,movieid in ranking]\n return recommendations[:10]", "_____no_output_____" ] ], [ [ "**NOTE**: We have applied the above three techniques only to specific subset of the dataset as the dataset is too big and iterating over every row multiple times will increase runtime manifolds.", "_____no_output_____" ], [ "### Implementations\n***\nWe will call all the functions one by one and let's see whether they return the desird output (or they return any output at all!) ;)", "_____no_output_____" ] ], [ [ "print(most_similar_users_(23,5))", "[(0.936585811581694, 61), (0.7076731463403717, 41), (0.6123724356957956, 21), (0.5970863767331771, 25), (0.5477225575051661, 64)]\n" ] ], [ [ "I don't know if few of the people have noticed that the most similar users' logic can be stregthened more by considering other factors as well sucb as age etc. Here, we have created our logic on the basis of only one feature i.e. rating.", "_____no_output_____" ] ], [ [ "print(get_recommendation_(320))", "['Contender, The ', 'Requiem for a Dream ', 'Bamboozled ', 'Invisible Man, The ', 'Creature From the Black Lagoon, The ', 'Hellraiser ', 'Almost Famous ', 'Way of the Gun, The ', 'Shane ', 'Naked Gun 2 1/2: The Smell of Fear, The ']\n" ] ], [ [ "Next in line, we will discuss and implement matrix factorization approach.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe12adc241842607bc47e65918d3f820700d192
22,166
ipynb
Jupyter Notebook
knn/digit-recognision.ipynb
ayushnagar123/Data-Science
22fa3a2d2eee1adaf4be51663b61bcae587cfe21
[ "MIT" ]
1
2020-12-19T19:04:41.000Z
2020-12-19T19:04:41.000Z
knn/digit-recognision.ipynb
ayushnagar123/Data-Science
22fa3a2d2eee1adaf4be51663b61bcae587cfe21
[ "MIT" ]
null
null
null
knn/digit-recognision.ipynb
ayushnagar123/Data-Science
22fa3a2d2eee1adaf4be51663b61bcae587cfe21
[ "MIT" ]
null
null
null
42.626923
4,828
0.611703
[ [ [ "# hand written digit recognision on mnist dataset using knn", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# step 1:- Data Preperation", "_____no_output_____" ] ], [ [ "df = pd.read_csv('mnist_train.csv')\nprint(df.shape)", "(42000, 785)\n" ], [ "print(df.columns)", "Index(['label', 'pixel0', 'pixel1', 'pixel2', 'pixel3', 'pixel4', 'pixel5',\n 'pixel6', 'pixel7', 'pixel8',\n ...\n 'pixel774', 'pixel775', 'pixel776', 'pixel777', 'pixel778', 'pixel779',\n 'pixel780', 'pixel781', 'pixel782', 'pixel783'],\n dtype='object', length=785)\n" ], [ "df.head(n=5)", "_____no_output_____" ], [ "data =df.values\nprint(data.shape)\nprint(type(data))", "(42000, 785)\n<class 'numpy.ndarray'>\n" ], [ "x = data[:,1:]\ny = data[:,0]\nprint(x.shape,y.shape)", "(42000, 784) (42000,)\n" ], [ "split = int(0.8*x.shape[0])\nprint(split)\n\nx_train = x[:split,:]\ny_train = y[:split]\n\nx_test = x[split:,:]\ny_test = y[split:]\n\nprint(x_train.shape,y_train.shape)\nprint(x_test.shape,y_test.shape)", "33600\n(33600, 784) (33600,)\n(8400, 784) (8400,)\n" ], [ "def drawImg(sample):\n img = sample.reshape((28,28))\n plt.imshow(img,cmap='gray')\n plt.show()\ndrawImg(x_train[3])", "_____no_output_____" ] ], [ [ "# Step 2 :- K-NN", "_____no_output_____" ] ], [ [ "def dist(x1,x2):\n return np.sqrt(sum((x1-x2)**2))\n\ndef knn(x,y,queryPoint,k=5):\n vals = []\n m = x.shape[0]\n \n for i in range(m):\n d = dist(queryPoint,x[i])\n vals.append((d,y[i]))\n vals = sorted(vals)\n \n vals = vals[:k]\n vals = np.array(vals)\n# print(vals)\n \n new_vals = np.unique(vals[:,1],return_counts = True)\n# print(new_vals)\n index = new_vals[1].argmax()\n pred = new_vals[0][index]\n return pred", "_____no_output_____" ] ], [ [ "# Step 3 :- Make predictions", "_____no_output_____" ] ], [ [ "pred = knn(x_train,y_train,x_test[1])\nprint(int(pred))", "7\n" ], [ "drawImg(x_test[1])\nprint(y_test[1])", "_____no_output_____" ] ], [ [ "# write one method to compute accuracy of KNN over the test set", "_____no_output_____" ] ], [ [ "c=0\nfor i in range(len(x_test)):\n if(int(knn(x_train,y_train,x_test[i]))==y_test[i]):\n c+=1\naccuracy = c*100/len(x_test)\nprint(accuracy)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe12cd281bf7b2a33085152d6d8a48fe38c597e
119,926
ipynb
Jupyter Notebook
Examples/EISImportPlot/EISImportPlot.ipynb
Zahner-elektrik/Thales-Remote-Python
23bd86c1a662ecbb5faf02e635aa8ef9c6596243
[ "MIT" ]
6
2021-02-03T19:31:59.000Z
2022-01-25T04:16:16.000Z
Examples/EISImportPlot/EISImportPlot.ipynb
Zahner-elektrik/Thales-Remote-Python
23bd86c1a662ecbb5faf02e635aa8ef9c6596243
[ "MIT" ]
null
null
null
Examples/EISImportPlot/EISImportPlot.ipynb
Zahner-elektrik/Thales-Remote-Python
23bd86c1a662ecbb5faf02e635aa8ef9c6596243
[ "MIT" ]
3
2020-11-08T14:25:20.000Z
2021-11-16T09:00:05.000Z
336.870787
69,606
0.933184
[ [ [ "# ism Import and Plotting\n\nThis example shows how to measure an impedance spectrum and then plot it in Bode and Nyquist using the Python library [matplotlib](https://matplotlib.org/).", "_____no_output_____" ] ], [ [ "import sys\nfrom thales_remote.connection import ThalesRemoteConnection\nfrom thales_remote.script_wrapper import PotentiostatMode,ThalesRemoteScriptWrapper\n\nfrom thales_file_import.ism_import import IsmImport\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import EngFormatter\n\nfrom jupyter_utils import executionInNotebook, notebookCodeToPython", "_____no_output_____" ] ], [ [ "\n# Connect Python to the already launched Thales-Software", "_____no_output_____" ] ], [ [ "if __name__ == \"__main__\":\n zenniumConnection = ThalesRemoteConnection()\n connectionSuccessful = zenniumConnection.connectToTerm(\"localhost\", \"ScriptRemote\")\n if connectionSuccessful:\n print(\"connection successfull\")\n else:\n print(\"connection not possible\")\n sys.exit()\n \n zahnerZennium = ThalesRemoteScriptWrapper(zenniumConnection)\n \n zahnerZennium.forceThalesIntoRemoteScript()", "connection successfull\n" ] ], [ [ "# Setting the parameters for the measurement\n\nAfter the connection with Thales, the naming of the files of the measurement results is set.\n\nMeasure EIS spectra with a sequential number in the file name that has been specified.\nStarting with number 1.", "_____no_output_____" ] ], [ [ " zahnerZennium.setEISNaming(\"counter\")\n zahnerZennium.setEISCounter(1)\n zahnerZennium.setEISOutputPath(r\"C:\\THALES\\temp\\test1\")\n zahnerZennium.setEISOutputFileName(\"spectra\")", "_____no_output_____" ] ], [ [ "Setting the parameters for the spectra.\nAlternatively a rule file can be used as a template.", "_____no_output_____" ] ], [ [ " zahnerZennium.setPotentiostatMode(PotentiostatMode.POTMODE_POTENTIOSTATIC)\n zahnerZennium.setAmplitude(10e-3)\n zahnerZennium.setPotential(0)\n zahnerZennium.setLowerFrequencyLimit(0.01)\n zahnerZennium.setStartFrequency(1000)\n zahnerZennium.setUpperFrequencyLimit(200000)\n zahnerZennium.setLowerNumberOfPeriods(3)\n zahnerZennium.setLowerStepsPerDecade(5)\n zahnerZennium.setUpperNumberOfPeriods(20)\n zahnerZennium.setUpperStepsPerDecade(10)\n zahnerZennium.setScanDirection(\"startToMax\")\n zahnerZennium.setScanStrategy(\"single\")", "_____no_output_____" ] ], [ [ "After setting the parameters, the measurement is started. \n\n<div class=\"alert alert-block alert-info\">\n<b>Note:</b> If the potentiostat is set to potentiostatic before the impedance measurement and is switched off, the measurement is performed at the open circuit voltage/potential.\n</div>\n\nAfter the measurement the potentiostat is switched off.", "_____no_output_____" ] ], [ [ " zahnerZennium.enablePotentiostat()\n zahnerZennium.measureEIS()\n zahnerZennium.disablePotentiostat()\n zenniumConnection.disconnectFromTerm()", "_____no_output_____" ] ], [ [ "# Importing the ism file\n\nImport the spectrum from the previous measurement. This was saved under the set path and name with the number expanded. \nThe measurement starts at 1 therefore the following path results: \"C:\\THALES\\temp\\test1\\spectra_0001.ism\".", "_____no_output_____" ] ], [ [ " ismFile = IsmImport(r\"C:\\THALES\\temp\\test1\\spectra_0001.ism\")\n \n impedanceFrequencies = ismFile.getFrequencyArray()\n \n impedanceAbsolute = ismFile.getImpedanceArray()\n impedancePhase = ismFile.getPhaseArray()\n \n impedanceComplex = ismFile.getComplexImpedanceArray()", "_____no_output_____" ] ], [ [ "The Python datetime object of the measurement date is output to the console next.", "_____no_output_____" ] ], [ [ " print(\"Measurement end time: \" + str(ismFile.getMeasurementEndDateTime()))", "Measurement end time: 2021-10-14 13:21:30.032500\n" ] ], [ [ "# Displaying the measurement results\n\nThe spectra are presented in the Bode and Nyquist representation. For this test, the Zahner test box was measured in the lin position.\n\n## Nyquist Plot\n\nThe matplotlib diagram is configured to match the Nyquist representation. For this, the diagram aspect is set equal and the axes are labeled in engineering units. The axis labeling is realized with [LaTeX](https://www.latex-project.org/) for subscript text.\n\nThe possible settings of the graph can be found in the detailed documentation and tutorials of [matplotlib](https://matplotlib.org/).", "_____no_output_____" ] ], [ [ " figNyquist, (nyquistAxis) = plt.subplots(1, 1)\n figNyquist.suptitle(\"Nyquist\")\n \n nyquistAxis.plot(np.real(impedanceComplex), -np.imag(impedanceComplex), marker=\"x\", markersize=5)\n nyquistAxis.grid(which=\"both\")\n nyquistAxis.set_aspect(\"equal\")\n nyquistAxis.xaxis.set_major_formatter(EngFormatter(unit=\"$\\Omega$\"))\n nyquistAxis.yaxis.set_major_formatter(EngFormatter(unit=\"$\\Omega$\"))\n nyquistAxis.set_xlabel(r\"$Z_{\\rm re}$\")\n nyquistAxis.set_ylabel(r\"$-Z_{\\rm im}$\")\n figNyquist.set_size_inches(18, 18)\n plt.show()\n figNyquist.savefig(\"nyquist.svg\")", "_____no_output_____" ] ], [ [ "## Bode Plot\n\nThe matplotlib representation was also adapted for the Bode plot. A figure with two plots was created for the separate display of phase and impedance which are plotted over the same x-axis.", "_____no_output_____" ] ], [ [ " figBode, (impedanceAxis, phaseAxis) = plt.subplots(2, 1, sharex=True)\n figBode.suptitle(\"Bode\")\n \n impedanceAxis.loglog(impedanceFrequencies, impedanceAbsolute, marker=\"+\", markersize=5)\n impedanceAxis.xaxis.set_major_formatter(EngFormatter(unit=\"Hz\"))\n impedanceAxis.yaxis.set_major_formatter(EngFormatter(unit=\"$\\Omega$\"))\n impedanceAxis.set_xlabel(r\"$f$\")\n impedanceAxis.set_ylabel(r\"$|Z|$\")\n impedanceAxis.grid(which=\"both\")\n \n phaseAxis.semilogx(impedanceFrequencies, np.abs(impedancePhase * (360 / (2 * np.pi))), marker=\"+\", markersize=5)\n phaseAxis.xaxis.set_major_formatter(EngFormatter(unit=\"Hz\"))\n phaseAxis.yaxis.set_major_formatter(EngFormatter(unit=\"$°$\", sep=\"\"))\n phaseAxis.set_xlabel(r\"$f$\")\n phaseAxis.set_ylabel(r\"$|Phase|$\")\n phaseAxis.grid(which=\"both\")\n phaseAxis.set_ylim([0, 90])\n figBode.set_size_inches(18, 12)\n plt.show()\n figBode.savefig(\"bode.svg\")", "_____no_output_____" ] ], [ [ "# Deployment of the source code\n\n**The following instruction is not needed by the user.**\n\nIt automatically extracts the pure python code from the jupyter notebook to provide it to the user. Thus the user does not need jupyter itself and does not have to copy the code manually.\n\nThe source code is saved in a .py file with the same name as the notebook.", "_____no_output_____" ] ], [ [ " if executionInNotebook() == True:\n notebookCodeToPython(\"EISImportPlot.ipynb\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe13597ee21a93f3ffebfb0847151c4945b3ad5
4,824
ipynb
Jupyter Notebook
2. Omega and Xi, Constraints.ipynb
dhruvspatel/Robot-Localization-and-Landmark-Detection-Using-Graph-SLAM
b4f199cd237b45bb45a410d1032beeef88a7da77
[ "MIT" ]
2
2020-09-28T21:08:00.000Z
2022-02-15T09:22:31.000Z
2. Omega and Xi, Constraints.ipynb
dhruvspatel/Robot-Localization-and-Landmark-Detection-Using-Graph-SLAM
b4f199cd237b45bb45a410d1032beeef88a7da77
[ "MIT" ]
null
null
null
2. Omega and Xi, Constraints.ipynb
dhruvspatel/Robot-Localization-and-Landmark-Detection-Using-Graph-SLAM
b4f199cd237b45bb45a410d1032beeef88a7da77
[ "MIT" ]
null
null
null
41.586207
607
0.615672
[ [ [ "#### Omega and Xi\n\nTo implement Graph SLAM, a matrix and a vector (omega and xi, respectively) are introduced. The matrix is square and labelled with all the robot poses (xi) and all the landmarks (Li). Every time you make an observation, for example, as you move between two poses by some distance `dx` and can relate those two positions, you can represent this as a numerical relationship in these matrices.\n\nIt's easiest to see how these work in an example. Below you can see a matrix representation of omega and a vector representation of xi.\n\n <img src='images/omega_xi.png' width=\"20%\" height=\"20%\" />\nNext, let's look at a simple example that relates 3 poses to one another. \n* When you start out in the world most of these values are zeros or contain only values from the initial robot position\n* In this example, you have been given constraints, which relate these poses to one another\n* Constraints translate into matrix values\n\n<img src='images/omega_xi_constraints.png' width=\"70%\" height=\"70%\" />\n\nIf you have ever solved linear systems of equations before, this may look familiar, and if not, let's keep going!\n\n### Solving for x\n\nTo \"solve\" for all these x values, we can use linear algebra; all the values of x are in the vector `mu` which can be calculated as a product of the inverse of omega times xi.\n\n<img src='images/solution.png' width=\"30%\" height=\"30%\" />\n\n---\n**You can confirm this result for yourself by executing the math in the cell below.**\n", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# define omega and xi as in the example\nomega = np.array([[1,0,0],\n [-1,1,0],\n [0,-1,1]])\n\nxi = np.array([[-3],\n [5],\n [3]])\n\n# calculate the inverse of omega\nomega_inv = np.linalg.inv(np.matrix(omega))\n\n# calculate the solution, mu\nmu = omega_inv*xi\n\n# print out the values of mu (x0, x1, x2)\nprint(mu)", "[[-3.]\n [ 2.]\n [ 5.]]\n" ] ], [ [ "## Motion Constraints and Landmarks\n\nIn the last example, the constraint equations, relating one pose to another were given to you. In this next example, let's look at how motion (and similarly, sensor measurements) can be used to create constraints and fill up the constraint matrices, omega and xi. Let's start with empty/zero matrices.\n\n<img src='images/initial_constraints.png' width=\"35%\" height=\"35%\" />\n\nThis example also includes relationships between poses and landmarks. Say we move from x0 to x1 with a displacement `dx` of 5. Then we have created a motion constraint that relates x0 to x1, and we can start to fill up these matrices.\n\n<img src='images/motion_constraint.png' width=\"50%\" height=\"50%\" />\n\nIn fact, the one constraint equation can be written in two ways. So, the motion constraint that relates x0 and x1 by the motion of 5 has affected the matrix, adding values for *all* elements that correspond to x0 and x1.\n\n---\n\n### 2D case\n\nIn these examples, we've been showing you change in only one dimension, the x-dimension. In the project, it will be up to you to represent x and y positional values in omega and xi. One solution could be to create an omega and xi that are 2x larger that the number of robot poses (that will be generated over a series of time steps) and the number of landmarks, so that they can hold both x and y values for poses and landmark locations. I might suggest drawing out a rough solution to graph slam as you read the instructions in the next notebook; that always helps me organize my thoughts. Good luck!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe13627259ed9905f6a6acf2a2f7057882d3b19
109,513
ipynb
Jupyter Notebook
Week1-Introduction-to-Python-_-NumPy/Intro_to_Python_plus_NumPy.ipynb
isabella232/Bitcamp-DataSci
78b921b60b66d8cfb88ce54dcfdef37664004552
[ "MIT" ]
1
2020-10-02T19:18:36.000Z
2020-10-02T19:18:36.000Z
Week1-Introduction-to-Python-_-NumPy/Intro_to_Python_plus_NumPy.ipynb
kylebegovich/Bitcamp-DataSci
0bf52ca1d250a915c3e7e4ba2eb6bc1edfb2766b
[ "MIT" ]
2
2020-09-10T05:45:50.000Z
2020-09-25T07:23:26.000Z
Week1-Introduction-to-Python-_-NumPy/Intro_to_Python_plus_NumPy.ipynb
kylebegovich/Bitcamp-DataSci
0bf52ca1d250a915c3e7e4ba2eb6bc1edfb2766b
[ "MIT" ]
3
2020-09-03T03:43:47.000Z
2020-12-27T02:33:49.000Z
22.598638
740
0.528741
[ [ [ "<a href=\"https://colab.research.google.com/github/bitprj/Bitcamp-DataSci/blob/master/Week1-Introduction-to-Python-_-NumPy/Intro_to_Python_plus_NumPy.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "<img src=\"https://github.com/bitprj/Bitcamp-DataSci/blob/master/Week1-Introduction-to-Python-_-NumPy/assets/icons/bitproject.png?raw=1\" width=\"200\" align=\"left\"> \n<img src=\"https://github.com/bitprj/Bitcamp-DataSci/blob/master/Week1-Introduction-to-Python-_-NumPy/assets/icons/data-science.jpg?raw=1\" width=\"300\" align=\"right\">", "_____no_output_____" ], [ "# Introduction to Python", "_____no_output_____" ], [ "### Table of Contents\n\n- Why, Where, and How we use Python\n- What we will be learning today\n - Goals\n- Numbers\n - Types of Numbers\n - Basic Arithmetic\n - Arithmetic Continued\n- Variable Assignment\n- Strings\n - Creating Strings\n - Printing Strings\n - String Basics\n - String Properties\n - Basic Built-In String Methods\n - Print Formatting\n - **1.0 Now Try This**\n- Booleans\n- Lists\n - Creating Lists\n - Basic List Methods\n - Nesting Lists\n - List Comprehensions\n - **2.0 Now Try This**\n- Tuples\n - Constructing Tuples\n - Basic Tuple Methods\n - Immutability\n - When To Use Tuples\n - **3.0 Now Try This**\n- Dictionaries\n - Constructing a Dictionary\n - Nesting With Dictionaries\n - Dictionary Methods\n - **4.0 Now Try This**\n- Comparison Operators\n- Functions\n - Intro to Functions\n - `def` Statements\n - Examples\n - Using `return`\n - **5.0 Now Try This**\n- Modules and Packages\n - Overview\n- NumPy\n - Creating Arrays\n - Indexing\n - Slicing\n - **6.0 Now Try This**\n - Data Types\n - **7.0 Now Try This**\n - Copy vs. View\n - **8.0 Now Try This**\n - Shape\n - **9.0 Now Try This**\n - Iterating Through Arrays\n - Joining Arrays\n - Splitting Arrays\n - Searching Arrays\n - Sorting Arrays\n - Filtering Arrays\n - **10.0 Now Try This**\n- Resources\n", "_____no_output_____" ], [ "## Why, Where, and How we use Python\n\nPython is a very popular scripting language that you can use to create applications and programs of all sizes and complexity. It is very easy to learn and has very little syntax, making it very efficient to code with. Python is also the language of choice for many when performing comprehensive data analysis. ", "_____no_output_____" ], [ "## What we will be learning today\n\n### Goals\n- Understanding key Python data types, operators and data structures\n- Understanding functions\n- Understanding modules\n- Understanding errors and exceptions", "_____no_output_____" ], [ "First data type we'll cover in detail is Numbers!", "_____no_output_____" ], [ "## Numbers", "_____no_output_____" ], [ "### Types of numbers\n\nPython has various \"types\" of numbers. We'll strictly cover integers and floating point numbers for now.\n\nIntegers are just whole numbers, positive or negative. (2,4,-21,etc.)\n\nFloating point numbers in Python have a decimal point in them, or use an exponential (e). For example 3.14 and 2.17 are *floats*. 5E7 (5 times 10 to the power of 7) is also a float. This is scientific notation and something you've probably seen in math classes.\n\nLet's start working through numbers and arithmetic:", "_____no_output_____" ], [ "### Basic Arithmetic", "_____no_output_____" ] ], [ [ "# Addition\n4+5", "_____no_output_____" ], [ "# Subtraction\n5-10", "_____no_output_____" ], [ "# Multiplication\n4*8", "_____no_output_____" ], [ "# Division\n25/5", "_____no_output_____" ], [ "# Floor Division\n12//4", "_____no_output_____" ] ], [ [ "What happened here?\n\nThe reason we get this result is because we are using \"*floor*\" division. The // operator (two forward slashes) removes any decimals and doesn't round. This always produces an integer answer.", "_____no_output_____" ], [ "**So what if we just want the remainder of division?**", "_____no_output_____" ] ], [ [ "# Modulo\n9 % 4", "_____no_output_____" ] ], [ [ "4 goes into 9 twice, with a remainder of 1. The % operator returns the remainder after division.", "_____no_output_____" ], [ "### Arithmetic continued", "_____no_output_____" ] ], [ [ "# Powers\n4**2", "_____no_output_____" ], [ "# A way to do roots\n144**0.5", "_____no_output_____" ], [ "# Order of Operations\n4 + 20 * 52 + 5", "_____no_output_____" ], [ "# Can use parentheses to specify orders\n(21+5) * (4+89)", "_____no_output_____" ] ], [ [ "## Variable Assignments\n\nWe can do a lot more with Python than just using it as a calculator. We can store any numbers we create in **variables**.\n\nWe use a single equals sign to assign labels or values to variables. Let's see a few examples of how we can do this.", "_____no_output_____" ] ], [ [ "# Let's create a variable called \"a\" and assign to it the number 10\na = 10\n\na", "_____no_output_____" ] ], [ [ "Now if I call *a* in my Python script, Python will treat it as the integer 10.", "_____no_output_____" ] ], [ [ "# Adding the objects\na+a", "_____no_output_____" ] ], [ [ "What happens on reassignment? Will Python let us write it over?", "_____no_output_____" ] ], [ [ "# Reassignment\na = 20\n\n# Check\na", "_____no_output_____" ] ], [ [ "Yes! Python allows you to write over assigned variable names. We can also use the variables themselves when doing the reassignment. Here is an example of what I mean:", "_____no_output_____" ] ], [ [ "# Use A to redefine A\na = a+a\n\n# check\na", "_____no_output_____" ] ], [ [ "The names you use when creating these labels need to follow a few rules:\n\n 1. Names can not start with a number.\n 2. There can be no spaces in the name, use _ instead.\n 3. Can't use any of these symbols :'\",<>/?|\\()!@#$%^&*~-+\n 4. Using lowercase names are best practice.\n 5. Can't words that have special meaning in Python like \"list\" and \"str\", we'll see why later\n\n\nUsing variable names can be a very useful way to keep track of different variables in Python. For example:", "_____no_output_____" ] ], [ [ "# Use object names to keep better track of what's going on in your code!\nincome = 1000\n\ntax_rate = 0.2\n\ntaxes = income*tax_rate", "_____no_output_____" ], [ "# Show the result!\ntaxes", "_____no_output_____" ] ], [ [ "So what have we learned? We learned some of the basics of numbers in Python. We also learned how to do arithmetic and use Python as a basic calculator. We then wrapped it up with learning about Variable Assignment in Python.\n\nUp next we'll learn about Strings!", "_____no_output_____" ], [ "## Strings", "_____no_output_____" ], [ "Strings are used in Python to record text information, such as names. Strings in Python are not treated like their own objects, but rather like a *sequence*, a consecutive series of characters. For example, Python understands the string \"hello' to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).\n", "_____no_output_____" ], [ "### Creating Strings\nTo create a string in Python you need to use either single quotes or double quotes. For example:", "_____no_output_____" ] ], [ [ "# A word\n'hi'", "_____no_output_____" ], [ "# A phrase\n'A string can even be a sentence like this.'", "_____no_output_____" ], [ "# Using double quotes\n\"The quote type doesn't really matter.\"", "_____no_output_____" ], [ "# Be wary of contractions and apostrophes!\n'I'm using single quotes, but this will create an error!'", "_____no_output_____" ] ], [ [ "The reason for the error above is because the single quote in <code>I'm</code> stopped the string. You can use combinations of double and single quotes to get the complete statement.", "_____no_output_____" ] ], [ [ "\"This shouldn't cause an error now.\"", "_____no_output_____" ] ], [ [ "Now let's learn about printing strings!", "_____no_output_____" ], [ "### Printing Strings\n\nJupyter Notebooks have many neat behaviors that aren't available in base python. One of those is the ability to print strings by just typing it into a cell. The universal way to display strings however, is to use a **print()** function.", "_____no_output_____" ] ], [ [ "# In Jupyter, this is all we need\n'Hello World'", "_____no_output_____" ], [ "# This is the same as:\nprint('Hello World')", "_____no_output_____" ], [ "# Without the print function, we can't print multiple times in one block of code:\n'Hello World'\n'Second string'", "_____no_output_____" ] ], [ [ "A print statement can look like the following.", "_____no_output_____" ] ], [ [ "print('Hello World')\nprint('Second string')\nprint('\\n prints a new line')\nprint('\\n')\nprint('Just to prove it to you.')", "Hello World\nSecond string\n\n prints a new line\n\n\nJust to prove it to you.\n" ] ], [ [ "Now let's move on to understanding how we can manipulate strings in our programs.", "_____no_output_____" ], [ "### String Basics", "_____no_output_____" ], [ "Oftentimes, we would like to know how many characters are in a string. We can do this very easily with the **len()** function (short for 'length').", "_____no_output_____" ] ], [ [ "len('Hello World')", "_____no_output_____" ] ], [ [ "Python's built-in len() function counts all of the characters in the string, including spaces and punctuation.", "_____no_output_____" ], [ "Naturally, we can assign strings to variables.", "_____no_output_____" ] ], [ [ "# Assign 'Hello World' to mystring variable\nmystring = 'Hello World'", "_____no_output_____" ], [ "# Did it work?\nmystring", "_____no_output_____" ], [ "# Print it to make sure\nprint(mystring) ", "Hello World\n" ] ], [ [ "As stated before, Python treats strings as a sequence of characters. That means we can interact with each letter in a string and manipulate it. The way we access these letters is called **indexing**. Each letter has an index, which corresponds to their position in the string. In python, indices start at 0. For instance, in the string 'Hello World', 'H' has an index of 0, 'e' has an index of 1, the 'W' has an index of 6 (because spaces count as characters), and 'd' has an index of 10. The syntax for indexing is shown below.", "_____no_output_____" ] ], [ [ "# Extract first character in a string.\nmystring[0]", "_____no_output_____" ], [ "mystring[1]", "_____no_output_____" ], [ "mystring[2]", "_____no_output_____" ] ], [ [ "We can use a <code>:</code> to perform *slicing* which grabs everything up to a designated index. For example:", "_____no_output_____" ] ], [ [ "# Grab all letters past the first letter all the way to the end of the string\nmystring[:]", "_____no_output_____" ], [ "# This does not change the original string in any way\nmystring", "_____no_output_____" ], [ "# Grab everything UP TO the 5th index\nmystring[:5]", "_____no_output_____" ] ], [ [ "Note what happened above. We told Python to grab everything from 0 up to 5. It doesn't include the character in the 5th index. You'll notice this a lot in Python, where statements are usually in the context of \"up to, but not including\".", "_____no_output_____" ] ], [ [ "# The whole string\nmystring[:]", "_____no_output_____" ], [ "# The 'default' values, if you leave the sides of the colon blank, are 0 and the length of the string\nend = len(mystring)\n\n# See that is matches above\nmystring[0:end]", "_____no_output_____" ] ], [ [ "But we don't have to go forwards. Negative indexing allows us to start from the *end* of the string and work backwards.", "_____no_output_____" ] ], [ [ "# The LAST letter (one index 'behind' 0, so it loops back around)\nmystring[-1]", "_____no_output_____" ], [ "# Grab everything but the last letter\nmystring[:-1]", "_____no_output_____" ] ], [ [ "We can also use indexing and slicing to grab characters by a specified step size (1 is the default). See the following examples.", "_____no_output_____" ] ], [ [ "# Grab everything (default), go in steps size of 1\nmystring[::1]", "_____no_output_____" ], [ "# Grab everything, but go in step sizes of 2 (every other letter)\nmystring[0::2]", "_____no_output_____" ], [ "# A handy way to reverse a string!\nmystring[::-1]", "_____no_output_____" ] ], [ [ "Strings have certain properties to them that affect the way we can, and cannot, interact with them.", "_____no_output_____" ], [ "### String Properties\nIt's important to note that strings are *immutable*. This means that once a string is created, the elements within it can not be changed or replaced. For example:", "_____no_output_____" ] ], [ [ "mystring", "_____no_output_____" ], [ "# Let's try to change the first letter\nmystring[0] = 'a'", "_____no_output_____" ] ], [ [ "The error tells it us to straight. Strings do not support assignment the same way other data types do.\n\nHowever, we *can* **concatenate** strings.", "_____no_output_____" ] ], [ [ "mystring", "_____no_output_____" ], [ "# Combine strings through concatenation\nmystring + \". It's me.\"", "_____no_output_____" ], [ "# We can reassign mystring to a new value, however\nmystring = mystring + \". It's me.\"", "_____no_output_____" ], [ "mystring", "_____no_output_____" ] ], [ [ "One neat trick we can do with strings is use multiplication whenever we want to repeat characters a certain number of times.", "_____no_output_____" ] ], [ [ "letter = 'a'", "_____no_output_____" ], [ "letter*20", "_____no_output_____" ] ], [ [ "We already saw how to use len(). This is an example of a built-in string method, but there are quite a few more which we will cover next.", "_____no_output_____" ], [ "### Basic Built-in String methods\n\nObjects in Python usually have built-in methods. These methods are functions inside the object that can perform actions or commands on the object itself.\n\nWe call methods with a period and then the method name. Methods are in the form:\n\nobject.method(parameters)\n\nParameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. We will be going into more depth with these later.\n\nHere are some examples of built-in methods in strings:", "_____no_output_____" ] ], [ [ "mystring", "_____no_output_____" ], [ "# Make all letters in a string uppercase\nmystring.upper()", "_____no_output_____" ], [ "# Make all letters in a string lowercase\nmystring.lower()", "_____no_output_____" ], [ "# Split strings with a specified character as the separator. Spaces are the default.\nmystring.split()", "_____no_output_____" ], [ "# Split by a specific character (doesn't include the character in the resulting string)\nmystring.split('W')", "_____no_output_____" ] ], [ [ "### 1.0 Now Try This", "_____no_output_____" ], [ "Given the string 'Amsterdam' give an index command that returns 'd'. Enter your code in the cell below:", "_____no_output_____" ] ], [ [ "s = 'Amsterdam'\n# Print out 'd' using indexing\nanswer1 = # INSERT CODE HERE\nprint(answer1)\n", "_____no_output_____" ] ], [ [ "Reverse the string 'Amsterdam' using slicing:", "_____no_output_____" ] ], [ [ "s ='Amsterdam'\n# Reverse the string using slicing\nanswer2 = # INSERT CODE HERE\nprint(answer2)", "_____no_output_____" ] ], [ [ "Given the string Amsterdam, extract the letter 'm' using negative indexing.", "_____no_output_____" ] ], [ [ "s ='Amsterdam'\n\n# Print out the 'm'\nanswer3 = # INSERT CODE HERE\nprint(answer3)", "_____no_output_____" ] ], [ [ "## Booleans\n\nPython comes with *booleans* (values that are essentially binary: True or False, 1 or 0). It also has a placeholder object called None. Let's walk through a few quick examples of Booleans.", "_____no_output_____" ] ], [ [ "# Set object to be a boolean\na = True", "_____no_output_____" ], [ "#Show\na", "_____no_output_____" ] ], [ [ "We can also use comparison operators to create booleans. We'll cover comparison operators a little later.", "_____no_output_____" ] ], [ [ "# Output is boolean\n1 > 2", "_____no_output_____" ] ], [ [ "We can use None as a placeholder for an object that we don't want to reassign yet:", "_____no_output_____" ] ], [ [ "# None placeholder\nb = None", "_____no_output_____" ], [ "# Show\nprint(b)", "_____no_output_____" ] ], [ [ "That's all to booleans! Next we start covering data structures. First up, lists.", "_____no_output_____" ], [ "## Lists\n\nEarlier when discussing strings we introduced the concept of a *sequence*. Lists is the most generalized version of sequences in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!\n\nLists are constructed with brackets [] and commas separating every element in the list.\n\nLet's start with seeing how we can build a list.", "_____no_output_____" ], [ "### Creating Lists", "_____no_output_____" ] ], [ [ "# Assign a list to an variable named my_list\nmy_list = [1,2,3]", "_____no_output_____" ] ], [ [ "We just created a list of integers, but lists can actually hold elements of multiple data types. For example:", "_____no_output_____" ] ], [ [ "my_list = ['A string',23,100.232,'o']", "_____no_output_____" ] ], [ [ "Just like strings, the len() function will tell you how many items are in the sequence of the list.", "_____no_output_____" ] ], [ [ "len(my_list)", "_____no_output_____" ], [ "my_list = ['one','two','three',4,5]", "_____no_output_____" ], [ "# Grab element at index 0\nmy_list[0]", "_____no_output_____" ], [ "# Grab index 1 and everything past it\nmy_list[1:]", "_____no_output_____" ], [ "# Grab everything UP TO index 3\nmy_list[:3]", "_____no_output_____" ] ], [ [ "We can also use + to concatenate lists, just like we did for strings.", "_____no_output_____" ] ], [ [ "my_list + ['new item']", "_____no_output_____" ] ], [ [ "Note: This doesn't actually change the original list!", "_____no_output_____" ] ], [ [ "my_list", "_____no_output_____" ] ], [ [ "You would have to reassign the list to make the change permanent.", "_____no_output_____" ] ], [ [ "# Reassign\nmy_list = my_list + ['add new item permanently']", "_____no_output_____" ], [ "my_list", "_____no_output_____" ] ], [ [ "We can also use the * for a duplication method similar to strings:", "_____no_output_____" ] ], [ [ "# Make the list double\nmy_list * 2", "_____no_output_____" ], [ "# Again doubling not permanent\nmy_list", "_____no_output_____" ] ], [ [ "Use the **append** method to permanently add an item to the end of a list:", "_____no_output_____" ] ], [ [ "# Append\nlist1.append('append me!')", "_____no_output_____" ], [ "# Show\nlist1", "_____no_output_____" ] ], [ [ "### List Comprehensions\nPython has an advanced feature called list comprehensions. They allow for quick construction of lists. To fully understand list comprehensions we need to understand for loops. So don't worry if you don't completely understand this section, and feel free to just skip it since we will return to this topic later.\n\nBut in case you want to know now, here are a few examples!", "_____no_output_____" ] ], [ [ "# Build a list comprehension by deconstructing a for loop within a []\nfirst_col = [row[0] for row in matrix]", "_____no_output_____" ], [ "first_col", "_____no_output_____" ] ], [ [ "We used a list comprehension here to grab the first element of every row in the matrix object. We will cover this in much more detail later on!", "_____no_output_____" ], [ "### 2.0 Now Try This", "_____no_output_____" ], [ "Build this list [0,0,0] using any of the shown ways.", "_____no_output_____" ] ], [ [ "# Build the list\nanswer1 = #INSERT CODE HERE\nprint(answer1)", "_____no_output_____" ] ], [ [ "## Tuples\n\nIn Python tuples are very similar to lists, however, unlike lists they are *immutable* meaning they can not be changed. You would use tuples to present things that shouldn't be changed, such as days of the week, or dates on a calendar. \n\nYou'll have an intuition of how to use tuples based on what you've learned about lists. We can treat them very similarly with the major distinction being that tuples are immutable.", "_____no_output_____" ], [ "### Constructing Tuples\n\nThe construction of a tuples use () with elements separated by commas. For example:", "_____no_output_____" ] ], [ [ "# Create a tuple\nt = (1,2,3)", "_____no_output_____" ], [ "# Check len just like a list\nlen(t)", "_____no_output_____" ], [ "# Can also mix object types\nt = ('one',2)\n\n# Show\nt", "_____no_output_____" ], [ "# Use indexing just like we did in lists\nt[0]", "_____no_output_____" ], [ "# Slicing just like a list\nt[-1]", "_____no_output_____" ] ], [ [ "### Basic Tuple Methods\n\nTuples have built-in methods, but not as many as lists do. Let's look at two of them:", "_____no_output_____" ] ], [ [ "# Use .index to enter a value and return the index\nt.index('one')", "_____no_output_____" ], [ "# Use .count to count the number of times a value appears\nt.count('one')", "_____no_output_____" ] ], [ [ "### Immutability\n\nIt can't be stressed enough that tuples are immutable. To drive that point home:", "_____no_output_____" ] ], [ [ "t[0]= 'change'", "_____no_output_____" ] ], [ [ "Because of this immutability, tuples can't grow. Once a tuple is made we can not add to it.", "_____no_output_____" ] ], [ [ "t.append('nope')", "_____no_output_____" ] ], [ [ "### When to use Tuples\n\nYou may be wondering, \"Why bother using tuples when they have fewer available methods?\" To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.\n\nYou should now be able to create and use tuples in your programming as well as have an understanding of their immutability.", "_____no_output_____" ], [ "### 3.0 Now Try This", "_____no_output_____" ], [ "Create a tuple.", "_____no_output_____" ] ], [ [ "answer1 = #INSERT CODE HERE\nprint(type(answer1))", "_____no_output_____" ] ], [ [ "## Dictionaries\n\nWe've been learning about *sequences* in Python but now we're going to switch gears and learn about *mappings* in Python. If you're familiar with other languages you can think of dictionaries as hash tables. \n\nSo what are mappings? Mappings are a collection of objects that are stored by a *key*, unlike a sequence that stored objects by their relative position. This is an important distinction, since mappings won't retain order as is no *order* to keys..\n\nA Python dictionary consists of a key and then an associated value. That value can be almost any Python object.", "_____no_output_____" ], [ "### Constructing a Dictionary\nLet's see how we can build dictionaries and better understand how they work.", "_____no_output_____" ] ], [ [ "# Make a dictionary with {} and : to signify a key and a value\nmy_dict = {'key1':'value1','key2':'value2'}", "_____no_output_____" ], [ "# Call values by their key\nmy_dict['key2']", "_____no_output_____" ] ], [ [ "Its important to note that dictionaries are very flexible in the data types they can hold. For example:", "_____no_output_____" ] ], [ [ "my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}", "_____no_output_____" ], [ "# Let's call items from the dictionary\nmy_dict['key3']", "_____no_output_____" ], [ "# Can call an index on that value\nmy_dict['key3'][0]", "_____no_output_____" ], [ "# Can then even call methods on that value\nmy_dict['key3'][0].upper()", "_____no_output_____" ] ], [ [ "We can affect the values of a key as well. For instance:", "_____no_output_____" ] ], [ [ "my_dict['key1']", "_____no_output_____" ], [ "# Subtract 123 from the value\nmy_dict['key1'] = my_dict['key1'] - 123", "_____no_output_____" ], [ "#Check\nmy_dict['key1']", "_____no_output_____" ] ], [ [ "A quick note, Python has a built-in method of doing a self subtraction or addition (or multiplication or division). We could have also used += or -= for the above statement. For example:", "_____no_output_____" ] ], [ [ "# Set the object equal to itself minus 123 \nmy_dict['key1'] -= 123\nmy_dict['key1']", "_____no_output_____" ] ], [ [ "We can also create keys by assignment. For instance if we started off with an empty dictionary, we could continually add to it:", "_____no_output_____" ] ], [ [ "# Create a new dictionary\nd = {}", "_____no_output_____" ], [ "# Create a new key through assignment\nd['animal'] = 'Dog'", "_____no_output_____" ], [ "# Can do this with any object\nd['answer'] = 42", "_____no_output_____" ], [ "#Show\nd", "_____no_output_____" ] ], [ [ "### Nesting with Dictionaries\n\nHopefully you're starting to see how powerful Python is with its flexibility of nesting objects and calling methods on them. Let's see a dictionary nested inside a dictionary:", "_____no_output_____" ] ], [ [ "# Dictionary nested inside a dictionary nested inside a dictionary\nd = {'key1':{'nestkey':{'subnestkey':'value'}}}", "_____no_output_____" ] ], [ [ "Seems complicated, but let's see how we can grab that value:", "_____no_output_____" ] ], [ [ "# Keep calling the keys\nd['key1']['nestkey']['subnestkey']", "_____no_output_____" ] ], [ [ "### Dictionary Methods\n\nThere are a few methods we can call on a dictionary. Let's get a quick introduction to a few of them:", "_____no_output_____" ] ], [ [ "# Create a typical dictionary\nd = {'key1':1,'key2':2,'key3':3}", "_____no_output_____" ], [ "# Method to return a list of all keys \nd.keys()", "_____no_output_____" ], [ "# Method to grab all values\nd.values()", "_____no_output_____" ], [ "# Method to return tuples of all items (we'll learn about tuples soon)\nd.items()", "_____no_output_____" ] ], [ [ "### 4.0 Now Try This\n", "_____no_output_____" ], [ "Using keys and indexing, grab the 'hello' from the following dictionaries:", "_____no_output_____" ] ], [ [ "d = {'simple_key':'hello'}\n\n# Grab 'hello'\nanswer1 = #INSERT CODE HERE\nprint(answer1)", "_____no_output_____" ], [ "d = {'k1':{'k2':'hello'}}\n\n# Grab 'hello'\nanswer2 = #INSERT CODE HERE\nprint(answer2)", "_____no_output_____" ], [ "# Getting a little tricker\nd = {'k1':[{'nest_key':['this is deep',['hello']]}]}\n\n#Grab hello\nanswer3 = #INSERT CODE HERE\nprint(answer3)", "_____no_output_____" ], [ "# This will be hard and annoying!\nd = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}\n\n# Grab hello\nanswer4 = #INSERT CODE HERE\nprint(answer4)", "_____no_output_____" ] ], [ [ "## Comparison Operators \n\nAs stated previously, comparison operators allow us to compare variables and output a Boolean value (True or False). \n\nThese operators are the exact same as what you've seen in Math, so there's nothing new here.\n\nFirst we'll present a table of the comparison operators and then work through some examples:\n\n<h2> Table of Comparison Operators </h2><p> In the table below, a=9 and b=11.</p>\n\n<table class=\"table table-bordered\">\n<tr>\n<th style=\"width:10%\">Operator</th><th style=\"width:45%\">Description</th><th>Example</th>\n</tr>\n<tr>\n<td>==</td>\n<td>If the values of two operands are equal, then the condition becomes true.</td>\n<td> (a == b) is not true.</td>\n</tr>\n<tr>\n<td>!=</td>\n<td>If the values of two operands are not equal, then the condition becomes true.</td>\n<td>(a != b) is true</td>\n</tr>\n<tr>\n<td>&gt;</td>\n<td>If the value of the left operand is greater than the value of the right operand, then the condition becomes true.</td>\n<td> (a &gt; b) is not true.</td>\n</tr>\n<tr>\n<td>&lt;</td>\n<td>If the value of the left operand is less than the value of the right operand, then the condition becomes true.</td>\n<td> (a &lt; b) is true.</td>\n</tr>\n<tr>\n<td>&gt;=</td>\n<td>If the value of the left operand is greater than or equal to the value of the right operand, then the condition becomes true.</td>\n<td> (a &gt;= b) is not true. </td>\n</tr>\n<tr>\n<td>&lt;=</td>\n<td>If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes true.</td>\n<td> (a &lt;= b) is true. </td>\n</tr>\n</table>", "_____no_output_____" ], [ "Let's now work through quick examples of each of these.\n\n#### Equal", "_____no_output_____" ] ], [ [ "4 == 4", "_____no_output_____" ], [ "1 == 0", "_____no_output_____" ] ], [ [ "Note that <code>==</code> is a <em>comparison</em> operator, while <code>=</code> is an <em>assignment</em> operator.", "_____no_output_____" ], [ "#### Not Equal", "_____no_output_____" ] ], [ [ "4 != 5", "_____no_output_____" ], [ "1 != 1", "_____no_output_____" ] ], [ [ "#### Greater Than", "_____no_output_____" ] ], [ [ "8 > 3", "_____no_output_____" ], [ "1 > 9", "_____no_output_____" ] ], [ [ "#### Less Than", "_____no_output_____" ] ], [ [ "3 < 8", "_____no_output_____" ], [ "7 < 0", "_____no_output_____" ] ], [ [ "#### Greater Than or Equal to", "_____no_output_____" ] ], [ [ "7 >= 7", "_____no_output_____" ], [ "9 >= 4", "_____no_output_____" ] ], [ [ "#### Less than or Equal to", "_____no_output_____" ] ], [ [ "4 <= 4", "_____no_output_____" ], [ "1 <= 3", "_____no_output_____" ] ], [ [ "Hopefully this was more of a review than anything new! Next, we move on to one of the most important aspects of building programs: functions and how to use them.", "_____no_output_____" ], [ "## Functions\n\n### Introduction to Functions\n\nHere, we will explain what a function is in Python and how to create one. Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.\n\n**So what is a function?**\n\nFormally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.\n\nOn a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.\n\nFunctions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design.", "_____no_output_____" ], [ "### def Statements\n\nLet's see how to build out a function's syntax in Python. It has the following form:", "_____no_output_____" ] ], [ [ "def name_of_function(arg1,arg2):\n '''\n This is where the function's Document String (docstring) goes\n '''\n # Do stuff here\n # Return desired result", "_____no_output_____" ] ], [ [ "We begin with <code>def</code> then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a [built-in function in Python](https://docs.python.org/2/library/functions.html) (such as len).\n\nNext come a pair of parentheses with a number of arguments separated by a comma. These arguments are the inputs for your function. You'll be able to use these inputs in your function and reference them. After this you put a colon.\n\nNow here is the important step, you must indent to begin the code inside your function correctly. Python makes use of *whitespace* to organize code. Lots of other programing languages do not do this, so keep that in mind.\n\nNext you'll see the docstring, this is where you write a basic description of the function. Docstrings are not necessary for simple functions, but it's good practice to put them in so you or other people can easily understand the code you write.\n\nAfter all this you begin writing the code you wish to execute.\n\nThe best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before.", "_____no_output_____" ], [ "### A simple print 'hello' function", "_____no_output_____" ] ], [ [ "def say_hello():\n print('hello')", "_____no_output_____" ] ], [ [ "Call the function:", "_____no_output_____" ] ], [ [ "say_hello()", "hello\n" ] ], [ [ "### A simple greeting function\nLet's write a function that greets people with their name.", "_____no_output_____" ] ], [ [ "def greeting(name):\n print('Hello %s' %(name))", "_____no_output_____" ], [ "greeting('Bob')", "Hello Bob\n" ] ], [ [ "### Using return\nLet's see some example that use a <code>return</code> statement. <code>return</code> allows a function to *return* a result that can then be stored as a variable, or used in whatever manner a user wants.\n\n### Example 3: Addition function", "_____no_output_____" ] ], [ [ "def add_num(num1,num2):\n return num1+num2", "_____no_output_____" ], [ "add_num(4,5)", "_____no_output_____" ], [ "# Can also save as variable due to return\nresult = add_num(4,5)", "_____no_output_____" ], [ "print(result)", "9\n" ] ], [ [ "What happens if we input two strings?", "_____no_output_____" ] ], [ [ "add_num('one','two')", "_____no_output_____" ] ], [ [ "Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.\n\nLet's also start using <code>break</code>, <code>continue</code>, and <code>pass</code> statements in our code. We introduced these during the <code>while</code> lecture.", "_____no_output_____" ], [ "Finally let's go over a full example of creating a function to check if a number is prime (a common interview exercise).\n\nWe know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks.", "_____no_output_____" ] ], [ [ "def is_prime(num):\n '''\n Naive method of checking for primes. \n '''\n for n in range(2,num): #'range()' is a function that returns an array based on the range you provide. Here, it is from 2 to 'num' inclusive.\n if num % n == 0:\n print(num,'is not prime')\n break # 'break' statements signify that we exit the loop if the above condition holds true\n else: # If never mod zero, then prime\n print(num,'is prime!')", "_____no_output_____" ], [ "is_prime(16)", "16 is not prime\n" ], [ "is_prime(17)", "17 is prime!\n" ] ], [ [ "Note how the <code>else</code> lines up under <code>for</code> and not <code>if</code>. This is because we want the <code>for</code> loop to exhaust all possibilities in the range before printing our number is prime.\n\nAlso note how we break the code after the first print statement. As soon as we determine that a number is not prime we break out of the <code>for</code> loop.\n\nWe can actually improve this function by only checking to the square root of the target number, and by disregarding all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:", "_____no_output_____" ] ], [ [ "import math\n\ndef is_prime2(num):\n '''\n Better method of checking for primes. \n '''\n if num % 2 == 0 and num > 2: \n return False\n for i in range(3, int(math.sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True", "_____no_output_____" ], [ "is_prime2(27)", "_____no_output_____" ] ], [ [ "Why don't we have any <code>break</code> statements? It should be noted that as soon as a function *returns* something, it shuts down. A function can deliver multiple print statements, but it will only obey one <code>return</code>.", "_____no_output_____" ], [ "### 5.0 Now Try This\n", "_____no_output_____" ], [ "Write a function that capitalizes the first and fourth letters of a name. For this, you might want to make use of a string's `.upper()` method.\n \n cap_four('macdonald') --> MacDonald\n \nNote: `'macdonald'.capitalize()` returns `'Macdonald'`", "_____no_output_____" ] ], [ [ "def cap_four(name):\n \n return new_name\n\n# Check\nanswer1 = cap_four('macdonald')\nprint(answer1)", "_____no_output_____" ] ], [ [ "## Modules and Packages\n\n### Understanding modules\n\nModules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.\n\nTo import a module, we use the import command. Check out the full list of built-in modules in the Python standard library here.\n\nThe first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice.\n\nIf we want to import the math module, we simply import the name of the module:", "_____no_output_____" ] ], [ [ "# import the library\nimport math\n\n# use it (ceiling rounding)\nmath.ceil(3.2)", "_____no_output_____" ] ], [ [ "## Why, Where, and How we use NumPy\n\nNumPy is a library for Python that allows you to create matrices and multidimensional arrays, as well as perform many sophisticated mathematical operations on them. Previously, dealing with anything more than a single-dimensional array was very difficult in base Python. Additionally, there weren't a lot of built-in functionality to perform many standard mathematical operations that data scientists typically do with data, such as transposing, dot products, cumulative sums, etc. All of this makes NumPy very useful in statistical analyses and analyzing datasets to produce insights.", "_____no_output_____" ], [ "### Creating Arrays \n\nNumPy allows you to work with arrays very efficiently. The array object in NumPy is called *ndarray*. This is short for 'n-dimensional array'.\n\nWe can create a NumPy ndarray object by using the array() function.", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([1,2,3,4,5,6,7,8,9,10])\n\nprint(arr)\n\nprint(type(arr))", "_____no_output_____" ] ], [ [ "### Indexing\n\nIndexing is the same thing as accessing an element of a list or string. In this case, we will be accessing an array element.\n\nYou can access an array element by referring to its **index number**. The indexes in NumPy arrays start with 0, also like in base Python.\n\nThe following example shows how you can access multiple elements of an array and perform operations on them.", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([1,2,3,4,5,6,7,8,9,10])\n\nprint(arr[4] + arr[8])", "_____no_output_____" ] ], [ [ "### Slicing\n\nSlicing in NumPy behaves much like in base Python, a quick recap from above:\n\nWe slice using this syntax: [start:end].\n\nWe can also define the step, like this: [start:end:step].", "_____no_output_____" ] ], [ [ "# Reverse an array through backwards/negative stepping\nimport numpy as np\narr = np.array([3,7,9,0])\n\nprint(arr[::-1])", "_____no_output_____" ], [ "# Slice elements from the beginning to index 8\n\nimport numpy as np\n\narr = np.array([1, 2, 3, 4, 5, 6, 7,8,9,10])\n\nprint(arr[:8])", "_____no_output_____" ] ], [ [ "You'll notice we only got to index 7. That's because the end is always *non-inclusive*. We slice up to but not including the end value. The start index on the other hand, **is** inclusive.", "_____no_output_____" ], [ "### 6.0 Now Try This:\n\nCreate an array of at least size 10 and populate it with random numbers. Then, use slicing to split it into two and create two new arrays. Then, find the sum of the third digits in each array.\n\n", "_____no_output_____" ] ], [ [ "# Answer here", "_____no_output_____" ] ], [ [ "### Data Types", "_____no_output_____" ], [ "Just like base Python, NumPy has many data types available. They are all differentiated by a single character, and here are the most common few:\n\n* i - int / integer (whole numbers)\n* b - boolean (true/false)\n* f - float (decimal numbers)\n* S - string\n* There are many more too!", "_____no_output_____" ] ], [ [ "# Checking the data type of an array\nimport numpy as np\n\narr = np.array([5, 7, 3, 1])\n\nprint(arr.dtype)", "_____no_output_____" ], [ "# How to convert between types\nimport numpy as np\n\narr = np.array([4.4, 24.1, 3.7])\nprint(arr)\nprint(arr.dtype)\n\n# Converts decimal numbers by rounding them all down to whole numbers\nnewarr = arr.astype('i')\n\nprint(newarr)\nprint(newarr.dtype)", "_____no_output_____" ] ], [ [ "### 7.0 Now Try This:\n\nModify the code below to fix the error and make the addition work:", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([1,3,5,7],dtype='S')\narr2 = np.array([2,4,6,8],dtype='i')\n\nprint(arr + arr2)", "_____no_output_____" ] ], [ [ "### Copy vs. View\n\nIn NumPy, you can work with either a copy of the data or the data itself, and it's very important that you know the difference. Namely, modifying a copy of the data will not change the original dataset but modifying the view **will**. Here are some examples:", "_____no_output_____" ] ], [ [ "# A Copy\nimport numpy as np\n\narr = np.array([6, 2, 1, 5, 3])\nx = arr.copy()\narr[0] = 8\n\nprint(arr)\nprint(x)", "_____no_output_____" ], [ "# A View\nimport numpy as np\n\narr = np.array([6, 2, 1, 5, 3])\nx = arr.view()\narr[0] = 8\n\nprint(arr)\nprint(x)", "_____no_output_____" ] ], [ [ "### 8.0 Now Try This:\n\nA student wants to create a copy of an array and modify the first element. The following is the code they wrote for it:\n\narr = np.array([1,2,3,4,5])\n\nx = arr\n\nx[0] = 0\n\n\nIs this correct?", "_____no_output_____" ], [ "### Shape\n\nAll NumPy arrays have an attribute called *shape*. This is helpful for 2d or n-dimensional arrays, but for simple lists, it is just the number of elements that it has.", "_____no_output_____" ] ], [ [ "# Print the shape of an array\nimport numpy as np\n\narr = np.array([2,7,3,7])\n\nprint(arr.shape)", "_____no_output_____" ] ], [ [ "### 9.0 Now Try This:\n\nWithout using Python, what is the shape of this array? Answer in the same format as the `shape` method.\n\narr = np.array([[0,1,2].[3,4,5])", "_____no_output_____" ], [ "### Iterating Through Arrays\n\nIterating simply means to traverse or travel through an object. In the case of arrays, we can iterate through them by using simple for loops.", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([1, 5, 7])\n\nfor x in arr:\n print(x)", "_____no_output_____" ] ], [ [ "### Joining Arrays \n\nJoining combining the elements of multiple arrays into one.\n\nThe basic way to do it is like this:", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr1 = np.array([7, 1, 0])\n\narr2 = np.array([2, 8, 1])\n\narr = np.concatenate((arr1, arr2))\n\nprint(arr)", "_____no_output_____" ] ], [ [ "### Splitting Arrays\n\nSplitting is the opposite of joining arrays. It takes one array and creates multiple from it.", "_____no_output_____" ] ], [ [ "# Split array into 4\nimport numpy as np\n\narr = np.array([1, 2, 3, 4, 5, 6,7,8])\n\nnewarr = np.array_split(arr, 4)\n\nprint(newarr)", "_____no_output_____" ] ], [ [ "### Searching Arrays \n\nSearching an array to find a certain element is a very important and basic operation. We can do this using the *where()* method.", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([1, 2, 5, 9, 5, 3, 4])\n\nx = np.where(arr == 4) # Returns the index of the array element(s) that matches this condition \n\nprint(x)", "_____no_output_____" ], [ "# Find all the odd numbers in an array\nimport numpy as np\n\narr = np.array([10, 20, 30, 40, 50, 60, 70, 80,99])\n\nx = np.where(arr%2 == 1)\n\nprint(x)", "_____no_output_____" ] ], [ [ "### Sorting Arrays\n\nSorting an array is another very important and commonly used operation. NumPy has a function called sort() for this task.", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([4, 1, 0, 3])\n\nprint(np.sort(arr))", "_____no_output_____" ], [ "# Sorting a string array alphabetically\nimport numpy as np\n\narr = np.array(['zephyr', 'gate', 'match'])\n\nprint(np.sort(arr))", "_____no_output_____" ] ], [ [ "### Filtering Arrays\n\nSometimes you would want to create a new array from an existing array where you select elements out based on a certain condition. Let's say you have an array with all integers from 1 to 10. You would like to create a new array with only the odd numbers from that list. You can do this very efficiently with **filtering**. When you filter something, you only take out what you want, and the same principle applies to objects in NumPy. NumPy uses what's called a **boolean index list** to filter. This is an array of True and False values that correspond directly to the target array and what values you would like to filter. For example, using the example above, the target array would look like this:\n\n[1,2,3,4,5,6,7,8,9,10]\n\nAnd if you wanted to filter out the odd values, you would use this particular boolean index list:\n\n[True,False,True,False,True,False,True,False,True,False]\n\nApplying this list onto the target array will get you what you want:\n\n[1,3,5,7,9]\n\nA working code example is shown below:", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([51, 52, 53, 54])\n\nx = [False, False, True, True]\n\nnewarr = arr[x]\n\nprint(newarr)", "_____no_output_____" ] ], [ [ "We don't need to hard-code the True and False values. Like stated previously, we can filter based on conditions.", "_____no_output_____" ] ], [ [ "arr = np.array([51, 52, 53, 54])\n\n# Create an empty list\nfilter_arr = []\n\n# go through each element in arr\nfor element in arr:\n # if the element is higher than 52, set the value to True, otherwise False:\n if element > 52:\n filter_arr.append(True)\n else:\n filter_arr.append(False)\n\nnewarr = arr[filter_arr]\n\nprint(filter_arr)\nprint(newarr)", "_____no_output_____" ] ], [ [ "Filtering is a very common task when working with data and as such, NumPy has an even more efficient way to perform it. It is possible to create a boolean index list directly from the target array and then apply it to obtain the filtered array. See the example below:", "_____no_output_____" ] ], [ [ "import numpy as np\n\narr = np.array([10,20,30,40,50,60,70,80,90,100])\n\nfilter = arr > 50\n\nfilter_arr = arr[filter]\n\nprint(filter)\nprint(filter_arr)", "[False False False False False True True True True True]\n[ 60 70 80 90 100]\n" ] ], [ [ "### 10.0 Now Try This:\n\nCreate an array with the first 10 numbers of the Fibonacci sequence. Split this array into two. On each half, search for any multiples of 4. Next, filter both arrays for multiples of 5. Finally, take the two filtered arrays, join them, and sort them.", "_____no_output_____" ] ], [ [ "# Answer here\n", "_____no_output_____" ] ], [ [ "## Resources", "_____no_output_____" ], [ "- [Python Documentation](https://docs.python.org/3/)\n- [Official Python Tutorial](https://docs.python.org/3/tutorial/)\n- [W3Schools Python Tutorial](https://www.w3schools.com/python/)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbe14ed163ad2a743eb5a2f0a4c5c55ed23fa329
26,560
ipynb
Jupyter Notebook
back-propa.ipynb
zzong2006/backpropaWithNumpy
9e6da18a044bb3d76d93d28c97ac05e80b9e0281
[ "MIT" ]
1
2021-05-15T23:28:24.000Z
2021-05-15T23:28:24.000Z
back-propa.ipynb
zzong2006/backpropagation-with-numpy
9e6da18a044bb3d76d93d28c97ac05e80b9e0281
[ "MIT" ]
null
null
null
back-propa.ipynb
zzong2006/backpropagation-with-numpy
9e6da18a044bb3d76d93d28c97ac05e80b9e0281
[ "MIT" ]
null
null
null
30.216155
151
0.373532
[ [ [ "Move current working directory, in case for developing the machine learning program by remote machine or it is fine not to use below single line.", "_____no_output_____" ] ], [ [ "%cd /tmp/pycharm_project_881", "/tmp/pycharm_project_881\n" ], [ "import numpy as np\nimport pandas as pd\n\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef softmax(x):\n x = x - x.max(axis=1, keepdims=True)\n return np.exp(x)/np.sum(np.exp(x),axis=1, keepdims=True)\n", "_____no_output_____" ], [ "df = pd.read_csv(\"adult.data.txt\", names=[\"age\",\"workclass\",\"fnlwgt\",\"education\",\"education-num\",\"marital-status\" \\\n ,\"occupation\",\"relationship\",\"race\",\"sex\",\"capital-gain\",\"capital-loss\",\"hours-per-week\",\"native-country\",\"class\"])\ndx = pd.read_csv(\"adult.test.txt\", names=[\"age\",\"workclass\",\"fnlwgt\",\"education\",\"education-num\",\"marital-status\" \\\n ,\"occupation\",\"relationship\",\"race\",\"sex\",\"capital-gain\",\"capital-loss\",\"hours-per-week\",\"native-country\",\"class\"])\n", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "for lf in df:\n if df[lf].dtype == \"object\":\n df[lf] = df[lf].astype(\"category\").cat.codes\n dx[lf] = dx[lf].astype(\"category\").cat.codes\n else :\n df[lf] = (df[lf] - df[lf].mean())/(df[lf].max() - df[lf].min())\n dx[lf] = (dx[lf] - dx[lf].mean()) / (dx[lf].max() - dx[lf].min())", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "Set initial hyperparameters..", "_____no_output_____" ] ], [ [ "x = df.drop(columns=[\"class\"])\ny = df[\"class\"].values\nx_test = dx.drop(columns=[\"class\"])\ny_test = dx[\"class\"].values\n\nmulti_y = np.zeros((y.size, y.max()+1))\nmulti_y[np.arange(y.size), y] = 1\nmulti_y_test = np.zeros((y_test.size, y_test.max()+1))\nmulti_y_test[np.arange(y_test.size), y_test] = 1\n\ninputSize = len(x.columns)\nnumberOfNodes = 150\nnumberOfClass = y.max() + 1\nnumberOfExamples = x.shape[0]\n\nw1 = np.random.random_sample(size=(inputSize, numberOfNodes))\nb1 = np.random.random_sample(numberOfNodes)\nw2 = np.random.random_sample(size=(numberOfNodes, numberOfClass))\nb2 = np.random.random_sample(numberOfClass)\n\nbatchSize = 32\ntrainNum = 150\nlearningRate = 0.01", "_____no_output_____" ], [ "# Start Training\nfor k in range(trainNum + 1):\n cost = 0\n accuracy = 0\n for i in range(int(numberOfExamples/batchSize)):\n # Forward-Propagation\n z = x[i * batchSize : (i+1) * batchSize]\n z_y = multi_y[i * batchSize : (i+1) * batchSize]\n layer1 = np.matmul(z, w1) + b1\n sig_layer1 = sigmoid(layer1)\n layer2 = np.matmul(sig_layer1, w2) + b2\n soft_layer2 = softmax(layer2)\n pred = np.argmax(soft_layer2, axis=1)\n # Cost Function: Cross-Entropy loss\n cost += -(z_y * np.log(soft_layer2 + 1e-9) + (1-z_y) * np.log(1 - soft_layer2 + 1e-9)).sum()\n accuracy += (pred == y[i * batchSize : (i + 1) * batchSize]).sum()\n\n # Back-Propagation\n dlayer2 = soft_layer2 - multi_y[i * batchSize : (i+1) * batchSize]\n dw2 = np.matmul(sig_layer1.T, dlayer2) / batchSize\n db2 = dlayer2.mean(axis=0)\n dsig_layer1 = (dlayer2.dot(w2.T))\n dlayer1 = sigmoid(layer1) * (1 - sigmoid(layer1)) * dsig_layer1\n dw1 = np.matmul(z.T, dlayer1) / batchSize\n db1 = dlayer1.mean(axis=0)\n\n w2 -= learningRate * dw2\n w1 -= learningRate * dw1\n b2 -= learningRate * db2\n b1 -= learningRate * db1\n if k % 10 == 0 :\n print(\"-------- # : {} ---------\".format(k))\n print(\"cost: {}\".format(cost/numberOfExamples))\n print(\"accuracy: {} %\".format(accuracy/numberOfExamples * 100))\n", "-------- # : 0 ---------\ncost: 1.141661040585942\naccuracy: 75.62114185682259 %\n" ], [ "# Test the trained model\ntest_cost = 0\ntest_accuracy = 0\n# Forward-Propagation\nlayer1 = np.matmul(x_test, w1) + b1\nsig_layer1 = sigmoid(layer1)\nlayer2 = np.matmul(sig_layer1, w2) + b2\nsoft_layer2 = softmax(layer2)\npred = np.argmax(soft_layer2, axis=1)\n# Cost Function: Cross-Entropy loss\ntest_cost += -(multi_y_test * np.log(soft_layer2 + 1e-9) + (1-multi_y_test) * np.log(1 - soft_layer2 + 1e-9)).sum()\ntest_accuracy += (pred == y_test).sum()\n\nprint(\"---- Result of applying test data to the trained model\")\nprint(\"cost: {}\".format(test_cost/numberOfExamples))\nprint(\"accuracy: {} %\".format(test_accuracy/numberOfExamples * 100))", "---- Result of applying test data to the trained model\ncost: 0.3799726049100673\naccuracy: 41.17809649580787 %\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbe1509ce58d8c92fc59c9b8360eb254628b5f83
34,437
ipynb
Jupyter Notebook
experiments/training_allen/SOMEFExtension_Description_InvocationDL.ipynb
liling10822/README-analysis
88d76b019f5b272a1d92deaaa0767f71bf685a75
[ "MIT" ]
1
2020-11-20T22:19:56.000Z
2020-11-20T22:19:56.000Z
experiments/training_allen/SOMEFExtension_Description_InvocationDL.ipynb
liling10822/README-analysis
88d76b019f5b272a1d92deaaa0767f71bf685a75
[ "MIT" ]
22
2020-10-21T01:03:55.000Z
2020-11-10T10:18:46.000Z
experiments/training_allen/SOMEFExtension_Description_InvocationDL.ipynb
liling10822/README-analysis
88d76b019f5b272a1d92deaaa0767f71bf685a75
[ "MIT" ]
1
2021-01-18T14:47:04.000Z
2021-01-18T14:47:04.000Z
120.409091
11,950
0.786509
[ [ [ "from google.colab import drive\ndrive.mount('/content/drive/')", "Mounted at /content/drive/\n" ], [ "import keras\nimport pandas as pd\nimport numpy as np\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "!ls \"/content/drive/My Drive/Deep Learning/SOMEF_Extension--main\"", "description.csv invocation.csv SOMEFExtension_Description_Invocation.ipynb\n" ], [ "ext_desc=pd.read_csv(\"/content/drive/My Drive/Deep Learning/SOMEF_Extension--main/description.csv\")\n\n\nX_desc, Y_desc = ext_desc.excerpt, ext_desc.extended_description\nvectorizer = CountVectorizer()\nX_desc=vectorizer.fit_transform(X_desc).toarray()\nY_desc = np.where(Y_desc == True, 1, Y_desc)\n\nX_train, X_test, Y_train, Y_test = train_test_split(X_desc, Y_desc)\n\nmodel=models.Sequential()\nmodel.add(layers.Dense(16,activation='relu',input_dim=X_desc.shape[1]))\nmodel.add(layers.Dense(16,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])\n\nx_val=X_train[:100]\npartial_x_train=X_train[100:]\ny_val=Y_train[:100]\npartial_y_train=Y_train[100:]\n\nhistory=model.fit(partial_x_train,partial_y_train, validation_data=(x_val,y_val),epochs=50,batch_size=512)", "_____no_output_____" ], [ "history_dict=history.history\nloss_values=history_dict['loss']\nval_loss_values=history_dict['val_loss']\nepochs=range(1,len(loss_values)+1)\n\nplt.plot(epochs,loss_values,'bo',label='Tr loss')\nplt.plot(epochs,val_loss_values,'b',label='Val loss')\nplt.legend()\nplt.show()\n\nacc_values=history_dict['accuracy']\nval_acc_values=history_dict['val_accuracy']\nepochs=range(1,len(val_acc_values)+1)\n\nplt.plot(epochs,acc_values,'bo',label='Tr acc')\nplt.plot(epochs,val_acc_values,'b',label='Val acc')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "model=models.Sequential()\nmodel.add(layers.Dense(16,activation='relu',input_dim=X_desc.shape[1]))\nmodel.add(layers.Dense(16,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmetric_ = [\n \n keras.metrics.Precision(name='precision'),\n keras.metrics.Recall(name='recall')\n ]\n\n## we choose 35 epochs because we start getting flat curves for accuracy above beyond 35 epochs\nmodel.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=metric_)\nhistory=model.fit(X_train,Y_train,epochs=35,batch_size=512)\nresults=model.evaluate(X_test,Y_test)\nprint(results)", "Epoch 1/35\n2/2 [==============================] - 0s 7ms/step - loss: 0.7123 - precision: 0.5652 - recall: 0.0831\nEpoch 2/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.6809 - precision: 0.8015 - recall: 0.6709\nEpoch 3/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.6644 - precision: 0.8309 - recall: 0.9105\nEpoch 4/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.6495 - precision: 0.8846 - recall: 0.9553\nEpoch 5/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.6322 - precision: 0.8886 - recall: 0.9681\nEpoch 6/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.6149 - precision: 0.9035 - recall: 0.9872\nEpoch 7/35\n2/2 [==============================] - 0s 5ms/step - loss: 0.5968 - precision: 0.8943 - recall: 1.0000\nEpoch 8/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.5807 - precision: 0.9176 - recall: 0.9968\nEpoch 9/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.5662 - precision: 0.9233 - recall: 1.0000\nEpoch 10/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.5514 - precision: 0.9315 - recall: 1.0000\nEpoch 11/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.5364 - precision: 0.9571 - recall: 0.9968\nEpoch 12/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.5226 - precision: 0.9658 - recall: 0.9936\nEpoch 13/35\n2/2 [==============================] - 0s 5ms/step - loss: 0.5090 - precision: 0.9720 - recall: 1.0000\nEpoch 14/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4953 - precision: 0.9781 - recall: 1.0000\nEpoch 15/35\n2/2 [==============================] - 0s 5ms/step - loss: 0.4808 - precision: 0.9779 - recall: 0.9904\nEpoch 16/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.4674 - precision: 0.9778 - recall: 0.9840\nEpoch 17/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4543 - precision: 0.9778 - recall: 0.9840\nEpoch 18/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4413 - precision: 0.9778 - recall: 0.9872\nEpoch 19/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4285 - precision: 0.9841 - recall: 0.9904\nEpoch 20/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4160 - precision: 0.9841 - recall: 0.9904\nEpoch 21/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.4040 - precision: 0.9872 - recall: 0.9840\nEpoch 22/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3916 - precision: 0.9871 - recall: 0.9808\nEpoch 23/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3803 - precision: 0.9840 - recall: 0.9808\nEpoch 24/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3696 - precision: 0.9904 - recall: 0.9872\nEpoch 25/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3585 - precision: 0.9903 - recall: 0.9808\nEpoch 26/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3482 - precision: 0.9903 - recall: 0.9808\nEpoch 27/35\n2/2 [==============================] - 0s 6ms/step - loss: 0.3375 - precision: 0.9935 - recall: 0.9840\nEpoch 28/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3276 - precision: 0.9935 - recall: 0.9840\nEpoch 29/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3174 - precision: 0.9968 - recall: 0.9840\nEpoch 30/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.3078 - precision: 0.9968 - recall: 0.9840\nEpoch 31/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.2981 - precision: 0.9968 - recall: 0.9840\nEpoch 32/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.2885 - precision: 0.9968 - recall: 0.9840\nEpoch 33/35\n2/2 [==============================] - 0s 3ms/step - loss: 0.2797 - precision: 0.9968 - recall: 0.9808\nEpoch 34/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.2707 - precision: 0.9968 - recall: 0.9808\nEpoch 35/35\n2/2 [==============================] - 0s 4ms/step - loss: 0.2619 - precision: 0.9968 - recall: 0.9808\n6/6 [==============================] - 0s 3ms/step - loss: 0.4578 - precision: 0.8913 - recall: 0.8119\n[0.4578087329864502, 0.8913043737411499, 0.8118811845779419]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cbe15a30565a84d9c44ac55815e964a151240ccf
975,306
ipynb
Jupyter Notebook
notebooks/RetinaNet - Movie.ipynb
vanvalenlab/deepcell-retinamask
c922d4d836e881270da8b43c420c60d365883639
[ "Apache-2.0" ]
null
null
null
notebooks/RetinaNet - Movie.ipynb
vanvalenlab/deepcell-retinamask
c922d4d836e881270da8b43c420c60d365883639
[ "Apache-2.0" ]
2
2021-11-26T11:18:44.000Z
2022-01-21T11:29:41.000Z
notebooks/RetinaNet - Movie.ipynb
vanvalenlab/deepcell-retinamask
c922d4d836e881270da8b43c420c60d365883639
[ "Apache-2.0" ]
null
null
null
1,812.836431
957,816
0.949888
[ [ [ "# 3D Nuclear Segmentation with RetinaNet", "_____no_output_____" ] ], [ [ "import os\nimport errno\n\nimport numpy as np\n\nimport deepcell\nimport deepcell_retinamask", "_____no_output_____" ], [ "# Download the data (saves to ~/.keras/datasets)\nfilename = 'HEK293.trks'\ntest_size = 0.1 # % of data saved as test\nseed = 0 # seed for random train-test split\n\n(X_train, y_train), (X_test, y_test) = deepcell.datasets.tracked.hek293.load_tracked_data(\n filename, test_size=test_size, seed=seed)\n\nprint('X.shape: {}\\ny.shape: {}'.format(X_train.shape, y_train.shape))", "X.shape: (233, 30, 135, 160, 1)\ny.shape: (233, 30, 135, 160, 1)\n" ] ], [ [ "### Set up filepath constants", "_____no_output_____" ] ], [ [ "# the path to the data file is currently required for `train_model_()` functions\n\n# NOTE: Change DATA_DIR if you are not using `deepcell.datasets`\nDATA_DIR = os.path.expanduser(os.path.join('~', '.keras', 'datasets'))\n\nDATA_FILE = os.path.join(DATA_DIR, filename)\n\n# confirm the data file is available\nassert os.path.isfile(DATA_FILE)", "_____no_output_____" ], [ "# Set up other required filepaths\n\n# If the data file is in a subdirectory, mirror it in MODEL_DIR and LOG_DIR\nPREFIX = os.path.relpath(os.path.dirname(DATA_FILE), DATA_DIR)\n\nROOT_DIR = '/data' # TODO: Change this! Usually a mounted volume\nMODEL_DIR = os.path.abspath(os.path.join(ROOT_DIR, 'models', PREFIX))\nLOG_DIR = os.path.abspath(os.path.join(ROOT_DIR, 'logs', PREFIX))\n\n# create directories if they do not exist\nfor d in (MODEL_DIR, LOG_DIR):\n try:\n os.makedirs(d)\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise", "_____no_output_____" ] ], [ [ "### Set up training parameters", "_____no_output_____" ] ], [ [ "from tensorflow.keras.optimizers import SGD, Adam\nfrom deepcell.utils.train_utils import rate_scheduler\n\nmodel_name = 'retinamovie_model'\nbackbone = 'resnet50' # vgg16, vgg19, resnet50, densenet121, densenet169, densenet201\n\nn_epoch = 3 # Number of training epochs\nlr = 1e-5\n\noptimizer = Adam(lr=lr, clipnorm=0.001)\n\nlr_sched = rate_scheduler(lr=lr, decay=0.99)\n\nbatch_size = 1\n\nnum_classes = 1 # \"object\" is the only class", "_____no_output_____" ], [ "# Each head of the model uses its own loss\nfrom deepcell_retinamask.losses import RetinaNetLosses\n\nsigma = 3.0\nalpha = 0.25\ngamma = 2.0\niou_threshold = 0.5\nmax_detections = 100\nmask_size = (28, 28)\n\nretinanet_losses = RetinaNetLosses(\n sigma=sigma, alpha=alpha, gamma=gamma,\n iou_threshold=iou_threshold,\n mask_size=mask_size)\n\nloss = {\n 'regression': retinanet_losses.regress_loss,\n 'classification': retinanet_losses.classification_loss,\n}", "_____no_output_____" ] ], [ [ "## Create the RetinaMovieMask Model", "_____no_output_____" ] ], [ [ "from deepcell_retinamask.utils.anchor_utils import get_anchor_parameters\n\nflat_shape = [y_train.shape[0] * y_train.shape[1]] + list(y_train.shape[2:])\nflat_y = np.reshape(y_train, tuple(flat_shape)).astype('int')\n\n# Generate backbone information from the data\nbackbone_levels, pyramid_levels, anchor_params = get_anchor_parameters(flat_y)\n\nfpb = 5 # number of frames in each training batch", "_____no_output_____" ], [ "from deepcell_retinamask import model_zoo\n\n# Pass frames_per_batch > 1 to enable 3D mode!\nmodel = model_zoo.RetinaNet(\n backbone=backbone,\n use_imagenet=True,\n panoptic=False,\n frames_per_batch=fpb,\n num_classes=num_classes,\n input_shape=X_train.shape[2:],\n backbone_levels=backbone_levels,\n pyramid_levels=pyramid_levels,\n num_anchors=anchor_params.num_anchors())\n\nprediction_model = model_zoo.retinanet_bbox(\n model,\n panoptic=False,\n frames_per_batch=fpb,\n max_detections=100,\n anchor_params=anchor_params)", "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/deprecation.py:574: calling map_fn_v2 (from tensorflow.python.ops.map_fn) with dtype is deprecated and will be removed in a future version.\nInstructions for updating:\nUse fn_output_signature instead\n" ], [ "model.compile(loss=loss, optimizer=optimizer)", "_____no_output_____" ] ], [ [ "## Train the model", "_____no_output_____" ] ], [ [ "from deepcell_retinamask.image_generators import RetinaMovieDataGenerator\n\ndatagen = RetinaMovieDataGenerator(\n rotation_range=180,\n zoom_range=(0.8, 1.2),\n horizontal_flip=True,\n vertical_flip=True)\n\ndatagen_val = RetinaMovieDataGenerator()", "_____no_output_____" ], [ "train_data = datagen.flow(\n {'X': X_train, 'y': y_train},\n batch_size=1,\n include_masks=False,\n frames_per_batch=fpb,\n pyramid_levels=pyramid_levels,\n anchor_params=anchor_params)\n\nval_data = datagen_val.flow(\n {'X': X_test, 'y': y_test},\n batch_size=1,\n include_masks=False,\n frames_per_batch=fpb,\n pyramid_levels=pyramid_levels,\n anchor_params=anchor_params)", "_____no_output_____" ], [ "from tensorflow.keras import callbacks\nfrom deepcell_retinamask.callbacks import RedirectModel, Evaluate\n\niou_threshold = 0.5\nscore_threshold = 0.01\nmax_detections = 100\n\nmodel.fit_generator(\n train_data,\n steps_per_epoch=X_train.shape[0] // batch_size,\n epochs=n_epoch,\n validation_data=val_data,\n validation_steps=X_test.shape[0] // batch_size,\n callbacks=[\n callbacks.LearningRateScheduler(lr_sched),\n callbacks.ModelCheckpoint(\n os.path.join(MODEL_DIR, model_name + '.h5'),\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n save_weights_only=False),\n RedirectModel(\n Evaluate(val_data,\n iou_threshold=iou_threshold,\n score_threshold=score_threshold,\n max_detections=max_detections,\n frames_per_batch=fpb,\n weighted_average=True),\n prediction_model)\n ])", "WARNING:tensorflow:From <ipython-input-12-787d9f17aab6>:29: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use Model.fit, which supports generators.\nEpoch 1/3\n233/233 [==============================] - ETA: 0s - loss: 3.0232 - regression_loss: 2.5155 - classification_loss: 0.5077\nEpoch 00001: val_loss improved from inf to 2.36478, saving model to /data/models/retinamovie_model.h5\nWARNING:tensorflow:Found duplicated `Variable`s in Model's `weights`. This is usually caused by `Variable`s being shared by Layers in the Model. These `Variable`s will be treated as separate `Variable`s when the Model is restored. To avoid this, please save with `save_format=\"tf\"`.\n374 instances of class 0 with average precision: 0.6596\nmAP: 0.6596\n233/233 [==============================] - 148s 635ms/step - loss: 3.0232 - regression_loss: 2.5155 - classification_loss: 0.5077 - val_loss: 2.3648 - val_regression_loss: 2.0626 - val_classification_loss: 0.3022\nEpoch 2/3\n233/233 [==============================] - ETA: 0s - loss: 2.2546 - regression_loss: 1.9746 - classification_loss: 0.2800\nEpoch 00002: val_loss improved from 2.36478 to 1.97483, saving model to /data/models/retinamovie_model.h5\nWARNING:tensorflow:Found duplicated `Variable`s in Model's `weights`. This is usually caused by `Variable`s being shared by Layers in the Model. These `Variable`s will be treated as separate `Variable`s when the Model is restored. To avoid this, please save with `save_format=\"tf\"`.\n374 instances of class 0 with average precision: 0.7653\nmAP: 0.7653\n233/233 [==============================] - 144s 616ms/step - loss: 2.2546 - regression_loss: 1.9746 - classification_loss: 0.2800 - val_loss: 1.9748 - val_regression_loss: 1.7234 - val_classification_loss: 0.2515\nEpoch 3/3\n233/233 [==============================] - ETA: 0s - loss: 1.9324 - regression_loss: 1.7075 - classification_loss: 0.2250\nEpoch 00003: val_loss improved from 1.97483 to 1.83277, saving model to /data/models/retinamovie_model.h5\nWARNING:tensorflow:Found duplicated `Variable`s in Model's `weights`. This is usually caused by `Variable`s being shared by Layers in the Model. These `Variable`s will be treated as separate `Variable`s when the Model is restored. To avoid this, please save with `save_format=\"tf\"`.\n374 instances of class 0 with average precision: 0.8505\nmAP: 0.8505\n233/233 [==============================] - 145s 624ms/step - loss: 1.9324 - regression_loss: 1.7075 - classification_loss: 0.2250 - val_loss: 1.8328 - val_regression_loss: 1.6180 - val_classification_loss: 0.2148\n" ] ], [ [ "## Evaluate results", "_____no_output_____" ] ], [ [ "from deepcell_retinamask.utils.anchor_utils import evaluate\n\niou_threshold = 0.5\nscore_threshold = 0.01\nmax_detections = 100\n\naverage_precisions = evaluate(\n val_data,\n prediction_model,\n frames_per_batch=fpb,\n iou_threshold=iou_threshold,\n score_threshold=score_threshold,\n max_detections=max_detections,\n)\n\n# print evaluation\ntotal_instances = []\nprecisions = []\n\nfor label, (average_precision, num_annotations) in average_precisions.items():\n print('{:.0f} instances of class'.format(num_annotations),\n label, 'with average precision: {:.4f}'.format(average_precision))\n total_instances.append(num_annotations)\n precisions.append(average_precision)\n\nif sum(total_instances) == 0:\n print('No test instances found.')\nelse:\n print('mAP using the weighted average of precisions among classes: {:.4f}'.format(\n sum([a * b for a, b in zip(total_instances, precisions)]) / sum(total_instances)))\n print('mAP: {:.4f}'.format(sum(precisions) / sum(x > 0 for x in total_instances)))", "374 instances of class 0 with average precision: 0.8505\nmAP using the weighted average of precisions among classes: 0.8505\nmAP: 0.8505\n" ] ], [ [ "## Display results", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport os\nimport time\n\nimport numpy as np\n\nfrom deepcell_retinamask.utils.plot_utils import draw_detections\n\n\nindex = np.random.randint(low=0, high=X_test.shape[0])\nframe = np.random.randint(low=0, high=X_test.shape[1] - fpb)\n\nprint('Image Number:', index)\nprint('Frame Number:', frame)\n\nimage = X_test[index:index + 1, frame:frame + fpb]\nmask = y_test[index:index + 1, frame:frame + fpb]\n\nboxes, scores, labels = prediction_model.predict(image)\ndisplay = 0.01 * np.tile(np.expand_dims(image[0, ..., 0], axis=-1), (1, 1, 3))\nmask = np.squeeze(mask)\n\ndraw_list = []\n\nfor i in range(fpb):\n draw = 0.1 * np.tile(image[0, i].copy(), (1, 1, 3))\n\n # draw detections\n draw_detections(\n draw, boxes[0, i], scores[0, i], labels[0, i],\n label_to_name=lambda x: 'cell', score_threshold=0.5)\n\n draw_list.append(draw)\n\nfig, axes = plt.subplots(ncols=3, nrows=fpb, figsize=(25, 25), sharex=True, sharey=True)\n\nfor i in range(fpb):\n axes[i, 0].imshow(display[i, ..., 0], cmap='jet')\n axes[i, 0].set_title('Source Image - Frame {}'.format(frame + i))\n\n axes[i, 1].imshow(mask[i], cmap='jet')\n axes[i, 1].set_title('Labeled Image - Frame {}'.format(frame + i))\n\n axes[i, 2].imshow(draw_list[i], cmap='jet')\n axes[i, 2].set_title('Detections')\n\nfig.tight_layout()\nplt.show()", "Image Number: 0\nFrame Number: 9\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe164e08010f39a47f143428853f596c7dc83ad
332,601
ipynb
Jupyter Notebook
CNNs.ipynb
ilias-ant/fashion-mnist-classification
1c9024a9ae315461ac0bb6583b61d2feb0d72d27
[ "MIT" ]
3
2022-03-11T08:50:33.000Z
2022-03-29T15:40:05.000Z
CNNs.ipynb
ilias-ant/fashion-mnist-classification
1c9024a9ae315461ac0bb6583b61d2feb0d72d27
[ "MIT" ]
null
null
null
CNNs.ipynb
ilias-ant/fashion-mnist-classification
1c9024a9ae315461ac0bb6583b61d2feb0d72d27
[ "MIT" ]
1
2022-03-12T10:11:27.000Z
2022-03-12T10:11:27.000Z
287.966234
83,988
0.898792
[ [ [ "## Fashion Item Recognition with CNN\n\n> Antonopoulos Ilias (p3352004) <br />\n> Ndoja Silva (p3352017) <br />\n> MSc Data Science AUEB", "_____no_output_____" ], [ "## Table of Contents\n\n- [Data Loading](#Data-Loading)\n- [Hyperparameter Tuning](#Hyperparameter-Tuning)\n- [Model Selection](#Model-Selection)\n- [Evaluation](#Evaluation)", "_____no_output_____" ] ], [ [ "import gc\nimport itertools\n\nimport numpy as np\nimport keras_tuner as kt\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix", "_____no_output_____" ], [ "print(tf.__version__)", "2.8.0\n" ], [ "print(\"Num GPUs Available: \", len(tf.config.list_physical_devices(\"GPU\")))", "Num GPUs Available: 0\n" ] ], [ [ "### Data Loading", "_____no_output_____" ] ], [ [ "fashion_mnist = tf.keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()", "_____no_output_____" ], [ "train_images.shape", "_____no_output_____" ], [ "train_labels", "_____no_output_____" ], [ "set(train_labels)", "_____no_output_____" ], [ "test_images.shape", "_____no_output_____" ] ], [ [ "This is a dataset of 60,000 28x28 grayscale images of 10 fashion categories,\n along with a test set of 10,000 images.\n \nThe classes are:\n \n| Label | Description |\n|:-----:|-------------|\n| 0 | T-shirt/top |\n| 1 | Trouser |\n| 2 | Pullover |\n| 3 | Dress |\n| 4 | Coat |\n| 5 | Sandal |\n| 6 | Shirt |\n| 7 | Sneaker |\n| 8 | Bag |\n| 9 | Ankle boot |", "_____no_output_____" ] ], [ [ "class_names = [\n \"T-shirt/top\",\n \"Trouser\",\n \"Pullover\",\n \"Dress\",\n \"Coat\",\n \"Sandal\",\n \"Shirt\",\n \"Sneaker\",\n \"Bag\",\n \"Ankle boot\",\n]", "_____no_output_____" ] ], [ [ "### Hyperparameter Tuning", "_____no_output_____" ] ], [ [ "SEED = 123456\n\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)", "_____no_output_____" ], [ "def clean_up(model_):\n tf.keras.backend.clear_session()\n del model_\n gc.collect()", "_____no_output_____" ], [ "def cnn_model_builder(hp):\n \"\"\"Creates a HyperModel instance (or callable that takes hyperparameters and returns a Model instance).\"\"\"\n model = tf.keras.Sequential(\n [\n tf.keras.layers.Conv2D(\n filters=hp.Int(\"1st-filter\", min_value=32, max_value=128, step=16),\n kernel_size=(3, 3),\n strides=(1, 1),\n padding=\"same\",\n kernel_regularizer=\"l2\",\n dilation_rate=(1, 1),\n activation=\"relu\",\n input_shape=(28, 28, 1),\n name=\"1st-convolution\",\n ),\n tf.keras.layers.MaxPool2D(\n pool_size=(2, 2), strides=(2, 2), padding=\"same\", name=\"1st-max-pooling\"\n ),\n tf.keras.layers.Dropout(\n rate=hp.Float(\"1st-dropout\", min_value=0.0, max_value=0.4, step=0.1),\n name=\"1st-dropout\",\n ),\n tf.keras.layers.Conv2D(\n filters=hp.Int(\"2nd-filter\", min_value=32, max_value=64, step=16),\n kernel_size=(3, 3),\n strides=(1, 1),\n padding=\"same\",\n kernel_regularizer=\"l2\",\n dilation_rate=(1, 1),\n activation=\"relu\",\n name=\"2nd-convolution\",\n ),\n tf.keras.layers.MaxPool2D(\n pool_size=(2, 2), strides=(2, 2), padding=\"same\", name=\"2nd-max-pooling\"\n ),\n tf.keras.layers.Dropout(\n rate=hp.Float(\"2nd-dropout\", min_value=0.0, max_value=0.4, step=0.1),\n name=\"2nd-dropout\",\n ),\n tf.keras.layers.Flatten(name=\"flatten-layer\"),\n tf.keras.layers.Dense(\n units=hp.Int(\"dense-layer-units\", min_value=32, max_value=128, step=16),\n kernel_regularizer=\"l2\",\n activation=\"relu\",\n name=\"dense-layer\",\n ),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(units=10, activation=\"softmax\", name=\"output-layer\"),\n ]\n )\n\n model.compile(\n optimizer=tf.keras.optimizers.Adam(\n learning_rate=hp.Choice(\n \"learning-rate\", values=[1e-3, 1e-4, 2 * 1e-4, 4 * 1e-4]\n )\n ),\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n metrics=[\"accuracy\"],\n )\n\n return model", "_____no_output_____" ], [ "# BayesianOptimization tuning with Gaussian process\n# THERE IS A BUG HERE: https://github.com/keras-team/keras-tuner/pull/655\n\n# tuner = kt.BayesianOptimization(\n# cnn_model_builder,\n# objective=\"val_accuracy\",\n# max_trials=5, # the total number of trials (model configurations) to test at most\n# allow_new_entries=True,\n# tune_new_entries=True,\n# seed=SEED,\n# directory=\"hparam-tuning\",\n# project_name=\"cnn\",\n# )", "_____no_output_____" ], [ "# Li, Lisha, and Kevin Jamieson.\n# \"Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization.\"\n# Journal of Machine Learning Research 18 (2018): 1-52.\n# https://jmlr.org/papers/v18/16-558.html\ntuner = kt.Hyperband(\n cnn_model_builder,\n objective=\"val_accuracy\",\n max_epochs=50, # the maximum number of epochs to train one model\n seed=SEED,\n directory=\"hparam-tuning\",\n project_name=\"cnn\",\n)", "_____no_output_____" ], [ "tuner.search_space_summary()", "Search space summary\nDefault search space size: 6\n1st-filter (Int)\n{'default': None, 'conditions': [], 'min_value': 32, 'max_value': 128, 'step': 16, 'sampling': None}\n1st-dropout (Float)\n{'default': 0.0, 'conditions': [], 'min_value': 0.0, 'max_value': 0.4, 'step': 0.1, 'sampling': None}\n2nd-filter (Int)\n{'default': None, 'conditions': [], 'min_value': 32, 'max_value': 64, 'step': 16, 'sampling': None}\n2nd-dropout (Float)\n{'default': 0.0, 'conditions': [], 'min_value': 0.0, 'max_value': 0.4, 'step': 0.1, 'sampling': None}\ndense-layer-units (Int)\n{'default': None, 'conditions': [], 'min_value': 32, 'max_value': 128, 'step': 16, 'sampling': None}\nlearning-rate (Choice)\n{'default': 0.001, 'conditions': [], 'values': [0.001, 0.0001, 0.0002, 0.0004], 'ordered': True}\n" ], [ "stop_early = tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=5)", "_____no_output_____" ], [ "tuner.search(\n train_images, train_labels, epochs=40, validation_split=0.2, callbacks=[stop_early]\n)\n\n# get the optimal hyperparameters\nbest_hps = tuner.get_best_hyperparameters(num_trials=1)[0]\n\nprint(\n f\"\"\"\nThe hyperparameter search is complete. \\n\n\nResults\n=======\n|\n---- optimal number of output filters in the 1st convolution : {best_hps.get('1st-filter')}\n|\n---- optimal first dropout rate : {best_hps.get('1st-dropout')}\n|\n---- optimal number of output filters in the 2nd convolution : {best_hps.get('2nd-filter')}\n|\n---- optimal second dropout rate : {best_hps.get('2nd-dropout')}\n|\n---- optimal number of units in the densely-connected layer : {best_hps.get('dense-layer-units')}\n|\n---- optimal learning rate for the optimizer : {best_hps.get('learning-rate')}\n\"\"\"\n)", "Trial 90 Complete [00h 13m 26s]\nval_accuracy: 0.8956666588783264\n\nBest val_accuracy So Far: 0.9276666641235352\nTotal elapsed time: 11h 27m 19s\nINFO:tensorflow:Oracle triggered exit\n\nThe hyperparameter search is complete. \n\n\nResults\n=======\n|\n---- optimal number of output filters in the 1st convolution : 48\n|\n---- optimal first dropout rate : 0.0\n|\n---- optimal number of output filters in the 2nd convolution : 48\n|\n---- optimal second dropout rate : 0.4\n|\n---- optimal number of units in the densely-connected layer : 96\n|\n---- optimal learning rate for the optimizer : 0.0001\n\n" ] ], [ [ "### Model Selection", "_____no_output_____" ] ], [ [ "model = tuner.get_best_models(num_models=1)[0]\n\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n 1st-convolution (Conv2D) (None, 28, 28, 48) 480 \n \n 1st-max-pooling (MaxPooling (None, 14, 14, 48) 0 \n 2D) \n \n 1st-dropout (Dropout) (None, 14, 14, 48) 0 \n \n 2nd-convolution (Conv2D) (None, 14, 14, 48) 20784 \n \n 2nd-max-pooling (MaxPooling (None, 7, 7, 48) 0 \n 2D) \n \n 2nd-dropout (Dropout) (None, 7, 7, 48) 0 \n \n flatten-layer (Flatten) (None, 2352) 0 \n \n dense-layer (Dense) (None, 96) 225888 \n \n batch_normalization (BatchN (None, 96) 384 \n ormalization) \n \n output-layer (Dense) (None, 10) 970 \n \n=================================================================\nTotal params: 248,506\nTrainable params: 248,314\nNon-trainable params: 192\n_________________________________________________________________\n" ], [ "tf.keras.utils.plot_model(\n model, to_file=\"static/cnn_model.png\", show_shapes=True, show_layer_names=True\n)", "_____no_output_____" ], [ "clean_up(model)", "_____no_output_____" ], [ "# build the model with the optimal hyperparameters and train it on the data for 50 epochs\nmodel = tuner.hypermodel.build(best_hps)\nhistory = model.fit(train_images, train_labels, epochs=50, validation_split=0.2)\n\n# keep best epoch\nval_acc_per_epoch = history.history[\"val_accuracy\"]\nbest_epoch = val_acc_per_epoch.index(max(val_acc_per_epoch)) + 1\nprint(\"Best epoch: %d\" % (best_epoch,))", "WARNING:tensorflow:Detecting that an object or model or tf.train.Checkpoint is being deleted with unrestored values. See the following logs for the specific values in question. To silence these warnings, use `status.expect_partial()`. See https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#restorefor details about the status object returned by the restore function.\nWARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.iter\nWARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_1\nWARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.beta_2\nWARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.decay\nWARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.learning_rate\nEpoch 1/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 2.2517 - accuracy: 0.7679 - val_loss: 1.5374 - val_accuracy: 0.8664\nEpoch 2/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 1.3132 - accuracy: 0.8569 - val_loss: 1.0355 - val_accuracy: 0.8827\nEpoch 3/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.9358 - accuracy: 0.8724 - val_loss: 0.7820 - val_accuracy: 0.8926\nEpoch 4/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.7357 - accuracy: 0.8842 - val_loss: 0.6457 - val_accuracy: 0.8957\nEpoch 5/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.6251 - accuracy: 0.8891 - val_loss: 0.5676 - val_accuracy: 0.9002\nEpoch 6/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.5539 - accuracy: 0.8944 - val_loss: 0.5082 - val_accuracy: 0.9044\nEpoch 7/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.5025 - accuracy: 0.8990 - val_loss: 0.4655 - val_accuracy: 0.9081\nEpoch 8/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.4669 - accuracy: 0.9033 - val_loss: 0.4334 - val_accuracy: 0.9151\nEpoch 9/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.4379 - accuracy: 0.9080 - val_loss: 0.4196 - val_accuracy: 0.9127\nEpoch 10/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.4183 - accuracy: 0.9109 - val_loss: 0.5503 - val_accuracy: 0.8722\nEpoch 11/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.4016 - accuracy: 0.9123 - val_loss: 0.3869 - val_accuracy: 0.9178\nEpoch 12/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3861 - accuracy: 0.9144 - val_loss: 0.3842 - val_accuracy: 0.9162\nEpoch 13/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3784 - accuracy: 0.9153 - val_loss: 0.3840 - val_accuracy: 0.9150\nEpoch 14/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3672 - accuracy: 0.9182 - val_loss: 0.3747 - val_accuracy: 0.9151\nEpoch 15/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3611 - accuracy: 0.9201 - val_loss: 0.3741 - val_accuracy: 0.9149\nEpoch 16/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3486 - accuracy: 0.9220 - val_loss: 0.3546 - val_accuracy: 0.9194\nEpoch 17/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3457 - accuracy: 0.9222 - val_loss: 0.3609 - val_accuracy: 0.9146\nEpoch 18/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3413 - accuracy: 0.9218 - val_loss: 0.3511 - val_accuracy: 0.9188\nEpoch 19/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3354 - accuracy: 0.9239 - val_loss: 0.3449 - val_accuracy: 0.9186\nEpoch 20/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3245 - accuracy: 0.9271 - val_loss: 0.3574 - val_accuracy: 0.9183\nEpoch 21/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3248 - accuracy: 0.9265 - val_loss: 0.3435 - val_accuracy: 0.9197\nEpoch 22/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3189 - accuracy: 0.9282 - val_loss: 0.3430 - val_accuracy: 0.9199\nEpoch 23/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3195 - accuracy: 0.9269 - val_loss: 0.3458 - val_accuracy: 0.9186\nEpoch 24/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3143 - accuracy: 0.9298 - val_loss: 0.3332 - val_accuracy: 0.9221\nEpoch 25/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3102 - accuracy: 0.9287 - val_loss: 0.3339 - val_accuracy: 0.9206\nEpoch 26/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3069 - accuracy: 0.9313 - val_loss: 0.3319 - val_accuracy: 0.9218\nEpoch 27/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3072 - accuracy: 0.9298 - val_loss: 0.3362 - val_accuracy: 0.9213\nEpoch 28/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.3035 - accuracy: 0.9309 - val_loss: 0.3366 - val_accuracy: 0.9208\nEpoch 29/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2981 - accuracy: 0.9332 - val_loss: 0.3330 - val_accuracy: 0.9197\nEpoch 30/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2988 - accuracy: 0.9332 - val_loss: 0.3494 - val_accuracy: 0.9157\nEpoch 31/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2978 - accuracy: 0.9330 - val_loss: 0.3317 - val_accuracy: 0.9228\nEpoch 32/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2947 - accuracy: 0.9348 - val_loss: 0.3289 - val_accuracy: 0.9237\nEpoch 33/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2979 - accuracy: 0.9327 - val_loss: 0.3313 - val_accuracy: 0.9229\nEpoch 34/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2957 - accuracy: 0.9321 - val_loss: 0.3367 - val_accuracy: 0.9188\nEpoch 35/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2935 - accuracy: 0.9351 - val_loss: 0.3409 - val_accuracy: 0.9177\nEpoch 36/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2894 - accuracy: 0.9359 - val_loss: 0.3307 - val_accuracy: 0.9237\nEpoch 37/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2867 - accuracy: 0.9374 - val_loss: 0.3294 - val_accuracy: 0.9220\nEpoch 38/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2866 - accuracy: 0.9368 - val_loss: 0.3347 - val_accuracy: 0.9214\nEpoch 39/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2897 - accuracy: 0.9353 - val_loss: 0.3304 - val_accuracy: 0.9205\nEpoch 40/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2850 - accuracy: 0.9373 - val_loss: 0.3295 - val_accuracy: 0.9245\nEpoch 41/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2802 - accuracy: 0.9379 - val_loss: 0.3278 - val_accuracy: 0.9242\nEpoch 42/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2847 - accuracy: 0.9376 - val_loss: 0.3341 - val_accuracy: 0.9178\nEpoch 43/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2797 - accuracy: 0.9385 - val_loss: 0.3295 - val_accuracy: 0.9194\nEpoch 44/50\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2811 - accuracy: 0.9383 - val_loss: 0.3222 - val_accuracy: 0.9239\nEpoch 45/50\n1500/1500 [==============================] - 51s 34ms/step - loss: 0.2758 - accuracy: 0.9410 - val_loss: 0.3143 - val_accuracy: 0.9268\nEpoch 46/50\n1500/1500 [==============================] - 48s 32ms/step - loss: 0.2802 - accuracy: 0.9394 - val_loss: 0.3296 - val_accuracy: 0.9226\nEpoch 47/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2752 - accuracy: 0.9414 - val_loss: 0.3292 - val_accuracy: 0.9211\nEpoch 48/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2753 - accuracy: 0.9403 - val_loss: 0.3254 - val_accuracy: 0.9227\nEpoch 49/50\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2774 - accuracy: 0.9396 - val_loss: 0.3200 - val_accuracy: 0.9269\nEpoch 50/50\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.2778 - accuracy: 0.9384 - val_loss: 0.3332 - val_accuracy: 0.9227\nBest epoch: 49\n" ], [ "clean_up(model)", "_____no_output_____" ], [ "hypermodel = tuner.hypermodel.build(best_hps)\n\n# retrain the model\nhistory = hypermodel.fit(\n train_images, train_labels, epochs=best_epoch, validation_split=0.2\n)", "Epoch 1/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 2.2733 - accuracy: 0.7600 - val_loss: 1.5262 - val_accuracy: 0.8676\nEpoch 2/49\n1500/1500 [==============================] - 44s 29ms/step - loss: 1.2994 - accuracy: 0.8566 - val_loss: 1.0114 - val_accuracy: 0.8851\nEpoch 3/49\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.9093 - accuracy: 0.8751 - val_loss: 0.7598 - val_accuracy: 0.8908\nEpoch 4/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.7066 - accuracy: 0.8870 - val_loss: 0.6278 - val_accuracy: 0.8938\nEpoch 5/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.5968 - accuracy: 0.8920 - val_loss: 0.5291 - val_accuracy: 0.9062\nEpoch 6/49\n1500/1500 [==============================] - 44s 29ms/step - loss: 0.5282 - accuracy: 0.8985 - val_loss: 0.4824 - val_accuracy: 0.9093\nEpoch 7/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.4815 - accuracy: 0.9023 - val_loss: 0.4622 - val_accuracy: 0.9040\nEpoch 8/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.4491 - accuracy: 0.9063 - val_loss: 0.4191 - val_accuracy: 0.9133\nEpoch 9/49\n1500/1500 [==============================] - 47s 31ms/step - loss: 0.4210 - accuracy: 0.9121 - val_loss: 0.4024 - val_accuracy: 0.9149\nEpoch 10/49\n1500/1500 [==============================] - 47s 31ms/step - loss: 0.4012 - accuracy: 0.9129 - val_loss: 0.4011 - val_accuracy: 0.9110\nEpoch 11/49\n1500/1500 [==============================] - 47s 31ms/step - loss: 0.3866 - accuracy: 0.9150 - val_loss: 0.3868 - val_accuracy: 0.9137\nEpoch 12/49\n1500/1500 [==============================] - 46s 31ms/step - loss: 0.3756 - accuracy: 0.9176 - val_loss: 0.3857 - val_accuracy: 0.9111\nEpoch 13/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3633 - accuracy: 0.9193 - val_loss: 0.3706 - val_accuracy: 0.9168\nEpoch 14/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3549 - accuracy: 0.9221 - val_loss: 0.3553 - val_accuracy: 0.9202\nEpoch 15/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3488 - accuracy: 0.9227 - val_loss: 0.3568 - val_accuracy: 0.9171\nEpoch 16/49\n1500/1500 [==============================] - 47s 32ms/step - loss: 0.3394 - accuracy: 0.9246 - val_loss: 0.3503 - val_accuracy: 0.9199\nEpoch 17/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3332 - accuracy: 0.9245 - val_loss: 0.3479 - val_accuracy: 0.9184\nEpoch 18/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3288 - accuracy: 0.9264 - val_loss: 0.3427 - val_accuracy: 0.9192\nEpoch 19/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3240 - accuracy: 0.9268 - val_loss: 0.3419 - val_accuracy: 0.9218\nEpoch 20/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3176 - accuracy: 0.9291 - val_loss: 0.3438 - val_accuracy: 0.9201\nEpoch 21/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3168 - accuracy: 0.9294 - val_loss: 0.3391 - val_accuracy: 0.9215\nEpoch 22/49\n1500/1500 [==============================] - 46s 30ms/step - loss: 0.3100 - accuracy: 0.9313 - val_loss: 0.3367 - val_accuracy: 0.9224\nEpoch 23/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3081 - accuracy: 0.9322 - val_loss: 0.3269 - val_accuracy: 0.9254\nEpoch 24/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3057 - accuracy: 0.9327 - val_loss: 0.3306 - val_accuracy: 0.9228\nEpoch 25/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3059 - accuracy: 0.9319 - val_loss: 0.3326 - val_accuracy: 0.9233\nEpoch 26/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2982 - accuracy: 0.9337 - val_loss: 0.3412 - val_accuracy: 0.9205\nEpoch 27/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.3001 - accuracy: 0.9329 - val_loss: 0.3295 - val_accuracy: 0.9233\nEpoch 28/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2958 - accuracy: 0.9350 - val_loss: 0.3255 - val_accuracy: 0.9234\nEpoch 29/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2948 - accuracy: 0.9346 - val_loss: 0.3513 - val_accuracy: 0.9168\nEpoch 30/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2913 - accuracy: 0.9365 - val_loss: 0.3322 - val_accuracy: 0.9220\nEpoch 31/49\n1500/1500 [==============================] - 46s 31ms/step - loss: 0.2910 - accuracy: 0.9359 - val_loss: 0.3226 - val_accuracy: 0.9250\nEpoch 32/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2887 - accuracy: 0.9354 - val_loss: 0.3283 - val_accuracy: 0.9233\nEpoch 33/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2883 - accuracy: 0.9364 - val_loss: 0.3238 - val_accuracy: 0.9240\nEpoch 34/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2845 - accuracy: 0.9377 - val_loss: 0.3277 - val_accuracy: 0.9233\nEpoch 35/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2828 - accuracy: 0.9386 - val_loss: 0.3199 - val_accuracy: 0.9262\nEpoch 36/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2807 - accuracy: 0.9390 - val_loss: 0.3229 - val_accuracy: 0.9259\nEpoch 37/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2823 - accuracy: 0.9393 - val_loss: 0.3200 - val_accuracy: 0.9261\nEpoch 38/49\n1500/1500 [==============================] - 47s 31ms/step - loss: 0.2841 - accuracy: 0.9376 - val_loss: 0.3268 - val_accuracy: 0.9259\nEpoch 39/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2802 - accuracy: 0.9388 - val_loss: 0.3297 - val_accuracy: 0.9229\nEpoch 40/49\n1500/1500 [==============================] - 44s 30ms/step - loss: 0.2809 - accuracy: 0.9391 - val_loss: 0.3361 - val_accuracy: 0.9213\nEpoch 41/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2760 - accuracy: 0.9408 - val_loss: 0.3362 - val_accuracy: 0.9231\nEpoch 42/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2763 - accuracy: 0.9407 - val_loss: 0.3255 - val_accuracy: 0.9236\nEpoch 43/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2753 - accuracy: 0.9422 - val_loss: 0.3491 - val_accuracy: 0.9167\nEpoch 44/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2723 - accuracy: 0.9423 - val_loss: 0.3369 - val_accuracy: 0.9214\nEpoch 45/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2752 - accuracy: 0.9411 - val_loss: 0.3162 - val_accuracy: 0.9283\nEpoch 46/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2690 - accuracy: 0.9425 - val_loss: 0.3180 - val_accuracy: 0.9265\nEpoch 47/49\n1500/1500 [==============================] - 46s 31ms/step - loss: 0.2717 - accuracy: 0.9417 - val_loss: 0.3248 - val_accuracy: 0.9270\nEpoch 48/49\n1500/1500 [==============================] - 45s 30ms/step - loss: 0.2697 - accuracy: 0.9432 - val_loss: 0.3206 - val_accuracy: 0.9284\nEpoch 49/49\n1500/1500 [==============================] - 47s 31ms/step - loss: 0.2700 - accuracy: 0.9426 - val_loss: 0.3207 - val_accuracy: 0.9266\n" ] ], [ [ "### Evaluation", "_____no_output_____" ] ], [ [ "eval_result = hypermodel.evaluate(test_images, test_labels, verbose=3)\nprint(\"[test loss, test accuracy]:\", eval_result)", "[test loss, test accuracy]: [0.33750301599502563, 0.9222999811172485]\n" ], [ "def plot_history(hs, epochs, metric):\n print()\n plt.style.use(\"dark_background\")\n plt.rcParams[\"figure.figsize\"] = [15, 8]\n plt.rcParams[\"font.size\"] = 16\n plt.clf()\n for label in hs:\n plt.plot(\n hs[label].history[metric],\n label=\"{0:s} train {1:s}\".format(label, metric),\n linewidth=2,\n )\n plt.plot(\n hs[label].history[\"val_{0:s}\".format(metric)],\n label=\"{0:s} validation {1:s}\".format(label, metric),\n linewidth=2,\n )\n x_ticks = np.arange(0, epochs + 1, epochs / 10)\n x_ticks[0] += 1\n plt.xticks(x_ticks)\n plt.ylim((0, 1))\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\" if metric == \"loss\" else \"Accuracy\")\n plt.legend()\n plt.show()", "_____no_output_____" ], [ "print(\"Train Loss : {0:.5f}\".format(history.history[\"loss\"][-1]))\nprint(\"Validation Loss : {0:.5f}\".format(history.history[\"val_loss\"][-1]))\nprint(\"Test Loss : {0:.5f}\".format(eval_result[0]))\nprint(\"-------------------\")\nprint(\"Train Accuracy : {0:.5f}\".format(history.history[\"accuracy\"][-1]))\nprint(\"Validation Accuracy : {0:.5f}\".format(history.history[\"val_accuracy\"][-1]))\nprint(\"Test Accuracy : {0:.5f}\".format(eval_result[1]))\n\n# Plot train and validation error per epoch.\nplot_history(hs={\"CNN\": history}, epochs=best_epoch, metric=\"loss\")\nplot_history(hs={\"CNN\": history}, epochs=best_epoch, metric=\"accuracy\")", "Train Loss : 0.26999\nValidation Loss : 0.32069\nTest Loss : 0.33750\n-------------------\nTrain Accuracy : 0.94256\nValidation Accuracy : 0.92658\nTest Accuracy : 0.92230\n\n" ], [ "def plot_confusion_matrix(\n cm, classes, normalize=False, title=\"Confusion matrix\", cmap=plt.cm.PuBuGn\n):\n\n plt.style.use(\"default\")\n plt.rcParams[\"figure.figsize\"] = [11, 9]\n plt.imshow(cm, interpolation=\"nearest\", cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=90)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\n\n thresh = cm.max() / 2.0\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(\n j,\n i,\n cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\",\n )\n\n plt.tight_layout()\n plt.ylabel(\"True label\")\n plt.xlabel(\"Predicted label\")", "_____no_output_____" ], [ "# Predict the values from the validation dataset\nY_pred = hypermodel.predict(test_images)\n\n# Convert predictions classes to one hot vectors\nY_pred_classes = np.argmax(Y_pred, axis=1)\n\n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(test_labels, Y_pred_classes)\n\n# plot the confusion matrix\nplot_confusion_matrix(\n confusion_mtx,\n classes=class_names,\n)", "_____no_output_____" ], [ "incorrect = []\nfor i in range(len(test_labels)):\n if not Y_pred_classes[i] == test_labels[i]:\n incorrect.append(i)\n if len(incorrect) == 4:\n break", "_____no_output_____" ], [ "fig, ax = plt.subplots(2, 2, figsize=(12, 6))\nfig.set_size_inches(10, 10)\nax[0, 0].imshow(test_images[incorrect[0]].reshape(28, 28), cmap=\"gray\")\n\nax[0, 0].set_title(\n \"Predicted Label : \"\n + class_names[Y_pred_classes[incorrect[0]]]\n + \"\\n\"\n + \"Actual Label : \"\n + class_names[test_labels[incorrect[0]]]\n)\nax[0, 1].imshow(test_images[incorrect[1]].reshape(28, 28), cmap=\"gray\")\nax[0, 1].set_title(\n \"Predicted Label : \"\n + class_names[Y_pred_classes[incorrect[1]]]\n + \"\\n\"\n + \"Actual Label : \"\n + class_names[test_labels[incorrect[1]]]\n)\nax[1, 0].imshow(test_images[incorrect[2]].reshape(28, 28), cmap=\"gray\")\nax[1, 0].set_title(\n \"Predicted Label : \"\n + class_names[Y_pred_classes[incorrect[2]]]\n + \"\\n\"\n + \"Actual Label : \"\n + class_names[test_labels[incorrect[2]]]\n)\nax[1, 1].imshow(test_images[incorrect[3]].reshape(28, 28), cmap=\"gray\")\nax[1, 1].set_title(\n \"Predicted Label : \"\n + class_names[Y_pred_classes[incorrect[3]]]\n + \"\\n\"\n + \"Actual Label : \"\n + class_names[test_labels[incorrect[3]]]\n)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbe172257b13b187d3e463e5a3846471d817da57
360,574
ipynb
Jupyter Notebook
Code/4.Construct_validity_(figure_6).ipynb
jeroenvanbaar/ReciprocityMotives
9a6708f723a15e3cc614be9f438be42c6cc1a715
[ "MIT" ]
1
2021-01-19T23:50:13.000Z
2021-01-19T23:50:13.000Z
Code/4.Construct_validity_(figure_6).ipynb
jeroenvanbaar/ReciprocityMotives
9a6708f723a15e3cc614be9f438be42c6cc1a715
[ "MIT" ]
null
null
null
Code/4.Construct_validity_(figure_6).ipynb
jeroenvanbaar/ReciprocityMotives
9a6708f723a15e3cc614be9f438be42c6cc1a715
[ "MIT" ]
1
2021-01-19T23:50:39.000Z
2021-01-19T23:50:39.000Z
379.951528
109,116
0.922279
[ [ [ "%matplotlib inline\n\n# Packages\nimport os, glob, scipy, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Project directory\nbase_dir = os.path.realpath('..')\nprint(base_dir)\n\n# Project-specific functions\nfunDir = os.path.join(base_dir,'Code/Functions')\nprint(funDir)\nsys.path.append(funDir)\nimport choiceModels, costFunctions, penalizedModelFit, simulateModel\n\n# General-use python functions\ndbPath = '/'.join(base_dir.split('/')[0:4])\nsys.path.append('%s/Python'%dbPath)\nimport FigureTools", "/Users/jeroen/Dropbox (Brown)/PhD/0. Working folder/HMTG_followUp_final/ShareDataCode\n/Users/jeroen/Dropbox (Brown)/PhD/0. Working folder/HMTG_followUp_final/ShareDataCode/Code/Functions\n" ] ], [ [ "## Choose set", "_____no_output_____" ], [ "#### Select subs who are constant in their study 1 cluster", "_____no_output_____" ] ], [ [ "model = 'MP_ppSOE'\nstudy = 1\nclusters_4 = pd.read_csv(os.path.join(base_dir,'Data/Study1/ComputationalModel',\n 'ParamsClusters_study-1_baseMult-4_model-MP_ppSOE_precision-100.csv'),index_col=0)[\n ['sub','ClustName']]\nclusters_6 = pd.read_csv(os.path.join(base_dir,'Data/Study1/ComputationalModel',\n 'ParamsClusters_study-1_baseMult-6_model-MP_ppSOE_precision-100.csv'),index_col=0)[\n ['sub','ClustName']]\nexclude = np.array(pd.read_csv(os.path.join(base_dir,'Data/Study1/HMTG/exclude.csv'),index_col=None,header=None).T)[0]\nclusters = clusters_4.merge(clusters_6,on='sub')\nclusters = clusters.loc[~clusters['sub'].isin(exclude)]\nclusters.columns = ['sub','x4','x6']\nclusters['stable'] = 1*(clusters['x4']==clusters['x6'])\nclusters.head()\nclusters = clusters[['sub','x4','stable']]\nclusters.columns = ['sub','cluster','stable']\nclusters_study2 = pd.read_csv(os.path.join(base_dir,'Data/Study2/ComputationalModel',\n 'ParamsClusters_study-2_model-MP_ppSOE_precision-100.csv'),index_col=0)[\n ['sub','ClustName']]\nexclude = np.array(pd.read_csv(os.path.join(base_dir,'Data/Study2/HMTG/exclude.csv'),index_col=0,header=0).T)[0]\nclusters_study2 = clusters_study2.loc[~clusters_study2['sub'].isin(exclude)]\nclusters_study2.columns = ['sub','cluster']\nclusters_study2['stable'] = 1\nclusters = clusters.append(clusters_study2)\nclusters.head()", "_____no_output_____" ], [ "print(clusters.query('sub < 150')['stable'].sum())\nprint(clusters.query('sub > 150')['stable'].sum())\nprint(clusters['stable'].sum())", "74\n55\n129\n" ] ], [ [ "#### Load self-reported strategy", "_____no_output_____" ] ], [ [ "strat_1 = pd.read_csv(os.path.join(base_dir,\n 'Data/Study%i/SelfReportStrategy/parsed.csv'%1),index_col=0)\nstrat_1['sub'] = strat_1['record']-110000\nstrat_1.replace(to_replace=np.nan,value=0,inplace=True)\nstrat_1.head()\nstrat_2 = pd.read_csv(os.path.join(base_dir,\n 'Data/Study%i/SelfReportStrategy/parsed.csv'%2),index_col=0)\nstrat_2.head()\nstrat_2.replace(to_replace=np.nan,value=0,inplace=True)\nstrat_2_map = pd.read_csv(os.path.join(base_dir,'Data/Study2/SubCastorMap.csv'),index_col=None,header=None)\nstrat_2_map.columns = ['sub','record']\nstrat_2['record'] = strat_2['record'].astype(int)\nstrat_2 = strat_2.merge(strat_2_map,on='record')\nstrat_2.head()\n\nstrat_both = strat_1.append(strat_2)\nstrat_both = strat_both[['sub','GR','IA','GA','Altruism','AdvantEquity','DoubleInv','MoralOpport','Reciprocity','Return10','ReturnInv','RiskAssess','SplitEndow']]\nstrat_both.replace(to_replace=np.nan,value=0,inplace=True)\nstrat_both.head()\n\n### Merge with clustering and additional measures\nstrat_use = strat_both.merge(clusters,on='sub')\nstrat_use = strat_use.loc[(strat_use['stable']==1)]\nstrat_use.head()\nprint (strat_use.shape)", "/Users/jeroen/anaconda3/envs/hmtg_fu/lib/python3.8/site-packages/pandas/core/frame.py:7134: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\nof pandas will change to not sort by default.\n\nTo accept the future behavior, pass 'sort=False'.\n\nTo retain the current behavior and silence the warning, pass 'sort=True'.\n\n return concat(\n" ] ], [ [ "## Plot", "_____no_output_____" ] ], [ [ "strategyList = ['GR','IA','GA','Altruism','AdvantEquity','DoubleInv','MoralOpport',\n 'Reciprocity','Return10','ReturnInv','RiskAssess','SplitEndow']\nallStrategies_melted = strat_use.melt(id_vars=['sub','cluster'],value_vars=strategyList,\n var_name='Strategy',value_name='Weight')\nallStrategies_melted.head()", "_____no_output_____" ], [ "FigureTools.mydesign(context='poster')\nsns.set_palette('tab10',len(strategyList))\nstrategyListOrder = [list(strategyList).index(list(strat_use.iloc[:,1:-2].mean().sort_values(\n ascending=False).index)[i]) for i in range(len(strategyList))]\nstrategyListOrdered = [strategyList[i] for i in strategyListOrder]\nfig,ax = plt.subplots(1,1,figsize=[16,5])\nsns.barplot(data=allStrategies_melted,x='Strategy',y='Weight',ax=ax,\n errwidth = 1, capsize = 0.1,errcolor='k',alpha=.9,\n hue='cluster',hue_order=['GR','GA','IA','MO'],\n order = strategyListOrdered,\n )\nstrategyListOrdered_renamed = list(['50-50','Keep','Expectation'])+strategyListOrdered[3:]\nplt.xticks(range(len(strategyList)),strategyListOrdered_renamed,rotation=45);\nfor i,strat in enumerate(strategyListOrdered):\n allImp = allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat),'Weight']\n stats = scipy.stats.f_oneway(\n allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']=='GR'),'Weight'],\n allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']=='GA'),'Weight'],\n allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']=='IA'),'Weight'],\n allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']=='MO'),'Weight'])\n if stats[1] < 0.05:\n FigureTools.add_sig_markers(ax,relationships=[[i-.2,i+.2,stats[1]]],linewidth=0,ystart=70)\n print ('%s: F = %.2f, p = %.4f'%(strat,stats[0],stats[1]))\nplt.xlabel('Self-reported strategy')\nplt.ylabel('Importance (%)')\nplt.legend(title='Model-derived strategy')", "IA: F = 33.49, p = 0.0000\nGR: F = 52.51, p = 0.0000\nGA: F = 13.63, p = 0.0000\n" ], [ "groups = ['GR','GA','IA','MO']\npairs = [[0,1],[0,2],[0,3],[1,2],[2,3],[1,3]]\nfor strat in ['IA','GA','GR']:\n print (strat)\n stratResults = pd.DataFrame(columns=['group1','group2','t','df','p'])\n for pair in pairs:\n group1 = groups[pair[0]]\n group2 = groups[pair[1]]\n samp1 = allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']==group1),'Weight']\n samp2 = allStrategies_melted.loc[(allStrategies_melted['Strategy']==strat) & \n (allStrategies_melted['cluster']==group2),'Weight']\n df = len(samp1) + len(samp2) -1\n stats = scipy.stats.ttest_ind(samp1,samp2)\n# print '%s vs %s: t(%i) = %.2f, p = %.4f, p-corr = %.4f'%(\n# group1,group2,df,stats[0],stats[1],stats[1]*len(pairs))\n stratResults = stratResults.append(pd.DataFrame([[group1,group2,df,stats[0],stats[1]]],\n columns=stratResults.columns))\n stratResults = stratResults.sort_values(by='p',ascending=False)\n stratResults['p_holm'] = np.multiply(np.array(stratResults['p']),np.arange(1,7))\n print (stratResults)", "IA\n group1 group2 t df p p_holm\n0 GA MO 73 1.542849 1.272515e-01 1.272515e-01\n0 GA IA 53 -3.094441 3.171295e-03 6.342590e-03\n0 GR MO 74 -5.042293 3.238856e-06 9.716569e-06\n0 GR GA 30 -6.146267 1.067144e-06 4.268575e-06\n0 IA MO 97 6.961503 4.161373e-10 2.080686e-09\n0 GR IA 54 -8.614668 1.181892e-11 7.091355e-11\nGA\n group1 group2 t df p p_holm\n0 GR IA 54 -1.327026 0.190189 0.190189\n0 GA MO 73 1.403849 0.164662 0.329325\n0 GR GA 30 -3.926371 0.000488 0.001465\n0 GR MO 74 -4.120314 0.000099 0.000395\n0 GA IA 53 4.707956 0.000019 0.000095\n0 IA MO 97 -4.699145 0.000009 0.000052\nGR\n group1 group2 t df p p_holm\n0 GA MO 73 -1.932614 5.721764e-02 5.721764e-02\n0 GA IA 53 2.224236 3.049888e-02 6.099776e-02\n0 GR GA 30 7.082825 8.594400e-08 2.578320e-07\n0 IA MO 97 -5.848842 6.831512e-08 2.732605e-07\n0 GR MO 74 7.888962 2.276212e-11 1.138106e-10\n0 GR IA 54 14.318761 7.410539e-20 4.446323e-19\n" ], [ "savedat = allStrategies_melted.loc[allStrategies_melted['Strategy'].isin(['IA','GA','GR','Altruism'])].reset_index(drop=True)\nsavedat.to_csv(base_dir+'/Data/Pooled/SelfReportStrategies/SelfReportStrategies2.csv')", "_____no_output_____" ] ], [ [ "## Plot by group in 3-strat space", "_____no_output_____" ] ], [ [ "stratsInclude = ['GR', 'IA', 'GA']\ndat = allStrategies_melted.loc[allStrategies_melted['Strategy'].isin(stratsInclude)]\ndat.head()", "_____no_output_____" ], [ "sns.barplot(data=dat,x='cluster',y='Weight',\n errwidth = 1, capsize = 0.1,errcolor='k',alpha=.9,\n hue='Strategy',hue_order=stratsInclude,\n order = ['GR','GA','IA','MO'],\n )\nplt.legend(loc=[1.1,.5])\n# plt.legend(['Keep','50-50','Expectation','Altruism'])", "_____no_output_____" ], [ "dat_piv = dat.pivot_table(index=['sub','cluster'],columns='Strategy',values='Weight').reset_index()\ndat_piv.head()", "_____no_output_____" ], [ "sns.lmplot(data=dat_piv,x='GA',y='IA',hue='cluster',fit_reg=False)", "_____no_output_____" ], [ "FigureTools.mydesign()\nsns.set_context('talk')\ncolors = sns.color_palette('tab10',4)\nmarkers = ['o','*','s','d']\nsizes = [70,170,60,80]\nclusters = ['GR','GA','IA','MO']\nfig,ax = plt.subplots(1,3,figsize=[12,4])\naxisContents = [['IA','GA'],['GA','GR'],['GR','IA']]\nfaceWhiteFactor = 3\nfaceColors = colors\nfor i in range(faceWhiteFactor):\n faceColors = np.add(faceColors,np.tile([1,1,1],[4,1]))\nfaceColors = faceColors/(faceWhiteFactor+1)\nstratTranslate = dict(zip(['IA','GA','GR'],['50-50','Expectation','Keep']))\nfor i in range(3):\n points = []\n axCur = ax[i]\n for clustInd,clust in enumerate(clusters):\n print (clust)\n x_point = dat_piv.loc[dat_piv['cluster']==clust,axisContents[i][0]].mean()\n y_point = dat_piv.loc[dat_piv['cluster']==clust,axisContents[i][1]].mean()\n handle = axCur.scatter(x_point,y_point, alpha=1,zorder=10, linewidth=2, edgecolor=colors[clustInd],\n c=[faceColors[clustInd]], s=sizes[clustInd], marker=markers[clustInd])\n points.append(handle)\n x_sterr = scipy.stats.sem(dat_piv.loc[dat_piv['cluster']==clust,axisContents[i][0]])\n y_sterr = scipy.stats.sem(dat_piv.loc[dat_piv['cluster']==clust,axisContents[i][1]])\n x_range = [x_point - x_sterr, x_point + x_sterr]\n y_range = [y_point - y_sterr, y_point + y_sterr]\n axCur.plot(x_range,[y_point,y_point],c=colors[clustInd],linewidth=2,zorder=1)#,alpha=.5)\n axCur.plot([x_point,x_point],y_range,c=colors[clustInd],linewidth=2,zorder=1)#,alpha=.5)\n axCur.set(xlabel = 'Percentage %s'%stratTranslate[axisContents[i][0]],\n ylabel = 'Percentage %s'%stratTranslate[axisContents[i][1]])\nax[2].legend(points,clusters)#,loc=[1.1,.5])\nfor i in range(3):\n ax[i].set(xlim = [0,85], ylim = [0,85], aspect=1)\nplt.tight_layout()\nplt.suptitle('Relative importance of main 3 motives',y=1.05)\nplt.show()\n# FigureTools.mysavefig(fig,'Motives')", "GR\nGA\nIA\nMO\nGR\nGA\nIA\nMO\nGR\nGA\nIA\nMO\n" ] ], [ [ "##### Set up 3d plot", "_____no_output_____" ] ], [ [ "%matplotlib inline\nfrom mpl_toolkits.mplot3d import Axes3D\nFigureTools.mydesign()\nsns.set_style('darkgrid', {\"axes.facecolor\": \"1\"})\nsns.set_context('paper')\ncolors = sns.color_palette('tab10',4)\nmarkers = ['o','*','s','d']\nsizes = [70,170,60,80]\nclusters = ['GR','GA','IA','MO']\nfaceWhiteFactor = 3\nfaceColors = colors\nfor i in range(faceWhiteFactor):\n faceColors = np.add(faceColors,np.tile([1,1,1],[4,1]))\nfaceColors = faceColors/(faceWhiteFactor+1)\nstratTranslate = dict(zip(['IA','GA','GR'],['50-50','Expectation','Keep']))", "_____no_output_____" ], [ "fig = plt.figure(figsize = [11,8])\nax = fig.add_subplot(111, projection='3d')\nsns.set_context('talk')\n\npoints = []\nfor clustInd,clust in enumerate(clusters):\n dat = dat_piv.query('cluster == @clust')\n means = dat[['IA','GA','GR']].mean().values\n sterrs = scipy.stats.sem(dat[['IA','GA','GR']])\n handle = ax.scatter(*means, linewidth=1, edgecolor=colors[clustInd],\n c=[faceColors[clustInd]], s=sizes[clustInd]/2, marker=markers[clustInd])\n points.append(handle)\n ax.plot([0,means[0]],[means[1],means[1]],[means[2],means[2]],':',color=colors[clustInd])\n ax.plot([means[0],means[0]],[0,means[1]],[means[2],means[2]],':',color=colors[clustInd])\n ax.plot([means[0],means[0]],[means[1],means[1]],[0,means[2]],':',color=colors[clustInd])\n \n ax.plot([means[0] - sterrs[0],means[0] + sterrs[0]], [means[1],means[1]], [means[2],means[2]],\n c=colors[clustInd],linewidth=2,zorder=1)\n ax.plot([means[0],means[0]], [means[1] - sterrs[1],means[1] + sterrs[1]], [means[2],means[2]],\n c=colors[clustInd],linewidth=2,zorder=1)\n ax.plot([means[0],means[0]], [means[1],means[1]], [means[2] - sterrs[2],means[2] + sterrs[2]],\n c=colors[clustInd],linewidth=2,zorder=1)\nax.set(xlabel = '%% %s'%stratTranslate['IA'],\n ylabel = '%% %s'%stratTranslate['GA'],\n zlabel = '%% %s'%stratTranslate['GR'])\nax.legend(points,clusters, title = 'Participant\\ngroup', loc = [1.1,.5], frameon=False)\nax.set(xlim = [0,85], ylim = [0,50], zlim = [0,85])\nplt.title('Self-reported importance of motives',y=1.05)\nplt.tight_layout()\nax.view_init(elev=35,azim=-15) # Or azim -110\nplt.savefig(base_dir + '/Results/Figure6.pdf',bbox_inches='tight')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe1803c31bf4d13901579689a8f4a34f78f3cb4
10,948
ipynb
Jupyter Notebook
ensenso_detect/manikin/cnn_lstm_demo.ipynb
lakehanne/ensenso
10d3cbec97441a2eb2c8335be27764e8a82549cf
[ "MIT" ]
3
2017-04-25T20:32:19.000Z
2021-01-20T09:16:04.000Z
ensenso_detect/manikin/cnn_lstm_demo.ipynb
lakehanne/ensenso
10d3cbec97441a2eb2c8335be27764e8a82549cf
[ "MIT" ]
1
2017-06-28T21:31:25.000Z
2017-07-07T23:44:37.000Z
ensenso_detect/manikin/cnn_lstm_demo.ipynb
lakehanne/ensenso
10d3cbec97441a2eb2c8335be27764e8a82549cf
[ "MIT" ]
2
2017-04-25T20:32:30.000Z
2017-06-19T22:31:36.000Z
49.763636
125
0.487304
[ [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom model import RecurrentModel\nreg = RecurrentModel(inputSize=4096, nHidden=[4096,1024, 64*32], \\\n noutputs=64*32, batchSize=1, ship2gpu=True, \\\n numLayers=1)\n\n# for m in reg.modules(): \n# if(isinstance(m, nn.LSTM)): \n# mkeys = m.state_dict().keys()\n# mvals = m.state_dict().values()\n# init.uniform(mvals[1], 0, 1)\n# print(mvals[1])\n\"\"\"\nfor m in reg.lstm3.modules(): \n for t in m.state_dict().values():\n print init.uniform(t, 0, 1)\n\"\"\"\n\n# for m in reg.modules():\n# if (isinstance, nn.LSTM):\n# keys = m.state_dict().keys\n#weight_ih_l", "_____no_output_____" ], [ "params = list(reg.parameters())\nprint params", "[Parameter containing:\n-6.1764e-03 1.0196e-02 -4.8158e-03 ... -1.3005e-02 1.2572e-02 1.0006e-02\n 5.8714e-03 -1.0709e-02 -1.4068e-02 ... 4.7597e-03 -1.3672e-02 -1.0446e-02\n 3.8936e-03 1.5572e-02 1.0738e-02 ... 1.9629e-03 8.2544e-04 1.5378e-02\n ... ⋱ ... \n-9.6988e-03 5.6114e-03 7.2494e-03 ... -9.7322e-03 -1.4987e-03 -1.5181e-02\n 9.1930e-03 -7.7751e-04 1.0126e-02 ... 7.0993e-03 -9.6946e-03 9.2351e-03\n 1.7392e-03 -3.1567e-03 1.1008e-02 ... 4.8549e-03 -1.4407e-02 1.3779e-02\n[torch.DoubleTensor of size 16384x4096]\n, Parameter containing:\n 3.0674e-03 -1.4418e-02 -1.4713e-02 ... -1.3884e-02 1.5112e-02 -1.5605e-03\n 6.5186e-03 9.7675e-03 -1.0814e-02 ... 7.6088e-03 1.2152e-02 -3.0384e-03\n-1.2199e-02 9.5358e-03 -2.4002e-03 ... -1.1985e-02 -6.3747e-03 1.2077e-02\n ... ⋱ ... \n-8.7445e-03 3.0171e-03 -3.5812e-03 ... 1.2019e-02 1.3638e-02 -8.1813e-03\n-1.3924e-02 1.3511e-02 1.4339e-02 ... -1.0296e-02 -4.0513e-03 -4.2915e-03\n-1.5116e-02 -7.9915e-03 7.7508e-03 ... 1.4098e-02 1.0286e-02 -1.4088e-02\n[torch.DoubleTensor of size 16384x4096]\n, Parameter containing:\n-7.9938e-03 -6.8149e-03 -2.8361e-02 ... 2.2732e-04 8.0911e-03 2.7480e-02\n-5.7078e-03 -3.0018e-02 1.6093e-02 ... -1.0365e-02 -6.9713e-03 2.5716e-02\n-1.3081e-02 2.1478e-02 3.7763e-03 ... 9.1951e-03 2.9470e-02 -1.6416e-02\n ... ⋱ ... \n 1.3396e-02 1.3351e-02 6.1546e-04 ... -3.0222e-02 2.6748e-02 2.6073e-02\n-2.0555e-02 -3.0876e-02 2.3071e-02 ... -9.0544e-03 2.0729e-02 -8.2354e-03\n 1.7304e-02 -1.8979e-02 1.4538e-02 ... -2.9897e-02 -1.4413e-02 -2.1524e-02\n[torch.DoubleTensor of size 4096x4096]\n, Parameter containing:\n 2.4741e-02 -1.5301e-02 2.5316e-02 ... -1.2111e-02 1.0435e-02 -2.8739e-02\n-2.3048e-02 -2.6921e-02 -2.0897e-02 ... -4.4201e-03 3.0935e-02 3.0540e-02\n 2.5862e-02 -1.9326e-02 -2.2926e-02 ... -1.0019e-02 -1.3795e-02 9.1855e-03\n ... ⋱ ... \n 2.8649e-02 2.5118e-02 1.8011e-02 ... -2.0008e-03 1.4374e-02 -2.8311e-02\n 2.0291e-02 4.5106e-03 -1.1679e-02 ... 1.2991e-02 1.5746e-02 -2.6977e-02\n-2.7820e-02 1.8272e-02 -1.6348e-02 ... -1.7788e-02 -7.7549e-03 -1.3663e-02\n[torch.DoubleTensor of size 4096x1024]\n, Parameter containing:\n-1.9138e-02 -9.4376e-03 -2.1603e-02 ... -2.1392e-02 -1.3221e-03 -2.1732e-02\n 7.2356e-03 6.0557e-03 -1.2403e-02 ... -2.3860e-03 1.1154e-02 -3.3996e-03\n-1.0013e-02 3.2242e-03 7.5778e-03 ... 1.1446e-02 1.2351e-02 1.4997e-02\n ... ⋱ ... \n-5.0316e-03 -1.2850e-02 6.2053e-03 ... 2.1595e-02 -2.5359e-03 -6.5198e-03\n 1.9525e-02 -5.4727e-03 -1.0127e-02 ... 5.0508e-03 -1.4952e-03 -5.4373e-03\n-2.7979e-03 -1.5377e-02 -1.3318e-03 ... -7.3602e-03 -8.9475e-03 -3.5579e-03\n[torch.DoubleTensor of size 8192x1024]\n, Parameter containing:\n 1.6421e-05 1.3183e-03 2.9429e-03 ... 1.5533e-02 1.1309e-02 -1.4332e-02\n 3.5590e-03 9.1467e-03 -1.1816e-02 ... -2.8441e-03 1.9235e-02 2.3587e-03\n 1.6672e-02 -1.8863e-02 -1.0777e-02 ... -1.9488e-02 -1.5322e-02 1.6784e-02\n ... ⋱ ... \n 1.3867e-02 -1.6166e-02 4.7729e-03 ... 9.2436e-03 -3.4599e-03 1.4893e-04\n 1.8080e-02 1.3096e-02 -1.9225e-02 ... 8.4135e-03 7.3216e-04 2.1693e-02\n 3.4534e-03 -9.0428e-03 1.6899e-02 ... -2.5820e-04 1.5144e-02 -1.3443e-02\n[torch.DoubleTensor of size 8192x2048]\n]\n" ], [ "for i in range(len(params)):\n init.uniform(params[i], 0, 1)\nprint(list(reg.parameters()))", "[Parameter containing:\n 7.8732e-01 8.7127e-03 2.5498e-01 ... 9.7151e-01 7.0045e-01 8.0179e-01\n 5.9271e-01 8.7199e-01 2.8282e-01 ... 9.2077e-01 2.3692e-02 4.6481e-01\n 3.1488e-01 6.8871e-01 9.7602e-01 ... 5.4705e-01 1.8657e-01 4.4125e-01\n ... ⋱ ... \n 2.3685e-01 4.8616e-01 5.9912e-01 ... 6.3499e-01 5.5828e-01 3.4472e-01\n 4.3522e-01 1.7198e-01 9.3313e-01 ... 3.6230e-01 8.7210e-01 2.7585e-01\n 1.9875e-01 4.4363e-01 2.8850e-01 ... 5.6620e-01 2.1519e-01 3.7712e-01\n[torch.DoubleTensor of size 16384x4096]\n, Parameter containing:\n 5.0426e-01 5.4531e-02 7.8249e-01 ... 8.5079e-01 7.6380e-01 5.5872e-01\n 1.7001e-01 4.9714e-01 1.8019e-01 ... 5.3173e-01 6.0125e-02 5.9271e-01\n 5.6888e-01 1.6904e-01 3.3299e-01 ... 2.0617e-01 8.9110e-01 2.1650e-01\n ... ⋱ ... \n 2.6615e-01 6.7556e-01 9.8385e-04 ... 2.6373e-01 4.0696e-01 5.5842e-01\n 5.8705e-01 9.2699e-01 5.7709e-01 ... 4.3778e-01 1.7824e-01 6.7693e-01\n 5.2773e-01 8.3292e-01 6.0711e-01 ... 5.6245e-01 6.1239e-01 7.6092e-01\n[torch.DoubleTensor of size 16384x4096]\n, Parameter containing:\n 4.5064e-01 2.3110e-01 3.3303e-01 ... 3.3549e-01 8.6444e-01 3.5573e-01\n 4.8742e-02 7.3461e-01 7.5073e-01 ... 2.5214e-01 2.7292e-01 5.6398e-01\n 1.3773e-01 1.6539e-03 5.2152e-01 ... 4.9379e-01 8.0150e-01 6.1325e-01\n ... ⋱ ... \n 3.0222e-01 9.3854e-01 9.8024e-01 ... 2.2727e-01 5.9206e-01 4.1467e-01\n 2.8625e-01 1.5102e-01 6.7757e-01 ... 7.3678e-01 8.7848e-01 3.4654e-01\n 1.3479e-01 5.3564e-02 5.7687e-02 ... 6.4621e-01 7.0807e-01 7.2826e-01\n[torch.DoubleTensor of size 4096x4096]\n, Parameter containing:\n 7.0781e-01 6.3431e-02 3.8171e-01 ... 2.1702e-01 8.9114e-01 6.9316e-01\n 5.5395e-01 7.9579e-02 9.9122e-01 ... 7.3171e-01 5.2518e-01 4.0740e-01\n 8.0593e-01 6.6224e-01 9.1686e-01 ... 1.9911e-01 3.2145e-01 6.8971e-01\n ... ⋱ ... \n 7.4174e-01 6.5799e-01 3.1992e-03 ... 1.8419e-01 6.7892e-01 8.7800e-01\n 4.3848e-01 7.2543e-01 9.0873e-02 ... 6.9933e-01 4.1620e-01 9.5101e-01\n 2.0775e-01 9.0825e-01 3.4861e-01 ... 6.4109e-01 4.0008e-01 6.1257e-01\n[torch.DoubleTensor of size 4096x1024]\n, Parameter containing:\n 9.6045e-01 9.7580e-01 1.7768e-01 ... 4.5329e-01 6.3651e-01 5.2336e-01\n 2.3537e-01 6.6579e-01 3.0231e-01 ... 2.4843e-01 2.8533e-01 7.2911e-01\n 4.2500e-01 2.4578e-02 1.8030e-01 ... 5.0404e-01 2.5446e-01 3.1119e-01\n ... ⋱ ... \n 5.4096e-01 8.7669e-01 7.9158e-01 ... 6.3855e-01 6.9397e-01 9.8296e-01\n 2.1805e-01 1.8647e-01 5.6119e-01 ... 3.8049e-01 9.7390e-01 8.2169e-01\n 8.7761e-01 3.5373e-01 7.3494e-01 ... 5.1408e-01 2.1345e-01 3.5590e-01\n[torch.DoubleTensor of size 8192x1024]\n, Parameter containing:\n 2.1546e-01 5.3919e-01 6.8705e-01 ... 4.3722e-01 9.3209e-01 6.6289e-01\n 5.1668e-01 5.4269e-01 1.6900e-01 ... 7.2303e-01 9.3884e-01 2.8335e-01\n 5.6254e-01 8.1803e-01 1.9909e-01 ... 6.5482e-02 8.0398e-02 5.9281e-01\n ... ⋱ ... \n 1.3541e-01 8.8949e-01 1.7041e-01 ... 6.9329e-01 1.4280e-01 4.4319e-01\n 4.4677e-01 4.0816e-01 6.2033e-01 ... 8.1556e-01 4.9535e-01 7.7868e-01\n 1.1293e-01 7.8041e-01 9.4200e-01 ... 4.3383e-01 2.2709e-01 9.6178e-01\n[torch.DoubleTensor of size 8192x2048]\n]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbe181898e76e02016b9aa5bf1896c92a3c611df
19,030
ipynb
Jupyter Notebook
Skeleton/.ipynb_checkpoints/Untitled-checkpoint.ipynb
tadeleTuli/HARNets
4c81087fff6938d960b9e08b293d3b0ad1a188dd
[ "MIT" ]
null
null
null
Skeleton/.ipynb_checkpoints/Untitled-checkpoint.ipynb
tadeleTuli/HARNets
4c81087fff6938d960b9e08b293d3b0ad1a188dd
[ "MIT" ]
null
null
null
Skeleton/.ipynb_checkpoints/Untitled-checkpoint.ipynb
tadeleTuli/HARNets
4c81087fff6938d960b9e08b293d3b0ad1a188dd
[ "MIT" ]
null
null
null
42.383073
1,939
0.514398
[ [ [ "#!/usr/bin/env python\n# coding: utf-8\n\n'''\nThis module helps to predict new data sets using a trained model\nAuthor: Tadele Belay Tuli, Valay Mukesh Patel, \n\nUniversity of Siegen, Germany (2022)\nLicense: MIT\n'''\n\nimport glob\nimport os\nimport subprocess\nimport pandas as pd\nfrom scipy import stats\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow \nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Activation, Flatten, Dropout\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import load_model\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sn\n\n\n# Lists of methods \ndef merge_rot_pos(df1,df2,label):\n \"\"\"\n This function merges position and orientation of BVH data into CSV format\n \n The output is a concatinated data frame\"\"\"\n # df1 is for rotation and df2 is for position\n df1 = df1.drop(columns=['Time']) # Drop the time coloumn from rotation and postion CSV file.\n df2 = df2.drop(columns=['Time']) \n df_concat = pd.concat([df1, df2], axis=1) # Mereging rotation and position CSV data.\n df_concat = df_concat.dropna()\n df_concat['category'] = label # Adding the associated lable (folder_name) to fetch postion and rotation CSV data. \n return df_concat\n\n\ndef convert_dataset_to_csv(file_loc):\n\n \"\"\"\n Function takes the file from dataset folder and convert it into CSV using BVH-converter library from https://github.com/tekulvw/bvh-converter. \n \"\"\"\n \n for directory in glob.glob(file_loc): # Path of dataset directory.\n for file in glob.glob(directory+\"*.bvh\"): # Fetch each BVH file in dataset directory.\n f = file.split('/') \n command_dir = f[0]+'/'+f[1] \n command_file = f[2] \n command = \"bvh-converter -r \" + command_file # Load BVH to CSV converter.\n subprocess.call(command, shell=True, cwd=command_dir) # Executing BVH TO CSV conveter command with shell. \n #return command\n\n\n\ndef convert_CSV_into_df(file_loc):\n \"\"\" \n Generate Panda dataframe from CSV data (rotation and position).\n \"\"\" \n df = pd.DataFrame() \n for directory in glob.glob(file_loc): # Selecting all the folders in dataset directory.\n d = [] # Empty list.\n f = directory.split('/')\n for file in glob.glob(directory+\"*.csv\"): # Reading all the CSV files in dataset directory one by one.\n d.append(file)\n d = sorted(d) # Ensures rotation and position are together\n while len(d)!=0:\n rot = d.pop(0) # Rmove the header row from rotation and postion CSV.\n pos = d.pop(0) \n df1 = pd.read_csv(rot, nrows=200) # Read the first 200 rows from rotation and position CSV. value can be 200 or 150.\n df2 = pd.read_csv(pos, nrows=200) \n df_merge = merge_rot_pos(df1,df2,f[1]) # Call the mearge function to mearge fetch data of rotation and position CSV with class lable.\n df = df.append(df_merge,ignore_index=True) # Append the merge data to panda dataframe one by one.\n return df\n\nfile_loc = \"Dataset/*/\"\n\nfor directory in glob.glob(file_loc): # Path of dataset directory.\n for file in glob.glob(directory+\"*.bvh\"): # Fetch each BVH file in dataset directory.\n #f = file.split('\\') \n path_to_files, file_name = os.path.split(file) \n command = \"bvh-converter -r \" + file_name # Load BVH to CSV converter.\n subprocess.call(command, shell=True, cwd=path_to_files) # Executing BVH TO CSV conveter command with shell. \n print(command)\n\n\n\"\"\"\n# Function to merge the rotation and position CSV files generated by BVH TO CSV converter. \n\ndef merge_rot_pos(df1,df2,label):\n # df1 is for rotation and df2 is for position\n df1 = df1.drop(columns=['Time']) # Drop the time coloumn from rotation and postion CSV file.\n df2 = df2.drop(columns=['Time']) \n df_concat = pd.concat([df1, df2], axis=1) # Mereging rotation and position CSV data.\n df_concat = df_concat.dropna()\n df_concat['category'] = label # Adding the associated lable (folder_name) to fetch postion and rotation CSV data. \n return df_concat\n\n\n\n\n# Panda dataframe is generated from CSV data (rotation and position). \n\ndf = pd.DataFrame() \nfor directory in glob.glob(\"Dataset/*/\"): # Selecting all the folders in dataset directory.\n d = [] # Empty list.\n f = directory.split('/')\n for file in glob.glob(directory+\"*.csv\"): # Reading all the CSV files in dataset directory one by one.\n d.append(file)\n d = sorted(d) # Ensures rotation and position are together\n while len(d)!=0:\n rot = d.pop(0) # Rmove the header row from rotation and postion CSV.\n pos = d.pop(0) \n df1 = pd.read_csv(rot, nrows=200) # Read the first 200 rows from rotation and position CSV. value can be 200 or 150.\n df2 = pd.read_csv(pos, nrows=200) \n df_merge = merge_rot_pos(df1,df2,f[1]) # Call the mearge function to mearge fetch data of rotation and position CSV with class lable.\n df = df.append(df_merge,ignore_index=True) # Append the merge data to panda dataframe one by one.\n\n\n\n\"\"\"\n\n#new_df = df.drop('category',axis = 1) # drop the class lable coloumn from panda dataframe.\n#print(new_df.shape)\n", "Dataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (2).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (3).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (4).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (5).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (6).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (7).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy (8).bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80 - Copy.bvh\nDataset\\Assemble_system\nbvh-converter -r P01_R01_0026.48_0028.80.bvh\n" ], [ "df", "_____no_output_____" ], [ "\n\n# Function takes the file from dataset folder and convert it into CSV. \n\nfor directory in glob.glob(\"Dataset/*/\"): # Path of dataset directory.\n for file in glob.glob(directory+\"*.bvh\"): # Fetch each BVH file in dataset directory.\n #f = file.split('/') \n path_to_files, file_name = os.path.split(file)\n command_dir = path_to_files \n command_file = file_name \n command = \"bvh-converter -r \" + command_file # Load BVH to CSV converter.\n subprocess.call(command, shell=True, cwd=command_dir) # Executing BVH TO CSV conveter command with shell. \n\n\n\n\n# Function to merge the rotation and position CSV files generated by BVH TO CSV converter. \n\ndef merge_rot_pos(df1,df2,label):\n # df1 is for rotation and df2 is for position\n df1 = df1.drop(columns=['Time']) # Drop the time coloumn from rotation and postion CSV file.\n df2 = df2.drop(columns=['Time']) \n df_concat = pd.concat([df1, df2], axis=1) # Mereging rotation and position CSV data.\n df_concat = df_concat.dropna()\n df_concat['category'] = label # Adding the associated lable (folder_name) to fetch postion and rotation CSV data. \n return df_concat\n\n\n\n\n# Panda dataframe is generated from CSV data (rotation and position). \n\ndf = pd.DataFrame() \nfor directory in glob.glob(\"Dataset/*/\"): # Selecting all the folders in dataset directory.\n d = [] # Empty list.\n f = directory.split('/')\n for file in glob.glob(directory+\"*.csv\"): # Reading all the CSV files in dataset directory one by one.\n d.append(file)\n d = sorted(d) # Ensures rotation and position are together\n while len(d)!=0:\n rot = d.pop(0) # Rmove the header row from rotation and postion CSV.\n pos = d.pop(0) \n df1 = pd.read_csv(rot, nrows=200) # Read the first 200 rows from rotation and position CSV. value can be 200 or 150.\n df2 = pd.read_csv(pos, nrows=200) \n df_merge = merge_rot_pos(df1,df2,f[1]) # Call the mearge function to mearge fetch data of rotation and position CSV with class lable.\n df = df.append(df_merge,ignore_index=True) # Append the merge data to panda dataframe one by one.\n\n\n\n\n\n#new_df = df.drop('category',axis = 1) # drop the class lable coloumn from panda dataframe.\n#print(new_df.shape)\n\n", "_____no_output_____" ], [ "df1", "_____no_output_____" ], [ "import subprocess", "_____no_output_____" ], [ "dir(subprocess)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cbe1820bd934578ae1d708c23d41b4755b10e64f
9,187
ipynb
Jupyter Notebook
docs/serving/writing-custom-steps.ipynb
george0st/mlrun
6467d3a5ceadf6cd35512b84b3ddc3da611cf39a
[ "Apache-2.0" ]
null
null
null
docs/serving/writing-custom-steps.ipynb
george0st/mlrun
6467d3a5ceadf6cd35512b84b3ddc3da611cf39a
[ "Apache-2.0" ]
null
null
null
docs/serving/writing-custom-steps.ipynb
george0st/mlrun
6467d3a5ceadf6cd35512b84b3ddc3da611cf39a
[ "Apache-2.0" ]
null
null
null
41.197309
1,999
0.581583
[ [ [ "# Writing custom steps\n\n<!-- Add overview -->", "_____no_output_____" ], [ "The Graph executes built-in task classes, or task classes and functions that you implement.\nThe task parameters include the following:\n* `class_name` (str): the relative or absolute class name.\n* `handler` (str): the function handler (if class_name is not specified it is the function handler).\n* `**class_args`: a set of class `__init__` arguments.\n\nFor example, see the following simple `echo` class:", "_____no_output_____" ] ], [ [ "import mlrun", "_____no_output_____" ], [ "# mlrun: start", "_____no_output_____" ], [ "# echo class, custom class example\nclass Echo:\n def __init__(self, context, name=None, **kw):\n self.context = context\n self.name = name\n self.kw = kw\n \n def do(self, x):\n print(\"Echo:\", self.name, x)\n return x", "_____no_output_____" ], [ "# mlrun: end", "_____no_output_____" ] ], [ [ "Test the graph: first convert the code to function, and then add the step to the graph:", "_____no_output_____" ] ], [ [ "fn_echo = mlrun.code_to_function(\"echo_function\", kind=\"serving\", image=\"mlrun/mlrun\")\n\ngraph_echo = fn_echo.set_topology(\"flow\")\n\ngraph_echo.to(class_name=\"Echo\", name=\"pre-process\", some_arg='abc')\n\ngraph_echo.plot(rankdir='LR')", "_____no_output_____" ] ], [ [ "Create a mock server to test this locally:", "_____no_output_____" ] ], [ [ "echo_server = fn_echo.to_mock_server(current_function=\"*\")\n\nresult = echo_server.test(\"\", {\"inputs\": 123})\n\nprint(result)", "{'id': '97397ea412334afdb5e4cb7d7c2e6dd3'}\nEcho: pre-process {'inputs': 123}\n" ] ], [ [ "**For more information, see the [Advanced Graph Notebook Example](./graph-example.ipynb)**", "_____no_output_____" ], [ "<!-- Requires better description - and title? -->\n\nYou can use any Python function by specifying the handler name (e.g. `handler=json.dumps`).\nThe function is triggered with the `event.body` as the first argument, and its result \nis passed to the next step.\n\nAlternatively, you can use classes that can also store some step/configuration and separate the \none time init logic from the per event logic. The classes are initialized with the `class_args`.\nIf the class init args contain `context` or `name`, they are initialized with the \n[graph context](./realtime-pipelines.ipynb) and the step name. \n\nBy default, the `class_name` and handler specify a class/function name in the `globals()` (i.e. this module).\nAlternatively, those can be full paths to the class (module.submodule.class), e.g. `storey.WriteToParquet`.\nYou can also pass the module as an argument to functions such as `function.to_mock_server(namespace=module)`.\nIn this case the class or handler names are also searched in the provided module.\n <!-- the previous sentence needs clarification -->\n\nWhen using classes the class event handler is invoked on every event with the `event.body`.\nIf the Task step `full_event` parameter is set to `True` the handler is invoked and returns\nthe full `event` object. If the class event handler is not specified, it invokes the class `do()` method. \n\nIf you need to implement async behavior, then subclass `storey.MapClass`.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbe186d108624c55a7a99da3c88c77f23c1bdd2d
75,042
ipynb
Jupyter Notebook
notebooks/1.3.2_nc_exp3_analysis.ipynb
ashish1610dhiman/learning_norms_with_mcmc_from_pcfg_IJCAI21
90d42333e7d810822ccf19864f5badc743b066a1
[ "MIT" ]
1
2021-05-19T08:30:20.000Z
2021-05-19T08:30:20.000Z
notebooks/1.3.2_nc_exp3_analysis.ipynb
ashish1610dhiman/learning_norms_with_mcmc_from_pcfg_IJCAI21
90d42333e7d810822ccf19864f5badc743b066a1
[ "MIT" ]
null
null
null
notebooks/1.3.2_nc_exp3_analysis.ipynb
ashish1610dhiman/learning_norms_with_mcmc_from_pcfg_IJCAI21
90d42333e7d810822ccf19864f5badc743b066a1
[ "MIT" ]
null
null
null
58.902669
29,316
0.603582
[ [ [ "import sys\nsys.path.append('../src')\n\nfrom mcmc_norm_learning.algorithm_1_v4 import to_tuple\nfrom mcmc_norm_learning.rules_4 import get_log_prob\nfrom pickle_wrapper import unpickle\nimport pandas as pd\nimport yaml\nimport tqdm\nfrom numpy import log", "_____no_output_____" ], [ "with open(\"../params_nc.yaml\", 'r') as fd:\n params = yaml.safe_load(fd)", "_____no_output_____" ], [ "num_obs=params[\"num_observations\"]\ntrue_norm=params['true_norm']['exp']", "_____no_output_____" ], [ "num_obs", "_____no_output_____" ], [ "base_path=\"../data_nc/exp_nc3/\"\nexp_paths=!ls $base_path", "_____no_output_____" ], [ "def get_num_viols(nc_obs):\n n_viols=0\n for obs in nc_obs:\n for action_pairs in zip(obs, obs[1:]):\n if action_pairs[0] in [(('pickup', 8), ('putdown', 8, '1')),(('pickup', 40), ('putdown', 40, '1'))]:\n if action_pairs[1][1][2] =='1': #not in obl zone\n n_viols+=1\n elif action_pairs[1][1][2] =='3':\n if action_pairs[1][1][1] not in [35,13]: #permission not applicable\n n_viols+=1\n return (n_viols)", "_____no_output_____" ], [ "z1=pd.DataFrame()\nfor exp_path in exp_paths:\n temp=pd.DataFrame()\n #Add params\n obs_path=base_path+exp_path+\"/obs.pickle\"\n obs = unpickle(obs_path)\n temp[\"w_nc\"] = [float(exp_path.split(\"w_nc=\")[1].split(\",\")[0])]\n trial=1 if \"trial\" not in exp_path else exp_path.split(\",trial=\")[-1]\n temp[\"trial\"]=[int(trial)]\n #Add violations\n n_viols=get_num_viols(obs)\n temp[\"violation_rate\"]=[n_viols/num_obs]\n #Add lik,post\n prior_true=!grep \"For True Norm\" {base_path+exp_path+\"/run.log\"}\n lik_true=!grep \"lik_no_norm\" {base_path+exp_path+\"/run.log\"}\n post_true=float(prior_true[0].split(\"log_prior=\")[-1]) + float(lik_true[0].split(\"lik_true_norm=\")[1])\n temp[\"true_norm_posterior\"]=[post_true]\n #Add if True Norm found in some chain\n if_true_norm=!grep \"True norm in some chain(s)\" {base_path+exp_path+\"/chain_info.txt\"}\n temp[\"if_true_norm_found\"]= [\"False\" not in if_true_norm[0]]\n #Rank of True Norm if found as per posterior\n rank_df=pd.read_csv(base_path+exp_path+\"/ranked_posteriors.csv\",index_col=False)\n rank_true=rank_df.loc[rank_df.expression==str(to_tuple(true_norm))][[\"post_rank\",\"log_posterior\"]].values\n rank=rank_true[0][0] if rank_true.shape[0]==1 else None\n temp[\"true_norm_rank_wrt_posterior\"]= [rank]\n #max posterior found in chains\n rank_1=rank_df.loc[rank_df.post_rank==1]\n temp[\"max_posterior_in_chain\"]= [rank_1.log_posterior.values[0]]\n temp[\"norm_wi_max_post\"]= [rank_1.expression.values[0]]\n #chain summary\n chain_details = pd.read_csv(f\"{base_path+exp_path}/chain_posteriors_nc.csv\")\n n_chains1=chain_details.loc[chain_details.expression==str(true_norm)].chain_number.nunique()\n temp[\"#chains_wi_true_norm\"]= [n_chains1]\n chain_max_min=chain_details.groupby([\"chain_number\"])[[\"log_posterior\"]].agg(['min', 'max', 'mean', 'std'])\n n_chains2=(chain_max_min[\"log_posterior\",\"max\"]>post_true).sum()\n temp[\"#chains_wi_post_gt_true_norm\"]= [n_chains2]\n #Posterior Estimation\n n=params[\"n\"]\n top_norms=chain_details.loc[chain_details.chain_pos>2*n\\\n ].groupby([\"expression\"]).agg({\"log_posterior\":[\"mean\",\"count\"]})\n top_norms[\"chain_rank\"]=top_norms[[('log_posterior', 'count')]].rank(method='dense',ascending=False)\n top_norms.sort_values(by=[\"chain_rank\"],inplace=True)\n rank_true_wi_freq=top_norms.iloc[top_norms.index==str(true_norm)][\"chain_rank\"].values\n rank_true_wi_freq = float(rank_true_wi_freq[0]) if rank_true_wi_freq.size>0 else None\n temp[\"#rank_true_wi_freq\"]= [rank_true_wi_freq]\n post_norm_top=top_norms.loc[top_norms.chain_rank==1][\"log_posterior\",\"mean\"].values\n post_norm_top = post_norm_top[0] if post_norm_top.size>0 else None\n temp[\"posterior_norm_top\"]= [post_norm_top]\n #Num equivalent norms in posterior\n log_lik=float(lik_true[0].split(\"lik_true_norm=\")[1])\n top_norms[\"log_prior\"]=top_norms.index.to_series().apply(lambda x: get_log_prob(\"NORMS\",eval(x)))[0]\n top_norms[\"log_lik\"]=top_norms[('log_posterior', 'mean')]-top_norms[\"log_prior\"]\n mask_equiv=abs((top_norms[\"log_lik\"]-log_lik)/log_lik)<=0.0005\n n_equiv=mask_equiv.sum()\n temp[\"total_equiv_norms_in_top_norms\"]= [n_equiv]\n n_equiv_20=mask_equiv[:20].sum()\n temp[\"total_equiv_norms_in_top_20_norms\"]= [n_equiv_20]\n best_equiv_norm_rank=top_norms.loc[mask_equiv][\"chain_rank\"].min()\n temp[\"best_equiv_norm_rank\"]= [best_equiv_norm_rank]\n best_equiv_norm=eval(top_norms.loc[mask_equiv].index[0]) if n_equiv>0 else None\n temp[\"best_equiv_norm\"]= [best_equiv_norm]\n z1=z1.append(temp)", "_____no_output_____" ], [ "z1.columns", "_____no_output_____" ], [ "z1[\"if_equiv_norm_found\"]=z1[\"total_equiv_norms_in_top_norms\"]>0\n\nz1[\"if_true_or_equiv_norm_found\"]=z1[\"if_equiv_norm_found\"] | z1[\"if_true_norm_found\"]\n\nz1[\"true_post/max_post\"]=z1[\"true_norm_posterior\"]/z1[\"max_posterior_in_chain\"]\nz1[\"%chains_wi_true_norm\"]=z1[\"#chains_wi_true_norm\"]/10\nz1[\"%chains_wi_post_gt_true_norm\"]=z1[\"#chains_wi_post_gt_true_norm\"]/10\n\nz1[\"expected_violation_rate\"]=z1[\"w_nc\"]*108/243", "_____no_output_____" ], [ "z1[\"chk\"]=z1[\"violation_rate\"]/z1[\"expected_violation_rate\"]", "_____no_output_____" ] ], [ [ "### Summary", "_____no_output_____" ] ], [ [ "print (\"%trials where true norms found: {:.2%}\".format(z1[\"if_true_norm_found\"].mean()))\nprint (\"%trials where equiv norms found: {:.2%}\".format(z1[\"if_equiv_norm_found\"].mean()))\nprint (\"%trials where true/equiv norms found: {:.2%}\".format(z1[\"if_true_or_equiv_norm_found\"].mean()))", "%trials where true norms found: 56.00%\n%trials where equiv norms found: 60.00%\n%trials where true/equiv norms found: 68.00%\n" ] ], [ [ "### Where are neither True nor equivalent Norms found ?", "_____no_output_____" ] ], [ [ "z1.groupby([\"chk\"]).agg({\"if_true_or_equiv_norm_found\":\"mean\",\"trial\":\"count\"})", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nz1.plot(x=\"chk\",y=[\"max_posterior_in_chain\",\"true_norm_posterior\",\\\n \"#rank_true_wi_freq\",\"best_equiv_norm_rank\"],subplots=True,\\\n marker=\"o\",kind = 'line',ls=\"none\",figsize = (10,10))\n#z1.plot(x=\"chk\",y=\"true_norm_posterior\",kind=\"scatter\")", "_____no_output_____" ], [ "108/243*0.3", "_____no_output_____" ], [ "z1.groupby([\"w_nc\",\"violation_rate\"]).agg({\"trial\":\"count\",\"if_true_or_equiv_norm_found\":\"mean\"})", "_____no_output_____" ], [ "z1.groupby([\"w_nc\"]).agg({\"trial\":\"count\",\"if_true_norm_found\":[(\"mean\")],\"if_equiv_norm_found\":\"mean\",\\\n \"if_true_or_equiv_norm_found\":\"mean\",\"true_norm_posterior\":\"mean\",\\\n \"true_post/max_post\":\"mean\",\"%chains_wi_true_norm\":\"mean\"})", "_____no_output_____" ], [ "z1.dtypes", "_____no_output_____" ], [ "z1.groupby([\"w_nc\"]).mean()", "_____no_output_____" ], [ "true_norm", "_____no_output_____" ], [ "z1.loc[~(z1.if_true_norm_found)][[\"w_nc\",\"best_equiv_norm_rank\",\"best_equiv_norm\"]].values", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe18c90823d642292679958d8edafb3efdb4cc9
10,891
ipynb
Jupyter Notebook
docs/ssl_blacklist.ipynb
threatlead/abusech
6c62f51f773cb17ac6943d87fb697ce1e9dae049
[ "MIT" ]
null
null
null
docs/ssl_blacklist.ipynb
threatlead/abusech
6c62f51f773cb17ac6943d87fb697ce1e9dae049
[ "MIT" ]
null
null
null
docs/ssl_blacklist.ipynb
threatlead/abusech
6c62f51f773cb17ac6943d87fb697ce1e9dae049
[ "MIT" ]
null
null
null
35.132258
548
0.579561
[ [ [ "# AbuseCH Data Scraper", "_____no_output_____" ], [ "## SSLBL\n\n> The SSL Blacklist (SSLBL) is a project of abuse.ch with the goal of detecting malicious SSL connections, by identifying and blacklisting SSL certificates used by botnet C&C servers. In addition, SSLBL identifies JA3 fingerprints that helps you to detect & block malware botnet C&C communication on the TCP layer.\n\nReference: https://sslbl.abuse.ch/", "_____no_output_____" ] ], [ [ "from pprint import pprint\nfrom abusech.sslbl import SslBl\nsslbl = SslBl()", "_____no_output_____" ] ], [ [ "### IPAddress\n\n> An SSL certificate can be associated with one or more servers (IP address:port combination). SSLBL collects IP addresses that are running with an SSL certificate blacklisted on SSLBL. These are usually botnet Command&Control servers (C&C). SSLBL hence publishes a blacklist containing these IPs which can be used to detect botnet C2 traffic from infected machines towards the internet, leaving your network. The CSV format is useful if you want to process the blacklisted IP addresses further, e.g. loading them into your SIEM.\n\nReference: https://sslbl.abuse.ch/blacklist/#botnet-c2-ips-csv", "_____no_output_____" ] ], [ [ "data = sslbl.get_ip_blacklist()\npprint(data[0:2])", "[IPAddress(datetime=datetime.datetime(2019, 11, 23, 5, 8, 49), ipaddress='185.147.15.21', port=443),\n IPAddress(datetime=datetime.datetime(2019, 11, 22, 23, 22, 36), ipaddress='185.130.104.152', port=443)]\n" ] ], [ [ "### IpAddress - Aggressive\n\n> If you want to fetch a comprehensive list of all IP addresses that SSLBL has ever seen, please use the CSV provided below.\n\nReference: https://sslbl.abuse.ch/blacklist/#botnet-c2-ips-csv", "_____no_output_____" ] ], [ [ "data = sslbl.get_ip_blacklist(aggressive=True)\npprint(data[0:2])", "[IPAddress(datetime=datetime.datetime(2019, 11, 23, 5, 8, 49), ipaddress='185.147.15.21', port=443),\n IPAddress(datetime=datetime.datetime(2019, 11, 22, 23, 22, 36), ipaddress='185.130.104.152', port=443)]\n" ] ], [ [ "### SSLs\n\n> The SSL Certificate Blacklist (CSV) is a CSV that contains SHA1 Fingerprint of all SSL certificates blacklisted on SSLBL. This format is useful if you want to process the blacklisted SSL certificate further, e.g. loading them into your SIEM.\n\nReference: https://sslbl.abuse.ch/blacklist/#ssl-certificates-csv", "_____no_output_____" ] ], [ [ "data = sslbl.get_ssl_blacklist()\npprint(data[0:2])", "[SSL(datetime=datetime.datetime(2019, 11, 23, 10, 17, 58), sha1='93451cec2fb6853fbd6fb5053bae747162e0feaf', reason='Ostap C&C'),\n SSL(datetime=datetime.datetime(2019, 11, 22, 14, 1, 45), sha1='6953081218a0bd0229b1b0bf6397378ead0660cf', reason='TA505 C&C')]\n" ] ], [ [ "### SSL Details\n\n> An SSL certificate is identified by a unique SHA1 hash (aka SSL certificate fingerprint). The following table shows further information as well as a list of malware samples including the corresponding botnet C&C associated with the SSL certificate fingerprint 7cf902ff50b3869ccaa4715b25bbea3cb18a18b5.\n\nReference: https://sslbl.abuse.ch/ssl-certificates/sha1/7cf902ff50b3869ccaa4715b25bbea3cb18a18b5/", "_____no_output_____" ] ], [ [ "data = sslbl.get_ssl_details(sha1='7cf902ff50b3869ccaa4715b25bbea3cb18a18b5')\npprint(data)", "{'details': {'cn': 'c=xx, l=default city, o=default company ltd',\n 'dn': 'c=xx, l=default city, o=default company ltd',\n 'first_seen': datetime.datetime(2019, 11, 21, 14, 39, 29),\n 'ipaddress_count': 1,\n 'last_seen': None,\n 'listing_date': datetime.datetime(2019, 11, 22, 6, 46, 43),\n 'reason': 'findpos c&c',\n 'sample_count': 1,\n 'ssl_sha1': '7cf902ff50b3869ccaa4715b25bbea3cb18a18b5',\n 'tls_version': 'tls 1.2'},\n 'hashes': [{'family': 'findpos',\n 'ipaddress': '81.25.71.88',\n 'md5': 'ebf67410ebe1d5dcabf7ef2ac6db120e',\n 'port': '443',\n 'timestamp': datetime.datetime(2019, 11, 21, 14, 39, 29),\n 'virustotal': {'link': 'https://www.virustotal.com/file/5b915e4c0a9e49b27cddc24d1b1e07b7ad3869d2796b9975297dbd27b43acbb2/analysis/1574230049/',\n 'results': '44',\n 'sha256': '5b915e4c0a9e49b27cddc24d1b1e07b7ad3869d2796b9975297dbd27b43acbb2'}}]}\n" ] ], [ [ "### JA3 fingerprint\n\n> JA3 is an open source tool used to fingerprint SSL/TLS client applications. In the best case, you can use JA3 to identify malware and botnet C2 traffic that is leveraging SSL/TLS. The CSV format is useful if you want to process the JA3 fingerprints further, e.g. loading them into your SIEM. The JA3 fingerprints blacklisted on SSLBL have been collected by analysing more than 25,000,000 PCAPs generated by malware samples. These fingerprints have not been tested against known good traffic yet and may cause a significant amount of FPs!\n\nReference: https://sslbl.abuse.ch/blacklist/#ja3-fingerprints-csv", "_____no_output_____" ] ], [ [ "data = sslbl.get_ja3_blacklist()\npprint(data[0:2])", "[JA3(first_seen=datetime.datetime(2017, 7, 14, 18, 8, 15), last_seen=datetime.datetime(2019, 7, 27, 20, 42, 54), md5='b386946a5a44d1ddcc843bc75336dfce', reason='dridex'),\n JA3(first_seen=datetime.datetime(2017, 7, 14, 19, 2, 3), last_seen=datetime.datetime(2019, 7, 28, 0, 34, 38), md5='8991a387e4cc841740f25d6f5139f92d', reason='adware')]\n" ] ], [ [ "### JA3 details\n\n> JA3 is an open source tool used to fingerprint SSL/TLS client applications. In the best case, you can use JA3 to identify malware traffic that is leveraging SSL/TLS.You can find further information about the JA3 fingerprint d76ee64fb7273733cbe455ac81c292e6, including the corresponding malware samples as well as the associated botnet C&Cs.\n\nReference: https://sslbl.abuse.ch/ja3-fingerprints/d76ee64fb7273733cbe455ac81c292e6/", "_____no_output_____" ] ], [ [ "data = sslbl.get_ja3_details(md5='d76ee64fb7273733cbe455ac81c292e6')\npprint(data)", "{'details': {'family': 'tofsee',\n 'first_seen': datetime.datetime(2018, 11, 16, 13, 26, 39),\n 'ipaddress_count': 2,\n 'ja3': 'd76ee64fb7273733cbe455ac81c292e6',\n 'last_seen': datetime.datetime(2018, 11, 18, 19, 19, 36),\n 'listing_date': datetime.datetime(2018, 11, 19, 11, 34, 25),\n 'sample_count': 2},\n 'hashes': [{'ipaddress': '159.53.52.227',\n 'md5': 'bc95c3f699cea00f31cc288e669d9bd3',\n 'port': '443',\n 'timestamp': datetime.datetime(2018, 11, 18, 19, 19, 36),\n 'virustotal': {'link': 'https://www.virustotal.com/file/7a2ad98a994ba2f3bfcc04b2177be74fb16b29e742d7ed7798cf77460a26a98a/analysis/1542196979/',\n 'results': '18/67',\n 'sha256': '7a2ad98a994ba2f3bfcc04b2177be74fb16b29e742d7ed7798cf77460a26a98a'}},\n {'ipaddress': '159.53.116.245',\n 'md5': '0d0e3832ff519b3ce734f8f122debcf4',\n 'port': '443',\n 'timestamp': datetime.datetime(2018, 11, 16, 13, 26, 40),\n 'virustotal': {'link': 'https://www.virustotal.com/file/cd08ec098893f6045d7eb34ce27574338eb5c207d86e651a4acc24e7013716a4/analysis/1542193940/',\n 'results': '27/67',\n 'sha256': 'cd08ec098893f6045d7eb34ce27574338eb5c207d86e651a4acc24e7013716a4'}}]}\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe18d17f4df1a526c1f284be9fd8a051c9526ef
31,323
ipynb
Jupyter Notebook
hpc/openacc/English/C/jupyter_notebook/openacc_c_lab2.ipynb
Anish-Saxena/gpubootcamp
469ed5ed1fbfdaee780cec90e2fb59e5bba089b5
[ "Apache-2.0" ]
1
2022-02-20T12:33:03.000Z
2022-02-20T12:33:03.000Z
hpc/openacc/English/C/jupyter_notebook/openacc_c_lab2.ipynb
hiter-joe/gpubootcamp
bc358e6af3a06f5f554ec93cbf402da82c56e93d
[ "Apache-2.0" ]
null
null
null
hpc/openacc/English/C/jupyter_notebook/openacc_c_lab2.ipynb
hiter-joe/gpubootcamp
bc358e6af3a06f5f554ec93cbf402da82c56e93d
[ "Apache-2.0" ]
1
2021-03-02T17:24:29.000Z
2021-03-02T17:24:29.000Z
46.267356
1,003
0.614532
[ [ [ "# Data Management with OpenACC", "_____no_output_____" ], [ "This version of the lab is intended for C/C++ programmers. The Fortran version of this lab is available [here](../../Fortran/jupyter_notebook/openacc_fortran_lab2.ipynb).", "_____no_output_____" ], [ "You will receive a warning five minutes before the lab instance shuts down. Remember to save your work! If you are about to run out of time, please see the [Post-Lab](#Post-Lab-Summary) section for saving this lab to view offline later.", "_____no_output_____" ], [ "---\nLet's execute the cell below to display information about the GPUs running on the server. To do this, execute the cell block below by giving it focus (clicking on it with your mouse), and hitting Ctrl-Enter, or pressing the play button in the toolbar above. If all goes well, you should see some output returned below the grey cell.", "_____no_output_____" ] ], [ [ "!pgaccelinfo", "_____no_output_____" ] ], [ [ "---\n\n## Introduction\n\nOur goal for this lab is to use the OpenACC Data Directives to properly manage our data.\n \n<img src=\"images/development_cycle.png\" alt=\"OpenACC development cycle\" width=\"50%\">\n\nThis is the OpenACC 3-Step development cycle.\n\n**Analyze** your code, and predict where potential parallelism can be uncovered. Use profiler to help understand what is happening in the code, and where parallelism may exist.\n\n**Parallelize** your code, starting with the most time consuming parts. Focus on maintaining correct results from your program.\n\n**Optimize** your code, focusing on maximizing performance. Performance may not increase all-at-once during early parallelization.\n\nWe are currently tackling the **parallelize** and **optimize** steps by adding the *data clauses* necessary to parallelize the code without CUDA Managed Memory and then *structured data directives* to optimize the data movement of our code.", "_____no_output_____" ], [ "---\n\n## Run the Code (With Managed Memory)\n\nIn the [previous lab](openacc_c_lab1.ipynb), we added OpenACC loop directives and relied on a feature called CUDA Managed Memory to deal with the separate CPU & GPU memories for us. Just adding OpenACC to our two loop nests we achieved a considerable performance boost. However, managed memory is not compatible with all GPUs or all compilers and it sometimes performs worse than programmer-defined memory management. Let's start with our solution from the previous lab and use this as our performance baseline. Note the runtime from the follow cell.", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2 && make clean && make laplace_managed && ./laplace_managed", "_____no_output_____" ] ], [ [ "### Optional: Analyze the Code\n\nIf you would like a refresher on the code files that we are working on, you may view both of them using the two links below by openning the downloaded file.\n\n[jacobi.c](../source_code/lab2/jacobi.c) \n[laplace2d.c](../source_code/lab2/laplace2d.c) ", "_____no_output_____" ], [ "## Building Without Managed Memory\n\nFor this exercise we ultimately don't want to use CUDA Managed Memory, so let's remove the managed option from our compiler options. Try building and running the code now. What happens?", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2 && make clean && make laplace_no_managed && ./laplace", "_____no_output_____" ] ], [ [ "Uh-oh, this time our code failed to build. Let's take a look at the compiler output to understand why:\n\n```\njacobi.c:\nlaplace2d.c:\nPGC-S-0155-Compiler failed to translate accelerator region (see -Minfo messages): Could not find allocated-variable index for symbol (laplace2d.c: 47)\ncalcNext:\n 47, Accelerator kernel generated\n Generating Tesla code\n 48, #pragma acc loop gang /* blockIdx.x */\n 50, #pragma acc loop vector(128) /* threadIdx.x */\n 54, Generating implicit reduction(max:error)\n 48, Accelerator restriction: size of the GPU copy of Anew,A is unknown\n 50, Loop is parallelizable\nPGC-F-0704-Compilation aborted due to previous errors. (laplace2d.c)\nPGC/x86-64 Linux 18.7-0: compilation aborted\n```\n\nThis error message is not very intuitive, so let me explain it to you.:\n\n* `PGC-S-0155-Compiler failed to translate accelerator region (see -Minfo messages): Could not find allocated-variable index for symbol (laplace2d.c: 47)` - The compiler doesn't like something about a variable from line 47 of our code.\n* `48, Accelerator restriction: size of the GPU copy of Anew,A is unknown` - I don't see any further information about line 47, but at line 48 the compiler is struggling to understand the size and shape of the arrays Anew and A. It turns out, this is our problem.\n\nSo, what these cryptic compiler errors are telling us is that the compiler needs to create copies of A and Anew on the GPU in order to run our code there, but it doesn't know how big they are, so it's giving up. We'll need to give the compiler more information about these arrays before it can move forward, so let's find out how to do that.", "_____no_output_____" ], [ "## OpenACC Data Clauses\n\nData clauses allow the programmer to specify data transfers between the host and device (or in our case, the CPU and the GPU). Because they are clauses, they can be added to other directives, such as the `parallel loop` directive that we used in the previous lab. Let's look at an example where we do not use a data clause.\n\n```cpp\nint *A = (int*) malloc(N * sizeof(int));\n\n#pragma acc parallel loop\nfor( int i = 0; i < N; i++ )\n{\n A[i] = 0;\n}\n```\n\nWe have allocated an array `A` outside of our parallel region. This means that `A` is allocated in the CPU memory. However, we access `A` inside of our loop, and that loop is contained within a *parallel region*. Within that parallel region, `A[i]` is attempting to access a memory location within the GPU memory. We didn't explicitly allocate `A` on the GPU, so one of two things will happen.\n\n1. The compiler will understand what we are trying to do, and automatically copy `A` from the CPU to the GPU.\n2. The program will check for an array `A` in GPU memory, it won't find it, and it will throw an error.\n\nInstead of hoping that we have a compiler that can figure this out, we could instead use a *data clause*.\n\n```cpp\nint *A = (int*) malloc(N * sizeof(int));\n\n#pragma acc parallel loop copy(A[0:N])\nfor( int i = 0; i < N; i++ )\n{\n A[i] = 0;\n}\n```\n\nWe will learn the `copy` data clause first, because it is the easiest to use. With the inclusion of the `copy` data clause, our program will now copy the content of `A` from the CPU memory, into GPU memory. Then, during the execution of the loop, it will properly access `A` from the GPU memory. After the parallel region is finished, our program will copy `A` from the GPU memory back to the CPU memory. Let's look at one more direct example.\n\n```cpp\nint *A = (int*) malloc(N * sizeof(int));\n\nfor( int i = 0; i < N; i++ )\n{\n A[i] = 0;\n}\n\n#pragma acc parallel loop copy(A[0:N])\nfor( int i = 0; i < N; i++ )\n{\n A[i] = 1;\n}\n```\n\nNow we have two loops; the first loop will execute on the CPU (since it does not have an OpenACC parallel directive), and the second loop will execute on the GPU. Array `A` will be allocated on the CPU, and then the first loop will execute. This loop will set the contents of `A` to be all 0. Then the second loop is encountered; the program will copy the array `A` (which is full of 0's) into GPU memory. Then, we will execute the second loop on the GPU. This will edit the GPU's copy of `A` to be full of 1's.\n\nAt this point, we have two separate copies of `A`. The CPU copy is full of 0's, and the GPU copy is full of 1's. Now, after the parallel region finishes, the program will copy `A` back from the GPU to the CPU. After this copy, both the CPU and the GPU will contain a copy of `A` that contains all 1's. The GPU copy of `A` will then be deallocated.\n\nThis image offers another step-by-step example of using the copy clause.\n\n![copy_step_by_step](images/copy_step_by_step.png)\n\nWe are also able to copy multiple arrays at once by using the following syntax.\n\n```cpp\n#pragma acc parallel loop copy(A[0:N], B[0:N])\nfor( int i = 0; i < N; i++ )\n{\n A[i] = B[i];\n}\n```\n\nOf course, we might not want to copy our data both to and from the GPU memory. Maybe we only need the array's values as inputs to the GPU region, or maybe it's only the final results we care about, or perhaps the array is only used temporarily on the GPU and we don't want to copy it either directive. The following OpenACC data clauses provide a bit more control than just the `copy` clause.\n\n* `copyin` - Create space for the array and copy the input values of the array to the device. At the end of the region, the array is deleted without copying anything back to the host.\n* `copyout` - Create space for the array on the device, but don't initialize it to anything. At the end of the region, copy the results back and then delete the device array.\n* `create` - Create space of the array on the device, but do not copy anything to the device at the beginning of the region, nor back to the host at the end. The array will be deleted from the device at the end of the region.\n* `present` - Don't do anything with these variables. I've put them on the device somewhere else, so just assume they're available.\n\nYou may also use them to operate on multiple arrays at once, by including those arrays as a comma separated list.\n\n```cpp\n#pragma acc parallel loop copy( A[0:N], B[0:M], C[0:Q] )\n```\n\nYou may also use more than one data clause at a time.\n\n```cpp\n#pragma acc parallel loop create( A[0:N] ) copyin( B[0:M] ) copyout( C[0:Q] )\n```\n", "_____no_output_____" ], [ "### Array Shaping\n\nThe shape of the array specifies how much data needs to be transferred. Let's look at an example:\n\n```cpp\n#pragma acc parallel loop copy(A[0:N])\nfor( int i = 0; i < N; i++ )\n{\n A[i] = 0;\n}\n```\n\nFocusing specifically on the `copy(A[0:N])`, the shape of the array is defined within the brackets. The syntax for array shape is `[starting_index:size]`. This means that (in the code example) we are copying data from array `A`, starting at index 0 (the start of the array), and copying N elements (which is most likely the length of the entire array).\n\nWe are also able to only copy a portion of the array:\n\n```cpp\n#pragma acc parallel loop copy(A[1:N-2])\n```\n\nThis would copy all of the elements of `A` except for the first, and last element.\n\nLastly, if you do not specify a starting index, 0 is assumed. This means that\n\n```cpp\n#pragma acc parallel loop copy(A[0:N])\n```\n\nis equivalent to\n\n```cpp\n#pragma acc parallel loop copy(A[:N])\n```", "_____no_output_____" ], [ "## Making the Sample Code Work without Managed Memory\n\nIn order to build our example code without CUDA managed memory we need to give the compiler more information about the arrays. How do our two loop nests use the arrays `A` and `Anew`? The `calcNext` function take `A` as input and generates `Anew` as output, but also needs Anew copied in because we need to maintain that *hot* boundary at the top. So you will want to add a `copyin` clause for `A` and a `copy` clause for `Anew` on your region. The `swap` function takes `Anew` as input and `A` as output, so it needs the exact opposite data clauses. It's also necessary to tell the compiler the size of the two arrays by using array shaping. Our arrays are `m` times `n` in size, so we'll tell the compiler their shape starts at `0` and has `n*m` elements, using the syntax above. Go ahead and add data clauses to the two `parallel loop` directives in `laplace2d.c`.\n\nFrom the top menu, click on *File*, and *Open* `laplace2d.c` from the current directory at `C/source_code/lab2` directory. Remember to **SAVE** your code after changes, before running below cells.\n\nThen try to build again.", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2 && make clean && make laplace_no_managed && ./laplace", "_____no_output_____" ] ], [ [ "Well, the good news is that it should have built correctly and run. If it didn't, check your data clauses carefully. The bad news is that now it runs a whole lot slower than it did before. Let's try to figure out why. The PGI compiler provides your executable with built-in timers, so let's start by enabling them and seeing what it shows. You can enable these timers by setting the environment variable `PGI_ACC_TIME=1`. Run the cell below to get the program output with the built-in profiler enabled.\n\n**Note:** Profiling will not be covered in this lab. Please have a look at the supplementary [slides](https://drive.google.com/file/d/1Asxh0bpntlmYxAPjBxOSThFIz7Ssd48b/view?usp=sharing).", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2 && make clean && make laplace_no_managed && PGI_ACC_TIME=1 ./laplace ", "_____no_output_____" ] ], [ [ "Your output should look something like what you see below.\n```\n total: 189.014216 s\n\nAccelerator Kernel Timing data\n/labs/lab2/English/C/laplace2d.c\n calcNext NVIDIA devicenum=0\n time(us): 53,290,779\n 47: compute region reached 1000 times\n 47: kernel launched 1000 times\n grid: [4094] block: [128]\n device time(us): total=2,427,090 max=2,447 min=2,406 avg=2,427\n elapsed time(us): total=2,486,633 max=2,516 min=2,464 avg=2,486\n 47: reduction kernel launched 1000 times\n grid: [1] block: [256]\n device time(us): total=19,025 max=20 min=19 avg=19\n elapsed time(us): total=48,308 max=65 min=44 avg=48\n 47: data region reached 4000 times\n 47: data copyin transfers: 17000\n device time(us): total=33,878,622 max=2,146 min=6 avg=1,992\n 57: data copyout transfers: 10000\n device time(us): total=16,966,042 max=2,137 min=9 avg=1,696\n/labs/lab2/English/C/laplace2d.c\n swap NVIDIA devicenum=0\n time(us): 36,214,666\n 62: compute region reached 1000 times\n 62: kernel launched 1000 times\n grid: [4094] block: [128]\n device time(us): total=2,316,826 max=2,331 min=2,305 avg=2,316\n elapsed time(us): total=2,378,419 max=2,426 min=2,366 avg=2,378\n 62: data region reached 2000 times\n 62: data copyin transfers: 8000\n device time(us): total=16,940,591 max=2,352 min=2,114 avg=2,117\n 70: data copyout transfers: 9000\n device time(us): total=16,957,249 max=2,133 min=13 avg=1,884\n```\n \nThe total runtime was roughly 190 with the profiler turned on, but only about 130 seconds without. We can see that `calcNext` required roughly 53 seconds to run by looking at the `time(us)` line under the `calcNext` line. We can also look at the `data region` section and determine that 34 seconds were spent copying data to the device and 17 seconds copying data out for the device. The `swap` function has very similar numbers. That means that the program is actually spending very little of its runtime doing calculations. Why is the program copying so much data around? The screenshot below comes from the Nsight Systems profiler and shows part of one step of our outer while loop. The greenish and pink colors are data movement and the blue colors are our kernels (calcNext and swap). Notice that for each kernel we have copies to the device (greenish) before and copies from the device (pink) after. The means we have 4 segments of data copies for every iteration of the outer while loop.\n \n![Profile before adding data region](images/pre-data-c.png)\n \nLet's contrast this with the managed memory version. The image below shows the same program built with managed memory. Notice that there's a lot of \"data migration\" at the first kernel launch, where the data is first used, but there's no data movement between kernels after that. This tells me that the data movement isn't really needed between these kernels, but we need to tell the compiler that.\n \n\n![Profile using managed memory](images/managed-c.png)\n\nBecause the loops are in two separate function, the compiler can't really see that the data is reused on the GPU between those function. We need to move our data movement up to a higher level where we can reuse it for each step through the program. To do that, we'll add OpenACC data directives.", "_____no_output_____" ], [ "---\n\n## OpenACC Structured Data Directive\n\nThe OpenACC data directives allow the programmer to explicitly manage the data on the device (in our case, the GPU). Specifically, the structured data directive will mark a static region of our code as a **data region**.\n\n```cpp\n< Initialize data on host (CPU) >\n\n#pragma acc data < data clauses >\n{\n\n < Code >\n\n}\n```\n\nDevice memory allocation happens at the beginning of the region, and device memory deallocation happens at the end of the region. Additionally, any data movement from the host to the device (CPU to GPU) happens at the beginning of the region, and any data movement from the device to the host (GPU to CPU) happens at the end of the region. Memory allocation/deallocation and data movement is defined by which clauses the programmer includes (the `copy`, `copyin`, `copyout`, and `create` clauses we saw above).\n", "_____no_output_____" ], [ "### Encompassing Multiple Compute Regions\n\nA single data region can contain any number of parallel/kernels regions. Take the following example:\n\n```cpp\n#pragma acc data copyin(A[0:N], B[0:N]) create(C[0:N])\n{\n\n #pragma acc parallel loop\n for( int i = 0; i < N; i++ )\n {\n C[i] = A[i] + B[i];\n }\n \n #pragma acc parallel loop\n for( int i = 0; i < N; i++ )\n {\n A[i] = C[i] + B[i];\n }\n\n}\n```\n\nYou may also encompass function calls within the data region:\n\n```cpp\nvoid copy(int *A, int *B, int N)\n{\n #pragma acc parallel loop\n for( int i = 0; i < N; i++ )\n {\n A[i] = B[i];\n }\n}\n\n...\n\n#pragma acc data copyout(A[0:N],B[0:N]) copyin(C[0:N])\n{\n copy(A, C, N);\n \n copy(A, B, N);\n}\n```", "_____no_output_____" ], [ "### Adding the Structured Data Directive to our Code\n\nAdd a structured data directive to the code to properly handle the arrays `A` and `Anew`. We've already added data clauses to our two functions, so this time we'll move up the calltree and add a structured data region around our while loop in the main program. Think about the input and output to this while loop and choose your data clauses for `A` and `Anew` accordingly.\n\nFrom the top menu, click on *File*, and *Open* `jacobi.c` from the current directory at `C/source_code/lab2` directory. Remember to **SAVE** your code after changes, before running below cells.\n\nThen, run the following script to check you solution. You code should run just as good as (or slightly better) than our managed memory code.", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2 && make clean && make laplace_no_managed && ./laplace", "_____no_output_____" ] ], [ [ "Did your runtime go down? It should have but the answer should still match the previous runs. Let's take a look at the profiler now.\n\n![Profile after adding data region](images/post-data-c.png)\n\nNotice that we no longer see the greenish and pink bars on either side of each iteration, like we did before. Instead, we see a red OpenACC `Enter Data` region which contains some greenish bars corresponding to host-to-device data transfer preceding any GPU kernel launches. This is because our data movement is now handled by the outer data region, not the data clauses on each loop. Data clauses count how many times an array has been placed into device memory and only copies data the outermost time it encounters an array. This means that the data clauses we added to our two functions are now used only for shaping and no data movement will actually occur here anymore, thanks to our outer `data` region.\n\n\n\nThis reference counting behavior is really handy for code development and testing. Just like we just did, you can add clauses to each of your OpenACC `parallel loop` or `kernels` regions to get everything running on the accelerator and then just wrap those functions with a data region when you're done and the data movement magically disappears. Furthermore, if you want to isolate one of those functions into a standalone test case you can do so easily, because the data clause is already in the code. ", "_____no_output_____" ], [ "---\n\n## OpenACC Update Directive\n\nWhen we use the data clauses you are only able to copy data between host and device memory at the beginning and end of your regions, but what if you need to copy data in the middle? For example, what if we wanted to debug our code by printing out the array every 100 steps to make sure it looks right? In order to transfer data at those times, we can use the `update` directive. The update directive will explicitly transfer data between the host and the device. The `update` directive has two clauses:\n\n* `self` - The self clause will transfer data from the device to the host (GPU to CPU). You will sometimes see this clause called the `host` clause.\n* `device` - The device clause will transfer data from the host to the device (CPU to GPU).\n\nThe syntax would look like:\n\n`#pragma acc update self(A[0:N])`\n\n`#pragma acc update device(A[0:N])`\n\nAll of the array shaping rules apply.\n\nAs an example, let's create a version of our laplace code where we want to print the array `A` after every 100 iterations of our loop. The code will look like this:\n\n```cpp\n#pragma acc data copyin( A[:m*n],Anew[:m*n] )\n{\n while ( error > tol && iter < iter_max )\n {\n error = calcNext(A, Anew, m, n);\n swap(A, Anew, m, n);\n \n if(iter % 100 == 0)\n {\n printf(\"%5d, %0.6f\\n\", iter, error);\n for( int i = 0; i < n; i++ )\n {\n for( int j = 0; j < m; j++ )\n {\n printf(\"%0.2f \", A[i+j*m]);\n }\n printf(\"\\n\");\n }\n }\n \n iter++;\n\n }\n}\n```\n\nLet's run this code (on a very small data set, so that we don't overload the console by printing thousands of numbers).", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2/update && make clean && make laplace_no_update && ./laplace_no_update 10 10", "_____no_output_____" ] ], [ [ "We can see that the array is not changing. This is because the host copy of `A` is not being *updated* between loop iterations. Let's add the update directive, and see how the output changes.\n\n```cpp\n#pragma acc data copyin( A[:m*n],Anew[:m*n] )\n{\n while ( error > tol && iter < iter_max )\n {\n error = calcNext(A, Anew, m, n);\n swap(A, Anew, m, n);\n \n if(iter % 100 == 0)\n {\n printf(\"%5d, %0.6f\\n\", iter, error);\n \n #pragma acc update self(A[0:m*n])\n \n for( int i = 0; i < n; i++ )\n {\n for( int j = 0; j < m; j++ )\n {\n printf(\"%0.2f \", A[i+j*m]);\n }\n printf(\"\\n\");\n }\n }\n \n iter++;\n\n }\n}\n```", "_____no_output_____" ] ], [ [ "!cd ../source_code/lab2/update/solution && make clean && make laplace_update && ./laplace_update 10 10", "_____no_output_____" ] ], [ [ "Although you weren't required to add an `update` directive to this example code, except in the contrived example above, it's an extremely important directive for real applications because it allows you to do I/O or communication necessary for your code to execute without having to pay the cost of allocating and decallocating arrays on the device each time you do so.", "_____no_output_____" ], [ "---\n\n## Conclusion\n\nRelying on managed memory to handle data management can reduce the effort the programmer needs to parallelize their code, however, not all GPUs work with managed memory, and it is also lower performance than using explicit data management. In this lab you learned about how to use *data clauses* and *structured data directives* to explicitly manage device memory and remove your reliance on CUDA Managed Memory. ", "_____no_output_____" ], [ "---\n\n## Bonus Task\n\nIf you would like some additional lessons on using OpenACC, there is an Introduction to OpenACC video series available from the OpenACC YouTube page. The fifth video in the series covers a lot of the content that was covered in this lab. \n\n[Introduction to Parallel Programming with OpenACC - Part 5](https://youtu.be/0zTX7-CPvV8) ", "_____no_output_____" ], [ "## Post-Lab Summary\n\nIf you would like to download this lab for later viewing, it is recommend you go to your browsers File menu (not the Jupyter notebook file menu) and save the complete web page. This will ensure the images are copied down as well.\n\nYou can also execute the following cell block to create a zip-file of the files you've been working on, and download it with the link below.", "_____no_output_____" ] ], [ [ "%%bash\ncd ..\nrm -f openacc_files.zip\nzip -r openacc_files.zip *", "_____no_output_____" ] ], [ [ "**After** executing the above zip command, you should be able to download the zip file [here](../openacc_files.zip)\n\n--- \n\n## Licensing \n\nThis material is released by NVIDIA Corporation under the Creative Commons Attribution 4.0 International (CC BY 4.0). ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
cbe1a84a058dab7db9ba21eb0791b8b21d6a1ccc
7,843
ipynb
Jupyter Notebook
computer_vision/disparity_map_estimation.ipynb
suleymanaslan/bilkent-coursework
33b3e73d17a2b29800777e459809fc3e46f298a3
[ "MIT" ]
null
null
null
computer_vision/disparity_map_estimation.ipynb
suleymanaslan/bilkent-coursework
33b3e73d17a2b29800777e459809fc3e46f298a3
[ "MIT" ]
null
null
null
computer_vision/disparity_map_estimation.ipynb
suleymanaslan/bilkent-coursework
33b3e73d17a2b29800777e459809fc3e46f298a3
[ "MIT" ]
null
null
null
32.012245
168
0.573888
[ [ [ "%matplotlib inline\n\nimport cv2\nimport numpy as np\nimport scipy\n\nfrom tqdm.notebook import tqdm\n\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\n\nimport utils\nimport disparity_functions", "_____no_output_____" ], [ "data_ix = 1\nif data_ix == 0:\n img_list = [cv2.imread(\"dataset/data_disparity_estimation/Plastic/view1.png\"),\n cv2.imread(\"dataset/data_disparity_estimation/Plastic/view5.png\")]\n\nelif data_ix == 1:\n img_list = [cv2.imread(\"dataset/data_disparity_estimation/Cloth1/view1.png\"),\n cv2.imread(\"dataset/data_disparity_estimation/Cloth1/view5.png\")]", "_____no_output_____" ], [ "fig = plt.figure(figsize=(8*len(img_list), 8))\nfig.patch.set_facecolor('white')\nfor i in range(len(img_list)):\n plt.subplot(1, len(img_list), i+1)\n plt.imshow(cv2.cvtColor(img_list[i], cv2.COLOR_BGR2RGB))", "_____no_output_____" ], [ "keypoints, descriptors, img_keypoints = utils.find_keypoints(img_list)\nfig = plt.figure(figsize=(8*len(img_keypoints), 8))\nfig.patch.set_facecolor('white')\nfor i in range(len(img_keypoints)):\n plt.subplot(1, len(img_keypoints), i+1)\n plt.imshow(cv2.cvtColor(img_keypoints[i], cv2.COLOR_BGR2RGB))", "_____no_output_____" ], [ "matched_points, _ = utils.find_matches(descriptors, use_nndr=False, number_of_matches=50)\n\nfiltered_keypoints = []\nfiltered_keypoints.append([keypoints[0][match[0]] for match in matched_points])\nfiltered_keypoints.append([keypoints[1][match[1]] for match in matched_points])\nimg_keypoints = []\nimg_keypoints.append(cv2.drawKeypoints(img_list[0], filtered_keypoints[0], None))\nimg_keypoints.append(cv2.drawKeypoints(img_list[1], filtered_keypoints[1], None))\n\nfig = plt.figure(figsize=(8*len(img_keypoints), 8))\nfig.patch.set_facecolor('white')\nfor i in range(len(img_keypoints)):\n plt.subplot(1, len(img_keypoints), i+1)\n plt.imshow(cv2.cvtColor(img_keypoints[i], cv2.COLOR_BGR2RGB))", "_____no_output_____" ], [ "(_, mask) = cv2.findHomography(np.float32([kp.pt for kp in filtered_keypoints[1]]), \n np.float32([kp.pt for kp in filtered_keypoints[0]]), \n cv2.RANSAC, ransacReprojThreshold=3.0)", "_____no_output_____" ], [ "good_matches = []\ngood_points_l = []\ngood_points_r = []\n\nfor i in range(len(mask)):\n if mask[i] == 1:\n good_points_l.append(filtered_keypoints[0][i])\n good_points_r.append(filtered_keypoints[1][i])\n \ngood_matches.append(good_points_l)\ngood_matches.append(good_points_r)\n\nmatches1to2 = [cv2.DMatch(i, i, 0) for i in range(len(good_matches[0]))]\n\nmatching_img = cv2.drawMatches(img_list[0], filtered_keypoints[0], img_list[1], filtered_keypoints[1], matches1to2, None)\nfig = plt.figure(figsize=(16, 8))\nfig.patch.set_facecolor('white')\nplt.imshow(cv2.cvtColor(matching_img, cv2.COLOR_BGR2RGB))", "_____no_output_____" ], [ "left_img_rectified, right_img_rectified = disparity_functions.rectify_images(img_list, filtered_keypoints)\nfig = plt.figure(figsize=(8*2, 8))\nfig.patch.set_facecolor('white')\nplt.subplot(1, 2, 1)\nplt.imshow(cv2.cvtColor(left_img_rectified, cv2.COLOR_BGR2RGB))\nplt.subplot(1, 2, 2)\nplt.imshow(cv2.cvtColor(right_img_rectified, cv2.COLOR_BGR2RGB))", "_____no_output_____" ], [ "img_list_r = [cv2.resize(img, (0,0), fx=0.5, fy=0.5) for img in img_list]\nimg_l = img_list_r[0]\nimg_r = img_list_r[1]\nkeypoints_r, descriptors_l, descriptors_r, max_i, max_j = disparity_functions.compute_descriptors(img_l, img_r)", "_____no_output_____" ], [ "disp_img = np.zeros((img_l.shape[0], img_l.shape[1]))\nfor i in tqdm(range(img_l.shape[1])):\n for j in range(img_l.shape[0]):\n matched_point = disparity_functions.match_point(keypoints_r, descriptors_l, descriptors_r, (i, j), 40, max_i, max_j)\n disp_img[j][i] = np.sum(np.abs(np.subtract(matched_point, (i, j))))", "_____no_output_____" ], [ "fig = plt.figure(figsize=(8, 8))\nfig.patch.set_facecolor('white')\nplt.imshow(cv2.resize(disp_img, (0,0), fx=2.0, fy=2.0, interpolation=cv2.INTER_NEAREST), cmap='gray')", "_____no_output_____" ], [ "cv2.imwrite(f\"output/disparity_{data_ix}_1.png\", cv2.resize((((disp_img - np.min(disp_img)) / (np.max(disp_img) - np.min(disp_img))) * 255).astype(np.uint8),\n (0,0), fx=2.0, fy=2.0, interpolation=cv2.INTER_NEAREST))", "_____no_output_____" ], [ "disp_img = np.zeros((img_l.shape[0], img_l.shape[1]))\nfor i in tqdm(range(img_l.shape[1])):\n for j in range(img_l.shape[0]):\n matched_point = disparity_functions.match_point(keypoints_r, descriptors_l, descriptors_r, (i, j), 40, max_i, max_j, compute_right_img=True)\n disp_img[j][i] = np.sum(np.abs(np.subtract(matched_point, (i, j))))", "_____no_output_____" ], [ "fig = plt.figure(figsize=(8, 8))\nfig.patch.set_facecolor('white')\nplt.imshow(cv2.resize(disp_img, (0,0), fx=2.0, fy=2.0, interpolation=cv2.INTER_NEAREST), cmap='gray')", "_____no_output_____" ], [ "cv2.imwrite(f\"output/disparity_{data_ix}_2.png\", cv2.resize((((disp_img - np.min(disp_img)) / (np.max(disp_img) - np.min(disp_img))) * 255).astype(np.uint8),\n (0,0), fx=2.0, fy=2.0, interpolation=cv2.INTER_NEAREST))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe1b2fd56dc08623a3ed8ad64cad793be5c0abd
452,991
ipynb
Jupyter Notebook
older_model/figures/make_paper_figures.ipynb
seanrsinclair/Online-Resource-Allocation
235eda314cf3ed1499c5264120e3fabad12bb334
[ "MIT" ]
1
2021-12-01T10:56:40.000Z
2021-12-01T10:56:40.000Z
older_model/figures/make_paper_figures.ipynb
seanrsinclair/Online-Resource-Allocation
235eda314cf3ed1499c5264120e3fabad12bb334
[ "MIT" ]
null
null
null
older_model/figures/make_paper_figures.ipynb
seanrsinclair/Online-Resource-Allocation
235eda314cf3ed1499c5264120e3fabad12bb334
[ "MIT" ]
null
null
null
993.401316
441,096
0.954811
[ [ [ "import sys\nsys.path.insert(1, '../functions')\nimport importlib\nimport numpy as np\nimport nbformat\nimport plotly.express\nimport plotly.express as px\nimport pandas as pd\nimport scipy.optimize as optimization\nimport food_bank_functions\nimport food_bank_bayesian\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom food_bank_functions import *\nfrom food_bank_bayesian import *\nimport time\nimportlib.reload(food_bank_functions)\n\nnp.random.seed(1)", "_____no_output_____" ], [ "problem = 'poisson'", "_____no_output_____" ], [ "loc = '../simulations/' + problem + '/'", "_____no_output_____" ], [ "plt.style.use('PaperDoubleFig.mplstyle.txt')\n# Make some style choices for plotting \ncolorWheel =['#2bd1e5',\n '#281bf5',\n '#db1bf5',\n '#F5CD1B',\n '#FF5733','#9cf51b',]\ndash_styles = [\"\",\n (4, 1.5),\n (1, 1),\n (3, 1, 1.5, 1),\n (5, 1, 1, 1),\n (5, 1, 2, 1, 2, 1),\n (2, 2, 3, 1.5),\n (1, 2.5, 3, 1.2)]", "_____no_output_____" ] ], [ [ "# Scaling with n dataset", "_____no_output_____" ] ], [ [ "algos_to_exclude = ['Threshold','Expected-Filling', 'Expect-Threshold', 'Fixed-Threshold', 'Expected_Filling', 'Expect_Threshold', 'Fixed_Threshold']", "_____no_output_____" ], [ "df_one = pd.read_csv(loc+'scale_with_n.csv')", "_____no_output_____" ], [ "# algos_to_exclude = ['Threshold','Expected-Filling']\ndf_one = (df_one[~df_one.variable.isin(algos_to_exclude)]\n .rename({'variable': 'Algorithm'}, axis = 1)\n )", "_____no_output_____" ], [ "df_one = df_one.sort_values(by='Algorithm')", "_____no_output_____" ], [ "df_one.Algorithm.unique()", "_____no_output_____" ], [ "print(df_one.Algorithm.str.title)", "<bound method _noarg_wrapper.<locals>.wrapper of <pandas.core.strings.StringMethods object at 0x000001B47FE7BC48>>\n" ], [ "df_one.Algorithm.unique()", "_____no_output_____" ] ], [ [ "# Expected Waterfilling Levels", "_____no_output_____" ] ], [ [ "df_two = pd.read_csv(loc+'comparison_of_waterfilling_levels.csv')\ndf_two = (df_two[~df_two.variable.isin(algos_to_exclude)].rename({'variable': 'Algorithm'}, axis=1))\ndf_two['Algorithm'] = df_two['Algorithm'].replace({'hope_Online':'Hope-Online', 'hope_Full':'Hope-Full', 'et_Online':'ET-Online', 'et_Full':'ET-Full', 'Max_Min_Heuristic':'Max-Min'})\n\ndf_two = df_two.sort_values(by='Algorithm')\nprint(df_two.Algorithm.unique())", "['ET_Full' 'ET_Online' 'Hope_Full' 'Hope_Online' 'Max_Min' 'True']\n" ], [ "df_two.head", "_____no_output_____" ], [ "df_two = df_two.sort_values(by='Algorithm')", "_____no_output_____" ], [ "df_two.Algorithm.unique()", "_____no_output_____" ] ], [ [ "# Group allocation difference", "_____no_output_____" ] ], [ [ "df_three = pd.read_csv(loc+'fairness_group_by_group.csv')\ndf_three = (df_three[~df_three.variable.isin(algos_to_exclude)]\n .rename({'variable': 'Algorithm'}, axis = 1)\n )", "_____no_output_____" ], [ "df_three = df_three.sort_values(by='Algorithm')", "_____no_output_____" ], [ "df_three.Algorithm.unique()", "_____no_output_____" ], [ "legends = False", "_____no_output_____" ], [ "fig = plt.figure(figsize = (20,15))\n# Create an array with the colors you want to use\n\ncolors = [\"#FFC20A\", \"#1AFF1A\", \"#994F00\", \"#006CD1\", \"#D35FB7\", \"#40B0A6\", \"#E66100\"]# Set your custom color palette\n\nplt.subplot(2,2,1)\n\nsns.set_palette(sns.color_palette(colors))\nif legends:\n g = sns.lineplot(x='NumGroups', y='value', hue='Algorithm', style = 'Algorithm', dashes = dash_styles, data=df_one[df_one.Norm == 'Linf'])\nelse:\n g = sns.lineplot(x='NumGroups', y='value', hue='Algorithm', style = 'Algorithm', dashes = dash_styles, data=df_one[df_one.Norm == 'Linf'], legend=False)\nplt.xlabel('Number of Agents')\nplt.ylabel('Distance')\nplt.title('Maximum Difference Between OPT and ALG Allocations')\n\nplt.subplot(2,2,2)\nsns.set_palette(sns.color_palette(colors))\nif legends:\n g = sns.lineplot(x='NumGroups', y='value', hue='Algorithm', style = 'Algorithm', dashes = dash_styles, data=df_one[df_one.Norm == 'L1']) \nelse:\n g = sns.lineplot(x='NumGroups', y='value', hue='Algorithm', style = 'Algorithm', dashes = dash_styles, data=df_one[df_one.Norm == 'L1'], legend=False)\nplt.xlabel('Number of Agents')\nplt.ylabel('Distance')\nplt.title('Total Difference Between OPT and ALG Allocations')\n\nplt.subplot(2,2,3)\nnew_colors = colors[1:3] + colors[4:]+['#000000']\nnew_dashes = dash_styles[1:3]+dash_styles[4:]\nsns.set_palette(sns.color_palette(new_colors))\nif legends:\n g = sns.lineplot(x='Group', y='value', style='Algorithm', hue = 'Algorithm', data=df_two, dashes=new_dashes)\nelse:\n g = sns.lineplot(x='Group', y='value', style='Algorithm', hue = 'Algorithm', data=df_two, dashes=new_dashes, legend=False)\nplt.title('Estimated Threshold Level by Agent')\nplt.xlabel('Agent')\nplt.ylabel('Level')\n# plt.xlabel('Estimated Level')\n\nplt.subplot(2,2,4)\nsns.set_palette(sns.color_palette(colors))\n\ntry:\n sns.lineplot(x='Agent', y='value', hue='Algorithm', data=df_three, style = 'Algorithm', dashes = dash_styles)\nexcept ValueError:\n sns.lineplot(x='Group', y='value', hue='Algorithm', data=df_three, style = 'Algorithm', dashes = dash_styles)\nplt.title('Allocation Difference per Agent between OPT and ALG')\nplt.ylabel('Difference')\nplt.xlabel('Agent')\n\nplt.show()\nfig.savefig(problem+'.pdf', bbox_inches = 'tight',pad_inches = 0.01, dpi=900)", "_____no_output_____" ], [ "print(colors)", "['#FFC20A', '#1AFF1A', '#994F00', '#006CD1', '#D35FB7', '#40B0A6', '#E66100']\n" ], [ "print(new_colors)", "['#1AFF1A', '#994F00', '#D35FB7', '#40B0A6', '#E66100', '#000000']\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbe1b98e9b1119c8beb8b616d6a68dcd339a4b85
1,782
ipynb
Jupyter Notebook
T_Test.ipynb
amcodec1/My_Practice_Notebooks
27c17ec0f660651664e473b30936f77dd09f4362
[ "MIT" ]
null
null
null
T_Test.ipynb
amcodec1/My_Practice_Notebooks
27c17ec0f660651664e473b30936f77dd09f4362
[ "MIT" ]
null
null
null
T_Test.ipynb
amcodec1/My_Practice_Notebooks
27c17ec0f660651664e473b30936f77dd09f4362
[ "MIT" ]
null
null
null
22.846154
91
0.551627
[ [ [ "import numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nimport random\nimport math", "_____no_output_____" ], [ "%matplotlib inline\n# 1-sample t-testfrom scipy import stats\navg_height_of_indian_men_2017 = 165\none_sample_data = [177.3, 159, 173, 176.3, 165, 175.4, 178.5, 177.2, 181.8, 176.5]\nmean_1 = avg_height_of_indian_men_2017\none_sample = stats.ttest_1samp(one_sample_data, avg_height_of_indian_men_2017)\nt_critical = stats.t.ppf(q = 0.975, df=9) \nprint \"Mean of one_sample = %0.3f\"%mean_1\nprint \"t=critical value = %0.3f.\" %t_critical\nprint \"The t-statistic is %.3f and the p-value is %.3f.\" % one_sample", "Mean of one_sample = 165.000\nt=critical value = 2.262.\nThe t-statistic is 4.153 and the p-value is 0.002.\n" ], [ "\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbe1be7421a1f20141bec6c1aae3f007906ddac2
1,403
ipynb
Jupyter Notebook
code/algorithms/course_udemy_1/Riddles/Interview/Problems/.ipynb_checkpoints/Egg Drop -checkpoint.ipynb
vicb1/miscellaneous
2c9762579abf75ef6cba75d1d1536a693d69e82a
[ "MIT" ]
null
null
null
code/algorithms/course_udemy_1/Riddles/Interview/Problems/.ipynb_checkpoints/Egg Drop -checkpoint.ipynb
vicb1/miscellaneous
2c9762579abf75ef6cba75d1d1536a693d69e82a
[ "MIT" ]
null
null
null
code/algorithms/course_udemy_1/Riddles/Interview/Problems/.ipynb_checkpoints/Egg Drop -checkpoint.ipynb
vicb1/miscellaneous
2c9762579abf75ef6cba75d1d1536a693d69e82a
[ "MIT" ]
null
null
null
35.974359
460
0.66144
[ [ [ "# Egg Drop \nThis is probably the most common brain teaser riddle out of the group, so really try to think algorithmically about this problem before looking at the solution!\n## Problem Statement\n\nA tower has 100 floors. You've been given two eggs. The eggs are strong enough that they can be dropped from a particular floor in the tower without breaking. You've been tasked to find the highest floor an egg can be dropped without breaking, in as few drops as possible. If an egg is dropped from above its target floor it will break. If it is dropped from that floor or below, it will be intact and you can test drop the egg again on another floor.\n\nShow algorithmically how you would go about doing this in as few drops as possible. (Your answer should be a number of the fewest drops needed for testing 2 eggs on 100 floors)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
cbe1bf9834148d2dad314f8e0bf5878bd8e5f6c0
110,009
ipynb
Jupyter Notebook
blogs/DipanjanS/data_science_for_all/Working with SQL at Scale - Spark SQL Tutorial.ipynb
machine-learning-helpers/induction-books-python
d26816f92d4f6a64e8c4c2ed6c7c8343c77cd3ad
[ "RSA-MD" ]
3
2018-02-11T12:34:19.000Z
2021-09-22T18:06:01.000Z
blogs/DipanjanS/data_science_for_all/Working with SQL at Scale - Spark SQL Tutorial.ipynb
machine-learning-helpers/induction-books-python
d26816f92d4f6a64e8c4c2ed6c7c8343c77cd3ad
[ "RSA-MD" ]
17
2019-11-22T00:48:20.000Z
2022-01-16T11:00:50.000Z
blogs/DipanjanS/data_science_for_all/Working with SQL at Scale - Spark SQL Tutorial.ipynb
machine-learning-helpers/induction-python
631a735a155f0feb7012472fbca13efbc273dfb0
[ "RSA-MD" ]
null
null
null
55,004.5
110,008
0.727713
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbe1c3564b509d608d96d973272b4454ab27b40c
3,299
ipynb
Jupyter Notebook
stable/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
stable/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
stable/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
36.655556
1,120
0.562898
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n# Compute power spectrum densities of the sources with dSPM\n\n\nReturns an STC file containing the PSD (in dB) of each of the sources.\n", "_____no_output_____" ] ], [ [ "# Authors: Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne import io\nfrom mne.datasets import sample\nfrom mne.minimum_norm import read_inverse_operator, compute_source_psd\n\nprint(__doc__)", "_____no_output_____" ] ], [ [ "Set parameters\n\n", "_____no_output_____" ] ], [ [ "data_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'\nfname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'\nfname_label = data_path + '/MEG/sample/labels/Aud-lh.label'\n\n# Setup for reading the raw data\nraw = io.read_raw_fif(raw_fname, verbose=False)\nevents = mne.find_events(raw, stim_channel='STI 014')\ninverse_operator = read_inverse_operator(fname_inv)\nraw.info['bads'] = ['MEG 2443', 'EEG 053']\n\n# picks MEG gradiometers\npicks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,\n stim=False, exclude='bads')\n\ntmin, tmax = 0, 120 # use the first 120s of data\nfmin, fmax = 4, 100 # look at frequencies between 4 and 100Hz\nn_fft = 2048 # the FFT size (n_fft). Ideally a power of 2\nlabel = mne.read_label(fname_label)\n\nstc = compute_source_psd(raw, inverse_operator, lambda2=1. / 9., method=\"dSPM\",\n tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax,\n pick_ori=\"normal\", n_fft=n_fft, label=label,\n dB=True)\n\nstc.save('psd_dSPM')", "_____no_output_____" ] ], [ [ "View PSD of sources in label\n\n", "_____no_output_____" ] ], [ [ "plt.plot(1e3 * stc.times, stc.data.T)\nplt.xlabel('Frequency (Hz)')\nplt.ylabel('PSD (dB)')\nplt.title('Source Power Spectrum (PSD)')\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe1dca63f76e55de43370e4b46ea08473a731f0
210,647
ipynb
Jupyter Notebook
6.3_advanced_use_of_recurrent_neural_networks.ipynb
agaitanis/deep_learning_with_python
590e4171c4e4e83136a8633665586e07f0d4c2e3
[ "MIT" ]
1
2019-02-28T16:03:05.000Z
2019-02-28T16:03:05.000Z
6.3_advanced_use_of_recurrent_neural_networks.ipynb
agaitanis/deep_learning_with_python
590e4171c4e4e83136a8633665586e07f0d4c2e3
[ "MIT" ]
null
null
null
6.3_advanced_use_of_recurrent_neural_networks.ipynb
agaitanis/deep_learning_with_python
590e4171c4e4e83136a8633665586e07f0d4c2e3
[ "MIT" ]
null
null
null
156.498514
24,104
0.838431
[ [ [ "import sys\nimport keras\nimport tensorflow as tf\n\nprint('python version:', sys.version)\nprint('keras version:', keras.__version__)\nprint('tensorflow version:', tf.__version__)", "Using TensorFlow backend.\n" ] ], [ [ "# 6.3 Advanced use of recurrent neural networks\n---\n## A temperature-forecasting problem", "_____no_output_____" ], [ "### Inspecting the data of the Jena weather dataset", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n%matplotlib inline\n\ndata_dir = 'jena_climate'\nfname = os.path.join(data_dir, 'jena_climate_2009_2016.csv')\n\nf = open(fname)\ndata = f.read()\nf.close()\n\nlines = data.split('\\n')\nheader = lines[0].split(',')\nlines = lines[1:]\n\nprint(header)\nprint(len(lines))", "['\"Date Time\"', '\"p (mbar)\"', '\"T (degC)\"', '\"Tpot (K)\"', '\"Tdew (degC)\"', '\"rh (%)\"', '\"VPmax (mbar)\"', '\"VPact (mbar)\"', '\"VPdef (mbar)\"', '\"sh (g/kg)\"', '\"H2OC (mmol/mol)\"', '\"rho (g/m**3)\"', '\"wv (m/s)\"', '\"max. wv (m/s)\"', '\"wd (deg)\"']\n420551\n" ] ], [ [ "### Parsing the data", "_____no_output_____" ] ], [ [ "float_data = np.zeros((len(lines), len(header) - 1))\n\nfor i, line in enumerate(lines):\n values = [float(x) for x in line.split(',')[1:]]\n float_data[i, :] = values", "_____no_output_____" ] ], [ [ "### Plotting the temperature timeseries", "_____no_output_____" ] ], [ [ "temp = float_data[:, 1]\nplt.plot(range(len(temp)), temp)\nplt.show()", "_____no_output_____" ] ], [ [ "### Plotting the first 10 days of the temperature timeseries", "_____no_output_____" ] ], [ [ "plt.plot(range(1440), temp[:1440])\nplt.show()", "_____no_output_____" ] ], [ [ "### Normalizing the data", "_____no_output_____" ] ], [ [ "mean = float_data[:200000].mean(axis = 0)\nfloat_data -= mean\nstd = float_data[:200000].std(axis = 0)\nfloat_data /= std", "_____no_output_____" ] ], [ [ "### Generator yielding timeseries samples and their targets", "_____no_output_____" ] ], [ [ "def generator(data, lookback, delay, min_index, max_index,\n shuffle = False, batch_size = 128, step = 6, revert = False):\n if max_index is None:\n max_index = len(data) - delay - 1\n i = min_index + lookback\n \n while 1:\n if shuffle:\n rows = np.random.randint(min_index + lookback, max_index, size = batch_size)\n else:\n if i + batch_size >= max_index:\n i = min_index + lookback\n rows = np.arange(i, min(i + batch_size, max_index))\n i += len(rows)\n \n samples = np.zeros((len(rows), lookback//step, data.shape[-1]))\n targets = np.zeros((len(rows),))\n \n for j, row in enumerate(rows):\n indices = range(rows[j] - lookback, rows[j], step)\n samples[j] = data[indices]\n targets[j] = data[rows[j] + delay][1]\n \n if revert:\n yield samples[:, ::-1, :], targets\n else:\n yield samples, targets", "_____no_output_____" ] ], [ [ "### Preparing the training, validation and test generators", "_____no_output_____" ] ], [ [ "lookback = 1440\nstep = 6\ndelay = 144\nbatch_size = 128\n\ntrain_gen = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 0,\n max_index = 200000,\n shuffle = True,\n step = step,\n batch_size = batch_size)\n\nval_gen = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 200001,\n max_index = 300000,\n step = step,\n batch_size = batch_size)\n\ntest_gen = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 300001,\n max_index = None,\n step = step,\n batch_size = batch_size)\n\ntrain_gen_r = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 0,\n max_index = 200000,\n shuffle = True,\n step = step,\n batch_size = batch_size,\n revert = True)\n\nval_gen_r = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 200001,\n max_index = 300000,\n step = step,\n batch_size = batch_size,\n revert = True)\n\ntest_gen_r = generator(float_data,\n lookback = lookback,\n delay = delay,\n min_index = 300001,\n max_index = None,\n step = step,\n batch_size = batch_size,\n revert = True)\n\n# How many steps to draw from val_gen in order to see the entire validation set\nval_steps = (300000 - 200001 - lookback) // batch_size\n\n# How many steps to draw from test_gen in order to see the entire test set\ntest_steps = (len(float_data) - 300001 - lookback) // batch_size", "_____no_output_____" ] ], [ [ "### Computing the common-sense baseline MAE", "_____no_output_____" ] ], [ [ "def evaluate_naive_method():\n batch_maes = []\n for step in range(val_steps):\n samples, targets = next(val_gen)\n preds = samples[:, -1, 1]\n mae = np.mean(np.abs(preds - targets))\n batch_maes.append(mae)\n print(np.mean(batch_maes))\n\nevaluate_naive_method()", "0.2897359729905486\n" ] ], [ [ "### Training and evaluating a densely connected model", "_____no_output_____" ] ], [ [ "from keras import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.Flatten(input_shape = (lookback // step, float_data.shape[-1])))\nmodel.add(layers.Dense(32, activation = 'relu'))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\nhistory = model.fit_generator(train_gen,\n steps_per_epoch = 500,\n epochs = 20,\n validation_data = val_gen,\n validation_steps = val_steps)", "Epoch 1/20\n500/500 [==============================] - 10s 19ms/step - loss: 1.4729 - val_loss: 0.6716\nEpoch 2/20\n500/500 [==============================] - 10s 19ms/step - loss: 0.5668 - val_loss: 0.2824\nEpoch 3/20\n500/500 [==============================] - 10s 19ms/step - loss: 0.3173 - val_loss: 0.2395\nEpoch 4/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2745 - val_loss: 0.2512\nEpoch 5/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2580 - val_loss: 0.2883\nEpoch 6/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2497 - val_loss: 0.2913\nEpoch 7/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2402 - val_loss: 0.3340\nEpoch 8/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2341 - val_loss: 0.3189\nEpoch 9/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2294 - val_loss: 0.2732\nEpoch 10/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2269 - val_loss: 0.2660\nEpoch 11/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2238 - val_loss: 0.2138\nEpoch 12/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2214 - val_loss: 0.2648\nEpoch 13/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2164 - val_loss: 0.2866\nEpoch 14/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2157 - val_loss: 0.2729\nEpoch 15/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2127 - val_loss: 0.2477\nEpoch 16/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2098 - val_loss: 0.2757\nEpoch 17/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2075 - val_loss: 0.2396\nEpoch 18/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2049 - val_loss: 0.2714\nEpoch 19/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2040 - val_loss: 0.3487\nEpoch 20/20\n500/500 [==============================] - 9s 19ms/step - loss: 0.2028 - val_loss: 0.2871\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Training and evaluating a GRU-based model", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.GRU(32,\n implementation = 1,\n input_shape = (None, float_data.shape[-1])))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\n\nhistory = model.fit_generator(train_gen,\n steps_per_epoch = 500,\n epochs = 20,\n validation_data = val_gen,\n validation_steps = val_steps)", "Epoch 1/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2980 - val_loss: 0.3195\nEpoch 2/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2847 - val_loss: 0.3473\nEpoch 3/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2806 - val_loss: 0.3474\nEpoch 4/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2742 - val_loss: 0.3503\nEpoch 5/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2705 - val_loss: 0.3574\nEpoch 6/20\n500/500 [==============================] - 112s 223ms/step - loss: 0.2665 - val_loss: 0.3738\nEpoch 7/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2604 - val_loss: 0.3774\nEpoch 8/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2577 - val_loss: 0.3480\nEpoch 9/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2547 - val_loss: 0.3596\nEpoch 10/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2504 - val_loss: 0.3517\nEpoch 11/20\n500/500 [==============================] - 112s 223ms/step - loss: 0.2467 - val_loss: 0.3934\nEpoch 12/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2419 - val_loss: 0.3751\nEpoch 13/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2409 - val_loss: 0.3757\nEpoch 14/20\n500/500 [==============================] - 111s 223ms/step - loss: 0.2377 - val_loss: 0.3973\nEpoch 15/20\n500/500 [==============================] - 112s 223ms/step - loss: 0.2332 - val_loss: 0.3903\nEpoch 16/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2287 - val_loss: 0.3980\nEpoch 17/20\n500/500 [==============================] - 111s 223ms/step - loss: 0.2251 - val_loss: 0.3653\nEpoch 18/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2205 - val_loss: 0.4370\nEpoch 19/20\n500/500 [==============================] - 112s 224ms/step - loss: 0.2172 - val_loss: 0.3876\nEpoch 20/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.2143 - val_loss: 0.3970\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Training and evaluating a dropout-regularized GRU-based model", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.GRU(32,\n implementation = 1,\n dropout = 0.2,\n recurrent_dropout = 0.2,\n input_shape = (None, float_data.shape[-1])))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\n\nhistory = model.fit_generator(train_gen,\n steps_per_epoch = 500,\n epochs = 40,\n validation_data = val_gen,\n validation_steps = val_steps)", "Epoch 1/40\n500/500 [==============================] - 132s 264ms/step - loss: 0.3396 - val_loss: 0.3607\nEpoch 2/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.3178 - val_loss: 0.3121\nEpoch 3/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.3120 - val_loss: 0.2772\nEpoch 4/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.3051 - val_loss: 0.2512\nEpoch 5/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.3011 - val_loss: 0.2310\nEpoch 6/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2984 - val_loss: 0.2308\nEpoch 7/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2973 - val_loss: 0.1925\nEpoch 8/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2957 - val_loss: 0.1910\nEpoch 9/40\n500/500 [==============================] - 132s 264ms/step - loss: 0.2916 - val_loss: 0.1659\nEpoch 10/40\n500/500 [==============================] - 132s 263ms/step - loss: 0.2912 - val_loss: 0.1695\nEpoch 11/40\n500/500 [==============================] - 132s 263ms/step - loss: 0.2900 - val_loss: 0.1607\nEpoch 12/40\n500/500 [==============================] - 130s 260ms/step - loss: 0.2890 - val_loss: 0.1244\nEpoch 13/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2860 - val_loss: 0.1405\nEpoch 14/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2848 - val_loss: 0.1140\nEpoch 15/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2858 - val_loss: 0.0965\nEpoch 16/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2832 - val_loss: 0.1384\nEpoch 17/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2828 - val_loss: 0.1235\nEpoch 18/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2818 - val_loss: 0.1068\nEpoch 19/40\n500/500 [==============================] - 133s 265ms/step - loss: 0.2826 - val_loss: 0.1112\nEpoch 20/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2801 - val_loss: 0.1187\nEpoch 21/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2810 - val_loss: 0.1231\nEpoch 22/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2786 - val_loss: 0.1397\nEpoch 23/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2786 - val_loss: 0.1119\nEpoch 24/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2759 - val_loss: 0.1190\nEpoch 25/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2770 - val_loss: 0.1137\nEpoch 26/40\n500/500 [==============================] - 132s 263ms/step - loss: 0.2744 - val_loss: 0.0967\nEpoch 27/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2727 - val_loss: 0.1121\nEpoch 28/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2749 - val_loss: 0.1107\nEpoch 29/40\n500/500 [==============================] - 130s 260ms/step - loss: 0.2739 - val_loss: 0.1035\nEpoch 30/40\n500/500 [==============================] - 130s 260ms/step - loss: 0.2730 - val_loss: 0.1151\nEpoch 31/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2719 - val_loss: 0.1110\nEpoch 32/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2719 - val_loss: 0.1047\nEpoch 33/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2709 - val_loss: 0.1130\nEpoch 34/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2711 - val_loss: 0.0954\nEpoch 35/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2715 - val_loss: 0.0979\nEpoch 36/40\n500/500 [==============================] - 131s 262ms/step - loss: 0.2689 - val_loss: 0.1260\nEpoch 37/40\n500/500 [==============================] - 132s 264ms/step - loss: 0.2684 - val_loss: 0.1002\nEpoch 38/40\n500/500 [==============================] - 132s 263ms/step - loss: 0.2674 - val_loss: 0.1196\nEpoch 39/40\n500/500 [==============================] - 131s 261ms/step - loss: 0.2680 - val_loss: 0.1154\nEpoch 40/40\n500/500 [==============================] - 130s 261ms/step - loss: 0.2667 - val_loss: 0.1094\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Training and evaluating a dropout-regularized, stacked GRU model", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.GRU(32,\n implementation = 1,\n dropout = 0.1,\n recurrent_dropout = 0.5,\n return_sequences = True,\n input_shape = (None, float_data.shape[-1])))\nmodel.add(layers.GRU(64,\n implementation = 1,\n activation = 'relu',\n dropout = 0.1,\n recurrent_dropout = 0.5))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\n\nhistory = model.fit_generator(train_gen,\n steps_per_epoch = 500,\n epochs = 40,\n validation_data = val_gen,\n validation_steps = val_steps)", "Epoch 1/40\n500/500 [==============================] - 272s 544ms/step - loss: 0.3343 - val_loss: 0.3196\nEpoch 2/40\n500/500 [==============================] - 270s 541ms/step - loss: 0.3115 - val_loss: 0.3645\nEpoch 3/40\n500/500 [==============================] - 270s 539ms/step - loss: 0.3066 - val_loss: 0.3743\nEpoch 4/40\n500/500 [==============================] - 271s 542ms/step - loss: 0.3014 - val_loss: 0.3528\nEpoch 5/40\n500/500 [==============================] - 271s 542ms/step - loss: 0.2982 - val_loss: 0.3656\nEpoch 6/40\n500/500 [==============================] - 269s 539ms/step - loss: 0.2951 - val_loss: 0.3426\nEpoch 7/40\n500/500 [==============================] - 270s 540ms/step - loss: 0.2934 - val_loss: 0.3331\nEpoch 8/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2910 - val_loss: 0.2878\nEpoch 9/40\n500/500 [==============================] - 268s 537ms/step - loss: 0.2875 - val_loss: 0.2180\nEpoch 10/40\n500/500 [==============================] - 269s 539ms/step - loss: 0.2831 - val_loss: 0.3205\nEpoch 11/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2828 - val_loss: 0.3026\nEpoch 12/40\n500/500 [==============================] - 269s 539ms/step - loss: 0.2812 - val_loss: 0.2925\nEpoch 13/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2775 - val_loss: 0.2927\nEpoch 14/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2760 - val_loss: 0.2238\nEpoch 15/40\n500/500 [==============================] - 270s 539ms/step - loss: 0.2755 - val_loss: 0.2486\nEpoch 16/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2730 - val_loss: 0.2210\nEpoch 17/40\n500/500 [==============================] - 270s 540ms/step - loss: 0.2726 - val_loss: 0.2071\nEpoch 18/40\n500/500 [==============================] - 271s 542ms/step - loss: 0.2698 - val_loss: 0.2640\nEpoch 19/40\n500/500 [==============================] - 270s 540ms/step - loss: 0.2670 - val_loss: 0.2151\nEpoch 20/40\n500/500 [==============================] - 268s 536ms/step - loss: 0.2677 - val_loss: 0.2260\nEpoch 21/40\n500/500 [==============================] - 270s 539ms/step - loss: 0.2662 - val_loss: 0.2454\nEpoch 22/40\n500/500 [==============================] - 268s 537ms/step - loss: 0.2657 - val_loss: 0.2588\nEpoch 23/40\n500/500 [==============================] - 268s 537ms/step - loss: 0.2643 - val_loss: 0.3296\nEpoch 24/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2637 - val_loss: 0.2207\nEpoch 25/40\n500/500 [==============================] - 268s 536ms/step - loss: 0.2624 - val_loss: 0.2556\nEpoch 26/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2597 - val_loss: 0.2375\nEpoch 27/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2597 - val_loss: 0.2617\nEpoch 28/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2608 - val_loss: 0.1483\nEpoch 29/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2581 - val_loss: 0.1491\nEpoch 30/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2591 - val_loss: 0.2073\nEpoch 31/40\n500/500 [==============================] - 268s 537ms/step - loss: 0.2575 - val_loss: 0.1844\nEpoch 32/40\n500/500 [==============================] - 268s 536ms/step - loss: 0.2565 - val_loss: 0.1762\nEpoch 33/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2553 - val_loss: 0.2028\nEpoch 34/40\n500/500 [==============================] - 268s 535ms/step - loss: 0.2547 - val_loss: 0.1651\nEpoch 35/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2541 - val_loss: 0.3088\nEpoch 36/40\n500/500 [==============================] - 268s 535ms/step - loss: 0.2519 - val_loss: 0.2785\nEpoch 37/40\n500/500 [==============================] - 269s 538ms/step - loss: 0.2517 - val_loss: 0.2566\nEpoch 38/40\n500/500 [==============================] - 269s 537ms/step - loss: 0.2529 - val_loss: 0.2509\nEpoch 39/40\n500/500 [==============================] - 270s 539ms/step - loss: 0.2518 - val_loss: 0.1870\nEpoch 40/40\n500/500 [==============================] - 268s 537ms/step - loss: 0.2499 - val_loss: 0.2100\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Training and evaluating an GRU-based model using reversed sequences", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.GRU(32,\n implementation = 1,\n input_shape = (None, float_data.shape[-1])))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\n\nhistory = model.fit_generator(train_gen_r,\n steps_per_epoch = 500,\n epochs = 20,\n validation_data = val_gen_r,\n validation_steps = val_steps)", "Epoch 1/20\n500/500 [==============================] - 115s 229ms/step - loss: 0.4803 - val_loss: 0.1689\nEpoch 2/20\n500/500 [==============================] - 114s 228ms/step - loss: 0.4316 - val_loss: 0.1871\nEpoch 3/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.3892 - val_loss: 0.2125\nEpoch 4/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.3501 - val_loss: 0.3165\nEpoch 5/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.3253 - val_loss: 0.3471\nEpoch 6/20\n500/500 [==============================] - 114s 227ms/step - loss: 0.3066 - val_loss: 0.2843\nEpoch 7/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2954 - val_loss: 0.1967\nEpoch 8/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2874 - val_loss: 0.1841\nEpoch 9/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.2768 - val_loss: 0.1796\nEpoch 10/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2695 - val_loss: 0.1128\nEpoch 11/20\n500/500 [==============================] - 114s 227ms/step - loss: 0.2650 - val_loss: 0.1606\nEpoch 12/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2600 - val_loss: 0.1946\nEpoch 13/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2557 - val_loss: 0.1295\nEpoch 14/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.2507 - val_loss: 0.2283\nEpoch 15/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.2460 - val_loss: 0.1619\nEpoch 16/20\n500/500 [==============================] - 112s 225ms/step - loss: 0.2410 - val_loss: 0.1570\nEpoch 17/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2389 - val_loss: 0.2195\nEpoch 18/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2348 - val_loss: 0.1838\nEpoch 19/20\n500/500 [==============================] - 113s 225ms/step - loss: 0.2332 - val_loss: 0.1683\nEpoch 20/20\n500/500 [==============================] - 113s 226ms/step - loss: 0.2294 - val_loss: 0.1413\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "### Training and evaluating an LSTM using reversed sequences", "_____no_output_____" ] ], [ [ "from keras.datasets import imdb\nfrom keras.preprocessing import sequence\nfrom keras import layers\nfrom keras.models import Sequential\n\nmax_features = 10000 # Number of words to consider as features\nmaxlen = 500 # Cuts off texts after this number of words\n\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = max_features)\n\n# Reverses sequences\nx_train = [x[::-1] for x in x_train]\nx_test = [x[::-1] for x in x_test]\n\n# Pads sequences\nx_train = sequence.pad_sequences(x_train, maxlen = maxlen)\nx_test = sequence.pad_sequences(x_test, maxlen = maxlen)\n\nmodel = Sequential()\nmodel.add(layers.Embedding(max_features, 128))\nmodel.add(layers.LSTM(32))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n\nmodel.compile(optimizer = 'rmsprop',\n loss = 'binary_crossentropy',\n metrics = ['acc'])\n\nhistory = model.fit(x_train, y_train,\n epochs = 10,\n batch_size = 128,\n validation_split = 0.2)", "C:\\Users\\alexa\\anaconda3\\envs\\keras-gpu\\lib\\site-packages\\tensorflow_core\\python\\framework\\indexed_slices.py:433: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n" ] ], [ [ "### Training and evaluating a bidirectional LSTM", "_____no_output_____" ] ], [ [ "model = Sequential()\nmodel.add(layers.Embedding(max_features, 32))\nmodel.add(layers.Bidirectional(layers.LSTM(32)))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n\nmodel.compile(optimizer = 'rmsprop',\n loss = 'binary_crossentropy',\n metrics = ['acc'])\n\nhistory = model.fit(x_train, y_train,\n epochs = 10,\n batch_size = 128,\n validation_split = 0.2)", "C:\\Users\\alexa\\anaconda3\\envs\\keras-gpu\\lib\\site-packages\\tensorflow_core\\python\\framework\\indexed_slices.py:433: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n" ] ], [ [ "### Training a bidirectional GRU", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras import layers\nfrom keras.optimizers import RMSprop\n\nmodel = Sequential()\nmodel.add(layers.Bidirectional(layers.GRU(32, implementation = 1),\n input_shape = (None, float_data.shape[-1])))\nmodel.add(layers.Dense(1))\n\nmodel.compile(optimizer = RMSprop(), loss = 'mae')\n\nhistory = model.fit_generator(train_gen,\n steps_per_epoch = 500,\n epochs = 40,\n validation_data = val_gen,\n validation_steps = val_steps)", "Epoch 1/40\n500/500 [==============================] - 226s 451ms/step - loss: 0.2954 - val_loss: 0.0823\nEpoch 2/40\n500/500 [==============================] - 224s 447ms/step - loss: 0.2741 - val_loss: 0.0969\nEpoch 3/40\n500/500 [==============================] - 223s 447ms/step - loss: 0.2685 - val_loss: 0.0955\nEpoch 4/40\n500/500 [==============================] - 226s 453ms/step - loss: 0.2635 - val_loss: 0.0743\nEpoch 5/40\n500/500 [==============================] - 226s 453ms/step - loss: 0.2587 - val_loss: 0.0794\nEpoch 6/40\n500/500 [==============================] - 228s 456ms/step - loss: 0.2536 - val_loss: 0.0699\nEpoch 7/40\n500/500 [==============================] - 226s 452ms/step - loss: 0.2475 - val_loss: 0.0770\nEpoch 8/40\n500/500 [==============================] - 228s 455ms/step - loss: 0.2396 - val_loss: 0.0718\nEpoch 9/40\n500/500 [==============================] - 230s 461ms/step - loss: 0.2344 - val_loss: 0.0793\nEpoch 10/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.2285 - val_loss: 0.0621\nEpoch 11/40\n500/500 [==============================] - 221s 443ms/step - loss: 0.2230 - val_loss: 0.0838\nEpoch 12/40\n500/500 [==============================] - 222s 444ms/step - loss: 0.2155 - val_loss: 0.0772\nEpoch 13/40\n500/500 [==============================] - 222s 444ms/step - loss: 0.2077 - val_loss: 0.1217\nEpoch 14/40\n500/500 [==============================] - 223s 445ms/step - loss: 0.2020 - val_loss: 0.1004\nEpoch 15/40\n500/500 [==============================] - 224s 447ms/step - loss: 0.1981 - val_loss: 0.1418\nEpoch 16/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1920 - val_loss: 0.0877\nEpoch 17/40\n500/500 [==============================] - 224s 447ms/step - loss: 0.1878 - val_loss: 0.1498\nEpoch 18/40\n500/500 [==============================] - 223s 445ms/step - loss: 0.1849 - val_loss: 0.1977\nEpoch 19/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1806 - val_loss: 0.1507\nEpoch 20/40\n500/500 [==============================] - 222s 443ms/step - loss: 0.1767 - val_loss: 0.2209\nEpoch 21/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1726 - val_loss: 0.0736\nEpoch 22/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1697 - val_loss: 0.1049\nEpoch 23/40\n500/500 [==============================] - 221s 442ms/step - loss: 0.1650 - val_loss: 0.1468\nEpoch 24/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1628 - val_loss: 0.0998\nEpoch 25/40\n500/500 [==============================] - 224s 447ms/step - loss: 0.1595 - val_loss: 0.1110\nEpoch 26/40\n500/500 [==============================] - 225s 451ms/step - loss: 0.1561 - val_loss: 0.0923\nEpoch 27/40\n500/500 [==============================] - 225s 451ms/step - loss: 0.1535 - val_loss: 0.0897\nEpoch 28/40\n500/500 [==============================] - 225s 451ms/step - loss: 0.1510 - val_loss: 0.0983\nEpoch 29/40\n500/500 [==============================] - 224s 448ms/step - loss: 0.1490 - val_loss: 0.0934\nEpoch 30/40\n500/500 [==============================] - 224s 449ms/step - loss: 0.1478 - val_loss: 0.0977\nEpoch 31/40\n500/500 [==============================] - 224s 448ms/step - loss: 0.1455 - val_loss: 0.1137\nEpoch 32/40\n500/500 [==============================] - 224s 448ms/step - loss: 0.1449 - val_loss: 0.0862\nEpoch 33/40\n500/500 [==============================] - 223s 446ms/step - loss: 0.1415 - val_loss: 0.1325\nEpoch 34/40\n500/500 [==============================] - 224s 448ms/step - loss: 0.1409 - val_loss: 0.0872\nEpoch 35/40\n500/500 [==============================] - 224s 449ms/step - loss: 0.1393 - val_loss: 0.1202\nEpoch 36/40\n500/500 [==============================] - 224s 449ms/step - loss: 0.1363 - val_loss: 0.1354\nEpoch 37/40\n500/500 [==============================] - 222s 445ms/step - loss: 0.1356 - val_loss: 0.0875\nEpoch 38/40\n500/500 [==============================] - 223s 447ms/step - loss: 0.1353 - val_loss: 0.1132\nEpoch 39/40\n500/500 [==============================] - 223s 447ms/step - loss: 0.1323 - val_loss: 0.1164\nEpoch 40/40\n500/500 [==============================] - 225s 450ms/step - loss: 0.1327 - val_loss: 0.1174\n" ] ], [ [ "### Plotting results", "_____no_output_____" ] ], [ [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\nplt.figure()\nplt.plot(epochs, loss, 'bo', label = 'Training loss')\nplt.plot(epochs, val_loss, 'b', label = 'Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe1ec2b98e9ffc08a4f61841f56a0b0a6023f3a
2,217
ipynb
Jupyter Notebook
ReproducingMLpipelines/Paper29/ModelBN.ipynb
CompareML/AIM-Manuscript
4cf118c1f06e8a1843d56e1f7f8f3d1698aac248
[ "MIT" ]
null
null
null
ReproducingMLpipelines/Paper29/ModelBN.ipynb
CompareML/AIM-Manuscript
4cf118c1f06e8a1843d56e1f7f8f3d1698aac248
[ "MIT" ]
null
null
null
ReproducingMLpipelines/Paper29/ModelBN.ipynb
CompareML/AIM-Manuscript
4cf118c1f06e8a1843d56e1f7f8f3d1698aac248
[ "MIT" ]
null
null
null
27.7125
114
0.518719
[ [ [ "### Bayesion Network Classfier(genes classification)\n\nFor each feature selection methods, we check both 50 and 90 genes selection below.", "_____no_output_____" ] ], [ [ "suppressMessages(library(bnlearn))\nset.seed(201703)\nload(\"../transformed data/paper29.rda\")\nk = c(5,10,20,30,50,70,90)\n# kmeans method\nkm_50 = empty.graph(c(\"class\", colnames(data.frame(train_kmeans))))\n#km_set = cbind( from = colnames(data.frame(golub_train_p_trans[,kmeans_id])), to = rep(\"class\", k[5]))\narcs(km_50) = matrix(c(rep(\"class\", k[5]), \n colnames(data.frame(train_kmeans))), \n ncol = 2, byrow = F, dimnames = list(c(), c(\"from\", \"to\")))\n#plot(km)\nkm_fitted_50 = bn.fit(km_50, train_kmeans_50)\nkm_predict_train_50 = predict(km_fitted_50, node = \"class\", method=\"bayes-lw\", train_kmeans_50)\nkm_predict_test_50 = predict(km_fitted_50, node = \"class\", method=\"bayes-lw\", test_kmeans_50)\ntable(Predict_train = km_predict_train_50, True = train_kmeans_50$class)\ntable(Predict_test = km_predict_test_50, True = golub_test_r)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cbe1f7adfc078999be8138141821ce0828c083f3
24,517
ipynb
Jupyter Notebook
notebooks/ICESat-2_MODIS_Arctic_Sea_Ice/Customize and Access Data-Rendered.ipynb
mikala-nsidc/NSIDC-Data-Tutorials
522e3d547347f8e8ca17c47b6dea1f16c5104fe8
[ "MIT" ]
null
null
null
notebooks/ICESat-2_MODIS_Arctic_Sea_Ice/Customize and Access Data-Rendered.ipynb
mikala-nsidc/NSIDC-Data-Tutorials
522e3d547347f8e8ca17c47b6dea1f16c5104fe8
[ "MIT" ]
null
null
null
notebooks/ICESat-2_MODIS_Arctic_Sea_Ice/Customize and Access Data-Rendered.ipynb
mikala-nsidc/NSIDC-Data-Tutorials
522e3d547347f8e8ca17c47b6dea1f16c5104fe8
[ "MIT" ]
2
2020-01-02T19:57:40.000Z
2020-02-14T22:00:19.000Z
48.452569
1,721
0.695517
[ [ [ "# Discover, Customize and Access NSIDC DAAC Data\n\nThis notebook is based off of the [NSIDC-Data-Access-Notebook](https://github.com/nsidc/NSIDC-Data-Access-Notebook) provided through NSIDC's Github organization. \n\nNow that we've visualized our study areas, we will first explore data coverage, size, and customization (subsetting, reformatting, reprojection) service availability, and then access those associated files. The __Data access for all datasets__ notebook provides the steps needed to subset and download all the data we'll be using in the final __Visualize and Analyze Data__.\n\n___A note on data access options:___\nWe will be pursuing data discovery and access \"programmatically\" using Application Programming Interfaces, or APIs. \n\n*What is an API?* You can think of an API as a middle man between an application or end-use (in this case, us) and a data provider. In this case the data provider is both the Common Metadata Repository (CMR) housing data information, and NSIDC as the data distributor. These APIs are generally structured as a URL with a base plus individual key-value-pairs separated by ‘&’.\n\nThere are other discovery and access methods available from NSIDC including access from the data set landing page 'Download Data' tab (e.g. [ATL07 Data Access](https://nsidc.org/data/atl07?qt-data_set_tabs=1#qt-data_set_tabs)) and [NASA Earthdata Search](https://search.earthdata.nasa.gov/). Programmatic API access is beneficial for those of you who want to incorporate data access into your visualization and analysis workflow. This method is also reproducible and documented to ensure data provenance. \n\nHere are the steps you will learn in this customize and access notebook:\n \n1. Search for data programmatically using the Common Metadata Repository API by time and area of interest.\n2. Determine subsetting, reformatting, and reprojection capabilities for our data of interest.\n3. Access and customize data using NSIDC's data access and service API.", "_____no_output_____" ], [ "## Import packages\n", "_____no_output_____" ] ], [ [ "import requests\nimport getpass\nimport json\n\n# This is our functions module. We created several functions used in this notebook and the Visualize and Analyze notebook.\nimport tutorial_helper_functions as fn ", "_____no_output_____" ] ], [ [ "## Explore data availability using the Common Metadata Repository \n\nThe Common Metadata Repository (CMR) is a high-performance, high-quality, continuously evolving metadata system that catalogs Earth Science data and associated service metadata records. These metadata records are registered, modified, discovered, and accessed through programmatic interfaces leveraging standard protocols and APIs. Note that not all NSIDC data can be searched at the file level using CMR, particularly those outside of the NASA DAAC program. \n\nCMR API documentation: https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html", "_____no_output_____" ], [ "### Select data set and determine version number\n\nData sets are selected by data set IDs (e.g. ATL07). In the CMR API documentation, a data set ids is referred to as a \"short name\". These short names are located at the top of each NSIDC data set landing page in gray above the full title. We are using the Python Requests package to access the CMR. Data are then converted to [JSON](https://en.wikipedia.org/wiki/JSON) format; a language independant human-readable open-standard file format. More than one version can exist for a given data set: ", "_____no_output_____" ] ], [ [ "CMR_COLLECTIONS_URL = 'https://cmr.earthdata.nasa.gov/search/collections.json' # CMR collection metadata endpoint\nresponse = requests.get(CMR_COLLECTIONS_URL, params={'short_name': 'ATL07'}) # Request metadata of specified short name\n\nresults = json.loads(response.content) # load JSON results\n# for each version entry, print version number\nfor entry in results['feed']['entry']:\n fn.print_cmr_metadata(entry) ", "dataset_id: ATLAS/ICESat-2 L3A Sea Ice Height V003, version_id: 003\ndataset_id: ATLAS/ICESat-2 L3A Sea Ice Height V004, version_id: 004\ndataset_id: ATLAS/ICESat-2 L3A Sea Ice Height V005, version_id: 005\n" ] ], [ [ "We will specify the most recent version for our remaining data set queries.", "_____no_output_____" ], [ "### Select time and area of interest", "_____no_output_____" ], [ "We will create a simple dictionary with our short name, version, time, and area of interest. We'll continue to add to this dictionary as we discover more information about our data set. The bounding box coordinates cover our region of interest over the East Siberian Sea and the temporal range covers March 23, 2019. ", "_____no_output_____" ] ], [ [ "bounding_box = '140,72,153,80' # Bounding Box spatial parameter in decimal degree 'W,S,E,N' format. \ntemporal = '2019-03-23T00:00:00Z,2019-03-23T23:59:59Z' # Each date in yyyy-MM-ddTHH:mm:ssZ format; date range in start,end format", "_____no_output_____" ] ], [ [ "Start our data dictionary with our data set, version, and area and time of interest. \n\n**Note that some version IDs include 3 digits and others include only 1 digit. Make sure to enter this value exactly as reported above.**", "_____no_output_____" ] ], [ [ "data_dict = {'short_name': 'ATL07', \n 'version': '005',\n 'bounding_box': bounding_box, \n 'temporal': temporal }", "_____no_output_____" ] ], [ [ "### Determine how many files exist over this time and area of interest, as well as the average size and total volume of those granules\n\nWe will use the `granule_info` function to query the CMR granule API. The function prints the number of granules, average size, and total volume of those granules. It returns the granule number value, which we will add to our data dictionary.", "_____no_output_____" ] ], [ [ "gran_num = fn.granule_info(data_dict)\ndata_dict['gran_num'] = gran_num # add file number to data dictionary", "There are 2 granules of ATL07 version 005 over my area and time of interest.\nThe average size of each granule is 320.07 MB and the total size of all 2 granules is 640.15 MB\n" ] ], [ [ "Note that subsetting, reformatting, or reprojecting can alter the size of the granules if those services are applied to your request.", "_____no_output_____" ], [ "## ***On your own***: Discover data availability for ATL07\n\nGo back to the \"Select data set and determine version number\" heading. Replace all `MOD29` instances with `ATL07` along with its most recent version number, keeping your time and area of interest the same. ***Note that ATL07 has a 3-digit version number.*** How does the data volume compare to MOD29? \n\n____", "_____no_output_____" ], [ "## Determine the subsetting, reformatting, and reprojection services enabled for your data set of interest.", "_____no_output_____" ], [ "The NSIDC DAAC supports customization (subsetting, reformatting, reprojection) services on many of our NASA Earthdata mission collections. Let's discover whether or not our data set has these services available using the `print_service_options` function. If services are available, we will also determine the specific service options supported for this data set, which we will then add to our data dictionary. ", "_____no_output_____" ], [ "### Input Earthdata Login credentials\n\nAn Earthdata Login account is required to query data services and to access data from the NSIDC DAAC. If you do not already have an Earthdata Login account, visit http://urs.earthdata.nasa.gov to register. We will input our credentials below, and we'll add our email address to our dictionary for use in our final access request.", "_____no_output_____" ] ], [ [ "uid = '' # Enter Earthdata Login user name\n\npswd = getpass.getpass('Earthdata Login password: ') # Input and store Earthdata Login password\n\nemail = '' # Enter email associated with Earthata Login account\n\ndata_dict['email'] = email # Add to data dictionary", "Earthdata Login password: ·········\n" ] ], [ [ "We now need to create an HTTP session in order to store cookies and pass our credentials to the data service URLs. The capability URL below is what we will query to determine service information. ", "_____no_output_____" ] ], [ [ "# Query service capability URL \ncapability_url = f'https://n5eil02u.ecs.nsidc.org/egi/capabilities/{data_dict[\"short_name\"]}.{data_dict[\"version\"]}.xml' \n\n# Create session to store cookie and pass credentials to capabilities url\nsession = requests.session() \ns = session.get(capability_url)\nresponse = session.get(s.url,auth=(uid,pswd))\nresponse.raise_for_status() # Raise bad request to check that Earthdata Login credentials were accepted ", "_____no_output_____" ] ], [ [ "This function provides a list of all available services:", "_____no_output_____" ] ], [ [ "fn.print_service_options(data_dict, response)", "Services available for ATL07 :\n\nBounding box subsetting\nShapefile subsetting\nTemporal subsetting\nVariable subsetting\nReformatting to the following options: ['TABULAR_ASCII', 'NetCDF4-CF', 'NetCDF-3']\n" ] ], [ [ "### Populate data dictionary with services of interest\n\nWe already added our CMR search keywords to our data dictionary, so now we need to add the service options we want to request. A list of all available service keywords for use with NSIDC's access and service API are available in our [Key-Value-Pair table](https://nsidc.org/support/tool/table-key-value-pair-kvp-operands-subsetting-reformatting-and-reprojection-services), as a part of our [Programmatic access guide](https://nsidc.org/support/how/how-do-i-programmatically-request-data-services). For our ATL07 request, we are interested in bounding box, temporal, and variable subsetting. These options crop the data values to the specified ranges and variables of interest. We will enter those values into our data dictionary below.\n", "_____no_output_____" ], [ "__Bounding box subsetting:__ Output files are cropped to the specified bounding box extent.\n\n__Temporal subsetting:__ Output files are cropped to the specified temporal range extent.", "_____no_output_____" ] ], [ [ "data_dict['bbox'] = '140,72,153,80' # Just like with the CMR bounding box search parameter, this value is provided in decimal degree 'W,S,E,N' format. \ndata_dict['time'] = '2019-03-23T00:00:00,2019-03-23T23:59:59' # Each date in yyyy-MM-ddTHH:mm:ss format; Date range in start,end format", "_____no_output_____" ] ], [ [ "__Variable subsetting:__ Subsets the data set variable or group of variables. For hierarchical data, all lower level variables are returned if a variable group or subgroup is specified. \n\nFor ATL07, we will use only strong beams since these groups contain higher coverage and resolution due to higher surface returns. According to the user guide, the spacecraft was in the backwards orientation during our day of interest, setting the `gt*l` beams as the strong beams. \n\nWe'll use these primary geolocation, height and quality variables of interest for each of the three strong beams. The following descriptions are provided in the [ATL07 Data Dictionary](https://nsidc.org/sites/nsidc.org/files/technical-references/ATL07-data-dictionary-v001.pdf), with additional information on the algorithm and variable descriptions in the [ATBD (Algorithm Theoretical Basis Document)](https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL07_ATL10_ATBD_r002.pdf).\n\n`delta_time`: Number of GPS seconds since the ATLAS SDP epoch. \n\n`latitude`: Latitude, WGS84, North=+, Lat of segment center\n\n`longitude`: Longitude, WGS84, East=+,Lon of segment center\n\n`height_segment_height`: Mean height from along-track segment fit determined by the sea ice algorithm\n\n`height_segment_confidence`: Confidence level in the surface height estimate based on the number of photons; the background noise rate; and the error\nanalysis\n\n`height_segment_quality`: Height segment quality flag, 1 is good quality, 0 is bad\n\n`height_segment_surface_error_est`: Error estimate of the surface height (reported in meters)\n\n`height_segment_length_seg`: along-track length of segment containing n_photons_actual", "_____no_output_____" ] ], [ [ "data_dict['coverage'] = '/gt1l/sea_ice_segments/delta_time,\\\n/gt1l/sea_ice_segments/latitude,\\\n/gt1l/sea_ice_segments/longitude,\\\n/gt1l/sea_ice_segments/heights/height_segment_confidence,\\\n/gt1l/sea_ice_segments/heights/height_segment_height,\\\n/gt1l/sea_ice_segments/heights/height_segment_quality,\\\n/gt1l/sea_ice_segments/heights/height_segment_surface_error_est,\\\n/gt1l/sea_ice_segments/heights/height_segment_length_seg,\\\n/gt2l/sea_ice_segments/delta_time,\\\n/gt2l/sea_ice_segments/latitude,\\\n/gt2l/sea_ice_segments/longitude,\\\n/gt2l/sea_ice_segments/heights/height_segment_confidence,\\\n/gt2l/sea_ice_segments/heights/height_segment_height,\\\n/gt2l/sea_ice_segments/heights/height_segment_quality,\\\n/gt2l/sea_ice_segments/heights/height_segment_surface_error_est,\\\n/gt2l/sea_ice_segments/heights/height_segment_length_seg,\\\n/gt3l/sea_ice_segments/delta_time,\\\n/gt3l/sea_ice_segments/latitude,\\\n/gt3l/sea_ice_segments/longitude,\\\n/gt3l/sea_ice_segments/heights/height_segment_confidence,\\\n/gt3l/sea_ice_segments/heights/height_segment_height,\\\n/gt3l/sea_ice_segments/heights/height_segment_quality,\\\n/gt3l/sea_ice_segments/heights/height_segment_surface_error_est,\\\n/gt3l/sea_ice_segments/heights/height_segment_length_seg'\n", "_____no_output_____" ] ], [ [ "### Select data access configurations\n\nThe data request can be accessed asynchronously or synchronously. The asynchronous option will allow concurrent requests to be queued and processed as orders. Those requested orders will be delivered to the specified email address, or they can be accessed programmatically as shown below. Synchronous requests will automatically download the data as soon as processing is complete. For this tutorial, we will be selecting the asynchronous method. ", "_____no_output_____" ] ], [ [ "base_url = 'https://n5eil02u.ecs.nsidc.org/egi/request' # Set NSIDC data access base URL\ndata_dict['request_mode'] = 'async' # Set the request mode to asynchronous\ndata_dict['page_size'] = 2000 # Set the page size to the maximum of 2000, which equals the number of output files that can be returned", "_____no_output_____" ] ], [ [ "## Create the data request API endpoint \nProgrammatic API requests are formatted as HTTPS URLs that contain key-value-pairs specifying the service operations that we specified above. We will first create a string of key-value-pairs from our data dictionary and we'll feed those into our API endpoint. This API endpoint can be executed via command line, a web browser, or in Python below. ", "_____no_output_____" ] ], [ [ "# Create a new param_dict with CMR configuration parameters removed from our data_dict \nparam_dict = dict((i, data_dict[i]) for i in data_dict if i!='gran_num' and i!='page_num')\n\nparam_string = '&'.join(\"{!s}={!r}\".format(k,v) for (k,v) in param_dict.items()) # Convert param_dict to string\nparam_string = param_string.replace(\"'\",\"\") # Remove quotes\n\nAPI_request = f'{base_url}?{param_string}' \nprint(API_request) # Print API base URL + request parameters", "https://n5eil02u.ecs.nsidc.org/egi/request?short_name=ATL07&version=005&bounding_box=140,72,153,80&temporal=2019-03-23T00:00:00Z,2019-03-23T23:59:59Z&page_size=2000&[email protected]&bbox=140,72,153,80&time=2019-03-23T00:00:00,2019-03-23T23:59:59&coverage=/gt1l/sea_ice_segments/delta_time,/gt1l/sea_ice_segments/latitude,/gt1l/sea_ice_segments/longitude,/gt1l/sea_ice_segments/heights/height_segment_confidence,/gt1l/sea_ice_segments/heights/height_segment_height,/gt1l/sea_ice_segments/heights/height_segment_quality,/gt1l/sea_ice_segments/heights/height_segment_surface_error_est,/gt1l/sea_ice_segments/heights/height_segment_length_seg,/gt2l/sea_ice_segments/delta_time,/gt2l/sea_ice_segments/latitude,/gt2l/sea_ice_segments/longitude,/gt2l/sea_ice_segments/heights/height_segment_confidence,/gt2l/sea_ice_segments/heights/height_segment_height,/gt2l/sea_ice_segments/heights/height_segment_quality,/gt2l/sea_ice_segments/heights/height_segment_surface_error_est,/gt2l/sea_ice_segments/heights/height_segment_length_seg,/gt3l/sea_ice_segments/delta_time,/gt3l/sea_ice_segments/latitude,/gt3l/sea_ice_segments/longitude,/gt3l/sea_ice_segments/heights/height_segment_confidence,/gt3l/sea_ice_segments/heights/height_segment_height,/gt3l/sea_ice_segments/heights/height_segment_quality,/gt3l/sea_ice_segments/heights/height_segment_surface_error_est,/gt3l/sea_ice_segments/heights/height_segment_length_seg&request_mode=async\n" ] ], [ [ "## Request data and clean up Output folder", "_____no_output_____" ], [ "We will now download data using the `request_data` function, which utilizes the Python requests library. Our param_dict and HTTP session will be passed to the function to allow Earthdata Login access. The data will be downloaded directly to this notebook directory in a new Outputs folder. The progress of the order will be reported. The data are returned in separate files, so we'll use the `clean_folder` function to remove those individual folders.", "_____no_output_____" ] ], [ [ "fn.request_data(param_dict,session)\nfn.clean_folder()", "Request HTTP response: 201\n\nOrder request URL: https://n5eil02u.ecs.nsidc.org/egi/request?short_name=ATL07&version=005&bounding_box=140%2C72%2C153%2C80&temporal=2019-03-23T00%3A00%3A00Z%2C2019-03-23T23%3A59%3A59Z&page_size=2000&email=amy.steiker%40nsidc.org&bbox=140%2C72%2C153%2C80&time=2019-03-23T00%3A00%3A00%2C2019-03-23T23%3A59%3A59&coverage=%2Fgt1l%2Fsea_ice_segments%2Fdelta_time%2C%2Fgt1l%2Fsea_ice_segments%2Flatitude%2C%2Fgt1l%2Fsea_ice_segments%2Flongitude%2C%2Fgt1l%2Fsea_ice_segments%2Fheights%2Fheight_segment_confidence%2C%2Fgt1l%2Fsea_ice_segments%2Fheights%2Fheight_segment_height%2C%2Fgt1l%2Fsea_ice_segments%2Fheights%2Fheight_segment_quality%2C%2Fgt1l%2Fsea_ice_segments%2Fheights%2Fheight_segment_surface_error_est%2C%2Fgt1l%2Fsea_ice_segments%2Fheights%2Fheight_segment_length_seg%2C%2Fgt2l%2Fsea_ice_segments%2Fdelta_time%2C%2Fgt2l%2Fsea_ice_segments%2Flatitude%2C%2Fgt2l%2Fsea_ice_segments%2Flongitude%2C%2Fgt2l%2Fsea_ice_segments%2Fheights%2Fheight_segment_confidence%2C%2Fgt2l%2Fsea_ice_segments%2Fheights%2Fheight_segment_height%2C%2Fgt2l%2Fsea_ice_segments%2Fheights%2Fheight_segment_quality%2C%2Fgt2l%2Fsea_ice_segments%2Fheights%2Fheight_segment_surface_error_est%2C%2Fgt2l%2Fsea_ice_segments%2Fheights%2Fheight_segment_length_seg%2C%2Fgt3l%2Fsea_ice_segments%2Fdelta_time%2C%2Fgt3l%2Fsea_ice_segments%2Flatitude%2C%2Fgt3l%2Fsea_ice_segments%2Flongitude%2C%2Fgt3l%2Fsea_ice_segments%2Fheights%2Fheight_segment_confidence%2C%2Fgt3l%2Fsea_ice_segments%2Fheights%2Fheight_segment_height%2C%2Fgt3l%2Fsea_ice_segments%2Fheights%2Fheight_segment_quality%2C%2Fgt3l%2Fsea_ice_segments%2Fheights%2Fheight_segment_surface_error_est%2C%2Fgt3l%2Fsea_ice_segments%2Fheights%2Fheight_segment_length_seg&request_mode=async\n\norder ID: 5000002720310\nstatus URL: https://n5eil02u.ecs.nsidc.org/egi/request/5000002720310\nHTTP response from order response URL: 201\n\nInitial request status is processing\n\nStatus is not complete. Trying again.\nRetry request status is: complete\nZip download URL: https://n5eil02u.ecs.nsidc.org/esir/5000002720310.zip\nBeginning download of zipped output...\nData request is complete.\n" ] ], [ [ "To review, we have explored data availability and volume over a region and time of interest, discovered and selected data customization options, constructed API endpoints for our requests, and downloaded data. Let's move on to the analysis portion of the tutorial.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
cbe1f8a1f610c3c4c9ac6c2f964cb0a3f81099fd
104,226
ipynb
Jupyter Notebook
courses/machine_learning/deepdive2/launching_into_ml/solutions/improve_data_quality.ipynb
tmpvmk/training-data-analyst
51bd3b4ce601efad1855c609c453dac37ae2565b
[ "Apache-2.0" ]
1
2020-12-22T18:51:57.000Z
2020-12-22T18:51:57.000Z
courses/machine_learning/deepdive2/launching_into_ml/solutions/improve_data_quality.ipynb
Starkultra/Reinforcement-learning-GCP
95a87b087701575c877fee615c2367ccc9a8e6a0
[ "Apache-2.0" ]
null
null
null
courses/machine_learning/deepdive2/launching_into_ml/solutions/improve_data_quality.ipynb
Starkultra/Reinforcement-learning-GCP
95a87b087701575c877fee615c2367ccc9a8e6a0
[ "Apache-2.0" ]
null
null
null
37.23687
11,568
0.456978
[ [ [ "# Improving Data Quality\n\n**Learning Objectives**\n\n\n1. Resolve missing values\n2. Convert the Date feature column to a datetime format\n3. Rename a feature column, remove a value from a feature column\n4. Create one-hot encoding features\n5. Understand temporal feature conversions \n\n\n## Introduction \n\nRecall that machine learning models can only consume numeric data, and that numeric data should be \"1\"s or \"0\"s. Data is said to be \"messy\" or \"untidy\" if it is missing attribute values, contains noise or outliers, has duplicates, wrong data, upper/lower case column names, and is essentially not ready for ingestion by a machine learning algorithm. \n\nThis notebook presents and solves some of the most common issues of \"untidy\" data. Note that different problems will require different methods, and they are beyond the scope of this notebook.\n\nEach learning objective will correspond to a __#TODO__ in the [student lab notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/deepdive2/launching_into_ml/labs/improve_data_quality.ipynb) -- try to complete that notebook first before reviewing this solution notebook.", "_____no_output_____" ] ], [ [ "# Use the chown command to change the ownership of the repository to user\n!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst", "_____no_output_____" ] ], [ [ "### Import Libraries", "_____no_output_____" ] ], [ [ "import os\n# Here we'll import Pandas and Numpy data processing libraries\nimport pandas as pd \nimport numpy as np\nfrom datetime import datetime\n# Use matplotlib for visualizing the model\nimport matplotlib.pyplot as plt\n# Use seaborn for data visualization\nimport seaborn as sns\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Load the Dataset", "_____no_output_____" ], [ "The dataset is based on California's [Vehicle Fuel Type Count by Zip Code](https://data.ca.gov/dataset/vehicle-fuel-type-count-by-zip-codeSynthetic) report. The dataset has been modified to make the data \"untidy\" and is thus a synthetic representation that can be used for learning purposes. \n", "_____no_output_____" ] ], [ [ "# Creating directory to store dataset\nif not os.path.isdir(\"../data/transport\"):\n os.makedirs(\"../data/transport\")", "_____no_output_____" ], [ "# Download the raw .csv data by copying the data from a cloud storage bucket.\n!gsutil cp gs://cloud-training-demos/feat_eng/transport/untidy_vehicle_data.csv ../data/transport", "Copying gs://cloud-training-demos/feat_eng/transport/untidy_vehicle_data.csv...\n/ [1 files][ 47.2 KiB/ 47.2 KiB] \nOperation completed over 1 objects/47.2 KiB. \n" ], [ "# ls shows the working directory's contents.\n# Using the -l parameter will lists files with assigned permissions\n!ls -l ../data/transport", "total 48\n-rw-r--r-- 1 jupyter jupyter 48343 May 15 04:48 untidy_vehicle_data.csv\n" ] ], [ [ "### Read Dataset into a Pandas DataFrame", "_____no_output_____" ], [ "Next, let's read in the dataset just copied from the cloud storage bucket and create a Pandas DataFrame. We also add a Pandas .head() function to show you the top 5 rows of data in the DataFrame. Head() and Tail() are \"best-practice\" functions used to investigate datasets. ", "_____no_output_____" ] ], [ [ "# Reading \"untidy_vehicle_data.csv\" file using the read_csv() function included in the pandas library.\ndf_transport = pd.read_csv('../data/transport/untidy_vehicle_data.csv')\n\n# Output the first five rows.\ndf_transport.head() ", "_____no_output_____" ] ], [ [ "### DataFrame Column Data Types\n\nDataFrames may have heterogenous or \"mixed\" data types, that is, some columns are numbers, some are strings, and some are dates etc. Because CSV files do not contain information on what data types are contained in each column, Pandas infers the data types when loading the data, e.g. if a column contains only numbers, Pandas will set that column’s data type to numeric: integer or float.\n\nRun the next cell to see information on the DataFrame.", "_____no_output_____" ] ], [ [ "# The .info() function will display the concise summary of an dataframe.\ndf_transport.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 999 entries, 0 to 998\nData columns (total 7 columns):\nDate 997 non-null object\nZip Code 997 non-null object\nModel Year 997 non-null object\nFuel 996 non-null object\nMake 996 non-null object\nLight_Duty 996 non-null object\nVehicles 996 non-null float64\ndtypes: float64(1), object(6)\nmemory usage: 54.8+ KB\n" ] ], [ [ "From what the .info() function shows us, we have six string objects and one float object. We can definitely see more of the \"string\" object values now!", "_____no_output_____" ] ], [ [ "# Let's print out the first and last five rows of each column.\nprint(df_transport,5)", " Date Zip Code Model Year Fuel Make \\\n0 10/1/2018 90000 2006 Gasoline OTHER/UNK \n1 10/1/2018 NaN 2014 Gasoline NaN \n2 NaN 90000 NaN Gasoline OTHER/UNK \n3 10/1/2018 90000 2017 Gasoline OTHER/UNK \n4 10/1/2018 90000 <2006 Diesel and Diesel Hybrid OTHER/UNK \n.. ... ... ... ... ... \n994 6/7/2019 90003 2012 Gasoline Type_R \n995 6/8/2019 90003 2012 Hybrid Gasoline OTHER/UNK \n996 6/9/2019 90003 2012 Hybrid Gasoline Type_Q \n997 6/10/2019 90003 2012 Natural Gas OTHER/UNK \n998 6/11/2019 90003 2012 Plug-in Hybrid OTHER/UNK \n\n Light_Duty Vehicles \n0 NaN 1.0 \n1 Yes 1.0 \n2 Yes NaN \n3 Yes 1.0 \n4 No 55.0 \n.. ... ... \n994 Yes 26.0 \n995 Yes 4.0 \n996 Yes 25.0 \n997 Yes 1.0 \n998 Yes 3.0 \n\n[999 rows x 7 columns] 5\n" ] ], [ [ "### Summary Statistics \n\nAt this point, we have only one column which contains a numerical value (e.g. Vehicles). For features which contain numerical values, we are often interested in various statistical measures relating to those values. Note, that because we only have one numeric feature, we see only one summary stastic - for now. ", "_____no_output_____" ] ], [ [ "# We can use .describe() to see some summary statistics for the numeric fields in our dataframe.\ndf_transport.describe()", "_____no_output_____" ] ], [ [ "Let's investigate a bit more of our data by using the .groupby() function.", "_____no_output_____" ] ], [ [ "# The .groupby() function is used for spliting the data into groups based on some criteria.\ngrouped_data = df_transport.groupby(['Zip Code','Model Year','Fuel','Make','Light_Duty','Vehicles'])\n\n # Get the first entry for each month.\ndf_transport.groupby('Fuel').first()", "_____no_output_____" ] ], [ [ "### Checking for Missing Values\n\nMissing values adversely impact data quality, as they can lead the machine learning model to make inaccurate inferences about the data. Missing values can be the result of numerous factors, e.g. \"bits\" lost during streaming transmission, data entry, or perhaps a user forgot to fill in a field. Note that Pandas recognizes both empty cells and “NaN” types as missing values. ", "_____no_output_____" ], [ "#### Let's show the null values for all features in the DataFrame.", "_____no_output_____" ] ], [ [ "df_transport.isnull().sum()", "_____no_output_____" ] ], [ [ "To see a sampling of which values are missing, enter the feature column name. You'll notice that \"False\" and \"True\" correpond to the presence or abscence of a value by index number.", "_____no_output_____" ] ], [ [ "print (df_transport['Date'])\nprint (df_transport['Date'].isnull())", "0 10/1/2018\n1 10/1/2018\n2 NaN\n3 10/1/2018\n4 10/1/2018\n ... \n994 6/7/2019\n995 6/8/2019\n996 6/9/2019\n997 6/10/2019\n998 6/11/2019\nName: Date, Length: 999, dtype: object\n0 False\n1 False\n2 True\n3 False\n4 False\n ... \n994 False\n995 False\n996 False\n997 False\n998 False\nName: Date, Length: 999, dtype: bool\n" ], [ "print (df_transport['Make'])\nprint (df_transport['Make'].isnull())", "0 OTHER/UNK\n1 NaN\n2 OTHER/UNK\n3 OTHER/UNK\n4 OTHER/UNK\n ... \n994 Type_R\n995 OTHER/UNK\n996 Type_Q\n997 OTHER/UNK\n998 OTHER/UNK\nName: Make, Length: 999, dtype: object\n0 False\n1 True\n2 False\n3 False\n4 False\n ... \n994 False\n995 False\n996 False\n997 False\n998 False\nName: Make, Length: 999, dtype: bool\n" ], [ "print (df_transport['Model Year'])\nprint (df_transport['Model Year'].isnull())", "0 2006\n1 2014\n2 NaN\n3 2017\n4 <2006\n ... \n994 2012\n995 2012\n996 2012\n997 2012\n998 2012\nName: Model Year, Length: 999, dtype: object\n0 False\n1 False\n2 True\n3 False\n4 False\n ... \n994 False\n995 False\n996 False\n997 False\n998 False\nName: Model Year, Length: 999, dtype: bool\n" ] ], [ [ "### What can we deduce about the data at this point?\n", "_____no_output_____" ], [ "# Let's summarize our data by row, column, features, unique, and missing values.\n", "_____no_output_____" ] ], [ [ "# In Python shape() is used in pandas to give the number of rows/columns.\n# The number of rows is given by .shape[0]. The number of columns is given by .shape[1].\n# Thus, shape() consists of an array having two arguments -- rows and columns\nprint (\"Rows : \" ,df_transport.shape[0])\nprint (\"Columns : \" ,df_transport.shape[1])\nprint (\"\\nFeatures : \\n\" ,df_transport.columns.tolist())\nprint (\"\\nUnique values : \\n\",df_transport.nunique())\nprint (\"\\nMissing values : \", df_transport.isnull().sum().values.sum())\n", "Rows : 999\nColumns : 7\n\nFeatures : \n ['Date', 'Zip Code', 'Model Year', 'Fuel', 'Make', 'Light_Duty', 'Vehicles']\n\nUnique values : \n Date 248\nZip Code 6\nModel Year 15\nFuel 8\nMake 43\nLight_Duty 3\nVehicles 210\ndtype: int64\n\nMissing values : 18\n" ] ], [ [ "Let's see the data again -- this time the last five rows in the dataset.", "_____no_output_____" ] ], [ [ "# Output the last five rows in the dataset.\ndf_transport.tail()", "_____no_output_____" ] ], [ [ "### What Are Our Data Quality Issues?\n\n1. **Data Quality Issue #1**: \n> **Missing Values**:\nEach feature column has multiple missing values. In fact, we have a total of 18 missing values.\n2. **Data Quality Issue #2**: \n> **Date DataType**: Date is shown as an \"object\" datatype and should be a datetime. In addition, Date is in one column. Our business requirement is to see the Date parsed out to year, month, and day. \n3. **Data Quality Issue #3**: \n> **Model Year**: We are only interested in years greater than 2006, not \"<2006\".\n4. **Data Quality Issue #4**: \n> **Categorical Columns**: The feature column \"Light_Duty\" is categorical and has a \"Yes/No\" choice. We cannot feed values like this into a machine learning model. In addition, we need to \"one-hot encode the remaining \"string\"/\"object\" columns.\n5. **Data Quality Issue #5**: \n> **Temporal Features**: How do we handle year, month, and day?\n", "_____no_output_____" ], [ "#### Data Quality Issue #1: \n##### Resolving Missing Values", "_____no_output_____" ], [ "Most algorithms do not accept missing values. Yet, when we see missing values in our dataset, there is always a tendency to just \"drop all the rows\" with missing values. Although Pandas will fill in the blank space with “NaN\", we should \"handle\" them in some way.\n\nWhile all the methods to handle missing values is beyond the scope of this lab, there are a few methods you should consider. For numeric columns, use the \"mean\" values to fill in the missing numeric values. For categorical columns, use the \"mode\" (or most frequent values) to fill in missing categorical values. \n\nIn this lab, we use the .apply and Lambda functions to fill every column with its own most frequent value. You'll learn more about Lambda functions later in the lab.", "_____no_output_____" ], [ "Let's check again for missing values by showing how many rows contain NaN values for each feature column.", "_____no_output_____" ] ], [ [ "# The isnull() method is used to check and manage NULL values in a data frame.\n# TODO 1a\ndf_transport.isnull().sum()", "_____no_output_____" ] ], [ [ "Run the cell to apply the lambda function.", "_____no_output_____" ] ], [ [ "# Here we are using the apply function with lambda.\n# We can use the apply() function to apply the lambda function to both rows and columns of a dataframe.\n# TODO 1b\ndf_transport = df_transport.apply(lambda x:x.fillna(x.value_counts().index[0]))", "_____no_output_____" ] ], [ [ "Let's check again for missing values.", "_____no_output_____" ] ], [ [ "# The isnull() method is used to check and manage NULL values in a data frame.\n# TODO 1c\ndf_transport.isnull().sum()", "_____no_output_____" ] ], [ [ "#### Data Quality Issue #2: \n##### Convert the Date Feature Column to a Datetime Format", "_____no_output_____" ] ], [ [ "# The date column is indeed shown as a string object. We can convert it to the datetime datatype with the to_datetime() function in Pandas.\n# TODO 2a\ndf_transport['Date'] = pd.to_datetime(df_transport['Date'],\n format='%m/%d/%Y')", "_____no_output_____" ], [ "# Date is now converted and will display the concise summary of an dataframe.\n# TODO 2b\ndf_transport.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 999 entries, 0 to 998\nData columns (total 7 columns):\nDate 999 non-null datetime64[ns]\nZip Code 999 non-null object\nModel Year 999 non-null object\nFuel 999 non-null object\nMake 999 non-null object\nLight_Duty 999 non-null object\nVehicles 999 non-null float64\ndtypes: datetime64[ns](1), float64(1), object(5)\nmemory usage: 54.8+ KB\n" ], [ "# Now we will parse Date into three columns that is year, month, and day.\ndf_transport['year'] = df_transport['Date'].dt.year\ndf_transport['month'] = df_transport['Date'].dt.month\ndf_transport['day'] = df_transport['Date'].dt.day\n\n#df['hour'] = df['date'].dt.hour - you could use this if your date format included hour.\n#df['minute'] = df['date'].dt.minute - you could use this if your date format included minute.\n\n# The .info() function will display the concise summary of an dataframe.\ndf_transport.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 999 entries, 0 to 998\nData columns (total 10 columns):\nDate 999 non-null datetime64[ns]\nZip Code 999 non-null object\nModel Year 999 non-null object\nFuel 999 non-null object\nMake 999 non-null object\nLight_Duty 999 non-null object\nVehicles 999 non-null float64\nyear 999 non-null int64\nmonth 999 non-null int64\nday 999 non-null int64\ndtypes: datetime64[ns](1), float64(1), int64(3), object(5)\nmemory usage: 78.2+ KB\n" ] ], [ [ "# Let's confirm the Date parsing. This will also give us a another visualization of the data.", "_____no_output_____" ] ], [ [ "# Here, we are creating a new dataframe called \"grouped_data\" and grouping by on the column \"Make\"\ngrouped_data = df_transport.groupby(['Make'])\n\n# Get the first entry for each month.\ndf_transport.groupby('Fuel').first()", "_____no_output_____" ] ], [ [ "Now that we have Dates as a integers, let's do some additional plotting.", "_____no_output_____" ] ], [ [ "# Here we will visualize our data using the figure() function in the pyplot module of matplotlib's library -- which is used to create a new figure.\nplt.figure(figsize=(10,6))\n\n# Seaborn's .jointplot() displays a relationship between 2 variables (bivariate) as well as 1D profiles (univariate) in the margins. This plot is a convenience class that wraps JointGrid.\nsns.jointplot(x='month',y='Vehicles',data=df_transport)\n\n# The title() method in matplotlib module is used to specify title of the visualization depicted and displays the title using various attributes.\nplt.title('Vehicles by Month')", "_____no_output_____" ] ], [ [ "#### Data Quality Issue #3: \n##### Rename a Feature Column and Remove a Value. \n\nOur feature columns have different \"capitalizations\" in their names, e.g. both upper and lower \"case\". In addition, there are \"spaces\" in some of the column names. In addition, we are only interested in years greater than 2006, not \"<2006\". ", "_____no_output_____" ], [ "We can also resolve the \"case\" problem too by making all the feature column names lower case.", "_____no_output_____" ] ], [ [ "# Let's remove all the spaces for feature columns by renaming them.\n# TODO 3a\ndf_transport.rename(columns = { 'Date': 'date', 'Zip Code':'zipcode', 'Model Year': 'modelyear', 'Fuel': 'fuel', 'Make': 'make', 'Light_Duty': 'lightduty', 'Vehicles': 'vehicles'}, inplace = True) \n\n# Output the first two rows.\ndf_transport.head(2)", "_____no_output_____" ] ], [ [ " **Note:** Next we create a copy of the dataframe to avoid the \"SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame\" warning. Run the cell to remove the value '<2006' from the modelyear feature column. ", "_____no_output_____" ] ], [ [ "# Here, we create a copy of the dataframe to avoid copy warning issues.\n# TODO 3b\ndf = df_transport.loc[df_transport.modelyear != '<2006'].copy()", "_____no_output_____" ], [ "# Here we will confirm that the modelyear value '<2006' has been removed by doing a value count.\ndf['modelyear'].value_counts(0)", "_____no_output_____" ] ], [ [ "#### Data Quality Issue #4: \n##### Handling Categorical Columns\n\nThe feature column \"lightduty\" is categorical and has a \"Yes/No\" choice. We cannot feed values like this into a machine learning model. We need to convert the binary answers from strings of yes/no to integers of 1/0. There are various methods to achieve this. We will use the \"apply\" method with a lambda expression. Pandas. apply() takes a function and applies it to all values of a Pandas series.\n\n##### What is a Lambda Function?\n\nTypically, Python requires that you define a function using the def keyword. However, lambda functions are anonymous -- which means there is no need to name them. The most common use case for lambda functions is in code that requires a simple one-line function (e.g. lambdas only have a single expression). \n\nAs you progress through the Course Specialization, you will see many examples where lambda functions are being used. Now is a good time to become familiar with them.", "_____no_output_____" ] ], [ [ "# Lets count the number of \"Yes\" and\"No's\" in the 'lightduty' feature column.\ndf['lightduty'].value_counts(0)", "_____no_output_____" ], [ "# Let's convert the Yes to 1 and No to 0.\n# The .apply takes a function and applies it to all values of a Pandas series (e.g. lightduty). \ndf.loc[:,'lightduty'] = df['lightduty'].apply(lambda x: 0 if x=='No' else 1)\ndf['lightduty'].value_counts(0)", "_____no_output_____" ], [ "# Confirm that \"lightduty\" has been converted.\ndf.head()", "_____no_output_____" ] ], [ [ "#### One-Hot Encoding Categorical Feature Columns\n\nMachine learning algorithms expect input vectors and not categorical features. Specifically, they cannot handle text or string values. Thus, it is often useful to transform categorical features into vectors.\n\nOne transformation method is to create dummy variables for our categorical features. Dummy variables are a set of binary (0 or 1) variables that each represent a single class from a categorical feature. We simply encode the categorical variable as a one-hot vector, i.e. a vector where only one element is non-zero, or hot. With one-hot encoding, a categorical feature becomes an array whose size is the number of possible choices for that feature.", "_____no_output_____" ], [ "Panda provides a function called \"get_dummies\" to convert a categorical variable into dummy/indicator variables.", "_____no_output_____" ] ], [ [ "# Making dummy variables for categorical data with more inputs. \ndata_dummy = pd.get_dummies(df[['zipcode','modelyear', 'fuel', 'make']], drop_first=True)\n\n# Output the first five rows.\ndata_dummy.head()", "_____no_output_____" ], [ "# Merging (concatenate) original data frame with 'dummy' dataframe.\n# TODO 4a\ndf = pd.concat([df,data_dummy], axis=1)\ndf.head()", "_____no_output_____" ], [ "# Dropping attributes for which we made dummy variables. Let's also drop the Date column.\n# TODO 4b\ndf = df.drop(['date','zipcode','modelyear', 'fuel', 'make'], axis=1)\n", "_____no_output_____" ], [ "# Confirm that 'zipcode','modelyear', 'fuel', and 'make' have been dropped.\ndf.head()", "_____no_output_____" ] ], [ [ "#### Data Quality Issue #5: \n##### Temporal Feature Columns\n\nOur dataset now contains year, month, and day feature columns. Let's convert the month and day feature columns to meaningful representations as a way to get us thinking about changing temporal features -- as they are sometimes overlooked. \n\nNote that the Feature Engineering course in this Specialization will provide more depth on methods to handle year, month, day, and hour feature columns.\n", "_____no_output_____" ] ], [ [ "# Let's print the unique values for \"month\", \"day\" and \"year\" in our dataset. \nprint ('Unique values of month:',df.month.unique())\nprint ('Unique values of day:',df.day.unique())\nprint ('Unique values of year:',df.year.unique())", "Unique values of month: [10 11 12 1 2 3 4 5 6 7]\nUnique values of day: [ 1 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n 2 3 4 5 6 7 8]\nUnique values of year: [2018 2019]\n" ] ], [ [ "Don't worry, this is the last time we will use this code, as you can develop an input pipeline to address these temporal feature columns in TensorFlow and Keras - and it is much easier! But, sometimes you need to appreciate what you're not going to encounter as you move through the course!\n\nRun the cell to view the output.", "_____no_output_____" ] ], [ [ "# Here we map each temporal variable onto a circle such that the lowest value for that variable appears right next to the largest value. We compute the x- and y- component of that point using the sin and cos trigonometric functions.\ndf['day_sin'] = np.sin(df.day*(2.*np.pi/31))\ndf['day_cos'] = np.cos(df.day*(2.*np.pi/31))\ndf['month_sin'] = np.sin((df.month-1)*(2.*np.pi/12))\ndf['month_cos'] = np.cos((df.month-1)*(2.*np.pi/12))\n\n# Let's drop month, and day\n# TODO 5\ndf = df.drop(['month','day','year'], axis=1)", "_____no_output_____" ], [ "# scroll left to see the converted month and day coluumns.\ndf.tail(4)", "_____no_output_____" ] ], [ [ "### Conclusion\n\nThis notebook introduced a few concepts to improve data quality. We resolved missing values, converted the Date feature column to a datetime format, renamed feature columns, removed a value from a feature column, created one-hot encoding features, and converted temporal features to meaningful representations. By the end of our lab, we gained an understanding as to why data should be \"cleaned\" and \"pre-processed\" before input into a machine learning model.", "_____no_output_____" ], [ "Copyright 2020 Google Inc.\nLicensed 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\nhttp://www.apache.org/licenses/LICENSE-2.0\nUnless 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.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
cbe20a119ab2ca9130fa75baa8d0f8c22cb6d50f
153,100
ipynb
Jupyter Notebook
Goodreads-2-Book-Recommender-System.ipynb
OmarZaghlol/GoodBooks-Recommender
a80c0ff392d7ac917a39019a274e3c33402e8fdc
[ "MIT" ]
5
2020-06-24T22:36:39.000Z
2021-07-10T10:05:44.000Z
Goodreads-2-Book-Recommender-System.ipynb
OmarZaghlol/GoodBooks-Recommender
a80c0ff392d7ac917a39019a274e3c33402e8fdc
[ "MIT" ]
null
null
null
Goodreads-2-Book-Recommender-System.ipynb
OmarZaghlol/GoodBooks-Recommender
a80c0ff392d7ac917a39019a274e3c33402e8fdc
[ "MIT" ]
2
2022-02-01T16:29:40.000Z
2022-03-30T20:15:36.000Z
35.366135
450
0.403096
[ [ [ "# Books Recommender System", "_____no_output_____" ], [ "![](http://labs.criteo.com/wp-content/uploads/2017/08/CustomersWhoBought3.jpg)", "_____no_output_____" ], [ "This is the second part of my project on Book Data Analysis and Recommendation Systems. \n\nIn my first notebook ([The Story of Book](https://www.kaggle.com/omarzaghlol/goodreads-1-the-story-of-book/)), I attempted at narrating the story of book by performing an extensive exploratory data analysis on Books Metadata collected from Goodreads.\n\nIn this notebook, I will attempt at implementing a few recommendation algorithms (Basic Recommender, Content-based and Collaborative Filtering) and try to build an ensemble of these models to come up with our final recommendation system.", "_____no_output_____" ], [ "# What's in this kernel?", "_____no_output_____" ], [ "- [Importing Libraries and Loading Our Data](#1)\n- [Clean the dataset](#2)\n- [Simple Recommender](#3)\n - [Top Books](#4)\n - [Top \"Genres\" Books](#5)\n- [Content Based Recommender](#6)\n - [Cosine Similarity](#7)\n - [Popularity and Ratings](#8)\n- [Collaborative Filtering](#9)\n - [User Based](#10)\n - [Item Based](#11)\n- [Hybrid Recommender](#12)\n- [Conclusion](#13)\n- [Save Model](#14)", "_____no_output_____" ], [ "# Importing Libraries and Loading Our Data <a id=\"1\"></a> <br>", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport datetime\n\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "books = pd.read_csv('../input/goodbooks-10k//books.csv')\nratings = pd.read_csv('../input/goodbooks-10k//ratings.csv')\nbook_tags = pd.read_csv('../input/goodbooks-10k//book_tags.csv')\ntags = pd.read_csv('../input/goodbooks-10k//tags.csv')", "_____no_output_____" ] ], [ [ "# Clean the dataset <a id=\"2\"></a> <br>\n\nAs with nearly any real-life dataset, we need to do some cleaning first. When exploring the data I noticed that for some combinations of user and book there are multiple ratings, while in theory there should only be one (unless users can rate a book several times). Furthermore, for the collaborative filtering it is better to have more ratings per user. So I decided to remove users who have rated fewer than 3 books.", "_____no_output_____" ] ], [ [ "books['original_publication_year'] = books['original_publication_year'].fillna(-1).apply(lambda x: int(x) if x != -1 else -1)", "_____no_output_____" ], [ "ratings_rmv_duplicates = ratings.drop_duplicates()\nunwanted_users = ratings_rmv_duplicates.groupby('user_id')['user_id'].count()\nunwanted_users = unwanted_users[unwanted_users < 3]\nunwanted_ratings = ratings_rmv_duplicates[ratings_rmv_duplicates.user_id.isin(unwanted_users.index)]\nnew_ratings = ratings_rmv_duplicates.drop(unwanted_ratings.index)", "_____no_output_____" ], [ "new_ratings['title'] = books.set_index('id').title.loc[new_ratings.book_id].values", "_____no_output_____" ], [ "new_ratings.head(10)", "_____no_output_____" ] ], [ [ "# Simple Recommender <a id=\"3\"></a> <br>\n\nThe Simple Recommender offers generalized recommnendations to every user based on book popularity and (sometimes) genre. The basic idea behind this recommender is that books that are more popular and more critically acclaimed will have a higher probability of being liked by the average audience. This model does not give personalized recommendations based on the user.\n\nThe implementation of this model is extremely trivial. All we have to do is sort our books based on ratings and popularity and display the top books of our list. As an added step, we can pass in a genre argument to get the top books of a particular genre.\n", "_____no_output_____" ], [ "I will use IMDB's *weighted rating* formula to construct my chart. Mathematically, it is represented as follows:\n\nWeighted Rating (WR) = $(\\frac{v}{v + m} . R) + (\\frac{m}{v + m} . C)$\n\nwhere,\n* *v* is the number of ratings for the book\n* *m* is the minimum ratings required to be listed in the chart\n* *R* is the average rating of the book\n* *C* is the mean rating across the whole report\n\nThe next step is to determine an appropriate value for *m*, the minimum ratings required to be listed in the chart. We will use **95th percentile** as our cutoff. In other words, for a book to feature in the charts, it must have more ratings than at least 95% of the books in the list.\n\nI will build our overall Top 250 Chart and will define a function to build charts for a particular genre. Let's begin!", "_____no_output_____" ] ], [ [ "v = books['ratings_count']\nm = books['ratings_count'].quantile(0.95)\nR = books['average_rating']\nC = books['average_rating'].mean()\nW = (R*v + C*m) / (v + m)", "_____no_output_____" ], [ "books['weighted_rating'] = W", "_____no_output_____" ], [ "qualified = books.sort_values('weighted_rating', ascending=False).head(250)", "_____no_output_____" ] ], [ [ "## Top Books <a id=\"4\"></a> <br>", "_____no_output_____" ] ], [ [ "qualified[['title', 'authors', 'average_rating', 'weighted_rating']].head(15)", "_____no_output_____" ] ], [ [ "We see that J.K. Rowling's **Harry Potter** Books occur at the very top of our chart. The chart also indicates a strong bias of Goodreads Users towards particular genres and authors. \n\nLet us now construct our function that builds charts for particular genres. For this, we will use relax our default conditions to the **85th** percentile instead of 95. ", "_____no_output_____" ], [ "## Top \"Genres\" Books <a id=\"5\"></a> <br>", "_____no_output_____" ] ], [ [ "book_tags.head()", "_____no_output_____" ], [ "tags.head()", "_____no_output_____" ], [ "genres = [\"Art\", \"Biography\", \"Business\", \"Chick Lit\", \"Children's\", \"Christian\", \"Classics\",\n \"Comics\", \"Contemporary\", \"Cookbooks\", \"Crime\", \"Ebooks\", \"Fantasy\", \"Fiction\",\n \"Gay and Lesbian\", \"Graphic Novels\", \"Historical Fiction\", \"History\", \"Horror\",\n \"Humor and Comedy\", \"Manga\", \"Memoir\", \"Music\", \"Mystery\", \"Nonfiction\", \"Paranormal\",\n \"Philosophy\", \"Poetry\", \"Psychology\", \"Religion\", \"Romance\", \"Science\", \"Science Fiction\", \n \"Self Help\", \"Suspense\", \"Spirituality\", \"Sports\", \"Thriller\", \"Travel\", \"Young Adult\"]", "_____no_output_____" ], [ "genres = list(map(str.lower, genres))\ngenres[:4]", "_____no_output_____" ], [ "available_genres = tags.loc[tags.tag_name.str.lower().isin(genres)]", "_____no_output_____" ], [ "available_genres.head()", "_____no_output_____" ], [ "available_genres_books = book_tags[book_tags.tag_id.isin(available_genres.tag_id)]", "_____no_output_____" ], [ "print('There are {} books that are tagged with above genres'.format(available_genres_books.shape[0]))", "There are 60573 books that are tagged with above genres\n" ], [ "available_genres_books.head()", "_____no_output_____" ], [ "available_genres_books['genre'] = available_genres.tag_name.loc[available_genres_books.tag_id].values\navailable_genres_books.head()", "_____no_output_____" ], [ "def build_chart(genre, percentile=0.85):\n df = available_genres_books[available_genres_books['genre'] == genre.lower()]\n qualified = books.set_index('book_id').loc[df.goodreads_book_id]\n\n v = qualified['ratings_count']\n m = qualified['ratings_count'].quantile(percentile)\n R = qualified['average_rating']\n C = qualified['average_rating'].mean()\n qualified['weighted_rating'] = (R*v + C*m) / (v + m)\n\n qualified.sort_values('weighted_rating', ascending=False, inplace=True)\n return qualified", "_____no_output_____" ] ], [ [ "Let us see our method in action by displaying the Top 15 Fiction Books (Fiction almost didn't feature at all in our Generic Top Chart despite being one of the most popular movie genres).", "_____no_output_____" ] ], [ [ "cols = ['title','authors','original_publication_year','average_rating','ratings_count','work_text_reviews_count','weighted_rating']", "_____no_output_____" ], [ "genre = 'Fiction'\nbuild_chart(genre)[cols].head(15)", "_____no_output_____" ] ], [ [ "For simplicity, you can just pass the index of the wanted genre from below. ", "_____no_output_____" ] ], [ [ "list(enumerate(available_genres.tag_name))", "_____no_output_____" ], [ "idx = 24 # romance\nbuild_chart(list(available_genres.tag_name)[idx])[cols].head(15)", "_____no_output_____" ] ], [ [ "# Content Based Recommender <a id=\"6\"></a> <br>\n\n![](https://miro.medium.com/max/828/1*1b-yMSGZ1HfxvHiJCiPV7Q.png)\n\nThe recommender we built in the previous section suffers some severe limitations. For one, it gives the same recommendation to everyone, regardless of the user's personal taste. If a person who loves business books (and hates fiction) were to look at our Top 15 Chart, s/he wouldn't probably like most of the books. If s/he were to go one step further and look at our charts by genre, s/he wouldn't still be getting the best recommendations.\n\nFor instance, consider a person who loves *The Fault in Our Stars*, *Twilight*. One inference we can obtain is that the person loves the romaintic books. Even if s/he were to access the romance chart, s/he wouldn't find these as the top recommendations.\n\nTo personalise our recommendations more, I am going to build an engine that computes similarity between movies based on certain metrics and suggests books that are most similar to a particular book that a user liked. Since we will be using book metadata (or content) to build this engine, this also known as **Content Based Filtering.**\n\nI will build this recommender based on book's *Title*, *Authors* and *Genres*.", "_____no_output_____" ] ], [ [ "from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel, cosine_similarity", "_____no_output_____" ] ], [ [ "My approach to building the recommender is going to be extremely *hacky*. These are steps I plan to do:\n1. **Strip Spaces and Convert to Lowercase** from authors. This way, our engine will not confuse between **Stephen Covey** and **Stephen King**.\n2. Combining books with their corresponding **genres** .\n2. I then use a **Count Vectorizer** to create our count matrix.\n\nFinally, we calculate the cosine similarities and return books that are most similar.", "_____no_output_____" ] ], [ [ "books['authors'] = books['authors'].apply(lambda x: [str.lower(i.replace(\" \", \"\")) for i in x.split(', ')])", "_____no_output_____" ], [ "def get_genres(x):\n t = book_tags[book_tags.goodreads_book_id==x]\n return [i.lower().replace(\" \", \"\") for i in tags.tag_name.loc[t.tag_id].values]", "_____no_output_____" ], [ "books['genres'] = books.book_id.apply(get_genres)", "_____no_output_____" ], [ "books['soup'] = books.apply(lambda x: ' '.join([x['title']] + x['authors'] + x['genres']), axis=1)", "_____no_output_____" ], [ "books.soup.head()", "_____no_output_____" ], [ "count = CountVectorizer(analyzer='word',ngram_range=(1, 2),min_df=0, stop_words='english')\ncount_matrix = count.fit_transform(books['soup'])", "_____no_output_____" ] ], [ [ "## Cosine Similarity <a id=\"7\"></a> <br>\n\nI will be using the Cosine Similarity to calculate a numeric quantity that denotes the similarity between two books. Mathematically, it is defined as follows:\n\n$cosine(x,y) = \\frac{x. y^\\intercal}{||x||.||y||} $\n\n", "_____no_output_____" ] ], [ [ "cosine_sim = cosine_similarity(count_matrix, count_matrix)", "_____no_output_____" ], [ "indices = pd.Series(books.index, index=books['title'])\ntitles = books['title']", "_____no_output_____" ], [ "def get_recommendations(title, n=10):\n idx = indices[title]\n sim_scores = list(enumerate(cosine_sim[idx]))\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n sim_scores = sim_scores[1:31]\n book_indices = [i[0] for i in sim_scores]\n return list(titles.iloc[book_indices].values)[:n]", "_____no_output_____" ], [ "get_recommendations(\"The One Minute Manager\")", "_____no_output_____" ] ], [ [ "What if I want a specific book but I can't remember it's full name!!\n\nSo I created the following *method* to get book titles from a **partial** title.", "_____no_output_____" ] ], [ [ "def get_name_from_partial(title):\n return list(books.title[books.title.str.lower().str.contains(title) == True].values)", "_____no_output_____" ], [ "title = \"business\"\nl = get_name_from_partial(title)\nlist(enumerate(l))", "_____no_output_____" ], [ "get_recommendations(l[1])", "_____no_output_____" ] ], [ [ "## Popularity and Ratings <a id=\"8\"></a> <br>\n\nOne thing that we notice about our recommendation system is that it recommends books regardless of ratings and popularity. It is true that ***Across the River and Into the Trees*** and ***The Old Man and the Sea*** were written by **Ernest Hemingway**, but the former one was cnosidered a bad (not the worst) book that shouldn't be recommended to anyone, since that most people hated the book for it's static plot and overwrought emotion.\n\nTherefore, we will add a mechanism to remove bad books and return books which are popular and have had a good critical response.\n\nI will take the top 30 movies based on similarity scores and calculate the vote of the 60th percentile book. Then, using this as the value of $m$, we will calculate the weighted rating of each book using IMDB's formula like we did in the Simple Recommender section.", "_____no_output_____" ] ], [ [ "def improved_recommendations(title, n=10):\n idx = indices[title]\n sim_scores = list(enumerate(cosine_sim[idx]))\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n sim_scores = sim_scores[1:31]\n book_indices = [i[0] for i in sim_scores]\n df = books.iloc[book_indices][['title', 'ratings_count', 'average_rating', 'weighted_rating']]\n\n v = df['ratings_count']\n m = df['ratings_count'].quantile(0.60)\n R = df['average_rating']\n C = df['average_rating'].mean()\n df['weighted_rating'] = (R*v + C*m) / (v + m)\n \n qualified = df[df['ratings_count'] >= m]\n qualified = qualified.sort_values('weighted_rating', ascending=False)\n return qualified.head(n)", "_____no_output_____" ], [ "improved_recommendations(\"The One Minute Manager\")", "_____no_output_____" ], [ "improved_recommendations(l[1])", "_____no_output_____" ] ], [ [ "I think the sorting of similar is more better now than before.\nTherefore, we will conclude our Content Based Recommender section here and come back to it when we build a hybrid engine.\n", "_____no_output_____" ], [ "# Collaborative Filtering <a id=\"9\"></a> <br>\n\n![](https://miro.medium.com/max/706/1*DYJ-HQnOVvmm5suNtqV3Jw.png)\n\nOur content based engine suffers from some severe limitations. It is only capable of suggesting books which are *close* to a certain book. That is, it is not capable of capturing tastes and providing recommendations across genres.\n\nAlso, the engine that we built is not really personal in that it doesn't capture the personal tastes and biases of a user. Anyone querying our engine for recommendations based on a book will receive the same recommendations for that book, regardless of who s/he is.\n\nTherefore, in this section, we will use a technique called **Collaborative Filtering** to make recommendations to Book Readers. Collaborative Filtering is based on the idea that users similar to a me can be used to predict how much I will like a particular product or service those users have used/experienced but I have not.\n\nI will not be implementing Collaborative Filtering from scratch. Instead, I will use the **Surprise** library that used extremely powerful algorithms like **Singular Value Decomposition (SVD)** to minimise RMSE (Root Mean Square Error) and give great recommendations.", "_____no_output_____" ], [ "There are two classes of Collaborative Filtering:\n![](https://miro.medium.com/max/1280/1*QvhetbRjCr1vryTch_2HZQ.jpeg)\n- **User-based**, which measures the similarity between target users and other users.\n- **Item-based**, which measures the similarity between the items that target users rate or interact with and other items.", "_____no_output_____" ], [ "## - User Based <a id=\"10\"></a> <br>", "_____no_output_____" ] ], [ [ "# ! pip install surprise", "_____no_output_____" ], [ "from surprise import Reader, Dataset, SVD\nfrom surprise.model_selection import cross_validate", "_____no_output_____" ], [ "reader = Reader()\ndata = Dataset.load_from_df(new_ratings[['user_id', 'book_id', 'rating']], reader)", "_____no_output_____" ], [ "svd = SVD()\ncross_validate(svd, data, measures=['RMSE', 'MAE'])", "_____no_output_____" ] ], [ [ "We get a mean **Root Mean Sqaure Error** of about 0.8419 which is more than good enough for our case. Let us now train on our dataset and arrive at predictions.", "_____no_output_____" ] ], [ [ "trainset = data.build_full_trainset()\nsvd.fit(trainset);", "_____no_output_____" ] ], [ [ "Let us pick users 10 and check the ratings s/he has given.", "_____no_output_____" ] ], [ [ "new_ratings[new_ratings['user_id'] == 10]", "_____no_output_____" ], [ "svd.predict(10, 1506)", "_____no_output_____" ] ], [ [ "For book with ID 1506, we get an estimated prediction of **3.393**. One startling feature of this recommender system is that it doesn't care what the book is (or what it contains). It works purely on the basis of an assigned book ID and tries to predict ratings based on how the other users have predicted the book.", "_____no_output_____" ], [ "## - Item Based <a id=\"11\"></a> <br>", "_____no_output_____" ], [ "Here we will build a table for users with their corresponding ratings for each book. ", "_____no_output_____" ] ], [ [ "# bookmat = new_ratings.groupby(['user_id', 'title'])['rating'].mean().unstack()\nbookmat = new_ratings.pivot_table(index='user_id', columns='title', values='rating')\nbookmat.head()", "_____no_output_____" ], [ "def get_similar(title, mat):\n title_user_ratings = mat[title]\n similar_to_title = mat.corrwith(title_user_ratings)\n corr_title = pd.DataFrame(similar_to_title, columns=['correlation'])\n corr_title.dropna(inplace=True)\n corr_title.sort_values('correlation', ascending=False, inplace=True)\n return corr_title", "_____no_output_____" ], [ "title = \"Twilight (Twilight, #1)\"\nsmlr = get_similar(title, bookmat)", "_____no_output_____" ], [ "smlr.head(10)", "_____no_output_____" ] ], [ [ "Ok, we got similar books, but we need to filter them by their *ratings_count*.", "_____no_output_____" ] ], [ [ "smlr = smlr.join(books.set_index('title')['ratings_count'])\nsmlr.head()", "_____no_output_____" ] ], [ [ "Get similar books with at least 500k ratings.", "_____no_output_____" ] ], [ [ "smlr[smlr.ratings_count > 5e5].sort_values('correlation', ascending=False).head(10)", "_____no_output_____" ] ], [ [ "That's more interesting and reasonable result, since we could get *Twilight* book series in our top results. ", "_____no_output_____" ], [ "# Hybrid Recommender <a id=\"12\"></a> <br>\n\n![](https://www.toonpool.com/user/250/files/hybrid_20095.jpg)\n\nIn this section, I will try to build a simple hybrid recommender that brings together techniques we have implemented in the content based and collaborative filter based engines. This is how it will work:\n\n* **Input:** User ID and the Title of a Book\n* **Output:** Similar books sorted on the basis of expected ratings by that particular user.", "_____no_output_____" ] ], [ [ "def hybrid(user_id, title, n=10):\n idx = indices[title]\n sim_scores = list(enumerate(cosine_sim[idx]))\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n sim_scores = sim_scores[1:51]\n book_indices = [i[0] for i in sim_scores]\n \n df = books.iloc[book_indices][['book_id', 'title', 'original_publication_year', 'ratings_count', 'average_rating']]\n df['est'] = df['book_id'].apply(lambda x: svd.predict(user_id, x).est)\n df = df.sort_values('est', ascending=False)\n return df.head(n)", "_____no_output_____" ], [ "hybrid(4, 'Eat, Pray, Love')", "_____no_output_____" ], [ "hybrid(10, 'Eat, Pray, Love')", "_____no_output_____" ] ], [ [ "We see that for our hybrid recommender, we get (almost) different recommendations for different users although the book is the same. But maybe we can make it better through following steps:\n1. Use our *improved_recommendations* technique , that we used in the **Content Based** seciton above\n2. Combine it with the user *estimations*, by dividing their summation by 2\n3. Finally, put the result into a new feature ***score***", "_____no_output_____" ] ], [ [ "def improved_hybrid(user_id, title, n=10):\n idx = indices[title]\n sim_scores = list(enumerate(cosine_sim[idx]))\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n sim_scores = sim_scores[1:51]\n book_indices = [i[0] for i in sim_scores]\n \n df = books.iloc[book_indices][['book_id', 'title', 'ratings_count', 'average_rating', 'original_publication_year']]\n v = df['ratings_count']\n m = df['ratings_count'].quantile(0.60)\n R = df['average_rating']\n C = df['average_rating'].mean()\n df['weighted_rating'] = (R*v + C*m) / (v + m)\n \n df['est'] = df['book_id'].apply(lambda x: svd.predict(user_id, x).est)\n \n df['score'] = (df['est'] + df['weighted_rating']) / 2\n df = df.sort_values('score', ascending=False)\n return df[['book_id', 'title', 'original_publication_year', 'ratings_count', 'average_rating', 'score']].head(n)", "_____no_output_____" ], [ "improved_hybrid(4, 'Eat, Pray, Love')", "_____no_output_____" ], [ "improved_hybrid(10, 'Eat, Pray, Love')", "_____no_output_____" ] ], [ [ "Ok, we see that the new results make more sense, besides to, the recommendations are more personalized and tailored towards particular users.", "_____no_output_____" ], [ "# Conclusion <a id=\"13\"></a> <br>\n\nIn this notebook, I have built 4 different recommendation engines based on different ideas and algorithms. They are as follows:\n\n1. **Simple Recommender:** This system used overall Goodreads Ratings Count and Rating Averages to build Top Books Charts, in general and for a specific genre. The IMDB Weighted Rating System was used to calculate ratings on which the sorting was finally performed.\n2. **Content Based Recommender:** We built content based engines that took book title, authors and genres as input to come up with predictions. We also deviced a simple filter to give greater preference to books with more votes and higher ratings.\n3. **Collaborative Filtering:** We built two Collaborative Filters; \n - one that uses the powerful Surprise Library to build an **user-based** filter based on single value decomposition, since the RMSE obtained was less than 1, and the engine gave estimated ratings for a given user and book.\n - And the other (**item-based**) which built a pivot table for users ratings corresponding to each book, and the engine gave similar books for a given book.\n4. **Hybrid Engine:** We brought together ideas from content and collaborative filterting to build an engine that gave book suggestions to a particular user based on the estimated ratings that it had internally calculated for that user.\n\nPrevious -> [The Story of Book](https://www.kaggle.com/omarzaghlol/goodreads-1-the-story-of-book/)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ] ]
cbe2132b6b54d109d13468216f1a4daad308162d
353,239
ipynb
Jupyter Notebook
correlation analysis.ipynb
laofei177/Ornstein-Uhlenbeck-Correlations
d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb
[ "MIT" ]
2
2020-12-29T02:28:29.000Z
2021-02-23T08:32:29.000Z
correlation analysis.ipynb
laofei177/Ornstein-Uhlenbeck-Correlations
d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb
[ "MIT" ]
null
null
null
correlation analysis.ipynb
laofei177/Ornstein-Uhlenbeck-Correlations
d1bcf4e1ec80ad3bf5e7851ac3d63c728aff76eb
[ "MIT" ]
null
null
null
109.294245
29,852
0.779755
[ [ [ "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom scipy.stats import gaussian_kde, chi2, pearsonr\n\nSMALL_SIZE = 16\nMEDIUM_SIZE = 18\nBIGGER_SIZE = 20\n\nplt.rc('font', size=SMALL_SIZE) # controls default text sizes\nplt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\nplt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\nplt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\nplt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n\nSEED = 35010732 # from random.org\nnp.random.seed(SEED)\n\nprint(plt.style.available)\nplt.style.use('seaborn-white')", "['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight', 'seaborn-whitegrid', 'classic', '_classic_test', 'fast', 'seaborn-talk', 'seaborn-dark-palette', 'seaborn-bright', 'seaborn-pastel', 'grayscale', 'seaborn-notebook', 'ggplot', 'seaborn-colorblind', 'seaborn-muted', 'seaborn', 'Solarize_Light2', 'seaborn-paper', 'bmh', 'tableau-colorblind10', 'seaborn-white', 'dark_background', 'seaborn-poster', 'seaborn-deep']\n" ], [ "cor1000 = pd.read_csv(\"correlations1kbig.csv\")\ncor10k = pd.read_csv(\"correlations10kbig.csv\")", "_____no_output_____" ], [ "cor1000", "_____no_output_____" ], [ "corr1000_avg = cor1000.groupby('rho').mean().reset_index()\ncorr1000_std = cor1000.groupby('rho').std().reset_index()\ncorr1000_avg", "_____no_output_____" ], [ "plt.figure(figsize=(5,5))\nrho_theory = np.linspace(-0.95,0.95,100)\nc_theory = 2*np.abs(rho_theory)/(1-np.abs(rho_theory))*np.sign(rho_theory)\nplt.scatter(cor1000['rho'],cor1000['C'])\nplt.plot(rho_theory,c_theory)\nplt.axhline(y=0.0, color='r')", "_____no_output_____" ], [ "plt.figure(figsize=(5,5))\nrho_theory = np.linspace(-0.95,0.95,100)\nc_theory = 2*np.abs(rho_theory)/(1-np.abs(rho_theory))*np.sign(rho_theory)\nplt.errorbar(corr1000_avg['rho'],corr1000_avg['C'],yerr=corr1000_avg['dC'],fmt=\"o\",color='k')\nplt.plot(rho_theory,c_theory,\"k\")\nplt.axhline(y=0.0, color='k')\nplt.xlabel(r'$\\rho$')\nplt.ylabel(\"C\")\nplt.savefig(\"corr.png\",format='png',dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "for rho in corr1000_avg['rho']:\n data1000_rho = cor1000[cor1000['rho']==rho]\n print(rho,data1000_rho['A1'].mean(),data1000_rho['A1'].std(),data1000_rho['dA1'].mean())\n print(rho,data1000_rho['A2'].mean(),data1000_rho['A2'].std(),data1000_rho['dA2'].mean())", "-0.9 0.05301701459568897 0.002515516253284246 0.002429792563943476\n-0.9 1.0818685626505147 0.15869614098396545 0.18032073951754793\n-0.8 0.11319464223731397 0.0073424514917234795 0.006104937437321736\n-0.8 1.0901007208305413 0.1688256052031771 0.18346285636164286\n-0.7000000000000001 0.1814470136785351 0.014286580945571748 0.011812670745756544\n-0.7000000000000001 1.082304079924507 0.1688198243407117 0.1819807215266534\n-0.6000000000000001 0.2521196711685988 0.017651397963112377 0.019014016641455356\n-0.6000000000000001 1.0611083567172692 0.16502680362880476 0.1757578997711312\n-0.5000000000000001 0.3403710814106374 0.02837735258534806 0.029781028307193952\n-0.5000000000000001 1.0470219431839467 0.13174383471076775 0.17133298312622014\n-0.4000000000000001 0.4330460357920816 0.04123338245534238 0.04302704079798649\n-0.4000000000000001 1.0691576679931747 0.13788654015917062 0.1777715606941423\n-0.30000000000000016 0.5516146896885783 0.06270752708273135 0.06243669464900841\n-0.30000000000000016 1.097947694683695 0.2000958982539863 0.18721983229728342\n-0.20000000000000015 0.6834305609998819 0.0819176211353721 0.08724056470566012\n-0.20000000000000015 1.052863341010581 0.15747876886040044 0.17407439007864817\n-0.1000000000000002 0.8723473499217238 0.1549990554085446 0.13018095963541876\n-0.1000000000000002 1.1163560302991564 0.2049518580789478 0.19373099008820657\n-2.220446049250313e-16 1.049521097590835 0.14401868611316737 0.1740904985684165\n-2.220446049250313e-16 1.0429611987161551 0.14372401955541805 0.1713130712237177\n0.09999999999999976 1.1170447447711698 0.19278687932422345 0.1917744170330967\n0.09999999999999976 0.8625660501058644 0.10665673035323327 0.1257284259057485\n0.1999999999999996 1.054659416807181 0.15640149670369777 0.1735691316680014\n0.1999999999999996 0.6967819185511153 0.08395189758776257 0.08974756346495875\n0.2999999999999997 1.0363631578644539 0.14758794941390074 0.16997903362015823\n0.2999999999999997 0.5556932235679382 0.061026529007408924 0.0635162995946039\n0.3999999999999998 1.0702877127162786 0.15616652995481686 0.1781780866753814\n0.3999999999999998 0.4358117186118178 0.03779030207210857 0.04329055599273048\n0.4999999999999997 1.0805427121361233 0.16874384935265968 0.18206246663381587\n0.4999999999999997 0.3402947174878042 0.029493931439976223 0.029922329603968373\n0.5999999999999995 1.1133820395578002 0.1765425506206242 0.1911731453891984\n0.5999999999999995 0.25118447738390737 0.01816817696823987 0.018972607011638696\n0.6999999999999996 1.0537999710759138 0.16102810649099694 0.17402606893716188\n0.6999999999999996 0.17572835986017388 0.009336224879971322 0.011262775629419235\n0.7999999999999997 1.0674650318609473 0.14815971754414722 0.17665593562476592\n0.7999999999999997 0.11089864983053528 0.007016267513394309 0.005955876713709982\n0.8999999999999996 1.071297965698285 0.1674632878703899 0.17827938428909348\n0.8999999999999996 0.053383685363191366 0.0019390701465062596 0.002448143482405957\n" ], [ "data1000_05 = cor1000[cor1000['rho']==0.4999999999999997]\ndata1000_05", "_____no_output_____" ], [ "plt.hist(data1000_05['A1'],bins=10,density=True)", "_____no_output_____" ], [ "data1k05 = pd.read_csv('correlations1k05.csv')\ndata1k05", "_____no_output_____" ], [ "plt.hist(data1k05['a2'],bins=30,density=True)\nprint(data1k05['A1'].mean(),data1k05['A1'].std(),data1k05['dA1'].mean(),data1k05['dA1'].std())\nprint(data1k05['a1'].mean(),data1k05['a1'].std(),data1k05['da1'].mean(),data1k05['da1'].std())\nprint(data1k05['A2'].mean(),data1k05['A2'].std(),data1k05['dA2'].mean(),data1k05['dA2'].std())\nprint(data1k05['a2'].mean(),data1k05['a2'].std(),data1k05['da2'].mean(),data1k05['da2'].std())", "1.063941227269644 0.15428905830587167 0.1767419338057733 0.04228487329157142\n0.994118110781075 0.13399997372170652 0.04354111573886395 0.008507779830677476\n0.33986122170707356 0.03099200135583867 0.02982305110184233 0.0041696208030104825\n0.33272776388498426 0.02969319216633135 0.01202465992657017 0.001151402955636694\n" ], [ "plt.figure(facecolor=\"white\")\nxs = np.linspace(0.25,2,200)\ndensityA1 = gaussian_kde(data1k05['A1'])\ndensityA2 = gaussian_kde(data1k05['A2'])\ndensitya1 = gaussian_kde(data1k05['a1'])\ndensitya2 = gaussian_kde(data1k05['a2'])\nplt.plot(xs,densityA1(xs),\"k-\",label=r\"$A_{1}$ MCMC\")\nplt.plot(xs,densitya1(xs),\"k:\",label=r\"$A_{1}$ ML\")\nplt.axvline(x=1.0,color=\"k\")\nplt.legend()\nplt.xlabel(r\"$A_1$\")\nplt.ylabel(r\"$p(A_{1})$\")\nplt.savefig(\"A1kde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "plt.figure(facecolor=\"white\")\nxs = np.linspace(0.25,0.5,200)\ndensityA2 = gaussian_kde(data1k05['A2'])\ndensitya2 = gaussian_kde(data1k05['a2'])\nplt.plot(xs,densityA2(xs),\"k-\",label=r\"$A_{2}$ MCMC\")\nplt.plot(xs,densitya2(xs),\"k:\",label=r\"$A_{2}$ ML\")\nplt.axvline(x=0.3333,color=\"k\")\nplt.legend()\nplt.xlabel(r\"$A_2$\")\nplt.ylabel(r\"$p(A_{2})$\")\nplt.savefig(\"A2kde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "data1k025 = pd.read_csv('correlations1k025.csv')\ndata1k025", "_____no_output_____" ], [ "plt.hist(data1k025['a2'],bins=30,density=True)\nprint(data1k025['A1'].mean(),data1k025['A1'].std(),data1k025['dA1'].mean(),data1k025['dA1'].std())\nprint(data1k025['a1'].mean(),data1k025['a1'].std(),data1k025['da1'].mean(),data1k025['da1'].std())\nprint(data1k025['A2'].mean(),data1k025['A2'].std(),data1k025['dA2'].mean(),data1k025['dA2'].std())\nprint(data1k025['a2'].mean(),data1k025['a2'].std(),data1k025['da2'].mean(),data1k025['da2'].std())", "1.0758144897779076 0.1607575594720723 0.18047464607859667 0.04544120818274805\n1.0041012252296502 0.13872496535748483 0.03359461470778005 0.005859331347381333\n0.6247488381384534 0.0701332387355429 0.07579024406369594 0.013396674802329613\n0.6008037670999967 0.06471284816307284 0.018644421099685535 0.0022068114943402765\n" ], [ "plt.figure(facecolor=\"white\")\nxs = np.linspace(0.25,2,200)\ndensityA1 = gaussian_kde(data1k025['A1'])\ndensityA2 = gaussian_kde(data1k025['A2'])\ndensitya1 = gaussian_kde(data1k025['a1'])\ndensitya2 = gaussian_kde(data1k025['a2'])\nplt.plot(xs,densityA1(xs),\"k-\",label=r\"$A_{1}$ MCMC\")\nplt.plot(xs,densitya1(xs),\"k:\",label=r\"$A_{1}$ ML\")\nplt.axvline(x=1.0,color=\"k\")\nplt.legend()\nplt.xlabel(r\"$A_1$\")\nplt.ylabel(r\"$p(A_{1})$\")\nplt.savefig(\"A1kde025.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "plt.figure(facecolor=\"white\")\nxs = np.linspace(0.35,1,200)\ndensityA2 = gaussian_kde(data1k025['A2'])\ndensitya2 = gaussian_kde(data1k025['a2'])\nplt.plot(xs,densityA2(xs),\"k-\",label=r\"$A_{2}$ MCMC\")\nplt.plot(xs,densitya2(xs),\"k:\",label=r\"$A_{2}$ ML\")\nplt.axvline(x=0.6,color=\"k\")\nplt.legend()\nplt.xlabel(r\"$A_2$\")\nplt.ylabel(r\"$p(A_{2})$\")\nplt.savefig(\"A2kde025.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "plt.figure(facecolor=\"white\")\nplt.scatter(data1k05['D'],data1k05['d'])\nplt.xlabel(r\"$A_1$ MCMC\")\nplt.ylabel(r\"$A_{1}$ ML\")\nplt.savefig(\"A1corrkde025.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "_____no_output_____" ], [ "print(pearsonr(data1k025['A1'],data1k025['a1']))\nprint(pearsonr(data1k025['A2'],data1k025['a2']))\nprint(pearsonr(data1k025['D'],data1k025['d']))", "(0.9996350192345431, 0.0)\n(0.9998819465020963, 0.0)\n(0.999988582828996, 0.0)\n" ], [ "p1 = np.polyfit(data1k05['dA1'],data1k05['da1'],1)\nprint(p1)\nprint(\"factor of underestimation: \",1/p1[0])\ndA1 = np.linspace(0.09,0.4,200)\nda1 = p1[0]*dA1 + p1[1]\nplt.figure(facecolor=\"white\")\nplt.scatter(data1k05['dA1'],data1k05['da1'],color=\"k\")\nplt.plot(dA1,da1,\"k:\")\nplt.xlabel(r\"$dA_1$ MCMC\")\nplt.ylabel(r\"$dA_{1}$ ML\")\nplt.savefig(\"dA1corrkde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "[0.19702769 0.00871806]\nfactor of underestimation: 5.075428736953656\n" ], [ "p2 = np.polyfit(data1k05['dA2'],data1k05['da2'],1)\nprint(p2)\nprint(\"factor of underestimation: \",1/p2[0])\ndA2 = np.linspace(0.03,0.15,200)\nda2 = p2[0]*dA2 + p2[1]\nplt.figure(facecolor=\"white\")\nplt.scatter(data1k05['dA2'],data1k05['da2'],color=\"k\")\nplt.plot(dA2,da2,\"k:\")\nplt.xlabel(r\"$dA_2$ MCMC\")\nplt.ylabel(r\"$dA_{2}$ ML\")\nplt.savefig(\"dA2corrkde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "[0.26825063 0.00402461]\nfactor of underestimation: 3.7278570472478068\n" ], [ "p1 = np.polyfit(data1k025['dA1'],data1k025['da1'],1)\nprint(p1)", "[0.12690797 0.01069094]\n" ], [ "p1 = np.polyfit(data1k05['dA1'],data1k05['da1'],1)\nprint(p1)\nprint(\"factor of underestimation: \",1/p1[0])\ndA1 = np.linspace(0.05,0.4,200)\nda1 = p1[0]*dA1 + p1[1]\nplt.figure(facecolor=\"white\")\nplt.scatter(data1k05['dA1'],data1k05['da1'],color=\"k\")\nplt.plot(dA1,da1,\"k:\")\nplt.xlabel(r\"$dA_1$ MCMC\")\nplt.ylabel(r\"$dA_{1}$ ML\")\nplt.savefig(\"dA1corrkde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "[0.12849691 0.01053264]\nfactor of underestimation: 7.782288407416904\n" ], [ "p2 = np.polyfit(data1k05['dA2'],data1k05['da2'],1)\nprint(p2)\nprint(\"factor of underestimation: \",1/p2[0])\ndA2 = np.linspace(0.015,0.05,200)\nda2 = p2[0]*dA2 + p2[1]\nplt.figure(facecolor=\"white\")\nplt.scatter(data1k05['dA2'],data1k05['da2'],color=\"k\")\nplt.plot(dA2,da2,\"k:\")\nplt.xlabel(r\"$dA_2$ MCMC\")\nplt.ylabel(r\"$dA_{2}$ ML\")\nplt.savefig(\"dA2corrkde05.png\",format=\"png\",dpi=300,bbox_inches='tight',facecolor=\"white\",backgroundcolor=\"white\")", "[0.20921369 0.00388881]\nfactor of underestimation: 4.779802045687235\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe21679fa85c21806d811912000a9e1ed5044ff
6,391
ipynb
Jupyter Notebook
3. Facial Keypoint Detection, Complete Pipeline-zh.ipynb
jaspartang/Facial_Keypoint_Detection
64897ad79052777ff34cb4466db52818d584cded
[ "MIT" ]
null
null
null
3. Facial Keypoint Detection, Complete Pipeline-zh.ipynb
jaspartang/Facial_Keypoint_Detection
64897ad79052777ff34cb4466db52818d584cded
[ "MIT" ]
null
null
null
3. Facial Keypoint Detection, Complete Pipeline-zh.ipynb
jaspartang/Facial_Keypoint_Detection
64897ad79052777ff34cb4466db52818d584cded
[ "MIT" ]
null
null
null
30.146226
180
0.59928
[ [ [ "## 人脸与人脸关键点检测\n\n在训练用于检测面部关键点的神经网络之后,你可以将此网络应用于包含人脸的*任何一个*图像。该神经网络需要一定大小的Tensor作为输入,因此,要检测任何一个人脸,你都首先必须进行一些预处理。\n\n1. 使用人脸检测器检测图像中的所有人脸。在这个notebook中,我们将使用Haar级联检测器。\n2. 对这些人脸图像进行预处理,使其成为灰度图像,并转换为你期望的输入尺寸的张量。这个步骤与你在Notebook 2中创建和应用的`data_transform` 类似,其作用是重新缩放、归一化,并将所有图像转换为Tensor,作为CNN的输入。\n3. 使用已被训练的模型检测图像上的人脸关键点。\n\n---\n\n在下一个python单元格中,我们要加载项目此部分所需的库。", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline", "_____no_output_____" ] ], [ [ "#### 选择图像 \n\n选择一张图像,执行人脸关键点检测。你可以在`images/`目录中选择任何一张人脸图像。", "_____no_output_____" ] ], [ [ "import cv2\n# load in color image for face detection\nimage = cv2.imread('images/obamas.jpg')\n\n# switch red and blue color channels \n# --> by default OpenCV assumes BLUE comes first, not RED as in many images\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# plot the image\nfig = plt.figure(figsize=(9,9))\nplt.imshow(image)", "_____no_output_____" ] ], [ [ "## 检测该图像中的所有人脸\n\n要想检测到所选图像中的所有人脸,接下来,你要用到的是OpenCV预先训练的一个Haar级联分类器,所有这些分类器都可以在`detector_architectures/`目录中找到。\n\n在下面的代码中,我们要遍历原始图像中的每个人脸,并在原始图像的副本中的每个人脸上绘制一个红色正方形,而原始图像不需要修改。此外,你也可以 [新增一项眼睛检测 ](https://docs.opencv.org/3.4.1/d7/d8b/tutorial_py_face_detection.html) ,作为使用Haar检测器的一个可选练习。\n\n下面是各种图像上的人脸检测示例。\n\n<img src='images/haar_cascade_ex.png' width=80% height=80%/>", "_____no_output_____" ] ], [ [ "# load in a haar cascade classifier for detecting frontal faces\nface_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')\n\n# run the detector\n# the output here is an array of detections; the corners of each detection box\n# if necessary, modify these parameters until you successfully identify every face in a given image\nfaces = face_cascade.detectMultiScale(image, 1.2, 2)\n\n# make a copy of the original image to plot detections on\nimage_with_detections = image.copy()\n\n# loop over the detected faces, mark the image where each face is found\nfor (x,y,w,h) in faces:\n # draw a rectangle around each detected face\n # you may also need to change the width of the rectangle drawn depending on image resolution\n cv2.rectangle(image_with_detections,(x,y),(x+w,y+h),(255,0,0),3) \n\nfig = plt.figure(figsize=(9,9))\n\nplt.imshow(image_with_detections)", "_____no_output_____" ] ], [ [ "## 加载到已训练的模型中\n\n有了一个可以使用的图像后(在这里,你可以选择`images/` 目录中的任何一张人脸图像),下一步是对该图像进行预处理并将其输入进CNN人脸关键点检测器。\n\n首先,按文件名加载你选定的最佳模型。", "_____no_output_____" ] ], [ [ "import torch\nfrom models import Net\n\nnet = Net()\n\n## TODO: load the best saved model parameters (by your path name)\n## You'll need to un-comment the line below and add the correct name for *your* saved model\n# net.load_state_dict(torch.load('saved_models/keypoints_model_1.pt'))\n\n## print out your net and prepare it for testing (uncomment the line below)\n# net.eval()", "_____no_output_____" ] ], [ [ "## 关键点检测\n\n现在,我们需要再一次遍历图像中每个检测到的人脸,只是这一次,你需要将这些人脸转换为CNN可以接受的张量形式的输入图像。\n\n### TODO: 将每个检测到的人脸转换为输入Tensor\n\n你需要对每个检测到的人脸执行以下操作:\n1. 将人脸从RGB图转换为灰度图\n2. 把灰度图像归一化,使其颜色范围落在[0,1]范围,而不是[0,255]\n3. 将检测到的人脸重新缩放为CNN的预期方形尺寸(我们建议为 224x224)\n4. 将numpy图像变形为torch图像。\n\n**提示**: Haar检测器检测到的人脸大小与神经网络训练过的人脸大小不同。如果你发现模型生成的关键点对给定的人脸来说,显得太小,请尝试在检测到的`roi`中添加一些填充,然后将其作为模型的输入。\n\n你可能会发现,参看`data_load.py`中的转换代码对帮助执行这些处理步骤很有帮助。\n\n\n### TODO: 检测并显示预测到的关键点\n\n将每个人脸适当地转换为网络的输入Tensor之后,就可以将`net` 应用于每个人脸。输出应该是预测到的人脸关键点,这些关键点需要“非归一化”才能显示。你可能会发现,编写一个类似`show_keypoints`的辅助函数会很有帮助。最后,你会得到一张如下的图像,其中人脸关键点与每张人脸上的面部特征非常匹配:\n\n<img src='images/michelle_detected.png' width=30% height=30%/>", "_____no_output_____" ] ], [ [ "image_copy = np.copy(image)\n\n# loop over the detected faces from your haar cascade\nfor (x,y,w,h) in faces:\n \n # Select the region of interest that is the face in the image \n roi = image_copy[y:y+h, x:x+w]\n \n ## TODO: Convert the face region from RGB to grayscale\n\n ## TODO: Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]\n \n ## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)\n \n ## TODO: Reshape the numpy image shape (H x W x C) into a torch image shape (C x H x W)\n \n ## TODO: Make facial keypoint predictions using your loaded, trained network \n\n ## TODO: Display each detected face and the corresponding keypoints \n \n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe21c63e89bc3534f9e2d90027fd26e35fe05d6
411,394
ipynb
Jupyter Notebook
pytorch/WGAN_CIFAR10_pytorch.ipynb
kawausomando/DeepLearningMugenKnock
b6592c26793aaa45a94753f4324ec183ef078297
[ "MIT" ]
10
2021-12-17T06:07:25.000Z
2022-03-25T13:50:05.000Z
pytorch/WGAN_CIFAR10_pytorch.ipynb
kawausomando/DeepLearningMugenKnock
b6592c26793aaa45a94753f4324ec183ef078297
[ "MIT" ]
null
null
null
pytorch/WGAN_CIFAR10_pytorch.ipynb
kawausomando/DeepLearningMugenKnock
b6592c26793aaa45a94753f4324ec183ef078297
[ "MIT" ]
2
2022-03-15T02:42:09.000Z
2022-03-30T23:19:55.000Z
498.05569
32,208
0.932201
[ [ [ "# WGAN\n\n元論文 : Wasserstein GAN https://arxiv.org/abs/1701.07875 (2017)\n\nWGANはGANのLossを変えることで、数学的に画像生成の学習を良くしよう!っていうもの。\n\n通常のGANはKLDivergenceを使って、Generatorによる確率分布を、生成したい画像の生起分布に近づけていく。だが、KLDでは連続性が保証されないので、代わりにWasserstain距離を用いて、近似していこうというのがWGAN。\n\nWasserstain距離によるLossを実現するために、WGANのDiscriminatorでは最後にSigmoid関数を適用しない。つまり、LossもSigmoid Cross Entropyでなく、Discriminatorの出力の値をそのまま使う。\n\nWGANのアルゴリズムは、イテレーション毎に以下のDiscriminatorとGeneratorの学習を交互に行っていく。\n- 最適化 : RMSProp(LearningRate:0.0005)\n\n#### Discriminatorの学習(以下操作をcriticの数値だけ繰り返す)\n1. Real画像と、一様分布からzをサンプリングする\n2. Loss $L_D = \\frac{1}{|Minibatch|} \\{ \\sum_{i} D(x^{(i)}) - \\sum_i D (G(z^{(i)})) \\}$ を計算し、SGD\n3. Discriminatorのパラメータを全て、 [- clip, clip] にクリッピングする\n\n#### Generatorの学習\n1. 一様分布からzをサンプリングする\n2. Loss $L_G = \\frac{1}{|Minibatch|} \\sum_i D (G(z^{(i)})) $ を計算し、SGD\n\n(WGANは収束がすごく遅い、、学習回数がめちゃくちゃ必要なので、注意!!!!)", "_____no_output_____" ], [ "## Import and Config", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn.functional as F\nimport torchvision\nimport numpy as np\nfrom collections import OrderedDict\nfrom easydict import EasyDict\nimport argparse\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom _main_base import *\n\n#---\n# config\n#---\ncfg = EasyDict()\n\n# class\ncfg.CLASS_LABEL = ['akahara', 'madara'] # list, dict('label' : '[B, G, R]')\ncfg.CLASS_NUM = len(cfg.CLASS_LABEL)\n\n# model\ncfg.INPUT_Z_DIM = 128\ncfg.INPUT_MODE = None\n\ncfg.OUTPUT_HEIGHT = 32\ncfg.OUTPUT_WIDTH = 32\ncfg.OUTPUT_CHANNEL = 3\ncfg.OUTPUT_MODE = 'RGB' # RGB, GRAY, EDGE, CLASS_LABEL\n\ncfg.G_DIM = 64\ncfg.D_DIM = 64\n\ncfg.CHANNEL_AXIS = 1 # 1 ... [mb, c, h, w], 3 ... [mb, h, w, c]\n\ncfg.GPU = False\ncfg.DEVICE = torch.device('cuda' if cfg.GPU and torch.cuda.is_available() else 'cpu')\n\n# train\ncfg.TRAIN = EasyDict()\ncfg.TRAIN.DISPAY_ITERATION_INTERVAL = 50\n\ncfg.PREFIX = 'WGAN'\ncfg.TRAIN.MODEL_G_SAVE_PATH = 'models/' + cfg.PREFIX + '_G_{}.pt'\ncfg.TRAIN.MODEL_D_SAVE_PATH = 'models/' + cfg.PREFIX + '_D_{}.pt'\ncfg.TRAIN.MODEL_SAVE_INTERVAL = 200\ncfg.TRAIN.ITERATION = 5000\ncfg.TRAIN.MINIBATCH = 32\ncfg.TRAIN.OPTIMIZER_G = torch.optim.Adam\ncfg.TRAIN.LEARNING_PARAMS_G = {'lr' : 0.0002, 'betas' : (0.5, 0.9)}\ncfg.TRAIN.OPTIMIZER_D = torch.optim.Adam\ncfg.TRAIN.LEARNING_PARAMS_D = {'lr' : 0.0002, 'betas' : (0.5, 0.9)}\ncfg.TRAIN.LOSS_FUNCTION = None\n\ncfg.TRAIN.DATA_PATH = './data/'\ncfg.TRAIN.DATA_HORIZONTAL_FLIP = False # data augmentation : holizontal flip\ncfg.TRAIN.DATA_VERTICAL_FLIP = False # data augmentation : vertical flip\ncfg.TRAIN.DATA_ROTATION = False # data augmentation : rotation False, or integer\n\ncfg.TRAIN.LEARNING_PROCESS_RESULT_SAVE = True\ncfg.TRAIN.LEARNING_PROCESS_RESULT_INTERVAL = 500\ncfg.TRAIN.LEARNING_PROCESS_RESULT_IMAGE_PATH = 'result/' + cfg.PREFIX + '_result_{}.jpg'\ncfg.TRAIN.LEARNING_PROCESS_RESULT_LOSS_PATH = 'result/' + cfg.PREFIX + '_loss.txt'\n\n#---\n# WGAN config\n#---\ncfg.TRAIN.WGAN_CLIPS_VALUE = 0.01\ncfg.TRAIN.WGAN_CRITIC_N = 5\n\n# test\ncfg.TEST = EasyDict()\ncfg.TEST.MODEL_G_PATH = cfg.TRAIN.MODEL_G_SAVE_PATH.format('final')\ncfg.TEST.DATA_PATH = './data'\ncfg.TEST.MINIBATCH = 10\ncfg.TEST.ITERATION = 2\ncfg.TEST.RESULT_SAVE = False\ncfg.TEST.RESULT_IMAGE_PATH = 'result/' + cfg.PREFIX + '_result_{}.jpg'\n\n# random seed\ntorch.manual_seed(0)\n\n\n# make model save directory\ndef make_dir(path):\n if '/' in path:\n model_save_dir = '/'.join(path.split('/')[:-1])\n os.makedirs(model_save_dir, exist_ok=True)\n\nmake_dir(cfg.TRAIN.MODEL_G_SAVE_PATH)\nmake_dir(cfg.TRAIN.MODEL_D_SAVE_PATH)\nmake_dir(cfg.TRAIN.LEARNING_PROCESS_RESULT_IMAGE_PATH)\nmake_dir(cfg.TRAIN.LEARNING_PROCESS_RESULT_LOSS_PATH)\n", "_____no_output_____" ] ], [ [ "## Define Model", "_____no_output_____" ] ], [ [ "class Generator(torch.nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.module = torch.nn.Sequential(OrderedDict({\n 'G_layer_1' : torch.nn.ConvTranspose2d(cfg.INPUT_Z_DIM, cfg.G_DIM * 4, kernel_size=[cfg.OUTPUT_HEIGHT // 8, cfg.OUTPUT_WIDTH // 8], stride=1, bias=False),\n 'G_layer_1_bn' : torch.nn.BatchNorm2d(cfg.G_DIM * 4),\n 'G_layer_1_ReLU' : torch.nn.ReLU(),\n 'G_layer_2' : torch.nn.ConvTranspose2d(cfg.G_DIM * 4, cfg.G_DIM * 2, kernel_size=4, stride=2, padding=1, bias=False),\n 'G_layer_2_bn' : torch.nn.BatchNorm2d(cfg.G_DIM * 2),\n 'G_layer_2_ReLU' : torch.nn.ReLU(),\n 'G_layer_3' : torch.nn.ConvTranspose2d(cfg.G_DIM * 2, cfg.G_DIM, kernel_size=4, stride=2, padding=1, bias=False),\n 'G_layer_3_bn' : torch.nn.BatchNorm2d(cfg.G_DIM),\n 'G_layer_3_ReLU' : torch.nn.ReLU(),\n 'G_layer_out' : torch.nn.ConvTranspose2d(cfg.G_DIM, cfg.OUTPUT_CHANNEL, kernel_size=4, stride=2, padding=1, bias=False),\n 'G_layer_out_tanh' : torch.nn.Tanh()\n }))\n\n def forward(self, x):\n x = self.module(x)\n return x\n\nclass Discriminator(torch.nn.Module):\n def __init__(self):\n super(Discriminator, self).__init__()\n self.module = torch.nn.Sequential(OrderedDict({\n 'D_layer_1' : torch.nn.Conv2d(cfg.OUTPUT_CHANNEL, cfg.D_DIM, kernel_size=4, padding=1, stride=2, bias=False),\n 'D_layer_1_leakyReLU' : torch.nn.LeakyReLU(0.2, inplace=True),\n 'D_layer_2' : torch.nn.Conv2d(cfg.D_DIM, cfg.D_DIM * 2, kernel_size=4, padding=1, stride=2, bias=False),\n 'D_layer_2_bn' : torch.nn.BatchNorm2d(cfg.D_DIM * 2),\n 'D_layer_2_leakyReLU' : torch.nn.LeakyReLU(0.2, inplace=True),\n 'D_layer_3' : torch.nn.Conv2d(cfg.D_DIM * 2, cfg.D_DIM * 4, kernel_size=4, padding=1, stride=2, bias=False),\n 'G_layer_3_bn' : torch.nn.BatchNorm2d(cfg.D_DIM * 4),\n 'D_layer_3_leakyReLU' : torch.nn.LeakyReLU(0.2, inplace=True),\n 'D_layer_out' : torch.nn.Conv2d(cfg.D_DIM * 4, 1, kernel_size=[cfg.OUTPUT_HEIGHT // 8, cfg.OUTPUT_WIDTH // 8], padding=0, stride=1, bias=False),\n }))\n\n def forward(self, x):\n x = self.module(x)\n return x", "_____no_output_____" ] ], [ [ "## Train", "_____no_output_____" ] ], [ [ "def result_show(G, z, path=None, save=False, show=False):\n if (save or show) is False:\n print('argument save >> {} and show >> {}, so skip')\n return\n\n Gz = G(z)\n Gz = Gz.detach().cpu().numpy()\n\n Gz = (Gz * 127.5 + 127.5).astype(np.uint8)\n Gz = Gz.reshape([-1, cfg.OUTPUT_CHANNEL, cfg.OUTPUT_HEIGHT, cfg.OUTPUT_WIDTH])\n Gz = Gz.transpose(0, 2, 3, 1)\n\n for i in range(cfg.TEST.MINIBATCH):\n _G = Gz[i]\n plt.subplot(1, cfg.TEST.MINIBATCH, i + 1)\n plt.imshow(_G)\n plt.axis('off')\n\n if path is not None:\n plt.savefig(path)\n print('result was saved to >> {}'.format(path))\n\n if show:\n plt.show()\n\n# train\ndef train():\n # model\n G = Generator().to(cfg.DEVICE)\n D = Discriminator().to(cfg.DEVICE)\n\n opt_G = cfg.TRAIN.OPTIMIZER_G(G.parameters(), **cfg.TRAIN.LEARNING_PARAMS_G)\n opt_D = cfg.TRAIN.OPTIMIZER_D(D.parameters(), **cfg.TRAIN.LEARNING_PARAMS_D)\n\n #path_dict = data_load(cfg)\n #paths = path_dict['paths']\n #paths_gt = path_dict['paths_gt']\n\n trainset = torchvision.datasets.CIFAR10(root=cfg.TRAIN.DATA_PATH , train=True, download=True, transform=None)\n train_Xs = trainset.data\n train_ys = trainset.targets\n\n # training\n mbi = 0\n train_N = len(train_Xs)\n train_ind = np.arange(train_N)\n np.random.seed(0)\n np.random.shuffle(train_ind)\n\n list_iter = []\n list_loss_G = []\n list_loss_D = []\n list_loss_D_real = []\n list_loss_D_fake = []\n list_loss_WDistance = []\n\n one = torch.FloatTensor([1])\n minus_one = one * -1\n\n print('training start')\n progres_bar = ''\n \n for i in range(cfg.TRAIN.ITERATION):\n if mbi + cfg.TRAIN.MINIBATCH > train_N:\n mb_ind = train_ind[mbi:]\n np.random.shuffle(train_ind)\n mb_ind = np.hstack((mb_ind, train_ind[ : (cfg.TRAIN.MINIBATCH - (train_N - mbi))]))\n mbi = cfg.TRAIN.MINIBATCH - (train_N - mbi)\n else:\n mb_ind = train_ind[mbi : mbi + cfg.TRAIN.MINIBATCH]\n mbi += cfg.TRAIN.MINIBATCH\n\n # update D\n for _ in range(cfg.TRAIN.WGAN_CRITIC_N):\n opt_D.zero_grad()\n\n # parameter clipping > [-clip_value, clip_value]\n for param in D.parameters():\n param.data.clamp_(- cfg.TRAIN.WGAN_CLIPS_VALUE, cfg.TRAIN.WGAN_CLIPS_VALUE)\n\n # sample X\n Xs = torch.tensor(preprocess(train_Xs[mb_ind], cfg, cfg.OUTPUT_MODE), dtype=torch.float).to(cfg.DEVICE)\n\n # sample x\n z = np.random.uniform(-1, 1, size=(cfg.TRAIN.MINIBATCH, cfg.INPUT_Z_DIM, 1, 1))\n z = torch.tensor(z, dtype=torch.float).to(cfg.DEVICE)\n\n # forward\n Gz = G(z)\n loss_D_fake = D(Gz).mean(0).view(1)\n loss_D_real = D(Xs).mean(0).view(1)\n loss_D = loss_D_fake - loss_D_real\n loss_D_real.backward(one)\n loss_D_fake.backward(minus_one)\n opt_D.step()\n Wasserstein_distance = loss_D_real - loss_D_fake\n\n # update G\n opt_G.zero_grad()\n z = np.random.uniform(-1, 1, size=(cfg.TRAIN.MINIBATCH, cfg.INPUT_Z_DIM, 1, 1))\n z = torch.tensor(z, dtype=torch.float).to(cfg.DEVICE)\n loss_G = D(G(z)).mean(0).view(1)\n loss_G.backward(one)\n opt_G.step()\n\n progres_bar += '|'\n print('\\r' + progres_bar, end='')\n\n _loss_G = loss_G.item()\n _loss_D = loss_D.item()\n _loss_D_real = loss_D_real.item()\n _loss_D_fake = loss_D_fake.item()\n _Wasserstein_distance = Wasserstein_distance.item()\n\n if (i + 1) % 10 == 0:\n progres_bar += str(i + 1)\n print('\\r' + progres_bar, end='')\n\n # save process result\n if cfg.TRAIN.LEARNING_PROCESS_RESULT_SAVE:\n list_iter.append(i + 1)\n list_loss_G.append(_loss_G)\n list_loss_D.append(_loss_D)\n list_loss_D_real.append(_loss_D_real)\n list_loss_D_fake.append(_loss_D_fake)\n list_loss_WDistance.append(_Wasserstein_distance)\n \n # display training state\n if (i + 1) % cfg.TRAIN.DISPAY_ITERATION_INTERVAL == 0:\n print('\\r' + ' ' * len(progres_bar), end='')\n print('\\rIter:{}, LossG (fake:{:.4f}), LossD:{:.4f} (real:{:.4f}, fake:{:.4f}), WDistance:{:.4f}'.format(\n i + 1, _loss_G, _loss_D, _loss_D_real, _loss_D_fake, _Wasserstein_distance))\n progres_bar = ''\n\n # save parameters\n if (cfg.TRAIN.MODEL_SAVE_INTERVAL != False) and ((i + 1) % cfg.TRAIN.MODEL_SAVE_INTERVAL == 0):\n G_save_path = cfg.TRAIN.MODEL_G_SAVE_PATH.format('iter{}'.format(i + 1))\n D_save_path = cfg.TRAIN.MODEL_D_SAVE_PATH.format('iter{}'.format(i + 1))\n torch.save(G.state_dict(), G_save_path)\n torch.save(D.state_dict(), D_save_path)\n print('save G >> {}, D >> {}'.format(G_save_path, D_save_path))\n\n # save process result\n if cfg.TRAIN.LEARNING_PROCESS_RESULT_SAVE and ((i + 1) % cfg.TRAIN.LEARNING_PROCESS_RESULT_INTERVAL == 0):\n result_show(\n G, z, cfg.TRAIN.LEARNING_PROCESS_RESULT_IMAGE_PATH.format('iter' + str(i + 1)), \n save=cfg.TRAIN.LEARNING_PROCESS_RESULT_SAVE, show=True)\n\n G_save_path = cfg.TRAIN.MODEL_G_SAVE_PATH.format('final')\n D_save_path = cfg.TRAIN.MODEL_D_SAVE_PATH.format('final')\n torch.save(G.state_dict(), G_save_path)\n torch.save(D.state_dict(), D_save_path)\n print('final paramters were saved to G >> {}, D >> {}'.format(G_save_path, D_save_path))\n\n if cfg.TRAIN.LEARNING_PROCESS_RESULT_SAVE:\n f = open(cfg.TRAIN.LEARNING_PROCESS_RESULT_LOSS_PATH, 'w')\n df = pd.DataFrame({'iteration' : list_iter, 'loss_G' : list_loss_G, 'loss_D' : list_loss_D, \n 'loss_D_real' : list_loss_D_real, 'loss_D_fake' : list_loss_D_fake, 'Wasserstein_Distance' : list_loss_WDistance})\n df.to_csv(cfg.TRAIN.LEARNING_PROCESS_RESULT_LOSS_PATH, index=False)\n print('loss was saved to >> {}'.format(cfg.TRAIN.LEARNING_PROCESS_RESULT_LOSS_PATH))\n\ntrain()", "Files already downloaded and verified\ntraining start\nIter:50, LossG (fake:0.3505), LossD:0.7016 (real:-0.3623, fake:0.3393), WDistance:-0.7016274333000183\nIter:100, LossG (fake:0.3378), LossD:0.6561 (real:-0.3374, fake:0.3187), WDistance:-0.6561057567596436\nIter:150, LossG (fake:0.3169), LossD:0.6249 (real:-0.3152, fake:0.3097), WDistance:-0.6249051094055176\nIter:200, LossG (fake:0.2962), LossD:0.5739 (real:-0.2957, fake:0.2782), WDistance:-0.5739462971687317\nsave G >> models/WGAN-GP_G_iter200.pt, D >> models/WGAN-GP_D_iter200.pt\nIter:250, LossG (fake:0.3003), LossD:0.5469 (real:-0.2822, fake:0.2648), WDistance:-0.5469043850898743\nIter:300, LossG (fake:0.2847), LossD:0.5567 (real:-0.2826, fake:0.2741), WDistance:-0.5567499399185181\nIter:350, LossG (fake:0.2797), LossD:0.5413 (real:-0.2862, fake:0.2551), WDistance:-0.5412789583206177\nIter:400, LossG (fake:0.2631), LossD:0.5034 (real:-0.2678, fake:0.2356), WDistance:-0.5034050345420837\nsave G >> models/WGAN-GP_G_iter400.pt, D >> models/WGAN-GP_D_iter400.pt\nIter:450, LossG (fake:0.2737), LossD:0.5318 (real:-0.2758, fake:0.2559), WDistance:-0.5317676067352295\nIter:500, LossG (fake:0.2681), LossD:0.5052 (real:-0.2648, fake:0.2404), WDistance:-0.5052473545074463\nresult was saved to >> result/WGAN-GP_result_iter500.jpg\n" ] ], [ [ "## Test", "_____no_output_____" ] ], [ [ "# test\ndef test():\n print('-' * 20)\n print('test function')\n print('-' * 20)\n G = Generator().to(cfg.DEVICE)\n G.load_state_dict(torch.load(cfg.TEST.MODEL_G_PATH, map_location=torch.device(cfg.DEVICE)))\n G.eval()\n\n np.random.seed(0)\n \n for i in range(cfg.TEST.ITERATION):\n z = np.random.uniform(-1, 1, size=(cfg.TEST.MINIBATCH, cfg.INPUT_Z_DIM, 1, 1))\n z = torch.tensor(z, dtype=torch.float).to(cfg.DEVICE)\n\n result_show(G, z, cfg.TEST.RESULT_IMAGE_PATH.format(i + 1), save=cfg.TEST.RESULT_SAVE, show=True)\n\ntest()", "--------------------\ntest function\n--------------------\nresult was saved to >> result/WGAN-GP_result_1.jpg\n" ], [ "def arg_parse():\n parser = argparse.ArgumentParser(description='CNN implemented with Keras')\n parser.add_argument('--train', dest='train', action='store_true')\n parser.add_argument('--test', dest='test', action='store_true')\n args = parser.parse_args()\n return args\n\n# main\nif __name__ == '__main__':\n args = arg_parse()\n\n if args.train:\n train()\n if args.test:\n test()\n\n if not (args.train or args.test):\n print(\"please select train or test flag\")\n print(\"train: python main.py --train\")\n print(\"test: python main.py --test\")\n print(\"both: python main.py --train --test\")\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe237589edda901d4676b975844dc695780a208
2,559
ipynb
Jupyter Notebook
src/examples/DEG_Annotation_remote.ipynb
andrewrocks/sos-docs
fb742052f761e6c3532d8e849a8d07167bc2b4ef
[ "MIT" ]
2
2018-03-08T18:41:23.000Z
2021-01-23T02:08:34.000Z
src/examples/DEG_Annotation_remote.ipynb
andrewrocks/sos-docs
fb742052f761e6c3532d8e849a8d07167bc2b4ef
[ "MIT" ]
60
2017-10-06T01:07:42.000Z
2021-02-12T15:39:24.000Z
src/examples/DEG_Annotation_remote.ipynb
andrewrocks/sos-docs
fb742052f761e6c3532d8e849a8d07167bc2b4ef
[ "MIT" ]
13
2017-10-08T18:24:24.000Z
2021-02-12T14:48:38.000Z
18.955556
95
0.479875
[ [ [ "import pandas as pd\ndata = pd.read_excel('DEG_list.xlsx')\ndata.to_csv('DEG_list.csv')", "_____no_output_____" ], [ "%run -q shark\ninput: 'DEG_list.csv'\noutput: 'annotated_DEG_list.csv'\ntask:\nR: expand=True\n data <- read.csv('{input}')\n library(biomaRt)\n ensembl <- useEnsembl(biomart='ensembl')\n ensembl <- useEnsembl(biomart=\"ensembl\", dataset=\"mmusculus_gene_ensembl\")\n \n hgnc <- getBM(attributes=c('ensembl_gene_id', 'external_gene_name'),\n filters = 'ensembl_gene_id', values = data['ensembl_gene_id'], mart = ensembl)\n\n annotated <- merge(data, hgnc, by='ensembl_gene_id', all.x=TRUE)\n write.csv(annotated, '{output}', row.names=FALSE)", "_____no_output_____" ], [ "annotated = pd.read_csv('annotated_DEG_list.csv')\nannotated = annotated.set_index('external_gene_name')\nannotated.sort_values(by='padj', inplace=True)\nannotated.to_excel('annotated_DEG_list.xlsx')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbe24810d85b80aeeaf4e9404192ba268d4d4ad2
19,269
ipynb
Jupyter Notebook
nbs/08_script.ipynb
abhinavm24/fastcore
b8598c3be540168e4ba58195b0f6eaedf7fa27e1
[ "Apache-2.0" ]
1
2021-01-24T23:17:37.000Z
2021-01-24T23:17:37.000Z
nbs/08_script.ipynb
abhinavm24/fastcore
b8598c3be540168e4ba58195b0f6eaedf7fa27e1
[ "Apache-2.0" ]
1
2022-02-26T12:19:20.000Z
2022-02-26T12:19:20.000Z
nbs/08_script.ipynb
abhinavm24/fastcore
b8598c3be540168e4ba58195b0f6eaedf7fa27e1
[ "Apache-2.0" ]
null
null
null
34.718919
748
0.578857
[ [ [ "#hide\n# default_exp script", "_____no_output_____" ] ], [ [ "# Script - command line interfaces\n\n> A fast way to turn your python function into a script.", "_____no_output_____" ], [ "Part of [fast.ai](https://www.fast.ai)'s toolkit for delightful developer experiences.", "_____no_output_____" ], [ "## Overview", "_____no_output_____" ], [ "Sometimes, you want to create a quick script, either for yourself, or for others. But in Python, that involves a whole lot of boilerplate and ceremony, especially if you want to support command line arguments, provide help, and other niceties. You can use [argparse](https://docs.python.org/3/library/argparse.html) for this purpose, which comes with Python, but it's complex and verbose.\n\n`fastcore.script` makes life easier. There are much fancier modules to help you write scripts (we recommend [Python Fire](https://github.com/google/python-fire), and [Click](https://click.palletsprojects.com/en/7.x/) is also popular), but fastcore.script is very fast and very simple. In fact, it's <50 lines of code! Basically, it's just a little wrapper around `argparse` that uses modern Python features and some thoughtful defaults to get rid of the boilerplate.\n\nFor full details, see the [docs](https://fastcore.script.fast.ai) for `core`.", "_____no_output_____" ], [ "## Example", "_____no_output_____" ], [ "Here's a complete example (available in `examples/test_fastcore.py`):\n\n```python\nfrom fastcore.script import *\n@call_parse\ndef main(msg:Param(\"The message\", str),\n upper:Param(\"Convert to uppercase?\", store_true)):\n \"Print `msg`, optionally converting to uppercase\"\n print(msg.upper() if upper else msg)\n````", "_____no_output_____" ], [ "If you copy that info a file and run it, you'll see:\n\n```\n$ examples/test_fastcore.py --help\nusage: test_fastcore.py [-h] [--upper] [--pdb PDB] [--xtra XTRA] msg\n\nPrint `msg`, optionally converting to uppercase\n\npositional arguments:\n msg The message\n\noptional arguments:\n -h, --help show this help message and exit\n --upper Convert to uppercase? (default: False)\n --pdb PDB Run in pdb debugger (default: False)\n --xtra XTRA Parse for additional args (default: '')\n```\n\nAs you see, we didn't need any `if __name__ == \"__main__\"`, we didn't have to parse arguments, we just wrote a function, added a decorator to it, and added some annotations to our function's parameters. As a bonus, we can also use this function directly from a REPL such as Jupyter Notebook - it's not just for command line scripts!", "_____no_output_____" ], [ "## Param annotations", "_____no_output_____" ], [ "Each parameter in your function should have an annotation `Param(...)` (as in the example above). You can pass the following when calling `Param`: `help`,`type`,`opt`,`action`,`nargs`,`const`,`choices`,`required` . Except for `opt`, all of these are just passed directly to `argparse`, so you have all the power of that module at your disposal. Generally you'll want to pass at least `help` (since this is provided as the help string for that parameter) and `type` (to ensure that you get the type of data you expect). `opt` is a bool that defines whether a param is optional or required (positional) - but you'll generally not need to set this manually, because fastcore.script will set it for you automatically based on *default* values.\n\nYou should provide a default (after the `=`) for any *optional* parameters. If you don't provide a default for a parameter, then it will be a *positional* parameter.", "_____no_output_____" ], [ "## setuptools scripts", "_____no_output_____" ], [ "There's a really nice feature of pip/setuptools that lets you create commandline scripts directly from functions, makes them available in the `PATH`, and even makes your scripts cross-platform (e.g. in Windows it creates an exe). fastcore.script supports this feature too. The trick to making a function available as a script is to add a `console_scripts` section to your setup file, of the form: `script_name=module:function_name`. E.g. in this case we use: `test_fastcore.script=fastcore.script.test_cli:main`. With this, you can then just type `test_fastcore.script` at any time, from any directory, and your script will be called (once it's installed using one of the methods below).\n\nYou don't actually have to write a `setup.py` yourself. Instead, just use [nbdev](https://nbdev.fast.ai). Then modify `settings.ini` as appropriate for your module/script. To install your script directly, you can type `pip install -e .`. Your script, when installed this way (it's called an [editable install](http://codumentary.blogspot.com/2014/11/python-tip-of-year-pip-install-editable.html), will automatically be up to date even if you edit it - there's no need to reinstall it after editing. With nbdev you can even make your module and script available for installation directly from pip and conda by running `make release`.", "_____no_output_____" ], [ "## API details", "_____no_output_____" ] ], [ [ "from fastcore.test import *", "_____no_output_____" ], [ "#export\nimport inspect,functools,argparse,shutil\nfrom fastcore.imports import *\nfrom fastcore.utils import *", "_____no_output_____" ], [ "#export\ndef store_true():\n \"Placeholder to pass to `Param` for `store_true` action\"\n pass", "_____no_output_____" ], [ "#export\ndef store_false():\n \"Placeholder to pass to `Param` for `store_false` action\"\n pass", "_____no_output_____" ], [ "#export\ndef bool_arg(v):\n \"Use as `type` for `Param` to get `bool` behavior\"\n return str2bool(v)", "_____no_output_____" ], [ "#export\ndef clean_type_str(x:str):\n x = str(x)\n x = re.sub(\"(enum |class|function|__main__\\.|\\ at.*)\", '', x)\n x = re.sub(\"(<|>|'|\\ )\", '', x) # spl characters\n return x", "_____no_output_____" ], [ "class Test: pass\n\ntest_eq(clean_type_str(argparse.ArgumentParser), 'argparse.ArgumentParser')\ntest_eq(clean_type_str(Test), 'Test')\ntest_eq(clean_type_str(int), 'int')\ntest_eq(clean_type_str(float), 'float')\ntest_eq(clean_type_str(store_false), 'store_false')", "_____no_output_____" ], [ "#export\nclass Param:\n \"A parameter in a function used in `anno_parser` or `call_parse`\"\n def __init__(self, help=None, type=None, opt=True, action=None, nargs=None, const=None,\n choices=None, required=None, default=None):\n if type==store_true: type,action,default=None,'store_true' ,False\n if type==store_false: type,action,default=None,'store_false',True\n if type and isinstance(type,typing.Type) and issubclass(type,enum.Enum) and not choices: choices=list(type)\n store_attr()\n \n def set_default(self, d):\n if self.default is None:\n if d==inspect.Parameter.empty: self.opt = False\n else: self.default = d\n if self.default is not None: self.help += f\" (default: {self.default})\"\n\n @property\n def pre(self): return '--' if self.opt else ''\n @property\n def kwargs(self): return {k:v for k,v in self.__dict__.items()\n if v is not None and k!='opt' and k[0]!='_'}\n def __repr__(self):\n if not self.help and self.type is None: return \"\"\n if not self.help and self.type is not None: return f\"{clean_type_str(self.type)}\"\n if self.help and self.type is None: return f\"<{self.help}>\"\n if self.help and self.type is not None: return f\"{clean_type_str(self.type)} <{self.help}>\"", "_____no_output_____" ], [ "test_eq(repr(Param(\"Help goes here\")), '<Help goes here>')\ntest_eq(repr(Param(\"Help\", int)), 'int <Help>')\ntest_eq(repr(Param(help=None, type=int)), 'int')\ntest_eq(repr(Param(help=None, type=None)), '')", "_____no_output_____" ] ], [ [ "Each parameter in your function should have an annotation `Param(...)`. You can pass the following when calling `Param`: `help`,`type`,`opt`,`action`,`nargs`,`const`,`choices`,`required` (i.e. it takes the same parameters as `argparse.ArgumentParser.add_argument`, plus `opt`). Except for `opt`, all of these are just passed directly to `argparse`, so you have all the power of that module at your disposal. Generally you'll want to pass at least `help` (since this is provided as the help string for that parameter) and `type` (to ensure that you get the type of data you expect).\n\n`opt` is a bool that defines whether a param is optional or required (positional) - but you'll generally not need to set this manually, because fastcore.script will set it for you automatically based on *default* values. You should provide a default (after the `=`) for any *optional* parameters. If you don't provide a default for a parameter, then it will be a *positional* parameter.\n\nParam's `__repr__` also allows for more informative function annotation when looking up the function's doc using shift+tab. You see the type annotation (if there is one) and the accompanying help documentation with it.", "_____no_output_____" ] ], [ [ "def f(required:Param(\"Required param\", int),\n a:Param(\"param 1\", bool_arg),\n b:Param(\"param 2\", str)=\"test\"):\n \"my docs\"\n ...", "_____no_output_____" ], [ "help(f)", "Help on function f in module __main__:\n\nf(required: int <Required param>, a: bool_arg <param 1>, b: str <param 2> = 'test')\n my docs\n\n" ], [ "p = Param(help=\"help\", type=int)\np.set_default(1)\ntest_eq(p.kwargs, {'help': 'help (default: 1)', 'type': int, 'default': 1})", "_____no_output_____" ], [ "#export\ndef anno_parser(func, prog=None, from_name=False):\n \"Look at params (annotated with `Param`) in func and return an `ArgumentParser`\"\n cols = shutil.get_terminal_size((120,30))[0]\n fmtr = partial(argparse.HelpFormatter, max_help_position=cols//2, width=cols)\n p = argparse.ArgumentParser(description=func.__doc__, prog=prog, formatter_class=fmtr)\n for k,v in inspect.signature(func).parameters.items():\n param = func.__annotations__.get(k, Param())\n param.set_default(v.default)\n p.add_argument(f\"{param.pre}{k}\", **param.kwargs)\n p.add_argument(f\"--pdb\", help=argparse.SUPPRESS, action='store_true')\n p.add_argument(f\"--xtra\", help=argparse.SUPPRESS, type=str)\n return p", "_____no_output_____" ] ], [ [ "This converts a function with parameter annotations of type `Param` into an `argparse.ArgumentParser` object. Function arguments with a default provided are optional, and other arguments are positional.", "_____no_output_____" ] ], [ [ "_en = str_enum('_en', 'aa','bb','cc')\ndef f(required:Param(\"Required param\", int),\n a:Param(\"param 1\", bool_arg),\n b:Param(\"param 2\", str)=\"test\",\n c:Param(\"param 3\", _en)=_en.aa):\n \"my docs\"\n ...\n\np = anno_parser(f, 'progname')\np.print_help()", "usage: progname [-h] [--b B] [--c {aa,bb,cc}] required a\n\nmy docs\n\npositional arguments:\n required Required param\n a param 1\n\noptional arguments:\n -h, --help show this help message and exit\n --b B param 2 (default: test)\n --c {aa,bb,cc} param 3 (default: aa)\n" ], [ "#export\ndef args_from_prog(func, prog):\n \"Extract args from `prog`\"\n if prog is None or '#' not in prog: return {}\n if '##' in prog: _,prog = prog.split('##', 1)\n progsp = prog.split(\"#\")\n args = {progsp[i]:progsp[i+1] for i in range(0, len(progsp), 2)}\n for k,v in args.items():\n t = func.__annotations__.get(k, Param()).type\n if t: args[k] = t(v)\n return args", "_____no_output_____" ] ], [ [ "Sometimes it's convenient to extract arguments from the actual name of the called program. `args_from_prog` will do this, assuming that names and values of the params are separated by a `#`. Optionally there can also be a prefix separated by `##` (double underscore).", "_____no_output_____" ] ], [ [ "exp = {'a': False, 'b': 'baa'}\ntest_eq(args_from_prog(f, 'foo##a#0#b#baa'), exp)\ntest_eq(args_from_prog(f, 'a#0#b#baa'), exp)", "_____no_output_____" ], [ "#export\nSCRIPT_INFO = SimpleNamespace(func=None)", "_____no_output_____" ], [ "#export\ndef call_parse(func):\n \"Decorator to create a simple CLI from `func` using `anno_parser`\"\n mod = inspect.getmodule(inspect.currentframe().f_back)\n if not mod: return func\n \n @functools.wraps(func)\n def _f(*args, **kwargs):\n mod = inspect.getmodule(inspect.currentframe().f_back)\n if not mod: return func(*args, **kwargs)\n if not SCRIPT_INFO.func and mod.__name__==\"__main__\": SCRIPT_INFO.func = func.__name__\n if len(sys.argv)>1 and sys.argv[1]=='': sys.argv.pop(1)\n p = anno_parser(func)\n args = p.parse_args().__dict__\n xtra = otherwise(args.pop('xtra', ''), eq(1), p.prog)\n tfunc = trace(func) if args.pop('pdb', False) else func\n tfunc(**merge(args, args_from_prog(func, xtra)))\n\n if mod.__name__==\"__main__\":\n setattr(mod, func.__name__, _f)\n SCRIPT_INFO.func = func.__name__\n return _f()\n else: return _f", "_____no_output_____" ], [ "@call_parse\ndef test_add(a:Param(\"param a\", int), b:Param(\"param 1\",int)): return a + b", "_____no_output_____" ] ], [ [ "`call_parse` decorated functions work as regular functions and also as command-line interface functions.", "_____no_output_____" ] ], [ [ "test_eq(test_add(1,2), 3)", "_____no_output_____" ] ], [ [ "This is the main way to use `fastcore.script`; decorate your function with `call_parse`, add `Param` annotations as shown above, and it can then be used as a script.", "_____no_output_____" ], [ "## Export -", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_test.ipynb.\nConverted 01_basics.ipynb.\nConverted 02_foundation.ipynb.\nConverted 03_xtras.ipynb.\nConverted 03a_parallel.ipynb.\nConverted 03b_net.ipynb.\nConverted 04_dispatch.ipynb.\nConverted 05_transform.ipynb.\nConverted 07_meta.ipynb.\nConverted 08_script.ipynb.\nConverted index.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cbe25410ec723041c703b2259f96bcbf1c857ba2
1,704
ipynb
Jupyter Notebook
testing_strategy_macd_60_5/results.ipynb
ajmal017/stock_price_prediction
36758056ba4a80792dfdc73d365bc4a78020a06d
[ "BSD-3-Clause" ]
null
null
null
testing_strategy_macd_60_5/results.ipynb
ajmal017/stock_price_prediction
36758056ba4a80792dfdc73d365bc4a78020a06d
[ "BSD-3-Clause" ]
null
null
null
testing_strategy_macd_60_5/results.ipynb
ajmal017/stock_price_prediction
36758056ba4a80792dfdc73d365bc4a78020a06d
[ "BSD-3-Clause" ]
1
2020-11-22T10:14:53.000Z
2020-11-22T10:14:53.000Z
20.780488
88
0.550469
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "stra1 = pd.read_csv('lstra_1_stocks.csv')\nstra1.sort_values('BattingAvg', ascending=False).head(10).to_csv('stra1_best.csv')", "_____no_output_____" ], [ "stra2 = pd.read_csv('lstra_2_stocks.csv')\nstra2.sort_values('ratio', ascending=False).head(10).to_csv('stra2_best.csv')", "_____no_output_____" ], [ "stra3 = pd.read_csv('lstra_3_stocks.csv')\nstra3.sort_values('ratio', ascending=False).head(10).to_csv('stra3_best.csv')", "_____no_output_____" ], [ "stra4 = pd.read_csv('lstra_4_stocks.csv')\nstra4.sort_values('ratio', ascending=False).head(10).to_csv('stra4_best.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
cbe25b48a8587d5f1a26c1d5c2545570b9801c39
3,150
ipynb
Jupyter Notebook
Examples/Bugs/asarray_issue.ipynb
sdrees/pyvtreat
fed9a653b2524ba04b1e92b1087e58bead25f99a
[ "BSD-3-Clause" ]
104
2019-07-21T06:15:02.000Z
2022-02-23T19:41:58.000Z
Examples/Bugs/asarray_issue.ipynb
arita37/pyvtreat
c32e7ce6db11a2ccdd63e545b25028cbec03a3ff
[ "BSD-3-Clause" ]
15
2019-08-12T09:59:40.000Z
2021-12-09T00:38:47.000Z
Examples/Bugs/asarray_issue.ipynb
arita37/pyvtreat
c32e7ce6db11a2ccdd63e545b25028cbec03a3ff
[ "BSD-3-Clause" ]
9
2019-08-15T13:29:15.000Z
2021-03-08T18:04:08.000Z
16.84492
87
0.458413
[ [ [ "Issue from: https://github.com/WinVector/pyvtreat/issues/7#issuecomment-546502465", "_____no_output_____" ] ], [ [ "import numpy\nimport pandas", "_____no_output_____" ], [ "print(numpy.__version__)", "1.16.4\n" ], [ "print(pandas.__version__)", "0.25.0\n" ], [ "numpy.random.seed(2019)\narr = numpy.random.randint(2, size=10)\nprint(arr)", "[0 0 1 1 0 0 0 0 1 1]\n" ], [ "\nsparr = pandas.SparseArray(arr, fill_value=0)\nprint(sparr)", "[0, 0, 1, 1, 0, 0, 0, 0, 1, 1]\nFill: 0\nIntIndex\nIndices: array([2, 3, 8, 9], dtype=int32)\n\n" ], [ "np_arr = numpy.asarray(sparr)\nprint(np_arr)\n\n", "[0 0 1 1 0 0 0 0 1 1]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cbe265971a9697e4a97f582503e4b9658b99ca0d
167,399
ipynb
Jupyter Notebook
archive/Untitled8.ipynb
KailongPeng/rtSynth
e0d45dc68cba259a1308842a584435e04b77858a
[ "Apache-2.0" ]
null
null
null
archive/Untitled8.ipynb
KailongPeng/rtSynth
e0d45dc68cba259a1308842a584435e04b77858a
[ "Apache-2.0" ]
null
null
null
archive/Untitled8.ipynb
KailongPeng/rtSynth
e0d45dc68cba259a1308842a584435e04b77858a
[ "Apache-2.0" ]
null
null
null
52.426871
317
0.619639
[ [ [ "'''\n这个code的目的是用neurosketch 的数据来检测现在在realtime data里面发现的issue:也就是ceiling有时候竟然比floor更小\n这个code的运行逻辑是\n用neurosketch前五个run训练2 way classifiers,然后用最后一个run来计算ceiling和floor的值,看是否合理\n'''\n\n\n'''\npurpose:\n find the best performed mask from the result of aggregate_greedy.py and save as chosenMask\n train all possible pairs of 2way classifiers and save for evidence calculation\n load saved classifiers and calculate different forms of evidence\nsteps:\n load the result of aggregate_greedy.py\n display the result of aggregate_greedy.py\n find the best performed ROI for each subject and display the accuracy of each subject, save the best performed ROI as chosenMask\n load the functional and behavior data and choseMask and train all possible pairs of 2way classifiers\n calculate the evidence floor and ceil for each subject and display different forms of evidences.\n \n\n'''\n\n\n\n\n'''\nload the result of aggregate_greedy.py\n'''\n# To visualize the greedy result starting for 31 ROIs, in total 25 subjects.\nimport os\nos.chdir(\"/gpfs/milgram/project/turk-browne/projects/rtTest/kp_scratch/\")\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport pickle5 as pickle\nimport subprocess\nimport numpy as np\nimport os\nprint(f\"conda env={os.environ['CONDA_DEFAULT_ENV']}\") \nimport numpy as np\nimport nibabel as nib\nimport sys\nimport time\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nimport itertools\nimport pickle\nimport subprocess\nfrom subprocess import call\nworkingDir=\"/gpfs/milgram/project/turk-browne/projects/rtTest/\"\n\ndef save_obj(obj, name):\n with open(name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\ndef load_obj(name):\n with open(name + '.pkl', 'rb') as f:\n return pickle.load(f)\nroiloc=\"schaefer2018\"\ndataSource=\"neurosketch\"\nsubjects_correctly_aligned=['1206161','0119173','1206162','1130161','1206163','0120171','0111171','1202161','0125172','0110172','0123173','0120173','0110171','0119172','0124171','0123171','1203161','0118172','0118171','0112171','1207162','0117171','0119174','0112173','0112172']\nsubjects=subjects_correctly_aligned\nN=25\nworkingPath=\"/gpfs/milgram/project/turk-browne/projects/rtTest/\"\nGreedyBestAcc=np.zeros((len(subjects),N+1))\nGreedyBestAcc[GreedyBestAcc==0]=None\nGreedyBestAcc={}\nnumberOfROIs={}\nfor ii,subject in enumerate(subjects):\n # try:\n # GreedyBestAcc[ii,N]=np.load(workingPath+\"./{}/{}/output/uniMaskRanktag2_top{}.npy\".format(roiloc, subject, N))\n # except:\n # pass\n t=np.load(workingPath+\"./{}/{}/output/uniMaskRanktag2_top{}.npy\".format(roiloc, subject, N))\n GreedyBestAcc[subject]=[np.float(t)]\n numberOfROIs[subject]=[N]\n # for len_topN_1 in range(N-1,0,-1):\n for len_topN in range(1,N):\n # Wait(f\"./tmp/{subject}_{N}_{roiloc}_{dataSource}_{len_topN_1}.pkl\")\n try:\n # {当前的被试}_{greedy开始的ROI数目,也就是25}_{mask的种类schaefer2018}_{数据来源neurosketch}_{当前的 megaROI 包含有的数目}\n di = load_obj(f\"./tmp__folder/{subject}_{N}_{roiloc}_{dataSource}_{len_topN}\")\n GreedyBestAcc[subject].append(np.float(di['bestAcc']))\n numberOfROIs[subject].append(len_topN)\n # GreedyBestAcc[ii,len_topN] = di['bestAcc']\n \n except:\n pass\n\n\n# '''\n# to load the imtermediate results from greedy code to examine the system\n# '''\n# def wait(tmpFile):\n# while not os.path.exists(tmpFile+'_result.npy'):\n# time.sleep(5)\n# print(f\"waiting for {tmpFile}_result.npy\\n\")\n# return np.load(tmpFile+'_result.npy')\n\n# subject= '0119173' #sys.argv[1]\n# sub_id = [i for i,x in enumerate(subjects) if x == subject][0]\n# intermediate_result=np.zeros((N+1,N+1))\n# # 应该有多少?25个24ROI,2个1ROI,24个\n# for i in range(N,1,-1):\n# for j in range(i):\n# tmpFile=f\"./tmp__folder/{subject}_{N}_{roiloc}_{dataSource}_{i}_{j}\"\n# sl_result=wait(tmpFile)\n# intermediate_result[i,j]=sl_result\n\n# # _=plt.imshow(intermediate_result)\n# #最后一行是25个24ROI,第2行是2个1ROI\n\n'''\ndisplay the result of aggregate_greedy.py\n'''\n# GreedyBestAcc=GreedyBestAcc.T\n# plt.imshow(GreedyBestAcc)\n# _=plt.figure()\n# for i in range(GreedyBestAcc.shape[0]):\n# plt.scatter([i]*GreedyBestAcc.shape[1],GreedyBestAcc[i,:],c='g',s=2)\n# plt.plot(np.arange(GreedyBestAcc.shape[0]),np.nanmean(GreedyBestAcc,axis=1))\n# # plt.ylim([0.19,0.36])\n# # plt.xlabel(\"number of ROIs\")\n# # plt.ylabel(\"accuracy\")\n# _=plt.figure()\n# for j in range(GreedyBestAcc.shape[1]):\n# plt.plot(GreedyBestAcc[:,j])\n\n\n# GreedyBestAcc=GreedyBestAcc.T\n# _=plt.figure()\n# plt.imshow(GreedyBestAcc)\n\n'''\nfind the best performed ROI for each subject and display the accuracy of each subject, save the best performed ROI as chosenMask\n'''\n#find best ID for each subject\nbestID={}\nfor ii,subject in enumerate(subjects):\n t=GreedyBestAcc[subject]\n bestID[subject] = numberOfROIs[subject][np.where(t==np.nanmax(t))[0][0]] #bestID 指的是每一个subject对应的最好的megaROI包含的ROI的数目\nchosenMask={}\nfor subject in bestID:\n # best ID \n # {当前的被试}_{greedy开始的ROI数目,也就是25}_{mask的种类schaefer2018}_{数据来源neurosketch}_{最好的megaROI 包含有的数目}\n di = load_obj(f\"./tmp__folder/{subject}_{N}_{roiloc}_{dataSource}_{bestID[subject]}\")\n chosenMask[subject] = di['bestROIs']\n\ndef getMask(topN, subject):\n workingDir=\"/gpfs/milgram/project/turk-browne/projects/rtTest/\"\n for pn, parc in enumerate(topN):\n _mask = nib.load(workingDir+\"/{}/{}/{}\".format(roiloc, subject, parc))\n aff = _mask.affine\n _mask = _mask.get_data()\n _mask = _mask.astype(int)\n # say some things about the mask.\n mask = _mask if pn == 0 else mask + _mask\n mask[mask>0] = 1\n return mask\n\nfor sub in chosenMask:\n mask=getMask(chosenMask[sub], sub)\n # if not os.path.exists(f\"{workingDir}/{roiloc}/{sub}/chosenMask.npy\"):\n np.save(f\"{workingDir}/{roiloc}/{sub}/chosenMask\",mask)\n \n\nfrom scipy.stats import zscore\ndef normalize(X):\n _X=X.copy()\n _X = zscore(_X, axis=0)\n _X[np.isnan(_X)]=0\n return _X\n\ndef mkdir(folder):\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n\n'''\nload the functional and behavior data and choseMask and train all possible pairs of 2way classifiers\n''' \ndef minimalClass(subject):\n '''\n purpose: \n train offline models\n\n steps:\n load preprocessed and aligned behavior and brain data \n select data with the wanted pattern like AB AC AD BC BD CD \n train correspondng classifier and save the classifier performance and the classifiers themselves.\n\n '''\n\n import os\n import numpy as np\n import pandas as pd\n import matplotlib.pyplot as plt\n import sklearn\n import joblib\n import nibabel as nib\n import itertools\n from sklearn.linear_model import LogisticRegression\n\n def gaussian(x, mu, sig):\n # mu and sig is determined before each neurofeedback session using 2 recognition runs.\n return round(1+18*(1 - np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))))) # map from (0,1) -> [1,19]\n\n def jitter(size,const=0):\n jit = np.random.normal(0+const, 0.05, size)\n X = np.zeros((size))\n X = X + jit\n return X\n\n def other(target):\n other_objs = [i for i in ['bed', 'bench', 'chair', 'table'] if i not in target]\n return other_objs\n\n def red_vox(n_vox, prop=0.1):\n return int(np.ceil(n_vox * prop))\n\n def get_inds(X, Y, pair, testRun=None):\n\n inds = {}\n\n # return relative indices\n if testRun:\n trainIX = Y.index[(Y['label'].isin(pair)) & (Y['run_num'] != int(testRun))]\n else:\n trainIX = Y.index[(Y['label'].isin(pair))]\n\n # pull training and test data\n trainX = X[trainIX]\n trainY = Y.iloc[trainIX].label\n\n # Main classifier on 5 runs, testing on 6th\n clf = LogisticRegression(penalty='l2',C=1, solver='lbfgs', max_iter=1000, \n multi_class='multinomial').fit(trainX, trainY)\n B = clf.coef_[0] # pull betas\n\n # retrieve only the first object, then only the second object\n if testRun:\n obj1IX = Y.index[(Y['label'] == pair[0]) & (Y['run_num'] != int(testRun))]\n obj2IX = Y.index[(Y['label'] == pair[1]) & (Y['run_num'] != int(testRun))]\n else:\n obj1IX = Y.index[(Y['label'] == pair[0])]\n obj2IX = Y.index[(Y['label'] == pair[1])]\n\n # Get the average of the first object, then the second object\n obj1X = np.mean(X[obj1IX], 0)\n obj2X = np.mean(X[obj2IX], 0)\n\n # Build the importance map\n mult1X = obj1X * B\n mult2X = obj2X * B\n\n # Sort these so that they are from least to most important for a given category.\n sortmult1X = mult1X.argsort()[::-1]\n sortmult2X = mult2X.argsort()\n\n # add to a dictionary for later use\n inds[clf.classes_[0]] = sortmult1X\n inds[clf.classes_[1]] = sortmult2X\n\n return inds\n\n if 'milgram' in os.getcwd():\n main_dir='/gpfs/milgram/project/turk-browne/projects/rtTest/'\n else:\n main_dir='/Users/kailong/Desktop/rtTest'\n\n working_dir=main_dir\n os.chdir(working_dir)\n\n objects = ['bed', 'bench', 'chair', 'table']\n\n\n if dataSource == \"neurosketch\":\n funcdata = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/subjects/{sub}_neurosketch/data/nifti/realtime_preprocessed/{sub}_neurosketch_recognition_run_{run}.nii.gz\"\n metadata = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/data/features/recog/metadata_{sub}_V1_{phase}.csv\"\n anat = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/subjects/{sub}_neurosketch/data/nifti/{sub}_neurosketch_anat_mprage_brain.nii.gz\"\n elif dataSource == \"realtime\":\n funcdata = \"/gpfs/milgram/project/turk-browne/projects/rtcloud_kp/subjects/{sub}/ses{ses}_recognition/run0{run}/nifti/{sub}_functional.nii.gz\"\n metadata = \"/gpfs/milgram/project/turk-browne/projects/rtcloud_kp/subjects/{sub}/ses{ses}_recognition/run0{run}/{sub}_0{run}_preprocessed_behavData.csv\"\n anat = \"$TO_BE_FILLED\"\n else:\n funcdata = \"/gpfs/milgram/project/turk-browne/projects/rtTest/searchout/feat/{sub}_pre.nii.gz\"\n metadata = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/data/features/recog/metadata_{sub}_V1_{phase}.csv\"\n anat = \"$TO_BE_FILLED\"\n\n # print('mask dimensions: {}'. format(mask.shape))\n # print('number of voxels in mask: {}'.format(np.sum(mask)))\n phasedict = dict(zip([1,2,3,4,5,6],[\"12\", \"12\", \"34\", \"34\", \"56\", \"56\"]))\n imcodeDict={\"A\": \"bed\", \"B\": \"Chair\", \"C\": \"table\", \"D\": \"bench\"}\n chosenMask = np.load(f\"/gpfs/milgram/project/turk-browne/projects/rtTest/schaefer2018/{subject}/chosenMask.npy\")\n print(f\"np.sum(chosenMask)={np.sum(chosenMask)}\")\n # Compile preprocessed data and corresponding indices\n metas = []\n for run in range(1, 7):\n print(run, end='--')\n # retrieve from the dictionary which phase it is, assign the session\n phase = phasedict[run]\n \n # Build the path for the preprocessed functional data\n this4d = funcdata.format(run=run, phase=phase, sub=subject)\n \n # Read in the metadata, and reduce it to only the TR values from this run, add to a list\n thismeta = pd.read_csv(metadata.format(run=run, phase=phase, sub=subject))\n if dataSource == \"neurosketch\":\n _run = 1 if run % 2 == 0 else 2\n else:\n _run = run\n thismeta = thismeta[thismeta['run_num'] == int(_run)]\n \n if dataSource == \"realtime\":\n TR_num = list(thismeta.TR.astype(int))\n labels = list(thismeta.Item)\n labels = [imcodeDict[label] for label in labels]\n else:\n TR_num = list(thismeta.TR_num.astype(int))\n labels = list(thismeta.label)\n \n print(\"LENGTH OF TR: {}\".format(len(TR_num)))\n # Load the functional data\n runIm = nib.load(this4d)\n affine_mat = runIm.affine\n runImDat = runIm.get_fdata()\n \n # Use the TR numbers to select the correct features\n features = [runImDat[:,:,:,n+3] for n in TR_num] # here shape is from (94, 94, 72, 240) to (80, 94, 94, 72)\n features = np.array(features)\n features = features[:, chosenMask==1]\n print(\"shape of features\", features.shape, \"shape of chosenMask\", chosenMask.shape)\n features = normalize(features)\n # features = np.expand_dims(features, 0)\n \n # Append both so we can use it later\n # metas.append(labels)\n # metas['label']\n\n t=pd.DataFrame()\n t['label']=labels\n t[\"run_num\"]=run\n behav_data=t if run==1 else pd.concat([behav_data,t])\n \n runs = features if run == 1 else np.concatenate((runs, features))\n\n dimsize = runIm.header.get_zooms()\n brain_data = runs\n print(brain_data.shape)\n print(behav_data.shape)\n FEAT=brain_data\n print(f\"FEAT.shape={FEAT.shape}\")\n META=behav_data\n\n def Class(brain_data,behav_data):\n accs = []\n for run in range(1,7):\n trainIX = behav_data['run_num']!=int(run)\n testIX = behav_data['run_num']==int(run)\n\n trainX = brain_data[trainIX]\n trainY = behav_data.iloc[np.asarray(trainIX)].label\n\n testX = brain_data[testIX]\n testY = behav_data.iloc[np.asarray(testIX)].label\n\n clf = LogisticRegression(penalty='l2',C=1, solver='lbfgs', max_iter=1000, \n multi_class='multinomial').fit(trainX, trainY)\n\n # Monitor progress by printing accuracy (only useful if you're running a test set)\n acc = clf.score(testX, testY)\n accs.append(acc)\n accs\n return np.mean(accs)\n accs=Class(brain_data,behav_data)\n print(f\"new trained 4 way classifier accuracy={accs}\")\n\n\n # convert item colume to label colume\n imcodeDict={\n 'A': 'bed',\n 'B': 'chair',\n 'C': 'table',\n 'D': 'bench'}\n\n # Which run to use as test data (leave as None to not have test data)\n testRun = 6 # when testing: testRun = 2 ; META['run_num'].iloc[:5]=2\n\n # Decide on the proportion of crescent data to use for classification\n include = 1\n objects = ['bed', 'bench', 'chair', 'table']\n allpairs = itertools.combinations(objects,2)\n accs={}\n # Iterate over all the possible target pairs of objects\n for pair in allpairs:\n # Find the control (remaining) objects for this pair\n altpair = other(pair)\n\n # pull sorted indices for each of the critical objects, in order of importance (low to high)\n # inds = get_inds(FEAT, META, pair, testRun=testRun)\n\n # Find the number of voxels that will be left given your inclusion parameter above\n # nvox = red_vox(FEAT.shape[1], include)\n\n for obj in pair:\n # foil = [i for i in pair if i != obj][0]\n for altobj in altpair:\n\n # establish a naming convention where it is $TARGET_$CLASSIFICATION\n # Target is the NF pair (e.g. bed/bench)\n # Classificationis is btw one of the targets, and a control (e.g. bed/chair, or bed/table, NOT bed/bench)\n naming = '{}{}_{}{}'.format(pair[0], pair[1], obj, altobj)\n\n # Pull the relevant inds from your previously established dictionary \n # obj_inds = inds[obj]\n\n # If you're using testdata, this function will split it up. Otherwise it leaves out run as a parameter\n # if testRun:\n # trainIX = META.index[(META['label'].isin([obj, altobj])) & (META['run_num'] != int(testRun))]\n # testIX = META.index[(META['label'].isin([obj, altobj])) & (META['run_num'] == int(testRun))]\n # else:\n # trainIX = META.index[(META['label'].isin([obj, altobj]))]\n # testIX = META.index[(META['label'].isin([obj, altobj]))]\n # # pull training and test data\n # trainX = FEAT[trainIX]\n # testX = FEAT[testIX]\n # trainY = META.iloc[trainIX].label\n # testY = META.iloc[testIX].label\n\n # print(f\"obj={obj},altobj={altobj}\")\n # print(f\"unique(trainY)={np.unique(trainY)}\")\n # print(f\"unique(testY)={np.unique(testY)}\")\n # assert len(np.unique(trainY))==2\n\n # for testRun in range(6):\n if testRun:\n trainIX = ((META['label']==obj) + (META['label']==altobj)) * (META['run_num']!=int(testRun))\n testIX = ((META['label']==obj) + (META['label']==altobj)) * (META['run_num']==int(testRun))\n else:\n trainIX = ((META['label']==obj) + (META['label']==altobj))\n testIX = ((META['label']==obj) + (META['label']==altobj))\n # pull training and test data\n trainX = FEAT[trainIX]\n testX = FEAT[testIX]\n trainY = META.iloc[np.asarray(trainIX)].label\n testY = META.iloc[np.asarray(testIX)].label\n\n # print(f\"obj={obj},altobj={altobj}\")\n # print(f\"unique(trainY)={np.unique(trainY)}\")\n # print(f\"unique(testY)={np.unique(testY)}\")\n assert len(np.unique(trainY))==2\n\n # # If you're selecting high-importance features, this bit handles that\n # if include < 1:\n # trainX = trainX[:, obj_inds[-nvox:]]\n # testX = testX[:, obj_inds[-nvox:]]\n\n # Train your classifier\n clf = LogisticRegression(penalty='l2',C=1, solver='lbfgs', max_iter=1000, \n multi_class='multinomial').fit(trainX, trainY)\n\n\n model_folder = f\"{working_dir}{roiloc}/{subject}/clf/\"\n mkdir(model_folder)\n # Save it for later use\n joblib.dump(clf, model_folder +'/{}.joblib'.format(naming))\n\n # Monitor progress by printing accuracy (only useful if you're running a test set)\n acc = clf.score(testX, testY)\n # print(naming, acc)\n accs[naming]=acc\n \n # _=plt.figure()\n # _=plt.hist(list(accs.values()))\n return accs \n\n# sub_id=7\nimport sys\n\nsubject= '0119173' #sys.argv[1]\nsub_id = [i for i,x in enumerate(subjects) if x == subject][0]\n\nprint(\"best 4way classifier accuracy = \",GreedyBestAcc[subject][bestID[subject]])\n\naccs = minimalClass(subject)\n\nfor acc in accs:\n print(acc,accs[acc])\n\n\n\n'''\ncalculate the evidence floor and ceil for each subject and display different forms of evidences.\n'''\ndef morphingTarget(subject):\n '''\n purpose:\n get the morphing target function\n steps:\n load train clf\n load brain data and behavior data\n get the morphing target function\n evidence_floor is C evidence for CD classifier(can also be D evidence for CD classifier)\n evidence_ceil is A evidence in AC and AD classifier\n '''\n\n import os\n import numpy as np\n import pandas as pd\n import joblib\n import nibabel as nib\n\n\n phasedict = dict(zip([1,2,3,4,5,6],[\"12\", \"12\", \"34\", \"34\", \"56\", \"56\"]))\n imcodeDict={\"A\": \"bed\", \"B\": \"Chair\", \"C\": \"table\", \"D\": \"bench\"}\n if 'milgram' in os.getcwd():\n main_dir='/gpfs/milgram/project/turk-browne/projects/rtTest/'\n else:\n main_dir='/Users/kailong/Desktop/rtTest'\n\n working_dir=main_dir\n os.chdir(working_dir)\n\n funcdata = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/subjects/{sub}_neurosketch/data/nifti/realtime_preprocessed/{sub}_neurosketch_recognition_run_{run}.nii.gz\"\n metadata = \"/gpfs/milgram/project/turk-browne/jukebox/ntb/projects/sketchloop02/data/features/recog/metadata_{sub}_V1_{phase}.csv\"\n\n metas = []\n # for run in range(1, 7):\n # print(run, end='--')\n # # retrieve from the dictionary which phase it is, assign the session\n # phase = phasedict[run]\n # ses = 1\n \n # # Build the path for the preprocessed functional data\n # this4d = funcdata.format(ses=ses, run=run, phase=phase, sub=subject)\n \n # # Read in the metadata, and reduce it to only the TR values from this run, add to a list\n # thismeta = pd.read_csv(metadata.format(ses=ses, run=run, phase=phase, sub=subject))\n # if dataSource == \"neurosketch\":\n # _run = 1 if run % 2 == 0 else 2\n # else:\n # _run = run\n # thismeta = thismeta[thismeta['run_num'] == int(_run)]\n \n # if dataSource == \"realtime\":\n # TR_num = list(thismeta.TR.astype(int))\n # labels = list(thismeta.Item)\n # labels = [imcodeDict[label] for label in labels]\n # else:\n # TR_num = list(thismeta.TR_num.astype(int))\n # labels = list(thismeta.label)\n \n # print(\"LENGTH OF TR: {}\".format(len(TR_num)))\n # # Load the functional data\n # runIm = nib.load(this4d)\n # affine_mat = runIm.affine\n # runImDat = runIm.get_fdata()\n \n # # Use the TR numbers to select the correct features\n # features = [runImDat[:,:,:,n+3] for n in TR_num]\n # features = np.array(features)\n # chosenMask = np.load(f\"/gpfs/milgram/project/turk-browne/projects/rtTest/schaefer2018/{subject}/chosenMask.npy\")\n # features = features[:, chosenMask==1]\n # print(\"shape of features\", features.shape, \"shape of mask\", mask.shape)\n # # featmean = features.mean(1).mean(1).mean(1)[..., None,None,None] #features.mean(1)[..., None]\n # # features = features - featmean\n # # features = features - features.mean(0)\n # features = normalize(features)\n # # features = np.expand_dims(features, 0)\n \n # # Append both so we can use it later\n # # metas.append(labels)\n # # metas['label']\n\n # t=pd.DataFrame()\n # t['label']=labels\n # t[\"run_num\"]=run\n # behav_data=t if run==1 else pd.concat([behav_data,t])\n \n # runs = features if run == 1 else np.concatenate((runs, features))\n # for run in range(1, 7):\n run=6\n print(run, end='--')\n # retrieve from the dictionary which phase it is, assign the session\n phase = phasedict[run]\n ses = 1\n \n # Build the path for the preprocessed functional data\n this4d = funcdata.format(ses=ses, run=run, phase=phase, sub=subject)\n \n # Read in the metadata, and reduce it to only the TR values from this run, add to a list\n thismeta = pd.read_csv(metadata.format(ses=ses, run=run, phase=phase, sub=subject))\n if dataSource == \"neurosketch\":\n _run = 1 if run % 2 == 0 else 2\n else:\n _run = run\n thismeta = thismeta[thismeta['run_num'] == int(_run)]\n \n if dataSource == \"realtime\":\n TR_num = list(thismeta.TR.astype(int))\n labels = list(thismeta.Item)\n labels = [imcodeDict[label] for label in labels]\n else:\n TR_num = list(thismeta.TR_num.astype(int))\n labels = list(thismeta.label)\n \n print(\"LENGTH OF TR: {}\".format(len(TR_num)))\n # Load the functional data\n runIm = nib.load(this4d)\n affine_mat = runIm.affine\n runImDat = runIm.get_fdata()\n \n # Use the TR numbers to select the correct features\n features = [runImDat[:,:,:,n+3] for n in TR_num]\n features = np.array(features)\n chosenMask = np.load(f\"/gpfs/milgram/project/turk-browne/projects/rtTest/schaefer2018/{subject}/chosenMask.npy\")\n features = features[:, chosenMask==1]\n print(\"shape of features\", features.shape, \"shape of mask\", mask.shape)\n # featmean = features.mean(1).mean(1).mean(1)[..., None,None,None] #features.mean(1)[..., None]\n # features = features - featmean\n # features = features - features.mean(0)\n features = normalize(features)\n # features = np.expand_dims(features, 0)\n \n # Append both so we can use it later\n # metas.append(labels)\n # metas['label']\n\n t=pd.DataFrame()\n t['label']=labels\n t[\"run_num\"]=run\n behav_data=t\n \n runs = features\n\n \n dimsize = runIm.header.get_zooms()\n \n brain_data = runs\n print(brain_data.shape)\n print(behav_data.shape)\n FEAT=brain_data\n print(f\"FEAT.shape={FEAT.shape}\")\n META=behav_data\n\n # print('mask dimensions: {}'. format(mask.shape))\n # print('number of voxels in mask: {}'.format(np.sum(mask)))\n\n # runRecording = pd.read_csv(f\"{cfg.recognition_dir}../runRecording.csv\")\n # actualRuns = list(runRecording['run'].iloc[list(np.where(1==1*(runRecording['type']=='recognition'))[0])]) # can be [1,2,3,4,5,6,7,8] or [1,2,4,5]\n\n # objects = ['bed', 'bench', 'chair', 'table']\n\n # for ii,run in enumerate(actualRuns[:2]): # load behavior and brain data for current session\n # t = np.load(f\"{cfg.recognition_dir}brain_run{run}.npy\")\n # # mask = nib.load(f\"{cfg.chosenMask}\").get_data()\n # mask = np.load(cfg.chosenMask)\n # t = t[:,mask==1]\n # t = normalize(t)\n # brain_data=t if ii==0 else np.concatenate((brain_data,t), axis=0)\n\n # t = pd.read_csv(f\"{cfg.recognition_dir}behav_run{run}.csv\")\n # behav_data=t if ii==0 else pd.concat([behav_data,t])\n\n # FEAT=brain_data.reshape(brain_data.shape[0],-1)\n # # FEAT_mean=np.mean(FEAT,axis=1)\n # # FEAT=(FEAT.T-FEAT_mean).T\n # # FEAT_mean=np.mean(FEAT,axis=0)\n # # FEAT=FEAT-FEAT_mean\n\n # META=behav_data\n\n # convert item colume to label colume\n imcodeDict={\n 'A': 'bed',\n 'B': 'chair',\n 'C': 'table',\n 'D': 'bench'}\n # label=[]\n # for curr_trial in range(META.shape[0]):\n # label.append(imcodeDict[META['Item'].iloc[curr_trial]])\n # META['label']=label # merge the label column with the data dataframe\n\n\n # def classifierEvidence(clf,X,Y): # X shape is [trials,voxelNumber], Y is ['bed', 'bed'] for example # return a 1-d array of probability\n # # This function get the data X and evidence object I want to know Y, and output the trained model evidence.\n # targetID=[np.where((clf.classes_==i)==True)[0][0] for i in Y]\n # # Evidence=(np.sum(X*clf.coef_,axis=1)+clf.intercept_) if targetID[0]==1 else (1-(np.sum(X*clf.coef_,axis=1)+clf.intercept_))\n # Evidence=([email protected]_.T+clf.intercept_) if targetID[0]==1 else (-([email protected]_.T+clf.intercept_))\n # Evidence = 1/(1+np.exp(-Evidence))\n # return np.asarray(Evidence)\n\n # def classifierEvidence(clf,X,Y):\n # ID=np.where((clf.classes_==Y[0])*1==1)[0][0]\n # p = clf.predict_proba(X)[:,ID]\n # BX=np.log(p/(1-p))\n # return BX\n\n def classifierEvidence(clf,X,Y):\n ID=np.where((clf.classes_==Y[0])*1==1)[0][0]\n Evidence=([email protected]_.T+clf.intercept_) if ID==1 else (-([email protected]_.T+clf.intercept_))\n # Evidence=([email protected]_.T+clf.intercept_) if ID==0 else (-([email protected]_.T+clf.intercept_))\n return np.asarray(Evidence)\n\n A_ID = (META['label']=='bed')\n X = FEAT[A_ID]\n\n # evidence_floor is C evidence for AC_CD BC_CD CD_CD classifier(can also be D evidence for CD classifier)\n # Y = ['table'] * X.shape[0]\n # CD_clf=joblib.load(cfg.usingModel_dir +'bedbench_benchtable.joblib') # These 4 clf are the same: bedbench_benchtable.joblib bedtable_tablebench.joblib benchchair_benchtable.joblib chairtable_tablebench.joblib\n # CD_C_evidence = classifierEvidence(CD_clf,X,Y)\n # evidence_floor = np.mean(CD_C_evidence)\n # print(f\"evidence_floor={evidence_floor}\")\n\n model_folder = f\"{working_dir}{roiloc}/{subject}/clf/\"\n\n # #try out other forms of floor: C evidence in AC and D evidence for AD\n # Y = ['bench'] * X.shape[0]\n # AD_clf=joblib.load(model_folder +'bedchair_bedbench.joblib') # These 4 clf are the same: bedchair_bedbench.joblib bedtable_bedbench.joblib benchchair_benchbed.joblib benchtable_benchbed.joblib\n # AD_D_evidence = classifierEvidence(AD_clf,X,Y)\n # evidence_floor = np.mean(AD_D_evidence)\n # print(f\"evidence_floor2={np.mean(evidence_floor)}\")\n\n\n\n # # floor\n # Y = ['bench'] * X.shape[0]\n # CD_clf=joblib.load(model_folder +'bedbench_benchtable.joblib') # These 4 clf are the same: bedbench_benchtable.joblib bedtable_tablebench.joblib benchchair_benchtable.joblib chairtable_tablebench.joblib\n # CD_D_evidence = classifierEvidence(CD_clf,X,Y)\n # evidence_floor = np.mean(CD_D_evidence)\n # print(f\"evidence_floor={evidence_floor}\")\n\n # Y = ['table'] * X.shape[0]\n # CD_clf=joblib.load(model_folder +'bedbench_benchtable.joblib') # These 4 clf are the same: bedbench_benchtable.joblib bedtable_tablebench.joblib benchchair_benchtable.joblib chairtable_tablebench.joblib\n # CD_C_evidence = classifierEvidence(CD_clf,X,Y)\n # evidence_floor = np.mean(CD_C_evidence)\n # print(f\"evidence_floor={evidence_floor}\")\n\n\n # # evidence_ceil is A evidence in AC and AD classifier\n # Y = ['bed'] * X.shape[0]\n # AC_clf=joblib.load(model_folder +'benchtable_tablebed.joblib') # These 4 clf are the same: bedbench_bedtable.joblib bedchair_bedtable.joblib benchtable_tablebed.joblib chairtable_tablebed.joblib\n # AC_A_evidence = classifierEvidence(AC_clf,X,Y)\n # evidence_ceil1 = AC_A_evidence\n # print(f\"evidence_ceil1={np.mean(evidence_ceil1)}\")\n\n # Y = ['bed'] * X.shape[0]\n # AD_clf=joblib.load(model_folder +'bedchair_bedbench.joblib') # These 4 clf are the same: bedchair_bedbench.joblib bedtable_bedbench.joblib benchchair_benchbed.joblib benchtable_benchbed.joblib\n # AD_A_evidence = classifierEvidence(AD_clf,X,Y)\n # evidence_ceil2 = AD_A_evidence\n # print(f\"evidence_ceil2={np.mean(evidence_ceil2)}\")\n\n # # evidence_ceil = np.mean(evidence_ceil1)\n # # evidence_ceil = np.mean(evidence_ceil2)\n # evidence_ceil = np.mean((evidence_ceil1+evidence_ceil2)/2)\n # print(f\"evidence_ceil={evidence_ceil}\")\n store=\"\\n\"\n print(\"floor\")\n # D evidence for AD_clf when A is presented.\n Y = ['bench'] * X.shape[0]\n AD_clf=joblib.load(model_folder +'bedchair_bedbench.joblib') # These 4 clf are the same: bedchair_bedbench.joblib bedtable_bedbench.joblib benchchair_benchbed.joblib benchtable_benchbed.joblib\n AD_D_evidence = classifierEvidence(AD_clf,X,Y)\n evidence_floor = np.mean(AD_D_evidence)\n print(f\"D evidence for AD_clf when A is presented={evidence_floor}\")\n store=store+f\"D evidence for AD_clf when A is presented={evidence_floor}\"\n\n # C evidence for AC_clf when A is presented.\n Y = ['table'] * X.shape[0]\n AC_clf=joblib.load(model_folder +'benchtable_tablebed.joblib') # These 4 clf are the same: bedbench_bedtable.joblib bedchair_bedtable.joblib benchtable_tablebed.joblib chairtable_tablebed.joblib\n AC_C_evidence = classifierEvidence(AC_clf,X,Y)\n evidence_floor = np.mean(AC_C_evidence)\n print(f\"C evidence for AC_clf when A is presented={evidence_floor}\")\n store=store+\"\\n\"+f\"C evidence for AC_clf when A is presented={evidence_floor}\"\n\n # D evidence for CD_clf when A is presented.\n Y = ['bench'] * X.shape[0]\n CD_clf=joblib.load(model_folder +'bedbench_benchtable.joblib') # These 4 clf are the same: bedbench_benchtable.joblib bedtable_tablebench.joblib benchchair_benchtable.joblib chairtable_tablebench.joblib\n CD_D_evidence = classifierEvidence(CD_clf,X,Y)\n evidence_floor = np.mean(CD_D_evidence)\n print(f\"D evidence for CD_clf when A is presented={evidence_floor}\")\n store=store+\"\\n\"+f\"D evidence for CD_clf when A is presented={evidence_floor}\"\n\n # C evidence for CD_clf when A is presented.\n Y = ['table'] * X.shape[0]\n CD_clf=joblib.load(model_folder +'bedbench_benchtable.joblib') # These 4 clf are the same: bedbench_benchtable.joblib bedtable_tablebench.joblib benchchair_benchtable.joblib chairtable_tablebench.joblib\n CD_C_evidence = classifierEvidence(CD_clf,X,Y)\n evidence_floor = np.mean(CD_C_evidence)\n print(f\"C evidence for CD_clf when A is presented={evidence_floor}\")\n store=store+\"\\n\"+f\"C evidence for CD_clf when A is presented={evidence_floor}\"\n\n\n\n\n print(\"ceil\")\n store=store+\"\\n\"+\"ceil\"\n # evidence_ceil is A evidence in AC and AD classifier\n Y = ['bed'] * X.shape[0]\n AC_clf=joblib.load(model_folder +'benchtable_tablebed.joblib') # These 4 clf are the same: bedbench_bedtable.joblib bedchair_bedtable.joblib benchtable_tablebed.joblib chairtable_tablebed.joblib\n AC_A_evidence = classifierEvidence(AC_clf,X,Y)\n evidence_ceil1 = AC_A_evidence\n print(f\"A evidence in AC_clf when A is presented={np.mean(evidence_ceil1)}\")\n store=store+\"\\n\"+f\"A evidence in AC_clf when A is presented={np.mean(evidence_ceil1)}\"\n\n Y = ['bed'] * X.shape[0]\n AD_clf=joblib.load(model_folder +'bedchair_bedbench.joblib') # These 4 clf are the same: bedchair_bedbench.joblib bedtable_bedbench.joblib benchchair_benchbed.joblib benchtable_benchbed.joblib\n AD_A_evidence = classifierEvidence(AD_clf,X,Y)\n evidence_ceil2 = AD_A_evidence\n print(f\"A evidence in AD_clf when A is presented={np.mean(evidence_ceil2)}\")\n store=store+\"\\n\"+f\"A evidence in AD_clf when A is presented={np.mean(evidence_ceil2)}\"\n\n # evidence_ceil = np.mean(evidence_ceil1)\n # evidence_ceil = np.mean(evidence_ceil2)\n evidence_ceil = np.mean((evidence_ceil1+evidence_ceil2)/2)\n print(f\"evidence_ceil={evidence_ceil}\")\n store=store+\"\\n\"+f\"evidence_ceil={evidence_ceil}\"\n\n return evidence_floor, evidence_ceil,store\n \nfloor, ceil,store = morphingTarget(subject)\nmu = (ceil+floor)/2\nsig = (ceil-floor)/2.3548\nprint(f\"floor={floor}, ceil={ceil}\")\nprint(f\"mu={mu}, sig={sig}\")\n\nstore=store+\"\\n\"+f\"floor={floor}, ceil={ceil}\"\nstore=store+\"\\n\"+f\"mu={mu}, sig={sig}\"\n\nsave_obj(store,f\"./{subject}store\")\n\n\n\n\n\n\n\n\n# # floorCeilNeurosketch_child.sh\n# #!/usr/bin/env bash\n# # Input python command to be submitted as a job\n# #SBATCH --output=logs/floorCeil-%j.out\n# #SBATCH --job-name floorCeil\n# #SBATCH --partition=short,day,scavenge,verylong\n# #SBATCH --time=1:00:00 #20:00:00\n# #SBATCH --mem=10000\n# #SBATCH -n 5\n\n# # Set up the environment\n\n# subject=$1\n\n# echo source activate /gpfs/milgram/project/turk-browne/users/kp578/CONDA/rtcloud\n# source activate /gpfs/milgram/project/turk-browne/users/kp578/CONDA/rtcloud\n\n# python -u ./floorCeilNeurosketch.py $subject\n\n\n\n\n# # floorCeilNeurosketch_parent.sh\n# subjects=\"1206161 0119173 1206162 1130161 1206163 0120171 0111171 1202161 0125172 0110172 0123173 0120173 0110171 0119172 0124171 0123171 1203161 0118172 0118171 0112171 1207162 0117171 0119174 0112173 0112172\" #these subjects are done with the batchRegions code\n# for sub in $subjects\n# do\n# for num in 25; #best ID is 30 thus the best num is 31\n# do\n# echo sbatch --requeue floorCeilNeurosketch_child.sh $sub\n# sbatch --requeue floorCeilNeurosketch_child.sh $sub\n# done\n# done\n", "conda env=/gpfs/milgram/project/turk-browne/users/kp578/CONDA/rtcloud\n" ], [ "def subLoop(subject):\n data={}\n accs = minimalClass(subject)\n print(\"best 4way classifier accuracy = \",GreedyBestAcc[subject][bestID[subject]])\n data['best 4way classifier accuracy']=GreedyBestAcc[subject][bestID[subject]]\n for acc in accs:\n print(acc,accs[acc])\n data[\"accs\"]=accs\n\n\n\n floor, ceil,store = morphingTarget(subject)\n mu = (ceil+floor)/2\n sig = (ceil-floor)/2.3548\n print(f\"floor={floor}, ceil={ceil}\")\n print(f\"mu={mu}, sig={sig}\")\n\n store=store+\"\\n\"+f\"floor={floor}, ceil={ceil}\"\n store=store+\"\\n\"+f\"mu={mu}, sig={sig}\"\n data[\"store\"]=store\n save_obj(store,f\"./{subject}store\")\n return data\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndata={}\nfor subject in subjects:\n data[subject]=subLoop(subject)\n", "np.sum(chosenMask)=4927\n1--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n2--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n3--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n4--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n5--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n6--LENGTH OF TR: 80\nshape of features (80, 4927) shape of chosenMask (94, 94, 72)\n(480, 4927)\n(480, 2)\nFEAT.shape=(480, 4927)\nnew trained 4 way classifier accuracy=0.3520833333333333\nbest 4way classifier accuracy = 0.3520833333333333\nbedbench_bedchair 0.5\nbedbench_bedtable 0.45\nbedbench_benchchair 0.575\nbedbench_benchtable 0.575\nbedchair_bedbench 0.6\nbedchair_bedtable 0.45\nbedchair_chairbench 0.575\nbedchair_chairtable 0.475\nbedtable_bedbench 0.6\nbedtable_bedchair 0.5\nbedtable_tablebench 0.575\nbedtable_tablechair 0.475\nbenchchair_benchbed 0.6\nbenchchair_benchtable 0.575\nbenchchair_chairbed 0.5\nbenchchair_chairtable 0.475\nbenchtable_benchbed 0.6\nbenchtable_benchchair 0.575\nbenchtable_tablebed 0.45\nbenchtable_tablechair 0.475\nchairtable_chairbed 0.5\nchairtable_chairbench 0.575\nchairtable_tablebed 0.45\nchairtable_tablebench 0.575\n6--LENGTH OF TR: 80\nshape of features (80, 4927) shape of mask (94, 94, 72)\n(80, 4927)\n(80, 2)\nFEAT.shape=(80, 4927)\nfloor\nD evidence for AD_clf when A is presented=-0.28403150374256286\nC evidence for AC_clf when A is presented=-0.08419816188336389\nD evidence for CD_clf when A is presented=-0.1040101817607326\nC evidence for CD_clf when A is presented=0.1040101817607326\nceil\nA evidence in AC_clf when A is presented=0.08419816188336389\nA evidence in AD_clf when A is presented=0.28403150374256286\nevidence_ceil=0.1841148328129634\nfloor=0.1040101817607326, ceil=0.1841148328129634\nmu=0.144062507286848, sig=0.03401760279099321\nnp.sum(chosenMask)=3488\n1--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n2--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n3--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n4--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n5--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n6--LENGTH OF TR: 80\nshape of features (80, 3488) shape of chosenMask (94, 94, 72)\n(480, 3488)\n(480, 2)\nFEAT.shape=(480, 3488)\nnew trained 4 way classifier accuracy=0.325\nbest 4way classifier accuracy = 0.325\nbedbench_bedchair 0.525\nbedbench_bedtable 0.55\nbedbench_benchchair 0.525\nbedbench_benchtable 0.675\nbedchair_bedbench 0.6\nbedchair_bedtable 0.55\nbedchair_chairbench 0.525\nbedchair_chairtable 0.5\nbedtable_bedbench 0.6\nbedtable_bedchair 0.525\nbedtable_tablebench 0.675\nbedtable_tablechair 0.5\nbenchchair_benchbed 0.6\nbenchchair_benchtable 0.675\nbenchchair_chairbed 0.525\nbenchchair_chairtable 0.5\nbenchtable_benchbed 0.6\nbenchtable_benchchair 0.525\nbenchtable_tablebed 0.55\nbenchtable_tablechair 0.5\nchairtable_chairbed 0.525\nchairtable_chairbench 0.525\nchairtable_tablebed 0.55\nchairtable_tablebench 0.675\n6--LENGTH OF TR: 80\nshape of features (80, 3488) shape of mask (94, 94, 72)\n(80, 3488)\n(80, 2)\nFEAT.shape=(80, 3488)\nfloor\nD evidence for AD_clf when A is presented=-0.051884448218457516\nC evidence for AC_clf when A is presented=-0.01705912876212199\nD evidence for CD_clf when A is presented=-0.0047471010805816725\nC evidence for CD_clf when A is presented=0.0047471010805816725\nceil\nA evidence in AC_clf when A is presented=0.01705912876212199\nA evidence in AD_clf when A is presented=0.051884448218457516\nevidence_ceil=0.03447178849028972\nfloor=0.0047471010805816725, ceil=0.03447178849028972\nmu=0.019609444785435696, sig=0.01262301996335487\nnp.sum(chosenMask)=3140\n1--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n2--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n3--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n4--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n5--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n6--LENGTH OF TR: 80\nshape of features (80, 3140) shape of chosenMask (94, 94, 72)\n(480, 3140)\n(480, 2)\nFEAT.shape=(480, 3140)\nnew trained 4 way classifier accuracy=0.3583333333333334\nbest 4way classifier accuracy = 0.3583333333333334\nbedbench_bedchair 0.525\nbedbench_bedtable 0.525\nbedbench_benchchair 0.6\nbedbench_benchtable 0.55\nbedchair_bedbench 0.6\nbedchair_bedtable 0.525\nbedchair_chairbench 0.6\nbedchair_chairtable 0.625\nbedtable_bedbench 0.6\nbedtable_bedchair 0.525\nbedtable_tablebench 0.55\nbedtable_tablechair 0.625\nbenchchair_benchbed 0.6\nbenchchair_benchtable 0.55\nbenchchair_chairbed 0.525\nbenchchair_chairtable 0.625\nbenchtable_benchbed 0.6\nbenchtable_benchchair 0.6\nbenchtable_tablebed 0.525\nbenchtable_tablechair 0.625\nchairtable_chairbed 0.525\nchairtable_chairbench 0.6\nchairtable_tablebed 0.525\nchairtable_tablebench 0.55\n6--LENGTH OF TR: 80\nshape of features (80, 3140) shape of mask (94, 94, 72)\n(80, 3140)\n(80, 2)\nFEAT.shape=(80, 3140)\nfloor\nD evidence for AD_clf when A is presented=-0.008206036134410222\nC evidence for AC_clf when A is presented=0.05725995583293899\nD evidence for CD_clf when A is presented=-0.08732330754110029\nC evidence for CD_clf when A is presented=0.08732330754110029\nceil\nA evidence in AC_clf when A is presented=-0.05725995583293899\nA evidence in AD_clf when A is presented=0.008206036134410222\nevidence_ceil=-0.024526959849264375\nfloor=0.08732330754110029, ceil=-0.024526959849264375\nmu=0.03139817384591796, sig=-0.04749883955765443\nnp.sum(chosenMask)=6267\n1--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n2--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n3--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n4--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n5--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n6--LENGTH OF TR: 80\nshape of features (80, 6267) shape of chosenMask (94, 94, 72)\n(480, 6267)\n(480, 2)\nFEAT.shape=(480, 6267)\nnew trained 4 way classifier accuracy=0.32083333333333336\nbest 4way classifier accuracy = 0.32083333333333336\nbedbench_bedchair 0.4\nbedbench_bedtable 0.575\nbedbench_benchchair 0.575\nbedbench_benchtable 0.575\nbedchair_bedbench 0.6\nbedchair_bedtable 0.575\nbedchair_chairbench 0.575\nbedchair_chairtable 0.3\nbedtable_bedbench 0.6\nbedtable_bedchair 0.4\nbedtable_tablebench 0.575\nbedtable_tablechair 0.3\nbenchchair_benchbed 0.6\nbenchchair_benchtable 0.575\nbenchchair_chairbed 0.4\nbenchchair_chairtable 0.3\nbenchtable_benchbed 0.6\nbenchtable_benchchair 0.575\nbenchtable_tablebed 0.575\nbenchtable_tablechair 0.3\nchairtable_chairbed 0.4\nchairtable_chairbench 0.575\nchairtable_tablebed 0.575\nchairtable_tablebench 0.575\n6--LENGTH OF TR: 80\nshape of features (80, 6267) shape of mask (94, 94, 72)\n(80, 6267)\n(80, 2)\nFEAT.shape=(80, 6267)\nfloor\nD evidence for AD_clf when A is presented=-0.19315217373157179\nC evidence for AC_clf when A is presented=-0.1360055950659129\nD evidence for CD_clf when A is presented=-0.02608689598450814\nC evidence for CD_clf when A is presented=0.02608689598450814\nceil\nA evidence in AC_clf when A is presented=0.1360055950659129\nA evidence in AD_clf when A is presented=0.19315217373157179\nevidence_ceil=0.16457888439874235\nfloor=0.02608689598450814, ceil=0.16457888439874235\nmu=0.09533289019162525, sig=0.058812633095903774\nnp.sum(chosenMask)=2759\n1--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n2--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n3--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n4--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n5--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n6--LENGTH OF TR: 80\nshape of features (80, 2759) shape of chosenMask (94, 94, 72)\n(480, 2759)\n(480, 2)\nFEAT.shape=(480, 2759)\nnew trained 4 way classifier accuracy=0.33958333333333335\n" ], [ "for sub in data:\n print(\"---------------------------------------------------------------\")\n print()\n print(f\"subject={sub}\")\n print(data[sub][\"store\"])", "---------------------------------------------------------------\n\nsubject=1206161\n\nD evidence for AD_clf when A is presented=-0.28403150374256286\nC evidence for AC_clf when A is presented=-0.08419816188336389\nD evidence for CD_clf when A is presented=-0.1040101817607326\nC evidence for CD_clf when A is presented=0.1040101817607326\nceil\nA evidence in AC_clf when A is presented=0.08419816188336389\nA evidence in AD_clf when A is presented=0.28403150374256286\nevidence_ceil=0.1841148328129634\nfloor=0.1040101817607326, ceil=0.1841148328129634\nmu=0.144062507286848, sig=0.03401760279099321\n---------------------------------------------------------------\n\nsubject=0119173\n\nD evidence for AD_clf when A is presented=-0.051884448218457516\nC evidence for AC_clf when A is presented=-0.01705912876212199\nD evidence for CD_clf when A is presented=-0.0047471010805816725\nC evidence for CD_clf when A is presented=0.0047471010805816725\nceil\nA evidence in AC_clf when A is presented=0.01705912876212199\nA evidence in AD_clf when A is presented=0.051884448218457516\nevidence_ceil=0.03447178849028972\nfloor=0.0047471010805816725, ceil=0.03447178849028972\nmu=0.019609444785435696, sig=0.01262301996335487\n---------------------------------------------------------------\n\nsubject=1206162\n\nD evidence for AD_clf when A is presented=-0.008206036134410222\nC evidence for AC_clf when A is presented=0.05725995583293899\nD evidence for CD_clf when A is presented=-0.08732330754110029\nC evidence for CD_clf when A is presented=0.08732330754110029\nceil\nA evidence in AC_clf when A is presented=-0.05725995583293899\nA evidence in AD_clf when A is presented=0.008206036134410222\nevidence_ceil=-0.024526959849264375\nfloor=0.08732330754110029, ceil=-0.024526959849264375\nmu=0.03139817384591796, sig=-0.04749883955765443\n---------------------------------------------------------------\n\nsubject=1130161\n\nD evidence for AD_clf when A is presented=-0.19315217373157179\nC evidence for AC_clf when A is presented=-0.1360055950659129\nD evidence for CD_clf when A is presented=-0.02608689598450814\nC evidence for CD_clf when A is presented=0.02608689598450814\nceil\nA evidence in AC_clf when A is presented=0.1360055950659129\nA evidence in AD_clf when A is presented=0.19315217373157179\nevidence_ceil=0.16457888439874235\nfloor=0.02608689598450814, ceil=0.16457888439874235\nmu=0.09533289019162525, sig=0.058812633095903774\n---------------------------------------------------------------\n\nsubject=1206163\n\nD evidence for AD_clf when A is presented=-0.30790850021531835\nC evidence for AC_clf when A is presented=-0.14028912971612328\nD evidence for CD_clf when A is presented=-0.14323473903859302\nC evidence for CD_clf when A is presented=0.14323473903859302\nceil\nA evidence in AC_clf when A is presented=0.14028912971612328\nA evidence in AD_clf when A is presented=0.30790850021531835\nevidence_ceil=0.22409881496572087\nfloor=0.14323473903859302, ceil=0.22409881496572087\nmu=0.18366677700215694, sig=0.034340103587195456\n---------------------------------------------------------------\n\nsubject=0120171\n\nD evidence for AD_clf when A is presented=-0.3114454460692828\nC evidence for AC_clf when A is presented=-0.2612863547268568\nD evidence for CD_clf when A is presented=-0.12792851161918303\nC evidence for CD_clf when A is presented=0.12792851161918303\nceil\nA evidence in AC_clf when A is presented=0.2612863547268568\nA evidence in AD_clf when A is presented=0.3114454460692828\nevidence_ceil=0.28636590039806975\nfloor=0.12792851161918303, ceil=0.28636590039806975\nmu=0.2071472060086264, sig=0.06728273686890042\n---------------------------------------------------------------\n\nsubject=0111171\n\nD evidence for AD_clf when A is presented=-0.29391009729191936\nC evidence for AC_clf when A is presented=0.054230111476429324\nD evidence for CD_clf when A is presented=-0.329794878788798\nC evidence for CD_clf when A is presented=0.329794878788798\nceil\nA evidence in AC_clf when A is presented=-0.054230111476429324\nA evidence in AD_clf when A is presented=0.29391009729191936\nevidence_ceil=0.11983999290774498\nfloor=0.329794878788798, ceil=0.11983999290774498\nmu=0.2248174358482715, sig=-0.08916038979151222\n---------------------------------------------------------------\n\nsubject=1202161\n\nD evidence for AD_clf when A is presented=0.19073727217774938\nC evidence for AC_clf when A is presented=0.11283785966706945\nD evidence for CD_clf when A is presented=0.2873623762795963\nC evidence for CD_clf when A is presented=-0.2873623762795963\nceil\nA evidence in AC_clf when A is presented=-0.11283785966706945\nA evidence in AD_clf when A is presented=-0.19073727217774938\nevidence_ceil=-0.15178756592240938\nfloor=-0.2873623762795963, ceil=-0.15178756592240938\nmu=-0.21957497110100285, sig=0.05757381109104252\n---------------------------------------------------------------\n\nsubject=0125172\n\nD evidence for AD_clf when A is presented=-0.07572211490965883\nC evidence for AC_clf when A is presented=-0.36251509153525197\nD evidence for CD_clf when A is presented=0.2106666303373797\nC evidence for CD_clf when A is presented=-0.2106666303373797\nceil\nA evidence in AC_clf when A is presented=0.36251509153525197\nA evidence in AD_clf when A is presented=0.07572211490965883\nevidence_ceil=0.21911860322245538\nfloor=-0.2106666303373797, ceil=0.21911860322245538\nmu=0.004225986442537841, sig=0.18251453777808524\n---------------------------------------------------------------\n\nsubject=0110172\n\nD evidence for AD_clf when A is presented=-0.1302477689102912\nC evidence for AC_clf when A is presented=-0.16320747005887973\nD evidence for CD_clf when A is presented=0.1072611082128088\nC evidence for CD_clf when A is presented=-0.1072611082128088\nceil\nA evidence in AC_clf when A is presented=0.16320747005887973\nA evidence in AD_clf when A is presented=0.1302477689102912\nevidence_ceil=0.14672761948458551\nfloor=-0.1072611082128088, ceil=0.14672761948458551\nmu=0.019733255635888354, sig=0.10785999987149411\n---------------------------------------------------------------\n\nsubject=0123173\n\nD evidence for AD_clf when A is presented=-0.35059961532186645\nC evidence for AC_clf when A is presented=-0.7236128340089738\nD evidence for CD_clf when A is presented=0.29176675572948063\nC evidence for CD_clf when A is presented=-0.29176675572948063\nceil\nA evidence in AC_clf when A is presented=0.7236128340089738\nA evidence in AD_clf when A is presented=0.35059961532186645\nevidence_ceil=0.53710622466542\nfloor=-0.29176675572948063, ceil=0.53710622466542\nmu=0.1226697344679697, sig=0.35199294224346045\n---------------------------------------------------------------\n\nsubject=0120173\n\nD evidence for AD_clf when A is presented=-0.24450883571925597\nC evidence for AC_clf when A is presented=-0.5563857865354273\nD evidence for CD_clf when A is presented=0.39001446762600817\nC evidence for CD_clf when A is presented=-0.39001446762600817\nceil\nA evidence in AC_clf when A is presented=0.5563857865354273\nA evidence in AD_clf when A is presented=0.24450883571925597\nevidence_ceil=0.4004473111273416\nfloor=-0.39001446762600817, ceil=0.4004473111273416\nmu=0.005216421750666722, sig=0.3356810679265117\n---------------------------------------------------------------\n\nsubject=0110171\n\nD evidence for AD_clf when A is presented=-0.25053023136977015\nC evidence for AC_clf when A is presented=-0.3147122594493354\nD evidence for CD_clf when A is presented=0.1281795099945023\nC evidence for CD_clf when A is presented=-0.1281795099945023\nceil\nA evidence in AC_clf when A is presented=0.3147122594493354\nA evidence in AD_clf when A is presented=0.25053023136977015\nevidence_ceil=0.2826212454095528\nfloor=-0.1281795099945023, ceil=0.2826212454095528\nmu=0.07722086770752525, sig=0.174452503568904\n---------------------------------------------------------------\n\nsubject=0119172\n\nD evidence for AD_clf when A is presented=-0.19139014915788372\nC evidence for AC_clf when A is presented=-0.33028578353097854\nD evidence for CD_clf when A is presented=0.1287003382515664\nC evidence for CD_clf when A is presented=-0.1287003382515664\nceil\nA evidence in AC_clf when A is presented=0.33028578353097854\nA evidence in AD_clf when A is presented=0.19139014915788372\nevidence_ceil=0.26083796634443124\nfloor=-0.1287003382515664, ceil=0.26083796634443124\nmu=0.06606881404643242, sig=0.1654230952080846\n---------------------------------------------------------------\n\nsubject=0124171\n\nD evidence for AD_clf when A is presented=-0.41405392320060985\nC evidence for AC_clf when A is presented=0.18433158819669515\nD evidence for CD_clf when A is presented=-0.5271831842105206\nC evidence for CD_clf when A is presented=0.5271831842105206\nceil\nA evidence in AC_clf when A is presented=-0.18433158819669515\nA evidence in AD_clf when A is presented=0.41405392320060985\nevidence_ceil=0.11486116750195734\nfloor=0.5271831842105206, ceil=0.11486116750195734\nmu=0.32102217585623893, sig=-0.17509852926302158\n---------------------------------------------------------------\n\nsubject=0123171\n\nD evidence for AD_clf when A is presented=-0.2633176850018941\nC evidence for AC_clf when A is presented=0.006569318340045377\nD evidence for CD_clf when A is presented=-0.38738580877994844\nC evidence for CD_clf when A is presented=0.38738580877994844\nceil\nA evidence in AC_clf when A is presented=-0.006569318340045377\nA evidence in AD_clf when A is presented=0.2633176850018941\nevidence_ceil=0.12837418333092437\nfloor=0.38738580877994844, ceil=0.12837418333092437\nmu=0.25787999605543643, sig=-0.10999304630925091\n---------------------------------------------------------------\n\nsubject=1203161\n\nD evidence for AD_clf when A is presented=0.46873258380602933\nC evidence for AC_clf when A is presented=0.05756020726280177\nD evidence for CD_clf when A is presented=0.3648195782936622\nC evidence for CD_clf when A is presented=-0.3648195782936622\nceil\nA evidence in AC_clf when A is presented=-0.05756020726280177\nA evidence in AD_clf when A is presented=-0.46873258380602933\nevidence_ceil=-0.26314639553441554\nfloor=-0.3648195782936622, ceil=-0.26314639553441554\nmu=-0.31398298691403886, sig=0.04317699284832964\n---------------------------------------------------------------\n\nsubject=0118172\n\nD evidence for AD_clf when A is presented=-0.13757684139398094\nC evidence for AC_clf when A is presented=-0.08913653310898256\nD evidence for CD_clf when A is presented=-0.16098131110004632\nC evidence for CD_clf when A is presented=0.16098131110004632\nceil\nA evidence in AC_clf when A is presented=0.08913653310898256\nA evidence in AD_clf when A is presented=0.13757684139398094\nevidence_ceil=0.1133566872514818\nfloor=0.16098131110004632, ceil=0.1133566872514818\nmu=0.13716899917576406, sig=-0.020224487790285593\n---------------------------------------------------------------\n\nsubject=0118171\n\nD evidence for AD_clf when A is presented=0.05159242405328811\nC evidence for AC_clf when A is presented=-0.16506470469776321\nD evidence for CD_clf when A is presented=0.044266984271820894\nC evidence for CD_clf when A is presented=-0.044266984271820894\nceil\nA evidence in AC_clf when A is presented=0.16506470469776321\nA evidence in AD_clf when A is presented=-0.05159242405328811\nevidence_ceil=0.056736140322237505\nfloor=-0.044266984271820894, ceil=0.056736140322237505\nmu=0.006234578025208305, sig=0.04289244292256599\n---------------------------------------------------------------\n\nsubject=0112171\n\nD evidence for AD_clf when A is presented=-0.08398606809985397\nC evidence for AC_clf when A is presented=-0.39685067053114337\nD evidence for CD_clf when A is presented=0.3083492418871271\nC evidence for CD_clf when A is presented=-0.3083492418871271\nceil\nA evidence in AC_clf when A is presented=0.39685067053114337\nA evidence in AD_clf when A is presented=0.08398606809985397\nevidence_ceil=0.24041836931549873\nfloor=-0.3083492418871271, ceil=0.24041836931549873\nmu=-0.03396543628581418, sig=0.23304213147724895\n---------------------------------------------------------------\n\nsubject=1207162\n\nD evidence for AD_clf when A is presented=0.0501038260561814\nC evidence for AC_clf when A is presented=0.0671101625543604\nD evidence for CD_clf when A is presented=-0.007039808378375289\nC evidence for CD_clf when A is presented=0.007039808378375289\nceil\nA evidence in AC_clf when A is presented=-0.0671101625543604\nA evidence in AD_clf when A is presented=-0.0501038260561814\nevidence_ceil=-0.05860699430527083\nfloor=0.007039808378375289, ceil=-0.05860699430527083\nmu=-0.02578359296344777, sig=-0.02787786762512575\n---------------------------------------------------------------\n\nsubject=0117171\n\nD evidence for AD_clf when A is presented=0.08630364479508822\nC evidence for AC_clf when A is presented=-0.4125088982145841\nD evidence for CD_clf when A is presented=0.3946784404562952\nC evidence for CD_clf when A is presented=-0.3946784404562952\nceil\nA evidence in AC_clf when A is presented=0.4125088982145841\nA evidence in AD_clf when A is presented=-0.08630364479508822\nevidence_ceil=0.16310262670974798\nfloor=-0.3946784404562952, ceil=0.16310262670974798\nmu=-0.1157879068732736, sig=0.236869826382726\n---------------------------------------------------------------\n\nsubject=0119174\n\nD evidence for AD_clf when A is presented=-0.08592125655002805\nC evidence for AC_clf when A is presented=-0.33118577819980866\nD evidence for CD_clf when A is presented=0.3404219633168125\nC evidence for CD_clf when A is presented=-0.3404219633168125\nceil\nA evidence in AC_clf when A is presented=0.33118577819980866\nA evidence in AD_clf when A is presented=0.08592125655002805\nevidence_ceil=0.20855351737491837\nfloor=-0.3404219633168125, ceil=0.20855351737491837\nmu=-0.06593422297094707, sig=0.23313040627302992\n---------------------------------------------------------------\n\nsubject=0112173\n\nD evidence for AD_clf when A is presented=-0.17147903598765182\nC evidence for AC_clf when A is presented=0.13629376597709592\nD evidence for CD_clf when A is presented=-0.16003539346363416\nC evidence for CD_clf when A is presented=0.16003539346363416\nceil\nA evidence in AC_clf when A is presented=-0.13629376597709592\nA evidence in AD_clf when A is presented=0.17147903598765182\nevidence_ceil=0.01759263500527793\nfloor=0.16003539346363416, ceil=0.01759263500527793\nmu=0.08881401423445605, sig=-0.06049038494069824\n---------------------------------------------------------------\n\nsubject=0112172\n\nD evidence for AD_clf when A is presented=-0.5329069158095847\nC evidence for AC_clf when A is presented=-0.6300600499795377\nD evidence for CD_clf when A is presented=-0.015923974858853485\nC evidence for CD_clf when A is presented=0.015923974858853485\nceil\nA evidence in AC_clf when A is presented=0.6300600499795377\nA evidence in AD_clf when A is presented=0.5329069158095847\nevidence_ceil=0.5814834828945612\nfloor=0.015923974858853485, ceil=0.5814834828945612\nmu=0.2987037288767073, sig=0.24017305420235593\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cbe286cfd89a49bd110a9ae754b7c9b99706dfe9
157,384
ipynb
Jupyter Notebook
05c - Transfer Learning (Tensorflow).ipynb
jschevers/ml-basics
54f598a5a9dd50993e2a19431af268b24e2eff11
[ "MIT" ]
null
null
null
05c - Transfer Learning (Tensorflow).ipynb
jschevers/ml-basics
54f598a5a9dd50993e2a19431af268b24e2eff11
[ "MIT" ]
null
null
null
05c - Transfer Learning (Tensorflow).ipynb
jschevers/ml-basics
54f598a5a9dd50993e2a19431af268b24e2eff11
[ "MIT" ]
null
null
null
210.688086
29,236
0.719273
[ [ [ "# Transfer Learning\n\nA Convolutional Neural Network (CNN) for image classification is made up of multiple layers that extract features, such as edges, corners, etc; and then use a final fully-connected layer to classify objects based on these features. You can visualize this like this:\n\n<table>\n <tr><td rowspan=2 style='border: 1px solid black;'>&#x21d2;</td><td style='border: 1px solid black;'>Convolutional Layer</td><td style='border: 1px solid black;'>Pooling Layer</td><td style='border: 1px solid black;'>Convolutional Layer</td><td style='border: 1px solid black;'>Pooling Layer</td><td style='border: 1px solid black;'>Fully Connected Layer</td><td rowspan=2 style='border: 1px solid black;'>&#x21d2;</td></tr>\n <tr><td colspan=4 style='border: 1px solid black; text-align:center;'>Feature Extraction</td><td style='border: 1px solid black; text-align:center;'>Classification</td></tr>\n</table>\n\n*Transfer Learning* is a technique where you can take an existing trained model and re-use its feature extraction layers, replacing its final classification layer with a fully-connected layer trained on your own custom images. With this technique, your model benefits from the feature extraction training that was performed on the base model (which may have been based on a larger training dataset than you have access to) to build a classification model for your own specific set of object classes.\n\nHow does this help? Well, think of it this way. Suppose you take a professional tennis player and a complete beginner, and try to teach them both how to play raquetball. It's reasonable to assume that the professional tennis player will be easier to train, because many of the underlying skills involved in raquetball are already learned. Similarly, a pre-trained CNN model may be easier to train to classify specific set of objects because it's already learned how to identify the features of common objects, such as edges and corners. Fundamentally, a pre-trained model can be a great way to produce an effective classifier even when you have limited data with which to train it.\n\nIn this notebook, we'll see how to implement transfer learning for a classification model using TensorFlow.", "_____no_output_____" ], [ "## Install and import TensorFlow libraries\n\nLet's start my ensuring that we have the latest version of the **TensorFlow** package installed and importing the Tensorflow libraries we're going to use.", "_____no_output_____" ] ], [ [ "!pip install --upgrade tensorflow", "Requirement already satisfied: tensorflow in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (2.5.0rc1)\nRequirement already satisfied: opt-einsum~=3.3.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (3.3.0)\nRequirement already satisfied: tensorflow-estimator<2.6.0,>=2.5.0rc0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (2.5.0rc0)\nRequirement already satisfied: termcolor~=1.1.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.1.0)\nRequirement already satisfied: grpcio~=1.34.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.34.1)\nRequirement already satisfied: keras-nightly~=2.5.0.dev in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (2.5.0.dev2021032900)\nRequirement already satisfied: tensorboard~=2.4 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (2.5.0)\nRequirement already satisfied: protobuf>=3.9.2 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (3.15.8)\nRequirement already satisfied: numpy~=1.19.2 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.19.5)\nRequirement already satisfied: six~=1.15.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.15.0)\nRequirement already satisfied: astunparse~=1.6.3 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.6.3)\nRequirement already satisfied: wheel~=0.35 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (0.36.2)\nRequirement already satisfied: absl-py~=0.10 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (0.12.0)\nRequirement already satisfied: wrapt~=1.12.1 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.12.1)\nRequirement already satisfied: keras-preprocessing~=1.1.2 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.1.2)\nRequirement already satisfied: flatbuffers~=1.12.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (1.12)\nRequirement already satisfied: typing-extensions~=3.7.4 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (3.7.4.3)\nRequirement already satisfied: google-pasta~=0.2 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (0.2.0)\nRequirement already satisfied: gast==0.4.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (0.4.0)\nRequirement already satisfied: h5py~=3.1.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorflow) (3.1.0)\nRequirement already satisfied: requests<3,>=2.21.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (2.25.1)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (1.8.0)\nRequirement already satisfied: setuptools>=41.0.0 in c:\\program files\\windowsapps\\pythonsoftwarefoundation.python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\\lib\\site-packages (from tensorboard~=2.4->tensorflow) (49.2.1)\nRequirement already satisfied: google-auth<2,>=1.6.3 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (1.29.0)\nRequirement already satisfied: markdown>=2.6.8 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (3.3.4)WARNING: You are using pip version 21.0.1; however, version 21.1 is available.\nYou should consider upgrading via the 'C:\\Users\\jesse\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\python.exe -m pip install --upgrade pip' command.\n\nRequirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (0.6.0)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (0.4.4)\nRequirement already satisfied: werkzeug>=0.11.15 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from tensorboard~=2.4->tensorflow) (1.0.1)\nRequirement already satisfied: rsa<5,>=3.1.4 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow) (4.7.2)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow) (0.2.8)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow) (4.2.1)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow) (1.3.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard~=2.4->tensorflow) (0.4.8)\nRequirement already satisfied: idna<3,>=2.5 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2.10)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (1.26.4)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (2020.12.5)\nRequirement already satisfied: chardet<5,>=3.0.2 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow) (4.0.0)\nRequirement already satisfied: oauthlib>=3.0.0 in c:\\users\\jesse\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\\localcache\\local-packages\\python39\\site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow) (3.1.0)\n" ], [ "import tensorflow\nfrom tensorflow import keras\nprint('TensorFlow version:',tensorflow.__version__)\nprint('Keras version:',keras.__version__)", "INFO:tensorflow:Enabling eager execution\nINFO:tensorflow:Enabling v2 tensorshape\nINFO:tensorflow:Enabling resource variables\nINFO:tensorflow:Enabling tensor equality\nINFO:tensorflow:Enabling control flow v2\nTensorFlow version: 2.5.0-rc1\nKeras version: 2.5.0\n" ] ], [ [ "## Prepare the base model\n\nTo use transfer learning, we need a base model from which we can use the trained feature extraction layers. The ***resnet*** model is an CNN-based image classifier that has been pre-trained using a huge dataset of 3-color channel images of 224x224 pixels. Let's create an instance of it with some pretrained weights, excluding its final (top) prediction layer.", "_____no_output_____" ] ], [ [ "base_model = keras.applications.resnet.ResNet50(weights='imagenet', include_top=False, input_shape=(224,224,3))\nprint(base_model.summary())", "0] \n__________________________________________________________________________________________________\nconv3_block4_out (Activation) (None, 28, 28, 512) 0 conv3_block4_add[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_conv (Conv2D) (None, 14, 14, 256) 131328 conv3_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_relu (Activation (None, 14, 14, 256) 0 conv4_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_relu (Activation (None, 14, 14, 256) 0 conv4_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_conv (Conv2D) (None, 14, 14, 1024) 525312 conv3_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_add (Add) (None, 14, 14, 1024) 0 conv4_block1_0_bn[0][0] \n conv4_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_out (Activation) (None, 14, 14, 1024) 0 conv4_block1_add[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block1_out[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_relu (Activation (None, 14, 14, 256) 0 conv4_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_relu (Activation (None, 14, 14, 256) 0 conv4_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_add (Add) (None, 14, 14, 1024) 0 conv4_block1_out[0][0] \n conv4_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_out (Activation) (None, 14, 14, 1024) 0 conv4_block2_add[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block2_out[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_relu (Activation (None, 14, 14, 256) 0 conv4_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_relu (Activation (None, 14, 14, 256) 0 conv4_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_add (Add) (None, 14, 14, 1024) 0 conv4_block2_out[0][0] \n conv4_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_out (Activation) (None, 14, 14, 1024) 0 conv4_block3_add[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block3_out[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_relu (Activation (None, 14, 14, 256) 0 conv4_block4_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block4_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_relu (Activation (None, 14, 14, 256) 0 conv4_block4_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block4_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block4_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_add (Add) (None, 14, 14, 1024) 0 conv4_block3_out[0][0] \n conv4_block4_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_out (Activation) (None, 14, 14, 1024) 0 conv4_block4_add[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_relu (Activation (None, 14, 14, 256) 0 conv4_block5_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block5_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_relu (Activation (None, 14, 14, 256) 0 conv4_block5_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block5_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block5_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_add (Add) (None, 14, 14, 1024) 0 conv4_block4_out[0][0] \n conv4_block5_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_out (Activation) (None, 14, 14, 1024) 0 conv4_block5_add[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block5_out[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_relu (Activation (None, 14, 14, 256) 0 conv4_block6_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block6_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_relu (Activation (None, 14, 14, 256) 0 conv4_block6_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block6_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block6_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_add (Add) (None, 14, 14, 1024) 0 conv4_block5_out[0][0] \n conv4_block6_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_out (Activation) (None, 14, 14, 1024) 0 conv4_block6_add[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_conv (Conv2D) (None, 7, 7, 512) 524800 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_relu (Activation (None, 7, 7, 512) 0 conv5_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_relu (Activation (None, 7, 7, 512) 0 conv5_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_conv (Conv2D) (None, 7, 7, 2048) 2099200 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_add (Add) (None, 7, 7, 2048) 0 conv5_block1_0_bn[0][0] \n conv5_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_out (Activation) (None, 7, 7, 2048) 0 conv5_block1_add[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block1_out[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_relu (Activation (None, 7, 7, 512) 0 conv5_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_relu (Activation (None, 7, 7, 512) 0 conv5_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_add (Add) (None, 7, 7, 2048) 0 conv5_block1_out[0][0] \n conv5_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_out (Activation) (None, 7, 7, 2048) 0 conv5_block2_add[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block2_out[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_relu (Activation (None, 7, 7, 512) 0 conv5_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_relu (Activation (None, 7, 7, 512) 0 conv5_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_add (Add) (None, 7, 7, 2048) 0 conv5_block2_out[0][0] \n conv5_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_out (Activation) (None, 7, 7, 2048) 0 conv5_block3_add[0][0] \n==================================================================================================\nTotal params: 23,587,712\nTrainable params: 23,534,592\nNon-trainable params: 53,120\n__________________________________________________________________________________________________\nNone\n" ] ], [ [ "## Prepare the image data\n\nThe pretrained model has many layers, starting with a convolutional layer that starts the feature extraction process from image data.\n\nFor feature extraction to work with our own images, we need to ensure that the image data we use the train our prediction layer has the same number of features (pixel values) as the images originally used to train the feature extraction layers, so we need data loaders for color images that are 224x224 pixels in size.\n\nTensorflow includes functions for loading and transforming data. We'll use these to create a generator for training data, and a second generator for test data (which we'll use to validate the trained model). The loaders will transform the image data to match the format used to train the original resnet CNN model and normalize them.\n\nRun the following cell to define the data generators and list the classes for our images.", "_____no_output_____" ] ], [ [ "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndata_folder = 'data/shapes'\npretrained_size = (224,224)\nbatch_size = 30\n\nprint(\"Getting Data...\")\ndatagen = ImageDataGenerator(rescale=1./255, # normalize pixel values\n validation_split=0.3) # hold back 30% of the images for validation\n\nprint(\"Preparing training dataset...\")\ntrain_generator = datagen.flow_from_directory(\n data_folder,\n target_size=pretrained_size, # resize to match model expected input\n batch_size=batch_size,\n class_mode='categorical',\n subset='training') # set as training data\n\nprint(\"Preparing validation dataset...\")\nvalidation_generator = datagen.flow_from_directory(\n data_folder,\n target_size=pretrained_size, # resize to match model expected input\n batch_size=batch_size,\n class_mode='categorical',\n subset='validation') # set as validation data\n\nclassnames = list(train_generator.class_indices.keys())\nprint(\"class names: \", classnames)", "Getting Data...\nPreparing training dataset...\nFound 840 images belonging to 3 classes.\nPreparing validation dataset...\nFound 360 images belonging to 3 classes.\nclass names: ['circle', 'square', 'triangle']\n" ] ], [ [ "## Create a prediction layer\n\nWe downloaded the complete *resnet* model excluding its final prediction layer, so need to combine these layers with a fully-connected (*dense*) layer that takes the flattened outputs from the feature extraction layers and generates a prediction for each of our image classes.\n\nWe also need to freeze the feature extraction layers to retain the trained weights. Then when we train the model using our images, only the final prediction layer will learn new weight and bias values - the pre-trained weights already learned for feature extraction will remain the same.", "_____no_output_____" ] ], [ [ "from tensorflow.keras import applications\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Flatten, Dense\n\n# Freeze the already-trained layers in the base model\nfor layer in base_model.layers:\n layer.trainable = False\n\n# Create prediction layer for classification of our images\nx = base_model.output\nx = Flatten()(x)\nprediction_layer = Dense(len(classnames), activation='softmax')(x) \nmodel = Model(inputs=base_model.input, outputs=prediction_layer)\n\n# Compile the model\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n# Now print the full model, which will include the layers of the base model plus the dense layer we added\nprint(model.summary())", " \n__________________________________________________________________________________________________\nconv4_block1_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_1_relu (Activation (None, 14, 14, 256) 0 conv4_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_2_relu (Activation (None, 14, 14, 256) 0 conv4_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_conv (Conv2D) (None, 14, 14, 1024) 525312 conv3_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block1_0_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block1_add (Add) (None, 14, 14, 1024) 0 conv4_block1_0_bn[0][0] \n conv4_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block1_out (Activation) (None, 14, 14, 1024) 0 conv4_block1_add[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block1_out[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_1_relu (Activation (None, 14, 14, 256) 0 conv4_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_2_relu (Activation (None, 14, 14, 256) 0 conv4_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block2_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block2_add (Add) (None, 14, 14, 1024) 0 conv4_block1_out[0][0] \n conv4_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block2_out (Activation) (None, 14, 14, 1024) 0 conv4_block2_add[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block2_out[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_1_relu (Activation (None, 14, 14, 256) 0 conv4_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_2_relu (Activation (None, 14, 14, 256) 0 conv4_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block3_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block3_add (Add) (None, 14, 14, 1024) 0 conv4_block2_out[0][0] \n conv4_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block3_out (Activation) (None, 14, 14, 1024) 0 conv4_block3_add[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block3_out[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_1_relu (Activation (None, 14, 14, 256) 0 conv4_block4_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block4_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block4_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_2_relu (Activation (None, 14, 14, 256) 0 conv4_block4_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block4_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block4_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block4_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block4_add (Add) (None, 14, 14, 1024) 0 conv4_block3_out[0][0] \n conv4_block4_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block4_out (Activation) (None, 14, 14, 1024) 0 conv4_block4_add[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block4_out[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_1_relu (Activation (None, 14, 14, 256) 0 conv4_block5_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block5_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block5_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_2_relu (Activation (None, 14, 14, 256) 0 conv4_block5_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block5_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block5_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block5_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block5_add (Add) (None, 14, 14, 1024) 0 conv4_block4_out[0][0] \n conv4_block5_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block5_out (Activation) (None, 14, 14, 1024) 0 conv4_block5_add[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_conv (Conv2D) (None, 14, 14, 256) 262400 conv4_block5_out[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_1_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_1_relu (Activation (None, 14, 14, 256) 0 conv4_block6_1_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_conv (Conv2D) (None, 14, 14, 256) 590080 conv4_block6_1_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_bn (BatchNormali (None, 14, 14, 256) 1024 conv4_block6_2_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_2_relu (Activation (None, 14, 14, 256) 0 conv4_block6_2_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_conv (Conv2D) (None, 14, 14, 1024) 263168 conv4_block6_2_relu[0][0] \n__________________________________________________________________________________________________\nconv4_block6_3_bn (BatchNormali (None, 14, 14, 1024) 4096 conv4_block6_3_conv[0][0] \n__________________________________________________________________________________________________\nconv4_block6_add (Add) (None, 14, 14, 1024) 0 conv4_block5_out[0][0] \n conv4_block6_3_bn[0][0] \n__________________________________________________________________________________________________\nconv4_block6_out (Activation) (None, 14, 14, 1024) 0 conv4_block6_add[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_conv (Conv2D) (None, 7, 7, 512) 524800 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_1_relu (Activation (None, 7, 7, 512) 0 conv5_block1_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block1_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block1_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_2_relu (Activation (None, 7, 7, 512) 0 conv5_block1_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_conv (Conv2D) (None, 7, 7, 2048) 2099200 conv4_block6_out[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block1_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block1_0_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_0_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block1_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block1_add (Add) (None, 7, 7, 2048) 0 conv5_block1_0_bn[0][0] \n conv5_block1_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block1_out (Activation) (None, 7, 7, 2048) 0 conv5_block1_add[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block1_out[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_1_relu (Activation (None, 7, 7, 512) 0 conv5_block2_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block2_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block2_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_2_relu (Activation (None, 7, 7, 512) 0 conv5_block2_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block2_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block2_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block2_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block2_add (Add) (None, 7, 7, 2048) 0 conv5_block1_out[0][0] \n conv5_block2_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block2_out (Activation) (None, 7, 7, 2048) 0 conv5_block2_add[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_conv (Conv2D) (None, 7, 7, 512) 1049088 conv5_block2_out[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_1_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_1_relu (Activation (None, 7, 7, 512) 0 conv5_block3_1_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_conv (Conv2D) (None, 7, 7, 512) 2359808 conv5_block3_1_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_bn (BatchNormali (None, 7, 7, 512) 2048 conv5_block3_2_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_2_relu (Activation (None, 7, 7, 512) 0 conv5_block3_2_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_conv (Conv2D) (None, 7, 7, 2048) 1050624 conv5_block3_2_relu[0][0] \n__________________________________________________________________________________________________\nconv5_block3_3_bn (BatchNormali (None, 7, 7, 2048) 8192 conv5_block3_3_conv[0][0] \n__________________________________________________________________________________________________\nconv5_block3_add (Add) (None, 7, 7, 2048) 0 conv5_block2_out[0][0] \n conv5_block3_3_bn[0][0] \n__________________________________________________________________________________________________\nconv5_block3_out (Activation) (None, 7, 7, 2048) 0 conv5_block3_add[0][0] \n__________________________________________________________________________________________________\nflatten (Flatten) (None, 100352) 0 conv5_block3_out[0][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 3) 301059 flatten[0][0] \n==================================================================================================\nTotal params: 23,888,771\nTrainable params: 301,059\nNon-trainable params: 23,587,712\n__________________________________________________________________________________________________\nNone\n" ] ], [ [ "## Train the Model\n\nWith the layers of the CNN defined, we're ready to train it using our image data. The weights used in the feature extraction layers from the base resnet model will not be changed by training, only the final dense layer that maps the features to our shape classes will be trained.", "_____no_output_____" ] ], [ [ "# Train the model over 3 epochs\nnum_epochs = 3\nhistory = model.fit(\n train_generator,\n steps_per_epoch = train_generator.samples // batch_size,\n validation_data = validation_generator, \n validation_steps = validation_generator.samples // batch_size,\n epochs = num_epochs)", "Epoch 1/3\n28/28 [==============================] - 71s 2s/step - loss: 4.2911 - accuracy: 0.4196 - val_loss: 0.7904 - val_accuracy: 0.6667\nEpoch 2/3\n28/28 [==============================] - 64s 2s/step - loss: 0.5436 - accuracy: 0.7702 - val_loss: 0.2246 - val_accuracy: 0.8917\nEpoch 3/3\n28/28 [==============================] - 65s 2s/step - loss: 0.1884 - accuracy: 0.9335 - val_loss: 0.1169 - val_accuracy: 0.9694\n" ] ], [ [ "## View the loss history\n\nWe tracked average training and validation loss for each epoch. We can plot these to verify that the loss reduced over the training process and to detect *over-fitting* (which is indicated by a continued drop in training loss after validation loss has levelled out or started to increase).", "_____no_output_____" ] ], [ [ "%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nepoch_nums = range(1,num_epochs+1)\ntraining_loss = history.history[\"loss\"]\nvalidation_loss = history.history[\"val_loss\"]\nplt.plot(epoch_nums, training_loss)\nplt.plot(epoch_nums, validation_loss)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(['training', 'validation'], loc='upper right')\nplt.show()", "_____no_output_____" ] ], [ [ "## Evaluate model performance\n\nWe can see the final accuracy based on the test data, but typically we'll want to explore performance metrics in a little more depth. Let's plot a confusion matrix to see how well the model is predicting each class.", "_____no_output_____" ] ], [ [ "# Tensorflow doesn't have a built-in confusion matrix metric, so we'll use SciKit-Learn\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nprint(\"Generating predictions from validation data...\")\n# Get the image and label arrays for the first batch of validation data\nx_test = validation_generator[0][0]\ny_test = validation_generator[0][1]\n\n# Use the model to predict the class\nclass_probabilities = model.predict(x_test)\n\n# The model returns a probability value for each class\n# The one with the highest probability is the predicted class\npredictions = np.argmax(class_probabilities, axis=1)\n\n# The actual labels are hot encoded (e.g. [0 1 0], so get the one with the value 1\ntrue_labels = np.argmax(y_test, axis=1)\n\n# Plot the confusion matrix\ncm = confusion_matrix(true_labels, predictions)\nplt.imshow(cm, interpolation=\"nearest\", cmap=plt.cm.Blues)\nplt.colorbar()\ntick_marks = np.arange(len(classnames))\nplt.xticks(tick_marks, classnames, rotation=85)\nplt.yticks(tick_marks, classnames)\nplt.xlabel(\"Predicted Shape\")\nplt.ylabel(\"Actual Shape\")\nplt.show()", "Generating predictions from validation data...\n" ] ], [ [ "## Use the trained model\n\nNow that we've trained the model, we can use it to predict the class of an image.", "_____no_output_____" ] ], [ [ "from tensorflow.keras import models\nimport numpy as np\nfrom random import randint\nimport os\n%matplotlib inline\n\n# Function to predict the class of an image\ndef predict_image(classifier, image):\n from tensorflow import convert_to_tensor\n # The model expects a batch of images as input, so we'll create an array of 1 image\n imgfeatures = img.reshape(1, img.shape[0], img.shape[1], img.shape[2])\n\n # We need to format the input to match the training data\n # The generator loaded the values as floating point numbers\n # and normalized the pixel values, so...\n imgfeatures = imgfeatures.astype('float32')\n imgfeatures /= 255\n \n # Use the model to predict the image class\n class_probabilities = classifier.predict(imgfeatures)\n \n # Find the class predictions with the highest predicted probability\n index = int(np.argmax(class_probabilities, axis=1)[0])\n return index\n\n# Function to create a random image (of a square, circle, or triangle)\ndef create_image (size, shape):\n from random import randint\n import numpy as np\n from PIL import Image, ImageDraw\n \n xy1 = randint(10,40)\n xy2 = randint(60,100)\n col = (randint(0,200), randint(0,200), randint(0,200))\n\n img = Image.new(\"RGB\", size, (255, 255, 255))\n draw = ImageDraw.Draw(img)\n \n if shape == 'circle':\n draw.ellipse([(xy1,xy1), (xy2,xy2)], fill=col)\n elif shape == 'triangle':\n draw.polygon([(xy1,xy1), (xy2,xy2), (xy2,xy1)], fill=col)\n else: # square\n draw.rectangle([(xy1,xy1), (xy2,xy2)], fill=col)\n del draw\n \n return np.array(img)\n\n# Create a random test image\nclassnames = os.listdir(os.path.join('data', 'shapes'))\nclassnames.sort()\nimg = create_image ((224,224), classnames[randint(0, len(classnames)-1)])\nplt.axis('off')\nplt.imshow(img)\n\n# Use the classifier to predict the class\nclass_idx = predict_image(model, img)\nprint (classnames[class_idx])", "square\n" ] ], [ [ "## Learn More\n\n* [Tensorflow Documentation](https://www.tensorflow.org/tutorials/images/transfer_learning)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe29480f0a2ca19ab75241341a80d3ecc04e00a
28,465
ipynb
Jupyter Notebook
code/MICE_Difference_WT_KO_DKO_in_HFD.ipynb
menchelab/Marco
a8f35f761cc2aec973af1fe42fa35d907e5918c6
[ "MIT" ]
null
null
null
code/MICE_Difference_WT_KO_DKO_in_HFD.ipynb
menchelab/Marco
a8f35f761cc2aec973af1fe42fa35d907e5918c6
[ "MIT" ]
null
null
null
code/MICE_Difference_WT_KO_DKO_in_HFD.ipynb
menchelab/Marco
a8f35f761cc2aec973af1fe42fa35d907e5918c6
[ "MIT" ]
null
null
null
37.257853
190
0.453083
[ [ [ "# Check Lipid differences in WT, KO and DKO\n- Show if some Lipids are particularly high in one of the three categories", "_____no_output_____" ], [ "### Included libraries", "_____no_output_____" ] ], [ [ "from matplotlib import cm\nfrom matplotlib.lines import Line2D\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom matplotlib import pylab as plt\nimport numpy as np\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "### Functions and definitions", "_____no_output_____" ] ], [ [ "#define classes of lipids e.g. PC = Phosphatidylcholines\ntypes_of_Lipids = ['CE','Cer','DAG','LPC','LPE','PC','PE','PI','PS','SM','TAG']\n\n#colormap (20 unique colors)\ncmap = cm.get_cmap('tab20')\n\n#assign for each class of lipid a unique color\nlipid_color = {}\nfor i,l in enumerate(types_of_Lipids):\n lipid_color[l] = cmap(i)", "_____no_output_____" ] ], [ [ "### Main Code", "_____no_output_____" ] ], [ [ "#Load the actual lipid results\nLipidData = pd.read_excel('../data/Report_MEC025_LIPID01_jb.xlsx' ,header=2, na_values='<LOD')", "_____no_output_____" ], [ "#extract the lipids\ncolumns = LipidData.columns\nLipids = columns[7:]\nprint (Lipids)", "Index(['CE 16:0', 'CE 16:1', 'CE 18:0', 'CE 18:1', 'CE 18:2', 'CE 18:3',\n 'CE 20:0', 'CE 20:3', 'CE 20:4', 'CE 20:5',\n ...\n 'TAG 54:5', 'TAG 54:6', 'TAG 55:1', 'TAG 55:3', 'TAG 56:1', 'TAG 56:4',\n 'TAG 56:7', 'TAG 57:1', 'TAG 58:8', 'TAG 58:9'],\n dtype='object', length=283)\n" ], [ "#the those columns/entry for serum results (NOT Cells) as well as WT, PTEN and DKO (all HFD)\ndata = LipidData.loc[(LipidData['Specimen'] == 'serum') & ((LipidData['Experiment'] == 'WT_HFD') | (LipidData['Experiment'] == 'PTEN_HFD') | (LipidData['Experiment'] == 'DKO_HFD'))]\n\n#remove entries that have no values\ndata = data.dropna(axis=1,how='all')\ndata.head(12)", "_____no_output_____" ], [ "#remaining lipids contains all valid columns (=lipids)\nremaining_Lipids = data.columns.values[7:]\nprint ('Number of remaining Lipids: %d' %len(remaining_Lipids))", "Number of remaining Lipids: 202\n" ], [ "# Make bar plot Lipids together\nfp_out = open('../results/Difference_WT_KO_DKO_Serum/Normalization.csv','w')\nfp_out.write('Lipid,Mean_WT,Normalized_WT,Mean_KO,Normalized_KO,Mean_DKO,Normalized_DKO,Max_Val,Min_Val\\n')\n\n#dictionary that contins the results for WT, KO (=PTEN) and DKO (=PTEN and MARCO KO)\nLipid_Group_Results = {'WT':{},'KO':{},'DKO':{}}\n\n#possible groups contains the lipid classses\npossible_groups = set()\n\n#go through all lipids\nfor Lipid in remaining_Lipids:\n \n \n # get the lipid replicates for the three groups (remove emtpy rows)\n #WT\n WT_values = data.loc[data['Experiment'] == 'WT_HFD'][Lipid]\n WT_values = WT_values.dropna()\n #PTEN\n KO_values = data.loc[data['Experiment'] == 'PTEN_HFD'][Lipid]\n KO_values = KO_values.dropna()\n #DKO\n DKO_values = data.loc[data['Experiment'] == 'DKO_HFD'][Lipid]\n DKO_values = DKO_values.dropna()\n \n #Only make analaysis if all three groups have at least one entry (=replicate)\n if len(WT_values) > 0 and len(KO_values) > 0 and len(DKO_values) > 0: \n \n #calculate the mean for the three groups\n WT_values = WT_values.mean()\n KO_values = KO_values.mean()\n DKO_values = DKO_values.mean()\n \n #extract Max/Min of the three means\n max_Val = max([WT_values,KO_values,DKO_values])\n min_Val = min([WT_values,KO_values,DKO_values])\n\n #normalize between this max/min (so that one value is always zero and one will be always 1 and the other in between)\n WT_values_norm = (WT_values-min_Val)/(max_Val-min_Val)\n KO_values_norm = (KO_values-min_Val)/(max_Val-min_Val)\n DKO_values_norm = (DKO_values-min_Val)/(max_Val-min_Val)\n\n #write results\n fp_out.write(Lipid+','+str(WT_values)+','+str(WT_values_norm)+','+\n str(KO_values)+','+str(KO_values_norm)+','+\n str(DKO_values)+','+str(DKO_values_norm)+','+\n str(max_Val)+','+str(min_Val)+'\\n')\n\n #if the result dictionary does not have an entry for this lipid class then add to dictionary\n if Lipid.split(' ')[0] not in Lipid_Group_Results['WT']:\n Lipid_Group_Results['WT'][Lipid.split(' ')[0]] = []\n if Lipid.split(' ')[0] not in Lipid_Group_Results['KO']:\n Lipid_Group_Results['KO'][Lipid.split(' ')[0]] = []\n if Lipid.split(' ')[0] not in Lipid_Group_Results['DKO'] :\n Lipid_Group_Results['DKO'][Lipid.split(' ')[0]] = []\n\n #add lipid class to set of all possible lipid classes\n possible_groups.add(Lipid.split(' ')[0])\n\n #write results\n Lipid_Group_Results['WT'][Lipid.split(' ')[0]].append(WT_values_norm)\n Lipid_Group_Results['KO'][Lipid.split(' ')[0]].append(KO_values_norm)\n Lipid_Group_Results['DKO'][Lipid.split(' ')[0]].append(DKO_values_norm)\n\n#close file\nfp_out.close() ", "_____no_output_____" ], [ "# Make actual plot\n##\n\n#create legend entries\nlegend_elements = []\nfor key in possible_groups:\n legend_elements.append(Line2D([0], [0], marker='o', color='w', label=key,\n markerfacecolor=lipid_color[key], markersize=10))\n\n#list of means (go throug the results to calculate actual mean (per lipid class))\nWT_means = []\nKO_means = []\nDKO_means = []\n\n#go through all lipid groups\nfor key in possible_groups:\n #make plot showing the mean results for each this lipid group (no errorbars)\n plt.errorbar([0,1,2,3,4,5],[np.mean(Lipid_Group_Results['WT'][key]),np.mean(Lipid_Group_Results['WT'][key]),\n np.mean(Lipid_Group_Results['KO'][key]), np.mean(Lipid_Group_Results['KO'][key]),\n np.mean(Lipid_Group_Results['DKO'][key]), np.mean(Lipid_Group_Results['DKO'][key])], \n \n #assign assocaited color\n color=lipid_color[key], alpha=0.8,lw=1.5)\n \n #add result to result lise\n WT_means.append(np.mean(Lipid_Group_Results['WT'][key]))\n KO_means.append(np.mean(Lipid_Group_Results['KO'][key]))\n DKO_means.append(np.mean(Lipid_Group_Results['DKO'][key]))\n \n #create legend element\n plt.legend(handles=legend_elements, loc='right',prop={'size': 5})\n\n\n#plot the averall mean (over all lipids, blask dashed line) \nplt.plot([0,1,2,3,4,5],[np.mean(WT_means),np.mean(WT_means),\n np.mean(KO_means), np.mean(KO_means),\n np.mean(DKO_means), np.mean(DKO_means)], \n\n color='black', alpha=1,ls = '--', lw=2,zorder=100)\n\n\n#Plot actual plot \nplt.ylabel('Mean Normalized Relative Abundance')\nplt.xlabel('Condition')\nplt.xticks([0.5,2.5,4.5],['WT','KO','DKO'])\nplt.savefig('../results/Difference_WT_KO_DKO_Serum/LipidGroups.pdf')\nplt.close()\n", "_____no_output_____" ] ], [ [ "### Additional plot as heatmap showing lipids", "_____no_output_____" ] ], [ [ "\n#lists for data to plot\ndata = []\ndata_allLipids = []\ncol_colors = []\n\n#go through all lipid groups to define correct color\nfor key in possible_groups:\n for lipid in Lipid_Group_Results['WT'][key]:\n col_colors.append(lipid_color[key])\n\n#calculate mean expression for this lipid\nfor group in ['WT','KO','DKO']:\n tmp = []\n tmp_allLipids = []\n for key in possible_groups:\n tmp.append(np.mean(Lipid_Group_Results[group][key]))\n for lipid in Lipid_Group_Results[group][key]:\n tmp_allLipids.append(lipid)\n \n data.append(tmp)\n data_allLipids.append(tmp_allLipids)\n \n#Make heatmap for LIPIDGROUPS\nsns.heatmap(data=data)\nplt.xlabel('Lipid Group')\nplt.ylabel('Category')\nplt.xticks([x-0.5 for x in range(1,len(possible_groups)+1)],possible_groups)\nplt.yticks([0.5,1.5,2.5],['WT','PTEN','DKO'])\nplt.savefig('../results/Difference_WT_KO_DKO_Serum/LipidGroups_Heatmap.pdf')\nplt.close()\n\n\n#Make heatmap for LIPIDS INDIVIDUALLY\nsns.heatmap(data=data_allLipids)\nplt.xlabel('Lipid')\nplt.ylabel('Category')\nplt.yticks([0.5,1.5,2.5],['WT','PTEN','DKO'])\nplt.xticks()\nplt.savefig('../results/Difference_WT_KO_DKO_Serum/Lipid_Heatmap.pdf')\nplt.close()\n\n\n#Make clustermap for LIPIDS INDIVIDUALLY\nsns.clustermap(data=data_allLipids,row_cluster=True, col_colors=col_colors,yticklabels=['WT','PTEN','DKO'], method='weighted', )\nplt.savefig('../results/Difference_WT_KO_DKO_Serum/Lipid_Clustermap.pdf')\nplt.close()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe295df911bc7900fde15732712c6b14d7fc834
4,212
ipynb
Jupyter Notebook
section3/3-2-3(stream data, key and value).ipynb
IzPerfect/Python-WebCrawling
e3a16e0e9de280851898323b625fc65fc7ec8ad1
[ "MIT" ]
null
null
null
section3/3-2-3(stream data, key and value).ipynb
IzPerfect/Python-WebCrawling
e3a16e0e9de280851898323b625fc65fc7ec8ad1
[ "MIT" ]
null
null
null
section3/3-2-3(stream data, key and value).ipynb
IzPerfect/Python-WebCrawling
e3a16e0e9de280851898323b625fc65fc7ec8ad1
[ "MIT" ]
null
null
null
19.232877
63
0.431624
[ [ [ "import sys\nimport io\nimport requests, json", "_____no_output_____" ] ], [ [ "stream은 json파일과 비슷하지만 그렇지 않다.", "_____no_output_____" ] ], [ [ "s = requests.Session()\n\nr = s.get('http://httpbin.org/stream/20', stream=True)\n#print(r.text)\nprint(r.encoding)\n#print(r.json())", "None\n" ] ], [ [ "인코딩이 되어 있지 않으면 utf-8로 실행", "_____no_output_____" ] ], [ [ "if r.encoding is None:\n r.encoding = 'utf-8'", "_____no_output_____" ], [ "for line in r.iter_lines(decode_unicode=True):\n #print(line)\n b = json.loads(line) #dict\n for e in b.keys():\n print(\"key:\",e)\n #print(\"values:\",b[e])", "key: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\nkey: url\nkey: args\nkey: id\nkey: origin\nkey: headers\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe296d383a2e507d36b5ad81dedd3b975801311
124,159
ipynb
Jupyter Notebook
_notebooks/2020-12-21-Image_Processing.ipynb
simsisim/sims-blog
5355a6fe2462279338ad01d585e1da651f321d74
[ "Apache-2.0" ]
1
2020-12-23T21:00:39.000Z
2020-12-23T21:00:39.000Z
_notebooks/2020-12-21-Image_Processing.ipynb
simsisim/sims-blog
5355a6fe2462279338ad01d585e1da651f321d74
[ "Apache-2.0" ]
3
2020-12-20T19:29:31.000Z
2022-02-26T10:23:16.000Z
_notebooks/2020-12-21-Image_Processing.ipynb
simsisim/sims-blog
5355a6fe2462279338ad01d585e1da651f321d74
[ "Apache-2.0" ]
null
null
null
294.21564
35,656
0.932893
[ [ [ "# Image Processing Dense Array, JPEG, PNG\n> In this post, we will cover the basics of working with images in Matplotlib, OpenCV and Keras.\n\n- toc: true \n- badges: true\n- comments: true\n- categories: [Image Processing, Computer Vision]\n- image: images/freedom.png", "_____no_output_____" ], [ "Images are dense matrixes, and have a certain numbers of rows and columns. They can have 1 (grey) or 3 (RGB) or 4 (RGB + alpha-transparency) channels. \n\nThe dimension of the image matrix is ( height, width, channels).", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom PIL import Image\nimport cv2\nfrom sys import getsizeof\nimport tensorflow as tf", "_____no_output_____" ] ], [ [ "# 1. Load image files (*.jpg, *.png, *.bmp, *.tif)\n\n - ~~using PIL~~\n - using matplotlib: reads image as RGB\n - using cv2 : reads image as BRG\n \n \n - imread: reads a file from disk and decodes it\n - imsave: encodes a image and writes it to a file on disk ", "_____no_output_____" ] ], [ [ "#using PIL\n#image = Image.open(\"images/freedom.png\")\n#plt.show(image)", "_____no_output_____" ] ], [ [ "#### Load image using Matplotlib\nThe Matplotlib image tutorial recommends using matplotlib.image.imread to read image formats from disk. This function will automatically change image array values to floats between zero and one, and it doesn't give any other options about how to read the image.\n\n - imshow works on 0-1 floats & 0-255 uint8 values\n - It doesn't work on int!", "_____no_output_____" ] ], [ [ "#using matplotlib.image\nimage = mpimg.imread(\"images/freedom.png\")\nplt.imshow(image)\nplt.colorbar()", "_____no_output_____" ], [ "print(image.dtype)\nfreedom_array_uint8 = (image*255).astype(np.uint8) #convert to 0-255 values", "float32\n" ] ], [ [ "#### Load image using OpenCV", "_____no_output_____" ] ], [ [ "#using opencv\nimage = cv2.imread(\"images/freedom.png\")\n#OpenCV uses BGR as its default colour order for images, matplotlib uses RGB \nRGB_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)# cv2.cvtColor() method is used to convert an image from one color space to another\nplt.imshow(RGB_image)\nplt.colorbar()", "_____no_output_____" ] ], [ [ "For this image, the matrix will have 600 x 400 x 3 = 720,000 values. Each value is an unsigned 8-bit integer, in total 720,000 bytes.\n\nUsing unsigned 8-bit integers (256 possible values) for each value in the image array is enough for displaying images to humans. But when working with image data, it isn't uncommon to switch to 32-bit floats, for example. This increases tremendously the size of the data.\n\nBy loading the image files we can save them as arrays. Typical array operations can be performed on them. ", "_____no_output_____" ] ], [ [ "print (RGB_image.shape, RGB_image.dtype)", "(600, 400, 3) uint8\n" ] ], [ [ "### Load image using keras.preprocessing.image\n\n - load_img(image): loads and decodes image\n - img_to_array(image)", "_____no_output_____" ] ], [ [ "image_keras = tf.keras.preprocessing.image.load_img(\"images/freedom.png\") # loads and decodes image\nprint(type(image_keras))\nprint(image_keras.format)\nprint(image_keras.mode)\nprint(image_keras.size)\n#image_keras.show()", "<class 'PIL.Image.Image'>\nNone\nRGB\n(400, 600)\n" ] ], [ [ "# 2. Image Processing", "_____no_output_____" ], [ "#### Dense Array\n\nOne way to store complete raster image data is by serializing a NumPy array to disk.\n\nimage04npy = 720,128 bytes\n\nThe file image04npy has 128 more bytes than the one required to store the array values. Those extra bytes specify things like the array shape/dimensions. ", "_____no_output_____" ] ], [ [ "np.save(\"images/freedom.npy\", RGB_image)\nfreedomnpy = np.load('images/freedom.npy')\nprint(\"Size of array:\", freedomnpy.nbytes)\nprint(\"Size of disk:\", getsizeof(freedomnpy))", "Size of array: 720000\nSize of disk: 720128\n" ] ], [ [ "Storing one pixels takes several bytes.There are two main options for saving images: whether to lose some information while saving, or not. ", "_____no_output_____" ], [ "#### JPG format \n\n - JPEG is lossy by deflaut\n\n - When saving an image as $*$.JPEG and read from it again, it is not necessary to get back the same values\n \n - The \"image04_jpg.jpg\" has 6.3 kB, less than the 7\\% of $*$.npy file that generated it\n \n - cv2.IMWRITE_JPEG_QUALITY is between (0, 100), and allows to save losseless", "_____no_output_____" ] ], [ [ "cv2.imwrite(\"images/freedom_jpg.jpg\", freedomnpy, [cv2.IMWRITE_JPEG_QUALITY, 0])\nfreedom_jpg = cv2.imread(\"images/freedom_jpg.jpg\") \nplt.imshow(freedom_jpg)", "_____no_output_____" ] ], [ [ "#### PNG format \n\n - PNG is lossless\n\n - When saving an image as $*$.PNG and read from it again one gets the same value backs\n \n - cv2.IMWRITE_PNG_COMPRESSION is between (0, 1): bigger file, slower compression\n \n - freedom_png.png = 721.8 kB, close to freedomnpy ", "_____no_output_____" ] ], [ [ "cv2.imwrite(\"images/freedom_png.png\", freedomnpy, [cv2.IMWRITE_PNG_COMPRESSION, 0])\nfreedom_png = cv2.imread(\"images/freedom_png.png\") \nplt.imshow(freedom_png)", "_____no_output_____" ] ], [ [ "References:\n\n<https://planspace.org/20170403-images_and_tfrecords/>\n\n<https://subscription.packtpub.com/book/application_development/9781788474443/1/ch01lvl1sec14/saving-images-using-lossy-and-lossless-compression>\n\n<https://www.tensorflow.org/tutorials/load_data/tfrecord>\n\n<https://machinelearningmastery.com/how-to-load-convert-and-save-images-with-the-keras-api/>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe2d5da3a507b754ace8533e51a23924639ed26
26,593
ipynb
Jupyter Notebook
contrib/fairness/fairlearn-azureml-mitigation.ipynb
lobrien/MachineLearningNotebooks
a56b69448c070b243125b66c303ba670a5a157c7
[ "MIT" ]
2
2021-04-16T08:24:28.000Z
2021-11-21T13:23:19.000Z
contrib/fairness/fairlearn-azureml-mitigation.ipynb
lobrien/MachineLearningNotebooks
a56b69448c070b243125b66c303ba670a5a157c7
[ "MIT" ]
null
null
null
contrib/fairness/fairlearn-azureml-mitigation.ipynb
lobrien/MachineLearningNotebooks
a56b69448c070b243125b66c303ba670a5a157c7
[ "MIT" ]
3
2021-06-22T11:38:12.000Z
2022-02-28T03:50:14.000Z
42.616987
1,002
0.591735
[ [ [ "Copyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the MIT License.", "_____no_output_____" ], [ "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/contrib/fairness/fairlearn-azureml-mitigation.png)", "_____no_output_____" ], [ "# Unfairness Mitigation with Fairlearn and Azure Machine Learning\n**This notebook shows how to upload results from Fairlearn's GridSearch mitigation algorithm into a dashboard in Azure Machine Learning Studio**\n\n## Table of Contents\n\n1. [Introduction](#Introduction)\n1. [Loading the Data](#LoadingData)\n1. [Training an Unmitigated Model](#UnmitigatedModel)\n1. [Mitigation with GridSearch](#Mitigation)\n1. [Uploading a Fairness Dashboard to Azure](#AzureUpload)\n 1. Registering models\n 1. Computing Fairness Metrics\n 1. Uploading to Azure\n1. [Conclusion](#Conclusion)\n\n<a id=\"Introduction\"></a>\n## Introduction\nThis notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.github.io) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.github.io/).\n\nWe will apply the [grid search algorithm](https://fairlearn.github.io/master/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n\n### Setup\n\nTo use this notebook, an Azure Machine Learning workspace is required.\nPlease see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\nThis notebook also requires the following packages:\n* `azureml-contrib-fairness`\n* `fairlearn==0.4.6` (v0.5.0 will work with minor modifications)\n* `joblib`\n* `shap`\n\nFairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:", "_____no_output_____" ] ], [ [ "# !pip install --upgrade scikit-learn>=0.22.1", "_____no_output_____" ] ], [ [ "Finally, please ensure that when you downloaded this notebook, you also downloaded the `fairness_nb_utils.py` file from the same location, and placed it in the same directory as this notebook.", "_____no_output_____" ], [ "<a id=\"LoadingData\"></a>\n## Loading the Data\nWe use the well-known `adult` census dataset, which we will fetch from the OpenML website. We start with a fairly unremarkable set of imports:", "_____no_output_____" ] ], [ [ "from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\nfrom fairlearn.widget import FairlearnDashboard\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import make_column_selector as selector\nfrom sklearn.pipeline import Pipeline\n\nimport pandas as pd", "_____no_output_____" ] ], [ [ "We can now load and inspect the data:", "_____no_output_____" ] ], [ [ "from fairness_nb_utils import fetch_openml_with_retries\n\ndata = fetch_openml_with_retries(data_id=1590)\n \n# Extract the items we want\nX_raw = data.data\ny = (data.target == '>50K') * 1\n\nX_raw[\"race\"].value_counts().to_dict()", "_____no_output_____" ] ], [ [ "We are going to treat the sex and race of each individual as protected attributes, and in this particular case we are going to remove these attributes from the main data (this is not always the best option - see the [Fairlearn website](http://fairlearn.github.io/) for further discussion). Protected attributes are often denoted by 'A' in the literature, and we follow that convention here:", "_____no_output_____" ] ], [ [ "A = X_raw[['sex','race']]\nX_raw = X_raw.drop(labels=['sex', 'race'],axis = 1)", "_____no_output_____" ] ], [ [ "We now preprocess our data. To avoid the problem of data leakage, we split our data into training and test sets before performing any other transformations. Subsequent transformations (such as scalings) will be fit to the training data set, and then applied to the test dataset.", "_____no_output_____" ] ], [ [ "(X_train, X_test, y_train, y_test, A_train, A_test) = train_test_split(\n X_raw, y, A, test_size=0.3, random_state=12345, stratify=y\n)\n\n# Ensure indices are aligned between X, y and A,\n# after all the slicing and splitting of DataFrames\n# and Series\n\nX_train = X_train.reset_index(drop=True)\nX_test = X_test.reset_index(drop=True)\ny_train = y_train.reset_index(drop=True)\ny_test = y_test.reset_index(drop=True)\nA_train = A_train.reset_index(drop=True)\nA_test = A_test.reset_index(drop=True)", "_____no_output_____" ] ], [ [ "We have two types of column in the dataset - categorical columns which will need to be one-hot encoded, and numeric ones which will need to be rescaled. We also need to take care of missing values. We use a simple approach here, but please bear in mind that this is another way that bias could be introduced (especially if one subgroup tends to have more missing values).\n\nFor this preprocessing, we make use of `Pipeline` objects from `sklearn`:", "_____no_output_____" ] ], [ [ "numeric_transformer = Pipeline(\n steps=[\n (\"impute\", SimpleImputer()),\n (\"scaler\", StandardScaler()),\n ]\n)\n\ncategorical_transformer = Pipeline(\n [\n (\"impute\", SimpleImputer(strategy=\"most_frequent\")),\n (\"ohe\", OneHotEncoder(handle_unknown=\"ignore\", sparse=False)),\n ]\n)\n\npreprocessor = ColumnTransformer(\n transformers=[\n (\"num\", numeric_transformer, selector(dtype_exclude=\"category\")),\n (\"cat\", categorical_transformer, selector(dtype_include=\"category\")),\n ]\n)", "_____no_output_____" ] ], [ [ "Now, the preprocessing pipeline is defined, we can run it on our training data, and apply the generated transform to our test data:", "_____no_output_____" ] ], [ [ "X_train = preprocessor.fit_transform(X_train)\nX_test = preprocessor.transform(X_test)", "_____no_output_____" ] ], [ [ "<a id=\"UnmitigatedModel\"></a>\n## Training an Unmitigated Model\n\nSo we have a point of comparison, we first train a model (specifically, logistic regression from scikit-learn) on the raw data, without applying any mitigation algorithm:", "_____no_output_____" ] ], [ [ "unmitigated_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n\nunmitigated_predictor.fit(X_train, y_train)", "_____no_output_____" ] ], [ [ "We can view this model in the fairness dashboard, and see the disparities which appear:", "_____no_output_____" ] ], [ [ "FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['Sex', 'Race'],\n y_true=y_test,\n y_pred={\"unmitigated\": unmitigated_predictor.predict(X_test)})", "_____no_output_____" ] ], [ [ "Looking at the disparity in accuracy when we select 'Sex' as the sensitive feature, we see that males have an error rate about three times greater than the females. More interesting is the disparity in opportunitiy - males are offered loans at three times the rate of females.\n\nDespite the fact that we removed the feature from the training data, our predictor still discriminates based on sex. This demonstrates that simply ignoring a protected attribute when fitting a predictor rarely eliminates unfairness. There will generally be enough other features correlated with the removed attribute to lead to disparate impact.", "_____no_output_____" ], [ "<a id=\"Mitigation\"></a>\n## Mitigation with GridSearch\n\nThe `GridSearch` class in `Fairlearn` implements a simplified version of the exponentiated gradient reduction of [Agarwal et al. 2018](https://arxiv.org/abs/1803.02453). The user supplies a standard ML estimator, which is treated as a blackbox - for this simple example, we shall use the logistic regression estimator from scikit-learn. `GridSearch` works by generating a sequence of relabellings and reweightings, and trains a predictor for each.\n\nFor this example, we specify demographic parity (on the protected attribute of sex) as the fairness metric. Demographic parity requires that individuals are offered the opportunity (a loan in this example) independent of membership in the protected class (i.e., females and males should be offered loans at the same rate). *We are using this metric for the sake of simplicity* in this example; the appropriate fairness metric can only be selected after *careful examination of the broader context* in which the model is to be used.", "_____no_output_____" ] ], [ [ "sweep = GridSearch(LogisticRegression(solver='liblinear', fit_intercept=True),\n constraints=DemographicParity(),\n grid_size=71)", "_____no_output_____" ] ], [ [ "With our estimator created, we can fit it to the data. After `fit()` completes, we extract the full set of predictors from the `GridSearch` object.\n\nThe following cell trains a many copies of the underlying estimator, and may take a minute or two to run:", "_____no_output_____" ] ], [ [ "sweep.fit(X_train, y_train,\n sensitive_features=A_train.sex)\n\n# For Fairlearn v0.5.0, need sweep.predictors_\npredictors = sweep._predictors", "_____no_output_____" ] ], [ [ "We could load these predictors into the Fairness dashboard now. However, the plot would be somewhat confusing due to their number. In this case, we are going to remove the predictors which are dominated in the error-disparity space by others from the sweep (note that the disparity will only be calculated for the protected attribute; other potentially protected attributes will *not* be mitigated). In general, one might not want to do this, since there may be other considerations beyond the strict optimisation of error and disparity (of the given protected attribute).", "_____no_output_____" ] ], [ [ "errors, disparities = [], []\nfor m in predictors:\n classifier = lambda X: m.predict(X)\n \n error = ErrorRate()\n error.load_data(X_train, pd.Series(y_train), sensitive_features=A_train.sex)\n disparity = DemographicParity()\n disparity.load_data(X_train, pd.Series(y_train), sensitive_features=A_train.sex)\n \n errors.append(error.gamma(classifier)[0])\n disparities.append(disparity.gamma(classifier).max())\n \nall_results = pd.DataFrame( {\"predictor\": predictors, \"error\": errors, \"disparity\": disparities})\n\ndominant_models_dict = dict()\nbase_name_format = \"census_gs_model_{0}\"\nrow_id = 0\nfor row in all_results.itertuples():\n model_name = base_name_format.format(row_id)\n errors_for_lower_or_eq_disparity = all_results[\"error\"][all_results[\"disparity\"]<=row.disparity]\n if row.error <= errors_for_lower_or_eq_disparity.min():\n dominant_models_dict[model_name] = row.predictor\n row_id = row_id + 1", "_____no_output_____" ] ], [ [ "We can construct predictions for the dominant models (we include the unmitigated predictor as well, for comparison):", "_____no_output_____" ] ], [ [ "predictions_dominant = {\"census_unmitigated\": unmitigated_predictor.predict(X_test)}\nmodels_dominant = {\"census_unmitigated\": unmitigated_predictor}\nfor name, predictor in dominant_models_dict.items():\n value = predictor.predict(X_test)\n predictions_dominant[name] = value\n models_dominant[name] = predictor", "_____no_output_____" ] ], [ [ "These predictions may then be viewed in the fairness dashboard. We include the race column from the dataset, as an alternative basis for assessing the models. However, since we have not based our mitigation on it, the variation in the models with respect to race can be large.", "_____no_output_____" ] ], [ [ "FairlearnDashboard(sensitive_features=A_test, \n sensitive_feature_names=['Sex', 'Race'],\n y_true=y_test.tolist(),\n y_pred=predictions_dominant)", "_____no_output_____" ] ], [ [ "When using sex as the sensitive feature and accuracy as the metric, we see a Pareto front forming - the set of predictors which represent optimal tradeoffs between accuracy and disparity in predictions. In the ideal case, we would have a predictor at (1,0) - perfectly accurate and without any unfairness under demographic parity (with respect to the protected attribute \"sex\"). The Pareto front represents the closest we can come to this ideal based on our data and choice of estimator. Note the range of the axes - the disparity axis covers more values than the accuracy, so we can reduce disparity substantially for a small loss in accuracy. Finally, we also see that the unmitigated model is towards the top right of the plot, with high accuracy, but worst disparity.\n\nBy clicking on individual models on the plot, we can inspect their metrics for disparity and accuracy in greater detail. In a real example, we would then pick the model which represented the best trade-off between accuracy and disparity given the relevant business constraints.", "_____no_output_____" ], [ "<a id=\"AzureUpload\"></a>\n## Uploading a Fairness Dashboard to Azure\n\nUploading a fairness dashboard to Azure is a two stage process. The `FairlearnDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. By default, the dashboard in Azure Machine Learning Studio also requires the models to be registered. The required stages are therefore:\n1. Register the dominant models\n1. Precompute all the required metrics\n1. Upload to Azure\n\nBefore that, we need to connect to Azure Machine Learning Studio:", "_____no_output_____" ] ], [ [ "from azureml.core import Workspace, Experiment, Model\n\nws = Workspace.from_config()\nws.get_details()", "_____no_output_____" ] ], [ [ "<a id=\"RegisterModels\"></a>\n### Registering Models\n\nThe fairness dashboard is designed to integrate with registered models, so we need to do this for the models we want in the Studio portal. The assumption is that the names of the models specified in the dashboard dictionary correspond to the `id`s (i.e. `<name>:<version>` pairs) of registered models in the workspace. We register each of the models in the `models_dominant` dictionary into the workspace. For this, we have to save each model to a file, and then register that file:", "_____no_output_____" ] ], [ [ "import joblib\nimport os\n\nos.makedirs('models', exist_ok=True)\ndef register_model(name, model):\n print(\"Registering \", name)\n model_path = \"models/{0}.pkl\".format(name)\n joblib.dump(value=model, filename=model_path)\n registered_model = Model.register(model_path=model_path,\n model_name=name,\n workspace=ws)\n print(\"Registered \", registered_model.id)\n return registered_model.id\n\nmodel_name_id_mapping = dict()\nfor name, model in models_dominant.items():\n m_id = register_model(name, model)\n model_name_id_mapping[name] = m_id", "_____no_output_____" ] ], [ [ "Now, produce new predictions dictionaries, with the updated names:", "_____no_output_____" ] ], [ [ "predictions_dominant_ids = dict()\nfor name, y_pred in predictions_dominant.items():\n predictions_dominant_ids[model_name_id_mapping[name]] = y_pred", "_____no_output_____" ] ], [ [ "<a id=\"PrecomputeMetrics\"></a>\n### Precomputing Metrics\n\nWe create a _dashboard dictionary_ using Fairlearn's `metrics` package. The `_create_group_metric_set` method has arguments similar to the Dashboard constructor, except that the sensitive features are passed as a dictionary (to ensure that names are available), and we must specify the type of prediction. Note that we use the `predictions_dominant_ids` dictionary we just created:", "_____no_output_____" ] ], [ [ "sf = { 'sex': A_test.sex, 'race': A_test.race }\n\nfrom fairlearn.metrics._group_metric_set import _create_group_metric_set\n\n\ndash_dict = _create_group_metric_set(y_true=y_test,\n predictions=predictions_dominant_ids,\n sensitive_features=sf,\n prediction_type='binary_classification')", "_____no_output_____" ] ], [ [ "<a id=\"DashboardUpload\"></a>\n### Uploading the Dashboard\n\nNow, we import our `contrib` package which contains the routine to perform the upload:", "_____no_output_____" ] ], [ [ "from azureml.contrib.fairness import upload_dashboard_dictionary, download_dashboard_by_upload_id", "_____no_output_____" ] ], [ [ "Now we can create an Experiment, then a Run, and upload our dashboard to it:", "_____no_output_____" ] ], [ [ "exp = Experiment(ws, \"Test_Fairlearn_GridSearch_Census_Demo\")\nprint(exp)\n\nrun = exp.start_logging()\ntry:\n dashboard_title = \"Dominant Models from GridSearch\"\n upload_id = upload_dashboard_dictionary(run,\n dash_dict,\n dashboard_name=dashboard_title)\n print(\"\\nUploaded to id: {0}\\n\".format(upload_id))\n\n downloaded_dict = download_dashboard_by_upload_id(run, upload_id)\nfinally:\n run.complete()", "_____no_output_____" ] ], [ [ "The dashboard can be viewed in the Run Details page.\n\nFinally, we can verify that the dashboard dictionary which we downloaded matches our upload:", "_____no_output_____" ] ], [ [ "print(dash_dict == downloaded_dict)", "_____no_output_____" ] ], [ [ "<a id=\"Conclusion\"></a>\n## Conclusion\n\nIn this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.github.io/) provides that discussion", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe2d7ce793f1bc1a6b60444e6568defd871637c
16,521
ipynb
Jupyter Notebook
tutorials/ranking/drmm.ipynb
Ambitioner-c/MatchZoo-py
bb088edce8e01c2c2326ca1a8ac647f0d23f088d
[ "Apache-2.0" ]
468
2019-07-03T02:43:52.000Z
2022-03-30T05:51:03.000Z
tutorials/ranking/drmm.ipynb
Ambitioner-c/MatchZoo-py
bb088edce8e01c2c2326ca1a8ac647f0d23f088d
[ "Apache-2.0" ]
126
2019-07-04T15:51:57.000Z
2021-07-31T13:14:40.000Z
tutorials/ranking/drmm.ipynb
dyuyang/MatchZoo-py
2d274879f444bb2556503d59145f7fd61652cea9
[ "Apache-2.0" ]
117
2019-07-04T11:31:08.000Z
2022-03-18T12:21:32.000Z
32.079612
172
0.567036
[ [ [ "%run init.ipynb", "matchzoo version 1.0\n`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\ndata loading ...\ndata loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n" ], [ "ranking_task = mz.tasks.Ranking(losses=mz.losses.RankCrossEntropyLoss(num_neg=10))\nranking_task.metrics = [\n mz.metrics.NormalizedDiscountedCumulativeGain(k=3),\n mz.metrics.NormalizedDiscountedCumulativeGain(k=5),\n mz.metrics.MeanAveragePrecision()\n]", "_____no_output_____" ], [ "preprocessor = mz.models.DRMM.get_default_preprocessor()", "_____no_output_____" ], [ "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\ndev_pack_processed = preprocessor.transform(dev_pack_raw)\ntest_pack_processed = preprocessor.transform(test_pack_raw)", "Processing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 7113.33it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:04<00:00, 3978.25it/s]\nProcessing text_right with append: 100%|██████████| 18841/18841 [00:00<00:00, 490493.51it/s]\nBuilding FrequencyFilter from a datapack.: 100%|██████████| 18841/18841 [00:00<00:00, 109302.57it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 132131.62it/s]\nProcessing text_left with extend: 100%|██████████| 2118/2118 [00:00<00:00, 524195.19it/s]\nProcessing text_right with extend: 100%|██████████| 18841/18841 [00:00<00:00, 784459.51it/s]\nBuilding Vocabulary from a datapack.: 100%|██████████| 418401/418401 [00:00<00:00, 2734112.41it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2118/2118 [00:00<00:00, 8663.39it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 18841/18841 [00:04<00:00, 4394.28it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 67567.99it/s]\nProcessing text_left with transform: 100%|██████████| 2118/2118 [00:00<00:00, 184305.72it/s]\nProcessing text_right with transform: 100%|██████████| 18841/18841 [00:00<00:00, 108278.18it/s]\nProcessing length_left with len: 100%|██████████| 2118/2118 [00:00<00:00, 542009.51it/s]\nProcessing length_right with len: 100%|██████████| 18841/18841 [00:00<00:00, 874372.16it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 122/122 [00:00<00:00, 8109.56it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 1115/1115 [00:00<00:00, 4648.20it/s]\nProcessing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 122271.73it/s]\nProcessing text_left with transform: 100%|██████████| 122/122 [00:00<00:00, 73121.62it/s]\nProcessing text_right with transform: 100%|██████████| 1115/1115 [00:00<00:00, 129164.22it/s]\nProcessing length_left with len: 100%|██████████| 122/122 [00:00<00:00, 196733.98it/s]\nProcessing length_right with len: 100%|██████████| 1115/1115 [00:00<00:00, 599186.29it/s]\nProcessing text_left with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 237/237 [00:00<00:00, 9027.54it/s]\nProcessing text_right with chain_transform of Tokenize => Lowercase => PuncRemoval: 100%|██████████| 2300/2300 [00:00<00:00, 4620.73it/s]\nProcessing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 127314.83it/s]\nProcessing text_left with transform: 100%|██████████| 237/237 [00:00<00:00, 159738.08it/s]\nProcessing text_right with transform: 100%|██████████| 2300/2300 [00:00<00:00, 91012.78it/s]\nProcessing length_left with len: 100%|██████████| 237/237 [00:00<00:00, 181164.58it/s]\nProcessing length_right with len: 100%|██████████| 2300/2300 [00:00<00:00, 689556.77it/s]\n" ], [ "preprocessor.context", "_____no_output_____" ], [ "glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=300)\nterm_index = preprocessor.context['vocab_unit'].state['term_index']\nembedding_matrix = glove_embedding.build_matrix(term_index)\nl2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\nembedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]", "_____no_output_____" ], [ "histgram_callback = mz.dataloader.callbacks.Histogram(\n embedding_matrix, bin_size=30, hist_mode='LCH'\n)\n\ntrainset = mz.dataloader.Dataset(\n data_pack=train_pack_processed,\n mode='pair',\n num_dup=5,\n num_neg=10,\n callbacks=[histgram_callback]\n)\ntestset = mz.dataloader.Dataset(\n data_pack=test_pack_processed,\n callbacks=[histgram_callback]\n)", "_____no_output_____" ], [ "padding_callback = mz.models.DRMM.get_default_padding_callback()\n\ntrainloader = mz.dataloader.DataLoader(\n device='cpu',\n dataset=trainset,\n batch_size=20,\n stage='train',\n resample=True,\n callback=padding_callback\n)\ntestloader = mz.dataloader.DataLoader(\n dataset=testset,\n batch_size=20,\n stage='dev',\n callback=padding_callback\n)", "_____no_output_____" ], [ "model = mz.models.DRMM()\n\nmodel.params['task'] = ranking_task\nmodel.params['mask_value'] = 0\nmodel.params['embedding'] = embedding_matrix\nmodel.params['hist_bin_size'] = 30\nmodel.params['mlp_num_layers'] = 1\nmodel.params['mlp_num_units'] = 10\nmodel.params['mlp_num_fan_out'] = 1\nmodel.params['mlp_activation_func'] = 'tanh'\n\nmodel.build()\n\nprint(model)\nprint('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))", "DRMM(\n (embedding): Embedding(30058, 300)\n (attention): Attention(\n (linear): Linear(in_features=300, out_features=1, bias=False)\n )\n (mlp): Sequential(\n (0): Sequential(\n (0): Linear(in_features=30, out_features=10, bias=True)\n (1): Tanh()\n )\n (1): Sequential(\n (0): Linear(in_features=10, out_features=1, bias=True)\n (1): Tanh()\n )\n )\n (out): Linear(in_features=1, out_features=1, bias=True)\n)\nTrainable params: 9018023\n" ], [ "optimizer = torch.optim.Adadelta(model.parameters())\n\ntrainer = mz.trainers.Trainer(\n device='cpu',\n model=model,\n optimizer=optimizer,\n trainloader=trainloader,\n validloader=testloader,\n validate_interval=None,\n epochs=10\n)", "_____no_output_____" ], [ "trainer.run()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe2d99c11b00e23ec5b463d7d4baf067d72ddfd
8,699
ipynb
Jupyter Notebook
3_Silla_de_ruedas/Python/1_Video_analysis_basics_for_lab_3.ipynb
BIOINSTRUMENTACION/BIO4
4ca5a0c6089ccbf71d9955c9c288769e2b6b40f7
[ "MIT" ]
1
2022-02-10T07:46:33.000Z
2022-02-10T07:46:33.000Z
3_Silla_de_ruedas/Python/1_Video_analysis_basics_for_lab_3.ipynb
BIOINSTRUMENTACION/BIO4
4ca5a0c6089ccbf71d9955c9c288769e2b6b40f7
[ "MIT" ]
null
null
null
3_Silla_de_ruedas/Python/1_Video_analysis_basics_for_lab_3.ipynb
BIOINSTRUMENTACION/BIO4
4ca5a0c6089ccbf71d9955c9c288769e2b6b40f7
[ "MIT" ]
null
null
null
41.822115
126
0.47948
[ [ [ "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# Data Base Generation\n\n### Basic Frame Capture ", "_____no_output_____" ] ], [ [ "## This is just an example to ilustrate how to display video from webcam##\nvid = cv2.VideoCapture(0) # define a video capture object \nstatus = True # Initalize status\nwhile(status): # Iterate while status is true, that is while there is a frame being captured\n status, frame = vid.read() # Capture the video frame by frame, returns status (Boolean) and frame (numpy.ndarray)\n cv2.imshow('frame', frame) # Display the resulting frame \n \n ## Exit if user presses q ##\n if cv2.waitKey(1) & 0xFF == ord('q'): \n break\n\nvid.release() # After the loop release the cap object \ncv2.destroyAllWindows() # Destroy all the windows ", "_____no_output_____" ] ], [ [ "### Create Screenshots off of Video", "_____no_output_____" ] ], [ [ "## This is just an example to ilustrate how to capture frames from webcam ##\npath = \"Bounding_box\" # Name of folder where information will be stored\nframe_id = 0 # Id of image\nvid = cv2.VideoCapture(0) # define a video capture object \nstatus = True # Initalize status\nwhile(status): # Iterate while status is True\n status, frame = vid.read() # Capture the video frame by frame \n cv2.imshow('frame', frame) # Display the resulting frame \n wait_key=cv2.waitKey(1) & 0xFF # Save Waitkey object in variable since we will use it multiple times\n if wait_key == ord('a'): # If a is pressed\n name =\"eye\"+str(frame_id)+'.jpg' \n name = path + \"\\\\\" + name # Set name and path\n cv2.imwrite(name, frame) # Save image\n frame_id += 1 # Incremente frame_id\n \n \n elif wait_key == ord('q'): # If user press \"q\" \n break # Exit from while Loop\n \n \nvid.release() # After the loop release the cap object \ncv2.destroyAllWindows() # Destroy all the windows ", "_____no_output_____" ] ], [ [ "## Use Haar Cascade to detect objects", "_____no_output_____" ] ], [ [ "## This is just an example to ilustrate how to use Haar Cascades in order to detect objects (LIVE) ##\nface = cv2.CascadeClassifier('Haarcascade/haarcascade_frontalface_default.xml') # Face Haar Cascade loading\neye = cv2.CascadeClassifier('Haarcascade/haarcascade_eye.xml') # Eye Haar Cascade Loading\npath = \"Bounding_box\" # Path to Store Photos\nframe_id = 0 # Frame Id\nvid = cv2.VideoCapture(0) # Define a video capture object \nstatus = True # Initalize status\nwhile(status): \n status, frame = vid.read() # Capture the video frame by frame \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to gray scale\n face_info = face.detectMultiScale(gray, 1.3, 5) # Get face infromation\n for (x,y,w,h) in face_info: # Iterate over this information\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),1) # Draw rectangle\n cropped_face = gray[y:y+h, x:x+w] # Crop face\n eye_info = eye.detectMultiScale(gray) # Get info of eyes\n for (ex,ey,ew,eh) in eye_info: # Iterate over eye information\n cv2.rectangle(frame,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) # Draw over eye information\n \n \n cv2.imshow('frame', frame) # Display the resulting frame \n wait_key = cv2.waitKey(1) & 0xFF # Store Waitkey object\n if wait_key == ord('a'): # If a is pressed\n name = \"eye\"+str(frame_id)+'.jpg' # Set name \n name = path + \"\\\\\" + name # Add path\n cv2.imwrite(name, frame) # Set photo\n frame_id += 1 # Increment frame id\n \n \n elif wait_key == ord('q'): # If q is pressed\n break # Break while loop\n \n \n\nvid.release() # After the loop release the cap object \ncv2.destroyAllWindows() # Destroy all the windows ", "_____no_output_____" ] ], [ [ "## Capture face gestures", "_____no_output_____" ] ], [ [ "## This is just an example to ilustrate how to use Haar Cascades in order to detect objects (LIVE) ##\nface = cv2.CascadeClassifier('Haarcascade/haarcascade_frontalface_default.xml') # Face Haar Cascade loading\neye = cv2.CascadeClassifier('Haarcascade/haarcascade_eye.xml') # Eye Haar Cascade Loading\npath = \"Bouding_box\" # Path to Store Photos\nframe_id = 0 # Frame Id\nvid = cv2.VideoCapture(0) # Define a video capture object \nstatus = True # Initalize status\nwhile(status): \n status, frame = vid.read() # Capture the video frame by frame \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to gray scale\n face_info = face.detectMultiScale(gray, 1.3, 5) # Get face infromation\n for (x,y,w,h) in face_info: # Iterate over this information\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),1) # Draw rectangle\n cropped_face_color = frame[y:y+h, x:x+w] # Crop face (color) \n \n \n cv2.imshow('frame', frame) # Display the resulting frame \n wait_key = cv2.waitKey(1) & 0xFF # Store Waitkey object\n if wait_key == ord('a'): # If a is pressed\n name = \"eye\"+str(frame_id)+'.jpg' # Set name \n name = path + \"\\\\\" + name # Add path\n cv2.imwrite(name, cropped_face_color) # Set photo\n frame_id += 1 # Increment frame id\n \n \n elif wait_key == ord('q'): # If q is pressed\n break # Break while loop\n \n \n\nvid.release() # After the loop release the cap object \ncv2.destroyAllWindows() # Destroy all the windows ", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe2da40cde96ddc67280d127b8df078ed025fc0
53,618
ipynb
Jupyter Notebook
homework-4/handout/hw4/training.ipynb
neelpawarcmu/deep-learning-library
401483fce40e3a025054596cbec368ff4f647661
[ "MIT" ]
null
null
null
homework-4/handout/hw4/training.ipynb
neelpawarcmu/deep-learning-library
401483fce40e3a025054596cbec368ff4f647661
[ "MIT" ]
null
null
null
homework-4/handout/hw4/training.ipynb
neelpawarcmu/deep-learning-library
401483fce40e3a025054596cbec368ff4f647661
[ "MIT" ]
null
null
null
74.058011
18,060
0.665112
[ [ [ "%matplotlib inline\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport time\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader\nfrom tests import test_prediction, test_generation", "_____no_output_____" ], [ "# load all that we need\n\ndataset = np.load('../dataset/wiki.train.npy', allow_pickle=True)\ndevset = np.load('../dataset/wiki.valid.npy', allow_pickle=True)\nfixtures_pred = np.load('../fixtures/prediction.npz') # dev\nfixtures_gen = np.load('../fixtures/generation.npy') # dev\nfixtures_pred_test = np.load('../fixtures/prediction_test.npz') # test\nfixtures_gen_test = np.load('../fixtures/generation_test.npy') # test\nvocab = np.load('../dataset/vocab.npy')", "_____no_output_____" ], [ "# set device as per system\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "_____no_output_____" ], [ "# data loader\n\n\nclass LanguageModelDataLoader(DataLoader):\n \"\"\"\n TODO: Define data loader logic here\n \"\"\"\n def __init__(self, dataset, batch_size, shuffle=True):\n self.dataset, self.batch_size, self.shuffle = dataset, batch_size, shuffle \n\n def __iter__(self):\n # concatenate dataset articles into single string\n # dataset shape: (579,), dataset[0].shape: (3803,)\n concatenate_string = np.concatenate(self.dataset) # concatenated shape: (2075677,)\n \n # generate input, output sequences eg: I ate an apple -> inp_seq: I ate an, out_seq: ate an apple\n # (also convert to torch tensors)\n input_sequence = torch.as_tensor(concatenate_string[:-1]) # first element to second last element \n output_sequence = torch.as_tensor(concatenate_string[1:]) # second element to last element\n\n # calculate excess length while batching and truncate it off\n excess_length = len(input_sequence)%self.batch_size\n truncated_length = len(input_sequence) - excess_length\n input_sequence, output_sequence = input_sequence[:truncated_length], output_sequence[:truncated_length]\n\n # convert to long tensors\n input_sequence, output_sequence = (input_sequence).type(torch.LongTensor), (output_sequence).type(torch.LongTensor)\n\n\n # batch the input and output sequences\n num_batches = truncated_length // self.batch_size\n input_sequence = input_sequence.reshape(self.batch_size, num_batches)\n output_sequence = output_sequence.reshape(self.batch_size, num_batches)\n # print(f'input sequence: {input_sequence.shape} \\noutput sequence: {output_sequence.shape}')\n\n # YIELD single batch of input, output for each batch (since we are designing an iter)\n prev = curr = 0 # current index for indexing data from sequences\n while curr < num_batches:\n # random BPTT length, https://arxiv.org/pdf/1708.02182.pdf section 5\n bptt_length = self.random_length()\n prev = curr\n curr += bptt_length\n yield input_sequence[:, prev:curr], output_sequence[:, prev:curr]\n\n\n # random BPTT length, https://arxiv.org/pdf/1708.02182.pdf section 5\n def random_length(self):\n random_probability = np.random.random_sample()\n if random_probability > 0.95:\n bptt_length = np.random.normal(70, 5)\n else:\n bptt_length = np.random.normal(35, 5)\n return round(bptt_length) #round off so we have integers\n\n\n \n# test code\nloader = LanguageModelDataLoader(dataset=dataset, batch_size=60, shuffle=True)\nloader.__iter__()\n# print(f'x:{x.shape}, y:{y.shape}')", "_____no_output_____" ], [ "# model\n\nclass LanguageModel(nn.Module):\n \"\"\"\n TODO: Define your model here\n \"\"\"\n def __init__(self, vocab_size):\n super(LanguageModel, self).__init__()\n # embedding size = 400 (https://arxiv.org/pdf/1708.02182.pdf section 5)\n self.embedding = nn.Embedding(num_embeddings = vocab_size, embedding_dim = 400) # simple lookup table that stores embeddings of a fixed dictionary and size\n # hidden size = 1150 (https://arxiv.org/pdf/1708.02182.pdf section 5)\n self.lstm = nn.LSTM(input_size=400, hidden_size=1150, num_layers=3, batch_first=True)\n # linear output = vocabulary size\n self.linear = nn.Linear(in_features=1150, out_features=vocab_size)\n\n def forward(self, x, hiddens=None):\n # Feel free to add extra arguments to forward (like an argument to pass in the hiddens)\n # embedding\n embeddings = self.embedding(x) \n # lstm / rnn\n out, hiddens = self.lstm(embeddings, hiddens) if hiddens else self.lstm(embeddings) #operate on hidden states only if they are available\n # linear\n out = self.linear(out) \n return out, hiddens\n\nmodel = LanguageModel(len(vocab))\nprint(model)", "LanguageModel(\n (embedding): Embedding(33278, 400)\n (lstm): LSTM(400, 1150, num_layers=3, batch_first=True)\n (linear): Linear(in_features=1150, out_features=33278, bias=True)\n)\n" ], [ "# model hyperparameters\nLEARNING_RATE = 1e-3\nWEIGHT_DECAY = 1e-6", "_____no_output_____" ], [ "# model trainer\nimport time \n\nclass LanguageModelTrainer:\n def __init__(self, model, loader, max_epochs=1, run_id='exp'):\n \"\"\"\n Use this class to train your model\n \"\"\"\n # feel free to add any other parameters here\n self.model = model\n self.loader = loader\n self.train_losses = []\n self.val_losses = []\n self.predictions = []\n self.predictions_test = []\n self.generated_logits = []\n self.generated = []\n self.generated_logits_test = []\n self.generated_test = []\n self.epochs = 0\n self.max_epochs = max_epochs\n self.run_id = run_id\n \n # TODO: Define your optimizer and criterion here\n self.optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY) #\n self.criterion = nn.CrossEntropyLoss()\n\n def train(self):\n self.model.train() # set to training mode\n epoch_loss = 0\n num_batches = 0\n start_time = time.time()\n for batch_num, (inputs, targets) in enumerate(self.loader):\n if batch_num % 50 == 0:\n print(f'batch : {batch_num} \\ttotal time elapsed : {round(time.time()-start_time, 2)} sec')\n epoch_loss += self.train_batch(inputs, targets)\n epoch_loss = epoch_loss / (batch_num + 1)\n self.epochs += 1\n print('[TRAIN] Epoch [%d/%d] Loss: %.4f'\n % (self.epochs + 1, self.max_epochs, epoch_loss))\n print(f'time taken = {round((time.time()-start_time)/60, 2)} min')\n self.train_losses.append(epoch_loss)\n\n def train_batch(self, inputs, targets):\n \"\"\" \n TODO: Define code for training a single batch of inputs\n \n \"\"\"\n # initialize and move to the active device (make sure everything (inputs, model, outputs, targets) on same device)\n self.optimizer.zero_grad()\n inputs = inputs.to(device)\n targets = targets.to(device)\n\n # get output from model\n outputs, _ = self.model(inputs)\n\n # reshape outputs and targets\n outputs = outputs.reshape(-1, outputs.shape[2])\n targets = targets.reshape(-1)\n \n # judge quality of output against the target using loss function\n loss = self.criterion(outputs, targets)\n \n # optimize weights\n loss.backward()\n self.optimizer.step()\n return loss\n\n \n def test(self):\n # don't change these\n self.model.eval() # set to eval mode\n predictions = TestLanguageModel.prediction(fixtures_pred['inp'], self.model) # get predictions\n self.predictions.append(predictions)\n generated_logits = TestLanguageModel.generation(fixtures_gen, 10, self.model) # generated predictions for 10 words\n generated_logits_test = TestLanguageModel.generation(fixtures_gen_test, 10, self.model)\n nll = test_prediction(predictions, fixtures_pred['out'])\n generated = test_generation(fixtures_gen, generated_logits, vocab)\n generated_test = test_generation(fixtures_gen_test, generated_logits_test, vocab)\n self.val_losses.append(nll)\n \n self.generated.append(generated)\n self.generated_test.append(generated_test)\n self.generated_logits.append(generated_logits)\n self.generated_logits_test.append(generated_logits_test)\n \n # generate predictions for test data\n predictions_test = TestLanguageModel.prediction(fixtures_pred_test['inp'], self.model) # get predictions\n self.predictions_test.append(predictions_test)\n \n print('[VAL] Epoch [%d/%d] Loss: %.4f'\n % (self.epochs + 1, self.max_epochs, nll))\n print('='*60)\n return nll\n\n def save(self):\n # don't change these\n model_path = os.path.join('experiments', self.run_id, 'model-{}.pkl'.format(self.epochs))\n torch.save({'state_dict': self.model.state_dict()},\n model_path)\n np.save(os.path.join('experiments', self.run_id, 'predictions-{}.npy'.format(self.epochs)), self.predictions[-1])\n np.save(os.path.join('experiments', self.run_id, 'predictions-test-{}.npy'.format(self.epochs)), self.predictions_test[-1])\n np.save(os.path.join('experiments', self.run_id, 'generated_logits-{}.npy'.format(self.epochs)), self.generated_logits[-1])\n np.save(os.path.join('experiments', self.run_id, 'generated_logits-test-{}.npy'.format(self.epochs)), self.generated_logits_test[-1])\n with open(os.path.join('experiments', self.run_id, 'generated-{}.txt'.format(self.epochs)), 'w') as fw:\n fw.write(self.generated[-1])\n with open(os.path.join('experiments', self.run_id, 'generated-{}-test.txt'.format(self.epochs)), 'w') as fw:\n fw.write(self.generated_test[-1])\n", "_____no_output_____" ], [ "class TestLanguageModel:\n def prediction(inp, model):\n \"\"\"\n TODO: write prediction code here\n \n :param inp:\n :return: a np.ndarray of logits\n \"\"\"\n # every input across notebook needs to be converted to long tensor\n # convert inputs to long tensor\n inp = torch.LongTensor(inp)\n # move to active device \n inp = inp.to(device)\n # get model output\n out, out_lengths = model(inp)\n out = out[:, -1]\n\n # detatch logits array from tensor\n predictions = out.cpu().detach().numpy()\n return predictions\n\n \n def generation(inp, forward, model):\n \"\"\"\n TODO: write generation code here\n\n Generate a sequence of words given a starting sequence.\n :param inp: Initial sequence of words (batch size, length)\n :param forward: number of additional words to generate\n :return: generated words (batch size, forward)\n \"\"\" \n model.eval()\n with torch.no_grad():\n result = [] # array of strings of length = forward\n # change to long type\n inp = torch.LongTensor(inp)\n # move inputs to device\n inp = inp.to(device)\n hidden = None\n for i in range(forward):\n out, hidden = model(inp, hidden) if hidden else model(inp) # pass in hidden input only if available\n predictions = torch.argmax(out, dim=2) \n predictions = predictions[:,-1]\n inp = predictions.unsqueeze(1)\n result.append(inp)\n # concatenate result shape\n result = torch.cat(result, dim=1)\n\n # detatch words array from tensor\n result = result.cpu().detach().numpy() \n return result", "_____no_output_____" ], [ "# TODO: define other hyperparameters here\n\nNUM_EPOCHS = 6 # based on writeup\nBATCH_SIZE = 80 # based on https://arxiv.org/pdf/1708.02182.pdf section 5", "_____no_output_____" ], [ "run_id = str(int(time.time()))\nif not os.path.exists('./experiments'):\n os.mkdir('./experiments')\nos.mkdir('./experiments/%s' % run_id)\nprint(\"Saving models, predictions, and generated words to ./experiments/%s\" % run_id)", "Saving models, predictions, and generated words to ./experiments/1639367590\n" ], [ "loader = LanguageModelDataLoader(dataset=dataset, batch_size=BATCH_SIZE, shuffle=True)\nmodel = LanguageModel(len(vocab))\nmodel = model.to(device)\ntrainer = LanguageModelTrainer(model=model, loader=loader, max_epochs=NUM_EPOCHS, run_id=run_id)", "_____no_output_____" ], [ "print(f'length of dataloader = {len(loader.dataset)}')", "length of dataloader = 579\n" ], [ "best_nll = 1e30\nfor epoch in range(NUM_EPOCHS):\n trainer.train()\n nll = trainer.test()\n if nll < best_nll:\n best_nll = nll\n print(\"Saving model, predictions and generated output for epoch \"+str(epoch)+\" with NLL: \"+ str(best_nll))\n trainer.save()", "batch : 0 \ttotal time elapsed : 0.01 sec\nbatch : 50 \ttotal time elapsed : 36.66 sec\nbatch : 100 \ttotal time elapsed : 72.51 sec\nbatch : 150 \ttotal time elapsed : 110.1 sec\nbatch : 200 \ttotal time elapsed : 148.35 sec\nbatch : 250 \ttotal time elapsed : 185.83 sec\nbatch : 300 \ttotal time elapsed : 223.14 sec\nbatch : 350 \ttotal time elapsed : 260.06 sec\nbatch : 400 \ttotal time elapsed : 297.58 sec\nbatch : 450 \ttotal time elapsed : 336.45 sec\nbatch : 500 \ttotal time elapsed : 374.18 sec\nbatch : 550 \ttotal time elapsed : 411.69 sec\nbatch : 600 \ttotal time elapsed : 449.06 sec\nbatch : 650 \ttotal time elapsed : 487.18 sec\nbatch : 700 \ttotal time elapsed : 522.77 sec\n[TRAIN] Epoch [2/6] Loss: 7.0571\ntime taken = 8.82 min\n[VAL] Epoch [2/6] Loss: 6.0492\n============================================================\nSaving model, predictions and generated output for epoch 0 with NLL: 6.0492325\nbatch : 0 \ttotal time elapsed : 0.01 sec\nbatch : 50 \ttotal time elapsed : 35.89 sec\nbatch : 100 \ttotal time elapsed : 71.38 sec\nbatch : 150 \ttotal time elapsed : 110.11 sec\nbatch : 200 \ttotal time elapsed : 147.03 sec\nbatch : 250 \ttotal time elapsed : 183.21 sec\nbatch : 300 \ttotal time elapsed : 222.18 sec\nbatch : 350 \ttotal time elapsed : 258.09 sec\nbatch : 400 \ttotal time elapsed : 296.98 sec\nbatch : 450 \ttotal time elapsed : 332.88 sec\nbatch : 500 \ttotal time elapsed : 371.07 sec\nbatch : 550 \ttotal time elapsed : 411.36 sec\nbatch : 600 \ttotal time elapsed : 447.67 sec\nbatch : 650 \ttotal time elapsed : 484.13 sec\nbatch : 700 \ttotal time elapsed : 522.34 sec\n[TRAIN] Epoch [3/6] Loss: 6.0887\ntime taken = 8.89 min\n[VAL] Epoch [3/6] Loss: 5.3978\n============================================================\nSaving model, predictions and generated output for epoch 1 with NLL: 5.3978324\nbatch : 0 \ttotal time elapsed : 0.01 sec\nbatch : 50 \ttotal time elapsed : 35.69 sec\nbatch : 100 \ttotal time elapsed : 75.32 sec\nbatch : 150 \ttotal time elapsed : 112.77 sec\nbatch : 200 \ttotal time elapsed : 153.2 sec\nbatch : 250 \ttotal time elapsed : 189.04 sec\nbatch : 300 \ttotal time elapsed : 227.48 sec\nbatch : 350 \ttotal time elapsed : 265.19 sec\nbatch : 400 \ttotal time elapsed : 302.24 sec\nbatch : 450 \ttotal time elapsed : 339.02 sec\nbatch : 500 \ttotal time elapsed : 375.52 sec\nbatch : 550 \ttotal time elapsed : 413.91 sec\nbatch : 600 \ttotal time elapsed : 452.38 sec\nbatch : 650 \ttotal time elapsed : 490.48 sec\nbatch : 700 \ttotal time elapsed : 527.54 sec\n[TRAIN] Epoch [4/6] Loss: 5.6062\ntime taken = 8.91 min\n[VAL] Epoch [4/6] Loss: 5.1104\n============================================================\nSaving model, predictions and generated output for epoch 2 with NLL: 5.1104355\nbatch : 0 \ttotal time elapsed : 0.01 sec\nbatch : 50 \ttotal time elapsed : 37.61 sec\nbatch : 100 \ttotal time elapsed : 74.1 sec\nbatch : 150 \ttotal time elapsed : 110.2 sec\nbatch : 200 \ttotal time elapsed : 146.28 sec\nbatch : 250 \ttotal time elapsed : 185.97 sec\nbatch : 300 \ttotal time elapsed : 225.17 sec\nbatch : 350 \ttotal time elapsed : 261.75 sec\nbatch : 400 \ttotal time elapsed : 299.92 sec\nbatch : 450 \ttotal time elapsed : 337.8 sec\nbatch : 500 \ttotal time elapsed : 375.47 sec\nbatch : 550 \ttotal time elapsed : 411.98 sec\nbatch : 600 \ttotal time elapsed : 449.38 sec\nbatch : 650 \ttotal time elapsed : 487.5 sec\nbatch : 700 \ttotal time elapsed : 524.16 sec\n[TRAIN] Epoch [5/6] Loss: 5.3117\ntime taken = 8.91 min\n[VAL] Epoch [5/6] Loss: 4.9230\n============================================================\nSaving model, predictions and generated output for epoch 3 with NLL: 4.9229994\nbatch : 0 \ttotal time elapsed : 0.02 sec\nbatch : 50 \ttotal time elapsed : 35.93 sec\nbatch : 100 \ttotal time elapsed : 74.17 sec\nbatch : 150 \ttotal time elapsed : 112.52 sec\nbatch : 200 \ttotal time elapsed : 150.6 sec\nbatch : 250 \ttotal time elapsed : 187.91 sec\nbatch : 300 \ttotal time elapsed : 224.61 sec\nbatch : 350 \ttotal time elapsed : 261.76 sec\nbatch : 400 \ttotal time elapsed : 298.24 sec\nbatch : 450 \ttotal time elapsed : 336.18 sec\nbatch : 500 \ttotal time elapsed : 376.71 sec\nbatch : 550 \ttotal time elapsed : 413.5 sec\nbatch : 600 \ttotal time elapsed : 452.56 sec\nbatch : 650 \ttotal time elapsed : 490.82 sec\nbatch : 700 \ttotal time elapsed : 528.43 sec\n[TRAIN] Epoch [6/6] Loss: 5.0796\ntime taken = 8.91 min\n[VAL] Epoch [6/6] Loss: 4.8226\n============================================================\nSaving model, predictions and generated output for epoch 4 with NLL: 4.8226085\nbatch : 0 \ttotal time elapsed : 0.01 sec\nbatch : 50 \ttotal time elapsed : 36.94 sec\nbatch : 100 \ttotal time elapsed : 76.4 sec\nbatch : 150 \ttotal time elapsed : 115.09 sec\nbatch : 200 \ttotal time elapsed : 151.03 sec\nbatch : 250 \ttotal time elapsed : 186.18 sec\nbatch : 300 \ttotal time elapsed : 223.17 sec\nbatch : 350 \ttotal time elapsed : 260.28 sec\nbatch : 400 \ttotal time elapsed : 298.29 sec\nbatch : 450 \ttotal time elapsed : 337.95 sec\nbatch : 500 \ttotal time elapsed : 372.83 sec\nbatch : 550 \ttotal time elapsed : 410.3 sec\nbatch : 600 \ttotal time elapsed : 448.71 sec\nbatch : 650 \ttotal time elapsed : 486.15 sec\nbatch : 700 \ttotal time elapsed : 524.1 sec\n[TRAIN] Epoch [7/6] Loss: 4.8873\ntime taken = 8.99 min\n[VAL] Epoch [7/6] Loss: 4.7296\n============================================================\nSaving model, predictions and generated output for epoch 5 with NLL: 4.7295513\n" ], [ "# Don't change these\n# plot training curves\nplt.figure()\nplt.plot(range(1, trainer.epochs + 1), trainer.train_losses, label='Training losses')\nplt.plot(range(1, trainer.epochs + 1), trainer.val_losses, label='Validation losses')\nplt.xlabel('Epochs')\nplt.ylabel('NLL')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "# see generated output\nprint (trainer.generated[-1]) # get last generated output", "Input | Output #0: while the group was en route , but only three were ultimately able to attack . None of them were | not damaged , and the ship was completed . <eol>\nInput | Output #1: <unk> , where he remained on loan until 30 June 2010 . <eol> = = = Return to Manchester United | = = = <eol> = = = <unk> = =\nInput | Output #2: 25 April 2013 , denoting shipments of 500 @,@ 000 copies . <eol> The song became One Direction 's fourth | single , and the first single in the United States\nInput | Output #3: , and Bruce R. ) one daughter ( Wendy J. <unk> ) and two grandchildren , died in <unk> , | <unk> , and the <unk> of the <unk> <unk> <unk>\nInput | Output #4: Warrior were examples of this type . Because their armor was so heavy , they could only carry a single | <unk> . <eol> = = = <unk> = = =\nInput | Output #5: the embassy at 1 : 49 and landed on Guam at 2 : 23 ; twenty minutes later , Ambassador | in the United States . <eol> = = = <unk>\nInput | Output #6: <unk> , $ 96 million USD ) . Damage was heaviest in South Korea , notably where it moved ashore | . The ship was completed in the United States in\nInput | Output #7: The <unk> were condemned as <unk> by <unk> , who saw the riots as hampering attempts to resolve the situation | . <eol> = = = <unk> = = = <eol>\nInput | Output #8: by a decision made by the War Office in mid @-@ 1941 , as it was considering the equipment to | be the first @-@ time field of the two .\nInput | Output #9: Division crossed the <unk> at a number of places and climbed the hills quietly toward the 9th Infantry river line | . <eol> = = = <unk> = = = <eol>\nInput | Output #10: = <eol> = = = French VIII . Corps ( Corps <unk> ) = = = <eol> On 6 November | , the route was completed in the United States in\nInput | Output #11: of the World from 9th Avenue \" . This is regarded as his most famous work . It is considered | to be a <unk> of the <unk> of the <unk>\nInput | Output #12: — <unk> @-@ 10 , <unk> @-@ 12 , <unk> @-@ 16 , <unk> @-@ 17 — were all converted | to the village . The ship was completed in the\nInput | Output #13: And now he has . \" <eol> = = Family = = <eol> <unk> lived 37 of his years in | the United States , and the first of the two\nInput | Output #14: Hell to which he has been condemned for <unk> . Eliot , in a letter to John <unk> dated 27 | December , was the first of the most important of\nInput | Output #15: Luoyang area , fulfilling his duties in domestic affairs . <eol> In the autumn of <unk> , he met Li | <unk> , who was appointed the \" <unk> \" and\nInput | Output #16: Power said they enjoyed Block Ball and its number of stages , but wondered how its eight <unk> of memory | was not to be the most popular . \" <eol>\nInput | Output #17: by Lloyd F. Lonergan . The cameraman was Jacques <unk> . <eol> = = Release and reception = = <eol> | = = = <unk> = = = <eol> The film\nInput | Output #18: alone , the Austrians lost more than half their reserve artillery park , 6 @,@ 000 ( out of 8 | ) and the <unk> <unk> ( <unk> ) . The\nInput | Output #19: while attacking a ship at <unk> in the Dutch East Indies ; the loss was compounded by the fact that | the war was not to be the <unk> of the\nInput | Output #20: first raised in 2007 by the member of parliament ( MP ) for <unk> . The gangsters may have run | to the <unk> of the <unk> . The <unk> is\nInput | Output #21: Species are also non @-@ spiny <unk> and includes both large trees with stout stems up to 30 metres ( | 0 @.@ 5 in ) . <eol> = = =\nInput | Output #22: \" : specific design issues with the building 's energy efficiency included the fact that the largest room in the | world is not a <unk> . \" <eol> = =\nInput | Output #23: were reported to support over 300 @,@ 000 households in the Brazilian state of <unk> in 2005 , and in | the early 19th century , the kakapo was also used\nInput | Output #24: port . <unk> in Vietnam also warned for the potential of heavy rainfall due to the dissipating Tropical Depression <unk> | . The ship was completed in the United States in\nInput | Output #25: T @-@ numbers in their tropical cyclone products . The following example is from discussion number 3 of Tropical Depression | <unk> of the <unk> <unk> <unk> ( <unk> ) ,\nInput | Output #26: South Australia hosted the three @-@ game semi @-@ final series against the New South Wales <unk> . Both teams | were also named the song 's first career in the\nInput | Output #27: Perth from contention and secured the last finals spot for the <unk> . <eol> = = = Statistical leaders = | = = <eol> = = = <unk> = = =\nInput | Output #28: deemed it an \" amazing pop song \" , lauding the group 's falsetto and its \" head @-@ <unk> | \" . <eol> = = = <unk> = = =\nInput | Output #29: , but began patrolling the English Channel after <unk> @-@ 6 pioneered a route past British <unk> nets and mines | in the village of <unk> . The ship was completed\nInput | Output #30: production executives to let him direct . He had already discussed the film with <unk> and Cohen , and felt | that the song was \" <unk> \" . <eol> =\nInput | Output #31: and Nick <unk> at Studio <unk> in Los Angeles , California , and was released on August 1 , 2006 | . <eol> = = = <unk> = = = <eol>\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe2e31fa1d96951dfdd251928d5d257df0fdb73
603
ipynb
Jupyter Notebook
Untitled.ipynb
song20607/Bigdata-X-Campus
eeffb805f7e3cb795f79f981ebdb95da3d90b481
[ "MIT" ]
null
null
null
Untitled.ipynb
song20607/Bigdata-X-Campus
eeffb805f7e3cb795f79f981ebdb95da3d90b481
[ "MIT" ]
null
null
null
Untitled.ipynb
song20607/Bigdata-X-Campus
eeffb805f7e3cb795f79f981ebdb95da3d90b481
[ "MIT" ]
null
null
null
16.297297
34
0.502488
[ [ [ "a= 0\n_a = 1\n__a = 2", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cbe2f1778d7f9b2bd152ebd7988b51c20b973a65
63,845
ipynb
Jupyter Notebook
tlcc.ipynb
wcneill/marine-heatwave-prediction
00ac1c1ede9c4d376253adb0e8a3bcd0c0cd7d00
[ "MIT" ]
null
null
null
tlcc.ipynb
wcneill/marine-heatwave-prediction
00ac1c1ede9c4d376253adb0e8a3bcd0c0cd7d00
[ "MIT" ]
null
null
null
tlcc.ipynb
wcneill/marine-heatwave-prediction
00ac1c1ede9c4d376253adb0e8a3bcd0c0cd7d00
[ "MIT" ]
null
null
null
411.903226
33,464
0.942376
[ [ [ "# Finding peak cross correlation to determine optimal lag.\nA small demonstration of why finding optimal lag might be helpful.", "_____no_output_____" ] ], [ [ "from scipy import signal\nfrom numpy.random import default_rng\nrng = default_rng()\nx = np.arange(0, 4 * np.pi, 0.01 * np.pi)\ny = np.cos(x)\nz = np.sin(x)", "_____no_output_____" ], [ "%matplotlib inline\nplt.plot(x, y, 'r')\nplt.plot(x, z, '--')\nplt.show()", "_____no_output_____" ] ], [ [ "Visually we can see that the cosine curve leads the sin curve in time. Therefore, given the appropriate lag time, we could say that $y(t) = cos(t)$ is a predictor of $z(t) = sin(t)$. Using time lagged cross correlation, we can find that optimal lag $\\Delta t$. Then we can estimate the value of z by:\n\n$$\n\\hat{z} = y(t + \\Delta t)\n$$", "_____no_output_____" ] ], [ [ "correlation = signal.correlate(x, y, mode=\"same\")\nlags = signal.correlation_lags(x.size, y.size, mode=\"same\")\nlag = lags[np.argmax(correlation)]\nlag", "_____no_output_____" ] ], [ [ "If we push the cosine signal forward by 152 time steps, we see that it estimates sine. ", "_____no_output_____" ] ], [ [ "lag_y = np.roll(y, -lag)\nplt.plot(x, lag_y, 'r')\nplt.plot(x, z, '--')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe2f8c96613fd6f06759ab083915d70f1c26f99
13,898
ipynb
Jupyter Notebook
CVND_Exercises/3_5_State_and_Motions/1 .Interacting with a Car Object.ipynb
darkmatter18/Udacity-Computer-Vision-Nanodegree
a52051991e079183d61d3442d8c49bcd5fe97dc6
[ "MIT" ]
33
2019-11-08T19:36:38.000Z
2022-03-30T23:41:54.000Z
CVND_Exercises/3_5_State_and_Motions/1 .Interacting with a Car Object.ipynb
kurthf19/Udacity-Computer-Vision-Nanodegree
2176e2838a63997d0024cf4d21d4e9feb08c0ecd
[ "MIT" ]
3
2019-11-04T09:52:57.000Z
2022-03-12T00:11:21.000Z
CVND_Exercises/3_5_State_and_Motions/1 .Interacting with a Car Object.ipynb
kurthf19/Udacity-Computer-Vision-Nanodegree
2176e2838a63997d0024cf4d21d4e9feb08c0ecd
[ "MIT" ]
34
2019-12-25T05:15:28.000Z
2022-02-26T17:38:56.000Z
63.461187
4,512
0.809685
[ [ [ "# Interacting with a Car Object", "_____no_output_____" ], [ "In this notebook, you've been given some of the starting code for creating and interacting with a car object.\n\nYour tasks are to:\n1. Become familiar with this code. \n - Know how to create a car object, and how to move and turn that car.\n2. Constantly visualize.\n - To make sure your code is working as expected, frequently call `display_world()` to see the result!\n3. **Make the car move in a 4x4 square path.** \n - If you understand the move and turn functions, you should be able to tell a car to move in a square path. This task is a **TODO** at the end of this notebook.\n\nFeel free to change the values of initial variables and add functions as you see fit!\n\nAnd remember, to run a cell in the notebook, press `Shift+Enter`.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport car\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "### Define the initial variables", "_____no_output_____" ] ], [ [ "# Create a 2D world of 0's\nheight = 4\nwidth = 6\nworld = np.zeros((height, width))\n\n# Define the initial car state\ninitial_position = [0, 0] # [y, x] (top-left corner)\nvelocity = [1, 0] # [vy, vx] (moving to the right)\n", "_____no_output_____" ] ], [ [ "### Create a car object", "_____no_output_____" ] ], [ [ "# Create a car object with these initial params\ncarla = car.Car(initial_position, velocity, world)\n\nprint('Carla\\'s initial state is: ' + str(carla.state))", "Carla's initial state is: [[0, 0], [1, 0]]\n" ] ], [ [ "### Move and track state", "_____no_output_____" ] ], [ [ "# Move in the direction of the initial velocity\ncarla.move()\n\n# Track the change in state\nprint('Carla\\'s state is: ' + str(carla.state))\n\n# Display the world\ncarla.display_world()", "Carla's state is: [[1, 0], [1, 0]]\n" ] ], [ [ "## TODO: Move in a square path\n\nUsing the `move()` and `turn_left()` functions, make carla traverse a 4x4 square path.\n\nThe output should look like:\n<img src=\"files/4x4_path.png\" style=\"width: 30%;\">", "_____no_output_____" ] ], [ [ "## TODO: Make carla traverse a 4x4 square path\n## Display the result\ncarla.move()\ncarla.move()\n\ncarla.turn_left()\ncarla.move()\ncarla.move()\ncarla.move()\n\ncarla.turn_left()\ncarla.move()\ncarla.move()\ncarla.move()\n\ncarla.turn_left()\ncarla.move()\ncarla.move()\ncarla.move()\n\ncarla.display_world()", "_____no_output_____" ] ], [ [ "There is also one potential solution included by clicking on the \"Jupyter\" in the top left of this notebook, and going into the solution notebook.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe3066d8f2784f903f09348d306545792e93270
12,976
ipynb
Jupyter Notebook
degradation_module.ipynb
GabrielYoong/Battery-System-Design-Framework
ebeb74636aa99f289803ff4724850b890260e653
[ "MIT" ]
null
null
null
degradation_module.ipynb
GabrielYoong/Battery-System-Design-Framework
ebeb74636aa99f289803ff4724850b890260e653
[ "MIT" ]
null
null
null
degradation_module.ipynb
GabrielYoong/Battery-System-Design-Framework
ebeb74636aa99f289803ff4724850b890260e653
[ "MIT" ]
null
null
null
38.277286
133
0.503545
[ [ [ "# Degradation Module", "_____no_output_____" ] ], [ [ "## Importing Packages\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n", "_____no_output_____" ], [ "## Pre-processing cycle dataframe for the battery pack in question\ndef deg_preprocessing(df):\n df['avg_ch_C'] = (df[\"avg_ch_MW\"]*1000)/design_dict['tot_cap'] # Charge C rate\n df['avg_disch_C'] = (df[\"avg_disch_MW\"]*1000)/design_dict['tot_cap'] # Discharge C rate\n df['av_temp'] = [25]*len(df['cycle_num'].tolist())\n df['SOC'] = [0]*len(df['cycle_num'].tolist())\n df['max_SOC'] = [0]*len(df['cycle_num'].tolist())\n df['min_SOC'] = [0]*len(df['cycle_num'].tolist())\n \n ## Iterating through cycle dataframe\n for index,row in df.iterrows():\n if index == 0: # first row exception\n start_SOC = 0 ##start at 0 SOC\n df.loc[df['cycle_num']==row['cycle_num'],'max_SOC'] = -row['ch_th_kWh']\n df.loc[df['cycle_num']==row['cycle_num'],'min_SOC'] = start_SOC\n df.loc[df['cycle_num']==row['cycle_num'],'SOC'] = -row['ch_th_kWh']-row['disch_th_kWh']\n prev_row = df.loc[df['cycle_num']==row['cycle_num'],:]\n else:\n df.loc[df['cycle_num']==row['cycle_num'],'max_SOC'] = -row['ch_th_kWh']+prev_row['SOC'].values\n df.loc[df['cycle_num']==row['cycle_num'],'min_SOC'] = min((-row['ch_th_kWh']-row['disch_th_kWh']),\n prev_row['SOC'].values)\n df.loc[df['cycle_num']==row['cycle_num'],'SOC'] = -row['ch_th_kWh']-row['disch_th_kWh']+prev_row['SOC'].values\n prev_row = df.loc[df['cycle_num']==row['cycle_num'],:]\n ## Determining the start SOC so SOC never goes <0\n overlap = min(df['SOC'].tolist()) # should be negative\n df['min_SOC']= 100*(df['min_SOC'] - overlap)/design_dict['tot_cap']\n df['max_SOC']= 100*(df['max_SOC'] - overlap)/design_dict['tot_cap']\n df['SOC']= 100*(df['SOC'] - overlap)/design_dict['tot_cap']\n\n df['DOD'] = df['max_SOC'] - df['SOC']\n\n return df", "_____no_output_____" ], [ "# ## Function to graph cell dispatch\n# def graphCellDispatch(res_path, df):\n# fig, axs = plt.subplots(2,2, figsize =(10,6))\n\n# axs[0,0].plot(df['cycle_num'],df['SOC'], label = 'SOC', c='turquoise')\n# axs[0,0].plot(df['cycle_num'],df['min_SOC'], label = 'min SOC', c= 'powderblue')\n# axs[0,0].plot(df['cycle_num'],df['max_SOC'], label = 'max SOC', c= 'powderblue')\n# axs[0,0].set_ylabel('end of cycle SOC (%)')\n# axs[0,0].set_xlabel('Cycle Number')\n# axs[0,0].legend()\n\n# axs[0,1].plot(df['cycle_num'],df['DOD'], label = 'DOD', c='turquoise')\n# axs[0,1].set_ylabel('Depth of Discharge (%)')\n# axs[0,1].set_xlabel('Cycle Number')\n# axs[0,1].legend()\n\n# axs[1,0].plot(df['cycle_num'],df['avg_disch_C'], label = 'Discharge', c='turquoise')\n# axs[1,0].plot(df['cycle_num'],df['avg_ch_C'], label = 'Charge', c='red')\n# axs[1,0].set_ylabel('C rate')\n# axs[1,0].set_xlabel('Cycle Number')\n# axs[1,0].legend()\n\n\n# axs[1,1].plot(df['cycle_num'],df['av_temp'], label = 'Average', c='turquoise')\n# axs[1,1].set_ylabel('Cell Temperature (degC)')\n# axs[1,1].set_xlabel('Cycle Number')\n# axs[1,1].legend()\n \n# fig.savefig(res_path/'02_Dispatch Data'/f'{today}_Cell Dispatch_{red_factor_th}_{minimum_voltage}.png')\n# # \n# return", "_____no_output_____" ], [ "def getNextHigher(num, li):\n higher = []\n for number in li:\n if number>num:\n higher.append(number)\n \n if higher:\n lowest = sorted(higher)[0]\n return lowest\n else: ## for when C rate is higher than all listed\n return 0", "_____no_output_____" ], [ "def getNextLower(num, li):\n lower = []\n for number in li:\n if number<num:\n lower.append(number)\n \n if lower:\n highest = sorted(lower, reverse = True)[0]\n return lowest\n else: ## for when C rate is higher than all listed\n return 0", "_____no_output_____" ], [ "## Function that carries out linear interpolution\ndef linInterp(low_a,high_a,low_p,high_p,p): \n # a = actual data being interpolated, p = data that determines interpolation coefficient\n result = low_a + (high_a-low_a)*((p-low_p)/(high_p-low_p))\n ## In the boundary cases:\n if low_p == high_p:\n if p<low_p:\n result = low_a\n else:\n result=high_a\n return result", "_____no_output_____" ], [ "# Empirical Model Coefficients\nempiricalModelCoeffs = {}\n\n## FOR LFP (from paper: https://www.sciencedirect.com/science/article/abs/pii/S0378775310021269)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [30330, 19330, 12000, 11500]\nCoef['Ea']=[31500, 31000, 29500, 28000]\nCoef['z']=[0.552, 0.554,0.56,0.56]\nempiricalModelCoeffs['LFP'] = Coef\n\n## FOR NMC (estimate)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [40000, 30000, 25000, 20000]\nCoef['Ea']=[30000, 29500, 29000, 28000]\nCoef['z']=[ 0.552, 0.554,0.56,0.56]\nempiricalModelCoeffs['NMC'] = Coef\n\n## FOR NCA (estimate)\n# (short cycle life, high energy density)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [60660, 38000, 25000, 23000]\nCoef['Ea']=[29000, 29000, 28000, 28000]\nCoef['z']=[0.6, 0.62,0.64,0.65]\nempiricalModelCoeffs['NCA'] = Coef\n\n## FOR LCO (estimate)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [50000, 40000, 30000, 25000]\nCoef['Ea']=[31500, 31000, 29500, 28000]\nCoef['z']=[0.57, 0.572,0.58,0.58]\nempiricalModelCoeffs['LCO'] = Coef\n\n## FOR IMR (estimate)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [50500, 45000, 30000, 30000]\nCoef['Ea']=[31500, 31000, 29500, 28000]\nCoef['z']=[0.552, 0.554,0.56,0.56]\nempiricalModelCoeffs['IMR'] = Coef\n\n## FOR LTO (estimate)\nCoef = pd.DataFrame()\nCoef['C-rate'] = [0.5,2,6,10]\nCoef['B'] = [15000, 10000, 6000, 5000]\nCoef['Ea']=[31500, 31000, 29500, 28000]\nCoef['z']=[0.552, 0.554,0.56,0.56]\nempiricalModelCoeffs['LTO'] = Coef", "{'lfp': C-rate B Ea z\n0 0.5 30330 31500 0.552\n1 2.0 19330 31000 0.554\n2 6.0 12000 29500 0.560\n3 10.0 11500 28000 0.560}\n" ], [ "## Function to carry out degradation modelling from processed data\ndef empiricalDegModel(df,design_dict, EOL, chem,chem_nom_voltage, chem_nom_cap):\n ## empirical model#\n tot_dur = (df.iloc[[-1]]['time']+df.iloc[[-1]]['disch_dur']+df.iloc[[-1]]['ch_dur']+df.iloc[[-1]]['rest_dur']).values[0]\n t_df = df[['cycle_num','time','disch_dur','ch_dur','rest_dur','disch_th_kWh','ch_th_kWh','av_temp','avg_ch_C']]\n t_df['avg_ch_C'] = abs(t_df['avg_ch_C']) #making all C rates +ive\n getNearest = lambda num,collection:min(collection,key=lambda x:abs(x-num))\n \n # Empirical Model Coefficients: dependant on chemistry\n Coef = pd.DataFrame()\n Coef = empiricalModelCoeffs[chem]\n \n # Initial Conditions\n R = 8.3144626 # gas constant\n running_deg = 0\n running_SOH = 100\n \n for index, row in t_df.iterrows():\n \n ##Getting Boundary C rates to interpolate coefficients: capped by highest and lowest val (no exterpolation)\n highC = getNextHigher(row['avg_ch_C'],Coef['C-rate'].tolist())\n if highC == 0:\n highC = max(Coef['C-rate'].tolist())\n lowC = highC\n else:\n lowC = getNextLower(row['avg_ch_C'],Coef['C-rate'].tolist())\n if lowC == 0:\n lowC = min(Coef['C-rate'].tolist())\n \n t_df.loc[t_df['cycle_num']==row['cycle_num'],'avg_ch_C'] = row['avg_ch_C']\n\n ## Interpolating Degradation Coefficients (for relevant C rate)\n B = linInterp(Coef.loc[Coef['C-rate']==lowC,'B'].values[0],\n Coef.loc[Coef['C-rate']==highC,'B'].values[0], \n lowC, highC, row['avg_ch_C'])\n Ea = linInterp(Coef.loc[Coef['C-rate']==lowC,'Ea'].values[0],\n Coef.loc[Coef['C-rate']==highC,'Ea'].values[0], \n lowC, highC, row['avg_ch_C'])\n z = linInterp(Coef.loc[Coef['C-rate']==lowC,'z'].values[0],\n Coef.loc[Coef['C-rate']==highC,'z'].values[0], \n lowC, highC, row['avg_ch_C'])\n \n av_th = (row['disch_th_kWh']+(-row['ch_th_kWh']))/2\n Ah = ((av_th*1000)/(chem_nom_voltage*design_dict['tot_cells']))*(2/chem_nom_cap)\n # Ah throughput per cell: (average of charge and discharge)\n # equivalent to throughput through a 2.2 Ah LFP (derated to 2Ah) with same no. of cycles\n \n temp = row['av_temp']+273.15 # Temperature (K)\n Qloss = B*(math.exp(-(Ea)/(R*temp)))*(Ah**z)# % capacity loss\n t_df.loc[t_df['cycle_num']==row['cycle_num'],'Qloss'] = Qloss\n \n running_SOH = running_SOH*((100-(Qloss))/100)\n running_deg = 100 - running_SOH\n t_df.loc[t_df['cycle_num']==row['cycle_num'],'running_deg'] = running_deg\n \n end_SOH = running_SOH\n \n ## Calculation of degradation life from EoL condition and running SoH\n deg_life = tot_dur*((np.log(EOL/100)/(np.log(end_SOH/100))))\n \n ## Storing data into dictionary\n deg_dict['test_dur'] = tot_dur\n deg_dict['end_SOH'] = end_SOH\n deg_dict['deg_life'] = deg_life\n \n return deg_dict", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe312621c1ccd63d49508dd97ba9e062600d1de
4,313
ipynb
Jupyter Notebook
code/classification/create-separate-datasets.ipynb
vlada-rozova/self-harm-jamia
27d3b3ad66ae1298e05868f89059d10e3ea689f5
[ "MIT" ]
null
null
null
code/classification/create-separate-datasets.ipynb
vlada-rozova/self-harm-jamia
27d3b3ad66ae1298e05868f89059d10e3ea689f5
[ "MIT" ]
null
null
null
code/classification/create-separate-datasets.ipynb
vlada-rozova/self-harm-jamia
27d3b3ad66ae1298e05868f89059d10e3ea689f5
[ "MIT" ]
null
null
null
20.060465
113
0.517505
[ [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "df = pd.read_csv(\"../../data/rmh_raw.csv\")\ndf.shape", "_____no_output_____" ], [ "df.SH.value_counts(dropna=False)", "_____no_output_____" ], [ "df.SI.value_counts(dropna=False)", "_____no_output_____" ], [ "df.SH.sum() / df.shape[0] * 100", "_____no_output_____" ] ], [ [ "**Create a holdout set**", "_____no_output_____" ] ], [ [ "df_ho = df[df.year==2018].copy()", "_____no_output_____" ], [ "df_ho.SH.value_counts(dropna=False)", "_____no_output_____" ], [ "df_ho.SI.value_counts(dropna=False)", "_____no_output_____" ], [ "df_ho[(df_ho.SH == 1) & (df_ho.SI == 1)].shape", "_____no_output_____" ], [ "df_ho.SH.sum() / df_ho.shape[0] * 100", "_____no_output_____" ], [ "df_ho.SI.sum() / df_ho.shape[0] * 100", "_____no_output_____" ], [ "df_ho.to_csv(\"../../data/rmh_raw_holdout.csv\", index=False)", "_____no_output_____" ], [ "df.drop(df[df.year==2018].index, inplace=True)\ndf.reset_index(drop=True, inplace=True)", "_____no_output_____" ] ], [ [ "**Number and percentage of SH cases**", "_____no_output_____" ] ], [ [ "df.SH.value_counts(dropna=False)", "_____no_output_____" ], [ "df.SH.sum() / df.shape[0] * 100", "_____no_output_____" ] ], [ [ "**Create a train/test split**", "_____no_output_____" ] ], [ [ "df_train, df_test = train_test_split(df, test_size=0.2, random_state=42, stratify=df.SH)\n\ndef size_mb(docs):\n return sum(len(s.encode('utf-8')) for s in docs) / 1e6\n\nprint(\"Data loaded\")\n\nprint(\"The training set contains {} records ({:.3f}MB):\".format(df_train.shape[0], size_mb(df_train)))\nprint(df_train.SH.value_counts())\nprint(\"\\nThe test set contains {} records ({:.3f}MB):\".format(df_test.shape[0], size_mb(df_test)))\nprint(df_test.SH.value_counts())", "_____no_output_____" ], [ "df_train.to_csv(\"../../data/rmh_raw_train.csv\", index=False)\ndf_test.to_csv(\"../../data/rmh_raw_test.csv\", index=False)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe317186289268f5453eb41b300c77af226c957
762,849
ipynb
Jupyter Notebook
churn_predict.ipynb
ftatarli/telecom_churn_predict
674426d3af0a2a87837a31d5e87628adea00c5aa
[ "MIT" ]
null
null
null
churn_predict.ipynb
ftatarli/telecom_churn_predict
674426d3af0a2a87837a31d5e87628adea00c5aa
[ "MIT" ]
null
null
null
churn_predict.ipynb
ftatarli/telecom_churn_predict
674426d3af0a2a87837a31d5e87628adea00c5aa
[ "MIT" ]
null
null
null
249.786837
339,800
0.863377
[ [ [ "import numpy as np\nimport pandas as pd\nfrom pandas.plotting import scatter_matrix\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set(style=\"white\")\n\n%matplotlib inline ", "_____no_output_____" ] ], [ [ "<h3>Carrega os arquivos e padroniza os sem informação</h3>", "_____no_output_____" ] ], [ [ "missing_values = [\"n/a\", \"na\", \"--\", \" \"] # mais comuns\ndf = pd.read_csv(\"/Users/filipetatarli/Documents/WA_Fn-UseC_-Telco-Customer-Churn.csv\", na_values = missing_values)", "_____no_output_____" ], [ "df.head(3)", "_____no_output_____" ] ], [ [ "<h3>Verifica se há valores não preenchidos</h3>", "_____no_output_____" ] ], [ [ "df.isnull().sum() # verificando se há valores não preenchidos", "_____no_output_____" ], [ "df.TotalCharges.fillna(value = df.tenure * df.MonthlyCharges, inplace = True)\ndf.isnull().sum() # verificando se há valores não preenchidos", "_____no_output_____" ] ], [ [ "<h2> Estuda variáveis </h2>", "_____no_output_____" ] ], [ [ "colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']\n\nax = df.groupby('Churn').size().transform(lambda x: x/x.sum())\n#ax.plot.pie(legend=\"True\")\nax.plot.pie(autopct='%1.1f%%', startangle=90,shadow=True,colors = colors)\n\n## https://medium.com/@kvnamipara/a-better-visualisation-of-pie-charts-by-matplotlib-935b7667d77f\n", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 7043 entries, 0 to 7042\nData columns (total 21 columns):\ncustomerID 7043 non-null object\ngender 7043 non-null object\nSeniorCitizen 7043 non-null int64\nPartner 7043 non-null object\nDependents 7043 non-null object\ntenure 7043 non-null int64\nPhoneService 7043 non-null object\nMultipleLines 7043 non-null object\nInternetService 7043 non-null object\nOnlineSecurity 7043 non-null object\nOnlineBackup 7043 non-null object\nDeviceProtection 7043 non-null object\nTechSupport 7043 non-null object\nStreamingTV 7043 non-null object\nStreamingMovies 7043 non-null object\nContract 7043 non-null object\nPaperlessBilling 7043 non-null object\nPaymentMethod 7043 non-null object\nMonthlyCharges 7043 non-null float64\nTotalCharges 7043 non-null float64\nChurn 7043 non-null object\ndtypes: float64(2), int64(2), object(17)\nmemory usage: 1.1+ MB\n" ], [ "# PADRONIZANDO COLUNAS \ndf.drop([\"customerID\"], axis=1, inplace=True)\ndf['gender'] = df['gender'].apply(lambda x: 1 if x == 'Male' else 0)\ndf['Partner'] = df['Partner'].str.lower().replace({\"yes\": 1, \"no\": 0})\ndf['Dependents'] = df['Dependents'].str.lower().replace({\"yes\": 1, \"no\": 0})\ndf['PhoneService'] = df['PhoneService'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['OnlineSecurity'] = df['OnlineSecurity'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['TechSupport'] = df['TechSupport'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['StreamingTV'] = df['StreamingTV'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['StreamingMovies'] = df['StreamingMovies'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['PaperlessBilling'] = df['PaperlessBilling'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['OnlineBackup'] = df['OnlineBackup'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['DeviceProtection'] = df['DeviceProtection'].str.lower().replace({\"yes\": 1, \"no\": 0, \"no internet service\": 0})\ndf['Churn'] = df['Churn'].str.lower().replace({\"yes\": 1, \"no\": 0})", "_____no_output_____" ], [ "display(df[['tenure','MonthlyCharges','TotalCharges']].describe())", "_____no_output_____" ], [ "sns.countplot(x=\"Contract\", data=df)", "_____no_output_____" ], [ "g = sns.FacetGrid(df, col=\"Churn\", size=10, palette=\"Set1\")\ng.map(sns.countplot, \"PaymentMethod\", alpha=.7);", "/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py:230: UserWarning: The `size` paramter has been renamed to `height`; please update your code.\n warnings.warn(msg, UserWarning)\n/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py:715: UserWarning: Using the countplot function without specifying `order` is likely to produce an incorrect plot.\n warnings.warn(warning)\n" ], [ "g = sns.FacetGrid(df, row=\"Churn\", height=1.7, aspect=4,)\ng.map(sns.distplot, \"MonthlyCharges\", hist=False, rug=False);", "_____no_output_____" ] ], [ [ "<h2> Achando Outliers </h2>", "_____no_output_____" ] ], [ [ "sns.boxplot(x=df['MonthlyCharges'])", "_____no_output_____" ], [ "pal = dict([(1,'seagreen'), (0,'gray')])\ng = sns.FacetGrid(df, hue=\"Churn\", palette=pal, height=5, size=8)\ng.map(plt.scatter, \"TotalCharges\", \"tenure\", s=50, alpha=.5, linewidth=.4, edgecolor=\"white\")\ng.add_legend();\n\n\n# https://github.com/mwaskom/seaborn/issues/1114", "/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py:230: UserWarning: The `size` paramter has been renamed to `height`; please update your code.\n warnings.warn(msg, UserWarning)\n" ], [ "#sns.pairplot(df[['tenure','MonthlyCharges','TotalCharges']]);\nsns.distplot(df['MonthlyCharges']);", "_____no_output_____" ], [ "df_log_transformed = df \ndf_log_transformed['MonthlyCharges'] = df['MonthlyCharges'].apply(lambda x: np.log(x + 1))", "_____no_output_____" ], [ "# REMOVENDO OUTLOIERS\n", "_____no_output_____" ], [ "sns.boxplot(y=df[\"TotalCharges\"])", "_____no_output_____" ], [ "# Produza uma matriz de dispersão para cada um dos pares de atributos dos dados\nscatter_matrix(df[['tenure','MonthlyCharges','TotalCharges']], alpha=0.3, figsize = (10,8), diagonal = 'kde')", "_____no_output_____" ], [ "plt.figure(figsize=(12,8))\n\nsubjective_corr = df.corr()\n\nmask = np.zeros_like(df, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\nsns.heatmap(df.corr(), annot = True, linewidths=.5, cmap='coolwarm', mask = mask)", "_____no_output_____" ], [ "# EXPLICAÇÃO", "_____no_output_____" ], [ "# GRAFICOS ", "_____no_output_____" ], [ "gp = df.groupby('Contract')[\"Churn\"].value_counts()/len(df)\ngp = gp.to_frame().rename({\"Churn\": \"Porcentagem\"}, axis=1).reset_index()\nsns.barplot(x='Contract', y=\"Porcentagem\", hue=\"Churn\", data=gp)", "_____no_output_____" ], [ "## CORRELAcao", "_____no_output_____" ], [ "df.dtypes.value_counts()", "_____no_output_____" ], [ "# TODO: Utilize o one-hot encoding nos dados em 'features_log_minmax_transform' utilizando pandas.get_dummies()\nfeatures_final = pd.get_dummies(df)", "_____no_output_____" ], [ "encoded = list(features_final.columns)\nprint(encoded)", "['gender', 'SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies', 'PaperlessBilling', 'MonthlyCharges', 'TotalCharges', 'Churn', 'MultipleLines_No', 'MultipleLines_No phone service', 'MultipleLines_Yes', 'InternetService_DSL', 'InternetService_Fiber optic', 'InternetService_No', 'Contract_Month-to-month', 'Contract_One year', 'Contract_Two year', 'PaymentMethod_Bank transfer (automatic)', 'PaymentMethod_Credit card (automatic)', 'PaymentMethod_Electronic check', 'PaymentMethod_Mailed check']\n" ], [ "features_final", "_____no_output_____" ], [ "df['SeniorCitizen'].value_counts()\nsns.countplot(x=\"Contract\", data=df)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe319fae160a79e470e55c031934ed53f2b735a
7,741
ipynb
Jupyter Notebook
map_Neic.ipynb
annefou/neicAllHands
e85f2647307a760b99e404130601acc0298c3f19
[ "MIT" ]
null
null
null
map_Neic.ipynb
annefou/neicAllHands
e85f2647307a760b99e404130601acc0298c3f19
[ "MIT" ]
null
null
null
map_Neic.ipynb
annefou/neicAllHands
e85f2647307a760b99e404130601acc0298c3f19
[ "MIT" ]
null
null
null
24.190625
122
0.43767
[ [ [ "import ipyleaflet as ipyl\nimport ipywidgets as ipyw\nimport json\nimport numpy as np\nimport pandas as pd\nfrom shapely.geometry import shape, Point\nfrom ipywidgets import jslink, IntSlider\n\nfrom traitlets import link", "_____no_output_____" ], [ "# generate Reindeer positions\nnvalues = 10\nlons = 7.48 + np.random.rand(nvalues,1)\nlons\n\nlats = 60.58 + np.random.rand(nvalues,1)\npd.DataFrame(np.concatenate((lons,lats),axis=1), columns=[\"lon\", \"lat\"]).to_csv(\"reindeers.csv\", index=False)", "_____no_output_____" ], [ "# Read reindeer positions\nreindeers = pd.read_csv(\"reindeers.csv\")\nreindeers", "_____no_output_____" ], [ "lon, lat = 7.48, 60.58\nzoom_start = 6\nm = ipyl.Map(\n# layers=(basemap_to_tiles(basemaps.OpenTopoMap), ),\n center=(lat, lon)\n)\nzoom_slider = IntSlider(description='Zoom', min=3, max=17, value=zoom_start)\njslink((zoom_slider, 'value'), (m, 'zoom'))", "_____no_output_____" ], [ "with open('/home/deeplearning/detect_cwd/nordfjella.json') as f:\n geo_json_data = json.load(f)", "_____no_output_____" ], [ "layer = ipyl.GeoJSON(data=geo_json_data)\nm.add_layer(layer)", "_____no_output_____" ], [ "\n# Black if healthy and red if CWD\nmarkers = ()\nfor lon,lat in zip(reindeers['lon'],reindeers['lat']):\n point = Point(lon,lat)\n outside=True\n for s in geo_json_data['features']:\n polygon = shape(s['geometry'])\n if point.within(polygon):\n print(\"INSIDE: Raise alarm\")\n outside=False\n \n if (outside):\n print(\"OUTSIDE\") \n markers= markers + (ipyl.Marker(location=(lat,lon)),)\n \nmarker_cluster = ipyl.MarkerCluster(\n markers=markers\n) \nm.add_layer(marker_cluster)", "OUTSIDE\nINSIDE: Raise alarm\nOUTSIDE\nOUTSIDE\nOUTSIDE\nINSIDE: Raise alarm\nOUTSIDE\nOUTSIDE\nOUTSIDE\nOUTSIDE\n" ], [ "m", "_____no_output_____" ], [ "zoom_slider", "_____no_output_____" ], [ "dc = ipyl.DrawControl()\n\ndef handle_draw(self, action, geo_json):\n print(action)\n print(geo_json)\n\ndc.on_draw(handle_draw)\nm.add_control(dc)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe331e09c086ace636c53769a44589f88ae2e82
19,859
ipynb
Jupyter Notebook
tutorial/1-basics.ipynb
zwangab91/ctw-baseline
f05560eaa5fc08cf61711479437e6dde7fa0114c
[ "MIT" ]
333
2018-03-09T12:50:49.000Z
2022-02-10T04:02:50.000Z
tutorial/1-basics.ipynb
zwangab91/ctw-baseline
f05560eaa5fc08cf61711479437e6dde7fa0114c
[ "MIT" ]
43
2018-03-19T08:11:28.000Z
2021-03-03T08:19:35.000Z
tutorial/1-basics.ipynb
zwangab91/ctw-baseline
f05560eaa5fc08cf61711479437e6dde7fa0114c
[ "MIT" ]
105
2018-03-15T10:17:50.000Z
2021-11-08T02:46:26.000Z
38.044061
288
0.58014
[ [ [ "# CTW dataset tutorial (Part 1: basics)\n\nHello, welcome to the tutorial of _Chinese Text in the Wild_ (CTW) dataset. In this tutorial, we will show you:\n\n1. [Basics](#CTW-dataset-tutorial-(Part-1:-Basics)\n\n - [The structure of this repository](#The-structure-of-this-repository)\n - [Dataset split](#Dataset-Split)\n - [Download images and annotations](#Download-images-and-annotations)\n - [Annotation format](#Annotation-format)\n - [Draw annotations on images](#Draw-annotations-on-images)\n - [Appendix: Adjusted bounding box conversion](#Appendix:-Adjusted-bounding-box-conversion)\n\n2. Classification baseline\n\n - Train classification model\n - Results format and evaluation API\n - Evaluate your classification model\n\n3. Detection baseline\n\n - Train detection model\n - Results format and evaluation API\n - Evaluate your classification model\n\nOur homepage is https://ctwdataset.github.io/, you may find some more useful information from that.\n\nIf you don't want to run the baseline code, please jump to [Dataset split](#Dataset-Split) and [Annotation format](#Annotation-format) sections.\n\nNotes:\n > This notebook MUST be run under `$CTW_ROOT/tutorial`.\n >\n > All the code SHOULD be run with `Python>=3.4`. We make it compatible with `Python>=2.7` with best effort.\n >\n > The key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL NOT\", \"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and \"OPTIONAL\" in this document are to be interpreted as described in [RFC 2119](https://tools.ietf.org/html/rfc2119).", "_____no_output_____" ], [ "## The structure of this repository\n\nOur git repository is `[email protected]:yuantailing/ctw-baseline.git`, which you can browse from [GitHub](https://github.com/yuantailing/ctw-baseline).\n\nThere are several directories under `$CTW_ROOT`.\n\n - **tutorial/**: this tutorial\n - **data/**: download and place images and annotations\n - **prepare/**: prepare dataset splits\n - **classification/**: classification baselines using [TensorFlow](https://www.tensorflow.org/)\n - **detection/**: a detection baseline using [YOLOv2](https://pjreddie.com/darknet/yolo/)\n - **judge/**: evaluate testing results and draw results and statistics\n - **pythonapi/**: APIs to traverse annotations, to evaluate results, and for common use\n - **cppapi/**: a faster implementation to detection AP evaluation\n - **codalab/**: which we run on [CodaLab](https://competitions.codalab.org/competitions/?q=CTW) (our evaluation server)\n - **ssd/**: a detection method using [SSD](https://github.com/weiliu89/caffe/tree/ssd)\n\nMost of the above directories have some similar structures.\n\n - **\\*/settings.py**: configure directory of images, file path to annotations, and dedicated configurations for each step\n - **\\*/products/**: store temporary files, logs, middle products, and final products \n - **\\*/pythonapi**: a symbolic link to `pythonapi/`, in order to use Python API more conveniently\n\nMost of the code is written in Python, while some code is written in C++, Shell, etc.\n\nAll the code is purposed to run in subdirectories, e.g., it's correct to execute `cd $CTW_ROOT/detection && python3 train.py`, and it's incorrect to execute `cd $CTW_ROOT && python3 detection/train.py`.\n\nAll our code won't create or modify any files out of `$CTW_ROOT` (except `/tmp/`), and don't need a privilege elevation (except for running docker workers on the evaluation server). You SHOULD install requirements before you run our code.\n\n - git>=1\n - Python>=3.4\n - Jupyter notebook>=5.0\n - gcc>=5\n - g++>=5\n - CUDA driver\n - CUDA toolkit>=8.0\n - CUDNN>=6.0\n - OpenCV>=3.0\n - requirements listed in `$CTW_ROOT/requirements.txt`\n\nRecommonded hardware requirements:\n\n - RAM >= 32GB\n - GPU memory >= 12 GB\n - Hard Disk free space >= 200 GB\n - CPU logical cores >= 8\n - Network connection", "_____no_output_____" ], [ "## Dataset Split\n\nWe split the dataset into 4 parts:\n\n1. Training set (~75%)\n\n For each image in training set, the annotation contains a lot of lines, while each lines contains some character instances.\n \n Each character instance contains:\n \n - its underlying character,\n - its bounding box (polygon),\n - and 6 attributes.\n\n Only Chinese character instances are completely annotated, non-Chinese characters (e.g., ASCII characters) are partially annotated.\n\n Some ignore regions are annotated, which contain character instances that cannot be recognized by human (e.g., too small, too fuzzy).\n\n We will show the annotation format in [next sections](#Annotation-format).\n\n2. Validation set (~5%)\n\n Annotations in validation set is the same as that in training set.\n \n The split between training set and validation set is only a recommendation. We make no restriction on how you split them. To enlarge training data, you MAY use TRAIN+VAL to train your models.\n\n3. Testing set for classification (~10%)\n\n For this testing set, we make images and annotated bounding boxes publicly available. Underlying character, attributes and ignored regions are not avaliable.\n\n To evaluate your results on testing set, please visit our evaluation server.\n\n4. Testing set for detection (~10%)\n\n For this testing set, we make images public.\n\n To evaluate your results on testing set, please visit our evaluation server.\n\nNotes:\n \n > You MUST NOT use annotations of testing set to fine tune your models or hyper-parameters. (e.g. use annotations of classification testing set to fine tune your detection models)\n >\n > You MUST NOT use evaluation server to fine tune your models or hyper-parameters.", "_____no_output_____" ], [ "## Download images and annotations\n\nVisit our homepage (https://ctwdataset.github.io/) and gain access to the dataset.\n\n1. Clone our git repository.\n\n ```sh\n$ git clone [email protected]:yuantailing/ctw-baseline.git\n```\n\n1. Download images, and unzip all the images to `$CTW_ROOT/data/all_images/`.\n\n For image file path, both `$CTW_ROOT/data/all_images/0000001.jpg` and `$CTW_ROOT/data/all_images/any/path/0000001.jpg` are OK, do not modify file name.\n\n1. Download annotations, and unzip it to `$CTW_ROOT/data/annotations/downloads/`.\n\n ```sh\n$ mkdir -p ../data/annotations/downloads && tar -xzf /path/to/ctw-annotations.tar.gz -C../data/annotations/downloads\n```\n\n1. In order to run evaluation and analysis code locally, we will use validation set as testing sets in this tutorial.\n\n ```sh\n$ cd ../prepare && python3 fake_testing_set.py\n```\n\n If you propose to train your model on TRAIN+VAL, you can execute `cp ../data/annotations/downloads/* ../data/annotations/` instead of running the above code. But you will not be able to run evaluation and analysis code locally, just submit the results to our evaluation server.\n\n1. Create symbolic links for TRAIN+VAL (`$CTW_ROOT/data/images/trainval/`) and TEST(`$CTW_ROOT/data/images/test/`) set, respectively.\n\n ```sh\n$ cd ../prepare && python3 symlink_images.py\n```", "_____no_output_____" ], [ "## Annotation format\n\nIn this section, we will show you:\n\n- Overall information format\n- Training set annotation format\n- Classification testing set format\n\nWe will display some examples in the next section.\n\n#### Overall information format\n\nOverall information file (`../data/annotations/info.json`) is UTF-8 (no BOM) encoded [JSON](https://www.json.org/).\n\nThe data struct for this information file is described below.\n\n```\ninformation:\n{\n train: [image_meta_0, image_meta_1, image_meta_2, ...],\n val: [image_meta_0, image_meta_1, image_meta_2, ...],\n test_cls: [image_meta_0, image_meta_1, image_meta_2, ...],\n test_det: [image_meta_0, image_meta_1, image_meta_2, ...],\n}\n\nimage_meta:\n{\n image_id: str,\n file_name: str,\n width: int,\n height: int,\n}\n```\n`train`, `val`, `test_cls`, `test_det` keys denote to training set, validation set, testing set for classification, testing set for detection, respectively.\n\nThe resolution of each image is always $2048 \\times 2048$. Image ID is a 7-digits string, the first digit of image ID indicates the camera orientation in the following rule.\n\n - '0': back\n - '1': left\n - '2': front\n - '3': right\n\nThe `file_name` filed doesn't contain directory name, and is always `image_id + '.jpg'`.\n\n#### Training set annotation format\n\nAll `.jsonl` annotation files (e.g. `../data/annotations/train.jsonl`) are UTF-8 encoded [JSON Lines](http://jsonlines.org/), each line is corresponding to the annotation of one image.\n\nThe data struct for each of the annotations in training set (and validation set) is described below.\n```\nannotation (corresponding to one line in .jsonl):\n{\n image_id: str,\n file_name: str,\n width: int,\n height: int,\n annotations: [sentence_0, sentence_1, sentence_2, ...], # MUST NOT be empty\n ignore: [ignore_0, ignore_1, ignore_2, ...], # MAY be an empty list\n}\n\nsentence:\n[instance_0, instance_1, instance_2, ...] # MUST NOT be empty\n\ninstance:\n{\n polygon: [[x0, y0], [x1, y1], [x2, y2], [x3, y3]], # x, y are floating-point numbers\n text: str, # the length of the text MUST be exactly 1\n is_chinese: bool,\n attributes: [attr_0, attr_1, attr_2, ...], # MAY be an empty list\n adjusted_bbox: [xmin, ymin, w, h], # x, y, w, h are floating-point numbers\n}\n\nattr:\n\"occluded\" | \"bgcomplex\" | \"distorted\" | \"raised\" | \"wordart\" | \"handwritten\"\n\nignore:\n{\n polygon: [[x0, y0], [x1, y1], [x2, y2], [x3, y3]],\n bbox: [xmin, ymin, w, h],\n]\n```\n\nOriginal bounding box annotations are polygons, we will describe how `polygon` is converted to `adjusted_bbox` in [appendix](#Appendix:-Adjusted-bounding-box-conversion).\n\nNotes:\n\n > The order of lines are not guaranteed to be consistent with `info.json`.\n >\n > A polygon MUST be a quadrangle.\n >\n > All characters in `CJK Unified Ideographs` are considered to be Chinese, while characters in `ASCII` and `CJK Unified Ideographs Extension`(s) are not.\n >\n > Adjusted bboxes of character `instance`s MUST be intersected with the image, while bboxes of `ignore` regions may not.\n >\n > Some logos on the camera car (e.g., \"`腾讯街景地图`\" in `2040368.jpg`) and licence plates are ignored to avoid bias.\n\n#### Classification testing set format\n\nThe data struct for each of the annotations in classification testing set is described below.\n\n```\nannotation:\n{\n image_id: str,\n file_name: str,\n width: int,\n height: int,\n proposals: [proposal_0, proposal_1, proposal_2, ...],\n}\n\nproposal:\n{\n polygon: [[x0, y0], [x1, y1], [x2, y2], [x3, y3]],\n adjusted_bbox: [xmin, ymin, w, h],\n}\n```\n\nNotes:\n\n > The order of `image_id` in each line are not guaranteed to be consistent with `info.json`.\n >\n > Non-Chinese characters (e.g., ASCII characters) MUST NOT appear in proposals.", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport json\nimport pprint\nimport settings\n\nfrom pythonapi import anno_tools\n\nprint('Image meta info format:')\nwith open(settings.DATA_LIST) as f:\n data_list = json.load(f)\npprint.pprint(data_list['train'][0])", "_____no_output_____" ], [ "print('Training set annotation format:')\nwith open(settings.TRAIN) as f:\n anno = json.loads(f.readline())\npprint.pprint(anno, depth=3)", "_____no_output_____" ], [ "print('Character instance format:')\npprint.pprint(anno['annotations'][0][0])", "_____no_output_____" ], [ "print('Traverse character instances in an image')\nfor instance in anno_tools.each_char(anno):\n print(instance['text'], end=' ')\nprint()", "_____no_output_____" ], [ "print('Classification testing set format')\nwith open(settings.TEST_CLASSIFICATION) as f:\n anno = json.loads(f.readline())\npprint.pprint(anno, depth=2)", "_____no_output_____" ], [ "print('Classification testing set proposal format')\npprint.pprint(anno['proposals'][0])", "_____no_output_____" ] ], [ [ "## Draw annotations on images\n\nIn this section, we will draw annotations on images. This would help you to understand the format of annotations.\n\nWe show polygon bounding boxes of Chinese character instances in **<span style=\"color: #0f0;\">green</span>**, non-Chinese character instances in **<span style=\"color: #f00;\">red</span>**, and ignore regions in **<span style=\"color: #ff0;\">yellow</span>**.", "_____no_output_____" ] ], [ [ "import cv2\nimport json\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\nimport os\nimport settings\n\nfrom pythonapi import anno_tools\n\n%matplotlib inline\n\nwith open(settings.TRAIN) as f:\n anno = json.loads(f.readline())\npath = os.path.join(settings.TRAINVAL_IMAGE_DIR, anno['file_name'])\nassert os.path.exists(path), 'file not exists: {}'.format(path)\nimg = cv2.imread(path)\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\nplt.figure(figsize=(16, 16))\nax = plt.gca()\nplt.imshow(img)\nfor instance in anno_tools.each_char(anno):\n color = (0, 1, 0) if instance['is_chinese'] else (1, 0, 0)\n ax.add_patch(patches.Polygon(instance['polygon'], fill=False, color=color))\nfor ignore in anno['ignore']:\n color = (1, 1, 0)\n ax.add_patch(patches.Polygon(ignore['polygon'], fill=False, color=color))\nplt.show()", "_____no_output_____" ] ], [ [ "## Appendix: Adjusted bounding box conversion\n\nIn order to create a tighter bounding box to character instances, we compute `adjusted_bbox` in following steps, instead of use the real bounding box.\n\n 1. Take trisections for each edge of the polygon. (<span style=\"color: #f00;\">red points</span>)\n 2. Compute the bouding box of above points. (<span style=\"color: #00f;\">blue rectangles</span>)\n\nAdjusted bounding box is better than the real bounding box, especially for sharp polygons.", "_____no_output_____" ] ], [ [ "from __future__ import division\n\nimport collections\nimport matplotlib.patches as patches\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\ndef poly2bbox(poly):\n key_points = list()\n rotated = collections.deque(poly)\n rotated.rotate(1)\n for (x0, y0), (x1, y1) in zip(poly, rotated):\n for ratio in (1/3, 2/3):\n key_points.append((x0 * ratio + x1 * (1 - ratio), y0 * ratio + y1 * (1 - ratio)))\n x, y = zip(*key_points)\n adjusted_bbox = (min(x), min(y), max(x) - min(x), max(y) - min(y))\n return key_points, adjusted_bbox\n\npolygons = [\n [[2, 1], [11, 2], [12, 18], [3, 16]],\n [[21, 1], [30, 5], [31, 19], [22, 14]],\n]\n\nplt.figure(figsize=(10, 6))\nplt.xlim(0, 35)\nplt.ylim(0, 20)\nax = plt.gca()\nfor polygon in polygons:\n color = (0, 1, 0)\n ax.add_patch(patches.Polygon(polygon, fill=False, color=(0, 1, 0)))\n key_points, adjusted_bbox = poly2bbox(polygon)\n ax.add_patch(patches.Rectangle(adjusted_bbox[:2], *adjusted_bbox[2:], fill=False, color=(0, 0, 1)))\n for kp in key_points:\n ax.add_patch(patches.Circle(kp, radius=0.1, fill=True, color=(1, 0, 0)))\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe35205436688d747c87ea6cd0c531fd52c8b76
957
ipynb
Jupyter Notebook
Practice1.ipynb
Rontu22/Artificial-Intelligence-with-Python
dc71020b977da2a3caeb1be0b7e8839967d705ee
[ "MIT" ]
null
null
null
Practice1.ipynb
Rontu22/Artificial-Intelligence-with-Python
dc71020b977da2a3caeb1be0b7e8839967d705ee
[ "MIT" ]
null
null
null
Practice1.ipynb
Rontu22/Artificial-Intelligence-with-Python
dc71020b977da2a3caeb1be0b7e8839967d705ee
[ "MIT" ]
null
null
null
23.925
251
0.517241
[ [ [ "<a href=\"https://colab.research.google.com/github/Rontu22/Artificial-Intelligence-with-Python/blob/master/Practice1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cbe352c7f9b6d9cfe70e4e48aa186699e859b6a8
110,101
ipynb
Jupyter Notebook
demo/BEDICT_model_demonstration.ipynb
zxChouSean/crispr_bedict_reproduce
8590ddaeaefedd370a60c1f61043333371526766
[ "MIT" ]
5
2021-11-15T06:46:55.000Z
2022-03-04T06:47:57.000Z
demo/BEDICT_model_demonstration.ipynb
zxChouSean/crispr_bedict_reproduce
8590ddaeaefedd370a60c1f61043333371526766
[ "MIT" ]
null
null
null
demo/BEDICT_model_demonstration.ipynb
zxChouSean/crispr_bedict_reproduce
8590ddaeaefedd370a60c1f61043333371526766
[ "MIT" ]
3
2021-09-02T02:18:41.000Z
2021-09-18T13:32:09.000Z
57.31442
23,084
0.612837
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "import os\nimport datetime\nimport numpy as np\nimport scipy\nimport pandas as pd\nimport torch\nfrom torch import nn\n", "_____no_output_____" ], [ "import criscas\nfrom criscas.utilities import create_directory, get_device, report_available_cuda_devices\nfrom criscas.predict_model import *\n", "_____no_output_____" ], [ "base_dir = os.path.abspath('..')\nbase_dir", "_____no_output_____" ] ], [ [ "### Read sample data", "_____no_output_____" ] ], [ [ "seq_df = pd.read_csv(os.path.join(base_dir, 'sample_data', 'abemax_sampledata.csv'), header=0)", "_____no_output_____" ], [ "seq_df", "_____no_output_____" ] ], [ [ "The models expect sequences (i.e. target sites) to be wrapped in a `pandas.DataFrame` with a header that includes `ID` of the sequence and `seq` columns.\nThe sequences should be of length 20 (i.e. 20 bases) and represent the protospacer target site.", "_____no_output_____" ] ], [ [ "# create a directory where we dump the predictions of the models\ncsv_dir = create_directory(os.path.join(base_dir, 'sample_data', 'predictions'))", "_____no_output_____" ] ], [ [ "### Specify device (i.e. CPU or GPU) to run the models on", "_____no_output_____" ], [ "Specify device to run the model on. The models can run on `GPU` or `CPU`. We can instantiate a device by running `get_device(to_gpu,gpu_index)` function. \n\n- To run on GPU we pass `to_gpu = True` and specify which card to use if we have multiple cards `gpu_index=int` (i.e. in case we have multiple GPU cards we specify the index counting from 0). \n- If there is no GPU installed, the function will return a `CPU` device.", "_____no_output_____" ], [ "We can get a detailed information on the GPU cards installed on the compute node by calling `report_available_cuda_devices` function.", "_____no_output_____" ] ], [ [ "report_available_cuda_devices()", "_____no_output_____" ], [ "# instantiate a device using the only one available :P\ndevice = get_device(True, 0)\ndevice", "_____no_output_____" ] ], [ [ "### Create a BE-DICT model by sepcifying the target base editor ", "_____no_output_____" ], [ "We start `BE-DICT` model by calling `BEDICT_CriscasModel(base_editor, device)` where we specify which base editor to use (i.e. `ABEmax`, `BE4max`, `ABE8e`, `Target-AID`) and the `device` we create earlier to run on.", "_____no_output_____" ] ], [ [ "base_editor = 'ABEmax'\nbedict = BEDICT_CriscasModel(base_editor, device)", "_____no_output_____" ] ], [ [ "We generate predictions by calling `predict_from_dataframe(seq_df)` where we pass the data frame wrapping the target sequences. The function returns two objects:\n\n- `pred_w_attn_runs_df` which is a data frame that contains predictions per target base and the attentions scores across all positions.\n\n- `proc_df` which is a data frame that represents the processed sequence data frame we passed (i.e. `seq_df`)", "_____no_output_____" ] ], [ [ "pred_w_attn_runs_df, proc_df = bedict.predict_from_dataframe(seq_df)", "--- processing input data frame ---\n--- creating datatensor ---\n--- building model ---\n--- loading trained model ---\n/mnt/orisenbazuru/crispr/trained_models/perbase/ABEmax/train_val/run_0\nrunning prediction for base_editor: ABEmax | run_num: 0\n--- loading trained model ---\n/mnt/orisenbazuru/crispr/trained_models/perbase/ABEmax/train_val/run_1\nrunning prediction for base_editor: ABEmax | run_num: 1\n--- loading trained model ---\n/mnt/orisenbazuru/crispr/trained_models/perbase/ABEmax/train_val/run_2\nrunning prediction for base_editor: ABEmax | run_num: 2\n--- loading trained model ---\n/mnt/orisenbazuru/crispr/trained_models/perbase/ABEmax/train_val/run_3\nrunning prediction for base_editor: ABEmax | run_num: 3\n--- loading trained model ---\n/mnt/orisenbazuru/crispr/trained_models/perbase/ABEmax/train_val/run_4\nrunning prediction for base_editor: ABEmax | run_num: 4\n" ] ], [ [ "`pred_w_attn_runs_df` contains predictions from 5 trained models for `ABEmax` base editor (we have 5 runs trained per base editor). For more info, see our [paper](https://www.biorxiv.org/content/10.1101/2020.07.05.186544v1) on biorxiv.", "_____no_output_____" ], [ "Target positions in the sequence reported in `base_pos` column in `pred_w_attn_runs_df` uses 0-based indexing (i.e. 0-19)", "_____no_output_____" ] ], [ [ "pred_w_attn_runs_df", "_____no_output_____" ], [ "proc_df", "_____no_output_____" ] ], [ [ "Given that we have 5 predictions per sequence, we can further reduce to one prediction by either `averaging` across all models, or taking the `median` or `max` prediction based on the probability of editing scores. For this we use `select_prediction(pred_w_attn_runs_df, pred_option)` where `pred_w_attn_runs_df` is the data frame containing predictions from 5 models for each sequence. `pred_option` can be assume one of {`mean`, `median`, `max`}.", "_____no_output_____" ] ], [ [ "pred_option = 'mean'\npred_w_attn_df = bedict.select_prediction(pred_w_attn_runs_df, pred_option)", "_____no_output_____" ], [ "pred_w_attn_df", "_____no_output_____" ] ], [ [ "We can dump the prediction results on a specified directory on disk. We will dump the predictions with all 5 runs `pred_w_attn_runs_df` and the one average across runs `pred_w_attn_df`.", "_____no_output_____" ], [ "Under `sample_data` directory we will have the following tree:\n\n<pre>\nsample_data\n└── predictions\n ├── predictions_allruns.csv\n └── predictions_predoption_mean.csv\n</pre>", "_____no_output_____" ] ], [ [ "pred_w_attn_runs_df.to_csv(os.path.join(csv_dir, f'predictions_allruns.csv'))", "_____no_output_____" ], [ "pred_w_attn_df.to_csv(os.path.join(csv_dir, f'predictions_predoption_{pred_option}.csv'))", "_____no_output_____" ] ], [ [ "### Generate attention plots", "_____no_output_____" ], [ "We can generate attention plots for the prediction of each target base in the sequence using `highlight_attn_per_seq` method that takes the following arguments:\n\n- `pred_w_attn_runs_df`: data frame that contains model's predictions (5 runs) for each target base of each sequence (see above).\n- `proc_df`: data frame that represents the processed sequence data frame we passed (i.e. seq_df)\n- `seqid_pos_map`: dictionary `{seq_id:list of positions}` where `seq_id` is the ID of the target sequence, and list of positions that we want to generate attention plots for. Users can specify a `position from 1 to 20` (i.e. length of protospacer sequence)\n- `pred_option`: selection option for aggregating across 5 models' predictions. That is we can average the predictions across 5 runs, or take `max`, `median`, `min` or `None` (i.e. keep all 5 runs) \n- `apply_attnscore_filter`: boolean (`True` or `False`) to further apply filtering on the generated attention scores. This filtering allow to plot only predictions where the associated attention scores have a maximum that is >= 3 times the base attention score value <=> (3 * 1/20)\n- `fig_dir`: directory where to dump the generated plots or `None` (to return the plots inline)", "_____no_output_____" ] ], [ [ "# create a dictionary to specify target sequence and the position we want attention plot for\n# we are targeting position 5 in the sequence\nseqid_pos_map = {'CTRL_HEKsiteNO1':[5], 'CTRL_HEKsiteNO2':[5]}\npred_option = 'mean'\napply_attn_filter = False\nbedict.highlight_attn_per_seq(pred_w_attn_runs_df, \n proc_df,\n seqid_pos_map=seqid_pos_map,\n pred_option=pred_option, \n apply_attnscore_filter=apply_attn_filter, \n fig_dir=None)", "seq_id: CTRL_HEKsiteNO1\nhighlighting seqid:CTRL_HEKsiteNO1, pos:4\nseq_id: CTRL_HEKsiteNO2\nhighlighting seqid:CTRL_HEKsiteNO2, pos:4\n" ] ], [ [ "We can save the plots on disk without returning them by specifing `fig_dir`", "_____no_output_____" ] ], [ [ "# create a dictionary to specify target sequence and the position I want attention plot for\n# we are targeting position 5 in the sequence\nseqid_pos_map = {'CTRL_HEKsiteNO1':[5], 'CTRL_HEKsiteNO2':[5]}\npred_option = 'mean'\napply_attn_filter = False\nfig_dir = create_directory(os.path.join(base_dir, 'sample_data', 'fig_dir'))\nbedict.highlight_attn_per_seq(pred_w_attn_runs_df, \n proc_df,\n seqid_pos_map=seqid_pos_map,\n pred_option=pred_option, \n apply_attnscore_filter=apply_attn_filter, \n fig_dir=create_directory(os.path.join(fig_dir, pred_option)))", "seq_id: CTRL_HEKsiteNO1\nhighlighting seqid:CTRL_HEKsiteNO1, pos:4\nseq_id: CTRL_HEKsiteNO2\nhighlighting seqid:CTRL_HEKsiteNO2, pos:4\n" ] ], [ [ "We will generate the following files:\n\n<pre>\nsample_data\n├── abemax_sampledata.csv\n├── fig_dir\n│   └── mean\n│   ├── ABEmax_seqattn_CTRL_HEKsiteNO1_basepos_5_predoption_mean.pdf\n│   └── ABEmax_seqattn_CTRL_HEKsiteNO2_basepos_5_predoption_mean.pdf\n└── predictions\n ├── predictions_allruns.csv\n └── predictions_predoption_mean.csv\n</pre>", "_____no_output_____" ], [ "Similarly we can change the other arguments such as `pred_option` `apply_attnscore_filter` and so on to get different filtering options - We leave this as an exercise for the user/reader :D", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbe37f4dcd4e63d5e4d8cbb04afd65477d8b30c4
252,813
ipynb
Jupyter Notebook
Classifiers/Day3/Day_3_Basic_Features_256_1e-3_swish_mult2_50E_normedweighted_rot_cart__split1.ipynb
GilesStrong/Kaggle_HiggsML
5c066554f87defb29275f4e6f1930a1641d542bc
[ "MIT" ]
null
null
null
Classifiers/Day3/Day_3_Basic_Features_256_1e-3_swish_mult2_50E_normedweighted_rot_cart__split1.ipynb
GilesStrong/Kaggle_HiggsML
5c066554f87defb29275f4e6f1930a1641d542bc
[ "MIT" ]
null
null
null
Classifiers/Day3/Day_3_Basic_Features_256_1e-3_swish_mult2_50E_normedweighted_rot_cart__split1.ipynb
GilesStrong/Kaggle_HiggsML
5c066554f87defb29275f4e6f1930a1641d542bc
[ "MIT" ]
null
null
null
114.550521
97,912
0.842029
[ [ [ "# Day 3\nbatch size 256 lr 1e-3, normed weighted, rotated, cartesian, split ny jet mult (1)", "_____no_output_____" ], [ "### Import modules", "_____no_output_____" ] ], [ [ "%matplotlib inline\nfrom __future__ import division\nimport sys\nimport os\nos.environ['MKL_THREADING_LAYER']='GNU'\nsys.path.append('../')\nfrom Modules.Basics import *\nfrom Modules.Class_Basics import *", "/home/giles/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n/home/giles/anaconda2/lib/python2.7/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n from pandas.core import datetools\nUsing TensorFlow backend.\n" ] ], [ [ "## Options", "_____no_output_____" ] ], [ [ "nJets = '1'\ninputPipe, outputPipe = getPreProcPipes(normIn=True)\nclassModel = 'modelSwish'\nvarSet = \"filtered_rot_cart_features\"\n\nnSplits = 10\nensembleSize = 10\nensembleMode = 'loss'\n\nmaxEpochs = 200\ncompileArgs = {'loss':'binary_crossentropy', 'optimizer':'adam'}\ntrainParams = {'epochs' : 1, 'batch_size' : 256, 'verbose' : 0}\nmodelParams = {'version':classModel, 'nIn':22, 'compileArgs':compileArgs}", "_____no_output_____" ] ], [ [ "## Import data", "_____no_output_____" ] ], [ [ "trainData = h5py.File(dirLoc + 'train_' + nJets + '.hdf5', \"r+\")\nvalData = h5py.File(dirLoc + 'val_' + nJets + '.hdf5', \"r+\")", "_____no_output_____" ] ], [ [ "## Determine LR", "_____no_output_____" ] ], [ [ "lrFinder = batchLRFindClassifier(trainData, nSplits, getClassifier, modelParams, trainParams, lrBounds=[1e-5,1e-1], trainOnWeights=True, verbose=0)", "2 classes found, running in binary mode\n\n\n______________________________________\nTraining finished\nCross-validation took 1.816s \n" ], [ "compileArgs['lr'] = 1e-3", "_____no_output_____" ] ], [ [ "## Train classifier", "_____no_output_____" ] ], [ [ "results, histories = batchTrainClassifier(trainData, nSplits, getClassifier, modelParams, trainParams, patience=100, cosAnnealMult=2, trainOnWeights=True, maxEpochs=maxEpochs, verbose=1)", "Using cosine annealing\nTraining using weights\nRunning fold 1 / 10\n2 classes found, running in binary mode\n\n" ] ], [ [ "## Construct ensemble", "_____no_output_____" ] ], [ [ "with open('train_weights/resultsFile.pkl', 'r') as fin: \n results = pickle.load(fin)", "_____no_output_____" ], [ "ensemble, weights = assembleEnsemble(results, ensembleSize, ensembleMode, compileArgs)", "Choosing ensemble by loss\nModel 0 is 3 with loss = 0.00011575449899517662\nModel 1 is 8 with loss = 0.0001178636336683302\nModel 2 is 2 with loss = 0.00011884003508589871\nModel 3 is 5 with loss = 0.0001193010406206114\nModel 4 is 4 with loss = 0.00011968487281697382\nModel 5 is 0 with loss = 0.0001204359034669732\nModel 6 is 7 with loss = 0.00012120768202688791\nModel 7 is 1 with loss = 0.00012299964583698526\nModel 8 is 6 with loss = 0.00012334767394723455\nModel 9 is 9 with loss = 0.00012352607678114361\n" ] ], [ [ "## Response on development data", "_____no_output_____" ] ], [ [ "batchEnsemblePredict(ensemble, weights, trainData, ensembleSize=10, verbose=1)", "Predicting batch 1 out of 10\nPrediction took 0.00164373439024s per sample\n\nPredicting batch 2 out of 10\nPrediction took 0.000412040299404s per sample\n\nPredicting batch 3 out of 10\nPrediction took 0.000445488266296s per sample\n\nPredicting batch 4 out of 10\nPrediction took 0.000415643478962s per sample\n\nPredicting batch 5 out of 10\nPrediction took 0.000418017250273s per sample\n\nPredicting batch 6 out of 10\nPrediction took 0.000410003211712s per sample\n\nPredicting batch 7 out of 10\nPrediction took 0.000429526848234s per sample\n\nPredicting batch 8 out of 10\nPrediction took 0.000444223741245s per sample\n\nPredicting batch 9 out of 10\nPrediction took 0.000406612451281s per sample\n\nPredicting batch 10 out of 10\nPrediction took 0.000358059497773s per sample\n\n" ], [ "print 'Training ROC AUC: unweighted {}, weighted {}'.format(roc_auc_score(getFeature('targets', trainData), getFeature('pred', trainData)),\n roc_auc_score(getFeature('targets', trainData), getFeature('pred', trainData), sample_weight=getFeature('weights', trainData)))", "Training ROC AUC: unweighted 0.891175953995, weighted 0.921425705287\n" ] ], [ [ "## Response on val data", "_____no_output_____" ] ], [ [ "batchEnsemblePredict(ensemble, weights, valData, ensembleSize=10, verbose=1)", "Predicting batch 1 out of 10\nPrediction took 0.000401813805718s per sample\n\nPredicting batch 2 out of 10\nPrediction took 0.000372840110789s per sample\n\nPredicting batch 3 out of 10\nPrediction took 0.00036254064324s per sample\n\nPredicting batch 4 out of 10\nPrediction took 0.000364492234495s per sample\n\nPredicting batch 5 out of 10\nPrediction took 0.000358374636839s per sample\n\nPredicting batch 6 out of 10\nPrediction took 0.000368739404986s per sample\n\nPredicting batch 7 out of 10\nPrediction took 0.000362008925407s per sample\n\nPredicting batch 8 out of 10\nPrediction took 0.000375865197951s per sample\n\nPredicting batch 9 out of 10\nPrediction took 0.000391886311193s per sample\n\nPredicting batch 10 out of 10\nPrediction took 0.000372826976161s per sample\n\n" ], [ "print 'Testing ROC AUC: unweighted {}, weighted {}'.format(roc_auc_score(getFeature('targets', valData), getFeature('pred', valData)),\n roc_auc_score(getFeature('targets', valData), getFeature('pred', valData), sample_weight=getFeature('weights', valData)))", "Testing ROC AUC: unweighted 0.888232824562, weighted 0.91495512869\n" ] ], [ [ "## Evaluation", "_____no_output_____" ], [ "### Import in dataframe", "_____no_output_____" ] ], [ [ "def convertToDF(datafile, columns={'gen_target', 'gen_weight', 'pred_class'}, nLoad=-1):\n data = pandas.DataFrame()\n data['gen_target'] = getFeature('targets', datafile, nLoad)\n data['gen_weight'] = getFeature('weights', datafile, nLoad)\n data['pred_class'] = getFeature('pred', datafile, nLoad)\n print len(data), \"candidates loaded\"\n return data", "_____no_output_____" ], [ "valData = convertToDF(valData)", "15509 candidates loaded\n" ], [ "sigVal = (valData.gen_target == 1)\nbkgVal = (valData.gen_target == 0)", "_____no_output_____" ] ], [ [ "### MVA distributions", "_____no_output_____" ] ], [ [ "getClassPredPlot([valData[bkgVal], valData[sigVal]], weightName='gen_weight')", "_____no_output_____" ], [ "amsScan(valData)", "[0.9558367133140564, 0.7872357608096916]\n" ], [ "def scoreTest(ensemble, weights, nJets):\n testData = h5py.File(dirLoc + 'testing_' + nJets + '.hdf5', \"r+\")\n batchEnsemblePredict(ensemble, weights, testData, ensembleSize=10, verbose=1)\n\ndef saveTest(cut, name, nJets):\n testData = h5py.File(dirLoc + 'testing_' + nJets + '.hdf5', \"r+\")\n \n data = pandas.DataFrame()\n data['EventId'] = getFeature('EventId', testData)\n data['pred_class'] = getFeature('pred', testData)\n \n data['Class'] = 'b'\n data.loc[data.pred_class >= cut, 'Class'] = 's'\n\n data.sort_values(by=['pred_class'], inplace=True)\n data['RankOrder']=range(1, len(data)+1)\n data.sort_values(by=['EventId'], inplace=True)\n\n print dirLoc + name + '_test.csv'\n data.to_csv(dirLoc + name + '_test.csv', columns=['EventId', 'RankOrder', 'Class'], index=False)", "_____no_output_____" ], [ "scoreTest(ensemble, weights, nJets)", "Predicting batch 1 out of 10\nPrediction took 0.000372283292384s per sample\n\nPredicting batch 2 out of 10\nPrediction took 0.000366555149758s per sample\n\nPredicting batch 3 out of 10\nPrediction took 0.000364242284443s per sample\n\nPredicting batch 4 out of 10\nPrediction took 0.00036599328151s per sample\n\nPredicting batch 5 out of 10\nPrediction took 0.000361512313045s per sample\n\nPredicting batch 6 out of 10\nPrediction took 0.000350501945832s per sample\n\nPredicting batch 7 out of 10\nPrediction took 0.000365458776123s per sample\n\nPredicting batch 8 out of 10\nPrediction took 0.000355169407979s per sample\n\nPredicting batch 9 out of 10\nPrediction took 0.00036763890618s per sample\n\nPredicting batch 10 out of 10\nPrediction took 0.000362303463362s per sample\n\n" ], [ "saveTest(0.9622855186462402, 'Day_2_Basic_Features_256_1e-3_swish_mult2_200E_normedweighted_rot_cart')", "_____no_output_____" ] ], [ [ "!kaggle competitions submit -c higgs-boson -f ../Data/Day_2_Basic_Features_256_1e-3_swish_mult2_200E_normedweighted_rot_cart_test.csv -m\"Day2\"", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cbe3860c8969bdbfd8724dc0b105246ea59bd59b
36,229
ipynb
Jupyter Notebook
trumpstweets/M5_Trumps_Tweets.ipynb
swmcpherson19/swmcpherson19.github.io
0b942bedeebf577a22d33d05c018d756630dbb9c
[ "CC0-1.0" ]
null
null
null
trumpstweets/M5_Trumps_Tweets.ipynb
swmcpherson19/swmcpherson19.github.io
0b942bedeebf577a22d33d05c018d756630dbb9c
[ "CC0-1.0" ]
null
null
null
trumpstweets/M5_Trumps_Tweets.ipynb
swmcpherson19/swmcpherson19.github.io
0b942bedeebf577a22d33d05c018d756630dbb9c
[ "CC0-1.0" ]
null
null
null
235.253247
31,508
0.912943
[ [ [ "# M5:Trump's Tweets Assignment - Scott McPherson\n# importing libraries and files into data\nimport matplotlib.pyplot as plt\nf_in = open ('C:/Users/Owner/Documents/BUAD 502C/Module5/words.csv','r')\ndata = f_in.readlines()\nf_in.close()\n\n\"\"\" The list below contains words that you are to exclude form your analysis \"\"\"\nstopWords = ['to', 'the', 'a', 'to', 'is', 'and', 'in', 'of', 'that', 'it', 'be','at', 'this', 'are', 'be', 'for', 'will', 'with', 'at', 'have','on','&amp', 'by']\n\n# data wrangling section\nfor i in range(len(data)):\n data[i]=data[i].strip()\ndata = [x for x in data if x not in stopWords]\n\n# dictionary setup -- tried to do dictionary comp., but the kernel kept crashing\ntweetDict={}\nfor i in data:\n if i in tweetDict:\n tweetDict[i] += 1\n else:\n tweetDict[i] = 1\n\n# sorting the dictionary by values to get the highest frequency at the beginning\nsortedtweetDict={k: v for k,v in sorted(tweetDict.items(), key=lambda item: item[1], reverse=True)}\n\n# removing the top ten of each the keys and values\nkeylist = list(sortedtweetDict.keys())\nvaluelist = list(sortedtweetDict.values())\nx = keylist[:10]\nxs = range(len(x)) # this is for use on the xticks later -- requires an integer to set up the number of ticks\ny = valuelist[:10]\n\n#set up subplots, axes, and figures\nfig,ax = plt.subplots()\nax.bar(xs,y, align='center', color='r')\nax.set_xticks(xs)\nax.set_xticklabels(x, rotation=45)\nax.xaxis.set_tick_params(labelsize=12)\nax.yaxis.set_tick_params(labelsize=12)\nax.xaxis.set_label_text(\"Words in Trump's Tweets\", fontsize=14)\nax.yaxis.set_label_text(\"Number of Occurrences\", fontsize=14)\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.tick_params(axis = 'x', which = 'both', direction = 'in', width = 2, color = 'black')\nfig.suptitle(\"Top 10 Most Frequently Tweeted Words by President Trump\")\nfig.set_size_inches(16,8)\nfig.savefig('tweets.jpg', bbox_inches='tight')\n\n# displaying graph\nplt.show()\n", "_____no_output_____" ], [ "min(valueList[:10])", "_____no_output_____" ], [ "\n", "_____no_output_____" ], [ "l = [\"a\",\"b\",\"b\"]\nl2={x:l.count(x) for x in set(l)}\n", "_____no_output_____" ], [ "type(l2)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
cbe39217af5aae840d38620e94f450f96237eb9c
124,027
ipynb
Jupyter Notebook
.ipynb_checkpoints/Bad Word Correction Strategy-checkpoint.ipynb
amalalexa/Cyberbullying_Detection
842dfd61f32dfb38ebbe91c2545667f72a7068f9
[ "MIT" ]
1
2021-04-13T21:11:36.000Z
2021-04-13T21:11:36.000Z
.ipynb_checkpoints/Bad Word Correction Strategy-checkpoint.ipynb
amalalexa/Cyberbullying_Detection
842dfd61f32dfb38ebbe91c2545667f72a7068f9
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Bad Word Correction Strategy-checkpoint.ipynb
amalalexa/Cyberbullying_Detection
842dfd61f32dfb38ebbe91c2545667f72a7068f9
[ "MIT" ]
1
2020-10-06T14:14:38.000Z
2020-10-06T14:14:38.000Z
16.545758
109
0.325211
[ [ [ "# Procedure for Word Correction Strategy as mentioned in Page 43 in the dissertation report", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport os\nimport nltk\nimport re\nimport string\nfrom bs4 import BeautifulSoup\nfrom spellchecker import SpellChecker", "_____no_output_____" ], [ "def read_file(df_new):\n print(\"Started extracting data from file\",df_new.shape)\n dfnew=pd.DataFrame()\n dfnew.insert(0,'Post',None)\n dfnew.insert(1,'class',None)\n for val in df_new.values:\n appList=[]\n sp=np.array_str(val).split(\",\")\n if len(sp)==2:\n appList.append(sp[0])\n appList.append(sp[1])\n dfnew.loc[len(dfnew)]=appList\n for i in range(0,dfnew.shape[0]):\n dfnew.values[i][1]=int(dfnew.values[i][1].strip(\"\\'|]|\\\"\"))\n print(dfnew['class'].value_counts())\n print(\"Finished extracting data from file\",dfnew.shape)\n return dfnew", "_____no_output_____" ], [ "def post_tokenizing_dataset1(df):\n print(\"Started cleaning data in dataframe\", df.shape)\n #print(df.head(5))\n wpt = nltk.WordPunctTokenizer()\n stop_words = nltk.corpus.stopwords.words('english')\n \n token_list=[]\n phrase_list=[]\n token_df=pd.DataFrame()\n token_df.insert(0,'Post',None)\n token_df.insert(1,'class',None)\n for val in df.values:\n append_list=[]\n filter_val=re.sub(r'Q:','',val[0])\n filter_val=re.sub(r'&#039;[a-z]{1}','',filter_val)\n filter_val=re.sub('<[a-z]+>',' ',filter_val).lower()\n filter_val=re.sub(r'[^a-zA-Z\\s]', '', filter_val, re.I|re.A)\n filter_val=[token for token in wpt.tokenize(filter_val)]\n filter_val=[word for word in filter_val if word.isalpha()]\n if(filter_val):\n append_list.append(' '.join(filter_val))\n append_list.append(val[1])\n token_df.loc[len(token_df)]=append_list\n print(\"Finished cleaning data in dataframe\",token_df.shape)\n #print(token_df.head(5))\n return token_df", "_____no_output_____" ], [ "def post_tokenizing_dataset3(df):\n print(\"Started cleaning data in dataframe\", df.shape)\n #print(df.head(5))\n wpt = nltk.WordPunctTokenizer()\n stop_words = nltk.corpus.stopwords.words('english')\n \n token_df=pd.DataFrame()\n token_df.insert(0,'Post',None)\n token_df.insert(1,'class',None)\n \n for val in df.values:\n filter_val=[]\n value=re.sub(r'@\\w*','',val[0])\n value=re.sub(r'&.*;','',value)\n value=re.sub(r'http[s?]?:\\/\\/.*[\\r\\n]*','',value)\n tokens=[token for token in wpt.tokenize(value)]\n tokens=[word for word in tokens if word.isalpha()]\n if len(tokens)!=0:\n filter_val.append(' '.join(tokens).lower())\n filter_val.append(val[1])\n token_df.loc[len(token_df)]=filter_val\n \n print(\"Finished cleaning data in dataframe\",token_df.shape)\n #print(token_df.head(5))\n return token_df", "_____no_output_____" ], [ "def correct_words(token_df_copy,badWordsDict):\n spell = SpellChecker()\n token_df_ones=token_df_copy[token_df_copy['class']==1]\n post_list=[]\n for val in token_df_ones.values:\n post_list.append(val[0])\n count=0\n val_counts=token_df_copy['class'].value_counts()\n print(val_counts[0],val_counts[0]+val_counts[1])\n for val in range(val_counts[0],val_counts[0]+val_counts[1]):\n sentiment=token_df_copy.loc[val][1]\n if sentiment==1:\n post=post_list[count]\n for word in post.split(' '):\n misspelled = spell.unknown([word])\n for value in misspelled:\n get_list=badWordsDict.get(word[0])\n if(get_list):\n candi_list=spell.candidates(word)\n list3 = list(set(get_list)&set(candi_list))\n if list3:\n post=[w.replace(word, list3[0]) for w in post.split()]\n post=' '.join(post)\n break\n \n \n token_df_copy.loc[val][0]=post\n count+=1\n print(count)\n token_df_copy.to_csv(\"cor.csv\",index=False, header=True)\n return token_df_copy", "_____no_output_____" ], [ "wordList=[]\nfor val in string.ascii_lowercase:\n with open(\"../swear-words/\"+val+\".html\") as fp:\n soup = BeautifulSoup(fp)\n wordSet=soup.find_all('table')[2]('b')\n for i in range(0,len(wordSet)-1):\n wordList.append(wordSet[i].string)\nbadWordsDict={}\nfor val in wordList:\n if not badWordsDict.get(val[0]):\n badWordsDict[val[0]]=[]\n badWordsDict.get(val[0]).append(val)", "_____no_output_____" ], [ "df_data_1=read_file(pd.read_csv(\"../post.csv\",sep=\"\\t\"))\ndf_data_2=read_file(pd.read_csv(\"../new_data.csv\",sep=\",\"))\ndf_data_3=pd.read_csv(\"../dataset_4.csv\",sep=\",\")", "Started extracting data from file (12642, 1)\n0 10794\n1 1848\nName: class, dtype: int64\nFinished extracting data from file (12642, 2)\nStarted extracting data from file (8856, 1)\n0 6312\n1 2505\nName: class, dtype: int64\nFinished extracting data from file (8817, 2)\n" ], [ "df_data_1=post_tokenizing_dataset1(df_data_1)\ntoken_data_2=df_data_2[df_data_2['class']==1].iloc[:,]\ntoken_data_2=post_tokenizing_dataset1(token_data_2)\ntoken_data_3=df_data_3[df_data_3['class']==1].iloc[0:3147,]\ntoken_data_3=post_tokenizing_dataset3(token_data_3)", "Started cleaning data in dataframe (12642, 2)\nFinished cleaning data in dataframe (12642, 2)\nStarted cleaning data in dataframe (2505, 2)\nFinished cleaning data in dataframe (2505, 2)\nStarted cleaning data in dataframe (3147, 2)\nFinished cleaning data in dataframe (3147, 2)\n" ], [ "token_data_3=post_tokenizing_dataset3(token_data_3)", "Started cleaning data in dataframe (3147, 2)\nFinished cleaning data in dataframe (2753, 2)\n" ], [ "print(df_data_2['class'].value_counts())", "0 6312\n1 2505\nName: class, dtype: int64\n" ], [ "df_data_1_new=pd.DataFrame()\ndf_data_1_new=df_data_1_new.append(df_data_1[df_data_1['class']==0].iloc[0:7500,],ignore_index=True)\ndf_data_1_new=df_data_1_new.append(df_data_1[df_data_1['class']==1],ignore_index=True)\ndf_data_1_new=df_data_1_new.append(token_data_2 ,ignore_index=True)\ndf_data_1_new=df_data_1_new.append(token_data_3,ignore_index=True)", "_____no_output_____" ], [ "token_df_2=df_data_1_new.copy()\ntoken_df_new=correct_words(token_df_2,badWordsDict)\ntoken_df_new.to_csv(\"corrected_post_2.csv\",index=False, header=True)\ndf_data_1_new.to_csv(\"without_correction_2.csv\",index=False, header=True)", "7500 14606\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501\n502\n503\n504\n505\n506\n507\n508\n509\n510\n511\n512\n513\n514\n515\n516\n517\n518\n519\n520\n521\n522\n523\n524\n525\n526\n527\n528\n529\n530\n531\n532\n533\n534\n535\n536\n537\n538\n539\n540\n541\n542\n543\n544\n545\n546\n547\n548\n549\n550\n551\n552\n553\n554\n555\n556\n557\n558\n559\n560\n561\n562\n563\n564\n565\n566\n567\n568\n569\n570\n571\n572\n573\n574\n575\n576\n577\n578\n579\n580\n581\n582\n583\n584\n585\n586\n587\n588\n589\n590\n591\n592\n593\n594\n595\n596\n597\n598\n599\n600\n601\n602\n603\n604\n605\n606\n607\n608\n609\n610\n611\n612\n613\n614\n615\n616\n617\n618\n619\n620\n621\n622\n623\n624\n625\n626\n627\n628\n629\n630\n631\n632\n633\n634\n635\n636\n637\n638\n639\n640\n641\n642\n643\n644\n645\n646\n647\n648\n649\n650\n651\n652\n653\n654\n655\n656\n657\n658\n659\n660\n661\n662\n663\n664\n665\n666\n667\n668\n669\n670\n671\n672\n673\n674\n675\n676\n677\n678\n679\n680\n681\n682\n683\n684\n685\n686\n687\n688\n689\n690\n691\n692\n693\n694\n695\n696\n697\n698\n699\n700\n701\n702\n703\n704\n705\n706\n707\n708\n709\n710\n711\n712\n713\n714\n715\n716\n717\n718\n719\n720\n721\n722\n723\n724\n725\n726\n727\n728\n729\n730\n731\n732\n733\n734\n735\n736\n737\n738\n739\n740\n741\n742\n743\n744\n745\n746\n747\n748\n749\n750\n751\n752\n753\n754\n755\n756\n757\n758\n759\n760\n761\n762\n763\n764\n765\n766\n767\n768\n769\n770\n771\n772\n773\n774\n775\n776\n777\n778\n779\n780\n781\n782\n783\n784\n785\n786\n787\n788\n789\n790\n791\n792\n793\n794\n795\n796\n797\n798\n799\n800\n801\n802\n803\n804\n805\n806\n807\n808\n809\n810\n811\n812\n813\n814\n815\n816\n817\n818\n819\n820\n821\n822\n823\n824\n825\n826\n827\n828\n829\n830\n831\n832\n833\n834\n835\n836\n837\n838\n839\n840\n841\n842\n843\n844\n845\n846\n847\n848\n849\n850\n851\n852\n853\n854\n855\n856\n857\n858\n859\n860\n861\n862\n863\n864\n865\n866\n867\n868\n869\n870\n871\n872\n873\n874\n875\n876\n877\n878\n879\n880\n881\n882\n883\n884\n885\n886\n887\n888\n889\n890\n891\n892\n893\n894\n895\n896\n897\n898\n899\n900\n901\n902\n903\n904\n905\n906\n907\n908\n909\n910\n911\n912\n913\n914\n915\n916\n917\n918\n919\n920\n921\n922\n923\n924\n925\n926\n927\n928\n929\n930\n931\n932\n933\n934\n935\n936\n937\n938\n939\n940\n941\n942\n943\n944\n945\n946\n947\n948\n949\n950\n951\n952\n953\n954\n955\n956\n957\n958\n959\n960\n961\n962\n963\n964\n965\n966\n967\n968\n969\n970\n971\n972\n973\n974\n975\n976\n977\n978\n979\n980\n981\n982\n983\n984\n985\n986\n987\n988\n989\n990\n991\n992\n993\n994\n995\n996\n997\n998\n999\n1000\n1001\n1002\n1003\n1004\n1005\n1006\n1007\n1008\n1009\n1010\n1011\n1012\n1013\n1014\n1015\n1016\n1017\n1018\n1019\n1020\n1021\n1022\n1023\n1024\n1025\n1026\n1027\n1028\n1029\n1030\n1031\n1032\n1033\n1034\n1035\n1036\n1037\n1038\n1039\n1040\n1041\n1042\n1043\n1044\n1045\n1046\n1047\n1048\n1049\n1050\n1051\n1052\n1053\n1054\n1055\n1056\n1057\n1058\n1059\n1060\n1061\n1062\n1063\n1064\n1065\n1066\n1067\n1068\n1069\n1070\n1071\n1072\n1073\n1074\n1075\n1076\n1077\n1078\n1079\n1080\n1081\n1082\n1083\n1084\n1085\n1086\n1087\n1088\n1089\n1090\n1091\n1092\n1093\n1094\n1095\n1096\n1097\n1098\n1099\n1100\n1101\n1102\n1103\n1104\n1105\n1106\n1107\n1108\n1109\n1110\n1111\n1112\n1113\n1114\n1115\n1116\n1117\n1118\n1119\n1120\n1121\n1122\n1123\n1124\n1125\n1126\n1127\n1128\n1129\n1130\n1131\n1132\n1133\n1134\n1135\n1136\n1137\n1138\n1139\n1140\n1141\n1142\n1143\n1144\n1145\n1146\n1147\n1148\n1149\n1150\n1151\n1152\n1153\n1154\n1155\n1156\n1157\n1158\n1159\n1160\n1161\n1162\n1163\n1164\n1165\n1166\n1167\n1168\n1169\n1170\n1171\n1172\n1173\n1174\n1175\n1176\n1177\n1178\n1179\n1180\n1181\n1182\n1183\n1184\n1185\n1186\n1187\n1188\n1189\n1190\n1191\n1192\n1193\n1194\n1195\n1196\n1197\n1198\n1199\n1200\n1201\n1202\n1203\n1204\n1205\n1206\n1207\n1208\n1209\n1210\n1211\n1212\n1213\n1214\n1215\n1216\n1217\n1218\n1219\n1220\n1221\n1222\n1223\n1224\n1225\n1226\n1227\n1228\n1229\n1230\n1231\n1232\n1233\n1234\n1235\n1236\n1237\n1238\n1239\n1240\n1241\n1242\n1243\n1244\n1245\n1246\n1247\n1248\n1249\n1250\n1251\n1252\n1253\n1254\n1255\n1256\n1257\n1258\n1259\n1260\n1261\n1262\n1263\n1264\n1265\n1266\n1267\n1268\n1269\n1270\n1271\n1272\n1273\n1274\n1275\n1276\n1277\n1278\n1279\n1280\n1281\n1282\n1283\n1284\n1285\n1286\n1287\n1288\n1289\n1290\n1291\n1292\n1293\n1294\n1295\n1296\n1297\n1298\n1299\n1300\n1301\n1302\n1303\n1304\n1305\n1306\n1307\n1308\n1309\n1310\n1311\n1312\n1313\n1314\n1315\n1316\n1317\n1318\n1319\n1320\n1321\n1322\n1323\n1324\n1325\n1326\n1327\n1328\n1329\n1330\n1331\n1332\n1333\n1334\n1335\n1336\n1337\n1338\n1339\n1340\n1341\n1342\n1343\n1344\n1345\n1346\n1347\n1348\n1349\n1350\n1351\n1352\n1353\n1354\n1355\n1356\n1357\n1358\n1359\n1360\n1361\n1362\n1363\n1364\n1365\n1366\n1367\n1368\n1369\n1370\n1371\n1372\n1373\n1374\n1375\n1376\n1377\n1378\n1379\n1380\n1381\n1382\n1383\n1384\n1385\n1386\n1387\n1388\n1389\n1390\n1391\n1392\n1393\n1394\n1395\n1396\n1397\n1398\n1399\n1400\n1401\n1402\n1403\n1404\n1405\n1406\n1407\n1408\n1409\n1410\n1411\n1412\n1413\n1414\n1415\n1416\n1417\n1418\n1419\n1420\n1421\n1422\n1423\n1424\n1425\n1426\n1427\n1428\n1429\n1430\n1431\n1432\n1433\n1434\n1435\n1436\n1437\n1438\n1439\n1440\n1441\n1442\n1443\n1444\n1445\n1446\n1447\n1448\n1449\n1450\n1451\n1452\n1453\n1454\n1455\n1456\n1457\n1458\n1459\n1460\n1461\n1462\n1463\n1464\n1465\n1466\n1467\n1468\n1469\n1470\n1471\n1472\n1473\n1474\n1475\n1476\n1477\n1478\n1479\n1480\n1481\n1482\n1483\n1484\n1485\n1486\n1487\n1488\n1489\n1490\n1491\n1492\n1493\n1494\n1495\n1496\n1497\n1498\n1499\n1500\n1501\n1502\n1503\n1504\n1505\n1506\n1507\n1508\n1509\n1510\n1511\n1512\n1513\n1514\n1515\n1516\n1517\n1518\n1519\n1520\n1521\n1522\n1523\n1524\n1525\n1526\n1527\n1528\n1529\n1530\n1531\n1532\n1533\n1534\n1535\n1536\n1537\n1538\n1539\n1540\n1541\n1542\n1543\n1544\n1545\n1546\n1547\n1548\n1549\n1550\n1551\n1552\n1553\n1554\n1555\n1556\n1557\n1558\n1559\n1560\n1561\n1562\n1563\n1564\n1565\n1566\n1567\n1568\n1569\n1570\n1571\n1572\n1573\n1574\n1575\n1576\n1577\n1578\n1579\n1580\n1581\n1582\n1583\n1584\n1585\n1586\n1587\n1588\n1589\n1590\n1591\n1592\n1593\n1594\n1595\n1596\n1597\n1598\n1599\n1600\n1601\n1602\n1603\n1604\n1605\n1606\n1607\n1608\n1609\n1610\n1611\n1612\n1613\n1614\n1615\n1616\n1617\n1618\n1619\n1620\n1621\n1622\n1623\n1624\n1625\n1626\n1627\n1628\n1629\n1630\n1631\n1632\n1633\n1634\n1635\n1636\n1637\n1638\n1639\n1640\n1641\n1642\n1643\n1644\n1645\n1646\n1647\n1648\n1649\n1650\n1651\n1652\n1653\n1654\n1655\n1656\n1657\n1658\n1659\n1660\n1661\n1662\n1663\n1664\n1665\n1666\n1667\n1668\n1669\n1670\n1671\n1672\n1673\n1674\n1675\n1676\n1677\n1678\n1679\n1680\n1681\n1682\n1683\n1684\n1685\n1686\n1687\n1688\n1689\n1690\n1691\n1692\n1693\n1694\n1695\n1696\n1697\n1698\n1699\n1700\n1701\n1702\n1703\n1704\n1705\n1706\n1707\n1708\n1709\n1710\n1711\n1712\n1713\n1714\n1715\n1716\n1717\n1718\n1719\n1720\n1721\n1722\n1723\n1724\n1725\n1726\n1727\n1728\n1729\n1730\n1731\n1732\n1733\n1734\n1735\n1736\n1737\n1738\n1739\n1740\n1741\n1742\n1743\n1744\n1745\n1746\n1747\n1748\n1749\n1750\n1751\n1752\n1753\n1754\n1755\n1756\n1757\n1758\n1759\n1760\n1761\n1762\n1763\n1764\n1765\n1766\n1767\n1768\n1769\n1770\n1771\n1772\n1773\n1774\n1775\n1776\n1777\n1778\n1779\n1780\n1781\n1782\n1783\n1784\n1785\n1786\n1787\n1788\n1789\n1790\n1791\n1792\n1793\n1794\n1795\n1796\n1797\n1798\n1799\n1800\n1801\n1802\n1803\n1804\n1805\n1806\n1807\n1808\n1809\n1810\n1811\n1812\n1813\n1814\n1815\n1816\n1817\n1818\n1819\n1820\n1821\n1822\n1823\n1824\n1825\n1826\n1827\n1828\n1829\n1830\n1831\n1832\n1833\n1834\n1835\n1836\n1837\n1838\n1839\n1840\n1841\n1842\n1843\n1844\n1845\n1846\n1847\n1848\n1849\n1850\n1851\n1852\n1853\n1854\n1855\n1856\n1857\n1858\n" ], [ "print(token_df_2.loc[11859])", "Post \nclass 1\nName: 11859, dtype: object\n" ], [ "dfnew=pd.DataFrame()\ndfnew.insert(0,'Post',None)\ndfnew.insert(1,'class',None)\nfor val in token_df_new.values:\n value=re.sub(r'http[a-z0-9]*[\\r\\n\\s]?','',val[0])\n dfnew.loc[len(dfnew)]=value\ndfnew['class']=token_df_new['class']\ndfnew.to_csv(\"without_correction_3.csv\",index=False, header=True)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe3958096e6e1a26993f21d2db253920d114b11
1,330
ipynb
Jupyter Notebook
test/py/Phyllochron.ipynb
Crop2ML-Catalog/SQ_Wheat_Phenology
8e9ec229e5f0754d0f4b9d79ac96a084d75dde67
[ "MIT" ]
3
2018-12-06T07:54:25.000Z
2022-02-03T16:31:33.000Z
test/py/Phyllochron.ipynb
Crop2ML-Catalog/SQ_Wheat_Phenology
8e9ec229e5f0754d0f4b9d79ac96a084d75dde67
[ "MIT" ]
2
2018-12-06T07:51:42.000Z
2020-11-14T18:03:12.000Z
test/py/Phyllochron.ipynb
Crop2ML-Catalog/SQ_Wheat_Phenology
8e9ec229e5f0754d0f4b9d79ac96a084d75dde67
[ "MIT" ]
5
2018-12-10T12:11:46.000Z
2022-03-04T10:52:03.000Z
21.451613
65
0.509774
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbe39ca42fb407a11a3c4601f59ceed9691a0d0c
169,634
ipynb
Jupyter Notebook
example_usage.ipynb
nupam/keras-callbacks
abc310c00344085a0de4961d90263e46540d5b01
[ "MIT" ]
1
2019-07-01T02:38:01.000Z
2019-07-01T02:38:01.000Z
example_usage.ipynb
nupam/keras-callbacks
abc310c00344085a0de4961d90263e46540d5b01
[ "MIT" ]
null
null
null
example_usage.ipynb
nupam/keras-callbacks
abc310c00344085a0de4961d90263e46540d5b01
[ "MIT" ]
null
null
null
249.095448
24,436
0.913909
[ [ [ "from extra import *\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential, Model\nfrom keras import regularizers\nfrom keras.layers import Dense, Dropout, Conv2D, Input, GlobalAveragePooling2D, GlobalMaxPooling2D\nfrom keras.layers import Add, Concatenate, BatchNormalization\nimport keras.backend as K\nfrom keras.optimizers import Adam\n\nimport pandas as pd\nimport numpy as np\n\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nbatch_size = 128\nnum_classes = 10\n\n# input image dimensions\nHEIGHT, WIDTH = 28, 28\nK.set_image_data_format('channels_first')", "Using TensorFlow backend.\n" ], [ "keras.__version__", "_____no_output_____" ], [ "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')", "x_train shape: (60000, 28, 28)\n60000 train samples\n10000 test samples\n" ], [ "print('pixel range',x_train.min(), x_train.max())", "pixel range 0 255\n" ] ], [ [ "images are as pixel values, ranging from 0-255", "_____no_output_____" ] ], [ [ "pd.DataFrame(y_train)[0].value_counts().plot(kind='bar')", "_____no_output_____" ], [ "## changes pixel range to 0 to 1\ndef normalize(images):\n images /= 255. \n return images", "_____no_output_____" ], [ "x_train = normalize(x_train.astype(np.float32))\nx_test = normalize(x_test.astype(np.float32))\nx_train = x_train.reshape(x_train.shape[0], 1, WIDTH, HEIGHT)\nx_test = x_test.reshape(x_test.shape[0], 1, WIDTH, HEIGHT)\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)", "_____no_output_____" ] ], [ [ "now we have images that are normalized, and labels are one hot encoded", "_____no_output_____" ] ], [ [ "def show_images(rows, columns):\n fig, axes = plt.subplots(rows,columns)\n for rows in axes:\n for ax in rows:\n idx = np.random.randint(0, len(y_train))\n ax.title.set_text(np.argmax(y_train[idx]))\n ax.imshow(x_train[idx][0], cmap='gray')\n ax.axis('off')\n plt.show()\n \nshow_images(2,4)", "_____no_output_____" ], [ "def build_model():\n inp = Input((1, HEIGHT, WIDTH))\n \n x = Conv2D(16, kernel_size=(7,7), strides=(2,2), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(inp)\n x = BatchNormalization()(x)\n \n y = Conv2D(16, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(x)\n y = BatchNormalization()(y)\n y = Conv2D(16, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(y)\n y = BatchNormalization()(y)\n x = Add()([x,y])\n x = Conv2D(32, kernel_size=(3,3), strides=(2,2), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(x)\n x = BatchNormalization()(x)\n \n \n y = Conv2D(32, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(x)\n y = BatchNormalization()(y)\n y = Conv2D(32, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(y)\n y = BatchNormalization()(y)\n x = Add()([x,y])\n x = Conv2D(64, kernel_size=(3,3), strides=(2,2), padding='same', activation='relu', kernel_regularizer=regularizers.l2(0.002))(x)\n x = BatchNormalization()(x)\n \n x = Concatenate()([GlobalMaxPooling2D(data_format='channels_first')(x) , GlobalAveragePooling2D(data_format='channels_first')(x)])\n x = Dropout(0.3)(x)\n \n out = Dense(10, activation='softmax')(x)\n \n return Model(inputs=inp, outputs=out)\n ", "_____no_output_____" ], [ "model = build_model()", "_____no_output_____" ], [ "model.summary()", "__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 1, 28, 28) 0 \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 16, 14, 14) 800 input_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 16, 14, 14) 56 conv2d_1[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 16, 14, 14) 2320 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 16, 14, 14) 56 conv2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 16, 14, 14) 2320 batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 16, 14, 14) 56 conv2d_3[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 16, 14, 14) 0 batch_normalization_1[0][0] \n batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 32, 7, 7) 4640 add_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 32, 7, 7) 28 conv2d_4[0][0] \n__________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 32, 7, 7) 9248 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 32, 7, 7) 28 conv2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 32, 7, 7) 9248 batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 32, 7, 7) 28 conv2d_6[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 32, 7, 7) 0 batch_normalization_4[0][0] \n batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 64, 4, 4) 18496 add_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 64, 4, 4) 16 conv2d_7[0][0] \n__________________________________________________________________________________________________\nglobal_max_pooling2d_1 (GlobalM (None, 64) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 64) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 128) 0 global_max_pooling2d_1[0][0] \n global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 128) 0 concatenate_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 10) 1290 dropout_1[0][0] \n==================================================================================================\nTotal params: 48,630\nTrainable params: 48,496\nNon-trainable params: 134\n__________________________________________________________________________________________________\n" ], [ "model.compile(Adam(), loss='categorical_crossentropy', metrics=['acc'])", "_____no_output_____" ], [ "K.get_value(model.optimizer.lr), K.get_value(model.optimizer.beta_1)", "_____no_output_____" ], [ "lr_find(model, data=(x_train, y_train)) ## use generator if using generator insted of (x_train, y_train) and pass parameter, generator=True", "Epoch 1/10\n20320/60000 [=========>....................] - ETA: 58s - loss: 3.2837 - acc: 0.5830stopping\n" ] ], [ [ "selecting lr as 2e-3", "_____no_output_____" ], [ "### high lr for demonstration of decay, from above graph anything b/w 0.002 to 0.004 seems nice", "_____no_output_____" ] ], [ [ "recorder = RecorderCallback()\nclr = CyclicLRCallback(max_lr=0.4, cycles=4, decay=0.6, DEBUG_MODE=True, patience=1, auto_decay=True, pct_start=0.3, monitor='val_loss') ", "_____no_output_____" ], [ "K.get_value(model.optimizer.lr), K.get_value(model.optimizer.beta_1)", "_____no_output_____" ], [ "model.fit(x_train, y_train, batch_size=128, epochs=4, callbacks=[recorder, clr], validation_data=(x_test, y_test))", "Train on 60000 samples, validate on 10000 samples\nepochs: 4 , steps per cycle: 469.0 , total steps: 1876.0 , cycles: 4 , max_lr: 0.4000001\nEpoch 1/4\n\ncycle no.: 1\n\ncycle 1 end status: 0.4000001 0.0 0.95\n60000/60000 [==============================] - 78s 1ms/step - loss: 1.4183 - acc: 0.7862 - val_loss: 0.9784 - val_acc: 0.7158\n\nat epoch 1 end, batch num: 469\ncheck at epoch end, epoch 1 curr_cycle: 1 best: 0.9783532136917115\nEpoch 2/4\n\ncycle no.: 2\n\ncycle 2 end status: 0.4000001 0.0 0.95\n60000/60000 [==============================] - 79s 1ms/step - loss: 19.7851 - acc: 0.3320 - val_loss: 20.3194 - val_acc: 0.1009\n\nat epoch 2 end, batch num: 938\n\ncycle 00002: Reducing learning rate to 0.24000006000000002.\nval_loss did not improve from 0.9783532136917115\ncheck at epoch end, epoch 2 curr_cycle: 2 best: 0.9783532136917115\nEpoch 3/4\n\ncycle no.: 3\n\ncycle 3 end status: 0.24000006000000002 0.0 0.95\n60000/60000 [==============================] - 77s 1ms/step - loss: 21.0757 - acc: 0.0998 - val_loss: 15.5444 - val_acc: 0.1009\n\nat epoch 3 end, batch num: 1407\n\ncycle 00003: Reducing learning rate to 0.144000036.\nval_loss did not improve from 0.9783532136917115\ncheck at epoch end, epoch 3 curr_cycle: 3 best: 0.9783532136917115\nEpoch 4/4\n\ncycle no.: 4\n\ncycle 4 end status: 0.144000036 0.0 0.95\n60000/60000 [==============================] - 76s 1ms/step - loss: 37.1987 - acc: 0.0991 - val_loss: 25.3879 - val_acc: 0.1009\n\nat epoch 4 end, batch num: 1876\n\ncycle 00004: Reducing learning rate to 0.0864000216.\nval_loss did not improve from 0.9783532136917115\ncheck at epoch end, epoch 4 curr_cycle: 4 best: 0.9783532136917115\n" ], [ "K.get_value(model.optimizer.lr), K.get_value(model.optimizer.beta_1)", "_____no_output_____" ], [ "recorder.plot_losses()", "_____no_output_____" ], [ "recorder.plot_losses(log=True) #take log scale for loss", "_____no_output_____" ], [ "recorder.plot_losses(clip=True) #clips loss between 2.5 and 97.5 precentile", "_____no_output_____" ], [ "recorder.plot_losses(clip=True, log=True)", "_____no_output_____" ], [ "recorder.plot_lr()", "_____no_output_____" ], [ "recorder.plot_mom() ##plots momentum, beta_1 in adam family of optimizers", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe39d711dafeeb5554d2daa94b61fe778cf5449
3,506
ipynb
Jupyter Notebook
src/ia/covid19/generate_augmented_dataset.ipynb
ufopcsilab/covid-19
115df8d15fe971b3ac21a8e650f76a8c86a037ac
[ "MIT" ]
1
2020-06-07T04:18:38.000Z
2020-06-07T04:18:38.000Z
src/ia/covid19/generate_augmented_dataset.ipynb
ufopcsilab/covid-19
115df8d15fe971b3ac21a8e650f76a8c86a037ac
[ "MIT" ]
null
null
null
src/ia/covid19/generate_augmented_dataset.ipynb
ufopcsilab/covid-19
115df8d15fe971b3ac21a8e650f76a8c86a037ac
[ "MIT" ]
3
2021-02-14T13:53:01.000Z
2021-12-02T19:09:12.000Z
3,506
3,506
0.723902
[ [ [ "# Data Augmentation\n\nLoad the COVID-19 X-ray images and and create new images by means of rotation, flipping and scaling. \n", "_____no_output_____" ] ], [ [ "from sklearn.metrics import confusion_matrix\nimport numpy as np\nimport tensorflow as tf\nimport os, argparse\nimport cv2", "_____no_output_____" ], [ "num_imgs = 1000 # number of images to generate\n", "_____no_output_____" ], [ "!pip install Augmentor", "Collecting Augmentor\n Downloading https://files.pythonhosted.org/packages/cb/79/861f38d5830cff631e30e33b127076bfef8ac98171e51daa06df0118c75f/Augmentor-0.2.8-py2.py3-none-any.whl\nRequirement already satisfied: tqdm>=4.9.0 in /usr/local/lib/python3.6/dist-packages (from Augmentor) (4.38.0)\nRequirement already satisfied: Pillow>=5.2.0 in /usr/local/lib/python3.6/dist-packages (from Augmentor) (7.0.0)\nRequirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.6/dist-packages (from Augmentor) (1.18.2)\nRequirement already satisfied: future>=0.16.0 in /usr/local/lib/python3.6/dist-packages (from Augmentor) (0.16.0)\nInstalling collected packages: Augmentor\nSuccessfully installed Augmentor-0.2.8\n" ], [ "import Augmentor\n\np = Augmentor.Pipeline('/<path to COVID-19 x-ray images>')\n\np.rotate(probability=1, max_left_rotation=0.15, max_right_rotation=0.15)\np.flip_left_right(probability=0.5)\np.zoom_random(probability=0.2, percentage_area=0.8)\np.status()", "_____no_output_____" ], [ "p.sample(1000)\np.process()", "Processing <PIL.Image.Image image mode=L size=931x1024 at 0x7F3BA337D9E8>: 100%|██████████| 5000/5000 [27:31<00:00, 3.03 Samples/s]\nProcessing <PIL.Image.Image image mode=RGBA size=2318x2765 at 0x7F3BB3385160>: 100%|██████████| 236/236 [01:15<00:00, 3.13 Samples/s]\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbe3b3bf37408b863df8c410937ce1757c48c8b0
253,593
ipynb
Jupyter Notebook
5_quantum_monte_carlo/sol12_SSE.ipynb
jhauschild/lecture_comp_methods
c4fc5d2af8289d59143558daa63039fad1c84c82
[ "MIT" ]
25
2019-03-07T08:41:24.000Z
2022-02-19T21:31:11.000Z
5_quantum_monte_carlo/sol12_SSE.ipynb
jhauschild/lecture_comp_methods
c4fc5d2af8289d59143558daa63039fad1c84c82
[ "MIT" ]
2
2019-05-15T12:30:41.000Z
2019-07-03T18:08:12.000Z
5_quantum_monte_carlo/sol12_SSE.ipynb
jhauschild/lecture_comp_methods
c4fc5d2af8289d59143558daa63039fad1c84c82
[ "MIT" ]
9
2018-12-04T21:01:33.000Z
2021-04-27T15:35:31.000Z
289.820571
86,274
0.904702
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "# a)\nimport sse", "_____no_output_____" ], [ "Lx, Ly = 8, 8\nn_updates_measure = 10000", "_____no_output_____" ], [ "# b)\n\nspins, op_string, bonds = sse.init_SSE_square(Lx, Ly)\n\nfor beta in [0.1, 1., 64.]:\n op_string = sse.thermalize(spins, op_string, bonds, beta, n_updates_measure//10)\n ns = sse.measure(spins, op_string, bonds, beta, n_updates_measure)\n plt.figure()\n plt.hist(ns, bins=np.arange(len(op_string)+1))\n plt.axvline(len(op_string), color='r', ) # mark the length of the operator string\n plt.xlim(0, len(op_string)*1.1)\n plt.title(\"T=1./{beta:.1f}, len of op_string={l:d}\".format(beta=beta, l=len(op_string)))\n plt.xlabel(\"number of operators $n$\")", "_____no_output_____" ] ], [ [ "The red bar indicates the size of the operator string after thermalization.\nThese histograms justify that we can fix the length of the operator string `M` (called $n*$ in the lecture notes).\nSince `M` is automatically chosen as large as needed, we effectively take into account *all* relevant terms of the full series $\\sum_{n=0}^\\infty$ in the expansion, even if our numerical simulations only use a finite `M`.", "_____no_output_____" ] ], [ [ "# c)\nTs = np.linspace(2., 0., 20, endpoint=False)\nbetas = 1./Ts\nLs = [4, 8, 16]", "_____no_output_____" ], [ "Es_Eerrs = []\nfor L in Ls:\n print(\"=\"*80)\n print(\"L =\", L)\n E = sse.run_simulation(L, L, betas) \n Es_Eerrs.append(E)", "================================================================================\nL = 4\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 8\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 16\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n" ], [ "plt.figure()\nfor E, L in zip(Es_Eerrs, Ls):\n plt.errorbar(Ts, E[:, 0], yerr=E[:, 1], label=\"L={L:d}\".format(L=L))\nplt.legend()\nplt.xlim(0, np.max(1./betas))\nplt.xlabel(\"temperature $T$\")\nplt.ylabel(\"energy $E$ per site\")", "_____no_output_____" ] ], [ [ "# specific heat", "_____no_output_____" ] ], [ [ "# d)\n\ndef run_simulation(Lx, Ly, betas=[1.], n_updates_measure=10000, n_bins=10):\n \"\"\"A full simulation: initialize, thermalize and measure for various betas.\"\"\"\n spins, op_string, bonds = sse.init_SSE_square(Lx, Ly)\n n_sites = len(spins)\n n_bonds = len(bonds)\n Es_Eerrs = []\n Cs_Cerrs = []\n for beta in betas:\n print(\"beta = {beta:.3f}\".format(beta=beta), flush=True)\n op_string = sse.thermalize(spins, op_string, bonds, beta, n_updates_measure//10)\n Es = []\n Cs = []\n for _ in range(n_bins):\n ns = sse.measure(spins, op_string, bonds, beta, n_updates_measure)\n # energy per site\n n_mean = np.mean(ns)\n E = (-n_mean/beta + 0.25*n_bonds) / n_sites\n Es.append(E)\n Cv = (np.mean(ns**2) - n_mean - n_mean**2)/ n_sites\n Cs.append(Cv)\n E, Eerr = np.mean(Es), np.std(Es)/np.sqrt(n_bins)\n Es_Eerrs.append((E, Eerr))\n C, Cerr = np.mean(Cs), np.std(Cs)/np.sqrt(n_bins)\n Cs_Cerrs.append((C, Cerr))\n return np.array(Es_Eerrs), np.array(Cs_Cerrs)", "_____no_output_____" ], [ "Es_Errs, Cs_Cerrs = run_simulation(8, 8, betas)", "beta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n" ], [ "plt.figure()\nplt.errorbar(Ts, Cs_Cerrs[:, 0], yerr=Cs_Cerrs[:, 1], label=\"L={L:d}\".format(L=L))\nplt.xlim(0, np.max(1./betas))\nplt.xlabel(\"temperature $T$\")\nplt.ylabel(\"Specific heat $C_v$ per site\")", "_____no_output_____" ] ], [ [ "## Interpretation\nWe see the behaviour expected from the previous plot considering $C_v= \\partial_T <E> $.\n\nHowever, as $T \\rightarrow 0$ or $\\beta \\rightarrow \\infty$ the error of $C_v$ blows up!\nLooking at the formula $C_v = <n^2> - <n>^2 - <n>$, we see that it consist of larger terms which should cancel to zero.\nStatistical noise is of the order of the large terms $<n^2>$, hence the relative error in $C_v$ explodes.\n\nThis is the essential problem of the infamous \"sign problem\" of quantum monte carlo (QMC): in many models (e.g. in our case of the SSE if we don't have a bipartite lattice) one encounters negative weights for some configurations in the partition function, and a cancelation of different terms. Similar as for the $C_v$ at low temperatures, this often leads to error bars which are often exponentially large in the system size. Obviously, phases from a \"time evolution\" lead to a similar problem. There is no generic solution to circumvent the sign problem (it's NP hard!), but for many specific models, there were actually sign-problem free solutions found.\n\nOn the other hand, whenever QMC has no sign problem, it is for sure one of the most powerful numerical methods we have. For example, it allows beautiful finite size scaling collapses to extract critical exponents etc. for quantum phase transitions even in 2D or 3D.\n\n# Staggered Magnetization", "_____no_output_____" ] ], [ [ "# e)\n\ndef get_staggering(Lx, Ly):\n stag = np.zeros(Lx*Ly, np.intp)\n for x in range(Lx):\n for y in range(Ly):\n s = sse.site(x, y, Lx, Ly)\n stag[s] = (-1)**(x+y)\n return stag\n\n\ndef staggered_magnetization(spins, stag):\n return 0.5*np.sum(spins * stag)\n\n\ndef measure(spins, op_string, bonds, stag, beta, n_updates_measure):\n \"\"\"Perform a lot of updates with measurements.\"\"\"\n ns = []\n ms = []\n for _ in range(n_updates_measure):\n n = sse.diagonal_update(spins, op_string, bonds, beta)\n m = staggered_magnetization(spins, stag)\n sse.loop_update(spins, op_string, bonds)\n ns.append(n)\n ms.append(m)\n return np.array(ns), np.array(ms)\n\n\ndef run_simulation(Lx, Ly, betas=[1.], n_updates_measure=10000, n_bins=10):\n \"\"\"A full simulation: initialize, thermalize and measure for various betas.\"\"\"\n spins, op_string, bonds = sse.init_SSE_square(Lx, Ly)\n stag = get_staggering(Lx, Ly)\n n_sites = len(spins)\n n_bonds = len(bonds)\n Es_Eerrs = []\n Cs_Cerrs = []\n Ms_Merrs = []\n for beta in betas:\n print(\"beta = {beta:.3f}\".format(beta=beta), flush=True)\n op_string = sse.thermalize(spins, op_string, bonds, beta, n_updates_measure//10)\n Es = []\n Cs = []\n Ms = []\n for _ in range(n_bins):\n ns, ms = measure(spins, op_string, bonds, stag, beta, n_updates_measure)\n # energy per site\n n_mean = np.mean(ns)\n E = (-n_mean/beta + 0.25*n_bonds) / n_sites\n Es.append(E)\n Cv = (np.mean(ns**2) - n_mean - n_mean**2)/ n_sites\n Cs.append(Cv)\n Ms.append(np.mean(np.abs(ms))/n_sites) # note that we need the absolute value here!\n # there is a symmetry of flipping all spins which ensures that <Ms> = 0\n E, Eerr = np.mean(Es), np.std(Es)/np.sqrt(n_bins)\n Es_Eerrs.append((E, Eerr))\n C, Cerr = np.mean(Cs), np.std(Cs)/np.sqrt(n_bins)\n Cs_Cerrs.append((C, Cerr))\n M, Merr = np.mean(Ms), np.std(Ms)/np.sqrt(n_bins)\n Ms_Merrs.append((M, Merr))\n return np.array(Es_Eerrs), np.array(Cs_Cerrs), np.array(Ms_Merrs)\n", "_____no_output_____" ], [ "# f)\nLs = [4, 8, 16]\nMs_Merrs = []\nfor L in Ls:\n print(\"=\"*80)\n print(\"L =\", L)\n E, C, M = run_simulation(L, L, betas) \n Ms_Merrs.append(M)", "================================================================================\nL = 4\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 8\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 16\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n" ], [ "plt.figure()\nfor M, L in zip(Ms_Merrs, Ls):\n plt.errorbar(Ts, M[:, 0], yerr=M[:, 1], label=\"L={L:d}\".format(L=L))\nplt.legend()\nplt.xlim(0, np.max(1./betas))\nplt.xlabel(\"temperature $T$\")\nplt.ylabel(\"staggered magnetization $<|M_s|>$ per site\")", "_____no_output_____" ] ], [ [ "# Honeycomb lattice", "_____no_output_____" ] ], [ [ "def site_honeycomb(x, y, u, Lx, Ly):\n \"\"\"Defines a numbering of the sites, given positions x and y and u=0,1 within the unit cell\"\"\"\n return y * Lx * 2 + x*2 + u\n\n\ndef init_SSE_honeycomb(Lx, Ly):\n \"\"\"Initialize a starting configuration on a 2D square lattice.\"\"\"\n n_sites = Lx*Ly*2\n # initialize spins randomly with numbers +1 or -1, but the average magnetization is 0\n spins = 2*np.mod(np.random.permutation(n_sites), 2) - 1\n op_string = -1 * np.ones(10, np.intp) # initialize with identities\n bonds = []\n for x0 in range(Lx):\n for y0 in range(Ly):\n sA = site_honeycomb(x0, y0, 0, Lx, Ly)\n sB0 = site_honeycomb(x0, y0, 1, Lx, Ly)\n bonds.append([sA, sB0])\n sB1 = site_honeycomb(np.mod(x0+1, Lx), np.mod(y0-1, Ly), 1, Lx, Ly)\n bonds.append([sA, sB1])\n sB2 = site_honeycomb(x0, np.mod(y0-1, Ly), 1, Lx, Ly)\n bonds.append([sA, sB2])\n bonds = np.array(bonds, dtype=np.intp)\n return spins, op_string, bonds\n\n\ndef get_staggering_honeycomb(Lx, Ly):\n stag = np.zeros(Lx*Ly*2, np.intp)\n for x in range(Lx):\n for y in range(Ly):\n stag[site_honeycomb(x, y, 0, Lx, Ly)] = +1\n stag[site_honeycomb(x, y, 1, Lx, Ly)] = -1\n return stag\n\n\ndef run_simulation_honeycomb(Lx, Ly, betas=[1.], n_updates_measure=10000, n_bins=10):\n \"\"\"A full simulation: initialize, thermalize and measure for various betas.\"\"\"\n spins, op_string, bonds = init_SSE_honeycomb(Lx, Ly)\n stag = get_staggering_honeycomb(Lx, Ly)\n n_sites = len(spins)\n n_bonds = len(bonds)\n Es_Eerrs = []\n Cs_Cerrs = []\n Ms_Merrs = []\n for beta in betas:\n print(\"beta = {beta:.3f}\".format(beta=beta), flush=True)\n op_string = sse.thermalize(spins, op_string, bonds, beta, n_updates_measure//10)\n Es = []\n Cs = []\n Ms = []\n for _ in range(n_bins):\n ns, ms = measure(spins, op_string, bonds, stag, beta, n_updates_measure)\n # energy per site\n n_mean = np.mean(ns)\n E = (-n_mean/beta + 0.25*n_bonds) / n_sites\n Es.append(E)\n Cv = (np.mean(ns**2) - n_mean - n_mean**2)/ n_sites\n Cs.append(Cv)\n Ms.append(np.mean(np.abs(ms))/n_sites)\n E, Eerr = np.mean(Es), np.std(Es)/np.sqrt(n_bins)\n Es_Eerrs.append((E, Eerr))\n C, Cerr = np.mean(Cs), np.std(Cs)/np.sqrt(n_bins)\n Cs_Cerrs.append((C, Cerr))\n M, Merr = np.mean(Ms), np.std(Ms)/np.sqrt(n_bins)\n Ms_Merrs.append((M, Merr))\n return np.array(Es_Eerrs), np.array(Cs_Cerrs), np.array(Ms_Merrs)", "_____no_output_____" ], [ "# just to check: plot the generated lattice\nL =4\nspins, op_string, bonds = init_SSE_honeycomb(L, L)\nstag = get_staggering_honeycomb(L, L)\nn_sites = len(spins)\nn_bonds = len(bonds)\n\n# use non-trivial unit-vectors\nunit_vectors = np.array([[1, 0], [0.5, 0.5*np.sqrt(3)]])\ndx = np.array([0., 0.5])\nsite_positions = np.zeros((n_sites, 2), np.float)\nfor x in range(L):\n for y in range(L):\n pos = x* unit_vectors[0, :] + y*unit_vectors[1, :] \n s0 = site_honeycomb(x, y, 0, L, L)\n site_positions[s0, :] = pos\n s1 = site_honeycomb(x, y, 1, L, L)\n site_positions[s1, :] = pos + dx\n# plot the sites and bonds\nplt.figure()\nfor bond in bonds:\n linestyle = '-'\n s0, s1 = bond\n if np.max(np.abs(site_positions[s0, :] - site_positions[s1, :])) > L/2:\n linestyle = ':' # plot bonds from the periodic boundary conditions dotted\n plt.plot(site_positions[bond, 0], site_positions[bond, 1], linestyle=linestyle, color='k')\nplt.plot(site_positions[:, 0], site_positions[:, 1], marker='o', linestyle='')\nplt.show()", "_____no_output_____" ], [ "Ls = [4, 8, 16]\nresult_honeycomb = []\nfor L in Ls:\n print(\"=\"*80)\n print(\"L =\", L)\n res = run_simulation_honeycomb(L, L, betas) \n result_honeycomb.append(res)", "================================================================================\nL = 4\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 8\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n================================================================================\nL = 16\nbeta = 0.500\nbeta = 0.526\nbeta = 0.556\nbeta = 0.588\nbeta = 0.625\nbeta = 0.667\nbeta = 0.714\nbeta = 0.769\nbeta = 0.833\nbeta = 0.909\nbeta = 1.000\nbeta = 1.111\nbeta = 1.250\nbeta = 1.429\nbeta = 1.667\nbeta = 2.000\nbeta = 2.500\nbeta = 3.333\nbeta = 5.000\nbeta = 10.000\n" ], [ "fig, axes = plt.subplots(nrows=3, figsize=(10, 15), sharex=True)\nfor res, L in zip(result_honeycomb, Ls):\n for data, ax in zip(res, axes):\n ax.errorbar(Ts, data[:, 0], yerr=data[:, 1], label=\"L={L:d}\".format(L=L))\nfor ax, ylabel in zip(axes, [\"energy $E$\", \"specific heat $C_v$\", \"stag. magnetization $<|M_s|>$\"]):\n ax.legend()\n ax.set_ylabel(ylabel)\naxes[0].set_xlim(0, np.max(1./betas))\naxes[-1].set_xlabel(\"temperature $T$\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe3b3f42c4cc820237f746adaac0d1f78955dfe
247,369
ipynb
Jupyter Notebook
python/notebooks/xor_keras_relu.ipynb
choas/uTensor_workshop
5e9ede8acc694f860fba42cc7b8b35797dee8ea2
[ "Apache-2.0" ]
3
2019-04-01T10:54:51.000Z
2021-03-03T13:31:46.000Z
python/notebooks/xor_keras_relu.ipynb
choas/uTensor_workshop
5e9ede8acc694f860fba42cc7b8b35797dee8ea2
[ "Apache-2.0" ]
null
null
null
python/notebooks/xor_keras_relu.ipynb
choas/uTensor_workshop
5e9ede8acc694f860fba42cc7b8b35797dee8ea2
[ "Apache-2.0" ]
null
null
null
56.245794
358
0.376316
[ [ [ "import sys\nimport numpy as np\nimport tensorflow as tf\nimport keras.backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.activations import sigmoid\nfrom keras.activations import relu\nfrom keras.activations import tanh\nfrom keras.losses import MSE\nfrom keras.losses import mean_squared_error\n#from keras.losses import binary_crossentropy\nfrom keras.optimizers import SGD\nfrom keras.metrics import binary_accuracy\n\nfrom tensorflow.python.framework.graph_util import convert_variables_to_constants\n\nimport keras\nprint keras.__name__, keras.__version__\nprint tf.__name__, tf.__version__", "keras 2.2.2\ntensorflow 1.12.0\n" ], [ "sess=tf.Session()\nK.set_session(sess)", "_____no_output_____" ], [ "training_data = np.array([[0,0], [0,1], [1,0], [1,1]])\ntarget_data = np.array([ [0], [1], [1], [0]])", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(16, input_dim=2, activation='relu', name='inputlayer'))\n\nmodel.add(Dense(64, activation='relu', name='hlayer'))\n\nmodel.add(Dense(1, activation='relu', name='outputlayer'))\nmodel.compile(loss='mean_squared_error', optimizer=SGD(lr=1), metrics=['accuracy'])", "_____no_output_____" ], [ "from keras.callbacks import TensorBoard\nfrom tensorflow.contrib.tensorboard.plugins import projector\ntensorboard = TensorBoard(log_dir='./logs/xor_logs/keras', histogram_freq=0,\n write_graph=True, write_images=False)", "_____no_output_____" ], [ "epochs = 2000\nmodel.fit(training_data, target_data, epochs=epochs, callbacks=[tensorboard])", "Epoch 1/2000\n4/4 [==============================] - 0s 14ms/step - loss: 0.5000 - acc: 0.5000\nEpoch 2/2000\n4/4 [==============================] - 0s 294us/step - loss: 0.5000 - acc: 0.5000\nEpoch 3/2000\n4/4 [==============================] - 0s 337us/step - loss: 0.5000 - acc: 0.5000\nEpoch 4/2000\n4/4 [==============================] - 0s 313us/step - loss: 0.5000 - acc: 0.5000\nEpoch 5/2000\n4/4 [==============================] - 0s 262us/step - loss: 0.5000 - acc: 0.5000\nEpoch 6/2000\n4/4 [==============================] - 0s 266us/step - loss: 0.5000 - acc: 0.5000\nEpoch 7/2000\n4/4 [==============================] - 0s 266us/step - loss: 0.5000 - acc: 0.5000\nEpoch 8/2000\n4/4 [==============================] - 0s 283us/step - loss: 0.5000 - acc: 0.5000\nEpoch 9/2000\n4/4 [==============================] - 0s 192us/step - loss: 0.5000 - acc: 0.5000\nEpoch 10/2000\n4/4 [==============================] - 0s 185us/step - loss: 0.5000 - acc: 0.5000\nEpoch 11/2000\n4/4 [==============================] - 0s 219us/step - loss: 0.5000 - acc: 0.5000\nEpoch 12/2000\n4/4 [==============================] - 0s 217us/step - loss: 0.5000 - acc: 0.5000\nEpoch 13/2000\n4/4 [==============================] - 0s 289us/step - loss: 0.5000 - acc: 0.5000\nEpoch 14/2000\n4/4 [==============================] - 0s 366us/step - loss: 0.5000 - acc: 0.5000\nEpoch 15/2000\n4/4 [==============================] - 0s 282us/step - loss: 0.5000 - acc: 0.5000\nEpoch 16/2000\n4/4 [==============================] - 0s 327us/step - loss: 0.5000 - acc: 0.5000\nEpoch 17/2000\n4/4 [==============================] - 0s 252us/step - loss: 0.5000 - acc: 0.5000\nEpoch 18/2000\n4/4 [==============================] - 0s 243us/step - loss: 0.5000 - acc: 0.5000\nEpoch 19/2000\n4/4 [==============================] - 0s 235us/step - loss: 0.5000 - acc: 0.5000\nEpoch 20/2000\n4/4 [==============================] - 0s 275us/step - loss: 0.5000 - acc: 0.5000\nEpoch 21/2000\n4/4 [==============================] - 0s 198us/step - loss: 0.5000 - acc: 0.5000\nEpoch 22/2000\n4/4 [==============================] - 0s 245us/step - loss: 0.5000 - acc: 0.5000\nEpoch 23/2000\n4/4 [==============================] - 0s 210us/step - loss: 0.5000 - acc: 0.5000\nEpoch 24/2000\n4/4 [==============================] - 0s 252us/step - loss: 0.5000 - acc: 0.5000\nEpoch 25/2000\n4/4 [==============================] - 0s 281us/step - loss: 0.5000 - acc: 0.5000\nEpoch 26/2000\n4/4 [==============================] - 0s 334us/step - loss: 0.5000 - acc: 0.5000\nEpoch 27/2000\n4/4 [==============================] - 0s 329us/step - loss: 0.5000 - acc: 0.5000\nEpoch 28/2000\n4/4 [==============================] - 0s 290us/step - loss: 0.5000 - acc: 0.5000\nEpoch 29/2000\n4/4 [==============================] - 0s 313us/step - loss: 0.5000 - acc: 0.5000\nEpoch 30/2000\n4/4 [==============================] - 0s 274us/step - loss: 0.5000 - acc: 0.5000\nEpoch 31/2000\n4/4 [==============================] - 0s 274us/step - loss: 0.5000 - acc: 0.5000\nEpoch 32/2000\n4/4 [==============================] - 0s 287us/step - loss: 0.5000 - acc: 0.5000\nEpoch 33/2000\n4/4 [==============================] - 0s 215us/step - loss: 0.5000 - acc: 0.5000\nEpoch 34/2000\n4/4 [==============================] - 0s 223us/step - loss: 0.5000 - acc: 0.5000\nEpoch 35/2000\n4/4 [==============================] - 0s 257us/step - loss: 0.5000 - acc: 0.5000\nEpoch 36/2000\n4/4 [==============================] - 0s 220us/step - loss: 0.5000 - acc: 0.5000\nEpoch 37/2000\n4/4 [==============================] - 0s 295us/step - loss: 0.5000 - acc: 0.5000\nEpoch 38/2000\n4/4 [==============================] - 0s 255us/step - loss: 0.5000 - acc: 0.5000\nEpoch 39/2000\n4/4 [==============================] - 0s 223us/step - loss: 0.5000 - acc: 0.5000\nEpoch 40/2000\n4/4 [==============================] - 0s 305us/step - loss: 0.5000 - acc: 0.5000\nEpoch 41/2000\n4/4 [==============================] - 0s 286us/step - loss: 0.5000 - acc: 0.5000\nEpoch 42/2000\n4/4 [==============================] - 0s 295us/step - loss: 0.5000 - acc: 0.5000\nEpoch 43/2000\n4/4 [==============================] - 0s 237us/step - loss: 0.5000 - acc: 0.5000\nEpoch 44/2000\n4/4 [==============================] - 0s 228us/step - loss: 0.5000 - acc: 0.5000\nEpoch 45/2000\n4/4 [==============================] - 0s 217us/step - loss: 0.5000 - acc: 0.5000\nEpoch 46/2000\n4/4 [==============================] - 0s 233us/step - loss: 0.5000 - acc: 0.5000\nEpoch 47/2000\n4/4 [==============================] - 0s 287us/step - loss: 0.5000 - acc: 0.5000\nEpoch 48/2000\n4/4 [==============================] - 0s 336us/step - loss: 0.5000 - acc: 0.5000\nEpoch 49/2000\n4/4 [==============================] - 0s 283us/step - loss: 0.5000 - acc: 0.5000\nEpoch 50/2000\n4/4 [==============================] - 0s 216us/step - loss: 0.5000 - acc: 0.5000\nEpoch 51/2000\n4/4 [==============================] - 0s 228us/step - loss: 0.5000 - acc: 0.5000\nEpoch 52/2000\n4/4 [==============================] - 0s 217us/step - loss: 0.5000 - acc: 0.5000\nEpoch 53/2000\n4/4 [==============================] - 0s 275us/step - loss: 0.5000 - acc: 0.5000\nEpoch 54/2000\n4/4 [==============================] - 0s 366us/step - loss: 0.5000 - acc: 0.5000\nEpoch 55/2000\n4/4 [==============================] - 0s 239us/step - loss: 0.5000 - acc: 0.5000\nEpoch 56/2000\n4/4 [==============================] - 0s 253us/step - loss: 0.5000 - acc: 0.5000\nEpoch 57/2000\n4/4 [==============================] - 0s 216us/step - loss: 0.5000 - acc: 0.5000\nEpoch 58/2000\n4/4 [==============================] - 0s 255us/step - loss: 0.5000 - acc: 0.5000\nEpoch 59/2000\n4/4 [==============================] - 0s 233us/step - loss: 0.5000 - acc: 0.5000\nEpoch 60/2000\n4/4 [==============================] - 0s 234us/step - loss: 0.5000 - acc: 0.5000\nEpoch 61/2000\n4/4 [==============================] - 0s 287us/step - loss: 0.5000 - acc: 0.5000\nEpoch 62/2000\n4/4 [==============================] - 0s 278us/step - loss: 0.5000 - acc: 0.5000\nEpoch 63/2000\n4/4 [==============================] - 0s 377us/step - loss: 0.5000 - acc: 0.5000\nEpoch 64/2000\n4/4 [==============================] - 0s 235us/step - loss: 0.5000 - acc: 0.5000\nEpoch 65/2000\n4/4 [==============================] - 0s 275us/step - loss: 0.5000 - acc: 0.5000\nEpoch 66/2000\n4/4 [==============================] - 0s 252us/step - loss: 0.5000 - acc: 0.5000\nEpoch 67/2000\n4/4 [==============================] - 0s 266us/step - loss: 0.5000 - acc: 0.5000\nEpoch 68/2000\n4/4 [==============================] - 0s 201us/step - loss: 0.5000 - acc: 0.5000\nEpoch 69/2000\n4/4 [==============================] - 0s 181us/step - loss: 0.5000 - acc: 0.5000\nEpoch 70/2000\n4/4 [==============================] - 0s 179us/step - loss: 0.5000 - acc: 0.5000\nEpoch 71/2000\n4/4 [==============================] - 0s 253us/step - loss: 0.5000 - acc: 0.5000\nEpoch 72/2000\n4/4 [==============================] - 0s 201us/step - loss: 0.5000 - acc: 0.5000\nEpoch 73/2000\n4/4 [==============================] - 0s 198us/step - loss: 0.5000 - acc: 0.5000\nEpoch 74/2000\n4/4 [==============================] - 0s 277us/step - loss: 0.5000 - acc: 0.5000\nEpoch 75/2000\n4/4 [==============================] - 0s 324us/step - loss: 0.5000 - acc: 0.5000\nEpoch 76/2000\n4/4 [==============================] - 0s 237us/step - loss: 0.5000 - acc: 0.5000\nEpoch 77/2000\n4/4 [==============================] - 0s 247us/step - loss: 0.5000 - acc: 0.5000\nEpoch 78/2000\n4/4 [==============================] - 0s 237us/step - loss: 0.5000 - acc: 0.5000\nEpoch 79/2000\n4/4 [==============================] - 0s 251us/step - loss: 0.5000 - acc: 0.5000\nEpoch 80/2000\n4/4 [==============================] - 0s 190us/step - loss: 0.5000 - acc: 0.5000\nEpoch 81/2000\n4/4 [==============================] - 0s 281us/step - loss: 0.5000 - acc: 0.5000\nEpoch 82/2000\n4/4 [==============================] - 0s 265us/step - loss: 0.5000 - acc: 0.5000\nEpoch 83/2000\n4/4 [==============================] - 0s 243us/step - loss: 0.5000 - acc: 0.5000\nEpoch 84/2000\n4/4 [==============================] - 0s 256us/step - loss: 0.5000 - acc: 0.5000\nEpoch 85/2000\n4/4 [==============================] - 0s 242us/step - loss: 0.5000 - acc: 0.5000\nEpoch 86/2000\n4/4 [==============================] - 0s 205us/step - loss: 0.5000 - acc: 0.5000\n" ], [ "print \"loss:\", model.evaluate(x=training_data, y=target_data, verbose=0)\nprint \"\"\nprint model.predict(training_data)\nprint \"\"\nprint model.predict(training_data).round()", "loss: [0.5, 0.5]\n\n[[0.]\n [0.]\n [0.]\n [0.]]\n\n[[0.]\n [0.]\n [0.]\n [0.]]\n" ] ], [ [ "## freeze model and save as Tensorflow ", "_____no_output_____" ] ], [ [ "freeze_var_names = list(set(v.op.name for v in tf.global_variables()))\nprint freeze_var_names\noutput_names = [model.outputs[0].name.split(\":\")[0]]\n\nfrom tensorflow.python.framework.graph_util import remove_training_nodes\nsub_graph_def = remove_training_nodes(sess.graph_def)\n\nfrozen_graph = convert_variables_to_constants(sess,\n sub_graph_def,\n output_names,\n freeze_var_names)\n\ngraph_path = tf.train.write_graph(frozen_graph, \"models\", \"xor_keras.pb\", as_text=False)\nprint output_names\nprint('%s written' % graph_path)", "[u'inputlayer/kernel', u'training/SGD/Variable', u'hlayer/bias', u'SGD/decay', u'hlayer/kernel', u'training/SGD/Variable_4', u'training/SGD/Variable_5', u'training/SGD/Variable_2', u'SGD/lr', u'outputlayer/bias', u'training/SGD/Variable_1', u'SGD/iterations', u'training/SGD/Variable_3', u'inputlayer/bias', u'outputlayer/kernel', u'SGD/momentum']\nINFO:tensorflow:Froze 6 variables.\nINFO:tensorflow:Converted 6 variables to const ops.\n[u'outputlayer/Relu']\nmodels/xor_keras.pb written\n" ], [ "model.outputs", "_____no_output_____" ], [ "# unsupported op type in uTensor: QuantizedBiasAdd", "_____no_output_____" ], [ "### tensorflow.js\n\nimport tensorflowjs as tfjs\ntfjs.converters.save_keras_model(model, \"web\")", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe3b459b17f2b3394c15b3fb04650ea3c4d83c5
6,278
ipynb
Jupyter Notebook
python/authentication/registerClient_generateToken_Python.ipynb
sassoftware/rest-api-use-cases
ee6015fe3d3f288384f53d95cbf45b9e32ed2aae
[ "Apache-2.0" ]
6
2021-10-30T15:29:42.000Z
2022-01-12T09:05:51.000Z
python/authentication/registerClient_generateToken_Python.ipynb
sassoftware/rest-api-use-cases
ee6015fe3d3f288384f53d95cbf45b9e32ed2aae
[ "Apache-2.0" ]
null
null
null
python/authentication/registerClient_generateToken_Python.ipynb
sassoftware/rest-api-use-cases
ee6015fe3d3f288384f53d95cbf45b9e32ed2aae
[ "Apache-2.0" ]
2
2022-01-12T07:33:39.000Z
2022-01-12T07:35:36.000Z
34.685083
286
0.607996
[ [ [ "# Register Client and Create Access Token Notebook\n- Find detailed information about client registration and access tokens in this blog post: [Authentication to SAS Viya: a couple of approaches](https://blogs.sas.com/content/sgf/2021/09/24/authentication-to-sas-viya/)\n- Use the client_id to create an access token you can use in the Jupyter environment or externally for API calls to SAS Viya.\n- You must add the following info to the script: client_id, client_secret, baseURL, and consul_token\n- Additional access token information is found at the end of this notebook.\n\n\n### Run the cells below and follow the resulting instructions.", "_____no_output_____" ], [ "# Get register access token", "_____no_output_____" ] ], [ [ "import requests\nimport json\nimport os\nimport base64\n\n# set/create variables\nclient_id=\"\"\nclient_secret=\"\"\nbaseURL = \"\" # sasserver.sas.com\nconsul_token = \"\"\n\n# generate API call for register access token\nurl = f\"https://{baseURL}/SASLogon/oauth/clients/consul?callback=false&serviceId={client_id}\"\nheaders = {\n'X-Consul-Token': consul_token\n}\n\n# process the results\nresponse = requests.request(\"POST\", url, headers=headers, verify=False)\n\nregister_access_token = json.loads(response.text)['access_token']\nprint(json.dumps(response.json(), indent=4, sort_keys=True))", "_____no_output_____" ] ], [ [ "# Register the client", "_____no_output_____" ] ], [ [ "# create API call payload data\npayload='{\"client_id\": \"' + client_id +'\",\"client_secret\": \"'+ client_secret +'\",\"scope\": [\"openid\", \"*\"],\"authorized_grant_types\": [\"authorization_code\",\"refresh_token\"],\"redirect_uri\": \"urn:ietf:wg:oauth:2.0:oob\",\"access_token_validity\": \"43199\"}'\n\n# generate API call for register access token\nurl = f\"https://{baseURL}/SASLogon/oauth/clients\"\nheaders = {\n'Content-Type': 'application/json',\n'Authorization': \"Bearer \" + register_access_token\n}\n\n# process the results\nresponse = requests.request(\"POST\", url, headers=headers, data=payload, verify=False)\nprint(json.dumps(response.json(), indent=4, sort_keys=True))", "_____no_output_____" ] ], [ [ "# Create access token", "_____no_output_____" ] ], [ [ "# create authorization url\ncodeURL = \"https://\" + baseURL + \"/SASLogon/oauth/authorize?client_id=\" + client_id + \"&response_type=code\"\n\n# enccode client string\nclient_string = client_id + \":\" + client_secret\nmessage_bytes = client_string.encode('ascii')\nbase64_bytes = base64.b64encode(message_bytes)\nbase64_message = base64_bytes.decode('ascii')\n\n# promt with instructions and entry for auth code\nprint(f\"* Please visit the following site {codeURL}\")\nprint(\"* If provided a login prompt, add your SAS login credentials\")\nprint(\"* Once authenticated, you'll be redirected to an authoriztion screen, check all of the boxes that appear\")\nprint(\"* This will result in a short string of numbers and letters such as `VAxVFVEnKr`; this is your authorization code; copy the code\")\ncode = input(\"Please enter the authoriztion code you generated through the previous instructions, and then press Enter: \")\n\n# generate API call for access token\nurl = f\"https://{baseURL}/SASLogon/oauth/token?grant_type=authorization_code&code={code}\"\nheaders = {\n'Accept': 'application/json',\n'Content-Type': 'application/x-www-form-urlencoded',\n'Authorization': \"Basic \" + base64_message\n}\n\n# process the results\nresponse = requests.request(\"GET\", url, headers=headers, verify=False)\naccess_token = json.loads(response.text)['access_token']\nprint(json.dumps(response.json(), indent=4, sort_keys=True))\n\n# Create access_token.txt file \ndirectory = os.getcwd()\nwith open(directory + '/access_token.txt', 'w') as f:\n f.write(access_token)\nprint('The access token was stored for you as ' + directory + '/access_token.txt')", "_____no_output_____" ] ], [ [ "## Notes on the access token\n- The access token has a 12 hour time-to-live (ttl) by default.\n- The authorization code is good for 30 minutes and is only good for a single use. \n- You can generate a new authorization code by reusing the authorization url.\n- The access_token is valid in this Notebook and is transferable to other notebooks and used for external API calls.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe3bf60e0e400ddfabbd1d80a79bf698b994d8b
78,865
ipynb
Jupyter Notebook
1. Beginner/Pytorch_RNN_NLP_Name_Classification.ipynb
gjustin40/Pytorch
b099fe7975490790f5179f2733a3fc546b5b3d46
[ "MIT" ]
null
null
null
1. Beginner/Pytorch_RNN_NLP_Name_Classification.ipynb
gjustin40/Pytorch
b099fe7975490790f5179f2733a3fc546b5b3d46
[ "MIT" ]
1
2022-03-12T01:01:53.000Z
2022-03-12T01:01:53.000Z
1. Beginner/Pytorch_RNN_NLP_Name_Classification.ipynb
gjustin40/Pytorch
b099fe7975490790f5179f2733a3fc546b5b3d46
[ "MIT" ]
1
2020-06-06T09:09:39.000Z
2020-06-06T09:09:39.000Z
64.117886
27,934
0.763457
[ [ [ "# 문자 단위 RNN으로 이름 분류하기\n- 문자 하나(ex. a, b,....,z)를 하나의 one-hot벡터로 표현하여 예측 실시\n- 한 문자의 벡터 길이는 alphabet의 길이(26)이다.\n- 18개 언어로 된 수천 개의 성을 훈련시킨 후, 철자에 따라 이름이 어떤 언어인지 예측", "_____no_output_____" ], [ "# DataLoad\n- data/name 디렉토리에 18개 텍스트 파일이 포함되어 있다.\n- 각 파일에는 한 줄에 하나의 이름이 포함되어 있다.(로마자)\n- ASCII로 변환해야 한다.", "_____no_output_____" ] ], [ [ "# data 보기\nfrom io import open\nimport glob\nimport os\n\npath = 'data/names/'\nfilenames = glob.glob(path + '*.txt')\nprint(filenames)\nprint('')\nprint(len(filenames))", "['data/names\\\\Arabic.txt', 'data/names\\\\Chinese.txt', 'data/names\\\\Czech.txt', 'data/names\\\\Dutch.txt', 'data/names\\\\English.txt', 'data/names\\\\French.txt', 'data/names\\\\German.txt', 'data/names\\\\Greek.txt', 'data/names\\\\Irish.txt', 'data/names\\\\Italian.txt', 'data/names\\\\Japanese.txt', 'data/names\\\\Korean.txt', 'data/names\\\\Polish.txt', 'data/names\\\\Portuguese.txt', 'data/names\\\\Russian.txt', 'data/names\\\\Scottish.txt', 'data/names\\\\Spanish.txt', 'data/names\\\\Vietnamese.txt']\n\n18\n" ], [ "import unicodedata\nimport string # 모든 알파벳을 출력하기 위해 import\n\nprint(string.hexdigits) # 16진수 표현하는 문자들\nprint(string.punctuation) # 특수문자, 특수기호\nprint(string.whitespace) # 공백문자\nprint(string.printable) # 모든 문자 + 기호\n\nall_letters = string.ascii_letters + ' .,;' # 알파벳(대 + 소) + 공백 + ,.;\nall_letters", "0123456789abcdefABCDEF\n!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n \t\n\r\u000b\f\n0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\u000b\f\n" ], [ "# 유니코드 문자열을 일반 ASCII로 변환\n# 한 단어를 문자 하나하나로 쪼개서 각각을 ascii로 변환\n# 또한 변환된 단어의 분류가 'Mn'이 아니고 all_letters에 포함되어 있으면 출력\ndef Unicode_to_Ascii(s):\n word = ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn' # Nonspacing Mark, 특정 언어에서 사용되는 기호\n and c in all_letters) # c가 all_letter에 포함되어 있는 것\n \n return word\n\nprint(Unicode_to_Ascii('Ślusàrski'))", "Slusarski\n" ], [ "# 각 파일로부터 이름 불러오기\ndef readline(filename):\n lines = open(filename, encoding = 'utf-8').read().strip().split('\\n')\n names = [name for name in lines]\n \n return names\n\nlan_list = []\nlan_name_list = {}\n\n# 국가별 이름 목록사전 만들기{lan : [name1, name2...]}\nfor filename in filenames:\n lan = os.path.splitext(os.path.basename(filename))[0]\n lan_list.append(lan)\n name = readline(filename)\n lan_name_list[lan] = name\n \nlan_n = len(lan_name_list)", "_____no_output_____" ] ], [ [ "### 변수 설명\n- lan_list : 국가 목록\n- lan_name_list : 국가별 이름 목록\n- lan_name_list_n : 국가 개수", "_____no_output_____" ], [ "# 이름을 Tensor로 변환\n- 하나의 문자(ex. a)를 표현하기 위해서는 size가 1xn_letter인 One-hot 벡터를 사용한다.\n- a : Tensor[[1,0,0,0......,0]]\n- b : Tensor[[0,1,0,0.......0]]\n- z : Tensor[[0,0,0,0.......1]]\n<br><br>\n- 단어를 만들어 주기 위해 2차원 행렬(len_of_word x 1 x n_letters)", "_____no_output_____" ] ], [ [ "import torch\n\n# 한 letter의 index값을 출력\ndef Letter_to_Index(letter):\n letter_index = all_letters.find(letter) \n \n return letter_index\n\n# 각 letter별 index사전 만들기(one-hot 벡터)\ndef Letter_to_Tensor(letter):\n letter_tensor = torch.zeros(1, len(all_letters))\n letter_tensor[0][Letter_to_Index(letter)] = 1\n \n return letter_tensor\n\ndef Name_to_Tensor(name):\n tensor = torch.zeros(len(name), 1, len(all_letters))\n for i, c in enumerate(name):\n tensor[i][0][Letter_to_Index(c)] = 1\n \n return tensor\n\nprint(Letter_to_Tensor('j'))\nprint(Name_to_Tensor('justin').size())", "tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0.]])\ntorch.Size([6, 1, 56])\n" ] ], [ [ "# RNN 생성\n- input layer와 hidden layer가 합쳐져 output layer(i2o)를 형성\n- input layer와 hideen layer가 합쳐져 다음 hidden layer(i2h)를 형성\n- i2o인 경우 sofrmax 함수를 이용해 확률값 출력하고 정답label과 오차값 계산\n- i2h인 경우 두 번째 h2로 \n넘어간다.\n\n# 진행 과정\n1. 이름 하나를 구성하는 각각의 letter들이 한 글자씩 input으로 들어간다.\n2. ", "_____no_output_____" ] ], [ [ "import torch.nn as nn\n\nclass RNN(nn.Module):\n \n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n \n self.hidden_size = hidden_size\n \n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.softmax = nn.LogSoftmax(dim = 1)\n \n def forward(self, input, hidden):\n \n combined = torch.cat((input, hidden), 1) # 열로 붙이기\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n \n return output, hidden\n\n def initHidden(self):\n \n return torch.zeros(1, self.hidden_size)\n \nhidden_n = 128\nletter_n = len(all_letters)\nlan_n = len(lan_name_list)\n\n\nrnn = RNN(letter_n, hidden_n, lan_n)", "_____no_output_____" ], [ "with torch.no_grad():\n input = Letter_to_Tensor('a')\n hidden = torch.zeros(1, hidden_n)\n\n output, hidden = rnn(input, hidden)\n print(output) # 출력은 국가 중 하나이고, 값이 높을수록 가능성이 높다.", "tensor([[-2.8130, -2.8156, -2.8805, -2.9628, -2.8684, -2.9068, -3.0163, -2.8829,\n -2.8716, -2.8223, -2.8996, -2.8302, -2.9353, -3.0007, -2.8497, -2.8181,\n -2.9474, -2.9397]])\n" ], [ "with torch.no_grad():\n input = Name_to_Tensor('justin')\n hidden = torch.zeros(1, hidden_n)\n output, hidden = rnn(input[0], hidden)\n \n print(output) # 출력은 국가 중 하나이고, 값이 높을수록 가능성이 높다.", "tensor([[-2.8659, -2.8775, -2.8675, -2.9458, -2.8337, -2.9207, -2.9108, -2.9311,\n -2.8282, -2.8395, -2.8389, -2.9530, -2.9586, -2.9144, -2.8015, -2.8867,\n -2.8588, -3.0215]])\n" ] ], [ [ "# 학습하기 전 준비과정\n도움되는 함수 몇 가지가 필요하다.\n 1. output 결과로부터 가장 큰 값이 무엇인지 출력하기(가장 가능성이 큰 국가 출력)\n 2. 학습 예시를 출력해주는 함수", "_____no_output_____" ] ], [ [ "def LanfromOutput(output):\n top_val, top_i = output.topk(1) # Tensor내에 최대값의 value와 index 찾기(input값으로 개수 선택)\n lan_i = top_i[0].item()\n \n return lan_list[lan_i], lan_i\n\nLanfromOutput(output)", "_____no_output_____" ], [ "# 학습 예시(이름과 언어) 얻는 빠른 방법도 필요하다.\nimport random\n\ndef RandomChoice(l):\n lan_random = l[random.randint(0, len(l) - 1)]\n \n return lan_random\n\ndef RandomTrainingExample():\n lan_random = RandomChoice(lan_list) # 랜덤 국가 선택\n name = RandomChoice(lan_name_list[lan_random]) # 선택된 국가 중 랜덤 이름 선택\n lan_tensor = torch.tensor([lan_list.index(lan_random)], dtype = torch.long) # 국가 index의 tensor\n name_tensor = Name_to_Tensor(name) # 이름을 tensor로\n \n return lan_random, name, lan_tensor, name_tensor\n\nfor i in range(10):\n lan, name, lan_tensor, name_tensor = RandomTrainingExample()\n print('Langauge : %s / name = %s' %(lan, name))", "Langauge : French / name = Colbert\nLangauge : Vietnamese / name = Quach\nLangauge : Italian / name = Masin\nLangauge : Arabic / name = Bahar\nLangauge : Chinese / name = Xing\nLangauge : Irish / name = Devin\nLangauge : Irish / name = Quinn\nLangauge : Dutch / name = Roosevelt\nLangauge : Greek / name = Pefanis\nLangauge : Portuguese / name = Medeiros\n" ] ], [ [ "# 학습 과정\n1. input과 target의 Tensor 생성\n2. 0으로 초기화 된 hidden layer 생성\n3. 각 문자 읽기 - 다음 문자를 위한 은닉 상태 유지\n4. output과 target 비교하여 오차 계산\n5. 오차 역전파\n6. output과 loss 출력", "_____no_output_____" ] ], [ [ "# 일단 optimizer를 사용 안하고 그냥 했는데... 일단 그냥 해봄\nimport torch.optim as optim\noptimizer = optim.SGD(rnn.parameters(), lr = 0.005) \n\nloss_function = nn.NLLLoss()\nlearning_rate = 0.005\n\ndef train(lan_tensor, name_tensor):\n \n hidden = rnn.initHidden()\n \n optimizer.zero_grad()\n \n for i in range(name_tensor.size()[0]):\n output, hidden = rnn(name_tensor[i], hidden)\n \n loss = loss_function(output, lan_tensor)\n loss.backward()\n \n optimizer.step()\n #for p in rnn.parameters():\n # p.data.add_(-learning_rate, p.grad.data)\n \n return output, loss.item()", "_____no_output_____" ], [ "import time\nimport math\n\niter_n = 100000\n\nloss_avg = 0\nloss_list = []\n\ndef timeSince(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\nstart = time.time()\n\n\nfor i in range(1, iter_n + 1):\n lan, name, lan_tensor, name_tensor = RandomTrainingExample()\n output, loss = train(lan_tensor, name_tensor)\n loss_avg += loss\n \n if i % 5000 == 0:\n guess, guess_i = LanfromOutput(output)\n correct = '✓' if guess == lan else '✗ (%s)' % lan\n print('%d %d%% (%s) %.4f %s / %s %s' % (i, i / iter_n * 100, timeSince(start), loss, name, guess, correct))\n\n if i % 1000 == 0:\n loss_list.append(loss_avg / 1000)\n loss_avg = 0 ", "5000 5% (0m 10s) 2.8048 Rios / Korean ✗ (Portuguese)\n10000 10% (0m 20s) 2.5161 Bazhaev / German ✗ (Russian)\n15000 15% (0m 30s) 1.2065 Seo / Chinese ✗ (Korean)\n20000 20% (0m 39s) 2.5200 Zimola / Japanese ✗ (Czech)\n25000 25% (0m 49s) 1.4307 Faerber / German ✓\n30000 30% (0m 58s) 1.5007 Vlasak / Polish ✗ (Czech)\n35000 35% (1m 8s) 1.0915 Santos / Portuguese ✓\n40000 40% (1m 17s) 0.1492 Vikhorev / Russian ✓\n45000 45% (1m 27s) 0.5221 Suh / Korean ✓\n50000 50% (1m 36s) 1.5349 Login / Russian ✗ (Irish)\n55000 55% (1m 46s) 0.0193 Abbracciabeni / Italian ✓\n60000 60% (1m 56s) 1.1287 Bach / Vietnamese ✓\n65000 65% (2m 6s) 2.6943 Specht / German ✗ (Dutch)\n70000 70% (2m 15s) 2.6231 Gouveia / Spanish ✗ (Portuguese)\n75000 75% (2m 25s) 0.0629 Nurmuhamedov / Russian ✓\n80000 80% (2m 36s) 0.0141 Kedzierski / Polish ✓\n85000 85% (2m 46s) 4.6938 Clark / Polish ✗ (Irish)\n90000 90% (2m 55s) 2.3861 Graham / Arabic ✗ (Scottish)\n95000 95% (3m 4s) 0.4466 Luu / Vietnamese ✓\n100000 100% (3m 14s) 1.4725 Rhee / Korean ✓\n" ] ], [ [ "# Loss값 시각화", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure()\nplt.plot(loss_list)", "_____no_output_____" ] ], [ [ "# 나만의 방식으로 재도전\n- 문서에 나와있는 방식은 너무 복잡하다.\n- 좀 더 간단하게 구현 시도!\n- 사실 대부분 비슷한데.... 디테일이 다르다", "_____no_output_____" ], [ "# 데이터 불러오기", "_____no_output_____" ] ], [ [ "import glob\nfrom io import open\n\npath = 'data/names/'\nfilenames = glob.glob(path + '*.txt')\nprint(filenames)", "['data/names\\\\Arabic.txt', 'data/names\\\\Chinese.txt', 'data/names\\\\Czech.txt', 'data/names\\\\Dutch.txt', 'data/names\\\\English.txt', 'data/names\\\\French.txt', 'data/names\\\\German.txt', 'data/names\\\\Greek.txt', 'data/names\\\\Irish.txt', 'data/names\\\\Italian.txt', 'data/names\\\\Japanese.txt', 'data/names\\\\Korean.txt', 'data/names\\\\Polish.txt', 'data/names\\\\Portuguese.txt', 'data/names\\\\Russian.txt', 'data/names\\\\Scottish.txt', 'data/names\\\\Spanish.txt', 'data/names\\\\Vietnamese.txt']\n" ] ], [ [ "# 국가별 이름 사전 만들기\n- {국가1 : [이름1, 이름2...], 국가2 : [이름1, 이름2...]}", "_____no_output_____" ] ], [ [ "import os\nfrom io import open\n\nlan_name_dict = {}\nlan_list = []\n\nfor filename in filenames:\n names = open(filename, encoding = 'utf-8').read().strip().split('\\n')\n lan = os.path.splitext(os.path.basename(filename))[0]\n lan_list.append(lan)\n lan_name_dict[lan] = names\n \nlan_list_n = len(lan_list)\nlan_name_dict_n = len(lan_name_dict)", "_____no_output_____" ], [ "names_n = []\nfor lan in lan_list:\n name_n = len(lan_name_dict[lan])\n names_n.append(name_n)\n\nprint('Number of languge : %d' %lan_list_n)\nprint('Number of names : %d' %sum(names_n))", "Number of languge : 18\nNumber of names : 20074\n" ] ], [ [ "# 이름을 Unicode -> Ascii로 변환", "_____no_output_____" ] ], [ [ "import unicodedata\nimport string\n\nletters = string.ascii_letters + \" .,;'\"\nletters_n = len(letters)\n\ndef Unicode_to_Ascii(s):\n w = ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in letters)\n \n return w\n\nfor lan, names in lan_name_dict.items():\n converted_names = [Unicode_to_Ascii(name) for name in names]\n lan_name_dict[lan] = converted_names ", "_____no_output_____" ], [ "lan_name_dict['Italian'][:5]", "_____no_output_____" ] ], [ [ "# 이름을 Tensor로 변환\n## 방법은 2가지\n1. Lookup 방식을 이용하기 위해 letter_to_vector 사전을 만든다.\n2. 함수를 이용해서 해당 letter에 해당하는 vector를 바로 만든다.", "_____no_output_____" ] ], [ [ "# 1. lookup 방식\nimport torch\n\nletter_to_vec = {}\n\nfor i, l in enumerate(letters):\n vec = torch.zeros(1, letters_n)\n vec[0][i] = 1\n letter_to_vec[l] = vec\n \ndef Name_to_Vec(name):\n vec = torch.zeros(len(name), 1, letters_n)\n for i, l in enumerate(name):\n vec[i][0] = letter_to_vec[l]\n \n return vec", "_____no_output_____" ], [ "print(letter_to_vec['J'])\nprint(Name_to_Vec('Jones').size())", "tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0.]])\ntorch.Size([5, 1, 57])\n" ] ], [ [ "# RNN 모델\n- input과 hidden을 합치는 combined layer\n- input에서 output으로 가는 i2o layer\n- input에서 hidden으로 가는 i2h layer\n- softmax를 적용시키는 softmax layer", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\n\nclass RNN(nn.Module):\n \n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n \n self.hidden_size = hidden_size\n \n self.i2o = nn.Linear(input_size + hidden_size, output_size)\n self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n self.softmax = nn.LogSoftmax(dim = 1)\n \n def forward(self, input, hidden):\n \n combined = torch.cat((input, hidden), 1)\n hidden = self.i2h(combined)\n output = self.i2o(combined)\n output = self.softmax(output)\n \n return output, hidden\n \n def initHidden(self):\n \n return torch.zeros(1, self.hidden_size)\n \nhidden_n = 128\nrnn = RNN(letters_n, hidden_n, lan_list_n)", "_____no_output_____" ], [ "# letter 1개 예시\nwith torch.no_grad():\n input_example = letter_to_vec['a']\n hidden_example = torch.zeros(1, hidden_n)\n output, next_hidden = rnn(input_example, hidden_example)\n \n print(output)", "tensor([[-2.8916, -2.8997, -2.8615, -2.9387, -2.9104, -2.9101, -2.8290, -2.8249,\n -2.8897, -2.8991, -2.9835, -2.8926, -2.8647, -2.8558, -2.8962, -2.9184,\n -2.9046, -2.8682]])\n" ], [ "# Name 1개 예시\nwith torch.no_grad():\n input_example = Name_to_Vec('Justin')\n hidden_example = torch.zeros(1, hidden_n)\n output, next_hidden = rnn(input_example[0], hidden_example)\n print(output)", "tensor([[-2.9028, -2.8339, -2.8316, -2.9295, -2.9498, -2.8423, -2.9440, -2.8958,\n -2.9672, -2.9163, -2.8731, -2.9394, -2.8422, -2.8369, -2.8012, -2.9675,\n -2.8805, -2.8953]])\n" ] ], [ [ "# input 데이터 랜덤으로 생성\n- Train할 이름들 랜덤으로 생성시키기\n 1. 랜덤으로 국가 선택\n 2. 해당 국가에서 랜덤으로 이름 선택\n- Output = 국가, 이름, 국가Tensor, 이름Tensor", "_____no_output_____" ] ], [ [ "import random\n\ndef RandomPick():\n lan_random_index = random.randint(0, lan_list_n - 1)\n lan_random = lan_list[lan_random_index]\n name_random_index = random.randint(0, len(lan_name_dict[lan_random]) - 1)\n name_random = lan_name_dict[lan_random][name_random_index]\n lan_tensor = torch.tensor([lan_list.index(lan_random)], dtype = torch.long)\n name_tensor = Name_to_Vec(name_random)\n \n return lan_random, name_random, lan_tensor, name_tensor", "_____no_output_____" ], [ "for i in range(10):\n lan, name, lan_tensor, name_tensor = RandomPick()\n print('Language : %s / Name : %s' %(lan, name))", "Language : Czech / Name : Planick\nLanguage : Korean / Name : Bang\nLanguage : Japanese / Name : Hashimoto\nLanguage : Vietnamese / Name : Giang\nLanguage : Portuguese / Name : Santiago\nLanguage : German / Name : Voigts\nLanguage : Japanese / Name : Tokuoka\nLanguage : Vietnamese / Name : Than\nLanguage : Czech / Name : Perevuznik\nLanguage : Czech / Name : Kessel\n" ] ], [ [ "# 학습하기", "_____no_output_____" ] ], [ [ "import torch.optim as optim\n\nloss_function = nn.NLLLoss()\noptimizer = optim.SGD(rnn.parameters(), lr = 0.01)\n\niter_n = 10000\nloss_current = 0\nloss_list = []\n\nfor i in range(1, iter_n):\n \n lan, name, lan_tensor, name_tensor = RandomPick()\n input = name_tensor\n target = lan_tensor\n hidden = rnn.initHidden()\n \n optimizer.zero_grad()\n \n for j in range(name_tensor.size()[0]):\n output, hidden = rnn(name_tensor[j], hidden)\n \n loss = loss_function(output, lan_tensor)\n loss.backward()\n optimizer.step()\n \n loss_current += loss\n \n if i % 500 == 0:\n print(loss_current/ 50)\n \n if i % 50 == 0:\n loss_current = loss_current / 50\n loss_list.append(loss_current)\n loss_current = 0", "tensor(2.8499, grad_fn=<DivBackward0>)\ntensor(2.7689, grad_fn=<DivBackward0>)\ntensor(2.7056, grad_fn=<DivBackward0>)\ntensor(2.5703, grad_fn=<DivBackward0>)\ntensor(2.4544, grad_fn=<DivBackward0>)\ntensor(2.3490, grad_fn=<DivBackward0>)\ntensor(2.3272, grad_fn=<DivBackward0>)\ntensor(2.4818, grad_fn=<DivBackward0>)\ntensor(2.2788, grad_fn=<DivBackward0>)\ntensor(2.3449, grad_fn=<DivBackward0>)\ntensor(2.0157, grad_fn=<DivBackward0>)\ntensor(2.1185, grad_fn=<DivBackward0>)\ntensor(2.3051, grad_fn=<DivBackward0>)\ntensor(2.2327, grad_fn=<DivBackward0>)\ntensor(2.1251, grad_fn=<DivBackward0>)\ntensor(1.8956, grad_fn=<DivBackward0>)\ntensor(1.8446, grad_fn=<DivBackward0>)\ntensor(2.0277, grad_fn=<DivBackward0>)\ntensor(2.1765, grad_fn=<DivBackward0>)\n" ] ], [ [ "# Loss 시각화", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.figure()\nplt.plot(loss_list)", "_____no_output_____" ] ], [ [ "# 새로 배운 사실\n\n1. unicodedata.normalize('NFD' or 'NFC', word) 역할\n - NFD(Normalization From Decomposition) : 소리 마디를 분해\n - NFC(Normalization From Composition) : 소리 마디를 결합\n - 즉 일단 A말고 위에 A'처럼 소리마디가 포함 된 언어의 경우 두 부분을 분해하거나 결합하는 인코딩", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe3ee7f81ec1e44673658cdfb0196bf31bbf0a5
12,139
ipynb
Jupyter Notebook
json-utilities.ipynb
feltor-dev/user-guide
27b296a1e262c2bfcd95fb9c405ad01ccdfdfc74
[ "MIT" ]
1
2022-01-13T20:16:48.000Z
2022-01-13T20:16:48.000Z
json-utilities.ipynb
feltor-dev/user-guide
27b296a1e262c2bfcd95fb9c405ad01ccdfdfc74
[ "MIT" ]
null
null
null
json-utilities.ipynb
feltor-dev/user-guide
27b296a1e262c2bfcd95fb9c405ad01ccdfdfc74
[ "MIT" ]
null
null
null
41.858621
405
0.58761
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cbe3f2807ddf605d0717d49d4aae1891cf9934b9
625,796
ipynb
Jupyter Notebook
03_unsupervised_learning/04_w3p_sklearn.data_visualization.ipynb
pkuderov/mlda-course
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
[ "MIT" ]
2
2019-02-28T02:25:34.000Z
2021-02-15T19:22:22.000Z
03_unsupervised_learning/04_w3p_sklearn.data_visualization.ipynb
pkuderov/mlda-course
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
[ "MIT" ]
null
null
null
03_unsupervised_learning/04_w3p_sklearn.data_visualization.ipynb
pkuderov/mlda-course
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
[ "MIT" ]
null
null
null
635.325888
170,072
0.944694
[ [ [ "# Sklearn", "_____no_output_____" ], [ "# Визуализация данных", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport scipy.stats as sts\nimport seaborn as sns\nfrom contextlib import contextmanager\n\nsns.set()\nsns.set_style(\"whitegrid\")\n\ncolor_palette = sns.color_palette('deep') + sns.color_palette('husl', 6) + sns.color_palette('bright') + sns.color_palette('pastel')\n\n%matplotlib inline\nsns.palplot(color_palette)\n\ndef ndprint(a, precision=3):\n with np.printoptions(precision=precision, suppress=True):\n print(a)", "_____no_output_____" ], [ "from sklearn import datasets, metrics, model_selection as mdsel", "_____no_output_____" ] ], [ [ "### Загрузка выборки", "_____no_output_____" ] ], [ [ "digits = datasets.load_digits()", "_____no_output_____" ], [ "print(digits.DESCR)", "_____no_output_____" ], [ "print('target:', digits.target[0])\nprint('features: \\n', digits.data[0])\nprint('number of features:', len(digits.data[0]))", "target: 0\nfeatures: \n [ 0. 0. 5. 13. 9. 1. 0. 0. 0. 0. 13. 15. 10. 15. 5. 0. 0. 3.\n 15. 2. 0. 11. 8. 0. 0. 4. 12. 0. 0. 8. 8. 0. 0. 5. 8. 0.\n 0. 9. 8. 0. 0. 4. 11. 0. 1. 12. 7. 0. 0. 2. 14. 5. 10. 12.\n 0. 0. 0. 0. 6. 13. 10. 0. 0. 0.]\nnumber of features: 64\n" ] ], [ [ "## Визуализация объектов выборки", "_____no_output_____" ] ], [ [ "#не будет работать: Invalid dimensions for image data\nplt.imshow(digits.data[0])", "_____no_output_____" ], [ "digits.data[0].shape", "_____no_output_____" ], [ "digits.data[0].reshape(8,8)", "_____no_output_____" ], [ "digits.data[0].reshape(8,8).shape", "_____no_output_____" ], [ "plt.imshow(digits.data[0].reshape(8,8))", "_____no_output_____" ], [ "digits.keys()", "_____no_output_____" ], [ "digits.images[0]", "_____no_output_____" ], [ "plt.imshow(digits.images[0])", "_____no_output_____" ], [ "plt.figure(figsize=(8, 8))\n\nplt.subplot(2, 2, 1)\nplt.imshow(digits.images[0])\n\nplt.subplot(2, 2, 2)\nplt.imshow(digits.images[0], cmap='hot')\n\nplt.subplot(2, 2, 3)\nplt.imshow(digits.images[0], cmap='gray')\n\nplt.subplot(2, 2, 4)\nplt.imshow(digits.images[0], cmap='gray', interpolation='sinc')", "_____no_output_____" ], [ "plt.figure(figsize=(20, 8))\n\nfor plot_number, plot in enumerate(digits.images[:10]):\n plt.subplot(2, 5, plot_number + 1)\n plt.imshow(plot, cmap = 'gray')\n plt.title('digit: ' + str(digits.target[plot_number]))", "_____no_output_____" ] ], [ [ "## Уменьшение размерности", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import classification_report\n\nfrom collections import Counter", "_____no_output_____" ], [ "data = digits.data[:1000]\nlabels = digits.target[:1000]", "_____no_output_____" ], [ "print(Counter(labels))", "Counter({3: 104, 1: 102, 6: 101, 2: 100, 5: 100, 0: 99, 7: 99, 9: 99, 4: 98, 8: 98})\n" ], [ "plt.figure(figsize = (10, 6))\nplt.bar(Counter(labels).keys(), Counter(labels).values())", "_____no_output_____" ], [ "classifier = KNeighborsClassifier()", "_____no_output_____" ], [ "classifier.fit(data, labels)", "_____no_output_____" ], [ "print(classification_report(classifier.predict(data), labels))", " precision recall f1-score support\n\n 0 1.00 1.00 1.00 99\n 1 1.00 0.97 0.99 105\n 2 1.00 1.00 1.00 100\n 3 1.00 0.98 0.99 106\n 4 1.00 1.00 1.00 98\n 5 0.99 1.00 0.99 99\n 6 1.00 1.00 1.00 101\n 7 0.99 0.99 0.99 99\n 8 0.97 0.99 0.98 96\n 9 0.96 0.98 0.97 97\n\n micro avg 0.99 0.99 0.99 1000\n macro avg 0.99 0.99 0.99 1000\nweighted avg 0.99 0.99 0.99 1000\n\n" ] ], [ [ "### Random projection", "_____no_output_____" ] ], [ [ "from sklearn import random_projection", "_____no_output_____" ], [ "projection = random_projection.SparseRandomProjection(n_components = 2, random_state = 0)\ndata_2d_rp = projection.fit_transform(data)", "_____no_output_____" ], [ "plt.figure(figsize=(10, 6))\nplt.scatter(data_2d_rp[:, 0], data_2d_rp[:, 1], c = labels)", "_____no_output_____" ], [ "classifier.fit(data_2d_rp, labels)\nprint(classification_report(classifier.predict(data_2d_rp), labels))", " precision recall f1-score support\n\n 0 0.74 0.47 0.58 154\n 1 0.75 0.58 0.65 131\n 2 0.67 0.59 0.63 113\n 3 0.71 0.51 0.60 144\n 4 0.38 0.56 0.45 66\n 5 0.42 0.53 0.47 79\n 6 0.52 0.57 0.55 93\n 7 0.35 0.51 0.42 69\n 8 0.37 0.58 0.45 62\n 9 0.62 0.69 0.65 89\n\n micro avg 0.55 0.55 0.55 1000\n macro avg 0.55 0.56 0.54 1000\nweighted avg 0.60 0.55 0.56 1000\n\n" ] ], [ [ "### PCA", "_____no_output_____" ] ], [ [ "from sklearn.decomposition import PCA", "_____no_output_____" ], [ "pca = PCA(n_components = 2, random_state = 0, svd_solver='randomized')\ndata_2d_pca = pca.fit_transform(data)", "_____no_output_____" ], [ "plt.figure(figsize = (10, 6))\nplt.scatter(data_2d_pca[:, 0], data_2d_pca[:, 1], c = labels)", "_____no_output_____" ], [ "classifier.fit(data_2d_pca, labels)\nprint(classification_report(classifier.predict(data_2d_pca), labels))", " precision recall f1-score support\n\n 0 0.83 0.73 0.77 113\n 1 0.56 0.54 0.55 105\n 2 0.59 0.57 0.58 104\n 3 0.77 0.79 0.78 101\n 4 0.95 0.93 0.94 100\n 5 0.56 0.54 0.55 104\n 6 0.92 0.93 0.93 100\n 7 0.76 0.71 0.74 105\n 8 0.62 0.66 0.64 92\n 9 0.52 0.67 0.58 76\n\n micro avg 0.71 0.71 0.71 1000\n macro avg 0.71 0.71 0.71 1000\nweighted avg 0.71 0.71 0.71 1000\n\n" ] ], [ [ "### MDS", "_____no_output_____" ] ], [ [ "from sklearn import manifold", "_____no_output_____" ], [ "mds = manifold.MDS(n_components = 2, n_init = 1, max_iter = 100)\ndata_2d_mds = mds.fit_transform(data)", "_____no_output_____" ], [ "plt.figure(figsize=(10, 6))\nplt.scatter(data_2d_mds[:, 0], data_2d_mds[:, 1], c = labels)", "_____no_output_____" ], [ "classifier.fit(data_2d_mds, labels)\nprint(classification_report(classifier.predict(data_2d_mds), labels))", " precision recall f1-score support\n\n 0 1.00 0.88 0.93 113\n 1 0.65 0.62 0.63 106\n 2 0.86 0.80 0.83 108\n 3 0.85 0.81 0.83 108\n 4 0.80 0.64 0.71 122\n 5 0.49 0.54 0.52 90\n 6 0.60 0.60 0.60 102\n 7 0.48 0.68 0.56 71\n 8 0.67 0.72 0.69 92\n 9 0.59 0.66 0.62 88\n\n micro avg 0.70 0.70 0.70 1000\n macro avg 0.70 0.69 0.69 1000\nweighted avg 0.72 0.70 0.70 1000\n\n" ] ], [ [ "### t- SNE", "_____no_output_____" ] ], [ [ "tsne = manifold.TSNE(n_components = 2, init = 'pca', random_state = 0)\ndata_2d_tsne = tsne.fit_transform(data)", "_____no_output_____" ], [ "plt.figure(figsize = (10, 6))\nplt.scatter(data_2d_tsne[:, 0], data_2d_tsne[:, 1], c = labels)", "_____no_output_____" ], [ "classifier.fit(data_2d_tsne, labels)\nprint(classification_report(classifier.predict(data_2d_tsne), labels))", " precision recall f1-score support\n\n 0 1.00 1.00 1.00 99\n 1 1.00 0.98 0.99 104\n 2 0.99 1.00 0.99 99\n 3 1.00 0.97 0.99 107\n 4 1.00 0.99 0.99 99\n 5 0.98 1.00 0.99 98\n 6 0.99 1.00 1.00 100\n 7 0.99 0.99 0.99 99\n 8 0.96 0.98 0.97 96\n 9 0.98 0.98 0.98 99\n\n micro avg 0.99 0.99 0.99 1000\n macro avg 0.99 0.99 0.99 1000\nweighted avg 0.99 0.99 0.99 1000\n\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbe4023aae8bd9eb16bdc5ec18607067111e9f41
85,997
ipynb
Jupyter Notebook
course1/.ipynb_checkpoints/Mnist1-checkpoint.ipynb
luigisaetta/advanced_tensorflow
8dad4e31c9a1bb544f4c5f17d5bd3a322c948f49
[ "MIT" ]
null
null
null
course1/.ipynb_checkpoints/Mnist1-checkpoint.ipynb
luigisaetta/advanced_tensorflow
8dad4e31c9a1bb544f4c5f17d5bd3a322c948f49
[ "MIT" ]
null
null
null
course1/.ipynb_checkpoints/Mnist1-checkpoint.ipynb
luigisaetta/advanced_tensorflow
8dad4e31c9a1bb544f4c5f17d5bd3a322c948f49
[ "MIT" ]
1
2021-04-12T13:06:26.000Z
2021-04-12T13:06:26.000Z
158.373849
22,768
0.856728
[ [ [ "## A first example of NN for Images, using Fashion Mnist", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# check TensorFlow version\nprint(tf.__version__)", "2.4.1\n" ], [ "data = tf.keras.datasets.fashion_mnist", "_____no_output_____" ], [ "(train_images, train_labels), (test_images, test_labels) = data.load_data()", "_____no_output_____" ], [ "print('Number of training images:', train_images.shape[0])\nprint('Number of test images:', test_images.shape[0])", "Number of training images: 60000\nNumber of test images: 10000\n" ], [ "# how many distinct classes\nnp.unique(train_labels)", "_____no_output_____" ], [ "# ok 10 distinct classes labeled as 0..9", "_____no_output_____" ], [ "# images are greyscale images\ntrain_images.shape", "_____no_output_____" ] ], [ [ "# first of all, normalize images\ntrain_images /= 255.\ntest_images /= 255.", "_____no_output_____" ] ], [ [ "# let's sess one image\nplt.imshow(train_images[0], cmap = 'Greys');", "_____no_output_____" ], [ "# let's build a first classification model\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28,28)),\n tf.keras.layers.Dense(128, activation = 'relu'),\n \n # adding these two intermediate layers I go from 0.85 to 0.88 validation accuracy\n tf.keras.layers.Dense(64, activation = 'relu'),\n tf.keras.layers.Dense(32, activation = 'relu'),\n \n tf.keras.layers.Dense(10, activation = 'softmax')\n])", "_____no_output_____" ], [ "# let's see how many parameters, etc\nmodel.summary()", "Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nflatten_3 (Flatten) (None, 784) 0 \n_________________________________________________________________\ndense_8 (Dense) (None, 128) 100480 \n_________________________________________________________________\ndense_9 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndense_10 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_11 (Dense) (None, 10) 330 \n=================================================================\nTotal params: 111,146\nTrainable params: 111,146\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy',\n metrics = ['accuracy'])", "_____no_output_____" ], [ "EPOCHS = 60\nBATCH_SIZE = 256\n\nhistory = model.fit(train_images, train_labels, epochs = EPOCHS, batch_size = BATCH_SIZE, validation_split = 0.1)", "Epoch 1/60\n211/211 [==============================] - 1s 3ms/step - loss: 17.6189 - accuracy: 0.5264 - val_loss: 1.0053 - val_accuracy: 0.7243\nEpoch 2/60\n211/211 [==============================] - 1s 4ms/step - loss: 0.9128 - accuracy: 0.7398 - val_loss: 0.7833 - val_accuracy: 0.7730\nEpoch 3/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.7024 - accuracy: 0.7827 - val_loss: 0.6535 - val_accuracy: 0.7973\nEpoch 4/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.5995 - accuracy: 0.8093 - val_loss: 0.5754 - val_accuracy: 0.8175\nEpoch 5/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.5289 - accuracy: 0.8265 - val_loss: 0.5446 - val_accuracy: 0.8233\nEpoch 6/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.4757 - accuracy: 0.8418 - val_loss: 0.5060 - val_accuracy: 0.8252\nEpoch 7/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.4455 - accuracy: 0.8488 - val_loss: 0.4966 - val_accuracy: 0.8373\nEpoch 8/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.4112 - accuracy: 0.8562 - val_loss: 0.4690 - val_accuracy: 0.8420\nEpoch 9/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3889 - accuracy: 0.8610 - val_loss: 0.4766 - val_accuracy: 0.8322\nEpoch 10/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3824 - accuracy: 0.8660 - val_loss: 0.4561 - val_accuracy: 0.8378\nEpoch 11/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3690 - accuracy: 0.8664 - val_loss: 0.4313 - val_accuracy: 0.8502\nEpoch 12/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3500 - accuracy: 0.8744 - val_loss: 0.4447 - val_accuracy: 0.8493\nEpoch 13/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3459 - accuracy: 0.8745 - val_loss: 0.4170 - val_accuracy: 0.8568\nEpoch 14/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3307 - accuracy: 0.8783 - val_loss: 0.4322 - val_accuracy: 0.8492\nEpoch 15/60\n211/211 [==============================] - 1s 5ms/step - loss: 0.3207 - accuracy: 0.8818 - val_loss: 0.4787 - val_accuracy: 0.8428\nEpoch 16/60\n211/211 [==============================] - 1s 4ms/step - loss: 0.3228 - accuracy: 0.8846 - val_loss: 0.4195 - val_accuracy: 0.8593\nEpoch 17/60\n211/211 [==============================] - 1s 4ms/step - loss: 0.3163 - accuracy: 0.8847 - val_loss: 0.4135 - val_accuracy: 0.8655\nEpoch 18/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3130 - accuracy: 0.8855 - val_loss: 0.4088 - val_accuracy: 0.8612\nEpoch 19/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.3015 - accuracy: 0.8889 - val_loss: 0.4375 - val_accuracy: 0.8578\nEpoch 20/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2960 - accuracy: 0.8930 - val_loss: 0.4190 - val_accuracy: 0.8637\nEpoch 21/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2841 - accuracy: 0.8959 - val_loss: 0.4199 - val_accuracy: 0.8652\nEpoch 22/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2846 - accuracy: 0.8929 - val_loss: 0.4066 - val_accuracy: 0.8693\nEpoch 23/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2824 - accuracy: 0.8939 - val_loss: 0.4049 - val_accuracy: 0.8670\nEpoch 24/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2779 - accuracy: 0.8966 - val_loss: 0.4101 - val_accuracy: 0.8685\nEpoch 25/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2776 - accuracy: 0.8973 - val_loss: 0.4178 - val_accuracy: 0.8670\nEpoch 26/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2664 - accuracy: 0.9016 - val_loss: 0.3981 - val_accuracy: 0.8697\nEpoch 27/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2697 - accuracy: 0.9003 - val_loss: 0.4060 - val_accuracy: 0.8680\nEpoch 28/60\n211/211 [==============================] - 1s 5ms/step - loss: 0.2674 - accuracy: 0.9025 - val_loss: 0.4175 - val_accuracy: 0.8630\nEpoch 29/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2606 - accuracy: 0.9030 - val_loss: 0.4084 - val_accuracy: 0.8730\nEpoch 30/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2588 - accuracy: 0.9048 - val_loss: 0.4330 - val_accuracy: 0.8685\nEpoch 31/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2582 - accuracy: 0.9063 - val_loss: 0.4098 - val_accuracy: 0.8748\nEpoch 32/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2598 - accuracy: 0.9023 - val_loss: 0.4178 - val_accuracy: 0.8733\nEpoch 33/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2440 - accuracy: 0.9106 - val_loss: 0.3943 - val_accuracy: 0.8742\nEpoch 34/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2442 - accuracy: 0.9097 - val_loss: 0.4142 - val_accuracy: 0.8730\nEpoch 35/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2393 - accuracy: 0.9117 - val_loss: 0.4079 - val_accuracy: 0.8792\nEpoch 36/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2482 - accuracy: 0.9081 - val_loss: 0.4215 - val_accuracy: 0.8700\nEpoch 37/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2394 - accuracy: 0.9127 - val_loss: 0.4046 - val_accuracy: 0.8728\nEpoch 38/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2252 - accuracy: 0.9152 - val_loss: 0.4058 - val_accuracy: 0.8723\nEpoch 39/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2301 - accuracy: 0.9144 - val_loss: 0.4285 - val_accuracy: 0.8743\nEpoch 40/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2314 - accuracy: 0.9133 - val_loss: 0.4050 - val_accuracy: 0.8700\nEpoch 41/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2243 - accuracy: 0.9163 - val_loss: 0.4217 - val_accuracy: 0.8765\nEpoch 42/60\n211/211 [==============================] - 1s 5ms/step - loss: 0.2284 - accuracy: 0.9160 - val_loss: 0.4171 - val_accuracy: 0.8765\nEpoch 43/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2118 - accuracy: 0.9213 - val_loss: 0.4107 - val_accuracy: 0.8770\nEpoch 44/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2246 - accuracy: 0.9179 - val_loss: 0.4055 - val_accuracy: 0.8738\nEpoch 45/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2152 - accuracy: 0.9204 - val_loss: 0.4406 - val_accuracy: 0.8685\nEpoch 46/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2126 - accuracy: 0.9211 - val_loss: 0.4046 - val_accuracy: 0.8798\nEpoch 47/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2148 - accuracy: 0.9186 - val_loss: 0.4356 - val_accuracy: 0.8778\nEpoch 48/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2203 - accuracy: 0.9183 - val_loss: 0.4192 - val_accuracy: 0.8805\nEpoch 49/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2038 - accuracy: 0.9256 - val_loss: 0.4121 - val_accuracy: 0.8743\nEpoch 50/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2116 - accuracy: 0.9214 - val_loss: 0.4500 - val_accuracy: 0.8732\nEpoch 51/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1981 - accuracy: 0.9272 - val_loss: 0.4604 - val_accuracy: 0.8732\nEpoch 52/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2089 - accuracy: 0.9221 - val_loss: 0.4495 - val_accuracy: 0.8730\nEpoch 53/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.2095 - accuracy: 0.9219 - val_loss: 0.4148 - val_accuracy: 0.8822\nEpoch 54/60\n211/211 [==============================] - 1s 6ms/step - loss: 0.1911 - accuracy: 0.9272 - val_loss: 0.4437 - val_accuracy: 0.8713\nEpoch 55/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1973 - accuracy: 0.9269 - val_loss: 0.4440 - val_accuracy: 0.8802\nEpoch 56/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1855 - accuracy: 0.9313 - val_loss: 0.4600 - val_accuracy: 0.8740\nEpoch 57/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1931 - accuracy: 0.9291 - val_loss: 0.4364 - val_accuracy: 0.8820\nEpoch 58/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1822 - accuracy: 0.9325 - val_loss: 0.4830 - val_accuracy: 0.8718\nEpoch 59/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1931 - accuracy: 0.9284 - val_loss: 0.4304 - val_accuracy: 0.8753\nEpoch 60/60\n211/211 [==============================] - 1s 3ms/step - loss: 0.1825 - accuracy: 0.9321 - val_loss: 0.4578 - val_accuracy: 0.8742\n" ], [ "loss = history.history['loss']\nval_loss = history.history['val_loss']\naccuracy = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']", "_____no_output_____" ], [ "plt.xlabel('epoch')\nplt.ylabel('loss')\nplt.plot(loss, label = 'loss')\nplt.plot(val_loss, label = 'validation loss')\nplt.legend(loc = 'upper right')\nplt.grid();", "_____no_output_____" ], [ "# wants to see if it starts overfitting\nSTART = 20\n\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.plot(loss[START:], label = 'loss')\nplt.plot(val_loss[START:], label = 'validation loss')\nplt.legend(loc = 'upper right')\nplt.grid();", "_____no_output_____" ], [ "# ok it has slightly started overfitting.. as we can see from epochs 15 validation loss becomes higher and training loss is still decreasing", "_____no_output_____" ], [ "plt.xlabel('epoch')\nplt.ylabel('accuracy')\nplt.plot(accuracy, label = 'accuracy')\nplt.plot(val_accuracy, label = 'validation accuracy')\nplt.legend(loc = 'lower right')\nplt.grid();", "_____no_output_____" ], [ "loss, acc = model.evaluate(test_images, test_labels)\n\nprint('')\nprint('Test accuracy is:', acc)", "313/313 [==============================] - 0s 1ms/step - loss: 0.4665 - accuracy: 0.8738\n\nTest accuracy is: 0.8737999796867371\n" ] ] ]
[ "markdown", "code", "raw", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe406fd818c0a5abffdc98f048007fdc3d22077
8,005
ipynb
Jupyter Notebook
chan/01_Centre_Expand_Handler_Alpha_15.ipynb
fs714/concurrency-example
fbff041804b9c46fb7f21ebbae22acff745c7b0c
[ "Apache-2.0" ]
null
null
null
chan/01_Centre_Expand_Handler_Alpha_15.ipynb
fs714/concurrency-example
fbff041804b9c46fb7f21ebbae22acff745c7b0c
[ "Apache-2.0" ]
null
null
null
chan/01_Centre_Expand_Handler_Alpha_15.ipynb
fs714/concurrency-example
fbff041804b9c46fb7f21ebbae22acff745c7b0c
[ "Apache-2.0" ]
1
2020-03-10T15:47:05.000Z
2020-03-10T15:47:05.000Z
33.078512
101
0.452467
[ [ [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom IPython.core.debugger import Pdb; pdb = Pdb()\n\n\ndef get_down_centre_last_low(p_list):\n zn_num = len(p_list) - 1\n available_num = min(9, (zn_num - 6))\n \n index = len(p_list) - 4\n for i in range(0, available_num // 2):\n if p_list[index - 2] < p_list[index]:\n index = index -2\n else:\n return index\n return index + 2\n\ndef get_down_centre_first_high(p_list):\n s = max(enumerate(p_list[3:]), key=lambda x: x[1])[0]\n return s + 3\n\ndef down_centre_expand_spliter(p_list):\n lr0 = get_down_centre_last_low(p_list)\n hl0 = get_down_centre_first_high(p_list[: lr0 - 2])\n \n hr0 = lr0 -1\n while hr0 < len(p_list) - 8:\n if p_list[hr0] > p_list[hl0] and (len(p_list) - hr0) > 5:\n hl0 = hr0\n lr0 = (len(p_list) - 1 + hr0) // 2\n if lr0 % 2 == 1:\n lr0 = lr0 -1\n # lr0 = hr0 + 3\n break\n hr0 = hr0 + 2\n return [0, hl0, lr0, len(p_list) - 1], [p_list[0], p_list[hl0], p_list[lr0], p_list[-1]]\n\n\n# y = [0, 100, 60, 130, 70, 120, 40, 90, 50, 140, 85, 105]\n# y = [0, 100, 60, 110, 70, 72, 61, 143, 77, 91, 82, 100, 83, 124, 89, 99]\n# y = [0, 100, 60, 110, 70, 115, 75, 120, 80, 125, 85, 130, 90, 135]\n# y = [0, 100, 60, 110, 70, 78, 77, 121, 60, 93, 82, 141, 78, 134]\n# y = [0, 110, 70, 100, 60, 100, 78, 90, 53, 109, 56, 141, 99, 106, 89, 99, 93, 141]\n\n# x = list(range(0, len(y)))\n# gg = [min(y[1], y[3])] * len(y)\n# dd = [max(y[2], y[4])] * len(y)\n\n# plt.figure(figsize=(len(y),4))\n# plt.grid()\n# plt.plot(x, y)\n# plt.plot(x, gg, '--')\n# plt.plot(x, dd, '--')\n# sx, sy = down_centre_expand_spliter(y)\n# plt.plot(sx, sy)\n# plt.show()\n", "_____no_output_____" ], [ "# Centre Expand Prototype\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\n\n\ny_base = [0, 100, 60, 130, 70, 120, 40, 90, 50, 140, 85, 105, 55, 80]\n\nfor i in range(10, len(y_base)):\n y = y_base[:(i + 1)]\n x = list(range(0, len(y)))\n gg = [min(y[1], y[3])] * len(y)\n dd = [max(y[2], y[4])] * len(y)\n\n plt.figure(figsize=(i,4))\n plt.grid()\n plt.plot(x, y)\n plt.plot(x, gg, '--')\n plt.plot(x, dd, '--')\n if i % 2 == 1:\n sx, sy = down_centre_expand_spliter(y)\n plt.plot(sx, sy)\n plt.show()\n ", "_____no_output_____" ], [ "# Random Centre Generator\n%matplotlib inline\n\nimport random\nimport matplotlib.pyplot as plt\n\ny_max = 150\ny_min = 50\nnum_max = 18\n\ndef generate_next(y_list, direction):\n if direction == 1:\n y_list.append(random.randint(max(y_list[2], y_list[4], y_list[-1]) + 1, y_max))\n elif direction == -1:\n y_list.append(random.randint(y_min, min(y_list[1], y_list[3], y_list[-1]) - 1))\n\n# y_base = [0, 100, 60, 110, 70]\ny_base = [0, 110, 70, 100, 60]\n# y_base = [0, 100, 60, 90, 70]\n# y_base = [0, 90, 70, 100, 60]\n\ndirection = 1\nfor i in range(5, num_max):\n generate_next(y_base, direction)\n direction = 0 - direction\n\nprint(y_base)\nfor i in range(11, len(y_base), 2):\n y = y_base[:(i + 1)]\n x = list(range(0, len(y)))\n gg = [min(y[1], y[3])] * len(y)\n dd = [max(y[2], y[4])] * len(y)\n\n plt.figure(figsize=(i,4))\n plt.title(y)\n plt.grid()\n plt.plot(x, y)\n plt.plot(x, gg, '--')\n plt.plot(x, dd, '--')\n sx, sy = down_centre_expand_spliter(y)\n plt.plot(sx, sy)\n plt.show()\n ", "_____no_output_____" ], [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt\n\n# Group 1\ny_base = [0, 100, 60, 110, 70, 99, 66, 121, 91, 141, 57, 111, 69, 111]\n# y_base = [0, 100, 60, 110, 70, 105, 58, 102, 74, 137, 87, 142, 55, 128]\n# y_base = [0, 100, 60, 110, 70, 115, 75, 120, 80, 125, 85, 130, 90, 135]\n# y_base = [0, 100, 60, 110, 70, 120, 80, 130, 90, 140, 50, 75]\n# y_base = [0, 100, 60, 110, 70, 114, 52, 75, 54, 77, 65, 100, 66, 87, 70, 116]\n# y_base = [0, 100, 60, 110, 70, 72, 61, 143, 77, 91, 82, 100, 83, 124, 89, 99, 89, 105]\n\n# Group 2\n# y_base = [0, 110, 70, 100, 60, 142, 51, 93, 78, 109, 60, 116, 50, 106]\n# y_base = [0, 110, 70, 100, 60, 88, 70, 128, 82, 125, 72, 80, 63, 119]\n# y_base = [0, 110, 70, 100, 60, 74, 66, 86, 57, 143, 50, 95, 70, 91]\n# y_base = [0, 110, 70, 100, 60, 77, 73, 122, 96, 116, 82, 124, 69, 129]\n# y_base = [0, 110, 70, 100, 60, 147, 53, 120, 77, 103, 56, 76, 74, 92]\n# y_base = [0, 110, 70, 100, 60, 95, 55, 90, 50, 85, 45, 80, 40, 75]\n# y_base = [0, 110, 70, 100, 60, 100, 78, 90, 53, 109, 56, 141, 99, 106, 89, 99, 93, 141]\n\n# Group 3\n# y_base = [0, 100, 60, 90, 70, 107, 55, 123, 79, 112, 64, 85, 74, 110]\n# y_base = [0, 100, 60, 90, 70, 77, 55, 107, 76, 141, 87, 91, 60, 83]\n# y_base = [0, 100, 60, 90, 70, 114, 67, 93, 58, 134, 53, 138, 64, 107]\n# y_base = [0, 100, 60, 90, 70, 77, 66, 84, 79, 108, 87, 107, 72, 89]\n# y_base = [0, 100, 60, 90, 70, 88, 72, 86, 74, 84, 76, 82, 74, 80]\n\n# Group 4\n# y_base = [0, 90, 70, 100, 60, 131, 57, 144, 85, 109, 82, 124, 87, 101]\n# y_base = [0, 90, 70, 100, 60, 150, 56, 112, 63, 95, 84, 118, 58, 110]\n# y_base = [0, 90, 70, 100, 60, 145, 64, 112, 69, 86, 71, 119, 54, 95]\n# y_base = [0, 90, 70, 100, 60, 105, 55, 110, 50, 115, 45, 120, 40, 125]\n\nfor i in range(11, len(y_base), 2):\n y = y_base[:(i + 1)]\n x = list(range(0, len(y)))\n gg = [min(y[1], y[3])] * len(y)\n dd = [max(y[2], y[4])] * len(y)\n\n plt.figure(figsize=(i,4))\n plt.title(y)\n plt.grid()\n plt.plot(x, y)\n plt.plot(x, gg, '--')\n plt.plot(x, dd, '--')\n sx, sy = down_centre_expand_spliter(y)\n plt.plot(sx, sy)\n plt.show()\n ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cbe40d99b629960e539f0fde914cf185b329c45f
425,259
ipynb
Jupyter Notebook
notebooks/exploratory/05_2019_CO_dataset_complete.ipynb
esowc/MaLePoM
5e4e5babdd1cb3976a8dfd38ae931b62ccc8721e
[ "MIT" ]
4
2021-06-29T17:25:33.000Z
2021-11-02T13:52:08.000Z
notebooks/exploratory/05_2019_CO_dataset_complete.ipynb
esowc/MaLePoM
5e4e5babdd1cb3976a8dfd38ae931b62ccc8721e
[ "MIT" ]
null
null
null
notebooks/exploratory/05_2019_CO_dataset_complete.ipynb
esowc/MaLePoM
5e4e5babdd1cb3976a8dfd38ae931b62ccc8721e
[ "MIT" ]
4
2021-07-03T18:28:12.000Z
2021-11-03T08:09:07.000Z
425,259
425,259
0.668992
[ [ [ "#Create the environment", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "%cd /content/drive/My Drive/ESoWC", "/content/drive/My Drive/ESoWC\n" ], [ "import pandas as pd\nimport xarray as xr\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\nimport seaborn as sns\n\n#Our class\nfrom create_dataset.make_dataset import CustomDataset", "_____no_output_____" ], [ "fn_land = 'Data/land_cover_data.nc'\nfn_weather = 'Data/05_2019_weather_and_CO_for_model.nc'\nfn_conc = 'Data/totalcolConcentretations_featured.nc'\nfn_traffic = 'Data/emissions_traffic_hourly_merged.nc'", "_____no_output_____" ] ], [ [ "#Load datasets", "_____no_output_____" ], [ "##Land", "_____no_output_____" ] ], [ [ "land_instance = CustomDataset(fn_land)\nland_instance.get_dataset()", "Opening dataset at : Data/land_cover_data.nc\nDone!\n" ], [ "land_instance.resample(\"1H\")\nland_fixed = land_instance.get_dataset()\nland_fixed = land_fixed.drop_vars('NO emissions') #They are already in the weather dataset\nland_fixed = land_fixed.transpose('latitude','longitude','time') \nland_fixed", "_____no_output_____" ] ], [ [ "##Weather", "_____no_output_____" ] ], [ [ "weather = xr.open_dataset(fn_weather)\nweather", "_____no_output_____" ], [ "#This variable is too much correlated with the tcw\nweather_fixed = weather.drop_vars('tcwv')\n\nweather_fixed = weather_fixed.transpose('latitude','longitude','time') \nweather_fixed", "_____no_output_____" ] ], [ [ "##Conc", "_____no_output_____" ] ], [ [ "conc_fidex = xr.open_dataset(fn_conc)\nconc_fidex", "_____no_output_____" ] ], [ [ "##Traffic", "_____no_output_____" ] ], [ [ "traffic_instance = CustomDataset(fn_traffic)\ntraffic_ds= traffic_instance.get_dataset()\ntraffic_ds", "Opening dataset at : Data/emissions_traffic_hourly_merged.nc\nDone!\n" ], [ "traffic_ds=traffic_ds.drop_vars('emissions')\nlat_bins = np.arange(43,51.25,0.25)\nlon_bins = np.arange(4,12.25,0.25)\ntraffic_ds = traffic_ds.sortby(['latitude','longitude','hour']) \ntraffic_ds = traffic_ds.interp(latitude=lat_bins, longitude=lon_bins, method=\"linear\")\ndays = np.arange(1,32,1)\ntraffic_ds=traffic_ds.expand_dims({'Days':days})\ntraffic_ds", "_____no_output_____" ], [ "trafic_df = traffic_ds.to_dataframe()\ntrafic_df = trafic_df.reset_index()\ntrafic_df['time'] = (pd.to_datetime(trafic_df['Days']-1,errors='ignore',\n unit='d',origin='2019-05') +\n pd.to_timedelta(trafic_df['hour'], unit='h'))\ntrafic_df=trafic_df.drop(columns=['Days', 'hour'])\ntrafic_df = trafic_df.set_index(['latitude','longitude','time'])\ntrafic_df.head()", "_____no_output_____" ], [ "traffic_fixed = trafic_df.to_xarray()\ntraffic_fixed = traffic_fixed.transpose('latitude','longitude','time') \ntraffic_fixed", "_____no_output_____" ], [ "traffic_fixed.isel(time=[15]).traffic.plot()", "_____no_output_____" ] ], [ [ "#Merge", "_____no_output_____" ] ], [ [ "tot_dataset = weather_fixed.merge(land_fixed)\ntot_dataset = tot_dataset.merge(conc_fidex)\ntot_dataset = tot_dataset.merge(traffic_fixed)\n\ntot_dataset", "_____no_output_____" ] ], [ [ "#Check", "_____no_output_____" ] ], [ [ "weather_fixed.to_dataframe().isnull().sum()", "_____no_output_____" ], [ "land_fixed.to_dataframe().isnull().sum()", "_____no_output_____" ], [ "conc_fidex.to_dataframe().isnull().sum()", "_____no_output_____" ], [ "traffic_fixed.to_dataframe().isnull().sum()", "_____no_output_____" ], [ "tot_dataset.to_dataframe().isnull().sum()", "_____no_output_____" ], [ "tot_dataset.isel(time=[12]).EMISSIONS_2019.plot()", "_____no_output_____" ], [ "tot_dataset.isel(time=[12]).u10.plot()", "_____no_output_____" ], [ "tot_dataset.isel(time=[15]).height.plot()", "_____no_output_____" ], [ "tot_dataset.isel(time=[12]).NO_tc.plot()", "_____no_output_____" ], [ "tot_dataset.isel(time=[15]).traffic.plot()", "_____no_output_____" ] ], [ [ "#Save the dataset", "_____no_output_____" ] ], [ [ "tot_dataset.to_netcdf('Data/05_2019_dataset_complete_for_model_CO.nc', 'w', 'NETCDF4')", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe419397553eec6965a45f31602d78ce64c43e8
21,003
ipynb
Jupyter Notebook
sagemaker-featurestore/feature_store_client_side_encryption.ipynb
Amirosimani/amazon-sagemaker-examples
bc35e7a9da9e2258e77f98098254c2a8e308041a
[ "Apache-2.0" ]
2,610
2020-10-01T14:14:53.000Z
2022-03-31T18:02:31.000Z
sagemaker-featurestore/feature_store_client_side_encryption.ipynb
Amirosimani/amazon-sagemaker-examples
bc35e7a9da9e2258e77f98098254c2a8e308041a
[ "Apache-2.0" ]
1,959
2020-09-30T20:22:42.000Z
2022-03-31T23:58:37.000Z
sagemaker-featurestore/feature_store_client_side_encryption.ipynb
Amirosimani/amazon-sagemaker-examples
bc35e7a9da9e2258e77f98098254c2a8e308041a
[ "Apache-2.0" ]
2,052
2020-09-30T22:11:46.000Z
2022-03-31T23:02:51.000Z
30.796188
708
0.600438
[ [ [ "## Amazon SageMaker Feature Store: Client-side Encryption using AWS Encryption SDK", "_____no_output_____" ], [ "This notebook demonstrates how client-side encryption with SageMaker Feature Store is done using the [AWS Encryption SDK library](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html) to encrypt your data prior to ingesting it into your Online or Offline Feature Store. We first demonstrate how to encrypt your data using the AWS Encryption SDK library, and then show how to use [Amazon Athena](https://aws.amazon.com/athena/) to query for a subset of encrypted columns of features for model training.\n\nCurrently, Feature Store supports encryption at rest and encryption in transit. With this notebook, we showcase an additional layer of security where your data is encrypted and then stored in your Feature Store. This notebook also covers the scenario where you want to query a subset of encrypted data using Amazon Athena for model training. This becomes particularly useful when you want to store encrypted data sets in a single Feature Store, and want to perform model training using only a subset of encrypted columns, forcing privacy over the remaining columns. \n\nIf you are interested in server side encryption with Feature Store, see [Feature Store: Encrypt Data in your Online or Offline Feature Store using KMS key](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-featurestore/feature_store_kms_key_encryption.html). \n\nFor more information on the AWS Encryption library, see [AWS Encryption SDK library](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html). \n\nFor detailed information about Feature Store, see the [Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store.html).\n\n### Overview\n1. Set up\n2. Load in and encrypt your data using AWS Encryption library (`aws-encryption-sdk`)\n3. Create Feature Group and ingest your encrypted data into it\n4. Query your encrypted data in your feature store using Amazon Athena\n5. Decrypt the data you queried\n\n### Prerequisites\nThis notebook uses the Python SDK library for Feature Store, the AWS Encryption SDK library, `aws-encryption-sdk` and the `Python 3 (DataScience)` kernel. To use the`aws-encryption-sdk` library you will need to have an active KMS key that you created. If you do not have a KMS key, then you can create one by following the [KMS Policy Template](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-featurestore/feature_store_kms_key_encryption.html#KMS-Policy-Template) steps, or you can visit the [KMS section in the console](https://console.aws.amazon.com/kms/home) and follow the button prompts for creating a KMS key. This notebook works with SageMaker Studio, Jupyter, and JupyterLab. \n\n### Library Dependencies:\n* `sagemaker>=2.0.0`\n* `numpy`\n* `pandas`\n* `aws-encryption-sdk`\n\n### Data\nThis notebook uses a synthetic data set that has the following features: `customer_id`, `ssn` (social security number), `credit_score`, `age`, and aims to simulate a relaxed data set that has some important features that would be needed during the credit card approval process.", "_____no_output_____" ] ], [ [ "import sagemaker\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "pip install -q 'aws-encryption-sdk'", "_____no_output_____" ] ], [ [ "### Set up", "_____no_output_____" ] ], [ [ "sagemaker_session = sagemaker.Session()\ns3_bucket_name = sagemaker_session.default_bucket()\nprefix = \"sagemaker-featurestore-demo\"\nrole = sagemaker.get_execution_role()\nregion = sagemaker_session.boto_region_name", "_____no_output_____" ] ], [ [ "Instantiate an encryption SDK client and provide your KMS ARN key to the `StrictAwsKmsMasterKeyProvider` object. This will be needed for data encryption and decryption by the AWS Encryption SDK library. You will need to substitute your KMS Key ARN for `kms_key`.", "_____no_output_____" ] ], [ [ "import aws_encryption_sdk\nfrom aws_encryption_sdk.identifiers import CommitmentPolicy\n\nclient = aws_encryption_sdk.EncryptionSDKClient(\n commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT\n)\n\nkms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(\n key_ids=[kms_key] ## Add your KMS key here\n)", "_____no_output_____" ] ], [ [ "Load in your data. ", "_____no_output_____" ] ], [ [ "credit_card_data = pd.read_csv(\"data/credit_card_approval_synthetic.csv\")", "_____no_output_____" ], [ "credit_card_data.head()", "_____no_output_____" ], [ "credit_card_data.dtypes", "_____no_output_____" ] ], [ [ "### Client-Side Encryption Methods\n\nBelow are some methods that use the Amazon Encryption SDK library for data encryption, and decryption. Note that the data type of the encryption is byte which we convert to an integer prior to storing it into Feature Store and do the reverse prior to decrypting. This is because Feature Store doesn't support byte format directly, thus why we convert the byte encryption to an integer. ", "_____no_output_____" ] ], [ [ "def encrypt_data_frame(df, columns):\n \"\"\"\n Input:\n df: A pandas Dataframe\n columns: A list of column names.\n\n Encrypt the provided columns in df. This method assumes that column names provided in columns exist in df,\n and uses the AWS Encryption SDK library.\n \"\"\"\n for col in columns:\n buffer = []\n for entry in np.array(df[col]):\n entry = str(entry)\n encrypted_entry, encryptor_header = client.encrypt(\n source=entry, key_provider=kms_key_provider\n )\n buffer.append(encrypted_entry)\n df[col] = buffer\n\n\ndef decrypt_data_frame(df, columns):\n \"\"\"\n Input:\n df: A pandas Dataframe\n columns: A list of column names.\n\n Decrypt the provided columns in df. This method assumes that column names provided in columns exist in df,\n and uses the AWS Encryption SDK library.\n \"\"\"\n for col in columns:\n buffer = []\n for entry in np.array(df[col]):\n decrypted_entry, decryptor_header = client.decrypt(\n source=entry, key_provider=kms_key_provider\n )\n buffer.append(float(decrypted_entry))\n df[col] = np.array(buffer)\n\n\ndef bytes_to_int(df, columns):\n \"\"\"\n Input:\n df: A pandas Dataframe\n columns: A list of column names.\n\n Convert the provided columns in df of type bytes to integers. This method assumes that column names provided\n in columns exist in df and that the columns passed in are of type bytes.\n \"\"\"\n for col in columns:\n for index, entry in enumerate(np.array(df[col])):\n df[col][index] = int.from_bytes(entry, \"little\")\n\n\ndef int_to_bytes(df, columns):\n \"\"\"\n Input:\n df: A pandas Dataframe\n columns: A list of column names.\n\n Convert the provided columns in df of type integers to bytes. This method assumes that column names provided\n in columns exist in df and that the columns passed in are of type integers.\n \"\"\"\n for col in columns:\n buffer = []\n for index, entry in enumerate(np.array(df[col])):\n current = int(df[col][index])\n current_bit_length = current.bit_length() + 1 # include the sign bit, 1\n current_byte_length = (current_bit_length + 7) // 8\n buffer.append(current.to_bytes(current_byte_length, \"little\"))\n df[col] = pd.Series(buffer)", "_____no_output_____" ], [ "## Encrypt credit card data. Note that we treat `customer_id` as a primary key, and since it's encryption is unique we can encrypt it.\nencrypt_data_frame(credit_card_data, [\"customer_id\", \"age\", \"SSN\", \"credit_score\"])", "_____no_output_____" ], [ "credit_card_data", "_____no_output_____" ], [ "print(credit_card_data.dtypes)", "_____no_output_____" ], [ "## Cast encryption of type bytes to an integer so it can be stored in Feature Store.\nbytes_to_int(credit_card_data, [\"customer_id\", \"age\", \"SSN\", \"credit_score\"])", "_____no_output_____" ], [ "print(credit_card_data.dtypes)", "_____no_output_____" ], [ "credit_card_data", "_____no_output_____" ], [ "def cast_object_to_string(data_frame):\n \"\"\"\n Input:\n data_frame: A pandas Dataframe\n\n Cast all columns of data_frame of type object to type string.\n \"\"\"\n for label in data_frame.columns:\n if data_frame.dtypes[label] == object:\n data_frame[label] = data_frame[label].astype(\"str\").astype(\"string\")\n return data_frame\n\n\ncredit_card_data = cast_object_to_string(credit_card_data)", "_____no_output_____" ], [ "print(credit_card_data.dtypes)", "_____no_output_____" ], [ "credit_card_data", "_____no_output_____" ] ], [ [ "### Create your Feature Group and Ingest your encrypted data into it\n\nBelow we start by appending the `EventTime` feature to your data to timestamp entries, then we load the feature definition, and instantiate the Feature Group object. Then lastly we ingest the data into your feature store. ", "_____no_output_____" ] ], [ [ "from time import gmtime, strftime, sleep\n\ncredit_card_feature_group_name = \"credit-card-feature-group-\" + strftime(\"%d-%H-%M-%S\", gmtime())", "_____no_output_____" ] ], [ [ "Instantiate a FeatureGroup object for `credit_card_data`.", "_____no_output_____" ] ], [ [ "from sagemaker.feature_store.feature_group import FeatureGroup\n\ncredit_card_feature_group = FeatureGroup(\n name=credit_card_feature_group_name, sagemaker_session=sagemaker_session\n)", "_____no_output_____" ], [ "import time\n\ncurrent_time_sec = int(round(time.time()))\n\n## Recall customer_id is encrypted therefore unique, and so it can be used as a record identifier.\nrecord_identifier_feature_name = \"customer_id\"", "_____no_output_____" ] ], [ [ "Append the `EventTime` feature to your data frame. This parameter is required, and time stamps each data point.", "_____no_output_____" ] ], [ [ "credit_card_data[\"EventTime\"] = pd.Series(\n [current_time_sec] * len(credit_card_data), dtype=\"float64\"\n)", "_____no_output_____" ], [ "credit_card_data.head()", "_____no_output_____" ], [ "print(credit_card_data.dtypes)", "_____no_output_____" ], [ "credit_card_feature_group.load_feature_definitions(data_frame=credit_card_data)", "_____no_output_____" ], [ "credit_card_feature_group.create(\n s3_uri=f\"s3://{s3_bucket_name}/{prefix}\",\n record_identifier_name=record_identifier_feature_name,\n event_time_feature_name=\"EventTime\",\n role_arn=role,\n enable_online_store=False,\n)", "_____no_output_____" ], [ "time.sleep(60)", "_____no_output_____" ] ], [ [ "Ingest your data into your feature group. ", "_____no_output_____" ] ], [ [ "credit_card_feature_group.ingest(data_frame=credit_card_data, max_workers=3, wait=True)", "_____no_output_____" ], [ "time.sleep(30)", "_____no_output_____" ] ], [ [ "Continually check your offline store until your data is available in it. ", "_____no_output_____" ] ], [ [ "s3_client = sagemaker_session.boto_session.client(\"s3\", region_name=region)\n\ncredit_card_feature_group_s3_uri = (\n credit_card_feature_group.describe()\n .get(\"OfflineStoreConfig\")\n .get(\"S3StorageConfig\")\n .get(\"ResolvedOutputS3Uri\")\n)\n\ncredit_card_feature_group_s3_prefix = credit_card_feature_group_s3_uri.replace(\n f\"s3://{s3_bucket_name}/\", \"\"\n)\noffline_store_contents = None\nwhile offline_store_contents is None:\n objects_in_bucket = s3_client.list_objects(\n Bucket=s3_bucket_name, Prefix=credit_card_feature_group_s3_prefix\n )\n if \"Contents\" in objects_in_bucket and len(objects_in_bucket[\"Contents\"]) > 1:\n offline_store_contents = objects_in_bucket[\"Contents\"]\n else:\n print(\"Waiting for data in offline store...\\n\")\n time.sleep(60)\n\nprint(\"Data available.\")", "_____no_output_____" ] ], [ [ "### Use Amazon Athena to Query your Encrypted Data in your Feature Store\nUsing Amazon Athena, we query columns `customer_id`, `age`, and `credit_score` from your offline feature store where your encrypted data is. ", "_____no_output_____" ] ], [ [ "credit_card_query = credit_card_feature_group.athena_query()\n\ncredit_card_table = credit_card_query.table_name\n\nquery_credit_card_table = 'SELECT customer_id, age, credit_score FROM \"' + credit_card_table + '\"'\n\nprint(\"Running \" + query_credit_card_table)\n\n# Run the Athena query\ncredit_card_query.run(\n query_string=query_credit_card_table,\n output_location=\"s3://\" + s3_bucket_name + \"/\" + prefix + \"/query_results/\",\n)", "_____no_output_____" ], [ "time.sleep(60)", "_____no_output_____" ], [ "credit_card_dataset = credit_card_query.as_dataframe()", "_____no_output_____" ], [ "print(credit_card_dataset.dtypes)", "_____no_output_____" ], [ "credit_card_dataset", "_____no_output_____" ], [ "int_to_bytes(credit_card_dataset, [\"customer_id\", \"age\", \"credit_score\"])", "_____no_output_____" ], [ "credit_card_dataset", "_____no_output_____" ], [ "decrypt_data_frame(credit_card_dataset, [\"customer_id\", \"age\", \"credit_score\"])", "_____no_output_____" ] ], [ [ "In this notebook, we queried a subset of encrypted features. From here you can now train a model on this new dataset while remaining privacy over other columns e.g., `ssn`.", "_____no_output_____" ] ], [ [ "credit_card_dataset", "_____no_output_____" ] ], [ [ "### Clean Up Resources\nRemove the Feature Group that was created. ", "_____no_output_____" ] ], [ [ "credit_card_feature_group.delete()", "_____no_output_____" ] ], [ [ "### Next Steps\n\nIn this notebook we covered client-side encryption with Feature Store. If you are interested in understanding how server-side encryption is done with Feature Store, see [Feature Store: Encrypt Data in your Online or Offline Feature Store using KMS key](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-featurestore/feature_store_kms_key_encryption.html). \n\nFor more information on the AWS Encryption library, see [AWS Encryption SDK library](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html). \n\nFor detailed information about Feature Store, see the [Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store.html).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe427bfff7804b40142f51fcba6a71c994ccb8d
27,232
ipynb
Jupyter Notebook
Strings/Strings.ipynb
yaozeliang/Python_Useful
3a663ed9f8bd3eb3f7303f6ad4d874f4c7d62585
[ "MIT" ]
1
2020-09-26T15:05:34.000Z
2020-09-26T15:05:34.000Z
Strings/Strings.ipynb
yaozeliang/Python_Useful
3a663ed9f8bd3eb3f7303f6ad4d874f4c7d62585
[ "MIT" ]
null
null
null
Strings/Strings.ipynb
yaozeliang/Python_Useful
3a663ed9f8bd3eb3f7303f6ad4d874f4c7d62585
[ "MIT" ]
null
null
null
16.768473
83
0.431221
[ [ [ "# Strings", "_____no_output_____" ], [ "### **Splitting strings**", "_____no_output_____" ] ], [ [ "'a,b,c'.split(',')", "_____no_output_____" ], [ "latitude = '37.24N'\nlongitude = '-115.81W'\n'Coordinates {0},{1}'.format(latitude,longitude)", "_____no_output_____" ], [ "f'Coordinates {latitude},{longitude}'", "_____no_output_____" ], [ "'{0},{1},{2}'.format(*('abc'))", "_____no_output_____" ], [ "coord = {\"latitude\":latitude,\"longitude\":longitude}\n'Coordinates {latitude},{longitude}'.format(**coord)", "_____no_output_____" ] ], [ [ "### **Access argument' s attribute **", "_____no_output_____" ] ], [ [ "class Point:\n def __init__(self,x,y):\n self.x,self.y = x,y\n def __str__(self):\n return 'Point({self.x},{self.y})'.format(self = self)\n def __repr__(self):\n return f'Point({self.x},{self.y})'", "_____no_output_____" ], [ "test_point = Point(4,2)\ntest_point", "_____no_output_____" ], [ "str(Point(4,2))", "_____no_output_____" ] ], [ [ "### **Replace with %s , %r ** :", "_____no_output_____" ] ], [ [ "\" repr() shows the quote {!r}, while str() doesn't:{!s} \".format('a1','a2')", "_____no_output_____" ] ], [ [ "### **Aligning the text with width** :", "_____no_output_____" ] ], [ [ "'{:<30}'.format('left aligned')", "_____no_output_____" ], [ "'{:>30}'.format('right aligned')", "_____no_output_____" ], [ "'{:^30}'.format('centerd')", "_____no_output_____" ], [ "'{:*^30}'.format('centerd')", "_____no_output_____" ] ], [ [ "### **Replace with %x , %o and convert the value to different base ** :", "_____no_output_____" ] ], [ [ "\"int:{0:d}, hex:{0:x}, oct:{0:o}, bin:{0:b}\".format(42)", "_____no_output_____" ], [ "'{:,}'.format(12345677)", "_____no_output_____" ] ], [ [ "### **Percentage ** :", "_____no_output_____" ] ], [ [ "points = 19\ntotal = 22\n'Correct answers: {:.2%}'.format(points/total)", "_____no_output_____" ], [ "import datetime as dt\nf\"{dt.datetime.now():%Y-%m-%d}\"", "_____no_output_____" ], [ "f\"{dt.datetime.now():%d_%m_%Y}\"", "_____no_output_____" ], [ "today = dt.datetime.today().strftime(\"%d_%m_%Y\")\ntoday", "_____no_output_____" ] ], [ [ "### **Splitting without parameters ** :", "_____no_output_____" ] ], [ [ "\"this is a test\".split()", "_____no_output_____" ] ], [ [ "### **Concatenating and joining Strings ** :", "_____no_output_____" ] ], [ [ "'do'*2", "_____no_output_____" ], [ "orig_string ='Hello'\norig_string+',World'", "_____no_output_____" ], [ "full_sentence = orig_string+',World'\nfull_sentence", "_____no_output_____" ] ], [ [ "### **Concatenating with join() , other basic funstions** :", "_____no_output_____" ] ], [ [ "strings = ['do','re','mi']\n', '.join(strings)", "_____no_output_____" ], [ "'z' not in 'abc'", "_____no_output_____" ], [ "ord('a'), ord('#')", "_____no_output_____" ], [ "chr(97)", "_____no_output_____" ], [ "s = \"foodbar\"\ns[2:5]", "_____no_output_____" ], [ "s[:4] + s[4:]", "_____no_output_____" ], [ "s[:4] + s[4:] == s", "_____no_output_____" ], [ "t=s[:]\nid(s)", "_____no_output_____" ], [ "id(t)", "_____no_output_____" ], [ "s is t", "_____no_output_____" ], [ "s[0:6:2]", "_____no_output_____" ], [ "s[5:0:-2]", "_____no_output_____" ], [ "s = 'tomorrow is monday'\nreverse_s = s[::-1]\nreverse_s", "_____no_output_____" ], [ "s.capitalize()", "_____no_output_____" ], [ "s.upper()", "_____no_output_____" ], [ "s.title()", "_____no_output_____" ], [ "s.count('o')", "_____no_output_____" ], [ "\"foobar\".startswith('foo')", "_____no_output_____" ], [ "\"foobar\".endswith('ar')", "_____no_output_____" ], [ "\"foobar\".endswith('oob',0,4)", "_____no_output_____" ], [ "\"foobar\".endswith('oob',2,4)", "_____no_output_____" ], [ "\"My name is yaozeliang, I work at Societe Generale\".find('yao')", "_____no_output_____" ], [ "# If can't find the string, return -1\n\"My name is yaozeliang, I work at Societe Generale\".find('gent')", "_____no_output_____" ], [ "# Check a string if consists of alphanumeric characters\n\"abc123\".isalnum()", "_____no_output_____" ], [ "\"abc%123\".isalnum()", "_____no_output_____" ], [ "\"abcABC\".isalpha()", "_____no_output_____" ], [ "\"abcABC1\".isalpha()", "_____no_output_____" ], [ "'123'.isdigit()", "_____no_output_____" ], [ "'123abc'.isdigit()", "_____no_output_____" ], [ "'abc'.islower()", "_____no_output_____" ], [ "\"This Is A Title\".istitle()", "_____no_output_____" ], [ "\"This is a title\".istitle()", "_____no_output_____" ], [ "'ABC'.isupper()", "_____no_output_____" ], [ "'ABC1%'.isupper()", "_____no_output_____" ], [ "'foo'.center(10)", "_____no_output_____" ], [ "' foo bar baz '.strip()", "_____no_output_____" ], [ "' foo bar baz '.lstrip()", "_____no_output_____" ], [ "' foo bar baz '.rstrip()", "_____no_output_____" ], [ "\"foo abc foo def fo ljk \".replace('foo','yao')", "_____no_output_____" ], [ "'www.realpython.com'.strip('w.moc')", "_____no_output_____" ], [ "'www.realpython.com'.strip('w.com')", "_____no_output_____" ], [ "'www.realpython.com'.strip('w.ncom')", "_____no_output_____" ] ], [ [ "### **Convert between strings and lists** :", "_____no_output_____" ] ], [ [ "', '.join(['foo','bar','baz','qux'])", "_____no_output_____" ], [ "list('corge')", "_____no_output_____" ], [ "':'.join('corge')", "_____no_output_____" ], [ "'www.foo'.partition('.')", "_____no_output_____" ], [ "'foo@@bar@@baz'.partition('@@')", "_____no_output_____" ], [ "'foo@@bar@@baz'.rpartition('@@')", "_____no_output_____" ], [ "'foo.bar'.partition('@@')", "_____no_output_____" ], [ "# By default , rsplit split a string with white space\n'foo bar adf yao'.rsplit()", "_____no_output_____" ], [ "'foo.bar.adf.ert'.split('.')", "_____no_output_____" ], [ "'foo\\nbar\\nadfa\\nlko'.splitlines()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe4490ba9826a14beb58de69feb7d1bf639ee2a
5,312
ipynb
Jupyter Notebook
ResNet_Analysis/9. Incorporating OD Veto Data.ipynb
WatChMaL/CNN
2e14397bca6ced2fdfeab406e3c28561bb3af384
[ "CNRI-Python", "RSA-MD" ]
3
2019-05-10T01:38:07.000Z
2021-09-06T16:30:18.000Z
ResNet_Analysis/9. Incorporating OD Veto Data.ipynb
WatChMaL/VAE
2e14397bca6ced2fdfeab406e3c28561bb3af384
[ "CNRI-Python", "RSA-MD" ]
3
2019-05-11T02:44:53.000Z
2019-05-24T18:37:58.000Z
ResNet_Analysis/9. Incorporating OD Veto Data.ipynb
WatChMaL/CNN
2e14397bca6ced2fdfeab406e3c28561bb3af384
[ "CNRI-Python", "RSA-MD" ]
8
2019-05-06T22:39:39.000Z
2020-11-29T17:15:50.000Z
27.381443
128
0.574172
[ [ [ "# 9. Incorporating OD Veto Data", "_____no_output_____" ] ], [ [ "import sys\nimport os\nimport h5py\nfrom collections import Counter\nfrom progressbar import *\nimport re\nimport numpy as np\nimport h5py\nfrom scipy import signal\nimport matplotlib\nfrom repeating_classifier_training_utils import *\nfrom functools import reduce\n\n# Add the path to the parent directory to augment search for module\npar_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir))\n\nif par_dir not in sys.path:\n sys.path.append(par_dir)\n%load_ext autoreload\n%matplotlib inline\n%autoreload 2", "_____no_output_____" ], [ "veto_path = '/fast_scratch/WatChMaL/data/IWCDmPMT_4pm_full_tank_ODveto.h5'", "_____no_output_____" ], [ "odv_file = h5py.File(veto_path,'r')\nodv_info = {}\nfor key in odv_file.keys():\n odv_info[key] = np.array(odv_file[key])", "_____no_output_____" ], [ "odv_dict = {}\npbar = ProgressBar(widgets=['Creating Event-Index Dictionary: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),\n ' ', ETA()], maxval=len(odv_info['event_ids']))\npbar.start()\nfor i in range(len(odv_info['event_ids'])):\n odv_dict[(odv_info['root_files'][i], odv_info['event_ids'][i])] = i\n pbar.update(i)\npbar.finish()", "Creating Event-Index Dictionary: 100% [0000000000000000000000000] Time: 0:00:15\n" ] ], [ [ "## Load test set", "_____no_output_____" ] ], [ [ "# Get original h5 file info\n# Import test events from h5 file\nfiltered_index = \"/fast_scratch/WatChMaL/data/IWCD_fulltank_300_pe_idxs.npz\"\nfiltered_indices = np.load(filtered_index, allow_pickle=True)\ntest_filtered_indices = filtered_indices['test_idxs']\n\noriginal_data_path = \"/data/WatChMaL/data/IWCDmPMT_4pi_fulltank_9M.h5\"\nf = h5py.File(original_data_path, \"r\")\n\noriginal_eventids = np.array(f['event_ids'])\noriginal_rootfiles = np.array(f['root_files'])\n\nfiltered_eventids = original_eventids[test_filtered_indices]\nfiltered_rootfiles = original_rootfiles[test_filtered_indices]", "_____no_output_____" ], [ "odv_mapping_indices = np.zeros(len(filtered_rootfiles))\npbar = ProgressBar(widgets=['Mapping Progress: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),\n ' ', ETA()], maxval=len(filtered_rootfiles))\npbar.start()\nfor i in range(len(filtered_rootfiles)):\n odv_mapping_indices[i] = odv_dict[(filtered_rootfiles[i], filtered_eventids[i])]\n pbar.update(i)\npbar.finish()\nodv_mapping_indices = np.int32(odv_mapping_indices)", "Mapping Progress: 100% [0000000000000000000000000000000000000000] Time: 0:00:09\n" ], [ "pbar = ProgressBar(widgets=['Verification Progress: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),\n ' ', ETA()], maxval=len(filtered_rootfiles))\npbar.start()\nfor i in range(len(filtered_rootfiles)):\n assert odv_info['root_files'][odv_mapping_indices[i]] == filtered_rootfiles[i]\n assert odv_info['event_ids'][odv_mapping_indices[i]] == filtered_eventids[i]\n pbar.update(i)\npbar.finish()", "Verification Progress: 100% [00000000000000000000000000000000000] Time: 0:00:13\n" ], [ "np.savez(os.path.join(os.getcwd(), 'Index_Storage/od_veto_mapping_idxs.npz'), mapping_idxs_full_set=odv_mapping_indices)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe44aaf586c7cce4c737dd21ccb2f69418e14d2
142,702
ipynb
Jupyter Notebook
efficientdet.ipynb
MostMoodee/EfficientDet
850206ac22e85c39be5d61621eb7be1fe9dc8fae
[ "Apache-2.0" ]
1
2021-09-06T16:48:46.000Z
2021-09-06T16:48:46.000Z
efficientdet.ipynb
MostMoodee/EfficientDet
850206ac22e85c39be5d61621eb7be1fe9dc8fae
[ "Apache-2.0" ]
null
null
null
efficientdet.ipynb
MostMoodee/EfficientDet
850206ac22e85c39be5d61621eb7be1fe9dc8fae
[ "Apache-2.0" ]
null
null
null
142,702
142,702
0.782302
[ [ [ "!git clone https://github.com/MostMoodee/EfficientDet.git", "Cloning into 'EfficientDet'...\nremote: Enumerating objects: 400, done.\u001b[K\nremote: Counting objects: 100% (400/400), done.\u001b[K\nremote: Compressing objects: 100% (141/141), done.\u001b[K\nremote: Total 400 (delta 256), reused 400 (delta 256), pack-reused 0\u001b[K\nReceiving objects: 100% (400/400), 1.46 MiB | 4.69 MiB/s, done.\nResolving deltas: 100% (256/256), done.\n" ], [ "%cd EfficientDet/", "/content/EfficientDet\n" ], [ "!pip install -r requirements.txt", "Collecting git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI (from -r requirements.txt (line 7))\n Cloning https://github.com/cocodataset/cocoapi.git to /tmp/pip-req-build-sxzvaf_x\n Running command git clone -q https://github.com/cocodataset/cocoapi.git /tmp/pip-req-build-sxzvaf_x\nCollecting Keras==2.2.5\n Downloading Keras-2.2.5-py2.py3-none-any.whl (336 kB)\n\u001b[K |████████████████████████████████| 336 kB 6.7 MB/s \n\u001b[?25hCollecting opencv-contrib-python==3.4.2.17\n Downloading opencv_contrib_python-3.4.2.17-cp37-cp37m-manylinux1_x86_64.whl (30.6 MB)\n\u001b[K |████████████████████████████████| 30.6 MB 24 kB/s \n\u001b[?25hCollecting opencv-python==3.4.2.17\n Downloading opencv_python-3.4.2.17-cp37-cp37m-manylinux1_x86_64.whl (25.0 MB)\n\u001b[K |████████████████████████████████| 25.0 MB 103 kB/s \n\u001b[?25hCollecting Pillow==6.2.0\n Downloading Pillow-6.2.0-cp37-cp37m-manylinux1_x86_64.whl (2.1 MB)\n\u001b[K |████████████████████████████████| 2.1 MB 59.1 MB/s \n\u001b[?25hCollecting tensorflow-gpu==1.15.0\n Downloading tensorflow_gpu-1.15.0-cp37-cp37m-manylinux2010_x86_64.whl (411.5 MB)\n\u001b[K |████████████████████████████████| 411.5 MB 8.2 kB/s \n\u001b[?25hRequirement already satisfied: progressbar2 in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 6)) (3.38.0)\nCollecting tqdm==4.28.1\n Downloading tqdm-4.28.1-py2.py3-none-any.whl (45 kB)\n\u001b[K |████████████████████████████████| 45 kB 3.8 MB/s \n\u001b[?25hRequirement already satisfied: setuptools>=18.0 in /usr/local/lib/python3.7/dist-packages (from pycocotools==2.0->-r requirements.txt (line 7)) (57.2.0)\nRequirement already satisfied: cython>=0.27.3 in /usr/local/lib/python3.7/dist-packages (from pycocotools==2.0->-r requirements.txt (line 7)) (0.29.23)\nRequirement already satisfied: matplotlib>=2.1.0 in /usr/local/lib/python3.7/dist-packages (from pycocotools==2.0->-r requirements.txt (line 7)) (3.2.2)\nRequirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (1.1.2)\nCollecting keras-applications>=1.0.8\n Downloading Keras_Applications-1.0.8-py3-none-any.whl (50 kB)\n\u001b[K |████████████████████████████████| 50 kB 7.0 MB/s \n\u001b[?25hRequirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (1.15.0)\nRequirement already satisfied: numpy>=1.9.1 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (1.19.5)\nRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (3.1.0)\nRequirement already satisfied: scipy>=0.14 in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (1.4.1)\nRequirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from Keras==2.2.5->-r requirements.txt (line 1)) (3.13)\nRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (1.12.1)\nCollecting gast==0.2.2\n Downloading gast-0.2.2.tar.gz (10 kB)\nCollecting tensorflow-estimator==1.15.1\n Downloading tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503 kB)\n\u001b[K |████████████████████████████████| 503 kB 58.6 MB/s \n\u001b[?25hRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (1.34.1)\nRequirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (0.2.0)\nRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (3.3.0)\nRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (3.17.3)\nRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (1.1.0)\nCollecting tensorboard<1.16.0,>=1.15.0\n Downloading tensorboard-1.15.0-py3-none-any.whl (3.8 MB)\n\u001b[K |████████████████████████████████| 3.8 MB 57.4 MB/s \n\u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (0.36.2)\nRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (0.8.1)\nRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (0.12.0)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools==2.0->-r requirements.txt (line 7)) (0.10.0)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools==2.0->-r requirements.txt (line 7)) (2.8.1)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools==2.0->-r requirements.txt (line 7)) (1.3.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.1.0->pycocotools==2.0->-r requirements.txt (line 7)) (2.4.7)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (3.3.4)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (1.0.1)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (4.6.1)\nRequirement already satisfied: python-utils>=2.3.0 in /usr/local/lib/python3.7/dist-packages (from progressbar2->-r requirements.txt (line 6)) (2.5.6)\nRequirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py->Keras==2.2.5->-r requirements.txt (line 1)) (1.5.2)\nRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (3.7.4.3)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow-gpu==1.15.0->-r requirements.txt (line 5)) (3.5.0)\nBuilding wheels for collected packages: pycocotools, gast\n Building wheel for pycocotools (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for pycocotools: filename=pycocotools-2.0-cp37-cp37m-linux_x86_64.whl size=263903 sha256=fa2e5203a89dc9d175b1e35a5a9725f4d3814296d4ace389b87cfa509341e99f\n Stored in directory: /tmp/pip-ephem-wheel-cache-6mxlmfzl/wheels/e2/6b/1d/344ac773c7495ea0b85eb228bc66daec7400a143a92d36b7b1\n Building wheel for gast (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for gast: filename=gast-0.2.2-py3-none-any.whl size=7553 sha256=c5669f4ec36421251f146e949fed07bc5f8d3b0d109bf0884ab51d87938d31ac\n Stored in directory: /root/.cache/pip/wheels/21/7f/02/420f32a803f7d0967b48dd823da3f558c5166991bfd204eef3\nSuccessfully built pycocotools gast\nInstalling collected packages: tensorflow-estimator, tensorboard, keras-applications, gast, tqdm, tensorflow-gpu, pycocotools, Pillow, opencv-python, opencv-contrib-python, Keras\n Attempting uninstall: tensorflow-estimator\n Found existing installation: tensorflow-estimator 2.5.0\n Uninstalling tensorflow-estimator-2.5.0:\n Successfully uninstalled tensorflow-estimator-2.5.0\n Attempting uninstall: tensorboard\n Found existing installation: tensorboard 2.5.0\n Uninstalling tensorboard-2.5.0:\n Successfully uninstalled tensorboard-2.5.0\n Attempting uninstall: gast\n Found existing installation: gast 0.4.0\n Uninstalling gast-0.4.0:\n Successfully uninstalled gast-0.4.0\n Attempting uninstall: tqdm\n Found existing installation: tqdm 4.41.1\n Uninstalling tqdm-4.41.1:\n Successfully uninstalled tqdm-4.41.1\n Attempting uninstall: pycocotools\n Found existing installation: pycocotools 2.0.2\n Uninstalling pycocotools-2.0.2:\n Successfully uninstalled pycocotools-2.0.2\n Attempting uninstall: Pillow\n Found existing installation: Pillow 7.1.2\n Uninstalling Pillow-7.1.2:\n Successfully uninstalled Pillow-7.1.2\n Attempting uninstall: opencv-python\n Found existing installation: opencv-python 4.1.2.30\n Uninstalling opencv-python-4.1.2.30:\n Successfully uninstalled opencv-python-4.1.2.30\n Attempting uninstall: opencv-contrib-python\n Found existing installation: opencv-contrib-python 4.1.2.30\n Uninstalling opencv-contrib-python-4.1.2.30:\n Successfully uninstalled opencv-contrib-python-4.1.2.30\n Attempting uninstall: Keras\n Found existing installation: Keras 2.4.3\n Uninstalling Keras-2.4.3:\n Successfully uninstalled Keras-2.4.3\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ntensorflow 2.5.0 requires gast==0.4.0, but you have gast 0.2.2 which is incompatible.\ntensorflow 2.5.0 requires tensorboard~=2.5, but you have tensorboard 1.15.0 which is incompatible.\ntensorflow 2.5.0 requires tensorflow-estimator<2.6.0,>=2.5.0rc0, but you have tensorflow-estimator 1.15.1 which is incompatible.\ntensorflow-probability 0.13.0 requires gast>=0.3.2, but you have gast 0.2.2 which is incompatible.\nspacy 2.2.4 requires tqdm<5.0.0,>=4.38.0, but you have tqdm 4.28.1 which is incompatible.\nfbprophet 0.7.1 requires tqdm>=4.36.1, but you have tqdm 4.28.1 which is incompatible.\nbokeh 2.3.3 requires pillow>=7.1.0, but you have pillow 6.2.0 which is incompatible.\nalbumentations 0.1.12 requires imgaug<0.2.7,>=0.2.5, but you have imgaug 0.2.9 which is incompatible.\u001b[0m\nSuccessfully installed Keras-2.2.5 Pillow-6.2.0 gast-0.2.2 keras-applications-1.0.8 opencv-contrib-python-3.4.2.17 opencv-python-3.4.2.17 pycocotools-2.0 tensorboard-1.15.0 tensorflow-estimator-1.15.1 tensorflow-gpu-1.15.0 tqdm-4.28.1\n" ], [ "!python3 setup.py build_ext --inplace", "Compiling utils/compute_overlap.pyx because it changed.\n[1/1] Cythonizing utils/compute_overlap.pyx\n/usr/local/lib/python3.7/dist-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /content/EfficientDet/utils/compute_overlap.pyx\n tree = Parsing.p_module(s, pxd, full_module_name)\nrunning build_ext\nbuilding 'utils.compute_overlap' extension\ncreating build\ncreating build/temp.linux-x86_64-3.7\ncreating build/temp.linux-x86_64-3.7/utils\nx86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fdebug-prefix-map=/build/python3.7-LSlbJj/python3.7-3.7.11=. -fstack-protector-strong -Wformat -Werror=format-security -g -fdebug-prefix-map=/build/python3.7-LSlbJj/python3.7-3.7.11=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/local/lib/python3.7/dist-packages/numpy/core/include -I/usr/include/python3.7m -c utils/compute_overlap.c -o build/temp.linux-x86_64-3.7/utils/compute_overlap.o\nIn file included from \u001b[01m\u001b[K/usr/local/lib/python3.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1822:0\u001b[m\u001b[K,\n from \u001b[01m\u001b[K/usr/local/lib/python3.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:12\u001b[m\u001b[K,\n from \u001b[01m\u001b[K/usr/local/lib/python3.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4\u001b[m\u001b[K,\n from \u001b[01m\u001b[Kutils/compute_overlap.c:625\u001b[m\u001b[K:\n\u001b[01m\u001b[K/usr/local/lib/python3.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2:\u001b[m\u001b[K \u001b[01;35m\u001b[Kwarning: \u001b[m\u001b[K#warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [\u001b[01;35m\u001b[K-Wcpp\u001b[m\u001b[K]\n #\u001b[01;35m\u001b[Kwarning\u001b[m\u001b[K \"Using deprecated NumPy API, disable it with \" \\\n \u001b[01;35m\u001b[K^~~~~~~\u001b[m\u001b[K\nx86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.7-LSlbJj/python3.7-3.7.11=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/utils/compute_overlap.o -o /content/EfficientDet/utils/compute_overlap.cpython-37m-x86_64-linux-gnu.so\n" ], [ "!pip install h5py==2.10.0", "Collecting h5py==2.10.0\n Downloading h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)\n\u001b[K |████████████████████████████████| 2.9 MB 7.2 MB/s \n\u001b[?25hRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from h5py==2.10.0) (1.15.0)\nRequirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.7/dist-packages (from h5py==2.10.0) (1.19.5)\nInstalling collected packages: h5py\n Attempting uninstall: h5py\n Found existing installation: h5py 3.1.0\n Uninstalling h5py-3.1.0:\n Successfully uninstalled h5py-3.1.0\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ntensorflow 2.5.0 requires gast==0.4.0, but you have gast 0.2.2 which is incompatible.\ntensorflow 2.5.0 requires h5py~=3.1.0, but you have h5py 2.10.0 which is incompatible.\ntensorflow 2.5.0 requires tensorboard~=2.5, but you have tensorboard 1.15.0 which is incompatible.\ntensorflow 2.5.0 requires tensorflow-estimator<2.6.0,>=2.5.0rc0, but you have tensorflow-estimator 1.15.1 which is incompatible.\u001b[0m\nSuccessfully installed h5py-2.10.0\n" ] ], [ [ "# inference image", "_____no_output_____" ] ], [ [ "cp /content/drive/MyDrive/efficientdet-d1.h5 ./", "_____no_output_____" ], [ "cp /content/drive/MyDrive/railway_forward.jpg ../", "_____no_output_____" ], [ "!python3 inference.py -model_path efficientdet-d1.h5 -image_dir ../ -output_image_dir ../", "_____no_output_____" ] ], [ [ "# inference video", "_____no_output_____" ] ], [ [ "cp /content/drive/MyDrive/rail-test-videos/rail-test3.mp4 ../", "_____no_output_____" ], [ "cp /content/drive/MyDrive/efficientdet-d1.h5 ./", "_____no_output_____" ], [ "!python3 inference_video.py -model_path efficientdet-d1.h5 -video_path ../rail-test3.mp4", "\u001b[1;30;43mStreaming output truncated to the last 5000 lines.\u001b[0m\n0.05691099166870117\n0.058413028717041016\n0.06241464614868164\n0.0626218318939209\n0.05616354942321777\n0.0555877685546875\n0.05634713172912598\n0.055869102478027344\n0.057032108306884766\n0.05814814567565918\n0.05703854560852051\n0.05803632736206055\n0.055403709411621094\n0.05495262145996094\n0.05591726303100586\n0.05911087989807129\n0.0574798583984375\n0.056783199310302734\n0.05800366401672363\n0.05614662170410156\n0.055609703063964844\n0.055085182189941406\n0.055260419845581055\n0.05568838119506836\n0.05550551414489746\n0.0554811954498291\n0.06070566177368164\n0.05708050727844238\n0.05609583854675293\n0.056561946868896484\n0.06067061424255371\n0.05780601501464844\n0.05531907081604004\n0.06003427505493164\n0.05630755424499512\n0.05602407455444336\n0.05564451217651367\n0.05674576759338379\n0.06156754493713379\n0.060990095138549805\n0.057631492614746094\n0.057157039642333984\n0.059439659118652344\n0.05689048767089844\n0.05654144287109375\n0.05709648132324219\n0.05666351318359375\n0.057845354080200195\n0.0573577880859375\n0.05649590492248535\n0.05748629570007324\n0.06158280372619629\n0.055979013442993164\n0.055826663970947266\n0.06249237060546875\n0.058010101318359375\n0.05662822723388672\n0.06274127960205078\n0.0598912239074707\n0.05691838264465332\n0.05709528923034668\n0.060640811920166016\n0.055294036865234375\n0.05574440956115723\n0.057277679443359375\n0.06879854202270508\n0.056961774826049805\n0.06337213516235352\n0.0572967529296875\n0.06023073196411133\n0.055243492126464844\n0.05650043487548828\n0.05676698684692383\n0.0571138858795166\n0.06469130516052246\n0.05510902404785156\n0.055808305740356445\n0.05964946746826172\n0.2214498519897461\n0.057671546936035156\n0.05831408500671387\n0.05911588668823242\n0.05758237838745117\n0.05784010887145996\n0.05827021598815918\n0.056255340576171875\n0.057550907135009766\n0.057604312896728516\n0.05898141860961914\n0.05749177932739258\n0.05837678909301758\n0.05882740020751953\n0.05595231056213379\n0.05999398231506348\n0.0616908073425293\n0.061818599700927734\n0.057294607162475586\n0.05564594268798828\n0.059072017669677734\n0.05649542808532715\n0.06419253349304199\n0.05826926231384277\n0.05653047561645508\n0.05538058280944824\n0.06678414344787598\n0.05778694152832031\n0.057416439056396484\n0.061660051345825195\n0.060628414154052734\n0.05801558494567871\n0.0579071044921875\n0.05463719367980957\n0.054973602294921875\n0.05725264549255371\n0.06577491760253906\n0.0559697151184082\n0.05539345741271973\n0.05762195587158203\n0.057558298110961914\n0.06343793869018555\n0.05595564842224121\n0.05536174774169922\n0.05849194526672363\n0.05659890174865723\n0.058943748474121094\n0.05787825584411621\n0.0623624324798584\n0.05843377113342285\n0.05903029441833496\n0.0560152530670166\n0.055283308029174805\n0.05839204788208008\n0.05599713325500488\n0.05610251426696777\n0.05749654769897461\n0.06650686264038086\n0.058145761489868164\n0.05834174156188965\n0.057807207107543945\n0.058485984802246094\n0.05646252632141113\n0.05772519111633301\n0.055600881576538086\n0.05608534812927246\n0.05707669258117676\n0.05692791938781738\n0.059882164001464844\n0.058478593826293945\n0.05690741539001465\n0.05693411827087402\n0.056162118911743164\n0.057204484939575195\n0.05682015419006348\n0.06307530403137207\n0.057871341705322266\n0.05639338493347168\n0.05857205390930176\n0.05749702453613281\n0.05704784393310547\n0.05858588218688965\n0.06391668319702148\n0.0596768856048584\n0.05657458305358887\n0.056998252868652344\n0.06120133399963379\n0.055884361267089844\n0.059389352798461914\n0.05657839775085449\n0.05546689033508301\n0.05517840385437012\n0.05638599395751953\n0.0558466911315918\n0.05576777458190918\n0.06148719787597656\n0.055368661880493164\n0.05603790283203125\n0.05714225769042969\n0.05804133415222168\n0.05599546432495117\n0.05893588066101074\n0.056685686111450195\n0.05952715873718262\n0.056511878967285156\n0.05942225456237793\n0.0576171875\n0.059953927993774414\n0.05769705772399902\n0.05681467056274414\n0.059955596923828125\n0.05640673637390137\n0.0568234920501709\n0.05954718589782715\n0.05811929702758789\n0.060124874114990234\n0.06118416786193848\n0.05695199966430664\n0.056082963943481445\n0.05702710151672363\n0.05589914321899414\n0.05637502670288086\n0.06100296974182129\n0.05681490898132324\n0.05734062194824219\n0.05770397186279297\n0.05953860282897949\n0.06272673606872559\n0.05927586555480957\n0.056569576263427734\n0.05557107925415039\n0.055633544921875\n0.05552482604980469\n0.05444526672363281\n0.0552668571472168\n0.0551609992980957\n0.0546879768371582\n0.055081844329833984\n0.054598331451416016\n0.05484342575073242\n0.06469416618347168\n0.05723977088928223\n0.05438113212585449\n0.05557417869567871\n0.05579519271850586\n0.05649971961975098\n0.05898737907409668\n0.055132150650024414\n0.05492854118347168\n0.054929494857788086\n0.05576181411743164\n0.06391525268554688\n0.0564732551574707\n0.05554795265197754\n0.056391239166259766\n0.059037208557128906\n0.05569005012512207\n0.05494236946105957\n0.05609560012817383\n0.05537772178649902\n0.05623483657836914\n0.056475162506103516\n0.05620574951171875\n0.05701112747192383\n0.0553431510925293\n0.055238962173461914\n0.0552976131439209\n0.055356502532958984\n0.05628561973571777\n0.056165218353271484\n0.058756351470947266\n0.057335853576660156\n0.057248592376708984\n0.05687141418457031\n0.05539751052856445\n0.06024003028869629\n0.05716109275817871\n0.055709123611450195\n0.05653548240661621\n0.05976080894470215\n0.05493521690368652\n0.05420184135437012\n0.05462837219238281\n0.05635857582092285\n0.05636787414550781\n0.05548977851867676\n0.05379819869995117\n0.06196737289428711\n0.053464412689208984\n0.054491281509399414\n0.0535435676574707\n0.05563020706176758\n0.05452132225036621\n0.05791306495666504\n0.05462360382080078\n0.05530381202697754\n0.05552053451538086\n0.05710554122924805\n0.05480480194091797\n0.05693697929382324\n0.058486223220825195\n0.06055879592895508\n0.05580711364746094\n0.057032108306884766\n0.060703277587890625\n0.056571006774902344\n0.0601654052734375\n0.0559847354888916\n0.0557100772857666\n0.05803728103637695\n0.05693626403808594\n0.05536317825317383\n0.05629372596740723\n0.055342912673950195\n0.055428504943847656\n0.05688977241516113\n0.05601096153259277\n0.05573153495788574\n0.057399749755859375\n0.05706071853637695\n0.059090614318847656\n0.056623220443725586\n0.05641293525695801\n0.057741641998291016\n0.055007219314575195\n0.06444311141967773\n0.05683112144470215\n0.05620384216308594\n0.05631208419799805\n0.0594937801361084\n0.05449080467224121\n0.05544614791870117\n0.05447554588317871\n0.05594182014465332\n0.055158376693725586\n0.06149911880493164\n0.05762362480163574\n0.05631756782531738\n0.055312395095825195\n0.05548548698425293\n0.05503368377685547\n0.05493783950805664\n0.055516719818115234\n0.05567002296447754\n0.0560152530670166\n0.057128190994262695\n0.05485963821411133\n0.05594611167907715\n0.06269001960754395\n0.05641818046569824\n0.05643033981323242\n0.05532336235046387\n0.056231021881103516\n0.06226038932800293\n0.05750608444213867\n0.05693411827087402\n0.05951881408691406\n0.05823874473571777\n0.05474352836608887\n0.05510282516479492\n0.05525612831115723\n0.05655312538146973\n0.06063699722290039\n0.06057548522949219\n0.05700063705444336\n0.057267189025878906\n0.05843687057495117\n0.054984331130981445\n0.05551719665527344\n0.05402874946594238\n0.05400991439819336\n0.055281639099121094\n0.05538773536682129\n0.054282426834106445\n0.0597529411315918\n0.05543088912963867\n0.05504417419433594\n0.054172515869140625\n0.05388689041137695\n0.05583763122558594\n0.05481314659118652\n0.05440521240234375\n0.056703805923461914\n0.055350542068481445\n0.05511212348937988\n0.054807186126708984\n0.05598783493041992\n0.054750919342041016\n0.054414987564086914\n0.054720401763916016\n0.05538034439086914\n0.054502248764038086\n0.053472280502319336\n0.05395841598510742\n0.05503726005554199\n0.06447887420654297\n0.056023597717285156\n0.05522775650024414\n0.061452388763427734\n0.0558924674987793\n0.05572080612182617\n0.05532526969909668\n0.056509971618652344\n0.060219764709472656\n0.055066823959350586\n0.05475497245788574\n0.05600595474243164\n0.056317806243896484\n0.056200265884399414\n0.05642890930175781\n0.055451393127441406\n0.05466604232788086\n0.05501365661621094\n0.06180429458618164\n0.05392861366271973\n0.056549787521362305\n0.05431246757507324\n0.05436301231384277\n0.0531611442565918\n0.05660414695739746\n0.054454803466796875\n0.05834555625915527\n0.053826093673706055\n0.05462050437927246\n0.05500316619873047\n0.05746936798095703\n0.0550234317779541\n0.054666757583618164\n0.06021595001220703\n0.05507040023803711\n0.0712130069732666\n0.056298255920410156\n0.055916547775268555\n0.05453896522521973\n0.054831743240356445\n0.055572509765625\n0.05489921569824219\n0.05581212043762207\n0.053437232971191406\n0.053734779357910156\n0.05532336235046387\n0.05524444580078125\n0.0543670654296875\n0.055277109146118164\n0.05470705032348633\n0.055391550064086914\n0.05560803413391113\n0.05579781532287598\n0.05726265907287598\n0.05614161491394043\n0.05985546112060547\n0.055909156799316406\n0.05687665939331055\n0.05640101432800293\n0.05604052543640137\n0.0558774471282959\n0.0561215877532959\n0.06206393241882324\n0.05751919746398926\n0.055817604064941406\n0.05573558807373047\n0.055779218673706055\n0.05593681335449219\n0.05454707145690918\n0.05574774742126465\n0.05402970314025879\n0.054445505142211914\n0.054654598236083984\n0.0549471378326416\n0.05881357192993164\n0.055631399154663086\n0.055338382720947266\n0.05443406105041504\n0.05432558059692383\n0.05447673797607422\n0.05582427978515625\n0.054244041442871094\n0.056212663650512695\n0.06525397300720215\n0.05612301826477051\n0.05857062339782715\n0.0540313720703125\n0.056649208068847656\n0.054833173751831055\n0.055341482162475586\n0.05468583106994629\n0.06420397758483887\n0.05623149871826172\n0.055358171463012695\n0.05550885200500488\n0.053667545318603516\n0.054317474365234375\n0.054316043853759766\n0.055425405502319336\n0.056154727935791016\n0.05656099319458008\n0.058499813079833984\n0.05733489990234375\n0.05739331245422363\n0.05749869346618652\n0.06016063690185547\n0.055685997009277344\n0.05579805374145508\n0.0556950569152832\n0.05554962158203125\n0.06456375122070312\n0.05640697479248047\n0.055730581283569336\n0.05618095397949219\n0.0564885139465332\n0.054863929748535156\n0.0550689697265625\n0.05472564697265625\n0.05667376518249512\n0.05984044075012207\n0.0601811408996582\n0.056778669357299805\n0.05559539794921875\n0.05988264083862305\n0.05559825897216797\n0.054514169692993164\n0.05457758903503418\n0.05381155014038086\n0.06103801727294922\n0.0546259880065918\n0.054678916931152344\n0.054733991622924805\n0.05557727813720703\n0.05494880676269531\n0.05582070350646973\n0.05511474609375\n0.053503990173339844\n0.05456733703613281\n0.06336855888366699\n0.05867910385131836\n0.054894208908081055\n0.05438566207885742\n0.05469965934753418\n0.05490517616271973\n0.05404067039489746\n0.05492687225341797\n0.05621457099914551\n0.05652165412902832\n0.055486202239990234\n0.0577390193939209\n0.056031227111816406\n0.057207345962524414\n0.05960392951965332\n0.05539298057556152\n0.056797027587890625\n0.05881977081298828\n0.059189558029174805\n0.05582404136657715\n0.05616283416748047\n0.05665230751037598\n0.05797219276428223\n0.06047677993774414\n0.05581974983215332\n0.055166006088256836\n0.05673384666442871\n0.05718708038330078\n0.05470705032348633\n0.05627608299255371\n0.056703805923461914\n0.05984640121459961\n0.05718588829040527\n0.05508923530578613\n0.055365562438964844\n0.059239864349365234\n0.05694103240966797\n0.05602431297302246\n0.055941104888916016\n0.0548100471496582\n0.056354522705078125\n0.057633399963378906\n0.05560135841369629\n0.05559945106506348\n0.05484414100646973\n0.0552978515625\n0.055635929107666016\n0.05885195732116699\n0.05528736114501953\n0.05559492111206055\n0.05508065223693848\n0.056282997131347656\n0.05460834503173828\n0.055727243423461914\n0.05565333366394043\n0.05528664588928223\n0.05611062049865723\n0.05515170097351074\n0.055852651596069336\n0.058637142181396484\n0.0564117431640625\n0.056299448013305664\n0.05594611167907715\n0.05639171600341797\n0.05974531173706055\n0.05587029457092285\n0.055867910385131836\n0.055144548416137695\n0.055694580078125\n0.06267094612121582\n0.05621910095214844\n0.05639243125915527\n0.0560915470123291\n0.05607485771179199\n0.05520153045654297\n0.06491518020629883\n0.05616641044616699\n0.05903482437133789\n0.06183052062988281\n0.05768752098083496\n0.058400869369506836\n0.06018352508544922\n0.057530879974365234\n0.056472063064575195\n0.05624842643737793\n0.0572361946105957\n0.06599545478820801\n0.05820655822753906\n0.05816769599914551\n0.05838727951049805\n0.058507680892944336\n0.06052231788635254\n0.05883598327636719\n0.062134742736816406\n0.05709695816040039\n0.06716537475585938\n0.05575251579284668\n0.05697441101074219\n0.05828142166137695\n0.05770254135131836\n0.056290388107299805\n0.05664324760437012\n0.05712699890136719\n0.05766773223876953\n0.05755352973937988\n0.05611252784729004\n0.05936908721923828\n0.058280229568481445\n0.05725407600402832\n0.05721473693847656\n0.05958294868469238\n0.0565645694732666\n0.055402278900146484\n0.05992770195007324\n0.06253552436828613\n0.0571136474609375\n0.057913780212402344\n0.061475276947021484\n0.059545040130615234\n0.06269454956054688\n0.06542396545410156\n0.05858016014099121\n0.05590319633483887\n0.056658267974853516\n0.05925440788269043\n0.0563657283782959\n0.05977058410644531\n0.05732607841491699\n0.06176280975341797\n0.05661416053771973\n0.06025290489196777\n0.2245945930480957\n0.059821128845214844\n0.05715227127075195\n0.05687665939331055\n0.06237435340881348\n0.06006169319152832\n0.05652737617492676\n0.0568540096282959\n0.06451058387756348\n0.05797600746154785\n0.05701160430908203\n0.057080745697021484\n0.057396888732910156\n0.061631202697753906\n0.05762457847595215\n0.061383724212646484\n0.056031227111816406\n0.06574511528015137\n0.0579524040222168\n0.056302547454833984\n0.05646514892578125\n0.06023597717285156\n0.057909250259399414\n0.057762861251831055\n0.0588376522064209\n0.06752467155456543\n0.0570378303527832\n0.05597710609436035\n0.06777620315551758\n0.05751347541809082\n0.05716419219970703\n0.056452274322509766\n0.059348344802856445\n0.0565032958984375\n0.05639052391052246\n0.05780458450317383\n0.06366801261901855\n0.057682037353515625\n0.056566476821899414\n0.059461116790771484\n0.05750441551208496\n0.05937361717224121\n0.0616912841796875\n0.05744028091430664\n0.05750298500061035\n0.05562639236450195\n0.05650591850280762\n0.05693650245666504\n0.06150674819946289\n0.05688762664794922\n0.061002492904663086\n0.056880950927734375\n0.060903310775756836\n0.06595468521118164\n0.05774641036987305\n0.06389665603637695\n0.058652400970458984\n0.06282973289489746\n0.0591588020324707\n0.05807852745056152\n0.05750727653503418\n0.06302642822265625\n0.058068037033081055\n0.05974984169006348\n0.061641693115234375\n0.05722522735595703\n0.05689597129821777\n0.05824685096740723\n0.05786871910095215\n0.058937788009643555\n0.0570986270904541\n0.058805227279663086\n0.06232953071594238\n0.0573117733001709\n0.05779433250427246\n0.06234145164489746\n0.06493115425109863\n0.05694317817687988\n0.05656599998474121\n0.055832624435424805\n0.0572810173034668\n0.058081626892089844\n0.06323575973510742\n0.06333017349243164\n0.057614803314208984\n0.05833005905151367\n0.05968785285949707\n0.056738853454589844\n0.05693960189819336\n0.06013655662536621\n0.06110501289367676\n0.057129859924316406\n0.06477856636047363\n0.061200857162475586\n0.05721879005432129\n0.06275033950805664\n0.06105780601501465\n0.05766701698303223\n0.05780291557312012\n0.06413984298706055\n0.05713772773742676\n0.05583524703979492\n0.05960845947265625\n0.05660295486450195\n0.05633425712585449\n0.05693244934082031\n0.057940006256103516\n0.059035539627075195\n0.05919051170349121\n0.06195664405822754\n0.06376290321350098\n0.06308221817016602\n0.056817054748535156\n0.05731844902038574\n0.062041282653808594\n0.057608604431152344\n0.0581357479095459\n0.05931520462036133\n0.058557748794555664\n0.05844736099243164\n0.05693387985229492\n0.05920124053955078\n0.058210134506225586\n0.05668139457702637\n0.06065821647644043\n0.05702018737792969\n0.06030774116516113\n0.06037497520446777\n0.05930352210998535\n0.057062387466430664\n0.06508302688598633\n0.056787729263305664\n0.057057857513427734\n0.05763554573059082\n0.05762743949890137\n0.056424617767333984\n0.05684208869934082\n0.07034635543823242\n0.05618023872375488\n0.05604219436645508\n0.06353092193603516\n0.05753350257873535\n0.05742764472961426\n0.057274818420410156\n0.06268763542175293\n0.057541847229003906\n0.055606842041015625\n0.056504249572753906\n0.05619931221008301\n0.055240631103515625\n0.061949968338012695\n0.05522727966308594\n0.06000661849975586\n0.05595064163208008\n0.06438088417053223\n0.06251740455627441\n0.05583500862121582\n0.05870795249938965\n0.05553460121154785\n0.05599641799926758\n0.061182260513305664\n0.05717349052429199\n0.05960822105407715\n0.055457353591918945\n0.05569791793823242\n0.05590534210205078\n0.055176734924316406\n0.06001996994018555\n0.057079315185546875\n0.05617332458496094\n0.0540313720703125\n0.05480360984802246\n0.06318187713623047\n0.05437493324279785\n0.05870175361633301\n0.05489468574523926\n0.05628681182861328\n0.05646991729736328\n0.060576438903808594\n0.05515575408935547\n0.05579829216003418\n0.05988311767578125\n0.05525851249694824\n0.057015180587768555\n0.055670738220214844\n0.056906938552856445\n0.05541563034057617\n0.05529284477233887\n0.06153464317321777\n0.05837392807006836\n0.055283546447753906\n0.057340383529663086\n0.05592155456542969\n0.06242537498474121\n0.055211544036865234\n0.05514407157897949\n0.07078003883361816\n0.054962158203125\n0.05466151237487793\n0.05823397636413574\n0.05471014976501465\n0.05808734893798828\n0.053774356842041016\n0.054297685623168945\n0.05529522895812988\n0.055251121520996094\n0.05474257469177246\n0.05491948127746582\n0.054261207580566406\n0.05499720573425293\n0.05523419380187988\n0.055635690689086914\n0.05672717094421387\n0.05665993690490723\n0.06791305541992188\n0.05593228340148926\n0.05472707748413086\n0.05558300018310547\n0.06120800971984863\n0.05494952201843262\n0.05458188056945801\n0.053956031799316406\n0.05434083938598633\n0.053873300552368164\n0.056629180908203125\n0.055278778076171875\n0.06020069122314453\n0.0561528205871582\n0.0576474666595459\n0.056246042251586914\n0.0613706111907959\n0.05713057518005371\n0.05652427673339844\n0.05548810958862305\n0.05643725395202637\n0.057924509048461914\n0.061298370361328125\n0.0603792667388916\n0.05532574653625488\n0.055097103118896484\n0.05443239212036133\n0.0594484806060791\n0.06155133247375488\n0.0573878288269043\n0.05752825736999512\n0.062021493911743164\n0.05661177635192871\n0.054286956787109375\n0.0564267635345459\n0.05339694023132324\n0.05481386184692383\n0.05243062973022461\n0.05809450149536133\n0.052262306213378906\n0.06193900108337402\n0.052230119705200195\n0.05415701866149902\n0.05384254455566406\n0.0523834228515625\n0.052153587341308594\n0.05250406265258789\n0.0554807186126709\n0.0544126033782959\n0.05337381362915039\n0.05389118194580078\n0.05341529846191406\n0.05164313316345215\n0.052117347717285156\n0.05234527587890625\n0.052629947662353516\n0.0534060001373291\n0.055639028549194336\n0.052889347076416016\n0.06061124801635742\n0.05467033386230469\n0.05768537521362305\n0.055684566497802734\n0.060762643814086914\n0.05311441421508789\n0.053369998931884766\n0.057300567626953125\n0.05209231376647949\n0.05731558799743652\n0.05803823471069336\n0.05283951759338379\n0.05748605728149414\n0.05388522148132324\n0.052858829498291016\n0.05247354507446289\n0.05276656150817871\n0.05508995056152344\n0.0542445182800293\n0.05326485633850098\n0.05700087547302246\n0.05205059051513672\n0.06516313552856445\n0.055387020111083984\n0.059308767318725586\n0.0546107292175293\n0.05458188056945801\n0.05457186698913574\n0.055169105529785156\n0.053700923919677734\n0.054521799087524414\n0.06150221824645996\n0.05601668357849121\n0.055315494537353516\n0.05387258529663086\n0.055243730545043945\n0.060991764068603516\n0.05652976036071777\n0.053972721099853516\n0.053459882736206055\n0.0677039623260498\n0.05803275108337402\n0.05371403694152832\n0.054390907287597656\n0.054224252700805664\n0.05409693717956543\n0.05458879470825195\n0.05699038505554199\n0.06067919731140137\n0.05384492874145508\n0.05426144599914551\n0.05709719657897949\n0.055429697036743164\n0.05619096755981445\n0.05696535110473633\n0.05659365653991699\n0.05776023864746094\n0.05505728721618652\n0.057752370834350586\n0.059067487716674805\n0.056234121322631836\n0.05452847480773926\n0.05686020851135254\n0.055008888244628906\n0.05471634864807129\n0.055965423583984375\n0.055166006088256836\n0.06100916862487793\n0.05552077293395996\n0.060662269592285156\n0.054691314697265625\n0.05451321601867676\n0.05571603775024414\n0.05530858039855957\n0.054572343826293945\n0.05471682548522949\n0.05357193946838379\n0.05397820472717285\n0.05875587463378906\n0.05868220329284668\n0.05758547782897949\n0.055379390716552734\n0.0547177791595459\n0.05565476417541504\n0.05763816833496094\n0.0550684928894043\n0.05445075035095215\n0.059174537658691406\n0.05488324165344238\n0.05904865264892578\n0.05607175827026367\n0.05480337142944336\n0.057791709899902344\n0.05678582191467285\n0.05456352233886719\n0.054825544357299805\n0.056287288665771484\n0.06414198875427246\n0.05660057067871094\n0.055120229721069336\n0.05647420883178711\n0.05817580223083496\n0.06470298767089844\n0.05572772026062012\n0.05566906929016113\n0.06234598159790039\n0.055355072021484375\n0.05579376220703125\n0.055449485778808594\n0.05450725555419922\n0.055678606033325195\n0.05530381202697754\n0.05477261543273926\n0.05495095252990723\n0.057848453521728516\n0.05594635009765625\n0.05843806266784668\n0.05504441261291504\n0.0559995174407959\n0.05629754066467285\n0.05598902702331543\n0.054956912994384766\n0.054364919662475586\n0.06146717071533203\n0.05690264701843262\n0.06071138381958008\n0.05976605415344238\n0.05545783042907715\n0.055049896240234375\n0.058515071868896484\n0.05414247512817383\n0.055342674255371094\n0.055021047592163086\n0.05547618865966797\n0.05549812316894531\n0.055346012115478516\n0.05529379844665527\n0.05426502227783203\n0.06324267387390137\n0.05592751502990723\n0.05438232421875\n0.05878090858459473\n0.05448150634765625\n0.056029319763183594\n0.055785179138183594\n0.055520057678222656\n0.0544893741607666\n0.05449962615966797\n0.05499696731567383\n0.0673828125\n0.06746411323547363\n0.058339595794677734\n0.055230140686035156\n0.05764317512512207\n0.05632209777832031\n0.05485820770263672\n0.05660223960876465\n0.05949521064758301\n0.05507969856262207\n0.05649852752685547\n0.05547046661376953\n0.0558316707611084\n0.06646370887756348\n0.05543255805969238\n0.054790496826171875\n0.06255364418029785\n0.0564732551574707\n0.056714534759521484\n0.06402254104614258\n0.06333780288696289\n0.06023359298706055\n0.05488276481628418\n0.05538010597229004\n0.05733036994934082\n0.05586576461791992\n0.05425834655761719\n0.05764603614807129\n0.06069827079772949\n0.05476737022399902\n0.054436683654785156\n0.05525016784667969\n0.05898761749267578\n0.05698060989379883\n0.056878089904785156\n0.05820727348327637\n0.05468273162841797\n0.0588529109954834\n0.05701160430908203\n0.054534912109375\n0.0590207576751709\n0.054955244064331055\n0.054105520248413086\n0.05507326126098633\n0.05378985404968262\n0.056006669998168945\n0.056005001068115234\n0.05561566352844238\n0.05704069137573242\n0.05603957176208496\n0.05585050582885742\n0.06070876121520996\n0.055850982666015625\n0.055169105529785156\n0.05623793601989746\n0.05682539939880371\n0.060576438903808594\n0.05836939811706543\n0.05432605743408203\n0.05598640441894531\n0.05553030967712402\n0.05924844741821289\n0.057135581970214844\n0.05597281455993652\n0.059128761291503906\n0.05635356903076172\n0.05466198921203613\n0.055115461349487305\n0.05552935600280762\n0.054950714111328125\n0.05970644950866699\n0.0550229549407959\n0.05438351631164551\n0.0541996955871582\n0.061199188232421875\n0.059844970703125\n0.05472850799560547\n0.054296255111694336\n0.0549015998840332\n0.054698944091796875\n0.05431246757507324\n0.05576324462890625\n0.055880069732666016\n0.05543088912963867\n0.05805778503417969\n0.05580735206604004\n0.05567145347595215\n0.05521559715270996\n0.05515933036804199\n0.05640816688537598\n0.05444693565368652\n0.05429434776306152\n0.05453920364379883\n0.055385589599609375\n0.05481123924255371\n0.0562286376953125\n0.05489301681518555\n0.05630660057067871\n0.055417776107788086\n0.055151939392089844\n0.05573678016662598\n0.05666184425354004\n0.05512499809265137\n0.05473160743713379\n0.05945444107055664\n0.05593585968017578\n0.056763648986816406\n0.05722665786743164\n0.057442426681518555\n0.05742669105529785\n0.055525779724121094\n0.0568850040435791\n0.057236433029174805\n0.05772137641906738\n0.058577775955200195\n0.05717778205871582\n0.05774211883544922\n0.056508541107177734\n0.060178518295288086\n0.05597734451293945\n0.056597232818603516\n0.05567121505737305\n0.0560910701751709\n0.05805039405822754\n0.05894136428833008\n0.055361032485961914\n0.05998992919921875\n0.056394100189208984\n0.05566716194152832\n0.060726165771484375\n0.06209588050842285\n0.0626981258392334\n0.05979275703430176\n0.055497169494628906\n0.05486464500427246\n0.0563662052154541\n0.057007789611816406\n0.055588483810424805\n0.05861210823059082\n0.06110882759094238\n0.05525398254394531\n0.0617825984954834\n0.057579994201660156\n0.21598482131958008\n0.05704474449157715\n0.05828070640563965\n0.056267499923706055\n0.058571815490722656\n0.06162238121032715\n0.05679178237915039\n0.056844234466552734\n0.06094527244567871\n0.058036088943481445\n0.05708932876586914\n0.06178641319274902\n0.057340383529663086\n0.056684255599975586\n0.058252811431884766\n0.056997060775756836\n0.057373762130737305\n0.05997133255004883\n0.05573248863220215\n0.06438350677490234\n0.05771923065185547\n0.058214664459228516\n0.05881023406982422\n0.055686235427856445\n0.05473780632019043\n0.06058192253112793\n0.05591011047363281\n0.056235313415527344\n0.05468010902404785\n0.0546875\n0.055098772048950195\n0.05553913116455078\n0.055506229400634766\n0.061040639877319336\n0.05447530746459961\n0.05562543869018555\n0.05515170097351074\n0.053802490234375\n0.056653738021850586\n0.055640459060668945\n0.05963850021362305\n0.05520987510681152\n0.054885149002075195\n0.0585176944732666\n0.05883431434631348\n0.06183171272277832\n0.0571131706237793\n0.05673718452453613\n0.055458784103393555\n0.05794572830200195\n0.0620877742767334\n0.05940890312194824\n0.05842185020446777\n0.05776667594909668\n0.05729174613952637\n0.0568394660949707\n0.06385660171508789\n0.05990314483642578\n0.05571556091308594\n0.0559999942779541\n0.0625143051147461\n0.06933712959289551\n0.0570070743560791\n0.05604124069213867\n0.056586265563964844\n0.05639076232910156\n0.060729265213012695\n0.06295919418334961\n0.05558323860168457\n0.05565190315246582\n0.05647587776184082\n0.056343793869018555\n0.061377525329589844\n0.056137800216674805\n0.06187796592712402\n0.05667877197265625\n0.059014081954956055\n0.059229373931884766\n0.054878950119018555\n0.0634312629699707\n0.06041550636291504\n0.0570216178894043\n0.05563640594482422\n0.05539536476135254\n0.05549192428588867\n0.05556440353393555\n0.05836606025695801\n0.057727813720703125\n0.05963325500488281\n0.058960676193237305\n0.056606292724609375\n0.05740022659301758\n0.054866790771484375\n0.05500984191894531\n0.054682254791259766\n0.05591249465942383\n0.05852317810058594\n0.05534052848815918\n0.055873870849609375\n0.05771493911743164\n0.061248064041137695\n0.057511091232299805\n0.06010723114013672\n0.05785107612609863\n0.056488752365112305\n0.0638425350189209\n0.06267619132995605\n0.05684232711791992\n0.05782270431518555\n0.05630612373352051\n0.05879044532775879\n0.05910682678222656\n0.05752301216125488\n0.05631208419799805\n0.05744218826293945\n0.060181617736816406\n0.056285858154296875\n0.05562162399291992\n0.05981016159057617\n0.05559659004211426\n0.05583333969116211\n0.05776715278625488\n0.06567096710205078\n0.056204795837402344\n0.05789065361022949\n0.05880117416381836\n0.05615735054016113\n0.055616140365600586\n0.05908513069152832\n0.0569002628326416\n0.058521270751953125\n0.06001472473144531\n0.057134389877319336\n0.06182122230529785\n0.05558443069458008\n0.05874896049499512\n0.0568544864654541\n0.059348344802856445\n0.059029340744018555\n0.05554795265197754\n0.0562283992767334\n0.057572126388549805\n0.05655217170715332\n0.05563068389892578\n0.05560016632080078\n0.05765557289123535\n0.05992269515991211\n0.05669450759887695\n0.05767393112182617\n0.0596773624420166\n0.061421871185302734\n0.05764937400817871\n0.06089329719543457\n0.05724835395812988\n0.05749773979187012\n0.0660238265991211\n0.05705595016479492\n0.059433937072753906\n0.055733442306518555\n0.056646108627319336\n0.06310105323791504\n0.057164669036865234\n0.060193538665771484\n0.05887413024902344\n0.056990623474121094\n0.06038475036621094\n0.058872222900390625\n0.057602643966674805\n0.05800819396972656\n0.0631105899810791\n0.05776357650756836\n0.059365272521972656\n0.05789303779602051\n0.05794358253479004\n0.06173133850097656\n0.05739784240722656\n0.060095787048339844\n0.05858802795410156\n0.06180715560913086\n0.05834460258483887\n0.05591869354248047\n0.05740642547607422\n0.0559544563293457\n0.05671381950378418\n0.06263327598571777\n0.05898928642272949\n0.05650043487548828\n0.05698060989379883\n0.05648040771484375\n0.058548688888549805\n0.05866098403930664\n0.05610942840576172\n0.055129289627075195\n0.055622100830078125\n0.05760908126831055\n0.055565834045410156\n0.05504965782165527\n0.05612659454345703\n0.0629124641418457\n0.054740190505981445\n0.0549776554107666\n0.0581059455871582\n0.055943965911865234\n0.057779788970947266\n0.05574655532836914\n0.05585622787475586\n0.057566165924072266\n0.06302189826965332\n0.05567502975463867\n0.058689117431640625\n0.05573320388793945\n0.05568861961364746\n0.06521821022033691\n0.055799245834350586\n0.05793428421020508\n0.05659198760986328\n0.05651140213012695\n0.05519676208496094\n0.05440497398376465\n0.05574679374694824\n0.05556678771972656\n0.05547356605529785\n0.05529165267944336\n0.054955244064331055\n0.054791927337646484\n0.0555272102355957\n0.05452752113342285\n0.06073117256164551\n0.05413079261779785\n0.05681610107421875\n0.055721282958984375\n0.0548100471496582\n0.0549015998840332\n0.05405783653259277\n0.06306910514831543\n0.055390119552612305\n0.05382800102233887\n0.06167244911193848\n0.05463981628417969\n0.056349992752075195\n0.0550990104675293\n0.05696988105773926\n0.05574607849121094\n0.05985379219055176\n0.05799579620361328\n0.05480146408081055\n0.05442166328430176\n0.0629110336303711\n0.0558474063873291\n0.05808544158935547\n0.05421257019042969\n0.06469464302062988\n0.05563688278198242\n0.05918765068054199\n0.05627036094665527\n0.05756568908691406\n0.05742383003234863\n0.05998086929321289\n0.055666208267211914\n0.05776095390319824\n0.05485081672668457\n0.055333852767944336\n0.05644869804382324\n0.05424141883850098\n0.05939936637878418\n0.05512428283691406\n0.05767536163330078\n0.055573225021362305\n0.05544018745422363\n0.05432462692260742\n0.05810403823852539\n0.06089448928833008\n0.057062625885009766\n0.056192636489868164\n0.05624723434448242\n0.05498647689819336\n0.05474400520324707\n0.05575823783874512\n0.05475878715515137\n0.05504941940307617\n0.05543708801269531\n0.05626559257507324\n0.05669140815734863\n0.05701470375061035\n0.061978816986083984\n0.055147647857666016\n0.059723615646362305\n0.0552983283996582\n0.05681562423706055\n0.057356834411621094\n0.056290626525878906\n0.05619454383850098\n0.05955862998962402\n0.06225776672363281\n0.05684518814086914\n0.06413960456848145\n0.057507991790771484\n0.05898857116699219\n0.05558443069458008\n0.05611109733581543\n0.0567474365234375\n0.06350541114807129\n0.06255435943603516\n0.05457758903503418\n0.05758810043334961\n0.06304645538330078\n0.060837507247924805\n0.056937217712402344\n0.05930161476135254\n0.057843685150146484\n0.06500792503356934\n0.05743551254272461\n0.06006288528442383\n0.05667304992675781\n0.060536861419677734\n0.05697321891784668\n0.06039690971374512\n0.05698513984680176\n0.056906938552856445\n0.05610918998718262\n0.05794358253479004\n0.05868983268737793\n0.0558779239654541\n0.06138324737548828\n0.060912370681762695\n0.05625510215759277\n0.05900716781616211\n0.06553387641906738\n0.05893731117248535\n0.05529451370239258\n0.06004047393798828\n0.05746650695800781\n0.056175947189331055\n0.06040048599243164\n0.05552864074707031\n0.06297779083251953\n0.06369543075561523\n0.05656886100769043\n0.06233978271484375\n0.05637502670288086\n0.05938267707824707\n0.05578780174255371\n0.06459259986877441\n0.05547785758972168\n0.05501532554626465\n0.0598447322845459\n0.056756019592285156\n0.05949544906616211\n0.05541181564331055\n0.05510210990905762\n0.05490612983703613\n0.05609846115112305\n0.05950021743774414\n0.058324337005615234\n0.05719637870788574\n0.05642342567443848\n0.05671381950378418\n0.05650210380554199\n0.058225154876708984\n0.05650782585144043\n0.05861496925354004\n0.06425666809082031\n0.056746721267700195\n0.05592751502990723\n0.056787967681884766\n0.05915212631225586\n0.05738496780395508\n0.05619549751281738\n0.059485435485839844\n0.057045698165893555\n0.055426836013793945\n0.057753562927246094\n0.056461334228515625\n0.0573735237121582\n0.05744171142578125\n0.05797219276428223\n0.05636954307556152\n0.05502915382385254\n0.058905839920043945\n0.057019710540771484\n0.0573577880859375\n0.06653571128845215\n0.05764603614807129\n0.056253910064697266\n0.055002450942993164\n0.05655789375305176\n0.055635929107666016\n0.06201767921447754\n0.05462336540222168\n0.057643890380859375\n0.055879831314086914\n0.05613207817077637\n0.05748105049133301\n0.055771827697753906\n0.05519843101501465\n0.057417869567871094\n0.05505990982055664\n0.055716514587402344\n0.05484724044799805\n0.05469155311584473\n0.055700063705444336\n0.059281349182128906\n0.055413007736206055\n0.05546450614929199\n0.05688619613647461\n0.05934500694274902\n0.055506229400634766\n0.05607461929321289\n0.055938005447387695\n0.05588126182556152\n0.05608487129211426\n0.0579068660736084\n0.06098175048828125\n0.06035757064819336\n0.05840182304382324\n0.05824160575866699\n0.0577392578125\n0.06157207489013672\n0.05665469169616699\n0.05589890480041504\n0.057342529296875\n0.05651497840881348\n0.05612587928771973\n0.05563926696777344\n0.058455467224121094\n0.056627511978149414\n0.05577516555786133\n0.055889129638671875\n0.05682826042175293\n0.057474374771118164\n0.05657362937927246\n0.055937767028808594\n0.05710196495056152\n0.0567781925201416\n0.06404876708984375\n0.05540752410888672\n0.06455135345458984\n0.055832862854003906\n0.05521273612976074\n0.05624055862426758\n0.05887436866760254\n0.05653810501098633\n0.05437064170837402\n0.054987192153930664\n0.05489826202392578\n0.056176185607910156\n0.05708718299865723\n0.06187105178833008\n0.057235002517700195\n0.06120920181274414\n0.0561223030090332\n0.0623021125793457\n0.0553436279296875\n0.059189558029174805\n0.05911087989807129\n0.06264328956604004\n0.05680537223815918\n0.05971670150756836\n0.06037116050720215\n0.05715537071228027\n0.06085658073425293\n0.05869746208190918\n0.05710792541503906\n0.05760383605957031\n0.06236767768859863\n0.06015825271606445\n0.05637693405151367\n0.05826091766357422\n0.05531597137451172\n0.05791616439819336\n0.057718515396118164\n0.058431148529052734\n0.05781745910644531\n0.05550742149353027\n0.057564496994018555\n0.06222701072692871\n0.055429697036743164\n0.05538225173950195\n0.05612778663635254\n0.05488133430480957\n0.05436062812805176\n0.05543017387390137\n0.05487179756164551\n0.05597686767578125\n0.05486869812011719\n0.056488752365112305\n0.05680394172668457\n0.05593156814575195\n0.05585885047912598\n0.06141543388366699\n0.05688953399658203\n0.05635476112365723\n0.055886268615722656\n0.054860591888427734\n0.05588364601135254\n0.055449724197387695\n0.05600881576538086\n0.05404090881347656\n0.05388784408569336\n0.05512428283691406\n0.05544161796569824\n0.057387590408325195\n0.054678916931152344\n0.05846381187438965\n0.054120540618896484\n0.054906606674194336\n0.06459212303161621\n0.05664706230163574\n0.05623149871826172\n0.05522799491882324\n0.05500173568725586\n0.05669283866882324\n0.061737775802612305\n0.05752086639404297\n0.06025123596191406\n0.05553293228149414\n0.05475950241088867\n0.061450958251953125\n0.05493950843811035\n0.06169390678405762\n0.05579519271850586\n0.055443763732910156\n0.06439805030822754\n0.054578542709350586\n0.059777021408081055\n0.05435061454772949\n0.05470132827758789\n0.06626367568969727\n0.05441427230834961\n0.05523371696472168\n0.05372500419616699\n0.06218290328979492\n0.053169965744018555\n0.05898475646972656\n0.05317330360412598\n0.05712318420410156\n0.055002689361572266\n0.05800938606262207\n0.05358099937438965\n0.058836936950683594\n0.05343747138977051\n0.05363035202026367\n0.05951380729675293\n0.05291271209716797\n0.05255007743835449\n0.06048178672790527\n0.0538485050201416\n0.05639958381652832\n0.05331826210021973\n0.05310368537902832\n0.051455020904541016\n0.05141901969909668\n0.050591230392456055\n0.05142855644226074\n0.0538785457611084\n0.051557064056396484\n0.05164980888366699\n0.051509857177734375\n0.05639910697937012\n0.05282449722290039\n0.0511014461517334\n0.05161619186401367\n0.052117347717285156\n0.051247358322143555\n0.21249103546142578\n0.05241084098815918\n0.05338335037231445\n0.052085161209106445\n0.0534970760345459\n0.05278921127319336\n0.052397966384887695\n0.056223392486572266\n0.053705692291259766\n0.05539822578430176\n0.054434776306152344\n0.05347633361816406\n0.05413627624511719\n0.057799339294433594\n0.05368828773498535\n0.05231642723083496\n0.05356788635253906\n0.060279130935668945\n0.05192422866821289\n0.05309343338012695\n0.05197000503540039\n0.06305789947509766\n0.0525364875793457\n0.05676412582397461\n0.0522003173828125\n0.05332803726196289\n0.05670523643493652\n0.05257391929626465\n0.060248374938964844\n0.054666757583618164\n0.05911993980407715\n0.056894779205322266\n0.054144859313964844\n0.05161714553833008\n0.05274248123168945\n0.05223536491394043\n0.05247759819030762\n0.052124977111816406\n0.052472591400146484\n0.05258011817932129\n0.055519819259643555\n0.05223393440246582\n0.050995588302612305\n0.0561826229095459\n0.05186796188354492\n0.055484771728515625\n0.05139613151550293\n0.05420637130737305\n0.05768179893493652\n0.05304574966430664\n0.050729990005493164\n0.052423715591430664\n0.051206350326538086\n0.05298328399658203\n0.05260109901428223\n0.051522254943847656\n0.05163145065307617\n0.051809072494506836\n0.05913996696472168\n0.05361032485961914\n0.05996537208557129\n0.05354881286621094\n0.06104326248168945\n0.0539708137512207\n0.05252861976623535\n0.05302882194519043\n0.05695033073425293\n0.05669355392456055\n0.05367112159729004\n0.057981252670288086\n0.05360817909240723\n0.05472850799560547\n0.058648109436035156\n0.06158590316772461\n0.05527853965759277\n0.054335832595825195\n0.053586721420288086\n0.05620718002319336\n0.05343461036682129\n0.05631208419799805\n0.05247855186462402\n0.05692887306213379\n0.05227184295654297\n0.0579829216003418\n0.053648948669433594\n0.05164504051208496\n0.05151700973510742\n0.05488324165344238\n0.05176591873168945\n0.05724167823791504\n0.05307435989379883\n0.05248904228210449\n0.0521397590637207\n0.053856849670410156\n0.05462813377380371\n0.05374503135681152\n0.05263829231262207\n0.05308365821838379\n0.05637693405151367\n0.05879092216491699\n0.054277658462524414\n0.0537874698638916\n0.05441403388977051\n0.05410480499267578\n0.05445122718811035\n0.05649590492248535\n0.0547785758972168\n0.053415536880493164\n0.05382871627807617\n0.06147575378417969\n0.054556846618652344\n0.054988861083984375\n0.05449271202087402\n0.05790996551513672\n0.05512404441833496\n0.054705142974853516\n0.055071353912353516\n0.05563163757324219\n0.05533623695373535\n0.057637691497802734\n0.06068682670593262\n0.05506563186645508\n0.055229902267456055\n0.05469179153442383\n0.055841922760009766\n0.05662965774536133\n0.054698944091796875\n0.06222033500671387\n0.05667567253112793\n0.055144548416137695\n0.05582761764526367\n0.05539679527282715\n0.05380654335021973\n0.05385303497314453\n0.05403923988342285\n0.05578184127807617\n0.05419588088989258\n0.05431985855102539\n0.05427145957946777\n0.056780099868774414\n0.054326772689819336\n0.05790829658508301\n0.05389761924743652\n0.06085062026977539\n0.053349971771240234\n0.05594372749328613\n0.06410479545593262\n0.05617165565490723\n0.053659677505493164\n0.05296897888183594\n0.0559995174407959\n0.06412863731384277\n0.054499149322509766\n0.05579066276550293\n0.057997941970825195\n0.055335044860839844\n0.05666780471801758\n0.05846118927001953\n0.05523872375488281\n0.0547938346862793\n0.05464911460876465\n0.05956554412841797\n0.05739331245422363\n0.05483603477478027\n0.05549907684326172\n0.05480074882507324\n0.0535273551940918\n0.052950382232666016\n0.05276322364807129\n0.052954912185668945\n0.05304098129272461\n0.05347800254821777\n0.059720754623413086\n0.05464005470275879\n0.059616804122924805\n0.05357098579406738\n0.059355974197387695\n0.05479001998901367\n0.05882835388183594\n0.05417776107788086\n0.05324816703796387\n0.06027626991271973\n0.05367279052734375\n0.06100773811340332\n0.054290056228637695\n0.05440878868103027\n0.061685800552368164\n0.054312944412231445\n0.05372476577758789\n0.05421257019042969\n0.0584874153137207\n0.055568695068359375\n0.055397987365722656\n0.054138898849487305\n0.052987098693847656\n0.05378413200378418\n0.05309915542602539\n0.05457949638366699\n0.05486464500427246\n0.053719282150268555\n0.053734779357910156\n0.061447858810424805\n0.059472084045410156\n0.05474448204040527\n0.053325653076171875\n0.057092905044555664\n0.0550994873046875\n0.055283546447753906\n0.05587124824523926\n0.056723833084106445\n0.05518317222595215\n0.05730581283569336\n0.055722713470458984\n0.05503106117248535\n0.05570244789123535\n0.05528664588928223\n0.05539512634277344\n0.055292367935180664\n0.05479907989501953\n0.05607438087463379\n0.05615878105163574\n0.05587339401245117\n0.0550076961517334\n0.05523228645324707\n0.05500173568725586\n0.05485844612121582\n0.05614900588989258\n0.05516338348388672\n0.055059194564819336\n0.05537223815917969\n0.06522488594055176\n0.05631065368652344\n0.05513811111450195\n0.05576825141906738\n0.05439496040344238\n0.05560588836669922\n0.05601382255554199\n0.05748581886291504\n0.054167747497558594\n0.05454421043395996\n0.054785728454589844\n0.05511641502380371\n0.05585432052612305\n0.05441594123840332\n0.057562828063964844\n0.05906963348388672\n0.05832552909851074\n0.05461764335632324\n0.06362318992614746\n0.05383610725402832\n0.05474042892456055\n0.05617499351501465\n0.05523395538330078\n0.05431842803955078\n0.05500531196594238\n0.059764862060546875\n0.05513739585876465\n0.05513191223144531\n0.05899786949157715\n0.05645012855529785\n0.05755257606506348\n0.055200815200805664\n0.05553579330444336\n0.05638718605041504\n0.05605196952819824\n0.056188344955444336\n0.0548703670501709\n0.0549924373626709\n0.05598139762878418\n0.05538320541381836\n0.05647778511047363\n0.05743694305419922\n0.0593562126159668\n0.055992841720581055\n0.05594325065612793\n0.05532503128051758\n0.0602719783782959\n0.05709552764892578\n0.05443382263183594\n0.05513501167297363\n0.05455899238586426\n0.05416154861450195\n0.05443215370178223\n0.05464315414428711\n0.05955958366394043\n0.05565667152404785\n0.05455899238586426\n0.05463910102844238\n0.05466055870056152\n0.05521726608276367\n0.0554196834564209\n0.05623984336853027\n0.056501150131225586\n0.058463335037231445\n0.05550336837768555\n0.05542349815368652\n0.06150674819946289\n0.05756187438964844\n0.057105064392089844\n0.054877281188964844\n0.06726717948913574\n0.057591915130615234\n0.054328203201293945\n0.055907487869262695\n0.05398702621459961\n0.05623197555541992\n0.05704331398010254\n0.055666446685791016\n0.05475974082946777\n0.05529141426086426\n0.05535602569580078\n0.056409358978271484\n0.05761528015136719\n0.05824565887451172\n0.05814480781555176\n0.05720090866088867\n0.05603957176208496\n0.05512833595275879\n0.05539131164550781\n0.05591845512390137\n0.056850433349609375\n0.05697774887084961\n0.05672883987426758\n0.05611228942871094\n0.0580134391784668\n0.05735063552856445\n0.05902361869812012\n0.05591464042663574\n0.054630279541015625\n0.05475211143493652\n0.06354093551635742\n0.055504560470581055\n0.05618548393249512\n0.06197810173034668\n0.05479025840759277\n0.057624101638793945\n0.0592193603515625\n0.0604705810546875\n0.05607342720031738\n0.059212446212768555\n0.06156039237976074\n0.06111025810241699\n0.05700230598449707\n0.05653572082519531\n0.05627775192260742\n0.06052851676940918\n0.06067657470703125\n0.05603337287902832\n0.05447030067443848\n0.0563807487487793\n0.05741596221923828\n0.058307647705078125\n0.05611133575439453\n0.05638742446899414\n0.05738639831542969\n0.05657649040222168\n0.05631828308105469\n0.05727744102478027\n0.07230305671691895\n0.05761361122131348\n0.06195211410522461\n0.05549907684326172\n0.05520224571228027\n0.05603432655334473\n0.05903816223144531\n0.05666041374206543\n0.05668020248413086\n0.061192989349365234\n0.05903267860412598\n0.057968854904174805\n0.056813955307006836\n0.05996561050415039\n0.057361602783203125\n0.05676841735839844\n0.057077884674072266\n0.05765366554260254\n0.06328201293945312\n0.06008028984069824\n0.05742168426513672\n0.05474448204040527\n0.05445599555969238\n0.055208683013916016\n0.0553281307220459\n0.05999445915222168\n0.053643226623535156\n0.05699634552001953\n0.05578041076660156\n0.059051513671875\n0.05818748474121094\n0.05983400344848633\n0.05989480018615723\n0.0561676025390625\n0.06098651885986328\n0.05607724189758301\n0.05941653251647949\n0.06058359146118164\n0.06442499160766602\n0.055144548416137695\n0.057556867599487305\n0.05608034133911133\n0.05829024314880371\n0.05654644966125488\n0.05904197692871094\n0.0622708797454834\n0.06191301345825195\n0.058321237564086914\n0.05655097961425781\n0.061856746673583984\n0.05891895294189453\n0.059177398681640625\n0.057559967041015625\n0.056912899017333984\n0.0562586784362793\n0.06105446815490723\n0.05606532096862793\n0.0607295036315918\n0.05604124069213867\n0.05611133575439453\n0.057097434997558594\n0.05678844451904297\n0.061829328536987305\n0.057367563247680664\n0.05825924873352051\n0.0556795597076416\n0.05826973915100098\n0.05677056312561035\n0.05498337745666504\n0.0553743839263916\n0.05609631538391113\n0.05585360527038574\n0.05859637260437012\n0.05751490592956543\n0.060559988021850586\n0.05662655830383301\n0.05555009841918945\n0.06908082962036133\n0.05582380294799805\n0.05557560920715332\n0.06127166748046875\n0.0564267635345459\n0.05640101432800293\n0.060094594955444336\n0.06650519371032715\n0.056171417236328125\n0.0560297966003418\n0.05719804763793945\n0.05841183662414551\n0.06398844718933105\n0.055444955825805664\n0.05534839630126953\n0.05839729309082031\n0.05693507194519043\n0.059419870376586914\n0.05569767951965332\n0.05527019500732422\n0.05777597427368164\n0.056482553482055664\n0.05622243881225586\n0.05723452568054199\n0.057935476303100586\n0.05743527412414551\n0.0582575798034668\n0.05644941329956055\n0.05713629722595215\n0.06148266792297363\n0.057309865951538086\n0.056687355041503906\n0.05744528770446777\n0.05691099166870117\n0.055375099182128906\n0.05588555335998535\n0.055309295654296875\n0.05593085289001465\n0.0558319091796875\n0.05793642997741699\n0.05806612968444824\n0.05713915824890137\n0.05503726005554199\n0.0532841682434082\n0.058257341384887695\n0.06104445457458496\n0.06418728828430176\n0.0551600456237793\n0.055296897888183594\n0.05541849136352539\n0.059682369232177734\n0.05533099174499512\n0.06190752983093262\n0.05395078659057617\n0.05675959587097168\n0.05588126182556152\n0.055878639221191406\n0.05517745018005371\n0.05481266975402832\n0.056433916091918945\n0.05768609046936035\n0.05791354179382324\n0.05639386177062988\n0.05617260932922363\n0.059511423110961914\n0.060683488845825195\n0.05633997917175293\n0.059053897857666016\n0.056326866149902344\n0.055824995040893555\n0.05594468116760254\n0.05499744415283203\n0.06017470359802246\n0.05500340461730957\n0.055181264877319336\n0.06022977828979492\n0.05753278732299805\n0.05983924865722656\n0.056344032287597656\n0.06190776824951172\n0.057930946350097656\n0.06038331985473633\n0.05573391914367676\n0.05587482452392578\n0.05797767639160156\n0.05617523193359375\n0.05574655532836914\n0.05644822120666504\n0.059180259704589844\n0.05791616439819336\n0.05687856674194336\n0.060227394104003906\n0.05630064010620117\n0.056351423263549805\n0.0566098690032959\n0.06086111068725586\n0.05581045150756836\n0.0550684928894043\n0.05599641799926758\n0.056406497955322266\n0.06082010269165039\n0.05388951301574707\n0.055078744888305664\n0.05441594123840332\n0.055819034576416016\n0.05944347381591797\n0.05874228477478027\n0.055020809173583984\n0.055563926696777344\n0.05817055702209473\n0.056429386138916016\n0.06385302543640137\n0.05634927749633789\n0.056958913803100586\n0.056828975677490234\n0.05795478820800781\n0.05852150917053223\n0.05689120292663574\n0.05951714515686035\n0.05568981170654297\n0.05616402626037598\n0.05598282814025879\n0.05455732345581055\n0.05771684646606445\n0.05852198600769043\n0.05461883544921875\n0.05561709403991699\n0.056180477142333984\n0.060497283935546875\n0.21782302856445312\n0.0555424690246582\n0.05513596534729004\n0.059877634048461914\n0.05621647834777832\n0.06402921676635742\n0.061742305755615234\n0.05670309066772461\n0.05734395980834961\n0.0554046630859375\n0.05867123603820801\n0.059783220291137695\n0.05562448501586914\n0.05472588539123535\n0.05460309982299805\n0.06164741516113281\n0.0580446720123291\n0.05458807945251465\n0.053757429122924805\n0.056891441345214844\n0.054440975189208984\n0.055939435958862305\n0.05630636215209961\n0.06107616424560547\n0.05448317527770996\n0.05483245849609375\n0.05480241775512695\n0.05633878707885742\n0.05731654167175293\n0.05855846405029297\n0.05516171455383301\n0.05900096893310547\n0.06109476089477539\n0.05615854263305664\n0.05543398857116699\n0.055341482162475586\n0.05607891082763672\n0.0621798038482666\n0.05671191215515137\n0.055393218994140625\n0.06738615036010742\n0.05567765235900879\n0.0549464225769043\n0.05542302131652832\n0.05652356147766113\n0.06077861785888672\n0.05501198768615723\n0.06783866882324219\n0.06409740447998047\n0.05520272254943848\n0.056738853454589844\n0.05538296699523926\n0.058913469314575195\n0.05946516990661621\n0.054686784744262695\n0.05598139762878418\n0.05534839630126953\n0.05534625053405762\n0.05510306358337402\n0.055312395095825195\n0.06499218940734863\n0.05730938911437988\n0.054735422134399414\n0.056139230728149414\n0.055152177810668945\n0.05581808090209961\n0.057378292083740234\n0.054343461990356445\n0.056932687759399414\n0.05474495887756348\n0.05858111381530762\n0.05495405197143555\n0.059928178787231445\n0.05394744873046875\n0.05421757698059082\n0.05451202392578125\n0.05463695526123047\n0.0552518367767334\n0.05529308319091797\n0.05520224571228027\n0.05574488639831543\n0.060129642486572266\n0.05629897117614746\n0.055562734603881836\n0.0564112663269043\n0.05599236488342285\n0.057132720947265625\n0.0607602596282959\n0.06917119026184082\n0.05787062644958496\n0.06180524826049805\n0.05609011650085449\n0.05611729621887207\n0.05936169624328613\n0.0552980899810791\n0.057389020919799805\n0.056792259216308594\n0.05658364295959473\n0.05673980712890625\n0.05753517150878906\n0.05548238754272461\n0.06206345558166504\n0.056139469146728516\n0.06432795524597168\n0.05461525917053223\n0.0572202205657959\n0.058229684829711914\n0.05849480628967285\n0.05512189865112305\n0.05851435661315918\n0.05721426010131836\n0.06316590309143066\n0.055669307708740234\n0.05732297897338867\n0.05904388427734375\n0.05594801902770996\n0.05703449249267578\n0.05608963966369629\n0.055124521255493164\n0.05707097053527832\n0.061655282974243164\n0.05626249313354492\n0.06205916404724121\n0.05585885047912598\n0.06036257743835449\n0.06283211708068848\n0.05681920051574707\n0.056153297424316406\n0.057066917419433594\n0.05669522285461426\n0.05656075477600098\n0.058107852935791016\n0.055968284606933594\n0.055882930755615234\n0.06347537040710449\n0.05819392204284668\n0.057988643646240234\n0.0565943717956543\n0.05696439743041992\n0.05634593963623047\n0.05615973472595215\n0.05695509910583496\n0.056418657302856445\n0.06065511703491211\n0.056365966796875\n0.05593585968017578\n0.05559182167053223\n0.05570554733276367\n0.055324554443359375\n0.058419227600097656\n0.05578255653381348\n0.05578780174255371\n0.05468416213989258\n0.05662202835083008\n0.05470752716064453\n0.05942964553833008\n0.05476999282836914\n0.05687546730041504\n0.05433464050292969\n0.055685997009277344\n0.05443143844604492\n0.0602567195892334\n0.06355953216552734\n0.0559840202331543\n0.06077933311462402\n0.055924177169799805\n0.05537986755371094\n0.05726122856140137\n0.05653214454650879\n0.055470943450927734\n0.059874773025512695\n0.05559062957763672\n0.05473518371582031\n0.055571556091308594\n0.05717897415161133\n0.05889177322387695\n0.056169748306274414\n0.05588269233703613\n0.054830312728881836\n0.05588936805725098\n0.05803632736206055\n0.058626651763916016\n0.05468106269836426\n0.05453300476074219\n0.054106712341308594\n0.056656599044799805\n0.05854368209838867\n0.0566253662109375\n0.05519747734069824\n0.06278681755065918\n0.05551648139953613\n0.05444693565368652\n0.05518221855163574\n0.05486011505126953\n0.05553078651428223\n0.05534553527832031\n0.05629253387451172\n0.054100990295410156\n0.054494619369506836\n0.05449509620666504\n0.05743718147277832\n0.05663347244262695\n0.055072784423828125\n0.056143999099731445\n0.05394768714904785\n0.055805206298828125\n0.05527162551879883\n0.05493903160095215\n0.056639909744262695\n0.05453991889953613\n0.05443549156188965\n0.054869890213012695\n0.05503201484680176\n0.05689525604248047\n0.06239151954650879\n0.05488467216491699\n0.05414986610412598\n0.05637931823730469\n0.05520939826965332\n0.05636763572692871\n0.05583930015563965\n0.055417776107788086\n0.055696964263916016\n0.056717634201049805\n0.060648441314697266\n0.05597710609436035\n0.05868220329284668\n0.05765676498413086\n0.055730581283569336\n0.056118011474609375\n0.06042337417602539\n0.06293487548828125\n0.05623769760131836\n0.05460095405578613\n0.055217742919921875\n0.056406259536743164\n0.06213212013244629\n0.055471181869506836\n0.055680274963378906\n0.056970834732055664\n0.05898141860961914\n0.05636715888977051\n0.05522584915161133\n0.0557255744934082\n0.05618000030517578\n0.056352853775024414\n0.0562586784362793\n0.05482625961303711\n0.05608391761779785\n0.055768728256225586\n0.05472159385681152\n0.05451631546020508\n0.05414414405822754\n0.05743002891540527\n0.05589795112609863\n0.059194087982177734\n0.054802894592285156\n0.05535626411437988\n0.05635881423950195\n0.055483341217041016\n0.05524396896362305\n0.05590057373046875\n0.06424260139465332\n0.05540871620178223\n0.05640602111816406\n0.056223154067993164\n0.055646419525146484\n0.055071115493774414\n0.05585932731628418\n0.05762028694152832\n0.05486631393432617\n0.05491948127746582\n0.055091142654418945\n0.057061195373535156\n0.05569791793823242\n0.06398415565490723\n0.05519700050354004\n0.05935406684875488\n0.05491447448730469\n0.056426286697387695\n0.05628013610839844\n0.06268906593322754\n0.05513930320739746\n0.058573246002197266\n0.05555248260498047\n0.05599856376647949\n0.056162357330322266\n0.05656266212463379\n0.05616354942321777\n0.05614733695983887\n0.05760955810546875\n0.056433677673339844\n0.05532360076904297\n0.055687904357910156\n0.05549955368041992\n0.05605268478393555\n0.054319143295288086\n0.054549217224121094\n0.05521202087402344\n0.05620718002319336\n0.05432891845703125\n0.06362056732177734\n0.05550098419189453\n0.056006669998168945\n0.05574655532836914\n0.05497622489929199\n0.058588504791259766\n0.055437564849853516\n0.05464363098144531\n0.05856013298034668\n0.05739450454711914\n0.0587158203125\n0.05538511276245117\n0.05573534965515137\n0.0547025203704834\n0.05526089668273926\n0.05486345291137695\n0.05603671073913574\n0.05554795265197754\n0.055253028869628906\n0.055864572525024414\n0.055335283279418945\n0.05564379692077637\n0.055312156677246094\n0.05533742904663086\n0.05600786209106445\n0.05561089515686035\n0.055107831954956055\n0.05613064765930176\n0.05494356155395508\n0.05488467216491699\n0.05603909492492676\n0.05551028251647949\n0.05659794807434082\n0.059185028076171875\n0.05654335021972656\n0.055771589279174805\n0.05581188201904297\n0.05515909194946289\n0.05646491050720215\n0.054357051849365234\n0.055457353591918945\n0.06243586540222168\n0.059615373611450195\n0.05627775192260742\n0.05672883987426758\n0.061701297760009766\n0.06074714660644531\n0.0555267333984375\n0.06329846382141113\n0.05895853042602539\n0.05750012397766113\n0.056769371032714844\n0.056916236877441406\n0.056748390197753906\n0.05680990219116211\n0.06049346923828125\n0.058533430099487305\n0.05767703056335449\n0.05676627159118652\n0.06375360488891602\n0.05622506141662598\n0.05702781677246094\n0.0612943172454834\n0.05617809295654297\n0.06395435333251953\n0.059213876724243164\n0.05566287040710449\n0.055161476135253906\n0.057189226150512695\n0.05919790267944336\n0.05672192573547363\n0.05857276916503906\n0.058333635330200195\n0.05595040321350098\n0.05552983283996582\n0.06354427337646484\n0.058823585510253906\n0.05600762367248535\n0.05709266662597656\n0.05715203285217285\n0.06211400032043457\n0.05759167671203613\n0.05881309509277344\n0.057443857192993164\n0.05807685852050781\n0.056314706802368164\n0.05715489387512207\n0.057027578353881836\n0.057211875915527344\n0.059088706970214844\n0.05926823616027832\n0.056656837463378906\n0.05753922462463379\n0.06033897399902344\n0.05722332000732422\n0.0615839958190918\n0.05648231506347656\n0.07199215888977051\n0.056374311447143555\n0.057372331619262695\n0.056316375732421875\n0.055707454681396484\n0.05748343467712402\n0.05951571464538574\n0.055892229080200195\n0.05655384063720703\n0.06119680404663086\n0.05449032783508301\n0.056938886642456055\n0.05482316017150879\n0.055490970611572266\n0.05786275863647461\n0.06358766555786133\n0.05607271194458008\n0.06292438507080078\n0.056151628494262695\n0.0626063346862793\n0.05773615837097168\n0.0616912841796875\n0.05824398994445801\n0.05760669708251953\n0.05571460723876953\n0.05707883834838867\n0.06112408638000488\n0.058441877365112305\n0.0569000244140625\n0.05975079536437988\n0.06124281883239746\n0.05649256706237793\n0.06400060653686523\n0.05659747123718262\n0.0563812255859375\n0.060851097106933594\n0.0566556453704834\n0.06604671478271484\n0.06172013282775879\n0.05570697784423828\n0.05569148063659668\n0.0563206672668457\n0.05669569969177246\n0.05727577209472656\n0.05763125419616699\n0.05744147300720215\n0.05654430389404297\n0.05911827087402344\n0.0551915168762207\n0.055017709732055664\n0.05551886558532715\n0.05538439750671387\n0.055036067962646484\n0.05667257308959961\n0.05815720558166504\n0.06224632263183594\n0.05799436569213867\n0.05909228324890137\n0.05856943130493164\n0.0641171932220459\n0.05816221237182617\n0.05855536460876465\n0.0565190315246582\n0.05654144287109375\n0.05943155288696289\n0.05798816680908203\n0.05631756782531738\n0.05661296844482422\n0.05659937858581543\n0.0554962158203125\n0.05804443359375\n0.057869672775268555\n0.055243730545043945\n0.055520057678222656\n0.05530953407287598\n0.05619072914123535\n0.06338167190551758\n0.056632041931152344\n0.05509185791015625\n0.05541419982910156\n0.05539417266845703\n0.056069374084472656\n0.05567121505737305\n0.057260751724243164\n0.05513739585876465\n0.05601358413696289\n0.055089473724365234\n0.05696463584899902\n0.05708432197570801\n0.05858302116394043\n0.057578086853027344\n0.05825972557067871\n0.06343364715576172\n0.057315826416015625\n0.05922389030456543\n0.062310218811035156\n0.05640411376953125\n0.055693864822387695\n0.06542158126831055\n0.05596160888671875\n0.055286407470703125\n0.055744171142578125\n0.05676746368408203\n0.0668034553527832\n0.06072568893432617\n0.057178497314453125\n0.05485224723815918\n0.05621957778930664\n0.059195518493652344\n0.05620408058166504\n0.06307435035705566\n0.05738711357116699\n0.05504560470581055\n0.06352996826171875\n0.060955047607421875\n0.056848764419555664\n0.05456733703613281\n0.0610198974609375\n0.05641031265258789\n0.05918121337890625\n0.06076979637145996\n0.05618715286254883\n0.05477595329284668\n0.06147456169128418\n0.06223106384277344\n0.05620884895324707\n0.05920052528381348\n0.057515859603881836\n0.06259012222290039\n0.058393239974975586\n0.061125993728637695\n0.05723428726196289\n0.05588865280151367\n0.058264732360839844\n0.05704760551452637\n0.056654930114746094\n0.056302547454833984\n0.058827877044677734\n0.06162714958190918\n0.06196904182434082\n0.0598444938659668\n0.05711960792541504\n0.0577702522277832\n0.06688857078552246\n0.05556035041809082\n0.05680251121520996\n0.05577731132507324\n0.058623552322387695\n0.05558586120605469\n0.055605173110961914\n0.05608177185058594\n0.05675387382507324\n0.057273149490356445\n0.06119108200073242\n0.055643558502197266\n0.056539058685302734\n0.05531430244445801\n0.054525136947631836\n0.05493664741516113\n0.05668377876281738\n0.05851101875305176\n0.05570554733276367\n0.06048130989074707\n0.05774664878845215\n0.061005592346191406\n0.05623149871826172\n0.23332810401916504\n0.05707049369812012\n0.056960344314575195\n0.056883811950683594\n0.055963754653930664\n0.05774092674255371\n0.058290719985961914\n0.06475520133972168\n0.05641341209411621\n0.05802512168884277\n0.057214975357055664\n0.06195068359375\n0.05763363838195801\n0.06347274780273438\n0.05794095993041992\n0.06308794021606445\n0.05881214141845703\n0.05950307846069336\n0.056975364685058594\n0.055646419525146484\n0.055991172790527344\n0.05549192428588867\n0.06273460388183594\n0.05696558952331543\n0.05576515197753906\n0.05895829200744629\n0.0613703727722168\n0.05551004409790039\n0.056592464447021484\n0.056101083755493164\n0.05400705337524414\n0.056691884994506836\n0.05733060836791992\n0.06358909606933594\n0.05707073211669922\n0.05681800842285156\n0.05564451217651367\n0.06239938735961914\n0.055151939392089844\n0.05618476867675781\n0.05745887756347656\n0.05567121505737305\n0.05550241470336914\n0.06069016456604004\n0.05458641052246094\n0.05510306358337402\n0.05471086502075195\n0.055727481842041016\n0.05682516098022461\n0.05824637413024902\n0.05596661567687988\n0.06122469902038574\n0.055873870849609375\n0.056035757064819336\n0.05711627006530762\n0.05498480796813965\n0.05465364456176758\n0.055663347244262695\n0.055792808532714844\n0.05512714385986328\n0.05595660209655762\n0.05599570274353027\n0.0582277774810791\n0.05866074562072754\n0.05687880516052246\n0.05591702461242676\n0.055886030197143555\n0.05687522888183594\n0.05490994453430176\n0.05500984191894531\n0.05840921401977539\n0.05656123161315918\n0.0572352409362793\n0.05611276626586914\n0.05403566360473633\n0.05588698387145996\n0.054792165756225586\n0.05409860610961914\n0.057665109634399414\n0.056021928787231445\n0.062150001525878906\n0.05646538734436035\n0.05478978157043457\n0.05874991416931152\n0.05644392967224121\n0.05554699897766113\n0.05508303642272949\n0.05516552925109863\n0.05489039421081543\n0.06154227256774902\n0.054238080978393555\n0.05516362190246582\n0.0572659969329834\n0.054902076721191406\n0.05438685417175293\n0.054026126861572266\n0.05589103698730469\n0.056787729263305664\n0.05564689636230469\n0.05633282661437988\n0.05598640441894531\n0.05532073974609375\n0.07011175155639648\n0.05657553672790527\n0.05466127395629883\n0.05606198310852051\n0.0626840591430664\n0.05695223808288574\n0.057584285736083984\n0.05572032928466797\n0.05517101287841797\n0.05461859703063965\n0.054904937744140625\n0.057129621505737305\n0.054566383361816406\n0.054901838302612305\n0.057231903076171875\n0.05941510200500488\n0.05423903465270996\n0.05734825134277344\n0.055680036544799805\n0.0571138858795166\n0.05472612380981445\n0.06428074836730957\n0.05523848533630371\n0.05591607093811035\n0.05518007278442383\n0.05576062202453613\n0.058762311935424805\n0.05456352233886719\n0.05759263038635254\n0.05464744567871094\n0.05398750305175781\n0.05713248252868652\n0.05426287651062012\n0.05549120903015137\n0.05549216270446777\n0.06047630310058594\n0.05632281303405762\n0.05668377876281738\n0.05970430374145508\n0.0571134090423584\n0.054924726486206055\n0.05435466766357422\n0.05529356002807617\n0.05642199516296387\n0.05620932579040527\n0.055056095123291016\n0.054712772369384766\n0.055843353271484375\n0.06041908264160156\n0.055074214935302734\n0.05619215965270996\n0.05827522277832031\n0.05558180809020996\n0.05897641181945801\n0.05540347099304199\n0.05545377731323242\n0.05691838264465332\n0.05457353591918945\n0.054552316665649414\n0.06226158142089844\n0.05360221862792969\n0.054692745208740234\n0.054941654205322266\n0.05458784103393555\n0.05471992492675781\n0.055917978286743164\n0.05489706993103027\n0.05532693862915039\n0.0551607608795166\n0.05707526206970215\n0.05748152732849121\n0.05529642105102539\n0.05334186553955078\n0.05391120910644531\n0.0545651912689209\n0.05549502372741699\n0.053397178649902344\n0.05670523643493652\n0.057393550872802734\n0.06262850761413574\n0.054677486419677734\n0.05673837661743164\n0.05425429344177246\n0.05568742752075195\n0.06077861785888672\n0.05399346351623535\n0.05406594276428223\n0.05514216423034668\n0.05590367317199707\n0.05543112754821777\n0.054468393325805664\n0.05478549003601074\n0.05557584762573242\n0.055555105209350586\n0.0551762580871582\n0.05585741996765137\n0.05663728713989258\n0.06344461441040039\n0.05583643913269043\n0.05598640441894531\n0.05868339538574219\n0.05524945259094238\n0.05728507041931152\n0.05483293533325195\n0.0548710823059082\n0.05661511421203613\n0.05515003204345703\n0.062331438064575195\n0.05572819709777832\n0.05388927459716797\n0.0535123348236084\n0.05870461463928223\n0.05360007286071777\n0.05446767807006836\n0.05453372001647949\n0.05746126174926758\n0.05481433868408203\n0.05793285369873047\n0.05470776557922363\n0.054651498794555664\n0.05597329139709473\n0.05654597282409668\n0.056807756423950195\n0.05589461326599121\n0.05787849426269531\n0.05512213706970215\n0.054511070251464844\n0.054895877838134766\n0.05612802505493164\n0.056221961975097656\n0.054468393325805664\n0.05757498741149902\n0.05483102798461914\n0.054129838943481445\n0.05574178695678711\n0.05481266975402832\n0.05488085746765137\n0.05393195152282715\n0.05408978462219238\n0.055405378341674805\n0.05545687675476074\n0.05611729621887207\n0.0581364631652832\n0.055167436599731445\n0.058889150619506836\n0.057517290115356445\n0.05563974380493164\n0.05547022819519043\n0.055826425552368164\n0.05691981315612793\n0.05487966537475586\n0.05504441261291504\n0.06792497634887695\n0.05617213249206543\n0.06000089645385742\n0.054939985275268555\n0.05547690391540527\n0.05523324012756348\n0.05599164962768555\n0.054320335388183594\n0.05412030220031738\n0.0568850040435791\n0.05439114570617676\n0.05422067642211914\n0.0585484504699707\n0.054964303970336914\n0.0573735237121582\n0.05499076843261719\n0.05441594123840332\n0.05807971954345703\n0.054207563400268555\n0.05919003486633301\n0.05430293083190918\n0.05520820617675781\n0.05456423759460449\n0.05465435981750488\n0.054242849349975586\n0.054819583892822266\n0.0532376766204834\n0.05445575714111328\n0.05333995819091797\n0.056426048278808594\n0.055683135986328125\n0.054025888442993164\n0.05314326286315918\n0.054207563400268555\n0.05582284927368164\n0.05430912971496582\n0.05467939376831055\n0.056581974029541016\n0.05565667152404785\n0.05640435218811035\n0.054964542388916016\n0.05496954917907715\n0.057092905044555664\n0.06329941749572754\n0.057105064392089844\n0.05555272102355957\n0.05852913856506348\n0.05646324157714844\n0.05482983589172363\n0.06365418434143066\n0.055628061294555664\n0.0550539493560791\n0.05656909942626953\n0.058127641677856445\n0.058501243591308594\n0.05524706840515137\n0.05609273910522461\n0.057756900787353516\n0.055605411529541016\n0.06549859046936035\n0.05564475059509277\n0.05907320976257324\n0.06315779685974121\n0.05564069747924805\n0.055373430252075195\n0.05717015266418457\n0.05573892593383789\n0.05770540237426758\n0.056040287017822266\n0.05530548095703125\n0.05526614189147949\n0.054125308990478516\n0.05413103103637695\n0.05529069900512695\n0.05404996871948242\n0.05447649955749512\n0.05733346939086914\n0.05692553520202637\n0.054471492767333984\n0.05434918403625488\n0.05512189865112305\n0.05485248565673828\n0.054796457290649414\n0.059911489486694336\n0.05535578727722168\n0.062259674072265625\n0.057207345962524414\n0.05465984344482422\n0.05467653274536133\n0.05510401725769043\n0.054673194885253906\n0.055278778076171875\n0.054294586181640625\n0.05532073974609375\n0.05550861358642578\n0.05640053749084473\n0.057286739349365234\n0.05685305595397949\n0.061597585678100586\n0.055376529693603516\n0.06129741668701172\n0.05469942092895508\n0.05549454689025879\n0.06334567070007324\n0.05708169937133789\n0.06103920936584473\n0.05958819389343262\n0.061481475830078125\n0.05557441711425781\n0.05559277534484863\n0.0556943416595459\n0.054618120193481445\n0.05802130699157715\n0.056915998458862305\n0.06690287590026855\n0.05617713928222656\n0.05854225158691406\n0.05602860450744629\n0.054289817810058594\n0.0547022819519043\n0.054496049880981445\n0.054988861083984375\n0.054320573806762695\n0.055995941162109375\n0.055309295654296875\n0.05578041076660156\n0.05453801155090332\n0.05426740646362305\n0.0573115348815918\n0.058485984802246094\n0.060033321380615234\n0.05791640281677246\n0.056763648986816406\n0.055873870849609375\n0.054886817932128906\n0.059731245040893555\n0.062009572982788086\n0.056127071380615234\n0.06009936332702637\n0.061502695083618164\n0.05709528923034668\n0.06358647346496582\n0.05775880813598633\n0.05663275718688965\n0.056148529052734375\n0.0587000846862793\n0.055803537368774414\n0.05676531791687012\n0.05905914306640625\n0.06027054786682129\n0.05577492713928223\n0.05527639389038086\n0.0647592544555664\n0.05754661560058594\n0.057672977447509766\n0.05633091926574707\n0.05617499351501465\n0.05703401565551758\n0.05722379684448242\n0.05941653251647949\n0.0560450553894043\n0.05767202377319336\n0.05694270133972168\n0.05716538429260254\n0.054401397705078125\n0.057335853576660156\n0.05468297004699707\n0.060199737548828125\n0.05637359619140625\n0.05730247497558594\n0.060155630111694336\n0.055932044982910156\n0.05548977851867676\n0.056880950927734375\n0.0643777847290039\n0.055379390716552734\n0.060256242752075195\n0.06598806381225586\n0.05626034736633301\n0.05684638023376465\n0.05627131462097168\n0.056708335876464844\n0.06108546257019043\n0.05552554130554199\n0.0587153434753418\n0.05706501007080078\n0.05616164207458496\n0.05690169334411621\n0.05747866630554199\n0.056963443756103516\n0.05908966064453125\n0.06282997131347656\n0.05815553665161133\n0.058388710021972656\n0.05798530578613281\n0.05702805519104004\n0.05488133430480957\n0.0567171573638916\n0.0581204891204834\n0.05738496780395508\n0.05614161491394043\n0.056723833084106445\n0.05662345886230469\n0.05805373191833496\n0.05791664123535156\n0.06249690055847168\n0.05734586715698242\n0.057709455490112305\n0.057163238525390625\n0.05886030197143555\n0.05798840522766113\n0.056281328201293945\n0.05564451217651367\n0.06296610832214355\n0.054840803146362305\n0.05755472183227539\n0.05705666542053223\n0.056310415267944336\n0.05587029457092285\n0.05603361129760742\n0.06239914894104004\n0.056873321533203125\n0.054764509201049805\n0.0576016902923584\n0.05505728721618652\n0.0564875602722168\n0.061376333236694336\n0.05707812309265137\n0.056545257568359375\n0.055856943130493164\n0.06356525421142578\n0.05649614334106445\n0.06403207778930664\n0.05722475051879883\n0.05570173263549805\n0.05577254295349121\n0.056532859802246094\n0.06329751014709473\n0.056746482849121094\n0.06068158149719238\n0.0600733757019043\n0.05675530433654785\n0.05575132369995117\n0.05837225914001465\n0.05633354187011719\n0.06050920486450195\n0.05722689628601074\n0.0587766170501709\n0.05870366096496582\n0.05594491958618164\n0.057398319244384766\n0.05677390098571777\n0.05590987205505371\n0.05625271797180176\n0.056839704513549805\n0.05901956558227539\n0.056729793548583984\n0.05947566032409668\n0.05557727813720703\n0.05616402626037598\n0.05574822425842285\n0.06023454666137695\n0.055779457092285156\n0.055914878845214844\n0.054994821548461914\n0.05536198616027832\n0.054379940032958984\n0.05465865135192871\n0.062380313873291016\n0.054958343505859375\n0.053583383560180664\n0.06146097183227539\n0.05434131622314453\n0.05494523048400879\n0.05444693565368652\n0.055647850036621094\n0.05648350715637207\n0.06421375274658203\n0.061948299407958984\n0.056488037109375\n0.0557553768157959\n0.05718398094177246\n0.05766010284423828\n0.06228518486022949\n0.05704808235168457\n0.05840659141540527\n0.058336734771728516\n0.06181144714355469\n0.05621457099914551\n0.056708335876464844\n0.057421207427978516\n0.057276010513305664\n0.06705784797668457\n0.058484554290771484\n0.05505704879760742\n0.0565187931060791\n0.055205583572387695\n0.05598258972167969\n0.05643010139465332\n0.0626668930053711\n0.05722832679748535\n0.05704140663146973\n0.0574491024017334\n0.05859851837158203\n0.05696415901184082\n0.06106257438659668\n0.06163763999938965\n0.056937217712402344\n0.055376291275024414\n0.055882930755615234\n0.05663561820983887\n0.2204437255859375\n0.05964040756225586\n0.06001925468444824\n0.05478477478027344\n0.056171417236328125\n0.05536603927612305\n0.05561494827270508\n0.05588817596435547\n0.05837130546569824\n0.05630779266357422\n0.05826401710510254\n0.0640709400177002\n0.056348562240600586\n0.05626344680786133\n0.05549335479736328\n0.05533623695373535\n0.056412458419799805\n0.05718851089477539\n0.06468391418457031\n0.05861663818359375\n0.057981014251708984\n0.05614328384399414\n0.05704092979431152\n0.06319808959960938\n0.056795597076416016\n0.05642509460449219\n0.05713057518005371\n0.062171220779418945\n0.05624675750732422\n0.06983184814453125\n0.057037353515625\n0.0639493465423584\n0.06051993370056152\n0.05562925338745117\n0.05899310111999512\n0.05648207664489746\n0.058713436126708984\n0.060834407806396484\n0.061084747314453125\n0.0584719181060791\n0.05789375305175781\n0.06187319755554199\n0.05718111991882324\n0.06301474571228027\n0.060543060302734375\n0.05705976486206055\n0.05696439743041992\n0.055509090423583984\n0.05701637268066406\n0.055052995681762695\n0.05715584754943848\n0.055571794509887695\n0.056490421295166016\n0.055745601654052734\n0.05635571479797363\n0.059678077697753906\n0.06054973602294922\n0.05513572692871094\n0.05492234230041504\n0.06339526176452637\n0.05539894104003906\n0.054696083068847656\n0.054621219635009766\n0.05721020698547363\n0.05589866638183594\n0.06160783767700195\n0.05977892875671387\n0.05609941482543945\n0.055998802185058594\n0.055722951889038086\n0.05647134780883789\n0.05405855178833008\n0.05741167068481445\n0.055459022521972656\n0.06018829345703125\n0.05687069892883301\n0.05690646171569824\n0.05532431602478027\n0.06057310104370117\n0.05479907989501953\n0.055483102798461914\n0.06980156898498535\n0.05560779571533203\n0.055004119873046875\n0.058257102966308594\n0.05485677719116211\n0.05646204948425293\n0.05813956260681152\n0.05613994598388672\n0.053780555725097656\n0.05530977249145508\n0.05379652976989746\n0.06270265579223633\n0.054465293884277344\n0.05428791046142578\n0.05765891075134277\n0.0534214973449707\n0.05504870414733887\n0.05956888198852539\n0.05476689338684082\n0.05497932434082031\n0.06091713905334473\n0.055332183837890625\n0.05787968635559082\n0.05842852592468262\n0.05455946922302246\n0.05435943603515625\n0.053406476974487305\n0.05202031135559082\n0.050881147384643555\n0.05292081832885742\n0.054436445236206055\n0.05558371543884277\n0.053435325622558594\n0.05435442924499512\n0.06367707252502441\n0.05214977264404297\n0.05004429817199707\n0.05569314956665039\n0.05193305015563965\n0.052855491638183594\n0.04978752136230469\n0.05094790458679199\n0.05111980438232422\n0.05097150802612305\n0.05113029479980469\n0.050150156021118164\n0.05104565620422363\n0.05292224884033203\n0.049854278564453125\n0.05054783821105957\n0.05028510093688965\n0.05053353309631348\n0.05122017860412598\n0.050234317779541016\n0.05578303337097168\n0.05044221878051758\n0.05504274368286133\n0.053557634353637695\n0.05202078819274902\n0.052950143814086914\n0.05238151550292969\n0.054557085037231445\n0.052381038665771484\n0.054702043533325195\n0.05151820182800293\n0.05366706848144531\n0.05185723304748535\n0.05272078514099121\n0.05450916290283203\n0.05678153038024902\n0.052169084548950195\n0.05181312561035156\n0.052295684814453125\n0.053644418716430664\n0.05686783790588379\n0.05281186103820801\n0.053611040115356445\n0.052700042724609375\n0.05386924743652344\n0.05341911315917969\n0.05228281021118164\n0.05087637901306152\n0.05828070640563965\n0.0517582893371582\n0.05099344253540039\n0.05564475059509277\n0.05099320411682129\n0.05147957801818848\n0.05105257034301758\n0.051766157150268555\n0.05338001251220703\n0.05062460899353027\n0.05225062370300293\n0.05191636085510254\n0.05175209045410156\n0.051896095275878906\n0.05195021629333496\n0.05279088020324707\n0.05202984809875488\n0.05281209945678711\n0.05235433578491211\n0.05285239219665527\n0.053403377532958984\n0.05291247367858887\n0.05253148078918457\n0.053995370864868164\n0.060057878494262695\n0.052461862564086914\n0.0528414249420166\n0.05910897254943848\n0.05433773994445801\n0.05644726753234863\n0.05661511421203613\n0.05352616310119629\n0.05356454849243164\n0.05603313446044922\n0.05386209487915039\n0.05265402793884277\n0.05243062973022461\n0.055243492126464844\n0.0537562370300293\n0.05385613441467285\n0.05511808395385742\n0.05346035957336426\n0.052633047103881836\n0.06139206886291504\n0.052968502044677734\n0.05963897705078125\n0.05209183692932129\n0.0522761344909668\n0.05135989189147949\n0.05497884750366211\n0.05254197120666504\n0.05196189880371094\n0.06098461151123047\n0.05729556083679199\n0.05267024040222168\n0.05434083938598633\n0.05283403396606445\n0.054573774337768555\n0.0520479679107666\n0.05986976623535156\n0.05412650108337402\n0.05365896224975586\n0.05804634094238281\n0.05340313911437988\n0.05442667007446289\n0.06438827514648438\n0.054443359375\n0.054158687591552734\n0.05432868003845215\n0.05376267433166504\n0.056693315505981445\n0.05515480041503906\n0.05615377426147461\n0.06218242645263672\n0.05567288398742676\n0.059059858322143555\n0.05413651466369629\n0.05422639846801758\n0.055190086364746094\n0.05674314498901367\n0.054653167724609375\n0.05376839637756348\n0.05347275733947754\n0.0590059757232666\n0.05588555335998535\n0.05789637565612793\n0.05423092842102051\n0.05831742286682129\n0.05407285690307617\n0.05438971519470215\n0.05394482612609863\n0.05549478530883789\n0.05403256416320801\n0.05559515953063965\n0.05359387397766113\n0.05543112754821777\n0.05389237403869629\n0.05401015281677246\n0.052353858947753906\n0.06094765663146973\n0.06159806251525879\n0.05382251739501953\n0.059145450592041016\n0.05489659309387207\n0.05996108055114746\n0.05335211753845215\n0.053023338317871094\n0.05699801445007324\n0.05362343788146973\n0.05756330490112305\n0.05394291877746582\n0.05913281440734863\n0.055310726165771484\n0.05427050590515137\n0.058165788650512695\n0.05499911308288574\n0.05344057083129883\n0.05924701690673828\n0.05451035499572754\n0.06050872802734375\n0.05424809455871582\n0.05422663688659668\n0.05468606948852539\n0.05537557601928711\n0.05758333206176758\n0.05645012855529785\n0.05392122268676758\n0.05473947525024414\n0.05387759208679199\n0.05545401573181152\n0.054671287536621094\n0.055591583251953125\n0.05435442924499512\n0.0574336051940918\n0.05278658866882324\n0.05547332763671875\n0.05422186851501465\n0.05541872978210449\n0.0545504093170166\n0.054421424865722656\n0.05452299118041992\n0.05571937561035156\n0.05598902702331543\n0.05545186996459961\n0.05443596839904785\n0.0571441650390625\n0.05469632148742676\n0.05552935600280762\n0.055156707763671875\n0.05677390098571777\n0.054273366928100586\n0.055661678314208984\n0.05426645278930664\n0.060638427734375\n0.053673505783081055\n0.05506634712219238\n0.053818702697753906\n0.05828094482421875\n0.057105064392089844\n0.06598281860351562\n0.054276466369628906\n0.05486416816711426\n0.054764509201049805\n0.05519247055053711\n0.05365467071533203\n0.05559420585632324\n0.05666971206665039\n0.053785085678100586\n0.053626298904418945\n0.06138277053833008\n0.05369901657104492\n0.052663564682006836\n0.05737137794494629\n0.055492401123046875\n0.06456518173217773\n0.05460715293884277\n0.05306291580200195\n0.053858041763305664\n0.053060054779052734\n0.05361318588256836\n0.052713871002197266\n0.05298781394958496\n0.05470609664916992\n0.0553278923034668\n0.05367684364318848\n0.05407452583312988\n0.05360007286071777\n0.05837202072143555\n0.05620837211608887\n0.05424690246582031\n0.059094905853271484\n0.05420565605163574\n0.05677390098571777\n0.05578207969665527\n0.05995035171508789\n0.05912637710571289\n0.05747652053833008\n0.05420827865600586\n0.05440044403076172\n0.05551338195800781\n0.05502820014953613\n0.0572049617767334\n0.06058669090270996\n0.05542635917663574\n0.054815053939819336\n0.054775238037109375\n0.05534100532531738\n0.05488705635070801\n0.05640125274658203\n0.05469560623168945\n0.0590205192565918\n0.05922555923461914\n0.055391550064086914\n0.057123661041259766\n0.053847551345825195\n0.05469465255737305\n0.05364394187927246\n0.05403614044189453\n0.05411028861999512\n0.05393266677856445\n0.05399751663208008\n0.05994558334350586\n0.06040620803833008\n0.05435538291931152\n0.05768609046936035\n0.05487203598022461\n0.056783437728881836\n0.05533313751220703\n0.05477452278137207\n0.05552840232849121\n0.05665445327758789\n0.05900764465332031\n0.054863691329956055\n0.054351806640625\n0.05516862869262695\n0.05400371551513672\n0.05287981033325195\n0.05851125717163086\n0.053637027740478516\n0.053908348083496094\n0.0573885440826416\n0.057369232177734375\n0.062027692794799805\n0.054186105728149414\n0.052535295486450195\n0.05416274070739746\n0.05264759063720703\n0.05854606628417969\n0.05428194999694824\n0.05531454086303711\n0.0519561767578125\n0.05643320083618164\n0.053261756896972656\n0.05446624755859375\n0.052384138107299805\n0.05592489242553711\n0.05122637748718262\n0.05835890769958496\n0.05198335647583008\n0.058873891830444336\n0.05183696746826172\n0.060484886169433594\n0.054897308349609375\n0.05245566368103027\n0.05614757537841797\n0.051750898361206055\n0.05157160758972168\n0.052756547927856445\n0.05044913291931152\n0.05072426795959473\n0.05115818977355957\n0.05047035217285156\n0.05117177963256836\n0.05033063888549805\n0.04989933967590332\n0.05156254768371582\n0.055136919021606445\n0.0523838996887207\n0.05319070816040039\n0.05426216125488281\n0.05213642120361328\n0.06415534019470215\n0.05731320381164551\n0.05271649360656738\n0.05304431915283203\n0.05256056785583496\n0.051213979721069336\n0.05476546287536621\n0.055212974548339844\n0.054924964904785156\n0.053934574127197266\n0.05826973915100098\n0.059113264083862305\n0.05537819862365723\n0.054059505462646484\n0.05420875549316406\n0.053821563720703125\n0.05668807029724121\n0.05918169021606445\n0.05443120002746582\n0.058867454528808594\n0.058073997497558594\n0.057915687561035156\n0.05750131607055664\n0.054589033126831055\n0.05384516716003418\n0.0541539192199707\n0.05488109588623047\n0.05344223976135254\n0.05873465538024902\n0.056640625\n0.055220842361450195\n0.05579781532287598\n0.05601930618286133\n0.054274797439575195\n0.05585002899169922\n0.05466818809509277\n0.0553891658782959\n0.0548403263092041\n0.056806087493896484\n0.05709218978881836\n0.054762840270996094\n0.05709123611450195\n0.056099891662597656\n0.057611942291259766\n0.05706954002380371\n0.05597710609436035\n0.05586552619934082\n0.0560154914855957\n0.06146860122680664\n0.05877113342285156\n0.05742001533508301\n0.057098388671875\n0.06220293045043945\n0.05627179145812988\n0.0577089786529541\n0.054897308349609375\n0.05757570266723633\n0.057291269302368164\n0.05729365348815918\n0.06380343437194824\n0.05732321739196777\n0.05741429328918457\n0.06144547462463379\n0.056952714920043945\n0.06380009651184082\n0.055703163146972656\n0.055880069732666016\n0.05650019645690918\n0.06237220764160156\n0.056150197982788086\n0.05935502052307129\n0.05614304542541504\n0.0575556755065918\n0.06232452392578125\n0.0562891960144043\n0.05510854721069336\n0.05862116813659668\n0.0574498176574707\n0.05698657035827637\n0.0553433895111084\n0.05674457550048828\n0.05692005157470703\n0.05684971809387207\n0.05549788475036621\n0.057152748107910156\n0.05506539344787598\n0.05908036231994629\n0.05557060241699219\n0.05683708190917969\n0.058104515075683594\n0.057184457778930664\n0.05502009391784668\n0.05562901496887207\n0.060433387756347656\n0.0556027889251709\n0.05667519569396973\n0.056355953216552734\n0.056456565856933594\n0.05930352210998535\n0.058028221130371094\n0.05607199668884277\n0.05797266960144043\n0.05638766288757324\n0.05711054801940918\n0.055927276611328125\n0.057631731033325195\n0.05802559852600098\n0.056192636489868164\n0.05845332145690918\n0.05660247802734375\n0.05593252182006836\n0.05576276779174805\n0.05725264549255371\n0.05675101280212402\n0.057439327239990234\n0.06266331672668457\n0.05667853355407715\n0.05706310272216797\n0.057006120681762695\n0.05925726890563965\n0.21680951118469238\n0.05649232864379883\n0.06243753433227539\n0.05865907669067383\n0.06335616111755371\n0.058999061584472656\n0.06247568130493164\n0.059297800064086914\n0.05896472930908203\n0.05779767036437988\n0.05846834182739258\n0.0565335750579834\n0.057326316833496094\n0.05532336235046387\n0.05653953552246094\n0.05533003807067871\n0.06158089637756348\n0.05870556831359863\n0.05859947204589844\n0.05703473091125488\n0.05763864517211914\n0.06118583679199219\n0.05699610710144043\n0.05681252479553223\n0.06574821472167969\n0.057732343673706055\n0.057525634765625\n0.05717921257019043\n0.061158180236816406\n0.056243181228637695\n0.05609750747680664\n0.0669407844543457\n0.06244850158691406\n0.05799078941345215\n0.05606865882873535\n0.05641770362854004\n0.05556893348693848\n0.06298661231994629\n0.06159853935241699\n0.056224822998046875\n0.05643749237060547\n0.054968833923339844\n0.06370735168457031\n0.056336402893066406\n0.0558779239654541\n0.06038832664489746\n0.05613279342651367\n0.0561826229095459\n0.055474042892456055\n0.055158376693725586\n0.055594444274902344\n0.055123329162597656\n0.06827211380004883\n0.05612826347351074\n0.05534052848815918\n0.05664563179016113\n0.05671262741088867\n0.05591106414794922\n0.05560612678527832\n0.05599474906921387\n0.05733084678649902\n0.05638003349304199\n0.05943751335144043\n0.059916019439697266\n0.05826544761657715\n0.05946469306945801\n0.0586247444152832\n0.06319761276245117\n0.06339836120605469\n0.05638313293457031\n0.0645749568939209\n0.05792379379272461\n0.05944347381591797\n0.056772708892822266\n0.056325435638427734\n0.0635988712310791\n0.055815696716308594\n0.056250810623168945\n0.05876493453979492\n0.05768632888793945\n0.057108163833618164\n0.05621910095214844\n0.06392407417297363\n0.05664682388305664\n0.05737709999084473\n0.05842399597167969\n0.05652570724487305\n0.06178617477416992\n0.05706501007080078\n0.056378841400146484\n0.06789112091064453\n0.05621671676635742\n0.0563359260559082\n0.05661511421203613\n0.05697512626647949\n0.05835843086242676\n0.06790566444396973\n0.055498600006103516\n0.06132793426513672\n0.05589032173156738\n0.05829119682312012\n0.0619044303894043\n0.055234432220458984\n0.06209206581115723\n0.05539298057556152\n0.05634140968322754\n0.05542278289794922\n0.05654287338256836\n0.054831504821777344\n0.05725526809692383\n0.05420970916748047\n0.055475473403930664\n0.054749250411987305\n0.055368900299072266\n0.05646395683288574\n0.05584526062011719\n0.05939364433288574\n0.05551481246948242\n0.05553460121154785\n0.05641365051269531\n0.05647540092468262\n0.06745624542236328\n0.05586361885070801\n0.05496048927307129\n0.056075334548950195\n0.05593228340148926\n0.06096053123474121\n0.05553412437438965\n0.056070804595947266\n0.05611896514892578\n0.0554502010345459\n0.05533719062805176\n0.057263851165771484\n0.054187774658203125\n0.06264185905456543\n0.05566287040710449\n0.05559849739074707\n0.057311296463012695\n0.0549921989440918\n0.054708003997802734\n0.057123422622680664\n0.05674910545349121\n0.06096148490905762\n0.05812525749206543\n0.05722975730895996\n0.07008910179138184\n0.060426950454711914\n0.05645585060119629\n0.05714750289916992\n0.05687069892883301\n0.055441856384277344\n0.054968833923339844\n0.05686783790588379\n0.05692481994628906\n0.058236122131347656\n0.05571413040161133\n0.057393789291381836\n0.05404090881347656\n0.05478191375732422\n0.06195402145385742\n0.057038068771362305\n0.057953834533691406\n0.06200075149536133\n0.05631208419799805\n0.05564689636230469\n0.06178140640258789\n0.058574676513671875\n0.05692291259765625\n0.05581808090209961\n0.05481576919555664\n0.056498050689697266\n0.05614590644836426\n0.06092691421508789\n0.05600476264953613\n0.05962514877319336\n0.05668973922729492\n0.05730772018432617\n0.055742502212524414\n0.05645108222961426\n0.05719900131225586\n0.05997800827026367\n0.05852103233337402\n0.05679678916931152\n0.05923128128051758\n0.05788445472717285\n0.054849863052368164\n0.06846952438354492\n0.05633211135864258\n0.05766582489013672\n0.05737018585205078\n0.05658364295959473\n0.05693316459655762\n0.0569911003112793\n0.06980228424072266\n0.05571126937866211\n0.056691646575927734\n0.05650138854980469\n0.058913230895996094\n0.05594968795776367\n0.062215328216552734\n0.0560297966003418\n0.05977439880371094\n0.05554366111755371\n0.05511331558227539\n0.056296348571777344\n0.055011749267578125\n0.06513285636901855\n0.0586392879486084\n0.05736947059631348\n0.061567068099975586\n0.05640816688537598\n0.05613398551940918\n0.05657792091369629\n0.06331539154052734\n0.058176279067993164\n0.05873441696166992\n0.06189322471618652\n0.056296586990356445\n0.05670428276062012\n0.05966901779174805\n0.06508517265319824\n0.05741691589355469\n0.06237316131591797\n0.06317472457885742\n0.05717301368713379\n0.0629892349243164\n0.05763578414916992\n0.06366229057312012\n0.06176877021789551\n0.05621743202209473\n0.05876803398132324\n0.05471038818359375\n0.05672955513000488\n0.05803394317626953\n0.05880880355834961\n0.06474637985229492\n0.057482242584228516\n0.05522632598876953\n0.05722618103027344\n0.06021690368652344\n0.05635857582092285\n0.05552101135253906\n0.06372594833374023\n0.05744791030883789\n0.05514979362487793\n0.060182809829711914\n0.06589150428771973\n0.05597567558288574\n0.05774378776550293\n0.056571245193481445\n0.05559968948364258\n0.06082653999328613\n0.058748722076416016\n0.060617923736572266\n0.06379532814025879\n0.05717587471008301\n0.060797691345214844\n0.05755496025085449\n0.05977749824523926\n0.059188127517700195\n0.0600128173828125\n0.06358885765075684\n0.058989763259887695\n0.06241154670715332\n0.05790853500366211\n0.056847333908081055\n0.056852102279663086\n0.05715775489807129\n0.05661344528198242\n0.05992388725280762\n0.060417890548706055\n0.05636763572692871\n0.05668377876281738\n0.057233333587646484\n0.05940580368041992\n0.05584526062011719\n0.060083627700805664\n0.05678963661193848\n0.060907840728759766\n0.057778358459472656\n0.05871176719665527\n0.05586123466491699\n0.057054758071899414\n0.05892372131347656\n0.056903839111328125\n0.05387377738952637\n0.057617902755737305\n0.060315608978271484\n0.05630779266357422\n0.06323838233947754\n0.05810213088989258\n0.05679798126220703\n0.05622744560241699\n0.055887460708618164\n0.05714535713195801\n0.0563349723815918\n0.05746865272521973\n0.05854010581970215\n0.06518077850341797\n0.05711936950683594\n0.0688331127166748\n0.056096792221069336\n0.0568079948425293\n0.06424212455749512\n0.0577692985534668\n0.05911421775817871\n0.059223175048828125\n0.05717778205871582\n0.05942058563232422\n0.06300616264343262\n0.057373762130737305\n0.05914735794067383\n0.05696678161621094\n0.06281733512878418\n0.05595088005065918\n0.059448957443237305\n0.060248613357543945\n0.056494951248168945\n0.0567326545715332\n0.05834841728210449\n0.05659317970275879\n0.05637311935424805\n0.06355667114257812\n0.05742073059082031\n0.0574643611907959\n0.05619239807128906\n0.06358885765075684\n0.05700874328613281\n0.05698966979980469\n0.059670448303222656\n0.057279109954833984\n0.06028914451599121\n0.057936906814575195\n0.058672428131103516\n0.058692216873168945\n0.05676984786987305\n0.05770373344421387\n0.05588030815124512\n0.06333661079406738\n0.05624032020568848\n0.05665016174316406\n0.06538248062133789\n0.057717084884643555\n0.05808615684509277\n0.058638572692871094\n0.05619668960571289\n0.0646200180053711\n0.05633831024169922\n0.056768178939819336\n0.05764007568359375\n0.059067726135253906\n0.059320926666259766\n0.05715608596801758\n0.06993365287780762\n0.06684994697570801\n0.057034969329833984\n0.0595240592956543\n0.057057857513427734\n0.05900168418884277\n0.05746054649353027\n0.05707716941833496\n0.05734610557556152\n0.05654430389404297\n0.05466437339782715\n0.05982232093811035\n0.06148719787597656\n0.057091474533081055\n0.05915212631225586\n0.05724024772644043\n0.0687265396118164\n0.0575556755065918\n0.05686593055725098\n0.05655503273010254\n0.05605936050415039\n0.05945396423339844\n0.06308770179748535\n0.060576677322387695\n0.0579986572265625\n0.057797908782958984\n0.05562329292297363\n0.0561823844909668\n0.05838656425476074\n0.056206464767456055\n0.05937361717224121\n0.06105375289916992\n0.06310725212097168\n0.05681157112121582\n0.05661630630493164\n0.05700802803039551\n0.05515265464782715\n0.06084704399108887\n0.05988359451293945\n0.05893111228942871\n0.06604886054992676\n0.0575408935546875\n0.056716203689575195\n0.05646347999572754\n0.06034994125366211\n0.05827665328979492\n0.057567596435546875\n0.058014631271362305\n0.057829856872558594\n0.05900740623474121\n0.06337475776672363\n0.05657792091369629\n0.057190895080566406\n0.05684208869934082\n0.06906747817993164\n0.05668473243713379\n0.05615520477294922\n0.06452703475952148\n0.057416677474975586\n0.05748391151428223\n0.0558626651763916\n0.05631446838378906\n0.05654597282409668\n0.055739402770996094\n0.05676603317260742\n0.05696916580200195\n0.06766510009765625\n0.05789351463317871\n0.05535101890563965\n0.05585765838623047\n0.059954166412353516\n0.055927276611328125\n0.05592703819274902\n0.06335735321044922\n0.05792093276977539\n0.059235334396362305\n0.05885481834411621\n0.0643160343170166\n0.05946636199951172\n0.05566692352294922\n0.06186199188232422\n0.056149959564208984\n0.05814862251281738\n0.056652069091796875\n0.05736970901489258\n0.057566165924072266\n0.06321430206298828\n0.05728912353515625\n0.05694913864135742\n0.056880950927734375\n0.05643272399902344\n0.05621075630187988\n0.05721879005432129\n0.05729198455810547\n0.06179618835449219\n0.056740760803222656\n0.05897998809814453\n0.06859087944030762\n0.0583193302154541\n0.05669379234313965\n0.0562434196472168\n0.06423234939575195\n0.05739855766296387\n0.058423519134521484\n0.05956530570983887\n0.06189918518066406\n0.05558037757873535\n0.05575108528137207\n0.054288387298583984\n0.05703234672546387\n0.07036256790161133\n0.05600929260253906\n0.055787086486816406\n0.056122541427612305\n0.06550192832946777\n0.057485342025756836\n0.05468297004699707\n0.05939841270446777\n0.05510759353637695\n0.05684828758239746\n0.06010746955871582\n0.054831504821777344\n0.056560516357421875\n0.05510592460632324\n0.056395769119262695\n0.0654146671295166\n0.05494379997253418\n0.06571435928344727\n0.06133437156677246\n0.05704998970031738\n0.057526350021362305\n0.055359840393066406\n0.055728912353515625\n0.061675071716308594\n0.05605268478393555\n0.05658984184265137\n0.056551456451416016\n0.05575442314147949\n0.05726313591003418\n0.056231021881103516\n0.0559840202331543\n0.061411380767822266\n0.05695843696594238\n0.05686783790588379\n0.05691242218017578\n0.062497854232788086\n0.05662035942077637\n0.058997392654418945\n0.05852007865905762\n0.056128501892089844\n0.05898404121398926\n0.05896115303039551\n0.05959177017211914\n0.05637216567993164\n0.061533212661743164\n0.05641007423400879\n0.056967973709106445\n0.05561256408691406\n0.05744624137878418\n0.06081032752990723\n0.05576348304748535\n0.05472874641418457\n0.05465102195739746\n0.05954694747924805\n0.056159257888793945\n0.057085514068603516\n0.05721712112426758\n0.055326223373413086\n0.06518793106079102\n0.05567479133605957\n0.05578327178955078\n0.05756354331970215\n0.06572818756103516\n0.05779409408569336\n0.055658817291259766\n0.05685305595397949\n0.0583038330078125\n0.06221175193786621\n0.055171966552734375\n0.055587053298950195\n0.05760025978088379\n0.06595349311828613\n0.056633949279785156\n0.06587409973144531\n0.06331872940063477\n0.05826377868652344\n0.05752253532409668\n0.057715415954589844\n0.05929875373840332\n0.05678963661193848\n0.0556485652923584\n0.06373786926269531\n0.05567646026611328\n0.05759572982788086\n0.06619596481323242\n0.056508541107177734\n0.05615234375\n0.05574154853820801\n0.056574106216430664\n0.05870652198791504\n0.05915212631225586\n0.05647420883178711\n0.05915999412536621\n0.05757284164428711\n0.054917097091674805\n0.05658149719238281\n0.056772470474243164\n0.05807971954345703\n0.05998992919921875\n0.055417537689208984\n0.05500984191894531\n0.2353057861328125\n0.05541372299194336\n0.056815147399902344\n0.056853532791137695\n0.06258106231689453\n0.06591963768005371\n0.05823564529418945\n0.05526566505432129\n0.055902957916259766\n0.05892658233642578\n0.058099985122680664\n0.05551886558532715\n0.05686354637145996\n0.06087088584899902\n0.0565028190612793\n0.05782270431518555\n0.059140920639038086\n0.05624818801879883\n0.058286190032958984\n0.056730031967163086\n0.06008791923522949\n0.056261539459228516\n0.05641674995422363\n0.06134366989135742\n0.054939985275268555\n0.05501914024353027\n0.05860447883605957\n0.05599856376647949\n0.05618548393249512\n0.055223703384399414\n0.05638265609741211\n0.05618739128112793\n0.05525779724121094\n0.05872082710266113\n0.06282281875610352\n0.05825686454772949\n0.05608725547790527\n0.05596494674682617\n0.05670619010925293\n0.05621767044067383\n0.0552830696105957\n0.05478191375732422\n0.060576677322387695\n0.05755734443664551\n0.05703902244567871\n0.05499148368835449\n0.05642080307006836\n0.0650167465209961\n0.05575108528137207\n0.0558164119720459\n0.0556490421295166\n0.055084943771362305\n0.062352895736694336\n0.05647087097167969\n0.05690765380859375\n0.0557248592376709\n0.05592489242553711\n0.061844825744628906\n0.05689859390258789\n0.05556631088256836\n0.05960273742675781\n0.05700516700744629\n0.056615591049194336\n0.056379079818725586\n0.05655980110168457\n0.056702375411987305\n0.061067819595336914\n0.05473661422729492\n0.05759072303771973\n0.061661481857299805\n0.05571699142456055\n0.05565214157104492\n0.055182456970214844\n0.05534720420837402\n0.06016111373901367\n0.05552530288696289\n0.05581855773925781\n0.056549787521362305\n0.05736398696899414\n0.0564427375793457\n0.05675244331359863\n0.06406688690185547\n0.05797576904296875\n0.056867361068725586\n0.05979514122009277\n0.05873441696166992\n0.055895328521728516\n0.05535554885864258\n0.05637526512145996\n0.05569887161254883\n0.05864214897155762\n0.05551266670227051\n0.056511878967285156\n0.06172966957092285\n0.0635683536529541\n0.05598902702331543\n0.05550861358642578\n0.054497718811035156\n0.05620169639587402\n0.05932283401489258\n0.05642271041870117\n0.06203746795654297\n0.05587267875671387\n0.05582785606384277\n0.05588102340698242\n0.057643890380859375\n0.056143999099731445\n0.055672407150268555\n0.05574750900268555\n0.05890178680419922\n0.05614018440246582\n0.05652666091918945\n0.06466364860534668\n0.05757880210876465\n0.05656242370605469\n0.05695176124572754\n0.05645895004272461\n0.06088519096374512\n0.057579755783081055\n0.05548286437988281\n0.056259870529174805\n0.061004638671875\n0.057578086853027344\n0.05623459815979004\n0.05638694763183594\n0.06030535697937012\n0.06279921531677246\n0.05666327476501465\n0.05557441711425781\n0.05652189254760742\n0.05569767951965332\n0.06477665901184082\n0.055321455001831055\n0.05753183364868164\n0.05511164665222168\n0.06314444541931152\n0.05903959274291992\n0.05876755714416504\n0.06008625030517578\n0.06321358680725098\n0.056937456130981445\n0.05527067184448242\n0.0557246208190918\n0.05635952949523926\n0.05550265312194824\n0.05490612983703613\n0.05564379692077637\n0.05712246894836426\n0.06181526184082031\n0.054749488830566406\n0.055478811264038086\n0.056056976318359375\n0.0547943115234375\n0.0555417537689209\n0.055162668228149414\n0.05433535575866699\n0.05523371696472168\n0.058457374572753906\n0.06041121482849121\n0.05662989616394043\n0.05989813804626465\n0.055835723876953125\n0.055891990661621094\n0.058393001556396484\n0.0586848258972168\n0.05637097358703613\n0.05929875373840332\n0.05744361877441406\n0.05794811248779297\n0.05710768699645996\n0.06352591514587402\n0.0563814640045166\n0.055651187896728516\n0.0604097843170166\n0.05832791328430176\n0.0650472640991211\n0.05597805976867676\n0.06467986106872559\n0.05791592597961426\n0.05572152137756348\n0.06519198417663574\n0.05905032157897949\n0.06047964096069336\n0.05637311935424805\n0.05659747123718262\n0.05900764465332031\n0.05649161338806152\n0.055588722229003906\n0.05681896209716797\n0.05514669418334961\n0.05486106872558594\n0.05902218818664551\n0.05688071250915527\n0.0557713508605957\n0.05588698387145996\n0.06331872940063477\n0.05665302276611328\n0.054666757583618164\n0.05939149856567383\n0.056439876556396484\n0.05834484100341797\n0.0588374137878418\n0.05620312690734863\n0.05910229682922363\n0.05786848068237305\n0.057575225830078125\n0.05859541893005371\n0.056029558181762695\n0.05786633491516113\n0.06466484069824219\n0.05842781066894531\n0.05668759346008301\n0.05709958076477051\n0.061248064041137695\n0.05737948417663574\n0.0576322078704834\n0.05826830863952637\n0.0576171875\n0.056525230407714844\n0.06167125701904297\n0.05967116355895996\n0.05766463279724121\n0.057880401611328125\n0.05624866485595703\n0.05727577209472656\n0.05767655372619629\n0.06451749801635742\n0.05602288246154785\n0.057599544525146484\n0.056963205337524414\n0.05977606773376465\n0.05716371536254883\n0.05759096145629883\n0.05807304382324219\n0.05745410919189453\n0.06531095504760742\n0.05991983413696289\n0.05605030059814453\n0.06510114669799805\n0.056713104248046875\n0.05798816680908203\n0.05580401420593262\n0.06526660919189453\n0.05859065055847168\n0.05704069137573242\n0.05521798133850098\n0.05489778518676758\n0.05635809898376465\n0.058531999588012695\n0.05725407600402832\n0.05799388885498047\n0.05642247200012207\n0.05731773376464844\n0.07384419441223145\n0.06261539459228516\n0.05823230743408203\n0.05571627616882324\n0.0567319393157959\n0.06875419616699219\n0.05740833282470703\n0.05726194381713867\n0.0589900016784668\n0.057007551193237305\n0.05682659149169922\n0.057970523834228516\n0.061241865158081055\n0.05597257614135742\n0.059159278869628906\n0.05671572685241699\n0.05568718910217285\n0.05688190460205078\n0.056711435317993164\n0.056777238845825195\n0.05798602104187012\n0.05934309959411621\n0.058847665786743164\n0.058267831802368164\n0.06528162956237793\n0.05726122856140137\n0.05818629264831543\n0.061922311782836914\n0.05677604675292969\n0.05675768852233887\n0.05580592155456543\n0.05701851844787598\n0.05713772773742676\n0.05554986000061035\n0.0635533332824707\n0.06346774101257324\n0.057894229888916016\n0.06146383285522461\n0.05497550964355469\n0.05701947212219238\n0.06258320808410645\n0.05890250205993652\n0.05679726600646973\n0.056584835052490234\n0.05753636360168457\n0.0615391731262207\n0.05738711357116699\n0.05727696418762207\n0.0657951831817627\n0.05780959129333496\n0.05761551856994629\n0.05774402618408203\n0.05678677558898926\n0.0600125789642334\n0.05662989616394043\n0.05626535415649414\n0.05560755729675293\n0.0628666877746582\n0.05707526206970215\n0.05803108215332031\n0.05932188034057617\n0.056380510330200195\n0.05977964401245117\n0.05777764320373535\n0.06386899948120117\n0.05515313148498535\n0.05601811408996582\n0.0644993782043457\n0.05750322341918945\n0.05760002136230469\n0.057656288146972656\n0.0598752498626709\n0.06312680244445801\n0.05872535705566406\n0.057650089263916016\n0.05831432342529297\n0.05640268325805664\n0.07268834114074707\n0.05527782440185547\n0.05571293830871582\n0.057828426361083984\n0.05787801742553711\n0.06086540222167969\n0.05773425102233887\n0.0571441650390625\n0.06699442863464355\n0.057829856872558594\n0.06081819534301758\n0.0557403564453125\n0.05609774589538574\n0.05791306495666504\n0.05813884735107422\n0.057732343673706055\n0.05823373794555664\n0.05681157112121582\n0.059511423110961914\n0.06000781059265137\n0.058968544006347656\n0.06267094612121582\n0.05737805366516113\n0.057822465896606445\n0.05852985382080078\n0.06393885612487793\n0.05977988243103027\n0.05730867385864258\n0.05863142013549805\n0.05657219886779785\n0.05634331703186035\n0.06399321556091309\n0.05896711349487305\n0.06917977333068848\n0.061673879623413086\n0.06541562080383301\n0.05774974822998047\n0.0621488094329834\n0.05846667289733887\n0.06075119972229004\n0.059583425521850586\n0.05976605415344238\n0.057465553283691406\n0.0566563606262207\n0.06054067611694336\n0.05663418769836426\n0.058875083923339844\n0.05773448944091797\n0.05649685859680176\n0.05599045753479004\n0.06790852546691895\n0.05670738220214844\n0.0559694766998291\n0.05457758903503418\n0.06006574630737305\n0.05848073959350586\n0.05652904510498047\n0.057430267333984375\n0.058283090591430664\n0.057973384857177734\n0.059969425201416016\n0.057660579681396484\n0.05611300468444824\n0.055881500244140625\n0.05640888214111328\n0.056321144104003906\n0.055864572525024414\n0.05718994140625\n0.05796980857849121\n0.05475735664367676\n0.05657625198364258\n0.05515432357788086\n0.055597543716430664\n0.05431008338928223\n0.0558319091796875\n0.05521535873413086\n0.059241533279418945\n0.05855512619018555\n" ], [ "cp result.mp4 /content/drive/MyDrive/", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbe44dcfacc7f7a869e7a0b34d7c33b2388de497
317,823
ipynb
Jupyter Notebook
Notebooks/4. Model | Google Word2Vec | Multi Variable Weighted Method.ipynb
iamdv/mooc-recommender
93c1c199f72bda59820669965f0e36e6e8c88132
[ "MIT" ]
6
2019-04-02T04:11:07.000Z
2020-12-26T10:30:05.000Z
Notebooks/4. Model | Google Word2Vec | Multi Variable Weighted Method.ipynb
iamdv/mooc-recommender
93c1c199f72bda59820669965f0e36e6e8c88132
[ "MIT" ]
null
null
null
Notebooks/4. Model | Google Word2Vec | Multi Variable Weighted Method.ipynb
iamdv/mooc-recommender
93c1c199f72bda59820669965f0e36e6e8c88132
[ "MIT" ]
null
null
null
46.8973
212
0.398678
[ [ [ "###### Name: Deepak Vadithala\n###### Course: MSc Data Science\n###### Project Name: MOOC Recommender System\n\n##### Notes:\nThis notebook contains the analysis of the **Google's Word2Vec** model. This model is trained on the news articles. \ntwo variable **(Role and Skill Scores)** is used to predict the course category. \nSkill Score is calculated using the similarity between the skills from LinkedIn compared with the course description with keywords from Coursera.\n\n\n*Model Source Code Path: /mooc-recommender/Model/Cosine_Distance.py*\n\n*Github Repo: https://github.com/iamdv/mooc-recommender*", "_____no_output_____" ] ], [ [ "# **************************** IMPORTANT ****************************\n'''\nThis cell configuration settings for the Notebook. \nYou can run one role at a time to evaluate the performance of the model\nChange the variable names to run for multiple roles\n\nIn this model:\n1. Google word2vec model has two variables Roles and Skills with \n50% weightage for each\n'''\n\n# *******************************************************************\n# For each role a list of category names are grouped. \n# Please don't change these variables\n\nlabel_DataScientist = ['Data Science','Data Analysis','Data Mining','Data Visualization']\n\nlabel_SoftwareDevelopment = ['Software Development','Computer Science',\n 'Programming Languages', 'Algorithms and Data Structures', \n 'Information Technology']\n\n\nlabel_DatabaseAdministrator = ['Databases']\n\nlabel_Cybersecurity = ['Cybersecurity']\n\nlabel_FinancialAccountant = ['Finance', 'Accounting']\n\nlabel_MachineLearning = ['Machine Learning', 'Deep Learning']\n\nlabel_Musician = ['Music']\n\nlabel_Dietitian = ['Nutrition & Wellness', 'Health & Medicine']\n\n \n# *******************************************************************\n\n\n# *******************************************************************\n# Environment and Config Variables. Change these variables as per the requirement.\n\nmy_fpath_model = \"../Data/Final_Model_Output.csv\"\n\nmy_fpath_courses = \"../Data/main_coursera.csv\"\n\nmy_fpath_skills_DataScientist = \"../Data/Word2Vec-Google/Word2VecGoogle_DataScientist.csv\"\n\nmy_fpath_skills_SoftwareDevelopment = \"../Data/Word2Vec-Google/Word2VecGoogle_SoftwareDevelopment.csv\" \n\nmy_fpath_skills_DatabaseAdministrator = \"../Data/Word2Vec-Google/Word2VecGoogle_DatabaseAdministrator.csv\"\n\nmy_fpath_skills_Cybersecurity = \"../Data/Word2Vec-Google/Word2VecGoogle_Cybersecurity.csv\"\n\nmy_fpath_skills_FinancialAccountant = \"../Data/Word2Vec-Google/Word2VecGoogle_FinancialAccountant.csv\"\n\nmy_fpath_skills_MachineLearning = \"../Data/Word2Vec-Google/Word2VecGoogle_MachineLearning.csv\"\n\nmy_fpath_skills_Musician = \"../Data/Word2Vec-Google/Word2VecGoogle_Musician.csv\"\n\nmy_fpath_skills_Dietitian = \"../Data/Word2Vec-Google/Word2VecGoogle_Dietitian.csv\"\n\n\n# *******************************************************************\n\n\n# *******************************************************************\n# Weighting Variables. Change them as per the requirement.\n# Role score is not applicable for Google's Word2Vec model.\n\nmy_role_weight = 0.5\n\nmy_skill_weight = 0.5\n\nmy_threshold = 0.37\n\n# *******************************************************************\n", "_____no_output_____" ], [ "# Importing required modules/packages\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport nltk, string\nimport string\nimport csv\nimport json\n\n", "_____no_output_____" ], [ "# Downloading the stopwords like i, me, and, is, the etc.\n\nnltk.download('stopwords')", "[nltk_data] Downloading package stopwords to /Users/DV/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "# Loading courses and skills data from the CSV files\n\ndf_courses = pd.read_csv(my_fpath_courses)\n\ndf_DataScientist = pd.read_csv(my_fpath_skills_DataScientist)\ndf_DataScientist = df_DataScientist.drop('Role', 1)\ndf_DataScientist.columns = ['Course Id', 'DataScientist_Skill_Score', 'DataScientist_Role_Score', 'DataScientist_Keyword_Score']\n\ndf_SoftwareDevelopment = pd.read_csv(my_fpath_skills_SoftwareDevelopment)\ndf_SoftwareDevelopment = df_SoftwareDevelopment.drop('Role', 1)\ndf_SoftwareDevelopment.columns = ['Course Id','SoftwareDevelopment_Skill_Score', 'SoftwareDevelopment_Role_Score', 'SoftwareDevelopment_Keyword_Score']\n\ndf_DatabaseAdministrator = pd.read_csv(my_fpath_skills_DatabaseAdministrator)\ndf_DatabaseAdministrator = df_DatabaseAdministrator.drop('Role', 1)\ndf_DatabaseAdministrator.columns = ['Course Id','DatabaseAdministrator_Skill_Score', 'DatabaseAdministrator_Role_Score', 'DatabaseAdministrator_Keyword_Score']\n\ndf_Cybersecurity = pd.read_csv(my_fpath_skills_Cybersecurity)\ndf_Cybersecurity = df_Cybersecurity.drop('Role', 1)\ndf_Cybersecurity.columns = ['Course Id','Cybersecurity_Skill_Score', 'Cybersecurity_Role_Score', 'Cybersecurity_Keyword_Score']\n\ndf_FinancialAccountant = pd.read_csv(my_fpath_skills_FinancialAccountant)\ndf_FinancialAccountant = df_FinancialAccountant.drop('Role', 1)\ndf_FinancialAccountant.columns = ['Course Id','FinancialAccountant_Skill_Score', 'FinancialAccountant_Role_Score', 'FinancialAccountant_Keyword_Score']\n\ndf_MachineLearning = pd.read_csv(my_fpath_skills_MachineLearning)\ndf_MachineLearning = df_MachineLearning.drop('Role', 1)\ndf_MachineLearning.columns = ['Course Id','MachineLearning_Skill_Score', 'MachineLearning_Role_Score', 'MachineLearning_Keyword_Score']\n\ndf_Musician = pd.read_csv(my_fpath_skills_Musician)\ndf_Musician = df_Musician.drop('Role', 1)\ndf_Musician.columns = ['Course Id','Musician_Skill_Score', 'Musician_Role_Score', 'Musician_Keyword_Score']\n\ndf_Dietitian = pd.read_csv(my_fpath_skills_Dietitian)\ndf_Dietitian = df_Dietitian.drop('Role', 1)\ndf_Dietitian.columns = ['Course Id','Dietitian_Skill_Score', 'Dietitian_Role_Score','Dietitian_Keyword_Score']\n", "_____no_output_____" ], [ "# Merging the csv files\n\ndf_cosdist = df_DataScientist.merge(df_SoftwareDevelopment, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_DatabaseAdministrator, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_Cybersecurity, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_FinancialAccountant, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_MachineLearning, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_Musician, on = 'Course Id', how = 'outer')\n\ndf_cosdist = df_cosdist.merge(df_Dietitian, on = 'Course Id', how = 'outer')\n\n", "_____no_output_____" ], [ "# Exploring data dimensionality, feature names, and feature types.\n\nprint(df_courses.shape,\"\\n\")\n\nprint(df_cosdist.shape,\"\\n\")\n\nprint(df_courses.columns, \"\\n\")\n\nprint(df_cosdist.shape,\"\\n\")\n\nprint(df_courses.describe(), \"\\n\")\n\nprint(df_cosdist.describe(), \"\\n\")\n", "(2213, 19) \n\n(2213, 25) \n\nIndex(['Unnamed: 0', 'Course Id', 'Course Name', 'Course Description', 'Slug',\n 'Provider', 'Universities/Institutions', 'Parent Subject',\n 'Child Subject', 'Category', 'Url', 'Length', 'Language',\n 'Credential Name', 'Rating', 'Number of Ratings', 'Certificate',\n 'Workload', 'Course Keywords'],\n dtype='object') \n\n(2213, 25) \n\n Unnamed: 0 Course Id Length Rating Number of Ratings \\\ncount 2213.000000 2213.000000 964.000000 2213.000000 2213.000000 \nmean 1106.000000 4816.998192 6.063278 2.352785 10.321735 \nstd 638.982394 3033.878865 2.724669 2.129134 110.680382 \nmin 0.000000 303.000000 1.000000 0.000000 0.000000 \n25% 553.000000 1829.000000 4.000000 0.000000 0.000000 \n50% 1106.000000 4880.000000 6.000000 3.000000 1.000000 \n75% 1659.000000 7329.000000 7.000000 4.428571 4.000000 \nmax 2212.000000 9969.000000 47.000000 5.000000 3008.000000 \n\n Certificate \ncount 2089.0 \nmean 1.0 \nstd 0.0 \nmin 1.0 \n25% 1.0 \n50% 1.0 \n75% 1.0 \nmax 1.0 \n\n Course Id DataScientist_Skill_Score DataScientist_Role_Score \\\ncount 2213.000000 2213.000000 2213.000000 \nmean 4816.998192 0.253603 0.202148 \nstd 3033.878865 0.063825 0.095905 \nmin 303.000000 0.073427 -0.045646 \n25% 1829.000000 0.209730 0.136829 \n50% 4880.000000 0.246833 0.190079 \n75% 7329.000000 0.290165 0.253134 \nmax 9969.000000 0.496512 0.684108 \n\n DataScientist_Keyword_Score SoftwareDevelopment_Skill_Score \\\ncount 2213.000000 2213.000000 \nmean 0.091181 0.387198 \nstd 0.059478 0.084046 \nmin -0.063642 0.102160 \n25% 0.050196 0.325518 \n50% 0.088732 0.383269 \n75% 0.125501 0.440745 \nmax 0.396320 0.700534 \n\n SoftwareDevelopment_Role_Score SoftwareDevelopment_Keyword_Score \\\ncount 2213.000000 2213.000000 \nmean 0.270533 0.120804 \nstd 0.123348 0.116932 \nmin -0.024631 -0.100123 \n25% 0.181528 0.032989 \n50% 0.254739 0.093796 \n75% 0.349016 0.193437 \nmax 0.726558 0.659895 \n\n DatabaseAdministrator_Skill_Score DatabaseAdministrator_Role_Score \\\ncount 2213.000000 2213.000000 \nmean 0.223889 0.213700 \nstd 0.062702 0.102178 \nmin 0.044565 -0.024762 \n25% 0.179406 0.141179 \n50% 0.211521 0.200258 \n75% 0.257764 0.271785 \nmax 0.484228 0.707394 \n\n DatabaseAdministrator_Keyword_Score ... \\\ncount 2213.000000 ... \nmean 0.148530 ... \nstd 0.097067 ... \nmin -0.124045 ... \n25% 0.080847 ... \n50% 0.138213 ... \n75% 0.207535 ... \nmax 0.627908 ... \n\n FinancialAccountant_Keyword_Score MachineLearning_Skill_Score \\\ncount 2213.000000 2213.000000 \nmean 0.189876 0.318955 \nstd 0.114190 0.054524 \nmin -0.036009 0.013001 \n25% 0.113617 0.284579 \n50% 0.169959 0.319259 \n75% 0.246636 0.354664 \nmax 0.811558 0.578443 \n\n MachineLearning_Role_Score MachineLearning_Keyword_Score \\\ncount 2213.000000 2213.000000 \nmean 0.271231 0.098372 \nstd 0.106121 0.060126 \nmin 0.000000 -0.080490 \n25% 0.206380 0.059618 \n50% 0.264095 0.094563 \n75% 0.322249 0.135300 \nmax 0.878551 0.620310 \n\n Musician_Skill_Score Musician_Role_Score Musician_Keyword_Score \\\ncount 2213.000000 2213.000000 2213.000000 \nmean 0.234268 0.114262 0.097471 \nstd 0.060516 0.083243 0.075950 \nmin 0.060548 -0.067947 -0.070993 \n25% 0.199681 0.060388 0.047330 \n50% 0.227106 0.099685 0.084650 \n75% 0.258019 0.150736 0.133394 \nmax 0.643528 0.643383 0.560303 \n\n Dietitian_Skill_Score Dietitian_Role_Score Dietitian_Keyword_Score \ncount 2213.000000 2213.000000 2213.000000 \nmean 0.258961 0.210623 0.233843 \nstd 0.075362 0.102585 0.111411 \nmin 0.005550 -0.032185 -0.060747 \n25% 0.211049 0.139227 0.159844 \n50% 0.248664 0.200446 0.223151 \n75% 0.294546 0.267689 0.294443 \nmax 0.758306 0.684655 0.833940 \n\n[8 rows x 25 columns] \n\n" ], [ "# Quick check to see if the dataframe showing the right results\n\ndf_cosdist.head(20)", "_____no_output_____" ], [ "# Joining two dataframes - Courses and the Cosein Similarity Results based on the 'Course Id' variable. \n# Inner joins: Joins two tables with the common rows. This is a set operateion.\n\ndf_courses_score = df_courses.merge(df_cosdist, on ='Course Id', how='inner')\n\nprint(df_courses_score.shape,\"\\n\")\n", "(2213, 43) \n\n" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: DATA SCIENTIST\n\ny_actu_DataScientist = ''\ny_pred_DataScientist = ''\n\ndf_courses_score['DataScientist_Final_Score'] = (df_courses_score['DataScientist_Role_Score'] * my_role_weight) + (df_courses_score['DataScientist_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['DataScientist_Predict'] = (df_courses_score['DataScientist_Final_Score'] >= my_threshold)\n\ndf_courses_score['DataScientist_Label'] = df_courses_score.Category.isin(label_DataScientist)\n\ny_pred_DataScientist = pd.Series(df_courses_score['DataScientist_Predict'], name='Predicted')\n\ny_actu_DataScientist = pd.Series(df_courses_score['DataScientist_Label'], name='Actual')\n\ndf_confusion_DataScientist = pd.crosstab(y_actu_DataScientist, y_pred_DataScientist , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: SOFTWARE ENGINEER/DEVELOPER\n\ny_actu_SoftwareDevelopment = ''\ny_pred_SoftwareDevelopment = ''\n\ndf_courses_score['SoftwareDevelopment_Final_Score'] = (df_courses_score['SoftwareDevelopment_Role_Score'] * my_role_weight) + (df_courses_score['SoftwareDevelopment_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['SoftwareDevelopment_Predict'] = (df_courses_score['SoftwareDevelopment_Final_Score'] >= my_threshold)\n\ndf_courses_score['SoftwareDevelopment_Label'] = df_courses_score.Category.isin(label_SoftwareDevelopment)\n\ny_pred_SoftwareDevelopment = pd.Series(df_courses_score['SoftwareDevelopment_Predict'], name='Predicted')\n\ny_actu_SoftwareDevelopment = pd.Series(df_courses_score['SoftwareDevelopment_Label'], name='Actual')\n\ndf_confusion_SoftwareDevelopment = pd.crosstab(y_actu_SoftwareDevelopment, y_pred_SoftwareDevelopment , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: DATABASE DEVELOPER/ADMINISTRATOR\n\ny_actu_DatabaseAdministrator = ''\ny_pred_DatabaseAdministrator = ''\n\ndf_courses_score['DatabaseAdministrator_Final_Score'] = (df_courses_score['DatabaseAdministrator_Role_Score'] * my_role_weight) + (df_courses_score['DatabaseAdministrator_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['DatabaseAdministrator_Predict'] = (df_courses_score['DatabaseAdministrator_Final_Score'] >= my_threshold)\n\ndf_courses_score['DatabaseAdministrator_Label'] = df_courses_score.Category.isin(label_DatabaseAdministrator)\n\ny_pred_DatabaseAdministrator = pd.Series(df_courses_score['DatabaseAdministrator_Predict'], name='Predicted')\n\ny_actu_DatabaseAdministrator = pd.Series(df_courses_score['DatabaseAdministrator_Label'], name='Actual')\n\ndf_confusion_DatabaseAdministrator = pd.crosstab(y_actu_DatabaseAdministrator, y_pred_DatabaseAdministrator , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: CYBERSECURITY CONSULTANT\n\ny_actu_Cybersecurity = ''\ny_pred_Cybersecurity = ''\n\ndf_courses_score['Cybersecurity_Final_Score'] = (df_courses_score['Cybersecurity_Role_Score'] * my_role_weight) + (df_courses_score['Cybersecurity_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['Cybersecurity_Predict'] = (df_courses_score['Cybersecurity_Final_Score'] >= my_threshold)\n\ndf_courses_score['Cybersecurity_Label'] = df_courses_score.Category.isin(label_Cybersecurity)\n\ny_pred_Cybersecurity = pd.Series(df_courses_score['Cybersecurity_Predict'], name='Predicted')\n\ny_actu_Cybersecurity = pd.Series(df_courses_score['Cybersecurity_Label'], name='Actual')\n\ndf_confusion_Cybersecurity = pd.crosstab(y_actu_Cybersecurity, y_pred_Cybersecurity , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: FINANCIAL ACCOUNTANT\n\ny_actu_FinancialAccountant = ''\ny_pred_FinancialAccountant = ''\n\ndf_courses_score['FinancialAccountant_Final_Score'] = (df_courses_score['FinancialAccountant_Role_Score'] * my_role_weight) + (df_courses_score['FinancialAccountant_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['FinancialAccountant_Predict'] = (df_courses_score['FinancialAccountant_Final_Score'] >= my_threshold)\n\ndf_courses_score['FinancialAccountant_Label'] = df_courses_score.Category.isin(label_FinancialAccountant)\n\ny_pred_FinancialAccountant = pd.Series(df_courses_score['FinancialAccountant_Predict'], name='Predicted')\n\ny_actu_FinancialAccountant = pd.Series(df_courses_score['FinancialAccountant_Label'], name='Actual')\n\ndf_confusion_FinancialAccountant = pd.crosstab(y_actu_FinancialAccountant, y_pred_FinancialAccountant , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: MACHINE LEARNING ENGINEER\n\ny_actu_MachineLearning = ''\ny_pred_MachineLearning = ''\n\ndf_courses_score['MachineLearning_Final_Score'] = (df_courses_score['MachineLearning_Role_Score'] * my_role_weight) + (df_courses_score['MachineLearning_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['MachineLearning_Predict'] = (df_courses_score['MachineLearning_Final_Score'] >= my_threshold)\n\ndf_courses_score['MachineLearning_Label'] = df_courses_score.Category.isin(label_MachineLearning)\n\ny_pred_MachineLearning = pd.Series(df_courses_score['MachineLearning_Predict'], name='Predicted')\n\ny_actu_MachineLearning = pd.Series(df_courses_score['MachineLearning_Label'], name='Actual')\n\ndf_confusion_MachineLearning = pd.crosstab(y_actu_MachineLearning, y_pred_MachineLearning , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: MUSICIAN\n\ny_actu_Musician = ''\ny_pred_Musician = ''\n\ndf_courses_score['Musician_Final_Score'] = (df_courses_score['Musician_Role_Score'] * my_role_weight) + (df_courses_score['Musician_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['Musician_Predict'] = (df_courses_score['Musician_Final_Score'] >= my_threshold)\n\ndf_courses_score['Musician_Label'] = df_courses_score.Category.isin(label_Musician)\n\ny_pred_Musician = pd.Series(df_courses_score['Musician_Predict'], name='Predicted')\n\ny_actu_Musician = pd.Series(df_courses_score['Musician_Label'], name='Actual')\n\ndf_confusion_Musician = pd.crosstab(y_actu_Musician, y_pred_Musician , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "# Tranforming and shaping the data to create the confusion matrix for the ROLE: NUTRITIONIST/DIETITIAN\n\ny_actu_Dietitian = ''\ny_pred_Dietitian = ''\n\ndf_courses_score['Dietitian_Final_Score'] = (df_courses_score['Dietitian_Role_Score'] * my_role_weight) + (df_courses_score['Dietitian_Skill_Score'] * my_skill_weight)\n\ndf_courses_score['Dietitian_Predict'] = (df_courses_score['Dietitian_Final_Score'] >= my_threshold)\n\ndf_courses_score['Dietitian_Label'] = df_courses_score.Category.isin(label_Dietitian)\n\ny_pred_Dietitian = pd.Series(df_courses_score['Dietitian_Predict'], name='Predicted')\n\ny_actu_Dietitian = pd.Series(df_courses_score['Dietitian_Label'], name='Actual')\n\ndf_confusion_Dietitian = pd.crosstab(y_actu_Dietitian, y_pred_Dietitian , rownames=['Actual'], colnames=['Predicted'], margins=False)\n", "_____no_output_____" ], [ "df_confusion_DataScientist\n", "_____no_output_____" ], [ "df_confusion_SoftwareDevelopment", "_____no_output_____" ], [ "df_confusion_DatabaseAdministrator", "_____no_output_____" ], [ "df_confusion_Cybersecurity", "_____no_output_____" ], [ "df_confusion_FinancialAccountant", "_____no_output_____" ], [ "df_confusion_MachineLearning", "_____no_output_____" ], [ "df_confusion_Musician", "_____no_output_____" ], [ "df_confusion_Dietitian", "_____no_output_____" ], [ "# Performance summary for the ROLE: DATA SCIENTIST\n\n\ntry:\n tn_DataScientist = df_confusion_DataScientist.iloc[0][False]\nexcept:\n tn_DataScientist = 0\n \ntry:\n tp_DataScientist = df_confusion_DataScientist.iloc[1][True]\nexcept:\n tp_DataScientist = 0\n\n \ntry:\n fn_DataScientist = df_confusion_DataScientist.iloc[1][False]\nexcept:\n fn_DataScientist = 0\n \ntry:\n fp_DataScientist = df_confusion_DataScientist.iloc[0][True]\nexcept:\n fp_DataScientist = 0 \n \n \ntotal_count_DataScientist = tn_DataScientist + tp_DataScientist + fn_DataScientist + fp_DataScientist\n\nprint('Data Scientist Accuracy Rate : ', '{0:.2f}'.format((tn_DataScientist + tp_DataScientist) / total_count_DataScientist * 100))\n\nprint('Data Scientist Misclassifcation Rate : ', '{0:.2f}'.format((fn_DataScientist + fp_DataScientist) / total_count_DataScientist * 100))\n\nprint('Data Scientist True Positive Rate : ', '{0:.2f}'.format(tp_DataScientist / (tp_DataScientist + fn_DataScientist) * 100))\n\nprint('Data Scientist False Positive Rate : ', '{0:.2f}'.format(fp_DataScientist / (tn_DataScientist + fp_DataScientist) * 100))\n", "Data Scientist Accuracy Rate : 96.11\nData Scientist Misclassifcation Rate : 3.89\nData Scientist True Positive Rate : 68.29\nData Scientist False Positive Rate : 2.82\n" ], [ "# Performance summary for the ROLE: SOFTWARE ENGINEER\n\n\ntry:\n tn_SoftwareDevelopment = df_confusion_SoftwareDevelopment.iloc[0][False]\nexcept:\n tn_SoftwareDevelopment = 0\n \ntry:\n tp_SoftwareDevelopment = df_confusion_SoftwareDevelopment.iloc[1][True]\nexcept:\n tp_SoftwareDevelopment = 0\n\n \ntry:\n fn_SoftwareDevelopment = df_confusion_SoftwareDevelopment.iloc[1][False]\nexcept:\n fn_SoftwareDevelopment = 0\n \ntry:\n fp_SoftwareDevelopment = df_confusion_SoftwareDevelopment.iloc[0][True]\nexcept:\n fp_SoftwareDevelopment = 0 \n \n \ntotal_count_SoftwareDevelopment = tn_SoftwareDevelopment + tp_SoftwareDevelopment + fn_SoftwareDevelopment + fp_SoftwareDevelopment\n\nprint('Software Engineer Accuracy Rate : ', '{0:.2f}'.format((tn_SoftwareDevelopment + tp_SoftwareDevelopment) / total_count_SoftwareDevelopment * 100))\n\nprint('Software Engineer Misclassifcation Rate : ', '{0:.2f}'.format((fn_SoftwareDevelopment + fp_SoftwareDevelopment) / total_count_SoftwareDevelopment * 100))\n\nprint('Software Engineer True Positive Rate : ', '{0:.2f}'.format(tp_SoftwareDevelopment / (tp_SoftwareDevelopment + fn_SoftwareDevelopment) * 100))\n\nprint('Software Engineer False Positive Rate : ', '{0:.2f}'.format(fp_SoftwareDevelopment / (tn_SoftwareDevelopment + fp_SoftwareDevelopment) * 100))\n", "Software Engineer Accuracy Rate : 73.11\nSoftware Engineer Misclassifcation Rate : 26.89\nSoftware Engineer True Positive Rate : 88.43\nSoftware Engineer False Positive Rate : 27.77\n" ], [ "# Performance summary for the ROLE: DATABASE DEVELOPER/ ADMINISTRATOR\n\n\ntry:\n tn_DatabaseAdministrator = df_confusion_DatabaseAdministrator.iloc[0][False]\nexcept:\n tn_DatabaseAdministrator = 0\n \ntry:\n tp_DatabaseAdministrator = df_confusion_DatabaseAdministrator.iloc[1][True]\nexcept:\n tp_DatabaseAdministrator = 0\n\n \ntry:\n fn_DatabaseAdministrator = df_confusion_DatabaseAdministrator.iloc[1][False]\nexcept:\n fn_DatabaseAdministrator = 0\n \ntry:\n fp_DatabaseAdministrator = df_confusion_DatabaseAdministrator.iloc[0][True]\nexcept:\n fp_DatabaseAdministrator = 0 \n \n \ntotal_count_DatabaseAdministrator = tn_DatabaseAdministrator + tp_DatabaseAdministrator + fn_DatabaseAdministrator + fp_DatabaseAdministrator\n\nprint('Database Administrator Accuracy Rate : ', '{0:.2f}'.format((tn_DatabaseAdministrator + tp_DatabaseAdministrator) / total_count_DatabaseAdministrator * 100))\n\nprint('Database Administrator Misclassifcation Rate : ', '{0:.2f}'.format((fn_DatabaseAdministrator + fp_DatabaseAdministrator) / total_count_DatabaseAdministrator * 100))\n\nprint('Database Administrator True Positive Rate : ', '{0:.2f}'.format(tp_DatabaseAdministrator / (tp_DatabaseAdministrator + fn_DatabaseAdministrator) * 100))\n\nprint('Database Administrator False Positive Rate : ', '{0:.2f}'.format(fp_DatabaseAdministrator / (tn_DatabaseAdministrator + fp_DatabaseAdministrator) * 100))\n", "Database Administrator Accuracy Rate : 95.44\nDatabase Administrator Misclassifcation Rate : 4.56\nDatabase Administrator True Positive Rate : 81.82\nDatabase Administrator False Positive Rate : 4.50\n" ], [ "# Performance summary for the ROLE: CYBERSECURITY CONSULTANT\n\n\ntry:\n tn_Cybersecurity = df_confusion_Cybersecurity.iloc[0][False]\nexcept:\n tn_Cybersecurity = 0\n \ntry:\n tp_Cybersecurity = df_confusion_Cybersecurity.iloc[1][True]\nexcept:\n tp_Cybersecurity = 0\n\n \ntry:\n fn_Cybersecurity = df_confusion_Cybersecurity.iloc[1][False]\nexcept:\n fn_Cybersecurity = 0\n \ntry:\n fp_Cybersecurity = df_confusion_Cybersecurity.iloc[0][True]\nexcept:\n fp_Cybersecurity = 0 \n \n \ntotal_count_Cybersecurity = tn_Cybersecurity + tp_Cybersecurity + fn_Cybersecurity + fp_Cybersecurity\n\nprint('Cybersecurity Consultant Accuracy Rate : ', '{0:.2f}'.format((tn_Cybersecurity + tp_Cybersecurity) / total_count_Cybersecurity * 100))\n\nprint('Cybersecurity Consultant Misclassifcation Rate : ', '{0:.2f}'.format((fn_Cybersecurity + fp_Cybersecurity) / total_count_Cybersecurity * 100))\n\nprint('Cybersecurity Consultant True Positive Rate : ', '{0:.2f}'.format(tp_Cybersecurity / (tp_Cybersecurity + fn_Cybersecurity) * 100))\n\nprint('Cybersecurity Consultant False Positive Rate : ', '{0:.2f}'.format(fp_Cybersecurity / (tn_Cybersecurity + fp_Cybersecurity) * 100))\n", "Cybersecurity Consultant Accuracy Rate : 96.70\nCybersecurity Consultant Misclassifcation Rate : 3.30\nCybersecurity Consultant True Positive Rate : 100.00\nCybersecurity Consultant False Positive Rate : 3.34\n" ], [ "# Performance summary for the ROLE: FINANCIAL ACCOUNTANT\n\n\ntry:\n tn_FinancialAccountant = df_confusion_FinancialAccountant.iloc[0][False]\nexcept:\n tn_FinancialAccountant = 0\n \ntry:\n tp_FinancialAccountant = df_confusion_FinancialAccountant.iloc[1][True]\nexcept:\n tp_FinancialAccountant = 0\n\n \ntry:\n fn_FinancialAccountant = df_confusion_FinancialAccountant.iloc[1][False]\nexcept:\n fn_FinancialAccountant = 0\n \ntry:\n fp_FinancialAccountant = df_confusion_FinancialAccountant.iloc[0][True]\nexcept:\n fp_FinancialAccountant = 0 \n \n \ntotal_count_FinancialAccountant = tn_FinancialAccountant + tp_FinancialAccountant + fn_FinancialAccountant + fp_FinancialAccountant\n\nprint('Financial Accountant Consultant Accuracy Rate : ', '{0:.2f}'.format((tn_FinancialAccountant + tp_FinancialAccountant) / total_count_FinancialAccountant * 100))\n\nprint('Financial Accountant Consultant Misclassifcation Rate : ', '{0:.2f}'.format((fn_FinancialAccountant + fp_FinancialAccountant) / total_count_FinancialAccountant * 100))\n\nprint('Financial Accountant Consultant True Positive Rate : ', '{0:.2f}'.format(tp_FinancialAccountant / (tp_FinancialAccountant + fn_FinancialAccountant) * 100))\n\nprint('Financial Accountant Consultant False Positive Rate : ', '{0:.2f}'.format(fp_FinancialAccountant / (tn_FinancialAccountant + fp_FinancialAccountant) * 100))\n", "Financial Accountant Consultant Accuracy Rate : 93.90\nFinancial Accountant Consultant Misclassifcation Rate : 6.10\nFinancial Accountant Consultant True Positive Rate : 77.67\nFinancial Accountant Consultant False Positive Rate : 5.31\n" ], [ "# Performance summary for the ROLE: MACHINE LEARNING ENGINEER\n\n\ntry:\n tn_MachineLearning = df_confusion_MachineLearning.iloc[0][False]\nexcept:\n tn_MachineLearning = 0\n \ntry:\n tp_MachineLearning = df_confusion_MachineLearning.iloc[1][True]\nexcept:\n tp_MachineLearning = 0\n\n \ntry:\n fn_MachineLearning = df_confusion_MachineLearning.iloc[1][False]\nexcept:\n fn_MachineLearning = 0\n \ntry:\n fp_MachineLearning = df_confusion_MachineLearning.iloc[0][True]\nexcept:\n fp_MachineLearning = 0 \n \n \ntotal_count_MachineLearning = tn_MachineLearning + tp_MachineLearning + fn_MachineLearning + fp_MachineLearning\n\nprint('Machine Learning Engineer Accuracy Rate : ', '{0:.2f}'.format((tn_MachineLearning + tp_MachineLearning) / total_count_MachineLearning * 100))\n\nprint('Machine Learning Engineer Misclassifcation Rate : ', '{0:.2f}'.format((fn_MachineLearning + fp_MachineLearning) / total_count_MachineLearning * 100))\n\nprint('Machine Learning Engineer True Positive Rate : ', '{0:.2f}'.format(tp_MachineLearning / (tp_MachineLearning + fn_MachineLearning) * 100))\n\nprint('Machine Learning Engineer False Positive Rate : ', '{0:.2f}'.format(fp_MachineLearning / (tn_MachineLearning + fp_MachineLearning) * 100))\n", "Machine Learning Engineer Accuracy Rate : 90.96\nMachine Learning Engineer Misclassifcation Rate : 9.04\nMachine Learning Engineer True Positive Rate : 95.83\nMachine Learning Engineer False Positive Rate : 9.09\n" ], [ "# Performance summary for the ROLE: MUSICIAN\n\n\ntry:\n tn_Musician = df_confusion_Musician.iloc[0][False]\nexcept:\n tn_Musician = 0\n \ntry:\n tp_Musician = df_confusion_Musician.iloc[1][True]\nexcept:\n tp_Musician = 0\n\n \ntry:\n fn_Musician = df_confusion_Musician.iloc[1][False]\nexcept:\n fn_Musician = 0\n \ntry:\n fp_Musician = df_confusion_Musician.iloc[0][True]\nexcept:\n fp_Musician = 0 \n \n \ntotal_count_Musician = tn_Musician + tp_Musician + fn_Musician + fp_Musician\n\nprint('Musician Accuracy Rate : ', '{0:.2f}'.format((tn_Musician + tp_Musician) / total_count_Musician * 100))\n\nprint('Musician Misclassifcation Rate : ', '{0:.2f}'.format((fn_Musician + fp_Musician) / total_count_Musician * 100))\n\nprint('Musician True Positive Rate : ', '{0:.2f}'.format(tp_Musician / (tp_Musician + fn_Musician) * 100))\n\nprint('Musician False Positive Rate : ', '{0:.2f}'.format(fp_Musician / (tn_Musician + fp_Musician) * 100))\n", "Musician Accuracy Rate : 99.32\nMusician Misclassifcation Rate : 0.68\nMusician True Positive Rate : 94.59\nMusician False Positive Rate : 0.60\n" ], [ "# Performance summary for the ROLE: DIETITIAN\n\n\ntry:\n tn_Dietitian = df_confusion_Dietitian.iloc[0][False]\nexcept:\n tn_Dietitian = 0\n \ntry:\n tp_Dietitian = df_confusion_Dietitian.iloc[1][True]\nexcept:\n tp_Dietitian = 0\n\n \ntry:\n fn_Dietitian = df_confusion_Dietitian.iloc[1][False]\nexcept:\n fn_Dietitian = 0\n \ntry:\n fp_Dietitian = df_confusion_Dietitian.iloc[0][True]\nexcept:\n fp_Dietitian = 0 \n \n \ntotal_count_Dietitian = tn_Dietitian + tp_Dietitian + fn_Dietitian + fp_Dietitian\n\nprint('Dietitian Accuracy Rate : ', '{0:.2f}'.format((tn_Dietitian + tp_Dietitian) / total_count_Dietitian * 100))\n\nprint('Dietitian Misclassifcation Rate : ', '{0:.2f}'.format((fn_Dietitian + fp_Dietitian) / total_count_Dietitian * 100))\n\nprint('Dietitian True Positive Rate : ', '{0:.2f}'.format(tp_Dietitian / (tp_Dietitian + fn_Dietitian) * 100))\n\nprint('Dietitian False Positive Rate : ', '{0:.2f}'.format(fp_Dietitian / (tn_Dietitian + fp_Dietitian) * 100))\n", "Dietitian Accuracy Rate : 93.85\nDietitian Misclassifcation Rate : 6.15\nDietitian True Positive Rate : 55.56\nDietitian False Positive Rate : 5.35\n" ], [ "df_final_model = df_courses_score[['Course Id', 'Course Name', 'Course Description', 'Slug',\n 'Provider', 'Universities/Institutions', 'Parent Subject',\n 'Child Subject', 'Category', 'Url', 'Length', 'Language',\n 'Credential Name', 'Rating', 'Number of Ratings', 'Certificate',\n 'Workload',\n 'DataScientist_Final_Score', 'DataScientist_Predict',\n 'SoftwareDevelopment_Final_Score', 'SoftwareDevelopment_Predict', \n 'DatabaseAdministrator_Final_Score', 'DatabaseAdministrator_Predict',\n 'Cybersecurity_Final_Score', 'Cybersecurity_Predict',\n 'FinancialAccountant_Final_Score', 'FinancialAccountant_Predict',\n 'MachineLearning_Final_Score', 'MachineLearning_Predict',\n 'Musician_Final_Score', 'Musician_Predict',\n 'Dietitian_Final_Score', 'Dietitian_Predict']]", "_____no_output_____" ], [ "df_final_model\n\ntest = df_final_model.sort_values('FinancialAccountant_Final_Score', ascending=False)\n\n\ntest\n", "_____no_output_____" ], [ "# Save the model results to the CSV File\n\ndf_final_model.columns\n\n\ndf_final_model = df_final_model.drop(df_final_model.columns[df_final_model.columns.str.contains('unnamed',case = False)],axis = 1)\ndf_final_model = df_final_model.replace(np.nan, '', regex=True)\ndf_final_model.columns = ['courseId', 'courseName', 'courseDescription', 'slug', 'provider', \n'universitiesInstitutions', 'parentSubject', 'childSubject', \n'category', 'url', 'length', 'language', 'credentialName', 'rating', \n'numberOfRatings', 'certificate', 'workload', \n'dataScientistFinalScore', 'dataScientistPredict',\n'softwareDevelopmentFinalScore', 'softwareDevelopmentPredict', \n'databaseAdministratorFinalScore', 'databaseAdministratorPredict',\n'cybersecurityFinalScore', 'cybersecurityPredict',\n'financialAccountantFinalScore', 'financialAccountantPredict',\n'machineLearningFinalScore', 'machineLearningPredict',\n'musicianFinalScore', 'musicianPredict',\n'dietitianFinalScore', 'dietitianPredict']\n\n\ndf_final_model\n", "_____no_output_____" ], [ "df_final_model.to_csv(my_fpath_model, sep=',', encoding='utf-8')", "_____no_output_____" ] ], [ [ "### End of the Notebook. Thank you!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cbe45067eff6387ff78a114cd00b8cf1ddb5879b
477,192
ipynb
Jupyter Notebook
Football_1_Plotting_pass_and_shot.ipynb
sreyaschaithanya/football_analysis
d60f0ade95a80d009e9b3bbe2bad1b2317fde80f
[ "MIT" ]
1
2021-02-17T10:12:31.000Z
2021-02-17T10:12:31.000Z
Football_1_Plotting_pass_and_shot.ipynb
sreyaschaithanya/football_analysis
d60f0ade95a80d009e9b3bbe2bad1b2317fde80f
[ "MIT" ]
null
null
null
Football_1_Plotting_pass_and_shot.ipynb
sreyaschaithanya/football_analysis
d60f0ade95a80d009e9b3bbe2bad1b2317fde80f
[ "MIT" ]
null
null
null
71.243953
73,390
0.496096
[ [ [ "<a href=\"https://colab.research.google.com/github/sreyaschaithanya/football_analysis/blob/main/Football_1_Plotting_pass_and_shot.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "#! git clone https://github.com/statsbomb/open-data.git\nfrom google.colab import drive\ndrive.mount('/content/drive')\n#!rm -rf /content/open-data\n#!cp -r \"/content/drive/My Drive/Football/open-data\" \"open-data\"\n#!cp \"/content/drive/My Drive/Football/open-data.zip\" \"open-data.zip\"\n#!unzip /content/open-data.zip -d /content/\n#from google.colab import files\n\n#files.download('open-data.zip')", "Mounted at /content/drive\n" ], [ "DATA_PATH = \"/content/drive/My Drive/Football/open-data/data/\"\nMATCHES_PATH = DATA_PATH+\"matches/\"", "_____no_output_____" ], [ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 25 17:32:00 2020\n\n@author: davsu428\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Arc\n\ndef createPitch(length,width, unity,linecolor): # in meters\n # Code by @JPJ_dejong\n\n \"\"\"\n creates a plot in which the 'length' is the length of the pitch (goal to goal).\n And 'width' is the width of the pitch (sideline to sideline). \n Fill in the unity in meters or in yards.\n\n \"\"\"\n #Set unity\n if unity == \"meters\":\n # Set boundaries\n if length >= 120.5 or width >= 75.5:\n return(str(\"Field dimensions are too big for meters as unity, didn't you mean yards as unity?\\\n Otherwise the maximum length is 120 meters and the maximum width is 75 meters. Please try again\"))\n #Run program if unity and boundaries are accepted\n else:\n #Create figure\n fig=plt.figure()\n #fig.set_size_inches(7, 5)\n ax=fig.add_subplot(1,1,1)\n \n #Pitch Outline & Centre Line\n plt.plot([0,0],[0,width], color=linecolor)\n plt.plot([0,length],[width,width], color=linecolor)\n plt.plot([length,length],[width,0], color=linecolor)\n plt.plot([length,0],[0,0], color=linecolor)\n plt.plot([length/2,length/2],[0,width], color=linecolor)\n \n #Left Penalty Area\n plt.plot([16.5 ,16.5],[(width/2 +16.5),(width/2-16.5)],color=linecolor)\n plt.plot([0,16.5],[(width/2 +16.5),(width/2 +16.5)],color=linecolor)\n plt.plot([16.5,0],[(width/2 -16.5),(width/2 -16.5)],color=linecolor)\n \n #Right Penalty Area\n plt.plot([(length-16.5),length],[(width/2 +16.5),(width/2 +16.5)],color=linecolor)\n plt.plot([(length-16.5), (length-16.5)],[(width/2 +16.5),(width/2-16.5)],color=linecolor)\n plt.plot([(length-16.5),length],[(width/2 -16.5),(width/2 -16.5)],color=linecolor)\n \n #Left 5-meters Box\n plt.plot([0,5.5],[(width/2+7.32/2+5.5),(width/2+7.32/2+5.5)],color=linecolor)\n plt.plot([5.5,5.5],[(width/2+7.32/2+5.5),(width/2-7.32/2-5.5)],color=linecolor)\n plt.plot([5.5,0.5],[(width/2-7.32/2-5.5),(width/2-7.32/2-5.5)],color=linecolor)\n \n #Right 5 -eters Box\n plt.plot([length,length-5.5],[(width/2+7.32/2+5.5),(width/2+7.32/2+5.5)],color=linecolor)\n plt.plot([length-5.5,length-5.5],[(width/2+7.32/2+5.5),width/2-7.32/2-5.5],color=linecolor)\n plt.plot([length-5.5,length],[width/2-7.32/2-5.5,width/2-7.32/2-5.5],color=linecolor)\n \n #Prepare Circles\n centreCircle = plt.Circle((length/2,width/2),9.15,color=linecolor,fill=False)\n centreSpot = plt.Circle((length/2,width/2),0.8,color=linecolor)\n leftPenSpot = plt.Circle((11,width/2),0.8,color=linecolor)\n rightPenSpot = plt.Circle((length-11,width/2),0.8,color=linecolor)\n \n #Draw Circles\n ax.add_patch(centreCircle)\n ax.add_patch(centreSpot)\n ax.add_patch(leftPenSpot)\n ax.add_patch(rightPenSpot)\n \n #Prepare Arcs\n leftArc = Arc((11,width/2),height=18.3,width=18.3,angle=0,theta1=308,theta2=52,color=linecolor)\n rightArc = Arc((length-11,width/2),height=18.3,width=18.3,angle=0,theta1=128,theta2=232,color=linecolor)\n \n #Draw Arcs\n ax.add_patch(leftArc)\n ax.add_patch(rightArc)\n #Axis titles\n\n #check unity again\n elif unity == \"yards\":\n #check boundaries again\n if length <= 95:\n return(str(\"Didn't you mean meters as unity?\"))\n elif length >= 131 or width >= 101:\n return(str(\"Field dimensions are too big. Maximum length is 130, maximum width is 100\"))\n #Run program if unity and boundaries are accepted\n else:\n #Create figure\n fig=plt.figure()\n #fig.set_size_inches(7, 5)\n ax=fig.add_subplot(1,1,1)\n \n #Pitch Outline & Centre Line\n plt.plot([0,0],[0,width], color=linecolor)\n plt.plot([0,length],[width,width], color=linecolor)\n plt.plot([length,length],[width,0], color=linecolor)\n plt.plot([length,0],[0,0], color=linecolor)\n plt.plot([length/2,length/2],[0,width], color=linecolor)\n \n #Left Penalty Area\n plt.plot([18 ,18],[(width/2 +18),(width/2-18)],color=linecolor)\n plt.plot([0,18],[(width/2 +18),(width/2 +18)],color=linecolor)\n plt.plot([18,0],[(width/2 -18),(width/2 -18)],color=linecolor)\n \n #Right Penalty Area\n plt.plot([(length-18),length],[(width/2 +18),(width/2 +18)],color=linecolor)\n plt.plot([(length-18), (length-18)],[(width/2 +18),(width/2-18)],color=linecolor)\n plt.plot([(length-18),length],[(width/2 -18),(width/2 -18)],color=linecolor)\n \n #Left 6-yard Box\n plt.plot([0,6],[(width/2+7.32/2+6),(width/2+7.32/2+6)],color=linecolor)\n plt.plot([6,6],[(width/2+7.32/2+6),(width/2-7.32/2-6)],color=linecolor)\n plt.plot([6,0],[(width/2-7.32/2-6),(width/2-7.32/2-6)],color=linecolor)\n \n #Right 6-yard Box\n plt.plot([length,length-6],[(width/2+7.32/2+6),(width/2+7.32/2+6)],color=linecolor)\n plt.plot([length-6,length-6],[(width/2+7.32/2+6),width/2-7.32/2-6],color=linecolor)\n plt.plot([length-6,length],[(width/2-7.32/2-6),width/2-7.32/2-6],color=linecolor)\n \n #Prepare Circles; 10 yards distance. penalty on 12 yards\n centreCircle = plt.Circle((length/2,width/2),10,color=linecolor,fill=False)\n centreSpot = plt.Circle((length/2,width/2),0.8,color=linecolor)\n leftPenSpot = plt.Circle((12,width/2),0.8,color=linecolor)\n rightPenSpot = plt.Circle((length-12,width/2),0.8,color=linecolor)\n \n #Draw Circles\n ax.add_patch(centreCircle)\n ax.add_patch(centreSpot)\n ax.add_patch(leftPenSpot)\n ax.add_patch(rightPenSpot)\n \n #Prepare Arcs\n leftArc = Arc((11,width/2),height=20,width=20,angle=0,theta1=312,theta2=48,color=linecolor)\n rightArc = Arc((length-11,width/2),height=20,width=20,angle=0,theta1=130,theta2=230,color=linecolor)\n \n #Draw Arcs\n ax.add_patch(leftArc)\n ax.add_patch(rightArc)\n \n #Tidy Axes\n plt.axis('off')\n \n return fig,ax\n\n\ndef createPitchOld():\n #Taken from FC Python \n #Create figure\n fig=plt.figure()\n ax=fig.add_subplot(1,1,1)\n\n #Pitch Outline & Centre Line\n plt.plot([0,0],[0,90], color=linecolor)\n plt.plot([0,130],[90,90], color=linecolor)\n plt.plot([130,130],[90,0], color=linecolor)\n plt.plot([130,0],[0,0], color=linecolor)\n plt.plot([65,65],[0,90], color=linecolor)\n \n #Left Penalty Area\n plt.plot([16.5,16.5],[65,25],color=linecolor)\n plt.plot([0,16.5],[65,65],color=linecolor)\n plt.plot([16.5,0],[25,25],color=linecolor)\n \n #Right Penalty Area\n plt.plot([130,113.5],[65,65],color=linecolor)\n plt.plot([113.5,113.5],[65,25],color=linecolor)\n plt.plot([113.5,130],[25,25],color=linecolor)\n \n #Left 6-yard Box\n plt.plot([0,5.5],[54,54],color=linecolor)\n plt.plot([5.5,5.5],[54,36],color=linecolor)\n plt.plot([5.5,0.5],[36,36],color=linecolor)\n \n #Right 6-yard Box\n plt.plot([130,124.5],[54,54],color=linecolor)\n plt.plot([124.5,124.5],[54,36],color=linecolor)\n plt.plot([124.5,130],[36,36],color=linecolor)\n \n #Prepare Circles\n centreCircle = plt.Circle((65,45),9.15,color=linecolor,fill=False)\n centreSpot = plt.Circle((65,45),0.8,color=linecolor)\n leftPenSpot = plt.Circle((11,45),0.8,color=linecolor)\n rightPenSpot = plt.Circle((119,45),0.8,color=linecolor)\n \n #Draw Circles\n ax.add_patch(centreCircle)\n ax.add_patch(centreSpot)\n ax.add_patch(leftPenSpot)\n ax.add_patch(rightPenSpot)\n \n #Prepare Arcs\n leftArc = Arc((11,45),height=18.3,width=18.3,angle=0,theta1=310,theta2=50,color=linecolor)\n rightArc = Arc((119,45),height=18.3,width=18.3,angle=0,theta1=130,theta2=230,color=linecolor)\n\n #Draw Arcs\n ax.add_patch(leftArc)\n ax.add_patch(rightArc)\n \n #Tidy Axes\n plt.axis('off')\n \n return fig,ax\n\ndef createGoalMouth():\n #Adopted from FC Python\n #Create figure\n fig=plt.figure()\n ax=fig.add_subplot(1,1,1)\n\n linecolor='black'\n\n #Pitch Outline & Centre Line\n plt.plot([0,65],[0,0], color=linecolor)\n plt.plot([65,65],[50,0], color=linecolor)\n plt.plot([0,0],[50,0], color=linecolor)\n \n #Left Penalty Area\n plt.plot([12.5,52.5],[16.5,16.5],color=linecolor)\n plt.plot([52.5,52.5],[16.5,0],color=linecolor)\n plt.plot([12.5,12.5],[0,16.5],color=linecolor)\n \n #Left 6-yard Box\n plt.plot([41.5,41.5],[5.5,0],color=linecolor)\n plt.plot([23.5,41.5],[5.5,5.5],color=linecolor)\n plt.plot([23.5,23.5],[0,5.5],color=linecolor)\n \n #Goal\n plt.plot([41.5-5.34,41.5-5.34],[-2,0],color=linecolor)\n plt.plot([23.5+5.34,41.5-5.34],[-2,-2],color=linecolor)\n plt.plot([23.5+5.34,23.5+5.34],[0,-2],color=linecolor)\n \n #Prepare Circles\n leftPenSpot = plt.Circle((65/2,11),0.8,color=linecolor)\n \n #Draw Circles\n ax.add_patch(leftPenSpot)\n \n #Prepare Arcs\n leftArc = Arc((32.5,11),height=18.3,width=18.3,angle=0,theta1=38,theta2=142,color=linecolor)\n \n #Draw Arcs\n ax.add_patch(leftArc)\n \n #Tidy Axes\n plt.axis('off')\n \n return fig,ax\n", "_____no_output_____" ], [ "import pandas as pd\nimport json", "_____no_output_____" ], [ "competitions = pd.read_json(DATA_PATH+\"competitions.json\")", "_____no_output_____" ], [ "competitions.head()", "_____no_output_____" ], [ "competitions.describe()", "_____no_output_____" ], [ "competitions.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 37 entries, 0 to 36\nData columns (total 8 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 competition_id 37 non-null int64 \n 1 season_id 37 non-null int64 \n 2 country_name 37 non-null object\n 3 competition_name 37 non-null object\n 4 competition_gender 37 non-null object\n 5 season_name 37 non-null object\n 6 match_updated 37 non-null object\n 7 match_available 37 non-null object\ndtypes: int64(2), object(6)\nmemory usage: 2.4+ KB\n" ], [ "competitions[\"competition_id\"].unique(), competitions[\"competition_id\"].nunique()", "_____no_output_____" ], [ "#show all the competitions and the related files for matches\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\nfor i in competitions[\"competition_id\"].unique():\n print(competitions[competitions[\"competition_id\"]==i])", " competition_id season_id country_name competition_name \\\n0 16 4 Europe Champions League \n1 16 1 Europe Champions League \n2 16 2 Europe Champions League \n3 16 27 Europe Champions League \n4 16 26 Europe Champions League \n5 16 25 Europe Champions League \n6 16 24 Europe Champions League \n7 16 23 Europe Champions League \n8 16 22 Europe Champions League \n9 16 21 Europe Champions League \n10 16 41 Europe Champions League \n11 16 39 Europe Champions League \n12 16 37 Europe Champions League \n13 16 44 Europe Champions League \n14 16 76 Europe Champions League \n\n competition_gender season_name match_updated \\\n0 male 2018/2019 2020-07-29T05:00 \n1 male 2017/2018 2020-07-29T05:00 \n2 male 2016/2017 2020-08-26T12:33:15.869622 \n3 male 2015/2016 2020-08-26T12:33:15.869622 \n4 male 2014/2015 2020-08-26T12:33:15.869622 \n5 male 2013/2014 2020-08-26T12:33:15.869622 \n6 male 2012/2013 2020-08-26T12:33:15.869622 \n7 male 2011/2012 2020-08-26T12:33:15.869622 \n8 male 2010/2011 2020-07-29T05:00 \n9 male 2009/2010 2020-07-29T05:00 \n10 male 2008/2009 2020-08-30T10:18:39.435424 \n11 male 2006/2007 2020-07-29T05:00 \n12 male 2004/2005 2020-07-29T05:00 \n13 male 2003/2004 2020-08-30T10:18:39.435424 \n14 male 1999/2000 2020-07-29T05:00 \n\n match_available \n0 2020-07-29T05:00 \n1 2020-07-29T05:00 \n2 2020-07-29T05:00 \n3 2020-07-29T05:00 \n4 2020-07-29T05:00 \n5 2020-07-29T05:00 \n6 2020-07-29T05:00 \n7 2020-07-29T05:00 \n8 2020-07-29T05:00 \n9 2020-07-29T05:00 \n10 2020-08-30T10:18:39.435424 \n11 2020-07-29T05:00 \n12 2020-07-29T05:00 \n13 2020-08-30T10:18:39.435424 \n14 2020-07-29T05:00 \n competition_id season_id country_name competition_name \\\n15 37 42 England FA Women's Super League \n16 37 4 England FA Women's Super League \n\n competition_gender season_name match_updated \\\n15 female 2019/2020 2020-09-30T14:59:21.257704 \n16 female 2018/2019 2020-08-24T14:34:34.401523 \n\n match_available \n15 2020-09-30T14:59:21.257704 \n16 2020-08-24T14:34:34.401523 \n competition_id season_id country_name competition_name \\\n17 43 3 International FIFA World Cup \n\n competition_gender season_name match_updated match_available \n17 male 2018 2020-07-29T05:00 2020-07-29T05:00 \n competition_id season_id country_name competition_name \\\n18 11 42 Spain La Liga \n19 11 4 Spain La Liga \n20 11 1 Spain La Liga \n21 11 2 Spain La Liga \n22 11 27 Spain La Liga \n23 11 26 Spain La Liga \n24 11 25 Spain La Liga \n25 11 24 Spain La Liga \n26 11 23 Spain La Liga \n27 11 22 Spain La Liga \n28 11 21 Spain La Liga \n29 11 41 Spain La Liga \n30 11 40 Spain La Liga \n31 11 39 Spain La Liga \n32 11 38 Spain La Liga \n33 11 37 Spain La Liga \n\n competition_gender season_name match_updated \\\n18 male 2019/2020 2020-10-11T20:05:57.703730 \n19 male 2018/2019 2020-07-29T05:00 \n20 male 2017/2018 2020-07-29T05:00 \n21 male 2016/2017 2020-10-09T04:20:42.205355 \n22 male 2015/2016 2020-07-29T05:00 \n23 male 2014/2015 2020-07-29T05:00 \n24 male 2013/2014 2020-07-29T05:00 \n25 male 2012/2013 2020-07-29T05:00 \n26 male 2011/2012 2020-07-29T05:00 \n27 male 2010/2011 2020-07-29T05:00 \n28 male 2009/2010 2020-07-29T05:00 \n29 male 2008/2009 2020-07-29T05:00 \n30 male 2007/2008 2020-07-29T05:00 \n31 male 2006/2007 2020-07-29T05:00 \n32 male 2005/2006 2020-07-29T05:00 \n33 male 2004/2005 2020-07-29T05:00 \n\n match_available \n18 2020-10-11T20:05:57.703730 \n19 2020-07-29T05:00 \n20 2020-07-29T05:00 \n21 2020-10-09T04:20:42.205355 \n22 2020-07-29T05:00 \n23 2020-07-29T05:00 \n24 2020-07-29T05:00 \n25 2020-07-29T05:00 \n26 2020-07-29T05:00 \n27 2020-07-29T05:00 \n28 2020-07-29T05:00 \n29 2020-07-29T05:00 \n30 2020-07-29T05:00 \n31 2020-07-29T05:00 \n32 2020-07-29T05:00 \n33 2020-07-29T05:00 \n competition_id season_id country_name competition_name \\\n34 49 3 United States of America NWSL \n\n competition_gender season_name match_updated match_available \n34 female 2018 2020-07-29T05:00 2020-07-29T05:00 \n competition_id season_id country_name competition_name \\\n35 2 44 England Premier League \n\n competition_gender season_name match_updated \\\n35 male 2003/2004 2020-08-31T20:40:28.969635 \n\n match_available \n35 2020-08-31T20:40:28.969635 \n competition_id season_id country_name competition_name \\\n36 72 30 International Women's World Cup \n\n competition_gender season_name match_updated match_available \n36 female 2019 2020-07-29T05:00 2020-07-29T05:00 \n" ], [ "# show files\nimport glob\ncompetitions_path_list = glob.glob(MATCHES_PATH+\"/*\")\ncompetition_file_dict = {}\nfor i in competitions_path_list:\n competition_file_dict[i] = glob.glob(i+\"/*.json\")\ncompetition_file_dict", "_____no_output_____" ], [ "DATA_PATH", "_____no_output_____" ], [ "with open(DATA_PATH + 'matches/72/30.json') as f:\n matches = json.load(f)", "_____no_output_____" ], [ "matches[0]", "_____no_output_____" ], [ "for match in matches:\n if match[\"home_team\"]['home_team_name']==\"Sweden Women's\" or match[\"away_team\"]['away_team_name']==\"Sweden Women's\":\n print(\"match between: \"+ match[\"home_team\"]['home_team_name']+\" vs \" +match[\"away_team\"]['away_team_name'] +\" with score {}:{}\".format(match[\"home_score\"],match[\"away_score\"]))", "match between: Sweden Women's vs Canada Women's with score 1:0\nmatch between: England Women's vs Sweden Women's with score 1:2\nmatch between: Germany Women's vs Sweden Women's with score 1:2\nmatch between: Sweden Women's vs Thailand Women's with score 5:1\nmatch between: Chile Women's vs Sweden Women's with score 0:2\nmatch between: Sweden Women's vs United States Women's with score 0:2\nmatch between: Netherlands Women's vs Sweden Women's with score 1:0\n" ] ], [ [ "# Pitch map", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np", "_____no_output_____" ], [ "pitchLenX = 120\npitchWidY = 80", "_____no_output_____" ], [ "match_id = 69301\ndef get_match(match_id):\n for i in matches:\n if i[\"match_id\"]==match_id:\n return i\ndef get_event(match_id):\n with open(DATA_PATH+\"events/\"+str(match_id)+\".json\") as f:\n event = json.load(f)\n return event\nmatch = get_match(match_id)\nevents = get_event(match_id)", "_____no_output_____" ], [ "match", "_____no_output_____" ], [ "events_df = pd.json_normalize(events)", "_____no_output_____" ], [ "events_df.columns.values", "_____no_output_____" ], [ "shots = events_df[events_df[\"type.name\"]==\"Shot\"]\nshots[[\"period\",\"minute\",\"location\",\"team.name\",\"shot.outcome.name\"]]", "_____no_output_____" ], [ "(fig,ax) = createPitch(pitchLenX,pitchWidY,\"yards\",\"grey\")", "_____no_output_____" ], [ "for i,shot in shots.iterrows():\n x = shot.location[0]\n y = shot.location[1]\n\n goal = shot[\"shot.outcome.name\"] == \"Goal\"\n shot_team = shot[\"team.name\"]\n\n circle_size = np.sqrt(shot[\"shot.statsbomb_xg\"]*15)\n print(circle_size)\n\n if shot_team == \"Sweden Women's\":\n if goal:\n shotCircle = plt.Circle((x,pitchWidY-y),circle_size,color=\"red\")\n #plt.text(x,pitchWidY-y,\"hi\") \n else:\n shotCircle = plt.Circle((x,pitchWidY-y),circle_size,color=\"red\")\n shotCircle.set_alpha(0.2)\n else:\n if goal:\n shotCircle = plt.Circle((pitchLenX-x,y),circle_size,color=\"blue\")\n #plt.text((pitchLenX-x+1),y+1,shot['player.name']) \n else:\n shotCircle = plt.Circle((pitchLenX-x,y),circle_size,color=\"blue\")\n shotCircle.set_alpha(0.2)\n ax.add_patch(shotCircle)\n #\"England Women's\"\n#plt.show()", "1.3154804445524837\n0.8414811049572058\n0.6491755771746192\n0.453465877988631\n1.3482839092713375\n0.39473485404762526\n2.0316760322452985\n1.723552871251706\n0.456252380815706\n0.36295789011950136\n0.47181022668017697\n1.1621432097637536\n0.7438810792055408\n0.716430694484819\n0.35235837580508855\n0.8354685810968597\n1.3415841009791374\n0.36648144564220436\n2.0386098204413714\n" ], [ "fig", "_____no_output_____" ] ], [ [ "# passes plotting", "_____no_output_____" ] ], [ [ "#passes = events_df[(events_df[\"type.name\"]==\"Pass\") & (events_df[\"player.name\"]==\"Sara Caroline Seger\") & (events_df[\"play_pattern.name\"]==\"Regular Play\")]\npasses = events_df[(events_df[\"type.name\"]==\"Pass\") & (events_df[\"player.name\"]==\"Sara Caroline Seger\")]\n# shots[[\"period\",\"minute\",\"location\",\"team.name\",\"shot.outcome.name\"]]\n#\n#events_df[\"type.name\"].unique()", "_____no_output_____" ], [ "#passes[[\"location\"]+[i for i in passes.columns.values if \"pass\" in i]]\npasses", "_____no_output_____" ], [ "(fig,ax) = createPitch(pitchLenX,pitchWidY,\"yards\",\"green\")\nfig.set_size_inches(15, 10.5)\nfor i,shot in passes.iterrows():\n x_start = shot.location[0]\n y_start = shot.location[1]\n x_end = shot[\"pass.end_location\"][0]\n y_end = shot[\"pass.end_location\"][1]\n #goal = shot[\"shot.outcome.name\"] == \"Goal\"\n\n #circle_size = np.sqrt(shot[\"shot.statsbomb_xg\"]*15)\n #print(circle_size)\n shotarrow = plt.Arrow(x_start, pitchWidY-y_start, x_end-x_start, pitchWidY-y_end-pitchWidY+y_start,width=2,color=\"blue\")\n ax.add_patch(shotarrow)\n #\"England Women's\"\n#plt.show()", "_____no_output_____" ], [ "(fig, ax) = createPitch(120, 80, 'yards', 'gray')\n\nfor i, p in passes.iterrows(): \n x, y = p.location\n x, y = (x,pitchWidY-y)\n\n end_x, end_y = p[\"pass.end_location\"]\n end_x, end_y = (end_x, pitchWidY-end_y)\n\n start_circle = plt.Circle((x, y), 1, alpha=.2, color=\"blue\")\n pass_arrow = plt.Arrow(x, y, end_x - x, end_y - y, width=2, color=\"blue\")\n ax.add_patch(pass_arrow)\n ax.add_patch(start_circle)\n\nfig.set_size_inches(15, 10.5)\nplt.show()", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cbe45108da820b62c0de8b70bc2d0f3eb88426b4
11,325
ipynb
Jupyter Notebook
4_6_Matrices_and_Transformation_of_State/.ipynb_checkpoints/1_vector_coding-checkpoint.ipynb
ramanpreet9/CVND_udacity
d70e3dd897c463eb594e7804bc4c323cc7b4a704
[ "MIT" ]
null
null
null
4_6_Matrices_and_Transformation_of_State/.ipynb_checkpoints/1_vector_coding-checkpoint.ipynb
ramanpreet9/CVND_udacity
d70e3dd897c463eb594e7804bc4c323cc7b4a704
[ "MIT" ]
5
2021-03-19T01:13:24.000Z
2022-03-11T23:49:57.000Z
4_6_Matrices_and_Transformation_of_State/1_vector_coding.ipynb
ramanpreet9/CVND_udacity
d70e3dd897c463eb594e7804bc4c323cc7b4a704
[ "MIT" ]
null
null
null
32.731214
310
0.573775
[ [ [ "# Vectors in Python\n\nIn the following exercises, you will work on coding vectors in Python.\n\nAssume that you have a state vector \n$$\\mathbf{x_0}$$\n\nrepresenting the x position, y position, velocity in the x direction, and velocity in the y direction of a car that is driving in front of your vehicle. You are tracking the other vehicle.\n\nCurrently, the other vehicle is 5 meters ahead of you along your x-axis, 2 meters to your left along your y-axis, driving 10 m/s in the x direction and 0 m/s in the y-direction. How would you represent this in a Python list where the vector contains `<x, y, vx, vy>` in exactly that order? \n\n\n### Vector Assignment: Example 1", "_____no_output_____" ] ], [ [ "## Practice working with Python vectors\n\n## TODO: Assume the state vector contains values for <x, y, vx, vy>\n## Currently, x = 5, y = 2, vx = 10, vy = 0\n## Represent this information in a list\nx0 = [5, 2, 10, 0]\n", "_____no_output_____" ] ], [ [ "### Test your code\n\nRun the cell below to test your code. \n\nThe test code uses a Python assert statement. If you have a code statement that resolves to either True or False, an assert statement will either:\n* do nothing if the statement is True\n* throw an error if the statement is False\n\n\nA Python assert statement\nwill output an error if the answer was not as expected. If the\nanswer was as expected, then nothing will be outputted.", "_____no_output_____" ] ], [ [ "### Test Cases \n### Run these test cases to see if your results are as expected\n### Running this cell should produce no output if all assertions are True\n\nassert x0 == [5, 2, 10, 0]", "_____no_output_____" ] ], [ [ "### Vector Assignment: Example 2\n\nThe vehicle ahead of you has now moved farther away from you. You know that the vehicle has moved 3 meters forward in the x-direction, 5 meters forward in the y-direction, has increased its x velocity by 2 m/s and has increased its y velocity by 5 m/s. \n\nStore the change in position and velocity in a list variable called xdelta", "_____no_output_____" ] ], [ [ "## TODO: Assign the change in position and velocity to the variable\n## xdelta. Remember that the order of the vector is x, y, vx, vy\n\nxdelta = [3, 5, 2, 5]", "_____no_output_____" ], [ "### Test Case \n### Run this test case to see if your results are as expected\n### Running this cell should produce no output if all assertions are True\n\nassert xdelta == [3, 5, 2, 5]", "_____no_output_____" ] ], [ [ "### Vector Math: Addition\n\nCalculate the tracked vehicle's new position and velocity. Here are the steps you need to carry this out:\n\n* initialize an empty list called x1\n* add xdelta to x0 using a for loop\n* store your results in x1 as you iterate through the for loop using the append method", "_____no_output_____" ] ], [ [ "## TODO: Add the vectors together element-wise. For example, \n## element-wise addition of [2, 6] and [10, 3] is [12, 9].\n## Place the answer in the x1 variable. \n##\n## Hint: You can use a for loop. The append method might also\n## be helpful.\n\nx1 = []\nfor i in range(len(x0)):\n x1.append(x0[i]+xdelta[i])\nprint(x1)", "[8, 7, 12, 5]\n" ], [ "### Test Case \n### Run this test case to see if your results are as expected\n### Running this cell should produce no output if all assertions are True\nassert x1 == [8, 7, 12, 5]", "_____no_output_____" ] ], [ [ "### Vector Math: Scalar Multiplication\n\nYou have your current position in meters and current velocity in meters per second. But you need to report your results at a company meeting where most people will only be familiar with working in feet rather than meters. Convert your position vector x1 to feet and feet/second.\n\nThis will involve scalar multiplication. The process for coding scalar multiplication is very similar to vector addition. You will need to:\n* initialize an empty list\n* use a for loop to access each element in the vector\n* multiply each element by the scalar\n* append the result to the empty list", "_____no_output_____" ] ], [ [ "## TODO: Multiply each element in the x1 vector by the conversion\n## factor shown belowand store the results in the variable s. \n## Use a for loop\n\nmeters_to_feet = 1.0 / 0.3048\nx1feet = []\nfor i in range(len(x1)):\n x1feet.append(meters_to_feet*x1[i])\nprint(x1feet)", "[26.246719160104984, 22.96587926509186, 39.370078740157474, 16.404199475065614]\n" ], [ "### Test Cases\n### Run this test case to see if your results are as expected\n### Running this cell should produce no output if all assertions are True\nx1feet_sol = [8/.3048, 7/.3048, 12/.3048, 5/.3048]\n\nassert(len(x1feet) == len(x1feet_sol)) \nfor response, expected in zip(x1feet, x1feet_sol):\n assert(abs(response-expected) < 0.001)", "_____no_output_____" ] ], [ [ "### Vector Math: Dot Product\n\nThe tracked vehicle is currently at the state represented by \n$$\\mathbf{x_1} = [8, 7, 12, 5] $$.\n\nWhere will the vehicle be in two seconds?\n\nYou could actually solve this problem very quickly using Matrix multiplication, but we have not covered that yet. Instead, think about the x-direction and y-direction separately and how you could do this with the dot product.\n\n#### Solving with the Dot Product\nYou know that the tracked vehicle at x1 is 8m ahead of you in the x-direction and traveling at 12m/s. Assuming constant velocity, the new x-position after 2 seconds would be\n\n$$8 + 12*2 = 32$$\n\nThe new y-position would be\n$$7 + 5*2 = 17$$\n\nYou could actually solve each of these equations using the dot product:\n\n$$x_2 = [8, 7, 12, 5]\\cdot[1, 0, 2, 0] \\\\\\ \n= 8\\times1 + 7\\times0 + 12\\times2 + 5\\times0 \\\\\\\n= 32$$\n\n$$y_2 = [8, 7, 12, 5]\\cdot[0, 1, 0, 2] \\\\\\ \n= 8\\times0 + 7\\times1 + 12\\times0 + 5\\times2 \\\\\\\n= 17$$\n\nSince you are assuming constant velocity, the final state vector would be \n\n$$\\mathbf{x_2} = [32, 17, 12, 5]$$\n\n#### Coding the Dot Product\n\nNow, calculate the state vector $$\\mathbf{x_2}$$ but with code. You will need to calculate the dot product of two vectors. Rather than writing the dot product code for the x-direction and then copying the code for the y-direction, write a function that calculates the dot product of two Python lists.\n\nHere is an outline of the steps:\n* initialize an empty list\n* initialize a variable with value zero to accumulate the sum\n* use a for loop to iterate through the vectors. Assume the two vectors have the same length\n* accumulate the sum as you multiply elements together\n\nYou will see in the starter code that x2 is already being calculated for you based on the results of your dotproduct function", "_____no_output_____" ] ], [ [ "## TODO: Fill in the dotproduct() function to calculate the \n## dot product of two vectors.\n##\n\n## Here are the inputs and outputs of the dotproduct() function:\n## INPUTS: vector, vector\n## OUTPUT: dot product of the two vectors\n## \n##\n## The dot product involves mutliplying the vectors element\n## by element and then taking the sum of the results\n##\n## For example, the dot product of [9, 7, 5] and [2, 3, 4] is \n## 9*2+7*3 +5*4 = 59\n## \n## Hint: You can use a for loop. You will also need to accumulate\n## the sum as you iterate through the vectors. In Python, you can accumulate \n## sums with syntax like w = w + 1\n\nx2 = []\n\ndef dotproduct(vectora, vectorb):\n \n # variable for accumulating the sum\n result = 0\n \n # TODO: Use a for loop to multiply the two vectors\n # element by element. Accumulate the sum in the result variable\n for i in range(len(vectora)):\n result+=vectora[i]*vectorb[i]\n \n return result\n \nx2 = [dotproduct([8, 7, 12, 5], [1, 0, 2, 0]), \n dotproduct([8, 7, 12, 5], [0, 1, 0, 2]),\n 12,\n 5]", "_____no_output_____" ], [ "### Test Case\n### Run this test case to see if your results are as expected\n### Running this cell should produce no output if all assertions are True\nassert x2 == [32, 17, 12, 5]", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe45c44aec62aa4dca440e6459c250d9c592fa7
230,820
ipynb
Jupyter Notebook
LGBM(41)/Data in 5 files(41).ipynb
sokolovm19/malware_prediction
0d9e5f1a59792e434eabfd19138b6a41e42fc116
[ "MIT" ]
null
null
null
LGBM(41)/Data in 5 files(41).ipynb
sokolovm19/malware_prediction
0d9e5f1a59792e434eabfd19138b6a41e42fc116
[ "MIT" ]
null
null
null
LGBM(41)/Data in 5 files(41).ipynb
sokolovm19/malware_prediction
0d9e5f1a59792e434eabfd19138b6a41e42fc116
[ "MIT" ]
null
null
null
41.484543
362
0.266515
[ [ [ "%matplotlib inline\n\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier, forest\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nimport matplotlib.pyplot as plt\nfrom IPython.display import display\nimport numpy as np\nimport scipy\nimport re\ntrain = pd.read_csv('train41.csv')", "/python3.7/site-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.ensemble.forest module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.ensemble. Anything that cannot be imported from sklearn.ensemble is now part of the private API.\n warnings.warn(message, FutureWarning)\n" ], [ "df, drop = train.drop('Unnamed: 0', axis=1), train['Unnamed: 0']", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df1, df2345 = df.iloc[:1427437, :], df.iloc[1427437:, :]", "_____no_output_____" ], [ "df1", "_____no_output_____" ], [ "df2345", "_____no_output_____" ], [ "df2, df345 = df2345.iloc[:1427437, :], df2345.iloc[1427437:, :]", "_____no_output_____" ], [ "df2", "_____no_output_____" ], [ "df3, df45 = df345.iloc[:1427437, :], df345.iloc[1427437:, :]", "_____no_output_____" ], [ "df4, df5 = df45.iloc[:1427437, :], df45.iloc[1427437:, :]", "_____no_output_____" ], [ "df2.reset_index()", "_____no_output_____" ], [ "df3.reset_index()", "_____no_output_____" ], [ "df4.reset_index()", "_____no_output_____" ], [ "df5.reset_index()", "_____no_output_____" ], [ "df1.to_csv('df1.csv')", "_____no_output_____" ], [ "df22 = df2.reset_index()", "_____no_output_____" ], [ "df222, drop = df22.drop('index', axis=1), df22['index']", "_____no_output_____" ], [ "df222", "_____no_output_____" ], [ "df222.to_csv('df2.csv')", "_____no_output_____" ], [ "df33 = df3.reset_index()\ndf333, drop = df33.drop('index', axis=1), df33['index']\ndf333", "_____no_output_____" ], [ "df333.to_csv('df3.csv')", "_____no_output_____" ], [ "df44 = df4.reset_index()\ndf444, drop = df44.drop('index', axis=1), df44['index']\ndf444", "_____no_output_____" ], [ "df444.to_csv('df4.csv')", "_____no_output_____" ], [ "df55 = df5.reset_index()\ndf555, drop = df55.drop('index', axis=1), df55['index']\ndf555", "_____no_output_____" ], [ "df555.to_csv('df5.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe46142f10b7297dc4c38b9eafdeb2d048f605e
655,911
ipynb
Jupyter Notebook
serbia_neighbours_indicators.ipynb
nitrif/WorldBank
5affd83d3e8ae18e42dd179fe9d1618a8023d8d3
[ "Unlicense" ]
null
null
null
serbia_neighbours_indicators.ipynb
nitrif/WorldBank
5affd83d3e8ae18e42dd179fe9d1618a8023d8d3
[ "Unlicense" ]
null
null
null
serbia_neighbours_indicators.ipynb
nitrif/WorldBank
5affd83d3e8ae18e42dd179fe9d1618a8023d8d3
[ "Unlicense" ]
1
2020-03-05T09:05:35.000Z
2020-03-05T09:05:35.000Z
3,507.545455
127,410
0.949862
[ [ [ "import requests\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "Countries and indicators to compare", "_____no_output_____" ] ], [ [ "#countries = ['SRB', 'HRV', 'BIH', 'MKD', 'ALB', 'BGR', 'ROM', 'SVN', 'GRC', 'HUN']\ncountries = ['SRB', 'HRV', 'BIH', 'MKD', 'ALB', 'BGR', 'ROM', 'HUN']\n\nindicators = [\n 'NY.GDP.MKTP.CD', # GDP\n 'NY.GDP.PCAP.CD', # GDP per capita\n 'NY.GDP.PCAP.KD.ZG', # GDP per capita growth (annual %)\n #'NY.GDP.MKTP.PP.CD', # PPP\n 'NY.GDP.PCAP.PP.CD', # PPP per capita\n #'NY.GNP.MKTP.CD', # GNI\n 'NY.GNP.MKTP.PC.CD', # GNI per capita\n #'3.0.Gini', # GINI\n 'VC.IHR.PSRC.P5', # Intentional homicides (per 100,000 people)\n 'SL.UEM.TOTL.ZS', # Unemployment, total (% of total labor force)\n 'SP.POP.TOTL' # Population, total'\n ]", "_____no_output_____" ], [ "def get_country_indicator(country_code, indicator):\n #url = 'http://api.worldbank.org/v2/countries/{}/indicators/{}?format=json'.format(country_code, indicator)\n url = 'http://api.worldbank.org/v2/countries/{}/indicators/{}?date=2008:2020&format=json'.format(country_code, indicator)\n #print('GET: ' + url)\n json_response = requests.get(url).json()\n time.sleep(0.5)\n return json_response\n\ndef parse_response(json_response):\n values = [[json_response[1][i]['date'], json_response[1][i]['value']] for i in range(len(json_response[1]))]\n country_name = json_response[1][0]['country']['value']\n indicator_name = json_response[1][0]['indicator']['value']\n return np.array(values), country_name, indicator_name\n\nfor indicator in indicators:\n fig = plt.figure(figsize=(15,8))\n for country in countries:\n json_response = get_country_indicator(country, indicator)\n values, country_name, indicator_name = parse_response(json_response)\n plt.plot(values[:,0], values[:,1].astype(np.float), label=country_name)\n\n plt.title(indicator_name)\n plt.legend(loc=2)\n plt.grid()\n plt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cbe4660bbc8b321faf884be8e77d53313dfea295
6,035
ipynb
Jupyter Notebook
Appendix3_Materials/Video_Lectures_NBs/NB_06_Data_Visualization_1.ipynb
suparera/algopython
43ef84871f565f50182bdda10e973e68acf025da
[ "Apache-2.0" ]
null
null
null
Appendix3_Materials/Video_Lectures_NBs/NB_06_Data_Visualization_1.ipynb
suparera/algopython
43ef84871f565f50182bdda10e973e68acf025da
[ "Apache-2.0" ]
null
null
null
Appendix3_Materials/Video_Lectures_NBs/NB_06_Data_Visualization_1.ipynb
suparera/algopython
43ef84871f565f50182bdda10e973e68acf025da
[ "Apache-2.0" ]
null
null
null
18.859375
151
0.492626
[ [ [ "# Appendix 3: Python Libraries Crash Course", "_____no_output_____" ], [ "## Part 6: Data Visualization with Matplotlib", "_____no_output_____" ], [ "## The plot() method", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ], [ "titanic = pd.read_csv(\"titanic.csv\")", "_____no_output_____" ], [ "titanic.head()", "_____no_output_____" ], [ "titanic.info()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "titanic.plot(subplots= True, figsize=(15, 12), sharex= False, sharey=False)\nplt.show()", "_____no_output_____" ], [ "titanic.age.plot(figsize=(12, 8))\nplt.show()", "_____no_output_____" ] ], [ [ "## Customization", "_____no_output_____" ] ], [ [ "xticks = [x for x in range(0,901, 50)]\nxticks", "_____no_output_____" ], [ "yticks = [y for y in range(0, 81, 5)]\nyticks", "_____no_output_____" ], [ "plt.style.available", "_____no_output_____" ], [ "plt.style.use(\"classic\")", "_____no_output_____" ], [ "titanic.age.plot(figsize = (12,8), fontsize= 13, c = \"r\", linestyle = \"-\",\n xlim = (0,900), ylim = (0,80), xticks = xticks, yticks = yticks, rot = 45) \nplt.title(\"Titanic - Ages\", fontsize = 15)\nplt.legend(loc = 3, fontsize = 15)\nplt.xlabel(\"Passenger No\", fontsize = 13)\nplt.ylabel(\"Age\", fontsize = 13)\n#plt.grid()\nplt.show()", "_____no_output_____" ] ], [ [ "## Histograms", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn\")", "_____no_output_____" ], [ "titanic = pd.read_csv(\"titanic.csv\")", "_____no_output_____" ], [ "titanic.head()", "_____no_output_____" ], [ "titanic.age.value_counts()", "_____no_output_____" ], [ "titanic.age.plot(kind = \"hist\", figsize = (12,8), fontsize = 15, bins = 80, density = True)\nplt.show()", "_____no_output_____" ], [ "titanic.age.hist(figsize = (12,8), bins = 80, xlabelsize=15, ylabelsize= 15, cumulative = True)\nplt.show()", "_____no_output_____" ], [ "plt.figure(figsize = (12,8))\nplt.hist(titanic.age.dropna(), bins = 80, density = True, cumulative= True)\nplt.show()", "_____no_output_____" ] ], [ [ "## Scatterplots", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn\")", "_____no_output_____" ], [ "titanic = pd.read_csv(\"titanic.csv\")", "_____no_output_____" ], [ "titanic.head()", "_____no_output_____" ], [ "titanic.plot(kind = \"scatter\", figsize = (15,8), x = \"age\", y = \"fare\", c = \"pclass\", marker = \"x\", s = 20, colormap= \"viridis\" ) \nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe46e81ff9f7c2baf63180c74054aeed7ebe998
7,815
ipynb
Jupyter Notebook
materials/materials/lectures/13-reproducibility-wrap-up.ipynb
UBC-DSCI/reproducible-and-trustworthy-workflows-for-data-science
6676e628ec858acdfae43fbf5b27891849952e83
[ "CC-BY-4.0" ]
null
null
null
materials/materials/lectures/13-reproducibility-wrap-up.ipynb
UBC-DSCI/reproducible-and-trustworthy-workflows-for-data-science
6676e628ec858acdfae43fbf5b27891849952e83
[ "CC-BY-4.0" ]
1
2022-01-06T00:23:55.000Z
2022-01-06T00:23:55.000Z
materials/materials/lectures/13-reproducibility-wrap-up.ipynb
UBC-DSCI/reproducible-and-trustworthy-workflows-for-data-science
6676e628ec858acdfae43fbf5b27891849952e83
[ "CC-BY-4.0" ]
null
null
null
46.242604
401
0.677159
[ [ [ "# Workflows for reproducibile and trustworthy data science wrap-up\n\nThis topic serves as a wrap-up of the course, summarizing the course learning objectives, redefining what is meant by reproducible and trustworthy data science, as well as contains data analysis project critique exercises to reinforce what has been learned in the course.\n\n## Course learning objectives\n\nBy the end of this course, students should be able to:\n\n- Defend and justify the importance of creating data science workflows that are\nreproducible and trustworthy and the elements that go into such a workflow (e.g.,\nwriting clear, robust, accurate and reproducible code, managing and sharing compute\nenvironments, defined collaboration strategies, etc).\n- Constructively criticize the workflows and data analysis of others in regards to its\nreproducibility and trustworthiness.\n- Develop a data science project (including code and non-code documents such as\nreports) that uses reproducible and trustworthy workflows\n- Demonstrate how to effectively share and collaborate on data science projects and\nsoftware by creating robust code packages, using reproducible compute environments,\nand leveraging collaborative development tools.\n- Defend and justify the benefit of, and employ automated testing regimes, continuous\nintegration and continuous deployment for managing and maintaining data science\nprojects and packages.\n- Demonstrate strong communication, teamwork, and collaborative skills by working on\na significant data science project with peers throughout the course.", "_____no_output_____" ], [ "## Definitions review:\n\n### Data science\n\n*the study, development and practice of __reproducible and auditable processes__ to obtain __insight from data.__*\n\nFrom this definition, we must also define reproducible and auditable analysis:\n\n### Reproducible analysis:\n*reaching the same result given the same input, computational methods and conditions $^1$.*\n\n- input = data\n- computational methods = computer code\n- conditions = computational environment (e.g., programming language & it's dependencies)\n\n### Auditable/transparent analysis,\n*a readable record of the steps used to carry out the analysis as well as a record of how the analysis methods evolved $^2$.*\n\n1. [National Academies of Sciences, 2019](https://www.nap.edu/catalog/25303/reproducibility-and-replicability-in-science)\n2. [Parker, 2017](https://peerj.com/preprints/3210/) and [Ram, 2013](https://scfbm.biomedcentral.com/articles/10.1186/1751-0473-8-7)", "_____no_output_____" ], [ "## What makes trustworthy data science?\n\nSome possible criteria:\n\n1. It should be reproducible and auditable\n\n2. It should be correct \n\n3. It should be fair, equitable and honest\n\nThere are many ways a data science can be untrustworthy... In this course we will focus on workflows that can help build trust. I highly recommend taking a course in data science ethics* to help round out your education in how to do this. Further training in statistics and machine learning will also help with making sure your analysis is correct.\n\n>*\\* UBC's CPSC 430 (Computers and Society) will have a section reserved for DSCI minor students next year in 2022 T1, which will focus on ethics in data science.*", "_____no_output_____" ], [ "#### Exercise\n\nAnswer the questions below to more concretely connect with the criteria suggested above.\n\n1. Give an example of a data science workflow that affords reproducibility, and one that affords auditable analysis.\n\n2. Can a data analysis be reproducible but not auditable? How about auditable, but not reproducible?\n\n3. Name at least two ways that a data analysis project could be correct (or incorrect).", "_____no_output_____" ], [ "## Critiquing data analysis projects\n\nCritiquing is defined as evaluating something in a detailed and analytical way \n(source: [Oxford Languages Dictionary](https://languages.oup.com/dictionaries/)).\nIt is used in many domains as a means to improve something (related to peer review),\nbut also serves as an excellent pedagogical tool to actively practice evaluation.\n\nWe will work together in class to critique the following projects from the lens of reproducible and trustworthy workflows:\n\n- [Genomic data and code](https://github.com/ttimbers/Million-Mutation-Project-dye-filling-SKAT) to accompany the \"Accelerating Gene Discovery by Phenotyping Whole-Genome Sequenced Multi-mutation Strains and Using the Sequence Kernel Association Test (SKAT)\" manuscript by [Timbers et al., PLoS Genetics, 2015](https://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1006235)\n\n- [Data and code](https://github.com/jasonpriem/plos_altmetrics_study) to accompany the \"Altmetrics in the wild: Using social media to explore scholarly impact\" manuscript by [Priem et al., arXiv, 2021](https://arxiv.org/abs/1203.4745)\n\n- [Code](https://github.com/sacadena/Cadena2019PlosCB) to accompany the \"Deep convolutional models improve predictions of macaque V1 responses to natural images\" manuscript by [Cadena et al., PLoS Computational Biology, 2019](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1006897)\n", "_____no_output_____" ], [ "### Exercise\n\nWhen prompted for each project listed above:\n\n- In groups of ~5, take 10 minutes to review the project from the lens of reproducible and trustworthy workflows. You want to evaluate the project with the questions in mind: \n - Would I know where to get started reproducing the project?\n - If I could get started, do I think I could reproduce the project?\n\n\n\n- As a group, come up with at least 1-2 things that have been done well, as well as 1-2 things that could be improved\n from this lens. Justify these with respect to reproducibility and trustworthiness.\n\n- Choose one person to be the reporter to bring back these critiques to the larger group.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbe478d65b7e31dc8f55e8fc08e4525a08b295d1
37,095
ipynb
Jupyter Notebook
1 - Fundamental of GANs/dcgan_faces_tutorial.ipynb
DSC-UI-SRIN/Introduction-to-GAN
477d414b21dc28af5476008213dba4ec284bfd2f
[ "MIT" ]
21
2019-11-20T03:26:32.000Z
2022-03-01T15:51:57.000Z
1 - Fundamental of GANs/dcgan_faces_tutorial.ipynb
DSC-UI-SRIN/Introduction-to-GAN
477d414b21dc28af5476008213dba4ec284bfd2f
[ "MIT" ]
1
2019-11-02T03:20:43.000Z
2019-11-02T03:20:43.000Z
1 - Fundamental of GANs/dcgan_faces_tutorial.ipynb
DSC-UI-SRIN/Introduction-to-GAN
477d414b21dc28af5476008213dba4ec284bfd2f
[ "MIT" ]
10
2019-11-20T02:45:41.000Z
2022-02-08T10:58:32.000Z
39.97306
206
0.580752
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nDCGAN Tutorial\n==============\n\n**Author**: `Nathan Inkawhich <https://github.com/inkawhich>`__\n\n\n", "_____no_output_____" ], [ "Introduction\n------------\n\nThis tutorial will give an introduction to DCGANs through an example. We\nwill train a generative adversarial network (GAN) to generate new\ncelebrities after showing it pictures of many real celebrities. Most of\nthe code here is from the dcgan implementation in\n`pytorch/examples <https://github.com/pytorch/examples>`__, and this\ndocument will give a thorough explanation of the implementation and shed\nlight on how and why this model works. But don’t worry, no prior\nknowledge of GANs is required, but it may require a first-timer to spend\nsome time reasoning about what is actually happening under the hood.\nAlso, for the sake of time it will help to have a GPU, or two. Lets\nstart from the beginning.\n\nGenerative Adversarial Networks\n-------------------------------\n\nWhat is a GAN?\n~~~~~~~~~~~~~~\n\nGANs are a framework for teaching a DL model to capture the training\ndata’s distribution so we can generate new data from that same\ndistribution. GANs were invented by Ian Goodfellow in 2014 and first\ndescribed in the paper `Generative Adversarial\nNets <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__.\nThey are made of two distinct models, a *generator* and a\n*discriminator*. The job of the generator is to spawn ‘fake’ images that\nlook like the training images. The job of the discriminator is to look\nat an image and output whether or not it is a real training image or a\nfake image from the generator. During training, the generator is\nconstantly trying to outsmart the discriminator by generating better and\nbetter fakes, while the discriminator is working to become a better\ndetective and correctly classify the real and fake images. The\nequilibrium of this game is when the generator is generating perfect\nfakes that look as if they came directly from the training data, and the\ndiscriminator is left to always guess at 50% confidence that the\ngenerator output is real or fake.\n\nNow, lets define some notation to be used throughout tutorial starting\nwith the discriminator. Let $x$ be data representing an image.\n$D(x)$ is the discriminator network which outputs the (scalar)\nprobability that $x$ came from training data rather than the\ngenerator. Here, since we are dealing with images the input to\n$D(x)$ is an image of CHW size 3x64x64. Intuitively, $D(x)$\nshould be HIGH when $x$ comes from training data and LOW when\n$x$ comes from the generator. $D(x)$ can also be thought of\nas a traditional binary classifier.\n\nFor the generator’s notation, let $z$ be a latent space vector\nsampled from a standard normal distribution. $G(z)$ represents the\ngenerator function which maps the latent vector $z$ to data-space.\nThe goal of $G$ is to estimate the distribution that the training\ndata comes from ($p_{data}$) so it can generate fake samples from\nthat estimated distribution ($p_g$).\n\nSo, $D(G(z))$ is the probability (scalar) that the output of the\ngenerator $G$ is a real image. As described in `Goodfellow’s\npaper <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`__,\n$D$ and $G$ play a minimax game in which $D$ tries to\nmaximize the probability it correctly classifies reals and fakes\n($logD(x)$), and $G$ tries to minimize the probability that\n$D$ will predict its outputs are fake ($log(1-D(G(x)))$).\nFrom the paper, the GAN loss function is\n\n\\begin{align}\\underset{G}{\\text{min}} \\underset{D}{\\text{max}}V(D,G) = \\mathbb{E}_{x\\sim p_{data}(x)}\\big[logD(x)\\big] + \\mathbb{E}_{z\\sim p_{z}(z)}\\big[log(1-D(G(z)))\\big]\\end{align}\n\nIn theory, the solution to this minimax game is where\n$p_g = p_{data}$, and the discriminator guesses randomly if the\ninputs are real or fake. However, the convergence theory of GANs is\nstill being actively researched and in reality models do not always\ntrain to this point.\n\nWhat is a DCGAN?\n~~~~~~~~~~~~~~~~\n\nA DCGAN is a direct extension of the GAN described above, except that it\nexplicitly uses convolutional and convolutional-transpose layers in the\ndiscriminator and generator, respectively. It was first described by\nRadford et. al. in the paper `Unsupervised Representation Learning With\nDeep Convolutional Generative Adversarial\nNetworks <https://arxiv.org/pdf/1511.06434.pdf>`__. The discriminator\nis made up of strided\n`convolution <https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d>`__\nlayers, `batch\nnorm <https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm2d>`__\nlayers, and\n`LeakyReLU <https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU>`__\nactivations. The input is a 3x64x64 input image and the output is a\nscalar probability that the input is from the real data distribution.\nThe generator is comprised of\n`convolutional-transpose <https://pytorch.org/docs/stable/nn.html#torch.nn.ConvTranspose2d>`__\nlayers, batch norm layers, and\n`ReLU <https://pytorch.org/docs/stable/nn.html#relu>`__ activations. The\ninput is a latent vector, $z$, that is drawn from a standard\nnormal distribution and the output is a 3x64x64 RGB image. The strided\nconv-transpose layers allow the latent vector to be transformed into a\nvolume with the same shape as an image. In the paper, the authors also\ngive some tips about how to setup the optimizers, how to calculate the\nloss functions, and how to initialize the model weights, all of which\nwill be explained in the coming sections.\n\n\n", "_____no_output_____" ] ], [ [ "from __future__ import print_function\n#%matplotlib inline\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\n\n# Set random seed for reproducibility\nmanualSeed = 999\n#manualSeed = random.randint(1, 10000) # use if you want new results\nprint(\"Random Seed: \", manualSeed)\nrandom.seed(manualSeed)\ntorch.manual_seed(manualSeed)", "_____no_output_____" ] ], [ [ "Inputs\n------\n\nLet’s define some inputs for the run:\n\n- **dataroot** - the path to the root of the dataset folder. We will\n talk more about the dataset in the next section\n- **workers** - the number of worker threads for loading the data with\n the DataLoader\n- **batch_size** - the batch size used in training. The DCGAN paper\n uses a batch size of 128\n- **image_size** - the spatial size of the images used for training.\n This implementation defaults to 64x64. If another size is desired,\n the structures of D and G must be changed. See\n `here <https://github.com/pytorch/examples/issues/70>`__ for more\n details\n- **nc** - number of color channels in the input images. For color\n images this is 3\n- **nz** - length of latent vector\n- **ngf** - relates to the depth of feature maps carried through the\n generator\n- **ndf** - sets the depth of feature maps propagated through the\n discriminator\n- **num_epochs** - number of training epochs to run. Training for\n longer will probably lead to better results but will also take much\n longer\n- **lr** - learning rate for training. As described in the DCGAN paper,\n this number should be 0.0002\n- **beta1** - beta1 hyperparameter for Adam optimizers. As described in\n paper, this number should be 0.5\n- **ngpu** - number of GPUs available. If this is 0, code will run in\n CPU mode. If this number is greater than 0 it will run on that number\n of GPUs\n\n\n", "_____no_output_____" ] ], [ [ "# Root directory for dataset\ndataroot = \"data/celeba\"\n\n# Number of workers for dataloader\nworkers = 2\n\n# Batch size during training\nbatch_size = 128\n\n# Spatial size of training images. All images will be resized to this\n# size using a transformer.\nimage_size = 64\n\n# Number of channels in the training images. For color images this is 3\nnc = 3\n\n# Size of z latent vector (i.e. size of generator input)\nnz = 100\n\n# Size of feature maps in generator\nngf = 64\n\n# Size of feature maps in discriminator\nndf = 64\n\n# Number of training epochs\nnum_epochs = 5\n\n# Learning rate for optimizers\nlr = 0.0002\n\n# Beta1 hyperparam for Adam optimizers\nbeta1 = 0.5\n\n# Number of GPUs available. Use 0 for CPU mode.\nngpu = 1", "_____no_output_____" ] ], [ [ "Data\n----\n\nIn this tutorial we will use the `Celeb-A Faces\ndataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`__ which can\nbe downloaded at the linked site, or in `Google\nDrive <https://drive.google.com/drive/folders/0B7EVK8r0v71pTUZsaXdaSnZBZzg>`__.\nThe dataset will download as a file named *img_align_celeba.zip*. Once\ndownloaded, create a directory named *celeba* and extract the zip file\ninto that directory. Then, set the *dataroot* input for this notebook to\nthe *celeba* directory you just created. The resulting directory\nstructure should be:\n\n::\n\n /path/to/celeba\n -> img_align_celeba \n -> 188242.jpg\n -> 173822.jpg\n -> 284702.jpg\n -> 537394.jpg\n ...\n\nThis is an important step because we will be using the ImageFolder\ndataset class, which requires there to be subdirectories in the\ndataset’s root folder. Now, we can create the dataset, create the\ndataloader, set the device to run on, and finally visualize some of the\ntraining data.\n\n\n", "_____no_output_____" ] ], [ [ "# We can use an image folder dataset the way we have it setup.\n# Create the dataset\ndataset = dset.ImageFolder(root=dataroot,\n transform=transforms.Compose([\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]))\n# Create the dataloader\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,\n shuffle=True, num_workers=workers)\n\n# Decide which device we want to run on\ndevice = torch.device(\"cuda:0\" if (torch.cuda.is_available() and ngpu > 0) else \"cpu\")\n\n# Plot some training images\nreal_batch = next(iter(dataloader))\nplt.figure(figsize=(8,8))\nplt.axis(\"off\")\nplt.title(\"Training Images\")\nplt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))", "_____no_output_____" ] ], [ [ "Implementation\n--------------\n\nWith our input parameters set and the dataset prepared, we can now get\ninto the implementation. We will start with the weigth initialization\nstrategy, then talk about the generator, discriminator, loss functions,\nand training loop in detail.\n\nWeight Initialization\n~~~~~~~~~~~~~~~~~~~~~\n\nFrom the DCGAN paper, the authors specify that all model weights shall\nbe randomly initialized from a Normal distribution with mean=0,\nstdev=0.02. The ``weights_init`` function takes an initialized model as\ninput and reinitializes all convolutional, convolutional-transpose, and\nbatch normalization layers to meet this criteria. This function is\napplied to the models immediately after initialization.\n\n\n", "_____no_output_____" ] ], [ [ "# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)", "_____no_output_____" ] ], [ [ "Generator\n~~~~~~~~~\n\nThe generator, $G$, is designed to map the latent space vector\n($z$) to data-space. Since our data are images, converting\n$z$ to data-space means ultimately creating a RGB image with the\nsame size as the training images (i.e. 3x64x64). In practice, this is\naccomplished through a series of strided two dimensional convolutional\ntranspose layers, each paired with a 2d batch norm layer and a relu\nactivation. The output of the generator is fed through a tanh function\nto return it to the input data range of $[-1,1]$. It is worth\nnoting the existence of the batch norm functions after the\nconv-transpose layers, as this is a critical contribution of the DCGAN\npaper. These layers help with the flow of gradients during training. An\nimage of the generator from the DCGAN paper is shown below.\n\n.. figure:: /_static/img/dcgan_generator.png\n :alt: dcgan_generator\n\nNotice, the how the inputs we set in the input section (*nz*, *ngf*, and\n*nc*) influence the generator architecture in code. *nz* is the length\nof the z input vector, *ngf* relates to the size of the feature maps\nthat are propagated through the generator, and *nc* is the number of\nchannels in the output image (set to 3 for RGB images). Below is the\ncode for the generator.\n\n\n", "_____no_output_____" ] ], [ [ "# Generator Code\n\nclass Generator(nn.Module):\n def __init__(self, ngpu):\n super(Generator, self).__init__()\n self.ngpu = ngpu\n self.main = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (nc) x 64 x 64\n )\n\n def forward(self, input):\n return self.main(input)", "_____no_output_____" ] ], [ [ "Now, we can instantiate the generator and apply the ``weights_init``\nfunction. Check out the printed model to see how the generator object is\nstructured.\n\n\n", "_____no_output_____" ] ], [ [ "# Create the generator\nnetG = Generator(ngpu).to(device)\n\n# Handle multi-gpu if desired\nif (device.type == 'cuda') and (ngpu > 1):\n netG = nn.DataParallel(netG, list(range(ngpu)))\n\n# Apply the weights_init function to randomly initialize all weights\n# to mean=0, stdev=0.2.\nnetG.apply(weights_init)\n\n# Print the model\nprint(netG)", "_____no_output_____" ] ], [ [ "Discriminator\n~~~~~~~~~~~~~\n\nAs mentioned, the discriminator, $D$, is a binary classification\nnetwork that takes an image as input and outputs a scalar probability\nthat the input image is real (as opposed to fake). Here, $D$ takes\na 3x64x64 input image, processes it through a series of Conv2d,\nBatchNorm2d, and LeakyReLU layers, and outputs the final probability\nthrough a Sigmoid activation function. This architecture can be extended\nwith more layers if necessary for the problem, but there is significance\nto the use of the strided convolution, BatchNorm, and LeakyReLUs. The\nDCGAN paper mentions it is a good practice to use strided convolution\nrather than pooling to downsample because it lets the network learn its\nown pooling function. Also batch norm and leaky relu functions promote\nhealthy gradient flow which is critical for the learning process of both\n$G$ and $D$.\n\n\n", "_____no_output_____" ], [ "Discriminator Code\n\n", "_____no_output_____" ] ], [ [ "class Discriminator(nn.Module):\n def __init__(self, ngpu):\n super(Discriminator, self).__init__()\n self.ngpu = ngpu\n self.main = nn.Sequential(\n # input is (nc) x 64 x 64\n nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf) x 32 x 32\n nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*2) x 16 x 16\n nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*4) x 8 x 8\n nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 8),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*8) x 4 x 4\n nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, input):\n return self.main(input)", "_____no_output_____" ] ], [ [ "Now, as with the generator, we can create the discriminator, apply the\n``weights_init`` function, and print the model’s structure.\n\n\n", "_____no_output_____" ] ], [ [ "# Create the Discriminator\nnetD = Discriminator(ngpu).to(device)\n\n# Handle multi-gpu if desired\nif (device.type == 'cuda') and (ngpu > 1):\n netD = nn.DataParallel(netD, list(range(ngpu)))\n \n# Apply the weights_init function to randomly initialize all weights\n# to mean=0, stdev=0.2.\nnetD.apply(weights_init)\n\n# Print the model\nprint(netD)", "_____no_output_____" ] ], [ [ "Loss Functions and Optimizers\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWith $D$ and $G$ setup, we can specify how they learn\nthrough the loss functions and optimizers. We will use the Binary Cross\nEntropy loss\n(`BCELoss <https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss>`__)\nfunction which is defined in PyTorch as:\n\n\\begin{align}\\ell(x, y) = L = \\{l_1,\\dots,l_N\\}^\\top, \\quad l_n = - \\left[ y_n \\cdot \\log x_n + (1 - y_n) \\cdot \\log (1 - x_n) \\right]\\end{align}\n\nNotice how this function provides the calculation of both log components\nin the objective function (i.e. $log(D(x))$ and\n$log(1-D(G(z)))$). We can specify what part of the BCE equation to\nuse with the $y$ input. This is accomplished in the training loop\nwhich is coming up soon, but it is important to understand how we can\nchoose which component we wish to calculate just by changing $y$\n(i.e. GT labels).\n\nNext, we define our real label as 1 and the fake label as 0. These\nlabels will be used when calculating the losses of $D$ and\n$G$, and this is also the convention used in the original GAN\npaper. Finally, we set up two separate optimizers, one for $D$ and\none for $G$. As specified in the DCGAN paper, both are Adam\noptimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track\nof the generator’s learning progression, we will generate a fixed batch\nof latent vectors that are drawn from a Gaussian distribution\n(i.e. fixed_noise) . In the training loop, we will periodically input\nthis fixed_noise into $G$, and over the iterations we will see\nimages form out of the noise.\n\n\n", "_____no_output_____" ] ], [ [ "# Initialize BCELoss function\ncriterion = nn.BCELoss()\n\n# Create batch of latent vectors that we will use to visualize\n# the progression of the generator\nfixed_noise = torch.randn(64, nz, 1, 1, device=device)\n\n# Establish convention for real and fake labels during training\nreal_label = 1\nfake_label = 0\n\n# Setup Adam optimizers for both G and D\noptimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))", "_____no_output_____" ] ], [ [ "Training\n~~~~~~~~\n\nFinally, now that we have all of the parts of the GAN framework defined,\nwe can train it. Be mindful that training GANs is somewhat of an art\nform, as incorrect hyperparameter settings lead to mode collapse with\nlittle explanation of what went wrong. Here, we will closely follow\nAlgorithm 1 from Goodfellow’s paper, while abiding by some of the best\npractices shown in `ganhacks <https://github.com/soumith/ganhacks>`__.\nNamely, we will “construct different mini-batches for real and fake”\nimages, and also adjust G’s objective function to maximize\n$logD(G(z))$. Training is split up into two main parts. Part 1\nupdates the Discriminator and Part 2 updates the Generator.\n\n**Part 1 - Train the Discriminator**\n\nRecall, the goal of training the discriminator is to maximize the\nprobability of correctly classifying a given input as real or fake. In\nterms of Goodfellow, we wish to “update the discriminator by ascending\nits stochastic gradient”. Practically, we want to maximize\n$log(D(x)) + log(1-D(G(z)))$. Due to the separate mini-batch\nsuggestion from ganhacks, we will calculate this in two steps. First, we\nwill construct a batch of real samples from the training set, forward\npass through $D$, calculate the loss ($log(D(x))$), then\ncalculate the gradients in a backward pass. Secondly, we will construct\na batch of fake samples with the current generator, forward pass this\nbatch through $D$, calculate the loss ($log(1-D(G(z)))$),\nand *accumulate* the gradients with a backward pass. Now, with the\ngradients accumulated from both the all-real and all-fake batches, we\ncall a step of the Discriminator’s optimizer.\n\n**Part 2 - Train the Generator**\n\nAs stated in the original paper, we want to train the Generator by\nminimizing $log(1-D(G(z)))$ in an effort to generate better fakes.\nAs mentioned, this was shown by Goodfellow to not provide sufficient\ngradients, especially early in the learning process. As a fix, we\ninstead wish to maximize $log(D(G(z)))$. In the code we accomplish\nthis by: classifying the Generator output from Part 1 with the\nDiscriminator, computing G’s loss *using real labels as GT*, computing\nG’s gradients in a backward pass, and finally updating G’s parameters\nwith an optimizer step. It may seem counter-intuitive to use the real\nlabels as GT labels for the loss function, but this allows us to use the\n$log(x)$ part of the BCELoss (rather than the $log(1-x)$\npart) which is exactly what we want.\n\nFinally, we will do some statistic reporting and at the end of each\nepoch we will push our fixed_noise batch through the generator to\nvisually track the progress of G’s training. The training statistics\nreported are:\n\n- **Loss_D** - discriminator loss calculated as the sum of losses for\n the all real and all fake batches ($log(D(x)) + log(D(G(z)))$).\n- **Loss_G** - generator loss calculated as $log(D(G(z)))$\n- **D(x)** - the average output (across the batch) of the discriminator\n for the all real batch. This should start close to 1 then\n theoretically converge to 0.5 when G gets better. Think about why\n this is.\n- **D(G(z))** - average discriminator outputs for the all fake batch.\n The first number is before D is updated and the second number is\n after D is updated. These numbers should start near 0 and converge to\n 0.5 as G gets better. Think about why this is.\n\n**Note:** This step might take a while, depending on how many epochs you\nrun and if you removed some data from the dataset.\n\n\n", "_____no_output_____" ] ], [ [ "# Training Loop\n\n# Lists to keep track of progress\nimg_list = []\nG_losses = []\nD_losses = []\niters = 0\n\nprint(\"Starting Training Loop...\")\n# For each epoch\nfor epoch in range(num_epochs):\n # For each batch in the dataloader\n for i, data in enumerate(dataloader, 0):\n \n ############################\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n ###########################\n ## Train with all-real batch\n netD.zero_grad()\n # Format batch\n real_cpu = data[0].to(device)\n b_size = real_cpu.size(0)\n label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n # Forward pass real batch through D\n output = netD(real_cpu).view(-1)\n # Calculate loss on all-real batch\n errD_real = criterion(output, label)\n # Calculate gradients for D in backward pass\n errD_real.backward()\n D_x = output.mean().item()\n\n ## Train with all-fake batch\n # Generate batch of latent vectors\n noise = torch.randn(b_size, nz, 1, 1, device=device)\n # Generate fake image batch with G\n fake = netG(noise)\n label.fill_(fake_label)\n # Classify all fake batch with D\n output = netD(fake.detach()).view(-1)\n # Calculate D's loss on the all-fake batch\n errD_fake = criterion(output, label)\n # Calculate the gradients for this batch\n errD_fake.backward()\n D_G_z1 = output.mean().item()\n # Add the gradients from the all-real and all-fake batches\n errD = errD_real + errD_fake\n # Update D\n optimizerD.step()\n\n ############################\n # (2) Update G network: maximize log(D(G(z)))\n ###########################\n netG.zero_grad()\n label.fill_(real_label) # fake labels are real for generator cost\n # Since we just updated D, perform another forward pass of all-fake batch through D\n output = netD(fake).view(-1)\n # Calculate G's loss based on this output\n errG = criterion(output, label)\n # Calculate gradients for G\n errG.backward()\n D_G_z2 = output.mean().item()\n # Update G\n optimizerG.step()\n \n # Output training stats\n if i % 50 == 0:\n print('[%d/%d][%d/%d]\\tLoss_D: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'\n % (epoch, num_epochs, i, len(dataloader),\n errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n \n # Save Losses for plotting later\n G_losses.append(errG.item())\n D_losses.append(errD.item())\n \n # Check how the generator is doing by saving G's output on fixed_noise\n if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):\n with torch.no_grad():\n fake = netG(fixed_noise).detach().cpu()\n img_list.append(vutils.make_grid(fake, padding=2, normalize=True))\n \n iters += 1", "_____no_output_____" ] ], [ [ "Results\n-------\n\nFinally, lets check out how we did. Here, we will look at three\ndifferent results. First, we will see how D and G’s losses changed\nduring training. Second, we will visualize G’s output on the fixed_noise\nbatch for every epoch. And third, we will look at a batch of real data\nnext to a batch of fake data from G.\n\n**Loss versus training iteration**\n\nBelow is a plot of D & G’s losses versus training iterations.\n\n\n", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,5))\nplt.title(\"Generator and Discriminator Loss During Training\")\nplt.plot(G_losses,label=\"G\")\nplt.plot(D_losses,label=\"D\")\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "**Visualization of G’s progression**\n\nRemember how we saved the generator’s output on the fixed_noise batch\nafter every epoch of training. Now, we can visualize the training\nprogression of G with an animation. Press the play button to start the\nanimation.\n\n\n", "_____no_output_____" ] ], [ [ "#%%capture\nfig = plt.figure(figsize=(8,8))\nplt.axis(\"off\")\nims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]\nani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)\n\nHTML(ani.to_jshtml())", "_____no_output_____" ] ], [ [ "**Real Images vs. Fake Images**\n\nFinally, lets take a look at some real images and fake images side by\nside.\n\n\n", "_____no_output_____" ] ], [ [ "# Grab a batch of real images from the dataloader\nreal_batch = next(iter(dataloader))\n\n# Plot the real images\nplt.figure(figsize=(15,15))\nplt.subplot(1,2,1)\nplt.axis(\"off\")\nplt.title(\"Real Images\")\nplt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))\n\n# Plot the fake images from the last epoch\nplt.subplot(1,2,2)\nplt.axis(\"off\")\nplt.title(\"Fake Images\")\nplt.imshow(np.transpose(img_list[-1],(1,2,0)))\nplt.show()", "_____no_output_____" ] ], [ [ "Where to Go Next\n----------------\n\nWe have reached the end of our journey, but there are several places you\ncould go from here. You could:\n\n- Train for longer to see how good the results get\n- Modify this model to take a different dataset and possibly change the\n size of the images and the model architecture\n- Check out some other cool GAN projects\n `here <https://github.com/nashory/gans-awesome-applications>`__\n- Create GANs that generate\n `music <https://deepmind.com/blog/wavenet-generative-model-raw-audio/>`__\n\n\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe47adf12225fe6a7fb76e6105fe991801ca091
601,966
ipynb
Jupyter Notebook
docs/tutorials/ktr2.ipynb
juanitorduz/orbit
850818077feb7bdfbeee6b49e38bce392ad6b465
[ "Apache-2.0" ]
null
null
null
docs/tutorials/ktr2.ipynb
juanitorduz/orbit
850818077feb7bdfbeee6b49e38bce392ad6b465
[ "Apache-2.0" ]
null
null
null
docs/tutorials/ktr2.ipynb
juanitorduz/orbit
850818077feb7bdfbeee6b49e38bce392ad6b465
[ "Apache-2.0" ]
null
null
null
503.737238
232,368
0.932789
[ [ [ "# Kernel-based Time-varying Regression - Part II\n\nThe previous tutorial covered the basic syntax and structure of **KTR** (or so called **BTVC**); time-series data was fitted with a KTR model accounting for trend and seasonality. In this tutorial a KTR model is fit with trend, seasonality, and additional regressors. To summarize part 1, **KTR** considers a time-series as an additive combination of local-trend, seasonality, and additional regressors. The coefficients for all three components are allowed to vary over time. The time-varying of the coefficients is modeled using kernel smoothing of latent variables. This can also be an advantage of picking this model over other static regression coefficients models. \n\nThis tutorial covers:\n\n1. KTR model structure with regression\n2. syntax to initialize, fit and predict a model with regressors\n3. visualization of regression coefficients\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom math import pi\nimport matplotlib.pyplot as plt\n\nimport orbit\nfrom orbit.models import KTR\nfrom orbit.diagnostics.plot import plot_predicted_components\nfrom orbit.utils.plot import get_orbit_style\nfrom orbit.constants.palette import OrbitPalette\n\n%matplotlib inline\npd.set_option('display.float_format', lambda x: '%.5f' % x)\norbit_style = get_orbit_style()\nplt.style.use(orbit_style);", "_____no_output_____" ], [ "print(orbit.__version__)", "1.1.1dev\n" ] ], [ [ "## Model Structure", "_____no_output_____" ], [ "This section gives the mathematical structure of the KTR model. In short, it considers a time-series ($y_t$) as the linear combination of three parts. These are the local-trend ($l_t$), seasonality (s_t), and regression ($r_t$) terms at time $t$. That is \n\n$$y_t = l_t + s_t + r_t + \\epsilon_t, ~ t = 1,\\cdots, T,$$\n\nwhere \n\n- $\\epsilon_t$s comprise a stationary random error process.\n- $r_t$ is the regression component which can be further expressed as $\\sum_{i=1}^{I} {x_{i,t}\\beta_{i, t}}$ with covariate $x$ and coefficient $\\beta$ on indexes $i,t$\n\nFor details of how on $l_t$ and $s_t$, please refer to **Part I**.", "_____no_output_____" ], [ "Recall in **KTR**, we express coefficients as\n\n$$B=K b^T$$\n\nwhere\n- *coefficient matrix* $\\text{B}$ has size $t \\times P$ with rows equal to the $\\beta_t$ \n- *knot matrix* $b$ with size $P\\times J$; each entry is a latent variable $b_{p, j}$. The $b_j$ can be viewed as the \"knots\" from the perspective of spline regression and $j$ is a time index such that $t_j \\in [1, \\cdots, T]$.\n- *kernel matrix* $K$ with size $T\\times J$ where the $i$th row and $j$th element can be viewed as the normalized weight $k(t_j, t) / \\sum_{j=1}^{J} k(t_j, t)$\n\n\nIn regression, we generate the matrix $K$ with Gaussian kernel $k_\\text{reg}$ as such:\n\n$k_\\text{reg}(t, t_j;\\rho) = \\exp ( -\\frac{(t-t_j)^2}{2\\rho^2} ),$\n\nwhere $\\rho$ is the scale hyper-parameter.", "_____no_output_____" ], [ "## Data Simulation Module\n\nIn this example, we will use simulated data in order to have true regression coefficients for comparison. We propose two set of simulation data with three predictors each:\n\nThe two data sets are:\n- random walk\n- sine-cosine like \n\nNote the data are random so it may be worthwhile to repeat the next few sets a few times to see how different data sets work. ", "_____no_output_____" ], [ "### Random Walk Simulated Dataset", "_____no_output_____" ] ], [ [ "def sim_data_seasonal(n, RS):\n \"\"\" coefficients curve are sine-cosine like\n \"\"\"\n np.random.seed(RS)\n # make the time varing coefs \n tau = np.arange(1, n+1)/n\n data = pd.DataFrame({\n 'tau': tau,\n 'date': pd.date_range(start='1/1/2018', periods=n),\n 'beta1': 2 * tau,\n 'beta2': 1.01 + np.sin(2*pi*tau),\n 'beta3': 1.01 + np.sin(4*pi*(tau-1/8)),\n 'x1': np.random.normal(0, 10, size=n),\n 'x2': np.random.normal(0, 10, size=n),\n 'x3': np.random.normal(0, 10, size=n),\n 'trend': np.cumsum(np.concatenate((np.array([1]), np.random.normal(0, 0.1, n-1)))),\n 'error': np.random.normal(0, 1, size=n) #stats.t.rvs(30, size=n),#\n })\n \n data['y'] = data.x1 * data.beta1 + data.x2 * data.beta2 + data.x3 * data.beta3 + data.error\n return data", "_____no_output_____" ], [ "def sim_data_rw(n, RS, p=3):\n \"\"\" coefficients curve are random walk like\n \"\"\"\n np.random.seed(RS)\n\n # initializing coefficients at zeros, simulate all coefficient values\n lev = np.cumsum(np.concatenate((np.array([5.0]), np.random.normal(0, 0.01, n-1))))\n beta = np.concatenate(\n [np.random.uniform(0.05, 0.12, size=(1,p)),\n np.random.normal(0.0, 0.01, size=(n-1,p))], \n axis=0)\n beta = np.cumsum(beta, 0)\n\n # simulate regressors\n covariates = np.random.normal(0, 10, (n, p))\n\n # observation with noise\n y = lev + (covariates * beta).sum(-1) + 0.3 * np.random.normal(0, 1, n)\n\n regressor_col = ['x{}'.format(pp) for pp in range(1, p+1)]\n data = pd.DataFrame(covariates, columns=regressor_col)\n beta_col = ['beta{}'.format(pp) for pp in range(1, p+1)]\n beta_data = pd.DataFrame(beta, columns=beta_col)\n data = pd.concat([data, beta_data], axis=1)\n \n data['y'] = y\n data['date'] = pd.date_range(start='1/1/2018', periods=len(y))\n\n return data", "_____no_output_____" ], [ "rw_data = sim_data_rw(n=300, RS=2021, p=3)\nrw_data.head(10)", "_____no_output_____" ] ], [ [ "### Sine-Cosine Like Simulated Dataset", "_____no_output_____" ] ], [ [ "sc_data = sim_data_seasonal(n=80, RS=2021)\nsc_data.head(10)", "_____no_output_____" ] ], [ [ "## Fitting a Model with Regressors", "_____no_output_____" ], [ "The metadata for simulated data sets.", "_____no_output_____" ] ], [ [ "# num of predictors\np = 3\nregressor_col = ['x{}'.format(pp) for pp in range(1, p + 1)]\nresponse_col = 'y'\ndate_col='date'", "_____no_output_____" ] ], [ [ "As in **Part I** KTR follows sklearn model API style. First an instance of the Orbit class `KTR` is created. Second fit and predict methods are called for that instance. Besides providing meta data such `response_col`, `date_col` and `regressor_col`, there are additional args to provide to specify the estimator and the setting of the estimator. For details, please refer to other tutorials of the **Orbit** site.", "_____no_output_____" ] ], [ [ "ktr = KTR(\n response_col=response_col,\n date_col=date_col,\n regressor_col=regressor_col,\n prediction_percentiles=[2.5, 97.5],\n seed=2021,\n estimator='pyro-svi',\n)", "_____no_output_____" ] ], [ [ "Here `predict` has the additional argument `decompose=True`. This returns the compponents ($l_t$, $s_t$, and $r_t$) of the regression along with the prediction.", "_____no_output_____" ] ], [ [ "ktr.fit(df=rw_data)\nktr.predict(df=rw_data, decompose=True).head(5)", "INFO:orbit:Optimizing(PyStan) with algorithm:LBFGS .\nINFO:orbit:Using SVI(Pyro) with steps:301 , samples:100 , learning rate:0.1, learning_rate_total_decay:1.0 and particles:100 .\nINFO:root:Guessed max_plate_nesting = 1\nINFO:orbit:step 0 loss = 3107, scale = 0.091353\nINFO:orbit:step 100 loss = 319.68, scale = 0.050692\nINFO:orbit:step 200 loss = 305.49, scale = 0.05142\nINFO:orbit:step 300 loss = 314.01, scale = 0.05279\n" ] ], [ [ "## Visualization of Regression Coefficient Curves\n\nThe function `get_regression_coefs` to extract coefficients (they will have central credibility intervals if the argument `include_ci=True` is used).", "_____no_output_____" ] ], [ [ "coef_mid, coef_lower, coef_upper = ktr.get_regression_coefs(include_ci=True)", "_____no_output_____" ], [ "coef_mid.head(5)", "_____no_output_____" ] ], [ [ "Because this is simulated data it is possible to overlay the estimate with the true coefficients. ", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(p, 1, figsize=(12, 12), sharex=True)\n\nx = np.arange(coef_mid.shape[0])\nfor idx in range(p):\n axes[idx].plot(x, coef_mid['x{}'.format(idx + 1)], label='est' if idx == 0 else \"\", color=OrbitPalette.BLUE.value)\n axes[idx].fill_between(x, coef_lower['x{}'.format(idx + 1)], coef_upper['x{}'.format(idx + 1)], alpha=0.2, color=OrbitPalette.BLUE.value)\n axes[idx].scatter(x, rw_data['beta{}'.format(idx + 1)], label='truth' if idx == 0 else \"\", s=10, alpha=0.6, color=OrbitPalette.BLACK.value)\n axes[idx].set_title('beta{}'.format(idx + 1))\n\nfig.legend(bbox_to_anchor = (1,0.5));", "_____no_output_____" ] ], [ [ "To plot coefficients use the function `plot_regression_coefs` from the KTR class.", "_____no_output_____" ] ], [ [ "ktr.plot_regression_coefs(figsize=(10, 5), include_ci=True);", "_____no_output_____" ] ], [ [ "These type of time-varying coefficients detection problems are not new. Bayesian approach such as the R packages Bayesian Structural Time Series (a.k.a **BSTS**) by Scott and Varian (2014) and **tvReg** Isabel Casas and Ruben Fernandez-Casal (2021). Other frequentist approach such as Wu and Chiang (2000).\n\nFor further studies on benchmarking coefficients detection, Ng, Wang and Dai (2021) provides a detailed comparison of **KTR** with other popular time-varying coefficients methods; **KTR** demonstrates superior performance in the random walk data simulation. ", "_____no_output_____" ], [ "## Customizing Priors and Number of Knot Segments", "_____no_output_____" ], [ "To demonstrate how to specify the number of knots and priors consider the sine-cosine like simulated dataset. In this dataset, the fitting is more tricky since there could be some better way to define the number and position of the knots. There are obvious \"change points\" within the sine-cosine like curves. In **KTR** there are a few arguments that can leveraged to asign a priori knot attributes:\n\n1. `regressor_init_knot_loc` is used to define the prior mean of the knot value. e.g. in this case, there is not a lot of prior knowledge so zeros are used.\n2. The `regressor_init_knot_scale` and `regressor_knot_scale` are used to tune the prior sd of the global mean of the knot and the sd of each knot from the global mean respectively. These create a plausible range for the knot values.\n3. The `regression_segments` defines the number of between knot segments (the number of knots - 1). The higher the number of segments the more change points are possible. \n", "_____no_output_____" ] ], [ [ "ktr = KTR(\n response_col=response_col,\n date_col=date_col,\n \n regressor_col=regressor_col,\n regressor_init_knot_loc=[0] * len(regressor_col),\n regressor_init_knot_scale=[10.0] * len(regressor_col),\n regressor_knot_scale=[2.0] * len(regressor_col),\n regression_segments=6,\n\n prediction_percentiles=[2.5, 97.5],\n seed=2021,\n estimator='pyro-svi',\n)\nktr.fit(df=sc_data)", "INFO:orbit:Optimizing(PyStan) with algorithm:LBFGS .\nINFO:orbit:Using SVI(Pyro) with steps:301 , samples:100 , learning rate:0.1, learning_rate_total_decay:1.0 and particles:100 .\nINFO:root:Guessed max_plate_nesting = 1\nINFO:orbit:step 0 loss = 828.02, scale = 0.10882\nINFO:orbit:step 100 loss = 340.58, scale = 0.87797\nINFO:orbit:step 200 loss = 266.67, scale = 0.37411\nINFO:orbit:step 300 loss = 261.21, scale = 0.43775\n" ], [ "coef_mid, coef_lower, coef_upper = ktr.get_regression_coefs(include_ci=True)\nfig, axes = plt.subplots(p, 1, figsize=(12, 12), sharex=True)\n\nx = np.arange(coef_mid.shape[0])\nfor idx in range(p):\n axes[idx].plot(x, coef_mid['x{}'.format(idx + 1)], label='est' if idx == 0 else \"\", color=OrbitPalette.BLUE.value)\n axes[idx].fill_between(x, coef_lower['x{}'.format(idx + 1)], coef_upper['x{}'.format(idx + 1)], alpha=0.2, color=OrbitPalette.BLUE.value)\n axes[idx].scatter(x, sc_data['beta{}'.format(idx + 1)], label='truth' if idx == 0 else \"\", s=10, alpha=0.6, color=OrbitPalette.BLACK.value)\n axes[idx].set_title('beta{}'.format(idx + 1))\n\nfig.legend(bbox_to_anchor = (1, 0.5));", "_____no_output_____" ] ], [ [ "Visualize the knots using the `plot_regression_coefs` function with `with_knot=True`.", "_____no_output_____" ] ], [ [ "ktr.plot_regression_coefs(with_knot=True, figsize=(10, 5), include_ci=True);", "_____no_output_____" ] ], [ [ "There are more ways to define knots for regression as well as seasonality and trend (a.k.a levels). These are described in **Part III**", "_____no_output_____" ], [ "## References\n\n1. Ng, Wang and Dai (2021). Bayesian Time Varying Coefficient Model with Applications to Marketing Mix Modeling, arXiv preprint arXiv:2106.03322 \n2. Isabel Casas and Ruben Fernandez-Casal (2021). tvReg: Time-Varying Coefficients Linear Regression for Single and Multi-Equations. https://CRAN.R-project.org/package=tvReg R package version 0.5.4.\n3. Steven L Scott and Hal R Varian (2014). Predicting the present with bayesian structural time series. International Journal of Mathematical Modelling and Numerical Optimisation 5, 1-2 (2014), 4–23.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cbe4934159ad8dbab9827f13a7347f10169133a8
4,361
ipynb
Jupyter Notebook
AOC_2021/Day-13-Transparent-Origami/day-13.ipynb
shankar-shiv/Advent-of-Code
b654393e4243c9aeb81c20451b32c2cb727e29f7
[ "MIT" ]
null
null
null
AOC_2021/Day-13-Transparent-Origami/day-13.ipynb
shankar-shiv/Advent-of-Code
b654393e4243c9aeb81c20451b32c2cb727e29f7
[ "MIT" ]
null
null
null
AOC_2021/Day-13-Transparent-Origami/day-13.ipynb
shankar-shiv/Advent-of-Code
b654393e4243c9aeb81c20451b32c2cb727e29f7
[ "MIT" ]
null
null
null
21.914573
167
0.417565
[ [ [ "with open(r'C:\\Users\\ShivaShankar\\Desktop\\Advent-of-Code\\AOC_2021\\Day-13-Transparent-Origami\\sample.txt') as f:\n nums, folds = f.read().split('\\n\\n')\n\n\nnums = {tuple(map(int, line.split(','))) for line in nums.splitlines()}\n\nfolds = [\n (axis[-1], int(num))\n for line in folds.splitlines()\n for axis, num in [line.split('=')]\n]\n\nfor i, (axis, t) in enumerate(folds):\n if axis == 'x':\n nums = set((x, y) if x < t else (t+t-x, y) for (x, y) in nums)\n else:\n print(nums)\n nums = set((x, y) if y < t else (x, t+t-y) for (x, y) in nums)\n print(f'their nums = {nums}')\n if i == 0:\n print(f\"Part 1: {len(nums)}\\nPart 2:\")", "{(9, 10), (6, 12), (2, 14), (9, 0), (8, 4), (3, 4), (10, 4), (0, 13), (0, 3), (8, 10), (3, 0), (6, 10), (10, 12), (6, 0), (1, 10), (4, 11), (0, 14), (4, 1)}\ntheir nums = {(0, 1), (9, 0), (6, 2), (8, 4), (3, 4), (4, 3), (0, 0), (10, 4), (0, 3), (2, 0), (6, 4), (1, 4), (3, 0), (6, 0), (4, 1), (10, 2), (9, 4)}\nPart 1: 17\nPart 2:\n" ], [ "max(y for _, y in nums)+1", "_____no_output_____" ], [ "max(x for x, _ in nums)+1", "_____no_output_____" ], [ "nums", "_____no_output_____" ], [ "\".#\"[(0,5) in nums]", "_____no_output_____" ], [ "for y in range(max(y for _, y in nums)+1):\n for x in range(max(x for x, _ in nums)+1):\n print('.#'[(x, y) in nums], end='')\n print()", "#####\n#...#\n#...#\n#...#\n#####\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cbe495af4899bc86ca231ff4a80b8ca105cd1c33
77,215
ipynb
Jupyter Notebook
chapters/chapter_8/8_5_NMT/8_5_NMT_No_Sampling_refactored.ipynb
RRisto/pytorchnlpbook
3ab532236ded14338b53683aa9adc75790bd8f0c
[ "Apache-2.0" ]
2
2020-02-08T23:39:11.000Z
2020-03-01T02:51:20.000Z
chapters/chapter_8/8_5_NMT/8_5_NMT_No_Sampling_refactored.ipynb
RRisto/pytorchnlpbook
3ab532236ded14338b53683aa9adc75790bd8f0c
[ "Apache-2.0" ]
1
2020-02-07T18:02:15.000Z
2020-02-07T18:02:15.000Z
chapters/chapter_8/8_5_NMT/8_5_NMT_No_Sampling_refactored.ipynb
RRisto/pytorchnlpbook
3ab532236ded14338b53683aa9adc75790bd8f0c
[ "Apache-2.0" ]
null
null
null
186.060241
11,780
0.912996
[ [ [ "from src.learner import Learner\nfrom argparse import Namespace", "_____no_output_____" ] ], [ [ "## Args", "_____no_output_____" ] ], [ [ "args = Namespace(dataset_csv=\"data/nmt/simplest_eng_fra.csv\",\n vectorizer_file=\"vectorizer.json\",\n model_state_file=\"model.pth\",\n save_dir=\"model_storage/ch8/nmt_luong_no_sampling\",\n reload_from_files=False,\n expand_filepaths_to_save_dir=True,\n cuda=False,\n seed=1337,\n learning_rate=5e-4,\n batch_size=64,\n num_epochs=2,\n early_stopping_criteria=5, \n source_embedding_size=64, \n target_embedding_size=64,\n encoding_size=64,\n catch_keyboard_interrupt=True,\n sampling=False)", "_____no_output_____" ] ], [ [ "## Learner", "_____no_output_____" ] ], [ [ "learner=Learner.learner_from_args(args)", "Expanded filepaths: \n\tmodel_storage/ch8/nmt_luong_no_sampling\\vectorizer.json\n\tmodel_storage/ch8/nmt_luong_no_sampling\\model.pth\nUsing CUDA: False\nLoading dataset and creating vectorizer\n" ] ], [ [ "## train", "_____no_output_____" ] ], [ [ "learner.train()", "_____no_output_____" ] ], [ [ "## Bleu", "_____no_output_____" ] ], [ [ "learner.calc_bleu()", "bleu-4 mean for test data: 0.14824427687451144\nbleu-4 median for test data: 0.11909895322804873\n" ] ], [ [ "## See predictions", "_____no_output_____" ] ], [ [ "learner.plot_top_val_sentences(max_n=5)", "sentence over threshold: 34\n" ], [ "learner.get_val_1batch_sentence(1)", "_____no_output_____" ] ], [ [ "## Generate text", "_____no_output_____" ] ], [ [ "learner.generate_text('i m going to go to')", "_____no_output_____" ] ], [ [ "## Load saved model", "_____no_output_____" ] ], [ [ "args_saved = Namespace(dataset_csv=\"data/nmt/simplest_eng_fra.csv\",\n vectorizer_file=\"vectorizer.json\",\n model_state_file=\"model.pth\",\n save_dir=\"model_storage/ch8/nmt_luong_no_sampling\",\n reload_from_files=True,\n expand_filepaths_to_save_dir=True,\n cuda=False,\n seed=1337,\n learning_rate=5e-4,\n batch_size=64,\n num_epochs=2,\n early_stopping_criteria=5, \n source_embedding_size=64, \n target_embedding_size=64,\n encoding_size=64,\n catch_keyboard_interrupt=True,\n sampling=False)", "_____no_output_____" ], [ "learner_loaded=Learner.learner_from_args(args_saved)", "Expanded filepaths: \n\tmodel_storage/ch8/nmt_luong_no_sampling\\vectorizer.json\n\tmodel_storage/ch8/nmt_luong_no_sampling\\model.pth\nUsing CUDA: False\nLoading dataset and loading vectorizer\n" ], [ "learner.calc_bleu()", "bleu-4 mean for test data: 0.148597481614956\nbleu-4 median for test data: 0.11865649707332009\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbe49ead0c89d96c2809430bdc148c5d819d9f51
8,269
ipynb
Jupyter Notebook
tutorials/advanced/validation.ipynb
rdmolony/fugue-tutorials
e6f47773eb4e821649269e6d6b4914f8857f857f
[ "Apache-2.0" ]
28
2020-06-26T19:43:26.000Z
2022-03-27T23:01:28.000Z
tutorials/advanced/validation.ipynb
rdmolony/fugue-tutorials
e6f47773eb4e821649269e6d6b4914f8857f857f
[ "Apache-2.0" ]
50
2020-09-28T08:12:06.000Z
2022-01-26T06:16:54.000Z
tutorials/advanced/validation.ipynb
rdmolony/fugue-tutorials
e6f47773eb4e821649269e6d6b4914f8857f857f
[ "Apache-2.0" ]
7
2020-10-28T19:27:44.000Z
2021-11-16T06:25:00.000Z
37.931193
447
0.593784
[ [ [ "# Extension Input Data Validation\n\nWhen using extensions in Fugue, you may add input data validation logic inside your code. However, there is standard way to add your validation logic. Here is a simple example:", "_____no_output_____" ] ], [ [ "from typing import List, Dict, Any\n\n# partitionby_has: a\n# schema: a:int,ct:int\ndef get_count(df:List[Dict[str,Any]]) -> List[List[Any]]:\n return [[df[0][\"a\"],len(df)]]", "_____no_output_____" ] ], [ [ "The following commented-out code will fail, because of the hint `partitionby_has: a` requires the input dataframe to be prepartitioned by at least column `a`.", "_____no_output_____" ] ], [ [ "from fugue import FugueWorkflow\n\nwith FugueWorkflow() as dag:\n df = dag.df([[0,1],[1,1],[0,2]], \"a:int,b:int\")\n # df.transform(get_count).show() # will fail because of no partition by\n df.partition(by=[\"a\"]).transform(get_count).show()\n df.partition(by=[\"b\",\"a\"]).transform(get_count).show() # b,a is a super set of a", "_____no_output_____" ] ], [ [ "You can also have multiple rules, the following requires partition keys to contain `a`, and presort to be exactly `b asc` (`b == b asc`)", "_____no_output_____" ] ], [ [ "from typing import List, Dict, Any\n\n# partitionby_has: a\n# presort_is: b\n# schema: a:int,ct:int\ndef get_count2(df:List[Dict[str,Any]]) -> List[List[Any]]:\n return [[df[0][\"a\"],len(df)]]", "_____no_output_____" ], [ "from fugue import FugueWorkflow\n\nwith FugueWorkflow() as dag:\n df = dag.df([[0,1],[1,1],[0,2]], \"a:int,b:int\")\n # df.partition(by=[\"a\"]).transform(get_count).show() # will fail because of no presort\n df.partition(by=[\"a\"], presort=\"b asc\").transform(get_count).show()", "_____no_output_____" ] ], [ [ "## Supported Validations\n\nThe following are all supported validations. **Compile time validations** will happen when you construct the [FugueWorkflow](/dag.ipynb) while **runtime validations** happen during execution. Compile time validations are very useful to quickly identify logical issues. Runtime validations may take longer time to happen but they are still useful.On Fugue level, we are trying to move runtime validations to compile time as much as we can.\n\n Rule | Description | Compile Time | Order Matters | Examples\n:---|:---|:---|:---|:---\n**partitionby_has** | assert the input dataframe is prepartitioned, and the partition keys contain these values | Yes | No | `partitionby_has: a,b` means the partition keys must contain `a` and `b` columns\n**partitionby_is** | assert the input dataframe is prepartitioned, and the partition keys are exactly these values | Yes | Yes | `partitionby_is: a,b` means the partition keys must contain and only contain `a` and `b` columns\n**presort_has** | assert the input dataframe is prepartitioned and [presorted](./partition.ipynb#Presort), and the presort keys contain these values | Yes | No | `presort_has: a,b desc` means the presort contains `a asc` and `b desc` (`a == a asc`)\n**presort_is** | assert the input dataframe is prepartitioned and [presorted](./partition.ipynb#Presort), and the presort keys are exactly these values | Yes | Yes | `presort_is: a,b desc` means the presort is exactly `a asc, b desc`\n**schema_has** | assert input dataframe schema has certain keys or key type pairs | No | No | `schema_has: a,b:str` means input dataframe schema contains column `a` regardless of type, and `b` of type string, order doesn't matter. So `b:str,a:int` is valid, `b:int,a:int` is invalid because of `b` type, and `b:str` is invalid because `a` is not in the schema\n**schema_is** | assert input dataframe schema is exactly this value (the value must be a [schema expression](./schema_dataframes.ipynb#Schema)) | No | Yes | `schema_is: a:int,b:str`, then `b:str,a:int` is invalid because of order, `a:str,b:str` is invalid because of `a` type\n\n\n## Extensions Compatibility\n\nExtension Type | Supported | Not Supported\n:---|:---|:---\nTransformer | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is` | None\nCoTransformer | None | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is`\nOutputTransformer | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is` | None\nOutputCoTransformer | None | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is`\nCreator | N/A | N/A\nProcessor | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is` | None\nOutputter | `partitionby_has`, `partitionby_is`, `presort_has`, `presort_is`, `schema_has`, `schema_is` | None\n\n\n## How To Add Validations\n\nIt depends on how you write your extension, by comment, by decorator or by interface, feature wise, they are equivalent.\n\n## By Comment", "_____no_output_____" ] ], [ [ "from typing import List, Dict, Any\n\n# schema: a:int,ct:int\ndef get_count2(df:List[Dict[str,Any]]) -> List[List[Any]]:\n return [[df[0][\"a\"],len(df)]]", "_____no_output_____" ] ], [ [ "## By Decorator", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom typing import List, Dict, Any\nfrom fugue import processor, transformer\n\n@transformer(schema=\"*\", partitionby_has=[\"a\",\"d\"], presort_is=\"b, c desc\")\ndef example1(df:pd.DataFrame) -> pd.DataFrame:\n return df\n\n@transformer(schema=\"*\", partitionby_has=\"a,d\", presort_is=[\"b\",(\"c\",False)])\ndef example2(df:pd.DataFrame) -> pd.DataFrame:\n return df\n\n# partitionby_has: a\n# presort_is: b\n@transformer(schema=\"*\")\ndef example3(df:pd.DataFrame) -> pd.DataFrame:\n return df\n\n@processor(partitionby_has=[\"a\",\"d\"], presort_is=\"b, c desc\")\ndef example4(df:pd.DataFrame) -> pd.DataFrame:\n return df", "_____no_output_____" ] ], [ [ "## By Interface\n\nIn every extension, you can override `validation_rules`", "_____no_output_____" ] ], [ [ "from fugue import Transformer\n\nclass T(Transformer):\n @property\n def validation_rules(self):\n return {\n \"partitionby_has\": [\"a\"]\n }\n\n def get_output_schema(self, df):\n return df.schema\n \n def transform(self, df):\n return df", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cbe4ba306ee959b2ead4a903d184ab7b99431d16
40,070
ipynb
Jupyter Notebook
docs/tutorials/bandits_tutorial.ipynb
king821221/agents
ab7bee286ead30d7c5d4353627f9da90b6f0c316
[ "Apache-2.0" ]
2
2019-08-28T11:55:30.000Z
2020-05-18T11:01:39.000Z
docs/tutorials/bandits_tutorial.ipynb
king821221/agents
ab7bee286ead30d7c5d4353627f9da90b6f0c316
[ "Apache-2.0" ]
1
2021-01-31T08:17:47.000Z
2021-01-31T08:17:47.000Z
docs/tutorials/bandits_tutorial.ipynb
king821221/agents
ab7bee286ead30d7c5d4353627f9da90b6f0c316
[ "Apache-2.0" ]
1
2021-01-31T08:13:34.000Z
2021-01-31T08:13:34.000Z
38.454894
613
0.561268
[ [ [ "##### Copyright 2020 The TF-Agents Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ] ], [ [ "# Tutorial on Multi Armed Bandits in TF-Agents", "_____no_output_____" ], [ "### Get Started\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/agents/tutorials/bandits_tutorial\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/bandits_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/agents/blob/master/docs/tutorials/bandits_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/bandits_tutorial.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n", "_____no_output_____" ], [ "### Setup", "_____no_output_____" ], [ "If you haven't installed the following dependencies, run:", "_____no_output_____" ] ], [ [ "!pip install tf-agents", "_____no_output_____" ] ], [ [ "### Imports", "_____no_output_____" ] ], [ [ "import abc\nimport numpy as np\nimport tensorflow as tf\n\nfrom tf_agents.agents import tf_agent\nfrom tf_agents.drivers import driver\nfrom tf_agents.environments import py_environment\nfrom tf_agents.environments import tf_environment\nfrom tf_agents.environments import tf_py_environment\nfrom tf_agents.policies import tf_policy\nfrom tf_agents.specs import array_spec\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.trajectories import trajectory\nfrom tf_agents.trajectories import policy_step\n\n# Clear any leftover state from previous colabs run.\n# (This is not necessary for normal programs.)\ntf.compat.v1.reset_default_graph()\n\ntf.compat.v1.enable_resource_variables()\ntf.compat.v1.enable_v2_behavior()\nnest = tf.compat.v2.nest", "_____no_output_____" ] ], [ [ "# Introduction\n", "_____no_output_____" ], [ "The Multi-Armed Bandit problem (MAB) is a special case of Reinforcement Learning: an agent collects rewards in an environment by taking some actions after observing some state of the environment. The main difference between general RL and MAB is that in MAB, we assume that the action taken by the agent does not influence the next state of the environment. Therefore, agents do not model state transitions, credit rewards to past actions, or \"plan ahead\" to get to reward-rich states.\n\nAs in other RL domains, the goal of a MAB *agent* is to find a *policy* that collects as much reward as possible. It would be a mistake, however, to always try to exploit the action that promises the highest reward, because then there is a chance that we miss out on better actions if we do not explore enough. This is the main problem to be solved in (MAB), often called the *exploration-exploitation dilemma*.\n\n\n\nBandit environments, policies, and agents for MAB can be found in subdirectories of [tf_agents/bandits](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits).", "_____no_output_____" ], [ "# Environments", "_____no_output_____" ], [ "In TF-Agents, the environment class serves the role of giving information on the current state (this is called **observation** or **context**), receiving an action as input, performing a state transition, and outputting a reward. This class also takes care of resetting when an episode ends, so that a new episode can start. This is realized by calling a `reset` function when a state is labelled as \"last\" of the episode.\n\nFor more details, see the [TF-Agents environments tutorial](https://github.com/tensorflow/agents/blob/master/docs/tutorials/2_environments_tutorial.ipynb).\n\nAs mentioned above, MAB differs from general RL in that actions do not influence the next observation. Another difference is that in Bandits, there are no \"episodes\": every time step starts with a new observation, independently of previous time steps.\n\nTo make sure observations are independent and to abstract away the concept of RL episodes, we introduce subclasses of `PyEnvironment` and `TFEnvironment`: [BanditPyEnvironment](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_tf_environment.py) and [BanditTFEnvironment](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/bandit_py_environment.py). These classes expose two private member functions that remain to be implemented by the user:\n\n```python\[email protected]\ndef _observe(self):\n```\nand\n```python\[email protected]\ndef _apply_action(self, action):\n```\nThe `_observe` function returns an observation. Then, the policy chooses an action based on this observation. The `_apply_action` receives that action as an input, and returns the corresponding reward. These private member functions are called by the functions `reset` and `step`, respectively.", "_____no_output_____" ] ], [ [ "class BanditPyEnvironment(py_environment.PyEnvironment):\n\n def __init__(self, observation_spec, action_spec):\n self._observation_spec = observation_spec\n self._action_spec = action_spec\n super(BanditPyEnvironment, self).__init__()\n\n # Helper functions.\n def action_spec(self):\n return self._action_spec\n\n def observation_spec(self):\n return self._observation_spec\n\n def _empty_observation(self):\n return tf.nest.map_structure(lambda x: np.zeros(x.shape, x.dtype),\n self.observation_spec())\n\n # These two functions below should not be overridden by subclasses.\n def _reset(self):\n \"\"\"Returns a time step containing an observation.\"\"\"\n return ts.restart(self._observe(), batch_size=self.batch_size)\n\n def _step(self, action):\n \"\"\"Returns a time step containing the reward for the action taken.\"\"\"\n reward = self._apply_action(action)\n return ts.termination(self._observe(), reward)\n\n # These two functions below are to be implemented in subclasses.\n @abc.abstractmethod\n def _observe(self):\n \"\"\"Returns an observation.\"\"\"\n\n @abc.abstractmethod\n def _apply_action(self, action):\n \"\"\"Applies `action` to the Environment and returns the corresponding reward.\n \"\"\"", "_____no_output_____" ] ], [ [ "The above interim abstract class implements `PyEnvironment`'s `_reset` and `_step` functions and exposes the abstract functions `_observe` and `_apply_action` to be implemented by subclasses.", "_____no_output_____" ], [ "## A Simple Example Environment Class", "_____no_output_____" ], [ "The following class gives a very simple environment for which the observation is a random integer between -2 and 2, there are 3 possible actions (0, 1, 2), and the reward is the product of the action and the observation.", "_____no_output_____" ] ], [ [ "class SimplePyEnvironment(BanditPyEnvironment):\n\n def __init__(self):\n action_spec = array_spec.BoundedArraySpec(\n shape=(), dtype=np.int32, minimum=0, maximum=2, name='action')\n observation_spec = array_spec.BoundedArraySpec(\n shape=(1,), dtype=np.int32, minimum=-2, maximum=2, name='observation')\n super(SimplePyEnvironment, self).__init__(observation_spec, action_spec)\n\n def _observe(self):\n self._observation = np.random.randint(-2, 3, (1,), dtype='int32')\n return self._observation\n\n def _apply_action(self, action):\n return action * self._observation", "_____no_output_____" ] ], [ [ "Now we can use this environment to get observations, and receive rewards for our actions.", "_____no_output_____" ] ], [ [ "environment = SimplePyEnvironment()\nobservation = environment.reset().observation\nprint(\"observation: %d\" % observation)\n\naction = 2 #@param\n\nprint(\"action: %d\" % action)\nreward = environment.step(action).reward\nprint(\"reward: %f\" % reward)", "_____no_output_____" ] ], [ [ "## TF Environments", "_____no_output_____" ], [ "One can define a bandit environment by subclassing `BanditTFEnvironment`, or, similarly to RL environments, one can define a `BanditPyEnvironment` and wrap it with `TFPyEnvironment`. For the sake of simplicity, we go with the latter option in this tutorial.", "_____no_output_____" ] ], [ [ "tf_environment = tf_py_environment.TFPyEnvironment(environment)", "_____no_output_____" ] ], [ [ "# Policies", "_____no_output_____" ], [ "A *policy* in a bandit problem works the same way as in an RL problem: it provides an action (or a distribution of actions), given an observation as input.\n\nFor more details, see the [TF-Agents Policy tutorial](https://github.com/tensorflow/agents/blob/master/docs/tutorials/3_policies_tutorial.ipynb).\n\nAs with environments, there are two ways to construct a policy: One can create a `PyPolicy` and wrap it with `TFPyPolicy`, or directly create a `TFPolicy`. Here we elect to go with the direct method.\n\nSince this example is quite simple, we can define the optimal policy manually. The action only depends on the sign of the observation, 0 when is negative and 2 when is positive.", "_____no_output_____" ] ], [ [ "class SignPolicy(tf_policy.TFPolicy):\n def __init__(self):\n observation_spec = tensor_spec.BoundedTensorSpec(\n shape=(1,), dtype=tf.int32, minimum=-2, maximum=2)\n time_step_spec = ts.time_step_spec(observation_spec)\n\n action_spec = tensor_spec.BoundedTensorSpec(\n shape=(), dtype=tf.int32, minimum=0, maximum=2)\n\n super(SignPolicy, self).__init__(time_step_spec=time_step_spec,\n action_spec=action_spec)\n def _distribution(self, time_step):\n pass\n\n def _variables(self):\n return ()\n\n def _action(self, time_step, policy_state, seed):\n observation_sign = tf.cast(tf.sign(time_step.observation[0]), dtype=tf.int32)\n action = observation_sign + 1\n return policy_step.PolicyStep(action, policy_state)", "_____no_output_____" ] ], [ [ "Now we can request an observation from the environment, call the policy to choose an action, then the environment will output the reward:", "_____no_output_____" ] ], [ [ "sign_policy = SignPolicy()\n\ncurrent_time_step = tf_environment.reset()\nprint('Observation:')\nprint (current_time_step.observation)\naction = sign_policy.action(current_time_step).action\nprint('Action:')\nprint (action)\nreward = tf_environment.step(action).reward\nprint('Reward:')\nprint(reward)", "_____no_output_____" ] ], [ [ "The way bandit environments are implemented ensures that every time we take a step, we not only receive the reward for the action we took, but also the next observation.", "_____no_output_____" ] ], [ [ "step = tf_environment.reset()\naction = 1\nnext_step = tf_environment.step(action)\nreward = next_step.reward\nnext_observation = next_step.observation\nprint(\"Reward: \")\nprint(reward)\nprint(\"Next observation:\")\nprint(next_observation)", "_____no_output_____" ] ], [ [ "# Agents", "_____no_output_____" ], [ "Now that we have bandit environments and bandit policies, it is time to also define bandit agents, that take care of changing the policy based on training samples.\n\nThe API for bandit agents does not differ from that of RL agents: the agent just needs to implement the `_initialize` and `_train` methods, and define a `policy` and a `collect_policy`.", "_____no_output_____" ], [ "## A More Complicated Environment", "_____no_output_____" ], [ "Before we write our bandit agent, we need to have an environment that is a bit harder to figure out. To spice up things just a little bit, the next environment will either always give `reward = observation * action` or `reward = -observation * action`. This will be decided when the environment is initialized.", "_____no_output_____" ] ], [ [ "class TwoWayPyEnvironment(BanditPyEnvironment):\n\n def __init__(self):\n action_spec = array_spec.BoundedArraySpec(\n shape=(), dtype=np.int32, minimum=0, maximum=2, name='action')\n observation_spec = array_spec.BoundedArraySpec(\n shape=(1,), dtype=np.int32, minimum=-2, maximum=2, name='observation')\n\n # Flipping the sign with probability 1/2.\n self._reward_sign = 2 * np.random.randint(2) - 1\n print(\"reward sign:\")\n print(self._reward_sign)\n\n super(TwoWayPyEnvironment, self).__init__(observation_spec, action_spec)\n\n def _observe(self):\n self._observation = np.random.randint(-2, 3, (1,), dtype='int32')\n return self._observation\n\n def _apply_action(self, action):\n return self._reward_sign * action * self._observation[0]\n\ntwo_way_tf_environment = tf_py_environment.TFPyEnvironment(TwoWayPyEnvironment())", "_____no_output_____" ] ], [ [ "## A More Complicated Policy", "_____no_output_____" ], [ "A more complicated environment calls for a more complicated policy. We need a policy that detects the behavior of the underlying environment. There are three situations that the policy needs to handle:\n\n0. The agent has not detected know yet which version of the environment is running.\n1. The agent detected that the original version of the environment is running.\n2. The agent detected that the flipped version of the environment is running.\n\nWe define a `tf_variable` named `_situation` to store this information encoded as values in `[0, 2]`, then make the policy behave accordingly.", "_____no_output_____" ] ], [ [ "class TwoWaySignPolicy(tf_policy.TFPolicy):\n def __init__(self, situation):\n observation_spec = tensor_spec.BoundedTensorSpec(\n shape=(1,), dtype=tf.int32, minimum=-2, maximum=2)\n action_spec = tensor_spec.BoundedTensorSpec(\n shape=(), dtype=tf.int32, minimum=0, maximum=2)\n time_step_spec = ts.time_step_spec(observation_spec)\n self._situation = situation\n super(TwoWaySignPolicy, self).__init__(time_step_spec=time_step_spec,\n action_spec=action_spec)\n def _distribution(self, time_step):\n pass\n\n def _variables(self):\n return [self._situation]\n\n def _action(self, time_step, policy_state, seed):\n sign = tf.cast(tf.sign(time_step.observation[0, 0]), dtype=tf.int32)\n def case_unknown_fn():\n # Choose 1 so that we get information on the sign.\n return tf.constant(1, shape=(1,))\n\n # Choose 0 or 2, depending on the situation and the sign of the observation.\n def case_normal_fn():\n return tf.constant(sign + 1, shape=(1,))\n def case_flipped_fn():\n return tf.constant(1 - sign, shape=(1,))\n\n cases = [(tf.equal(self._situation, 0), case_unknown_fn),\n (tf.equal(self._situation, 1), case_normal_fn),\n (tf.equal(self._situation, 2), case_flipped_fn)]\n action = tf.case(cases, exclusive=True)\n return policy_step.PolicyStep(action, policy_state)", "_____no_output_____" ] ], [ [ "## The Agent", "_____no_output_____" ], [ "Now it's time to define the agent that detects the sign of the environment and sets the policy appropriately.", "_____no_output_____" ] ], [ [ "class SignAgent(tf_agent.TFAgent):\n def __init__(self):\n self._situation = tf.compat.v2.Variable(0, dtype=tf.int32)\n policy = TwoWaySignPolicy(self._situation)\n time_step_spec = policy.time_step_spec\n action_spec = policy.action_spec\n super(SignAgent, self).__init__(time_step_spec=time_step_spec,\n action_spec=action_spec,\n policy=policy,\n collect_policy=policy,\n train_sequence_length=None)\n\n def _initialize(self):\n return tf.compat.v1.variables_initializer(self.variables)\n\n def _train(self, experience, weights=None):\n observation = experience.observation\n action = experience.action\n reward = experience.reward\n\n # We only need to change the value of the situation variable if it is\n # unknown (0) right now, and we can infer the situation only if the\n # observation is not 0.\n needs_action = tf.logical_and(tf.equal(self._situation, 0),\n tf.not_equal(reward, 0))\n\n\n def new_situation_fn():\n \"\"\"This returns either 1 or 2, depending on the signs.\"\"\"\n return (3 - tf.sign(tf.cast(observation[0, 0, 0], dtype=tf.int32) *\n tf.cast(action[0, 0], dtype=tf.int32) *\n tf.cast(reward[0, 0], dtype=tf.int32))) / 2\n\n new_situation = tf.cond(needs_action,\n new_situation_fn,\n lambda: self._situation)\n new_situation = tf.cast(new_situation, tf.int32)\n tf.compat.v1.assign(self._situation, new_situation)\n return tf_agent.LossInfo((), ())\n\nsign_agent = SignAgent()\n", "_____no_output_____" ] ], [ [ "In the above code, the agent defines the policy, and the variable `situation` is shared by the agent and the policy.\n\nAlso, the parameter `experience` of the `_train` function is a trajectory:", "_____no_output_____" ], [ "# Trajectories", "_____no_output_____" ], [ "In TF-Agents, `trajectories` are named tuples that contain samples from previous steps taken. These samples are then used by the agent to train and update the policy. In RL, trajectories must contain information about the current state, the next state, and whether the current episode has ended. Since in the Bandit world we do not need these things, we set up a helper function to create a trajectory:", "_____no_output_____" ] ], [ [ "# We need to add another dimension here because the agent expects the\n# trajectory of shape [batch_size, time, ...], but in this tutorial we assume\n# that both batch size and time are 1. Hence all the expand_dims.\n\ndef trajectory_for_bandit(initial_step, action_step, final_step):\n return trajectory.Trajectory(observation=tf.expand_dims(initial_step.observation, 0),\n action=tf.expand_dims(action_step.action, 0),\n policy_info=action_step.info,\n reward=tf.expand_dims(final_step.reward, 0),\n discount=tf.expand_dims(final_step.discount, 0),\n step_type=tf.expand_dims(initial_step.step_type, 0),\n next_step_type=tf.expand_dims(final_step.step_type, 0))\n", "_____no_output_____" ] ], [ [ "# Training an Agent", "_____no_output_____" ], [ "Now all the pieces are ready for training our bandit agent.", "_____no_output_____" ] ], [ [ "step = two_way_tf_environment.reset()\nfor _ in range(10):\n action_step = sign_agent.collect_policy.action(step)\n next_step = two_way_tf_environment.step(action_step.action)\n experience = trajectory_for_bandit(step, action_step, next_step)\n print(experience)\n sign_agent.train(experience)\n step = next_step\n", "_____no_output_____" ] ], [ [ "From the output one can see that after the second step (unless the observation was 0 in the first step), the policy chooses the action in the right way and thus the reward collected is always non-negative.", "_____no_output_____" ], [ "# A Real Contextual Bandit Example", "_____no_output_____" ], [ "In the rest of this tutorial, we use the pre-implemented [environments](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/) and [agents](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/) of the TF-Agents Bandits library.", "_____no_output_____" ] ], [ [ "# Imports for example.\nfrom tf_agents.bandits.agents import lin_ucb_agent\nfrom tf_agents.bandits.environments import stationary_stochastic_py_environment as sspe\nfrom tf_agents.bandits.metrics import tf_metrics\nfrom tf_agents.drivers import dynamic_step_driver\nfrom tf_agents.replay_buffers import tf_uniform_replay_buffer\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Stationary Stochastic Environment with Linear Payoff Functions", "_____no_output_____" ], [ "The environment used in this example is the [StationaryStochasticPyEnvironment](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/environments/stationary_stochastic_py_environment.py). This environment takes as parameter a (usually noisy) function for giving observations (context), and for every arm takes an (also noisy) function that computes the reward based on the given observation. In our example, we sample the context uniformly from a d-dimensional cube, and the reward functions are linear functions of the context, plus some Gaussian noise.", "_____no_output_____" ] ], [ [ "batch_size = 2 # @param\narm0_param = [-3, 0, 1, -2] # @param\narm1_param = [1, -2, 3, 0] # @param\narm2_param = [0, 0, 1, 1] # @param\ndef context_sampling_fn(batch_size):\n \"\"\"Contexts from [-10, 10]^4.\"\"\"\n def _context_sampling_fn():\n return np.random.randint(-10, 10, [batch_size, 4]).astype(np.float32)\n return _context_sampling_fn\n\nclass LinearNormalReward(object):\n \"\"\"A class that acts as linear reward function when called.\"\"\"\n def __init__(self, theta, sigma):\n self.theta = theta\n self.sigma = sigma\n def __call__(self, x):\n mu = np.dot(x, self.theta)\n return np.random.normal(mu, self.sigma)\n\narm0_reward_fn = LinearNormalReward(arm0_param, 1)\narm1_reward_fn = LinearNormalReward(arm1_param, 1)\narm2_reward_fn = LinearNormalReward(arm2_param, 1)\n\nenvironment = tf_py_environment.TFPyEnvironment(\n sspe.StationaryStochasticPyEnvironment(\n context_sampling_fn(batch_size),\n [arm0_reward_fn, arm1_reward_fn, arm2_reward_fn],\n batch_size=batch_size))\n", "_____no_output_____" ] ], [ [ "## The LinUCB Agent", "_____no_output_____" ], [ "The agent below implements the [LinUCB](http://rob.schapire.net/papers/www10.pdf) algorithm.", "_____no_output_____" ] ], [ [ "observation_spec = tensor_spec.TensorSpec([4], tf.float32)\ntime_step_spec = ts.time_step_spec(observation_spec)\naction_spec = tensor_spec.BoundedTensorSpec(\n dtype=tf.int32, shape=(), minimum=0, maximum=2)\n\nagent = lin_ucb_agent.LinearUCBAgent(time_step_spec=time_step_spec,\n action_spec=action_spec)", "_____no_output_____" ] ], [ [ "## Regret Metric", "_____no_output_____" ], [ "Bandits' most important metric is *regret*, calculated as the difference between the reward collected by the agent and the expected reward of an oracle policy that has access to the reward functions of the environment. The [RegretMetric](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py) thus needs a *baseline_reward_fn* function that calculates the best achievable expected reward given an observation. For our example, we need to take the maximum of the no-noise equivalents of the reward functions that we already defined for the environment.", "_____no_output_____" ] ], [ [ "def compute_optimal_reward(observation):\n expected_reward_for_arms = [\n tf.linalg.matvec(observation, tf.cast(arm0_param, dtype=tf.float32)),\n tf.linalg.matvec(observation, tf.cast(arm1_param, dtype=tf.float32)),\n tf.linalg.matvec(observation, tf.cast(arm2_param, dtype=tf.float32))]\n optimal_action_reward = tf.reduce_max(expected_reward_for_arms, axis=0)\n return optimal_action_reward\n\nregret_metric = tf_metrics.RegretMetric(compute_optimal_reward)", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ], [ "Now we put together all the components that we introduced above: the environment, the policy, and the agent. We run the policy on the environment and output training data with the help of a *driver*, and train the agent on the data.\n\nNote that there are two parameters that together specify the number of steps taken. `num_iterations` specifies how many times we run the trainer loop, while the driver will take `steps_per_loop` steps per iteration. The main reason behind keeping both of these parameters is that some operations are done per iteration, while some are done by the driver in every step. For example, the agent's `train` function is only called once per iteration. The trade-off here is that if we train more often then our policy is \"fresher\", on the other hand, training in bigger batches might be more time efficient.", "_____no_output_____" ] ], [ [ "num_iterations = 90 # @param\nsteps_per_loop = 1 # @param\n\nreplay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n data_spec=agent.policy.trajectory_spec,\n batch_size=batch_size,\n max_length=steps_per_loop)\n\nobservers = [replay_buffer.add_batch, regret_metric]\n\ndriver = dynamic_step_driver.DynamicStepDriver(\n env=environment,\n policy=agent.collect_policy,\n num_steps=steps_per_loop * batch_size,\n observers=observers)\n\nregret_values = []\n\nfor _ in range(num_iterations):\n driver.run()\n loss_info = agent.train(replay_buffer.gather_all())\n replay_buffer.clear()\n regret_values.append(regret_metric.result())\n\nplt.plot(regret_values)\nplt.ylabel('Average Regret')\nplt.xlabel('Number of Iterations')", "_____no_output_____" ] ], [ [ "After running the last code snippet, the resulting plot (hopefully) shows that the average regret is going down as the agent is trained and the policy gets better in figuring out what the right action is, given the observation.", "_____no_output_____" ], [ "# What's Next?", "_____no_output_____" ], [ "To see more working examples, please see the [bandits/agents/examples](https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/agents/examples) directory that has ready-to-run examples for different agents and environments.\n\nThe TF-Agents library is also capable of handling Multi-Armed Bandits with per-arm features. To that end, we refer the reader to the per-arm bandit [tutorial](https://github.com/tensorflow/agents/blob/master/tf_agents/g3doc/tutorials/per_arm_bandits_tutorial.ipynb).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cbe4c0aa70653b6e92c4de1e704bb08799ddef4e
9,854
ipynb
Jupyter Notebook
lectures/Week4.ipynb
witting97/socialdata2022
0deaf049175c52b41ba905227e7f4e6cf42f53d4
[ "MIT" ]
14
2022-01-30T12:30:30.000Z
2022-03-27T12:36:03.000Z
lectures/Week4.ipynb
witting97/socialdata2022
0deaf049175c52b41ba905227e7f4e6cf42f53d4
[ "MIT" ]
1
2022-01-31T21:30:35.000Z
2022-01-31T21:45:34.000Z
lectures/Week4.ipynb
witting97/socialdata2022
0deaf049175c52b41ba905227e7f4e6cf42f53d4
[ "MIT" ]
40
2022-01-30T12:30:39.000Z
2022-03-28T17:35:29.000Z
75.8
484
0.70408
[ [ [ "# Week 4\n\nYay! It's week 4. Today's we'll keep things light. \n\nI've noticed that many of you are struggling a bit to keep up and still working on exercises from the previous weeks. Thus, this week we only have two components with no lectures and very little reading. \n\n\n## Overview\n\n* An exercise on visualizing geodata using a different set of tools from the ones we played with during Lecture 2.\n* Thinking about visualization, data quality, and binning. Why ***looking at the details of the data before applying fancy methods*** is often important.", "_____no_output_____" ], [ "## Part 1: Visualizing geo-data\n\nIt turns out that `plotly` (which we used during Week 2) is not the only way of working with geo-data. There are many different ways to go about it. (The hard-core PhD and PostDoc researchers in my group simply use matplotlib, since that provides more control. For an example of that kind of thing, check out [this one](https://towardsdatascience.com/visualizing-geospatial-data-in-python-e070374fe621).)\n\nToday, we'll try another library for geodata called \"[Folium](https://github.com/python-visualization/folium)\". It's good for you all to try out a few different libraries - remember that data visualization and analysis in Python is all about the ability to use many different tools. \n\nThe exercise below is based on the code illustrated in this nice [tutorial](https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data), so let us start by taking a look at that one.", "_____no_output_____" ], [ "*Reading*. Read through the following tutorial\n * \"How to: Folium for maps, heatmaps & time data\". Get it here: https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data\n * (Optional) There are also some nice tricks in \"Spatial Visualizations and Analysis in Python with Folium\". Read it here: https://towardsdatascience.com/data-101s-spatial-visualizations-and-analysis-in-python-with-folium-39730da2adf", "_____no_output_____" ], [ "> *Exercise 1.1*: A new take on geospatial data. \n>\n>A couple of weeks ago (Part 3 of Week 2), we worked with spacial data by using color-intensity of shapefiles to show the counts of certain crimes within those individual areas. Today, we look at studying geospatial data by plotting raw data points as well as heatmaps on top of actual maps.\n> \n> * First start by plotting a map of San Francisco with a nice tight zoom. Simply use the command `folium.Map([lat, lon], zoom_start=13)`, where you'll have to look up San Francisco's longitude and latitude.\n> * Next, use the the coordinates for SF City Hall `37.77919, -122.41914` to indicate its location on the map with a nice, pop-up enabled maker. (In the screenshot below, I used the black & white Stamen tiles, because they look cool).\n> <img src=\"https://raw.githubusercontent.com/suneman/socialdata2022/main/files/city_hall_2022.png\" alt=\"drawing\" width=\"600\"/>\n> * Now, let's plot some more data (no need for pop-ups this time). Select a couple of months of data for `'DRUG/NARCOTIC'` and draw a little dot for each arrest for those two months. You could, for example, choose June-July 2016, but you can choose anything you like - the main concern is to not have too many points as this uses a lot of memory and makes Folium behave non-optimally. \n> We can call this kind of visualization a *point scatter plot*.\n\nOk. Time for a little break. Note that a nice thing about Folium is that you can zoom in and out of the maps.\n\n> *Exercise 1.2*: Heatmaps.\n> * Now, let's play with **heatmaps**. You can figure out the appropriate commands by grabbing code from the main [tutorial](https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data)) and modifying to suit your needs.\n> * To create your first heatmap, grab all arrests for the category `'SEX OFFENSES, NON FORCIBLE'` across all time. Play with parameters to get plots you like.\n> * Now, comment on the differences between scatter plots and heatmaps. \n>. - What can you see using the scatter-plots that you can't see using the heatmaps? \n>. - And *vice versa*: what does the heatmaps help you see that's difficult to distinguish in the scatter-plots?\n> * Play around with the various parameters for heatmaps. You can find a list here: https://python-visualization.github.io/folium/plugins.html\n> * Comment on the effect on the various parameters for the heatmaps. How do they change the picture? (at least talk about the `radius` and `blur`).\n> For one combination of settings, my heatmap plot looks like this.\n> <img src=\"https://raw.githubusercontent.com/suneman/socialdata2022/main/files/crime_hot_spot.png\" alt=\"drawing\" width=\"600\"/>\n> * In that screenshot, I've (manually) highlighted a specific hotspot for this type of crime. Use your detective skills to find out what's going on in that building on the 800 block of Bryant street ... and explain in your own words. \n\n(*Fun fact*: I remembered the concentration of crime-counts discussed at the end of this exercise from when I did the course back in 2016. It popped up when I used a completely different framework for visualizing geodata called [`geoplotlib`](https://github.com/andrea-cuttone/geoplotlib). You can spot it if you go to that year's [lecture 2](https://nbviewer.jupyter.org/github/suneman/socialdataanalysis2016/blob/master/lectures/Week3.ipynb), exercise 4.)", "_____no_output_____" ], [ "For the final element of working with heatmaps, let's now use the cool Folium functionality `HeatMapWithTime` to create a visualization of how the patterns of your favorite crime-type changes over time.\n\n> *Exercise 1.3*: Heatmap movies. This exercise is a bit more independent than above - you get to make all the choices.\n> * Start by choosing your favorite crimetype. Prefereably one with spatial patterns that change over time (use your data-exploration from the previous lectures to choose a good one).\n> * Now, choose a time-resolution. You could plot daily, weekly, monthly datasets to plot in your movie. Again the goal is to find interesting temporal patterns to display. We want at least 20 frames though.\n> * Create the movie using `HeatMapWithTime`.\n> * Comment on your results: \n> - What patterns does your movie reveal?\n> - Motivate/explain the reasoning behind your choice of crimetype and time-resolution. ", "_____no_output_____" ], [ "## Part 2: Errors in the data. The importance of looking at raw (or close to raw) data.\n\nWe started the course by plotting simple histogram and bar plots that showed a lot of cool patterns. But sometimes the binning can hide imprecision, irregularity, and simple errors in the data that could be misleading. In the work we've done so far, we've already come across at least three examples of this in the SF data. \n\n1. In the temporal activity for `PROSTITUTION` something surprising is going on on Thursday. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2022/main/files/prostitution.png), where I've highlighted the phenomenon I'm talking about.\n2. When we investigated the details of how the timestamps are recorded using jitter-plots, we saw that many more crimes were recorded e.g. on the hour, 15 minutes past the hour, and to a lesser in whole increments of 10 minutes. Crimes didn't appear to be recorded as frequently in between those round numbers. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2022/main/files/jitter.png), where I've highlighted the phenomenon I'm talking about.\n3. And, today we saw that the Hall of Justice seemed to be an unlikely hotspot for sex offences. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2022/main/files/crime_hot_spot.png).\n\n> *Exercise 2*: Data errors. The data errors we discovered above become difficult to notice when we aggregate data (and when we calculate mean values, as well as statistics more generally). Thus, when we visualize, errors become difficult to notice when binning the data. We explore this process in the exercise below.\n>\n>This last exercise for today has two parts:\n> * In each of the examples above, describe in your own words how the data-errors I call attention to above can bias the binned versions of the data. Also, briefly mention how not noticing these errors can result in misconceptions about the underlying patterns of what's going on in San Francisco (and our modeling).\n> * Find your own example of human noise in the data and visualize it.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbe4d21daf8d41639143cce39e94360803fdec33
382,300
ipynb
Jupyter Notebook
notebooks/Milestone4.ipynb
UBC-MDS/dsci_525_group_22
1caeda4de4b57b3d825b7b6feb3f2275678efb7b
[ "MIT" ]
null
null
null
notebooks/Milestone4.ipynb
UBC-MDS/dsci_525_group_22
1caeda4de4b57b3d825b7b6feb3f2275678efb7b
[ "MIT" ]
5
2022-03-29T21:46:59.000Z
2022-03-30T05:27:47.000Z
notebooks/Milestone4.ipynb
UBC-MDS/dsci_525_group_22
1caeda4de4b57b3d825b7b6feb3f2275678efb7b
[ "MIT" ]
null
null
null
992.987013
264,374
0.94977
[ [ [ "# DSCI 525 - Web and Cloud Computing", "_____no_output_____" ], [ "***Milestone 4:*** In this milestone, you will deploy the machine learning model you trained in milestone 3.\n\nYou might want to go over [this sample project](https://github.ubc.ca/mds-2021-22/DSCI_525_web-cloud-comp_students/blob/master/release/milestone4/sampleproject.ipynb) and get it done before starting this milestone.\n\nMilestone 4 checklist :\n\n- [x] Use an EC2 instance.\n- [x] Develop your API here in this notebook.\n- [x] Copy it to ```app.py``` file in EC2 instance.\n- [x] Run your API for other consumers and test among your colleagues.\n- [x] Summarize your journey.\n\nIn this milestone, you will do certain things that you learned. For example...\n- Login to the instance\n- Work with Linux and use some basic commands\n- Configure security groups so that it accepts your webserver requests from your laptop\n- Configure AWS CLI\n\nIn some places, I explicitly mentioned these to remind you.", "_____no_output_____" ] ], [ [ "## Import all the packages that you need\nfrom flask import Flask, request, jsonify\nimport joblib\nimport numpy as np", "_____no_output_____" ] ], [ [ "## 1. Develop your API\n\nrubric={mechanics:45}", "_____no_output_____" ], [ "You probably got how to set up primary URL endpoints from the [sampleproject.ipynb](https://github.ubc.ca/mds-2021-22/DSCI_525_web-cloud-comp_students/blob/master/release/milestone4/sampleproject.ipynb) and have them process and return some data. Here we are going to create a new endpoint that accepts a POST request of the features required to run the machine learning model that you trained and saved in last milestone (i.e., a user will post the predictions of the 25 climate model rainfall predictions, i.e., features, needed to predict with your machine learning model). Your code should then process this data, use your model to make a prediction, and return that prediction to the user. To get you started with all this, I've given you a template that you should fill out to set up this functionality:\n\n***NOTE:*** You won't be able to test the flask module (or the API you make here) unless you go through steps in ```2. Deploy your API```. However, you can make sure that you develop all your functions and inputs properly here.\n\n```python\nfrom flask import Flask, request, jsonify\nimport joblib\nimport numpy as np\n## Import any other packages that are needed\n\napp = Flask(__name__)\n\n# 1. Load your model here\nmodel = joblib.load(...)\n\n# 2. Define a prediction function\ndef return_prediction(...):\n\n # format input_data here so that you can pass it to model.predict()\n\n return model.predict(...)\n\n# 3. Set up home page using basic html\[email protected](\"/\")\ndef index():\n # feel free to customize this if you like\n return \"\"\"\n <h1>Welcome to our rain prediction service</h1>\n To use this service, make a JSON post request to the /predict url with 25 climate model outputs.\n \"\"\"\n\n# 4. define a new route which will accept POST requests and return model predictions\[email protected]('/predict', methods=['POST'])\ndef rainfall_prediction():\n content = request.json # this extracts the JSON content we sent\n prediction = return_prediction(...)\n results = {...} # return whatever data you wish, it can be just the prediction\n # or it can be the prediction plus the input data, it's up to you\n return jsonify(results)\n```", "_____no_output_____" ] ], [ [ "from flask import Flask, request, jsonify\nfrom flask.logging import create_logger\nimport logging\nimport joblib\nimport numpy as np\nimport pandas as pd\n\napp = Flask(__name__)\nlogger = create_logger(app)\nlogger.setLevel(logging.INFO)\n\n# app.run(debug=True)\n\n# 1. Load your model here\nmodel = joblib.load(\"model.joblib\")\n\n# 2. Define a prediction function\ndef return_prediction(payload):\n # format input_data here so that you can pass it to model.predict()\n df = pd.DataFrame(payload)\n return model.predict(df)\n\n\n# 3. Set up home page using basic html\[email protected](\"/\")\ndef index():\n # feel free to customize this if you like\n return \"\"\"\n <h1>Welcome to our rain prediction service</h1>\n To use this service, make a JSON post request to the /predict url with 25 climate model outputs.\n \"\"\"\n\n\n# 4. define a new route which will accept POST requests and return model predictions\[email protected](\"/predict\", methods=[\"POST\"])\ndef rainfall_prediction():\n content = request.json # this extracts the JSON content we sent\n logger.info(f\"Making prediction for {content}\")\n prediction = return_prediction(content)\n prediction = list(\n prediction\n ) # return whatever data you wish, it can be just the prediction\n # or it can be the prediction plus the input data, it's up to you\n logger.info(f\"Returning prediction {prediction}\")\n return jsonify({\"predicion\": prediction})", "_____no_output_____" ] ], [ [ "## 2. Deploy your API\n\nrubric={mechanics:40}", "_____no_output_____" ], [ "Once your API (app.py) is working, we're ready to deploy it! For this, do the following:\n\n1. Setup an EC2 instance. Make sure you add a rule in security groups to accept `All TCP` connections from `Anywhere`. SSH into your EC2 instance from milestone2.\n2. Make a file `app.py` file in your instance and copy what you developed above in there. \n\n 2.1 You can use the Linux editor using ```vi```. More details on vi Editor [here](https://www.guru99.com/the-vi-editor.html). Use your previous learnings, notes, mini videos, etc. You can copy code from your jupyter and paste it into `app.py`.\n \n 2.2 Or else you can make a file in your laptop called app.py and copy it over to your EC2 instance using ```scp```. Eg: ```scp -r -i \"ggeorgeAD.pem\" ~/Desktop/app.py [email protected]:~/```\n\n3. Download your model from s3 to your EC2 instance. You want to configure your S3 for this. Use your previous learnings, notes, mini videos, etc.\n4. You should use one of those package managers to install the dependencies of your API, like `flask`, `joblib`, `sklearn`, etc...\n\n 4.1. (Additional help) you can install the required packages inside your terminal.\n - Install conda:\n wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n bash Miniconda3-latest-Linux-x86_64.sh\n - Install packages (there might be others): \n conda install flask scikit-learn joblib\n\n5. Now you're ready to start your service, go ahead and run `flask run --host=0.0.0.0 --port=8080`. This will make your service available at your EC2 instance's `Public IPv4 address` on port 8080. Please ensure that you run this from where ```app.py``` and ```model.joblib``` reside.\n6. You can now access your service by typing your EC2 instances `public IPv4 address` append with `:8080` into a browser, so something like `http://Public IPv4 address:8080`. From step 4, you might notice that flask output saying \"Running on http://XXXX:8080/ (Press CTRL+C to quit)\", where XXXX is `Private IPv4 address`, and you want to replace it with the `Public IPv4 address`\n7. You should use `curl` to send a post request to your service to make sure it's working as expected.\n>EG: curl -X POST http://your_EC2_ip:8080/predict -d '{\"data\":[1,2,3,4,53,11,22,37,41,53,11,24,31,44,53,11,22,35,42,53,12,23,31,42,53]}' -H \"Content-Type: application/json\"\n\n8. Now, what happens if you exit your connection with the EC2 instance? Can you still reach your service?\n9. We could use several options to help us persist our server even after we exit our shell session. We'll be using `screen`. `screen` will allow us to create a separate session within which we can run `flask` and won't shut down when we exit the main shell session. Read [this](https://linuxize.com/post/how-to-use-linux-screen/) to learn more on ```screen```.\n10. Now, create a new `screen` session (think of this as a new, separate shell), using: `screen -S myapi`. If you want to list already created sessions do ```screen -list```. If you want to get into an existing ```screen -x myapi```.\n11. Within that session, start up your flask app. You can then exit the session by pressing `Ctrl + A then press D`. Here you are detaching the session, once you log back into EC2 instance you can attach it using ```screen -x myapi```.\n12. Feel free to exit your connection with the EC2 instance now and try reaccessing your service with `curl`. You should find that the service has now persisted!\n13. ***CONGRATULATIONS!!!*** You have successfully got to the end of our milestones. Move to Task 3 and submit it.", "_____no_output_____" ], [ "> https://github.com/UBC-MDS/dsci_525_group_22/blob/main/screenshots/api.png", "_____no_output_____" ] ], [ [ "from IPython.display import Image\nImage(filename='../screenshots/api.png')", "_____no_output_____" ], [ "Image(filename='../screenshots/payload.png')", "_____no_output_____" ] ], [ [ "**Note** - We have used a different input values in the example above. The following files look more like the sample ipynb file and also uses the same values as input.\n\n1. https://github.com/UBC-MDS/dsci_525_group_22/blob/michelle/notebooks/Milestone4.ipynb\n\n2. https://github.com/UBC-MDS/dsci_525_group_22/blob/milestone4-mahsa/notebooks/mahsa/Milestone4.ipynb\n\nBelow is the screenshot from one of the version mentioned above.", "_____no_output_____" ], [ "> https://github.com/UBC-MDS/dsci_525_group_22/blob/main/screenshots/milestone4_curl_ms.png", "_____no_output_____" ] ], [ [ "Image(\"../screenshots/milestone4_curl_ms.png\")", "_____no_output_____" ] ], [ [ "## 3. Summarize your journey from Milestone 1 to Milestone 4\nrubric={mechanics:10}\n>There is no format or structure on how you write this. (also, no minimum number of words). It's your choice on how well you describe it.", "_____no_output_____" ], [ "**Milestone 1**\n\nIn milestone 1, we learned about different methods of making reading of data faster locally, like just loading columns needed or using chunking technique. We also learned different file formats that are optimized for the loading of big data, for example parquet files. Parquet files use arrow engine and make use of projections/predicate pushdown to speed up the reading of columns and rows of data. 'Arrow Exchange' method works best in terms of speed and implementation because it's compatible with both Python and R and Arrow's serialization/deserialization process is minimal as well as a zero-copy process. By converting to arrow format, the dataframe reading and data analysis process was a lot faster for large files.\n\n**Milestone 2**\n\nMilestone 2 we were concerned with the basics of cloud computing and setting up simple cloud instances. We also focused on the interaction between stable long term storage (S3) with the dynamic and ephemeral nature of computational power in the cloud. We practiced setting both of these services up and configuring them.\n\nThere is a mental hurdle for many in understanding what it means to connect remotely via Secure Shell - that you are connected to a computer just like your local terminal! So for beginners, understanding that is a big moment. Configuring our instances this way, and interacting with our S3 buckets are foundational cloud computing ideas that we explored and became comfortable with in this milestone.\n\n\n**Milestone 3**\n\nWe put what we learnt in lectures 5 and 6 into precise at this milestone. We learnt more about scale up and scale out in data processing, how to set up EMR, the architecture of the EMR cluster, and the distinction between the master and the slave nodes. One of the AWS primary services is EMR and scaling out with HADOOP framework and Spark processor. We developed our machine learning model in the local machine with scikit-learn. For tuning hyperparameter, we built an AWS EMR and learned how to spin an EMR cluster with the elements we want from the Hadoop ecosystem.\n\n**Milestone 4**\n\nMilestone 4's primary goal is to gain hands-on experience creating REST APIs to serve our model, and deploy in an AWS ec2 instance. In this milestone, we created app.py, which adheres to the flask app naming convention. We added code in app.py for initializing the flask app, writing a function to provide prediction, adding a home page and adding a route for prediction in flask. Then we copied app.py to AWS and served our model by running the flask app on the remote machine. The API was tested by using a curl command to send request to the server with a data instance containing all of the features required by our model.", "_____no_output_____" ], [ "## 4. Submission instructions\nrubric={mechanics:5}\n\nIn the textbox provided on Canvas please put a link where TAs can find the following-\n- [x] This notebook with solution to ```1 & 3```\n- [x] Screenshot from \n - [x] Output after trying curl. Here is a [sample](https://github.ubc.ca/mds-2021-22/DSCI_525_web-cloud-comp_students/blob/master/release/milestone4/images/curl_deploy_sample.png). This is just an example; your input/output doesn't have to look like this, you can design the way you like. But at a minimum, it should show your prediction value.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cbe4d2b640955c58c1273d22cc1f61ddda70749d
2,734
ipynb
Jupyter Notebook
.ipynb_checkpoints/Problem 20 -checkpoint.ipynb
kutayeroglu/euler-project-solutions
b6859fcec99d8d6eb1906b84a73f1b8bdc852ead
[ "MIT" ]
2
2020-05-09T22:16:04.000Z
2021-03-31T14:48:20.000Z
.ipynb_checkpoints/Problem 20 -checkpoint.ipynb
kutayeroglu/euler-project-solutions
b6859fcec99d8d6eb1906b84a73f1b8bdc852ead
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Problem 20 -checkpoint.ipynb
kutayeroglu/euler-project-solutions
b6859fcec99d8d6eb1906b84a73f1b8bdc852ead
[ "MIT" ]
null
null
null
18.598639
90
0.4594
[ [ [ "### This problem was taken from projecteuler.net", "_____no_output_____" ] ], [ [ "\"\"\"\nProblem 20 : \n\nn! means n × (n − 1) × ... × 3 × 2 × 1\n\nFor example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\nand the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n\nFind the sum of the digits in the number 100!\n\"\"\"", "_____no_output_____" ], [ "import math", "_____no_output_____" ], [ "x = math.factorial(100)", "_____no_output_____" ], [ "def digit_sum(n) : \n \n str_num = (str)(n) ## casting to string so we can iterate through the number \n digit_sum = 0\n \n for num in str_num : \n \n digit_sum += (int)(num)\n \n return digit_sum", "_____no_output_____" ], [ "print(digit_sum(x))", "648\n" ] ], [ [ "# Code runtime", "_____no_output_____" ], [ "### Processor : 2 GHz Quad-Core Intel Core i7\n", "_____no_output_____" ] ], [ [ "q = datetime.now()\nprint(digit_sum(x))\nprint(\"Solution-1 runtime : \", datetime.now()-q) ", "648\nSolution-1 runtime : 0:00:00.000362\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cbe4f3d2f291eaa0c987694187732e92a357116b
7,951
ipynb
Jupyter Notebook
2-Regression/2-Data/notebook.ipynb
PotentialError/ML-For-Beginners
c49fe3125684c806582293fc158883098eed7d6b
[ "MIT" ]
null
null
null
2-Regression/2-Data/notebook.ipynb
PotentialError/ML-For-Beginners
c49fe3125684c806582293fc158883098eed7d6b
[ "MIT" ]
null
null
null
2-Regression/2-Data/notebook.ipynb
PotentialError/ML-For-Beginners
c49fe3125684c806582293fc158883098eed7d6b
[ "MIT" ]
null
null
null
113.585714
6,021
0.864797
[ [ [ "# Pumpkin Case Study", "_____no_output_____" ] ], [ [ "import pandas as pd\r\nimport matplotlib.pyplot as plt\r\npumpkins = pd.read_csv('../data/US-pumpkins.csv')\r\npumpkins = pumpkins[pumpkins['Package'].str.contains('bushel')]\r\npumpkins = pumpkins[['Package', 'Low Price', 'High Price', 'Date']]\r\nmonth = pd.DatetimeIndex(pumpkins['Date']).month\r\nprice = (pumpkins['Low Price'] + pumpkins['High Price']) / 2\r\nnew_pumpkins = pd.DataFrame({'Month': month, 'Package': pumpkins['Package'], 'Price': price})\r\nnew_pumpkins.loc[new_pumpkins['Package'].str.contains('1 1/9'), 'Price'] = price/(1+1/9)\r\nnew_pumpkins.loc[new_pumpkins['Package'].str.contains('1/2'), 'Price'] = price/(1/2)\r\n# plt.scatter(new_pumpkins.Price, new_pumpkins.Month)\r\n#new_pumpkins.groupby(['Month'])['Price'].mean().plot(kind='bar')\r\n#plt.ylabel(\"Pumpkin Price\")\r\nnew_pumpkins.groupby(['Month'])['Price'].mean().plot.pie(y='Price', figsize=(5,5))\r\nplt.show()\r\n\r\n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
cbe5074d741ba3d0355588c0411d8543ef81eae3
7,565
ipynb
Jupyter Notebook
jupyter/tutorial/03_image_classification_with_your_model.ipynb
michaellavelle/djl
468b29490b94f8b8dc38f7f7237a119884c25ff6
[ "Apache-2.0" ]
1
2020-09-18T04:29:36.000Z
2020-09-18T04:29:36.000Z
jupyter/tutorial/03_image_classification_with_your_model.ipynb
michaellavelle/djl
468b29490b94f8b8dc38f7f7237a119884c25ff6
[ "Apache-2.0" ]
null
null
null
jupyter/tutorial/03_image_classification_with_your_model.ipynb
michaellavelle/djl
468b29490b94f8b8dc38f7f7237a119884c25ff6
[ "Apache-2.0" ]
null
null
null
34.386364
467
0.618638
[ [ [ "# Inference with your model\n\nThis is the third and final tutorial of our [beginner tutorial series](https://github.com/awslabs/djl/tree/master/jupyter/tutorial) that will take you through creating, training, and running inference on a neural network. In this tutorial, you will learn how to execute your image classification model for a production system.\n\nIn the [previous tutorial](02_train_your_first_model.ipynb), you successfully trained your model. Now, we will learn how to implement a `Translator` to convert between POJO and `NDArray` as well as a `Predictor` to run inference.\n\n\n## Preparation\n\nThis tutorial requires the installation of the Java Jupyter Kernel. To install the kernel, see the [Jupyter README](https://github.com/awslabs/djl/blob/master/jupyter/README.md).", "_____no_output_____" ] ], [ [ "// Add the snapshot repository to get the DJL snapshot artifacts\n// %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/\n\n// Add the maven dependencies\n%maven ai.djl:api:0.6.0\n%maven ai.djl:model-zoo:0.6.0\n%maven ai.djl.mxnet:mxnet-engine:0.6.0\n%maven ai.djl.mxnet:mxnet-model-zoo:0.6.0\n%maven org.slf4j:slf4j-api:1.7.26\n%maven org.slf4j:slf4j-simple:1.7.26\n%maven net.java.dev.jna:jna:5.3.0\n \n// See https://github.com/awslabs/djl/blob/master/mxnet/mxnet-engine/README.md\n// for more MXNet library selection options\n%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-b", "_____no_output_____" ], [ "import java.awt.image.*;\nimport java.nio.file.*;\nimport java.util.*;\nimport java.util.stream.*;\nimport ai.djl.*;\nimport ai.djl.basicmodelzoo.basic.*;\nimport ai.djl.ndarray.*;\nimport ai.djl.modality.*;\nimport ai.djl.modality.cv.*;\nimport ai.djl.modality.cv.util.NDImageUtils;\nimport ai.djl.translate.*;", "_____no_output_____" ] ], [ [ "## Step 1: Load your handwritten digit image\n\nWe will start by loading the image that we want to run our model to classify.", "_____no_output_____" ] ], [ [ "var img = ImageFactory.getInstance().fromUrl(\"https://djl-ai.s3.amazonaws.com/resources/images/0.png\");\nimg.getWrappedImage();", "_____no_output_____" ] ], [ [ "## Step 2: Load your model\n\nNext, we need to load the model to run inference with. This model should have been saved to the `build/mlp` directory when running the [previous tutorial](02_train_your_first_model.ipynb).\n\nTODO: Mention model zoo? List models in model zoo?\nTODO: Key Concept ZooModel\nTODO: Link to Model javadoc", "_____no_output_____" ] ], [ [ "Path modelDir = Paths.get(\"build/mlp\");\nModel model = Model.newInstance(\"mlp\");\nmodel.setBlock(new Mlp(28 * 28, 10, new int[] {128, 64}));\nmodel.load(modelDir);", "_____no_output_____" ] ], [ [ "## Step 3: Create a `Translator`\n\nThe [`Translator`](https://javadoc.io/static/ai.djl/api/0.6.0/index.html?ai/djl/translate/Translator.html) is used to encapsulate the pre-processing and post-processing functionality of your application. The input to the processInput and processOutput should be single data items, not batches.", "_____no_output_____" ] ], [ [ "Translator<Image, Classifications> translator = new Translator<Image, Classifications>() {\n\n @Override\n public NDList processInput(TranslatorContext ctx, Image input) {\n // Convert Image to NDArray\n NDArray array = input.toNDArray(ctx.getNDManager(), Image.Flag.GRAYSCALE);\n return new NDList(NDImageUtils.toTensor(array));\n }\n\n @Override\n public Classifications processOutput(TranslatorContext ctx, NDList list) {\n NDArray probabilities = list.singletonOrThrow().softmax(0);\n List<String> indices = IntStream.range(0, 10).mapToObj(String::valueOf).collect(Collectors.toList());\n return new Classifications(indices, probabilities);\n }\n \n @Override\n public Batchifier getBatchifier() {\n return Batchifier.STACK;\n }\n};", "_____no_output_____" ] ], [ [ "## Step 4: Create Predictor\n\nUsing the translator, we will create a new [`Predictor`](https://javadoc.io/static/ai.djl/api/0.6.0/index.html?ai/djl/inference/Predictor.html). The predictor is the main class to orchestrate the inference process. During inference, a trained model is used to predict values, often for production use cases. The predictor is NOT thread-safe, so if you want to do prediction in parallel, you should create a predictor object(with the same model) for each thread.", "_____no_output_____" ] ], [ [ "var predictor = model.newPredictor(translator);", "_____no_output_____" ] ], [ [ "## Step 5: Run inference\n\nWith our predictor, we can simply call the predict method to run inference. Afterwards, the same predictor should be used for further inference calls. ", "_____no_output_____" ] ], [ [ "var classifications = predictor.predict(img);\n\nclassifications", "_____no_output_____" ] ], [ [ "## Summary\n\nNow, you've successfully built a model, trained it, and run inference. Congratulations on finishing the [beginner tutorial series](https://github.com/awslabs/djl/tree/master/jupyter/tutorial). After this, you should read our other [examples](https://github.com/awslabs/djl/tree/master/examples) and [jupyter notebooks](https://github.com/awslabs/djl/tree/master/jupyter) to learn more about DJL.\n\nYou can find the complete source code for this tutorial in the [examples project](https://github.com/awslabs/djl/blob/master/examples/src/main/java/ai/djl/examples/inference/ImageClassification.java).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cbe50bcc34da0d4900358051a94c0ffa589547e9
256,548
ipynb
Jupyter Notebook
Convolutional Neural Networks/Autonomous_driving_application_Car_detection_v3a.ipynb
nekomiao123/deeplearning_coursera_code
0b6868ab70ecc5344ab6abee45ff0c1bff5ebbf7
[ "MIT" ]
1
2021-06-02T11:15:44.000Z
2021-06-02T11:15:44.000Z
Convolutional Neural Networks/Autonomous_driving_application_Car_detection_v3a.ipynb
nekomiao123/deeplearning_coursera_code
0b6868ab70ecc5344ab6abee45ff0c1bff5ebbf7
[ "MIT" ]
null
null
null
Convolutional Neural Networks/Autonomous_driving_application_Car_detection_v3a.ipynb
nekomiao123/deeplearning_coursera_code
0b6868ab70ecc5344ab6abee45ff0c1bff5ebbf7
[ "MIT" ]
null
null
null
166.58961
179,682
0.84742
[ [ [ "# Autonomous driving - Car detection\n\nWelcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: [Redmon et al., 2016](https://arxiv.org/abs/1506.02640) and [Redmon and Farhadi, 2016](https://arxiv.org/abs/1612.08242). \n\n**You will learn to**:\n- Use object detection on a car detection dataset\n- Deal with bounding boxes\n\n", "_____no_output_____" ], [ "## <font color='darkblue'>Updates</font>\n\n#### If you were working on the notebook before this update...\n* The current notebook is version \"3a\".\n* You can find your original work saved in the notebook with the previous version name (\"v3\") \n* To view the file directory, go to the menu \"File->Open\", and this will open a new tab that shows the file directory.\n\n#### List of updates\n* Clarified \"YOLO\" instructions preceding the code. \n* Added details about anchor boxes.\n* Added explanation of how score is calculated.\n* `yolo_filter_boxes`: added additional hints. Clarify syntax for argmax and max.\n* `iou`: clarify instructions for finding the intersection.\n* `iou`: give variable names for all 8 box vertices, for clarity. Adds `width` and `height` variables for clarity.\n* `iou`: add test cases to check handling of non-intersecting boxes, intersection at vertices, or intersection at edges.\n* `yolo_non_max_suppression`: clarify syntax for tf.image.non_max_suppression and keras.gather.\n* \"convert output of the model to usable bounding box tensors\": Provides a link to the definition of `yolo_head`.\n* `predict`: hint on calling sess.run.\n* Spelling, grammar, wording and formatting updates to improve clarity.", "_____no_output_____" ], [ "## Import libraries\nRun the following cell to load the packages and dependencies that you will find useful as you build the object detector!", "_____no_output_____" ] ], [ [ "import argparse\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\nimport scipy.io\nimport scipy.misc\nimport numpy as np\nimport pandas as pd\nimport PIL\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda, Conv2D\nfrom keras.models import load_model, Model\nfrom yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes\nfrom yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body\n\n%matplotlib inline", "Using TensorFlow backend.\n" ] ], [ [ "**Important Note**: As you can see, we import Keras's backend as K. This means that to use a Keras function in this notebook, you will need to write: `K.function(...)`.", "_____no_output_____" ], [ "## 1 - Problem Statement\n\nYou are working on a self-driving car. As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds while you drive around. \n\n<center>\n<video width=\"400\" height=\"200\" src=\"nb_images/road_video_compressed2.mp4\" type=\"video/mp4\" controls>\n</video>\n</center>\n\n<caption><center> Pictures taken from a car-mounted camera while driving around Silicon Valley. <br> We thank [drive.ai](htps://www.drive.ai/) for providing this dataset.\n</center></caption>\n\nYou've gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like.\n\n<img src=\"nb_images/box_label.png\" style=\"width:500px;height:250;\">\n<caption><center> <u> **Figure 1** </u>: **Definition of a box**<br> </center></caption>\n\nIf you have 80 classes that you want the object detector to recognize, you can represent the class label $c$ either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1 and the rest of which are 0. The video lectures had used the latter representation; in this notebook, we will use both representations, depending on which is more convenient for a particular step. \n\nIn this exercise, you will learn how \"You Only Look Once\" (YOLO) performs object detection, and then apply it to car detection. Because the YOLO model is very computationally expensive to train, we will load pre-trained weights for you to use. ", "_____no_output_____" ], [ "## 2 - YOLO", "_____no_output_____" ], [ "\"You Only Look Once\" (YOLO) is a popular algorithm because it achieves high accuracy while also being able to run in real-time. This algorithm \"only looks once\" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.\n\n### 2.1 - Model details\n\n#### Inputs and outputs\n- The **input** is a batch of images, and each image has the shape (m, 608, 608, 3)\n- The **output** is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers $(p_c, b_x, b_y, b_h, b_w, c)$ as explained above. If you expand $c$ into an 80-dimensional vector, each bounding box is then represented by 85 numbers. \n\n#### Anchor Boxes\n* Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes. For this assignment, 5 anchor boxes were chosen for you (to cover the 80 classes), and stored in the file './model_data/yolo_anchors.txt'\n* The dimension for anchor boxes is the second to last dimension in the encoding: $(m, n_H,n_W,anchors,classes)$.\n* The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85). \n\n\n#### Encoding\nLet's look in greater detail at what this encoding represents. \n\n<img src=\"nb_images/architecture.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 2** </u>: **Encoding architecture for YOLO**<br> </center></caption>\n\nIf the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.", "_____no_output_____" ], [ "Since we are using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.\n\nFor simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425).\n\n<img src=\"nb_images/flatten.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 3** </u>: **Flattening the last two last dimensions**<br> </center></caption>", "_____no_output_____" ], [ "#### Class score\n\nNow, for each box (of each cell) we will compute the following element-wise product and extract a probability that the box contains a certain class. \nThe class score is $score_{c,i} = p_{c} \\times c_{i}$: the probability that there is an object $p_{c}$ times the probability that the object is a certain class $c_{i}$.\n\n<img src=\"nb_images/probability_extraction.png\" style=\"width:700px;height:400;\">\n<caption><center> <u> **Figure 4** </u>: **Find the class detected by each box**<br> </center></caption>\n\n##### Example of figure 4\n* In figure 4, let's say for box 1 (cell 1), the probability that an object exists is $p_{1}=0.60$. So there's a 60% chance that an object exists in box 1 (cell 1). \n* The probability that the object is the class \"category 3 (a car)\" is $c_{3}=0.73$. \n* The score for box 1 and for category \"3\" is $score_{1,3}=0.60 \\times 0.73 = 0.44$. \n* Let's say we calculate the score for all 80 classes in box 1, and find that the score for the car class (class 3) is the maximum. So we'll assign the score 0.44 and class \"3\" to this box \"1\".\n\n#### Visualizing classes\nHere's one way to visualize what YOLO is predicting on an image:\n- For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across the 80 classes, one maximum for each of the 5 anchor boxes).\n- Color that grid cell according to what object that grid cell considers the most likely.\n\nDoing this results in this picture: \n\n<img src=\"nb_images/proba_map.png\" style=\"width:300px;height:300;\">\n<caption><center> <u> **Figure 5** </u>: Each one of the 19x19 grid cells is colored according to which class has the largest predicted probability in that cell.<br> </center></caption>\n\nNote that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm. \n", "_____no_output_____" ], [ "#### Visualizing bounding boxes\nAnother way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this: \n\n<img src=\"nb_images/anchor_map.png\" style=\"width:200px;height:200;\">\n<caption><center> <u> **Figure 6** </u>: Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes. <br> </center></caption>\n\n#### Non-Max suppression\nIn the figure above, we plotted only boxes for which the model had assigned a high probability, but this is still too many boxes. You'd like to reduce the algorithm's output to a much smaller number of detected objects. \n\nTo do so, you'll use **non-max suppression**. Specifically, you'll carry out these steps: \n- Get rid of boxes with a low score (meaning, the box is not very confident about detecting a class; either due to the low probability of any object, or low probability of this particular class).\n- Select only one box when several boxes overlap with each other and detect the same object.\n\n", "_____no_output_____" ], [ "### 2.2 - Filtering with a threshold on class scores\n\nYou are going to first apply a filter by thresholding. You would like to get rid of any box for which the class \"score\" is less than a chosen threshold. \n\nThe model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It is convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables: \n- `box_confidence`: tensor of shape $(19 \\times 19, 5, 1)$ containing $p_c$ (confidence probability that there's some object) for each of the 5 boxes predicted in each of the 19x19 cells.\n- `boxes`: tensor of shape $(19 \\times 19, 5, 4)$ containing the midpoint and dimensions $(b_x, b_y, b_h, b_w)$ for each of the 5 boxes in each cell.\n- `box_class_probs`: tensor of shape $(19 \\times 19, 5, 80)$ containing the \"class probabilities\" $(c_1, c_2, ... c_{80})$ for each of the 80 classes for each of the 5 boxes per cell.\n\n#### **Exercise**: Implement `yolo_filter_boxes()`.\n1. Compute box scores by doing the elementwise product as described in Figure 4 ($p \\times c$). \nThe following code may help you choose the right operator: \n```python\na = np.random.randn(19*19, 5, 1)\nb = np.random.randn(19*19, 5, 80)\nc = a * b # shape of c will be (19*19, 5, 80)\n```\nThis is an example of **broadcasting** (multiplying vectors of different sizes).\n\n2. For each box, find:\n - the index of the class with the maximum box score\n - the corresponding box score\n \n **Useful references**\n * [Keras argmax](https://keras.io/backend/#argmax)\n * [Keras max](https://keras.io/backend/#max)\n\n **Additional Hints**\n * For the `axis` parameter of `argmax` and `max`, if you want to select the **last** axis, one way to do so is to set `axis=-1`. This is similar to Python array indexing, where you can select the last position of an array using `arrayname[-1]`.\n * Applying `max` normally collapses the axis for which the maximum is applied. `keepdims=False` is the default option, and allows that dimension to be removed. We don't need to keep the last dimension after applying the maximum here.\n * Even though the documentation shows `keras.backend.argmax`, use `keras.argmax`. Similarly, use `keras.max`.\n\n\n3. Create a mask by using a threshold. As a reminder: `([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4)` returns: `[False, True, False, False, True]`. The mask should be True for the boxes you want to keep. \n\n4. Use TensorFlow to apply the mask to `box_class_scores`, `boxes` and `box_classes` to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep. \n\n **Useful reference**:\n * [boolean mask](https://www.tensorflow.org/api_docs/python/tf/boolean_mask) \n\n **Additional Hints**: \n * For the `tf.boolean_mask`, we can keep the default `axis=None`.\n\n**Reminder**: to call a Keras function, you should use `K.function(...)`.", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_filter_boxes\n\ndef yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):\n \"\"\"Filters YOLO boxes by thresholding on object and class confidence.\n \n Arguments:\n box_confidence -- tensor of shape (19, 19, 5, 1)\n boxes -- tensor of shape (19, 19, 5, 4)\n box_class_probs -- tensor of shape (19, 19, 5, 80)\n threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box\n \n Returns:\n scores -- tensor of shape (None,), containing the class probability score for selected boxes\n boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes\n classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes\n \n Note: \"None\" is here because you don't know the exact number of selected boxes, as it depends on the threshold. \n For example, the actual output size of scores would be (10,) if there are 10 boxes.\n \"\"\"\n \n # Step 1: Compute box scores\n ### START CODE HERE ### (≈ 1 line)\n box_scores = box_confidence * box_class_probs\n ### END CODE HERE ###\n \n # Step 2: Find the box_classes thanks to the max box_scores, keep track of the corresponding score\n ### START CODE HERE ### (≈ 2 lines)\n box_classes = K.argmax(box_scores, axis=-1)\n box_class_scores = K.max(box_scores, axis=-1)\n ### END CODE HERE ###\n \n # Step 3: Create a filtering mask based on \"box_class_scores\" by using \"threshold\". The mask should have the\n # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)\n ### START CODE HERE ### (≈ 1 line)\n filtering_mask = ((box_class_scores) >= threshold)\n ### END CODE HERE ###\n \n # Step 4: Apply the mask to scores, boxes and classes\n ### START CODE HERE ### (≈ 3 lines)\n scores = tf.boolean_mask(box_class_scores, filtering_mask, name='boolean_mask')\n boxes = tf.boolean_mask(boxes, filtering_mask, name='boolean_mask')\n classes = tf.boolean_mask(box_classes, filtering_mask, name='boolean_mask')\n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_a:\n box_confidence = tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)\n boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)\n box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)\n scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.shape))\n print(\"boxes.shape = \" + str(boxes.shape))\n print(\"classes.shape = \" + str(classes.shape))", "scores[2] = 10.7506\nboxes[2] = [ 8.42653275 3.27136683 -0.5313437 -4.94137383]\nclasses[2] = 7\nscores.shape = (?,)\nboxes.shape = (?, 4)\nclasses.shape = (?,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 10.7506\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [ 8.42653275 3.27136683 -0.5313437 -4.94137383]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n 7\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (?,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (?, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (?,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "**Note** In the test for `yolo_filter_boxes`, we're using random numbers to test the function. In real data, the `box_class_probs` would contain non-zero values between 0 and 1 for the probabilities. The box coordinates in `boxes` would also be chosen so that lengths and heights are non-negative.", "_____no_output_____" ], [ "### 2.3 - Non-max suppression ###\n\nEven after filtering by thresholding over the class scores, you still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS). ", "_____no_output_____" ], [ "<img src=\"nb_images/non-max-suppression.png\" style=\"width:500px;height:400;\">\n<caption><center> <u> **Figure 7** </u>: In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probability) of the 3 boxes. <br> </center></caption>\n", "_____no_output_____" ], [ "Non-max suppression uses the very important function called **\"Intersection over Union\"**, or IoU.\n<img src=\"nb_images/iou.png\" style=\"width:500px;height:400;\">\n<caption><center> <u> **Figure 8** </u>: Definition of \"Intersection over Union\". <br> </center></caption>\n\n#### **Exercise**: Implement iou(). Some hints:\n- In this code, we use the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (1,1) is the lower-right corner. In other words, the (0,0) origin starts at the top left corner of the image. As x increases, we move to the right. As y increases, we move down.\n- For this exercise, we define a box using its two corners: upper left $(x_1, y_1)$ and lower right $(x_2,y_2)$, instead of using the midpoint, height and width. (This makes it a bit easier to calculate the intersection).\n- To calculate the area of a rectangle, multiply its height $(y_2 - y_1)$ by its width $(x_2 - x_1)$. (Since $(x_1,y_1)$ is the top left and $x_2,y_2$ are the bottom right, these differences should be non-negative.\n- To find the **intersection** of the two boxes $(xi_{1}, yi_{1}, xi_{2}, yi_{2})$: \n - Feel free to draw some examples on paper to clarify this conceptually.\n - The top left corner of the intersection $(xi_{1}, yi_{1})$ is found by comparing the top left corners $(x_1, y_1)$ of the two boxes and finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom.\n - The bottom right corner of the intersection $(xi_{2}, yi_{2})$ is found by comparing the bottom right corners $(x_2,y_2)$ of the two boxes and finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top.\n - The two boxes **may have no intersection**. You can detect this if the intersection coordinates you calculate end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculate the height $(y_2 - y_1)$ or width $(x_2 - x_1)$ and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero). \n - The two boxes may intersect at the **edges or vertices**, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero.\n\n\n**Additional Hints**\n\n- `xi1` = **max**imum of the x1 coordinates of the two boxes\n- `yi1` = **max**imum of the y1 coordinates of the two boxes\n- `xi2` = **min**imum of the x2 coordinates of the two boxes\n- `yi2` = **min**imum of the y2 coordinates of the two boxes\n- `inter_area` = You can use `max(height, 0)` and `max(width, 0)`\n", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: iou\n\ndef iou(box1, box2):\n \"\"\"Implement the intersection over union (IoU) between box1 and box2\n    \n Arguments:\n box1 -- first box, list object with coordinates (box1_x1, box1_y1, box1_x2, box_1_y2)\n    box2 -- second box, list object with coordinates (box2_x1, box2_y1, box2_x2, box2_y2)\n    \"\"\"\n\n # Assign variable names to coordinates for clarity\n (box1_x1, box1_y1, box1_x2, box1_y2) = box1\n (box2_x1, box2_y1, box2_x2, box2_y2) = box2\n \n # Calculate the (yi1, xi1, yi2, xi2) coordinates of the intersection of box1 and box2. Calculate its Area.\n ### START CODE HERE ### (≈ 7 lines)\n xi1 = max(box1[0], box2[0])\n yi1 = max(box1[1], box2[1])\n xi2 = min(box1[2], box2[2])\n yi2 = min(box1[3], box2[3])\n inter_width = xi2 - xi1\n inter_height = yi2 - yi1\n inter_area = max(inter_height, 0) * max(inter_width, 0)\n ### END CODE HERE ###    \n\n # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)\n ### START CODE HERE ### (≈ 3 lines)\n box1_area = (box1[3] - box1[1]) * (box1[2] - box1[0])\n box2_area = (box2[3] - box2[1]) * (box2[2] - box2[0])\n union_area = box1_area + box2_area - inter_area\n ### END CODE HERE ###\n \n # compute the IoU\n ### START CODE HERE ### (≈ 1 line)\n iou = inter_area / union_area\n ### END CODE HERE ###\n \n return iou", "_____no_output_____" ], [ "## Test case 1: boxes intersect\nbox1 = (2, 1, 4, 3)\nbox2 = (1, 2, 3, 4) \nprint(\"iou for intersecting boxes = \" + str(iou(box1, box2)))\n\n## Test case 2: boxes do not intersect\nbox1 = (1,2,3,4)\nbox2 = (5,6,7,8)\nprint(\"iou for non-intersecting boxes = \" + str(iou(box1,box2)))\n\n## Test case 3: boxes intersect at vertices only\nbox1 = (1,1,2,2)\nbox2 = (2,2,3,3)\nprint(\"iou for boxes that only touch at vertices = \" + str(iou(box1,box2)))\n\n## Test case 4: boxes intersect at edge only\nbox1 = (1,1,3,3)\nbox2 = (2,3,3,4)\nprint(\"iou for boxes that only touch at edges = \" + str(iou(box1,box2)))", "iou for intersecting boxes = 0.14285714285714285\niou for non-intersecting boxes = 0.0\niou for boxes that only touch at vertices = 0.0\niou for boxes that only touch at edges = 0.0\n" ] ], [ [ "**Expected Output**:\n\n```\niou for intersecting boxes = 0.14285714285714285\niou for non-intersecting boxes = 0.0\niou for boxes that only touch at vertices = 0.0\niou for boxes that only touch at edges = 0.0\n```", "_____no_output_____" ], [ "#### YOLO non-max suppression\n\nYou are now ready to implement non-max suppression. The key steps are: \n1. Select the box that has the highest score.\n2. Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= `iou_threshold`).\n3. Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.\n\nThis will remove all boxes that have a large overlap with the selected boxes. Only the \"best\" boxes remain.\n\n**Exercise**: Implement yolo_non_max_suppression() using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your `iou()` implementation):\n\n** Reference documentation ** \n\n- [tf.image.non_max_suppression()](https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression)\n```\ntf.image.non_max_suppression(\n boxes,\n scores,\n max_output_size,\n iou_threshold=0.5,\n name=None\n)\n```\nNote that in the version of tensorflow used here, there is no parameter `score_threshold` (it's shown in the documentation for the latest version) so trying to set this value will result in an error message: *got an unexpected keyword argument 'score_threshold.*\n\n- [K.gather()](https://www.tensorflow.org/api_docs/python/tf/keras/backend/gather) \nEven though the documentation shows `tf.keras.backend.gather()`, you can use `keras.gather()`. \n```\nkeras.gather(\n reference,\n indices\n)\n```", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_non_max_suppression\n\ndef yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):\n \"\"\"\n Applies Non-max suppression (NMS) to set of boxes\n \n Arguments:\n scores -- tensor of shape (None,), output of yolo_filter_boxes()\n boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later)\n classes -- tensor of shape (None,), output of yolo_filter_boxes()\n max_boxes -- integer, maximum number of predicted boxes you'd like\n iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n \n Returns:\n scores -- tensor of shape (, None), predicted score for each box\n boxes -- tensor of shape (4, None), predicted box coordinates\n classes -- tensor of shape (, None), predicted class for each box\n \n Note: The \"None\" dimension of the output tensors has obviously to be less than max_boxes. Note also that this\n function will transpose the shapes of scores, boxes, classes. This is made for convenience.\n \"\"\"\n \n max_boxes_tensor = K.variable(max_boxes, dtype='int32') # tensor to be used in tf.image.non_max_suppression()\n K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor\n \n # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep\n ### START CODE HERE ### (≈ 1 line)\n nms_indices = tf.image.non_max_suppression(boxes = boxes, scores = scores, max_output_size = max_boxes, iou_threshold = iou_threshold)\n ### END CODE HERE ###\n \n # Use K.gather() to select only nms_indices from scores, boxes and classes\n ### START CODE HERE ### (≈ 3 lines)\n scores = K.gather(scores, nms_indices)\n boxes = K.gather(boxes, nms_indices)\n classes = K.gather(classes, nms_indices)\n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_b:\n scores = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n boxes = tf.random_normal([54, 4], mean=1, stddev=4, seed = 1)\n classes = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.eval().shape))\n print(\"boxes.shape = \" + str(boxes.eval().shape))\n print(\"classes.shape = \" + str(classes.eval().shape))", "scores[2] = 6.9384\nboxes[2] = [-5.299932 3.13798141 4.45036697 0.95942086]\nclasses[2] = -2.24527\nscores.shape = (10,)\nboxes.shape = (10, 4)\nclasses.shape = (10,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 6.9384\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [-5.299932 3.13798141 4.45036697 0.95942086]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n -2.24527\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (10, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "### 2.4 Wrapping up the filtering\n\nIt's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented. \n\n**Exercise**: Implement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which we have provided): \n\n```python\nboxes = yolo_boxes_to_corners(box_xy, box_wh) \n```\nwhich converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of `yolo_filter_boxes`\n```python\nboxes = scale_boxes(boxes, image_shape)\n```\nYOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image--for example, the car detection dataset had 720x1280 images--this step rescales the boxes so that they can be plotted on top of the original 720x1280 image. \n\nDon't worry about these two functions; we'll show you where they need to be called. ", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: yolo_eval\n\ndef yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):\n \"\"\"\n Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.\n \n Arguments:\n yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors:\n box_confidence: tensor of shape (None, 19, 19, 5, 1)\n box_xy: tensor of shape (None, 19, 19, 5, 2)\n box_wh: tensor of shape (None, 19, 19, 5, 2)\n box_class_probs: tensor of shape (None, 19, 19, 5, 80)\n image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype)\n max_boxes -- integer, maximum number of predicted boxes you'd like\n score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box\n iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n \n Returns:\n scores -- tensor of shape (None, ), predicted score for each box\n boxes -- tensor of shape (None, 4), predicted box coordinates\n classes -- tensor of shape (None,), predicted class for each box\n \"\"\"\n \n ### START CODE HERE ### \n \n # Retrieve outputs of the YOLO model (≈1 line)\n box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs[0], yolo_outputs[1], yolo_outputs[2], yolo_outputs[3]\n\n # Convert boxes to be ready for filtering functions \n boxes = yolo_boxes_to_corners(box_xy, box_wh)\n\n # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)\n scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)\n \n # Scale boxes back to original image shape.\n boxes = scale_boxes(boxes, image_shape)\n\n # Use one of the functions you've implemented to perform Non-max suppression with a threshold of iou_threshold (≈1 line)\n scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)\n \n ### END CODE HERE ###\n \n return scores, boxes, classes", "_____no_output_____" ], [ "with tf.Session() as test_b:\n yolo_outputs = (tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))\n scores, boxes, classes = yolo_eval(yolo_outputs)\n print(\"scores[2] = \" + str(scores[2].eval()))\n print(\"boxes[2] = \" + str(boxes[2].eval()))\n print(\"classes[2] = \" + str(classes[2].eval()))\n print(\"scores.shape = \" + str(scores.eval().shape))\n print(\"boxes.shape = \" + str(boxes.eval().shape))\n print(\"classes.shape = \" + str(classes.eval().shape))", "scores[2] = 138.791\nboxes[2] = [ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]\nclasses[2] = 54\nscores.shape = (10,)\nboxes.shape = (10, 4)\nclasses.shape = (10,)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **scores[2]**\n </td>\n <td>\n 138.791\n </td>\n </tr>\n <tr>\n <td>\n **boxes[2]**\n </td>\n <td>\n [ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]\n </td>\n </tr>\n\n <tr>\n <td>\n **classes[2]**\n </td>\n <td>\n 54\n </td>\n </tr>\n <tr>\n <td>\n **scores.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n <tr>\n <td>\n **boxes.shape**\n </td>\n <td>\n (10, 4)\n </td>\n </tr>\n\n <tr>\n <td>\n **classes.shape**\n </td>\n <td>\n (10,)\n </td>\n </tr>\n\n</table>", "_____no_output_____" ], [ "## Summary for YOLO:\n- Input image (608, 608, 3)\n- The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output. \n- After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):\n - Each cell in a 19x19 grid over the input image gives 425 numbers. \n - 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture. \n - 85 = 5 + 80 where 5 is because $(p_c, b_x, b_y, b_h, b_w)$ has 5 numbers, and 80 is the number of classes we'd like to detect\n- You then select only few boxes based on:\n - Score-thresholding: throw away boxes that have detected a class with a score less than the threshold\n - Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes\n- This gives you YOLO's final output. ", "_____no_output_____" ], [ "## 3 - Test YOLO pre-trained model on images", "_____no_output_____" ], [ "In this part, you are going to use a pre-trained model and test it on the car detection dataset. We'll need a session to execute the computation graph and evaluate the tensors.", "_____no_output_____" ] ], [ [ "sess = K.get_session()", "_____no_output_____" ] ], [ [ "### 3.1 - Defining classes, anchors and image shape.\n\n* Recall that we are trying to detect 80 classes, and are using 5 anchor boxes. \n* We have gathered the information on the 80 classes and 5 boxes in two files \"coco_classes.txt\" and \"yolo_anchors.txt\". \n* We'll read class names and anchors from text files.\n* The car detection dataset has 720x1280 images, which we've pre-processed into 608x608 images. ", "_____no_output_____" ] ], [ [ "class_names = read_classes(\"model_data/coco_classes.txt\")\nanchors = read_anchors(\"model_data/yolo_anchors.txt\")\nimage_shape = (720., 1280.) ", "_____no_output_____" ] ], [ [ "### 3.2 - Loading a pre-trained model\n\n* Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. \n* You are going to load an existing pre-trained Keras YOLO model stored in \"yolo.h5\". \n* These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the \"YOLOv2\" model, but we will simply refer to it as \"YOLO\" in this notebook.\n\nRun the cell below to load the model from this file.", "_____no_output_____" ] ], [ [ "yolo_model = load_model(\"model_data/yolo.h5\")", "/opt/conda/lib/python3.6/site-packages/keras/models.py:251: UserWarning: No training configuration found in save file: the model was *not* compiled. Compile it manually.\n warnings.warn('No training configuration found in save file: '\n" ] ], [ [ "This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains.", "_____no_output_____" ] ], [ [ "yolo_model.summary()", "____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\ninput_1 (InputLayer) (None, 608, 608, 3) 0 \n____________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 608, 608, 32) 864 input_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_1 (BatchNorm (None, 608, 608, 32) 128 conv2d_1[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_1 (LeakyReLU) (None, 608, 608, 32) 0 batch_normalization_1[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 304, 304, 32) 0 leaky_re_lu_1[0][0] \n____________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 304, 304, 64) 18432 max_pooling2d_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_2 (BatchNorm (None, 304, 304, 64) 256 conv2d_2[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_2 (LeakyReLU) (None, 304, 304, 64) 0 batch_normalization_2[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_2 (MaxPooling2D) (None, 152, 152, 64) 0 leaky_re_lu_2[0][0] \n____________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 152, 152, 128) 73728 max_pooling2d_2[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_3 (BatchNorm (None, 152, 152, 128) 512 conv2d_3[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_3 (LeakyReLU) (None, 152, 152, 128) 0 batch_normalization_3[0][0] \n____________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 152, 152, 64) 8192 leaky_re_lu_3[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_4 (BatchNorm (None, 152, 152, 64) 256 conv2d_4[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_4 (LeakyReLU) (None, 152, 152, 64) 0 batch_normalization_4[0][0] \n____________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 152, 152, 128) 73728 leaky_re_lu_4[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_5 (BatchNorm (None, 152, 152, 128) 512 conv2d_5[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_5 (LeakyReLU) (None, 152, 152, 128) 0 batch_normalization_5[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_3 (MaxPooling2D) (None, 76, 76, 128) 0 leaky_re_lu_5[0][0] \n____________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 76, 76, 256) 294912 max_pooling2d_3[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_6 (BatchNorm (None, 76, 76, 256) 1024 conv2d_6[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_6 (LeakyReLU) (None, 76, 76, 256) 0 batch_normalization_6[0][0] \n____________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 76, 76, 128) 32768 leaky_re_lu_6[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_7 (BatchNorm (None, 76, 76, 128) 512 conv2d_7[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_7 (LeakyReLU) (None, 76, 76, 128) 0 batch_normalization_7[0][0] \n____________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 76, 76, 256) 294912 leaky_re_lu_7[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_8 (BatchNorm (None, 76, 76, 256) 1024 conv2d_8[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_8 (LeakyReLU) (None, 76, 76, 256) 0 batch_normalization_8[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_4 (MaxPooling2D) (None, 38, 38, 256) 0 leaky_re_lu_8[0][0] \n____________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 38, 38, 512) 1179648 max_pooling2d_4[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_9 (BatchNorm (None, 38, 38, 512) 2048 conv2d_9[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_9 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_9[0][0] \n____________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 38, 38, 256) 131072 leaky_re_lu_9[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_10 (BatchNor (None, 38, 38, 256) 1024 conv2d_10[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_10 (LeakyReLU) (None, 38, 38, 256) 0 batch_normalization_10[0][0] \n____________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 38, 38, 512) 1179648 leaky_re_lu_10[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_11 (BatchNor (None, 38, 38, 512) 2048 conv2d_11[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_11 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_11[0][0] \n____________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 38, 38, 256) 131072 leaky_re_lu_11[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_12 (BatchNor (None, 38, 38, 256) 1024 conv2d_12[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_12 (LeakyReLU) (None, 38, 38, 256) 0 batch_normalization_12[0][0] \n____________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 38, 38, 512) 1179648 leaky_re_lu_12[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_13 (BatchNor (None, 38, 38, 512) 2048 conv2d_13[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_13 (LeakyReLU) (None, 38, 38, 512) 0 batch_normalization_13[0][0] \n____________________________________________________________________________________________________\nmax_pooling2d_5 (MaxPooling2D) (None, 19, 19, 512) 0 leaky_re_lu_13[0][0] \n____________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 19, 19, 1024) 4718592 max_pooling2d_5[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_14 (BatchNor (None, 19, 19, 1024) 4096 conv2d_14[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_14 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_14[0][0] \n____________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 19, 19, 512) 524288 leaky_re_lu_14[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_15 (BatchNor (None, 19, 19, 512) 2048 conv2d_15[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_15 (LeakyReLU) (None, 19, 19, 512) 0 batch_normalization_15[0][0] \n____________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 19, 19, 1024) 4718592 leaky_re_lu_15[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_16 (BatchNor (None, 19, 19, 1024) 4096 conv2d_16[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_16 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_16[0][0] \n____________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 19, 19, 512) 524288 leaky_re_lu_16[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_17 (BatchNor (None, 19, 19, 512) 2048 conv2d_17[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_17 (LeakyReLU) (None, 19, 19, 512) 0 batch_normalization_17[0][0] \n____________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 19, 19, 1024) 4718592 leaky_re_lu_17[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_18 (BatchNor (None, 19, 19, 1024) 4096 conv2d_18[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_18 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_18[0][0] \n____________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 19, 19, 1024) 9437184 leaky_re_lu_18[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_19 (BatchNor (None, 19, 19, 1024) 4096 conv2d_19[0][0] \n____________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 38, 38, 64) 32768 leaky_re_lu_13[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_19 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_19[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_21 (BatchNor (None, 38, 38, 64) 256 conv2d_21[0][0] \n____________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 19, 19, 1024) 9437184 leaky_re_lu_19[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_21 (LeakyReLU) (None, 38, 38, 64) 0 batch_normalization_21[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_20 (BatchNor (None, 19, 19, 1024) 4096 conv2d_20[0][0] \n____________________________________________________________________________________________________\nspace_to_depth_x2 (Lambda) (None, 19, 19, 256) 0 leaky_re_lu_21[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_20 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_20[0][0] \n____________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 19, 19, 1280) 0 space_to_depth_x2[0][0] \n leaky_re_lu_20[0][0] \n____________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 19, 19, 1024) 11796480 concatenate_1[0][0] \n____________________________________________________________________________________________________\nbatch_normalization_22 (BatchNor (None, 19, 19, 1024) 4096 conv2d_22[0][0] \n____________________________________________________________________________________________________\nleaky_re_lu_22 (LeakyReLU) (None, 19, 19, 1024) 0 batch_normalization_22[0][0] \n____________________________________________________________________________________________________\nconv2d_23 (Conv2D) (None, 19, 19, 425) 435625 leaky_re_lu_22[0][0] \n====================================================================================================\nTotal params: 50,983,561\nTrainable params: 50,962,889\nNon-trainable params: 20,672\n____________________________________________________________________________________________________\n" ] ], [ [ "**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do--it is fine.\n\n**Reminder**: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2).", "_____no_output_____" ], [ "### 3.3 - Convert output of the model to usable bounding box tensors\n\nThe output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following cell does that for you.\n\nIf you are curious about how `yolo_head` is implemented, you can find the function definition in the file ['keras_yolo.py'](https://github.com/allanzelener/YAD2K/blob/master/yad2k/models/keras_yolo.py). The file is located in your workspace in this path 'yad2k/models/keras_yolo.py'.", "_____no_output_____" ] ], [ [ "yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))", "_____no_output_____" ] ], [ [ "You added `yolo_outputs` to your graph. This set of 4 tensors is ready to be used as input by your `yolo_eval` function.", "_____no_output_____" ], [ "### 3.4 - Filtering boxes\n\n`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. You're now ready to perform filtering and select only the best boxes. Let's now call `yolo_eval`, which you had previously implemented, to do this. ", "_____no_output_____" ] ], [ [ "scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)", "_____no_output_____" ] ], [ [ "### 3.5 - Run the graph on an image\n\nLet the fun begin. You have created a graph that can be summarized as follows:\n\n1. <font color='purple'> yolo_model.input </font> is given to `yolo_model`. The model is used to compute the output <font color='purple'> yolo_model.output </font>\n2. <font color='purple'> yolo_model.output </font> is processed by `yolo_head`. It gives you <font color='purple'> yolo_outputs </font>\n3. <font color='purple'> yolo_outputs </font> goes through a filtering function, `yolo_eval`. It outputs your predictions: <font color='purple'> scores, boxes, classes </font>\n\n**Exercise**: Implement predict() which runs the graph to test YOLO on an image.\nYou will need to run a TensorFlow session, to have it compute `scores, boxes, classes`.\n\nThe code below also uses the following function:\n```python\nimage, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n```\nwhich outputs:\n- image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it.\n- image_data: a numpy-array representing the image. This will be the input to the CNN.\n\n**Important note**: when a model uses BatchNorm (as is the case in YOLO), you will need to pass an additional placeholder in the feed_dict {K.learning_phase(): 0}.\n\n#### Hint: Using the TensorFlow Session object\n* Recall that above, we called `K.get_Session()` and saved the Session object in `sess`.\n* To evaluate a list of tensors, we call `sess.run()` like this:\n```\nsess.run(fetches=[tensor1,tensor2,tensor3],\n feed_dict={yolo_model.input: the_input_variable,\n K.learning_phase():0\n }\n```\n* Notice that the variables `scores, boxes, classes` are not passed into the `predict` function, but these are global variables that you will use within the `predict` function.", "_____no_output_____" ] ], [ [ "def predict(sess, image_file):\n \"\"\"\n Runs the graph stored in \"sess\" to predict boxes for \"image_file\". Prints and plots the predictions.\n \n Arguments:\n sess -- your tensorflow/Keras session containing the YOLO graph\n image_file -- name of an image stored in the \"images\" folder.\n \n Returns:\n out_scores -- tensor of shape (None, ), scores of the predicted boxes\n out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes\n out_classes -- tensor of shape (None, ), class index of the predicted boxes\n \n Note: \"None\" actually represents the number of predicted boxes, it varies between 0 and max_boxes. \n \"\"\"\n\n # Preprocess your image\n image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n # You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})\n ### START CODE HERE ### (≈ 1 line)\n out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict={yolo_model.input: image_data, K.learning_phase(): 0})\n ### END CODE HERE ###\n\n # Print predictions info\n print('Found {} boxes for {}'.format(len(out_boxes), image_file))\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file), quality=90)\n # Display the results in the notebook\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file))\n imshow(output_image)\n \n return out_scores, out_boxes, out_classes", "_____no_output_____" ] ], [ [ "Run the following cell on the \"test.jpg\" image to verify that your function is correct.", "_____no_output_____" ] ], [ [ "out_scores, out_boxes, out_classes = predict(sess, \"test.jpg\")", "Found 7 boxes for test.jpg\ncar 0.60 (925, 285) (1045, 374)\ncar 0.66 (706, 279) (786, 350)\nbus 0.67 (5, 266) (220, 407)\ncar 0.70 (947, 324) (1280, 705)\ncar 0.74 (159, 303) (346, 440)\ncar 0.80 (761, 282) (942, 412)\ncar 0.89 (367, 300) (745, 648)\n" ] ], [ [ "**Expected Output**:\n\n<table>\n <tr>\n <td>\n **Found 7 boxes for test.jpg**\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.60 (925, 285) (1045, 374)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.66 (706, 279) (786, 350)\n </td>\n </tr>\n <tr>\n <td>\n **bus**\n </td>\n <td>\n 0.67 (5, 266) (220, 407)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.70 (947, 324) (1280, 705)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.74 (159, 303) (346, 440)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.80 (761, 282) (942, 412)\n </td>\n </tr>\n <tr>\n <td>\n **car**\n </td>\n <td>\n 0.89 (367, 300) (745, 648)\n </td>\n </tr>\n</table>", "_____no_output_____" ], [ "The model you've just run is actually able to detect 80 different classes listed in \"coco_classes.txt\". To test the model on your own images:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Write your image's name in the cell above code\n 4. Run the code and see the output of the algorithm!\n\nIf you were to run your session in a for loop over all your images. Here's what you would get:\n\n<center>\n<video width=\"400\" height=\"200\" src=\"nb_images/pred_video_compressed2.mp4\" type=\"video/mp4\" controls>\n</video>\n</center>\n\n<caption><center> Predictions of the YOLO model on pictures taken from a camera while driving around the Silicon Valley <br> Thanks [drive.ai](https://www.drive.ai/) for providing this dataset! </center></caption>", "_____no_output_____" ], [ "\n## <font color='darkblue'>What you should remember:\n \n- YOLO is a state-of-the-art object detection model that is fast and accurate\n- It runs an input image through a CNN which outputs a 19x19x5x85 dimensional volume. \n- The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.\n- You filter through all the boxes using non-max suppression. Specifically: \n - Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes\n - Intersection over Union (IoU) thresholding to eliminate overlapping boxes\n- Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise. ", "_____no_output_____" ], [ "**References**: The ideas presented in this notebook came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener's GitHub repository. The pre-trained weights used in this exercise came from the official YOLO website. \n- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - [You Only Look Once: Unified, Real-Time Object Detection](https://arxiv.org/abs/1506.02640) (2015)\n- Joseph Redmon, Ali Farhadi - [YOLO9000: Better, Faster, Stronger](https://arxiv.org/abs/1612.08242) (2016)\n- Allan Zelener - [YAD2K: Yet Another Darknet 2 Keras](https://github.com/allanzelener/YAD2K)\n- The official YOLO website (https://pjreddie.com/darknet/yolo/) ", "_____no_output_____" ], [ "**Car detection dataset**:\n<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" property=\"dct:title\">The Drive.ai Sample Dataset</span> (provided by drive.ai) is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>. We are grateful to Brody Huval, Chih Hu and Rahul Patel for providing this data. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cbe50d34a31df44a741f90dc36842b4bc7b25d31
72,089
ipynb
Jupyter Notebook
Gearbox Parameters.ipynb
apeir99n/gearbox-analytics
09a747a74b90925ac850353334d28ed1b8b0e502
[ "MIT" ]
null
null
null
Gearbox Parameters.ipynb
apeir99n/gearbox-analytics
09a747a74b90925ac850353334d28ed1b8b0e502
[ "MIT" ]
null
null
null
Gearbox Parameters.ipynb
apeir99n/gearbox-analytics
09a747a74b90925ac850353334d28ed1b8b0e502
[ "MIT" ]
null
null
null
169.223005
14,021
0.575969
[ [ [ "addressProviderAddr = '0xcF64698AFF7E5f27A11dff868AF228653ba53be0' #mainnet\n#addressProviderAddr = '0xA526311C39523F60b184709227875b5f34793bD4' #kovan", "_____no_output_____" ], [ "\nimport os\nfrom dotenv import load_dotenv \n\nload_dotenv() # add this line\nproviderRPC = os.getenv('RPC_NODE')\n\n", "_____no_output_____" ], [ "from web3 import Web3\nimport json \n\n\nw3 = Web3(Web3.HTTPProvider(providerRPC))\n", "_____no_output_____" ], [ "afAbi = json.loads( '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"addressProvider\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"miner\",\"type\":\"address\"}],\"name\":\"AccountMinerChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"creditManager\",\"type\":\"address\"}],\"name\":\"InitializeCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"NewCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"ReturnCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"TakeForever\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"_contractsRegister\",\"outputs\":[{\"internalType\":\"contract ContractsRegister\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"addCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"swapContract\",\"type\":\"address\"}],\"internalType\":\"struct DataTypes.MiningApproval[]\",\"name\":\"_miningApprovals\",\"type\":\"tuple[]\"}],\"name\":\"addMiningApprovals\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"}],\"name\":\"cancelAllowance\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"countCreditAccounts\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"countCreditAccountsInStock\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"creditAccounts\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"finishMining\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"getNext\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"head\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"isCreditAccount\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"isMiningFinished\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"masterCreditAccount\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"mineCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"miningApprovals\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"swapContract\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"usedAccount\",\"type\":\"address\"}],\"name\":\"returnCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tail\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_cumulativeIndexAtOpen\",\"type\":\"uint256\"}],\"name\":\"takeCreditAccount\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"prev\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"takeOut\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]' )\ncaAbi = json.loads( '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"swapContract\",\"type\":\"address\"}],\"name\":\"approveToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"borrowedAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"}],\"name\":\"cancelAllowance\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_creditManager\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_cumulativeIndexAtOpen\",\"type\":\"uint256\"}],\"name\":\"connectTo\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"creditManager\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"cumulativeIndexAtOpen\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"destination\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"execute\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"safeTransfer\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"since\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_cumulativeIndexAtOpen\",\"type\":\"uint256\"}],\"name\":\"updateParameters\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}] ' )\n\naddressProviderAbi = json.loads( '[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"service\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newAddress\",\"type\":\"address\"}],\"name\":\"AddressSet\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"user_id\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"leaf\",\"type\":\"bytes32\"}],\"name\":\"Claimed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"ACCOUNT_FACTORY\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"ACL\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"CONTRACTS_REGISTER\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"DATA_COMPRESSOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"GEAR_TOKEN\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"LEVERAGED_ACTIONS\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PRICE_ORACLE\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"TREASURY_CONTRACT\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"WETH_GATEWAY\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"WETH_TOKEN\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"addresses\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getACL\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getAccountFactory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getContractsRegister\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getDataCompressor\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getGearToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getLeveragedActions\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getPriceOracle\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getTreasuryContract\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getWETHGateway\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getWethToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setACL\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setAccountFactory\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setContractsRegister\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setDataCompressor\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setGearToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setLeveragedActions\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setPriceOracle\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setTreasuryContract\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setWETHGateway\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setWethToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]')\ncontractsRegistryAbi = json.loads( '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"addressProvider\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"creditManager\",\"type\":\"address\"}],\"name\":\"NewCreditManagerAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"pool\",\"type\":\"address\"}],\"name\":\"NewPoolAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newCreditManager\",\"type\":\"address\"}],\"name\":\"addCreditManager\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newPoolAddress\",\"type\":\"address\"}],\"name\":\"addPool\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"creditManagers\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getCreditManagers\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getCreditManagersCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getPools\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getPoolsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"isCreditManager\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"isPool\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"pools\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]')\ncreditManagerAbi = json.loads( '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_addressProvider\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_minAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maxAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maxLeverage\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"_poolService\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_creditFilterAddress\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_defaultSwapContract\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"onBehalfOf\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"AddCollateral\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"remainingFunds\",\"type\":\"uint256\"}],\"name\":\"CloseCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"ExecuteOrder\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"IncreaseBorrowedAmount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"liquidator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"remainingFunds\",\"type\":\"uint256\"}],\"name\":\"LiquidateCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"minAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"maxAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"maxLeverage\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeInterest\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"feeLiquidation\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"liquidationDiscount\",\"type\":\"uint256\"}],\"name\":\"NewParameters\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"onBehalfOf\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"borrowAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"referralCode\",\"type\":\"uint256\"}],\"name\":\"OpenCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"RepayCreditAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"oldOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"TransferAccount\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"totalValue\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"isLiquidated\",\"type\":\"bool\"}],\"name\":\"_calcClosePayments\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"_borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountToPool\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"remainingFunds\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"profit\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"loss\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"totalValue\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"isLiquidated\",\"type\":\"bool\"},{\"internalType\":\"uint256\",\"name\":\"borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"cumulativeIndexAtCreditAccountOpen_RAY\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"cumulativeIndexNow_RAY\",\"type\":\"uint256\"}],\"name\":\"_calcClosePaymentsPure\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"_borrowedAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountToPool\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"remainingFunds\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"profit\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"loss\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"onBehalfOf\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"addCollateral\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"isLiquidated\",\"type\":\"bool\"}],\"name\":\"calcRepayAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"components\":[{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"}],\"internalType\":\"struct DataTypes.Exchange[]\",\"name\":\"paths\",\"type\":\"tuple[]\"}],\"name\":\"closeCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"creditAccounts\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"creditFilter\",\"outputs\":[{\"internalType\":\"contract ICreditFilter\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"defaultSwapContract\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"executeOrder\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"feeInterest\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"feeLiquidation\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"}],\"name\":\"getCreditAccountOrRevert\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"}],\"name\":\"hasOpenedCreditAccount\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"increaseBorrowedAmount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"force\",\"type\":\"bool\"}],\"name\":\"liquidateCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"liquidationDiscount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"maxAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"maxLeverageFactor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"minAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"minHealthFactor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"onBehalfOf\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"leverageFactor\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"referralCode\",\"type\":\"uint256\"}],\"name\":\"openCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolService\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"provideCreditAccountAllowance\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"repayCreditAccount\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"repayCreditAccountETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_minAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maxAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maxLeverageFactor\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_feeInterest\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_feeLiquidation\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_liquidationDiscount\",\"type\":\"uint256\"}],\"name\":\"setParams\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferAccountOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"underlyingToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"wethAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"wethGateway\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]' )\nerc20Abi = json.loads( '[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"chainId_\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"src\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"guy\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":true,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes4\",\"name\":\"sig\",\"type\":\"bytes4\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"arg1\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"arg2\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"LogNote\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"src\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"dst\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"constant\":true,\"inputs\":[],\"name\":\"DOMAIN_SEPARATOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PERMIT_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"guy\",\"type\":\"address\"}],\"name\":\"deny\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"src\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"dst\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"move\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"nonces\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"holder\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expiry\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"allowed\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"permit\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"pull\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"usr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"push\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"guy\",\"type\":\"address\"}],\"name\":\"rely\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"dst\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"src\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"dst\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"wad\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"wards\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]')\ncreditFilterAbi = json.loads( '[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_addressProvider\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_underlyingToken\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"protocol\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"adapter\",\"type\":\"address\"}],\"name\":\"ContractAllowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"protocol\",\"type\":\"address\"}],\"name\":\"ContractForbidden\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"chiThreshold\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"fastCheckDelay\",\"type\":\"uint256\"}],\"name\":\"NewFastCheckParameters\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newPriceOracle\",\"type\":\"address\"}],\"name\":\"PriceOracleUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"liquidityThreshold\",\"type\":\"uint256\"}],\"name\":\"TokenAllowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"TokenForbidden\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"state\",\"type\":\"bool\"}],\"name\":\"TransferAccountAllowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"pugin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"state\",\"type\":\"bool\"}],\"name\":\"TransferPluginAllowed\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"addressProvider\",\"outputs\":[{\"internalType\":\"contract AddressProvider\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"adapter\",\"type\":\"address\"}],\"name\":\"allowContract\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"plugin\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"state\",\"type\":\"bool\"}],\"name\":\"allowPlugin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidationThreshold\",\"type\":\"uint256\"}],\"name\":\"allowToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"allowanceForAccountTransfers\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowedAdapters\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"allowedContracts\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"allowedContractsCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowedPlugins\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"allowedTokens\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"allowedTokensCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"state\",\"type\":\"bool\"}],\"name\":\"approveAccountTransfers\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"calcCreditAccountAccruedInterest\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"calcCreditAccountHealthFactor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"percentage\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"times\",\"type\":\"uint256\"}],\"name\":\"calcMaxPossibleDrop\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"calcThresholdWeightedValue\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"total\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"calcTotalValue\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"total\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"checkAndEnableToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenIn\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenOut\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"name\":\"checkCollateralChange\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"uint256[]\",\"name\":\"amountIn\",\"type\":\"uint256[]\"},{\"internalType\":\"uint256[]\",\"name\":\"amountOut\",\"type\":\"uint256[]\"},{\"internalType\":\"address[]\",\"name\":\"tokenIn\",\"type\":\"address[]\"},{\"internalType\":\"address[]\",\"name\":\"tokenOut\",\"type\":\"address[]\"}],\"name\":\"checkMultiTokenCollateral\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"chiThreshold\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_creditManager\",\"type\":\"address\"}],\"name\":\"connectCreditManager\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"contractToAdapter\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"creditManager\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"enabledTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"fastCheckCounter\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"}],\"name\":\"forbidContract\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"forbidToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"getCreditAccountTokenById\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"balance\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"tv\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"tvw\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"hfCheckInterval\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"}],\"name\":\"initEnabledTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"isTokenAllowed\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"liquidationThresholds\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"poolService\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"priceOracle\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"revertIfAccountTransferIsNotAllowed\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"creditAccount\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"minHealthFactor\",\"type\":\"uint256\"}],\"name\":\"revertIfCantIncreaseBorrowing\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"revertIfTokenNotAllowed\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_chiThreshold\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_hfCheckInterval\",\"type\":\"uint256\"}],\"name\":\"setFastCheckParameters\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"tokenMasksMap\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"underlyingToken\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"updateUnderlyingTokenLiquidationThreshold\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"upgradePriceOracle\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"wethAddress\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]' )", "_____no_output_____" ], [ "def initContract( address, abi ):\n checksumAddr = Web3.toChecksumAddress( address )\n contract = w3.eth.contract(checksumAddr, abi=abi )\n return contract", "_____no_output_____" ], [ "def toChecksumArray( arr ):\n result = []\n for addr in arr:\n result.append( Web3.toChecksumAddress( addr ) )\n return result", "_____no_output_____" ], [ "def erc20Params( address ): \n token = initContract( address, erc20Abi )\n symbol = token.functions.symbol().call()\n decimals = token.functions.decimals().call()\n \n return {'token': address, 'symbol': symbol, 'decimals': decimals }", "_____no_output_____" ], [ "def normalizeNumber( numb, decimals): \n return numb / 10**decimals", "_____no_output_____" ], [ "def filterParams( cFilter ): \n creditFilter = initContract( cFilter, creditFilterAbi )\n\n print( 'CreditFilter: ', cFilter )\n print( \" hfCheckInterval: \", creditFilter.functions.hfCheckInterval().call() )\n print( \" Paused: \", creditFilter.functions.paused().call() )\n \n allowedContractsCount = creditFilter.functions.allowedContractsCount().call()\n print( ' Allowed Contracts: ')\n \n for i in range(allowedContractsCount): \n allowedContractAddr = Web3.toChecksumAddress( creditFilter.functions.allowedContracts(i).call() )\n print( ' ', i, ': ', allowedContractAddr )\n \n print( ' Adapters: ')\n for i in range(allowedContractsCount): \n print( ' ', i, ': ', creditFilter.functions.contractToAdapter(i).call() )\n \n allowedTokensCount = creditFilter.functions.allowedTokensCount().call()\n print( ' Allowed Tokens: ' )\n for i in range( allowedTokensCount ): \n tokenAddr = creditFilter.functions.allowedTokens(i).call()\n lt = creditFilter.functions.liquidationThresholds(tokenAddr).call()\n token = erc20Params( tokenAddr )\n print( ' ', i, ': ', tokenAddr, token['symbol'], normalizeNumber(lt,4) )\n ", "_____no_output_____" ], [ "def managerParams( manager ): \n creditManager = initContract( manager, creditManagerAbi )\n print( '------------------------------------')\n \n tokenAddr = creditManager.functions.underlyingToken().call()\n token = erc20Params( tokenAddr )\n \n print( \"CreditManager: \", manager )\n print( \"DefaultSwapContract: \", creditManager.functions.defaultSwapContract().call() )\n print( \"Fee Interest(%): \", normalizeNumber( creditManager.functions.feeInterest().call(), 2) )\n print( \"Fee Liquidation(%): \", normalizeNumber( creditManager.functions.feeLiquidation().call(), 2) )\n print( \"Liquidation Discount(%): \", normalizeNumber( creditManager.functions.liquidationDiscount().call(), 2) )\n print( \"Min amount: \", normalizeNumber( creditManager.functions.minAmount().call(), token['decimals'] ) )\n print( \"Max amount: \", normalizeNumber(creditManager.functions.maxAmount().call(), token['decimals'] ) )\n print( \"Max Leverage Factor: \", normalizeNumber( creditManager.functions.maxLeverageFactor().call(), 2) )\n print( \"Min Health Factor: \", normalizeNumber( creditManager.functions.minHealthFactor().call(), 4) )\n print( \"Paused: \", creditManager.functions.paused().call() )\n\n print( \"Underlying token: \", token['symbol'] )\n \n cFilter = creditManager.functions.creditFilter().call()\n filterParams( cFilter )\n ", "_____no_output_____" ], [ "# find and init ContractRegistry\naddressProvider = initContract( addressProviderAddr, addressProviderAbi )\ncontractRegistryAddr = addressProvider.functions.getContractsRegister().call()\ncontractRegistry = initContract( contractRegistryAddr, contractsRegistryAbi )", "_____no_output_____" ], [ "# find pools and creditmanagers\npools = contractRegistry.functions.getPools().call()\nmanagers = contractRegistry.functions.getCreditManagers().call()", "_____no_output_____" ], [ "# print creditmanagers parameters\nfor i in range( len(managers)): \n managerParams( managers[i])", "------------------------------------\nCreditManager: 0x777E23A2AcB2fCbB35f6ccF98272d03C722Ba6EB\nDefaultSwapContract: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\nFee Interest(%): 10.0\nFee Liquidation(%): 2.0\nLiquidation Discount(%): 95.0\nMin amount: 1000.0\nMax amount: 10000.0\nMax Leverage Factor: 3.0\nMin Health Factor: 1.24\nPaused: False\nUnderlying token: DAI\nCreditFilter: 0x948D33a9537cf13bCC656218B385D19E5b6693e8\n hfCheckInterval: 4\n Paused: False\n Allowed Contracts: \n 0 : 0xE592427A0AEce92De3Edee1F18E0157C05861564\n 1 : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\n 2 : 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F\n 3 : 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7\n 4 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95\n 5 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE\n Allowed Tokens: \n 0 : 0x6B175474E89094C44Da98b954EedeAC495271d0F DAI 0.93\n 1 : 0x111111111117dC0aa78b770fA6A738034120C302 1INCH 0.775\n 2 : 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 AAVE 0.75\n 3 : 0xc00e94Cb662C3520282E6f5717214004A7f26888 COMP 0.8\n 4 : 0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b DPI 0.775\n 5 : 0x956F47F50A910163D8BF957Cf5846D573E7f87CA FEI 0.85\n 6 : 0x514910771AF9Ca656af840dff83E8264EcF986CA LINK 0.75\n 7 : 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F SNX 0.775\n 8 : 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 UNI 0.75\n 9 : 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 USDC 0.875\n 10 : 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 WBTC 0.85\n 11 : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 WETH 0.85\n 12 : 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e YFI 0.725\n 13 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95 yvDAI 0.9\n 14 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE yvUSDC 0.875\n------------------------------------\nCreditManager: 0x2664cc24CBAd28749B3Dd6fC97A6B402484De527\nDefaultSwapContract: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\nFee Interest(%): 10.0\nFee Liquidation(%): 2.0\nLiquidation Discount(%): 95.0\nMin amount: 1000.0\nMax amount: 10000.0\nMax Leverage Factor: 3.0\nMin Health Factor: 1.24\nPaused: False\nUnderlying token: USDC\nCreditFilter: 0x301E7Ed8ac816747A65cf67D8901659e637a4383\n hfCheckInterval: 4\n Paused: False\n Allowed Contracts: \n 0 : 0xE592427A0AEce92De3Edee1F18E0157C05861564\n 1 : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\n 2 : 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F\n 3 : 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7\n 4 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95\n 5 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE\n Allowed Tokens: \n 0 : 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 USDC 0.93\n 1 : 0x111111111117dC0aa78b770fA6A738034120C302 1INCH 0.775\n 2 : 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 AAVE 0.75\n 3 : 0xc00e94Cb662C3520282E6f5717214004A7f26888 COMP 0.8\n 4 : 0x6B175474E89094C44Da98b954EedeAC495271d0F DAI 0.875\n 5 : 0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b DPI 0.775\n 6 : 0x956F47F50A910163D8BF957Cf5846D573E7f87CA FEI 0.85\n 7 : 0x514910771AF9Ca656af840dff83E8264EcF986CA LINK 0.75\n 8 : 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F SNX 0.775\n 9 : 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 UNI 0.75\n 10 : 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 WBTC 0.85\n 11 : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 WETH 0.85\n 12 : 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e YFI 0.775\n 13 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95 yvDAI 0.875\n 14 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE yvUSDC 0.9\n------------------------------------\nCreditManager: 0x968f9a68a98819E2e6Bb910466e191A7b6cf02F0\nDefaultSwapContract: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\nFee Interest(%): 10.0\nFee Liquidation(%): 2.0\nLiquidation Discount(%): 95.0\nMin amount: 0.3\nMax amount: 2.5\nMax Leverage Factor: 3.0\nMin Health Factor: 1.24\nPaused: False\nUnderlying token: WETH\nCreditFilter: 0x790D170C12e62aDa6CD2D409a50177680c4ddF29\n hfCheckInterval: 4\n Paused: False\n Allowed Contracts: \n 0 : 0xE592427A0AEce92De3Edee1F18E0157C05861564\n 1 : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\n 2 : 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F\n 3 : 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7\n 4 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95\n 5 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE\n Allowed Tokens: \n 0 : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 WETH 0.93\n 1 : 0x111111111117dC0aa78b770fA6A738034120C302 1INCH 0.775\n 2 : 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 AAVE 0.75\n 3 : 0xc00e94Cb662C3520282E6f5717214004A7f26888 COMP 0.8\n 4 : 0x6B175474E89094C44Da98b954EedeAC495271d0F DAI 0.85\n 5 : 0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b DPI 0.775\n 6 : 0x956F47F50A910163D8BF957Cf5846D573E7f87CA FEI 0.85\n 7 : 0x514910771AF9Ca656af840dff83E8264EcF986CA LINK 0.75\n 8 : 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F SNX 0.775\n 9 : 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 UNI 0.75\n 10 : 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 USDC 0.85\n 11 : 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 WBTC 0.85\n 12 : 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e YFI 0.725\n 13 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95 yvDAI 0.85\n 14 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE yvUSDC 0.85\n------------------------------------\nCreditManager: 0xC38478B0A4bAFE964C3526EEFF534d70E1E09017\nDefaultSwapContract: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\nFee Interest(%): 10.0\nFee Liquidation(%): 2.0\nLiquidation Discount(%): 95.0\nMin amount: 0.02\nMax amount: 0.2\nMax Leverage Factor: 3.0\nMin Health Factor: 1.24\nPaused: False\nUnderlying token: WBTC\nCreditFilter: 0xcF223eB26dA2Bf147D01b750d2D2393025cEA7Ca\n hfCheckInterval: 4\n Paused: False\n Allowed Contracts: \n 0 : 0xE592427A0AEce92De3Edee1F18E0157C05861564\n 1 : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\n 2 : 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F\n 3 : 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7\n 4 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95\n 5 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE\n Allowed Tokens: \n 0 : 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 WBTC 0.93\n 1 : 0x111111111117dC0aa78b770fA6A738034120C302 1INCH 0.775\n 2 : 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 AAVE 0.75\n 3 : 0xc00e94Cb662C3520282E6f5717214004A7f26888 COMP 0.8\n 4 : 0x6B175474E89094C44Da98b954EedeAC495271d0F DAI 0.85\n 5 : 0x1494CA1F11D487c2bBe4543E90080AeBa4BA3C2b DPI 0.775\n 6 : 0x956F47F50A910163D8BF957Cf5846D573E7f87CA FEI 0.85\n 7 : 0x514910771AF9Ca656af840dff83E8264EcF986CA LINK 0.75\n 8 : 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F SNX 0.775\n 9 : 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 UNI 0.75\n 10 : 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 USDC 0.85\n 11 : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 WETH 0.85\n 12 : 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e YFI 0.725\n 13 : 0xdA816459F1AB5631232FE5e97a05BBBb94970c95 yvDAI 0.85\n 14 : 0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE yvUSDC 0.85\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe514dc71eb7355e712f06d27968078ba9ab3d5
559
ipynb
Jupyter Notebook
examples/No-Op Notebook.ipynb
nrbgt/jupyterlab-starters
ef5384b754f92873d4ae328ad910e1de3b3782f7
[ "BSD-3-Clause" ]
26
2019-12-14T13:59:59.000Z
2022-02-23T08:57:54.000Z
examples/No-Op Notebook.ipynb
nrbgt/jupyterlab-starters
ef5384b754f92873d4ae328ad910e1de3b3782f7
[ "BSD-3-Clause" ]
45
2019-12-18T06:40:26.000Z
2022-03-16T16:14:31.000Z
examples/No-Op Notebook.ipynb
nrbgt/jupyterlab-starters
ef5384b754f92873d4ae328ad910e1de3b3782f7
[ "BSD-3-Clause" ]
6
2019-12-18T22:14:24.000Z
2022-02-14T07:56:24.000Z
16.939394
41
0.533095
[ [ [ "> This notebook doesn't do anything", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
cbe51eb30c69f7d8a70992cedd113391071cec3e
24,516
ipynb
Jupyter Notebook
models/energy_production_lr/energy_production_lr.ipynb
adrianghc/HEMS
94ffd85a050211efc6ef785b873ee39e906a8b78
[ "MIT" ]
4
2021-06-05T22:32:21.000Z
2022-03-15T11:05:13.000Z
models/energy_production_lr/energy_production_lr.ipynb
adrianghc/HEMS
94ffd85a050211efc6ef785b873ee39e906a8b78
[ "MIT" ]
4
2021-06-06T10:23:28.000Z
2021-06-06T10:42:24.000Z
models/energy_production_lr/energy_production_lr.ipynb
adrianghc/HEMS
94ffd85a050211efc6ef785b873ee39e906a8b78
[ "MIT" ]
1
2021-08-25T13:20:34.000Z
2021-08-25T13:20:34.000Z
31.151207
164
0.51289
[ [ [ "# Copyright (c) 2020-2021 Adrian Georg Herrmann", "_____no_output_____" ], [ "import os\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom scipy import interpolate\nfrom sklearn.linear_model import LinearRegression\n\nfrom datetime import datetime", "_____no_output_____" ], [ "data_root = \"../../data\"\n\nlocations = {\n \"berlin\": [\"52.4652025\", \"13.3412466\"],\n \"wijchen\": [\"51.8235504\", \"5.7329005\"]\n}\ndfs = { \"berlin\": None, \"wijchen\": None }", "_____no_output_____" ] ], [ [ "## Sunlight angles", "_____no_output_____" ] ], [ [ "def get_julian_day(time):\n if time.month > 2:\n y = time.year\n m = time.month\n else:\n y = time.year - 1\n m = time.month + 12\n d = time.day + time.hour / 24 + time.minute / 1440 + time.second / 86400\n b = 2 - np.floor(y / 100) + np.floor(y / 400)\n\n jd = np.floor(365.25 * (y + 4716)) + np.floor(30.6001 * (m + 1)) + d + b - 1524.5\n return jd", "_____no_output_____" ], [ "def get_angle(time, latitude, longitude):\n # Source: \n # https://de.wikipedia.org/wiki/Sonnenstand#Genauere_Ermittlung_des_Sonnenstandes_f%C3%BCr_einen_Zeitpunkt\n\n # 1. Eclipctical coordinates of the sun\n\n # Julian day\n jd = get_julian_day(time)\n\n n = jd - 2451545\n\n # Median ecliptic longitude of the sun<\n l = np.mod(280.46 + 0.9856474 * n, 360)\n\n # Median anomaly\n g = np.mod(357.528 + 0.9856003 * n, 360)\n\n # Ecliptic longitude of the sun\n lbd = l + 1.915 * np.sin(np.radians(g)) + 0.01997 * np.sin(np.radians(2*g))\n\n\n # 2. Equatorial coordinates of the sun\n\n # Ecliptic\n eps = 23.439 - 0.0000004 * n\n\n # Right ascension\n alpha = np.degrees(np.arctan(np.cos(np.radians(eps)) * np.tan(np.radians(lbd))))\n if np.cos(np.radians(lbd)) < 0:\n alpha += 180\n\n # Declination\n delta = np.degrees(np.arcsin(np.sin(np.radians(eps)) * np.sin(np.radians(lbd))))\n\n\n # 3. Horizontal coordinates of the sun\n\n t0 = (get_julian_day(time.replace(hour=0, minute=0, second=0)) - 2451545) / 36525\n\n # Median sidereal time\n theta_hg = np.mod(6.697376 + 2400.05134 * t0 + 1.002738 * (time.hour + time.minute / 60), 24)\n\n theta_g = theta_hg * 15\n theta = theta_g + longitude\n\n # Hour angle of the sun\n tau = theta - alpha\n\n # Elevation angle\n h = np.cos(np.radians(delta)) * np.cos(np.radians(tau)) * np.cos(np.radians(latitude))\n h += np.sin(np.radians(delta)) * np.sin(np.radians(latitude))\n h = np.degrees(np.arcsin(h))\n\n return (h if h > 0 else 0)", "_____no_output_____" ] ], [ [ "## Energy data", "_____no_output_____" ] ], [ [ "for location, _ in locations.items():\n # This list contains all time points for which energy measurements exist, therefore delimiting\n # the time frame that is to our interest.\n energy = {}\n\n data_path = os.path.join(data_root, location)\n for filename in os.listdir(data_path):\n with open(os.path.join(data_path, filename), \"r\") as file:\n for line in file:\n key = datetime.strptime(line.split(\";\")[0], '%Y-%m-%d %H:%M:%S').timestamp()\n energy[key] = int(line.split(\";\")[1].strip())\n\n df = pd.DataFrame(\n data={\"time\": energy.keys(), \"energy\": energy.values()},\n columns=[\"time\", \"energy\"]\n )\n dfs[location] = df.sort_values(by=\"time\", ascending=True)", "_____no_output_____" ], [ "# Summarize energy data per hour instead of keeping it per 15 minutes\n\nfor location, _ in locations.items():\n times = []\n energy = []\n\n df = dfs[location]\n for i, row in dfs[location].iterrows():\n if row[\"time\"] % 3600 == 0:\n try:\n t4 = row[\"time\"]\n e4 = row[\"energy\"]\n e3 = df[\"energy\"][df[\"time\"] == t4 - 900].values[0]\n e2 = df[\"energy\"][df[\"time\"] == t4 - 1800].values[0]\n e1 = df[\"energy\"][df[\"time\"] == t4 - 2700].values[0]\n\n times += [t4]\n energy += [e1 + e2 + e3 + e4]\n except:\n pass\n\n df = pd.DataFrame(data={\"time\": times, \"energy_h\": energy}, columns=[\"time\", \"energy_h\"])\n df = df.sort_values(by=\"time\", ascending=True)\n dfs[location] = dfs[location].join(df.set_index(\"time\"), on=\"time\", how=\"right\").drop(\"energy\", axis=1)\n dfs[location].rename(columns={\"energy_h\": \"energy\"}, inplace=True)", "_____no_output_____" ], [ "# These lists contain the time tuples that delimit connected ranges without interruptions.\ntime_delimiters = {}\n\nfor location, _ in locations.items():\n delimiters = []\n df = dfs[location]\n\n next_couple = [df[\"time\"].iloc[0], None]\n interval = df[\"time\"].iloc[1] - df[\"time\"].iloc[0]\n for i in range(len(df[\"time\"].index) - 1):\n if df[\"time\"].iloc[i+1] - df[\"time\"].iloc[i] > interval:\n next_couple[1] = df[\"time\"].iloc[i]\n delimiters += [next_couple]\n next_couple = [df[\"time\"].iloc[i+1], None]\n next_couple[1] = df[\"time\"].iloc[-1]\n delimiters += [next_couple]\n\n time_delimiters[location] = delimiters", "_____no_output_____" ], [ "# This are lists of dataframes containing connected ranges without interruptions.\n\ndataframes_wijchen = []\nfor x in time_delimiters[\"wijchen\"]:\n dataframes_wijchen += [dfs[\"wijchen\"].loc[(dfs[\"wijchen\"].time >= x[0]) & (dfs[\"wijchen\"].time <= x[1])]]\n\ndataframes_berlin = []\nfor x in time_delimiters[\"berlin\"]:\n dataframes_berlin += [dfs[\"berlin\"].loc[(dfs[\"berlin\"].time >= x[0]) & (dfs[\"berlin\"].time <= x[1])]]", "_____no_output_____" ], [ "for location, _ in locations.items():\n print(location, \":\")\n for delimiters in time_delimiters[location]:\n t0 = datetime.fromtimestamp(delimiters[0])\n t1 = datetime.fromtimestamp(delimiters[1])\n print(t0, \"-\", t1)\n print()", "_____no_output_____" ] ], [ [ "### Wijchen dataset", "_____no_output_____" ] ], [ [ "for d in dataframes_wijchen:\n print(len(d))", "_____no_output_____" ], [ "plt.figure(figsize=(200, 25))\nplt.plot(dfs[\"wijchen\"][\"time\"], dfs[\"wijchen\"][\"energy\"], drawstyle=\"steps-pre\")", "_____no_output_____" ], [ "energy_max_wijchen = dfs[\"wijchen\"][\"energy\"].max()\nenergy_max_wijchen_idx = dfs[\"wijchen\"][\"energy\"].argmax()\nenergy_max_wijchen_time = datetime.fromtimestamp(dfs[\"wijchen\"][\"time\"].iloc[energy_max_wijchen_idx])\n\nprint(energy_max_wijchen_time, \":\", energy_max_wijchen)", "_____no_output_____" ], [ "energy_avg_wijchen = dfs[\"wijchen\"][\"energy\"].mean()\nprint(energy_avg_wijchen)", "_____no_output_____" ] ], [ [ "### Berlin dataset", "_____no_output_____" ] ], [ [ "for d in dataframes_berlin:\n print(len(d))", "_____no_output_____" ], [ "plt.figure(figsize=(200, 25))\nplt.plot(dfs[\"berlin\"][\"time\"], dfs[\"berlin\"][\"energy\"], drawstyle=\"steps-pre\")", "_____no_output_____" ], [ "energy_max_berlin = dfs[\"berlin\"][\"energy\"].max()\nenergy_max_berlin_idx = dfs[\"berlin\"][\"energy\"].argmax()\nenergy_max_berlin_time = datetime.fromtimestamp(dfs[\"berlin\"][\"time\"].iloc[energy_max_berlin_idx])\n\nprint(energy_max_berlin_time, \":\", energy_max_berlin)", "_____no_output_____" ], [ "energy_avg_berlin = dfs[\"berlin\"][\"energy\"].mean()\nprint(energy_avg_berlin)", "_____no_output_____" ] ], [ [ "## Sunlight angles", "_____no_output_____" ] ], [ [ "for location, lonlat in locations.items():\n angles = [\n get_angle(\n datetime.fromtimestamp(x - 3600), float(lonlat[0]), float(lonlat[1])\n ) for x in dfs[location][\"time\"]\n ]\n dfs[location][\"angles\"] = angles", "_____no_output_____" ] ], [ [ "## Weather data", "_____no_output_____" ] ], [ [ "# Contact the author for a sample of data, see doc/thesis.pdf, page 72.\nweather_data = np.load(os.path.join(data_root, \"weather.npy\"), allow_pickle=True).item()", "_____no_output_____" ], [ "# There is no cloud cover data for berlin2, so use the data of berlin1.\nweather_data[\"berlin2\"][\"cloud\"] = weather_data[\"berlin1\"][\"cloud\"]", "_____no_output_____" ], [ "# There is no radiation data for berlin1, so use the data of berlin2.\nweather_data[\"berlin1\"][\"rad\"] = weather_data[\"berlin2\"][\"rad\"]", "_____no_output_____" ], [ "# Preprocess weather data\nweather_params = [ \"temp\", \"humid\", \"press\", \"cloud\", \"rad\" ]\nstations = [ \"wijchen1\", \"wijchen2\", \"berlin1\", \"berlin2\" ]\n\nfor station in stations:\n for param in weather_params:\n to_del = []\n for key, val in weather_data[station][param].items():\n if val is None:\n to_del.append(key)\n for x in to_del:\n del weather_data[station][param][x]", "_____no_output_____" ], [ "def interpolate_map(map, time_range):\n ret = {\n \"time\": [],\n \"value\": []\n }\n keys = list(map.keys())\n values = list(map.values())\n f = interpolate.interp1d(keys, values)\n ret[\"time\"] = time_range\n ret[\"value\"] = f(ret[\"time\"])\n return ret", "_____no_output_____" ], [ "def update_df(df, time_range, map1, map2, param1, param2):\n map1_ = interpolate_map(map1, time_range)\n df1 = pd.DataFrame(\n data={\"time\": map1_[\"time\"], param1: map1_[\"value\"]},\n columns=[\"time\", param1]\n )\n\n map2_ = interpolate_map(map2, time_range)\n df2 = pd.DataFrame(\n data={\"time\": map2_[\"time\"], param2: map2_[\"value\"]},\n columns=[\"time\", param2]\n )\n\n df_ = df.join(df1.set_index(\"time\"), on=\"time\").join(df2.set_index(\"time\"), on=\"time\")\n return df_", "_____no_output_____" ], [ "# Insert weather data into dataframes\nfor location, _ in locations.items():\n df = dfs[location]\n station1 = location + \"1\"\n station2 = location + \"2\"\n\n for param in weather_params:\n param1 = param + \"1\"\n param2 = param + \"2\"\n df = update_df(\n df, df[\"time\"], weather_data[station1][param], weather_data[station2][param], param1, param2\n )\n\n dfs[location] = df.set_index(keys=[\"time\"], drop=False)", "_____no_output_____" ], [ "# These are lists of dataframes containing connected ranges without interruptions.\n\ndataframes_wijchen = []\nfor x in time_delimiters[\"wijchen\"]:\n dataframes_wijchen += [dfs[\"wijchen\"].loc[(dfs[\"wijchen\"].time >= x[0]) & (dfs[\"wijchen\"].time <= x[1])]]\n\ndataframes_berlin = []\nfor x in time_delimiters[\"berlin\"]:\n dataframes_berlin += [dfs[\"berlin\"].loc[(dfs[\"berlin\"].time >= x[0]) & (dfs[\"berlin\"].time <= x[1])]]", "_____no_output_____" ] ], [ [ "### Linear regression model", "_____no_output_____" ], [ "#### Wijchen", "_____no_output_____" ] ], [ [ "df_train = dataframes_wijchen[9].iloc[17:258]\n# df_train = dataframes_wijchen[9].iloc[17:234]\n# df_train = pd.concat([dataframes_wijchen[9].iloc[17:], dataframes_wijchen[10], dataframes_wijchen[11]])\n\ndf_val = dataframes_wijchen[-3].iloc[:241]\n# df_val = dataframes_wijchen[-2].iloc[:241]", "_____no_output_____" ], [ "lr_x1 = df_train[[\"angles\", \"temp1\", \"humid1\", \"press1\", \"cloud1\", \"rad1\"]].to_numpy()\nlr_y1 = df_train[[\"energy\"]].to_numpy()\n\nlr_model1 = LinearRegression()\nlr_model1.fit(lr_x1, lr_y1)\nlr_model1.score(lr_x1, lr_y1)", "_____no_output_____" ], [ "lr_x2 = df_train[[\"angles\", \"temp2\", \"humid2\", \"press2\", \"cloud2\", \"rad2\"]].to_numpy()\nlr_y2 = df_train[[\"energy\"]].to_numpy()\n\nlr_model2 = LinearRegression()\nlr_model2.fit(lr_x2, lr_y2)\nlr_model2.score(lr_x2, lr_y2)", "_____no_output_____" ], [ "lr_x3 = df_train[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\nlr_y3 = df_train[[\"energy\"]].to_numpy()\n\nlr_model3 = LinearRegression()\nlr_model3.fit(lr_x3, lr_y3)\nlr_model3.score(lr_x3, lr_y3)", "_____no_output_____" ], [ "# filename = \"lr_model.pkl\"\n# with open(filename, 'wb') as file:\n# pickle.dump(lr_model3, file)", "_____no_output_____" ], [ "xticks = df_train[\"time\"].iloc[::24]\n\nlr_x3 = df_train[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\n\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 5))\n\nax.set_xticks(ticks=xticks)\nax.set_xticklabels(labels=[datetime.fromtimestamp(x).strftime(\"%d-%m-%y\") for x in xticks])\nax.tick_params(labelsize=18)\nax.plot(df_train[\"time\"], df_train[\"energy\"], label=\"Actual energy production in Wh\", drawstyle=\"steps-pre\")\nax.plot(df_train[\"time\"], lr_model3.predict(lr_x3), label=\"Predicted energy production in Wh (Volkel + Deelen)\", drawstyle=\"steps-pre\")\nax.legend(prop={'size': 18})", "_____no_output_____" ], [ "xticks = df_val[\"time\"].iloc[::24]\n\nlr_x1 = df_val[[\"angles\", \"temp1\", \"humid1\", \"press1\", \"cloud1\", \"rad1\"]].to_numpy()\nlr_x2 = df_val[[\"angles\", \"temp2\", \"humid2\", \"press2\", \"cloud2\", \"rad2\"]].to_numpy()\nlr_x3 = df_val[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\n\nprint(lr_model1.score(lr_x1, df_val[[\"energy\"]].to_numpy()))\nprint(lr_model2.score(lr_x2, df_val[[\"energy\"]].to_numpy())) \nprint(lr_model3.score(lr_x3, df_val[[\"energy\"]].to_numpy()))\n\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 5))\n\nax.set_xticks(ticks=xticks)\nax.set_xticklabels(labels=[datetime.fromtimestamp(x).strftime(\"%d-%m-%y\") for x in xticks])\nax.tick_params(labelsize=18)\nax.plot(df_val[\"time\"], df_val[\"energy\"], label=\"Actual energy production in Wh\", drawstyle=\"steps-pre\")\nax.plot(df_val[\"time\"], lr_model3.predict(lr_x3), label=\"Predicted energy production in Wh (Volkel + Deelen)\", drawstyle=\"steps-pre\")\nax.legend(prop={'size': 18})", "_____no_output_____" ], [ "print(df[\"angles\"].min(), df_val[\"angles\"].max())\nprint(df[\"angles\"].min(), df_train[\"angles\"].max())", "_____no_output_____" ] ], [ [ "#### Berlin", "_____no_output_____" ] ], [ [ "df_train = dataframes_berlin[1].iloc[:241]\n# df_train = dataframes_berlin[1].iloc[:720]\n\ndf_val = dataframes_berlin[1].iloc[312:553]\n# df_val = dataframes_berlin[1].iloc[720:961]", "_____no_output_____" ], [ "lr_x1 = df_train[[\"angles\", \"temp1\", \"humid1\", \"press1\", \"cloud1\", \"rad1\"]].to_numpy()\nlr_y1 = df_train[[\"energy\"]].to_numpy()\n\nlr_model1 = LinearRegression()\nlr_model1.fit(lr_x1, lr_y1)\nlr_model1.score(lr_x1, lr_y1)", "_____no_output_____" ], [ "lr_x2 = df_train[[\"angles\", \"temp2\", \"humid2\", \"press2\", \"cloud2\", \"rad2\"]].to_numpy()\nlr_y2 = df_train[[\"energy\"]].to_numpy()\n\nlr_model2 = LinearRegression()\nlr_model2.fit(lr_x2, lr_y2)\nlr_model2.score(lr_x2, lr_y2)", "_____no_output_____" ], [ "lr_x3 = df_train[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\nlr_y3 = df_train[[\"energy\"]].to_numpy()\n\nlr_model3 = LinearRegression()\nlr_model3.fit(lr_x3, lr_y3)\nlr_model3.score(lr_x3, lr_y3)", "_____no_output_____" ], [ "# filename = \"lr_model.pkl\"\n# with open(filename, 'wb') as file:\n# pickle.dump(lr_model3, file)", "_____no_output_____" ], [ "xticks = df_train[\"time\"].iloc[::24]\n\nlr_x3 = df_train[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\n\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 5))\n\nax.set_xticks(ticks=xticks)\nax.set_xticklabels(labels=[datetime.fromtimestamp(x).strftime(\"%d-%m-%y\") for x in xticks])\nax.tick_params(labelsize=18)\nax.plot(df_train[\"time\"], df_train[\"energy\"], label=\"Actual energy production in Wh\", drawstyle=\"steps-pre\")\nax.plot(df_train[\"time\"], lr_model3.predict(lr_x3), label=\"Predicted energy production in Wh\", drawstyle=\"steps-pre\")\nax.legend(prop={'size': 18})", "_____no_output_____" ], [ "xticks = df_val[\"time\"].iloc[::24]\n\nlr_x1 = df_val[[\"angles\", \"temp1\", \"humid1\", \"press1\", \"cloud1\", \"rad1\"]].to_numpy()\nlr_x2 = df_val[[\"angles\", \"temp2\", \"humid2\", \"press2\", \"cloud2\", \"rad2\"]].to_numpy()\nlr_x3 = df_val[[\"angles\", \"temp1\", \"temp2\", \"humid1\", \"humid2\", \"press1\", \"press2\", \"cloud1\", \"cloud2\", \"rad1\", \"rad2\"]].to_numpy()\n\nprint(lr_model1.score(lr_x1, df_val[[\"energy\"]].to_numpy()))\nprint(lr_model2.score(lr_x2, df_val[[\"energy\"]].to_numpy()))\nprint(lr_model3.score(lr_x3, df_val[[\"energy\"]].to_numpy()))\n\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 5))\n\nax.set_xticks(ticks=xticks)\nax.set_xticklabels(labels=[datetime.fromtimestamp(x).strftime(\"%d-%m-%y\") for x in xticks])\nax.tick_params(labelsize=18)\nax.plot(df_val[\"time\"], df_val[\"energy\"], label=\"Actual energy production in Wh\", drawstyle=\"steps-pre\")\nax.plot(df_val[\"time\"], lr_model3.predict(lr_x3), label=\"Predicted energy production in Wh\", drawstyle=\"steps-pre\")\nax.legend(prop={'size': 18})", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cbe52fb32ef76c67ef2a5a41bb4c4222664417f6
455,130
ipynb
Jupyter Notebook
dmu1/dmu1_ml_GAMA-09/4_Selection_function.ipynb
djbsmith/dmu_products
4a6e1496a759782057c87ab5a65763282f61c497
[ "MIT" ]
null
null
null
dmu1/dmu1_ml_GAMA-09/4_Selection_function.ipynb
djbsmith/dmu_products
4a6e1496a759782057c87ab5a65763282f61c497
[ "MIT" ]
null
null
null
dmu1/dmu1_ml_GAMA-09/4_Selection_function.ipynb
djbsmith/dmu_products
4a6e1496a759782057c87ab5a65763282f61c497
[ "MIT" ]
null
null
null
506.826281
154,684
0.906974
[ [ [ "# GAMA-09 Selection Functions\n## Depth maps and selection functions\n\nThe simplest selection function available is the field MOC which specifies the area for which there is Herschel data. Each pristine catalogue also has a MOC defining the area for which that data is available.\n\nThe next stage is to provide mean flux standard deviations which act as a proxy for the catalogue's 5$\\sigma$ depth", "_____no_output_____" ] ], [ [ "from herschelhelp_internal import git_version\nprint(\"This notebook was run with herschelhelp_internal version: \\n{}\".format(git_version()))\nimport datetime\nprint(\"This notebook was executed on: \\n{}\".format(datetime.datetime.now()))", "This notebook was run with herschelhelp_internal version: \n0246c5d (Thu Jan 25 17:01:47 2018 +0000) [with local modifications]\nThis notebook was executed on: \n2018-02-27 20:57:03.107730\n" ], [ "%matplotlib inline\n#%config InlineBackend.figure_format = 'svg'\n\nimport matplotlib.pyplot as plt\nplt.rc('figure', figsize=(10, 6))\n\nimport os\nimport time\n\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.table import Column, Table, join\nimport numpy as np\nfrom pymoc import MOC\nimport healpy as hp\n#import pandas as pd #Astropy has group_by function so apandas isn't required.\nimport seaborn as sns\n\nimport warnings\n#We ignore warnings - this is a little dangerous but a huge number of warnings are generated by empty cells later\nwarnings.filterwarnings('ignore')\n\nfrom herschelhelp_internal.utils import inMoc, coords_to_hpidx, flux_to_mag\nfrom herschelhelp_internal.masterlist import find_last_ml_suffix, nb_ccplots\n\nfrom astropy.io.votable import parse_single_table", "_____no_output_____" ], [ "FIELD = 'GAMA-09'\n#FILTERS_DIR = \"/Users/rs548/GitHub/herschelhelp_python/database_builder/filters/\"\nFILTERS_DIR = \"/opt/herschelhelp_python/database_builder/filters/\"", "_____no_output_____" ], [ "TMP_DIR = os.environ.get('TMP_DIR', \"./data_tmp\")\nOUT_DIR = os.environ.get('OUT_DIR', \"./data\")\nSUFFIX = find_last_ml_suffix()\n#SUFFIX = \"20171016\"\n\nmaster_catalogue_filename = \"master_catalogue_{}_{}.fits\".format(FIELD.lower(), SUFFIX)\nmaster_catalogue = Table.read(\"{}/{}\".format(OUT_DIR, master_catalogue_filename))\n\nprint(\"Depth maps produced using: {}\".format(master_catalogue_filename))\n\nORDER = 10\n#TODO write code to decide on appropriate order\n\nfield_moc = MOC(filename=\"../../dmu2/dmu2_field_coverages/{}_MOC.fits\".format(FIELD))", "Depth maps produced using: master_catalogue_gama-09_20171206.fits\n" ] ], [ [ "## I - Group masterlist objects by healpix cell and calculate depths\nWe add a column to the masterlist catalogue for the target order healpix cell <i>per object</i>.", "_____no_output_____" ] ], [ [ "#Add a column to the catalogue with the order=ORDER hp_idx\nmaster_catalogue.add_column(Column(data=coords_to_hpidx(master_catalogue['ra'],\n master_catalogue['dec'],\n ORDER), \n name=\"hp_idx_O_{}\".format(str(ORDER))\n )\n )", "_____no_output_____" ], [ "# Convert catalogue to pandas and group by the order=ORDER pixel\n\ngroup = master_catalogue.group_by([\"hp_idx_O_{}\".format(str(ORDER))])", "_____no_output_____" ], [ "#Downgrade the groups from order=ORDER to order=13 and then fill out the appropriate cells\n#hp.pixelfunc.ud_grade([2599293, 2599294], nside_out=hp.order2nside(13))", "_____no_output_____" ] ], [ [ "## II Create a table of all Order=13 healpix cells in the field and populate it\nWe create a table with every order=13 healpix cell in the field MOC. We then calculate the healpix cell at lower order that the order=13 cell is in. We then fill in the depth at every order=13 cell as calculated for the lower order cell that that the order=13 cell is inside.", "_____no_output_____" ] ], [ [ "depths = Table()\ndepths['hp_idx_O_13'] = list(field_moc.flattened(13))", "_____no_output_____" ], [ "depths[:10].show_in_notebook()", "_____no_output_____" ], [ "depths.add_column(Column(data=hp.pixelfunc.ang2pix(2**ORDER,\n hp.pixelfunc.pix2ang(2**13, depths['hp_idx_O_13'], nest=True)[0],\n hp.pixelfunc.pix2ang(2**13, depths['hp_idx_O_13'], nest=True)[1],\n nest = True),\n name=\"hp_idx_O_{}\".format(str(ORDER))\n )\n )", "_____no_output_____" ], [ "depths[:10].show_in_notebook()", "_____no_output_____" ], [ "for col in master_catalogue.colnames:\n if col.startswith(\"f_\"):\n errcol = \"ferr{}\".format(col[1:])\n depths = join(depths, \n group[\"hp_idx_O_{}\".format(str(ORDER)), errcol].groups.aggregate(np.nanmean),\n join_type='left')\n depths[errcol].name = errcol + \"_mean\"\n depths = join(depths, \n group[\"hp_idx_O_{}\".format(str(ORDER)), col].groups.aggregate(lambda x: np.nanpercentile(x, 90.)),\n join_type='left')\n depths[col].name = col + \"_p90\"\n\ndepths[:10].show_in_notebook()", "_____no_output_____" ] ], [ [ "## III - Save the depth map table", "_____no_output_____" ] ], [ [ "depths.write(\"{}/depths_{}_{}.fits\".format(OUT_DIR, FIELD.lower(), SUFFIX))", "_____no_output_____" ] ], [ [ "## IV - Overview plots\n\n### IV.a - Filters\nFirst we simply plot all the filters available on this field to give an overview of coverage.", "_____no_output_____" ] ], [ [ "tot_bands = [column[2:] for column in master_catalogue.colnames \n if (column.startswith('f_') & ~column.startswith('f_ap_'))]\nap_bands = [column[5:] for column in master_catalogue.colnames \n if column.startswith('f_ap_') ]\nbands = set(tot_bands) | set(ap_bands)\nbands", "_____no_output_____" ], [ "for b in bands:\n plt.plot(Table(data = parse_single_table(FILTERS_DIR + b + '.xml').array.data)['Wavelength']\n ,Table(data = parse_single_table(FILTERS_DIR + b + '.xml').array.data)['Transmission']\n , label=b)\nplt.xlabel('Wavelength ($\\AA$)')\nplt.ylabel('Transmission')\nplt.xscale('log')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.title('Passbands on {}'.format(FIELD))", "_____no_output_____" ] ], [ [ "### IV.a - Depth overview\nThen we plot the mean depths available across the area a given band is available", "_____no_output_____" ] ], [ [ "average_depths = []\nfor b in ap_bands:\n \n mean_err = np.nanmean(depths['ferr_ap_{}_mean'.format(b)])\n print(\"{}: mean flux error: {}, 3sigma in AB mag (Aperture): {}\".format(b, mean_err, flux_to_mag(3.0*mean_err*1.e-6)[0]))\n average_depths += [('ap_' + b, flux_to_mag(1.0*mean_err*1.e-6)[0], \n flux_to_mag(3.0*mean_err*1.e-6)[0], \n flux_to_mag(5.0*mean_err*1.e-6)[0])]\n \nfor b in tot_bands:\n \n mean_err = np.nanmean(depths['ferr_{}_mean'.format(b)])\n print(\"{}: mean flux error: {}, 3sigma in AB mag (Total): {}\".format(b, mean_err, flux_to_mag(3.0*mean_err*1.e-6)[0]))\n average_depths += [(b, flux_to_mag(1.0*mean_err*1.e-6)[0], \n flux_to_mag(3.0*mean_err*1.e-6)[0], \n flux_to_mag(5.0*mean_err*1.e-6)[0])]\n \naverage_depths = np.array(average_depths, dtype=[('band', \"<U16\"), ('1s', float), ('3s', float), ('5s', float)])\n ", "megacam_u: mean flux error: 0.06001316383481026, 3sigma in AB mag (Aperture): 25.761580555834833\nmegacam_g: mean flux error: 0.04263300448656082, 3sigma in AB mag (Aperture): 26.132832013523235\nmegacam_r: mean flux error: 0.07640354335308075, 3sigma in AB mag (Aperture): 25.49941311260566\nmegacam_i: mean flux error: 0.11145462840795517, 3sigma in AB mag (Aperture): 25.089451592548777\nmegacam_z: mean flux error: 0.24109889566898346, 3sigma in AB mag (Aperture): 24.251708810359297\ndecam_g: mean flux error: 2.755250534391962e-07, 3sigma in AB mag (Aperture): 39.10679412496186\ndecam_r: mean flux error: 4.143452372318279e-07, 3sigma in AB mag (Aperture): 38.66379098537599\ndecam_z: mean flux error: 9.148930644187203e-07, 3sigma in AB mag (Aperture): 37.80377102488412\nsuprime_g: mean flux error: inf, 3sigma in AB mag (Aperture): -inf\nsuprime_r: mean flux error: inf, 3sigma in AB mag (Aperture): -inf\nsuprime_i: mean flux error: 0.04259403422474861, 3sigma in AB mag (Aperture): 26.133824924405666\nsuprime_z: mean flux error: 0.06838009506464005, 3sigma in AB mag (Aperture): 25.619872612616085\nsuprime_y: mean flux error: 0.13980890810489655, 3sigma in AB mag (Aperture): 24.843359753390082\nomegacam_u: mean flux error: 0.23172791302204132, 3sigma in AB mag (Aperture): 24.29475098738684\nomegacam_g: mean flux error: 0.09827630966901779, 3sigma in AB mag (Aperture): 25.226074762923524\nomegacam_r: mean flux error: 0.10228602588176727, 3sigma in AB mag (Aperture): 25.182656099960973\nomegacam_i: mean flux error: 0.35833290219306946, 3sigma in AB mag (Aperture): 23.821480145710133\ngpc1_g: mean flux error: 29.589131192044412, 3sigma in AB mag (Aperture): 19.029366329653804\ngpc1_r: mean flux error: 9.615837262844897, 3sigma in AB mag (Aperture): 20.249729101254296\ngpc1_i: mean flux error: 120.43076068463053, 3sigma in AB mag (Aperture): 17.505353289390264\ngpc1_z: mean flux error: 128.73286659960064, 3sigma in AB mag (Aperture): 17.432973262828362\ngpc1_y: mean flux error: 46.23208883404382, 3sigma in AB mag (Aperture): 18.544838073332393\nukidss_y: mean flux error: 3.805072069168091, 3sigma in AB mag (Aperture): 21.256289646081136\nukidss_j: mean flux error: 4.7073259353637695, 3sigma in AB mag (Aperture): 21.025261188430044\nukidss_h: mean flux error: 5.433945655822754, 3sigma in AB mag (Aperture): 20.869408636247137\nukidss_k: mean flux error: 6.127557277679443, 3sigma in AB mag (Aperture): 20.73897841436409\nvista_z: mean flux error: 0.6562223434448242, 3sigma in AB mag (Aperture): 23.164569329660672\nvista_y: mean flux error: 1.5562821689480606, 3sigma in AB mag (Aperture): 22.226976009286467\nvista_j: mean flux error: 2.1356934335230027, 3sigma in AB mag (Aperture): 21.883349582296184\nvista_h: mean flux error: 3.1928191120449823, 3sigma in AB mag (Aperture): 21.446761077082435\nvista_ks: mean flux error: 3.644612961559255, 3sigma in AB mag (Aperture): 21.30306832483324\nmegacam_u: mean flux error: 0.07429558166859748, 3sigma in AB mag (Total): 25.52978939521943\nmegacam_g: mean flux error: 0.058633667782351004, 3sigma in AB mag (Total): 25.786829208251653\nmegacam_r: mean flux error: 0.10418303108069382, 3sigma in AB mag (Total): 25.16270439180321\nmegacam_i: mean flux error: 0.14648311624732832, 3sigma in AB mag (Total): 24.792727937024644\nmegacam_z: mean flux error: 0.3099865676724861, 3sigma in AB mag (Total): 23.978839674680536\ndecam_g: mean flux error: 20439098.0, 3sigma in AB mag (Total): 4.431042548226436\ndecam_r: mean flux error: 11573.4365234375, 3sigma in AB mag (Total): 12.548541028145607\ndecam_z: mean flux error: 33975.48046875, 3sigma in AB mag (Total): 11.379282845498828\nsuprime_g: mean flux error: inf, 3sigma in AB mag (Total): -inf\nsuprime_r: mean flux error: inf, 3sigma in AB mag (Total): -inf\nsuprime_i: mean flux error: inf, 3sigma in AB mag (Total): -inf\nsuprime_z: mean flux error: inf, 3sigma in AB mag (Total): -inf\nsuprime_y: mean flux error: 0.26284706592559814, 3sigma in AB mag (Total): 24.157939029459335\nomegacam_u: mean flux error: 0.2946048974990845, 3sigma in AB mag (Total): 24.034096957552542\nomegacam_g: mean flux error: 0.1202227920293808, 3sigma in AB mag (Total): 25.007229838912373\nomegacam_r: mean flux error: 0.12768588960170746, 3sigma in AB mag (Total): 24.941839596681028\nomegacam_i: mean flux error: 0.47057148814201355, 3sigma in AB mag (Total): 23.52563283870662\ngpc1_g: mean flux error: 47.38078680646244, 3sigma in AB mag (Total): 18.51819119232328\ngpc1_r: mean flux error: 11.63194498616533, 3sigma in AB mag (Total): 20.043066014442097\ngpc1_i: mean flux error: 75.45866666827068, 3sigma in AB mag (Total): 18.01292404549799\ngpc1_z: mean flux error: 106.25462729974325, 3sigma in AB mag (Total): 17.641327232465905\ngpc1_y: mean flux error: 41.98654094162309, 3sigma in AB mag (Total): 18.64942162122646\nukidss_y: mean flux error: 6.0485992431640625, 3sigma in AB mag (Total): 20.753059836239025\nukidss_j: mean flux error: 6.344705104827881, 3sigma in AB mag (Total): 20.70116825981996\nukidss_h: mean flux error: 9.80788516998291, 3sigma in AB mag (Total): 20.2282584319123\nukidss_k: mean flux error: 11.196520805358887, 3sigma in AB mag (Total): 20.084489134599558\nvista_z: mean flux error: 1.3729348182678223, 3sigma in AB mag (Total): 22.363072065517862\nvista_y: mean flux error: 3.0272901248787965, 3sigma in AB mag (Total): 21.504561752669296\nvista_j: mean flux error: 4.565136318476364, 3sigma in AB mag (Total): 21.0585624871241\nvista_h: mean flux error: 7.1035819264453375, 3sigma in AB mag (Total): 20.5785033792125\nvista_ks: mean flux error: 8.312054826216114, 3sigma in AB mag (Total): 20.407925865301145\n" ], [ "def FWHM(X,Y):\n \n half_max = max(Y) / 2.\n #find when function crosses line half_max (when sign of diff flips)\n #take the 'derivative' of signum(half_max - Y[])\n d = half_max - Y\n #plot(X,d) #if you are interested\n #find the left and right most indexes\n low_end = X[np.where(d < 0)[0][0]]\n high_end = X[np.where(d < 0)[0][-1]]\n return low_end, high_end, (high_end - low_end)\n", "_____no_output_____" ], [ "data = []\n\nfor b in ap_bands:\n data += [['ap_' + b, Table(data = parse_single_table(FILTERS_DIR + b +'.xml').array.data)]]\n \nfor b in tot_bands:\n data += [[b, Table(data = parse_single_table(FILTERS_DIR + b +'.xml').array.data)]]", "_____no_output_____" ], [ "wav_range = []\nfor dat in data:\n print(dat[0], FWHM(np.array(dat[1]['Wavelength']), np.array(dat[1]['Transmission'])))\n wav_range += [[dat[0], FWHM(np.array(dat[1]['Wavelength']), np.array(dat[1]['Transmission']))]]\n", "ap_megacam_u (3500.0, 4100.0, 600.0)\nap_megacam_g (4180.0, 5580.0, 1400.0)\nap_megacam_r (5680.0, 6880.0, 1200.0)\nap_megacam_i (6831.7305, 8388.5557, 1556.8252)\nap_megacam_z (8280.0, 9160.0, 880.0)\nap_decam_g (4180.0, 5470.0, 1290.0)\nap_decam_r (5680.0, 7150.0, 1470.0)\nap_decam_z (8490.0, 9960.0, 1470.0)\nap_suprime_g (4090.0, 5460.0, 1370.0)\nap_suprime_r (5440.0, 6960.0, 1520.0)\nap_suprime_i (6980.0, 8420.0, 1440.0)\nap_suprime_z (8540.0, 9280.0, 740.0)\nap_suprime_y (9360.0, 10120.0, 760.0)\nap_omegacam_u (3296.7, 3807.8999, 511.19995)\nap_omegacam_g (4077.8999, 5369.7002, 1291.8003)\nap_omegacam_r (5640.7002, 6962.7998, 1322.0996)\nap_omegacam_i (6841.5, 8373.7998, 1532.2998)\nap_gpc1_g (4260.0, 5500.0, 1240.0)\nap_gpc1_r (5500.0, 6900.0, 1400.0)\nap_gpc1_i (6910.0, 8190.0, 1280.0)\nap_gpc1_z (8190.0, 9210.0, 1020.0)\nap_gpc1_y (9200.0, 9820.0, 620.0)\nap_ukidss_y (9790.0, 10820.0, 1030.0)\nap_ukidss_j (11695.0, 13280.0, 1585.0)\nap_ukidss_h (14925.0, 17840.0, 2915.0)\nap_ukidss_k (20290.0, 23820.0, 3530.0)\nap_vista_z (8300.0, 9260.0, 960.0)\nap_vista_y (9740.0, 10660.0, 920.0)\nap_vista_j (11670.0, 13380.0, 1710.0)\nap_vista_h (15000.0, 17900.0, 2900.0)\nap_vista_ks (19930.0, 23010.0, 3080.0)\nmegacam_u (3500.0, 4100.0, 600.0)\nmegacam_g (4180.0, 5580.0, 1400.0)\nmegacam_r (5680.0, 6880.0, 1200.0)\nmegacam_i (6831.7305, 8388.5557, 1556.8252)\nmegacam_z (8280.0, 9160.0, 880.0)\ndecam_g (4180.0, 5470.0, 1290.0)\ndecam_r (5680.0, 7150.0, 1470.0)\ndecam_z (8490.0, 9960.0, 1470.0)\nsuprime_g (4090.0, 5460.0, 1370.0)\nsuprime_r (5440.0, 6960.0, 1520.0)\nsuprime_i (6980.0, 8420.0, 1440.0)\nsuprime_z (8540.0, 9280.0, 740.0)\nsuprime_y (9360.0, 10120.0, 760.0)\nomegacam_u (3296.7, 3807.8999, 511.19995)\nomegacam_g (4077.8999, 5369.7002, 1291.8003)\nomegacam_r (5640.7002, 6962.7998, 1322.0996)\nomegacam_i (6841.5, 8373.7998, 1532.2998)\ngpc1_g (4260.0, 5500.0, 1240.0)\ngpc1_r (5500.0, 6900.0, 1400.0)\ngpc1_i (6910.0, 8190.0, 1280.0)\ngpc1_z (8190.0, 9210.0, 1020.0)\ngpc1_y (9200.0, 9820.0, 620.0)\nukidss_y (9790.0, 10820.0, 1030.0)\nukidss_j (11695.0, 13280.0, 1585.0)\nukidss_h (14925.0, 17840.0, 2915.0)\nukidss_k (20290.0, 23820.0, 3530.0)\nvista_z (8300.0, 9260.0, 960.0)\nvista_y (9740.0, 10660.0, 920.0)\nvista_j (11670.0, 13380.0, 1710.0)\nvista_h (15000.0, 17900.0, 2900.0)\nvista_ks (19930.0, 23010.0, 3080.0)\n" ], [ "for dat in data:\n wav_deets = FWHM(np.array(dat[1]['Wavelength']), np.array(dat[1]['Transmission']))\n depth = average_depths['5s'][average_depths['band'] == dat[0]]\n #print(depth)\n plt.plot([wav_deets[0],wav_deets[1]], [depth,depth], label=dat[0])\n \nplt.xlabel('Wavelength ($\\AA$)')\nplt.ylabel('Depth')\nplt.xscale('log')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.title('Depths on {}'.format(FIELD))", "_____no_output_____" ] ], [ [ "### IV.c - Depth vs coverage comparison\n\nHow best to do this? Colour/intensity plot over area? Percentage coverage vs mean depth?", "_____no_output_____" ] ], [ [ "for dat in data:\n wav_deets = FWHM(np.array(dat[1]['Wavelength']), np.array(dat[1]['Transmission']))\n depth = average_depths['5s'][average_depths['band'] == dat[0]]\n #print(depth)\n coverage = np.sum(~np.isnan(depths['ferr_{}_mean'.format(dat[0])]))/len(depths)\n plt.plot(coverage, depth, 'x', label=dat[0])\n \nplt.xlabel('Coverage')\nplt.ylabel('Depth')\n#plt.xscale('log')\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nplt.title('Depths (5 $\\sigma$) vs coverage on {}'.format(FIELD))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cbe532e17e4f84049130d0520312c6ab5aba44dd
17,759
ipynb
Jupyter Notebook
Assignment2.ipynb
jereyel/LinearAlgebra
1280b98f316f433df3ce9ad3754690e93658eac8
[ "Apache-2.0" ]
null
null
null
Assignment2.ipynb
jereyel/LinearAlgebra
1280b98f316f433df3ce9ad3754690e93658eac8
[ "Apache-2.0" ]
null
null
null
Assignment2.ipynb
jereyel/LinearAlgebra
1280b98f316f433df3ce9ad3754690e93658eac8
[ "Apache-2.0" ]
null
null
null
21.268263
287
0.400755
[ [ [ "<a href=\"https://colab.research.google.com/github/jereyel/LinearAlgebra/blob/main/Assignment2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Welcome to Python Fundamentals\nIn this module, we are going to establish our skills in Python Programming. In this notebook we are going to cover:\n\n\n\n\n* Variables and Data Types\n* Operations\n* Input and Output Operations\n* Iterables\n* Functions\n\n", "_____no_output_____" ], [ "## Variables and Data Types", "_____no_output_____" ] ], [ [ "x = 1\na, b = 3, -2", "_____no_output_____" ], [ "type (x)", "_____no_output_____" ], [ "y = 3.0\ntype(y)", "_____no_output_____" ], [ "x = float(x)\ntype(x)", "_____no_output_____" ], [ "s, t, u = \"1\", '3', 'three'\ntype(s)", "_____no_output_____" ] ], [ [ "## Operations", "_____no_output_____" ], [ "### Arithmetic\n", "_____no_output_____" ] ], [ [ "w, x, y, z = 4.0, -3.0, 1, -32", "_____no_output_____" ], [ "### Addition\nS = w + x", "_____no_output_____" ], [ "### Subtractions\nD = y - z", "_____no_output_____" ], [ "### Multiplication\nP = w*z", "_____no_output_____" ], [ "### Division\nQ = y/x", "_____no_output_____" ], [ "### Floor Division\nQf = w//z\nQf", "_____no_output_____" ], [ "### Exponentiation\nE = w**w\nE", "_____no_output_____" ], [ "### Modulo\nmod = z%x\nmod", "_____no_output_____" ] ], [ [ "### Assignment\n", "_____no_output_____" ] ], [ [ "A, B, C, D, E = 0, 100, 2, 1, 2", "_____no_output_____" ], [ "A += w", "_____no_output_____" ], [ "B -= x", "_____no_output_____" ], [ "C *= w", "_____no_output_____" ], [ "D /= x\n", "_____no_output_____" ], [ "E **= y\nE", "_____no_output_____" ] ], [ [ "### Comparators", "_____no_output_____" ] ], [ [ "size_1, size_2, size_3 = 1, 2.0, \"1\"\ntrue_size = 1.0", "_____no_output_____" ], [ "## Equality\nsize_1 == true_size", "_____no_output_____" ], [ "## Non-Equality\nsize_2 != true_size", "_____no_output_____" ], [ "## Inequality\ns1 = size_1 > size_2\ns2 = size_1 < size_2/2\ns3 = true_size <= size_1\ns4 = size_2 <= true_size", "_____no_output_____" ] ], [ [ "### Logical", "_____no_output_____" ] ], [ [ "size_1 == true_size\nsize_1", "_____no_output_____" ], [ "size_1 is true_size", "_____no_output_____" ], [ "size_1 is not true_size", "_____no_output_____" ], [ "P, Q = True, False\nconj = P and Q", "_____no_output_____" ], [ "disj = P or Q\ndisj", "_____no_output_____" ], [ "nand = not (P and Q)\nnand", "_____no_output_____" ], [ "xor = (not P and Q) or (P and not Q)\nxor", "_____no_output_____" ] ], [ [ "## Input and Output", "_____no_output_____" ] ], [ [ "print(\"Helllo World!\")", "_____no_output_____" ], [ "cnt = 14000", "_____no_output_____" ], [ "string = \"Hello World!\"\nprint(string, \", Current COVID count is\", cnt)\ncnt += 10000", "_____no_output_____" ], [ "print(f\"{string}, current count is: {cnt}\")", "_____no_output_____" ], [ "sem_grade = 85.25\nname = \"jerbox\"\nprint(\"Hello {}, your semestral grade is: {}\".format(name, sem_grade))", "Hello jerbox, your semestral grade is: 85.25\n" ], [ "pg, mg, fg = 0.3, 0.3, 0.4\nprint(\"The weights of your semestral grade are:\\\n\\n\\t {:.2%} for Prelims\\\n\\n\\t {:.2%} for Midterms, and\\\n\\n\\t {:.2%} for Finals.\".format(pg, mg, fg))\n", "_____no_output_____" ], [ "e = input(\"Enter a number: \")", "_____no_output_____" ], [ "name = input(\"Enter your name: \");\npg = input(\"Enter prelim grade: \")\nmg = input(\"Enter midterm grade: \")\nfg = input(\"Enter final grade: \")\nsem_grade = None\nprint(\"Hello {}, your semestral grade is: {}\".format(name, sem_grade))", "_____no_output_____" ] ], [ [ "### Looping Statements", "_____no_output_____" ], [ "## While", "_____no_output_____" ] ], [ [ "i, j = 0, 10\nwhile(i<=j):\n print(f\"{i}\\t|\\t{j}\")\n i += 1", "_____no_output_____" ] ], [ [ "## For", "_____no_output_____" ] ], [ [ "i = 0\nfor i in range(11):\n print(i)", "_____no_output_____" ], [ "playlist = [\"Bahay Kubo\", \"Magandang Kanta\", \"Kubo\"]\nprint('Now Playing:\\n')\nfor song in playlist\nprint(song)", "_____no_output_____" ] ], [ [ "##Flow Control", "_____no_output_____" ], [ "###Condition Statements", "_____no_output_____" ] ], [ [ "num_1, num_2 = 14, 12\nif(num_1 == num_2):\n print(\"HAHA\")\nelif(num_1>num_2):\n else:\n print(\"HUHU\")", "_____no_output_____" ] ], [ [ "##Functions", "_____no_output_____" ] ], [ [ "# void Deleteuser (int userid){\n# delete(userid);\n# }\n\ndef delete_user (userid):\n print(\"Successfully deleted user: {}\".format(userid))", "_____no_output_____" ], [ "addend1, addend2 = 5, 6", "_____no_output_____" ], [ "def add(addend1, addend2):\n sum = addend1 + addend2\n return sum", "_____no_output_____" ], [ "add(5, 4)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cbe540704f7b76741ae8a786a5b7805bfd6e22bd
165,663
ipynb
Jupyter Notebook
quarter_of_vehicle_model_on_harmonic_road.ipynb
dgvallejo/exercises
8a938a1be3181fcee5a1ca042c4fa631c98d4819
[ "MIT" ]
1
2020-01-29T10:44:13.000Z
2020-01-29T10:44:13.000Z
quarter_of_vehicle_model_on_harmonic_road.ipynb
dgvallejo/exercises
8a938a1be3181fcee5a1ca042c4fa631c98d4819
[ "MIT" ]
null
null
null
quarter_of_vehicle_model_on_harmonic_road.ipynb
dgvallejo/exercises
8a938a1be3181fcee5a1ca042c4fa631c98d4819
[ "MIT" ]
1
2020-01-29T10:51:54.000Z
2020-01-29T10:51:54.000Z
1,227.133333
161,910
0.946319
[ [ [ "from matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\nx0 = 0.0\nx0p = 0.0\n\nm = 250.0\nc = 1250.0\nk = 25000.0\n\nY = 0.025\n\nv = 120.0*1000.0/3600.0 # en m/s\nlbd = 12.5 # wave length of road univeness\nw = 2*np.pi*v/lbd\n\nwn = np.sqrt(k/m)\nxi = c/(2*m*wn)\nwd = wn*np.sqrt(1-xi**2)\ntau = w/wn\n\nNP = 5000\nt = np.linspace(0,6,NP,endpoint = True)\nTr = np.sqrt(1 + (2*xi*t)**2)/np.sqrt((1-t**2)**2 + (2*xi*t)**2)\nNC = 20 # number of cicles to show\ntf = NC*2*np.pi/w\ntime = np.linspace(0,tf,NP,endpoint = True)\n\nplt.rcParams['figure.figsize'] = 15, 10\n\nplt.subplot(2,2,1)\nplt.plot(t,Tr)\nTr1 = np.sqrt(1 + (2*xi*tau)**2)/np.sqrt((1-tau**2)**2 + (2*xi*tau)**2)\nplt.plot([tau,tau,0],[0,Tr1,Tr1],':o')\nplt.ylabel(r'Magnitude of $Tr(\\omega)$')\nplt.xlabel(r'Non dimensional frequency, $\\tau=\\omega/\\omega_n$')\nplt.xlim((t.min(),t.max()))\nplt.ylim((0,1.2*Tr.max()))\nplt.grid(True)\nplt.subplot(2,2,2)\n\nalfa = np.arctan2(2*xi*tau*tau*tau,1-tau*tau + (2*xi*tau)**2)\n \nxP0 = Tr1*Y*np.sin(w*0-alfa)\nxP0p = Tr1*Y*w*np.cos(w*0-alfa)\nx = np.exp(-xi*wn*time)*(x0*np.cos(wd*time)+(x0p+xi*wn*x0)*np.sin(wd*time)/wd)-np.exp(-xi*wn*time)*(xP0*np.cos(wd*time)+(xP0p+xi*wn*xP0)*np.sin(wd*time)/wd)+Tr1*Y*np.sin(w*time-alfa)\n\nplt.plot(time,x,label='Displacement')\nplt.plot(time,Y*np.sin(w*time),label='Road univeness')\nplt.legend(loc='upper right')\nplt.ylabel(r'Time evolution of $x(t)$ (m)')\nplt.xlabel(r'Time (s)')\nplt.grid(True)\n\nplt.subplot(2,2,3)\nTr_phase = np.arctan2(2*xi*t*t*t,1-t*t + (2*xi*t)**2)\nplt.plot(t,Tr_phase)\nplt.plot([tau,tau,0],[0,alfa,alfa],':o')\nplt.grid(True)\nplt.ylabel(r'Phase of $Tr(\\omega)$')\nplt.xlabel(r'Non dimensional frequency, $\\tau=\\omega/\\omega_n$')\nplt.xlim((t.min(),t.max()))\nplt.ylim((0,1.2*Tr_phase.max()))\n\nax1 = plt.subplot(2,2,4)\nf = Y*np.sin(w*time)\nax1.plot(time,x,label='Displacement')\nplt.ylabel(r'Time evolution of $x(t)$ (m)')\nplt.xlabel(r'Time (s)')\nplt.legend(loc='lower left')\nplt.ylim((-Tr1*Y,Tr1*Y))\nax2 = ax1.twinx()\nax2.plot(time,f,'r',label='Road univeness')\nplt.xlim((tf-2*np.pi/w,tf))\nplt.grid(True)\nplt.legend(loc='upper right')\nplt.ylabel(r'Time evolution of $F(t)$ (N)')\nplt.ylim((-Y,Y));", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cbe5714f45f349ecebf89b342b100923ba507f3d
134,174
ipynb
Jupyter Notebook
_doc/notebooks/td2a_eco/TD2A_eco_API_SNCF_corrige.ipynb
mohamedelkansouli/Ensae_py
8bc867bd2081c259c793fadfa8be5dcc7bd1400b
[ "MIT" ]
null
null
null
_doc/notebooks/td2a_eco/TD2A_eco_API_SNCF_corrige.ipynb
mohamedelkansouli/Ensae_py
8bc867bd2081c259c793fadfa8be5dcc7bd1400b
[ "MIT" ]
null
null
null
_doc/notebooks/td2a_eco/TD2A_eco_API_SNCF_corrige.ipynb
mohamedelkansouli/Ensae_py
8bc867bd2081c259c793fadfa8be5dcc7bd1400b
[ "MIT" ]
null
null
null
78.6483
42,450
0.710413
[ [ [ "# 2A.eco - Exercice API SNCF corrigé\n\nManipulation d'une [API REST](https://fr.wikipedia.org/wiki/Representational_state_transfer), celle de la SNCF est prise comme exemple. Correction d'exercices.", "_____no_output_____" ] ], [ [ "from jyquickhelper import add_notebook_menu\nadd_notebook_menu()", "_____no_output_____" ] ], [ [ "## Partie 0 - modules recommandés et connexion à l'API \n\nIl vous faudra sûrement les modules suivant : \n\n- requests\n- datetime\n- pandas\n- matplotlib\n\nCréer un login pour vous connecter à l'API de la SNCF https://data.sncf.com/api \n\nVous pouvez maintenant commencer. Ce notebook peut prendre du temps à s'éxécuter, surout à partir de la partie 3", "_____no_output_____" ] ], [ [ "# !!!!! Attention à bien mettre votre token ici !!!!!\n\ntoken_auth = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'", "_____no_output_____" ], [ "import keyring, os\nif \"XXXXXX\" in token_auth:\n token_auth = keyring.get_password(\"sncf\", os.environ[\"COMPUTERNAME\"] + \"key\")", "_____no_output_____" ] ], [ [ "## Partie 1 - Trouver les gares accessibles _via_ la SNCF\n\n- Trouver l'ensemble des gares disponibles sur l'API et créer un fichier csv avec les codes de la gare, son nom et ses coordonnées latitude et longitude, ainsi que les informations administratives de la région quand elles sont disponibles\n\n- Représentez les sur un graphique", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport requests", "_____no_output_____" ], [ "def page_gares(numero_page) :\n return requests.get('https://api.sncf.com/v1/coverage/sncf/stop_areas?start_page={}'.format(numero_page), \n auth=(token_auth, ''))\n\n######################################\n# on commence par la première page qui nous donne le nombre de résultats par page ainsi que le nombre total de résultats \n\npage_initiale = page_gares(0) \nitem_per_page = page_initiale.json()['pagination']['items_per_page']\ntotal_items = page_initiale.json()['pagination']['total_result']\ndfs = []\n\n# on fait une boucle sur toutes les pages suivantes \nprint_done = {}\n\nfor page in range(int(total_items/item_per_page)+1) : \n stations_page = page_gares(page)\n \n ensemble_stations = stations_page.json()\n \n if 'stop_areas' not in ensemble_stations:\n # pas d'arrêt\n continue\n \n # on ne retient que les informations qui nous intéressent \n for station in ensemble_stations['stop_areas']:\n\n station['lat'] = station['coord']['lat']\n station[\"lon\"] = station['coord']['lon']\n\n if 'administrative_regions' in station.keys() : \n for var_api, var_df in zip(['insee','name','label','id','zip_code'],\n ['insee','region','label_region','id_region','zip_code']) : \n try:\n station[var_df] = station['administrative_regions'][0][var_api]\n except KeyError:\n if var_api not in print_done:\n print(\"key '{0}' not here but {1}\".format(var_api, \n \",\".join(station['administrative_regions'][0].keys())))\n print_done[var_api] = var_api\n\n [station.pop(k,None) for k in ['coord','links','administrative_regions', 'type', 'codes']]\n\n stations = ensemble_stations['stop_areas']\n try:\n dp = pd.DataFrame(stations)\n except Exception as e:\n # La SNCF modifie parfois le schéma de ses données.\n # On affiche station pour avoir une meilleure idée que l'erreur retournée par pandas\n raise Exception(\"Problème de données\\n{0}\".format(stations)) from e\n \n dfs.append(dp)\n if page % 10 == 0:\n print(\"je suis à la page\", page, \"---\", dp.shape)\n\nimport pandas\ndf = pandas.concat(dfs)\ndf.to_csv(\"./ensemble_gares.csv\") \nprint(df.shape)\ndf.head()", "je suis à la page 0 --- (25, 11)\nje suis à la page 10 --- (25, 11)\nje suis à la page 20 --- (25, 11)\nje suis à la page 30 --- (25, 11)\nje suis à la page 40 --- (25, 11)\nje suis à la page 50 --- (25, 11)\nje suis à la page 60 --- (25, 11)\nje suis à la page 70 --- (25, 11)\nje suis à la page 80 --- (25, 11)\nje suis à la page 90 --- (25, 11)\nje suis à la page 100 --- (25, 11)\nje suis à la page 110 --- (25, 11)\nje suis à la page 120 --- (25, 11)\n(3037, 11)\n" ], [ "df = pd.read_csv(\"./ensemble_gares.csv\", encoding = \"ISO-8859-1\")\nprint(df.columns)\nprint(df.shape)\n# Exemple des informations sur une gare\ndf.iloc[317]", "Index(['Unnamed: 0', 'id', 'id_region', 'insee', 'label', 'label_region',\n 'lat', 'lon', 'name', 'region', 'timezone', 'zip_code'],\n dtype='object')\n(3037, 12)\n" ], [ "# on crée un dictionnaire des correspondances entre les noms et les codes des gares\ndict_label_gare_code = df[['label','id']].set_index('label').to_dict()['id']\ndict_nom_gare_code = df[['name','id']].set_index('name').to_dict()['id']", "_____no_output_____" ], [ "print(df.columns)\n\n# graphique dans le plan des gares\n%matplotlib inline\nimport matplotlib.pyplot as plt\nlng_var = df[(df['lat']>35) & (df['lat']<60)][\"lon\"].tolist()\nlat_var = df[(df['lat']>35) & (df['lat']<60)][\"lat\"].tolist()\nplt.scatter(x = lng_var , y = lat_var,marker = \"o\")", "Index(['Unnamed: 0', 'id', 'id_region', 'insee', 'label', 'label_region',\n 'lat', 'lon', 'name', 'region', 'timezone', 'zip_code'],\n dtype='object')\n" ] ], [ [ "## Les trajets depuis la Gare de Lyon\n\n### Partons à Lyon : le 17 novembre 2016 à 19h57\n\nImaginez que vous vouliez un peu voyager hors de Paris, et il se trouve que justement on vous propose de passer quelques jours à Lyon. Vous partez le 17 novembre vers 19h50 pour ne pas trop écourter votre journée de travail. \n\n#### Question 1\n\n- Commencez par récupérer les informations sur le trajet entre Paris Gare de Lyon et Lyon Perrache le 17 novembre à 19h57\n\n - Paris - Gare de Lyon (code de la gare : __stop\\_area:OCE:SA:87686006__)\n\n - Lyon - Gare Lyon Perrache (code de la gare : __stop\\_area:OCE:SA:87722025__)\n \n - Indice : utiliser la requête \"journeys\"\n \n - Autre indice : le format de la date est AAAAMMJJTHHMMSS (Année, mois, jour, heure, minutes, secondes)\n \n- Répondez aux questions suivantes \n - combien y a-t-il d'arrêts entre ces deux gares ? (utilisez la clé 'journeys')\n - combien de temps d'arrêt à chacune d'elles ?", "_____no_output_____" ] ], [ [ "##### une fonction qui sera utile pour calculer des temps\n\nfrom datetime import datetime, timedelta\n\ndef convertir_en_temps(chaine) : \n ''' on convertit en date la chaine de caractères de l API'''\n return datetime.strptime(chaine.replace('T',''),'%Y%m%d%H%M%S')", "_____no_output_____" ] ], [ [ "Et l'inverse :", "_____no_output_____" ] ], [ [ "def convertir_en_chaine(dt) : \n ''' on convertit en chaîne de caractères un datetime'''\n return datetime.strftime(dt, '%Y%m%dT%H%M%S')", "_____no_output_____" ], [ "# informations sur le trajet qu'on choisit dans le futur\n# l'API ne retourne pas de résultatq très loin dans le passé\nnow = datetime.now()\ndt = now + timedelta(14) # dans deux semaines\n\ndate_depart = convertir_en_chaine(dt)\ngare_depart = 'stop_area:OCE:SA:87686006'\ngare_arrivee = 'stop_area:OCE:SA:87722025'\n\n# ensemble des départs \n\nparis_lyon = requests.get('https://api.sncf.com/v1/coverage/sncf/journeys?'\\\n 'from={}&to={}&datetime={}'.format(gare_depart, gare_arrivee, date_depart), \\\n auth=(token_auth, '')).json()\n\ndate_depart", "_____no_output_____" ], [ "# les gares du chemin entre Paris et Lyon sur ce trajet\n# ainsi que le temps d'arrêt\nsession = paris_lyon['journeys'][0]['sections'][1]\nif \"stop_date_times\" in session:\n for i in session['stop_date_times'] : \n print(i['stop_point']['name'], \n convertir_en_temps(i['departure_date_time'])-convertir_en_temps(i['arrival_date_time']),\"minutes d'arrêt\")", "Paris-Gare-de-Lyon 0:00:00 minutes d'arrêt\nLyon-Part-Dieu 0:05:00 minutes d'arrêt\nLyon-Perrache 0:00:00 minutes d'arrêt\n" ] ], [ [ "#### Question 2\nVous êtes un peu pressé et vous avez peur de vous tromper en arrivant à la gare car d'autres TGV partent à peu près en même temps (à partir de 19h00) de la gare de Lyon. \n\n- Si vous demandez à l'API, combien de résultats vous donne-t-elle ?", "_____no_output_____" ] ], [ [ "### les trains qui partent autour de 19h00\ndeparts_paris = requests.get('https://api.sncf.com/v1/coverage/sncf/stop_points/stop_point:OCE:SP:'\\\n 'TGV-87686006/departures?from_datetime={}'.format(date_depart) ,\n auth=(token_auth, '')).json()\n\n# Nombre de trains que l'API renvoit à partir de cet horaire-là\nprint(len(departs_paris['departures']))", "10\n" ] ], [ [ "- Quels sont les horaires de départ de ces trains ? ", "_____no_output_____" ] ], [ [ "for i in range(len(departs_paris['departures'])) :\n print(departs_paris['departures'][i]['stop_date_time']['departure_date_time'])", "20180722T215900\n20180723T055000\n20180723T060700\n20180723T060700\n20180723T063700\n20180723T064300\n20180723T064800\n20180723T071300\n20180723T071800\n20180723T073700\n" ] ], [ [ "- Parmi ces trains, combien de trains ont pour destination finale Lyon et qui partent le 17 novembre ?", "_____no_output_____" ] ], [ [ "nombre_trains_pour_lyon = 0\n\nfor depart in departs_paris['departures'] : \n if \"Lyon\" in depart['display_informations']['direction'] : \n if convertir_en_temps(depart['stop_date_time']['arrival_date_time']) > convertir_en_temps(date_depart) and \\\n convertir_en_temps(depart['stop_date_time']['arrival_date_time']) < datetime(2016,11,18,0,0,0):\n nombre_trains_pour_lyon += 1\n print(\"le prochain départ pour Lyon sera le\", convertir_en_temps(depart['stop_date_time']['arrival_date_time']))\n \nprint(\"Il y a\" , nombre_trains_pour_lyon, \"train(s) pour Lyon dans les trains proposés\", \n \"par l'API qui partent encore le 17 novembre\")", "Il y a 0 train(s) pour Lyon dans les trains proposés par l'API qui partent encore le 17 novembre\n" ] ], [ [ "-------------------------\n\n### C'est quand qu'on va où ?\n- En fait, vous n'êtes plus très sûr de vouloir aller à Lyon. Mais bon maintenant vous êtes Gare de Lyon et il est 18h00. \n\n#### Question 3\n- Combien de tgv partent entre 18h00 et 20h00 ?\n- Lequel arrive le plus tôt à sa destination finale ?", "_____no_output_____" ] ], [ [ "# on crée deux fonctions : \n\ndef trouver_destination_tgv(origine, datetime) : \n '''Permet d avoir les 10 prochains départs d une gare donnée '''\n return requests.get('https://api.sncf.com/v1/coverage/sncf/stop_points/{}/' \\\n 'departures?from_datetime={}'.format(origine, datetime) ,\n auth=(token_auth, '')).json()\n\ndef trouver_trajet_dispo_max_heure(gare_depart, date_heure_depart, date_heure_max) : \n ''' Permet d avoir toutes les informations sur des trajets partant d une gare entre une date X et une date Y '''\n \n destinations = []\n \n# on interroge l'API tant qu'il renvoie des informations sur les trains partant de Gare de lyon \n\n while convertir_en_temps(date_heure_depart) < convertir_en_temps(date_heure_max) :\n # on prend toutes les destinations qui partent à partir d'une certaine heure\n destinations = destinations + trouver_destination_tgv(gare_depart, date_heure_depart)['departures']\n \n nombre_resultats = trouver_destination_tgv(gare_depart, date_heure_depart)['pagination']['items_on_page']\n \n # on trouve l'heure max de la première série de 10 solutions que l'application renvoie\n # on remplace l'heure qu'on cherche par celle là\n date_heure_depart = trouver_destination_tgv(gare_depart,\n date_heure_depart)['departures'][nombre_resultats-1]['stop_date_time']['departure_date_time']\n\n return destinations", "_____no_output_____" ], [ "# on trouve l'ensemble des trajets dont le départ est compris entre deux horaires\n# informations sur le trajet qu'on choisit dans le futur\n# l'API ne retourne pas de résultatq très loin dans le passé\nnow = datetime.now()\nif now.hour < 6:\n # pas trop tôt\n now += timedelta(hours=4)\ndt = now + timedelta(14) # dans deux semaines\n\ndate_heure = convertir_en_chaine(dt)\nmax_date_heure = convertir_en_chaine(dt + timedelta(hours=4))\nprint(\"entre\", date_heure, \"et\", max_date_heure)\n\ngare_initiale = 'stop_point:OCE:SP:TGV-87686006'\n\n# on demande à avoir tous les trajets partant de gare de lyon entre 18h et 20h\n\ndestinations_depuis_paris_max_20h = trouver_trajet_dispo_max_heure(gare_initiale, date_heure, max_date_heure)\n\n# on veut supprimer ceux pour lesquels le départ est après 20h00\n\ndictionnaire_destinations = {}\n\ni = 0\n\nfor depart in destinations_depuis_paris_max_20h : \n print(depart['display_informations']['direction'],depart['stop_date_time']['departure_date_time'])\n if convertir_en_temps(depart['stop_date_time']['departure_date_time']) < convertir_en_temps(max_date_heure) : \n i += 1\n dictionnaire_destinations[i] = depart \n \nprint(\"Je peux prendre\", len(dictionnaire_destinations.keys()), \n \"trains qui partent entre 18h et 20h de Gare de Lyon le 17 novembre 2016\")", "entre 20180722T215414 et 20180723T015414\nLyon-Perrache (Lyon) 20180722T215900\nLyon-Perrache (Lyon) 20180723T055000\nMarseille-St-Charles (Marseille) 20180723T060700\nBéziers (Béziers) 20180723T060700\nMilano-Porta-Garibaldi (Milano) 20180723T063700\nMulhouse (Mulhouse) 20180723T064300\nSt-Etienne-Châteaucreux (Saint-Étienne) 20180723T064800\nPerpignan (Perpignan) 20180723T071300\nNice-Ville (Nice) 20180723T071800\nMarseille-St-Charles (Marseille) 20180723T073700\nJe peux prendre 1 trains qui partent entre 18h et 20h de Gare de Lyon le 17 novembre 2016\n" ], [ "# on cherche celui qui arrive le plus tôt à sa destination\n\ndef trouver_info_trajet(dep, arr, heure) :\n res = requests.get('https://api.sncf.com/v1/coverage/sncf/journeys?from={}&to={}&datetime={}'.format(dep,arr,heure), \\\n auth=(token_auth, '')).json()\n if 'journeys' not in res:\n if 'error' in res and \"no solution\" in res[\"error\"]['message']:\n print(\"Pas de solution pour '{0} --> '{1}' h: {2}.\".format(dep, arr, heure))\n return None\n return res['journeys'][0]\n\n# on initiale l'heure à la fin de la journée : on veut réduire cette variable au maximum\n# on veut 6h après le départ\nheure_minimale = dt + timedelta(hours=8)\ndestination_la_plus_rapide = None\nprint(\"heure_minimale\", heure_minimale, \" len \", len(dictionnaire_destinations))\n\n# parmi toutes les destinations possibles, on recherche le train qui arrive le plus tôt à sa destination finale\nfor code, valeurs in dictionnaire_destinations.items() : \n ''' on prend le code de la gare'''\n code_destination = dictionnaire_destinations[code]['route']['direction']['id']\n ''' on regarde à quelle heure arrive le train'''\n trajet = trouver_info_trajet('stop_area:OCE:SA:87686006',code_destination,\n dictionnaire_destinations[code]['stop_date_time']['arrival_date_time'])\n if trajet is None:\n continue\n if heure_minimale > convertir_en_temps(trajet['arrival_date_time']) : \n heure_minimale = convertir_en_temps(trajet['arrival_date_time'])\n destination_la_plus_rapide = dictionnaire_destinations[code]", "heure_minimale 2018-07-23 05:54:14.884764 len 1\n" ], [ "if destination_la_plus_rapide is not None:\n print(destination_la_plus_rapide['display_informations']['direction'], heure_minimale)\nelse:\n print(\"pas de résultat\")", "Lyon-Perrache (Lyon) 2018-07-23 00:09:00\n" ] ], [ [ "### Et les correspondances ? \n\n#### Question 4\n\n- On va essayer de voir jusqu'où on peut aller, en prenant des trains au départ de la Gare de Lyon : \n - Quelles sont toutes les gares atteignables en partant le 17 novembre, sans faire de changement et sans partir après minuit ?\n - Si on prend un de ces trains, jusqu'où peut-on aller, avec une correspondance, sans partir après 8h le lendemain matin ?", "_____no_output_____" ] ], [ [ "# on va trouver toutes les gares qui sont sur les trajets des trains retenus donc atteignables sans correspondance\n\ndef trouver_toutes_les_gares_du_trajet(gare_depart, gare_arrivee_finale, horaire_depart) :\n return requests.get('https://api.sncf.com/v1/coverage/sncf/journeys?from={}&to={}' \\\n '&datetime={}'.format(gare_depart,gare_arrivee_finale,horaire_depart), \\\n auth=(token_auth, '')).json()", "_____no_output_____" ], [ "# Exemple pour la première gare de la liste \ngare_depart = dictionnaire_destinations[1]['stop_point']['id']\ngare_arrivee = dictionnaire_destinations[1]['route']['direction']['id']\nhoraire_train = dictionnaire_destinations[1]['stop_date_time']['arrival_date_time']\n\n######################\ntrajet_recherche = trouver_toutes_les_gares_du_trajet(gare_depart,gare_arrivee,horaire_train)\nsession = trajet_recherche['journeys'][0]['sections'][0]\nif \"stop_date_times\" in session:\n for i in session['stop_date_times']:\n print(i['stop_point']['name'])", "Paris-Gare-de-Lyon\nLyon-Part-Dieu\nLyon-Perrache\n" ], [ "#### on fait la liste des gares où on peut aller sans correspondance\n\nliste_gares_direct = []\n\nfor x in dictionnaire_destinations.keys():\n # on prend les deux gares départ + finale\n gare_depart = dictionnaire_destinations[x]['stop_point']['id']\n gare_arrivee = dictionnaire_destinations[x]['route']['direction']['id']\n horaire_train = dictionnaire_destinations[x]['stop_date_time']['arrival_date_time']\n \n # on appelle la fonction définie précédemment\n trajet_recherche = trouver_toutes_les_gares_du_trajet(gare_depart,gare_arrivee,horaire_train)\n if 'error' in trajet_recherche:\n continue\n session = trajet_recherche['journeys'][0]['sections'][0]\n if \"stop_date_times\" in session:\n for i in session['stop_date_times']: \n print(i['stop_point']['name'], i['arrival_date_time'])\n liste_gares_direct.append(i['stop_point']['name'])\n print(\"-------------\") \n \n#### là on a la liste des gares atteignables sans correspondance \nliste_gares_direct = set(liste_gares_direct)", "Paris-Gare-de-Lyon 20180722T215900\nLyon-Part-Dieu 20180722T235600\nLyon-Perrache 20180723T000900\n-------------\n" ] ], [ [ "#### Exemple : trouver toutes les correspondances possibles depuis le trajet entre les gares de Paris et de Perpignan", "_____no_output_____" ] ], [ [ "# pour le premier trajet gare de la liste trouvée à l'étape précédente\n# on va chercher toutes les connexions des gares possibles, entre le moment de l'arrivée \n# et 8 heures le lendemain matin\n\ngare_depart = dictionnaire_destinations[1]['stop_point']['id']\ngare_arrivee = dictionnaire_destinations[1]['route']['direction']['id']\nhoraire_train = dictionnaire_destinations[1]['stop_date_time']['arrival_date_time']\n\nhoraire_max = convertir_en_chaine(dt + timedelta(hours=8))\nprint(\"horaire_max\", horaire_max)", "horaire_max 20180723T055414\n" ], [ "###################### en partant de gare de lyon en direction de Perpignan\n\ntrajet_recherche = trouver_toutes_les_gares_du_trajet(gare_depart,gare_arrivee,horaire_train)\n\ndictionnaire_correspondances = {}\n\nfor i in trajet_recherche['journeys'][0]['sections'][0]['stop_date_times']: \n\n #print(\"la gare où on est descendu depuis Paris\", i['stop_point']['name'])\n\n if i['stop_point']['id'] == \"stop_point:OCE:SP:TGV-87686006\" : \n #print(\"on ne prend pas la gare de Lyon - ce n'est pas une gare du trajet\")\n pass\n \n else :\n # on va appliquer à nouveau la fonction des trajets disponibles mais pour l'ensemble des gares\n gare_dep_connexion = i['stop_point']['id']\n nom_gare_dep = i['stop_point']['name']\n heure_dep_connexion = i['arrival_date_time']\n \n trajet_recherche_connexion = trouver_trajet_dispo_max_heure(gare_dep_connexion, heure_dep_connexion, horaire_max)\n \n test_as_connexion_on_time = True\n \n # pour chaque trajet possible depuis la gare où on est arrivé depuis paris, on va vérifier qu'on part bien \n # avant 8h le lendemain\n autre_gare = None\n for vers_autre_gare in trajet_recherche_connexion : \n heure_depart_depuis_autre_gare = vers_autre_gare['stop_date_time']['departure_date_time']\n destination_trajet = vers_autre_gare['display_informations']['direction']\n \n if convertir_en_temps(heure_depart_depuis_autre_gare) < convertir_en_temps(horaire_max) : \n dictionnaire_correspondances[(nom_gare_dep,heure_depart_depuis_autre_gare)] = destination_trajet \n test_as_connexion_on_time = False\n # print(nom_gare_dep,heure_depart_depuis_autre_gare, \"gare finale du trajet\", destination_trajet)\n autre_gare = vers_autre_gare\n \n if autre_gare and test_as_connexion_on_time: \n dictionnaire_correspondances[(nom_gare_dep,autre_gare['stop_date_time']['departure_date_time'])] = \"\"\n \n# on garde toutes les gares où on peut aller depuis une des gares de correspondance, avec un départ avant 8H\ndictionnaire_correspondances", "_____no_output_____" ], [ "# Pour les trajets qui partent avant 8h des gares, on va chercher toutes les gares qui sont sur le trajet\ngares_avec_connexion = []\nfor k,v in dictionnaire_correspondances.items() : \n if len(v) == 0 : \n pass\n else :\n if k[0] not in dict_nom_gare_code:\n print(\"'{0}' pas trouvé dans {1}\".format(k[0], \", \".join(\n sorted(_ for _ in dict_nom_gare_code if _[:4] == k[0][:4]))))\n continue\n if v not in dict_label_gare_code:\n print(\"'{0}' pas trouvé dans {1}\".format(v, \", \".join(\n sorted(_ for _ in dict_label_gare_code if _[:4] == v[:4]))))\n continue\n\n dep = dict_nom_gare_code[k[0]]\n arr = dict_label_gare_code[v]\n \n gares_entre_dep_arr = trouver_toutes_les_gares_du_trajet(dep, arr,k[1])\n for gare in gares_entre_dep_arr['journeys'][0]['sections'][1]['stop_date_times']: \n #print(\"gare depart:\", k[0], gare['stop_point']['name'])\n gares_avec_connexion.append(gare['stop_point']['name'])\n \n# la liste des gares atteignables avec 1 correspondance \ngares_avec_connexion = set(gares_avec_connexion)", "_____no_output_____" ], [ "print(gares_avec_connexion)", "{'Marne-la-Vallée-Chessy.', 'Lille Europe', 'Lyon-Perrache', 'Aéropt-C-de-Gaulle-TGV', 'Creusot - TGV (le)', 'Mâcon-Loché-TGV', 'Lyon-Part-Dieu', 'Paris-Gare-de-Lyon', 'Bruxelles-M./Brussel-Z.'}\n" ], [ "# on crée la liste des gares atteignables seulement avec une correspondance (pas directement atteignable)\ngares_atteintes_avec_connexion = [a for a in gares_avec_connexion if (a not in liste_gares_direct)]\nprint(gares_atteintes_avec_connexion)", "['Marne-la-Vallée-Chessy.', 'Lille Europe', 'Aéropt-C-de-Gaulle-TGV', 'Creusot - TGV (le)', 'Mâcon-Loché-TGV', 'Bruxelles-M./Brussel-Z.']\n" ] ], [ [ "##### Exemple : trouver toutes les correspondances possibles depuis les trains qu'on prend de la Gare de Lyon\n\nMaintenant qu'on a fait un exemple, on le fait pour tous les trajets qui partent de la Gare de Lyon\n\n!!! Attention cette celulle prend du temps (beaucoup beaucoup de temps) !!!!", "_____no_output_____" ] ], [ [ "gares_avec_connexion = []\n\nfor gare_initiale in dictionnaire_destinations: \n # pour le premier trajet gare de la liste trouvée à l'étape précédente\n # on va chercher toutes les connexions des gares possibles\n print(gare_initiale, \"/\", len(dictionnaire_destinations))\n\n gare_depart = dictionnaire_destinations[gare_initiale]['stop_point']['id']\n gare_arrivee = dictionnaire_destinations[gare_initiale]['route']['direction']['id']\n horaire_train = dictionnaire_destinations[gare_initiale]['stop_date_time']['arrival_date_time']\n \n # Pour les trajets qui partent avant 8h des gares, on va chercher toutes les gares qui sont sur le trajet\n \n trajet_recherche = trouver_toutes_les_gares_du_trajet(gare_depart, gare_arrivee, horaire_train)\n\n dictionnaire_correspondances = {}\n if 'journeys' not in trajet_recherche:\n print(\"Pas de trajet entre '{0}' et '{1}' h={2}.\".format(gare_depart, gare_arrivee, horaire_train))\n continue\n session = trajet_recherche['journeys'][0]['sections'][0] \n\n if \"stop_date_times\" in session:\n for i in session['stop_date_times']: \n\n if i['stop_point']['id'] == \"stop_point:OCE:SP:TGV-87686006\" : \n #print(\"on ne prend pas la gare de Lyon - ce n'est pas une gare du trajet\")\n pass\n\n else :\n # on va appliquer à nouveau la fonction des trajets disponibles mais pour l'ensemble des gares\n gare_dep_connexion = i['stop_point']['id']\n nom_gare_dep = i['stop_point']['name']\n heure_dep_connexion = i['arrival_date_time']\n\n trajet_recherche_connexion = trouver_trajet_dispo_max_heure(gare_dep_connexion, heure_dep_connexion, horaire_max)\n\n test_as_connexion_on_time = True\n\n # pour chaque trajet possible depuis la gare où on est arrivé depuis paris, on va vérifier qu'on part bien \n # avant 8h le lendemain\n for vers_autre_gare in trajet_recherche_connexion : \n heure_depart_depuis_autre_gare = vers_autre_gare['stop_date_time']['departure_date_time']\n destination_trajet = vers_autre_gare['display_informations']['direction']\n\n if convertir_en_temps(heure_depart_depuis_autre_gare) < convertir_en_temps(horaire_max) : \n dictionnaire_correspondances[(nom_gare_dep,heure_depart_depuis_autre_gare)] = destination_trajet \n test_as_connexion_on_time = False\n\n if test_as_connexion_on_time == True : \n dictionnaire_correspondances[(nom_gare_dep,vers_autre_gare['stop_date_time']['departure_date_time'])] = \"\"\n\n # on garde toutes les gares où on peut aller depuis une des gares de correspondance, avec un départ avant 8H\n\n for k,v in dictionnaire_correspondances.items() : \n if len(v) == 0:\n continue\n if k[0] not in dict_nom_gare_code:\n print(\"'{0}' pas trouvé dans {1}\".format(k[0], \", \".join(\n sorted(_ for _ in dict_nom_gare_code if _[:4] == k[0][:4]))))\n continue\n if v not in dict_label_gare_code:\n print(\"'{0}' pas trouvé dans {1}\".format(v, \", \".join(\n sorted(_ for _ in dict_label_gare_code if _[:4] == v[:4]))))\n continue\n dep = dict_nom_gare_code[k[0]]\n arr = dict_label_gare_code[v]\n gares_entre_dep_arr = trouver_toutes_les_gares_du_trajet(dep, arr, k[1])\n if 'journeys' not in gares_entre_dep_arr:\n print(\"Pas de trajet entre '{0}' et '{1}'.\".format(k[0], v))\n continue\n session = gares_entre_dep_arr['journeys'][0]['sections'][1]\n if \"stop_date_times\" in session:\n for gare in session['stop_date_times'] : \n gares_avec_connexion.append(gare['stop_point']['name'])", "1 / 1\n" ], [ "# la liste des gares atteignables avec 1 correspondance \ngares_avec_connexion = set(gares_avec_connexion)", "_____no_output_____" ], [ "gares_connexion = [a for a in gares_avec_connexion if a not in liste_gares_direct]\nprint(gares_connexion)", "['Marne-la-Vallée-Chessy.', 'Lille Europe', 'Aéropt-C-de-Gaulle-TGV', 'Creusot - TGV (le)', 'Mâcon-Loché-TGV', 'Bruxelles-M./Brussel-Z.']\n" ] ], [ [ "#### Question 5\n- Représenter toutes les gares atteignables avec un graphique de type scatter. Distinguer les gares atteintes en un seul trajet et celles atteintes avec une correspondance.", "_____no_output_____" ] ], [ [ "######### Type de chaque gare pour le graphique\ndict_type_gares = {}\nfor a in liste_gares_direct :\n dict_type_gares[a] = \"direct\"\nfor a in gares_connexion :\n dict_type_gares[a] = \"correspondance\" \ndict_type_gares['Paris-Gare-de-Lyon'] = 'depart'\ndict_type_gares", "_____no_output_____" ] ], [ [ "On représente tout ça sur un graphique", "_____no_output_____" ] ], [ [ "# on va les représenter grâce à la base des latitude / longitude\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib.lines import Line2D \n\nmpl.rcParams['axes.facecolor'] = \"whitesmoke\"\n\npalette = plt.cm.spring \n\nliste_couleurs = [palette(0), palette(0.5), palette(0.8)]\n\ndata_all = pd.read_csv(\"./ensemble_gares.csv\", encoding = \"ISO-8859-1\")\n\nconnexions = []\nlat = []\nlon = []\nlabels = []\n\ndict_lat = data_all.set_index('name')['lat'].to_dict()\ndict_lon = data_all.set_index('name')['lon'].to_dict()\n#dict_lab = data_all.set_index('name')['name'].str.replace(\"gare de\",\"\").to_dict()\n\n\nfor gare in dict_type_gares: \n if gare not in dict_lat:\n print(\"'{0}' pas trouvé dans dict_lat (problème d'accents?)\".format(gare))\n continue\n if gare not in dict_lon:\n print(\"'{0}' pas trouvé dans dict_lon (problème d'accents?)\".format(gare))\n continue\n lat.append(dict_lat[gare]) \n lon.append(dict_lon[gare])\n labels.append(gare)", "'Marne-la-Vallée-Chessy.' pas trouvé dans dict_lat (problème d'accents?)\n'Aéropt-C-de-Gaulle-TGV' pas trouvé dans dict_lat (problème d'accents?)\n'Mâcon-Loché-TGV' pas trouvé dans dict_lat (problème d'accents?)\n" ], [ "%matplotlib inline", "_____no_output_____" ], [ "### La carte \n###################################################################################################\n\ndef liste_unique(liste) : \n unicite = [] \n for x in liste : \n if x in unicite :\n pass\n else :\n unicite.append(x)\n return unicite\n\nlab_un = liste_unique(labels)\nlat_un = liste_unique(lat)\nlon_un = liste_unique(lon)\n\nfig = plt.figure(figsize=(12,10))\n\nfor label, x, y in set(zip(labels, lon, lat)) :\n if dict_type_gares[label] == \"direct\" : \n plt.annotate(label, xy = (x - 0.05, y - 0.05), horizontalalignment = 'right', size = 13)\n else :\n plt.annotate(label, xy = (x + 0.05, y + 0.05), horizontalalignment = 'left', size = 13)\n\ncolors = [] \nfor x in lab_un : \n if dict_type_gares[x] == \"depart\" : \n colors.append(liste_couleurs[0])\n if dict_type_gares[x] == \"direct\" :\n colors.append(liste_couleurs[1])\n if dict_type_gares[x] == \"correspondance\" : \n colors.append(liste_couleurs[2])\n \n \nplt.scatter(x = lon_un , y = lat_un, marker = \"o\", c = colors, s = 100, alpha = 0.5)\n\n#### Legende\n\ncirc1 = Line2D([0], [0], linestyle=\"none\", marker=\"o\", alpha=0.5, markersize=10, markerfacecolor = liste_couleurs[0])\ncirc2 = Line2D([0], [0], linestyle=\"none\", marker=\"o\", alpha=0.5, markersize=10, markerfacecolor = liste_couleurs[1])\ncirc3 = Line2D([0], [0], linestyle=\"none\", marker=\"o\", alpha=0.5, markersize=10, markerfacecolor = liste_couleurs[2])\n\nlegende = plt.legend((circ1, circ2, circ3), (\"Gare de départ\", \"Direct depuis Gare de Lyon le soir du 17 novembre\", \n \"Avec une correspondance depuis une gare directe\"), numpoints=1, loc=\"best\")\n\nlegende.get_frame().set_facecolor('white')\n\nplt.title(\"Gares atteignables avant minuit depuis la Gare de Lyon\", size = 20);", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cbe5738dc040dc77287820ab94755b3ad2f145f8
88,393
ipynb
Jupyter Notebook
Code/DataModelingAustralia.ipynb
bjw1622/AirbnbPricePrediction
0570b244e07dc818cd89a449bd54d24b0f54643d
[ "MIT" ]
1
2022-03-10T01:08:29.000Z
2022-03-10T01:08:29.000Z
Code/DataModelingAustralia.ipynb
bjw1622/AirbnbPricePrediction
0570b244e07dc818cd89a449bd54d24b0f54643d
[ "MIT" ]
null
null
null
Code/DataModelingAustralia.ipynb
bjw1622/AirbnbPricePrediction
0570b244e07dc818cd89a449bd54d24b0f54643d
[ "MIT" ]
4
2022-03-22T01:32:47.000Z
2022-03-22T01:33:45.000Z
44.824037
19,014
0.521116
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nPre_data = pd.read_csv(\"C:\\\\Users\\\\2019A00303\\\\Desktop\\\\Code\\\\Airbnb Project\\\\Data\\\\PreProcessingAustralia.csv\")\nPre_data", "_____no_output_____" ], [ "Pre_data['Price'].plot(kind='hist', bins=100)", "_____no_output_____" ], [ "Pre_data['group'] = pd.cut(x=Pre_data['Price'],\nbins=[0, 50, 100, 150, 200, 1000],\nlabels=['group_1','group_2','group_3','group_4','group_5'])\nPre_data.head()", "_____no_output_____" ], [ "from sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(Pre_data, Pre_data[\"group\"]):\n train = Pre_data.loc[train_index]\n test = Pre_data.loc[test_index]", "_____no_output_____" ], [ "train['group'].value_counts() / len(train)", "_____no_output_____" ], [ "test['group'].value_counts() / len(test)", "_____no_output_____" ], [ "train.drop('group', axis=1, inplace=True)\ntrain.head()", "_____no_output_____" ], [ "test.drop(['Unnamed: 0','group', 'Host Since', 'Country', 'Airbed', 'Couch', 'Futon', 'Pull-out Sofa', 'Real Bed', 'Cleaning Fee'], axis=1, inplace=True)\ntest.head()", "_____no_output_____" ], [ "train_y = train[['Price']]\ntrain_y.head()", "_____no_output_____" ], [ "train.drop(['Unnamed: 0', 'Price', 'Host Since', 'Country','Airbed', 'Couch', 'Futon', 'Pull-out Sofa', 'Real Bed', 'Cleaning Fee'], axis=1, inplace=True)\ntrain_X = train\ntrain_X.head()", "_____no_output_____" ], [ "test_y= test[['Price']]\ntest_y.head()", "_____no_output_____" ], [ "test.drop('Price', axis=1, inplace=True)\ntest_X = test\ntest_X.head()", "_____no_output_____" ], [ "# from sklearn.linear_model import LinearRegression\n\n# l_reg = LinearRegression()\n# l_reg.fit(train_X, train_y)", "_____no_output_____" ], [ "from sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nimport numpy as np\n\n# predictions = l_reg.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# predictions = l_reg.predict(test_X)\n# mse = mean_squared_error(test_y, predictions)\n# mae = mean_absolute_error(test_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# from sklearn.tree import DecisionTreeRegressor\n\n# d_reg = DecisionTreeRegressor()\n# d_reg.fit(train_X, train_y)", "_____no_output_____" ], [ "# predictions = d_reg.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# predictions = d_reg.predict(test_X)\n# mse = mean_squared_error(test_y, predictions)\n# mae = mean_absolute_error(test_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# from sklearn.svm import SVR\n\n# svr = SVR()\n# svr.fit(train_X, train_y)", "_____no_output_____" ], [ "# predictions = svr.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# predictions = svr.predict(test_X)\n# mse = mean_squared_error(test_y, predictions)\n# mae = mean_absolute_error(test_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# from sklearn.neighbors import KNeighborsRegressor\n# knn = KNeighborsRegressor()\n# knn.fit(train_X, train_y)", "_____no_output_____" ], [ "# predictions = knn.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# predictions = knn.predict(test_X)\n# mse = mean_squared_error(test_y, predictions)\n# mae = mean_absolute_error(test_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# from sklearn.neural_network import MLPRegressor\n\n# ann = MLPRegressor()\n# ann.fit(train_X, train_y)", "_____no_output_____" ], [ "# predictions = ann.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "# predictions = ann.predict(test_X)\n# mse = mean_squared_error(test_y, predictions)\n# mae = mean_absolute_error(test_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ], [ "from sklearn.ensemble import RandomForestRegressor\n\nr_reg = RandomForestRegressor()\nr_reg.fit(train_X, train_y)", "C:\\Users\\2019A0~1\\AppData\\Local\\Temp/ipykernel_18364/806139679.py:4: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n r_reg.fit(train_X, train_y)\n" ], [ "features = train_X.columns\nimportances = r_reg.feature_importances_\nindices = np.argsort(importances)\n\nplt.title('Australia Feature Importances')\nplt.barh(range(len(indices)), importances[indices], color='g', align='center')\nplt.yticks(range(len(indices)), [features[i] for i in indices])\nplt.xlabel('Relative Importance')", "_____no_output_____" ], [ "predictions = r_reg.predict(train_X)\nmse = mean_squared_error(train_y, predictions)\nmae = mean_absolute_error(train_y, predictions)\nrmse = np.sqrt(mse)\nprint(mse, rmse, mae)", "708.9470815123925 26.62606019508693 15.605091047040974\n" ], [ "# from sklearn.model_selection import GridSearchCV\n\n# param = {'n_estimators' : [800,900,1000], 'max_features' : ['sqrt','auto','log2'], 'max_depth' : [8,9,10],\n# 'min_samples_split': [2,3,4]}\n\n# r_reg = RandomForestRegressor(random_state=42)\n\n# search = GridSearchCV(r_reg, param, cv=5,\n# scoring='neg_mean_absolute_error')\n \n# search.fit(train_X, train_y['Price'].ravel())", "_____no_output_____" ], [ "# from sklearn.ensemble import RandomForestRegressor\n\n# r_reg = RandomForestRegressor(bootstrap=True,\n# min_samples_split=2,\n# criterion='mse',\n# max_depth=None,\n# max_features='auto',\n# n_estimators=1000,\n# random_state=42,\n# )\n# r_reg.fit(train_X, train_y['Price'].ravel())", "_____no_output_____" ], [ "# predictions = r_reg.predict(train_X)\n# mse = mean_squared_error(train_y, predictions)\n# mae = mean_absolute_error(train_y, predictions)\n# rmse = np.sqrt(mse)\n# print(mse, rmse, mae)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cbe5776698577a6702e43cd1b1b8c2b7511f5e21
687,247
ipynb
Jupyter Notebook
classification/.ipynb_checkpoints/knn-checkpoint.ipynb
nagarajbhat/100DaysOfCode
75d2d7c596ef0a1e10cfd4665d28d471aff05526
[ "MIT" ]
2
2020-05-23T22:30:26.000Z
2020-08-04T18:16:50.000Z
classification/.ipynb_checkpoints/knn-checkpoint.ipynb
nagarajbhat/100DaysOfCode
75d2d7c596ef0a1e10cfd4665d28d471aff05526
[ "MIT" ]
null
null
null
classification/.ipynb_checkpoints/knn-checkpoint.ipynb
nagarajbhat/100DaysOfCode
75d2d7c596ef0a1e10cfd4665d28d471aff05526
[ "MIT" ]
null
null
null
761.070875
584,580
0.945824
[ [ [ "# KNN(K Nearest Neighbours) for classification of glass types\nWe will make use of KNN algorithms to classify the type of glass.", "_____no_output_____" ], [ "### What is covered?\n- About KNN algorithm\n- Exploring dataset using visualization - scatterplot,pairplot, heatmap (correlation matrix).\n- Feature scaling\n- using KNN to predict \n- Optimization \n - Distance metrics\n - Finding the best K value\n", "_____no_output_____" ], [ "### About KNN-\n- It is an instance-based algorithm.\n- As opposed to model-based algorithms which pre trains on the data, and discards the data. Instance-based algorithms retain the data to classify when a new data point is given.\n- The distance metric is used to calculate its nearest neighbors (Euclidean, manhattan)\n- Can solve classification(by determining the majority class of nearest neighbors) and regression problems (by determining the means of nearest neighbors).\n- If the majority of the nearest neighbors of the new data point belong to a certain class, the model classifies the new data point to that class.\n", "_____no_output_____" ], [ "![Knn](./kNN_board.PNG)", "_____no_output_____" ], [ "For example, in the above plot, Assuming k=5, \n\nthe black point \n(new data) can be classified as class 1(Blue), because 3 out 5 of its nearest neighbors belong to class 1.\n", "_____no_output_____" ], [ "### Dataset\n[Glass classification dataset](https://www.kaggle.com/uciml/glass) . Download to follow along.", "_____no_output_____" ], [ "**Description** - \n\nThis is a Glass Identification Data Set from UCI. It contains 10 attributes including id. The response is glass type(discrete 7 values)\n\n- Id number: 1 to 214 (removed from CSV file)\n- RI: refractive index\n- Na: Sodium (unit measurement: weight percent in corresponding oxide, as are attributes 4-10)\n- Mg: Magnesium\n- Al: Aluminum\n- Si: Silicon\n- K: Potassium\n- Ca: Calcium\n- Ba: Barium\n- Fe: Iron\n- Type of glass: (class attribute)\n - 1 buildingwindowsfloatprocessed \n - 2 buildingwindowsnonfloatprocessed \n - 3 vehiclewindowsfloatprocessed\n - 4 vehiclewindowsnonfloatprocessed (none in this database)\n - 5 containers\n - 6 tableware\n - 7 headlamps", "_____no_output_____" ], [ "About Type 2,4 -> **Float processed glass** means they are made on a floating molten glass on a bed of molten metal, this gives the sheet uniform thickness and flat surfaces.", "_____no_output_____" ], [ "## Load dependencies and data", "_____no_output_____" ] ], [ [ "#import dependencies\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport seaborn as sns\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom sklearn.model_selection import cross_val_score\n", "_____no_output_____" ], [ "#load data\ndf = pd.read_csv('./data/glass.csv')\ndf.head()", "_____no_output_____" ], [ "# value count for glass types\ndf.Type.value_counts()", "_____no_output_____" ] ], [ [ "## Data exploration and visualizaion", "_____no_output_____" ], [ "#### correlation matrix - ", "_____no_output_____" ] ], [ [ "cor = df.corr()\nsns.heatmap(cor)", "_____no_output_____" ] ], [ [ "We can notice that Ca and K values don't affect Type that much.\n\nAlso Ca and RI are highly correlated, this means using only RI is enough.\n\nSo we can go ahead and drop Ca, and also K.(performed later)\n", "_____no_output_____" ], [ "## Scatter plot of two features", "_____no_output_____" ] ], [ [ "sns.scatterplot(df_feat['RI'],df_feat['Na'],hue=df['Type'])", "_____no_output_____" ] ], [ [ "Suppose we consider only RI, and Na values for classification for glass type.\n- From the above plot, We first calculate the nearest neighbors from the new data point to be calculated.\n- If the majority of nearest neighbors belong to a particular class, say type 4, then we classify the data point as type 4.\n", "_____no_output_____" ], [ "But there are a lot more than two features based on which we can classify.\nSo let us take a look at pairwise plot to capture all the features.", "_____no_output_____" ] ], [ [ "#pairwise plot of all the features\nsns.pairplot(df,hue='Type')\nplt.show()", "C:\\Users\\nagar\\Anaconda3\\lib\\site-packages\\statsmodels\\nonparametric\\kde.py:487: RuntimeWarning: invalid value encountered in true_divide\n binned = fast_linbin(X, a, b, gridsize) / (delta * nobs)\nC:\\Users\\nagar\\Anaconda3\\lib\\site-packages\\statsmodels\\nonparametric\\kdetools.py:34: RuntimeWarning: invalid value encountered in double_scalars\n FAC1 = 2*(np.pi*bw/RANGE)**2\n" ] ], [ [ "The pairplot shows that the data is not linear and KNN can be applied to get nearest neighbors and classify the glass types", "_____no_output_____" ], [ "## Feature Scaling ", "_____no_output_____" ], [ "Scaling is necessary for distance-based algorithms such as KNN.\nThis is to avoid higher weightage being assigned to data with a higher magnitude.\n\nUsing standard scaler we can scale down to unit variance.\n\n**Formula:**\n\nz = (x - u) / s\n\nwhere x -> value, u -> mean, s -> standard deviation\n\n\n", "_____no_output_____" ] ], [ [ "scaler = StandardScaler()\n", "_____no_output_____" ], [ "scaler.fit(df.drop('Type',axis=1))", "_____no_output_____" ], [ "#perform transformation\nscaled_features = scaler.transform(df.drop('Type',axis=1))\nscaled_features\n", "_____no_output_____" ], [ "df_feat = pd.DataFrame(scaled_features,columns=df.columns[:-1])\ndf_feat.head()", "_____no_output_____" ] ], [ [ "## Applying KNN", "_____no_output_____" ], [ "- Drop features that are not required\n- Use random state while splitting the data to ensure reproducibility and consistency\n- Experiment with distance metrics - Euclidean, manhattan", "_____no_output_____" ] ], [ [ "dff = df_feat.drop(['Ca','K'],axis=1) #Removing features - Ca and K \nX_train,X_test,y_train,y_test = train_test_split(dff,df['Type'],test_size=0.3,random_state=45) #setting random state ensures split is same eveytime, so that the results are comparable", "_____no_output_____" ], [ "knn = KNeighborsClassifier(n_neighbors=4,metric='manhattan')", "_____no_output_____" ], [ "knn.fit(X_train,y_train)", "_____no_output_____" ], [ "y_pred = knn.predict(X_test)", "_____no_output_____" ], [ "print(classification_report(y_test,y_pred))", " precision recall f1-score support\n\n 1 0.69 0.90 0.78 20\n 2 0.85 0.65 0.74 26\n 3 0.00 0.00 0.00 3\n 5 0.25 1.00 0.40 1\n 6 0.50 0.50 0.50 2\n 7 1.00 0.85 0.92 13\n\n accuracy 0.74 65\n macro avg 0.55 0.65 0.56 65\nweighted avg 0.77 0.74 0.74 65\n\n" ], [ "accuracy_score(y_test,y_pred)", "_____no_output_____" ] ], [ [ "### Finding the best K value\nWe can do this either -\n- by plotting Accuracy\n- or by plotting the error rate\n\nNote that plotting both is not required, both are plottted to show as an example.", "_____no_output_____" ] ], [ [ "k_range = range(1,25)\nk_scores = []\nerror_rate =[]\nfor k in k_range:\n knn = KNeighborsClassifier(n_neighbors=k)\n #kscores - accuracy\n scores = cross_val_score(knn,dff,df['Type'],cv=5,scoring='accuracy')\n k_scores.append(scores.mean())\n \n #error rate\n knn.fit(X_train,y_train)\n y_pred = knn.predict(X_test)\n error_rate.append(np.mean(y_pred!=y_test))\n\n#plot k vs accuracy\nplt.plot(k_range,k_scores)\nplt.xlabel('value of k - knn algorithm')\nplt.ylabel('Cross validated accuracy score')\nplt.show()\n\n#plot k vs error rate\nplt.plot(k_range,error_rate)\nplt.xlabel('value of k - knn algorithm')\nplt.ylabel('Error rate')\nplt.show()\n\n\n\n", "_____no_output_____" ] ], [ [ "we can see that k=4 produces the most accurate results", "_____no_output_____" ], [ "## Findings -\n- Manhattan distance produced better results (improved accuracy - more than 5%)\n- Applying feature scaling improved accuracy by almost 5%.\n- The best k value was found to be 4.\n- Dropping Ca produced better results by a bit, K value did not affect results in any way.\n- Also, we noticed that RI and Ca are highly correlated, \n this makes sense as it was found that the Refractive index of glass was found to increase with the increase in Cao. (https://link.springer.com/article/10.1134/S1087659614030249)\n ", "_____no_output_____" ], [ "## Further improvements - \n\nWe can see that the model can be improved further so we get better accuracy. Some suggestions - \n- Using KFold Cross-validation\n- Try different algorithms to find the best one for this problem - (SVM, Random forest, etc)\n", "_____no_output_____" ], [ "## Other Useful resources - \n- [K Nearest Neighbour Easily Explained with Implementation by Krish Naik - video](https://www.youtube.com/watch?v=wTF6vzS9fy4)\n- [KNN by sentdex -video](https://www.youtube.com/watch?v=1i0zu9jHN6U)\n- [KNN sklearn - docs ](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html)\n- [Complete guide to K nearest neighbours - python and R - blog](https://kevinzakka.github.io/2016/07/13/k-nearest-neighbor/)\n- [Why scaling is required in KNN and K-Means - blog](https://medium.com/analytics-vidhya/why-is-scaling-required-in-knn-and-k-means-8129e4d88ed7)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]