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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb051e187feab392eaeee8560ecdbc6af905d5ec | 5,019 | ipynb | Jupyter Notebook | t81_558_class_07_1_gan_intro.ipynb | napo178/Machine-Learning- | 8e718b026f0c3fb0151a6ff06fa3c62063ddab78 | [
"Apache-2.0"
] | 4,721 | 2016-08-02T02:04:07.000Z | 2022-03-31T23:18:54.000Z | t81_558_class_07_1_gan_intro.ipynb | alialahyari/t81_558_deep_learning | ead7950b12b64bc22839201d71e1fac363eee4b5 | [
"Apache-2.0"
] | 133 | 2016-11-25T12:50:10.000Z | 2022-03-31T20:24:10.000Z | t81_558_class_07_1_gan_intro.ipynb | alialahyari/t81_558_deep_learning | ead7950b12b64bc22839201d71e1fac363eee4b5 | [
"Apache-2.0"
] | 2,627 | 2016-09-05T23:41:32.000Z | 2022-03-31T16:12:27.000Z | 54.554348 | 762 | 0.707113 | [
[
[
"<a href=\"https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_1_gan_intro.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# T81-558: Applications of Deep Neural Networks\n**Module 7: Generative Adversarial Networks**\n* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)\n* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).",
"_____no_output_____"
],
[
"# Module 7 Material\n\n* **Part 7.1: Introduction to GANS for Image and Data Generation** [[Video]](https://www.youtube.com/watch?v=0QnCH6tlZgc&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_1_gan_intro.ipynb)\n* Part 7.2: Implementing a GAN in Keras [[Video]](https://www.youtube.com/watch?v=T-MCludVNn4&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_2_Keras_gan.ipynb)\n* Part 7.3: Face Generation with StyleGAN and Python [[Video]](https://www.youtube.com/watch?v=s1UQPK2KoBY&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_3_style_gan.ipynb)\n* Part 7.4: GANS for Semi-Supervised Learning in Keras [[Video]](https://www.youtube.com/watch?v=ZPewmEu7644&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_4_gan_semi_supervised.ipynb)\n* Part 7.5: An Overview of GAN Research [[Video]](https://www.youtube.com/watch?v=cvCvZKvlvq4&list=PLjy4p-07OYzulelvJ5KVaT2pDlxivl_BN) [[Notebook]](https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_07_5_gan_research.ipynb)\n",
"_____no_output_____"
],
[
"# Part 7.1: Introduction to GANS for Image and Data Generation\n\nA generative adversarial network (GAN) is a class of machine learning systems invented by Ian Goodfellow in 2014. [[Cite:goodfellow2014generative]](https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf) Two neural networks contest with each other in a game. Given a training set, this technique learns to generate new data with the same statistics as the training set. For example, a GAN trained on photographs can generate new photographs that look at least superficially authentic to human observers, having many realistic characteristics. Though originally proposed as a form of generative model for unsupervised learning, GANs have also proven useful for semi-supervised learning, fully supervised learning, and reinforcement learning. \n\nThis paper used neural networks to automatically generate images for several datasets that we've seen previously: MINST and CIFAR. However, it also included the Toronto Face Dataset (a private dataset used by some researchers). These generated images are given in Figure 7.GANS.\n\n**Figure 7.GANS: GAN Generated Images**\n\n\nOnly sub-figure D made use of convolutional neural networks. Figures A-C make use of fully connected neural networks. As we will see in this module, the role of convolutional neural networks with GANs was greatly increased.\n\nA GAN is called a generative model because it generates new data. The overall process of a GAN is given by the following diagram in Figure 7.GAN-FLOW.\n\n**Figure 7.GAN-FLOW: GAN Structure**\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb052c2560d8e6797090c6edc8c01fd5ef9748dd | 22,988 | ipynb | Jupyter Notebook | 6_genome_integration/3_parsing_magi_output.ipynb | nathaliagg/oak_metabolomics | d42a92e67b2b85575cfee6e8bfa4e8d48d4f204e | [
"MIT"
] | null | null | null | 6_genome_integration/3_parsing_magi_output.ipynb | nathaliagg/oak_metabolomics | d42a92e67b2b85575cfee6e8bfa4e8d48d4f204e | [
"MIT"
] | null | null | null | 6_genome_integration/3_parsing_magi_output.ipynb | nathaliagg/oak_metabolomics | d42a92e67b2b85575cfee6e8bfa4e8d48d4f204e | [
"MIT"
] | null | null | null | 36.201575 | 815 | 0.460023 | [
[
[
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Import-libraries\" data-toc-modified-id=\"Import-libraries-1\"><span class=\"toc-item-num\">1 </span>Import libraries</a></span></li><li><span><a href=\"#Understanding-MAGI-output\" data-toc-modified-id=\"Understanding-MAGI-output-2\"><span class=\"toc-item-num\">2 </span>Understanding MAGI output</a></span></li><li><span><a href=\"#My-approach-to-magi_results.csv\" data-toc-modified-id=\"My-approach-to-magi_results.csv-3\"><span class=\"toc-item-num\">3 </span>My approach to magi_results.csv</a></span></li><li><span><a href=\"#Get-MetaCyc-compound-ids\" data-toc-modified-id=\"Get-MetaCyc-compound-ids-4\"><span class=\"toc-item-num\">4 </span>Get MetaCyc compound ids</a></span></li></ul></div>",
"_____no_output_____"
],
[
"# Import libraries",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"# Understanding MAGI output\n\nExplanation of [MAGI output](https://magi.nersc.gov/help/#outputs), and what to do with [magi_results.csv](https://magi.nersc.gov/tutorial/#step4-4)\n\n- `compound_score` == if user doesn't provide a score, this will be 1.0\n- `level` describes how far into the chemical similarity network MAGI went to connect the compound to the gene\n - a value of 1 == used chemical network similarity\n - a value of 0 == chemical network was not used\n - no value == no compound associated with the gene\n- `homology_score` reciprocal homology score between the reaction in `database_id_r2g` and the gene.\n - a value of 400 is the maximum possible homology score, which means that both compound and genes were connected to the reaction with perfect homology\n- `reciprocal_score` is a direct representation of whether or not the reaction-to-gene and gene-to-reaction homology searches converged on the same reactions or not, and it is determined by using the top BLAST result\n - a value of 2 == reciprocal agreement\n - a value of 1 == reciprocal closeness because the E-score was close enough\n - a value of 0.1 == only one of the two searches resulted in a reaction\n - a value of 0.01 == no reciprocal agreement\n- `database_id_g2r` == reactions that a gene product can catalyze, which mean a gene-centric view\n- `database_id_r2g` == reactions that associated with both gene and compound, which means a compound-centric view\n\n\nThere are three approaches to explore results:\n\n1. Stich biochemical pathways. Filter the table to only show rows pertaining to a compound, look at the `database_id_r2g` for all the reactions, and `gene_id` for a list of genes associated with that compound\n\n2. Curating a metabolic model:\n 1. To see all the compounds a gene was connected to: filter the table to only show one gene, and look at the `database_id_g2r`\n 2. To see all the evidence for a particular biochemical reaction: filter the `database_id_g2r` or `database_id_r2g` to only show one reaction, and see all the compounds of that reaction were observed as well as genes associated with that reaction\n \n \n------------\n\n# My approach to magi_results.csv\n\nMy approach will be to:\n\n1. filter based on `MAGI_score` > 1, `homology_score` == 400, `reciprocal_score` > 1, and `note` column == direct\n2. filter based on gene-compound direct associations (when the `neighbor` column is empty), and indirect association (when `neighbor` column is not empty and note == direct)",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('magi_output/magi_results.csv')\n\ndf = df.sort_values('MAGI_score', ascending=False).reset_index(drop=True)\n\nprint(df.shape)\n\ndf['neighbor'] = df['neighbor'].replace(np.nan, '')\n\ndf.head()",
"(183089, 14)\n"
],
[
"# filtering\nsubset_df = df[(df['MAGI_score'] >= 2) & # (df['homology_score'] == 400) &\n (df['reciprocal_score'] >= 1) &\n (df['note'] == 'direct')].reset_index(drop=True)\n\n# getting the feature label from magi_output/magi_compound_result.csv\nft = pd.read_csv('magi_output/magi_compound_results.csv')\nft = ft[['original_compound', 'label']]\n\n# merge\nsubset_df = subset_df.merge(ft, on='original_compound')\n\n# direct association\nsubset_direct = subset_df[subset_df['neighbor'] == \"\"].reset_index(drop=True)\nprint(subset_direct.shape)\nsubset_direct.to_csv('magi_results_direct.csv', index=False)\n\n# indirect association\nsubset_indirect = subset_df[subset_df['neighbor']!=\"\"].reset_index(drop=True)\nprint(subset_indirect.shape)\n# subset_indirect.to_csv('magi_results_indirect.csv', index = False)",
"(912, 15)\n(0, 15)\n"
]
],
[
[
"# Get MetaCyc compound ids",
"_____no_output_____"
]
],
[
[
"metacyc = pd.read_csv(\"metacyc/All_compounds_of_MetaCyc.txt\", sep = '\\t')\n\nmetacyc['InChI-Key'] = metacyc['InChI-Key'].str[:-2]\n\nmetacyc",
"_____no_output_____"
],
[
"direct_compounds = subset_direct[['original_compound',\n 'label']].drop_duplicates(\n ['original_compound',\n 'label']).reset_index(drop=True)\n\ndirect_compounds['original_compound'] = \"InChIKey=\" + direct_compounds[\n 'original_compound'].str[:-2]\n\ndirect_compounds = direct_compounds.merge(metacyc,\n left_on='original_compound',\n right_on='InChI-Key')\n\ndirect_compounds.drop('original_compound', axis=1, inplace=True)\n\ndirect_compounds.to_csv('magi_compounds_direct.csv', sep='\\t', index=False)\n\ndirect_compounds",
"_____no_output_____"
]
],
[
[
"Imported this into MetaCyc as a SmartTable.\n\nIn MetaCyc's SmartTable, I added structure, reactions that consume and produce such compounds to be used in the discussion. I then, exported the SmartTable as frame_ids (which retains the compound and reaction identifiers) and common names (with common names of everything).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb053650749e0df7f60ecad464dcf066b4c9fcb4 | 17,915 | ipynb | Jupyter Notebook | notebooks/Doc2Vec With External Corpus Approach.ipynb | Elzawawy/DeftEval | 88d4e7531059cfc87d62119c31308f72ab5f4dc0 | [
"MIT"
] | 7 | 2020-04-06T16:11:56.000Z | 2021-12-09T10:07:21.000Z | notebooks/Doc2Vec With External Corpus Approach.ipynb | Elzawawy/DeftEval | 88d4e7531059cfc87d62119c31308f72ab5f4dc0 | [
"MIT"
] | null | null | null | notebooks/Doc2Vec With External Corpus Approach.ipynb | Elzawawy/DeftEval | 88d4e7531059cfc87d62119c31308f72ab5f4dc0 | [
"MIT"
] | null | null | null | 33.674812 | 818 | 0.554954 | [
[
[
"# **Solving the Definition Extraction Problem**\n",
"_____no_output_____"
],
[
"### **Approach 3: Using Doc2Vec model and Classifiers.**\n\n**Doc2Vec** is a Model that represents each Document as a Vector. The goal of Doc2Vec is to create a numeric representation of a document, regardless of its length. So, the input of texts per document can be various while the output is fixed-length vectors.\nDesign of Doc2Vec is based on Word2Vec. But unlike words, documents do not come in logical structures such as words, so the another method has to be found. There are two implementations:\n\n1. Paragraph Vector - Distributed Memory (PV-DM)\n2. Paragraph Vector - Distributed Bag of Words (PV-DBOW)\n\n**PV-DM** is analogous to Word2Vec continous bag of word CBOW. But instead of using just words to predict the next word, add another feature vector, which is document-unique. So, when training the word vectors W, the document vector D is trained as well, and in the end of training, it holds a numeric representation of the document.\n\n\n\n\n**PV-DBOW** is analogous to Word2Vec skip gram. Instead of predicting next word, it use a document vector to classify entire words in the document.\n\n\n\n\nNot: it's recommend to use a combination of both algorithms to infer the vector representation of a document. \n\n",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n"
],
[
"!unzip 'drive/My Drive/wikipedia-movie-plots.zip'",
"Archive: drive/My Drive/wikipedia-movie-plots.zip\n inflating: wiki_movie_plots_deduped.csv \n"
],
[
"import os\nimport nltk\nimport pandas as pd \nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom data_loader import DeftCorpusLoader\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import tree\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')",
"[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Unzipping tokenizers/punkt.zip.\n[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n[nltk_data] Downloading package wordnet to /root/nltk_data...\n[nltk_data] Unzipping corpora/wordnet.zip.\n"
]
],
[
[
"### **Load Doc2Vec Model Trainning Data**",
"_____no_output_____"
]
],
[
[
"# Load amazon review reports of movies.\nwith open('wiki_movie_plots_deduped.csv') as data:\n corpus_list = pd.read_csv(data, sep=\",\", header = None)\ncorpus_list = corpus_list[7].tolist()[1:]\nprint(\"Corpus legnth: \", len(corpus_list))",
"Corpus legnth: 34886\n"
],
[
"stop_words = set(stopwords.words('english'))\nporter = PorterStemmer()\nqoutes_list = [\"``\", \"\\\"\\\"\", \"''\"]\ntrain_corpus = []\nfor i, sentence in enumerate(corpus_list):\n \n # Lower all the letters in the sentence\n tokens = word_tokenize(sentence.lower())\n processed_tokens = []\n for j, token in enumerate(tokens):\n if not token.isdigit():\n if token not in stop_words and len(token) > 1 and token not in qoutes_list:\n\n # Convert each sentence from amazon reviews to list of words that doesn't include\n # stop words or any special letters or digits\n processed_tokens.append(porter.stem(token))\n train_corpus.append(TaggedDocument(words=processed_tokens, tags=[str(i)]))",
"_____no_output_____"
],
[
"train_corpus[:5]",
"_____no_output_____"
]
],
[
[
"### **Train Doc2Vec Model Based on Amazon Reviews.**\nFirst we will define the attributes of Doc2Vec model:\n\n\n* **Vector Size:** Dimensionality of the documents feature vector.\n* **Min Count:** Ignores all words with total frequency lower than this.\n* **Epochs:** Number of iterations (epochs) over the corpus.\n* **Workers:** Use these many worker threads to train the model (faster training with multicore machines).\n\nSecond build the **Vocabulary** based on the training corpus (processed amazon reviews). Finally train the model on the training corpus.\n\nNote: the default used algorithm is PV-DM.",
"_____no_output_____"
]
],
[
[
"model = Doc2Vec(vector_size=300, min_count=2, epochs=40, workers=8)\nmodel.build_vocab(train_corpus)\nmodel.train(train_corpus, total_examples=model.corpus_count, epochs=model.epochs)",
"_____no_output_____"
]
],
[
[
"### **Load DeftEval Trainning & Dev Data**\n\nNote: as the code is executed on google colab, the path of the data is rooted from the drive. So, the path of the data need to be change if the code will be executed on the local machine.",
"_____no_output_____"
]
],
[
[
"deft_loader = DeftCorpusLoader(\"drive/My Drive/DeftEval/deft_corpus/data\")\ntrainframe, devframe = deft_loader.load_classification_data()",
"_____no_output_____"
],
[
"deft_loader.preprocess_data(devframe)\ndeft_loader.clean_data(devframe)\ndev_vectors = []\n\n# Create test data vectors from Doc2Vec model\nfor parsed_list in devframe[\"Parsed\"]:\n dev_vectors.append(model.infer_vector(parsed_list))",
"_____no_output_____"
],
[
"deft_loader.preprocess_data(trainframe)\ndeft_loader.clean_data(trainframe)\ntrain_vectors=[]\n\n# Create training data vectors from Doc2Vec model\nfor parsed_list in trainframe[\"Parsed\"]:\n train_vectors.append(model.infer_vector(parsed_list))",
"_____no_output_____"
]
],
[
[
"### **Apply Classifiers Algorithms**\n\nFor each classifier test, **F1-score** and **Accuracy** are calculated.",
"_____no_output_____"
],
[
"**1. Naive Bayes Algorithm**",
"_____no_output_____"
]
],
[
[
"gnb = GaussianNB()\ntest_predict = gnb.fit(train_vectors, trainframe['HasDef']).predict(dev_vectors)\nprint(metrics.classification_report(list(devframe[\"HasDef\"]), test_predict))",
" precision recall f1-score support\n\n 0 0.69 0.69 0.69 510\n 1 0.42 0.42 0.42 275\n\n accuracy 0.60 785\n macro avg 0.56 0.56 0.56 785\nweighted avg 0.60 0.60 0.60 785\n\n"
]
],
[
[
"**2. Decision Tree Algorithm**",
"_____no_output_____"
]
],
[
[
"decision_tree = tree.DecisionTreeClassifier(class_weight=\"balanced\")\ntest_predict = decision_tree.fit(train_vectors, trainframe['HasDef']).predict(dev_vectors)\nprint(metrics.classification_report(list(devframe[\"HasDef\"]), test_predict))",
" precision recall f1-score support\n\n 0 0.68 0.72 0.70 510\n 1 0.42 0.38 0.40 275\n\n accuracy 0.60 785\n macro avg 0.55 0.55 0.55 785\nweighted avg 0.59 0.60 0.60 785\n\n"
]
],
[
[
"**3. Logistic Regression Algorithm**",
"_____no_output_____"
]
],
[
[
"test_predict = LogisticRegression(class_weight=\"balanced\", random_state=0).fit(train_vectors, trainframe['HasDef']).predict(dev_vectors)\nprint(metrics.classification_report(list(devframe[\"HasDef\"]), test_predict))",
" precision recall f1-score support\n\n 0 0.74 0.69 0.72 510\n 1 0.49 0.55 0.52 275\n\n accuracy 0.64 785\n macro avg 0.61 0.62 0.62 785\nweighted avg 0.65 0.64 0.65 785\n\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb0577e3143760c1b8a1e1fda33d13a66b9a01e5 | 270,151 | ipynb | Jupyter Notebook | models/pa005_insiders_deploy.ipynb | heitorfe/insiders_clustering | b2919167b87864948800cc74348c9940113c7eb7 | [
"MIT"
] | null | null | null | models/pa005_insiders_deploy.ipynb | heitorfe/insiders_clustering | b2919167b87864948800cc74348c9940113c7eb7 | [
"MIT"
] | null | null | null | models/pa005_insiders_deploy.ipynb | heitorfe/insiders_clustering | b2919167b87864948800cc74348c9940113c7eb7 | [
"MIT"
] | null | null | null | 125.476544 | 206,932 | 0.857743 | [
[
[
"# PA005: High Value Customer Identification (Insiders)",
"_____no_output_____"
],
[
"# 0.0. Imports",
"_____no_output_____"
]
],
[
[
"from sklearn import cluster as c\nfrom sklearn import metrics as m\nfrom sklearn import preprocessing as pp\nfrom sklearn import decomposition as dd\nfrom sqlalchemy import create_engine\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\nimport re\nimport boto3\nfrom sklearn.manifold import TSNE\nfrom matplotlib import pyplot as plt\n\n",
"_____no_output_____"
]
],
[
[
"## 0.2. Helper Functions",
"_____no_output_____"
]
],
[
[
"def num_attributes(df1):\n \n num_attributes = df1.select_dtypes(['int64', 'float64'])\n\n #central tendency\n ct1 = pd.DataFrame(num_attributes.apply(np.mean)).T\n ct2 = pd.DataFrame(num_attributes.apply(np.median)).T\n\n #dispersion\n d1 = pd.DataFrame(num_attributes.apply(np.min)).T\n d2 = pd.DataFrame(num_attributes.apply(np.max)).T\n d3 = pd.DataFrame(num_attributes.apply(lambda x: x.max() - x.min())).T\n d4 = pd.DataFrame(num_attributes.apply(np.std)).T\n d5 = pd.DataFrame(num_attributes.apply(lambda x: x.skew())).T\n d6 = pd.DataFrame(num_attributes.apply(lambda x: x.kurtosis())).T\n\n m = pd.concat( [d1, d2, d3, ct1, ct2, d4, d5, d6] ).T.reset_index()\n m.columns = ['attributes', 'min', 'max', 'range', 'mean', 'median', 'std','skew', 'kurtosis']\n return m",
"_____no_output_____"
]
],
[
[
"## 0.3. Load Data",
"_____no_output_____"
]
],
[
[
"s3 = boto3.resource(\n service_name='s3',\n region_name='us-east-2',\n aws_access_key_id='AKIAU4UCEADPNRXISEJV',\n aws_secret_access_key='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'\n)\n\n# # path_s3='s3://insiders-dataset-heitor'\n# # df_raw = pd.read_csv(path_s3 + 'Ecommerce.csv')\n# for bucket in s3.buckets.all():\n# print(bucket.name)\n \nobj = s3.Bucket('insiders-dataset-heitor').Object('Ecommerce.csv').get()\ndf_raw = pd.read_csv(obj['Body'], index_col=0)",
"insiders-dataset-heitor\n"
],
[
"df_raw.head()",
"_____no_output_____"
]
],
[
[
"# 1.0. Data Description",
"_____no_output_____"
]
],
[
[
"df1 = df_raw.reset_index().copy()",
"_____no_output_____"
]
],
[
[
"## 1.1. Rename Columns",
"_____no_output_____"
]
],
[
[
"df1.columns = ['invoice_no', 'stock_code', 'description', 'quantity', 'invoice_date',\n 'unit_price', 'customer_id', 'country']",
"_____no_output_____"
]
],
[
[
"## 1.2. Data Shape",
"_____no_output_____"
]
],
[
[
"print(f'Number of rows: {df1.shape[0]}')\nprint(f'Number of columns: {df1.shape[1]}')",
"Number of rows: 541909\nNumber of columns: 8\n"
]
],
[
[
"## 1.3. Data Types",
"_____no_output_____"
]
],
[
[
"df1.dtypes",
"_____no_output_____"
]
],
[
[
"## 1.4. Check NAs\n",
"_____no_output_____"
]
],
[
[
"df1.isna().sum()",
"_____no_output_____"
]
],
[
[
"## 1.5. Fill NAs",
"_____no_output_____"
]
],
[
[
"#remove na\ndf_missing = df1[df1['customer_id'].isna()]\ndf_not_missing = df1[-df1['customer_id'].isna()]\n\n",
"_____no_output_____"
],
[
"len(df_missing)",
"_____no_output_____"
],
[
"len(df_not_missing)",
"_____no_output_____"
],
[
"#create reference\ndf_backup = pd.DataFrame(df_missing['invoice_no'].drop_duplicates())\ndf_backup['customer_id'] = np.arange(19000, 19000+len(df_backup),1)\n\n#merge\ndf1 = pd.merge(df1, df_backup, on='invoice_no', how='left')\n\n#coalesce\ndf1['customer_id'] = df1['customer_id_x'].combine_first(df1['customer_id_y'])\n\n#drop extra columns\ndf1 = df1.drop(['customer_id_x', 'customer_id_y'], axis=1)\n\n\n",
"_____no_output_____"
],
[
"df1.isna().sum()",
"_____no_output_____"
]
],
[
[
"## 1.6. Change dtypes",
"_____no_output_____"
]
],
[
[
"df1.dtypes",
"_____no_output_____"
],
[
"#invoice_no \n# df1['invoice_no'] = df1['invoice_no'].astype(int)\n\n\n#stock_code \n# df1['stock_code'] = df1['stock_code'].astype(int)\n\n\n#invoice_date --> Month --> b\ndf1['invoice_date'] = pd.to_datetime(df1['invoice_date'], format=('%d-%b-%y'))\n\n\n#customer_id\ndf1['customer_id'] = df1['customer_id'].astype(int)\ndf1.dtypes",
"_____no_output_____"
]
],
[
[
"## 1.7. Descriptive statistics",
"_____no_output_____"
]
],
[
[
"\ncat_attributes = df1.select_dtypes(exclude = ['int64', 'float64', 'datetime64[ns]'])",
"_____no_output_____"
]
],
[
[
"### 1.7.1. Numerical Attributes",
"_____no_output_____"
]
],
[
[
"m1 = num_attributes(df1)\nm1",
"_____no_output_____"
]
],
[
[
"#### 1.7.1.1 Investigating",
"_____no_output_____"
],
[
"1. Negative quantity (devolution?)\n2. Price = 0 (Promo?)",
"_____no_output_____"
],
[
"## 1.7.2. Categorical Attributes",
"_____no_output_____"
]
],
[
[
"cat_attributes.head()",
"_____no_output_____"
]
],
[
[
"#### Invoice no",
"_____no_output_____"
]
],
[
[
"\n#invoice_no -- some of them has one char\ndf_invoice_char = df1.loc[df1['invoice_no'].apply(lambda x: bool(re.search('[^0-9]+', x))), :] \n\nlen(df_invoice_char[df_invoice_char['quantity']<0])\n\n\nprint('Total of invoices with letter: {}'.format(len(df_invoice_char)))\nprint('Total of negative quantaty: {}'.format(len(df1[df1['quantity']<0])))\nprint('Letter means negative quantity')",
"Total of invoices with letter: 9291\nTotal of negative quantaty: 10624\nLetter means negative quantity\n"
]
],
[
[
"#### Stock Code",
"_____no_output_____"
]
],
[
[
"#all stock codes with char\ndf1.loc[df1['stock_code'].apply(lambda x: bool(re.search('^[a-zA-Z]+$', x))), 'stock_code'].unique()\n\n#remove stock code in ['POST', 'D', 'M', 'PADS', 'DOT', 'CRUK']\n# df1 = df1[-df1.isin(['POST', 'D', 'M', 'PADS', 'DOT', 'CRUK'])]",
"_____no_output_____"
]
],
[
[
"#### Description",
"_____no_output_____"
]
],
[
[
"df1.head(2) #remove description\n",
"_____no_output_____"
]
],
[
[
"#### Country\n",
"_____no_output_____"
]
],
[
[
"df1['country'].value_counts(normalize='True').head()",
"_____no_output_____"
],
[
"df1[['country', 'customer_id']].drop_duplicates().groupby('country').count().reset_index().sort_values('customer_id', ascending=False).head()",
"_____no_output_____"
]
],
[
[
"# 2.0. Data Filtering",
"_____no_output_____"
]
],
[
[
"df2 = df1.copy()",
"_____no_output_____"
],
[
" # === Numerical attributes ====\ndf2 = df2.loc[df2['unit_price'] >= 0.04, :]\n\n# === Categorical attributes ====\ndf2 = df2[~df2['stock_code'].isin( ['POST', 'D', 'DOT', 'M', 'S', 'AMAZONFEE', 'm', 'DCGSSBOY', 'DCGSSGIRL', 'PADS', 'B', 'CRUK'] ) ]\n\n# description\ndf2 = df2.drop( columns='description', axis=1 )\n\n# map - \ndf2 = df2[~df2['country'].isin( ['European Community', 'Unspecified' ] ) ]\n\n# bad users\ndf2 = df2[~df2['customer_id'].isin( [16446] )]\n\n# quantity\ndf_returns = df2.loc[df1['quantity'] < 0, :]\ndf_purchase = df2.loc[df1['quantity'] >= 0, :]",
"_____no_output_____"
]
],
[
[
"# 3.0. Feature Engineering",
"_____no_output_____"
]
],
[
[
"df3 = df2.copy()",
"_____no_output_____"
]
],
[
[
"## 3.1. Feature Creation",
"_____no_output_____"
]
],
[
[
"# data reference\ndf_ref = df3.drop( ['invoice_no', 'stock_code', 'quantity', 'invoice_date', 'unit_price', 'country'], axis=1 ).drop_duplicates( ignore_index=True )\n\n",
"_____no_output_____"
]
],
[
[
"### 3.1.1. Gross Revenue",
"_____no_output_____"
]
],
[
[
"#calculate gross revenue\ndf_purchase.loc[:,'gross_revenue'] = df_purchase.loc[:, 'quantity'] * df_purchase.loc[:, 'unit_price'] \n\n#gross revenue by customer\ndf_monetary = df_purchase.loc[:,['customer_id', 'gross_revenue']].groupby('customer_id').sum().reset_index()\ndf_ref = pd.merge(df_ref, df_monetary, on='customer_id', how= 'left')\ndf_ref.isna().sum()\n\n",
"/tmp/ipykernel_17484/3123439491.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n df_purchase.loc[:,'gross_revenue'] = df_purchase.loc[:, 'quantity'] * df_purchase.loc[:, 'unit_price']\n"
]
],
[
[
"### 3.1.2. Recency - Days from last purchase\n",
"_____no_output_____"
]
],
[
[
"#recency \n\ndf_recency = df_purchase.loc[:,['customer_id', 'invoice_date']].groupby('customer_id').max().reset_index()\ndf_recency['recency_days'] = (df3['invoice_date'].max() - df_recency['invoice_date']).dt.days\ndf_recency = df_recency[['customer_id', 'recency_days']].copy()\ndf_ref = pd.merge(df_ref, df_recency, on='customer_id', how='left')\n",
"_____no_output_____"
]
],
[
[
"### 3.1.4. Quantity of purchase",
"_____no_output_____"
]
],
[
[
"\n# Número de compras\ndf_invoice = df_purchase.loc[:,['customer_id', 'invoice_no']].drop_duplicates().groupby('customer_id').count().reset_index().rename(columns={'invoice_no':'qt_invoice'})\ndf_ref = pd.merge(df_ref, df_invoice, on='customer_id', how='left')\n",
"_____no_output_____"
]
],
[
[
"### 3.1.4. Quantity of products purchase",
"_____no_output_____"
]
],
[
[
"# Número de compras\ndf_stock_code = df_purchase.loc[:,['customer_id', 'stock_code']].groupby('customer_id').count().reset_index().rename(columns={'stock_code':'qt_products'})\ndf_ref = pd.merge(df_ref, df_stock_code, on='customer_id', how='left')\n",
"_____no_output_____"
]
],
[
[
"### 3.1.6. Frequency",
"_____no_output_____"
]
],
[
[
"df_aux = (df_purchase[['customer_id', 'invoice_no', 'invoice_date']].drop_duplicates().groupby('customer_id').agg(\n max_ = ('invoice_date', 'max'),\n min_ = ('invoice_date', 'min'),\n days = ('invoice_date', lambda x: (x.max() - x.min()).days ),\n buys = ('invoice_no', 'count'))).reset_index()\n\n# #calculate frequency\ndf_aux['frequency'] = df_aux[['buys', 'days']].apply(lambda x: x['buys']/x['days'] if x['days']!= 0 else 0, axis=1)\n\n\n#merge\ndf_ref = pd.merge(df_ref, df_aux[['customer_id', 'frequency']], on='customer_id', how='left')\n",
"_____no_output_____"
]
],
[
[
"### 3.1.7. Returns\n",
"_____no_output_____"
]
],
[
[
"df_aux = df_returns[['customer_id', 'quantity']].groupby('customer_id').sum().reset_index().rename(columns={'quantity':'qt_returns'})\ndf_aux['qt_returns'] = -1*df_aux['qt_returns']\n#merge\ndf_ref = pd.merge(df_ref, df_aux, on='customer_id', how='left')\n\ndf_ref.loc[df_ref['qt_returns'].isna(), 'qt_returns'] = 0\n",
"_____no_output_____"
]
],
[
[
"# 4.0. Exploratory Data Analisys",
"_____no_output_____"
]
],
[
[
"df_ref.isna().sum()",
"_____no_output_____"
],
[
"df4 = df_ref.dropna()\n",
"_____no_output_____"
]
],
[
[
"## 4.3. Estudo do Espaço",
"_____no_output_____"
]
],
[
[
"# selected dataset\ncols_selected = ['customer_id', 'gross_revenue', 'recency_days', 'qt_products', 'frequency', 'qt_returns']\ndf43 = df4[ cols_selected ].drop( columns='customer_id', axis=1 ).copy() ",
"_____no_output_____"
],
[
"mm = pp.MinMaxScaler()\n\ndf43['gross_revenue'] = mm.fit_transform( df43[['gross_revenue']] )\ndf43['recency_days'] = mm.fit_transform( df43[['recency_days']] )\ndf43['qt_products'] = mm.fit_transform( df43[['qt_products']])\ndf43['frequency'] = mm.fit_transform( df43[['frequency']])\ndf43['qt_returns'] = mm.fit_transform( df43[['qt_returns']])",
"_____no_output_____"
]
],
[
[
"### PCA ",
"_____no_output_____"
]
],
[
[
"\nX=df43.copy()\npca = dd.PCA( n_components=X.shape[1] )\n\nprincipal_components = pca.fit_transform( X )\n\n# plot explained variable\nfeatures = range( pca.n_components_ )\n\nplt.bar( features, pca.explained_variance_ratio_, color='black' )\n\n# pca component\ndf_pca = pd.DataFrame( principal_components )",
"_____no_output_____"
]
],
[
[
"### TSNE",
"_____no_output_____"
]
],
[
[
"reducer = TSNE( n_components=2,n_jobs=-1, random_state=3)\nembedding = reducer.fit_transform(X)\n\ndf_tsne = pd.DataFrame()\ndf_tsne['embedding_x'] = embedding[:,0]\ndf_tsne['embedding_y'] = embedding[:,1]\nplt.figure(figsize=(20,12));\nsns.scatterplot(x='embedding_x', y='embedding_y',data=df_tsne);",
"/home/heitor/repos/insiders_clustering/venv/lib/python3.8/site-packages/sklearn/manifold/_t_sne.py:780: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2.\n warnings.warn(\n/home/heitor/repos/insiders_clustering/venv/lib/python3.8/site-packages/sklearn/manifold/_t_sne.py:790: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2.\n warnings.warn(\n"
]
],
[
[
"## 8.2. GMM",
"_____no_output_____"
]
],
[
[
"# model definition\nk = 8\nX=df43.copy()\n\n#model definition\nkmeans_model = c.KMeans(n_clusters=k, random_state=42)\n\n#model training\nkmeans_model.fit(X)\n\n#model predict\nlabels = kmeans_model.predict(X)\n\n#model performance\nsil = m.silhouette_score(X, labels, metric='euclidean')\n\n\n",
"_____no_output_____"
],
[
"m.silhouette_score(X, labels, metric='euclidean')",
"_____no_output_____"
]
],
[
[
"# 9.0. Cluster Analisys",
"_____no_output_____"
]
],
[
[
"cols_selected = ['customer_id', 'gross_revenue', 'recency_days', 'qt_products', 'frequency', 'qt_returns']\ndf9 = X.copy()\ndf9['cluster'] = labels\n",
"_____no_output_____"
]
],
[
[
"## 9.2. Cluster Profile",
"_____no_output_____"
]
],
[
[
"\ndf92 = df4[cols_selected].copy()\n\n\ndf92['cluster']= labels\n\n # Number of customer\ndf_cluster = df92[['customer_id', 'cluster']].groupby( 'cluster' ).count().reset_index()\ndf_cluster['perc_customer'] = 100*( df_cluster['customer_id'] / df_cluster['customer_id'].sum() )\n\n# Avg Gross revenue\ndf_avg_gross_revenue = df92[['gross_revenue', 'cluster']].groupby( 'cluster' ).mean().reset_index().rename(columns={'gross_revenue': 'avg_gmv'})\ndf_cluster = pd.merge( df_cluster, df_avg_gross_revenue, how='inner', on='cluster' )\n\n\n# Sum Gross revenue\ndf_avg_gross_revenue = df92[['gross_revenue', 'cluster']].groupby( 'cluster' ).sum().reset_index().rename(columns={'gross_revenue': 'total_gmv'})\ndf_cluster = pd.merge( df_cluster, df_avg_gross_revenue, how='inner', on='cluster' )\n\n# Avg recency days\ndf_avg_recency_days = df92[['recency_days', 'cluster']].groupby( 'cluster' ).mean().reset_index()\ndf_cluster = pd.merge( df_cluster, df_avg_recency_days, how='inner', on='cluster' )\n\n# Avg products\ndf_qtde_products = df92[['qt_products', 'cluster']].groupby( 'cluster' ).mean().reset_index().rename(columns={'qt_products': 'avg_products'})\ndf_cluster = pd.merge( df_cluster, df_qtde_products, how='inner', on='cluster' )\n\n# total products\ndf_qtde_products = df92[['qt_products', 'cluster']].groupby( 'cluster' ).sum().reset_index().rename(columns={'qt_products': 'total_products'})\ndf_cluster = pd.merge( df_cluster, df_qtde_products, how='inner', on='cluster' )\n\n# Frequency\ndf_frequency = df92[['frequency', 'cluster']].groupby( 'cluster' ).mean().reset_index()\ndf_cluster = pd.merge( df_cluster, df_frequency, how='inner', on='cluster' )\n\n# Returns avg\ndf_qtde_returns = df92[['qt_returns', 'cluster']].groupby( 'cluster' ).mean().reset_index().rename(columns={'gross_revenue': 'avg_returns'})\ndf_cluster = pd.merge( df_cluster, df_qtde_returns, how='inner', on='cluster' )\n\n# # Returns total\n# df_qtde_returns = df92[['qt_returns', 'cluster']].groupby( 'cluster' ).sum().reset_index().rename(columns={'gross_revenue': 'avg_returns'})\n# df_cluster = pd.merge( df_cluster, df_qtde_returns, how='inner', on='cluster' )\n\n# # Returns total\n# df_qtde_returns = df92[['qt_returns', 'cluster']].groupby( 'cluster' ).sum().reset_index().rename(columns={'gross_revenue': 'total_returns'})\n# df_cluster = pd.merge( df_cluster, df_qtde_returns, how='inner', on='cluster' )\n\ndf_cluster.sort_values( 'avg_gmv', ascending=False )\n",
"_____no_output_____"
],
[
"#Cluster 7 : Insider\n#Cluster 2 : More frequency\n#Cluster 0 : Lazy\n#Cluster 5 : Hibernating (High recency)\n#Cluster 4 : More products\n#Cluster 6 : Forgotten\n#Cluster 3 : Lost\n#Cluster 1 : One-time customer",
"_____no_output_____"
]
],
[
[
"# 10.0. Deploy to Production",
"_____no_output_____"
]
],
[
[
"df10 = df4[cols_selected].copy()\ndf10['cluster'] = labels\n\ndf10['recency_days'] = df10['recency_days'].astype(int)\ndf10['qt_products'] = df10['qt_products'].astype(int)\ndf10['qt_returns'] = df10['qt_returns'].astype(int)\ndf10['cluster'] = df10['cluster'].astype(int)\ndf10.dtypes",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb0578b709746e4b7221023cfeba4414e29b109e | 32,755 | ipynb | Jupyter Notebook | plang/ipynb/watermelon/chp6.ipynb | staugust/staugust.github.io | 270cde728443893c5e17180dc1463d17468636da | [
"Apache-2.0"
] | null | null | null | plang/ipynb/watermelon/chp6.ipynb | staugust/staugust.github.io | 270cde728443893c5e17180dc1463d17468636da | [
"Apache-2.0"
] | null | null | null | plang/ipynb/watermelon/chp6.ipynb | staugust/staugust.github.io | 270cde728443893c5e17180dc1463d17468636da | [
"Apache-2.0"
] | 1 | 2017-12-06T06:30:13.000Z | 2017-12-06T06:30:13.000Z | 141.185345 | 21,514 | 0.859838 | [
[
[
"from matplotlib import pyplot as plt\nfrom mpl_toolkits import axisartist\nimport numpy as np",
"_____no_output_____"
],
[
"np.random.seed(12345678)\nx1 = np.random.normal(0.5,0.5,20)\ny1 = x1 + np.random.normal(0.5,0.2,20)\nx2 = np.random.normal(1.5,0.5,20)\ny2 = x2 - np.random.normal(0.5,0.2,20)\nlx = np.linspace(-0.5,2.5,20) \nly1 = lx * 1.2 - 0.2\nly2 = lx * 0.9 + 0.2\nly3 = lx ",
"_____no_output_____"
],
[
"plt.scatter(x1,y1, marker=\"+\")\nplt.scatter(x2,y2,marker=\"_\")\nplt.plot(lx,ly1)\nplt.plot(lx,ly2)\nplt.plot(lx,ly3)\n\nax = plt.gca().axes\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\nplt.show()",
"_____no_output_____"
],
[
"axis = ax.axis['left']",
"_____no_output_____"
],
[
"fig.axes()",
"_____no_output_____"
],
[
"help(plt.axis)",
"Help on function axis in module matplotlib.pyplot:\n\naxis(*v, **kwargs)\n Convenience method to get or set axis properties.\n \n Calling with no arguments::\n \n >>> axis()\n \n returns the current axes limits ``[xmin, xmax, ymin, ymax]``.::\n \n >>> axis(v)\n \n sets the min and max of the x and y axes, with\n ``v = [xmin, xmax, ymin, ymax]``.::\n \n >>> axis('off')\n \n turns off the axis lines and labels.::\n \n >>> axis('equal')\n \n changes limits of *x* or *y* axis so that equal increments of *x*\n and *y* have the same length; a circle is circular.::\n \n >>> axis('scaled')\n \n achieves the same result by changing the dimensions of the plot box instead\n of the axis data limits.::\n \n >>> axis('tight')\n \n changes *x* and *y* axis limits such that all data is shown. If\n all data is already shown, it will move it to the center of the\n figure without modifying (*xmax* - *xmin*) or (*ymax* -\n *ymin*). Note this is slightly different than in MATLAB.::\n \n >>> axis('image')\n \n is 'scaled' with the axis limits equal to the data limits.::\n \n >>> axis('auto')\n \n and::\n \n >>> axis('normal')\n \n are deprecated. They restore default behavior; axis limits are automatically\n scaled to make the data fit comfortably within the plot box.\n \n if ``len(*v)==0``, you can pass in *xmin*, *xmax*, *ymin*, *ymax*\n as kwargs selectively to alter just those limits without changing\n the others.\n \n >>> axis('square')\n \n changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of\n the *x* and *y* axes to be the same, and have the same scaling,\n resulting in a square plot.\n \n The xmin, xmax, ymin, ymax tuple is returned\n \n .. seealso::\n \n :func:`xlim`, :func:`ylim`\n For setting the x- and y-limits individually.\n\n"
],
[
"x = [ -1,0,0,1]\ny = [1,1,0,0]\n\nplt.plot(x,y)\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb058c8bc17497756211c32f90331d4854a57730 | 6,458 | ipynb | Jupyter Notebook | 05/day5_functions_end.ipynb | stromal/30-Days-of-Python | 8ac8208b193679c5e35bc81ad5cbd969a0abc906 | [
"MIT"
] | null | null | null | 05/day5_functions_end.ipynb | stromal/30-Days-of-Python | 8ac8208b193679c5e35bc81ad5cbd969a0abc906 | [
"MIT"
] | null | null | null | 05/day5_functions_end.ipynb | stromal/30-Days-of-Python | 8ac8208b193679c5e35bc81ad5cbd969a0abc906 | [
"MIT"
] | null | null | null | 21.243421 | 291 | 0.471044 | [
[
[
"items = [\"Mic\", \"Phone\", 323.12, 3123.123, \"Justin\", \"Bag\", \"Cliff Bars\", 134]\nstr_items = []\nnum_items = []",
"_____no_output_____"
],
[
"for i in items:\n if isinstance(i, float) or isinstance(i, int):\n num_items.append(i)\n elif isinstance(i, str):\n str_items.append(i)\n else:\n pass",
"_____no_output_____"
],
[
"print(str_items)\nprint(num_items)",
"['Mic', 'Phone', 'Justin', 'Bag', 'Cliff Bars']\n[323.12, 3123.123, 134]\n"
],
[
"def parse_lists(abc):\n str_list_items = []\n num_list_items = []\n for i in abc:\n if isinstance(i, float) or isinstance(i, int):\n num_list_items.append(i)\n elif isinstance(i, str):\n str_list_items.append(i)\n else:\n pass\n return str_list_items, num_list_items",
"_____no_output_____"
],
[
"'''Def Call'''\nprint(parse_lists(items))",
"(['Mic', 'Phone', 'Justin', 'Bag', 'Cliff Bars'], [323.12, 3123.123, 134])\n"
],
[
"list_item = [123, 3234, \"adfasd\"]\nitems2 = [\"Mic\", \"Phone\", list_item]",
"_____no_output_____"
],
[
"print(parse_lists(items2))",
"(['Mic', 'Phone'], [])\n"
],
[
"items3 = [\"Mic\", \"Phone\", 323.12, 3123.123, \"Justin\", \"Bag\", \"Cliff Bars\", 134]",
"_____no_output_____"
],
[
"sum([123, 323, 423])",
"_____no_output_____"
],
[
"def my_sum(my_num_list):\n total = 0\n for i in my_num_list:\n if isinstance(i, float) or isinstance(i, int):\n total += i\n return total\n\n #if isinstance(i, float) or isinstance(i, int):\n\ndef count_nums(my_num_list):\n total = 0\n for i in my_num_list:\n if isinstance(i, float) or isinstance(i, int):\n total += 1\n return total",
"_____no_output_____"
],
[
"sum(items3)",
"_____no_output_____"
],
[
"my_sum(items3)",
"_____no_output_____"
],
[
"count_nums(items3)",
"_____no_output_____"
],
[
"def my_avg(my_num_list):\n the_sum = my_sum(my_num_list)\n #num_of_items = len(my_num_list)\n num_of_items = count_nums(my_num_list)\n return the_sum / (num_of_items * 1.0)\n\nmy_avg(items3)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb058cf245494e6ef8f8f615365709c82a639c52 | 266,258 | ipynb | Jupyter Notebook | notebooks/12_arakawa_C_2D_mgrid_quiver_netCDF.ipynb | atmos-cloud-sim-uj/MoAC | 4d342391020ceb4b6cb392259da30d70c52a0ee1 | [
"CC-BY-4.0"
] | 3 | 2020-02-23T19:55:51.000Z | 2020-08-17T18:56:34.000Z | notebooks/12_arakawa_C_2D_mgrid_quiver_netCDF.ipynb | atmos-cloud-sim-uj/MoAC | 4d342391020ceb4b6cb392259da30d70c52a0ee1 | [
"CC-BY-4.0"
] | null | null | null | notebooks/12_arakawa_C_2D_mgrid_quiver_netCDF.ipynb | atmos-cloud-sim-uj/MoAC | 4d342391020ceb4b6cb392259da30d70c52a0ee1 | [
"CC-BY-4.0"
] | 1 | 2021-04-04T12:20:51.000Z | 2021-04-04T12:20:51.000Z | 517.005825 | 110,144 | 0.942116 | [
[
[
"from MPyDATA import ScalarField, VectorField, PeriodicBoundaryCondition, Options, Stepper, Solver",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"dt, dx, dy = .1, .2, .3\nnt, nx, ny = 100, 15, 10\n\n# https://en.wikipedia.org/wiki/Arakawa_grids#Arakawa_C-grid\nx, y = np.mgrid[\n dx/2 : nx*dx : dx, \n dy/2 : ny*dy : dy\n]",
"_____no_output_____"
],
[
"# vector field (u,v) components\n\n# u - x component of the velocity field\nux, uy = np.mgrid[\n 0 : (nx+1)*dx : dx, \n dy/2 : ny*dy : dy\n]\n\n# v - y component of the velocity field\nvx, vy = np.mgrid[\n dx/2 : nx*dx : dx,\n 0: (ny+1)*dy : dy\n]",
"_____no_output_____"
],
[
"from matplotlib import pyplot, rcParams\nrcParams['figure.figsize'] = [12, 8]",
"_____no_output_____"
],
[
"pyplot.quiver(ux, uy, 1, 0, pivot='mid')\npyplot.quiver(vx, vy, 0, 1, pivot='mid')\n\npyplot.xticks(ux[:,0])\npyplot.yticks(vy[0,:])\n\npyplot.scatter(x, y)\npyplot.title('Arakawa-C grid')\npyplot.grid()\npyplot.show()",
"_____no_output_____"
],
[
"from MPyDATA import ScalarField, VectorField, PeriodicBoundaryCondition, Options, Stepper, Solver",
"_____no_output_____"
],
[
"bc = [PeriodicBoundaryCondition(), PeriodicBoundaryCondition()]",
"_____no_output_____"
],
[
"options = Options()",
"_____no_output_____"
],
[
"data = np.zeros((nx, ny))\ndata[1,1] = 10\n\nadvectee = ScalarField(data, options.n_halo, boundary_conditions=bc)",
"_____no_output_____"
],
[
"# https://en.wikipedia.org/wiki/Stream_function",
"_____no_output_____"
]
],
[
[
"stream function: \n$u=-\\partial_y \\psi$ \n$v=\\partial_x \\psi$\n\nexample flow field: \n$\\psi(x,y) = - w_{\\text{max}} \\frac{X}{\\pi} \n \\sin\\left(\\pi \\frac{y}{Y}\\right)\n \\cos\\left(2\\pi\\frac{x}{X}\\right)\n$ ",
"_____no_output_____"
]
],
[
[
"class Psi:\n def __init__(self, *, X, Y, w_max):\n self.X = X\n self.Y = Y\n self.w_max = w_max\n \n def __call__(self, x, y):\n return - self.w_max * self.X / np.pi * np.sin(np.pi * y/self.Y) * np.cos(2 * np.pi * x/self.X)",
"_____no_output_____"
],
[
"psi = Psi(X=nx*dx, Y=ny*dy, w_max=.6)",
"_____no_output_____"
],
[
"print(psi(0,0))",
"-0.0\n"
],
[
"print(psi(1,1))",
"0.24809800293980627\n"
],
[
"# https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition\n\n# C_x = u * dt / dx\n# C_y = v * dt / dy\n\nu = -(psi(ux, uy+dy/2) - psi(ux, uy-dy/2)) / dy \nv = +(psi(vx+dx/2, vy) - psi(vx-dx/2, vy)) / dx\n\nadvector = VectorField([u*dt/dx, v*dt/dy], halo=options.n_halo, boundary_conditions=bc)",
"_____no_output_____"
],
[
"def plot(advectee, advector):\n pyplot.scatter(x, y, s=100, c=advectee.get(), marker='s')\n pyplot.quiver(ux, uy, advector.get_component(0), 0, pivot='mid', scale=10)\n pyplot.quiver(vx, vy, 0, advector.get_component(1), pivot='mid', scale=10)\n pyplot.xticks(ux[:,0])\n pyplot.yticks(vy[0,:])\n pyplot.colorbar()\n pyplot.grid()\n pyplot.show()",
"_____no_output_____"
],
[
"plot(advectee, advector)",
"_____no_output_____"
],
[
"stepper = Stepper(options=options, grid=(nx, ny))",
"_____no_output_____"
],
[
"solver = Solver(stepper=stepper, advectee=advectee, advector=advector)",
"_____no_output_____"
],
[
"solver.advance(20)",
"_____no_output_____"
],
[
"plot(advectee, advector)",
"_____no_output_____"
],
[
"# https://en.wikipedia.org/wiki/NetCDF",
"_____no_output_____"
],
[
"from scipy.io.netcdf import netcdf_file",
"_____no_output_____"
],
[
"with netcdf_file('test.nc', mode='w') as ncdf:\n # global attributes (metadata)\n ncdf.MPyDATA_options = str(options)\n \n # dimensions\n ncdf.createDimension(\"T\", nt)\n ncdf.createDimension(\"X\", nx)\n ncdf.createDimension(\"Y\", ny)\n \n # variables (defined over defined dimensions)\n variables = {}\n variables[\"T\"] = ncdf.createVariable(\"T\", \"f\", [\"T\"])\n variables[\"T\"].units = \"seconds\"\n variables[\"T\"][:] = 0\n\n variables[\"X\"] = ncdf.createVariable(\"X\", \"f\", [\"X\"])\n variables[\"X\"][:] = x[:, 0]\n variables[\"X\"].units = \"metres\"\n\n variables[\"Y\"] = ncdf.createVariable(\"Y\", \"f\", [\"Y\"])\n variables[\"Y\"][:] = y[0, :]\n variables[\"Y\"].units = \"metres\"\n \n variables[\"advectee\"] = ncdf.createVariable(\"advectee\", \"f\", [\"T\", \"X\", \"Y\"])\n \n # attributes (per variable)\n # e.g. units above\n \n # note: initial condition not saved\n for i in range(nt):\n solver.advance(nt=1)\n variables[\"T\"][i] = (i+1) * dt\n variables[\"advectee\"][i, :, :] = solver.advectee.get()",
"_____no_output_____"
],
[
"! ls -lah test.nc",
"-rw-r--r-- 1 slayoo slayoo 60K May 25 10:55 test.nc\r\n"
],
[
"! file test.nc",
"test.nc: NetCDF Data Format data\r\n"
],
[
"! ncdump -c test.nc",
"netcdf test {\r\ndimensions:\r\n\tT = 100 ;\r\n\tX = 15 ;\r\n\tY = 10 ;\r\nvariables:\r\n\tfloat advectee(T, X, Y) ;\r\n\tfloat T(T) ;\r\n\t\tT:units = \"seconds\" ;\r\n\tfloat X(X) ;\r\n\t\tX:units = \"metres\" ;\r\n\tfloat Y(Y) ;\r\n\t\tY:units = \"metres\" ;\r\n\r\n// global attributes:\r\n\t\t:MPyDATA_options = \"{\\'n_iters\\': 2, \\'infinite_gauge\\': False, \\'epsilon\\': 1e-15, \\'divergent_flow\\': False, \\'flux_corrected_transport\\': False, \\'third_order_terms\\': False, \\'non_zero_mu_coeff\\': False}\" ;\r\ndata:\r\n\r\n T = 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, \r\n 1.6, 1.7, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, \r\n 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4, 4.1, 4.2, 4.3, 4.4, 4.5, \r\n 4.6, 4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6, \r\n 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.1, 7.2, 7.3, 7.4, 7.5, \r\n 7.6, 7.7, 7.8, 7.9, 8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9, \r\n 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10 ;\r\n\r\n X = 0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.1, 2.3, 2.5, 2.7, 2.9 ;\r\n\r\n Y = 0.15, 0.45, 0.75, 1.05, 1.35, 1.65, 1.95, 2.25, 2.55, 2.85 ;\r\n}\r\n"
],
[
"# https://en.wikipedia.org/wiki/Climate_and_Forecast_Metadata_Conventions",
"_____no_output_____"
],
[
"# try opening in Paraview (https://en.wikipedia.org/wiki/ParaView)...",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"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",
"code",
"code"
]
] |
cb0594281c92026d9c5238f65daa04710e8ab44d | 14,743 | ipynb | Jupyter Notebook | docs/development_notebooks/2021-05-19-kayvirus-pangenome.ipynb | cjprybol/Mycelia | 4dbf30f22201da52d5084cef9d7019b5faa57875 | [
"MIT"
] | null | null | null | docs/development_notebooks/2021-05-19-kayvirus-pangenome.ipynb | cjprybol/Mycelia | 4dbf30f22201da52d5084cef9d7019b5faa57875 | [
"MIT"
] | 27 | 2021-06-24T17:53:36.000Z | 2022-03-05T19:26:01.000Z | docs/development_notebooks/2021-05-19-kayvirus-pangenome.ipynb | cjprybol/Mycelia | 4dbf30f22201da52d5084cef9d7019b5faa57875 | [
"MIT"
] | 1 | 2022-01-08T14:45:20.000Z | 2022-01-08T14:45:20.000Z | 30.149284 | 164 | 0.563522 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb059bfbce08dcbb55db43182646003c05b66a37 | 20,091 | ipynb | Jupyter Notebook | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions | 838cb2d300a2d1de5fcf4c8b1982d7999ea997d7 | [
"Apache-2.0"
] | null | null | null | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions | 838cb2d300a2d1de5fcf4c8b1982d7999ea997d7 | [
"Apache-2.0"
] | 3 | 2022-03-09T21:23:05.000Z | 2022-03-14T15:12:29.000Z | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions | 838cb2d300a2d1de5fcf4c8b1982d7999ea997d7 | [
"Apache-2.0"
] | null | null | null | 34.34359 | 201 | 0.564283 | [
[
[
"# Upsert AOOS Priority Score Demo\n\n## Approaching Out of Stock (AOOS)\n\n* Priority scores of work items (inventories) in AOOS work queue are calculated and upserted to InfoHub\n* The function `AOOS_priority_score` is defined below - for understanding the business logic, refer to the accompanying Notebook **AOOS-Priority-Score.ipynb**\n\n## InfoHub\n\n* The InfoHub connection and queries are defined in the accompanying Notebook **InfoHub.ipynb**\n* Make sure that you have run the Kernel of the above Notebook",
"_____no_output_____"
]
],
[
[
"import json\nimport sys\nimport os\nimport pandas as pd\nimport time\nimport numpy as np\nimport datetime\nimport copy\nimport json",
"_____no_output_____"
]
],
[
[
"### Import `InfoHubConnection` Class\n\n* Install `ipynb` package for the following import to work\n\n `pip install ipynb`\n \n* Make sure that the Kernel of Notebook **InfoHub.ipynb** has been run without errors",
"_____no_output_____"
]
],
[
[
"from ipynb.fs.full.InfoHub import InfoHubConnection",
"_____no_output_____"
]
],
[
[
"### Priority Score Calculation\n\n* Priority score function for _Approaching Out of Stock_ work item\n* The business logic is explained in detail in the accompanying Notebook **AOOS-Priority-Score.ipynb**",
"_____no_output_____"
]
],
[
[
"def AOOS_priority_score(supply_plans, \n demand_plans,\n starting_inventory = 0,\n first_date = datetime.date(2021, 7, 31), \n last_date = datetime.date(2021, 8, 31), \n decay_weight = 3.0, \n inv_positive_threshold = 20, \n inv_negative_threshold = -100):\n \n horizon = (last_date - first_date).days + 1\n # Define Inventory horizon and add starting inventory\n inventory_horizon = np.zeros(horizon, dtype=int)\n inventory_horizon = inventory_horizon + starting_inventory\n\n # Add Supply plans\n for i in range(len(supply_plans)):\n supply_date = datetime.datetime.fromisoformat(supply_plans[i]['startDate'][:-1]).date()\n qty = supply_plans[i]['quantity']\n diff_days = (supply_date - first_date).days\n inventory_horizon[diff_days:] = inventory_horizon[diff_days:] + qty\n\n for i in range(len(demand_plans)):\n demand_date = datetime.datetime.fromisoformat(demand_plans[i]['startDate'][:-1]).date()\n qty = demand_plans[i]['quantity']\n diff_days = (demand_date - first_date).days\n inventory_horizon[diff_days:] = inventory_horizon[diff_days:] - qty\n\n # Calculate weights\n weights = np.exp(np.arange(decay_weight, 0, -(decay_weight/horizon)))/np.exp(decay_weight)\n\n # Calculate penalty\n inventory_below_threshold = inventory_horizon - inv_positive_threshold\n penalties = np.zeros(horizon, dtype=int)\n neg_inv_mask = inventory_below_threshold < 0\n penalties[neg_inv_mask] = inventory_below_threshold[neg_inv_mask] \n\n neg_threshold_mask = penalties < inv_negative_threshold\n penalties[neg_threshold_mask] = inv_negative_threshold\n\n total_penalty = np.sum(weights*-penalties)\n max_penalty = np.sum(weights*-inv_negative_threshold)\n priority_score = int(np.rint((total_penalty/max_penalty)*100))\n\n return priority_score\n",
"_____no_output_____"
]
],
[
[
"### InfoHub Connection Config\n\n* Load your InfoHub connection parameters from `credentials.json` file\n* `tenantId` is not required for establishing the connection, but is required in the GraphQL queries",
"_____no_output_____"
]
],
[
[
"with open(\"credentials.json\") as config_file:\n config = json.load(config_file)",
"_____no_output_____"
],
[
"url = config['url']\nheaders = config['headers']\ntenantId = config['tenantId']\ninfohub = InfoHubConnection(url=url, tenantId=tenantId, headers=headers)",
"_____no_output_____"
]
],
[
[
"### Priority Score Config\n\n* `timestamp`: Timestamp is needed in `upsert` operation, in ISO format.\n * In production, use the current system timestamp.\n* `maxDate`: Active supply and demand plans till this date are used for priority score calculation\n * For more details, check the accompanying Notebook **AOOS-Priority-Score.ipynb**",
"_____no_output_____"
]
],
[
[
"timestamp = \"2021-08-03T10:37:07+0800\"\nmaxDate = \"2021-08-31 00:00:00\"",
"_____no_output_____"
]
],
[
[
"### Work Queue List\n\n* Our goal is to evaluate / re-calculate the priority score of work items in the AOOS work queue\n* We need the AOOS work queue object ID to get the work items that are in progress\n* To get the AOOS work queue object ID, we use the following query to get the list of work queues.",
"_____no_output_____"
]
],
[
[
"workqueues = infohub.get_work_queues()\nfor i in range(len(workqueues)):\n print('WorkQueue: ', workqueues[i]['object']['name'])\n print('Id: ', workqueues[i]['object']['id'])\n print(\"--------------------------------------------------------------------------------\")",
"_____no_output_____"
]
],
[
[
"### Choose `workQueueId`\n\n* Choose the workQueueId of _Inventory approaching out of stock prioritized_",
"_____no_output_____"
]
],
[
[
"workQueueId = \"516dc12d-eff6-4c51-9222-7eca88a31c5e\"",
"_____no_output_____"
]
],
[
[
"### Collect Work Items\n\n* Given the work queue ID, collect all the work items",
"_____no_output_____"
]
],
[
[
"work_items = []\nprint(\"Querying work items in progress...\")\nwork_items_list = infohub.get_workitems_in_progress(workQueueId=workQueueId)\nprint(\"\\tNumber of WorkItems: {}\".format(len(work_items_list)))\nfor i in range(len(work_items_list)):\n wi = {\"workItemId\": work_items_list[i]['object'][\"id\"],\n \"priority\": work_items_list[i]['object'][\"priority\"],\n \"inventoryId\": work_items_list[i]['object'][\"businessObject\"][\"id\"],\n \"productId\": work_items_list[i]['object'][\"businessObject\"][\"product\"][\"id\"],\n \"partNumber\": work_items_list[i]['object'][\"businessObject\"][\"product\"][\"partNumber\"],\n \"locationId\": work_items_list[i]['object'][\"businessObject\"][\"location\"][\"id\"],\n \"locationIdentifier\": work_items_list[i]['object'][\"businessObject\"][\"location\"][\"locationIdentifier\"],\n \"starting_inventory\": work_items_list[i]['object'][\"businessObject\"][\"quantity\"]\n }\n work_items.append(wi)\n print(\"({}): Object-Id: {};\".format(i, wi[\"workItemId\"]))\n print(\"\\tPart-Number: {}; Location-Id: {}; Priority-Score: {}\".format(wi[\"partNumber\"], wi[\"locationIdentifier\"], wi[\"priority\"]))\nprint('Done.')",
"_____no_output_____"
]
],
[
[
"### Demo: Change in Priority Score\n* The priority scores are based on current supply plans and demand plans for next 30 days (`maxDate`)\n* In the event of a change in supply/demand plan(s), the priority score has to change to reflect the severity of going _out of stock_\n* We can test this by simulating a change in supply/demand plan (or both) and see how the priority score changes\n* Steps:\n * Step 1: Choose an WorkItem\n * Step 2: Get the supply and demand plans\n * Step 3: Upsert a plan with modified quantity and/or date\n * You can repeat this for multiple plans (supply or demand or both)\n * Step 4: Calculate the new priority score and compare",
"_____no_output_____"
],
[
"#### Step 1: Choose an WorkItem\n* Choose an WorkItem from the above list (by its index)",
"_____no_output_____"
]
],
[
[
"k = 3\npartNumber = work_items[k][\"partNumber\"]\nlocationIdentifier = work_items[k][\"locationIdentifier\"]\npriority = work_items[k][\"priority\"]\nworkItemId = work_items[k][\"workItemId\"]\nstarting_inventory = work_items[k][\"starting_inventory\"]\nprint(\"Selected WorkItem: Object ID: {}\".format(workItemId))\nprint(\"\\t({}): Part-Number: {}; Location-Id: {}; Priority-Score: {}\".format(k, partNumber, locationIdentifier, priority))",
"_____no_output_____"
]
],
[
[
"#### Step 2: Get Supply and Demand Plans\n* WorkItem can be identified with its unique object ID or by its unique `partNumber` and `locationIdentifier` combination\n* We have constructed all queries with `partNumber` and `locationIdentifier` combination for easy readability\n * Good practice is to use object ID as it is immune to possible changes in schema\n* To calculate the priority score we need both the supply and demand plans",
"_____no_output_____"
]
],
[
[
"# Get supply plans\nsupply_plans = []\nprint(\"Querying supply plans ...\")\nplan_list = infohub.get_supplyplans(partNumber=partNumber, locationIdentifier=locationIdentifier, maxDate=maxDate)\nprint(\"\\tNumber of Supply Plans: {}\".format(len(plan_list)))\nfor i in range(len(plan_list)):\n plan = {\"startDate\": plan_list[i]['object'][\"startDate\"],\n \"quantity\": plan_list[i]['object'][\"quantity\"],\n \"id\": plan_list[i]['object'][\"id\"]\n }\n supply_plans.append(plan)\n\n# Get demand plans\ndemand_plans =[]\nprint(\"Querying demand plans ...\")\nplan_list = infohub.get_demandplans(partNumber=partNumber, locationIdentifier=locationIdentifier, maxDate=maxDate)\nprint(\"\\tNumber of Demand Plans: {}\".format(len(plan_list)))\nfor i in range(len(plan_list)):\n plan = {\"startDate\": plan_list[i]['object'][\"startDate\"],\n \"quantity\": plan_list[i]['object'][\"quantity\"],\n \"id\": plan_list[i]['object'][\"id\"]\n }\n demand_plans.append(plan)\nprint(\"Done.\")",
"_____no_output_____"
],
[
"# Print Supply and Demand Plans\nprint(\"::Supply Plans::\")\nfor i in range(len(supply_plans)):\n print(\"\\t({}): Object ID: {}\".format(i, supply_plans[i][\"id\"]))\n print(\"\\t\\tStart Date: {}; Quantity: {};\".format(supply_plans[i][\"startDate\"], supply_plans[i][\"quantity\"]))\nprint(\"::Demand Plans::\")\nfor i in range(len(demand_plans)):\n print(\"\\t({}): Object ID: {}\".format(i, demand_plans[i][\"id\"]))\n print(\"\\t\\tStart Date: {}; Quantity: {};\".format(demand_plans[i][\"startDate\"], demand_plans[i][\"quantity\"]))",
"_____no_output_____"
]
],
[
[
"#### Step 3: Upsert a plan with modified quantity and/or date\n\n* Choose a supply/demand plan and change its quantity and/or date\n* Upsert the modified plan\n* You can repeat this for multiple plans (supply or demand or both)\n * Steps 3a and 3b",
"_____no_output_____"
]
],
[
[
"# To demonstrate the change in the priority\nchanged_plans = []\nnew_supply_plans = copy.deepcopy(supply_plans)\nnew_demand_plans = copy.deepcopy(demand_plans)",
"_____no_output_____"
]
],
[
[
"**Step 3a: _Modify Supply Plan_**",
"_____no_output_____"
]
],
[
[
"# Choose a supply plan to modify by its index\nk = 0\nid = supply_plans[k][\"id\"]\nstartDate = supply_plans[k][\"startDate\"]\nquantity = supply_plans[k][\"quantity\"]\nprint(\"Selected Supply Plan ({}): Object ID: {}\".format(k, id))\nprint(\"\\tStart Date: {}; Quantity: {};\".format(startDate, quantity))\nnew_startDate = startDate\nnew_quantity = quantity",
"_____no_output_____"
],
[
"# Modify quantity and/or date (Comment out to keep it the same)\n# new_startDate = \"2021-08-04T00:00:00.000Z\"\nnew_quantity = 350.0",
"_____no_output_____"
],
[
"# Upsert the modified supply plan\nprint(\"Upserting modified supply plan..\")\nupsert_result = infohub.upsert_supplyplan(supplyPlanID=id, quantity=new_quantity, startDate=new_startDate, timestamp=timestamp)\nprint(upsert_result)",
"_____no_output_____"
],
[
"# Update the new values in the local list\nnew_supply_plans[k][\"quantity\"] = new_quantity\nnew_supply_plans[k][\"startDate\"] = new_startDate\nchanged_plans.append({\"planType\": \"supply\",\n \"quantity\": quantity,\n \"startDate\": startDate,\n \"new_quantity\": new_quantity,\n \"new_startDate\": new_startDate})",
"_____no_output_____"
]
],
[
[
"**Step 3b: _Modify Demand Plan_**",
"_____no_output_____"
]
],
[
[
"# Choose a demand plan to modify by its index\nk = 0\nid = demand_plans[k][\"id\"]\nstartDate = demand_plans[k][\"startDate\"]\nquantity = demand_plans[k][\"quantity\"]\nprint(\"Selected Demand Plan ({}): Object ID: {}\".format(k, id))\nprint(\"\\tStart Date: {}; Quantity: {};\".format(startDate, quantity))\nnew_startDate = startDate\nnew_quantity = quantity",
"_____no_output_____"
],
[
"# Modify quantity and/or date (Comment out to keep it the same)\n#new_startDate = \"2021-08-02T00:00:00.000Z\"\nnew_quantity = 35.0",
"_____no_output_____"
],
[
"# Upsert the modified demand plan\nprint(\"Upserting modified demand plan..\")\nupsert_result = infohub.upsert_demandplan(demandPlanID=id, quantity=new_quantity, startDate=new_startDate, timestamp=timestamp)\nprint(upsert_result)",
"_____no_output_____"
],
[
"# Update the new values in the local list\nnew_demand_plans[k][\"quantity\"] = new_quantity\nnew_demand_plans[k][\"startDate\"] = new_startDate\nchanged_plans.append({\"planType\": \"demand\",\n \"quantity\": quantity,\n \"startDate\": startDate,\n \"new_quantity\": new_quantity,\n \"new_startDate\": new_startDate})",
"_____no_output_____"
]
],
[
[
"#### Step 4: Calculate Priority Score",
"_____no_output_____"
]
],
[
[
"new_priority = AOOS_priority_score(supply_plans=new_supply_plans, demand_plans=new_demand_plans, starting_inventory=starting_inventory, inv_positive_threshold=100, inv_negative_threshold=-300)\nprint(\"Updated priority score: {}\".format(new_priority))\n",
"_____no_output_____"
],
[
"# Results\nprint(\"Work Item / Inventory:\")\nprint(\"----------------------\")\nprint(\"\\tPart Number: {}; Location: {}\".format(partNumber, locationIdentifier))\nprint(\"----------------------\")\nprint(\"Changed Plans:\")\nfor i in range(len(changed_plans)):\n print(\"\\tPlan Type: {}\".format(changed_plans[i][\"planType\"]))\n if changed_plans[i][\"quantity\"] != changed_plans[i][\"new_quantity\"]:\n print(\"\\t\\t Quantity change: {} -> {}\".format(changed_plans[i][\"quantity\"], changed_plans[i][\"new_quantity\"]))\n if changed_plans[i][\"startDate\"] != changed_plans[i][\"new_startDate\"]:\n print(\"\\t\\t Start date change: {} -> {}\".format(changed_plans[i][\"startDate\"], changed_plans[i][\"new_startDate\"]))\nprint(\"---------------------------------------\")\nprint(\"Priority change: {} -> {}\".format(priority, new_priority))\nprint(\"---------------------------------------\")",
"_____no_output_____"
],
[
"# Upsert the new priority score\nupsert_result = infohub.upsert_workitem_priority(workItemId=workItemId, priority=new_priority, timestamp=timestamp)\nprint(upsert_result)",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb05b37ab74b456c53b707cd23f93a609e1ca6fe | 3,684 | ipynb | Jupyter Notebook | lab1_python_intro/ex2_intro_scientific_libraries.ipynb | ggruszczynski/CFDPython | 1662ede061fb899d6ed3f89c17877e65f65e521c | [
"CC-BY-3.0"
] | null | null | null | lab1_python_intro/ex2_intro_scientific_libraries.ipynb | ggruszczynski/CFDPython | 1662ede061fb899d6ed3f89c17877e65f65e521c | [
"CC-BY-3.0"
] | null | null | null | lab1_python_intro/ex2_intro_scientific_libraries.ipynb | ggruszczynski/CFDPython | 1662ede061fb899d6ed3f89c17877e65f65e521c | [
"CC-BY-3.0"
] | 1 | 2021-02-05T08:00:02.000Z | 2021-02-05T08:00:02.000Z | 20.581006 | 161 | 0.505157 | [
[
[
"# Welcome to the jungle: Numpy, Scipy, Sympy, Matplotlib, Pandas\n\n\nNumpy is a library (written is C) for numerical calculations.\n\nScipy is written on the top of numpy, and can perfrom some more advenced task like integration, optimization, signal processingm fourier transform, etc.\n\nSympy is for symbolic operations.\n\nMatplotlib is used to visualize data.\n\nPandas is like excel for python ;)\n",
"_____no_output_____"
],
[
"## Numpy\n",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"np.ones((2,3))\nnp.eye(4)",
"_____no_output_____"
],
[
"tab2D = np.array( [[ i*2+j for j in range(2)] for i in range(3)])\ntab2D",
"_____no_output_____"
]
],
[
[
"### Exercice:\n\nGenerate a 2D matrix 5x5 where $$ x_{i,j} = i + 100j $$\nDisplay its 3rd column.\nDisplay element at position 2,3.\n",
"_____no_output_____"
],
[
"## System of linear equations\n\nSolve the system of equations 3 * x0 + x1 = 9 and x0 + 2 * x1 = 8\n\nSee the [docs](https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html)",
"_____no_output_____"
]
],
[
[
"A = np.array([[3,1], [1,2]])\nb = np.array([9,8])\nx = np.linalg.solve(A, b)\nx",
"_____no_output_____"
],
[
"np.allclose(np.dot(A, x), b)",
"_____no_output_____"
],
[
"# alternatively, the dot product can be expressed as \nA @ x\n",
"_____no_output_____"
]
],
[
[
"### Prepare some data\n\nNumpy has a buildin function to generate arrays of data for computations.\nCheck the following\n\n* np.linspace(0, 2, 100)\n* np.logspace(0, 2, 100)\n* np.arrange(0, 2, 100)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb05d91f17ca67c4015f9aa90e2a2a95d958b831 | 13,583 | ipynb | Jupyter Notebook | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates | 378854171b36156f3a52218c880110201a06b0b1 | [
"CC0-1.0"
] | null | null | null | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates | 378854171b36156f3a52218c880110201a06b0b1 | [
"CC0-1.0"
] | null | null | null | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates | 378854171b36156f3a52218c880110201a06b0b1 | [
"CC0-1.0"
] | 1 | 2021-03-07T20:59:26.000Z | 2021-03-07T20:59:26.000Z | 26.222008 | 123 | 0.446661 | [
[
[
"## Model and Feature Selection",
"_____no_output_____"
],
[
"### Notebook Contents:\n\n- [Reading in the Data](#reading5)\n- [Defining X and y](#features5)\n- [AdaBoost Regressor](#ada)",
"_____no_output_____"
]
],
[
[
"# imports\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.feature_selection import RFE\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor, BaggingRegressor\n\nfrom sklearn.metrics import mean_squared_error, r2_score",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"reading5\"></a>",
"_____no_output_____"
],
[
"### Reading in the Data",
"_____no_output_____"
]
],
[
[
"# read the csv file with log scaled data\ndf = pd.read_csv('data/log_per_student.csv')",
"_____no_output_____"
],
[
"df.head(2)",
"_____no_output_____"
],
[
"df.columns = df.columns.str.lower() #make column names lower-case",
"_____no_output_____"
],
[
"df.set_index(df['leaid'], inplace = True) #set leaid column as index",
"_____no_output_____"
],
[
"dummies = pd.get_dummies(df['agchrt'], drop_first = True).astype('float64') # dummify agchrt column",
"_____no_output_____"
],
[
"df = pd.concat([df, dummies], axis = 1) # add to the dataframe",
"_____no_output_____"
],
[
"df.isnull().sum() # check for null values",
"_____no_output_____"
],
[
"df.dropna(axis = 0, inplace = True) #drop null values",
"_____no_output_____"
]
],
[
[
"<a class=\"anchor\" id=\"features5\"></a>",
"_____no_output_____"
],
[
"### Define X and y",
"_____no_output_____"
]
],
[
[
"# numeric X Features (excl stabbr)\nX = df[[2, 3,'tfedrev', 'tstrev', 'a13', 't06', 'a11', 'u30', 'totalexp', 't40', \n 'v93', 'z33', 'z35', 'z36', 'z38', 'z37', 'v11', 'v13', 'v17', 'v37', 'v10', 'v12', 'v14', \n 'v18', 'v24', 'v38', 'w01', 'w31', 'w61', '_19h', '_21f', '_41f', '_61v']]\n\ny = df['graduation rate']",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y) #train test split the variables",
"_____no_output_____"
],
[
"# data types (the only object is district name column)\nX_train.info()",
"<class 'pandas.core.frame.DataFrame'>\nIndex: 16848 entries, 4819650 to 3407800\nData columns (total 33 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 2.0 16848 non-null float64\n 1 3.0 16848 non-null float64\n 2 tfedrev 16848 non-null float64\n 3 tstrev 16848 non-null float64\n 4 a13 16848 non-null float64\n 5 t06 16848 non-null float64\n 6 a11 16848 non-null float64\n 7 u30 16848 non-null float64\n 8 totalexp 16848 non-null float64\n 9 t40 16848 non-null float64\n 10 v93 16848 non-null float64\n 11 z33 16848 non-null float64\n 12 z35 16848 non-null float64\n 13 z36 16848 non-null float64\n 14 z38 16848 non-null float64\n 15 z37 16848 non-null float64\n 16 v11 16848 non-null float64\n 17 v13 16848 non-null float64\n 18 v17 16848 non-null float64\n 19 v37 16848 non-null float64\n 20 v10 16848 non-null float64\n 21 v12 16848 non-null float64\n 22 v14 16848 non-null float64\n 23 v18 16848 non-null float64\n 24 v24 16848 non-null float64\n 25 v38 16848 non-null float64\n 26 w01 16848 non-null float64\n 27 w31 16848 non-null float64\n 28 w61 16848 non-null float64\n 29 _19h 16848 non-null float64\n 30 _21f 16848 non-null float64\n 31 _41f 16848 non-null float64\n 32 _61v 16848 non-null float64\ndtypes: float64(33)\nmemory usage: 4.4+ MB\n"
]
],
[
[
"<a class=\"anchor\" id=\"ada\"></a>",
"_____no_output_____"
],
[
"### Pipe: StandardScaler / AdaBoostRegressor",
"_____no_output_____"
]
],
[
[
"pipe_ada = make_pipeline(StandardScaler(), AdaBoostRegressor())",
"_____no_output_____"
],
[
"pipe_ada.fit(X_train, y_train)",
"_____no_output_____"
],
[
"pipe_ada.score(X_train, y_train)",
"_____no_output_____"
],
[
"pipe_ada.score(X_test, y_test)",
"_____no_output_____"
],
[
"# RMSE\nround(mean_squared_error(y_test, pipe_ada.predict(X_test), squared = False), 2)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb05d9abf2a2cd9286553f3acd220b98e43dd1ae | 50,949 | ipynb | Jupyter Notebook | JupyterTutorialStart.ipynb | JungDominik/binder_repo | f492ab181f9c9ee9f80a67d960809f464771a986 | [
"MIT"
] | null | null | null | JupyterTutorialStart.ipynb | JungDominik/binder_repo | f492ab181f9c9ee9f80a67d960809f464771a986 | [
"MIT"
] | null | null | null | JupyterTutorialStart.ipynb | JungDominik/binder_repo | f492ab181f9c9ee9f80a67d960809f464771a986 | [
"MIT"
] | null | null | null | 28.833616 | 864 | 0.342323 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame",
"_____no_output_____"
],
[
"series_obj = Series(np.arange(6), index = ['row 1','row 2','row 3','row 4',\"row 5\", \"row 6\"])",
"_____no_output_____"
],
[
"series_obj",
"_____no_output_____"
],
[
"series_obj['row 3']",
"_____no_output_____"
],
[
"series_obj[2]",
"_____no_output_____"
],
[
"series_obj[[2]]",
"_____no_output_____"
],
[
"series_obj[[0,4]]",
"_____no_output_____"
],
[
"np.random.seed(25)\nDF_obj = pd.DataFrame(np.random.rand(36).reshape(6,6), index = ['row 1','row 2','row 3','row 4',\"row 5\", \"row 6\"], columns = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"])",
"_____no_output_____"
],
[
"DF_obj",
"_____no_output_____"
],
[
"np.arange(3,7,2)",
"_____no_output_____"
],
[
"series_obj",
"_____no_output_____"
],
[
"series_obj[[3]]",
"_____no_output_____"
],
[
"df69 = pd.DataFrame(np.random.rand(36).reshape(6,6), index=[\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"], columns = [\"col1\",\"col2\",\"col3\",\"col4\",\"col5\",\"col6\"] )",
"_____no_output_____"
],
[
"df69.loc[[\"a\"],[\"col3\",\"col5\"]]",
"_____no_output_____"
],
[
"series_obj[2:4]",
"_____no_output_____"
],
[
"DF_obj2 = pd.DataFrame(np.random.rand(36).reshape(6,6), index = ['row 1','row 2','row 3','row 4',\"row 5\", \"row 6\"], columns = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"])",
"_____no_output_____"
],
[
"DF_obj2\n",
"_____no_output_____"
],
[
"series_obj<3",
"_____no_output_____"
],
[
"DF_obj2[series_obj<3]",
"_____no_output_____"
],
[
"DF_obj2[DF_obj2.iloc[[1]]<0.5]",
"_____no_output_____"
],
[
"series_obj[2:4] = \"changed\"\nseries_obj",
"_____no_output_____"
],
[
"DF_obj.loc[\"row 1\", \"3\"] = \"hallo_modv2\"\nDF_obj",
"_____no_output_____"
],
[
"fobj = open(\"untitled.txt\")\nfor line in fobj:\n print (line.rstrip())\nfobj.close()",
"_____no_output_____"
],
[
"import os\nos.chdir('C:\\\\Users\\\\d.jung\\\\')\nos.listdir()",
"_____no_output_____"
],
[
"address = 'mtcars.csv'\ncars = pd.read_csv(address)",
"_____no_output_____"
],
[
"cars.columns()",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df.loc[2,'cyl']",
"_____no_output_____"
],
[
"series_obj[[0]]",
"_____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"
]
] |
cb05e390f05229ccbfcae134c49c5c5f2fa87ed4 | 44,456 | ipynb | Jupyter Notebook | Soccer.ipynb | abhishekkumarm98/Web-Scraping | 612effb3471cc0f76d60b0a207d4a45cfe48fee8 | [
"MIT"
] | null | null | null | Soccer.ipynb | abhishekkumarm98/Web-Scraping | 612effb3471cc0f76d60b0a207d4a45cfe48fee8 | [
"MIT"
] | null | null | null | Soccer.ipynb | abhishekkumarm98/Web-Scraping | 612effb3471cc0f76d60b0a207d4a45cfe48fee8 | [
"MIT"
] | null | null | null | 40.562044 | 116 | 0.369849 | [
[
[
"import requests\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup",
"_____no_output_____"
],
[
"# Give a url for respective year\nresponse = requests.get(\"https://fbref.com/en/comps/22/1759/schedule/2018-Major-League-Soccer-Fixtures\")",
"_____no_output_____"
],
[
"soup = BeautifulSoup(response.content, features= \"html.parser\")",
"_____no_output_____"
],
[
"boxScores = []\nfor i in range(len(soup.find_all(\"tr\"))):\n try:\n boxScores.append(soup.find_all(\"tr\")[i].find_all(\"a\")[-1].get('href'))\n except IndexError:\n pass",
"_____no_output_____"
],
[
"len(boxScores)",
"_____no_output_____"
],
[
"def refinedInfo(lst,split_el):\n name = ['day','venue time', 'Venue', 'Attendance']\n dct = dict(zip(name,[0]*len(name)))\n for n in lst:\n t = n.split(split_el) \n if 'venue time' in n:\n dct['venue time'] = n.split(', ')[-1].replace(' (venue time) ','')\n dct['day'] = ','.join(n.split(',')[:2])\n elif 'Attendance' in n:\n elm_1 = t[0]\n elm_2 = t[1]\n dct[elm_1] = elm_2\n elif 'Venue' in n:\n elm_1 = t[0]\n elm_2 = t[1]\n dct[elm_1] = elm_2\n \n return list(dct.values())",
"_____no_output_____"
],
[
"col_name = ['Team_1','Team_1_score','Team_2','Team_2_score','Day&Date','Start Time','Stadium','Attendance']\ndf = pd.DataFrame(columns= col_name)\nfor i,half_url in enumerate(boxScores):\n url = \"https://fbref.com\" + half_url\n response_1 = requests.get(url)\n soup_1 = BeautifulSoup(response_1.content, features= \"html.parser\")\n \n pr = soup_1.find_all('div',attrs= {'class':\"scores\"})\n \n if pr != []:\n \n if (pr[0].find_all('div',attrs= {'class':\"score\"})[0].get_text() == '0') and \\\n (pr[1].find_all('div',attrs= {'class':\"score\"})[0].get_text() == '0'):\n try:\n score = [s.find('div',attrs= {'class':\"score_pen\"}).get_text() for s in pr]\n except AttributeError:\n score = [s.find('div',attrs= {'class':\"score\"}).get_text() for s in pr]\n else:\n score = [s.find('div',attrs= {'class':\"score\"}).get_text() for s in pr]\n\n teams = soup_1.title.get_text().split(' Match Report')[0].split(' vs. ')[:2]\n txt_1 = soup_1.find_all(\"div\", attrs= {'class':\"scorebox_meta\"})\n imd = [j.get_text() for j in txt_1[0].find_all(\"div\")]\n imd_2 = refinedInfo(imd,': ')\n df.loc[i] = [teams[0]] + [score[0]] + [teams[1]] + [score[1]] +imd_2\n else:\n pass",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"# df.to_excel(\"2018.xlsx\")",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb05e61597f6a5d5df94593d64a90810bfca48b7 | 85,128 | ipynb | Jupyter Notebook | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. | 27ae3b8b37564fca0c255a4c4eff3cbfc527705b | [
"MIT"
] | null | null | null | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. | 27ae3b8b37564fca0c255a4c4eff3cbfc527705b | [
"MIT"
] | null | null | null | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. | 27ae3b8b37564fca0c255a4c4eff3cbfc527705b | [
"MIT"
] | null | null | null | 44.291363 | 7,053 | 0.523424 | [
[
[
"<a href=\"https://colab.research.google.com/github/charanhu/Amazon-Fine-Food-Reviews-Analysis./blob/main/Amazon_Fine_Food_Reviews_Analysis.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"!wget --header=\"Host: storage.googleapis.com\" --header=\"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36\" --header=\"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\" --header=\"Accept-Language: en-US,en;q=0.9\" --header=\"Referer: https://www.kaggle.com/\" \"https://storage.googleapis.com/kaggle-data-sets/18/2157/bundle/archive.zip?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=gcp-kaggle-com%40kaggle-161607.iam.gserviceaccount.com%2F20210617%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210617T121304Z&X-Goog-Expires=259199&X-Goog-SignedHeaders=host&X-Goog-Signature=9a911766595be1862a3092d3324b51b0eb4e7c743ee7ace0cc6b48e3a0ab779e2e96add73b40062ee946e3a7b891cb652614cbe80f81d51dd11ef64c34e8f66d20ee312b2a391db6f0a171f6c094a42f1d6a97bb8ab50db5b630deed8a54cb6f111abe3e2ff557fc86028b38e8661c472ddfe51379540258b0509072c9278614c43d89f04652fa6c29459b57731f85d1fbb2c723b7f26beb14dc8b56220d68215fae03beb865641df4147c536bdb8e44704fc32f152a0ef51b7de8f138289474bd83413a04e0f048af50d9c31fa2a0edff2a6151ce7cfdb6dfa139130f27c39fdfa1787aa973c6ec01a43b824eb42103e12aa3e0bfc8044a347bda9640692ea7\" -c -O 'archive.zip'",
"--2021-08-16 09:11:38-- https://storage.googleapis.com/kaggle-data-sets/18/2157/bundle/archive.zip?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=gcp-kaggle-com%40kaggle-161607.iam.gserviceaccount.com%2F20210617%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210617T121304Z&X-Goog-Expires=259199&X-Goog-SignedHeaders=host&X-Goog-Signature=9a911766595be1862a3092d3324b51b0eb4e7c743ee7ace0cc6b48e3a0ab779e2e96add73b40062ee946e3a7b891cb652614cbe80f81d51dd11ef64c34e8f66d20ee312b2a391db6f0a171f6c094a42f1d6a97bb8ab50db5b630deed8a54cb6f111abe3e2ff557fc86028b38e8661c472ddfe51379540258b0509072c9278614c43d89f04652fa6c29459b57731f85d1fbb2c723b7f26beb14dc8b56220d68215fae03beb865641df4147c536bdb8e44704fc32f152a0ef51b7de8f138289474bd83413a04e0f048af50d9c31fa2a0edff2a6151ce7cfdb6dfa139130f27c39fdfa1787aa973c6ec01a43b824eb42103e12aa3e0bfc8044a347bda9640692ea7\nResolving storage.googleapis.com (storage.googleapis.com)... 108.177.97.128, 108.177.125.128, 142.250.157.128, ...\nConnecting to storage.googleapis.com (storage.googleapis.com)|108.177.97.128|:443... connected.\nHTTP request sent, awaiting response... 400 Bad Request\n2021-08-16 09:11:39 ERROR 400: Bad Request.\n\n"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"from google.colab import files\nfiles.upload()",
"_____no_output_____"
],
[
"!mkdir -p ~/.kaggle\n!cp kaggle.json ~/.kaggle/\n\n!chmod 600 ~/.kaggle/kaggle.json",
"_____no_output_____"
],
[
"!kaggle datasets download -d snap/amazon-fine-food-reviews",
"Downloading amazon-fine-food-reviews.zip to /content\n 98% 237M/242M [00:10<00:00, 15.5MB/s]\n100% 242M/242M [00:10<00:00, 23.1MB/s]\n"
],
[
"!unzip amazon-fine-food-reviews",
"Archive: amazon-fine-food-reviews.zip\n inflating: Reviews.csv \n inflating: database.sqlite \n inflating: hashes.txt \n"
]
],
[
[
"# Amazon Fine Food Reviews Analysis\n\n\nData Source: https://www.kaggle.com/snap/amazon-fine-food-reviews <br>\n\nEDA: https://nycdatascience.com/blog/student-works/amazon-fine-foods-visualization/\n\n\nThe Amazon Fine Food Reviews dataset consists of reviews of fine foods from Amazon.<br>\n\nNumber of reviews: 568,454<br>\nNumber of users: 256,059<br>\nNumber of products: 74,258<br>\nTimespan: Oct 1999 - Oct 2012<br>\nNumber of Attributes/Columns in data: 10 \n\nAttribute Information:\n\n1. Id\n2. ProductId - unique identifier for the product\n3. UserId - unqiue identifier for the user\n4. ProfileName\n5. HelpfulnessNumerator - number of users who found the review helpful\n6. HelpfulnessDenominator - number of users who indicated whether they found the review helpful or not\n7. Score - rating between 1 and 5\n8. Time - timestamp for the review\n9. Summary - brief summary of the review\n10. Text - text of the review\n\n\n#### Objective:\nGiven a review, determine whether the review is positive (Rating of 4 or 5) or negative (rating of 1 or 2).\n\n<br>\n[Q] How to determine if a review is positive or negative?<br>\n<br> \n[Ans] We could use the Score/Rating. A rating of 4 or 5 could be cosnidered a positive review. A review of 1 or 2 could be considered negative. A review of 3 is nuetral and ignored. This is an approximate and proxy way of determining the polarity (positivity/negativity) of a review.\n\n\n",
"_____no_output_____"
],
[
"## Loading the data\n\nThe dataset is available in two forms\n1. .csv file\n2. SQLite Database\n\nIn order to load the data, We have used the SQLITE dataset as it easier to query the data and visualise the data efficiently.\n<br> \n\nHere as we only want to get the global sentiment of the recommendations (positive or negative), we will purposefully ignore all Scores equal to 3. If the score id above 3, then the recommendation wil be set to \"positive\". Otherwise, it will be set to \"negative\".",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\nimport sqlite3\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport string\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_curve, auc\nfrom nltk.stem.porter import PorterStemmer\n\nimport re\n# Tutorial about Python regular expressions: https://pymotw.com/2/re/\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\nfrom gensim.models import Word2Vec\nfrom gensim.models import KeyedVectors\nimport pickle\n\nfrom tqdm import tqdm\nimport os",
"_____no_output_____"
]
],
[
[
"# [1]. Reading Data",
"_____no_output_____"
]
],
[
[
"\n# using the SQLite Table to read data.\ncon = sqlite3.connect('/content/database.sqlite') \n#filtering only positive and negative reviews i.e. \n# not taking into consideration those reviews with Score=3\n# SELECT * FROM Reviews WHERE Score != 3 LIMIT 500000, will give top 500000 data points\n# you can change the number to any other number based on your computing power\n\n# filtered_data = pd.read_sql_query(\"\"\" SELECT * FROM Reviews WHERE Score != 3 LIMIT 500000\"\"\", con) \n# for tsne assignment you can take 5k data points\n\nfiltered_data = pd.read_sql_query(\"\"\" SELECT * FROM Reviews WHERE Score != 3 LIMIT 5000\"\"\", con) \n\n# Give reviews with Score>3 a positive rating, and reviews with a score<3 a negative rating.\ndef partition(x):\n if x < 3:\n return 0\n return 1\n\n#changing reviews with score less than 3 to be positive and vice-versa\nactualScore = filtered_data['Score']\npositiveNegative = actualScore.map(partition) \nfiltered_data['Score'] = positiveNegative\nprint(\"Number of data points in our data\", filtered_data.shape)\n# filtered_data.head()\nprint()\nfiltered_data.tail()",
"Number of data points in our data (5000, 10)\n\n"
],
[
"display = pd.read_sql_query(\"\"\"\nSELECT UserId, ProductId, ProfileName, Time, Score, Text, COUNT(*)\nFROM Reviews\nGROUP BY UserId\nHAVING COUNT(*)>1\n\"\"\", con)",
"_____no_output_____"
],
[
"print(display.shape)\ndisplay.head()",
"(80668, 7)\n"
],
[
"display[display['UserId']=='AZY10LLTJ71NX']",
"_____no_output_____"
],
[
"display['COUNT(*)'].sum()",
"_____no_output_____"
]
],
[
[
"# Exploratory Data Analysis\n\n## [2] Data Cleaning: Deduplication\n\nIt is observed (as shown in the table below) that the reviews data had many duplicate entries. Hence it was necessary to remove duplicates in order to get unbiased results for the analysis of the data. Following is an example:",
"_____no_output_____"
]
],
[
[
"display= pd.read_sql_query(\"\"\"\nSELECT *\nFROM Reviews\nWHERE Score != 3 AND UserId=\"AR5J8UI46CURR\"\nORDER BY ProductID\n\"\"\", con)\ndisplay.head()",
"_____no_output_____"
]
],
[
[
"As can be seen above the same user has multiple reviews of the with the same values for HelpfulnessNumerator, HelpfulnessDenominator, Score, Time, Summary and Text and on doing analysis it was found that <br>\n<br> \nProductId=B000HDOPZG was Loacker Quadratini Vanilla Wafer Cookies, 8.82-Ounce Packages (Pack of 8)<br>\n<br> \nProductId=B000HDL1RQ was Loacker Quadratini Lemon Wafer Cookies, 8.82-Ounce Packages (Pack of 8) and so on<br>\n\nIt was inferred after analysis that reviews with same parameters other than ProductId belonged to the same product just having different flavour or quantity. Hence in order to reduce redundancy it was decided to eliminate the rows having same parameters.<br>\n\nThe method used for the same was that we first sort the data according to ProductId and then just keep the first similar product review and delelte the others. for eg. in the above just the review for ProductId=B000HDL1RQ remains. This method ensures that there is only one representative for each product and deduplication without sorting would lead to possibility of different representatives still existing for the same product.",
"_____no_output_____"
]
],
[
[
"#Sorting data according to ProductId in ascending order\nsorted_data=filtered_data.sort_values('ProductId', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')",
"_____no_output_____"
],
[
"#Deduplication of entries\nfinal=sorted_data.drop_duplicates(subset={\"UserId\",\"ProfileName\",\"Time\",\"Text\"}, keep='first', inplace=False)\nfinal.shape",
"_____no_output_____"
],
[
"#Checking to see how much % of data still remains\n(final['Id'].size*1.0)/(filtered_data['Id'].size*1.0)*100",
"_____no_output_____"
]
],
[
[
"<b>Observation:-</b> It was also seen that in two rows given below the value of HelpfulnessNumerator is greater than HelpfulnessDenominator which is not practically possible hence these two rows too are removed from calcualtions",
"_____no_output_____"
]
],
[
[
"display= pd.read_sql_query(\"\"\"\nSELECT *\nFROM Reviews\nWHERE Score != 3 AND Id=44737 OR Id=64422\nORDER BY ProductID\n\"\"\", con)\n\ndisplay.head()",
"_____no_output_____"
],
[
"final=final[final.HelpfulnessNumerator<=final.HelpfulnessDenominator]",
"_____no_output_____"
],
[
"#Before starting the next phase of preprocessing lets see the number of entries left\nprint(final.shape)\n\n#How many positive and negative reviews are present in our dataset?\nfinal['Score'].value_counts()",
"(4986, 10)\n"
]
],
[
[
"# [3]. Text Preprocessing.\n\nNow that we have finished deduplication our data requires some preprocessing before we go on further with analysis and making the prediction model.\n\nHence in the Preprocessing phase we do the following in the order below:-\n\n1. Begin by removing the html tags\n2. Remove any punctuations or limited set of special characters like , or . or # etc.\n3. Check if the word is made up of english letters and is not alpha-numeric\n4. Check to see if the length of the word is greater than 2 (as it was researched that there is no adjective in 2-letters)\n5. Convert the word to lowercase\n6. Remove Stopwords\n7. Finally Snowball Stemming the word (it was obsereved to be better than Porter Stemming)<br>\n\nAfter which we collect the words used to describe positive and negative reviews",
"_____no_output_____"
]
],
[
[
"# printing some random reviews\nsent_0 = final['Text'].values[0]\nprint(sent_0)\nprint(\"=\"*50)\n\nsent_1000 = final['Text'].values[1000]\nprint(sent_1000)\nprint(\"=\"*50)\n\nsent_1500 = final['Text'].values[1500]\nprint(sent_1500)\nprint(\"=\"*50)\n\nsent_4900 = final['Text'].values[4900]\nprint(sent_4900)\nprint(\"=\"*50)",
"Why is this $[...] when the same product is available for $[...] here?<br />http://www.amazon.com/VICTOR-FLY-MAGNET-BAIT-REFILL/dp/B00004RBDY<br /><br />The Victor M380 and M502 traps are unreal, of course -- total fly genocide. Pretty stinky, but only right nearby.\n==================================================\nI recently tried this flavor/brand and was surprised at how delicious these chips are. The best thing was that there were a lot of \"brown\" chips in the bsg (my favorite), so I bought some more through amazon and shared with family and friends. I am a little disappointed that there are not, so far, very many brown chips in these bags, but the flavor is still very good. I like them better than the yogurt and green onion flavor because they do not seem to be as salty, and the onion flavor is better. If you haven't eaten Kettle chips before, I recommend that you try a bag before buying bulk. They are thicker and crunchier than Lays but just as fresh out of the bag.\n==================================================\nWow. So far, two two-star reviews. One obviously had no idea what they were ordering; the other wants crispy cookies. Hey, I'm sorry; but these reviews do nobody any good beyond reminding us to look before ordering.<br /><br />These are chocolate-oatmeal cookies. If you don't like that combination, don't order this type of cookie. I find the combo quite nice, really. The oatmeal sort of \"calms\" the rich chocolate flavor and gives the cookie sort of a coconut-type consistency. Now let's also remember that tastes differ; so, I've given my opinion.<br /><br />Then, these are soft, chewy cookies -- as advertised. They are not \"crispy\" cookies, or the blurb would say \"crispy,\" rather than \"chewy.\" I happen to like raw cookie dough; however, I don't see where these taste like raw cookie dough. Both are soft, however, so is this the confusion? And, yes, they stick together. Soft cookies tend to do that. They aren't individually wrapped, which would add to the cost. Oh yeah, chocolate chip cookies tend to be somewhat sweet.<br /><br />So, if you want something hard and crisp, I suggest Nabiso's Ginger Snaps. If you want a cookie that's soft, chewy and tastes like a combination of chocolate and oatmeal, give these a try. I'm here to place my second order.\n==================================================\nlove to order my coffee on amazon. easy and shows up quickly.<br />This k cup is great coffee. dcaf is very good as well\n==================================================\n"
],
[
"# remove urls from text python: https://stackoverflow.com/a/40823105/4084039\nsent_0 = re.sub(r\"http\\S+\", \"\", sent_0)\nsent_1000 = re.sub(r\"http\\S+\", \"\", sent_1000)\nsent_150 = re.sub(r\"http\\S+\", \"\", sent_1500)\nsent_4900 = re.sub(r\"http\\S+\", \"\", sent_4900)\n\nprint(sent_0)",
"Why is this $[...] when the same product is available for $[...] here?<br /> /><br />The Victor M380 and M502 traps are unreal, of course -- total fly genocide. Pretty stinky, but only right nearby.\n"
],
[
"# https://stackoverflow.com/questions/16206380/python-beautifulsoup-how-to-remove-all-tags-from-an-element\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(sent_0, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_1000, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_1500, 'lxml')\ntext = soup.get_text()\nprint(text)\nprint(\"=\"*50)\n\nsoup = BeautifulSoup(sent_4900, 'lxml')\ntext = soup.get_text()\nprint(text)",
"Why is this $[...] when the same product is available for $[...] here? />The Victor M380 and M502 traps are unreal, of course -- total fly genocide. Pretty stinky, but only right nearby.\n==================================================\nI recently tried this flavor/brand and was surprised at how delicious these chips are. The best thing was that there were a lot of \"brown\" chips in the bsg (my favorite), so I bought some more through amazon and shared with family and friends. I am a little disappointed that there are not, so far, very many brown chips in these bags, but the flavor is still very good. I like them better than the yogurt and green onion flavor because they do not seem to be as salty, and the onion flavor is better. If you haven't eaten Kettle chips before, I recommend that you try a bag before buying bulk. They are thicker and crunchier than Lays but just as fresh out of the bag.\n==================================================\nWow. So far, two two-star reviews. One obviously had no idea what they were ordering; the other wants crispy cookies. Hey, I'm sorry; but these reviews do nobody any good beyond reminding us to look before ordering.These are chocolate-oatmeal cookies. If you don't like that combination, don't order this type of cookie. I find the combo quite nice, really. The oatmeal sort of \"calms\" the rich chocolate flavor and gives the cookie sort of a coconut-type consistency. Now let's also remember that tastes differ; so, I've given my opinion.Then, these are soft, chewy cookies -- as advertised. They are not \"crispy\" cookies, or the blurb would say \"crispy,\" rather than \"chewy.\" I happen to like raw cookie dough; however, I don't see where these taste like raw cookie dough. Both are soft, however, so is this the confusion? And, yes, they stick together. Soft cookies tend to do that. They aren't individually wrapped, which would add to the cost. Oh yeah, chocolate chip cookies tend to be somewhat sweet.So, if you want something hard and crisp, I suggest Nabiso's Ginger Snaps. If you want a cookie that's soft, chewy and tastes like a combination of chocolate and oatmeal, give these a try. I'm here to place my second order.\n==================================================\nlove to order my coffee on amazon. easy and shows up quickly.This k cup is great coffee. dcaf is very good as well\n"
],
[
"# https://stackoverflow.com/a/47091490/4084039\nimport re\n\ndef decontracted(phrase):\n # specific\n phrase = re.sub(r\"won't\", \"will not\", phrase)\n phrase = re.sub(r\"can\\'t\", \"can not\", phrase)\n\n # general\n phrase = re.sub(r\"n\\'t\", \" not\", phrase)\n phrase = re.sub(r\"\\'re\", \" are\", phrase)\n phrase = re.sub(r\"\\'s\", \" is\", phrase)\n phrase = re.sub(r\"\\'d\", \" would\", phrase)\n phrase = re.sub(r\"\\'ll\", \" will\", phrase)\n phrase = re.sub(r\"\\'t\", \" not\", phrase)\n phrase = re.sub(r\"\\'ve\", \" have\", phrase)\n phrase = re.sub(r\"\\'m\", \" am\", phrase)\n return phrase",
"_____no_output_____"
],
[
"sent_1500 = decontracted(sent_1500)\nprint(sent_1500)\nprint(\"=\"*50)",
"Wow. So far, two two-star reviews. One obviously had no idea what they were ordering; the other wants crispy cookies. Hey, I am sorry; but these reviews do nobody any good beyond reminding us to look before ordering.<br /><br />These are chocolate-oatmeal cookies. If you do not like that combination, do not order this type of cookie. I find the combo quite nice, really. The oatmeal sort of \"calms\" the rich chocolate flavor and gives the cookie sort of a coconut-type consistency. Now let is also remember that tastes differ; so, I have given my opinion.<br /><br />Then, these are soft, chewy cookies -- as advertised. They are not \"crispy\" cookies, or the blurb would say \"crispy,\" rather than \"chewy.\" I happen to like raw cookie dough; however, I do not see where these taste like raw cookie dough. Both are soft, however, so is this the confusion? And, yes, they stick together. Soft cookies tend to do that. They are not individually wrapped, which would add to the cost. Oh yeah, chocolate chip cookies tend to be somewhat sweet.<br /><br />So, if you want something hard and crisp, I suggest Nabiso is Ginger Snaps. If you want a cookie that is soft, chewy and tastes like a combination of chocolate and oatmeal, give these a try. I am here to place my second order.\n==================================================\n"
],
[
"#remove words with numbers python: https://stackoverflow.com/a/18082370/4084039\nsent_0 = re.sub(\"\\S*\\d\\S*\", \"\", sent_0).strip()\nprint(sent_0)",
"Why is this $[...] when the same product is available for $[...] here?<br /> /><br />The Victor and traps are unreal, of course -- total fly genocide. Pretty stinky, but only right nearby.\n"
],
[
"#remove spacial character: https://stackoverflow.com/a/5843547/4084039\nsent_1500 = re.sub('[^A-Za-z0-9]+', ' ', sent_1500)\nprint(sent_1500)",
"Wow So far two two star reviews One obviously had no idea what they were ordering the other wants crispy cookies Hey I am sorry but these reviews do nobody any good beyond reminding us to look before ordering br br These are chocolate oatmeal cookies If you do not like that combination do not order this type of cookie I find the combo quite nice really The oatmeal sort of calms the rich chocolate flavor and gives the cookie sort of a coconut type consistency Now let is also remember that tastes differ so I have given my opinion br br Then these are soft chewy cookies as advertised They are not crispy cookies or the blurb would say crispy rather than chewy I happen to like raw cookie dough however I do not see where these taste like raw cookie dough Both are soft however so is this the confusion And yes they stick together Soft cookies tend to do that They are not individually wrapped which would add to the cost Oh yeah chocolate chip cookies tend to be somewhat sweet br br So if you want something hard and crisp I suggest Nabiso is Ginger Snaps If you want a cookie that is soft chewy and tastes like a combination of chocolate and oatmeal give these a try I am here to place my second order \n"
],
[
"# https://gist.github.com/sebleier/554280\n# we are removing the words from the stop words list: 'no', 'nor', 'not'\n# <br /><br /> ==> after the above steps, we are getting \"br br\"\n# we are including them into stop words list\n# instead of <br /> if we have <br/> these tags would have revmoved in the 1st step\n\nstopwords= set(['br', 'the', 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \"you're\", \"you've\",\\\n \"you'll\", \"you'd\", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \\\n 'she', \"she's\", 'her', 'hers', 'herself', 'it', \"it's\", 'its', 'itself', 'they', 'them', 'their',\\\n 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', \"that'll\", 'these', 'those', \\\n 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \\\n 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \\\n 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\\\n 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\\\n 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\\\n 'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \\\n 's', 't', 'can', 'will', 'just', 'don', \"don't\", 'should', \"should've\", 'now', 'd', 'll', 'm', 'o', 're', \\\n 've', 'y', 'ain', 'aren', \"aren't\", 'couldn', \"couldn't\", 'didn', \"didn't\", 'doesn', \"doesn't\", 'hadn',\\\n \"hadn't\", 'hasn', \"hasn't\", 'haven', \"haven't\", 'isn', \"isn't\", 'ma', 'mightn', \"mightn't\", 'mustn',\\\n \"mustn't\", 'needn', \"needn't\", 'shan', \"shan't\", 'shouldn', \"shouldn't\", 'wasn', \"wasn't\", 'weren', \"weren't\", \\\n 'won', \"won't\", 'wouldn', \"wouldn't\"])",
"_____no_output_____"
],
[
"# Combining all the above stundents \nfrom tqdm import tqdm\npreprocessed_reviews = []\n# tqdm is for printing the status bar\nfor sentance in tqdm(final['Text'].values):\n sentance = re.sub(r\"http\\S+\", \"\", sentance)\n sentance = BeautifulSoup(sentance, 'lxml').get_text()\n sentance = decontracted(sentance)\n sentance = re.sub(\"\\S*\\d\\S*\", \"\", sentance).strip()\n sentance = re.sub('[^A-Za-z]+', ' ', sentance)\n # https://gist.github.com/sebleier/554280\n sentance = ' '.join(e.lower() for e in sentance.split() if e.lower() not in stopwords)\n preprocessed_reviews.append(sentance.strip())",
"100%|██████████| 4986/4986 [00:02<00:00, 2359.82it/s]\n"
],
[
"preprocessed_reviews[1500]",
"_____no_output_____"
]
],
[
[
"<h2><font color='red'>[3.2] Preprocess Summary</font></h2>",
"_____no_output_____"
]
],
[
[
"## Similartly you can do preprocessing for review summary also.",
"_____no_output_____"
]
],
[
[
"# [4] Featurization",
"_____no_output_____"
],
[
"## [4.1] BAG OF WORDS",
"_____no_output_____"
]
],
[
[
"#BoW\ncount_vect = CountVectorizer() #in scikit-learn\ncount_vect.fit(preprocessed_reviews)\nprint(\"some feature names \", count_vect.get_feature_names()[:10])\nprint('='*50)\n\nfinal_counts = count_vect.transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_counts))\nprint(\"the shape of out text BOW vectorizer \",final_counts.get_shape())\nprint(\"the number of unique words \", final_counts.get_shape()[1])",
"some feature names ['aa', 'aahhhs', 'aback', 'abandon', 'abates', 'abbott', 'abby', 'abdominal', 'abiding', 'ability']\n==================================================\nthe type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>\nthe shape of out text BOW vectorizer (4986, 12997)\nthe number of unique words 12997\n"
]
],
[
[
"## [4.2] Bi-Grams and n-Grams.",
"_____no_output_____"
]
],
[
[
"#bi-gram, tri-gram and n-gram\n\n#removing stop words like \"not\" should be avoided before building n-grams\n# count_vect = CountVectorizer(ngram_range=(1,2))\n# please do read the CountVectorizer documentation http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html\n# you can choose these numebrs min_df=10, max_features=5000, of your choice\ncount_vect = CountVectorizer(ngram_range=(1,2), min_df=10, max_features=5000)\nfinal_bigram_counts = count_vect.fit_transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_bigram_counts))\nprint(\"the shape of out text BOW vectorizer \",final_bigram_counts.get_shape())\nprint(\"the number of unique words including both unigrams and bigrams \", final_bigram_counts.get_shape()[1])",
"the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>\nthe shape of out text BOW vectorizer (4986, 3144)\nthe number of unique words including both unigrams and bigrams 3144\n"
]
],
[
[
"## [4.3] TF-IDF",
"_____no_output_____"
]
],
[
[
"tf_idf_vect = TfidfVectorizer(ngram_range=(1,2), min_df=10)\ntf_idf_vect.fit(preprocessed_reviews)\nprint(\"some sample features(unique words in the corpus)\",tf_idf_vect.get_feature_names()[0:10])\nprint('='*50)\n\nfinal_tf_idf = tf_idf_vect.transform(preprocessed_reviews)\nprint(\"the type of count vectorizer \",type(final_tf_idf))\nprint(\"the shape of out text TFIDF vectorizer \",final_tf_idf.get_shape())\nprint(\"the number of unique words including both unigrams and bigrams \", final_tf_idf.get_shape()[1])",
"some sample features(unique words in the corpus) ['ability', 'able', 'able find', 'able get', 'absolute', 'absolutely', 'absolutely delicious', 'absolutely love', 'absolutely no', 'according']\n==================================================\nthe type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>\nthe shape of out text TFIDF vectorizer (4986, 3144)\nthe number of unique words including both unigrams and bigrams 3144\n"
]
],
[
[
"## [4.4] Word2Vec",
"_____no_output_____"
]
],
[
[
"# Train your own Word2Vec model using your own text corpus\ni=0\nlist_of_sentance=[]\nfor sentance in preprocessed_reviews:\n list_of_sentance.append(sentance.split())",
"_____no_output_____"
],
[
"# Using Google News Word2Vectors\n\n# in this project we are using a pretrained model by google\n# its 3.3G file, once you load this into your memory \n# it occupies ~9Gb, so please do this step only if you have >12G of ram\n# we will provide a pickle file wich contains a dict , \n# and it contains all our courpus words as keys and model[word] as values\n# To use this code-snippet, download \"GoogleNews-vectors-negative300.bin\" \n# from https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit\n# it's 1.9GB in size.\n\n\n# http://kavita-ganesan.com/gensim-word2vec-tutorial-starter-code/#.W17SRFAzZPY\n# you can comment this whole cell\n# or change these varible according to your need\n\nis_your_ram_gt_16g=False\nwant_to_use_google_w2v = False\nwant_to_train_w2v = True\n\nif want_to_train_w2v:\n # min_count = 5 considers only words that occured atleast 5 times\n w2v_model=Word2Vec(list_of_sentance,min_count=5,size=50, workers=4)\n print(w2v_model.wv.most_similar('great'))\n print('='*50)\n print(w2v_model.wv.most_similar('worst'))\n \nelif want_to_use_google_w2v and is_your_ram_gt_16g:\n if os.path.isfile('GoogleNews-vectors-negative300.bin'):\n w2v_model=KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)\n print(w2v_model.wv.most_similar('great'))\n print(w2v_model.wv.most_similar('worst'))\n else:\n print(\"you don't have gogole's word2vec file, keep want_to_train_w2v = True, to train your own w2v \")",
"[('especially', 0.9966286420822144), ('wonderful', 0.9962908625602722), ('alternative', 0.9960046410560608), ('snack', 0.9958292245864868), ('fact', 0.9957460761070251), ('baked', 0.9957442283630371), ('excellent', 0.9957252144813538), ('describe', 0.9956888556480408), ('original', 0.9956517815589905), ('kids', 0.9956348538398743)]\n==================================================\n[('easily', 0.9994719624519348), ('close', 0.9994195699691772), ('must', 0.9993972778320312), ('wow', 0.9993919134140015), ('perhaps', 0.9993722438812256), ('beef', 0.9993717670440674), ('peanuts', 0.999367356300354), ('experience', 0.9993497133255005), ('cherry', 0.9993361830711365), ('tomatoes', 0.9993337988853455)]\n"
],
[
"w2v_words = list(w2v_model.wv.vocab)\nprint(\"number of words that occured minimum 5 times \",len(w2v_words))\nprint(\"sample words \", w2v_words[0:50])",
"number of words that occured minimum 5 times 3817\nsample words ['product', 'available', 'course', 'total', 'pretty', 'stinky', 'right', 'nearby', 'used', 'ca', 'not', 'beat', 'great', 'received', 'shipment', 'could', 'hardly', 'wait', 'try', 'love', 'call', 'instead', 'removed', 'easily', 'daughter', 'designed', 'printed', 'use', 'car', 'windows', 'beautifully', 'shop', 'program', 'going', 'lot', 'fun', 'everywhere', 'like', 'tv', 'computer', 'really', 'good', 'idea', 'final', 'outstanding', 'window', 'everybody', 'asks', 'bought', 'made']\n"
]
],
[
[
"## [4.4.1] Converting text into vectors using wAvg W2V, TFIDF-W2V",
"_____no_output_____"
],
[
"#### [4.4.1.1] Avg W2v",
"_____no_output_____"
]
],
[
[
"# average Word2Vec\n# compute average word2vec for each review.\nsent_vectors = []; # the avg-w2v for each sentence/review is stored in this list\nfor sent in tqdm(list_of_sentance): # for each review/sentence\n sent_vec = np.zeros(50) # as word vectors are of zero length 50, you might need to change this to 300 if you use google's w2v\n cnt_words =0; # num of words with a valid vector in the sentence/review\n for word in sent: # for each word in a review/sentence\n if word in w2v_words:\n vec = w2v_model.wv[word]\n sent_vec += vec\n cnt_words += 1\n if cnt_words != 0:\n sent_vec /= cnt_words\n sent_vectors.append(sent_vec)\nprint(len(sent_vectors))\nprint(len(sent_vectors[0]))",
"100%|██████████| 4986/4986 [00:06<00:00, 787.00it/s]"
]
],
[
[
"#### [4.4.1.2] TFIDF weighted W2v",
"_____no_output_____"
]
],
[
[
"# S = [\"abc def pqr\", \"def def def abc\", \"pqr pqr def\"]\nmodel = TfidfVectorizer()\nmodel.fit(preprocessed_reviews)\n# we are converting a dictionary with word as a key, and the idf as a value\ndictionary = dict(zip(model.get_feature_names(), list(model.idf_)))",
"_____no_output_____"
],
[
"# TF-IDF weighted Word2Vec\ntfidf_feat = model.get_feature_names() # tfidf words/col-names\n# final_tf_idf is the sparse matrix with row= sentence, col=word and cell_val = tfidf\n\ntfidf_sent_vectors = []; # the tfidf-w2v for each sentence/review is stored in this list\nrow=0;\nfor sent in tqdm(list_of_sentance): # for each review/sentence \n sent_vec = np.zeros(50) # as word vectors are of zero length\n weight_sum =0; # num of words with a valid vector in the sentence/review\n for word in sent: # for each word in a review/sentence\n if word in w2v_words and word in tfidf_feat:\n vec = w2v_model.wv[word]\n# tf_idf = tf_idf_matrix[row, tfidf_feat.index(word)]\n # to reduce the computation we are \n # dictionary[word] = idf value of word in whole courpus\n # sent.count(word) = tf valeus of word in this review\n tf_idf = dictionary[word]*(sent.count(word)/len(sent))\n sent_vec += (vec * tf_idf)\n weight_sum += tf_idf\n if weight_sum != 0:\n sent_vec /= weight_sum\n tfidf_sent_vectors.append(sent_vec)\n row += 1",
"100%|██████████| 4986/4986 [00:40<00:00, 123.46it/s]\n"
]
]
] | [
"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",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb05eadd0634f9c04d14152bd43d0d8ac077a3be | 1,316 | ipynb | Jupyter Notebook | library_learn/pymongo.ipynb | shiyeli/jupyter_notebook | eba4c070385708f8589bdc2dac4b785a70a9f460 | [
"MIT"
] | null | null | null | library_learn/pymongo.ipynb | shiyeli/jupyter_notebook | eba4c070385708f8589bdc2dac4b785a70a9f460 | [
"MIT"
] | null | null | null | library_learn/pymongo.ipynb | shiyeli/jupyter_notebook | eba4c070385708f8589bdc2dac4b785a70a9f460 | [
"MIT"
] | null | null | null | 20.5625 | 92 | 0.547112 | [
[
[
"## [Mongo Python Module Index](http://api.mongodb.com/python/current/py-modindex.html)",
"_____no_output_____"
]
],
[
[
"import pymongo\nimport bson\nimport datetime\nfrom bson import ObjectId\nfrom bson import DBRef\n\n# mongodb\nmongo_client = pymongo.MongoClient(host='mongodb://127.0.0.1:27017')\n\ntest = mongo_client.test\ndb = mongo_client.cloud\ncas = mongo_client.cas\nalarm = mongo_client.alarm\nbandwidth = mongo_client.bandwidth_db\n\ndata = db.user_group.find()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
cb05edf44b9112f442dab2c005319899006b4844 | 16,686 | ipynb | Jupyter Notebook | notebooks/notebook_gan64.ipynb | jbienkowski/saigon | a272f0eeca82d248352ffd7a6d6a9e68eeccd0db | [
"MIT"
] | null | null | null | notebooks/notebook_gan64.ipynb | jbienkowski/saigon | a272f0eeca82d248352ffd7a6d6a9e68eeccd0db | [
"MIT"
] | null | null | null | notebooks/notebook_gan64.ipynb | jbienkowski/saigon | a272f0eeca82d248352ffd7a6d6a9e68eeccd0db | [
"MIT"
] | null | null | null | 27.399015 | 117 | 0.522534 | [
[
[
"import os\nimport h5py\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom IPython import display\nfrom tensorflow.keras import layers\nfrom time import strftime\nfrom scipy.signal import spectrogram, stft, istft, resample",
"_____no_output_____"
],
[
"MODEL_NAME = \"GanPlayground\"\nSCALING_FACTOR = 0\nEPOCHS = 25\nBUFFER_SIZE = 1000\nBATCH_SIZE = 16\nNUM_EXAMPLES_TO_GENERATE = 1\nLATENT_DIM = 100\nSTEAD_PATH_DB_PROCESSED_STFT_64 = \"/Users/jarek/git/saigon/data/STEAD-processed-stft-64.hdf5\"",
"_____no_output_____"
],
[
"def plot_single_stream(do, label, fs=66, nperseg=127, file_path=None):\n d0 = pd.DataFrame(data=do)\n\n fig = plt.figure(figsize=(16, 16), dpi=60)\n ax1 = plt.subplot2grid((4, 1), (0, 0))\n ax2 = plt.subplot2grid((4, 1), (1, 0))\n ax3 = plt.subplot2grid((4, 1), (2, 0), rowspan=2)\n\n plt.subplots_adjust(hspace=0.5)\n\n sns.lineplot(data=do, ax=ax1, linewidth=1, legend=None)\n\n ax1.set_title(\"Waveform\")\n ax1.set(xlabel=\"Samples\", ylabel=\"Amplitude counts\")\n ax1.locator_params(nbins=6, axis=\"y\")\n\n f, t, Sxx = spectrogram(x=do, fs=fs)\n\n ax2.clear()\n ax2.set_title(\"Spectrogram\")\n ax2.pcolormesh(t, f, Sxx, shading=\"gouraud\")\n ax2.set(xlabel=\"Time [sec]\", ylabel=\"Frequency [Hz]\")\n\n f_sftt, t_sftt, Zxx = stft(do, window=\"hanning\", fs=fs, nperseg=nperseg)\n\n ax3.clear()\n ax3.set_title(\"STFT\")\n ax3.pcolormesh(t_sftt, f_sftt, np.abs(Zxx), shading=\"auto\")\n\n plt.suptitle(label, fontsize=14)\n\n if file_path != None:\n plt.savefig(file_path)\n else:\n plt.show()",
"_____no_output_____"
],
[
"def plot_stft(stream, fs=100, nperseg=155):\n f, t, Zxx = stft(stream, window='hanning', fs=fs, nperseg=nperseg)\n # plt.specgram(x_1[0][0], cmap='plasma', Fs=100)\n plt.pcolormesh(t, f, np.abs(Zxx), shading='auto')",
"_____no_output_____"
],
[
"def get_stft_data(file_path, arr_length):\n with h5py.File(file_path, \"r\") as f:\n keys = f[\"keys\"][:arr_length]\n components = f[\"components\"][:arr_length]\n data = f[\"data\"][:arr_length]\n return (keys, components, data)",
"_____no_output_____"
]
],
[
[
"# Read processed data",
"_____no_output_____"
]
],
[
[
"(keys, components, x_train) = get_stft_data(\n STEAD_PATH_DB_PROCESSED_STFT_64, 10000\n)",
"_____no_output_____"
]
],
[
[
"# Convert streams to STFT",
"_____no_output_____"
]
],
[
[
"# STFT of the stream and then reverse STFT back into original stream\n# f, t, Zxx = stft(x_1[1][0], window='hanning', fs=100, nperseg=155)\n# k2 = istft(Zxx, window='hanning', fs=100, nperseg=155)",
"_____no_output_____"
]
],
[
[
"# Scale and reshape data",
"_____no_output_____"
]
],
[
[
"SCALING_FACTOR = int(\n max(\n [\n abs(min([x.min() for x in x_train])),\n abs(max([x.max() for x in x_train])),\n ]\n )\n)\nSCALING_FACTOR",
"_____no_output_____"
],
[
"x_train /= SCALING_FACTOR",
"_____no_output_____"
],
[
"x_train = x_train.reshape(x_train.shape[0], 64, 64, 1)",
"_____no_output_____"
],
[
"train_dataset = (\n tf.data.Dataset.from_tensor_slices(x_train)\n .shuffle(BUFFER_SIZE)\n .batch(BATCH_SIZE)\n)",
"_____no_output_____"
],
[
"train_dataset",
"_____no_output_____"
]
],
[
[
"# Logs and Tensorboard",
"_____no_output_____"
]
],
[
[
"folder_name = f\"{MODEL_NAME} at {strftime('%H:%M')}\"\nlog_dir = os.path.join(\"../log/\", folder_name)\n\ntry:\n os.makedirs(log_dir)\nexcept OSError as exception:\n print(exception.strerror)\nelse:\n print(\"Successfully created dirs!\")",
"_____no_output_____"
]
],
[
[
"# Define GAN",
"_____no_output_____"
]
],
[
[
"def make_generator_model():\n model = tf.keras.Sequential()\n model.add(\n layers.Dense(2 * 2 * 128, use_bias=False, input_shape=(LATENT_DIM,))\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(layers.Reshape((2, 2, 128)))\n\n model.add(\n layers.Conv2DTranspose(\n 64, (20, 20), strides=(2, 2), padding=\"same\", use_bias=False\n )\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(\n layers.Conv2DTranspose(\n 64, (20, 20), strides=(2, 2), padding=\"same\", use_bias=False\n )\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(\n layers.Conv2DTranspose(\n 64, (20, 20), strides=(2, 2), padding=\"same\", use_bias=False\n )\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(\n layers.Conv2DTranspose(\n 64, (20, 20), strides=(2, 2), padding=\"same\", use_bias=False\n )\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(\n layers.Conv2DTranspose(\n 64, (20, 20), strides=(2, 2), padding=\"same\", use_bias=False\n )\n )\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n model.add(\n layers.Conv2DTranspose(\n 1,\n (1, 1),\n strides=(1, 1),\n padding=\"same\",\n use_bias=False,\n activation=\"tanh\",\n )\n )\n\n return model",
"_____no_output_____"
],
[
"generator = make_generator_model()\n\n# noise = tf.random.normal(dtype=tf.dtypes.float32, shape=[78, 78], stddev=5)\nnoise = tf.random.normal([BATCH_SIZE, LATENT_DIM], stddev=10e5)\ngenerated_stft = generator(noise, training=False)\n\ngenerated_stft.shape",
"_____no_output_____"
],
[
"tf.keras.utils.plot_model(generator, show_shapes=True)",
"_____no_output_____"
],
[
"inversed = istft(generated_stft[0, :, :, 0], window='hanning', fs=66, nperseg=127)\nplot_single_stream(inversed[1][:4000], \"GAN Generator Noise\")",
"_____no_output_____"
],
[
"def make_discriminator_model():\n model = tf.keras.Sequential()\n model.add(\n layers.Conv2D(64, (5, 5), strides=(2, 2), padding=\"same\", input_shape=[64, 64, 1])\n )\n model.add(layers.LeakyReLU())\n model.add(layers.Dropout(0.3))\n\n model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding=\"same\"))\n model.add(layers.LeakyReLU())\n model.add(layers.Dropout(0.3))\n\n model.add(layers.Flatten())\n model.add(layers.Dense(1))\n\n return model",
"_____no_output_____"
],
[
"discriminator = make_discriminator_model()\ndecision = discriminator(generated_stft)\ndecision",
"_____no_output_____"
],
[
"# This method returns a helper function to compute cross entropy loss\ncross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)",
"_____no_output_____"
],
[
"def discriminator_loss(real_output, fake_output):\n real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n total_loss = real_loss + fake_loss\n return total_loss",
"_____no_output_____"
],
[
"def generator_loss(fake_output):\n return cross_entropy(tf.ones_like(fake_output), fake_output)",
"_____no_output_____"
],
[
"generator_optimizer = tf.keras.optimizers.Adam(1e-4)\ndiscriminator_optimizer = tf.keras.optimizers.Adam(1e-4)",
"_____no_output_____"
],
[
"checkpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n discriminator_optimizer=discriminator_optimizer,\n generator=generator,\n discriminator=discriminator)",
"_____no_output_____"
],
[
"# You will reuse this seed overtime (so it's easier)\n# to visualize progress in the animated GIF)\nseed = tf.random.normal([NUM_EXAMPLES_TO_GENERATE, LATENT_DIM])",
"_____no_output_____"
],
[
"# Notice the use of `tf.function`\n# This annotation causes the function to be \"compiled\".\[email protected]\ndef train_step(images):\n noise = tf.random.normal([BATCH_SIZE, LATENT_DIM])\n\n with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n generated_images = generator(noise, training=True)\n\n real_output = discriminator(images, training=True)\n fake_output = discriminator(generated_images, training=True)\n\n gen_loss = generator_loss(fake_output)\n disc_loss = discriminator_loss(real_output, fake_output)\n\n gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)\n gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)\n\n generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))\n discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))",
"_____no_output_____"
],
[
"def train(dataset, epochs):\n for epoch in range(epochs):\n start = time.time()\n\n for image_batch in dataset:\n train_step(image_batch)\n\n # Produce images for the GIF as you go\n display.clear_output(wait=True)\n generate_and_save_images(generator,\n epoch + 1,\n seed)\n\n # Save the model every 15 epochs\n if (epoch + 1) % 15 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n\n # Generate after the final epoch\n display.clear_output(wait=True)\n generate_and_save_images(generator,\n epochs,\n seed)",
"_____no_output_____"
],
[
"def generate_and_save_images(model, epoch, test_input):\n # Notice `training` is set to False.\n # This is so all layers run in inference mode (batchnorm).\n predictions = model(test_input, training=False)\n\n for i in range(predictions.shape[0]):\n inversed = istft(\n predictions[i, :, :, 0][:4000], window=\"hanning\", fs=66, nperseg=127\n )\n plot_single_stream(\n inversed[1][:4000],\n f\"GAN Event (epoch {epoch})\",\n # file_path=f\"out/image_at_epoch_{epoch}.jpg\"\n )",
"_____no_output_____"
],
[
"train(train_dataset, EPOCHS)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb05f179356f4eb9027b713bd958a94773f3b42c | 61,785 | ipynb | Jupyter Notebook | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to | 79601b9d3dd2e2d389e324621e0792f5056fa428 | [
"MIT"
] | null | null | null | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to | 79601b9d3dd2e2d389e324621e0792f5056fa428 | [
"MIT"
] | null | null | null | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to | 79601b9d3dd2e2d389e324621e0792f5056fa428 | [
"MIT"
] | null | null | null | 88.517192 | 18,250 | 0.771417 | [
[
[
"# Introduction ",
"_____no_output_____"
],
[
"This is a basic tutorial on using Jupyter to use the scipy modules.",
"_____no_output_____"
],
[
"# Example of plotting sine and cosine functions in the same plot",
"_____no_output_____"
],
[
"Install matplotlib through conda via:\n\n conda install -y matplotlib",
"_____no_output_____"
],
[
"Below we plot a sine function from 0 to 2 pi. Pretty much what you would expect:",
"_____no_output_____"
]
],
[
[
"import math\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt \nimport numpy as np \n\nx = np.linspace(0, 3 * math.pi, 50)\ny = np.sin(x)\nplt.plot(x, y)\nplt.show()",
"_____no_output_____"
]
],
[
[
"The x values limit the range of the plot.",
"_____no_output_____"
],
[
"Let's get help on the plt.plot function, so as to understand how to use it, in addition to the tutorial at http://matplotlib.org/users/pyplot_tutorial.html",
"_____no_output_____"
]
],
[
[
"help(plt.plot)",
"Help on function plot in module matplotlib.pyplot:\n\nplot(*args, **kwargs)\n Plot lines and/or markers to the\n :class:`~matplotlib.axes.Axes`. *args* is a variable length\n argument, allowing for multiple *x*, *y* pairs with an\n optional format string. For example, each of the following is\n legal::\n \n plot(x, y) # plot x and y using default line style and color\n plot(x, y, 'bo') # plot x and y using blue circle markers\n plot(y) # plot y using x as index array 0..N-1\n plot(y, 'r+') # ditto, but with red plusses\n \n If *x* and/or *y* is 2-dimensional, then the corresponding columns\n will be plotted.\n \n If used with labeled data, make sure that the color spec is not\n included as an element in data, as otherwise the last case\n ``plot(\"v\",\"r\", data={\"v\":..., \"r\":...)``\n can be interpreted as the first case which would do ``plot(v, r)``\n using the default line style and color.\n \n If not used with labeled data (i.e., without a data argument),\n an arbitrary number of *x*, *y*, *fmt* groups can be specified, as in::\n \n a.plot(x1, y1, 'g^', x2, y2, 'g-')\n \n Return value is a list of lines that were added.\n \n By default, each line is assigned a different style specified by a\n 'style cycle'. To change this behavior, you can edit the\n axes.prop_cycle rcParam.\n \n The following format string characters are accepted to control\n the line style or marker:\n \n ================ ===============================\n character description\n ================ ===============================\n ``'-'`` solid line style\n ``'--'`` dashed line style\n ``'-.'`` dash-dot line style\n ``':'`` dotted line style\n ``'.'`` point marker\n ``','`` pixel marker\n ``'o'`` circle marker\n ``'v'`` triangle_down marker\n ``'^'`` triangle_up marker\n ``'<'`` triangle_left marker\n ``'>'`` triangle_right marker\n ``'1'`` tri_down marker\n ``'2'`` tri_up marker\n ``'3'`` tri_left marker\n ``'4'`` tri_right marker\n ``'s'`` square marker\n ``'p'`` pentagon marker\n ``'*'`` star marker\n ``'h'`` hexagon1 marker\n ``'H'`` hexagon2 marker\n ``'+'`` plus marker\n ``'x'`` x marker\n ``'D'`` diamond marker\n ``'d'`` thin_diamond marker\n ``'|'`` vline marker\n ``'_'`` hline marker\n ================ ===============================\n \n \n The following color abbreviations are supported:\n \n ========== ========\n character color\n ========== ========\n 'b' blue\n 'g' green\n 'r' red\n 'c' cyan\n 'm' magenta\n 'y' yellow\n 'k' black\n 'w' white\n ========== ========\n \n In addition, you can specify colors in many weird and\n wonderful ways, including full names (``'green'``), hex\n strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or\n grayscale intensities as a string (``'0.8'``). Of these, the\n string specifications can be used in place of a ``fmt`` group,\n but the tuple forms can be used only as ``kwargs``.\n \n Line styles and colors are combined in a single format string, as in\n ``'bo'`` for blue circles.\n \n The *kwargs* can be used to set line properties (any property that has\n a ``set_*`` method). You can use this to set a line label (for auto\n legends), linewidth, anitialising, marker face color, etc. Here is an\n example::\n \n plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)\n plot([1,2,3], [1,4,9], 'rs', label='line 2')\n axis([0, 4, 0, 10])\n legend()\n \n If you make multiple lines with one plot command, the kwargs\n apply to all those lines, e.g.::\n \n plot(x1, y1, x2, y2, antialiased=False)\n \n Neither line will be antialiased.\n \n You do not need to use format strings, which are just\n abbreviations. All of the line properties can be controlled\n by keyword arguments. For example, you can set the color,\n marker, linestyle, and markercolor with::\n \n plot(x, y, color='green', linestyle='dashed', marker='o',\n markerfacecolor='blue', markersize=12).\n \n See :class:`~matplotlib.lines.Line2D` for details.\n \n The kwargs are :class:`~matplotlib.lines.Line2D` properties:\n \n agg_filter: unknown\n alpha: float (0.0 transparent through 1.0 opaque) \n animated: [True | False] \n antialiased or aa: [True | False] \n axes: an :class:`~matplotlib.axes.Axes` instance \n clip_box: a :class:`matplotlib.transforms.Bbox` instance \n clip_on: [True | False] \n clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] \n color or c: any matplotlib color \n contains: a callable function \n dash_capstyle: ['butt' | 'round' | 'projecting'] \n dash_joinstyle: ['miter' | 'round' | 'bevel'] \n dashes: sequence of on/off ink in points \n drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] \n figure: a :class:`matplotlib.figure.Figure` instance \n fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] \n gid: an id string \n label: string or anything printable with '%s' conversion. \n linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]\n linewidth or lw: float value in points \n marker: :mod:`A valid marker style <matplotlib.markers>`\n markeredgecolor or mec: any matplotlib color \n markeredgewidth or mew: float value in points \n markerfacecolor or mfc: any matplotlib color \n markerfacecoloralt or mfcalt: any matplotlib color \n markersize or ms: float \n markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]\n path_effects: unknown\n picker: float distance in points or callable pick function ``fn(artist, event)`` \n pickradius: float distance in points \n rasterized: [True | False | None] \n sketch_params: unknown\n snap: unknown\n solid_capstyle: ['butt' | 'round' | 'projecting'] \n solid_joinstyle: ['miter' | 'round' | 'bevel'] \n transform: a :class:`matplotlib.transforms.Transform` instance \n url: a url string \n visible: [True | False] \n xdata: 1D array \n ydata: 1D array \n zorder: any number \n \n kwargs *scalex* and *scaley*, if defined, are passed on to\n :meth:`~matplotlib.axes.Axes.autoscale_view` to determine\n whether the *x* and *y* axes are autoscaled; the default is\n *True*.\n \n .. note::\n In addition to the above described arguments, this function can take a\n **data** keyword argument. If such a **data** argument is given, the\n following arguments are replaced by **data[<arg>]**:\n \n * All arguments with the following names: 'x', 'y'.\n\n"
]
],
[
[
"Let's add in 'bo' string to the mix to get dots on the trace:",
"_____no_output_____"
]
],
[
[
"import math\nimport matplotlib.pyplot as plt \nimport numpy as np \n\nx = np.linspace(0, 2 * math.pi, 50)\ny = np.sin(x)\nplt.plot(x, y, 'bo')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Let's try to add two traces, the second one is a cosine function:",
"_____no_output_____"
]
],
[
[
"import math\nimport matplotlib.pyplot as plt \nimport numpy as np \n\nx = np.linspace(0,2 * math.pi, 50)\ny1 = np.sin(x)\ny2 = np.cos(x)\n\nplt.plot(x, y1, 'bo', x, y2, 'r+')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Example of using optimize.fmin on the sine function",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nfrom scipy import linalg, optimize\n\n# Here, we called this function \"func2\" which is pretty arbitrary. You will need to use better name in practice, of course:\ndef func2(x):\n return np.sin(x)\n\noptimize.fmin(func2, math.pi - 0.01)",
"Optimization terminated successfully.\n Current function value: -1.000000\n Iterations: 17\n Function evaluations: 34\n"
]
],
[
[
"Pretty much what we expected. There is a minimum of -1 for this sine wave function (amplitude of 1 here ... would have been different if we multiplied the sine wave by some other factor). We can call the f function to see the value at that point which is pretty darn close to -1:",
"_____no_output_____"
]
],
[
[
"func2(4.71237414)",
"_____no_output_____"
],
[
"math.pi * 2 * 0.75",
"_____no_output_____"
]
],
[
[
"# Example of using optimize.root on the sine function",
"_____no_output_____"
]
],
[
[
"help(optimize.root)",
"Help on function root in module scipy.optimize._root:\n\nroot(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None, options=None)\n Find a root of a vector function.\n \n Parameters\n ----------\n fun : callable\n A vector function to find a root of.\n x0 : ndarray\n Initial guess.\n args : tuple, optional\n Extra arguments passed to the objective function and its Jacobian.\n method : str, optional\n Type of solver. Should be one of\n \n - 'hybr' :ref:`(see here) <optimize.root-hybr>`\n - 'lm' :ref:`(see here) <optimize.root-lm>`\n - 'broyden1' :ref:`(see here) <optimize.root-broyden1>`\n - 'broyden2' :ref:`(see here) <optimize.root-broyden2>`\n - 'anderson' :ref:`(see here) <optimize.root-anderson>`\n - 'linearmixing' :ref:`(see here) <optimize.root-linearmixing>`\n - 'diagbroyden' :ref:`(see here) <optimize.root-diagbroyden>`\n - 'excitingmixing' :ref:`(see here) <optimize.root-excitingmixing>`\n - 'krylov' :ref:`(see here) <optimize.root-krylov>`\n - 'df-sane' :ref:`(see here) <optimize.root-dfsane>`\n \n jac : bool or callable, optional\n If `jac` is a Boolean and is True, `fun` is assumed to return the\n value of Jacobian along with the objective function. If False, the\n Jacobian will be estimated numerically.\n `jac` can also be a callable returning the Jacobian of `fun`. In\n this case, it must accept the same arguments as `fun`.\n tol : float, optional\n Tolerance for termination. For detailed control, use solver-specific\n options.\n callback : function, optional\n Optional callback function. It is called on every iteration as\n ``callback(x, f)`` where `x` is the current solution and `f`\n the corresponding residual. For all methods but 'hybr' and 'lm'.\n options : dict, optional\n A dictionary of solver options. E.g. `xtol` or `maxiter`, see\n :obj:`show_options()` for details.\n \n Returns\n -------\n sol : OptimizeResult\n The solution represented as a ``OptimizeResult`` object.\n Important attributes are: ``x`` the solution array, ``success`` a\n Boolean flag indicating if the algorithm exited successfully and\n ``message`` which describes the cause of the termination. See\n `OptimizeResult` for a description of other attributes.\n \n See also\n --------\n show_options : Additional options accepted by the solvers\n \n Notes\n -----\n This section describes the available solvers that can be selected by the\n 'method' parameter. The default method is *hybr*.\n \n Method *hybr* uses a modification of the Powell hybrid method as\n implemented in MINPACK [1]_.\n \n Method *lm* solves the system of nonlinear equations in a least squares\n sense using a modification of the Levenberg-Marquardt algorithm as\n implemented in MINPACK [1]_.\n \n Method *df-sane* is a derivative-free spectral method. [3]_\n \n Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*,\n *diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods,\n with backtracking or full line searches [2]_. Each method corresponds\n to a particular Jacobian approximations. See `nonlin` for details.\n \n - Method *broyden1* uses Broyden's first Jacobian approximation, it is\n known as Broyden's good method.\n - Method *broyden2* uses Broyden's second Jacobian approximation, it\n is known as Broyden's bad method.\n - Method *anderson* uses (extended) Anderson mixing.\n - Method *Krylov* uses Krylov approximation for inverse Jacobian. It\n is suitable for large-scale problem.\n - Method *diagbroyden* uses diagonal Broyden Jacobian approximation.\n - Method *linearmixing* uses a scalar Jacobian approximation.\n - Method *excitingmixing* uses a tuned diagonal Jacobian\n approximation.\n \n .. warning::\n \n The algorithms implemented for methods *diagbroyden*,\n *linearmixing* and *excitingmixing* may be useful for specific\n problems, but whether they will work may depend strongly on the\n problem.\n \n .. versionadded:: 0.11.0\n \n References\n ----------\n .. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom.\n 1980. User Guide for MINPACK-1.\n .. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear\n Equations. Society for Industrial and Applied Mathematics.\n <http://www.siam.org/books/kelley/>\n .. [3] W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. 75, 1429 (2006).\n \n Examples\n --------\n The following functions define a system of nonlinear equations and its\n jacobian.\n \n >>> def fun(x):\n ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,\n ... 0.5 * (x[1] - x[0])**3 + x[1]]\n \n >>> def jac(x):\n ... return np.array([[1 + 1.5 * (x[0] - x[1])**2,\n ... -1.5 * (x[0] - x[1])**2],\n ... [-1.5 * (x[1] - x[0])**2,\n ... 1 + 1.5 * (x[1] - x[0])**2]])\n \n A solution can be obtained as follows.\n \n >>> from scipy import optimize\n >>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr')\n >>> sol.x\n array([ 0.8411639, 0.1588361])\n\n"
]
],
[
[
"Let's evaludate the f function (which we know is a sine function) at not quite at the point where it is zero (at pi):",
"_____no_output_____"
]
],
[
[
"func2(math.pi * 0.75)",
"_____no_output_____"
],
[
"import math\nimport numpy as np\nfrom scipy import linalg, optimize\n\n# Here, we called this function \"func2\" which is pretty arbitrary. You will need to use better name in practice, of course:\ndef func2(x):\n return np.sin(x)\n\noptimize.root(func2, math.pi * 0.75)",
"_____no_output_____"
]
],
[
[
"So it found the root at pi. Notice the \"x\" value at the end of the output.\n\nYou can turn off the verbose output using keyword arguments to the `optimize.root` function.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb05f2addb81e87028c51dc0d480c35b30c6880c | 1,743 | ipynb | Jupyter Notebook | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | arifmudi/The-Data-Wrangling-Workshop | c325f6fa1c6daf8dd22e9705df48ce2644217a73 | [
"MIT"
] | 22 | 2020-06-27T04:21:49.000Z | 2022-03-08T04:39:44.000Z | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | arifmudi/The-Data-Wrangling-Workshop | c325f6fa1c6daf8dd22e9705df48ce2644217a73 | [
"MIT"
] | 2 | 2021-02-02T22:49:16.000Z | 2021-06-02T02:09:21.000Z | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | Hubertus444/The-Data-Wrangling-Workshop | ddad20f8676602ac6624e72e802769fcaff45b0f | [
"MIT"
] | 46 | 2020-04-20T13:04:11.000Z | 2022-03-22T05:23:52.000Z | 17.785714 | 56 | 0.491681 | [
[
[
"## Exercise 18: Lambda Expression ",
"_____no_output_____"
],
[
"1. Import the math package ",
"_____no_output_____"
]
],
[
[
"import math ",
"_____no_output_____"
]
],
[
[
"2. Define two functions, my_sine and my_cosine",
"_____no_output_____"
]
],
[
[
"def my_sine(): \n return lambda x: math.sin(math.radians(x)) \n\ndef my_cosine(): \n return lambda x: math.cos(math.radians(x)) ",
"_____no_output_____"
]
],
[
[
"3. Define sine and cosine for our purpose",
"_____no_output_____"
]
],
[
[
"sine = my_sine() \ncosine = my_cosine() \nmath.pow(sine(30), 2) + math.pow(cosine(30), 2) ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb05f9d590011cc341a4cac9b090b38551ea18c4 | 5,666 | ipynb | Jupyter Notebook | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos | f16a11b4bba6b1927ee47677f000e8fa53f8b39b | [
"MIT"
] | null | null | null | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos | f16a11b4bba6b1927ee47677f000e8fa53f8b39b | [
"MIT"
] | null | null | null | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos | f16a11b4bba6b1927ee47677f000e8fa53f8b39b | [
"MIT"
] | null | null | null | 24.317597 | 247 | 0.53724 | [
[
[
"# Métodos de punto fijo I",
"_____no_output_____"
],
[
"En esta ocasión empezaremos a implementar un método para obtener una raiz real de una ecuación no lineal. Este método se le conoce como punto fijo, pero la variante especificamente que implementaremos ahora es la de aproximaciones sucesivas.",
"_____no_output_____"
],
[
"## Aproximaciones sucesivas",
"_____no_output_____"
],
[
"Tenemos un polinomio $f(x) = 2 x^2 - x - 5$ y un valor inicial $x_0 = 1$ y queremos saber cuales son sus raices reales. Lo primero que tenemos que hacer es pasarlo a la siguiente forma:\n\n$$x = g(x)$$\n\nPodemos notar que hay muchas maneras de hacer esto, como por ejemplo:\n\n* $x = 2 x^2 - 5$\n* $x = \\sqrt{\\frac{x + 5}{2}}$\n* $x = \\frac{5}{2x - 1}$\n\nPero no todas estas formas nos proveerán de un calculo que converja hacia la solución, por lo que tenemos que analizar la convergencia de cada una, hasta que encontremos una que nos acomode.\n\nSabemos que si el valor absoluto de la primera derivada de $g(x)$ es menor a 1, $\\left| g'(x) < 1 \\right|$, converjerá adecuadamente, por lo que esto es lo que analizaremos ahora:\n\n* $g_1(x) = 2 x^2 - 5$, entonces $g_1'(x) = 4 x$\n* $g_2(x) = \\sqrt{\\frac{x + 5}{2}}$, entonces $g_2' = \\frac{1}{2} \\frac{1}{\\sqrt{2(x + 5)}}$\n* $g_3(x) = \\frac{5}{2x - 1}$, entonces $g_3'(x) = - \\frac{10}{(2x - 1)^2}$\n\nDe aqui podemos ver que $g_1'(x_0) = 4$, por lo que no converjerá a la solución. $g_2'(x_0) = \\frac{1}{2\\sqrt{12}}$ en cambio, si nos da un numero menor a 1, por lo que es indicada para hacer iteraciones.",
"_____no_output_____"
]
],
[
[
"from numpy import sqrt",
"_____no_output_____"
],
[
"1/(2*sqrt(12))",
"_____no_output_____"
]
],
[
[
"Entonces ya tenemos una formula para iterar a través:\n\n$$x_1 = g(x_0)$$\n\nes decir:\n\n$$x_1 = \\sqrt{\\frac{x_0 + 5}{2}}$$",
"_____no_output_____"
]
],
[
[
"x_0 = 1\ng = lambda x: sqrt((x+5)/2)\nx_1 = g(x_0)\nx_1",
"_____no_output_____"
]
],
[
[
"Y ya tenemos la primera iteración. Cuando dejaremos de iterar? Cuando el error $\\varepsilon = x_1 - x_0$ sea menor a $0.001$ (para este ejemplo).",
"_____no_output_____"
]
],
[
[
"abs(x_1 - x_0)",
"_____no_output_____"
]
],
[
[
"Como podemos ver, aun falta mucho... pero podemos decirle a la computadora que lo siga haciendo sin notsotros. Primero creamos una funcion que itere la funcion g hasta que la diferencia de las ultimas iteraciones sea menor al error.",
"_____no_output_____"
]
],
[
[
"def aprox_sucesivas(g, x0, error):\n xs = [x0]\n while True:\n xs.append(g(xs[-1]))\n if abs(xs[-1] - xs[-2]) <= error:\n return xs[-1]",
"_____no_output_____"
]
],
[
[
"Y ahora le damos a esta funcion nuestra $g(x)$, el punto donde queremos que inicie $x_0$ y el error maximo permitido.",
"_____no_output_____"
]
],
[
[
"r = aprox_sucesivas(g, 0, 0.001)\nr",
"_____no_output_____"
],
[
"from numpy import sin",
"_____no_output_____"
]
],
[
[
"Creamos una funcion en codigo, que contiene la función original, para evaluar que tan bien se aproximo la raiz.",
"_____no_output_____"
]
],
[
[
"f = lambda x: 2*x**2 - x - 5",
"_____no_output_____"
],
[
"f(r)",
"_____no_output_____"
]
],
[
[
"Y como podemos ver hizo un muy buen trabajo sin nuestra supervision :)",
"_____no_output_____"
],
[
"## Ejercicio",
"_____no_output_____"
],
[
"1. Encuentra la segunda raiz de este polinomio.\n2. Implementa el método de la secante.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cb05fc6272aedbe809a0ec486eaed65e83bfb1cc | 472,471 | ipynb | Jupyter Notebook | TinyDB.ipynb | Nop287/game_db | 0348194ad8590b1e8c9cb4d6f9e763012466f2a2 | [
"BSD-2-Clause"
] | null | null | null | TinyDB.ipynb | Nop287/game_db | 0348194ad8590b1e8c9cb4d6f9e763012466f2a2 | [
"BSD-2-Clause"
] | null | null | null | TinyDB.ipynb | Nop287/game_db | 0348194ad8590b1e8c9cb4d6f9e763012466f2a2 | [
"BSD-2-Clause"
] | null | null | null | 269.521392 | 9,839 | 0.598591 | [
[
[
"import pandas as pd\nimport os\nimport json\nimport re\nfrom tinydb import TinyDB, Query\nimport sqlalchemy as db",
"_____no_output_____"
]
],
[
[
"# Building the Database\n\nWe use a database in the backend to serve the data over a REST API to our client. The database is being built with the data frame generated using the `build_game_db.ipynb` notebook. We stored it in the feather format as it is both efficient and compact. We start by reading the stored data frame.",
"_____no_output_____"
]
],
[
[
"df_tmp = pd.read_feather(\"spiele_db.ftr\")\n\ndf_tmp",
"_____no_output_____"
]
],
[
[
"We use TinyDB aus our backend. Note that TinyDB is not fit for production use. Up to a few hundred or even a few thousand entries it will do. The advantage is that it is a document database, so it should be possible to port with reasonable effort to a larger scale document database such as MongoDB or CouchDB. Note that this will make our architecture more complex since we will need a separate database server.\n\nWe create a new TinyDB database which is basically a JSON file in a specific structure.",
"_____no_output_____"
]
],
[
[
"if os.path.exists('spiele_tinydb.json'):\n os.remove('spiele_tinydb.json')\n\ngame_db = TinyDB('spiele_tinydb.json')",
"_____no_output_____"
]
],
[
[
"Now we just insert our data frame row by row. Note that this is time consuming. As a workaround we could directly manipulate the JSON but this may not work with future TinyDB versions.",
"_____no_output_____"
]
],
[
[
"for i in df_tmp.index:\n game_db.insert(json.loads(df_tmp.loc[i].to_json()))",
"_____no_output_____"
]
],
[
[
"Once we have the TinyDB database we can query it. The syntax is a bit clumsy, but generally it works. In my configuration case insensitive search did not work for some unknow reason.",
"_____no_output_____"
]
],
[
[
"my_query = Query()\n\nquery_result = game_db.search(my_query.game_title.matches('.*Dark.*', flags=re.IGNORECASE))\n\nfor item in query_result:\n print(item[\"game_title\"], \" / \", item[\"game_igdb_name\"], \": \", round(item[\"game_rating\"], 2), \" / \", item[\"game_rating_count\"])",
"Darksiders II Deathinitive Edition / Darksiders II: Deathinitive Edition : 74.78 / 59\nDark Cloud 2 / Dark Cloud 2 : 87.56 / 33\nDarksiders III / Darksiders III : 70.46 / 80\n"
]
],
[
[
"Since we are dealing with JSON here there will be entries where some values are not set in the JSON. Unfortunately searching for them the gives an error. So we have to use a lambda function for searching.",
"_____no_output_____"
]
],
[
[
"def search_by_rating(min_rating = 0, max_rating = 100):\n my_query = Query()\n test_func = lambda s: True if(isinstance(s, float) and s >= min_rating and s <= max_rating) else False\n return game_db.search(my_query.game_rating.test(test_func))\n\nquery_result = search_by_rating(90)\n\nprint(print(json.dumps(query_result, indent=4, sort_keys=True)))",
"[\n {\n \"game_buy_date\": \" 8/4/2018\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Indie\",\n \"game_igdb_id\": 20919,\n \"game_igdb_name\": \"In Space We Brawl\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 Mac PlayStation 4 Xbox One\",\n \"game_rating\": 90.0,\n \"game_rating_count\": 1,\n \"game_size\": \" 238.81 MB \",\n \"game_themes\": \"Action Science fiction\",\n \"game_title\": \"In Space We Brawl\",\n \"games_found\": 1,\n \"hltb_main\": 0.5333333333,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 20919,\\n \\\"genres\\\": [\\n 5,\\n 32\\n ],\\n \\\"name\\\": \\\"In Space We Brawl\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 14,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 71091,\\n 71092,\\n 151108,\\n 151109,\\n 218672\\n ],\\n \\\"summary\\\": \\\"In Space We Brawl is a frantic couch twin-stick shooter. Get ready for the excitement of pure local multiplayer matches for up to 4 players, including teams. Choose from more than 150 combinations of weapons and ships and conquer maps full of obstacles such as asteroids and black holes!\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 90.0,\\n \\\"total_rating_count\\\": 1,\\n \\\"url\\\": \\\"https://www.igdb.com/games/in-space-we-brawl\\\"\\n }\\n]\",\n \"igdb_release_date\": 1455235200000,\n \"summary\": \"In Space We Brawl is a frantic couch twin-stick shooter. Get ready for the excitement of pure local multiplayer matches for up to 4 players, including teams. Choose from more than 150 combinations of weapons and ships and conquer maps full of obstacles such as asteroids and black holes!\",\n \"web-scraper-order\": \"1003\"\n },\n {\n \"game_buy_date\": \" 13/3/2018\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Role-playing (RPG)\",\n \"game_igdb_id\": 11156,\n \"game_igdb_name\": \"Horizon Zero Dawn\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4\",\n \"game_rating\": 90.1021994732,\n \"game_rating_count\": 1049,\n \"game_size\": \" 43.04 GB \",\n \"game_themes\": \"Action Science fiction Open world\",\n \"game_title\": \"Horizon Zero Dawn\\u2122\",\n \"games_found\": 5,\n \"hltb_main\": 22.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 11156,\\n \\\"artworks\\\": [\\n 3263,\\n 3264,\\n 3265,\\n 3266,\\n 3267,\\n 3268,\\n 3269,\\n 3270,\\n 3271,\\n 3272,\\n 3273,\\n 3274\\n ],\\n \\\"genres\\\": [\\n 5,\\n 12\\n ],\\n \\\"name\\\": \\\"Horizon Zero Dawn\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 65848,\\n 103575,\\n 103576,\\n 203967\\n ],\\n \\\"summary\\\": \\\"Horizon Zero Dawn, an exhilarating new action role playing game exclusively for the PlayStation 4 system, developed by the award winning Guerrilla Games, creatos of PlayStation\\\\u0027s venerated Killzone franchise. As Horizon Zero Dawn\\\\u0027s main protagonist Aloy, a skilled hunter, explore a vibrant and lush world inhabited by mysterious mechanized creatures.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 38\\n ],\\n \\\"total_rating\\\": 90.10219947324345,\\n \\\"total_rating_count\\\": 1049,\\n \\\"url\\\": \\\"https://www.igdb.com/games/horizon-zero-dawn\\\"\\n },\\n {\\n \\\"id\\\": 72870,\\n \\\"genres\\\": [\\n 5,\\n 12\\n ],\\n \\\"name\\\": \\\"Horizon Zero Dawn Complete Edition\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 130573,\\n 203015\\n ],\\n \\\"summary\\\": \\\"In an era where machines roam the land and mankind is no longer the dominant species, a young hunter named Aloy embarks on a journey to discover her destiny. Explore a vibrant and lush world inhabited by mysterious mechanized creatures. Embark on a compelling, emotional journey and unravel mysteries of tribal societies, ancient artefacts and enhanced technologies that will determine the fate of this planet and of life itself. \\\\n \\\\nHorizon: Zero Dawn Complete Edition includes Horizon Zero Dawn and the frozen wilds expansion.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 38\\n ],\\n \\\"total_rating\\\": 92.41131370124066,\\n \\\"total_rating_count\\\": 66,\\n \\\"url\\\": \\\"https://www.igdb.com/games/horizon-zero-dawn-complete-edition\\\"\\n },\\n {\\n \\\"id\\\": 37083,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Horizon Zero Dawn - The Frozen Wilds\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 108620,\\n 133762,\\n 133763\\n ],\\n \\\"summary\\\": \\\"The Frozen Wilds contains additional content for Horizon Zero Dawn, including new storylines, characters and experiences in a beautiful but unforgiving new area.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 38\\n ],\\n \\\"total_rating\\\": 85.97088953187196,\\n \\\"total_rating_count\\\": 72,\\n \\\"url\\\": \\\"https://www.igdb.com/games/horizon-zero-dawn-the-frozen-wilds\\\"\\n },\\n {\\n \\\"id\\\": 42920,\\n \\\"genres\\\": [\\n 5,\\n 12\\n ],\\n \\\"name\\\": \\\"Horizon Zero Dawn Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 89802\\n ],\\n \\\"summary\\\": \\\"The plot revolves around Aloy, a hunter and archer living in a world overrun by robots. Having been cloistered her whole life, she sets out to discover the dangers that kept her sheltered. The character makes use of ranged, melee weapons and stealth tactics to combat the mechanised creatures, whose remains can also be looted for resources. A skill tree facilitates gameplay improvements. The game features an open world environment for Aloy to explore, divided into tribes that hold side quests to undertake, while the main story guides her throughout the whole world.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 38\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/horizon-zero-dawn-collectors-edition\\\"\\n },\\n {\\n \\\"id\\\": 112874,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Horizon Forbidden West\\\",\\n \\\"platforms\\\": [\\n 48,\\n 167\\n ],\\n \\\"release_dates\\\": [\\n 217641,\\n 217642\\n ],\\n \\\"summary\\\": \\\"Horizon Forbidden West continues Aloy\\u2019s story as she moves west to a far-future America to brave a majestic, but dangerous frontier where she\\u2019ll face awe-inspiring machines and mysterious new threats.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 38\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/horizon-forbidden-west\\\"\\n }\\n]\",\n \"igdb_release_date\": 1488326400000,\n \"summary\": \"Horizon Zero Dawn, an exhilarating new action role playing game exclusively for the PlayStation 4 system, developed by the award winning Guerrilla Games, creatos of PlayStation's venerated Killzone franchise. As Horizon Zero Dawn's main protagonist Aloy, a skilled hunter, explore a vibrant and lush world inhabited by mysterious mechanized creatures.\",\n \"web-scraper-order\": \"1009\"\n },\n {\n \"game_buy_date\": \" 6/3/2018\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Role-playing (RPG) Adventure\",\n \"game_igdb_id\": 7334,\n \"game_igdb_name\": \"Bloodborne\",\n \"game_platforms\": \"PlayStation 4\",\n \"game_rating\": 91.3362859512,\n \"game_rating_count\": 846,\n \"game_size\": \" 27.19 GB \",\n \"game_themes\": \"Action Fantasy Horror\",\n \"game_title\": \"Bloodborne\\u2122\",\n \"games_found\": 6,\n \"hltb_main\": 34.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7334,\\n \\\"artworks\\\": [\\n 161,\\n 162,\\n 163,\\n 164,\\n 165,\\n 166,\\n 167,\\n 168\\n ],\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Bloodborne\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 23719,\\n 101953,\\n 101954\\n ],\\n \\\"summary\\\": \\\"An action RPG in which the player embodies a Hunter who, after being transfused with the mysterious blood local to the city of Yharnam, sets off into a \\\\\\\"night of the Hunt\\\\\\\", an extended night in which Hunters may phase in and out of dream and reality in order to thin the outbreak of abominable beasts that plague the land and, for the more resilient and insightful Hunters, uncover the answers to the Hunt\\\\u0027s many mysteries.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 19\\n ],\\n \\\"total_rating\\\": 91.33628595115175,\\n \\\"total_rating_count\\\": 846,\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne\\\"\\n },\\n {\\n \\\"id\\\": 14647,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Bloodborne: The Old Hunters\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 40863\\n ],\\n \\\"summary\\\": \\\"The Old Hunters is the first Expansion for Bloodborne. It will feature all new Locations, Bosses, Weapons, and Armor.\\\\n\\\\nSet in a nightmare world where hunters from the past are trapped forever, explore brand new stages full of dangers, rewards and deadly beasts to overcome. You\\u2019ll find multiple new outfits and weapons to add to your arsenal as well as additional magic to wield and add more variety to your combat strategy.\\\\n\\\\nWith new story details, learn the tale of hunters who once made Yharnam their hunting grounds, meet new NPCs, and discover another side of the history and world of Bloodborne.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 19\\n ],\\n \\\"total_rating\\\": 91.0160745910903,\\n \\\"total_rating_count\\\": 113,\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne-the-old-hunters--1\\\"\\n },\\n {\\n \\\"id\\\": 44651,\\n \\\"genres\\\": [\\n 12\\n ],\\n \\\"name\\\": \\\"Bloodborne: Nightmare Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 99903\\n ],\\n \\\"summary\\\": \\\"Face your fears as you search for answers in the ancient city of Yharnam, now cursed with a strange endemic illness spreading through the streets like wildfire. Danger, death and madness lurk around every corner of this dark and horrific world, and you must discover its darkest secrets in order to survive. \\\\n \\\\nNightmare Edition comes with: \\\\nBloodborne PS4 game \\\\nSteelBook case \\\\nPremium art book with exclusive concept art \\\\nDigital soundtrack of the game \\\\nBloodborne gothic notebook \\\\nQuill \\\\u0026 red ink set \\\\n\\u201cTop Hat\\u201d Messenger skin \\\\nBell trinket\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 19\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne-nightmare-edition\\\"\\n },\\n {\\n \\\"id\\\": 44542,\\n \\\"genres\\\": [\\n 12\\n ],\\n \\\"name\\\": \\\"Bloodborne: Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 99910\\n ],\\n \\\"summary\\\": \\\"Face your fears as you search for answers in the ancient city of Yharnam, now cursed with a strange endemic illness spreading through the streets like wildfire. Danger, death and madness lurk around every corner of this dark and horrific world, and you must discover its darkest secrets in order to survive. \\\\n \\\\nA Terrifying New World: Journey to a horror-filled gothic city where deranged mobs and nightmarish creatures lurk around every corner. \\\\n \\\\nStrategic Action Combat: Armed with a unique arsenal of weaponry, including guns and saw cleavers, you\\\\u0027ll need wits, strategy and reflexes to take down the agile and intelligent enemies that guard the city\\\\u0027s dark secrets. \\\\n \\\\nA New Generation of Action RPG: Stunningly detailed gothic environments, atmospheric lighting, and advanced new online experiences showcase the power and prowess of the PlayStation(R)4 system.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 19\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne-collectors-edition\\\"\\n },\\n {\\n \\\"id\\\": 136691,\\n \\\"name\\\": \\\"Bloodborne: The Old Hunters Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 214240\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne-the-old-hunters-edition\\\"\\n },\\n {\\n \\\"id\\\": 42931,\\n \\\"genres\\\": [\\n 12\\n ],\\n \\\"name\\\": \\\"Bloodborne: Game Of The Year Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 168817\\n ],\\n \\\"summary\\\": \\\"With new story details, learn the tale of hunters who once made Yharnam their hunting grounds, meet new NPCs, and discover another side of the history and world of Bloodborne. Includes: \\\\nThe Original Bloodborne Experience / Bloodborne: The Old Hunters Expansion / Bloodborne: The Old Hunters\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 19\\n ],\\n \\\"total_rating\\\": 96.3163529387505,\\n \\\"total_rating_count\\\": 52,\\n \\\"url\\\": \\\"https://www.igdb.com/games/bloodborne-game-of-the-year-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1427414400000,\n \"summary\": \"An action RPG in which the player embodies a Hunter who, after being transfused with the mysterious blood local to the city of Yharnam, sets off into a \\\"night of the Hunt\\\", an extended night in which Hunters may phase in and out of dream and reality in order to thin the outbreak of abominable beasts that plague the land and, for the more resilient and insightful Hunters, uncover the answers to the Hunt's many mysteries.\",\n \"web-scraper-order\": \"1015\"\n },\n {\n \"game_buy_date\": \" 3/10/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Tactical Adventure\",\n \"game_igdb_id\": 1985,\n \"game_igdb_name\": \"Metal Gear Solid V: The Phantom Pain\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 Xbox 360 PlayStation 4 Xbox One\",\n \"game_rating\": 90.4961059572,\n \"game_rating_count\": 665,\n \"game_size\": \" 26.97 GB \",\n \"game_themes\": \"Action Fantasy Historical Stealth Open world\",\n \"game_title\": \"METAL GEAR SOLID V: THE PHANTOM PAIN\",\n \"games_found\": 2,\n \"hltb_main\": 46.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1985,\\n \\\"artworks\\\": [\\n 326,\\n 328,\\n 329,\\n 330,\\n 331,\\n 4593,\\n 4594,\\n 6630,\\n 8233,\\n 8234,\\n 8235,\\n 8236\\n ],\\n \\\"genres\\\": [\\n 5,\\n 24,\\n 31\\n ],\\n \\\"name\\\": \\\"Metal Gear Solid V: The Phantom Pain\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 12,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 28440,\\n 28543,\\n 28544,\\n 28545,\\n 28546,\\n 108035,\\n 108036,\\n 122509,\\n 133875,\\n 133876,\\n 136144\\n ],\\n \\\"summary\\\": \\\"The 5th installment of the Metal Gear Solid saga, Metal Gear Solid V: The Phantom Pain continues the story of Big Boss (aka Naked Snake, aka David), connecting the story lines from Metal Gear Solid: Peace Walker, Metal Gear Solid: Ground Zeroes, and the rest of the Metal Gear Universe.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22,\\n 23,\\n 38\\n ],\\n \\\"total_rating\\\": 90.4961059572052,\\n \\\"total_rating_count\\\": 665,\\n \\\"url\\\": \\\"https://www.igdb.com/games/metal-gear-solid-v-the-phantom-pain\\\"\\n },\\n {\\n \\\"id\\\": 42945,\\n \\\"genres\\\": [\\n 5,\\n 24,\\n 31\\n ],\\n \\\"name\\\": \\\"Metal Gear Solid V: The Phantom Pain Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 89755\\n ],\\n \\\"summary\\\": \\\"Metal Gear Solid V: The Phantom Pain Collector\\\\u0027s Edition Includes: Metal Gear Solid V: The Phantom Pain Game Collectible Steelbook Case Exclusive Packaging Map Half Scale Replica of Snake\\\\u0027s Bionic Arm Behind the Scenes Documentary and Trailers Blu-ray Additional Game Content: Customizable \\\\u0027Venom Snake\\\\u0027 Emblem Snake Costume X 4 Cardboard Box X 3 Weapon and Shield Set X 4 MGO Item X 4 XP Boost\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22,\\n 23,\\n 38\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/metal-gear-solid-v-the-phantom-pain-collectors-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1441065600000,\n \"summary\": \"The 5th installment of the Metal Gear Solid saga, Metal Gear Solid V: The Phantom Pain continues the story of Big Boss (aka Naked Snake, aka David), connecting the story lines from Metal Gear Solid: Peace Walker, Metal Gear Solid: Ground Zeroes, and the rest of the Metal Gear Universe.\",\n \"web-scraper-order\": \"1047\"\n },\n {\n \"game_buy_date\": \" 7/4/2020\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Adventure\",\n \"game_igdb_id\": 7331,\n \"game_igdb_name\": \"Uncharted 4: A Thief's End\",\n \"game_platforms\": \"PlayStation 4\",\n \"game_rating\": 92.7313918351,\n \"game_rating_count\": 1306,\n \"game_size\": \" 48.69 GB \",\n \"game_themes\": \"Action Fantasy Historical\",\n \"game_title\": \"Uncharted\\u2122 4: A Thief\\u2019s End\",\n \"games_found\": 3,\n \"hltb_main\": 15.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7331,\\n \\\"artworks\\\": [\\n 6303,\\n 6304,\\n 6305,\\n 6306,\\n 6307\\n ],\\n \\\"genres\\\": [\\n 5,\\n 31\\n ],\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 47481,\\n 106655,\\n 106656\\n ],\\n \\\"summary\\\": \\\"Several years after his last adventure, retired fortune hunter, Nathan Drake, is forced back into the world of thieves. With the stakes much more personal, Drake embarks on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. His greatest adventure will test his physical limits, his resolve, and ultimately what he\\\\u0027s willing to sacrifice to save the ones he loves.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22\\n ],\\n \\\"total_rating\\\": 92.73139183508785,\\n \\\"total_rating_count\\\": 1306,\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thief-s-end\\\"\\n },\\n {\\n \\\"id\\\": 41874,\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End Special Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 154696\\n ],\\n \\\"summary\\\": \\\"The Special Edition of Uncharted 4: A Thief\\u2019s End includes: \\\\n \\\\n- Collector\\u2019s SteelBook Case designed by Alexander \\u201cThat Kid Who Draws\\u201d Iaccarino \\\\n- 48 Page Hardcover Mini Art Book by Naughty Dog and Dark Horse \\\\n- Naughty Dog \\\\u0026 Pirate Sigil Sticker Sheet \\\\n- Multiplayer Bonuses: \\\\n- Multiplayer Outfit \\u2013 Heist Drake \\\\n- Naughty Dog Points \\u2013 Redeem the points to unlock new multiplayer content and character upgrades. \\\\n- Snow Weapon Skin\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thiefs-end-special-edition\\\"\\n },\\n {\\n \\\"id\\\": 41879,\\n \\\"genres\\\": [\\n 31\\n ],\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End Libertalia Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 89763\\n ],\\n \\\"summary\\\": \\\"Uncharted 4: A Thief\\\\u0027s End is an upcoming American action-adventure video game published by Sony Computer Entertainment and developed by Naughty Dog exclusively for the PlayStation 4. Initially teased at Spike TV\\\\u0027s PS4 launch event on November 14, 2013, a full in-engine trailer confirmed the title during Sony\\\\u0027s E3 2014 press conference on June 9, 2014. The game is set to release in 2015. \\\\n \\\\nSeveral years after the events of Uncharted 3: Drake\\\\u0027s Deception, Nathan Drake, who retired as a fortune hunter, will embark on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. Naughty Dog outlined the game\\\\u0027s plot as \\\\\\\"his greatest adventure yet and will test his physical limits, his resolve, and ultimately what he\\\\u0027s willing to sacrifice to save the ones he loves\\\\\\\".\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thiefs-end-libertalia-collectors-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1462838400000,\n \"summary\": \"Several years after his last adventure, retired fortune hunter, Nathan Drake, is forced back into the world of thieves. With the stakes much more personal, Drake embarks on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. His greatest adventure will test his physical limits, his resolve, and ultimately what he's willing to sacrifice to save the ones he loves.\",\n \"web-scraper-order\": \"855\"\n },\n {\n \"game_buy_date\": \" 1/10/2019\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Adventure\",\n \"game_igdb_id\": 6036,\n \"game_igdb_name\": \"The Last of Us Remastered\",\n \"game_platforms\": \"PlayStation 4\",\n \"game_rating\": 95.9493647506,\n \"game_rating_count\": 705,\n \"game_size\": \" 47.19 GB \",\n \"game_themes\": \"Action Horror Survival Stealth\",\n \"game_title\": \"The Last of Us\\u2122 Remastered\",\n \"games_found\": 2,\n \"hltb_main\": 14.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 6036,\\n \\\"artworks\\\": [\\n 6199,\\n 6200,\\n 6201\\n ],\\n \\\"genres\\\": [\\n 5,\\n 31\\n ],\\n \\\"name\\\": \\\"The Last of Us Remastered\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 106246,\\n 106247,\\n 150147,\\n 150148\\n ],\\n \\\"summary\\\": \\\"Winner of over 200 game of the year awards, The Last of Us has been remastered for the PlayStation\\u00ae4. Now featuring higher resolution character models, improved shadows and lighting, in addition to several other gameplay improvements. \\\\n \\\\nAbandoned cities reclaimed by nature. A population decimated by a modern plague. Survivors are killing each other for food, weapons whatever they can get their hands on. Joel, a brutal survivor, and Ellie, a brave young teenage girl who is wise beyond her years, must work together if they hope to survive their journey across the US. \\\\n \\\\nThe Last of Us: Remastered includes the Abandoned Territories Map Pack, Reclaimed Territories Map Pack, and the critically acclaimed The Last of Us: Left Behind Single Player campaign. \\\\n \\\\nPS4 PRO ENHANCED: \\\\n- PS4 Pro HD \\\\n- Dynamic 4K Gaming \\\\n- Greater Draw Distance \\\\n- Visual FX \\\\n- Vivid Textures \\\\n- Deep Shadows \\\\n- High Fidelity Assets \\\\n- HDR\\\",\\n \\\"themes\\\": [\\n 1,\\n 19,\\n 21,\\n 23\\n ],\\n \\\"total_rating\\\": 95.94936475060166,\\n \\\"total_rating_count\\\": 705,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-last-of-us-remastered\\\"\\n },\\n {\\n \\\"id\\\": 25984,\\n \\\"name\\\": \\\"The Last Of Us Remastered: Agility Survival Skill\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 61048\\n ],\\n \\\"summary\\\": \\\"Climb, vault, and move while crouching faster than you could before. At level 3 you are nearly impossible to hear while moving. For one price, get this content for your PS4\\u2122 and PS3\\u2122 systems. Purchase it on one system and it will automatically appear for download on the other system at no additional cost.\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-last-of-us-remastered-agility-survival-skill\\\"\\n }\\n]\",\n \"igdb_release_date\": 1406851200000,\n \"summary\": \"Winner of over 200 game of the year awards, The Last of Us has been remastered for the PlayStation\\u00ae4. Now featuring higher resolution character models, improved shadows and lighting, in addition to several other gameplay improvements. \\n \\nAbandoned cities reclaimed by nature. A population decimated by a modern plague. Survivors are killing each other for food, weapons whatever they can get their hands on. Joel, a brutal survivor, and Ellie, a brave young teenage girl who is wise beyond her years, must work together if they hope to survive their journey across the US. \\n \\nThe Last of Us: Remastered includes the Abandoned Territories Map Pack, Reclaimed Territories Map Pack, and the critically acclaimed The Last of Us: Left Behind Single Player campaign. \\n \\nPS4 PRO ENHANCED: \\n- PS4 Pro HD \\n- Dynamic 4K Gaming \\n- Greater Draw Distance \\n- Visual FX \\n- Vivid Textures \\n- Deep Shadows \\n- High Fidelity Assets \\n- HDR\",\n \"web-scraper-order\": \"881\"\n },\n {\n \"game_buy_date\": \" 1/5/2019\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Role-playing (RPG) Adventure\",\n \"game_igdb_id\": 9927,\n \"game_igdb_name\": \"Persona 5\",\n \"game_platforms\": \"PlayStation 3 PlayStation 4\",\n \"game_rating\": 93.7039991179,\n \"game_rating_count\": 535,\n \"game_size\": \" 20.2 GB \",\n \"game_themes\": \"Action Fantasy Stealth\",\n \"game_title\": \"Persona 5\",\n \"games_found\": 7,\n \"hltb_main\": 97.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 9927,\\n \\\"artworks\\\": [\\n 3797,\\n 3798,\\n 3799,\\n 3800,\\n 3801,\\n 6095,\\n 6096,\\n 6097\\n ],\\n \\\"genres\\\": [\\n 8,\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Persona 5\\\",\\n \\\"platforms\\\": [\\n 9,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 50396,\\n 60562,\\n 60564,\\n 104841,\\n 104842,\\n 104843\\n ],\\n \\\"summary\\\": \\\"Persona 5, a turn-based JRPG with visual novel elements, follows a high school student with a criminal record for a crime he didn\\\\u0027t commit. Soon he meets several characters who share similar fates to him, and discovers a metaphysical realm which allows him and his friends to channel their pent-up frustrations into becoming a group of vigilantes reveling in aesthetics and rebellion while fighting corruption.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 23\\n ],\\n \\\"total_rating\\\": 93.70399911794084,\\n \\\"total_rating_count\\\": 535,\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5\\\"\\n },\\n {\\n \\\"id\\\": 117731,\\n \\\"genres\\\": [\\n 12,\\n 25\\n ],\\n \\\"name\\\": \\\"Persona 5 Scramble: The Phantom Strikers\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 179497,\\n 179498,\\n 220695,\\n 220696,\\n 220697\\n ],\\n \\\"summary\\\": \\\"Persona 5 Scramble is crossover between Koei Tecmo\\\\u0027s hack and slash Dynasty Warriors series, and Atlus\\\\u0027s turn-based role-playing game Persona series. As a result, it features gameplay elements from both, such as the real-time action combat of the former with the turn-based Persona-battling aspect of the latter. The game is set six months after the events of Persona 5, and follows Joker and the rest of the Phantom Thieves of Hearts as they end up in a mysterious version of Tokyo filled with supernatural enemies.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-scramble-the-phantom-strikers\\\"\\n },\\n {\\n \\\"id\\\": 114283,\\n \\\"artworks\\\": [\\n 7817,\\n 7818,\\n 7819\\n ],\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Persona 5 Royal\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 168747,\\n 180874,\\n 180875,\\n 180876\\n ],\\n \\\"summary\\\": \\\"An enhanced version of Persona 5 with some new characters and a third semester added to the game. Released Internationally in 2020.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17\\n ],\\n \\\"total_rating\\\": 96.8344481071584,\\n \\\"total_rating_count\\\": 59,\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-royal\\\"\\n },\\n {\\n \\\"id\\\": 74879,\\n \\\"genres\\\": [\\n 8,\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Persona 5: Ultimate Edition\\\",\\n \\\"platforms\\\": [\\n 9,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 180836,\\n 180837,\\n 180838,\\n 180839\\n ],\\n \\\"summary\\\": \\\"Persona 5, a turn-based JRPG with visual novel elements, follows a high school student with a criminal record for a crime he didn\\\\u0027t commit. Soon he meets several characters who share similar fates to him, and discovers a metaphysical realm which allows him and his friends to channel their pent-up frustrations into becoming a group of vigilantes reveling in aesthetics and rebellion while fighting corruption. \\\\n \\\\nThis special bundle contains: \\\\n* Persona 5 \\\\n* all additional Personas \\\\n* all special Costumes \\\\n* Healing Item Set \\\\n* Skill Card Set \\\\n* Japanese Audio Track \\\\n* New Difficulty Level (Merciless)\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 23\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-ultimate-edition\\\"\\n },\\n {\\n \\\"id\\\": 54218,\\n \\\"genres\\\": [\\n 7\\n ],\\n \\\"name\\\": \\\"Persona 5: Dancing in Starlight\\\",\\n \\\"platforms\\\": [\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 133973,\\n 152181,\\n 161617,\\n 161618,\\n 161619,\\n 161620\\n ],\\n \\\"summary\\\": \\\"Dancing game featuring characters from Persona 5.\\\",\\n \\\"total_rating\\\": 72.99719218018521,\\n \\\"total_rating_count\\\": 20,\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-dancing-in-starlight\\\"\\n },\\n {\\n \\\"id\\\": 116559,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Persona 5 Royal Limited Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 168688,\\n 168743,\\n 168744,\\n 168745\\n ],\\n \\\"summary\\\": \\\"A limited edition version Persona 5 Royal, called Persona 5 The Royal in Japan.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 31,\\n 43\\n ],\\n \\\"total_rating\\\": 97.8981937602627,\\n \\\"total_rating_count\\\": 6,\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-royal-limited-edition\\\"\\n },\\n {\\n \\\"id\\\": 41866,\\n \\\"name\\\": \\\"Persona 5: Take Your Heart - Premium Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 185063,\\n 185064\\n ],\\n \\\"summary\\\": \\\"Persona 5 \\u201cTake Your Heart\\u201d Premium Edition contains: Game, SteelBook Collectible Case, Soundtrack CD, 4\\\\\\\" Morgana Plush, 64-page Hardcover Art Book, School Bag \\\\u0026 Collectible Outer Box \\\\n \\\\nThe 5th numbered game in the series, created by renowned developers - \\\\n \\\\nA deep and engaging storyline - Each case will take you one step closer to the truth veiled in darkness...What awaits our heroes: glory or ruin? \\\\n \\\\nUnique and interesting dungeons with various tricks and traps await - Overcome various obstacles with graceful Phantom Thief action \\\\n \\\\nA stable of talented voice actors have provided English voice-overs while ATLUS\\u2019 celebrated localization team offers an English script that provides a faithful and engaging play experience\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/persona-5-take-your-heart-premium-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1491264000000,\n \"summary\": \"Persona 5, a turn-based JRPG with visual novel elements, follows a high school student with a criminal record for a crime he didn't commit. Soon he meets several characters who share similar fates to him, and discovers a metaphysical realm which allows him and his friends to channel their pent-up frustrations into becoming a group of vigilantes reveling in aesthetics and rebellion while fighting corruption.\",\n \"web-scraper-order\": \"931\"\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Shooter Role-playing (RPG) Adventure\",\n \"game_igdb_id\": 25076,\n \"game_igdb_name\": \"Red Dead Redemption 2\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4 Xbox One Google Stadia\",\n \"game_rating\": 93.1083249086,\n \"game_rating_count\": 997,\n \"game_size\": null,\n \"game_themes\": \"Action Open world\",\n \"game_title\": \"Red Dead Redemption II\",\n \"games_found\": 1,\n \"hltb_main\": 48.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 25076,\\n \\\"artworks\\\": [\\n 5330,\\n 5332,\\n 5333,\\n 5334,\\n 5335,\\n 5336,\\n 5337,\\n 5338,\\n 5339,\\n 5340,\\n 5341,\\n 5645\\n ],\\n \\\"genres\\\": [\\n 5,\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Red Dead Redemption 2\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49,\\n 170\\n ],\\n \\\"release_dates\\\": [\\n 137262,\\n 137263,\\n 137264,\\n 137265,\\n 137266,\\n 147060,\\n 177006,\\n 179286\\n ],\\n \\\"summary\\\": \\\"Developed by the creators of Grand Theft Auto V and Red Dead Redemption, Red Dead Redemption 2 is an epic tale of life in America\\u2019s unforgiving heartland. The game\\\\u0027s vast and atmospheric world will also provide the foundation for a brand new online multiplayer experience.\\\",\\n \\\"themes\\\": [\\n 1,\\n 38\\n ],\\n \\\"total_rating\\\": 93.10832490856174,\\n \\\"total_rating_count\\\": 997,\\n \\\"url\\\": \\\"https://www.igdb.com/games/red-dead-redemption-2\\\"\\n }\\n]\",\n \"igdb_release_date\": 1540512000000,\n \"summary\": \"Developed by the creators of Grand Theft Auto V and Red Dead Redemption, Red Dead Redemption 2 is an epic tale of life in America\\u2019s unforgiving heartland. The game's vast and atmospheric world will also provide the foundation for a brand new online multiplayer experience.\",\n \"web-scraper-order\": null\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Role-playing (RPG) Adventure\",\n \"game_igdb_id\": 36926,\n \"game_igdb_name\": \"Monster Hunter: World\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4 Xbox One\",\n \"game_rating\": 90.0037707715,\n \"game_rating_count\": 279,\n \"game_size\": null,\n \"game_themes\": \"Action\",\n \"game_title\": \"Monster Hunter World\",\n \"games_found\": 6,\n \"hltb_main\": 49.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 36926,\\n \\\"artworks\\\": [\\n 1304,\\n 1305,\\n 1306,\\n 1307\\n ],\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Monster Hunter: World\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 113479,\\n 147904,\\n 155500\\n ],\\n \\\"summary\\\": \\\"Monster Hunter: World sees players take on the role of a hunter that completes various quests to hunt and slay monsters within a lively living and breathing eco-system full of predators\\u2026. and prey. In the video you can see some of the creatures you can expect to come across within the New World, the newly discovered continent where Monster Hunter: World is set, including the Great Jagras which has the ability to swallow its prey whole and one of the Monster Hunter series favourites, Rathalos. \\\\n \\\\nPlayers are able to utilise survival tools such as the slinger and Scoutfly to aid them in their hunt. By using these skills to their advantage hunters can lure monsters into traps and even pit them against each other in an epic fierce battle. Can our hunter successfully survive the fight and slay the Anjanath? He\\u2019ll need to select his weapon choice carefully from 14 different weapon classes and think strategically about how to take the giant foe down. Don\\u2019t forget to pack the camouflaging ghillie suit!\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 90.00377077149675,\\n \\\"total_rating_count\\\": 279,\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world\\\"\\n },\\n {\\n \\\"id\\\": 113344,\\n \\\"artworks\\\": [\\n 7618,\\n 7619\\n ],\\n \\\"genres\\\": [\\n 31\\n ],\\n \\\"name\\\": \\\"Monster Hunter: World - Iceborne\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 169398,\\n 187392,\\n 187393\\n ],\\n \\\"summary\\\": \\\"Let your hunting instinct take you further than ever! \\\\\\\"Iceborne\\\\\\\" is a massive expansion that picks up after the ending of Monster Hunter: World and opens up the new \\\\\\\"master rank!\\\\\\\" New quests, monsters, weapons, armor, and story await to take your hunting to the next level.\\\",\\n \\\"themes\\\": [\\n 17\\n ],\\n \\\"total_rating\\\": 93.63011625172065,\\n \\\"total_rating_count\\\": 31,\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world-iceborne\\\"\\n },\\n {\\n \\\"id\\\": 81355,\\n \\\"name\\\": \\\"Monster Hunter: World - Steelbook Edition\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 135332,\\n 135333\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world-steelbook-edition\\\"\\n },\\n {\\n \\\"id\\\": 118273,\\n \\\"genres\\\": [\\n 12,\\n 25,\\n 31\\n ],\\n \\\"name\\\": \\\"Monster Hunter World: Iceborne Master Edition\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 169393,\\n 169394,\\n 169395\\n ],\\n \\\"summary\\\": \\\"Discover breathtaking environments and battle titanic creatures in this collection that includes Monster Hunter: World and its massive expansion, Iceborne. As a hunter, you\\\\u0027ll take on quests to track \\\\u0026 slay monsters in a variety of living, breathing habitats. Take down these monsters and use their materials to forge even more powerful weapons and armor, then prepare for even tougher foes as the story unfolds. Each discovery adds new areas, creatures, and drama to the adventure! The Iceborne expansion adds new monsters, gear and abilities to Monster Hunter: World. Picking up right where the base game left off, the Research Commission and your hunter set off to a new polar region, kicking off a brand-new story set in Hoarfrost Reach. Conquer these missions alone, or play online with other hunters for epic multiplayer quests.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world-iceborne-master-edition\\\"\\n },\\n {\\n \\\"id\\\": 81289,\\n \\\"name\\\": \\\"Monster Hunter: World - Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 135145,\\n 135146\\n ],\\n \\\"summary\\\": \\\"Monster Hunter: World - Collector\\\\u0027s Edition contains: \\\\n \\\\nDeluxe Kit product download code. \\\\nNergigante figure. \\\\nMonster Hunter: World special soundtrack. \\\\nMonster Hunter: World artbook \\\\\\\"Monster Designs\\\\\\\".\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world-collectors-edition\\\"\\n },\\n {\\n \\\"id\\\": 81354,\\n \\\"name\\\": \\\"Monster Hunter: World - Digital Deluxe Edition\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 135330,\\n 135331\\n ],\\n \\\"summary\\\": \\\"Monster Hunter: World - Digital Deluxe Edition contains: \\\\n \\\\nDeluxe Kit contents: \\\\nSamurai set. \\\\n3 Additional Gestures: \\\\\\\"Zen\\\\\\\", \\\\\\\"Ninja Star\\\\\\\", \\\\\\\"Sumo Slap\\\\\\\". \\\\n2 Additional Sticker Sets: \\\\\\\"MH All-Stars Set\\\\\\\", \\\\\\\"Sir Loin Set\\\\\\\". \\\\n1 Additional Face Paint: \\\\\\\"Wyvern\\\\\\\". \\\\n1 Additional Hairstyle: \\\\\\\"Topknot\\\\\\\".\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/monster-hunter-world-digital-deluxe-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1516924800000,\n \"summary\": \"Monster Hunter: World sees players take on the role of a hunter that completes various quests to hunt and slay monsters within a lively living and breathing eco-system full of predators\\u2026. and prey. In the video you can see some of the creatures you can expect to come across within the New World, the newly discovered continent where Monster Hunter: World is set, including the Great Jagras which has the ability to swallow its prey whole and one of the Monster Hunter series favourites, Rathalos. \\n \\nPlayers are able to utilise survival tools such as the slinger and Scoutfly to aid them in their hunt. By using these skills to their advantage hunters can lure monsters into traps and even pit them against each other in an epic fierce battle. Can our hunter successfully survive the fight and slay the Anjanath? He\\u2019ll need to select his weapon choice carefully from 14 different weapon classes and think strategically about how to take the giant foe down. Don\\u2019t forget to pack the camouflaging ghillie suit!\",\n \"web-scraper-order\": null\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Shooter Adventure\",\n \"game_igdb_id\": 6036,\n \"game_igdb_name\": \"The Last of Us Remastered\",\n \"game_platforms\": \"PlayStation 4\",\n \"game_rating\": 95.9493647506,\n \"game_rating_count\": 705,\n \"game_size\": null,\n \"game_themes\": \"Action Horror Survival Stealth\",\n \"game_title\": \"The Last of Us Remastered\",\n \"games_found\": 2,\n \"hltb_main\": 14.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 6036,\\n \\\"artworks\\\": [\\n 6199,\\n 6200,\\n 6201\\n ],\\n \\\"genres\\\": [\\n 5,\\n 31\\n ],\\n \\\"name\\\": \\\"The Last of Us Remastered\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 106246,\\n 106247,\\n 150147,\\n 150148\\n ],\\n \\\"summary\\\": \\\"Winner of over 200 game of the year awards, The Last of Us has been remastered for the PlayStation\\u00ae4. Now featuring higher resolution character models, improved shadows and lighting, in addition to several other gameplay improvements. \\\\n \\\\nAbandoned cities reclaimed by nature. A population decimated by a modern plague. Survivors are killing each other for food, weapons whatever they can get their hands on. Joel, a brutal survivor, and Ellie, a brave young teenage girl who is wise beyond her years, must work together if they hope to survive their journey across the US. \\\\n \\\\nThe Last of Us: Remastered includes the Abandoned Territories Map Pack, Reclaimed Territories Map Pack, and the critically acclaimed The Last of Us: Left Behind Single Player campaign. \\\\n \\\\nPS4 PRO ENHANCED: \\\\n- PS4 Pro HD \\\\n- Dynamic 4K Gaming \\\\n- Greater Draw Distance \\\\n- Visual FX \\\\n- Vivid Textures \\\\n- Deep Shadows \\\\n- High Fidelity Assets \\\\n- HDR\\\",\\n \\\"themes\\\": [\\n 1,\\n 19,\\n 21,\\n 23\\n ],\\n \\\"total_rating\\\": 95.94936475060166,\\n \\\"total_rating_count\\\": 705,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-last-of-us-remastered\\\"\\n },\\n {\\n \\\"id\\\": 25984,\\n \\\"name\\\": \\\"The Last Of Us Remastered: Agility Survival Skill\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 61048\\n ],\\n \\\"summary\\\": \\\"Climb, vault, and move while crouching faster than you could before. At level 3 you are nearly impossible to hear while moving. For one price, get this content for your PS4\\u2122 and PS3\\u2122 systems. Purchase it on one system and it will automatically appear for download on the other system at no additional cost.\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-last-of-us-remastered-agility-survival-skill\\\"\\n }\\n]\",\n \"igdb_release_date\": 1406851200000,\n \"summary\": \"Winner of over 200 game of the year awards, The Last of Us has been remastered for the PlayStation\\u00ae4. Now featuring higher resolution character models, improved shadows and lighting, in addition to several other gameplay improvements. \\n \\nAbandoned cities reclaimed by nature. A population decimated by a modern plague. Survivors are killing each other for food, weapons whatever they can get their hands on. Joel, a brutal survivor, and Ellie, a brave young teenage girl who is wise beyond her years, must work together if they hope to survive their journey across the US. \\n \\nThe Last of Us: Remastered includes the Abandoned Territories Map Pack, Reclaimed Territories Map Pack, and the critically acclaimed The Last of Us: Left Behind Single Player campaign. \\n \\nPS4 PRO ENHANCED: \\n- PS4 Pro HD \\n- Dynamic 4K Gaming \\n- Greater Draw Distance \\n- Visual FX \\n- Vivid Textures \\n- Deep Shadows \\n- High Fidelity Assets \\n- HDR\",\n \"web-scraper-order\": null\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Shooter Adventure\",\n \"game_igdb_id\": 7331,\n \"game_igdb_name\": \"Uncharted 4: A Thief's End\",\n \"game_platforms\": \"PlayStation 4\",\n \"game_rating\": 92.7313918351,\n \"game_rating_count\": 1306,\n \"game_size\": null,\n \"game_themes\": \"Action Fantasy Historical\",\n \"game_title\": \"Uncharted 4 - A Thief\\u2019s End\",\n \"games_found\": 3,\n \"hltb_main\": 15.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7331,\\n \\\"artworks\\\": [\\n 6303,\\n 6304,\\n 6305,\\n 6306,\\n 6307\\n ],\\n \\\"genres\\\": [\\n 5,\\n 31\\n ],\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 47481,\\n 106655,\\n 106656\\n ],\\n \\\"summary\\\": \\\"Several years after his last adventure, retired fortune hunter, Nathan Drake, is forced back into the world of thieves. With the stakes much more personal, Drake embarks on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. His greatest adventure will test his physical limits, his resolve, and ultimately what he\\\\u0027s willing to sacrifice to save the ones he loves.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22\\n ],\\n \\\"total_rating\\\": 92.73139183508785,\\n \\\"total_rating_count\\\": 1306,\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thief-s-end\\\"\\n },\\n {\\n \\\"id\\\": 41874,\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End Special Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 154696\\n ],\\n \\\"summary\\\": \\\"The Special Edition of Uncharted 4: A Thief\\u2019s End includes: \\\\n \\\\n- Collector\\u2019s SteelBook Case designed by Alexander \\u201cThat Kid Who Draws\\u201d Iaccarino \\\\n- 48 Page Hardcover Mini Art Book by Naughty Dog and Dark Horse \\\\n- Naughty Dog \\\\u0026 Pirate Sigil Sticker Sheet \\\\n- Multiplayer Bonuses: \\\\n- Multiplayer Outfit \\u2013 Heist Drake \\\\n- Naughty Dog Points \\u2013 Redeem the points to unlock new multiplayer content and character upgrades. \\\\n- Snow Weapon Skin\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thiefs-end-special-edition\\\"\\n },\\n {\\n \\\"id\\\": 41879,\\n \\\"genres\\\": [\\n 31\\n ],\\n \\\"name\\\": \\\"Uncharted 4: A Thief\\\\u0027s End Libertalia Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 89763\\n ],\\n \\\"summary\\\": \\\"Uncharted 4: A Thief\\\\u0027s End is an upcoming American action-adventure video game published by Sony Computer Entertainment and developed by Naughty Dog exclusively for the PlayStation 4. Initially teased at Spike TV\\\\u0027s PS4 launch event on November 14, 2013, a full in-engine trailer confirmed the title during Sony\\\\u0027s E3 2014 press conference on June 9, 2014. The game is set to release in 2015. \\\\n \\\\nSeveral years after the events of Uncharted 3: Drake\\\\u0027s Deception, Nathan Drake, who retired as a fortune hunter, will embark on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. Naughty Dog outlined the game\\\\u0027s plot as \\\\\\\"his greatest adventure yet and will test his physical limits, his resolve, and ultimately what he\\\\u0027s willing to sacrifice to save the ones he loves\\\\\\\".\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/uncharted-4-a-thiefs-end-libertalia-collectors-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1462838400000,\n \"summary\": \"Several years after his last adventure, retired fortune hunter, Nathan Drake, is forced back into the world of thieves. With the stakes much more personal, Drake embarks on a globe-trotting journey in pursuit of a historical conspiracy behind a fabled pirate treasure. His greatest adventure will test his physical limits, his resolve, and ultimately what he's willing to sacrifice to save the ones he loves.\",\n \"web-scraper-order\": null\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Shooter Racing Sport Adventure\",\n \"game_igdb_id\": 1020,\n \"game_igdb_name\": \"Grand Theft Auto V\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 Xbox 360 PlayStation 4 Xbox One\",\n \"game_rating\": 93.3929790512,\n \"game_rating_count\": 2896,\n \"game_size\": null,\n \"game_themes\": \"Action Comedy Sandbox Open world\",\n \"game_title\": \"Grand Theft Auto V\",\n \"games_found\": 2,\n \"hltb_main\": 31.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1020,\\n \\\"artworks\\\": [\\n 2628,\\n 2629,\\n 2630,\\n 2631,\\n 2632,\\n 2633,\\n 2634,\\n 2635,\\n 2636,\\n 5650,\\n 5848,\\n 5849\\n ],\\n \\\"genres\\\": [\\n 5,\\n 10,\\n 14,\\n 31\\n ],\\n \\\"name\\\": \\\"Grand Theft Auto V\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 12,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 20290,\\n 20291,\\n 20293,\\n 20294,\\n 27436,\\n 103344,\\n 103345,\\n 133723,\\n 133724,\\n 136048\\n ],\\n \\\"summary\\\": \\\"The biggest, most dynamic and most diverse open world ever created, Grand Theft Auto V blends storytelling and gameplay in new ways as players repeatedly jump in and out of the lives of the game\\u2019s three lead characters, playing all sides of the game\\u2019s interwoven story.\\\",\\n \\\"themes\\\": [\\n 1,\\n 27,\\n 33,\\n 38\\n ],\\n \\\"total_rating\\\": 93.39297905115895,\\n \\\"total_rating_count\\\": 2896,\\n \\\"url\\\": \\\"https://www.igdb.com/games/grand-theft-auto-v\\\"\\n },\\n {\\n \\\"id\\\": 98077,\\n \\\"genres\\\": [\\n 5,\\n 10,\\n 14,\\n 31\\n ],\\n \\\"name\\\": \\\"Grand Theft Auto V: Premium Online Edition\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 189410,\\n 189411,\\n 189412\\n ],\\n \\\"summary\\\": \\\"The Grand Theft Auto V: Premium Online Edition includes the complete Grand Theft Auto V story experience, free access to the ever evolving Grand Theft Auto Online and all existing gameplay upgrades and content including The Doomsday Heist, Gunrunning, Smuggler\\u2019s Run, Bikers and much more. You\\u2019ll also get the Criminal Enterprise Starter Pack, the fastest way to jumpstart your criminal empire in Grand Theft Auto Online.\\\",\\n \\\"themes\\\": [\\n 1,\\n 27,\\n 38\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/grand-theft-auto-v-premium-online-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1416268800000,\n \"summary\": \"The biggest, most dynamic and most diverse open world ever created, Grand Theft Auto V blends storytelling and gameplay in new ways as players repeatedly jump in and out of the lives of the game\\u2019s three lead characters, playing all sides of the game\\u2019s interwoven story.\",\n \"web-scraper-order\": null\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Role-playing (RPG) Adventure\",\n \"game_igdb_id\": 1942,\n \"game_igdb_name\": \"The Witcher 3: Wild Hunt\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4 Xbox One\",\n \"game_rating\": 93.5855808015,\n \"game_rating_count\": 2554,\n \"game_size\": null,\n \"game_themes\": \"Action Fantasy Open world\",\n \"game_title\": \"The Witcher 3: Wild Hunt\",\n \"games_found\": 5,\n \"hltb_main\": 51.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1942,\\n \\\"artworks\\\": [\\n 142,\\n 143,\\n 144,\\n 145,\\n 146,\\n 147,\\n 148,\\n 149,\\n 150,\\n 901,\\n 1146,\\n 1147,\\n 1148\\n ],\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"The Witcher 3: Wild Hunt\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 23743,\\n 23744,\\n 23745\\n ],\\n \\\"summary\\\": \\\"RPG and sequel to The Witcher 2 (2011), The Witcher 3 follows witcher Geralt of Rivia as he seeks out his former lover and his young subject while intermingling with the political workings of the wartorn Northern Kingdoms. Geralt has to fight monsters and deal with people of all sorts in order to solve complex problems and settle contentious disputes, each ranging from the personal to the world-changing.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 38\\n ],\\n \\\"total_rating\\\": 93.58558080146204,\\n \\\"total_rating_count\\\": 2554,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-witcher-3-wild-hunt\\\"\\n },\\n {\\n \\\"id\\\": 22439,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"The Witcher 3: Wild Hunt - Game of the Year Edition\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 55024,\\n 55025,\\n 107493\\n ],\\n \\\"summary\\\": \\\"Become a professional monster slayer and embark on an adventure of epic proportions! Upon its release, The Witcher 3: Wild Hunt became an instant classic, claiming over 250 Game of the Year awards. Now you can enjoy this huge, over 100-hour long, open-world adventure along with both its story-driven expansions worth an extra 50 hours of gameplay. This edition includes all additional content - new weapons, armor, companion outfits, new game mode and side quests.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22,\\n 38\\n ],\\n \\\"total_rating\\\": 99.06680039444299,\\n \\\"total_rating_count\\\": 305,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-witcher-3-wild-hunt-game-of-the-year-edition\\\"\\n },\\n {\\n \\\"id\\\": 13166,\\n \\\"artworks\\\": [\\n 6234\\n ],\\n \\\"genres\\\": [\\n 12\\n ],\\n \\\"name\\\": \\\"The Witcher 3: Wild Hunt - Blood and Wine\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 50537,\\n 50538,\\n 50539\\n ],\\n \\\"summary\\\": \\\"Blood and Wine is the second major expansion to The Witcher 3: Wild Hunt. \\\\n \\\\nThe players will accompany Geralt of Rivia to the region of Toussaint, one of the few places in the Witcher universe which has remained largely untouched by the war. The calm, laid-back atmosphere holds a dark and bloody secret that only the White Wolf can uncover; the expansion features brand new items for us to collect on our adventure and also introduces previously unknown characters.\\\",\\n \\\"themes\\\": [\\n 17,\\n 38\\n ],\\n \\\"total_rating\\\": 94.31647388607415,\\n \\\"total_rating_count\\\": 276,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-witcher-3-wild-hunt-blood-and-wine\\\"\\n },\\n {\\n \\\"id\\\": 12503,\\n \\\"artworks\\\": [\\n 1971\\n ],\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"The Witcher 3: Wild Hunt - Hearts of Stone\\\",\\n \\\"platforms\\\": [\\n 6,\\n 45,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 38585,\\n 38586,\\n 38587,\\n 106356,\\n 106357\\n ],\\n \\\"summary\\\": \\\"Hired by the Merchant of Mirrors, Geralt is tasked with overcoming Olgierd von Everec -- a ruthless bandit captain enchanted with the power of immortality. \\\\n \\\\n \\\\n \\\\nStep again into the shoes of Geralt of Rivia, a professional monster slayer, this time hired to defeat a ruthless bandit captain, Olgierd von Everec, a man who possesses the power of immortality. This expansion to \\u201cThe Witcher 3: Wild Hunt\\u201d packs over 10 hours of new adventures, introducing new characters, powerful monsters, unique romance and a brand new storyline shaped by your choices.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 38\\n ],\\n \\\"total_rating\\\": 92.45542708537221,\\n \\\"total_rating_count\\\": 358,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-witcher-3-wild-hunt-hearts-of-stone\\\"\\n },\\n {\\n \\\"id\\\": 44549,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"The Witcher 3: Wild Hunt Collector\\\\u0027s Edition\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 99902\\n ],\\n \\\"summary\\\": \\\"Contents of the Collector\\\\u0027s Edition: the game, an exclusive CD with the official soundtrack, the official developer-created Witcher Universe: The Compendium, a beautiful detailed map of the in-game world, a set of unique The Witcher 3: Wild Hunt stickers, a 33 x 24 x 25 cm hand-painted Polystone figure of Geralt of Rivia battling a Griffin, an exclusive collector-grade Witcher medallion, a unique SteelBook, a 200-page artbook containing breathtaking art from the game, and huge outer and inner collector\\\\u0027s boxes in which you can store your Witcher merchandise\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 22,\\n 38\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-witcher-3-wild-hunt-collectors-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1431993600000,\n \"summary\": \"RPG and sequel to The Witcher 2 (2011), The Witcher 3 follows witcher Geralt of Rivia as he seeks out his former lover and his young subject while intermingling with the political workings of the wartorn Northern Kingdoms. Geralt has to fight monsters and deal with people of all sorts in order to solve complex problems and settle contentious disputes, each ranging from the personal to the world-changing.\",\n \"web-scraper-order\": null\n }\n]\nNone\n"
]
],
[
[
"## The REST API\n\nTo get a list of games in our frontend on the client we want to filter by the following attributes:\n- Minimum Rating: Games above a certain rating as documented in the IGDB.\n- Maximum Rating: Games below a certain rating as documented in the IGDB. Mainly to restrict the number of results.\n- Minimum Rating Count: Less popular games often have a few ratings on which their overall rating is based. This is not representative, so we select games with a minimum number of ratings.\n- Maximum playing time: We potentially want to play only games which don't have excessive playing time.\n\nNote that since we have imperfect data quality by search for these attributes we exclude games where for any reason these attributes are not set.",
"_____no_output_____"
]
],
[
[
"def search_api(min_rating = 0, max_rating = 100, min_rating_count = 0, max_playing_time = 1000):\n my_query = Query()\n test_rating = lambda s: True if(isinstance(s, float) and s >= min_rating and s <= max_rating) else False\n test_time = lambda s: True if(isinstance(s, float) and s <= max_playing_time) else False\n return game_db.search((my_query.game_rating.test(test_rating)) & (my_query.game_rating_count >= min_rating_count) &\n (my_query.hltb_main.test(test_time)))\n\nquery_result = search_api(min_rating = 75, min_rating_count = 20, max_playing_time = 5)\n\nprint(\"Number of results: \", len(query_result))\n\nprint(print(json.dumps(query_result, indent=4, sort_keys=True)))",
"Number of results: 23\n[\n {\n \"game_buy_date\": \" 25/6/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Adventure Indie\",\n \"game_igdb_id\": 9730,\n \"game_igdb_name\": \"Firewatch\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) Mac PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 79.6556401824,\n \"game_rating_count\": 618,\n \"game_size\": \" 3.16 GB \",\n \"game_themes\": \"Action Drama Open world Mystery\",\n \"game_title\": \"Firewatch\",\n \"games_found\": 1,\n \"hltb_main\": 4.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 9730,\\n \\\"artworks\\\": [\\n 8852\\n ],\\n \\\"genres\\\": [\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Firewatch\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 14,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 38731,\\n 38733,\\n 38734,\\n 136016,\\n 152656,\\n 152657,\\n 152658,\\n 161671\\n ],\\n \\\"summary\\\": \\\"Firewatch is a mystery set in the woods of Wyoming, where your only emotional lifeline is the person on the other end of a handheld radio. You play as a man named Henry who has retreated from his messy life to work as a fire lookout in the wilderness. Perched high atop a mountain, it\\u2019s your job to look for smoke and keep the wilderness safe. An especially hot and dry summer has everyone on edge. Your supervisor, a woman named Delilah, is available to you at all times over a small, handheld radio -- and is your only contact with the world you\\u2019ve left behind. But when something strange draws you out of your lookout tower and into the world, you\\u2019ll explore a wild and unknown environment, facing questions and making interpersonal choices that can build or destroy the only meaningful relationship you have.\\\",\\n \\\"themes\\\": [\\n 1,\\n 31,\\n 38,\\n 43\\n ],\\n \\\"total_rating\\\": 79.6556401824191,\\n \\\"total_rating_count\\\": 618,\\n \\\"url\\\": \\\"https://www.igdb.com/games/firewatch\\\"\\n }\\n]\",\n \"igdb_release_date\": 1454976000000,\n \"summary\": \"Firewatch is a mystery set in the woods of Wyoming, where your only emotional lifeline is the person on the other end of a handheld radio. You play as a man named Henry who has retreated from his messy life to work as a fire lookout in the wilderness. Perched high atop a mountain, it\\u2019s your job to look for smoke and keep the wilderness safe. An especially hot and dry summer has everyone on edge. Your supervisor, a woman named Delilah, is available to you at all times over a small, handheld radio -- and is your only contact with the world you\\u2019ve left behind. But when something strange draws you out of your lookout tower and into the world, you\\u2019ll explore a wild and unknown environment, facing questions and making interpersonal choices that can build or destroy the only meaningful relationship you have.\",\n \"web-scraper-order\": \"1069\"\n },\n {\n \"game_buy_date\": \" 6/4/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Simulator Adventure Indie Arcade\",\n \"game_igdb_id\": 12520,\n \"game_igdb_name\": \"Lovers in a Dangerous Spacetime\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) Mac PlayStation Network PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 78.827974555,\n \"game_rating_count\": 48,\n \"game_size\": \" 900.01 MB \",\n \"game_themes\": \"Action Science fiction\",\n \"game_title\": \"Lovers in a Dangerous Spacetime\",\n \"games_found\": 1,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 12520,\\n \\\"genres\\\": [\\n 13,\\n 31,\\n 32,\\n 33\\n ],\\n \\\"name\\\": \\\"Lovers in a Dangerous Spacetime\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 14,\\n 45,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 35919,\\n 35920,\\n 35921,\\n 35922,\\n 44935,\\n 107854,\\n 107855,\\n 113567,\\n 133848,\\n 136127\\n ],\\n \\\"summary\\\": \\\"Lovers in a Dangerous Spacetime is a frantic 1- or 2-player couch co-op action space shooter set in a massive neon battleship. Only through teamwork can you triumph over the evil forces of Anti-Love, rescue kidnapped space-bunnies, and avoid a vacuumy demise. Deep space is a dangerous place, but you don\\u2019t have to face it alone!\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 78.82797455503655,\\n \\\"total_rating_count\\\": 48,\\n \\\"url\\\": \\\"https://www.igdb.com/games/lovers-in-a-dangerous-spacetime\\\"\\n }\\n]\",\n \"igdb_release_date\": 1454976000000,\n \"summary\": \"Lovers in a Dangerous Spacetime is a frantic 1- or 2-player couch co-op action space shooter set in a massive neon battleship. Only through teamwork can you triumph over the evil forces of Anti-Love, rescue kidnapped space-bunnies, and avoid a vacuumy demise. Deep space is a dangerous place, but you don\\u2019t have to face it alone!\",\n \"web-scraper-order\": \"1112\"\n },\n {\n \"game_buy_date\": \" 12/3/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle Adventure Indie\",\n \"game_igdb_id\": 7342,\n \"game_igdb_name\": \"INSIDE\",\n \"game_platforms\": \"PC (Microsoft Windows) Mac iOS PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 89.7611687332,\n \"game_rating_count\": 866,\n \"game_size\": \" 2.08 GB \",\n \"game_themes\": \"Action Science fiction Horror Drama\",\n \"game_title\": \"INSIDE\",\n \"games_found\": 2,\n \"hltb_main\": 3.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7342,\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"INSIDE\\\",\\n \\\"platforms\\\": [\\n 6,\\n 14,\\n 39,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 113871,\\n 113872,\\n 113873,\\n 147713,\\n 154372,\\n 154373,\\n 218742\\n ],\\n \\\"summary\\\": \\\"An atmospheric 2D side-scroller in which, hunted and alone, a boy finds himself drawn into the center of a dark project and struggles to preserve his identity.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 19,\\n 31\\n ],\\n \\\"total_rating\\\": 89.76116873316846,\\n \\\"total_rating_count\\\": 866,\\n \\\"url\\\": \\\"https://www.igdb.com/games/inside\\\"\\n },\\n {\\n \\\"id\\\": 9687,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Little Devil Inside\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49,\\n 130,\\n 167\\n ],\\n \\\"release_dates\\\": [\\n 215937,\\n 215938,\\n 215939,\\n 215940,\\n 215941\\n ],\\n \\\"summary\\\": \\\"Little Devil Inside is a truly engaging 3D action adventure RPG game where you are thrown into a surreal but somewhat familiar setting with men, creatures and monsters to interact with, learn and hunt \\u2013 survive and discover the world that exists beyond.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/little-devil-inside\\\"\\n }\\n]\",\n \"igdb_release_date\": 1471910400000,\n \"summary\": \"An atmospheric 2D side-scroller in which, hunted and alone, a boy finds himself drawn into the center of a dark project and struggles to preserve his identity.\",\n \"web-scraper-order\": \"1118\"\n },\n {\n \"game_buy_date\": \" 12/3/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle Adventure Indie\",\n \"game_igdb_id\": 1331,\n \"game_igdb_name\": \"Limbo\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) PlayStation 3 Xbox 360 Mac Android iOS PlayStation Vita PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 82.8255222052,\n \"game_rating_count\": 879,\n \"game_size\": \" 168.82 MB \",\n \"game_themes\": \"Action Horror\",\n \"game_title\": \"LIMBO\",\n \"games_found\": 2,\n \"hltb_main\": 3.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1331,\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Limbo\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 12,\\n 14,\\n 34,\\n 39,\\n 46,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 107789,\\n 107790,\\n 107791,\\n 146865,\\n 147822,\\n 154368,\\n 154370,\\n 154371,\\n 164518,\\n 164519,\\n 186469,\\n 186470,\\n 186471,\\n 186472,\\n 186473,\\n 186474,\\n 186490\\n ],\\n \\\"summary\\\": \\\"Limbo is a black and white puzzle-platforming adventure. Play the role of a young boy traveling through an eerie and treacherous world in an attempt to discover the fate of his sister. Limbo\\\\u0027s design is an example of gaming as an art form. Short and sweet, doesn\\\\u0027t overstay its welcome. Puzzles are challenging and fun, not illogical and frustrating.\\\",\\n \\\"themes\\\": [\\n 1,\\n 19\\n ],\\n \\\"total_rating\\\": 82.82552220515444,\\n \\\"total_rating_count\\\": 879,\\n \\\"url\\\": \\\"https://www.igdb.com/games/limbo\\\"\\n },\\n {\\n \\\"id\\\": 27159,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"Touhou Shinpiroku\\uff5eUrban Legend in Limbo\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 117470,\\n 123457\\n ],\\n \\\"summary\\\": \\\"The 5th fighting game in the Touhou Project and 14.5th game overall.\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/touhou-shinpiroku-urban-legend-in-limbo\\\"\\n }\\n]\",\n \"igdb_release_date\": 1424822400000,\n \"summary\": \"Limbo is a black and white puzzle-platforming adventure. Play the role of a young boy traveling through an eerie and treacherous world in an attempt to discover the fate of his sister. Limbo's design is an example of gaming as an art form. Short and sweet, doesn't overstay its welcome. Puzzles are challenging and fun, not illogical and frustrating.\",\n \"web-scraper-order\": \"1119\"\n },\n {\n \"game_buy_date\": \" 8/2/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Adventure\",\n \"game_igdb_id\": 7330,\n \"game_igdb_name\": \"LittleBigPlanet 3\",\n \"game_platforms\": \"PlayStation 3 PlayStation 4\",\n \"game_rating\": 76.6274818742,\n \"game_rating_count\": 76,\n \"game_size\": \" 15.68 GB \",\n \"game_themes\": \"Sandbox\",\n \"game_title\": \"LittleBigPlanet 3\",\n \"games_found\": 1,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7330,\\n \\\"genres\\\": [\\n 8,\\n 31\\n ],\\n \\\"name\\\": \\\"LittleBigPlanet 3\\\",\\n \\\"platforms\\\": [\\n 9,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 20736,\\n 20738,\\n 20739,\\n 107807,\\n 107808,\\n 133844\\n ],\\n \\\"summary\\\": \\\"In LittleBigPlanet 3, explore a world filled with creativity as you explore all corners of the Imagisphere, meet the inhabitants of the mysterious planet Bunkum and face the nefarious Newton. Discover endless surprises that the LittleBigPlanet Community have created and shared for you to enjoy, with new levels and games to play every day. Then if you\\\\u0027re feeling inspired, flex your creative muscles with the powerful and intuitive customization tools, to bring your own imagination to life in LittleBigPlanet 3.\\\",\\n \\\"themes\\\": [\\n 33\\n ],\\n \\\"total_rating\\\": 76.62748187417435,\\n \\\"total_rating_count\\\": 76,\\n \\\"url\\\": \\\"https://www.igdb.com/games/littlebigplanet-3\\\"\\n }\\n]\",\n \"igdb_release_date\": 1417132800000,\n \"summary\": \"In LittleBigPlanet 3, explore a world filled with creativity as you explore all corners of the Imagisphere, meet the inhabitants of the mysterious planet Bunkum and face the nefarious Newton. Discover endless surprises that the LittleBigPlanet Community have created and shared for you to enjoy, with new levels and games to play every day. Then if you're feeling inspired, flex your creative muscles with the powerful and intuitive customization tools, to bring your own imagination to life in LittleBigPlanet 3.\",\n \"web-scraper-order\": \"1129\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Point-and-click Adventure\",\n \"game_igdb_id\": 15862,\n \"game_igdb_name\": \"Day of the Tentacle Remastered\",\n \"game_platforms\": \"PC (Microsoft Windows) Mac iOS PlayStation Network PlayStation 4 Xbox One\",\n \"game_rating\": 81.0952501079,\n \"game_rating_count\": 75,\n \"game_size\": \" 1.79 GB \",\n \"game_themes\": \"Fantasy Science fiction Historical Comedy\",\n \"game_title\": \"Day of the Tentacle Remastered\",\n \"games_found\": 1,\n \"hltb_main\": 4.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 15862,\\n \\\"artworks\\\": [\\n 8887\\n ],\\n \\\"genres\\\": [\\n 2,\\n 31\\n ],\\n \\\"name\\\": \\\"Day of the Tentacle Remastered\\\",\\n \\\"platforms\\\": [\\n 6,\\n 14,\\n 39,\\n 45,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 49179,\\n 49180,\\n 102383,\\n 134543,\\n 150413,\\n 166069,\\n 214601\\n ],\\n \\\"summary\\\": \\\"Originally released by LucasArts in 1993 as a sequel to Ron Gilbert\\u2019s ground \\\\nbreaking Maniac Mansion, Day of the Tentacle is a mind-bending, time \\\\ntravel, cartoon puzzle adventure game in which three unlikely friends work \\\\ntogether to prevent an evil mutated purple tentacle from taking over the \\\\nworld!\\\\n\\\\nNow, over twenty years later, Day of the Tentacle is back in a remastered \\\\nedition that features all new hand-drawn, high resolution artwork, with \\\\nremastered audio, music and sound effects (which the original 90s marketing \\\\nblurb described as \\u2018zany!\\u2019)\\\\n\\\\nPlayers are able to switch back and forth between classic and remastered \\\\nmodes, and mix and match audio, graphics and user interface to their heart\\\\u0027s \\\\ndesire. We\\u2019ve also included a concept art browser, and recorded a \\\\ncommentary track with the game\\u2019s original creators Tim Schafer, Dave \\\\nGrossman, Larry Ahern, Peter Chan, Peter McConnell and Clint Bajakian.\\\\n \\\\nDay of the Tentacle was Tim Schafer\\u2019s \\ufb01rst game as co-project lead, and a \\\\nmuch beloved cult classic! This special edition has been lovingly restored \\\\nand remade with the care and attention that can only come from involving \\\\nthe game\\\\u0027s original creators. It\\u2019s coming to Windows, OSX, PlayStation 4 \\\\nand PlayStation Vita early next year!\\\",\\n \\\"themes\\\": [\\n 17,\\n 18,\\n 22,\\n 27\\n ],\\n \\\"total_rating\\\": 81.09525010789625,\\n \\\"total_rating_count\\\": 75,\\n \\\"url\\\": \\\"https://www.igdb.com/games/day-of-the-tentacle-remastered\\\"\\n }\\n]\",\n \"igdb_release_date\": 1458604800000,\n \"summary\": \"Originally released by LucasArts in 1993 as a sequel to Ron Gilbert\\u2019s ground \\nbreaking Maniac Mansion, Day of the Tentacle is a mind-bending, time \\ntravel, cartoon puzzle adventure game in which three unlikely friends work \\ntogether to prevent an evil mutated purple tentacle from taking over the \\nworld!\\n\\nNow, over twenty years later, Day of the Tentacle is back in a remastered \\nedition that features all new hand-drawn, high resolution artwork, with \\nremastered audio, music and sound effects (which the original 90s marketing \\nblurb described as \\u2018zany!\\u2019)\\n\\nPlayers are able to switch back and forth between classic and remastered \\nmodes, and mix and match audio, graphics and user interface to their heart's \\ndesire. We\\u2019ve also included a concept art browser, and recorded a \\ncommentary track with the game\\u2019s original creators Tim Schafer, Dave \\nGrossman, Larry Ahern, Peter Chan, Peter McConnell and Clint Bajakian.\\n \\nDay of the Tentacle was Tim Schafer\\u2019s \\ufb01rst game as co-project lead, and a \\nmuch beloved cult classic! This special edition has been lovingly restored \\nand remade with the care and attention that can only come from involving \\nthe game's original creators. It\\u2019s coming to Windows, OSX, PlayStation 4 \\nand PlayStation Vita early next year!\",\n \"web-scraper-order\": \"1152\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Adventure Indie\",\n \"game_igdb_id\": 14740,\n \"game_igdb_name\": \"The Deadly Tower of Monsters\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation Network PlayStation 4\",\n \"game_rating\": 75.8169185565,\n \"game_rating_count\": 39,\n \"game_size\": \" 1.92 GB \",\n \"game_themes\": \"Action Science fiction Comedy\",\n \"game_title\": \"The Deadly Tower of Monsters\",\n \"games_found\": 1,\n \"hltb_main\": 4.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 14740,\\n \\\"genres\\\": [\\n 5,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"The Deadly Tower of Monsters\\\",\\n \\\"platforms\\\": [\\n 6,\\n 45,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 51297,\\n 51298,\\n 106149,\\n 106150,\\n 118604\\n ],\\n \\\"summary\\\": \\\"Scarlet Nova - the space diva with a checkered past - and introducing...the robot! Amazing adventures! Strange drama and more await in the deadly tower of monsters. The action-filled adventure game for personal computers and the Playstation 4 entertainment system.\\\\n\\\\nMarooned on the desolate planet Gravoria, the trio of adventurers find their only method of escape awaits at the top of a tower - a tower renowned for its deadliness and its propensity to be filled with monsters! Lizard-men! UFO\\u2019s! Nuclear ants! Dinosaurs! Robot monkeys! All of these horrors await our intrepid adventurers as they ascend the deadly tower. Will they avoid their own doom? Find out this fall, only in theaters on PC and PS4!\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 27\\n ],\\n \\\"total_rating\\\": 75.8169185564509,\\n \\\"total_rating_count\\\": 39,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-deadly-tower-of-monsters\\\"\\n }\\n]\",\n \"igdb_release_date\": 1453161600000,\n \"summary\": \"Scarlet Nova - the space diva with a checkered past - and introducing...the robot! Amazing adventures! Strange drama and more await in the deadly tower of monsters. The action-filled adventure game for personal computers and the Playstation 4 entertainment system.\\n\\nMarooned on the desolate planet Gravoria, the trio of adventurers find their only method of escape awaits at the top of a tower - a tower renowned for its deadliness and its propensity to be filled with monsters! Lizard-men! UFO\\u2019s! Nuclear ants! Dinosaurs! Robot monkeys! All of these horrors await our intrepid adventurers as they ascend the deadly tower. Will they avoid their own doom? Find out this fall, only in theaters on PC and PS4!\",\n \"web-scraper-order\": \"1163\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Adventure Indie\",\n \"game_igdb_id\": 7405,\n \"game_igdb_name\": \"Everybody's Gone to the Rapture\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation Network PlayStation 4\",\n \"game_rating\": 75.7491029859,\n \"game_rating_count\": 133,\n \"game_size\": \" 6.04 GB \",\n \"game_themes\": \"Science fiction Drama\",\n \"game_title\": \"Everybody's Gone To The Rapture\\u2122\",\n \"games_found\": 1,\n \"hltb_main\": 4.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7405,\\n \\\"genres\\\": [\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Everybody\\\\u0027s Gone to the Rapture\\\",\\n \\\"platforms\\\": [\\n 6,\\n 45,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 32210,\\n 48857,\\n 102903,\\n 102904\\n ],\\n \\\"summary\\\": \\\"For the last twelve months, we\\u2019ve had our heads down working hard on Everybody\\u2019s Gone to the Rapture and it\\u2019s really exciting to be able to share some more information with you as well as a new trailer.\\\\n\\\\nIf you already know The Chinese Room, you\\u2019ll know that we make story-driven games. Creating a rich, deep world with strong drama and exceptional production values is key to what we\\u2019re all about. Rapture is set in a remote valley in June 1984 and is a story about people and how they live with each other. But it\\u2019s also about the end of the world. \\\\n\\\\nRapture is inspired by the fiction of John Wyndham, J. G. Ballard, John Christopher and other authors who deal with ordinary people in extraordinary circumstances. There\\u2019s a very particular English feel that we wanted to capture in the game, a combination of the epic and the intimate. Rapture also came from our obsession with post-apocalyptic gaming, and the simple idea that whilst we normally play as the hero, in reality, most of us would be the piles of ash and bone littering the game world. That\\u2019s an interesting place to start telling a story.\\\\n\\\\nOur approach is to create a game that you can utterly immerse yourself in. Yaughton Valley, where Rapture takes place, is a living, breathing world. The world of Rapture is not just a backdrop; it\\u2019s a character in its own right. It\\u2019s great working with PS4 as its processing power makes a game like this possible for a team our size.\\\\n\\\\nThe game is all about discovery. It\\u2019s open-world so you have the freedom to explore wherever you like, visiting areas in an order you define, and the story is written to allow this whilst making sure every player has a strong dramatic experience. It\\u2019s a type of storytelling that is completely unique to games. The choices you make as a player have a direct impact on how you understand the story \\u2013 the more you explore and interact, the deeper you are drawn into Rapture\\u2019s world.\\\",\\n \\\"themes\\\": [\\n 18,\\n 31\\n ],\\n \\\"total_rating\\\": 75.7491029858802,\\n \\\"total_rating_count\\\": 133,\\n \\\"url\\\": \\\"https://www.igdb.com/games/everybody-s-gone-to-the-rapture\\\"\\n }\\n]\",\n \"igdb_release_date\": 1439251200000,\n \"summary\": \"For the last twelve months, we\\u2019ve had our heads down working hard on Everybody\\u2019s Gone to the Rapture and it\\u2019s really exciting to be able to share some more information with you as well as a new trailer.\\n\\nIf you already know The Chinese Room, you\\u2019ll know that we make story-driven games. Creating a rich, deep world with strong drama and exceptional production values is key to what we\\u2019re all about. Rapture is set in a remote valley in June 1984 and is a story about people and how they live with each other. But it\\u2019s also about the end of the world. \\n\\nRapture is inspired by the fiction of John Wyndham, J. G. Ballard, John Christopher and other authors who deal with ordinary people in extraordinary circumstances. There\\u2019s a very particular English feel that we wanted to capture in the game, a combination of the epic and the intimate. Rapture also came from our obsession with post-apocalyptic gaming, and the simple idea that whilst we normally play as the hero, in reality, most of us would be the piles of ash and bone littering the game world. That\\u2019s an interesting place to start telling a story.\\n\\nOur approach is to create a game that you can utterly immerse yourself in. Yaughton Valley, where Rapture takes place, is a living, breathing world. The world of Rapture is not just a backdrop; it\\u2019s a character in its own right. It\\u2019s great working with PS4 as its processing power makes a game like this possible for a team our size.\\n\\nThe game is all about discovery. It\\u2019s open-world so you have the freedom to explore wherever you like, visiting areas in an order you define, and the story is written to allow this whilst making sure every player has a strong dramatic experience. It\\u2019s a type of storytelling that is completely unique to games. The choices you make as a player have a direct impact on how you understand the story \\u2013 the more you explore and interact, the deeper you are drawn into Rapture\\u2019s world.\",\n \"web-scraper-order\": \"1181\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Point-and-click Adventure Indie\",\n \"game_igdb_id\": 1906,\n \"game_igdb_name\": \"Gone Home\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) Mac iOS PlayStation Network PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 79.6114644805,\n \"game_rating_count\": 362,\n \"game_size\": \" 3.27 GB \",\n \"game_themes\": \"Drama Mystery\",\n \"game_title\": \"Gone Home\",\n \"games_found\": 1,\n \"hltb_main\": 2.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1906,\\n \\\"artworks\\\": [\\n 8870\\n ],\\n \\\"genres\\\": [\\n 2,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Gone Home\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 14,\\n 39,\\n 45,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 20755,\\n 20757,\\n 43952,\\n 43953,\\n 53808,\\n 103317,\\n 103318,\\n 147117,\\n 157553,\\n 157554,\\n 161898\\n ],\\n \\\"summary\\\": \\\"Gone Home is a conceptual simulation game somewhat themed after classic adventure titles where how you interact with space around your characters determines how far you progress in the game. This title is all about exploring a modern, residential locale, and discovering the story of what happened there by investigating a deeply interactive gameworld. The development team aims to push for true simulation,both in the sense of the physics system but also in allowing the player to open any door or drawer they\\\\u0027d logically be able to and examine what\\\\u0027s inside, down to small details.\\\",\\n \\\"themes\\\": [\\n 31,\\n 43\\n ],\\n \\\"total_rating\\\": 79.61146448054691,\\n \\\"total_rating_count\\\": 362,\\n \\\"url\\\": \\\"https://www.igdb.com/games/gone-home\\\"\\n }\\n]\",\n \"igdb_release_date\": 1455235200000,\n \"summary\": \"Gone Home is a conceptual simulation game somewhat themed after classic adventure titles where how you interact with space around your characters determines how far you progress in the game. This title is all about exploring a modern, residential locale, and discovering the story of what happened there by investigating a deeply interactive gameworld. The development team aims to push for true simulation,both in the sense of the physics system but also in allowing the player to open any door or drawer they'd logically be able to and examine what's inside, down to small details.\",\n \"web-scraper-order\": \"1182\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Puzzle Adventure\",\n \"game_igdb_id\": 8352,\n \"game_igdb_name\": \"The Unfinished Swan\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 Mac iOS PlayStation Vita PlayStation 4\",\n \"game_rating\": 78.0818722535,\n \"game_rating_count\": 62,\n \"game_size\": \" 1.4 GB \",\n \"game_themes\": null,\n \"game_title\": \"The Unfinished Swan\",\n \"games_found\": 1,\n \"hltb_main\": 2.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 8352,\\n \\\"genres\\\": [\\n 9,\\n 31\\n ],\\n \\\"name\\\": \\\"The Unfinished Swan\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 14,\\n 39,\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 134251,\\n 134252,\\n 209914,\\n 209915,\\n 209916,\\n 209917,\\n 209918\\n ],\\n \\\"summary\\\": \\\"The Unfinished Swan is a game about exploring the unknown. \\\\n \\\\nThe player is a young boy chasing after a swan who has wandered off into a surreal, unfinished kingdom. The game begins in a completely white space where players can throw paint to splatter their surroundings and reveal the world around them.\\\",\\n \\\"total_rating\\\": 78.08187225350545,\\n \\\"total_rating_count\\\": 62,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-unfinished-swan\\\"\\n }\\n]\",\n \"igdb_release_date\": 1414454400000,\n \"summary\": \"The Unfinished Swan is a game about exploring the unknown. \\n \\nThe player is a young boy chasing after a swan who has wandered off into a surreal, unfinished kingdom. The game begins in a completely white space where players can throw paint to splatter their surroundings and reveal the world around them.\",\n \"web-scraper-order\": \"1187\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Music Platform Puzzle Strategy\",\n \"game_igdb_id\": 7729,\n \"game_igdb_name\": \"Sound Shapes\",\n \"game_platforms\": \"PlayStation 3 PlayStation Network PlayStation Vita PlayStation 4\",\n \"game_rating\": 80.509865238,\n \"game_rating_count\": 40,\n \"game_size\": \" 1.29 GB \",\n \"game_themes\": \"Action Survival\",\n \"game_title\": \"Sound Shapes\",\n \"games_found\": 1,\n \"hltb_main\": 3.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7729,\\n \\\"genres\\\": [\\n 7,\\n 8,\\n 9,\\n 15\\n ],\\n \\\"name\\\": \\\"Sound Shapes\\\",\\n \\\"platforms\\\": [\\n 9,\\n 45,\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 20264,\\n 20265,\\n 20266,\\n 105717,\\n 105718,\\n 134127,\\n 134128,\\n 134763,\\n 134764\\n ],\\n \\\"summary\\\": \\\"Play, Compose and Share in a unique take on the classic side-scrolling platformer where your actions make the music. \\\\n \\\\nEqual parts instrument and game, Sound Shapes\\u2122 gives everyone the ability to make music. Play through a unique campaign that fuses music and artwork into a classic 2D platformer, featuring artwork by Pixeljam, Capy, Superbrothers and more, with music by I Am Robot and Proud, Jim Guthrie and Deadmau5. Create your own unique musical levels with all of the campaign content and share with the world. Sound Shapes creates an ever-changing musical community for everyone to enjoy at home or on the go.\\\",\\n \\\"themes\\\": [\\n 1,\\n 21\\n ],\\n \\\"total_rating\\\": 80.50986523797675,\\n \\\"total_rating_count\\\": 40,\\n \\\"url\\\": \\\"https://www.igdb.com/games/sound-shapes\\\"\\n }\\n]\",\n \"igdb_release_date\": 1385683200000,\n \"summary\": \"Play, Compose and Share in a unique take on the classic side-scrolling platformer where your actions make the music. \\n \\nEqual parts instrument and game, Sound Shapes\\u2122 gives everyone the ability to make music. Play through a unique campaign that fuses music and artwork into a classic 2D platformer, featuring artwork by Pixeljam, Capy, Superbrothers and more, with music by I Am Robot and Proud, Jim Guthrie and Deadmau5. Create your own unique musical levels with all of the campaign content and share with the world. Sound Shapes creates an ever-changing musical community for everyone to enjoy at home or on the go.\",\n \"web-scraper-order\": \"1189\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle Adventure Indie\",\n \"game_igdb_id\": 5892,\n \"game_igdb_name\": \"The Swapper\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) PlayStation 3 Mac Wii U PlayStation Network PlayStation Vita PlayStation 4 Xbox One\",\n \"game_rating\": 83.5059281324,\n \"game_rating_count\": 133,\n \"game_size\": \" 410.52 MB \",\n \"game_themes\": \"Action Science fiction\",\n \"game_title\": \"The Swapper\",\n \"games_found\": 1,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 5892,\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"The Swapper\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 41,\\n 45,\\n 46,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 14423,\\n 32933,\\n 32934,\\n 32935,\\n 32936,\\n 32937,\\n 32938,\\n 32939,\\n 32940,\\n 32941,\\n 32942,\\n 32943,\\n 106313,\\n 106314,\\n 136381,\\n 144325\\n ],\\n \\\"summary\\\": \\\"The Swapper is a short puzzle platformer where you must complete every puzzle and collect 124 orbs, in groups of 3 and 9 later on, to complete the game.\\\\n\\\\nThe game has a tool which lets you create up to 4 clones and switch between them as long as you have a clear line of sight.\\\\n\\\\nThe main obstacles for the puzzles are 3 kinds of lights that interfere with the tool in different ways to make the puzzles harder.\\\\n\\\\nAchievements/Trophies are tied to hidden consoles instead of story progress so a guide will most likely be needed to find all 10.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 83.50592813244465,\\n \\\"total_rating_count\\\": 133,\\n \\\"url\\\": \\\"https://www.igdb.com/games/the-swapper\\\"\\n }\\n]\",\n \"igdb_release_date\": 1407283200000,\n \"summary\": \"The Swapper is a short puzzle platformer where you must complete every puzzle and collect 124 orbs, in groups of 3 and 9 later on, to complete the game.\\n\\nThe game has a tool which lets you create up to 4 clones and switch between them as long as you have a clear line of sight.\\n\\nThe main obstacles for the puzzles are 3 kinds of lights that interfere with the tool in different ways to make the puzzles harder.\\n\\nAchievements/Trophies are tied to hidden consoles instead of story progress so a guide will most likely be needed to find all 10.\",\n \"web-scraper-order\": \"1194\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Platform Adventure Indie\",\n \"game_igdb_id\": 8879,\n \"game_igdb_name\": \"Super Time Force Ultra\",\n \"game_platforms\": \"PC (Microsoft Windows) Xbox 360 PlayStation Network PlayStation Vita PlayStation 4 Xbox One\",\n \"game_rating\": 85.2461347893,\n \"game_rating_count\": 23,\n \"game_size\": \" 640.55 MB \",\n \"game_themes\": \"Action\",\n \"game_title\": \"Super Time Force Ultra\",\n \"games_found\": 1,\n \"hltb_main\": 4.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 8879,\\n \\\"genres\\\": [\\n 5,\\n 8,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Super Time Force Ultra\\\",\\n \\\"platforms\\\": [\\n 6,\\n 12,\\n 45,\\n 46,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 29152,\\n 29153,\\n 29154,\\n 43003,\\n 43004,\\n 105958,\\n 105959\\n ],\\n \\\"summary\\\": \\\"Super Time Force Ultra is an action-packed platformer with a time-travelling twist! You\\u2019re in control of time itself, bending and stretching it to your advantage on the battlefield. Rewind time and choose when to jump back into the action, teaming-up with your past selves in a unique single-player co-op experience! Take control of up to 16 unique characters, and battle across 6 different time periods, from the long-ago past to the far-away future.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 85.24613478932031,\\n \\\"total_rating_count\\\": 23,\\n \\\"url\\\": \\\"https://www.igdb.com/games/super-time-force-ultra\\\"\\n }\\n]\",\n \"igdb_release_date\": 1441152000000,\n \"summary\": \"Super Time Force Ultra is an action-packed platformer with a time-travelling twist! You\\u2019re in control of time itself, bending and stretching it to your advantage on the battlefield. Rewind time and choose when to jump back into the action, teaming-up with your past selves in a unique single-player co-op experience! Take control of up to 16 unique characters, and battle across 6 different time periods, from the long-ago past to the far-away future.\",\n \"web-scraper-order\": \"1197\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Sport Indie\",\n \"game_igdb_id\": 9523,\n \"game_igdb_name\": \"OlliOlli2: Welcome to Olliwood\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) PlayStation 3 Mac PlayStation Vita PlayStation 4 Xbox One\",\n \"game_rating\": 78.3917248127,\n \"game_rating_count\": 33,\n \"game_size\": \" 139 MB \",\n \"game_themes\": \"Action\",\n \"game_title\": \"OlliOlli2: Welcome to Olliwood\",\n \"games_found\": 1,\n \"hltb_main\": 3.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 9523,\\n \\\"genres\\\": [\\n 8,\\n 14,\\n 32\\n ],\\n \\\"name\\\": \\\"OlliOlli2: Welcome to Olliwood\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 46,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 28265,\\n 28266,\\n 28267,\\n 130297,\\n 183942,\\n 183943,\\n 183944\\n ],\\n \\\"summary\\\": \\\"Drop in to Olliwood and prepare for finger-flippin\\u2019 mayhem in this follow up to cult skateboarding smashOlliOlli. The iconic skater is going all green-screen with a stunning new look, plucking you from the street and dropping you squarely in the middle of the big screen\\u2019s most bodacious cinematic locations.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 78.39172481274615,\\n \\\"total_rating_count\\\": 33,\\n \\\"url\\\": \\\"https://www.igdb.com/games/olliolli2-welcome-to-olliwood\\\"\\n }\\n]\",\n \"igdb_release_date\": 1425427200000,\n \"summary\": \"Drop in to Olliwood and prepare for finger-flippin\\u2019 mayhem in this follow up to cult skateboarding smashOlliOlli. The iconic skater is going all green-screen with a stunning new look, plucking you from the street and dropping you squarely in the middle of the big screen\\u2019s most bodacious cinematic locations.\",\n \"web-scraper-order\": \"1206\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Hack and slash/Beat 'em up Adventure Indie\",\n \"game_igdb_id\": 17026,\n \"game_igdb_name\": \"Furi\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation Network PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 79.0436333285,\n \"game_rating_count\": 142,\n \"game_size\": \" 3.65 GB \",\n \"game_themes\": \"Action Science fiction\",\n \"game_title\": \"Furi\",\n \"games_found\": 10,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 17026,\\n \\\"genres\\\": [\\n 5,\\n 25,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Furi\\\",\\n \\\"platforms\\\": [\\n 6,\\n 45,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 53089,\\n 53090,\\n 60514,\\n 103218,\\n 103219,\\n 116252,\\n 131745,\\n 136030\\n ],\\n \\\"summary\\\": \\\"Fight your way free in our frenzied all-boss fighter, and discover what\\u2019s waiting behind the last gate. Furi is all about the tension of one-on-one fights against deadly adversaries. It\\u2019s an intense, ultra-responsive hack-and-slash with a unique mix of fast-paced sword fighting and dual-stick shooting. Each of the formidable guardians \\u2014designed by Afro Samurai creator Takashi Okazaki\\u2014 has a unique and surprising combat style that requires focus and skill to defeat. The high-energy action gets a boost from an explosive soundtrack composed by electro musicians including Carpenter Brut, who created the trailer\\u2019s theme.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 79.0436333285202,\\n \\\"total_rating_count\\\": 142,\\n \\\"url\\\": \\\"https://www.igdb.com/games/furi\\\"\\n },\\n {\\n \\\"id\\\": 54844,\\n \\\"artworks\\\": [\\n 4979,\\n 4980,\\n 7955,\\n 7956,\\n 7957\\n ],\\n \\\"genres\\\": [\\n 5,\\n 32\\n ],\\n \\\"name\\\": \\\"Ion Fury\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 172628,\\n 172629,\\n 195813,\\n 195814,\\n 195815\\n ],\\n \\\"summary\\\": \\\"Shelly \\u201cBombshell\\u201d Harrison earned her nickname as a bomb disposal expert for the Global Defense Force. When transhumanist cult mastermind Dr. Jadus Heskel unleashes a cybernetic army on Neo DC, Shelly decides it\\u2019s time to start chucking bombs rather than diffusing them. \\\\n \\\\nHer journey will leave trails of blood and gore in huge, multi-path levels filled with those famous colorful keycards and plenty of secrets and Easter Eggs to discover behind every corner. There\\u2019s also no regenerating health here, so stop taking cover and start running and gunning. Honestly, Ion Maiden should probably come out on three hundred floppy disks. \\\\n \\\\nShelly\\u2019s quest to take down Dr. Heskel\\u2019s army will see her use an arsenal of weapons, all with alternate fire modes or different ammo types. Her signature revolver, Loverboy, brings enemies pain and players pleasure with single shots, or Shelly can fan the hammer Old West style. Shotguns are fun, but tossing grenades down their barrels and firing explosive rounds is even better. Bowling Bombs are just as violent and over-the-top as one would hope. \\\\n \\\\nIon Maiden laughs at the idea of constant checkpoints and straight paths through shooting galleries. But just because this is a true old-school first-person shooter doesn\\u2019t mean there won\\u2019t be all the good new stuff the last two decades have brought. Headshots? Hell yeah. More physics and interactivity? You betcha. Widescreen, controller support, and Auto Saves? 3D Realms and Voidpoint took the best of both worlds and cooked it all into a bloody stew.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 81.11534457391255,\\n \\\"total_rating_count\\\": 22,\\n \\\"url\\\": \\\"https://www.igdb.com/games/ion-fury\\\"\\n },\\n {\\n \\\"id\\\": 112185,\\n \\\"artworks\\\": [\\n 9297\\n ],\\n \\\"genres\\\": [\\n 5,\\n 8,\\n 12,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"Fury Unleashed\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 189312,\\n 192469,\\n 196089,\\n 202756\\n ],\\n \\\"summary\\\": \\\"Fury Unleashed is an action platformer where you shoot your way through the pages of an ever-changing comic book. Take advantage of unique combo system to unleash your fury and become a whirling tornado of destruction. Discover why your creator doubted you and prove him wrong. \\\\n \\\\nYour guns are your best friends, and ink is your most valuable resource \\u2013 collect it from defeated enemies to permanently upgrade your hero. The more dynamic and brave your play style, the greater the rewards! But remember to stay focused at all times, or you will die sooner than you think and lose everything you looted on your way.\\\",\\n \\\"themes\\\": [\\n 1,\\n 17,\\n 18\\n ],\\n \\\"total_rating\\\": 78.3333333333333,\\n \\\"total_rating_count\\\": 6,\\n \\\"url\\\": \\\"https://www.igdb.com/games/fury-unleashed\\\"\\n },\\n {\\n \\\"id\\\": 28507,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"ACA NEOGEO FATAL FURY\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 175996,\\n 175997,\\n 176350\\n ],\\n \\\"summary\\\": \\\"FATAL FURY is a fighting game released by SNK in 1991. Players take part in brutal street fights in a variety of locations, with the goal of toppling the infamous crime lord Geese Howard.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/aca-neogeo-fatal-fury\\\"\\n },\\n {\\n \\\"id\\\": 11052,\\n \\\"genres\\\": [\\n 33\\n ],\\n \\\"name\\\": \\\"Kung Fury: Street Rage\\\",\\n \\\"platforms\\\": [\\n 6,\\n 34,\\n 39,\\n 45,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 30499,\\n 30500,\\n 30501,\\n 32240,\\n 103883,\\n 103884,\\n 120654\\n ],\\n \\\"summary\\\": \\\"Get blown into another dimension as you experience the gutbusting fun with the Kung Fury game. Beat the Nazis to stop Kung F\\u00fchrer and uphold the law! Become the action!\\\\n\\\\nBe. Kung. Fury!!!!\\\",\\n \\\"themes\\\": [\\n 1,\\n 27\\n ],\\n \\\"total_rating\\\": 50.2683931085663,\\n \\\"total_rating_count\\\": 25,\\n \\\"url\\\": \\\"https://www.igdb.com/games/kung-fury-street-rage\\\"\\n },\\n {\\n \\\"id\\\": 99484,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"ACA NEOGEO FATAL FURY 3\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 175948,\\n 175949,\\n 176364\\n ],\\n \\\"summary\\\": \\\"FATAL FURY 3 is a fighting game released by SNK in 1995. A new \\u201cStory\\u201d is about to begin in the city of South Town. Five new characters join for a total of 10 hungry wolves ready for battle.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/aca-neogeo-fatal-fury-3\\\"\\n },\\n {\\n \\\"id\\\": 99510,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"ACA NEOGEO FATAL FURY 2\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 175965,\\n 175966,\\n 176353\\n ],\\n \\\"summary\\\": \\\"FATAL FURY 2 is a fighting game released by SNK in 1992. Terry, Andy, Joe return from the previous installment along with five new fighters in order to decide who is the strongest one.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/aca-neogeo-fatal-fury-2\\\"\\n },\\n {\\n \\\"id\\\": 28138,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"Fatal Fury: Wild Ambition\\\",\\n \\\"platforms\\\": [\\n 7,\\n 45,\\n 135\\n ],\\n \\\"release_dates\\\": [\\n 68186,\\n 68187,\\n 68188,\\n 68189,\\n 68190,\\n 126844\\n ],\\n \\\"summary\\\": \\\"The only Hyper Neo Geo 64 game to be ported to another system.\\\",\\n \\\"themes\\\": [\\n 17\\n ],\\n \\\"total_rating\\\": 66.6708023478881,\\n \\\"total_rating_count\\\": 6,\\n \\\"url\\\": \\\"https://www.igdb.com/games/fatal-fury-wild-ambition\\\"\\n },\\n {\\n \\\"id\\\": 99742,\\n \\\"artworks\\\": [\\n 8956\\n ],\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"ACA NEOGEO FATAL FURY SPECIAL\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 176321,\\n 176322,\\n 176323\\n ],\\n \\\"summary\\\": \\\"FATAL FURY SPECIAL is a powered-up version of \\\\u0027FATAL FURY 2\\\\u0027 which brings a faster game speed, introduces combo attacks for the first time in the Series, and welcomes more returning characters for a total of 15 fighters.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/aca-neogeo-fatal-fury-special\\\"\\n },\\n {\\n \\\"id\\\": 90199,\\n \\\"genres\\\": [\\n 4,\\n 33\\n ],\\n \\\"name\\\": \\\"ACA NEOGEO REAL BOUT FATAL FURY\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 176309,\\n 176310,\\n 176365\\n ],\\n \\\"summary\\\": \\\"REAL BOUT FATAL FURY is a fighting game released by SNK in 1995. Using the previous system as a base, isolating the Sweep Button, the inclusion of Combination Attacks, and other elements such as ring outs make for an even speedier and tempo-based play style. Sixteen fighters battle it out to see who is the strongest.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/aca-neogeo-real-bout-fatal-fury\\\"\\n }\\n]\",\n \"igdb_release_date\": 1467676800000,\n \"summary\": \"Fight your way free in our frenzied all-boss fighter, and discover what\\u2019s waiting behind the last gate. Furi is all about the tension of one-on-one fights against deadly adversaries. It\\u2019s an intense, ultra-responsive hack-and-slash with a unique mix of fast-paced sword fighting and dual-stick shooting. Each of the formidable guardians \\u2014designed by Afro Samurai creator Takashi Okazaki\\u2014 has a unique and surprising combat style that requires focus and skill to defeat. The high-energy action gets a boost from an explosive soundtrack composed by electro musicians including Carpenter Brut, who created the trailer\\u2019s theme.\",\n \"web-scraper-order\": \"1210\"\n },\n {\n \"game_buy_date\": \" 22/1/2017\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Strategy Adventure\",\n \"game_igdb_id\": 5328,\n \"game_igdb_name\": \"Metal Gear Solid V: Ground Zeroes\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 Xbox 360 PlayStation 4 Xbox One\",\n \"game_rating\": 77.4949480898,\n \"game_rating_count\": 336,\n \"game_size\": \" 3.9 GB \",\n \"game_themes\": \"Action Science fiction Stealth Open world\",\n \"game_title\": \"METAL GEAR SOLID V: GROUND ZEROES\",\n \"games_found\": 1,\n \"hltb_main\": 2.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 5328,\\n \\\"genres\\\": [\\n 5,\\n 15,\\n 31\\n ],\\n \\\"name\\\": \\\"Metal Gear Solid V: Ground Zeroes\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 12,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 12601,\\n 12602,\\n 12603,\\n 12604,\\n 108034,\\n 133873,\\n 133874,\\n 223274\\n ],\\n \\\"summary\\\": \\\"World-renowned Kojima Productions showcases another masterpiece in the Metal Gear Solid franchise with Metal Gear Solid V: Ground Zeroes. Metal Gear Solid V: Ground Zeroes is the first segment of the \\u2018Metal Gear Solid V Experience\\u2019 and prologue to the larger second segment, Metal Gear Solid V: The Phantom Pain launching thereafter. \\\\n \\\\n \\\\nMGSV: GZ gives core fans the opportunity to get a taste of the world-class production\\u2019s unparalleled visual presentation and gameplay before the release of the main game. It also provides an opportunity for gamers who have never played a Kojima Productions game, and veterans alike, to gain familiarity with the radical new game design and unparalleled style of presentation. \\\\n \\\\n \\\\nThe critically acclaimed Metal Gear Solid franchise has entertained fans for decades and revolutionized the gaming industry. Kojima Productions once again raises the bar with the FOX Engine offering incredible graphic fidelity and the introduction of open world game design in the Metal Gear Solid universe. This is the experience that core gamers have been waiting for.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 23,\\n 38\\n ],\\n \\\"total_rating\\\": 77.49494808981589,\\n \\\"total_rating_count\\\": 336,\\n \\\"url\\\": \\\"https://www.igdb.com/games/metal-gear-solid-v-ground-zeroes\\\"\\n }\\n]\",\n \"igdb_release_date\": 1395360000000,\n \"summary\": \"World-renowned Kojima Productions showcases another masterpiece in the Metal Gear Solid franchise with Metal Gear Solid V: Ground Zeroes. Metal Gear Solid V: Ground Zeroes is the first segment of the \\u2018Metal Gear Solid V Experience\\u2019 and prologue to the larger second segment, Metal Gear Solid V: The Phantom Pain launching thereafter. \\n \\n \\nMGSV: GZ gives core fans the opportunity to get a taste of the world-class production\\u2019s unparalleled visual presentation and gameplay before the release of the main game. It also provides an opportunity for gamers who have never played a Kojima Productions game, and veterans alike, to gain familiarity with the radical new game design and unparalleled style of presentation. \\n \\n \\nThe critically acclaimed Metal Gear Solid franchise has entertained fans for decades and revolutionized the gaming industry. Kojima Productions once again raises the bar with the FOX Engine offering incredible graphic fidelity and the introduction of open world game design in the Metal Gear Solid universe. This is the experience that core gamers have been waiting for.\",\n \"web-scraper-order\": \"1213\"\n },\n {\n \"game_buy_date\": \" 27/11/2015\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle Indie\",\n \"game_igdb_id\": 7641,\n \"game_igdb_name\": \"Teslagrad\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) PlayStation 3 Mac Wii U PlayStation Network PlayStation Vita PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 76.6677350731,\n \"game_rating_count\": 41,\n \"game_size\": \" 843.91 MB \",\n \"game_themes\": \"Action Science fiction\",\n \"game_title\": \"Teslagrad\",\n \"games_found\": 1,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 7641,\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 32\\n ],\\n \\\"name\\\": \\\"Teslagrad\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 41,\\n 45,\\n 46,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 19963,\\n 20726,\\n 20727,\\n 20728,\\n 49710,\\n 49711,\\n 49712,\\n 49713,\\n 106084,\\n 122361,\\n 127742,\\n 128854,\\n 134205,\\n 136348,\\n 144065,\\n 146574,\\n 146575\\n ],\\n \\\"summary\\\": \\\"Teslagrad is a 2D puzzle platformer with action elements, where magnetism and other electromagnetic powers are the key to go throughout the game, and thereby discover the secrets kept in the long abandoned Tesla Tower. Gain new abilities to explore a non-linear world with more than 100 beautiful hand-drawn environments, in a steampunk-inspired vision of old Europe. Jump into an outstanding adventure told through voiceless storytelling, writing your own part. Armed with ancient Teslamancer technology and your own ingenuity and creativity, your path lies through the decrepit Tesla Tower and beyond.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18\\n ],\\n \\\"total_rating\\\": 76.66773507312445,\\n \\\"total_rating_count\\\": 41,\\n \\\"url\\\": \\\"https://www.igdb.com/games/teslagrad\\\"\\n }\\n]\",\n \"igdb_release_date\": 1417564800000,\n \"summary\": \"Teslagrad is a 2D puzzle platformer with action elements, where magnetism and other electromagnetic powers are the key to go throughout the game, and thereby discover the secrets kept in the long abandoned Tesla Tower. Gain new abilities to explore a non-linear world with more than 100 beautiful hand-drawn environments, in a steampunk-inspired vision of old Europe. Jump into an outstanding adventure told through voiceless storytelling, writing your own part. Armed with ancient Teslamancer technology and your own ingenuity and creativity, your path lies through the decrepit Tesla Tower and beyond.\",\n \"web-scraper-order\": \"1244\"\n },\n {\n \"game_buy_date\": \" 12/3/2015\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Shooter Indie\",\n \"game_igdb_id\": 1384,\n \"game_igdb_name\": \"Hotline Miami\",\n \"game_platforms\": \"Linux PC (Microsoft Windows) PlayStation 3 Mac Android PlayStation Network PlayStation Vita PlayStation 4\",\n \"game_rating\": 85.2013970117,\n \"game_rating_count\": 788,\n \"game_size\": \" 828.7 MB \",\n \"game_themes\": \"Action\",\n \"game_title\": \"Hotline Miami\",\n \"games_found\": 2,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 1384,\\n \\\"artworks\\\": [\\n 8863\\n ],\\n \\\"genres\\\": [\\n 5,\\n 32\\n ],\\n \\\"name\\\": \\\"Hotline Miami\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 34,\\n 45,\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 39930,\\n 39931,\\n 39932,\\n 39933,\\n 39934,\\n 39935,\\n 39936,\\n 39937,\\n 39938,\\n 39939,\\n 135461,\\n 135462\\n ],\\n \\\"summary\\\": \\\"A top-down slasher/shooter with unlockable gameplay-altering masks and weapons, featuring a neon-flavoured electronic aesthetic, in which a hitman receives anonymous calls ordering him to travel to certain residences and crime dens and massacre those within, as he stumbles through unreal visions and inconsistencies without any answers to how, why or who.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 85.20139701174546,\\n \\\"total_rating_count\\\": 788,\\n \\\"url\\\": \\\"https://www.igdb.com/games/hotline-miami\\\"\\n },\\n {\\n \\\"id\\\": 2126,\\n \\\"artworks\\\": [\\n 8994\\n ],\\n \\\"genres\\\": [\\n 5,\\n 32\\n ],\\n \\\"name\\\": \\\"Hotline Miami 2: Wrong Number\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 45,\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 27592,\\n 27593,\\n 27594,\\n 29067,\\n 29068,\\n 29069,\\n 103581,\\n 103582,\\n 122484\\n ],\\n \\\"summary\\\": \\\"A sequel, sidequel and prequel to Hotline Miami (2012) with similar unlockables, violent top-down gameplay and \\\\u002780s Miami/modern electronic aesthetics, Hotline Miami 2 follows multiple factions related to the events of the original game as they commit increasingly bloody and surreal acts. A greater emphasis is put on storytelling, and the boundaries between real and fictional violence.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 75.32491666820175,\\n \\\"total_rating_count\\\": 252,\\n \\\"url\\\": \\\"https://www.igdb.com/games/hotline-miami-2-wrong-number\\\"\\n }\\n]\",\n \"igdb_release_date\": 1372204800000,\n \"summary\": \"A top-down slasher/shooter with unlockable gameplay-altering masks and weapons, featuring a neon-flavoured electronic aesthetic, in which a hitman receives anonymous calls ordering him to travel to certain residences and crime dens and massacre those within, as he stumbles through unreal visions and inconsistencies without any answers to how, why or who.\",\n \"web-scraper-order\": \"1248\"\n },\n {\n \"game_buy_date\": \" 6/3/2020\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle\",\n \"game_igdb_id\": 19241,\n \"game_igdb_name\": \"Unravel Two\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 80.6010214846,\n \"game_rating_count\": 67,\n \"game_size\": \" 3.05 GB \",\n \"game_themes\": \"Kids\",\n \"game_title\": \"Unravel\",\n \"games_found\": 3,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 19241,\\n \\\"artworks\\\": [\\n 5074\\n ],\\n \\\"genres\\\": [\\n 8,\\n 9\\n ],\\n \\\"name\\\": \\\"Unravel Two\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 153680,\\n 153681,\\n 153682,\\n 165084\\n ],\\n \\\"summary\\\": \\\"Unravel two is the sequel to the 2015 puzzle platforming game Unravel. It was announced during E3 2018, that the game was actually already finished and available instantly! In the game there are two Yarny\\\\u0027s (made out of yarn) which can be controlled by one player, though the game can also be played in co-op. Together the Yarny\\\\u0027s explore area\\\\u0027s and solve the puzzles within them.\\\",\\n \\\"themes\\\": [\\n 35\\n ],\\n \\\"total_rating\\\": 80.60102148462995,\\n \\\"total_rating_count\\\": 67,\\n \\\"url\\\": \\\"https://www.igdb.com/games/unravel-two\\\"\\n },\\n {\\n \\\"id\\\": 11170,\\n \\\"artworks\\\": [\\n 6313\\n ],\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31\\n ],\\n \\\"name\\\": \\\"Unravel\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49\\n ],\\n \\\"release_dates\\\": [\\n 42383,\\n 42384,\\n 106687,\\n 106688,\\n 134324,\\n 136426\\n ],\\n \\\"summary\\\": \\\"Unravel is a game about Yarny, a tiny character born from a single thread. Yarny embarks on a big adventure into the nature, inspired by the beauty of Northern Scandinavia. Without any spoken words, the character will have to solve puzzles and use tools to overcome tough challenges. All this, in order to find memories of his lost family. \\\\nOnly Yarny can be the bond that ties everything together in the end.\\\",\\n \\\"total_rating\\\": 81.31358716746085,\\n \\\"total_rating_count\\\": 151,\\n \\\"url\\\": \\\"https://www.igdb.com/games/unravel\\\"\\n },\\n {\\n \\\"id\\\": 115025,\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31\\n ],\\n \\\"name\\\": \\\"Unravel: Yarny Bundle\\\",\\n \\\"platforms\\\": [\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 164669,\\n 164670,\\n 164671\\n ],\\n \\\"summary\\\": \\\"Discover the delightful adventures of Unravel and Unravel Two, with the Unravel Yarny Bundle.\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/unravel-yarny-bundle\\\"\\n }\\n]\",\n \"igdb_release_date\": 1528502400000,\n \"summary\": \"Unravel two is the sequel to the 2015 puzzle platforming game Unravel. It was announced during E3 2018, that the game was actually already finished and available instantly! In the game there are two Yarny's (made out of yarn) which can be controlled by one player, though the game can also be played in co-op. Together the Yarny's explore area's and solve the puzzles within them.\",\n \"web-scraper-order\": \"863\"\n },\n {\n \"game_buy_date\": \" 5/6/2019\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Adventure\",\n \"game_igdb_id\": 21062,\n \"game_igdb_name\": \"Sonic Mania\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 84.6740957806,\n \"game_rating_count\": 194,\n \"game_size\": \" 198.57 MB \",\n \"game_themes\": \"Action\",\n \"game_title\": \"Sonic Mania\",\n \"games_found\": 2,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 21062,\\n \\\"artworks\\\": [\\n 1406\\n ],\\n \\\"genres\\\": [\\n 8,\\n 31\\n ],\\n \\\"name\\\": \\\"Sonic Mania\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 90787,\\n 90788,\\n 90791,\\n 90792,\\n 90793,\\n 108909,\\n 134114,\\n 134115,\\n 136302,\\n 143324\\n ],\\n \\\"summary\\\": \\\"It\\\\u0027s the ultimate Sonic celebration! Sonic returns in a new 2D platforming high speed adventure, and he\\\\u0027s not alone! \\\\n \\\\nDeveloped in collaboration between SEGA, Christian Whitehead, Headcannon, and PagodaWest Games, experience new zones and remixed classic levels with Sonic, Tails, and Knuckles!\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 84.6740957805855,\\n \\\"total_rating_count\\\": 194,\\n \\\"url\\\": \\\"https://www.igdb.com/games/sonic-mania\\\"\\n },\\n {\\n \\\"id\\\": 94873,\\n \\\"genres\\\": [\\n 8\\n ],\\n \\\"name\\\": \\\"Sonic Mania Plus\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 155713,\\n 155714,\\n 155715\\n ],\\n \\\"summary\\\": \\\"Sonic Mania Plus is an expanded version of Sonic Mania. \\\\n \\\\nIt\\\\u0027s the ultimate Sonic celebration! Sonic returns in a new 2D platforming high speed adventure, and he\\\\u0027s not alone! \\\\n \\\\nDeveloped in collaboration between SEGA, Christian Whitehead, Headcannon, and PagodaWest Games, experience new zones and remixed classic levels with Sonic, Tails, and Knuckles!\\\",\\n \\\"total_rating\\\": 91.0679826849325,\\n \\\"total_rating_count\\\": 30,\\n \\\"url\\\": \\\"https://www.igdb.com/games/sonic-mania-plus\\\"\\n }\\n]\",\n \"igdb_release_date\": 1502755200000,\n \"summary\": \"It's the ultimate Sonic celebration! Sonic returns in a new 2D platforming high speed adventure, and he's not alone! \\n \\nDeveloped in collaboration between SEGA, Christian Whitehead, Headcannon, and PagodaWest Games, experience new zones and remixed classic levels with Sonic, Tails, and Knuckles!\",\n \"web-scraper-order\": \"896\"\n },\n {\n \"game_buy_date\": \" 8/5/2019\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Puzzle Adventure Indie\",\n \"game_igdb_id\": 11233,\n \"game_igdb_name\": \"What Remains of Edith Finch\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation Network PlayStation 4 Xbox One Nintendo Switch\",\n \"game_rating\": 85.9428890749,\n \"game_rating_count\": 444,\n \"game_size\": \" 2.78 GB \",\n \"game_themes\": \"Drama\",\n \"game_title\": \"What Remains of Edith Finch\",\n \"games_found\": 1,\n \"hltb_main\": 2.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 11233,\\n \\\"genres\\\": [\\n 9,\\n 31,\\n 32\\n ],\\n \\\"name\\\": \\\"What Remains of Edith Finch\\\",\\n \\\"platforms\\\": [\\n 6,\\n 45,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 68356,\\n 68357,\\n 93183,\\n 106850,\\n 106851,\\n 171957\\n ],\\n \\\"summary\\\": \\\"What Remains of Edith Finch is a collection of short stories about a cursed family in Washington State. \\\\n \\\\nEach story offers a chance to experience the life of a different family member with stories ranging from the early 1900s to the present day. The gameplay and tone of the stories are as varied as the family members themselves. The only constants are that each is played from a first-person perspective and that each story ends with that family member\\\\u0027s death. It\\\\u0027s a game about what it feels like to be humbled and astonished by the vast and unknowable world around us. \\\\n \\\\nYou\\\\u0027ll follow Edith Finch as she explores the history of her family and tries to figure out why she\\\\u0027s the last Finch left alive.\\\",\\n \\\"themes\\\": [\\n 31\\n ],\\n \\\"total_rating\\\": 85.94288907494915,\\n \\\"total_rating_count\\\": 444,\\n \\\"url\\\": \\\"https://www.igdb.com/games/what-remains-of-edith-finch\\\"\\n }\\n]\",\n \"igdb_release_date\": 1493078400000,\n \"summary\": \"What Remains of Edith Finch is a collection of short stories about a cursed family in Washington State. \\n \\nEach story offers a chance to experience the life of a different family member with stories ranging from the early 1900s to the present day. The gameplay and tone of the stories are as varied as the family members themselves. The only constants are that each is played from a first-person perspective and that each story ends with that family member's death. It's a game about what it feels like to be humbled and astonished by the vast and unknowable world around us. \\n \\nYou'll follow Edith Finch as she explores the history of her family and tries to figure out why she's the last Finch left alive.\",\n \"web-scraper-order\": \"901\"\n },\n {\n \"game_buy_date\": \" 5/9/2018\",\n \"game_category\": \"Spiel \",\n \"game_flag\": null,\n \"game_genres\": \"Platform Puzzle Adventure\",\n \"game_igdb_id\": 4348,\n \"game_igdb_name\": \"Another World\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 PC DOS Amiga Super Nintendo Entertainment System (SNES) Sega Mega Drive/Genesis Android Nintendo 3DS iOS Wii U PlayStation Network PlayStation Vita PlayStation 4 Xbox One 3DO Interactive Multiplayer Mobile Super Famicom Atari ST/STE Windows Phone Apple IIGS\",\n \"game_rating\": 87.05956629,\n \"game_rating_count\": 114,\n \"game_size\": \" 170.66 MB \",\n \"game_themes\": \"Action Science fiction Survival\",\n \"game_title\": \"Another World\",\n \"games_found\": 6,\n \"hltb_main\": 2.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 4348,\\n \\\"artworks\\\": [\\n 5763\\n ],\\n \\\"genres\\\": [\\n 8,\\n 9,\\n 31\\n ],\\n \\\"name\\\": \\\"Another World\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 13,\\n 16,\\n 19,\\n 29,\\n 34,\\n 37,\\n 39,\\n 41,\\n 45,\\n 46,\\n 48,\\n 49,\\n 50,\\n 55,\\n 58,\\n 63,\\n 74,\\n 115\\n ],\\n \\\"release_dates\\\": [\\n 10074,\\n 25757,\\n 25760,\\n 25761,\\n 25762,\\n 25763,\\n 25764,\\n 25765,\\n 25766,\\n 25767,\\n 25768,\\n 25769,\\n 25770,\\n 25771,\\n 25772,\\n 34982,\\n 39843,\\n 101595,\\n 101596,\\n 218931,\\n 218932,\\n 218933\\n ],\\n \\\"summary\\\": \\\"Another World chronicles the story of a man hurtled through space and time by a nuclear experiment gone wrong. You assume the role of Lester Knight Chaykin, a young physicist. You\\u2019ll need to dodge, outwit, and overcome a host of alien monsters and deadly earthquakes that plague the alien landscape you now call home. Only a perfect blend of logic and skill will get you past the deadly obstacles that lie in waiting.\\\",\\n \\\"themes\\\": [\\n 1,\\n 18,\\n 21\\n ],\\n \\\"total_rating\\\": 87.0595662900337,\\n \\\"total_rating_count\\\": 114,\\n \\\"url\\\": \\\"https://www.igdb.com/games/another-world\\\"\\n },\\n {\\n \\\"id\\\": 16493,\\n \\\"genres\\\": [\\n 31\\n ],\\n \\\"name\\\": \\\"Another World: 20th Anniversary Edition\\\",\\n \\\"platforms\\\": [\\n 3,\\n 6,\\n 9,\\n 14,\\n 37,\\n 41,\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 44468,\\n 44469,\\n 44470,\\n 135842,\\n 137418,\\n 137419,\\n 146082,\\n 146083,\\n 154505,\\n 154506,\\n 159057,\\n 218678\\n ],\\n \\\"summary\\\": \\\"Also known as Out Of This World, Another World is a pioneer action/platformer that released across more than a dozen platforms since its debut in 1991. Along the years, Another World has attained cult status among critics and sophisticated gamers alike.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 68.95924710476291,\\n \\\"total_rating_count\\\": 12,\\n \\\"url\\\": \\\"https://www.igdb.com/games/another-world-20th-anniversary-edition\\\"\\n },\\n {\\n \\\"id\\\": 63656,\\n \\\"genres\\\": [\\n 12,\\n 31\\n ],\\n \\\"name\\\": \\\"Oz no Mahoutsukai - Another World - RungRung\\\",\\n \\\"platforms\\\": [\\n 7,\\n 45\\n ],\\n \\\"release_dates\\\": [\\n 211204,\\n 211205,\\n 211206\\n ],\\n \\\"summary\\\": \\\"A heartwarming adventure RPG based on \\\\\\\"The Wonderful Wizard of Oz\\\\\\\". In the game, Dorothy Gale and Toto must collect magical items in order to get back to Kansas.\\\",\\n \\\"themes\\\": [\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/oz-no-mahoutsukai-another-world-rungrung\\\"\\n },\\n {\\n \\\"id\\\": 26668,\\n \\\"genres\\\": [\\n 31\\n ],\\n \\\"name\\\": \\\"Re:Zero -Starting Life in Another World- Death or Kiss\\\",\\n \\\"platforms\\\": [\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 101254,\\n 101255\\n ],\\n \\\"summary\\\": \\\"Based on a light novel by Nagatsuki Tappei. It follows an original story that differs from the original light novel series and the anime. \\\\n \\\\nIn its original story, the Ruler Election has spun off a beauty contest, giving the winner a treasure that promises the recipient great luck and a powerful advantage to achieving the throne. \\\\nExcept, the prize isn\\\\u0027t what it seems, and, taking on its \\\\\\\"Death Curse\\\\\\\", Subaru must use his power to return from the dead to solve the mystery, build the trusts with the girls, receive the \\\\\\\"kiss of a beautiful girl\\\\\\\" and break the curse to escape death. \\\\n \\\\nCandidates for a relationship with Subaru are Emilia, Rem, Ram, Felt, Beatrice, Crusch, Priscilla and Anastasia.\\\",\\n \\\"themes\\\": [\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/re-zero-starting-life-in-another-world-death-or-kiss\\\"\\n },\\n {\\n \\\"id\\\": 134556,\\n \\\"genres\\\": [\\n 24,\\n 31\\n ],\\n \\\"name\\\": \\\"Re:ZERO -Starting Life in Another World- The Prophecy of the Throne\\\",\\n \\\"platforms\\\": [\\n 6,\\n 48,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 221467,\\n 221468,\\n 221469,\\n 221470,\\n 221471,\\n 221472,\\n 221473\\n ],\\n \\\"summary\\\": \\\"The popular light novel/anime series, Re:ZERO - Starting Life in Another World - is coming as a Tactical Adventure game!\\\",\\n \\\"themes\\\": [\\n 17\\n ],\\n \\\"url\\\": \\\"https://www.igdb.com/games/re-zero-starting-life-in-another-world-the-prophecy-of-the-throne\\\"\\n },\\n {\\n \\\"id\\\": 130804,\\n \\\"name\\\": \\\"Another World/Flashback\\\",\\n \\\"platforms\\\": [\\n 48,\\n 49,\\n 130\\n ],\\n \\\"release_dates\\\": [\\n 222284,\\n 222285,\\n 222286\\n ],\\n \\\"summary\\\": \\\"Rediscover the 90\\u2019s cornerstones of adventure videogames, gathered together for the first time! \\\\nAlso known as Out Of This World\\u2122, Another World is a pioneer action/platformer that released across more than a dozen platforms since its debut in 1991. Along the years, Another World\\u2122 has attained cult status among critics and sophisticated gamers alike. \\\\n \\\\nAnother World\\u2122 chronicles the story of Lester Knight Chaykin a young scientist hurtled through space and time by a nuclear experiment that goes wrong. In an alien and inhospitable world, you will have to dodge, outwit, and overcome the host of alien monsters, while surviving an environment as deadly as your enemies. Only a perfect blend of logic and skill will get you past the deadly obstacles that lie in wait. \\\\n \\\\nKey Features: \\\\n \\\\nRemastered presentation: High Definition graphics faithful to the original design. \\\\n \\\\n3 difficulty modes: Normal (easier than original game), Difficult (Equal to original game) and Hardcore (more difficult than original game) \\\\n \\\\nA new immersive experience: rediscover a cult adventure with 100% remastered sounds and FX \\\\n \\\\nFlashback: 2142. After fleeing from a spaceship but stripped of all memory, the young scientist Conrad B. Hart awakens on Titan, a colonized moon of the planet Saturn. His enemies and kidnappers are snapping at his heels. He must find a way back to Earth, defending himself against the dangers he encounters and unravelling an insidious extra-terrestrial plot that threatens the planet\\u2026 \\\\n \\\\nRediscover this classic, consistently ranked among the best 100 games of all time! It was one of the first games to use motion capture technology for more realistic animations, with backgrounds that were entirely hand-drawn and a gripping science-fiction storyline. \\\\n \\\\nChoose to play with the original graphics and sounds from the 90\\u2019s and face an unforgiving difficulty. \\\\n \\\\nOr go with the Modern mode. You can also tune your experience by turning Modern mode options independently and on the fly. \\\\n \\\\nModern mode: \\\\n- Post-FX graphic filters \\\\n- Completely remastered sound and music \\\\n- A brand new \\\\\\\"Rewind\\\\\\\" function, variable according to the level of difficulty \\\\n- Tutorials for those who need a boost!\\\",\\n \\\"url\\\": \\\"https://www.igdb.com/games/another-world-slash-flashback\\\"\\n }\\n]\",\n \"igdb_release_date\": 1403654400000,\n \"summary\": \"Another World chronicles the story of a man hurtled through space and time by a nuclear experiment gone wrong. You assume the role of Lester Knight Chaykin, a young physicist. You\\u2019ll need to dodge, outwit, and overcome a host of alien monsters and deadly earthquakes that plague the alien landscape you now call home. Only a perfect blend of logic and skill will get you past the deadly obstacles that lie in waiting.\",\n \"web-scraper-order\": \"982\"\n },\n {\n \"game_buy_date\": null,\n \"game_category\": null,\n \"game_flag\": null,\n \"game_genres\": \"Fighting\",\n \"game_igdb_id\": 23354,\n \"game_igdb_name\": \"Injustice: Gods Among Us - Ultimate Edition\",\n \"game_platforms\": \"PC (Microsoft Windows) PlayStation 3 PlayStation Vita PlayStation 4\",\n \"game_rating\": 75.9948753817,\n \"game_rating_count\": 58,\n \"game_size\": null,\n \"game_themes\": \"Action\",\n \"game_title\": \"Injustice Ultimate Edition\",\n \"games_found\": 1,\n \"hltb_main\": 5.0,\n \"igdb_json\": \"[\\n {\\n \\\"id\\\": 23354,\\n \\\"genres\\\": [\\n 4\\n ],\\n \\\"name\\\": \\\"Injustice: Gods Among Us - Ultimate Edition\\\",\\n \\\"platforms\\\": [\\n 6,\\n 9,\\n 46,\\n 48\\n ],\\n \\\"release_dates\\\": [\\n 61458,\\n 103677,\\n 103678,\\n 133777,\\n 133778,\\n 134998,\\n 134999,\\n 179452,\\n 179458\\n ],\\n \\\"summary\\\": \\\"Injustice: Gods Among Us Ultimate Edition enhances the bold new franchise to the fighting game genre from NetherRealm Studios. Featuring six new playable characters, over 30 new skins, and 60 new S.T.A.R. Labs missions, this edition packs a punch. In addition to DC Comics icons such as Batman, The Joker, Green Lantern, The Flash, Superman and Wonder Woman, the latest title from the award-winning studio presents a deep original story. Heroes and villains will engage in epic battles on a massive scale in a world where the line between good and evil has been blurred.\\\",\\n \\\"themes\\\": [\\n 1\\n ],\\n \\\"total_rating\\\": 75.99487538172156,\\n \\\"total_rating_count\\\": 58,\\n \\\"url\\\": \\\"https://www.igdb.com/games/injustice-gods-among-us-ultimate-edition\\\"\\n }\\n]\",\n \"igdb_release_date\": 1385683200000,\n \"summary\": \"Injustice: Gods Among Us Ultimate Edition enhances the bold new franchise to the fighting game genre from NetherRealm Studios. Featuring six new playable characters, over 30 new skins, and 60 new S.T.A.R. Labs missions, this edition packs a punch. In addition to DC Comics icons such as Batman, The Joker, Green Lantern, The Flash, Superman and Wonder Woman, the latest title from the award-winning studio presents a deep original story. Heroes and villains will engage in epic battles on a massive scale in a world where the line between good and evil has been blurred.\",\n \"web-scraper-order\": null\n }\n]\nNone\n"
]
],
[
[
"Summarising the result gives a better overview. We are working with lists of dictionaries a return valies of the search functions in TinyDB.",
"_____no_output_____"
]
],
[
[
"result_sorted = sorted(query_result, key=lambda x: x[\"game_rating\"], reverse=True)\n\nfor item in result_sorted:\n print(item[\"game_title\"], \" / \", item[\"game_igdb_name\"], \": \", round(item[\"game_rating\"], 2), \" / \", item[\"game_rating_count\"])",
"INSIDE / INSIDE : 89.76 / 866\nAnother World / Another World : 87.06 / 114\nWhat Remains of Edith Finch / What Remains of Edith Finch : 85.94 / 444\nSuper Time Force Ultra / Super Time Force Ultra : 85.25 / 23\nHotline Miami / Hotline Miami : 85.2 / 788\nSonic Mania / Sonic Mania : 84.67 / 194\nThe Swapper / The Swapper : 83.51 / 133\nLIMBO / Limbo : 82.83 / 879\nDay of the Tentacle Remastered / Day of the Tentacle Remastered : 81.1 / 75\nUnravel / Unravel Two : 80.6 / 67\nSound Shapes / Sound Shapes : 80.51 / 40\nFirewatch / Firewatch : 79.66 / 618\nGone Home / Gone Home : 79.61 / 362\nFuri / Furi : 79.04 / 142\nLovers in a Dangerous Spacetime / Lovers in a Dangerous Spacetime : 78.83 / 48\nOlliOlli2: Welcome to Olliwood / OlliOlli2: Welcome to Olliwood : 78.39 / 33\nThe Unfinished Swan / The Unfinished Swan : 78.08 / 62\nMETAL GEAR SOLID V: GROUND ZEROES / Metal Gear Solid V: Ground Zeroes : 77.49 / 336\nTeslagrad / Teslagrad : 76.67 / 41\nLittleBigPlanet 3 / LittleBigPlanet 3 : 76.63 / 76\nInjustice Ultimate Edition / Injustice: Gods Among Us - Ultimate Edition : 75.99 / 58\nThe Deadly Tower of Monsters / The Deadly Tower of Monsters : 75.82 / 39\nEverybody's Gone To The Rapture™ / Everybody's Gone to the Rapture : 75.75 / 133\n"
]
],
[
[
"## Alternative Databases\n\nShortly tried playing around with SQL Alchemy and an SQLite database. As the base structures returned by IGDB are all JSONs substantial cleaning up would be necessary to create a proper SQL database. I stuck with TinyDB as database in the backend.\n\nAnother thing to consider would be just a plain JSON object being queried with eg JMESPath. Like TinyDB this would not be production ready, but the querying capabilities would potentially more powerful. Also it would involve porting the code to a real database as JMESPath to my knowledge is not directly supported by any document database.\n",
"_____no_output_____"
]
],
[
[
"engine = db.create_engine('sqlite://', echo=False)",
"_____no_output_____"
],
[
"df_tmp.to_sql('games', con=engine)\nengine.execute(\"SELECT * FROM games\").fetchall()\n",
"_____no_output_____"
],
[
"metadata = db.MetaData()\n\ngames_table = db.Table('games', metadata, autoload=True, autoload_with=engine)\n\nprint(metadata.tables)\nprint(games_table.columns)\nprint(games_table.metadata)\n",
"immutabledict({'games': Table('games', MetaData(bind=None), Column('index', BIGINT(), table=<games>), Column('web-scraper-order', TEXT(), table=<games>), Column('game_title', TEXT(), table=<games>), Column('game_platforms', TEXT(), table=<games>), Column('game_flag', FLOAT(), table=<games>), Column('game_category', TEXT(), table=<games>), Column('game_size', TEXT(), table=<games>), Column('game_buy_date', TEXT(), table=<games>), Column('games_found', BIGINT(), table=<games>), Column('igdb_json', TEXT(), table=<games>), Column('game_rating', FLOAT(), table=<games>), Column('game_rating_count', BIGINT(), table=<games>), Column('game_genres', TEXT(), table=<games>), Column('game_themes', TEXT(), table=<games>), Column('game_igdb_id', BIGINT(), table=<games>), Column('game_igdb_name', TEXT(), table=<games>), Column('summary', TEXT(), table=<games>), Column('igdb_cover_url', TEXT(), table=<games>), Column('igdb_release_date', DATETIME(), table=<games>), Column('hltb_main', FLOAT(), table=<games>), schema=None)})\n['games.index', 'games.web-scraper-order', 'games.game_title', 'games.game_platforms', 'games.game_flag', 'games.game_category', 'games.game_size', 'games.game_buy_date', 'games.games_found', 'games.igdb_json', 'games.game_rating', 'games.game_rating_count', 'games.game_genres', 'games.game_themes', 'games.game_igdb_id', 'games.game_igdb_name', 'games.summary', 'games.igdb_cover_url', 'games.igdb_release_date', 'games.hltb_main']\nMetaData(bind=None)\n"
]
]
] | [
"code",
"markdown",
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb0602c7b657e11b181b27cb66e2e29e6a17db0e | 264,116 | ipynb | Jupyter Notebook | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter | 09cfc208bbaa811a92285c2fe41e6abd9a8398b8 | [
"BSD-3-Clause"
] | null | null | null | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter | 09cfc208bbaa811a92285c2fe41e6abd9a8398b8 | [
"BSD-3-Clause"
] | null | null | null | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter | 09cfc208bbaa811a92285c2fe41e6abd9a8398b8 | [
"BSD-3-Clause"
] | null | null | null | 53.649401 | 30,984 | 0.605208 | [
[
[
"# IPython: beyond plain Python\n\nAdapted from the ICESat2 Hackweek [intro-jupyter-git](https://github.com/ICESAT-2HackWeek/intro-jupyter-git) session. Courtesy of [@fperez](https://github.com/fperez).\n\nWhen executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.",
"_____no_output_____"
],
[
"## First things first: running code, getting help\n\nIn the notebook, to run a cell of code, hit `Shift-Enter`. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use:\n \n- `Alt-Enter` to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).\n- `Control-Enter` executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.",
"_____no_output_____"
]
],
[
[
"print(\"Hi\")",
"Hi\n"
]
],
[
[
"Getting help:",
"_____no_output_____"
]
],
[
[
"?",
"_____no_output_____"
]
],
[
[
"Typing `object_name?` will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nnp.linspace?",
"_____no_output_____"
],
[
"np.isclose??",
"_____no_output_____"
],
[
"*int*?",
"_____no_output_____"
]
],
[
[
"An IPython quick reference card:",
"_____no_output_____"
]
],
[
[
"%quickref",
"_____no_output_____"
]
],
[
[
"## Tab completion\n\nTab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type `object_name.<TAB>` to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.",
"_____no_output_____"
]
],
[
[
"np.",
"_____no_output_____"
]
],
[
[
"## The interactive workflow: input, output, history",
"_____no_output_____"
]
],
[
[
"2+10",
"_____no_output_____"
],
[
"_+10",
"_____no_output_____"
]
],
[
[
"You can suppress the storage and rendering of output if you append `;` to the last cell (this comes in handy when plotting with matplotlib, for example):",
"_____no_output_____"
]
],
[
[
"10+20;",
"_____no_output_____"
],
[
"_",
"_____no_output_____"
]
],
[
[
"The output is stored in `_N` and `Out[N]` variables:",
"_____no_output_____"
]
],
[
[
"_11 == Out[11]",
"_____no_output_____"
]
],
[
[
"Previous inputs are available, too:",
"_____no_output_____"
]
],
[
[
"In[11]",
"_____no_output_____"
],
[
"_i",
"_____no_output_____"
],
[
"%history -n 1-5",
" 1: print(\"Hi\")\n 2: ?\n 3: import numpy as np\n 4:\nimport numpy as np\nnp.linspace?\n 5: np.isclose??\n"
]
],
[
[
"**Exercise**\n\nUse `%history?` to have a look at `%history`'s magic documentation, and write the last 10 lines of history to a file named `log.py`.",
"_____no_output_____"
],
[
"## Accessing the underlying operating system\n",
"_____no_output_____"
]
],
[
[
"!pwd",
"/Users/lindseyjh/git/scipy-la/scipyla-jupyter\n"
],
[
"files = !ls \nprint(\"files this directory:\")\nprint(files)",
"files this directory:\n['01-Intro Jupyter.ipynb', '02-Beyond Plain Python.ipynb', '03-Rich Output.ipynb', '04-widgets-introduction.ipynb', '05-widgets-interact.ipynb', '06-widget_basics.ipynb', 'README.md', 'Rich Output Exercises - Custom Display Logic .ipynb', 'a-01-Git-Tutorial.ipynb', 'a-02-widgets-moreinto.ipynb', 'binder-overview.pdf', 'environment.yml', 'images', 'index.ipynb', 'jupyter-intro-lab.pdf']\n"
],
[
"files",
"_____no_output_____"
],
[
"!echo $files",
"[01-Intro Jupyter.ipynb, 02-Beyond Plain Python.ipynb, 03-Rich Output.ipynb, 04-widgets-introduction.ipynb, 05-widgets-interact.ipynb, 06-widget_basics.ipynb, README.md, Rich Output Exercises - Custom Display Logic .ipynb, a-01-Git-Tutorial.ipynb, a-02-widgets-moreinto.ipynb, binder-overview.pdf, environment.yml, images, index.ipynb, jupyter-intro-lab.pdf]\n"
],
[
"!echo {files[0].upper()}",
"01-INTRO JUPYTER.IPYNB\n"
]
],
[
[
"Note that all this is available even in multiline blocks:",
"_____no_output_____"
]
],
[
[
"import os\nfor i,f in enumerate(files):\n if f.endswith('ipynb'):\n !echo {\"%02d\" % i} - \"{os.path.splitext(f)[0]}\"\n else:\n print('--')",
"00 - 01-Intro Jupyter\n01 - 02-Beyond Plain Python\n02 - 03-Rich Output\n03 - 04-widgets-introduction\n04 - 05-widgets-interact\n05 - 06-widget_basics\n--\n07 - Rich Output Exercises - Custom Display Logic \n08 - a-01-Git-Tutorial\n09 - a-02-widgets-moreinto\n--\n--\n--\n13 - index\n--\n"
]
],
[
[
"## Beyond Python: magic functions\n\nThe IPyhton 'magic' functions are a set of commands, invoked by prepending one or two `%` signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with `--` and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:\n \n- To provide an namespace for controlling IPython itself and exposing other system-oriented functionality that is separate from your Python variables and functions. This lets you have a `cd` command accessible as a magic regardless of whether you have a Python `cd` variable.\n\n- To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.",
"_____no_output_____"
]
],
[
[
"%magic",
"_____no_output_____"
]
],
[
[
"Line vs cell magics:\n\nMagics can be applied at the single-line level or to entire cells. Line magics are identified with a single `%` prefix, while cell magics use `%%` and can only be used as the first line of the cell (since they apply to the entire cell). Some magics, like the convenient `%timeit` that ships built-in with IPython, can be called in either mode, while others may be line- or cell-only (you can see all magics with `%lsmagic`).\n\nLet's see this with some `%timeit` examples:",
"_____no_output_____"
]
],
[
[
"%timeit list(range(1000))",
"15 µs ± 276 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
],
[
"%%timeit\n# comment here\n\nlist(range(10))\nlist(range(100))",
"1.63 µs ± 175 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
]
],
[
[
"Line magics can be used even inside code blocks:",
"_____no_output_____"
]
],
[
[
"for i in range(1, 5):\n size = i*100\n print('size:', size, end=' ')\n %timeit list(range(size))",
"size: 100 1.09 µs ± 37.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\nsize: 200 1.61 µs ± 10.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\nsize: 300 2.78 µs ± 13.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\nsize: 400 4.88 µs ± 267 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
]
],
[
[
"Magics can do anything they want with their input, so it doesn't have to be valid Python (note that the below may not work on a Windows machine, depending on how you are running Jupyter on it):",
"_____no_output_____"
]
],
[
[
"%%bash\necho \"My shell is:\" $SHELL\necho \"My disk usage is:\"\ndf -h",
"My shell is: /bin/zsh\nMy disk usage is:\nFilesystem Size Used Avail Capacity iused ifree %iused Mounted on\n/dev/disk1s1 466Gi 439Gi 16Gi 97% 4374206 9223372036850401601 0% /\ndevfs 194Ki 194Ki 0Bi 100% 670 0 100% /dev\n/dev/disk1s4 466Gi 10Gi 16Gi 40% 10 9223372036854775797 0% /private/var/vm\nmap -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net\nmap auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home\n"
]
],
[
[
"Another interesting cell magic: create any file you want locally from the notebook:",
"_____no_output_____"
]
],
[
[
"%%writefile test.txt\nThis is a test file!\nIt can contain anything I want...\n\nAnd more...\n\n",
"Writing test.txt\n"
],
[
"!cat test.txt",
"This is a test file!\nIt can contain anything I want...\n\nAnd more...\n"
]
],
[
[
"Let's see what other magics are currently defined in the system:",
"_____no_output_____"
]
],
[
[
"%lsmagic",
"_____no_output_____"
],
[
"def to_optimize(N):\n total = [0,0]\n ta = 0\n tb = 0\n for i in range(N):\n for j in range(N):\n a = i**2\n b = j*2\n total[0] += a\n total[1] += b\n return total",
"_____no_output_____"
],
[
"%timeit to_optimize(1_000)",
"_____no_output_____"
],
[
"%prun to_optimize(1_000)",
"_____no_output_____"
]
],
[
[
"## Running normal Python code: execution and errors\n\nNot only can you input normal Python code, you can even paste straight from a Python or IPython shell session:",
"_____no_output_____"
]
],
[
[
">>> # Fibonacci series:\n... # the sum of two elements defines the next\n... a, b = 0, 1\n>>> while b < 10:\n... print(b)\n... a, b = b, a+b",
"1\n1\n2\n3\n5\n8\n"
],
[
"In [1]: for i in range(10):\n ...: print(i, end=' ')\n ...: ",
"0 1 2 3 4 5 6 7 8 9 "
]
],
[
[
"And when your code produces errors, you can control how they are displayed with the `%xmode` magic:",
"_____no_output_____"
]
],
[
[
"%%writefile mod.py\n\ndef f(x):\n return 1.0/(x-1)\n\ndef g(y):\n return f(y+1)",
"Writing mod.py\n"
]
],
[
[
"Now let's call the function `g` with an argument that would produce an error:",
"_____no_output_____"
]
],
[
[
"import mod\nmod.g(0)",
"_____no_output_____"
]
],
[
[
"## Basic debugging\n\nWhen running code interactively, it can be tricky to figure out how to debug... ",
"_____no_output_____"
]
],
[
[
"%debug",
"> \u001b[0;32m/Users/lindseyjh/git/scipy-la/scipyla-jupyter/mod.py\u001b[0m(3)\u001b[0;36mf\u001b[0;34m()\u001b[0m\n\u001b[0;32m 1 \u001b[0;31m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m----> 3 \u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;36m1.0\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4 \u001b[0;31m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5 \u001b[0;31m\u001b[0;32mdef\u001b[0m \u001b[0mg\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\n"
],
[
"enjoy = input('Are you enjoying this tutorial? ')\nprint('enjoy is:', enjoy)",
"Are you enjoying this tutorial? :) \n"
]
],
[
[
"## Running code in other languages with special `%%` magics",
"_____no_output_____"
]
],
[
[
"%%perl\n@months = (\"July\", \"August\", \"September\");\nprint $months[0];",
"July"
]
],
[
[
"## Plotting in the notebook",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"x = np.linspace(0, 2*np.pi, 300)\ny = np.sin(x**2)\nplt.plot(x, y)\nplt.title(\"A little chirp\")",
"_____no_output_____"
]
],
[
[
"---\n\n## A quick tour of widgets\n\nThis is meant to provide a quick overview of some of the things you can do with Jupyter widgets. For more ideas, you can check out [the docs](https://ipywidgets.readthedocs.io/en/latest/), and the notebooks from the [ICESat2 Hackweek](https://github.com/ICESAT-2HackWeek/intro-jupyter-git)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport ipywidgets\n\n%matplotlib inline",
"_____no_output_____"
],
[
"def sin_x(x, frequency=1, phase=0):\n return np.sin(\n 2*np.pi*frequency*x + phase\n )",
"_____no_output_____"
],
[
"def plot_sin_x(frequency=1, phase=0, title=\"a\"):\n x = np.linspace(-1, 1, 200)\n plt.plot(x, sin_x(x, frequency, phase))\n plt.title(title)",
"_____no_output_____"
],
[
"plot_sin_x()",
"_____no_output_____"
]
],
[
[
"### using interactive",
"_____no_output_____"
]
],
[
[
"widget = ipywidgets.interactive(plot_sin_x, frequency=1.5, phase=0.)\nwidget",
"_____no_output_____"
]
],
[
[
"### specifying the widgets",
"_____no_output_____"
]
],
[
[
"mywidget = ipywidgets.interactive(\n plot_sin_x,\n frequency = ipywidgets.FloatSlider(min=0, max=10, value=1, display=\"f\"),\n# phase = ipywidgets.FloatSlider(min=-np.pi, max=np.pi, value=0)\n phase = ipywidgets.FloatText(value=0),\n title = ipywidgets.ToggleButtons(options=[\"a\", \"b\"])\n)\nmywidget",
"_____no_output_____"
],
[
"mywidget.children[1].value",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb0604f8d08772347e0ddaf907e1047c8cf4df61 | 16,052 | ipynb | Jupyter Notebook | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com | b69f333d5b2d36338185a0c49b62ecb337a879de | [
"MIT"
] | null | null | null | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com | b69f333d5b2d36338185a0c49b62ecb337a879de | [
"MIT"
] | null | null | null | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com | b69f333d5b2d36338185a0c49b62ecb337a879de | [
"MIT"
] | null | null | null | 26.753333 | 173 | 0.399826 | [
[
[
"## API Package: usda_com \n\nThis notebook provides a simple use case for the USDA Commodity Database. The package can be downloaded via github using the following code. \n",
"_____no_output_____"
]
],
[
[
"import pandas as pd ",
"_____no_output_____"
],
[
"data = pd.read_csv('../usda_com/data/commodities.csv')",
"_____no_output_____"
],
[
"data = data.iloc[:, 1:]",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data.to_csv('../usda_com/data/commodities.csv', index=False)",
"_____no_output_____"
],
[
"! pip install git+https://github.com/LightnerAndrew/usda_com --quiet",
"_____no_output_____"
],
[
"import os\nos.chdir('..')",
"_____no_output_____"
],
[
"import usda_com\n\n# create the query object. \nqry = usda_com.query()",
"_____no_output_____"
]
],
[
[
"#### API Key \n\nThe first step in building and using the API is to create an account and generate an API key. https://apps.fas.usda.gov/psdonline/app/index.html#/app/about\n\n1. Create an account: \n2. Generate an API Key ",
"_____no_output_____"
]
],
[
[
"qry.api_key = 'D892ADB8-DBC1-4AF5-BCFF-BA338AAE2B6E'",
"_____no_output_____"
]
],
[
[
"### Explore commodity options\n\nThe `commodity_options` attribute holds commodity code information. ",
"_____no_output_____"
]
],
[
[
"qry.commodity_options.head()",
"_____no_output_____"
]
],
[
[
"Although you could query the datafrmae using pandas, there is also a convenient `find_commodity_code()` method to search the Commodity names for those of interest. \n\nFor this example, we will access data for fresh apples. ",
"_____no_output_____"
]
],
[
[
"qry.find_commodity_code('Apples')",
"_____no_output_____"
],
[
"qry.com_selection = ['574000']",
"_____no_output_____"
]
],
[
[
"### Year selection \n\nThe USDA records data from 1960 until the most recent data (2018 at the time of creating this notebook). \n\nThe year_selection attribute takes a string in two different formats. \n1. `{year0},{year1},..` will select only the years specified. \n2. `{year0}:{year1}` will return all years within a given range. ",
"_____no_output_____"
]
],
[
[
"qry.year_selection = '1990,2000'",
"_____no_output_____"
]
],
[
[
"### Access Data!",
"_____no_output_____"
]
],
[
[
"raw_data = qry.run()",
"_____no_output_____"
],
[
"raw_data.head()",
"_____no_output_____"
],
[
"raw_data.columns",
"_____no_output_____"
],
[
"raw_data.MarketYear.unique()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb0606e09b88028569b758f0fc2edfbe03d7193e | 47,681 | ipynb | Jupyter Notebook | ProjetTripAdvisor_Final.ipynb | a-essa/Sentiment-Analysis-and-Satisfaction-Prediction | 2f63db26b23819db4850a3995d668282c0ee2452 | [
"MIT"
] | null | null | null | ProjetTripAdvisor_Final.ipynb | a-essa/Sentiment-Analysis-and-Satisfaction-Prediction | 2f63db26b23819db4850a3995d668282c0ee2452 | [
"MIT"
] | null | null | null | ProjetTripAdvisor_Final.ipynb | a-essa/Sentiment-Analysis-and-Satisfaction-Prediction | 2f63db26b23819db4850a3995d668282c0ee2452 | [
"MIT"
] | null | null | null | 30.101641 | 275 | 0.486064 | [
[
[
"<a href=\"https://colab.research.google.com/github/a-essa/Sentiment-Analysis-and-Satisfaction-Prediction/blob/master/ProjetTripAdvisor_Final.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Projet",
"_____no_output_____"
]
],
[
[
"%tensorflow_version 2.x\nimport tensorflow as tf\nprint(tf.__version__)",
"TensorFlow 2.x selected.\n2.0.0\n"
],
[
"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom google.colab import files\nimport numpy as np\nimport tensorflow_datasets as tfds\nimport tensorflow as tf\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport io\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport keras.preprocessing.text\nimport tensorflow.keras.backend as K\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix as cm\nfrom sklearn.metrics import multilabel_confusion_matrix as mcm\nimport tensorflow_hub as hub\ntf.keras.backend.clear_session()\nnp.set_printoptions(precision=3, suppress=True)\npd.options.display.max_colwidth = 1000\nfrom keras.regularizers import l2",
"Using TensorFlow backend.\n"
],
[
"print(tf.__version__)",
"2.0.0\n"
],
[
"from google.colab import drive \ndrive.mount('/content/gdrive')",
"_____no_output_____"
]
],
[
[
"# Read CSV",
"_____no_output_____"
]
],
[
[
"Total_data_for_tokenizer=pd.read_csv('/content/gdrive/My Drive/Data/Total_data_for_tokenizer.csv' , sep='\\t')",
"_____no_output_____"
],
[
"training_set_TripAdvisor=pd.read_csv('/content/gdrive/My Drive/Data/training_set_TripAdvisor.csv' , sep='\\t')",
"_____no_output_____"
],
[
"test_set_TripAdvisor=pd.read_csv('/content/gdrive/My Drive/Data/test_set_TripAdvisor.csv' , sep='\\t')",
"_____no_output_____"
],
[
"training_set_IMDB=pd.read_csv('/content/gdrive/My Drive/Data/training_set_IMDB.csv' , sep='\\t')",
"_____no_output_____"
],
[
"test_set_IMDB=pd.read_csv('/content/gdrive/My Drive/Data/test_set_IMDB.csv' , sep='\\t')",
"_____no_output_____"
],
[
"del Total_data_for_tokenizer['Unnamed: 0']\ndel training_set_TripAdvisor['Unnamed: 0']\ndel test_set_TripAdvisor['Unnamed: 0']\ndel training_set_IMDB['Unnamed: 0']\ndel test_set_IMDB['Unnamed: 0']",
"_____no_output_____"
]
],
[
[
"# Tokenizer",
"_____no_output_____"
]
],
[
[
"def create_dataset(dataframe):\n msk = np.random.rand(len(dataframe)) < 0.8\n\n train = dataframe[msk]\n\n test = dataframe[~msk]\n #print(train_file_path.head)\n all_data = np.array(dataframe.values.tolist())\n training_set = np.array(train.values.tolist())\n test_set=np.array(test.values.tolist())\n print(\"Dataset Length: \",len(training_set)+ len(test_set))\n return all_data, training_set, test_set",
"_____no_output_____"
],
[
"def create_tokenizer(dataset):\n tokenizer = Tokenizer(filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n', lower=True, split=' ', char_level=False, oov_token='UNK')\n # fit the tokenizer on the documents\n tokenizer.fit_on_texts(dataset[:,1])\n # summarize what was learned\n print(\"Word counter: \",tokenizer.word_counts)\n print(\"Number of sentences: \",tokenizer.document_count)\n print(\"Word Index: \", tokenizer.word_index)\n print(\"Word Docs: \",tokenizer.word_docs)\n return tokenizer",
"_____no_output_____"
],
[
"def vocab_size(tokenizer):\n voca_size=len(tokenizer.word_counts)+2 # 1 ?\n return voca_size",
"_____no_output_____"
],
[
"def maxlen(data):\n return max([len(x) for x in data])",
"_____no_output_____"
],
[
"Total_data_for_tokenizer_np = np.array(Total_data_for_tokenizer.values.tolist())",
"_____no_output_____"
],
[
"tokenizer=create_tokenizer(Total_data_for_tokenizer_np)",
"IOPub data rate exceeded.\nThe notebook server will temporarily stop sending output\nto the client in order to avoid crashing it.\nTo change this limit, set the config variable\n`--NotebookApp.iopub_data_rate_limit`.\n\nCurrent values:\nNotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)\nNotebookApp.rate_limit_window=3.0 (secs)\n\n"
],
[
"def tokenize_sentences(input_set):\n input_sequences = []\n for line in input_set[:,1]:\n token_list = tokenizer.texts_to_sequences([line])[0]\n input_sequences.append(token_list)\n return input_sequences",
"_____no_output_____"
],
[
"training_set_IMDB_np = np.array(training_set_IMDB.values.tolist())\ntest_set_IMDB_np = np.array(test_set_IMDB.values.tolist())\ntraining_set_TripAdvisor_np = np.array(training_set_TripAdvisor.values.tolist())\ntest_set_TripAdvisor_np = np.array(test_set_TripAdvisor.values.tolist())",
"_____no_output_____"
],
[
"input_training_set_IMDB = tokenize_sentences(training_set_IMDB_np)\ninput_test_set_IMDB = tokenize_sentences(test_set_IMDB_np)\ninput_training_set_TripAdvisor = tokenize_sentences(training_set_TripAdvisor_np)\ninput_test_set_TripAdvisor = tokenize_sentences(test_set_TripAdvisor_np)",
"_____no_output_____"
],
[
"def pad_sentences(input_sequences, max_sequence_len):\n input_padded_sequences = np.array(pad_sequences(input_sequences, \n maxlen=max_sequence_len, padding='pre'))\n return input_padded_sequences",
"_____no_output_____"
],
[
"def pad_sentences_post(input_sequences, max_sequence_len):\n input_padded_sequences = np.array(pad_sequences(input_sequences, \n maxlen=max_sequence_len, padding='post'))\n return input_padded_sequences",
"_____no_output_____"
],
[
"def maxlen(data1, data2 , data3 , data4):\n max_len_data1 = max([len(x) for x in data1])\n max_len_data2 = max([len(x) for x in data2])\n max_len_data3 = max([len(x) for x in data3])\n max_len_data4 = max([len(x) for x in data4])\n return max(max_len_data1, max_len_data2 , max_len_data3 , max_len_data4)",
"_____no_output_____"
],
[
"max_len = maxlen(input_training_set_IMDB, input_test_set_IMDB, input_training_set_TripAdvisor, input_test_set_TripAdvisor)",
"_____no_output_____"
]
],
[
[
"#Embeddings pretraining (Next Word Prediction)\n",
"_____no_output_____"
]
],
[
[
"def split_sentences_forward(input_set):\n input_sequences = []\n for line in input_set:\n for i in range(1, len(line)):\n if i < 99 :\n n_gram_sequence = line[:i+1]\n else :\n n_gram_sequence = line[i-99:i+1]\n input_sequences.append(n_gram_sequence)\n return input_sequences",
"_____no_output_____"
],
[
"def split_sentences_Backward(input_set):\n input_sequences = []\n for line in input_set[:,1]:\n token_list = tokenizer.texts_to_sequences([line])[0]\n for i in range(1, len(token_list)):\n if i < 99 :\n n_gram_sequence = token_list[:i+1]\n else :\n n_gram_sequence = token_list[i-99:i+1]\n input_sequences.append(n_gram_sequence)\n return input_sequences",
"_____no_output_____"
],
[
"def create_dataset_slices_embaddings(input_sequences):\n predictors, label = input_sequences[:,:-1],input_sequences[:,-1]\n #label = tf.keras.utils.to_categorical(label, num_classes=voc_size)\n return predictors, label",
"_____no_output_____"
],
[
"def create_preprocessed_dataset(predictors, labels):\n dataset = tf.data.Dataset.from_tensor_slices((predictors, labels))\n return dataset",
"_____no_output_____"
],
[
"def top_k_categorical_accuracy1(y_true, y_pred, k=10):\n return K.mean(K.in_top_k(K.cast(y_pred,dtype='float32'),K.argmax(y_true, axis=-1), k), axis=-1)",
"_____no_output_____"
],
[
"input_train_WE_1=split_sentences_forward(input_training_set_IMDB)",
"_____no_output_____"
],
[
"input_train_WE_2=split_sentences_forward(input_training_set_TripAdvisor)",
"_____no_output_____"
],
[
"input_test_WE_1=split_sentences_forward(input_test_set_IMDB[5000:])",
"_____no_output_____"
],
[
"input_test_WE_2=split_sentences_forward(input_test_set_TripAdvisor)",
"_____no_output_____"
],
[
"input_train_WE_sequences_1 = pad_sentences(input_train_WE_1, 100)\ninput_train_WE_sequences_2 = pad_sentences(input_train_WE_2, 100)\ninput_test_WE_sequences_1 = pad_sentences(input_test_WE_1, 100)\ninput_test_WE_sequences_2 = pad_sentences(input_test_WE_2, 100)",
"_____no_output_____"
],
[
"training_predictors_WE, training_label_WE=create_dataset_slices_embaddings(input_train_WE_sequences_1)\ntest_predictors_WE, test_label_WE= create_dataset_slices_embaddings(input_test_WE_sequences_1)",
"_____no_output_____"
],
[
"training_predictors_WE_2, training_label_WE_2=create_dataset_slices_embaddings(input_train_WE_sequences_2)\ntest_predictors_WE_2, test_label_WE_2= create_dataset_slices_embaddings(input_test_WE_sequences_2)",
"_____no_output_____"
],
[
"voc_size = vocab_size(tokenizer)",
"_____no_output_____"
],
[
"EmbeddingLayer = tf.keras.layers.Embedding(voc_size, 64)\nLstmLayer = tf.keras.layers.LSTM(150)\nDenseLayerEmbedding = tf.keras.layers.Dense(64, activation='relu')\nDropLayerEmbedding = tf.keras.layers.Dropout(0.1)\nDenseLayerOutputEmbedding = tf.keras.layers.Dense(voc_size, activation='softmax')",
"_____no_output_____"
],
[
"model = tf.keras.Sequential()\nmodel.add(EmbeddingLayer)\nmodel.add(LstmLayer)\nmodel.add(DenseLayerEmbedding)\nmodel.add(DropLayerEmbedding)\nmodel.add(DenseLayerOutputEmbedding)\n\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding (Embedding) (None, None, 64) 5120512 \n_________________________________________________________________\nlstm (LSTM) (None, 150) 129000 \n_________________________________________________________________\ndense (Dense) (None, 64) 9664 \n_________________________________________________________________\ndropout (Dropout) (None, 64) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 80008) 5200520 \n=================================================================\nTotal params: 10,459,696\nTrainable params: 10,459,696\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(loss='sparse_categorical_crossentropy',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=[\"accuracy\"])",
"_____no_output_____"
],
[
"checkpoint_path = \"training_Embadding/cp-{epoch:04d}.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\n\n# Create a callback that saves the model's weights every epochs\ncp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_path, \n verbose=1, \n save_weights_only=True)",
"_____no_output_____"
],
[
"history = model.fit(training_predictors_WE, \n training_label_WE,\n epochs=2,\n batch_size=100,\n validation_data=(test_predictors_WE, test_label_WE),\n verbose=1,\n callbacks=[cp_callback])",
"Train on 3616784 samples, validate on 2831359 samples\nEpoch 1/2\n3616700/3616784 [============================>.] - ETA: 0s - loss: 7.6951 - accuracy: 0.0596\nEpoch 00001: saving model to training_Embadding/cp-0001.ckpt\n3616784/3616784 [==============================] - 2552s 706us/sample - loss: 7.6951 - accuracy: 0.0596 - val_loss: 7.5867 - val_accuracy: 0.0709\nEpoch 2/2\n2262000/3616784 [=================>............] - ETA: 12:57 - loss: 7.4362 - accuracy: 0.0723Buffered data was truncated after reaching the output size limit."
],
[
"history = model.fit(training_predictors_WE_2, \n training_label_WE_2,\n epochs=2,\n batch_size=100,\n validation_data=(test_predictors_WE_2, test_label_WE_2),\n verbose=1,\n callbacks=[cp_callback])",
"Train on 947983 samples, validate on 237895 samples\nEpoch 1/2\n947900/947983 [============================>.] - ETA: 0s - loss: 5.7982 - accuracy: 0.1446\nEpoch 00001: saving model to training_Embadding/cp-0001.ckpt\n947983/947983 [==============================] - 547s 577us/sample - loss: 5.7982 - accuracy: 0.1446 - val_loss: 5.1032 - val_accuracy: 0.1927\nEpoch 2/2\n947900/947983 [============================>.] - ETA: 0s - loss: 4.9881 - accuracy: 0.1962\nEpoch 00002: saving model to training_Embadding/cp-0002.ckpt\n947983/947983 [==============================] - 528s 557us/sample - loss: 4.9881 - accuracy: 0.1962 - val_loss: 4.7930 - val_accuracy: 0.2161\n"
]
],
[
[
"#Dataset slices",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals",
"_____no_output_____"
],
[
"input_train_CL_sequences_1 = pad_sentences_post(input_training_set_IMDB, max_len)\ninput_train_CL_sequences_2 = pad_sentences_post(input_training_set_TripAdvisor, max_len)\ninput_test_CL_sequences_1 = pad_sentences_post(input_test_set_IMDB, max_len)\ninput_test_CL_sequences_2 = pad_sentences_post(input_test_set_TripAdvisor, max_len)",
"_____no_output_____"
],
[
"def create_dataset_slices_sentence_Regre(input_sequences, targets):\n predictors= tf.constant(input_sequences)\n targets=targets.astype(int)\n return predictors, targets",
"_____no_output_____"
],
[
"training_predictors, training_label=create_dataset_slices_sentence_Regre(input_train_CL_sequences_2,training_set_TripAdvisor_np[:,0])\ntest_predictors, test_label=create_dataset_slices_sentence_Regre(input_test_CL_sequences_2,test_set_TripAdvisor_np[:,0])\ntraining_predictors_tfds, training_label_tfds=create_dataset_slices_sentence_Regre(input_train_CL_sequences_1,training_set_IMDB_np[:,0])\ntest_predictors_tfds, test_label_tfds=create_dataset_slices_sentence_Regre(input_test_CL_sequences_1,test_set_IMDB_np[:,0])",
"_____no_output_____"
],
[
"from keras.regularizers import l2",
"_____no_output_____"
]
],
[
[
"#Model",
"_____no_output_____"
]
],
[
[
"BidirectionalLayer1 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True))\nBidirectionalLayer2 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True))\nGlobalMaxPool1DLayer = tf.keras.layers.GlobalMaxPool1D()\nDenseLayer1 = tf.keras.layers.Dense(40, kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01) , activation='relu')\nDropLayer = tf.keras.layers.Dropout(0.1)\nDenseLayerOutputRE = tf.keras.layers.Dense(1, activation=tf.keras.activations.linear)",
"_____no_output_____"
],
[
"EmbeddingLayer.trainable = False",
"_____no_output_____"
],
[
"modelBin = tf.keras.Sequential()\nmodelBin.add(EmbeddingLayer)\nmodelBin.add(BidirectionalLayer1)\nmodelBin.add(BidirectionalLayer2)\nmodelBin.add(GlobalMaxPool1DLayer)\nmodelBin.add(DenseLayer1)\nmodelBin.add(DropLayer)\nmodelBin.add(DenseLayerOutputRE)\nmodelBin.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding (Embedding) (None, None, 64) 5120512 \n_________________________________________________________________\nbidirectional (Bidirectional (None, None, 128) 66048 \n_________________________________________________________________\nbidirectional_1 (Bidirection (None, None, 128) 98816 \n_________________________________________________________________\nglobal_max_pooling1d (Global (None, 128) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 40) 5160 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 40) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 1) 41 \n=================================================================\nTotal params: 5,290,577\nTrainable params: 170,065\nNon-trainable params: 5,120,512\n_________________________________________________________________\n"
],
[
"modelBin.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['mse','mae'])",
"_____no_output_____"
],
[
"history = modelBin.fit(training_predictors_tfds, \n training_label_tfds,\n epochs=3,\n batch_size=100,\n validation_data=(test_predictors_tfds, test_label_tfds),\n verbose=1)",
"Train on 25000 samples, validate on 25000 samples\nEpoch 1/3\n25000/25000 [==============================] - 158s 6ms/sample - loss: 0.3988 - mse: 0.1875 - mae: 0.3710 - val_loss: 0.2184 - val_mse: 0.1716 - val_mae: 0.3166\nEpoch 2/3\n25000/25000 [==============================] - 152s 6ms/sample - loss: 0.1737 - mse: 0.1491 - mae: 0.3064 - val_loss: 0.1576 - val_mse: 0.1442 - val_mae: 0.3057\nEpoch 3/3\n24300/25000 [============================>.] - ETA: 2s - loss: 0.1416 - mse: 0.1319 - mae: 0.2760"
],
[
"EmbeddingLayer.trainable = True ",
"_____no_output_____"
],
[
"modelBin.compile(loss='mean_squared_error', \n optimizer=tf.keras.optimizers.Adam(),\n metrics=['mse','mae','accuracy'])",
"_____no_output_____"
],
[
"history = modelBin.fit(training_predictors_tfds, \n training_label_tfds,\n epochs=2,\n batch_size=100,\n validation_data=(test_predictors_tfds, test_label_tfds),\n verbose=1)",
"_____no_output_____"
],
[
"model1 = tf.keras.Sequential()\nmodel1.add(EmbeddingLayer)\nmodel1.add(BidirectionalLayer1)\nmodel1.add(BidirectionalLayer2)\nmodel1.add(GlobalMaxPool1DLayer)\nmodel1.add(DenseLayer1)\nmodel1.add(DropLayer)\nmodel1.add(DenseLayerOutputRE)\n\nmodel1.summary()",
"_____no_output_____"
],
[
"EmbeddingLayer.trainable = False\nBidirectionalLayer1.trainable = False\nBidirectionalLayer2.trainable = False\nGlobalMaxPool1DLayer.trainable = False\nDenseLayer1.trainable = False",
"_____no_output_____"
],
[
"model1.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['mse','mae','accuracy'])",
"_____no_output_____"
],
[
"history = model1.fit(training_predictors, \n training_label,\n epochs=5,\n batch_size=100,\n validation_data=(test_predictors, test_label),\n verbose=1)",
"_____no_output_____"
],
[
"DenseLayer1.trainable = True",
"_____no_output_____"
],
[
"model1.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['mse','mae','accuracy'])",
"_____no_output_____"
],
[
"history = model1.fit(training_predictors, \n training_label,\n epochs=4,\n batch_size=100,\n validation_data=(test_predictors, test_label),\n verbose=1)",
"_____no_output_____"
],
[
"EmbeddingLayer.trainable = True\nBidirectionalLayer1.trainable = True\nBidirectionalLayer2.trainable = True\nGlobalMaxPool1DLayer.trainable = True",
"_____no_output_____"
],
[
"model1.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(),\n metrics=['mse','mae','accuracy'])",
"_____no_output_____"
],
[
"history = model1.fit(training_predictors, \n training_label,\n epochs=4,\n batch_size=100,\n validation_data=(test_predictors, test_label),\n verbose=1)",
"_____no_output_____"
]
],
[
[
"#From saved weights",
"_____no_output_____"
]
],
[
[
"'''EmbeddingLayer = tf.keras.layers.Embedding(80008, 64)\nBidirectionalLayer1 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True))\nBidirectionalLayer2 = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences = True))\nGlobalMaxPool1DLayer = tf.keras.layers.GlobalMaxPool1D()\nDenseLayer1 = tf.keras.layers.Dense(40, kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01) , activation='relu')\nDropLayer = tf.keras.layers.Dropout(0.1)\nDenseLayerOutputRE = tf.keras.layers.Dense(1, activation=tf.keras.activations.linear)'''",
"_____no_output_____"
],
[
"'''model1 = tf.keras.Sequential()\nmodel1.add(EmbeddingLayer)\nmodel1.add(BidirectionalLayer1)\nmodel1.add(BidirectionalLayer2)\nmodel1.add(GlobalMaxPool1DLayer)\nmodel1.add(DenseLayer1)\nmodel1.add(DropLayer)\nmodel1.add(DenseLayerOutputRE)\n\nmodel1.summary()'''",
"_____no_output_____"
],
[
"'''model1.load_weights('/content/gdrive/My Drive/Chekpoints/model_checkpoint')'''",
"_____no_output_____"
]
],
[
[
"#Validation",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import mean_squared_error",
"_____no_output_____"
],
[
"import nltk\n\nnltk.download(\"stopwords\")\nnltk.download(\"punkt\")\n\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \nnltk.download('wordnet')\nfrom nltk.stem import WordNetLemmatizer \n \ndef clean_set(set_len):\n stop_words = list(stopwords.words('english'))\n stop_words.remove(\"not\")\n stop_words.remove(\"no\")\n stop_words.remove(\"isn't\")\n stop_words.remove(\"hasn't\")\n stop_words.remove(\"wasn't\")\n stop_words.remove(\"didn't\")\n stop_words.remove(\"haven't\")\n stop_words.remove(\"don't\")\n stop_words.remove(\"doesn't\")\n stop_words.remove(\"weren't\")\n stop_words.remove(\"shouldn't\")\n lemmatizer = WordNetLemmatizer() \n for elem in set_len:\n word_tokens = word_tokenize(elem[1]) \n filtered_sentence = [] \n for w in word_tokens: \n if w not in stop_words: \n filtered_sentence.append(lemmatizer.lemmatize(w)) \n elem[1]=' '.join(filtered_sentence)",
"_____no_output_____"
],
[
"column_names = ['reviews.rating','reviews.text']\neval_data = pd.read_csv('http://christophe-rodrigues.fr/eval_reviews.csv', usecols=column_names, sep=\";\")",
"_____no_output_____"
],
[
"eval_data = np.array(eval_data.values.tolist())",
"_____no_output_____"
],
[
"clean_set(eval_data)",
"_____no_output_____"
],
[
"eval_data_Text = tokenize_sentences(eval_data)",
"_____no_output_____"
],
[
"input_eval = pad_sentences_post(eval_data_Text, max_len)",
"_____no_output_____"
],
[
"eval_predictors, eval_label =create_dataset_slices_sentence_Regre(input_eval,eval_data[:,0])",
"_____no_output_____"
],
[
"prediction = model1.predict(eval_predictors)",
"_____no_output_____"
],
[
"mse = mean_squared_error(prediction, eval_label)",
"_____no_output_____"
],
[
"mse",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"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",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb060f96c21fd120326c675b9984732d3c18eeca | 57,246 | ipynb | Jupyter Notebook | NLTK/NLTK.ipynb | jimit105/Python-Libraries | 7e45e996454d323dad3aaa54875eef8eb865739b | [
"MIT"
] | 1 | 2018-10-02T13:36:56.000Z | 2018-10-02T13:36:56.000Z | NLTK/NLTK.ipynb | shubhanshu1995/Python-Libraries | ac4df5e28ac3bce2da4376b7989ffc96f2848fd9 | [
"MIT"
] | null | null | null | NLTK/NLTK.ipynb | shubhanshu1995/Python-Libraries | ac4df5e28ac3bce2da4376b7989ffc96f2848fd9 | [
"MIT"
] | 2 | 2019-07-15T06:57:54.000Z | 2021-11-17T05:00:21.000Z | 66.256944 | 34,467 | 0.653618 | [
[
[
"# NLTK",
"_____no_output_____"
],
[
"## Sentence and Word Tokenization",
"_____no_output_____"
]
],
[
[
"from nltk.tokenize import sent_tokenize, word_tokenize",
"_____no_output_____"
],
[
"EXAMPLE_TEXT = \"Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard.\"",
"_____no_output_____"
],
[
"# Sentence Tokenization\nprint(sent_tokenize(EXAMPLE_TEXT))",
"['Hello Mr. Smith, how are you doing today?', 'The weather is great, and Python is awesome.', 'The sky is pinkish-blue.', \"You shouldn't eat cardboard.\"]\n"
],
[
"# Word Tokenization\nprint(word_tokenize(EXAMPLE_TEXT))",
"['Hello', 'Mr.', 'Smith', ',', 'how', 'are', 'you', 'doing', 'today', '?', 'The', 'weather', 'is', 'great', ',', 'and', 'Python', 'is', 'awesome', '.', 'The', 'sky', 'is', 'pinkish-blue', '.', 'You', 'should', \"n't\", 'eat', 'cardboard', '.']\n"
]
],
[
[
"## Stopwords",
"_____no_output_____"
]
],
[
[
"from nltk.corpus import stopwords",
"_____no_output_____"
],
[
"# Printing all stopwords (english)\nset(stopwords.words('english'))",
"_____no_output_____"
],
[
"example_sent = \"This is a sample sentence, showing off the stop words filtration.\"\nstop_words = set(stopwords.words('english'))\nword_tokens = word_tokenize(example_sent)\nfiltered_sentence = [w for w in word_tokens if not w in stop_words]\nprint(word_tokens)\nprint(filtered_sentence)",
"['This', 'is', 'a', 'sample', 'sentence', ',', 'showing', 'off', 'the', 'stop', 'words', 'filtration', '.']\n['This', 'sample', 'sentence', ',', 'showing', 'stop', 'words', 'filtration', '.']\n"
]
],
[
[
"## Stemming words",
"_____no_output_____"
]
],
[
[
"# Porter Stemmer is a stemming algorithm\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nps = PorterStemmer()",
"_____no_output_____"
],
[
"example_words = [\"python\",\"pythoner\",\"pythoning\",\"pythoned\",\"pythonly\"]",
"_____no_output_____"
],
[
"for w in example_words:\n print(ps.stem(w))",
"python\npython\npython\npython\npythonli\n"
],
[
"new_text = \"It is important to by very pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once.\"",
"_____no_output_____"
],
[
"words = word_tokenize(new_text)\n\nfor w in words:\n print(ps.stem(w))",
"It\nis\nimport\nto\nby\nveri\npythonli\nwhile\nyou\nare\npython\nwith\npython\n.\nall\npython\nhave\npython\npoorli\nat\nleast\nonc\n.\n"
]
],
[
[
"## Part of Speech Tagging",
"_____no_output_____"
],
[
"# POS tag list:\n\nCC\tcoordinating conjunction \nCD\tcardinal digit \nDT\tdeterminer \nEX\texistential there (like: \"there is\" ... think of it like \"there exists\") \nFW\tforeign word \nIN\tpreposition/subordinating conjunction \nJJ\tadjective\t'big' \nJJR\tadjective, comparative\t'bigger' \nJJS\tadjective, superlative\t'biggest' \nLS\tlist marker\t1) \nMD\tmodal\tcould, will \nNN\tnoun, singular 'desk' \nNNS\tnoun plural\t'desks' \nNNP\tproper noun, singular\t'Harrison' \nNNPS proper noun, plural\t'Americans' \nPDT\tpredeterminer\t'all the kids' \nPOS\tpossessive ending\tparent's \nPRP\tpersonal pronoun\tI, he, she \nPRP\\$ possessive pronoun\tmy, his, hers \nRB\tadverb\tvery, silently, \nRBR\tadverb, comparative\tbetter \nRBS\tadverb, superlative\tbest \nRP\tparticle\tgive up \nTO\tto\tgo 'to' the store. \nUH\tinterjection\terrrrrrrrm \nVB\tverb, base form\ttake \nVBD\tverb, past tense\ttook \nVBG\tverb, gerund/present participle\ttaking \nVBN\tverb, past participle\ttaken \nVBP\tverb, sing. present, non-3d\ttake \nVBZ\tverb, 3rd person sing. present\ttakes \nWDT\twh-determiner\twhich \nWP\twh-pronoun\twho, what \nWP$\tpossessive wh-pronoun\twhose \nWRB\twh-abverb\twhere, when ",
"_____no_output_____"
],
[
"#### PunktSentenceTokenizer\n> This tokenizer is capable of unsupervised machine learning, so you can actually train it on any body of text that you use.",
"_____no_output_____"
]
],
[
[
"import nltk\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer",
"_____no_output_____"
],
[
"# Create training and testing data\ntrain_text = state_union.raw('2005-GWBush.txt')\nsample_text = state_union.raw('2006-GWBush.txt')",
"_____no_output_____"
],
[
"# Train Punkt tokenizer\ncustom_sent_tokenizer = PunktSentenceTokenizer(train_text)",
"_____no_output_____"
],
[
"# Actually tokenize\ntokenized = custom_sent_tokenizer.tokenize(sample_text)",
"_____no_output_____"
],
[
"print(tokenized)",
"[\"PRESIDENT GEORGE W. BUSH'S ADDRESS BEFORE A JOINT SESSION OF THE CONGRESS ON THE STATE OF THE UNION\\n \\nJanuary 31, 2006\\n\\nTHE PRESIDENT: Thank you all.\", 'Mr. Speaker, Vice President Cheney, members of Congress, members of the Supreme Court and diplomatic corps, distinguished guests, and fellow citizens: Today our nation lost a beloved, graceful, courageous woman who called America to its founding ideals and carried on a noble dream.', 'Tonight we are comforted by the hope of a glad reunion with the husband who was taken so long ago, and we are grateful for the good life of Coretta Scott King.', '(Applause.)', 'President George W. Bush reacts to applause during his State of the Union Address at the Capitol, Tuesday, Jan.', '31, 2006.', \"White House photo by Eric DraperEvery time I'm invited to this rostrum, I'm humbled by the privilege, and mindful of the history we've seen together.\", 'We have gathered under this Capitol dome in moments of national mourning and national achievement.', 'We have served America through one of the most consequential periods of our history -- and it has been my honor to serve with you.', 'In a system of two parties, two chambers, and two elected branches, there will always be differences and debate.', 'But even tough debates can be conducted in a civil tone, and our differences cannot be allowed to harden into anger.', 'To confront the great issues before us, we must act in a spirit of goodwill and respect for one another -- and I will do my part.', 'Tonight the state of our Union is strong -- and together we will make it stronger.', '(Applause.)', 'In this decisive year, you and I will make choices that determine both the future and the character of our country.', 'We will choose to act confidently in pursuing the enemies of freedom -- or retreat from our duties in the hope of an easier life.', 'We will choose to build our prosperity by leading the world economy -- or shut ourselves off from trade and opportunity.', 'In a complex and challenging time, the road of isolationism and protectionism may seem broad and inviting -- yet it ends in danger and decline.', 'The only way to protect our people, the only way to secure the peace, the only way to control our destiny is by our leadership -- so the United States of America will continue to lead.', '(Applause.)', 'Abroad, our nation is committed to an historic, long-term goal -- we seek the end of tyranny in our world.', 'Some dismiss that goal as misguided idealism.', 'In reality, the future security of America depends on it.', 'On September the 11th, 2001, we found that problems originating in a failed and oppressive state 7,000 miles away could bring murder and destruction to our country.', 'Dictatorships shelter terrorists, and feed resentment and radicalism, and seek weapons of mass destruction.', 'Democracies replace resentment with hope, respect the rights of their citizens and their neighbors, and join the fight against terror.', \"Every step toward freedom in the world makes our country safer -- so we will act boldly in freedom's cause.\", '(Applause.)', 'Far from being a hopeless dream, the advance of freedom is the great story of our time.', 'In 1945, there were about two dozen lonely democracies in the world.', 'Today, there are 122.', \"And we're writing a new chapter in the story of self-government -- with women lining up to vote in Afghanistan, and millions of Iraqis marking their liberty with purple ink, and men and women from Lebanon to Egypt debating the rights of individuals and the necessity of freedom.\", 'At the start of 2006, more than half the people of our world live in democratic nations.', 'And we do not forget the other half -- in places like Syria and Burma, Zimbabwe, North Korea, and Iran -- because the demands of justice, and the peace of this world, require their freedom, as well.', '(Applause.)', 'President George W. Bush delivers his State of the Union Address at the Capitol, Tuesday, Jan.', '31, 2006.', 'White House photo by Eric Draper No one can deny the success of freedom, but some men rage and fight against it.', 'And one of the main sources of reaction and opposition is radical Islam -- the perversion by a few of a noble faith into an ideology of terror and death.', 'Terrorists like bin Laden are serious about mass murder -- and all of us must take their declared intentions seriously.', 'They seek to impose a heartless system of totalitarian control throughout the Middle East, and arm themselves with weapons of mass murder.', 'Their aim is to seize power in Iraq, and use it as a safe haven to launch attacks against America and the world.', 'Lacking the military strength to challenge us directly, the terrorists have chosen the weapon of fear.', 'When they murder children at a school in Beslan, or blow up commuters in London, or behead a bound captive, the terrorists hope these horrors will break our will, allowing the violent to inherit the Earth.', 'But they have miscalculated: We love our freedom, and we will fight to keep it.', '(Applause.)', 'In a time of testing, we cannot find security by abandoning our commitments and retreating within our borders.', 'If we were to leave these vicious attackers alone, they would not leave us alone.', 'They would simply move the battlefield to our own shores.', 'There is no peace in retreat.', 'And there is no honor in retreat.', 'By allowing radical Islam to work its will -- by leaving an assaulted world to fend for itself -- we would signal to all that we no longer believe in our own ideals, or even in our own courage.', 'But our enemies and our friends can be certain: The United States will not retreat from the world, and we will never surrender to evil.', '(Applause.)', 'America rejects the false comfort of isolationism.', 'We are the nation that saved liberty in Europe, and liberated death camps, and helped raise up democracies, and faced down an evil empire.', 'Once again, we accept the call of history to deliver the oppressed and move this world toward peace.', 'We remain on the offensive against terror networks.', 'We have killed or captured many of their leaders -- and for the others, their day will come.', 'President George W. Bush greets members of Congress after his State of the Union Address at the Capitol, Tuesday, Jan.', '31, 2006.', 'White House photo by Eric Draper We remain on the offensive in Afghanistan, where a fine President and a National Assembly are fighting terror while building the institutions of a new democracy.', \"We're on the offensive in Iraq, with a clear plan for victory.\", \"First, we're helping Iraqis build an inclusive government, so that old resentments will be eased and the insurgency will be marginalized.\", \"Second, we're continuing reconstruction efforts, and helping the Iraqi government to fight corruption and build a modern economy, so all Iraqis can experience the benefits of freedom.\", \"And, third, we're striking terrorist targets while we train Iraqi forces that are increasingly capable of defeating the enemy.\", 'Iraqis are showing their courage every day, and we are proud to be their allies in the cause of freedom.', '(Applause.)', 'Our work in Iraq is difficult because our enemy is brutal.', 'But that brutality has not stopped the dramatic progress of a new democracy.', 'In less than three years, the nation has gone from dictatorship to liberation, to sovereignty, to a constitution, to national elections.', 'At the same time, our coalition has been relentless in shutting off terrorist infiltration, clearing out insurgent strongholds, and turning over territory to Iraqi security forces.', 'I am confident in our plan for victory; I am confident in the will of the Iraqi people; I am confident in the skill and spirit of our military.', 'Fellow citizens, we are in this fight to win, and we are winning.', '(Applause.)', 'The road of victory is the road that will take our troops home.', 'As we make progress on the ground, and Iraqi forces increasingly take the lead, we should be able to further decrease our troop levels -- but those decisions will be made by our military commanders, not by politicians in Washington, D.C.', '(Applause.)', 'Our coalition has learned from our experience in Iraq.', \"We've adjusted our military tactics and changed our approach to reconstruction.\", 'Along the way, we have benefitted from responsible criticism and counsel offered by members of Congress of both parties.', 'In the coming year, I will continue to reach out and seek your good advice.', 'Yet, there is a difference between responsible criticism that aims for success, and defeatism that refuses to acknowledge anything but failure.', '(Applause.)', 'Hindsight alone is not wisdom, and second-guessing is not a strategy.', '(Applause.)', 'With so much in the balance, those of us in public office have a duty to speak with candor.', 'A sudden withdrawal of our forces from Iraq would abandon our Iraqi allies to death and prison, would put men like bin Laden and Zarqawi in charge of a strategic country, and show that a pledge from America means little.', 'Members of Congress, however we feel about the decisions and debates of the past, our nation has only one option: We must keep our word, defeat our enemies, and stand behind the American military in this vital mission.', '(Applause.)', 'Laura Bush is applauded as she is introduced Tuesday evening, Jan.', '31, 2006 during the State of the Union Address at United States Capitol in Washington.', 'White House photo by Eric Draper Our men and women in uniform are making sacrifices -- and showing a sense of duty stronger than all fear.', \"They know what it's like to fight house to house in a maze of streets, to wear heavy gear in the desert heat, to see a comrade killed by a roadside bomb.\", 'And those who know the costs also know the stakes.', 'Marine Staff Sergeant Dan Clay was killed last month fighting in Fallujah.', 'He left behind a letter to his family, but his words could just as well be addressed to every American.', 'Here is what Dan wrote: \"I know what honor is.', '... It has been an honor to protect and serve all of you.', 'I faced death with the secure knowledge that you would not have to....', 'Never falter!', 'Don\\'t hesitate to honor and support those of us who have the honor of protecting that which is worth protecting.\"', \"Staff Sergeant Dan Clay's wife, Lisa, and his mom and dad, Sara Jo and Bud, are with us this evening.\", 'Welcome.', '(Applause.)', 'Our nation is grateful to the fallen, who live in the memory of our country.', \"We're grateful to all who volunteer to wear our nation's uniform -- and as we honor our brave troops, let us never forget the sacrifices of America's military families.\", '(Applause.)', 'Our offensive against terror involves more than military action.', 'Ultimately, the only way to defeat the terrorists is to defeat their dark vision of hatred and fear by offering the hopeful alternative of political freedom and peaceful change.', 'So the United States of America supports democratic reform across the broader Middle East.', 'Elections are vital, but they are only the beginning.', 'Raising up a democracy requires the rule of law, and protection of minorities, and strong, accountable institutions that last longer than a single vote.', 'The great people of Egypt have voted in a multi-party presidential election -- and now their government should open paths of peaceful opposition that will reduce the appeal of radicalism.', 'The Palestinian people have voted in elections.', 'And now the leaders of Hamas must recognize Israel, disarm, reject terrorism, and work for lasting peace.', '(Applause.)', 'Saudi Arabia has taken the first steps of reform -- now it can offer its people a better future by pressing forward with those efforts.', 'Democracies in the Middle East will not look like our own, because they will reflect the traditions of their own citizens.', 'Yet liberty is the future of every nation in the Middle East, because liberty is the right and hope of all humanity.', '(Applause.)', 'President George W. Bush waves toward the upper visitors gallery of the House Chamber following his State of the Union remarks Tuesday, Jan.', '31, 2006 at the United States Capitol.', 'White House photo by Eric Draper The same is true of Iran, a nation now held hostage by a small clerical elite that is isolating and repressing its people.', 'The regime in that country sponsors terrorists in the Palestinian territories and in Lebanon -- and that must come to an end.', '(Applause.)', 'The Iranian government is defying the world with its nuclear ambitions, and the nations of the world must not permit the Iranian regime to gain nuclear weapons.', '(Applause.)', 'America will continue to rally the world to confront these threats.', 'Tonight, let me speak directly to the citizens of Iran: America respects you, and we respect your country.', 'We respect your right to choose your own future and win your own freedom.', 'And our nation hopes one day to be the closest of friends with a free and democratic Iran.', '(Applause.)', 'To overcome dangers in our world, we must also take the offensive by encouraging economic progress, and fighting disease, and spreading hope in hopeless lands.', 'Isolationism would not only tie our hands in fighting enemies, it would keep us from helping our friends in desperate need.', 'We show compassion abroad because Americans believe in the God-given dignity and worth of a villager with HIV/AIDS, or an infant with malaria, or a refugee fleeing genocide, or a young girl sold into slavery.', 'We also show compassion abroad because regions overwhelmed by poverty, corruption, and despair are sources of terrorism, and organized crime, and human trafficking, and the drug trade.', 'In recent years, you and I have taken unprecedented action to fight AIDS and malaria, expand the education of girls, and reward developing nations that are moving forward with economic and political reform.', 'For people everywhere, the United States is a partner for a better life.', 'Short-changing these efforts would increase the suffering and chaos of our world, undercut our long-term security, and dull the conscience of our country.', 'I urge members of Congress to serve the interests of America by showing the compassion of America.', 'Our country must also remain on the offensive against terrorism here at home.', 'The enemy has not lost the desire or capability to attack us.', 'Fortunately, this nation has superb professionals in law enforcement, intelligence, the military, and homeland security.', 'These men and women are dedicating their lives, protecting us all, and they deserve our support and our thanks.', '(Applause.)', 'They also deserve the same tools they already use to fight drug trafficking and organized crime -- so I ask you to reauthorize the Patriot Act.', '(Applause.)', 'It is said that prior to the attacks of September the 11th, our government failed to connect the dots of the conspiracy.', 'We now know that two of the hijackers in the United States placed telephone calls to al Qaeda operatives overseas.', 'But we did not know about their plans until it was too late.', 'So to prevent another attack -- based on authority given to me by the Constitution and by statute -- I have authorized a terrorist surveillance program to aggressively pursue the international communications of suspected al Qaeda operatives and affiliates to and from America.', 'Previous Presidents have used the same constitutional authority I have, and federal courts have approved the use of that authority.', 'Appropriate members of Congress have been kept informed.', 'The terrorist surveillance program has helped prevent terrorist attacks.', 'It remains essential to the security of America.', 'If there are people inside our country who are talking with al Qaeda, we want to know about it, because we will not sit back and wait to be hit again.', '(Applause.)', 'In all these areas -- from the disruption of terror networks, to victory in Iraq, to the spread of freedom and hope in troubled regions -- we need the support of our friends and allies.', 'To draw that support, we must always be clear in our principles and willing to act.', 'The only alternative to American leadership is a dramatically more dangerous and anxious world.', 'Yet we also choose to lead because it is a privilege to serve the values that gave us birth.', 'American leaders -- from Roosevelt to Truman to Kennedy to Reagan -- rejected isolation and retreat, because they knew that America is always more secure when freedom is on the march.', 'Our own generation is in a long war against a determined enemy -- a war that will be fought by Presidents of both parties, who will need steady bipartisan support from the Congress.', 'And tonight I ask for yours.', 'Together, let us protect our country, support the men and women who defend us, and lead this world toward freedom.', '(Applause.)', 'Here at home, America also has a great opportunity: We will build the prosperity of our country by strengthening our economic leadership in the world.', 'Our economy is healthy and vigorous, and growing faster than other major industrialized nations.', 'In the last two-and-a-half years, America has created 4.6 million new jobs -- more than Japan and the European Union combined.', '(Applause.)', 'Even in the face of higher energy prices and natural disasters, the American people have turned in an economic performance that is the envy of the world.', 'The American economy is preeminent, but we cannot afford to be complacent.', \"In a dynamic world economy, we are seeing new competitors, like China and India, and this creates uncertainty, which makes it easier to feed people's fears.\", \"So we're seeing some old temptations return.\", 'Protectionists want to escape competition, pretending that we can keep our high standard of living while walling off our economy.', 'Others say that the government needs to take a larger role in directing the economy, centralizing more power in Washington and increasing taxes.', 'We hear claims that immigrants are somehow bad for the economy -- even though this economy could not function without them.', '(Applause.)', 'All these are forms of economic retreat, and they lead in the same direction -- toward a stagnant and second-rate economy.', 'Tonight I will set out a better path: an agenda for a nation that competes with confidence; an agenda that will raise standards of living and generate new jobs.', 'Americans should not fear our economic future, because we intend to shape it.', 'Keeping America competitive begins with keeping our economy growing.', 'And our economy grows when Americans have more of their own money to spend, save, and invest.', 'In the last five years, the tax relief you passed has left $880 billion in the hands of American workers, investors, small businesses, and families -- and they have used it to help produce more than four years of uninterrupted economic growth.', '(Applause.)', 'Yet the tax relief is set to expire in the next few years.', 'If we do nothing, American families will face a massive tax increase they do not expect and will not welcome.', 'Because America needs more than a temporary expansion, we need more than temporary tax relief.', 'I urge the Congress to act responsibly, and make the tax cuts permanent.', '(Applause.)', 'Keeping America competitive requires us to be good stewards of tax dollars.', \"Every year of my presidency, we've reduced the growth of non-security discretionary spending, and last year you passed bills that cut this spending.\", 'This year my budget will cut it again, and reduce or eliminate more than 140 programs that are performing poorly or not fulfilling essential priorities.', 'By passing these reforms, we will save the American taxpayer another $14 billion next year, and stay on track to cut the deficit in half by 2009.', '(Applause.)', 'I am pleased that members of Congress are working on earmark reform, because the federal budget has too many special interest projects.', '(Applause.)', 'And we can tackle this problem together, if you pass the line-item veto.', '(Applause.)', 'We must also confront the larger challenge of mandatory spending, or entitlements.', \"This year, the first of about 78 million baby boomers turn 60, including two of my Dad's favorite people -- me and President Clinton.\", '(Laughter.)', 'This milestone is more than a personal crisis -- (laughter) -- it is a national challenge.', 'The retirement of the baby boom generation will put unprecedented strains on the federal government.', 'By 2030, spending for Social Security, Medicare and Medicaid alone will be almost 60 percent of the entire federal budget.', 'And that will present future Congresses with impossible choices -- staggering tax increases, immense deficits, or deep cuts in every category of spending.', 'Congress did not act last year on my proposal to save Social Security -- (applause) -- yet the rising cost of entitlements is a problem that is not going away.', '(Applause.)', 'And every year we fail to act, the situation gets worse.', 'So tonight, I ask you to join me in creating a commission to examine the full impact of baby boom retirements on Social Security, Medicare, and Medicaid.', 'This commission should include members of Congress of both parties, and offer bipartisan solutions.', 'We need to put aside partisan politics and work together and get this problem solved.', '(Applause.)', 'Keeping America competitive requires us to open more markets for all that Americans make and grow.', 'One out of every five factory jobs in America is related to global trade, and we want people everywhere to buy American.', 'With open markets and a level playing field, no one can out-produce or out-compete the American worker.', '(Applause.)', 'Keeping America competitive requires an immigration system that upholds our laws, reflects our values, and serves the interests of our economy.', 'Our nation needs orderly and secure borders.', '(Applause.)', 'To meet this goal, we must have stronger immigration enforcement and border protection.', '(Applause.)', 'And we must have a rational, humane guest worker program that rejects amnesty, allows temporary jobs for people who seek them legally, and reduces smuggling and crime at the border.', '(Applause.)', 'Keeping America competitive requires affordable health care.', '(Applause.)', 'Our government has a responsibility to provide health care for the poor and the elderly, and we are meeting that responsibility.', '(Applause.)', 'For all Americans -- for all Americans, we must confront the rising cost of care, strengthen the doctor-patient relationship, and help people afford the insurance coverage they need.', '(Applause.)', 'We will make wider use of electronic records and other health information technology, to help control costs and reduce dangerous medical errors.', 'We will strengthen health savings accounts -- making sure individuals and small business employees can buy insurance with the same advantages that people working for big businesses now get.', '(Applause.)', 'We will do more to make this coverage portable, so workers can switch jobs without having to worry about losing their health insurance.', '(Applause.)', 'And because lawsuits are driving many good doctors out of practice -- leaving women in nearly 1,500 American counties without a single OB/GYN -- I ask the Congress to pass medical liability reform this year.', '(Applause.)', 'Keeping America competitive requires affordable energy.', 'And here we have a serious problem: America is addicted to oil, which is often imported from unstable parts of the world.', 'The best way to break this addiction is through technology.', 'Since 2001, we have spent nearly $10 billion to develop cleaner, cheaper, and more reliable alternative energy sources -- and we are on the threshold of incredible advances.', 'So tonight, I announce the Advanced Energy Initiative -- a 22-percent increase in clean-energy research -- at the Department of Energy, to push for breakthroughs in two vital areas.', 'To change how we power our homes and offices, we will invest more in zero-emission coal-fired plants, revolutionary solar and wind technologies, and clean, safe nuclear energy.', '(Applause.)', 'We must also change how we power our automobiles.', 'We will increase our research in better batteries for hybrid and electric cars, and in pollution-free cars that run on hydrogen.', \"We'll also fund additional research in cutting-edge methods of producing ethanol, not just from corn, but from wood chips and stalks, or switch grass.\", 'Our goal is to make this new kind of ethanol practical and competitive within six years.', '(Applause.)', 'Breakthroughs on this and other new technologies will help us reach another great goal: to replace more than 75 percent of our oil imports from the Middle East by 2025.', '(Applause.)', 'By applying the talent and technology of America, this country can dramatically improve our environment, move beyond a petroleum-based economy, and make our dependence on Middle Eastern oil a thing of the past.', '(Applause.)', 'And to keep America competitive, one commitment is necessary above all: We must continue to lead the world in human talent and creativity.', \"Our greatest advantage in the world has always been our educated, hardworking, ambitious people -- and we're going to keep that edge.\", \"Tonight I announce an American Competitiveness Initiative, to encourage innovation throughout our economy, and to give our nation's children a firm grounding in math and science.\", '(Applause.)', 'First, I propose to double the federal commitment to the most critical basic research programs in the physical sciences over the next 10 years.', \"This funding will support the work of America's most creative minds as they explore promising areas such as nanotechnology, supercomputing, and alternative energy sources.\", 'Second, I propose to make permanent the research and development tax credit -- (applause) -- to encourage bolder private-sector initiatives in technology.', 'With more research in both the public and private sectors, we will improve our quality of life -- and ensure that America will lead the world in opportunity and innovation for decades to come.', '(Applause.)', 'Third, we need to encourage children to take more math and science, and to make sure those courses are rigorous enough to compete with other nations.', \"We've made a good start in the early grades with the No Child Left Behind Act, which is raising standards and lifting test scores across our country.\", 'Tonight I propose to train 70,000 high school teachers to lead advanced-placement courses in math and science, bring 30,000 math and science professionals to teach in classrooms, and give early help to students who struggle with math, so they have a better chance at good, high-wage jobs.', \"If we ensure that America's children succeed in life, they will ensure that America succeeds in the world.\", '(Applause.)', 'Preparing our nation to compete in the world is a goal that all of us can share.', 'I urge you to support the American Competitiveness Initiative, and together we will show the world what the American people can achieve.', 'America is a great force for freedom and prosperity.', 'Yet our greatness is not measured in power or luxuries, but by who we are and how we treat one another.', 'So we strive to be a compassionate, decent, hopeful society.', 'In recent years, America has become a more hopeful nation.', 'Violent crime rates have fallen to their lowest levels since the 1970s.', 'Welfare cases have dropped by more than half over the past decade.', 'Drug use among youth is down 19 percent since 2001.', 'There are fewer abortions in America than at any point in the last three decades, and the number of children born to teenage mothers has been falling for a dozen years in a row.', '(Applause.)', 'These gains are evidence of a quiet transformation -- a revolution of conscience, in which a rising generation is finding that a life of personal responsibility is a life of fulfillment.', 'Government has played a role.', 'Wise policies, such as welfare reform and drug education and support for abstinence and adoption have made a difference in the character of our country.', 'And everyone here tonight, Democrat and Republican, has a right to be proud of this record.', '(Applause.)', 'Yet many Americans, especially parents, still have deep concerns about the direction of our culture, and the health of our most basic institutions.', \"They're concerned about unethical conduct by public officials, and discouraged by activist courts that try to redefine marriage.\", 'They worry about children in our society who need direction and love, and about fellow citizens still displaced by natural disaster, and about suffering caused by treatable diseases.', 'As we look at these challenges, we must never give in to the belief that America is in decline, or that our culture is doomed to unravel.', 'The American people know better than that.', 'We have proven the pessimists wrong before -- and we will do it again.', '(Applause.)', 'A hopeful society depends on courts that deliver equal justice under the law.', 'The Supreme Court now has two superb new members -- new members on its bench: Chief Justice John Roberts and Justice Sam Alito.', '(Applause.)', 'I thank the Senate for confirming both of them.', 'I will continue to nominate men and women who understand that judges must be servants of the law, and not legislate from the bench.', '(Applause.)', 'Today marks the official retirement of a very special American.', \"For 24 years of faithful service to our nation, the United States is grateful to Justice Sandra Day O'Connor.\", '(Applause.)', 'A hopeful society has institutions of science and medicine that do not cut ethical corners, and that recognize the matchless value of every life.', 'Tonight I ask you to pass legislation to prohibit the most egregious abuses of medical research: human cloning in all its forms, creating or implanting embryos for experiments, creating human-animal hybrids, and buying, selling, or patenting human embryos.', 'Human life is a gift from our Creator -- and that gift should never be discarded, devalued or put up for sale.', '(Applause.)', 'A hopeful society expects elected officials to uphold the public trust.', '(Applause.)', 'Honorable people in both parties are working on reforms to strengthen the ethical standards of Washington -- I support your efforts.', 'Each of us has made a pledge to be worthy of public responsibility -- and that is a pledge we must never forget, never dismiss, and never betray.', '(Applause.)', 'As we renew the promise of our institutions, let us also show the character of America in our compassion and care for one another.', 'A hopeful society gives special attention to children who lack direction and love.', \"Through the Helping America's Youth Initiative, we are encouraging caring adults to get involved in the life of a child -- and this good work is being led by our First Lady, Laura Bush.\", '(Applause.)', \"This year we will add resources to encourage young people to stay in school, so more of America's youth can raise their sights and achieve their dreams.\", \"A hopeful society comes to the aid of fellow citizens in times of suffering and emergency -- and stays at it until they're back on their feet.\", 'So far the federal government has committed $85 billion to the people of the Gulf Coast and New Orleans.', \"We're removing debris and repairing highways and rebuilding stronger levees.\", \"We're providing business loans and housing assistance.\", 'Yet as we meet these immediate needs, we must also address deeper challenges that existed before the storm arrived.', 'In New Orleans and in other places, many of our fellow citizens have felt excluded from the promise of our country.', 'The answer is not only temporary relief, but schools that teach every child, and job skills that bring upward mobility, and more opportunities to own a home and start a business.', 'As we recover from a disaster, let us also work for the day when all Americans are protected by justice, equal in hope, and rich in opportunity.', '(Applause.)', 'A hopeful society acts boldly to fight diseases like HIV/AIDS, which can be prevented, and treated, and defeated.', 'More than a million Americans live with HIV, and half of all AIDS cases occur among African Americans.', 'I ask Congress to reform and reauthorize the Ryan White Act, and provide new funding to states, so we end the waiting lists for AIDS medicines in America.', '(Applause.)', 'We will also lead a nationwide effort, working closely with African American churches and faith-based groups, to deliver rapid HIV tests to millions, end the stigma of AIDS, and come closer to the day when there are no new infections in America.', '(Applause.)', \"Fellow citizens, we've been called to leadership in a period of consequence.\", \"We've entered a great ideological conflict we did nothing to invite.\", 'We see great changes in science and commerce that will influence all our lives.', 'Sometimes it can seem that history is turning in a wide arc, toward an unknown shore.', 'Yet the destination of history is determined by human action, and every great movement of history comes to a point of choosing.', 'Lincoln could have accepted peace at the cost of disunity and continued slavery.', 'Martin Luther King could have stopped at Birmingham or at Selma, and achieved only half a victory over segregation.', 'The United States could have accepted the permanent division of Europe, and been complicit in the oppression of others.', 'Today, having come far in our own historical journey, we must decide: Will we turn back, or finish well?', 'Before history is written down in books, it is written in courage.', 'Like Americans before us, we will show that courage and we will finish well.', \"We will lead freedom's advance.\", 'We will compete and excel in the global economy.', 'We will renew the defining moral commitments of this land.', 'And so we move forward -- optimistic about our country, faithful to its cause, and confident of the victories to come.', 'May God bless America.', '(Applause.)']\n"
],
[
"# Create a function that will run through and tag all of the parts of speech per sentence\n\ndef process_content():\n try:\n for i in tokenized[ :5]:\n words = nltk.word_tokenize(i)\n tagged = nltk.pos_tag(words)\n print(tagged)\n \n except Exception as e:\n print(str(e))",
"_____no_output_____"
],
[
"# Output should be a list of tuples, where the first element in the tuple is the word, and the second is the part of speech tag\n\nprocess_content()",
"[('PRESIDENT', 'NNP'), ('GEORGE', 'NNP'), ('W.', 'NNP'), ('BUSH', 'NNP'), (\"'S\", 'POS'), ('ADDRESS', 'NNP'), ('BEFORE', 'IN'), ('A', 'NNP'), ('JOINT', 'NNP'), ('SESSION', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('CONGRESS', 'NNP'), ('ON', 'NNP'), ('THE', 'NNP'), ('STATE', 'NNP'), ('OF', 'IN'), ('THE', 'NNP'), ('UNION', 'NNP'), ('January', 'NNP'), ('31', 'CD'), (',', ','), ('2006', 'CD'), ('THE', 'NNP'), ('PRESIDENT', 'NNP'), (':', ':'), ('Thank', 'NNP'), ('you', 'PRP'), ('all', 'DT'), ('.', '.')]\n[('Mr.', 'NNP'), ('Speaker', 'NNP'), (',', ','), ('Vice', 'NNP'), ('President', 'NNP'), ('Cheney', 'NNP'), (',', ','), ('members', 'NNS'), ('of', 'IN'), ('Congress', 'NNP'), (',', ','), ('members', 'NNS'), ('of', 'IN'), ('the', 'DT'), ('Supreme', 'NNP'), ('Court', 'NNP'), ('and', 'CC'), ('diplomatic', 'JJ'), ('corps', 'NN'), (',', ','), ('distinguished', 'JJ'), ('guests', 'NNS'), (',', ','), ('and', 'CC'), ('fellow', 'JJ'), ('citizens', 'NNS'), (':', ':'), ('Today', 'VB'), ('our', 'PRP$'), ('nation', 'NN'), ('lost', 'VBD'), ('a', 'DT'), ('beloved', 'VBN'), (',', ','), ('graceful', 'JJ'), (',', ','), ('courageous', 'JJ'), ('woman', 'NN'), ('who', 'WP'), ('called', 'VBD'), ('America', 'NNP'), ('to', 'TO'), ('its', 'PRP$'), ('founding', 'NN'), ('ideals', 'NNS'), ('and', 'CC'), ('carried', 'VBD'), ('on', 'IN'), ('a', 'DT'), ('noble', 'JJ'), ('dream', 'NN'), ('.', '.')]\n[('Tonight', 'NN'), ('we', 'PRP'), ('are', 'VBP'), ('comforted', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('a', 'DT'), ('glad', 'JJ'), ('reunion', 'NN'), ('with', 'IN'), ('the', 'DT'), ('husband', 'NN'), ('who', 'WP'), ('was', 'VBD'), ('taken', 'VBN'), ('so', 'RB'), ('long', 'RB'), ('ago', 'RB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('grateful', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('good', 'JJ'), ('life', 'NN'), ('of', 'IN'), ('Coretta', 'NNP'), ('Scott', 'NNP'), ('King', 'NNP'), ('.', '.')]\n[('(', '('), ('Applause', 'NNP'), ('.', '.'), (')', ')')]\n[('President', 'NNP'), ('George', 'NNP'), ('W.', 'NNP'), ('Bush', 'NNP'), ('reacts', 'VBZ'), ('to', 'TO'), ('applause', 'VB'), ('during', 'IN'), ('his', 'PRP$'), ('State', 'NNP'), ('of', 'IN'), ('the', 'DT'), ('Union', 'NNP'), ('Address', 'NNP'), ('at', 'IN'), ('the', 'DT'), ('Capitol', 'NNP'), (',', ','), ('Tuesday', 'NNP'), (',', ','), ('Jan', 'NNP'), ('.', '.')]\n"
]
],
[
[
"## Lemmatizing",
"_____no_output_____"
],
[
"> A very similar operation to stemming is called lemmatizing. The major difference between these is, as you saw earlier, stemming can often create non-existent words, whereas lemmas are actual words. \n\n> So, your root stem, meaning the word you end up with, is not something you can just look up in a dictionary, but you can look up a lemma. \n\n> Some times you will wind up with a very similar word, but sometimes, you will wind up with a completely different word.",
"_____no_output_____"
]
],
[
[
"from nltk.stem import WordNetLemmatizer\n\nlemmatizer = WordNetLemmatizer()",
"_____no_output_____"
],
[
"print(lemmatizer.lemmatize(\"cats\"))\nprint(lemmatizer.lemmatize(\"cacti\"))\nprint(lemmatizer.lemmatize(\"geese\"))\nprint(lemmatizer.lemmatize(\"rocks\"))\nprint(lemmatizer.lemmatize(\"python\"))\nprint(lemmatizer.lemmatize(\"better\", pos=\"a\"))\nprint(lemmatizer.lemmatize(\"best\", pos=\"a\"))\nprint(lemmatizer.lemmatize(\"run\"))\nprint(lemmatizer.lemmatize(\"run\",'v'))\n\n# Here, we've got a bunch of examples of the lemma for the words that we use. \n# The only major thing to note is that lemmatize takes a part of speech parameter, \"pos.\" \n# If not supplied, the default is \"noun.\" This means that an attempt will be made to find the closest noun, which can create trouble for you. \n# Keep this in mind if you use lemmatizing!",
"cat\ncactus\ngoose\nrock\npython\ngood\nbest\nrun\nrun\n"
]
],
[
[
"## Corpora\n\n> The NLTK corpus is a massive dump of all kinds of natural language data sets ",
"_____no_output_____"
]
],
[
[
"# Opening the Gutenberg Bible, and reading the first few lines\n\nfrom nltk.tokenize import sent_tokenize, PunktSentenceTokenizer\nfrom nltk.corpus import gutenberg\n\n#sample text\nsample = gutenberg.raw('bible-kjv.txt')\n\ntok = sent_tokenize(sample)\n\nfor x in range(5):\n print(tok[x])",
"[The King James Bible]\n\nThe Old Testament of the King James Bible\n\nThe First Book of Moses: Called Genesis\n\n\n1:1 In the beginning God created the heaven and the earth.\n1:2 And the earth was without form, and void; and darkness was upon\nthe face of the deep.\nAnd the Spirit of God moved upon the face of the\nwaters.\n1:3 And God said, Let there be light: and there was light.\n1:4 And God saw the light, that it was good: and God divided the light\nfrom the darkness.\n"
]
],
[
[
"## Wordnet\n\n> Wordnet is a collection of words, definitions, examples of their use, synonyms, antonyms, and more.",
"_____no_output_____"
]
],
[
[
"# Import wordnet\nfrom nltk.corpus import wordnet",
"_____no_output_____"
],
[
"# use the term \"program\" to find synsets\nsyns = wordnet.synsets('program')\n\nprint(syns)",
"[Synset('plan.n.01'), Synset('program.n.02'), Synset('broadcast.n.02'), Synset('platform.n.02'), Synset('program.n.05'), Synset('course_of_study.n.01'), Synset('program.n.07'), Synset('program.n.08'), Synset('program.v.01'), Synset('program.v.02')]\n"
],
[
"#Print first synset\nprint(syns[0].name())",
"plan.n.01\n"
],
[
"# Print only the word\nprint(syns[0].lemmas()[0].name())",
"plan\n"
],
[
"# Definition for that first synset\nprint(syns[0].definition())",
"a series of steps to be carried out or goals to be accomplished\n"
],
[
"# Examples of the word in use\nprint(syns[0].examples())",
"['they drew up a six-step plan', 'they discussed plans for a new bond issue']\n"
],
[
"# Synonyms and Antonyms\n\n# The lemmas will be synonyms, \n# and then you can use .antonyms to find the antonyms to the lemmas\n\nsynonyms = []\nantonyms = []\n\nfor syn in wordnet.synsets('good'):\n for l in syn.lemmas():\n synonyms.append(l.name())\n if l.antonyms():\n antonyms.append(l.antonyms()[0].name())\n\nprint(set(synonyms))\nprint(set(antonyms))",
"{'in_effect', 'honest', 'unspoiled', 'serious', 'ripe', 'beneficial', 'full', 'respectable', 'good', 'skilful', 'secure', 'trade_good', 'honorable', 'soundly', 'practiced', 'unspoilt', 'estimable', 'skillful', 'right', 'goodness', 'safe', 'in_force', 'adept', 'salutary', 'proficient', 'dependable', 'well', 'upright', 'expert', 'sound', 'undecomposed', 'thoroughly', 'commodity', 'near', 'dear', 'just', 'effective'}\n{'evil', 'evilness', 'badness', 'ill', 'bad'}\n"
],
[
"# compare the similarity of two words and their tenses\n\nw1 = wordnet.synset('ship.n.01')\nw2 = wordnet.synset('boat.n.01')\nprint(w1.wup_similarity(w2))\n\nw1 = wordnet.synset('ship.n.01')\nw2 = wordnet.synset('car.n.01')\nprint(w1.wup_similarity(w2))\n\nw1 = wordnet.synset('ship.n.01')\nw2 = wordnet.synset('cat.n.01')\nprint(w1.wup_similarity(w2))",
"0.9090909090909091\n0.6956521739130435\n0.32\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb061f797f7ca463a3a4f6c452db38a768dee575 | 127,883 | ipynb | Jupyter Notebook | 2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb | TheManohar/DSci_Pro | fd9631013929271bf2e295181be228a1f6b1a6d7 | [
"MIT"
] | null | null | null | 2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb | TheManohar/DSci_Pro | fd9631013929271bf2e295181be228a1f6b1a6d7 | [
"MIT"
] | null | null | null | 2_Data_Analysis/jogging_ex/pandas_jogging_ex.ipynb | TheManohar/DSci_Pro | fd9631013929271bf2e295181be228a1f6b1a6d7 | [
"MIT"
] | null | null | null | 52.778787 | 36,212 | 0.710392 | [
[
[
"# 1) CSV Data File Analysis",
"_____no_output_____"
]
],
[
[
"from os import path\nfname = path.expanduser('track.csv')",
"_____no_output_____"
]
],
[
[
"## CSV File Info",
"_____no_output_____"
]
],
[
[
"!ls -lh \"$fname\"",
"-rw-rw-r-- 1 manohar manohar 43K Feb 16 17:11 track.csv\n"
],
[
"path.getsize(fname)",
"_____no_output_____"
],
[
"path.getsize(fname) / (1<<10)",
"_____no_output_____"
],
[
"!head \"$fname\"",
"time,lat,lng,height\n2015-08-20 03:48:07.235,35.015021,32.519585,136.1999969482422\n2015-08-20 03:48:24.734,35.014954,32.519606,126.5999984741211\n2015-08-20 03:48:25.660,35.014871,32.519612,123.0\n2015-08-20 03:48:26.819,35.014824,32.519654,120.5\n2015-08-20 03:48:27.828,35.014776,32.519689,118.9000015258789\n2015-08-20 03:48:29.720,35.014704,32.519691,119.9000015258789\n2015-08-20 03:48:30.669,35.014657,32.519734,120.9000015258789\n2015-08-20 03:48:33.793,35.014563,32.519719,121.69999694824219\n2015-08-20 03:48:34.869,35.014549,32.519694,121.19999694824219\n"
],
[
"with open(fname) as fp:\n for lnum, line in enumerate(fp):\n if lnum > 10:\n break\n print(line[:-1])",
"time,lat,lng,height\n2015-08-20 03:48:07.235,35.015021,32.519585,136.1999969482422\n2015-08-20 03:48:24.734,35.014954,32.519606,126.5999984741211\n2015-08-20 03:48:25.660,35.014871,32.519612,123.0\n2015-08-20 03:48:26.819,35.014824,32.519654,120.5\n2015-08-20 03:48:27.828,35.014776,32.519689,118.9000015258789\n2015-08-20 03:48:29.720,35.014704,32.519691,119.9000015258789\n2015-08-20 03:48:30.669,35.014657,32.519734,120.9000015258789\n2015-08-20 03:48:33.793,35.014563,32.519719,121.69999694824219\n2015-08-20 03:48:34.869,35.014549,32.519694,121.19999694824219\n2015-08-20 03:48:37.708,35.014515,32.519625,121.69999694824219\n"
],
[
"!wc -l \"$fname\"",
"741 track.csv\n"
],
[
"with open(fname) as fp:\n print(sum(1 for line in fp))",
"741\n"
]
],
[
[
"# 2) Parse Time Series",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_csv(fname)",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 740 entries, 0 to 739\nData columns (total 4 columns):\ntime 740 non-null object\nlat 740 non-null float64\nlng 740 non-null float64\nheight 740 non-null float64\ndtypes: float64(3), object(1)\nmemory usage: 23.2+ KB\n"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"## Parse Dates",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(fname, parse_dates=['time'])",
"_____no_output_____"
],
[
"df.dtypes",
"_____no_output_____"
]
],
[
[
"# 3) Access Rows & Columns Data",
"_____no_output_____"
]
],
[
[
"df['lat'].head()",
"_____no_output_____"
],
[
"df.lat.head()",
"_____no_output_____"
],
[
"df[['lat', 'lng']].head()",
"_____no_output_____"
],
[
"df['lat'][0]",
"_____no_output_____"
],
[
"df.loc[0]",
"_____no_output_____"
],
[
"df.loc[2:7]",
"_____no_output_____"
],
[
"df[['lat', 'lng']][2:7]",
"_____no_output_____"
],
[
"df.index",
"_____no_output_____"
]
],
[
[
"## NumPy`.loc[]` example",
"_____no_output_____"
]
],
[
[
"import numpy as np\ndf1 = pd.DataFrame(np.arange(10).reshape((5,2)), columns=['x', 'y'], index=['a', 'b', 'c', 'd', 'e'])\ndf1",
"_____no_output_____"
],
[
"df1.loc['a']",
"_____no_output_____"
],
[
"df1.loc['b': 'd']",
"_____no_output_____"
]
],
[
[
"## Set Index",
"_____no_output_____"
]
],
[
[
"df.index",
"_____no_output_____"
],
[
"df.index = df['time']\ndf.index",
"_____no_output_____"
]
],
[
[
"## Locate Specific Time Data",
"_____no_output_____"
]
],
[
[
"df.loc['2015-08-20 04:18:54']",
"_____no_output_____"
],
[
"# all masures in this particular minute\ndf.loc['2015-08-20 03:48']",
"_____no_output_____"
]
],
[
[
"## Timezone Localization",
"_____no_output_____"
]
],
[
[
"# pytz module contains all timezone information\nimport pytz",
"_____no_output_____"
],
[
"ts = df.index[0]",
"_____no_output_____"
],
[
"ts.tz_localize(pytz.UTC)",
"_____no_output_____"
],
[
"ts.tz_localize(pytz.UTC).tz_convert(pytz.timezone('Asia/Jerusalem'))",
"_____no_output_____"
],
[
"df.index = df.index.tz_localize(pytz.UTC).tz_convert(pytz.timezone('Asia/Jerusalem'))\ndf.index[:10]",
"_____no_output_____"
],
[
"%pwd",
"_____no_output_____"
]
],
[
[
"# 4) Import Custom Modules",
"_____no_output_____"
]
],
[
[
"import geo",
"_____no_output_____"
],
[
"import sys\nsys.path",
"_____no_output_____"
],
[
"??geo",
"_____no_output_____"
],
[
"from geo import circle_dist",
"_____no_output_____"
],
[
"lat1, lng1 = df.iloc[0].lat, df.iloc[0].lng\nlat2, lng2 = df.iloc[1].lat, df.iloc[1].lng",
"_____no_output_____"
],
[
"circle_dist(lat1, lng1, lat2, lng2)",
"_____no_output_____"
]
],
[
[
"# 5) Calculate Speed (geo)",
"_____no_output_____"
],
[
"## pandas.`shift()` example",
"_____no_output_____"
]
],
[
[
"s = pd.Series(np.arange(5))\ns",
"_____no_output_____"
],
[
"s.shift()",
"_____no_output_____"
],
[
"s.shift(-1)",
"_____no_output_____"
]
],
[
[
"## Calculate Circle Distance of Data",
"_____no_output_____"
]
],
[
[
"dist = circle_dist(df['lat'], df['lng'], df['lat'].shift(), df['lng'].shift())",
"_____no_output_____"
],
[
"dist[:10]",
"_____no_output_____"
],
[
"dist.sum()",
"_____no_output_____"
],
[
"dt = df['time'] - df['time'].shift()\ndt[:10] # NaT means Not a Time",
"_____no_output_____"
],
[
"dt.sum()",
"_____no_output_____"
],
[
"dt[1].total_seconds()",
"_____no_output_____"
],
[
"dt[1] / np.timedelta64(1, 'h')",
"_____no_output_____"
],
[
"dt[1].total_seconds()/3600",
"_____no_output_____"
],
[
"speed = dist / (dt / np.timedelta64(1, 'h'))\nspeed[:10]",
"_____no_output_____"
],
[
"df['dist'] = dist\ndf['dt'] = dt",
"_____no_output_____"
],
[
"df1m = df.resample('1min').sum()",
"_____no_output_____"
],
[
"df1m.index",
"_____no_output_____"
],
[
"# gives error as dt is not indexed as time\n#speed = df1m['dist'] / (df1m['dt'])\ndf1m.columns",
"_____no_output_____"
],
[
"df['dt'] = dt / np.timedelta64(1, 'h')\ndf1m = df.resample('1min').sum()\nspeed1m = df1m['dist'] / df1m['dt']",
"_____no_output_____"
],
[
"speed1m[:10]",
"_____no_output_____"
]
],
[
[
"# 6) Display Speed Box Plot",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"speed1m.plot()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.rcParams['figure.figsize'] = (10, 6)",
"_____no_output_____"
],
[
"plt.style.available",
"_____no_output_____"
],
[
"plt.style.use('seaborn-whitegrid')",
"_____no_output_____"
],
[
"speed1m.plot()",
"_____no_output_____"
],
[
"speed1m.plot.box()",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"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"
]
] |
cb0622764d711d2adfcb1132fac85ff988eebd33 | 206,359 | ipynb | Jupyter Notebook | SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb | MTandHJ/digital-image-processing | 0f1b9215a8118d72fd9c96a36e1ed20da5702a54 | [
"MIT"
] | null | null | null | SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb | MTandHJ/digital-image-processing | 0f1b9215a8118d72fd9c96a36e1ed20da5702a54 | [
"MIT"
] | null | null | null | SMOOTHING (LOWPASS) SPATIAL FILTERS.ipynb | MTandHJ/digital-image-processing | 0f1b9215a8118d72fd9c96a36e1ed20da5702a54 | [
"MIT"
] | null | null | null | 721.534965 | 68,364 | 0.949917 | [
[
[
"# SMOOTHING (LOWPASS) SPATIAL FILTERS",
"_____no_output_____"
]
],
[
[
"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"## FILTERS\n\n\n\nfilters实际上就是通过一些特殊的kernel $w$ 对图片进行如下操作:\n$$\ng(x, y) = \\sum_{s=-a}^a \\sum_{t=-b}^b w(s, t) f(x+s, y+t), \\: x = 1,2,\\cdots, M, \\: y = 1, 2,\\cdots N.\n$$\n其中$w(s, t) \\in \\mathbb{R}^{m \\times n}, m=2a+1, n = 2b+1$.\n\n注: 一般来说kernel的边是奇数, 这样可以确定唯一的中心, 但是偶数其实也是可以的.\n\n实际上, 上面可以转换成卷积的形式:\n$$\n(w * f) (x, y) = \\sum_{s=-a}^a \\sum_{t=-b}^b w'(s, t) f(x-s, y-t), \\: x = 1,2,\\cdots, M, \\: y = 1, 2,\\cdots N.\n$$\n只是$w'(s, t) = w(-s, -t)$, 不过下面我们仅考虑卷积操作, 故直接定义为:\n$$\n(w * f) (x, y) = \\sum_{s=-a}^a \\sum_{t=-b}^b w(s, t) f(x-s, y-t), \\: x = 1,2,\\cdots, M, \\: y = 1, 2,\\cdots N.\n$$\n即可.\n\n注: 注意到上面会出现$f(-1, -1)$之类的未定义情况, 常见的处理方式是在图片周围加padding(分别为pad a, b), 比如补0或者镜像补.\n\n用卷积的目的是其特别的性质:\n\n1. $f * g = g * f$;\n2. $f * (g * h) = (f * g) * h$;\n3. $f * (g + h) = (f * g) + (g * h)$.\n\n注: $f, g, h$应当形状一致.\n\n\n\n特别的, 如果\n$$\nw = uv^T,\n$$\n则\n$$\nw * f = u' * (v^T * f), \\quad u'(x) = u(-x).\n$$\n可以显著降低计算量.\n\n",
"_____no_output_____"
],
[
"## Box Filter Kernels\n\n即\n$$\nw_{ij} = \\frac{1}{mn}, \\quad i=1,2,\\cdots, m, \\: j=1,2,\\cdots, n.\n$$",
"_____no_output_____"
]
],
[
[
"img = cv2.imread(\"./pics/alphabeta.png\")\nimg.shape",
"_____no_output_____"
],
[
"img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 由于是截图, 先转成灰度图\nplt.imshow(img, cmap='gray')",
"_____no_output_____"
],
[
"# 或者等价地用 cv2.blur(img, (m, n))\nkernels = [np.ones((i, i)) / (i * i) for i in [3, 11, 21]]\nimgs_smoothed = [cv2.filter2D(img, -1, kernel) for kernel in kernels]\nfig, axes = plt.subplots(2, 2)\naxes[0, 0].imshow(img, cmap='gray')\naxes[0, 0].set_title(\"raw\")\naxes[0, 1].imshow(imgs_smoothed[0], cmap=\"gray\")\naxes[0, 1].set_title(\"3x3\")\naxes[1, 0].imshow(imgs_smoothed[1], cmap=\"gray\")\naxes[1, 0].set_title(\"11x11\")\naxes[1, 1].imshow(imgs_smoothed[2], cmap=\"gray\")\naxes[1, 1].set_title(\"21x21\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Lowpass Gaussian Filter Kernels\n\n\n\n即\n$$\nw(s, t) = G(s, t) = K e^{-\\frac{s^2+t^2}{2\\sigma^2}},\n$$\n高斯分布的特点是绝大部分集中于$(-3\\sigma, +3\\sigma)$之间, 故一般$w$的大小选择为$(-6\\sigma, +6\\sigma)$, 需要注意的是, $\\sigma$的选择和图片的大小息息相关.\n\n",
"_____no_output_____"
]
],
[
[
"imgs_smoothed = [cv2.GaussianBlur(img, ksize=ksize, sigmaX=sigma) for (ksize, sigma) in [((5, 5), 1), ((21, 21), 3.5), ((43, 43), 7)]]\nfig, axes = plt.subplots(1, 4)\naxes[0].imshow(img, cmap='gray')\naxes[0].set_title(\"raw\")\naxes[1].imshow(imgs_smoothed[0], cmap=\"gray\")\naxes[1].set_title(\"5x5, 1\")\naxes[2].imshow(imgs_smoothed[1], cmap=\"gray\")\naxes[2].set_title(\"21x21, 3.5\")\naxes[3].imshow(imgs_smoothed[2], cmap=\"gray\")\naxes[3].set_title(\"43x43, 7\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Order-Statistic (Nonlinear) Filters\n\n即$g(x, y)$由$(x, y)$周围的点的一个某个顺序的值代替, 比如median.",
"_____no_output_____"
]
],
[
[
"imgs_smoothed = [cv2.medianBlur(img, ksize=ksize) for ksize in [3, 7, 15]]\nfig, axes = plt.subplots(1, 4)\naxes[0].imshow(img, cmap='gray')\naxes[0].set_title(\"raw\")\naxes[1].imshow(imgs_smoothed[0], cmap=\"gray\")\naxes[1].set_title(\"3x3\")\naxes[2].imshow(imgs_smoothed[1], cmap=\"gray\")\naxes[2].set_title(\"7x7\")\naxes[3].imshow(imgs_smoothed[2], cmap=\"gray\")\naxes[3].set_title(\"15x15\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb062c74b4ad13f7c21f1b81feb1585fa6e8c7a3 | 8,063 | ipynb | Jupyter Notebook | colabs/colabs-pyrosetta.ipynb | matteoferla/pyrosetta_scripts | 160a095db15256a75b9bf45ab51606d083a3591c | [
"MIT"
] | 1 | 2021-04-07T23:50:48.000Z | 2021-04-07T23:50:48.000Z | colabs/colabs-pyrosetta.ipynb | matteoferla/pyrosetta_scripts | 160a095db15256a75b9bf45ab51606d083a3591c | [
"MIT"
] | null | null | null | colabs/colabs-pyrosetta.ipynb | matteoferla/pyrosetta_scripts | 160a095db15256a75b9bf45ab51606d083a3591c | [
"MIT"
] | 1 | 2021-04-07T08:56:25.000Z | 2021-04-07T08:56:25.000Z | 32.776423 | 269 | 0.575344 | [
[
[
"#@title blank template\n#@markdown This notebook from [github.com/matteoferla/pyrosetta_help](https://github.com/matteoferla/pyrosetta_help).\n\n#@markdown It can be opened in Colabs via [https://colab.research.google.com/github/matteoferla/pyrosetta_help/blob/main/colabs/colabs-pyrosetta.ipynb](https://colab.research.google.com/github/matteoferla/pyrosetta_help/blob/main/colabs/colabs-pyrosetta.ipynb)\n\n#@markdown It just for loading up PyRosetta",
"_____no_output_____"
],
[
"#@title Installation\n#@markdown Installing PyRosetta with optional backup to your drive (way quicker next time!).\n#@markdown Note that PyRosetta occupies some 10 GB, so you'll need to be on the 100 GB plan of Google Drive (it's one pound a month).\n\n#@markdown The following is not the real password. However, the format is similar.\nusername = 'boltzmann' #@param {type:\"string\"}\npassword = 'constant' #@param {type:\"string\"}\n#@markdown Release to install:\n_release = 'release-295' #@param {type:\"string\"}\n#@markdown Use Google Drive for PyRosetta (way faster next time, but takes up space)\n#@markdown (NB. You may be prompted to follow a link and possibly authenticate and then copy a code into a box\nuse_drive = True #@param {type:\"boolean\"}\n#@markdown Installing `rdkit` and `rdkit_to_params` allows the creation of custom topologies (params) for new ligands\ninstall_rdkit = True #@param {type:\"boolean\"}\n\n\nimport sys\nimport platform\nimport os\nassert platform.dist()[0] == 'Ubuntu'\npy_version = str(sys.version_info.major) + str(sys.version_info.minor)\nif use_drive:\n from google.colab import drive\n drive.mount('/content/drive')\n _path = '/content/drive/MyDrive'\n os.chdir(_path)\nelse:\n _path = '/content'\nif not any(['PyRosetta4.Release' in filename for filename in os.listdir()]):\n assert not os.system(f'curl -u {username}:{password} https://graylab.jhu.edu/download/PyRosetta4/archive/release/PyRosetta4.Release.python{py_version}.ubuntu/PyRosetta4.Release.python{py_version}.ubuntu.{_release}.tar.bz2 -o /content/a.tar.bz2')\n assert not os.system('tar -xf /content/a.tar.bz2')\nassert not os.system(f'pip3 install -e {_path}/PyRosetta4.Release.python{py_version}.ubuntu.{_release}/setup/')\nassert not os.system(f'pip3 install pyrosetta-help biopython')\nif install_rdkit:\n assert not os.system(f'pip3 install rdkit-pypi rdkit-to-params')\n\nimport site\nsite.main()",
"_____no_output_____"
],
[
"#@title Start PyRosetta\nimport pyrosetta\nimport pyrosetta_help as ph\n\nno_optH = False #@param {type:\"boolean\"}\nignore_unrecognized_res=False #@param {type:\"boolean\"}\nload_PDB_components=False #@param {type:\"boolean\"}\nignore_waters=False #@param {type:\"boolean\"}\n\n\nextra_options= ph.make_option_string(no_optH=no_optH,\n ex1=None,\n ex2=None,\n mute='all',\n ignore_unrecognized_res=ignore_unrecognized_res,\n load_PDB_components=load_PDB_components,\n ignore_waters=ignore_waters)\n\n\n# capture to log\nlogger = ph.configure_logger()\npyrosetta.init(extra_options=extra_options)",
"_____no_output_____"
],
[
"## Usual stuff\npose = ph.pose_from_alphafold2('P02144')\n\nscorefxn = pyrosetta.get_fa_scorefxn()\nrelax = pyrosetta.rosetta.protocols.relax.FastRelax(scorefxn, 3)\nmovemap = pyrosetta.MoveMap()\nmovemap.set_bb(False)\nmovemap.set_chi(True)\nrelax.apply(pose)",
"_____no_output_____"
],
[
"# Note that nglview does not work with Colabs but py3Dmol does.\n# install py3Dmol\nos.system(f'pip3 install py3Dmol')\nimport site\nsite.main()\n# run\nimport py3Dmol\nview = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js',)\nview.addModel(ph.get_pdbstr(pose),'pdb')\nview.zoomTo()\nview",
"_____no_output_____"
],
[
"# Also note that RDKit Chem.Mol instances are not displays as representations by default.",
"_____no_output_____"
],
[
"#@title Upload to Michelanglo (optional)\n#@markdown [Michelanglo](https://michelanglo.sgc.ox.ac.uk/) is a website that\n#@markdown allows the creation, annotation and sharing of a webpage with an interactive protein viewport.\n#@markdown ([examples](https://michelanglo.sgc.ox.ac.uk/gallery)).\n#@markdown The created pages are private —they have a 1 in a quintillion change to be guessed within 5 tries.\n\n#@markdown Registered users (optional) can add interactive annotations to pages.\n#@markdown A page created by a guest is editable by registered users with the URL to it\n#@markdown (this can be altered in the page settings).\n#@markdown Leave blank for guest (it will not add an interactive description):\n\nusername = '' #@param {type:\"string\"}\npassword = '' #@param {type:\"string\"}\n\nimport os\nassert not os.system(f'pip3 install michelanglo-api')\nimport site\nsite.main()\nfrom michelanglo_api import MikeAPI, Prolink\nif not username:\n mike = MikeAPI.guest_login()\nelse:\n mike = MikeAPI(username, password)\n \npage = mike.convert_pdb(pdbblock=ph.get_pdbstr(pose),\n data_selection='ligand',\n data_focus='residue',\n )\nif username:\n page.retrieve()\n page.description = '## Description\\n\\n'\n page.description += 'autogen bla bla'\n page.commit()\npage.show_link()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb063e0349e53fc67fc0cb60258b0c6553fc2f71 | 116,712 | ipynb | Jupyter Notebook | Code/108_D_end_street density_analysis.ipynb | Rise-group/database_cyclists_medellin | e04f7d5275d3013cd039fb53d96e4193d4a8ea72 | [
"MIT"
] | null | null | null | Code/108_D_end_street density_analysis.ipynb | Rise-group/database_cyclists_medellin | e04f7d5275d3013cd039fb53d96e4193d4a8ea72 | [
"MIT"
] | null | null | null | Code/108_D_end_street density_analysis.ipynb | Rise-group/database_cyclists_medellin | e04f7d5275d3013cd039fb53d96e4193d4a8ea72 | [
"MIT"
] | null | null | null | 86.581602 | 56,136 | 0.795077 | [
[
[
"# Destination's street density INDEX ",
"_____no_output_____"
],
[
"This code allows you to estimate:\nThe street density INDEX at the DESTINATION for only one origin point or for a set of origins. The street density is estimated base on a selection of arcs contained within a 600m buffer around each destination. All the arcs selected in relation to each destination are assumed to be previously estimated. ",
"_____no_output_____"
],
[
"## Importing libraries",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport csv\nimport math\n\nprint (\"it works\")",
"it works\n"
]
],
[
[
"### Example for only one route",
"_____no_output_____"
]
],
[
[
"route = 1002\ndb = gpd.read_file('../Shapes/end_arcs600/R' +\"%s\" % (route) +'_end_arcs600.shp')\nprint (db.crs)\ndb.head()",
"{'init': 'epsg:3116'}\n"
],
[
"db.info()",
"<class 'geopandas.geodataframe.GeoDataFrame'>\nRangeIndex: 307 entries, 0 to 306\nData columns (total 46 columns):\nOBJECTID 307 non-null int64\nbridge 13 non-null object\nfrom_ 304 non-null object\nhighway 307 non-null object\nname 227 non-null object\noneway 302 non-null object\nosmid 302 non-null object\nto 304 non-null object\nID_PhD 307 non-null object\nCyclypath 307 non-null int64\nPed_path 307 non-null int64\nX_from 307 non-null float64\nY_from 307 non-null float64\nZ_from 307 non-null float64\nX_to 307 non-null float64\nY_to 307 non-null float64\nZ_to 307 non-null float64\nslope 307 non-null float64\nspeed 307 non-null float64\nv_80 307 non-null float64\nv_60 307 non-null float64\nv_40 307 non-null float64\nv_30 307 non-null float64\nv_5 307 non-null float64\nLong 307 non-null float64\nCycle_long 307 non-null float64\nPed_long 307 non-null float64\nruta 307 non-null int64\nHeri_tot 307 non-null float64\nk30_tot 307 non-null float64\nPheri 307 non-null float64\nPz30 307 non-null float64\nN_rutas 307 non-null int64\nfrecuencia 307 non-null int64\np_acc 307 non-null float64\nN_Heri 307 non-null float64\nvc80 307 non-null int64\nvc60 307 non-null int64\nvc40 307 non-null float64\nvc30 307 non-null int64\nvc5 307 non-null int64\nHle 307 non-null float64\nLle 307 non-null int64\nbnocycle 307 non-null int64\nbcycle 307 non-null int64\ngeometry 307 non-null object\ndtypes: float64(24), int64(13), object(9)\nmemory usage: 110.4+ KB\n"
],
[
"db.plot()",
"_____no_output_____"
],
[
"radio = 0.6\narea = 3.14159265358979 * radio**2\nD_Lstreet = (db['Long']).sum()/1000\nD_streetdens = D_Lstreet / area ",
"_____no_output_____"
],
[
"print (\"D_Lstreet:\" + str(D_Lstreet))\nprint (\"D_streetdens:\" + str(D_streetdens))",
"D_Lstreet:24.733079128306873\nD_streetdens:21.868843339739048\n"
],
[
"results = pd.DataFrame ({\n \"route\":[route],\n \"D_Lstreet\":[D_Lstreet],\n \"D_streetdens\":[D_streetdens]})\nresults.to_csv('../Tables/OUT/R' +\"%s\" %(route)+'_end_sd600.txt',index=False, header=True)",
"_____no_output_____"
]
],
[
[
"## Street density estimated for All routes ",
"_____no_output_____"
],
[
"The code requires the list of the origin points associated to all the routes. This list is located in the Tables folder. If you move this file out of this folder, please modify the code. ",
"_____no_output_____"
]
],
[
[
"routes = np.loadtxt('../Tables/Routes.txt',dtype='str')",
"_____no_output_____"
],
[
"for i in routes:\n db = gpd.read_file('../Shapes/end_arcs600/R' +\"%s\" % (i) +'_end_arcs600.shp')\n radio = 0.6\n area = 3.14159265358979 * radio**2\n D_Lstreet = (db['Long']).sum()/1000\n D_streetdens = D_Lstreet / area \n results = pd.DataFrame ({\n \"route\":[i],\n \"D_Lstreet\":[D_Lstreet],\n \"D_sttdens\":[D_streetdens]})\n results.to_csv('../Tables/OUT/R' +\"%s\" %(i)+'_end_sd600.txt',index=False, header=True)",
"_____no_output_____"
]
],
[
[
"This part of the code summarizes the intersection index related to each origin in only one table. Please copy it to a text file and save. ",
"_____no_output_____"
]
],
[
[
"print ('route,D_Lstreet,D_sttdens')\nfor i in routes:\n df=np.loadtxt('../Tables/OUT/R' +\"%s\" %(i)+'_end_sd600.txt', delimiter=',',skiprows=1)\n print ((df[0]),(df[1]),(df[2])) ",
"route,D_Lstreet,D_sttdens\n1002.0 24.733079128306873 21.868843339739048\n1006.0 26.1401686196655 23.112983605974527\n1009.0 16.660137417108547 14.73079568068372\n1050.0 16.93572274099809 14.974466605909287\n1052.0 21.618809667095352 19.11522456822823\n1079.0 25.1494328077544 22.236980818397786\n1100.0 24.85527662835564 21.97688965177368\n1101.0 22.88048809032435 20.230793221835356\n1102.0 19.04886329847957 16.842893079082295\n1104.0 25.00274107677708 22.107276851199188\n1124.0 23.94542405120202 21.17240334544646\n1128.0 22.76605491077984 20.12961207640074\n1132.0 16.38779888039773 14.489995545617386\n1134.0 19.04886329847957 16.842893079082295\n1137.0 21.781874579723812 19.259405606504156\n1147.0 23.98631574145481 21.208559537863763\n1151.0 28.39254197813488 25.10451890424617\n1381.0 17.30280133504041 15.299035343381833\n1392.0 28.168837937217226 24.906721104792414\n1397.0 11.756419919256619 10.39495746229841\n1398.0 25.564096838356782 22.603624319468775\n1399.0 24.35361897226257 21.53332689784531\n1401.0 22.270693237328967 19.69161619335641\n1404.0 19.04886329847957 16.842893079082295\n1408.0 28.168837937217226 24.906721104792414\n1409.0 19.04886329847957 16.842893079082295\n1413.0 28.10276782948937 24.84830230348407\n1415.0 28.75633806592159 25.426185268961436\n1419.0 18.855683578897867 16.67208470532377\n1421.0 19.850414846638827 17.55162025148511\n1423.0 19.04886329847957 16.842893079082295\n2001.0 27.07614170932684 23.940565516088952\n2019.0 22.45432420447866 19.85398161628207\n3001.0 25.62762621095561 22.659796617694496\n3002.0 26.683628967797944 23.593508054750753\n3003.0 26.683241775188108 23.593165701318622\n3004.0 26.683628967797944 23.593508054750753\n3006.0 22.409502293563726 19.814350345832423\n3009.0 20.285190315533182 17.936046168205294\n3012.0 12.0268688241122 10.634086795973717\n3013.0 14.058440943309499 12.430390934962205\n3015.0 18.11341441227823 16.01577466658923\n3016.0 18.11341441227823 16.01577466658923\n3018.0 23.47671736081707 20.75797564191864\n3019.0 22.176317693057317 19.608169891257404\n3024.0 19.04886329847957 16.842893079082295\n3025.0 27.037366460651878 23.906280668887632\n3026.0 19.04886329847957 16.842893079082295\n3028.0 20.104296741300992 17.776101132024106\n3029.0 26.683628967797944 23.593508054750753\n3030.0 23.440013758285293 20.72552253207302\n3032.0 19.04886329847957 16.842893079082295\n3033.0 19.04886329847957 16.842893079082295\n3034.0 19.704951335317762 17.423002268894827\n3035.0 10.94972106620695 9.68167907313498\n3036.0 23.00411488770819 20.340103310181238\n3037.0 22.595850650585696 19.979118468927425\n3038.0 22.92986692812064 20.27445370027654\n3039.0 14.527105138557552 12.844781064539498\n3040.0 14.527105138557552 12.844781064539498\n3041.0 27.430559927539406 24.253940023590907\n3042.0 22.193769449731555 19.62360063203708\n3043.0 18.17689818793373 16.071906648265394\n3044.0 18.72715026143572 16.55843630073432\n3045.0 26.40488923274824 23.347048017699166\n3046.0 22.185707089117642 19.616471940122114\n4001.0 26.58345161540401 23.50493182797657\n4003.0 25.398885415691197 22.457545349621704\n4004.0 14.058440943309499 12.430390934962205\n4006.0 19.04886329847957 16.842893079082295\n4007.0 16.338930261095527 14.44678619937282\n4009.0 19.04886329847957 16.842893079082295\n4010.0 12.0268688241122 10.634086795973717\n4011.0 16.338930261095527 14.44678619937282\n4012.0 28.10276782948937 24.84830230348407\n4013.0 16.46214268507594 14.55572990118847\n4014.0 20.285190315533182 17.936046168205294\n4016.0 18.39381452767265 16.263702802192338\n4017.0 24.59134506605332 21.743522914116006\n4018.0 16.338930261095527 14.44678619937282\n4019.0 23.64470162217385 20.906506339455156\n4020.0 25.275395213445453 22.34835603789488\n4021.0 16.74986654592629 14.810133649520795\n4022.0 28.10195264422567 24.847581521460434\n4024.0 23.16575857454856 20.483027708960364\n4025.0 20.729539741640117 18.328937321677326\n4026.0 25.26327346769357 22.33763806147646\n4027.0 19.04886329847957 16.842893079082295\n4028.0 22.15708297428844 19.591162665862683\n4029.0 25.846836388619792 22.853620969646204\n4030.0 22.17689940600588 19.60868423843087\n4031.0 27.037366460651878 23.906280668887632\n4032.0 23.103481799826653 20.427962950422522\n4033.0 25.47487399672036 22.524734006784648\n4034.0 28.06714459947517 24.816804452674848\n4035.0 16.309863569809796 14.421085601609208\n4036.0 26.282928671329643 23.239211205410097\n4037.0 27.130059412577648 23.988239232714108\n4038.0 25.7607946119344 22.777543335913485\n4039.0 28.10195264422567 24.847581521460434\n4040.0 22.55008068344816 19.938648932732466\n4041.0 22.909473645222782 20.25642207928173\n4042.0 14.302438313495749 12.646131976998676\n4043.0 19.982537082613398 17.668441956750147\n4044.0 12.52330459383102 11.073032388631384\n5001.0 19.04886329847957 16.842893079082295\n5002.0 23.74211350336401 20.992637352829014\n5003.0 26.80102487527106 23.697308826823562\n5006.0 22.61414966130405 19.995298346758076\n5007.0 26.03546694296914 23.020406998217666\n5008.0 26.63367721215127 23.54934100571027\n5009.0 18.6096895062181 16.45457819066659\n5010.0 26.150742927090004 23.12233334650999\n5011.0 14.48856813142455 12.810706869110694\n5013.0 9.91611953558741 8.767774668771374\n5014.0 27.64517808104431 24.44370413474402\n5018.0 18.541063451416214 16.39389943596317\n5022.0 19.04886329847957 16.842893079082295\n5023.0 16.75714092194396 14.816565610082579\n5028.0 21.618809667095352 19.11522456822823\n5029.0 26.1611002391073 23.131491220980532\n5032.0 25.47859943058027 22.52802801352891\n5033.0 22.61414966130405 19.995298346758076\n5035.0 22.81413153223502 20.17212114279935\n5036.0 21.717462322828652 19.20245266716766\n5037.0 22.61414966130405 19.995298346758076\n5038.0 22.744035300782677 20.11014246653405\n5039.0 24.48977781132737 21.65371774386096\n5040.0 21.399396680753117 18.92122089403422\n5042.0 25.88586488451137 22.888129736549462\n5043.0 26.683628967797944 23.593508054750753\n5044.0 24.878527364086867 21.997447815785613\n5049.0 25.36905788174714 22.431172019247047\n5052.0 20.805079375392648 18.395729022294365\n5053.0 19.04886329847957 16.842893079082295\n5054.0 22.15708297428844 19.591162665862683\n5055.0 18.39381452767265 16.263702802192338\n5056.0 26.683628967797944 23.593508054750753\n5061.0 27.130059412577648 23.988239232714108\n5063.0 24.05825164188492 21.2721648386372\n5064.0 19.04886329847957 16.842893079082295\n5065.0 25.693627538605 22.71815460406132\n5067.0 27.430559927539406 24.253940023590907\n5068.0 19.04886329847957 16.842893079082295\n5071.0 25.86300822052091 22.86792000845684\n5074.0 14.22699052167549 12.579421482478883\n5075.0 20.422257214762407 18.057239915686463\n5077.0 25.541840022394258 22.583944973480314\n5080.0 25.03475011806755 22.13557905756036\n5081.0 17.40559350433719 15.389923575908064\n5086.0 23.766112844050898 21.01385742894715\n5088.0 25.98702155007077 22.977571866274307\n5089.0 23.00411488770819 20.340103310181238\n5090.0 28.346017730808942 25.063382437937545\n5091.0 25.214673127760882 22.294665926275165\n5092.0 18.97858694172955 16.78075513708643\n5093.0 23.103481799826653 20.427962950422522\n5104.0 26.683628967797944 23.593508054750753\n5105.0 27.130059412577648 23.988239232714108\n5106.0 24.2800922602586 21.46831501081905\n5109.0 24.61006141086955 21.76007179630554\n5111.0 26.52834005175299 23.456202506995552\n5112.0 13.194749721059768 11.66672022759484\n5114.0 26.313794647089992 23.26650271994129\n5116.0 20.20935852308154 17.868996142581977\n5118.0 20.41778803235301 18.053288290841824\n5119.0 17.34290373585256 15.334493650710199\n5120.0 20.41778803235301 18.053288290841824\n5121.0 20.41778803235301 18.053288290841824\n5122.0 28.26854614958121 24.99488252070677\n5123.0 19.04886329847957 16.842893079082295\n5126.0 21.399396680753117 18.92122089403422\n5128.0 11.138940428055092 9.848985721839567\n5131.0 26.544057758353947 23.470100010882273\n5132.0 18.85204446458529 16.668867021816418\n5133.0 21.68585244087578 19.174503395149042\n5134.0 8.835254227711507 7.8120799100769664\n5135.0 26.683628967797944 23.593508054750753\n5143.0 23.03207977620416 20.364829700387613\n5147.0 21.89094312398764 19.355843372923186\n5148.0 14.527105138557552 12.844781064539498\n5149.0 26.683628967797944 23.593508054750753\n5153.0 20.104296741300992 17.776101132024106\n5155.0 12.083747587228077 10.684378664345077\n5156.0 12.0268688241122 10.634086795973717\n5158.0 28.10276782948937 24.84830230348407\n5160.0 26.683628967797944 23.593508054750753\n5165.0 21.05221620516842 18.61424595606589\n5166.0 22.916234874052428 20.262400318112917\n5167.0 28.06714459947517 24.816804452674848\n5170.0 21.399396680753117 18.92122089403422\n5171.0 26.96169183434047 23.839369608642674\n5174.0 22.61414966130405 19.995298346758076\n5177.0 25.379195907882355 22.44013600242824\n5179.0 12.690385875471591 11.220764676804864\n5180.0 23.50270110750276 20.780950318169058\n5181.0 23.264520217593383 20.570352173840703\n5182.0 28.168837937217226 24.906721104792414\n5183.0 19.59414616365768 17.325028986729002\n5187.0 24.54381771388823 21.701499508398545\n5190.0 28.26854614958121 24.99488252070677\n5191.0 13.88364531539244 12.275837667107474\n5192.0 21.618809667095352 19.11522456822823\n5193.0 16.746353846352488 14.807027741183196\n5194.0 22.61414966130405 19.995298346758076\n5195.0 17.051674969154828 15.076990885207419\n5196.0 28.10276782948937 24.84830230348407\n5197.0 18.11341441227823 16.01577466658923\n5198.0 17.16833777078977 15.180143449402697\n5199.0 26.095716656576368 23.07367944122023\n5201.0 22.17689940600588 19.60868423843087\n5202.0 16.309863569809796 14.421085601609208\n5203.0 28.26854614958121 24.99488252070677\n5207.0 20.67569745005355 18.281330283602898\n5209.0 16.309863569809796 14.421085601609208\n5213.0 21.399396680753117 18.92122089403422\n5215.0 20.285190315533182 17.936046168205294\n5218.0 23.965157191952223 21.189851272630477\n5220.0 22.61414966130405 19.995298346758076\n5221.0 27.07221018048744 23.937089281373957\n5223.0 26.683628967797944 23.593508054750753\n5227.0 19.41926268964948 17.17039804587629\n5228.0 25.69637187657098 22.72058113157688\n5229.0 18.369494876809778 16.242199509697368\n5230.0 15.91049238336718 14.067963943549112\n5231.0 19.43010847989732 17.179987829930077\n5234.0 26.683628967797944 23.593508054750753\n5236.0 22.61414966130405 19.995298346758076\n5238.0 15.179988127627642 13.422056369934591\n5241.0 25.379195907882355 22.44013600242824\n5243.0 19.04886329847957 16.842893079082295\n5244.0 21.18554194138707 18.732131789180134\n5248.0 21.399396680753117 18.92122089403422\n5251.0 20.29606722853966 17.945663470819525\n5252.0 20.187929424823 17.85004865972726\n5255.0 23.304408531185 20.605621186505736\n5256.0 19.410990622388027 17.16308393257491\n5259.0 23.475059283677872 20.756509579847915\n5260.0 18.8553099887675 16.671754379124113\n5261.0 21.371678664584948 18.896712786890525\n5262.0 26.23939536324886 23.200719310020105\n5264.0 12.0268688241122 10.634086795973717\n5267.0 19.51128033926583 17.251759511365957\n5270.0 25.379195907882355 22.44013600242824\n5275.0 25.541840022394258 22.583944973480314\n5276.0 26.05574978213162 23.038340965510148\n5277.0 27.653324881898044 24.450907488223226\n5280.0 24.756237847227123 21.88932014302701\n5281.0 17.71745249808087 15.665667467030126\n5283.0 20.285190315533182 17.936046168205294\n5293.0 16.66893647651208 14.738575757342783\n5295.0 17.849664995994246 15.782568981371462\n5297.0 15.96998680407675 14.12056856100643\n5302.0 22.05319096845598 19.49930196432953\n5303.0 19.04886329847957 16.842893079082295\n5304.0 25.19988002413384 22.281585950908973\n5305.0 19.04886329847957 16.842893079082295\n5306.0 11.3247366281517 10.013265631023268\n5307.0 22.61414966130405 19.995298346758076\n5309.0 19.71354744768318 17.430602900974435\n5310.0 19.04886329847957 16.842893079082295\n5311.0 19.04886329847957 16.842893079082295\n5316.0 22.61414966130405 19.995298346758076\n5317.0 20.104296741300992 17.776101132024106\n5318.0 21.18554194138707 18.732131789180134\n5319.0 18.25338608806736 16.139536800448653\n5320.0 17.994024215871644 15.910210555951338\n5322.0 21.18554194138707 18.732131789180134\n5323.0 19.04886329847957 16.842893079082295\n5324.0 19.04886329847957 16.842893079082295\n5325.0 22.37452374141235 19.78342251540415\n5326.0 19.04886329847957 16.842893079082295\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb064c4431280c488c728e15d6b51a7fd77bc5af | 1,520 | ipynb | Jupyter Notebook | solutions/15.ipynb | egnha/AoC-2020 | bf52430e59ff4a6346c65dea41fcb663b5c76036 | [
"MIT"
] | null | null | null | solutions/15.ipynb | egnha/AoC-2020 | bf52430e59ff4a6346c65dea41fcb663b5c76036 | [
"MIT"
] | null | null | null | solutions/15.ipynb | egnha/AoC-2020 | bf52430e59ff4a6346c65dea41fcb663b5c76036 | [
"MIT"
] | null | null | null | 18.765432 | 79 | 0.490132 | [
[
[
"# [Day 15](https://adventofcode.com/2020/day/15): Rambunctious Recitation",
"_____no_output_____"
]
],
[
[
"data = 0, 20, 7, 16, 1, 18, 15\ninit = {d: i for i, d in enumerate(data, 1)}\n\ndef number_spoken(turns, n=data[-1], l=len(data)):\n prev = init.copy()\n for i in range(l, turns):\n prev[n], n = i, i - prev.get(n, i)\n return n",
"_____no_output_____"
]
],
[
[
"## Part 1",
"_____no_output_____"
]
],
[
[
"assert 1025 == number_spoken(2020)",
"_____no_output_____"
]
],
[
[
"## Part 2",
"_____no_output_____"
]
],
[
[
"assert 129262 == number_spoken(30000000)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb066cea1204614e0b34b440dd2f0e7a2e9ef1e6 | 32,448 | ipynb | Jupyter Notebook | lab03.ipynb | mocurin/dt-lab-03 | 575a547ac349fc1dce020ab4964025f90f199644 | [
"MIT"
] | null | null | null | lab03.ipynb | mocurin/dt-lab-03 | 575a547ac349fc1dce020ab4964025f90f199644 | [
"MIT"
] | null | null | null | lab03.ipynb | mocurin/dt-lab-03 | 575a547ac349fc1dce020ab4964025f90f199644 | [
"MIT"
] | null | null | null | 31.811765 | 6,210 | 0.388468 | [
[
[
"from simplexlib.src.table import Table, V, Format, Simplex, pretty_value\nfrom IPython.display import display_markdown\n\nfrom src.branch_and_bound import BranchAndBound\n\nsource = Table.straight(\n [2, 5, 3],\n V[2, 1, 2] <= 6,\n V[1, 2, 0] <= 6,\n V[0, 0.5, 1] <= 2,\n) >> min\n\n\ndisplay_markdown(\n \"### Исходная задача в канонической форме\",\n f\"${Format(source).target()}$\",\n Format(source).system(),\n f\"${Format(source).var_zero_constraint()}$\",\n raw=True\n)",
"_____no_output_____"
],
[
"sresult = Simplex.resolve(source >> max)\n\ndisplay_markdown(\n \"### Решение исходной ЦЛП simplex-методом:\",\n \"#### Исходная таблица:\",\n Format(source).table(),\n raw=True,\n)\n\nfor table, pos in zip(sresult.history, sresult.solvers):\n display_markdown(\n f\"#### Индекс разрешающего элемента: {pos}\",\n Format(table).table(),\n f\"{Format(table).base_vars()}, {Format(table).free_vars()}\",\n raw=True,\n )\n\ndisplay_markdown(\n \"#### Проверка решения\",\n Format(table).check(sresult.source.c * -1),\n raw=True\n)",
"_____no_output_____"
],
[
"from src.brute_force import BruteForce\n\nbresult = BruteForce.resolve(source >> min, sresult.result.F)\n\n\ndisplay_markdown(\n \"### Решение методом полного перебора\",\n \"Организуем полный перебор возможных значений исходных переменных. Полученные целочисленные решения:\",\n '\\n\\n'.join(f\"$F={pretty_value(key, 2)}, X={value}$\" for key, value in bresult.result.items()),\n f\"Максимальное значение функции $F={bresult.maximum}$ достигается при $X={bresult.maxset}$\",\n raw=True,\n)",
"_____no_output_____"
],
[
"tree = BranchAndBound.resolve(source >> max)\n\n\ndisplay_markdown(\n \"### Графическая визуализация решения при помощи метода ветвей и границ:\",\n raw=True\n)\n\ntree.visualize(\n node_attr={\"shape\": \"record\", \"fontname\": \"helvetica\"},\n graph_attr={},\n edge_attr={\"fontname\": \"helvetica\"},\n)",
"_____no_output_____"
],
[
"def expose_node(node):\n result = node.data\n\n display_markdown(\n f\"#### Исходная таблица\",\n Format(result.source).table(),\n f\"#### Конечная таблица\",\n Format(result.history[-1]).table(),\n f\"{Format(result.history[-1]).base_vars()}, {Format(table).free_vars()}\" if result.solved else \"Нет решений\",\n raw=True,\n )\n \n if node.left:\n display_markdown(\n f\"### Ветвление влево по {node.left.label(pretty=True)}\",\n raw=True,\n )\n\n expose_node(node.left.target)\n \n if node.right:\n display_markdown(\n f\"### Ветвление вправо по {node.right.label(pretty=True)}\",\n raw=True,\n )\n\n expose_node(node.right.target)\n \n if not node.left and not node.right:\n display_markdown(\n f\"### Заканчиваем ветвление:\",\n node.label(pretty=True),\n raw=True,\n )\n\nexpose_node(tree)",
"_____no_output_____"
],
[
"solutions = [node.data.result for node in tree.leaves if not node.invalid]\n\ndisplay_markdown(\n \"### Целочисленные решения:\",\n *[\n ', '.join([\n f\"$F={pretty_value(table.result, 2)}$\",\n Format(table).solution(),\n ])\n for table in solutions\n ],\n raw=True, \n)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb0672226577371593bc9940c41f75f81ab6d4e4 | 84,718 | ipynb | Jupyter Notebook | Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb | ithakker/CISC367-Projects | ff61f5dccad430dde0fe980311ad956e2130b1ab | [
"MIT"
] | null | null | null | Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb | ithakker/CISC367-Projects | ff61f5dccad430dde0fe980311ad956e2130b1ab | [
"MIT"
] | 1 | 2021-02-25T00:56:06.000Z | 2021-02-25T00:56:06.000Z | Day16/.ipynb_checkpoints/regex_exercises-checkpoint.ipynb | ithakker/CISC367-Projects | ff61f5dccad430dde0fe980311ad956e2130b1ab | [
"MIT"
] | null | null | null | 27.776393 | 400 | 0.534184 | [
[
[
"# Regular Expression Exercises\n\n* Debugger: When debugging regular expressions, the best tool is [Regex101](https://regex101.com/). This is an interactive tool that let's you visualize a regular expression in action.\n* Tutorial: I tend to like RealPython's tutorials, here is their's on [Regular Expressions](https://realpython.com/regex-python/).\n* Tutorial: The [Official Python tutorial on Regular Expressions](https://docs.python.org/3/howto/regex.html) is not a bad introduction.\n* Cheat Sheet: People often make use of [Cheat Sheets](https://www.debuggex.com/cheatsheet/regex/python) when they have to do a lot of Regular Expressions.\n* Documentation: If you need it, the official [Python documentation on the `re` module](https://docs.python.org/3/library/re.html) can also be a resource.",
"_____no_output_____"
],
[
"PLEASE FILL IN THE FOLLOWING:\n \n* Your name:\n* Link to the Github repo with this file:",
"_____no_output_____"
]
],
[
[
"import re",
"_____no_output_____"
]
],
[
[
"## 1. Introduction\n\n**a)** Check whether the given strings contain `0xB0`. Display a boolean result as shown below.",
"_____no_output_____"
]
],
[
[
"line1 = 'start address: 0xA0, func1 address: 0xC0'\nline2 = 'end address: 0xFF, func2 address: 0xB0'\n\nassert bool(re.search(r'', line1)) == False\nassert bool(re.search(r'', line2)) == True",
"_____no_output_____"
]
],
[
[
"**b)** Replace all occurrences of `5` with `five` for the given string.",
"_____no_output_____"
]
],
[
[
"ip = 'They ate 5 apples and 5 oranges'\n\nassert re.sub() == 'They ate five apples and five oranges'",
"_____no_output_____"
]
],
[
[
"**c)** Replace first occurrence of `5` with `five` for the given string.",
"_____no_output_____"
]
],
[
[
"ip = 'They ate 5 apples and 5 oranges'\n\nassert re.sub() == 'They ate five apples and 5 oranges'",
"_____no_output_____"
]
],
[
[
"**d)** For the given list, filter all elements that do *not* contain `e`.",
"_____no_output_____"
]
],
[
[
"items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']\n\nassert [w for w in items if not re.search()] == ['goal', 'sit']",
"_____no_output_____"
]
],
[
[
"**e)** Replace all occurrences of `note` irrespective of case with `X`.",
"_____no_output_____"
]
],
[
[
"ip = 'This note should not be NoTeD'\n\nassert re.sub() == 'This X should not be XD'",
"_____no_output_____"
]
],
[
[
"**f)** Check if `at` is present in the given byte input data.",
"_____no_output_____"
]
],
[
[
"ip = 'tiger imp goat'\n\nassert bool(re.search()) == True",
"_____no_output_____"
]
],
[
[
"**g)** For the given input string, display all lines not containing `start` irrespective of case.",
"_____no_output_____"
]
],
[
[
"para = '''good start\nStart working on that\nproject you always wanted\nstars are shining brightly\nhi there\nstart and try to\nfinish the book\nbye'''\n\npat = re.compile() ##### add your solution here\nfor line in para.split('\\n'):\n if not pat.search(line):\n print(line)\n\n\"\"\"project you always wanted\nstars are shining brightly\nhi there\nfinish the book\nbye\"\"\"",
"_____no_output_____"
]
],
[
[
"**h)** For the given list, filter all elements that contains either `a` or `w`.",
"_____no_output_____"
]
],
[
[
"items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']\n\n##### add your solution here\nassert [w for w in items if re.search() or re.search()] == ['goal', 'new', 'eat']",
"_____no_output_____"
]
],
[
[
"**i)** For the given list, filter all elements that contains both `e` and `n`.",
"_____no_output_____"
]
],
[
[
"items = ['goal', 'new', 'user', 'sit', 'eat', 'dinner']\n\n##### add your solution here\nassert [w for w in items if re.search() and re.search()] == ['new', 'dinner']",
"_____no_output_____"
]
],
[
[
"**j)** For the given string, replace `0xA0` with `0x7F` and `0xC0` with `0x1F`.",
"_____no_output_____"
]
],
[
[
"ip = 'start address: 0xA0, func1 address: 0xC0'\n\n##### add your solution here\nassert ___ == 'start address: 0x7F, func1 address: 0x1F'",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 2. Anchors\n\n**a)** Check if the given strings start with `be`.",
"_____no_output_____"
]
],
[
[
"line1 = 'be nice'\nline2 = '\"best!\"'\nline3 = 'better?'\nline4 = 'oh no\\nbear spotted'\n\npat = re.compile() ##### add your solution here\nassert bool(pat.search(line1)) == True\nassert bool(pat.search(line2)) == False\nassert bool(pat.search(line3)) == True\nassert bool(pat.search(line4)) == False",
"_____no_output_____"
]
],
[
[
"**b)** For the given input string, change only whole word `red` to `brown`",
"_____no_output_____"
]
],
[
[
"words = 'bred red spread credible'\n\nassert re.sub() == 'bred brown spread credible'",
"_____no_output_____"
]
],
[
[
"**c)** For the given input list, filter all elements that contains `42` surrounded by word characters.",
"_____no_output_____"
]
],
[
[
"words = ['hi42bye', 'nice1423', 'bad42', 'cool_42a', 'fake4b']\n\nassert [w for w in words if re.search()] == ['hi42bye', 'nice1423', 'cool_42a']",
"_____no_output_____"
]
],
[
[
"**d)** For the given input list, filter all elements that start with `den` or end with `ly`.",
"_____no_output_____"
]
],
[
[
"items = ['lovely', '1\\ndentist', '2 lonely', 'eden', 'fly\\n', 'dent']\n\nassert [e for e in items if ] == ['lovely', '2 lonely', 'dent']",
"_____no_output_____"
]
],
[
[
"**e)** For the given input string, change whole word `mall` to `1234` only if it is at the start of a line.",
"_____no_output_____"
]
],
[
[
"para = '''\nball fall wall tall\nmall call ball pall\nwall mall ball fall\nmallet wallet malls'''\n\nassert re.sub() == \"\"\"ball fall wall tall\n1234 call ball pall\nwall mall ball fall\nmallet wallet malls\"\"\"",
"_____no_output_____"
]
],
[
[
"**f)** For the given list, filter all elements having a line starting with `den` or ending with `ly`.",
"_____no_output_____"
]
],
[
[
"items = ['lovely', '1\\ndentist', '2 lonely', 'eden', 'fly\\nfar', 'dent']\n\n##### add your solution here\nassert ___ == ['lovely', '1\\ndentist', '2 lonely', 'fly\\nfar', 'dent']",
"_____no_output_____"
]
],
[
[
"**g)** For the given input list, filter all whole elements `12\\nthree` irrespective of case.",
"_____no_output_____"
]
],
[
[
"items = ['12\\nthree\\n', '12\\nThree', '12\\nthree\\n4', '12\\nthree']\n##### add your solution here\nassert ___ == ['12\\nThree', '12\\nthree']",
"_____no_output_____"
]
],
[
[
"**h)** For the given input list, replace `hand` with `X` for all elements that start with `hand` followed by at least one word character.",
"_____no_output_____"
]
],
[
[
"items = ['handed', 'hand', 'handy', 'unhanded', 'handle', 'hand-2']\n\n##### add your solution here\nassert ___ == ['Xed', 'hand', 'Xy', 'unhanded', 'Xle', 'hand-2']",
"_____no_output_____"
]
],
[
[
"**i)** For the given input list, filter all elements starting with `h`. Additionally, replace `e` with `X` for these filtered elements.",
"_____no_output_____"
]
],
[
[
"items = ['handed', 'hand', 'handy', 'unhanded', 'handle', 'hand-2']\n\n##### add your solution here\nassert ___ == ['handXd', 'hand', 'handy', 'handlX', 'hand-2']",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 3. Alternation and Grouping\n\n**a)** For the given input list, filter all elements that start with `den` or end with `ly`",
"_____no_output_____"
]
],
[
[
"items = ['lovely', '1\\ndentist', '2 lonely', 'eden', 'fly\\n', 'dent']\n\n##### add your solution here\nassert ___ == ['lovely', '2 lonely', 'dent']",
"_____no_output_____"
]
],
[
[
"**b)** For the given list, filter all elements having a line starting with `den` or ending with `ly`.",
"_____no_output_____"
]
],
[
[
"items = ['lovely', '1\\ndentist', '2 lonely', 'eden', 'fly\\nfar', 'dent']\n\n##### add your solution here\nassert ___ == ['lovely', '1\\ndentist', '2 lonely', 'fly\\nfar', 'dent']",
"_____no_output_____"
]
],
[
[
"**c)** For the given input strings, replace all occurrences of `removed` or `reed` or `received` or `refused` with `X`.",
"_____no_output_____"
]
],
[
[
"s1 = 'creed refuse removed read'\ns2 = 'refused reed redo received'\n\npat = re.compile() ##### add your solution here\nassert pat.sub('X', s1) == 'cX refuse X read'\nassert pat.sub('X', s2) == 'X X redo X'",
"_____no_output_____"
]
],
[
[
"**d)** For the given input strings, replace all matches from the list `words` with `A`.",
"_____no_output_____"
]
],
[
[
"s1 = 'plate full of slate'\ns2 = \"slated for later, don't be late\"\nwords = ['late', 'later', 'slated']\n\npat = re.compile() ##### add your solution here\nassert pat.sub('A', s1) == 'pA full of sA'\nassert pat.sub('A', s2) == \"A for A, don't be A\"",
"_____no_output_____"
]
],
[
[
"**e)** Filter all whole elements from the input list `items` based on elements listed in `words`.",
"_____no_output_____"
]
],
[
[
"items = ['slate', 'later', 'plate', 'late', 'slates', 'slated ']\nwords = ['late', 'later', 'slated']\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here\nassert ___ == ['later', 'late']",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 4. Escaping metacharacters\n\n**a)** Transform the given input strings to the expected output using same logic on both strings.",
"_____no_output_____"
]
],
[
[
"str1 = '(9-2)*5+qty/3'\nstr2 = '(qty+4)/2-(9-2)*5+pq/4'\n\n##### add your solution here for str1\nassert ___ == '35+qty/3'\n##### add your solution here for str2\nassert ___ == '(qty+4)/2-35+pq/4'",
"_____no_output_____"
]
],
[
[
"**b)** Replace `(4)\\|` with `2` only at the start or end of given input strings.",
"_____no_output_____"
]
],
[
[
"s1 = r'2.3/(4)\\|6 foo 5.3-(4)\\|'\ns2 = r'(4)\\|42 - (4)\\|3'\ns3 = 'two - (4)\\\\|\\n'\n\npat = re.compile() ##### add your solution here\nassert pat.sub('2', s1) == '2.3/(4)\\\\|6 foo 5.3-2'\nassert pat.sub('2', s2) == '242 - (4)\\\\|3'\nassert pat.sub('2', s3) == 'two - (4)\\\\|\\n'",
"_____no_output_____"
]
],
[
[
"**c)** Replace any matching element from the list `items` with `X` for given the input strings. Match the elements from `items` literally. Assume no two elements of `items` will result in any matching conflict.",
"_____no_output_____"
]
],
[
[
"items = ['a.b', '3+n', r'x\\y\\z', 'qty||price', '{n}']\npat = re.compile() ##### add your solution here\nassert pat.sub('X', '0a.bcd') == '0Xcd'\nassert pat.sub('X', 'E{n}AMPLE') == 'EXAMPLE'\nassert pat.sub('X', r'43+n2 ax\\y\\ze') == '4X2 aXe'",
"_____no_output_____"
]
],
[
[
"**d)** Replace backspace character `\\b` with a single space character for the given input string.",
"_____no_output_____"
]
],
[
[
"ip = '123\\b456'\nip",
"_____no_output_____"
],
[
"assert re.sub() == '123 456'",
"_____no_output_____"
]
],
[
[
"**e)** Replace all occurrences of `\\e` with `e`.",
"_____no_output_____"
]
],
[
[
"ip = r'th\\er\\e ar\\e common asp\\ects among th\\e alt\\ernations'\n\nassert re.sub() == 'there are common aspects among the alternations'",
"_____no_output_____"
]
],
[
[
"**f)** Replace any matching item from the list `eqns` with `X` for given the string `ip`. Match the items from `eqns` literally.",
"_____no_output_____"
]
],
[
[
"ip = '3-(a^b)+2*(a^b)-(a/b)+3'\neqns = ['(a^b)', '(a/b)', '(a^b)+2']\n\n##### add your solution here\n\nassert pat.sub('X', ip) == '3-X*X-X+3'",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 5. Dot metacharacter and Quantifiers\n\nSince `.` metacharacter doesn't match newline character by default, assume that the input strings in the following exercises will not contain newline characters.\n\n**a)** Replace `42//5` or `42/5` with `8` for the given input.",
"_____no_output_____"
]
],
[
[
"ip = 'a+42//5-c pressure*3+42/5-14256'\n\nassert re.sub() == 'a+8-c pressure*3+8-14256'",
"_____no_output_____"
]
],
[
[
"**b)** For the list `items`, filter all elements starting with `hand` and ending with at most one more character or `le`.",
"_____no_output_____"
]
],
[
[
"items = ['handed', 'hand', 'handled', 'handy', 'unhand', 'hands', 'handle']\n\n##### add your solution here\nassert ___ == ['hand', 'handy', 'hands', 'handle']",
"_____no_output_____"
]
],
[
[
"**c)** Use `re.split` to get the output as shown for the given input strings.",
"_____no_output_____"
]
],
[
[
"eqn1 = 'a+42//5-c'\neqn2 = 'pressure*3+42/5-14256'\neqn3 = 'r*42-5/3+42///5-42/53+a'\n##### add your solution here for eqn1\nassert ___ == ['a+', '-c']\n##### add your solution here for eqn2\nassert ___ == ['pressure*3+', '-14256']\n##### add your solution here for eqn3\nassert ___ == ['r*42-5/3+42///5-', '3+a']",
"_____no_output_____"
]
],
[
[
"**d)** For the given input strings, remove everything from the first occurrence of `i` till end of the string.",
"_____no_output_____"
]
],
[
[
"s1 = 'remove the special meaning of such constructs'\ns2 = 'characters while constructing'\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub('', s1) == 'remove the spec'\n\nassert pat.sub('', s2) == 'characters wh'",
"_____no_output_____"
]
],
[
[
"**e)** For the given strings, construct a RE to get output as shown.",
"_____no_output_____"
]
],
[
[
"str1 = 'a+b(addition)'\nstr2 = 'a/b(division) + c%d(#modulo)'\nstr3 = 'Hi there(greeting). Nice day(a(b)'\n\nremove_parentheses = re.compile() ##### add your solution here\n\nassert remove_parentheses.sub('', str1) == 'a+b'\nassert remove_parentheses.sub('', str2) == 'a/b + c%d'\nassert remove_parentheses.sub('', str3) == 'Hi there. Nice day'",
"_____no_output_____"
]
],
[
[
"**f)** Correct the given RE to get the expected output.",
"_____no_output_____"
]
],
[
[
"words = 'plink incoming tint winter in caution sentient'\nchange = re.compile(r'int|in|ion|ing|inco|inter|ink')\n\n# wrong output\nassert change.sub('X', words) == 'plXk XcomXg tX wXer X cautX sentient'\n\n# expected output\nchange = re.compile() ##### add your solution here\nassert change.sub('X', words) == 'plX XmX tX wX X cautX sentient'",
"_____no_output_____"
]
],
[
[
"**g)** For the given greedy quantifiers, what would be the equivalent form using `{m,n}` representation?\n\n* `?` is same as\n* `*` is same as\n* `+` is same as\n\n**h)** `(a*|b*)` is same as `(a|b)*` — True or False?\n\n\n**i)** For the given input strings, remove everything from the first occurrence of `test` (irrespective of case) till end of the string, provided `test` isn't at the end of the string.",
"_____no_output_____"
]
],
[
[
"s1 = 'this is a Test'\ns2 = 'always test your RE for corner cases'\ns3 = 'a TEST of skill tests?'\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub('', s1) == 'this is a Test'\nassert pat.sub('', s2) == 'always '\nassert pat.sub('', s3) == 'a '",
"_____no_output_____"
]
],
[
[
"**j)** For the input list `words`, filter all elements starting with `s` and containing `e` and `t` in any order.",
"_____no_output_____"
]
],
[
[
"words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site']\n\n##### add your solution here\nassert ___ == ['subtle', 'sets', 'site']",
"_____no_output_____"
]
],
[
[
"**k)** For the input list `words`, remove all elements having less than `6` characters.",
"_____no_output_____"
]
],
[
[
"words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site']\n\n##### add your solution here\nassert ___ == ['sequoia', 'subtle', 'exhibit']",
"_____no_output_____"
]
],
[
[
"**l)** For the input list `words`, filter all elements starting with `s` or `t` and having a maximum of `6` characters.",
"_____no_output_____"
]
],
[
[
"words = ['sequoia', 'subtle', 'exhibit', 'asset', 'sets', 'tests', 'site']\n\n##### add your solution here\nassert ___ == ['subtle', 'sets', 'tests', 'site']",
"_____no_output_____"
]
],
[
[
"**m)** Can you reason out why this code results in the output shown? The aim was to remove all `<characters>` patterns but not the `<>` ones. The expected result was `'a 1<> b 2<> c'`.",
"_____no_output_____"
]
],
[
[
"ip = 'a<apple> 1<> b<bye> 2<> c<cat>'\n\nassert re.sub(r'<.+?>', '', ip) == 'a 1 2'",
"_____no_output_____"
]
],
[
[
"**n)** Use `re.split` to get the output as shown below for given input strings.",
"_____no_output_____"
]
],
[
[
"s1 = 'go there // \"this // that\"'\ns2 = 'a//b // c//d e//f // 4//5'\ns3 = '42// hi//bye//see // carefully'\n\npat = re.compile() ##### add your solution here\n\nassert pat.split() == ['go there', '\"this // that\"']\nassert pat.split() == ['a//b', 'c//d e//f // 4//5']\nassert pat.split() == ['42// hi//bye//see', 'carefully']",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 6. Working with matched portions\n\n**a)** For the given strings, extract the matching portion from first `is` to last `t`.",
"_____no_output_____"
]
],
[
[
"str1 = 'This the biggest fruit you have seen?'\nstr2 = 'Your mission is to read and practice consistently'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for str1\nassert ___ == 'is the biggest fruit'\n##### add your solution here for str2\nassert ___ == 'ission is to read and practice consistent'",
"_____no_output_____"
]
],
[
[
"**b)** Find the starting index of first occurrence of `is` or `the` or `was` or `to` for the given input strings.",
"_____no_output_____"
]
],
[
[
"s1 = 'match after the last newline character'\ns2 = 'and then you want to test'\ns3 = 'this is good bye then'\ns4 = 'who was there to see?'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for s1\nassert ___ == 12\n##### add your solution here for s2\nassert ___ == 4\n##### add your solution here for s3\nassert ___ == 2\n##### add your solution here for s4\nassert ___ == 4",
"_____no_output_____"
]
],
[
[
"**c)** Find the starting index of last occurrence of `is` or `the` or `was` or `to` for the given input strings.",
"_____no_output_____"
]
],
[
[
"s1 = 'match after the last newline character'\ns2 = 'and then you want to test'\ns3 = 'this is good bye then'\ns4 = 'who was there to see?'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for s1\nassert ___ == 12\n##### add your solution here for s2\nassert ___ == 18\n##### add your solution here for s3\nassert ___ == 17\n##### add your solution here for s4\nassert ___ == 14",
"_____no_output_____"
]
],
[
[
"**d)** The given input string contains `:` exactly once. Extract all characters after the `:` as output.",
"_____no_output_____"
]
],
[
[
"ip = 'fruits:apple, mango, guava, blueberry'\n\n##### add your solution here\nassert ___ == 'apple, mango, guava, blueberry'",
"_____no_output_____"
]
],
[
[
"**e)** The given input strings contains some text followed by `-` followed by a number. Replace that number with its `log` value using `math.log()`.",
"_____no_output_____"
]
],
[
[
"s1 = 'first-3.14'\ns2 = 'next-123'\n\npat = re.compile() ##### add your solution here\n\nimport math\nassert pat.sub() == 'first-1.144222799920162'\nassert pat.sub() == 'next-4.812184355372417'",
"_____no_output_____"
]
],
[
[
"**f)** Replace all occurrences of `par` with `spar`, `spare` with `extra` and `park` with `garden` for the given input strings.",
"_____no_output_____"
]
],
[
[
"str1 = 'apartment has a park'\nstr2 = 'do you have a spare cable'\nstr3 = 'write a parser'\n\n##### add your solution here\n\nassert pat.sub() == 'aspartment has a garden'\nassert pat.sub() == 'do you have a extra cable'\nassert pat.sub() == 'write a sparser'",
"_____no_output_____"
]
],
[
[
"**g)** Extract all words between `(` and `)` from the given input string as a list. Assume that the input will not contain any broken parentheses.",
"_____no_output_____"
]
],
[
[
"ip = 'another (way) to reuse (portion) matched (by) capture groups'\n\nassert re.findall() == ['way', 'portion', 'by']",
"_____no_output_____"
]
],
[
[
"**h)** Extract all occurrences of `<` up to next occurrence of `>`, provided there is at least one character in between `<` and `>`.",
"_____no_output_____"
]
],
[
[
"ip = 'a<apple> 1<> b<bye> 2<> c<cat>'\n\nassert re.findall() == ['<apple>', '<> b<bye>', '<> c<cat>']",
"_____no_output_____"
]
],
[
[
"**i)** Use `re.findall` to get the output as shown below for the given input strings. Note the characters used in the input strings carefully.",
"_____no_output_____"
]
],
[
[
"row1 = '-2,5 4,+3 +42,-53 4356246,-357532354 '\nrow2 = '1.32,-3.14 634,5.63 63.3e3,9907809345343.235 '\n\npat = re.compile() ##### add your solution here\n\nassert pat.findall(row1) == [('-2', '5'), ('4', '+3'), ('+42', '-53'), ('4356246', '-357532354')]\npat.findall(row2) == [('1.32', '-3.14'), ('634', '5.63'), ('63.3e3', '9907809345343.235')]",
"_____no_output_____"
]
],
[
[
"**j)** This is an extension to previous question.\n\n* For `row1`, find the sum of integers of each tuple element. For example, sum of `-2` and `5` is `3`.\n* For `row2`, find the sum of floating-point numbers of each tuple element. For example, sum of `1.32` and `-3.14` is `-1.82`.",
"_____no_output_____"
]
],
[
[
"row1 = '-2,5 4,+3 +42,-53 4356246,-357532354 '\nrow2 = '1.32,-3.14 634,5.63 63.3e3,9907809345343.235 '\n\n# should be same as previous question\npat = re.compile() ##### add your solution here\n\n##### add your solution here for row1\nassert ___ == [3, 7, -11, -353176108]\n\n##### add your solution here for row2\nassert ___ == [-1.82, 639.63, 9907809408643.234]",
"_____no_output_____"
]
],
[
[
"**k)** Use `re.split` to get the output as shown below.",
"_____no_output_____"
]
],
[
[
"ip = '42:no-output;1000:car-truck;SQEX49801'\n\nassert re.split() == ['42', 'output', '1000', 'truck', 'SQEX49801']",
"_____no_output_____"
]
],
[
[
"**l)** For the given list of strings, change the elements into a tuple of original element and number of times `t` occurs in that element.",
"_____no_output_____"
]
],
[
[
"words = ['sequoia', 'attest', 'tattletale', 'asset']\n\n##### add your solution here\nassert ___ == [('sequoia', 0), ('attest', 3), ('tattletale', 4), ('asset', 1)]",
"_____no_output_____"
]
],
[
[
"**m)** The given input string has fields separated by `:`. Each field contains four uppercase alphabets followed optionally by two digits. Ignore the last field, which is empty. See [docs.python: Match.groups](https://docs.python.org/3/library/re.html#re.Match.groups) and use `re.finditer` to get the output as shown below. If the optional digits aren't present, show `'NA'` instead of `None`.",
"_____no_output_____"
]
],
[
[
"ip = 'TWXA42:JWPA:NTED01:'\n\n##### add your solution here\nassert ___ == [('TWXA', '42'), ('JWPA', 'NA'), ('NTED', '01')]",
"_____no_output_____"
]
],
[
[
"> Note that this is different from `re.findall` which will just give empty string instead of `None` when a capture group doesn't participate.\n\n**n)** Convert the comma separated strings to corresponding `dict` objects as shown below.",
"_____no_output_____"
]
],
[
[
"row1 = 'name:rohan,maths:75,phy:89,'\nrow2 = 'name:rose,maths:88,phy:92,'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for row1\nassert ___ == {'name': 'rohan', 'maths': '75', 'phy': '89'}\n##### add your solution here for row2\nassert ___ == {'name': 'rose', 'maths': '88', 'phy': '92'}",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 7. Character class\n\n**a)** For the list `items`, filter all elements starting with `hand` and ending with `s` or `y` or `le`.",
"_____no_output_____"
]
],
[
[
"items = ['-handy', 'hand', 'handy', 'unhand', 'hands', 'handle']\n\n##### add your solution here\nassert ___ == ['handy', 'hands', 'handle']",
"_____no_output_____"
]
],
[
[
"**b)** Replace all whole words `reed` or `read` or `red` with `X`.",
"_____no_output_____"
]
],
[
[
"ip = 'redo red credible :read: rod reed'\n\n##### add your solution here\nassert ___ == 'redo X credible :X: rod X'",
"_____no_output_____"
]
],
[
[
"**c)** For the list `words`, filter all elements containing `e` or `i` followed by `l` or `n`. Note that the order mentioned should be followed.",
"_____no_output_____"
]
],
[
[
"words = ['surrender', 'unicorn', 'newer', 'door', 'empty', 'eel', 'pest']\n\n##### add your solution here\nassert ___ == ['surrender', 'unicorn', 'eel']",
"_____no_output_____"
]
],
[
[
"**d)** For the list `words`, filter all elements containing `e` or `i` and `l` or `n` in any order.",
"_____no_output_____"
]
],
[
[
"words = ['surrender', 'unicorn', 'newer', 'door', 'empty', 'eel', 'pest']\n\n##### add your solution here\nassert ___ == ['surrender', 'unicorn', 'newer', 'eel']",
"_____no_output_____"
]
],
[
[
"**e)** Extract all hex character sequences, with `0x` optional prefix. Match the characters case insensitively, and the sequences shouldn't be surrounded by other word characters.",
"_____no_output_____"
]
],
[
[
"str1 = '128A foo 0xfe32 34 0xbar'\nstr2 = '0XDEADBEEF place 0x0ff1ce bad'\n\nhex_seq = re.compile() ##### add your solution here\n\n##### add your solution here for str1\nassert ___ == ['128A', '0xfe32', '34']\n\n##### add your solution here for str2\nassert ___ == ['0XDEADBEEF', '0x0ff1ce', 'bad']",
"_____no_output_____"
]
],
[
[
"**f)** Delete from `(` to the next occurrence of `)` unless they contain parentheses characters in between.",
"_____no_output_____"
]
],
[
[
"str1 = 'def factorial()'\nstr2 = 'a/b(division) + c%d(#modulo) - (e+(j/k-3)*4)'\nstr3 = 'Hi there(greeting). Nice day(a(b)'\n\nremove_parentheses = re.compile() ##### add your solution here\n\nassert ___ == remove_parentheses.sub('', str1)\n'def factorial'\nassert ___ == remove_parentheses.sub('', str2)\n'a/b + c%d - (e+*4)'\nassert ___ == remove_parentheses.sub('', str3)\n'Hi there. Nice day(a'",
"_____no_output_____"
]
],
[
[
"**g)** For the list `words`, filter all elements not starting with `e` or `p` or `u`.",
"_____no_output_____"
]
],
[
[
"words = ['surrender', 'unicorn', 'newer', 'door', 'empty', 'eel', 'pest']\n\n##### add your solution here\nassert ___ == ['surrender', 'newer', 'door']",
"_____no_output_____"
]
],
[
[
"**h)** For the list `words`, filter all elements not containing `u` or `w` or `ee` or `-`.",
"_____no_output_____"
]
],
[
[
"words = ['p-t', 'you', 'tea', 'heel', 'owe', 'new', 'reed', 'ear']\n\n##### add your solution here\nassert ___ == ['tea', 'ear']",
"_____no_output_____"
]
],
[
[
"**i)** The given input strings contain fields separated by `,` and fields can be empty too. Replace last three fields with `WHTSZ323`.",
"_____no_output_____"
]
],
[
[
"row1 = '(2),kite,12,,D,C,,'\nrow2 = 'hi,bye,sun,moon'\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub() == '(2),kite,12,,D,WHTSZ323'\nassert pat.sub() == 'hi,WHTSZ323'",
"_____no_output_____"
]
],
[
[
"**j)** Split the given strings based on consecutive sequence of digit or whitespace characters.",
"_____no_output_____"
]
],
[
[
"str1 = 'lion \\t Ink32onion Nice'\nstr2 = '**1\\f2\\n3star\\t7 77\\r**'\n\npat = re.compile() ##### add your solution here\n\nassert pat.split(str1) == ['lion', 'Ink', 'onion', 'Nice']\nassert pat.split(str2) == ['**', 'star', '**']",
"_____no_output_____"
]
],
[
[
"**k)** Delete all occurrences of the sequence `<characters>` where `characters` is one or more non `>` characters and cannot be empty.",
"_____no_output_____"
]
],
[
[
"ip = 'a<apple> 1<> b<bye> 2<> c<cat>'\n\n##### add your solution here\nassert ___ == 'a 1<> b 2<> c'",
"_____no_output_____"
]
],
[
[
"**l)** `\\b[a-z](on|no)[a-z]\\b` is same as `\\b[a-z][on]{2}[a-z]\\b`. True or False? Sample input lines shown below might help to understand the differences, if any.",
"_____no_output_____"
]
],
[
[
"print('known\\nmood\\nknow\\npony\\ninns')\nknown\nmood\nknow\npony\ninns",
"_____no_output_____"
]
],
[
[
"**m)** For the given list, filter all elements containing any number sequence greater than `624`.",
"_____no_output_____"
]
],
[
[
"items = ['hi0000432abcd', 'car00625', '42_624 0512', '3.14 96 2 foo1234baz']\n\n##### add your solution here\nassert ___ == ['car00625', '3.14 96 2 foo1234baz']",
"_____no_output_____"
]
],
[
[
"**n)** Count the maximum depth of nested braces for the given strings. Unbalanced or wrongly ordered braces should return `-1`. Note that this will require a mix of regular expressions and Python code.",
"_____no_output_____"
]
],
[
[
"def max_nested_braces(ip):\n##### add your solution here\n\nassert max_nested_braces('a*b') == 0\nassert max_nested_braces('}a+b{') == -1\nassert max_nested_braces('a*b+{}') == 1\nassert max_nested_braces('{{a+2}*{b+c}+e}') == 2\nassert max_nested_braces('{{a+2}*{b+{c*d}}+e}') == 3\nassert max_nested_braces('{{a+2}*{\\n{b+{c*d}}+e*d}}') == 4\nassert max_nested_braces('a*{b+c*{e*3.14}}}') == -1",
"_____no_output_____"
]
],
[
[
"**o)** By default, `str.split` method will split on whitespace and remove empty strings from the result. Which `re` module function would you use to replicate this functionality?",
"_____no_output_____"
]
],
[
[
"ip = ' \\t\\r so pole\\t\\t\\t\\n\\nlit in to \\r\\n\\v\\f '\n\nassert ip.split() == ['so', 'pole', 'lit', 'in', 'to']\n##### add your solution here\nassert ___ == ['so', 'pole', 'lit', 'in', 'to']",
"_____no_output_____"
]
],
[
[
"**p)** Convert the given input string to two different lists as shown below.",
"_____no_output_____"
]
],
[
[
"ip = 'price_42 roast^\\t\\n^-ice==cat\\neast'\n\n##### add your solution here\nassert ___ == ['price_42', 'roast', 'ice', 'cat', 'east']\n\n##### add your solution here\nassert ___ == ['price_42', ' ', 'roast', '^\\t\\n^-', 'ice', '==', 'cat', '\\n', 'east']",
"_____no_output_____"
]
],
[
[
"**q)** Filter all elements whose first non-whitespace character is not a `#` character. Any element made up of only whitespace characters should be ignored as well.",
"_____no_output_____"
]
],
[
[
"items = [' #comment', '\\t\\napple #42', '#oops', 'sure', 'no#1', '\\t\\r\\f']\n\n##### add your solution here\nassert ___ == ['\\t\\napple #42', 'sure', 'no#1']",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 8. Groupings and backreferences\n\n**a)** Replace the space character that occurs after a word ending with `a` or `r` with a newline character.",
"_____no_output_____"
]
],
[
[
"ip = 'area not a _a2_ roar took 22'\n\nassert re.sub() == \"\"\"area\nnot a\n_a2_ roar\ntook 22\"\"\"",
"_____no_output_____"
]
],
[
[
"**b)** Add `[]` around words starting with `s` and containing `e` and `t` in any order.",
"_____no_output_____"
]
],
[
[
"ip = 'sequoia subtle exhibit asset sets tests site'\n\n##### add your solution here\nassert ___ == 'sequoia [subtle] exhibit asset [sets] tests [site]'",
"_____no_output_____"
]
],
[
[
"**c)** Replace all whole words with `X` that start and end with the same word character. Single character word should get replaced with `X` too, as it satisfies the stated condition.",
"_____no_output_____"
]
],
[
[
"ip = 'oreo not a _a2_ roar took 22'\n\n##### add your solution here\nassert ___ == 'X not X X X took X'",
"_____no_output_____"
]
],
[
[
"**d)** Convert the given **markdown** headers to corresponding **anchor** tag. Consider the input to start with one or more `#` characters followed by space and word characters. The `name` attribute is constructed by converting the header to lowercase and replacing spaces with hyphens. Can you do it without using a capture group?",
"_____no_output_____"
]
],
[
[
"header1 = '# Regular Expressions'\nheader2 = '## Compiling regular expressions'\n\n##### add your solution here for header1\nassert ___ == '# <a name=\"regular-expressions\"></a>Regular Expressions'\n##### add your solution here for header2\nassert ___ == '## <a name=\"compiling-regular-expressions\"></a>Compiling regular expressions'",
"_____no_output_____"
]
],
[
[
"**e)** Convert the given **markdown** anchors to corresponding **hyperlinks**.",
"_____no_output_____"
]
],
[
[
"anchor1 = '# <a name=\"regular-expressions\"></a>Regular Expressions'\nanchor2 = '## <a name=\"subexpression-calls\"></a>Subexpression calls'\n\n##### add your solution here for anchor1\nassert ___ == '[Regular Expressions](#regular-expressions)'\n##### add your solution here for anchor2\nassert ___ == '[Subexpression calls](#subexpression-calls)'",
"_____no_output_____"
]
],
[
[
"**f)** Count the number of whole words that have at least two occurrences of consecutive repeated alphabets. For example, words like `stillness` and `Committee` should be counted but not words like `root` or `readable` or `rotational`.",
"_____no_output_____"
]
],
[
[
"ip = '''oppressed abandon accommodation bloodless\ncarelessness committed apparition innkeeper\noccasionally afforded embarrassment foolishness\ndepended successfully succeeded\npossession cleanliness suppress'''\n\n##### add your solution here\nassert ___ == 13",
"_____no_output_____"
]
],
[
[
"**g)** For the given input string, replace all occurrences of digit sequences with only the unique non-repeating sequence. For example, `232323` should be changed to `23` and `897897` should be changed to `897`. If there no repeats (for example `1234`) or if the repeats end prematurely (for example `12121`), it should not be changed.",
"_____no_output_____"
]
],
[
[
"ip = '1234 2323 453545354535 9339 11 60260260'\n\n##### add your solution here\nassert ___ == '1234 23 4535 9339 1 60260260'",
"_____no_output_____"
]
],
[
[
"**h)** Replace sequences made up of words separated by `:` or `.` by the first word of the sequence. Such sequences will end when `:` or `.` is not followed by a word character.",
"_____no_output_____"
]
],
[
[
"ip = 'wow:Good:2_two:five: hi-2 bye kite.777.water.'\n\n##### add your solution here\nassert ___ == 'wow hi-2 bye kite'",
"_____no_output_____"
]
],
[
[
"**i)** Replace sequences made up of words separated by `:` or `.` by the last word of the sequence. Such sequences will end when `:` or `.` is not followed by a word character.",
"_____no_output_____"
]
],
[
[
"ip = 'wow:Good:2_two:five: hi-2 bye kite.777.water.'\n\n##### add your solution here\nassert ___ == 'five hi-2 bye water'",
"_____no_output_____"
]
],
[
[
"**j)** Split the given input string on one or more repeated sequence of `cat`.",
"_____no_output_____"
]
],
[
[
"ip = 'firecatlioncatcatcatbearcatcatparrot'\n\n##### add your solution here\nassert ___ == ['fire', 'lion', 'bear', 'parrot']",
"_____no_output_____"
]
],
[
[
"**k)** For the given input string, find all occurrences of digit sequences with at least one repeating sequence. For example, `232323` and `897897`. If the repeats end prematurely, for example `12121`, it should not be matched.",
"_____no_output_____"
]
],
[
[
"ip = '1234 2323 453545354535 9339 11 60260260'\n\npat = re.compile() ##### add your solution here\n\n# entire sequences in the output\n##### add your solution here\nassert ___ == ['2323', '453545354535', '11']\n\n# only the unique sequence in the output\n##### add your solution here\nassert ___ == ['23', '4535', '1']",
"_____no_output_____"
]
],
[
[
"**l)** Convert the comma separated strings to corresponding `dict` objects as shown below. The keys are `name`, `maths` and `phy` for the three fields in the input strings.",
"_____no_output_____"
]
],
[
[
"row1 = 'rohan,75,89'\nrow2 = 'rose,88,92'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for row1\nassert ___ == {'name': 'rohan', 'maths': '75', 'phy': '89'}\n##### add your solution here for row2\nassert ___ == {'name': 'rose', 'maths': '88', 'phy': '92'}",
"_____no_output_____"
]
],
[
[
"**m)** Surround all whole words with `()`. Additionally, if the whole word is `imp` or `ant`, delete them. Can you do it with single substitution?",
"_____no_output_____"
]
],
[
[
"ip = 'tiger imp goat eagle ant important'\n\n##### add your solution here\nassert ___ == '(tiger) () (goat) (eagle) () (important)'",
"_____no_output_____"
]
],
[
[
"**n)** Filter all elements that contains a sequence of lowercase alphabets followed by `-` followed by digits. They can be optionally surrounded by `{{` and `}}`. Any partial match shouldn't be part of the output.",
"_____no_output_____"
]
],
[
[
"ip = ['{{apple-150}}', '{{mango2-100}}', '{{cherry-200', 'grape-87']\n\n##### add your solution here\nassert ___ == ['{{apple-150}}', 'grape-87']",
"_____no_output_____"
]
],
[
[
"**o)** The given input string has sequences made up of words separated by `:` or `.` and such sequences will end when `:` or `.` is not followed by a word character. For all such sequences, display only the last word followed by `-` followed by first word.",
"_____no_output_____"
]
],
[
[
"ip = 'wow:Good:2_two:five: hi-2 bye kite.777.water.'\n\n##### add your solution here\nassert ___ == ['five-wow', 'water-kite']",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 9. Lookarounds\n\nStarting from here, all following problems are optional!\n\nPlease use lookarounds for solving the following exercises even if you can do it without lookarounds. Unless you cannot use lookarounds for cases like variable length lookbehinds.\n\n**a)** Replace all whole words with `X` unless it is preceded by `(` character.",
"_____no_output_____"
]
],
[
[
"ip = '(apple) guava berry) apple (mango) (grape'\n\n##### add your solution here\nassert ___ == '(apple) X X) X (mango) (grape'",
"_____no_output_____"
]
],
[
[
"**b)** Replace all whole words with `X` unless it is followed by `)` character.",
"_____no_output_____"
]
],
[
[
"ip = '(apple) guava berry) apple (mango) (grape'\n\n##### add your solution here\nassert ___ == '(apple) X berry) X (mango) (X'",
"_____no_output_____"
]
],
[
[
"**c)** Replace all whole words with `X` unless it is preceded by `(` or followed by `)` characters.",
"_____no_output_____"
]
],
[
[
"ip = '(apple) guava berry) apple (mango) (grape'\n\n##### add your solution here\nassert ___ == '(apple) X berry) X (mango) (grape'",
"_____no_output_____"
]
],
[
[
"**d)** Extract all whole words that do not end with `e` or `n`.",
"_____no_output_____"
]
],
[
[
"ip = 'at row on urn e note dust n'\n\n##### add your solution here\nassert ___ == ['at', 'row', 'dust']",
"_____no_output_____"
]
],
[
[
"**e)** Extract all whole words that do not start with `a` or `d` or `n`.",
"_____no_output_____"
]
],
[
[
"ip = 'at row on urn e note dust n'\n\n##### add your solution here\nassert ___ == ['row', 'on', 'urn', 'e']",
"_____no_output_____"
]
],
[
[
"**f)** Extract all whole words only if they are followed by `:` or `,` or `-`.",
"_____no_output_____"
]
],
[
[
"ip = 'poke,on=-=so:ink.to/is(vast)ever-sit'\n\n##### add your solution here\nassert ___ == ['poke', 'so', 'ever']",
"_____no_output_____"
]
],
[
[
"**g)** Extract all whole words only if they are preceded by `=` or `/` or `-`.",
"_____no_output_____"
]
],
[
[
"ip = 'poke,on=-=so:ink.to/is(vast)ever-sit'\n\n##### add your solution here\nassert ___ == ['so', 'is', 'sit']",
"_____no_output_____"
]
],
[
[
"**h)** Extract all whole words only if they are preceded by `=` or `:` and followed by `:` or `.`.",
"_____no_output_____"
]
],
[
[
"ip = 'poke,on=-=so:ink.to/is(vast)ever-sit'\n\n##### add your solution here\nassert ___ == ['so', 'ink']",
"_____no_output_____"
]
],
[
[
"**i)** Extract all whole words only if they are preceded by `=` or `:` or `.` or `(` or `-` and not followed by `.` or `/`.",
"_____no_output_____"
]
],
[
[
"ip = 'poke,on=-=so:ink.to/is(vast)ever-sit'\n\n##### add your solution here\nassert ___ == ['so', 'vast', 'sit']",
"_____no_output_____"
]
],
[
[
"**j)** Remove leading and trailing whitespaces from all the individual fields where `,` is the field separator.",
"_____no_output_____"
]
],
[
[
"csv1 = ' comma ,separated ,values \\t\\r '\ncsv2 = 'good bad,nice ice , 42 , , stall small'\n\nremove_whitespace = re.compile() ##### add your solution here\n\nassert remove_whitespace.sub('', csv1) == 'comma,separated,values'\nassert remove_whitespace.sub('', csv2) == 'good bad,nice ice,42,,stall small'",
"_____no_output_____"
]
],
[
[
"**k)** Filter all elements that satisfy all of these rules:\n\n* should have at least two alphabets\n* should have at least 3 digits\n* should have at least one special character among `%` or `*` or `#` or `$`\n* should not end with a whitespace character",
"_____no_output_____"
]
],
[
[
"pwds = ['hunter2', 'F2H3u%9', '*X3Yz3.14\\t', 'r2_d2_42', 'A $B C1234']\n\n##### add your solution here\nassert ___ == ['F2H3u%9', 'A $B C1234']",
"_____no_output_____"
]
],
[
[
"**l)** For the given string, surround all whole words with `{}` except for whole words `par` and `cat` and `apple`.",
"_____no_output_____"
]
],
[
[
"ip = 'part; cat {super} rest_42 par scatter apple spar'\n\n##### add your solution here\nassert ___ == '{part}; cat {{super}} {rest_42} par {scatter} apple {spar}'",
"_____no_output_____"
]
],
[
[
"**m)** Extract integer portion of floating-point numbers for the given string. A number ending with `.` and no further digits should not be considered.",
"_____no_output_____"
]
],
[
[
"ip = '12 ab32.4 go 5 2. 46.42 5'\n\n##### add your solution here\nassert ___ == ['32', '46']",
"_____no_output_____"
]
],
[
[
"**n)** For the given input strings, extract all overlapping two character sequences.",
"_____no_output_____"
]
],
[
[
"s1 = 'apple'\ns2 = '1.2-3:4'\n\npat = re.compile() ##### add your solution here\n\n##### add your solution here for s1\nassert ___ == ['ap', 'pp', 'pl', 'le']\n##### add your solution here for s2\nassert ___ == ['1.', '.2', '2-', '-3', '3:', ':4']",
"_____no_output_____"
]
],
[
[
"**o)** The given input strings contain fields separated by `:` character. Delete `:` and the last field if there is a digit character anywhere before the last field.",
"_____no_output_____"
]
],
[
[
"s1 = '42:cat'\ns2 = 'twelve:a2b'\ns3 = 'we:be:he:0:a:b:bother'\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub() == '42'\nassert pat.sub() == 'twelve:a2b'\nassert pat.sub() == 'we:be:he:0:a:b'",
"_____no_output_____"
]
],
[
[
"**p)** Extract all whole words unless they are preceded by `:` or `<=>` or `----` or `#`.",
"_____no_output_____"
]
],
[
[
"ip = '::very--at<=>row|in.a_b#b2c=>lion----east'\n\n##### add your solution here\nassert ___ == ['at', 'in', 'a_b', 'lion']",
"_____no_output_____"
]
],
[
[
"**q)** Match strings if it contains `qty` followed by `price` but not if there is **whitespace** or the string `error` between them.",
"_____no_output_____"
]
],
[
[
"str1 = '23,qty,price,42'\nstr2 = 'qty price,oh'\nstr3 = '3.14,qty,6,errors,9,price,3'\nstr4 = '42\\nqty-6,apple-56,price-234,error'\nstr5 = '4,price,3.14,qty,4'\n\nneg = re.compile() ##### add your solution here\n\nassert bool(neg.search(str1)) == True\nassert bool(neg.search(str2)) == False\nassert bool(neg.search(str3)) == False\nassert bool(neg.search(str4)) == True\nassert bool(neg.search(str5)) == False",
"_____no_output_____"
]
],
[
[
"**r)** Can you reason out why the output shown is different for these two regular expressions?",
"_____no_output_____"
]
],
[
[
"ip = 'I have 12, he has 2!'\n\nassert re.sub(r'\\b..\\b', '{\\g<0>}', ip) == '{I }have {12}{, }{he} has{ 2}!'\n\nassert re.sub(r'(?<!\\w)..(?!\\w)', '{\\g<0>}', ip) == 'I have {12}, {he} has {2!}'",
"_____no_output_____"
]
],
[
[
"<br>\n\n# 10. Flags\n\n**a)** Remove from first occurrence of `hat` to last occurrence of `it` for the given input strings. Match these markers case insensitively.",
"_____no_output_____"
]
],
[
[
"s1 = 'But Cool THAT\\nsee What okay\\nwow quite'\ns2 = 'it this hat is sliced HIT.'\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub('', s1) == 'But Cool Te'\nassert pat.sub('', s2) == 'it this .'",
"_____no_output_____"
]
],
[
[
"**b)** Delete from `start` if it is at the beginning of a line up to the next occurrence of the `end` at the end of a line. Match these markers case insensitively.",
"_____no_output_____"
]
],
[
[
"para = '''\ngood start\nstart working on that\nproject you always wanted\nto, do not let it end\nhi there\nstart and end the end\n42\nStart and try to\nfinish the End\nbye'''\n\npat = re.compile() ##### add your solution here\n\nassert pat.sub('', para)) == \"\"\"\ngood start\n\nhi there\n\n42\n\nbye\"\"\"",
"_____no_output_____"
]
],
[
[
"**c)** For the given input strings, match all of these three patterns:\n\n* `This` case sensitively\n* `nice` and `cool` case insensitively",
"_____no_output_____"
]
],
[
[
"s1 = 'This is nice and Cool'\ns2 = 'Nice and cool this is'\ns3 = 'What is so nice and cool about This?'\n\npat = re.compile() ##### add your solution here\n\nassert bool(pat.search(s1)) == True\nassert bool(pat.search(s2)) == False\nassert bool(pat.search(s3)) == True",
"_____no_output_____"
]
],
[
[
"**d)** For the given input strings, match if the string begins with `Th` and also contains a line that starts with `There`.",
"_____no_output_____"
]
],
[
[
"s1 = 'There there\\nHave a cookie'\ns2 = 'This is a mess\\nYeah?\\nThereeeee'\ns3 = 'Oh\\nThere goes the fun'\n\npat = re.compile() ##### add your solution here\n\nassert bool(pat.search(s1)) == True\nassert bool(pat.search(s2)) == True\nassert bool(pat.search(s3)) == False",
"_____no_output_____"
]
],
[
[
"**e)** Explore what the `re.DEBUG` flag does. Here's some example patterns to check out.\n\n* `re.compile(r'\\Aden|ly\\Z', flags=re.DEBUG)`\n* `re.compile(r'\\b(0x)?[\\da-f]+\\b', flags=re.DEBUG)`\n* `re.compile(r'\\b(?:0x)?[\\da-f]+\\b', flags=re.I|re.DEBUG)`\n\n<br>\n\n# 11. Unicode\n\n**a)** Output `True` or `False` depending on input string made up of ASCII characters or not. Consider the input to be non-empty strings and any character that isn't part of 7-bit ASCII set should give `False`. Do you need regular expressions for this?",
"_____no_output_____"
]
],
[
[
"str1 = '123—456'\nstr2 = 'good fοοd'\nstr3 = 'happy learning!'\nstr4 = 'İıſK'\n\n##### add your solution here for str1\nassert ___ == False\n##### add your solution here for str2\nassert ___ == False\n##### add your solution here for str3\nassert ___ == True\n##### add your solution here for str4\nassert ___ == False",
"_____no_output_____"
]
],
[
[
"**b)** Does `.` quantifier with `re.ASCII` flag enabled match non-ASCII characters?\n\n**c)** Explore the following Q&A threads.\n\n* [stackoverflow: remove powered number from string](https://stackoverflow.com/questions/57553721/remove-powered-number-from-string-in-python)\n* [stackoverflow: regular expression for French characters](https://stackoverflow.com/questions/1922097/regular-expression-for-french-characters)\n\n<br>\n\n# 12. regex module\n\nThis part is super optional, it has you using the non-builtin `regex` module (https://pypi.org/project/regex/). I've never actually tried it. I skimmed through its features, and it doesn't strike me as adding *that* much more functionality.\n\n**a)** Filter all elements whose first non-whitespace character is not a `#` character. Any element made up of only whitespace characters should be ignored as well.",
"_____no_output_____"
]
],
[
[
"items = [' #comment', '\\t\\napple #42', '#oops', 'sure', 'no#1', '\\t\\r\\f']\n\n##### add your solution here\nassert ___ == ['\\t\\napple #42', 'sure', 'no#1']",
"_____no_output_____"
]
],
[
[
"**b)** Replace sequences made up of words separated by `:` or `.` by the first word of the sequence and the separator. Such sequences will end when `:` or `.` is not followed by a word character.",
"_____no_output_____"
]
],
[
[
"ip = 'wow:Good:2_two:five: hi bye kite.777.water.'\n\n##### add your solution here\nassert ___ == 'wow: hi bye kite.'",
"_____no_output_____"
]
],
[
[
"**c)** The given list of strings has fields separated by `:` character. Delete `:` and the last field if there is a digit character anywhere before the last field.",
"_____no_output_____"
]
],
[
[
"items = ['42:cat', 'twelve:a2b', 'we:be:he:0:a:b:bother']\n\n##### add your solution here\nassert ___ == ['42', 'twelve:a2b', 'we:be:he:0:a:b']",
"_____no_output_____"
]
],
[
[
"**d)** Extract all whole words unless they are preceded by `:` or `<=>` or `----` or `#`.",
"_____no_output_____"
]
],
[
[
"ip = '::very--at<=>row|in.a_b#b2c=>lion----east'\n\n##### add your solution here\nassert ___ == ['at', 'in', 'a_b', 'lion']",
"_____no_output_____"
]
],
[
[
"**e)** The given input string has fields separated by `:` character. Extract all fields if the previous field contains a digit character.",
"_____no_output_____"
]
],
[
[
"ip = 'vast:a2b2:ride:in:awe:b2b:3list:end'\n\n##### add your solution here\nassert ___ == ['ride', '3list', 'end']",
"_____no_output_____"
]
],
[
[
"**f)** The given input string has fields separated by `:` character. Delete all fields, including the separator, unless the field contains a digit character. Stop deleting once a field with digit character is found.",
"_____no_output_____"
]
],
[
[
"row1 = 'vast:a2b2:ride:in:awe:b2b:3list:end'\nrow2 = 'um:no:low:3e:s4w:seer'\n\npat = regex.compile() ##### add your solution here\n\nassert pat.sub('', row1) == 'a2b2:ride:in:awe:b2b:3list:end'\nassert pat.sub('', row2) == '3e:s4w:seer'",
"_____no_output_____"
]
],
[
[
"**g)** For the given input strings, extract `if` followed by any number of nested parentheses. Assume that there will be only one such pattern per input string.",
"_____no_output_____"
]
],
[
[
"ip1 = 'for (((i*3)+2)/6) if(3-(k*3+4)/12-(r+2/3)) while()'\nip2 = 'if+while if(a(b)c(d(e(f)1)2)3) for(i=1)'\n\npat = regex.compile() ##### add your solution here\n\nassert pat.search(ip1)[0] == 'if(3-(k*3+4)/12-(r+2/3))'\nassert pat.search(ip2)[0] == 'if(a(b)c(d(e(f)1)2)3)'",
"_____no_output_____"
]
],
[
[
"**h)** Read about `POSIX` flag from https://pypi.org/project/regex/. Is the following code snippet showing the correct output?",
"_____no_output_____"
]
],
[
[
"words = 'plink incoming tint winter in caution sentient'\n\nchange = regex.compile(r'int|in|ion|ing|inco|inter|ink', flags=regex.POSIX)\n\nassert change.sub('X', words) == 'plX XmX tX wX X cautX sentient'",
"_____no_output_____"
]
],
[
[
"**i)** Extract all whole words for the given input strings. However, based on user input `ignore`, do not match words if they contain any character present in the `ignore` variable.",
"_____no_output_____"
]
],
[
[
"s1 = 'match after the last newline character'\ns2 = 'and then you want to test'\n\nignore = 'aty'\nassert regex.findall() == ['newline']\nassert regex.findall() == []\n\nignore = 'esw'\nassert regex.findall() == ['match']\nassert regex.findall() == ['and', 'you', 'to']",
"_____no_output_____"
]
],
[
[
"**j)** Retain only punctuation characters for the given strings (generated from codepoints). Use Unicode character set definition for punctuation for solving this exercise.",
"_____no_output_____"
]
],
[
[
"s1 = ''.join(chr(c) for c in range(0, 0x80))\ns2 = ''.join(chr(c) for c in range(0x80, 0x100))\ns3 = ''.join(chr(c) for c in range(0x2600, 0x27ec))\n\npat = regex.compile() ##### add your solution here\n\nassert pat.sub('', s1) == '!\"#%&\\'()*,-./:;?@[\\\\]_{}'\nassert pat.sub('', s2) == '¡§«¶·»¿'\nassert pat.sub('', s3) == '❨❩❪❫❬❭❮❯❰❱❲❳❴❵⟅⟆⟦⟧⟨⟩⟪⟫'",
"_____no_output_____"
]
],
[
[
"**k)** For the given **markdown** file, replace all occurrences of the string `python` (irrespective of case) with the string `Python`. However, any match within code blocks that start with whole line ` ```python ` and end with whole line ` ``` ` shouldn't be replaced. Consider the input file to be small enough to fit memory requirements.\n\nRefer to [github: exercises folder](https://github.com/learnbyexample/py_regular_expressions/tree/master/exercises) for files `sample.md` and `expected.md` required to solve this exercise.",
"_____no_output_____"
]
],
[
[
"ip_str = open('sample.md', 'r').read()\npat = regex.compile() ##### add your solution here\nwith open('sample_mod.md', 'w') as op_file:\n ##### add your solution here\n\n305\nassert open('sample_mod.md').read() == open('expected.md').read()",
"_____no_output_____"
]
],
[
[
"**l)** For the given input strings, construct a word that is made up of last characters of all the words in the input. Use last character of last word as first character, last character of last but one word as second character and so on.",
"_____no_output_____"
]
],
[
[
"s1 = 'knack tic pi roar what'\ns2 = '42;rod;t2t2;car'\n\npat = regex.compile() ##### add your solution here\n\n##### add your solution here for s1\nassert ___ == 'trick'\n##### add your solution here for s2\nassert ___ == 'r2d2'",
"_____no_output_____"
]
],
[
[
"**m)** Replicate `str.rpartition` functionality with regular expressions. Split into three parts based on last match of sequences of digits, which is `777` and `12` for the given input strings.",
"_____no_output_____"
]
],
[
[
"s1 = 'Sample123string42with777numbers'\ns2 = '12apples'\n\n##### add your solution here for s1\nassert ___ == ['Sample123string42with', '777', 'numbers']\n##### add your solution here for s2\nassert ___ == ['', '12', 'apples']",
"_____no_output_____"
]
],
[
[
"**n)** Read about fuzzy matching on https://pypi.org/project/regex/. For the given input strings, return `True` if they are exactly same as `cat` or there is exactly one character difference. Ignore case when comparing differences. For example, `Ca2` should give `True`. `act` will be `False` even though the characters are same because position should be maintained.",
"_____no_output_____"
]
],
[
[
"pat = regex.compile() ##### add your solution here\n\nassert bool(pat.fullmatch('CaT')) == True\nassert bool(pat.fullmatch('scat')) == False\nassert bool(pat.fullmatch('ca.')) == True\nassert bool(pat.fullmatch('ca#')) == True\nassert bool(pat.fullmatch('c#t')) == True\nassert bool(pat.fullmatch('at')) == False\nassert bool(pat.fullmatch('act')) == False\nassert bool(pat.fullmatch('2a1')) == False",
"_____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",
"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"
],
[
"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",
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb067517a7676f7a54e9c8af33922b84ae50d7e2 | 2,265 | ipynb | Jupyter Notebook | Problem5-LevelMedium.ipynb | tyburam/daily-coding-problems | a2b871f9fce3d0fa422cb7adccd740ed594990bb | [
"MIT"
] | null | null | null | Problem5-LevelMedium.ipynb | tyburam/daily-coding-problems | a2b871f9fce3d0fa422cb7adccd740ed594990bb | [
"MIT"
] | null | null | null | Problem5-LevelMedium.ipynb | tyburam/daily-coding-problems | a2b871f9fce3d0fa422cb7adccd740ed594990bb | [
"MIT"
] | null | null | null | 19.358974 | 186 | 0.478146 | [
[
[
"## Problem statement\n\nGood morning! Here's your coding interview problem for today.\n\nThis problem was asked by Jane Street.\n\ncons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.\n\nGiven this implementation of cons:\n\n```\ndef cons(a, b):\n def pair(f):\n return f(a, b)\n return pair\n```\nImplement car and cdr.",
"_____no_output_____"
],
[
"## Implementations",
"_____no_output_____"
]
],
[
[
"def cons(a, b):\n def pair(f):\n return f(a, b)\n return pair",
"_____no_output_____"
],
[
"def car(pair):\n def first(a, b):\n return a\n return pair(first)",
"_____no_output_____"
],
[
"def cdr(pair):\n def last(a, b):\n return b\n return pair(last)",
"_____no_output_____"
]
],
[
[
"## Test",
"_____no_output_____"
]
],
[
[
"assert car(cons(3, 4)) == 3",
"_____no_output_____"
],
[
"assert cdr(cons(3, 4)) == 4",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb0675c513c41941cc2b648f187cf95ed29d9411 | 134,983 | ipynb | Jupyter Notebook | sourcecode/python/old/fakelite3_test.ipynb | magic-lantern/faker-prototype | 71015a8fce465a0dd554e464eeba27c52353eafa | [
"Apache-2.0"
] | 13 | 2018-06-05T17:04:07.000Z | 2021-09-03T16:38:41.000Z | sourcecode/python/old/fakelite3_test.ipynb | magic-lantern/faker-prototype | 71015a8fce465a0dd554e464eeba27c52353eafa | [
"Apache-2.0"
] | 6 | 2018-10-15T15:58:00.000Z | 2019-06-13T21:46:00.000Z | sourcecode/python/old/fakelite3_test.ipynb | magic-lantern/faker-prototype | 71015a8fce465a0dd554e464eeba27c52353eafa | [
"Apache-2.0"
] | 2 | 2018-08-09T04:58:29.000Z | 2018-09-10T21:07:18.000Z | 40.645288 | 7,044 | 0.401073 | [
[
[
"import sqlite3\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nimport scipy.stats as stats\n#import pylab as plt\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nfrom numpy.random import choice\n\n%matplotlib notebook\n\n\ndbname = '../../data/sepsis.db'\nconn = sqlite3.connect(dbname)\n\nsql = 'SELECT * FROM \"diagnoses\"'\n\ndf = pd.read_sql(sql,conn)",
"_____no_output_____"
],
[
"df.head()\n",
"_____no_output_____"
],
[
"from importlib import reload\nfrom fakelite3 import KungFauxPandas\n\nkfpd = KungFauxPandas()\nfdf=kfpd.read_sql(sql,conn)\nfdf.head()",
"Processing column Unnamed: 0 as a int64\nProcessing column SubjectId as a int64\nProcessing column EncounterId as a int64\nProcessing column Source as a object\nProcessing column StartDate as a object\nProcessing column Code as a object\nProcessing column Type as a object\n"
],
[
"col = 'Code'\nout_dict = dict()\n\ncolfact = df[col].factorize()\ncc=Counter(colfact[0])\n \n# convert from counts to proportions\n\nfor key in cc:\n cc[key] = cc[key] / len(df)\n\nfakes = choice(elements,p=weights, replace=True, size=len(df))\n\nout_dict[col] = [colfact[1][xx] for xx in fakes]\n",
"_____no_output_____"
],
[
"len(cc.values()), len(df), len(cc)/len(df)",
"_____no_output_____"
],
[
"col = 'Code'\nout_dict = dict()\n\ncolfact = df[col].factorize()\ncc=Counter(colfact[0])\n \n# convert from counts to proportions\n\nfor key in cc:\n cc[key] = cc[key] / len(df)\n\nfakes = choice(elements,p=weights, replace=True, size=len(df))\n\nout_dict[col] = [colfact[1][xx] for xx in fakes]\n#out_dict",
"_____no_output_____"
],
[
"col = 'SubjectId'\nkd = stats.gaussian_kde(df[col], bw_method='silverman')\nout_dict[col]=np.int64(kd.resample()[0])\n",
"_____no_output_____"
],
[
"\n\n",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"pd.crosstab(df.Codeode, df.squishcode)",
"_____no_output_____"
],
[
"np.corrcoef(df.Code, df.squishcode)",
"_____no_output_____"
],
[
"sdf = df.sample(5000)\nfor thiscol in sdf.columns:\n if sdf[thiscol].dtype=='object':\n print('Converting column ', thiscol)\n sdf[thiscol] = sdf[thiscol].factorize()[0]\n \n#np.cov(sdf)",
"Converting column Source\nConverting column StartDate\nConverting column Code\nConverting column Type\n"
],
[
"cc = np.corrcoef(sdf.transpose())\n#cc = np.cov(sdf.transpose())\n#cc[5,1]\nplt.imshow(cc,cmap='inferno')\nplt.colorbar()",
"/Users/seth/OneDrive - The University of Colorado Denver/Documents/ICML_2018_Paper/faker-prototype/sourcecode/python/kungfauxpandas/lib/python3.6/site-packages/numpy/lib/function_base.py:3183: RuntimeWarning: invalid value encountered in true_divide\n c /= stddev[:, None]\n/Users/seth/OneDrive - The University of Colorado Denver/Documents/ICML_2018_Paper/faker-prototype/sourcecode/python/kungfauxpandas/lib/python3.6/site-packages/numpy/lib/function_base.py:3184: RuntimeWarning: invalid value encountered in true_divide\n c /= stddev[None, :]\n"
],
[
"#sdf.head()\n#help(np.correlate)\ndf.iloc[3]",
"_____no_output_____"
],
[
"from statsmodels.nonparametric import kernel_density as kd",
"_____no_output_____"
],
[
"woo = kd.KDEMultivariate(np.array(sdf.iloc[:,[2,4,9]]), var_type=3*'u')\n#help(kd.KDEMultivariate)",
"_____no_output_____"
],
[
"np.array(data=sdf.sample(2000).iloc[:,[2,4,9]])",
"_____no_output_____"
],
[
"xx = range(40)\nbb = list(itertools.product(xx,xx,xx))",
"_____no_output_____"
],
[
"np.array(sdf.iloc[2]).shape",
"_____no_output_____"
],
[
"from scipy.optimize import fsolve\nimport statsmodels.api as sm\nimport numpy as np\n\n# fit\nkde = woo#sm.nonparametric.KDEMultivariate() # ... you already did this\n\n# sample\nu = np.random.random()\n\n# 1-d root-finding\ndef func(x):\n return kde.cdf([x]) - u\n#sample_x = brentq(func, -99999999, 99999999) # read brentq-docs about these constants\n # constants need to be sign-changing for the function\n",
"_____no_output_____"
],
[
"#u = np.random.random()\n#u\n#sample_x = brentq(func, -99999999, 99999999)",
"_____no_output_____"
],
[
"def func(x):\n return kde.cdf([x]) - u\n\nx0=[92,4,5,3,6,7,8,9,10,11]\n",
"_____no_output_____"
],
[
"from scipy.optimize import minimize\ndarf = minimize(func,np.array(x0))\nprint(darf)",
" fun: -0.9488937871588804\n hess_inv: array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]])\n jac: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])\n message: 'Optimization terminated successfully.'\n nfev: 12\n nit: 0\n njev: 1\n status: 0\n success: True\n x: array([ 992., 4., 5., 3., 6., 7., 8., 9., 10., 11.])\n"
],
[
"x0, func(x0)\n",
"_____no_output_____"
],
[
"func([0,0,0,0,0,3,0,0,0,0])",
"_____no_output_____"
],
[
"bork = np.mgrid[0:10,0:10, 0:10]",
"_____no_output_____"
],
[
"xx = range(4)\n\nimport itertools\nins = list(itertools.product(xx,xx,xx,xx,xx,xx,xx,xx,xx,xx))\n\nvals = [func(i) for i in ins[1004:2004]]\nfunc(ins[1004:2004])",
"_____no_output_____"
],
[
"func(bork[32532])",
"_____no_output_____"
],
[
"u\n",
"_____no_output_____"
],
[
"#kde.cdf(bork[9000:10000])\nfunc(x0)",
"_____no_output_____"
],
[
"list(bork[0])",
"_____no_output_____"
],
[
"x0",
"_____no_output_____"
],
[
"import statsmodels.api as sm\nnobs = 300\nnp.random.seed(1234) # Seed random generator\nc1 = np.random.normal(size=(nobs,1))\nc2 = np.random.normal(2, 1, size=(nobs,1))\n \n#Estimate a bivariate distribution and display the bandwidth found:\n \n#dens_u = sm.nonparametric.KDEMultivariate(data=[c1,c2], var_type='cc', bw='normal_reference')\n#dens_u.bw\n\nwoo = sm.nonparametric.KDEMultivariate(data=sdf.iloc[:,[2,4,9]], var_type=3*'u')\n\n",
"_____no_output_____"
],
[
"woo.cdf()",
"_____no_output_____"
],
[
"len(sdf)",
"_____no_output_____"
],
[
"len(set(sdf.iloc[:,9]))",
"_____no_output_____"
],
[
"np.corrcoef(sdf.iloc[:,[2,9]])",
"_____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",
"code",
"code",
"code",
"code"
]
] |
cb067c53165a141201f2ebc8e85c1e337c1fe005 | 1,553 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Untitled4-checkpoint.ipynb | junaid1460/deep_learning_tf_keras | 4b33851a111fd8170d0c673077482d3d7837fd6e | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Untitled4-checkpoint.ipynb | junaid1460/deep_learning_tf_keras | 4b33851a111fd8170d0c673077482d3d7837fd6e | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Untitled4-checkpoint.ipynb | junaid1460/deep_learning_tf_keras | 4b33851a111fd8170d0c673077482d3d7837fd6e | [
"MIT"
] | null | null | null | 18.710843 | 67 | 0.51642 | [
[
[
"import random\nimport cv2\nimport PIL.Image as image",
"_____no_output_____"
],
[
"img = image.open('dd.jpg')",
"_____no_output_____"
],
[
"def noise(x):\n return random.randint(x-30, x+10)\n\nimg = img.point(lambda x: noise(x))",
"_____no_output_____"
],
[
"img",
"IOPub data rate exceeded.\nThe notebook server will temporarily stop sending output\nto the client in order to avoid crashing it.\nTo change this limit, set the config variable\n`--NotebookApp.iopub_data_rate_limit`.\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
cb06894ff6e6955d2ac9397bda1dea8f77fddc6b | 7,012 | ipynb | Jupyter Notebook | tensorflow-lite/export_model.ipynb | kenttw/deeplearning_homework | 846799712dddd2267a7c18245deac9a2cad41422 | [
"MIT"
] | 5 | 2017-11-14T14:47:12.000Z | 2021-09-20T04:26:31.000Z | tensorflow-lite/export_model.ipynb | texib/deeplearning_homework | 846799712dddd2267a7c18245deac9a2cad41422 | [
"MIT"
] | null | null | null | tensorflow-lite/export_model.ipynb | texib/deeplearning_homework | 846799712dddd2267a7c18245deac9a2cad41422 | [
"MIT"
] | 3 | 2018-04-23T08:53:30.000Z | 2021-09-20T04:26:33.000Z | 31.026549 | 142 | 0.549914 | [
[
[
"# 以下為 Export 成 freeze_graph 的範例程式嗎",
"_____no_output_____"
]
],
[
[
"from keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.optimizers import SGD\nfrom keras import backend as K\n\nimport tensorflow as tf\nfrom tensorflow.python.tools import freeze_graph, optimize_for_inference_lib\n\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"## Exprot to frezen model 的標準作法\n* 由於在 Tensorflow Lite \n* 但在使用之前需要 Session 載入 Graph & Weight\n* tf.train.write_graph :如果是使用 Keras 的話就是用 K.get_session().graph_def 取得 grpah ,然後輸到 phtxt\n* tf.train.Saver() : 透過 K.get_session() 取得 Session ,而後透過 tf.train.Saver().save()",
"_____no_output_____"
]
],
[
[
"def export_model_for_mobile(model_name, input_node_name, output_node_name):\n \n \n # 先暫存成另一個檔檔\n tf.train.write_graph(K.get_session().graph_def, 'out', \\\n model_name + '_graph.pbtxt')\n\n tf.train.Saver().save(K.get_session(), 'out/' + model_name + '.chkp')\n\n freeze_graph.freeze_graph('out/' + model_name + '_graph.pbtxt', None, \\\n False, 'out/' + model_name + '.chkp', output_node_name, \\\n \"save/restore_all\", \"save/Const:0\", \\\n 'out/frozen_' + model_name + '.pb', True, \"\")\n\n input_graph_def = tf.GraphDef()\n with tf.gfile.Open('out/frozen_' + model_name + '.pb', \"rb\") as f:\n input_graph_def.ParseFromString(f.read())\n\n output_graph_def = optimize_for_inference_lib.optimize_for_inference(\n input_graph_def, [input_node_name], [output_node_name],\n tf.float32.as_datatype_enum)\n\n with tf.gfile.FastGFile('out/tensorflow_lite_' + model_name + '.pb', \"wb\") as f:\n f.write(output_graph_def.SerializeToString())",
"_____no_output_____"
]
],
[
[
"## 創建 Graph",
"_____no_output_____"
]
],
[
[
"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras import backend as K\n\nmodel = Sequential([\n\n Conv2D(8, (3, 3), activation='relu', input_shape=[128,128,3]),\n MaxPooling2D(pool_size=(2, 2)),\n Conv2D(8, (3, 3), activation='relu'),\n MaxPooling2D(pool_size=(2, 2)),\n Flatten(),\n Dense(128),\n Activation('relu'),\n Dense(7),\n Activation('softmax') \n])\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 126, 126, 8) 224 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 63, 63, 8) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 61, 61, 8) 584 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 30, 30, 8) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 7200) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 128) 921728 \n_________________________________________________________________\nactivation_1 (Activation) (None, 128) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 7) 903 \n_________________________________________________________________\nactivation_2 (Activation) (None, 7) 0 \n=================================================================\nTotal params: 923,439\nTrainable params: 923,439\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.load_weights(\"/home/kent/git/DeepLearning_ClassmatesImageClassification_jdwang2018_5_25/CNN_Classfier_32X32_jdwang_Weight_1.h5\")",
"_____no_output_____"
]
],
[
[
"## 呼叫預設的函式",
"_____no_output_____"
]
],
[
[
"export_model_for_mobile('classmate_new', model.input.name.split(\":\")[0], model.output.name.split(\":\")[0])",
"INFO:tensorflow:Restoring parameters from out/classmate_new.chkp\nINFO:tensorflow:Froze 8 variables.\nConverted 8 variables to const ops.\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb06895d60d1ade9f39a6b080e9cebb17e560974 | 929,121 | ipynb | Jupyter Notebook | code/.ipynb_checkpoints/Rover_Project_Test_Notebook-checkpoint.ipynb | joeross999/RoboND-Rover-Project | a786cbe01ddee5df6b018603fe245e1e4c18c09e | [
"MIT"
] | null | null | null | code/.ipynb_checkpoints/Rover_Project_Test_Notebook-checkpoint.ipynb | joeross999/RoboND-Rover-Project | a786cbe01ddee5df6b018603fe245e1e4c18c09e | [
"MIT"
] | null | null | null | code/.ipynb_checkpoints/Rover_Project_Test_Notebook-checkpoint.ipynb | joeross999/RoboND-Rover-Project | a786cbe01ddee5df6b018603fe245e1e4c18c09e | [
"MIT"
] | null | null | null | 1,205.085603 | 499,244 | 0.951124 | [
[
[
"## Rover Project Test Notebook\nThis notebook contains the functions from the lesson and provides the scaffolding you need to test out your mapping methods. The steps you need to complete in this notebook for the project are the following:\n\n* First just run each of the cells in the notebook, examine the code and the results of each.\n* Run the simulator in \"Training Mode\" and record some data. Note: the simulator may crash if you try to record a large (longer than a few minutes) dataset, but you don't need a ton of data, just some example images to work with. \n* Change the data directory path (2 cells below) to be the directory where you saved data\n* Test out the functions provided on your data\n* Write new functions (or modify existing ones) to report and map out detections of obstacles and rock samples (yellow rocks)\n* Populate the `process_image()` function with the appropriate steps/functions to go from a raw image to a worldmap.\n* Run the cell that calls `process_image()` using `moviepy` functions to create video output\n* Once you have mapping working, move on to modifying `perception.py` and `decision.py` to allow your rover to navigate and map in autonomous mode!\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n**Run the next cell to get code highlighting in the markdown cells.**",
"_____no_output_____"
]
],
[
[
"%%HTML\n<style> code {background-color : orange !important;} </style>",
"_____no_output_____"
],
[
"%matplotlib inline\n#%matplotlib qt # Choose %matplotlib qt to plot to an interactive window (note it may show up behind your browser)\n# Make some of the relevant imports\nimport os\nprint(os.sys.path)\nimport cv2 # OpenCV for perspective transform\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport scipy.misc # For saving images as needed\nimport glob # For reading in a list of images from a folder\nimport imageio\nimageio.plugins.ffmpeg.download()\n",
"['', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND\\\\python35.zip', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND\\\\DLLs', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND\\\\lib', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND\\\\lib\\\\site-packages', 'C:\\\\Users\\\\joero\\\\Anaconda3\\\\envs\\\\RoboND\\\\lib\\\\site-packages\\\\IPython\\\\extensions', 'C:\\\\Users\\\\joero\\\\.ipython']\n"
]
],
[
[
"## Quick Look at the Data\nThere's some example data provided in the `test_dataset` folder. This basic dataset is enough to get you up and running but if you want to hone your methods more carefully you should record some data of your own to sample various scenarios in the simulator. \n\nNext, read in and display a random image from the `test_dataset` folder",
"_____no_output_____"
]
],
[
[
"path = 'C:/Users/joero/Documents/Development/Udacity/RoboticsNanodegree/roversim/IMG/IMG/*'\nimg_list = glob.glob(path)\n# Grab a random image and display it\nidx = np.random.randint(0, len(img_list)-1)\nimage = mpimg.imread(img_list[idx])\nplt.imshow(image)",
"_____no_output_____"
],
[
"# In the simulator you can toggle on a grid on the ground for calibration\n# You can also toggle on the rock samples with the 0 (zero) key. \n# Here's an example of the grid and one of the rocks\nexample_grid = '../calibration_images/example_grid1.jpg'\nexample_rock = '../calibration_images/example_rock1.jpg'\ngrid_img = mpimg.imread(example_grid)\nrock_img = mpimg.imread(example_rock)\n\nfig = plt.figure(figsize=(12,3))\nplt.subplot(121)\nplt.imshow(grid_img)\nplt.subplot(122)\nplt.imshow(rock_img)",
"_____no_output_____"
]
],
[
[
"## Calibration Data\nRead in and display example grid and rock sample calibration images. You'll use the grid for perspective transform and the rock image for creating a new color selection that identifies these samples of interest. ",
"_____no_output_____"
],
[
"## Perspective Transform\n\nDefine the perspective transform function from the lesson and test it on an image.",
"_____no_output_____"
]
],
[
[
"# Define a function to perform a perspective transform\n# I've used the example grid image above to choose source points for the\n# grid cell in front of the rover (each grid cell is 1 square meter in the sim)\n# Define a function to perform a perspective transform\ndef perspect_transform(img, src, dst):\n \n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\n \n return warped\n\n\n# Define calibration box in source (actual) and destination (desired) coordinates\n# These source and destination points are defined to warp the image\n# to a grid where each 10x10 pixel square represents 1 square meter\n# The destination box will be 2*dst_size on each side\ndst_size = 5 \n# Set a bottom offset to account for the fact that the bottom of the image \n# is not the position of the rover but a bit in front of it\n# this is just a rough guess, feel free to change it!\nbottom_offset = 6\nsource = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\ndestination = np.float32([[image.shape[1]/2 - dst_size, image.shape[0] - bottom_offset],\n [image.shape[1]/2 + dst_size, image.shape[0] - bottom_offset],\n [image.shape[1]/2 + dst_size, image.shape[0] - 2*dst_size - bottom_offset], \n [image.shape[1]/2 - dst_size, image.shape[0] - 2*dst_size - bottom_offset],\n ])\nwarped = perspect_transform(grid_img, source, destination)\nplt.imshow(warped)\n#scipy.misc.imsave('../output/warped_example.jpg', warped)",
"_____no_output_____"
]
],
[
[
"## Color Thresholding\nDefine the color thresholding function from the lesson and apply it to the warped image\n\n**TODO:** Ultimately, you want your map to not just include navigable terrain but also obstacles and the positions of the rock samples you're searching for. Modify this function or write a new function that returns the pixel locations of obstacles (areas below the threshold) and rock samples (yellow rocks in calibration images), such that you can map these areas into world coordinates as well. \n**Hints and Suggestion:** \n* For obstacles you can just invert your color selection that you used to detect ground pixels, i.e., if you've decided that everything above the threshold is navigable terrain, then everthing below the threshold must be an obstacle!\n\n\n* For rocks, think about imposing a lower and upper boundary in your color selection to be more specific about choosing colors. You can investigate the colors of the rocks (the RGB pixel values) in an interactive matplotlib window to get a feel for the appropriate threshold range (keep in mind you may want different ranges for each of R, G and B!). Feel free to get creative and even bring in functions from other libraries. Here's an example of [color selection](http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html) using OpenCV. \n\n* **Beware However:** if you start manipulating images with OpenCV, keep in mind that it defaults to `BGR` instead of `RGB` color space when reading/writing images, so things can get confusing.",
"_____no_output_____"
]
],
[
[
"# Identify pixels above the threshold\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\n # Create an array of zeros same xy size as img, but single channel\n color_select = np.zeros_like(img[:,:,0])\n # Require that each pixel be above all three threshold values in RGB\n # above_thresh will now contain a boolean array with \"True\"\n # where threshold was met\n above_thresh = (img[:,:,0] > rgb_thresh[0]) \\\n & (img[:,:,1] > rgb_thresh[1]) \\\n & (img[:,:,2] > rgb_thresh[2])\n # Index the array of zeros with the boolean array and set to 1\n color_select[above_thresh] = 1\n # Return the binary image\n return color_select\n\nthreshed = color_thresh(warped)\nplt.imshow(threshed, cmap='gray')\n#scipy.misc.imsave('../output/warped_threshed.jpg', threshed*255)",
"_____no_output_____"
]
],
[
[
"## Coordinate Transformations\nDefine the functions used to do coordinate transforms and apply them to an image.",
"_____no_output_____"
]
],
[
[
"# Define a function to convert from image coords to rover coords\ndef rover_coords(binary_img):\n # Identify nonzero pixels\n ypos, xpos = binary_img.nonzero()\n # Calculate pixel positions with reference to the rover position being at the \n # center bottom of the image. \n x_pixel = -(ypos - binary_img.shape[0]).astype(np.float)\n y_pixel = -(xpos - binary_img.shape[1]/2 ).astype(np.float)\n return x_pixel, y_pixel\n\n# Define a function to convert to radial coords in rover space\ndef to_polar_coords(x_pixel, y_pixel):\n # Convert (x_pixel, y_pixel) to (distance, angle) \n # in polar coordinates in rover space\n # Calculate distance to each pixel\n dist = np.sqrt(x_pixel**2 + y_pixel**2)\n # Calculate angle away from vertical for each pixel\n angles = np.arctan2(y_pixel, x_pixel)\n return dist, angles\n\n# Define a function to map rover space pixels to world space\ndef rotate_pix(xpix, ypix, yaw):\n # Convert yaw to radians\n yaw_rad = yaw * np.pi / 180\n xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad))\n \n ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))\n # Return the result \n return xpix_rotated, ypix_rotated\n\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \n # Apply a scaling and a translation\n xpix_translated = (xpix_rot / scale) + xpos\n ypix_translated = (ypix_rot / scale) + ypos\n # Return the result \n return xpix_translated, ypix_translated\n\n\n# Define a function to apply rotation and translation (and clipping)\n# Once you define the two functions above this function should work\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\n # Apply rotation\n xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\n # Apply translation\n xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\n # Perform rotation, translation and clipping all at once\n x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\n y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\n # Return the result\n return x_pix_world, y_pix_world\n\n# Grab another random image\nidx = np.random.randint(0, len(img_list)-1)\nimage = mpimg.imread(img_list[idx])\nwarped = perspect_transform(image, source, destination)\nthreshed = color_thresh(warped)\n\n# Calculate pixel values in rover-centric coords and distance/angle to all pixels\nxpix, ypix = rover_coords(threshed)\ndist, angles = to_polar_coords(xpix, ypix)\nmean_dir = np.mean(angles)\n\n# Do some plotting\nfig = plt.figure(figsize=(12,9))\nplt.subplot(221)\nplt.imshow(image)\nplt.subplot(222)\nplt.imshow(warped)\nplt.subplot(223)\nplt.imshow(threshed, cmap='gray')\nplt.subplot(224)\nplt.plot(xpix, ypix, '.')\nplt.ylim(-160, 160)\nplt.xlim(0, 160)\narrow_length = 100\nx_arrow = arrow_length * np.cos(mean_dir)\ny_arrow = arrow_length * np.sin(mean_dir)\nplt.arrow(0, 0, x_arrow, y_arrow, color='red', zorder=2, head_width=10, width=2)\n\n",
"_____no_output_____"
]
],
[
[
"## Read in saved data and ground truth map of the world\nThe next cell is all setup to read your saved data into a `pandas` dataframe. Here you'll also read in a \"ground truth\" map of the world, where white pixels (pixel value = 1) represent navigable terrain. \n\nAfter that, we'll define a class to store telemetry data and pathnames to images. When you instantiate this class (`data = Databucket()`) you'll have a global variable called `data` that you can refer to for telemetry and map data within the `process_image()` function in the following cell. \n",
"_____no_output_____"
]
],
[
[
"# Import pandas and read in csv file as a dataframe\nimport pandas as pd\n# Change the path below to your data directory\n# If you are in a locale (e.g., Europe) that uses ',' as the decimal separator\n# change the '.' to ','\ndf = pd.read_csv('../test_dataset/robot_log.csv', delimiter=';', decimal='.')\ncsv_img_list = df[\"Path\"].tolist() # Create list of image pathnames\n# Read in ground truth map and create a 3-channel image with it\nground_truth = mpimg.imread('../calibration_images/map_bw.png')\nground_truth_3d = np.dstack((ground_truth*0, ground_truth*255, ground_truth*0)).astype(np.float)\n\n# Creating a class to be the data container\n# Will read in saved data from csv file and populate this object\n# Worldmap is instantiated as 200 x 200 grids corresponding \n# to a 200m x 200m space (same size as the ground truth map: 200 x 200 pixels)\n# This encompasses the full range of output position values in x and y from the sim\nclass Databucket():\n def __init__(self):\n self.images = csv_img_list \n self.xpos = df[\"X_Position\"].values\n self.ypos = df[\"Y_Position\"].values\n self.yaw = df[\"Yaw\"].values\n self.count = 0 # This will be a running index\n self.worldmap = np.zeros((200, 200, 3)).astype(np.float)\n self.ground_truth = ground_truth_3d # Ground truth worldmap\n\n# Instantiate a Databucket().. this will be a global variable/object\n# that you can refer to in the process_image() function below\ndata = Databucket()\n",
"_____no_output_____"
]
],
[
[
"## Write a function to process stored images\n\nModify the `process_image()` function below by adding in the perception step processes (functions defined above) to perform image analysis and mapping. The following cell is all set up to use this `process_image()` function in conjunction with the `moviepy` video processing package to create a video from the images you saved taking data in the simulator. \n\nIn short, you will be passing individual images into `process_image()` and building up an image called `output_image` that will be stored as one frame of video. You can make a mosaic of the various steps of your analysis process and add text as you like (example provided below). \n\n\n\nTo start with, you can simply run the next three cells to see what happens, but then go ahead and modify them such that the output video demonstrates your mapping process. Feel free to get creative!",
"_____no_output_____"
]
],
[
[
"\n# Define a function to pass stored images to\n# reading rover position and yaw angle from csv file\n# This function will be used by moviepy to create an output video\ndef process_image(img):\n image = img\n # Transform Perspective to top down view.\n source = np.float32([[ 14, 140], [ 302, 140], [ 200, 95], [ 118, 95]])\n destination_size = 5\n bottom_offset = 6\n destination = np.float32([[image.shape[1]/2 - destination_size, image.shape[0] - bottom_offset], \n [image.shape[1]/2 + destination_size, image.shape[0] - bottom_offset], \n [image.shape[1]/2 + destination_size, image.shape[0] - 2 * destination_size - bottom_offset], \n [image.shape[1]/2 - destination_size, image.shape[0] - 2 * destination_size - bottom_offset]])\n image_perspective = perspect_transform(image, source, destination)\n\n # Color Transform\n image_color_transform_ground = color_thresh(image_perspective)\n image_color_transform_walls = np.zeros_like(image_color_transform_ground)\n showWalls = image_color_transform_ground[: ,:] == 0\n image_color_transform_walls[showWalls] = 1\n\n# data.ground_truth[:,:,0] = image_color_transform_walls * 255\n# data.ground_truth[:,:,1] = image_color_transform_rocks * 255\n# data.ground_truth[:,:,2] = image_color_transform_ground * 255\n\n # converting to rover-centric coords\n xpix_ground, ypix_ground = rover_coords(image_color_transform_ground)\n xpix_walls, ypix_walls = rover_coords(image_color_transform_walls)\n\n # Converting to world coordinates\n scale = 10\n world_size = 200\n xpos = data.xpos[data.count]\n ypos = data.ypos[data.count]\n yaw = data.yaw[data.count]\n x_world_ground, y_world_ground = pix_to_world(xpix_ground, ypix_ground, xpos, \n ypos, yaw, \n world_size, scale)\n x_world_walls, y_world_walls = pix_to_world(xpix_walls, ypix_walls, xpos, \n ypos, yaw, \n world_size, scale)\n\n data.worldmap[y_world_walls, x_world_walls, 0] = 255\n data.worldmap[y_world_ground, x_world_ground, 2] += 1\n\n distances, angles = to_polar_coords(xpix_ground, ypix_ground) # Convert to polar coords\n avg_angle = np.mean(angles) # Compute the average angle\n\n# Rover.nav_angles = angles # Angles of navigable terrain pixels\n# Rover.nav_dists = distances\n \n # Example of how to use the Databucket() object defined above\n # to print the current x, y and yaw values \n # print(data.xpos[data.count], data.ypos[data.count], data.yaw[data.count])\n\n # TODO: \n # 1) Define source and destination points for perspective transform\n # 2) Apply perspective transform\n # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\n # 4) Convert thresholded image pixel values to rover-centric coords\n # 5) Convert rover-centric pixel values to world coords\n # 6) Update worldmap (to be displayed on right side of screen)\n # Example: data.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1\n # data.worldmap[rock_y_world, rock_x_world, 1] += 1\n # data.worldmap[navigable_y_world, navigable_x_world, 2] += 1\n\n # 7) Make a mosaic image, below is some example code\n # First create a blank image (can be whatever shape you like)\n output_image = np.zeros((img.shape[0] + data.worldmap.shape[0], img.shape[1]*2, 3))\n # Next you can populate regions of the image with various output\n # Here I'm putting the original image in the upper left hand corner\n output_image[0:img.shape[0], 0:img.shape[1]] = img\n\n # Let's create more images to add to the mosaic, first a warped image\n warped = perspect_transform(img, source, destination)\n # Add the warped image in the upper right hand corner\n output_image[0:img.shape[0], img.shape[1]:] = image_perspective\n\n # Overlay worldmap with ground truth map\n map_add = cv2.addWeighted(data.worldmap, 1, data.ground_truth, 0.5, 0)\n # Flip map overlay so y-axis points upward and add to output_image \n output_image[img.shape[0]:, 0:data.worldmap.shape[1]] = np.flipud(map_add)\n\n\n # Then putting some text over the image\n cv2.putText(output_image,\"Populate this image with your analyses to make a video!\", (20, 20), \n cv2.FONT_HERSHEY_COMPLEX, 0.4, (255, 255, 255), 1)\n if data.count < len(data.images) - 1:\n data.count += 1 # Keep track of the index in the Databucket()\n \n return output_image",
"_____no_output_____"
]
],
[
[
"## Make a video from processed image data\nUse the [moviepy](https://zulko.github.io/moviepy/) library to process images and create a video.\n ",
"_____no_output_____"
]
],
[
[
"# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom moviepy.editor import ImageSequenceClip\n\n\n# Define pathname to save the output video\noutput = '../output/test_mapping.mp4'\ndata = Databucket() # Re-initialize data in case you're running this cell multiple times\nclip = ImageSequenceClip(data.images, fps=60) # Note: output video will be sped up because \n # recording rate in simulator is fps=25\nnew_clip = clip.fl_image(process_image) #NOTE: this function expects color images!!\n%time new_clip.write_videofile(output, audio=False)",
"_____no_output_____"
]
],
[
[
"### This next cell should function as an inline video player\nIf this fails to render the video, try running the following cell (alternative video rendering method). You can also simply have a look at the saved mp4 in your `/output` folder",
"_____no_output_____"
]
],
[
[
"\nfrom IPython.display import HTML\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(output))",
"_____no_output_____"
]
],
[
[
"### Below is an alternative way to create a video in case the above cell did not work.",
"_____no_output_____"
]
],
[
[
"import io\nimport base64\nvideo = io.open(output, 'r+b').read()\nencoded_video = base64.b64encode(video)\nHTML(data='''<video alt=\"test\" controls>\n <source src=\"data:video/mp4;base64,{0}\" type=\"video/mp4\" />\n </video>'''.format(encoded_video.decode('ascii')))",
"_____no_output_____"
]
]
] | [
"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"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb0693a29976511579880f175bb91120543d7535 | 6,246 | ipynb | Jupyter Notebook | Notebook/_index.ipynb | gdsa-upc/2018-Equip3 | e4e06d209442a61826f95aec7adcc0a9a31e0a54 | [
"MIT"
] | null | null | null | Notebook/_index.ipynb | gdsa-upc/2018-Equip3 | e4e06d209442a61826f95aec7adcc0a9a31e0a54 | [
"MIT"
] | null | null | null | Notebook/_index.ipynb | gdsa-upc/2018-Equip3 | e4e06d209442a61826f95aec7adcc0a9a31e0a54 | [
"MIT"
] | null | null | null | 25.917012 | 256 | 0.567083 | [
[
[
"##### Copyright 2018 The TensorFlow Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");",
"_____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_____"
]
],
[
[
"# Get Started with TensorFlow",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\"><td>\n<a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /><span>Run in Google Colab</span></a> \n</td><td>\n<a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /><span>View source on GitHub</span></a></td></table>",
"_____no_output_____"
],
[
"This is a [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To run the Colab notebook:\n\n1. Connect to a Python runtime: At the top-right of the menu bar, select *CONNECT*.\n2. Run all the notebook code cells: Select *Runtime* > *Run all*.\n\nFor more examples and guides (including details for this program), see [Get Started with TensorFlow](https://www.tensorflow.org/get_started/).\n\nLet's get started, import the TensorFlow library into your program:",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf",
"_____no_output_____"
]
],
[
[
"Load and prepare the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. Convert the samples from integers to floating-point numbers:",
"_____no_output_____"
]
],
[
[
"mnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0",
"_____no_output_____"
]
],
[
[
"Build the `tf.keras` model by stacking layers. Select an optimizer and loss function used for training:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"Train and evaluate model:",
"_____no_output_____"
]
],
[
[
"model.fit(x_train, y_train, epochs=5)\n\nmodel.evaluate(x_test, y_test)",
"_____no_output_____"
]
],
[
[
"You’ve now trained an image classifier with ~98% accuracy on this dataset. See [Get Started with TensorFlow](https://www.tensorflow.org/get_started/) to learn more.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb06afdb63183d1a0e0076bc0065cf5171ae1a4b | 69,567 | ipynb | Jupyter Notebook | quantfin/financial-signal-processing/stochastic-calculus/pset2/stoch_calc_pset_q1.ipynb | georgh0021/PaTSwAPS | 62db213d3ec55a2d396a6ab884f2ce2f70a9feaa | [
"MIT"
] | 16 | 2018-08-24T13:05:50.000Z | 2020-03-25T04:34:49.000Z | quantfin/financial-signal-processing/stochastic-calculus/pset2/stoch_calc_pset_q1.ipynb | eigenfoo/random | 62db213d3ec55a2d396a6ab884f2ce2f70a9feaa | [
"MIT"
] | null | null | null | quantfin/financial-signal-processing/stochastic-calculus/pset2/stoch_calc_pset_q1.ipynb | eigenfoo/random | 62db213d3ec55a2d396a6ab884f2ce2f70a9feaa | [
"MIT"
] | 4 | 2018-09-18T14:40:51.000Z | 2019-10-01T13:08:03.000Z | 283.946939 | 64,144 | 0.926215 | [
[
[
"# Stochastic Calculus Problem Set II Question 1",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')",
"_____no_output_____"
],
[
"delta = 0.01\nN = 250\n\nS_0 = 1\nalpha = 0.1 / N\nsigma = alpha\nr = alpha / 3",
"_____no_output_____"
]
],
[
[
"## Part (a)",
"_____no_output_____"
]
],
[
[
"# alpha dt + sigma dW\nS = np.hstack([np.ones(shape=[1000, 1]),\n alpha*delta + sigma*np.random.normal(loc=0,\n scale=delta,\n size=[1000, N - 1])]).T\n\n# This accumulates to make the Brownian motion\nfor idx, row in enumerate(S[:-1]):\n S[idx + 1] *= row\n S[idx + 1] += row",
"_____no_output_____"
],
[
"# Python 0-indexes, so N/2 = 125 = index 124\n# Mean stock price at time t = 125 is ~ 1.0005\nprint(np.mean(S[N // 2 - 1]))",
"1.0004949287399365\n"
]
],
[
[
"## Part (b)",
"_____no_output_____"
]
],
[
[
"# 10 paths\npaths = S[:, :10]",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=[8, 6])\nax.plot(paths)\nax.set_title('10 Example Stock Prices')\nax.set_xlabel('Time')\nax.set_ylabel('Price');",
"_____no_output_____"
]
],
[
[
"## Part (c)",
"_____no_output_____"
],
[
"The discounted stock price $X_t$ is a martingale with respect to the risk-neutral measure, and $\\tilde{W_t}$ is a standard Wiener process with respect to the risk-neutral measure, so\n\n$$ dX_t = \\sigma X_t d\\tilde{W_t} $$\n\nFurthermore, we can express $S_t$ in terms of $X_t$:\n\n$$ S_t = X_t (1+r)^t $$",
"_____no_output_____"
]
],
[
[
"M = 1000",
"_____no_output_____"
],
[
"S_N2_hat = np.zeros([10])\n\nfor idx, path in enumerate(paths.T):\n S_N2 = path[N // 2]\n\n # Initial condition\n X_N2 = S_N2 / (1+r)**(N//2)\n\n # sigma dW_tilde\n X = np.hstack([X_N2 * np.ones(shape=[M, 1]),\n sigma*np.random.normal(loc=0, scale=delta,\n size=[M, N//2 - 1])]).T\n\n # This accumulates to make the Brownian motion\n for i, row in enumerate(X[:-1]):\n X[i + 1] *= row\n X[i + 1] += row\n \n S_N2_hat[idx] = np.mean(X[-1] * (1+r)**(N//2))",
"_____no_output_____"
]
],
[
[
"Actually, this becomes a fairly trivial issue, because $dX = 0dt + \\sigma X_t d\\tilde{W_t}$ and it is clearly obvious, therefore, than $X^{(i)}[N] = X^{(i)}[N/2] + Y$ where $Y$ is a random variable that is independent of $\\mathcal{F}_{N/2}$ and (under the risk-neutral measure) has mean value $0$, so obviously $\\tilde{E}(X_N | \\mathcal{F}_{N/2}) = X_{N/2}$.",
"_____no_output_____"
],
[
"## Part (d)\n\nThis is an estimate of the conditional variance.",
"_____no_output_____"
]
],
[
[
"np.mean((S_N2_hat - S_N2)**2)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cb06b209e0b2ddfb1060254d1b0c8c2e8c1b4509 | 49,843 | ipynb | Jupyter Notebook | data-ingestion-and-preparation/basic-data-ingestion-and-preparation.ipynb | michaelk-igz/tutorials | 903372d6d75db52ac458eb2fc45779c1274d429f | [
"Apache-2.0"
] | null | null | null | data-ingestion-and-preparation/basic-data-ingestion-and-preparation.ipynb | michaelk-igz/tutorials | 903372d6d75db52ac458eb2fc45779c1274d429f | [
"Apache-2.0"
] | null | null | null | data-ingestion-and-preparation/basic-data-ingestion-and-preparation.ipynb | michaelk-igz/tutorials | 903372d6d75db52ac458eb2fc45779c1274d429f | [
"Apache-2.0"
] | null | null | null | 46.150926 | 455 | 0.520575 | [
[
[
"# Getting Started with Data Ingestion and Preparation\n\nLearn how to quickly start using the Iguazio Data Science Platform to collect, ingest, and explore data.\n\n- [Overview](#gs-overview)\n- [Collecting and Ingesting Data](#gs-data-collection-and-ingestion)\n - [Ingesting Data From an External Database to a NoSQL Table Using V3IO Frames](#ingest-from-external-db-to-no-sql-using-frames)\n - [Ingesting Files from Amazon S3](#ingest-from-amazon-s3)\n - [Streaming Data From an External Streaming Engine Using Nuclio](#streaming-data-from-an-external-streaming-engine-using-nuclio)\n- [Exploring and Processing Data](#gs-data-exploration-and-processing)\n - [Exploring Data Using Spark DataFrames](#data-exploration-spark)\n - [Exploring Data Using V3IO Frames and pandas DataFrames](#data-exploration-v3io-frames-n-pandas)\n - [Exploring Data Using SQL](#data-exploration-sql)\n- [Data Collection and Exploration Getting-Started Example](#getting-started-example)\n - [Step 1: Ingest a Sample CSV File from Amazon S3](#getting-started-example-step-ingest-csv)\n - [Step 2: Convert the Sample CSV File to a NoSQL Table](#getting-started-example-step-convert-csv-to-nosql-table)\n - [Step 3: Run Interactive SQL Queries](#getting-started-example-step-run-sql-queries)\n - [Step 4: Convert the Data to a Parquet Table](#getting-started-example-step-convert-data-to-parquet)\n - [Step 5: Browse the Example Container Directory](#getting-started-example-step-browse-the-examples-dir)\n- [Cleanup](#cleanup)\n - [Delete Data](#delete-data)\n - [Release Spark Resources](#release-spark-resources)",
"_____no_output_____"
],
[
"<a id=\"gs-overview\"></a>\n## Overview\n\nThis tutorial explains and demonstrates how to collect, ingest, and explore data with the Iguazio Data Science Platform (**\"the platform\"**).<br>\nFor an overview of working with data in the platform's data store and the various available methods for ingesting, storing, and manipulating data in the platform, see the data ingestion and preparation **README** ([notebook](README.ipynb) / [Markdown](README.md)).",
"_____no_output_____"
],
[
"<a id=\"gs-data-collection-and-ingestion\"></a>\n## Collecting and Ingesting Data\n\nThe platform supports various alternative methods for collecting and ingesting data into its data containers (i.e., its data store).\nFor more information, see the [**platform-overview.ipynb**](../platform-overview.ipynb.ipynb#data-collection-and-ingestion) tutorial notebook\nThe data collection and ingestion can be done as a one-time operation, using different platform APIs — which can be run from your preferred programming interface, such as an interactive web-based Jupyter or Zeppelin notebook — or as an ongoing ingestion stream, using Nuclio serverless functions.\nThis section explains and demonstrates how to collect and ingest (import) data into the platform using code that's run from a Jupyter notebook.",
"_____no_output_____"
],
[
"<a id=\"ingest-from-external-db-to-no-sql-using-frames\"></a>\n### Ingesting Data From an External Database to a NoSQL Table Using V3IO Frames\n\nFor an example of how to collect data from an external database — such as MySQL, Oracle, and PostgreSQL — and ingest (write) it into a NoSQL table in the platform, using the V3IO Frames API, see the [read-external-db](read-external-db.ipynb) tutorial.",
"_____no_output_____"
],
[
"<a id=\"ingest-from-amazon-s3\"></a>\n### Ingesting Files from Amazon S3",
"_____no_output_____"
],
[
"<a id=\"ingest-from-amazon-s3-using-curl\"></a>\n#### Ingesting Files from Amazon S3 to the Platform File System Using curl\n\nYou can use a simple [curl](https://curl.haxx.se/) command to ingest a file (object) from an external web data source, such as an Amazon S3 bucket, to the platform's distributed file system (i.e., into the platform's data store).\nThis is demonstrated in the following code example and in the [getting-started example](#getting-started-example) in this notebook.\nThe [spark-sql-analytics](spark-sql-analytics.ipynb) tutorial notebook demonstrates a similar ingestion using [Botocore](https://github.com/boto/botocore).\n\nThe example in the following cells uses curl to read a CSV file from the [Iguazio sample data-sets](http://iguazio-sample-data.s3.amazonaws.com/) public Amazon S3 bucket and save it to an **examples** directory in the running-user directory of the predefined \"users\" data container (`/v3io/users/$V3IO_USERNAME` = `v3io/$V3IO_HOME` = `/User`).",
"_____no_output_____"
]
],
[
[
"!mkdir -p /User/examples # <=> /v3io/${V3IO_HOME}/examples or /v3io/users/${V3IO_USERNAME}/examples",
"_____no_output_____"
],
[
"%%sh\nCSV_PATH=\"/User/examples/stocks.csv\"\ncurl -L \"iguazio-sample-data.s3.amazonaws.com/2018-03-26_BINS_XETR08.csv\" > ${CSV_PATH}",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 861k 100 861k 0 0 493k 0 0:00:01 0:00:01 --:--:-- 493k\n"
]
],
[
[
"<a id=\"ingest-from-amazon-s3-to-nosql-table-using-v3io-frames-n-pandas\"></a>\n#### Ingesting Data from Amazon S3 to a NoSQL Table Using V3IO Frames and pandas\n\nFor an example of how to import data from Amazon S3 and save it into a NoSQL table in the platform's data store by using V3IO Frames and pandas DataFrames, see the [frames](frames.ipynb) tutorial notebook.",
"_____no_output_____"
],
[
"<a id=\"streaming-data-from-an-external-streaming-engine-using-nuclio\"></a>\n### Streaming Data From an External Streaming Engine Using Nuclio\n\nTo read data from an external streaming engine — such as Kafka, Kinesis, or RabbitMQ — create a Nuclio function that listens on the stream, and write the stream data to a NoSQL or time-series database (TSDB) table:\n\n1. In the dashboard's side navigation menu, select **Functions** to display the Nuclio serverless functions dashboard.\n2. Create a new Nuclio project or select an existing project.\n3. In the action toolbar, select **Create Function**.\n4. Enter a function name, select an appropriate template, such as **kafka-to-tsdb**, configure the required template parameters, and apply your changes.\n5. Select **Deploy** from the action toolbar to deploy your function.",
"_____no_output_____"
],
[
"<a id=\"gs-data-exploration-and-processing\"></a>\n## Exploring and Processing Data\n\nAfter you have ingested data into the platform's data containers, you can use various alternative methods and tools to explore and analyze the data.\nData scientists typically use Jupyter Notebook to run the exploration phase.\nAs outlined in the [**welcome**](../welcome.ipynb#data-exploration-and-processing) tutorial notebook, the platform's Jupyter Notebook service has a wide range of pre-deployed popular data science tools (such as Spark and Presto) and allows installation of additional tools and packages, enabling you to use different APIs to access the same data from a single Jupyter notebook.\nThis section explains and demonstrates how to explore data in the platform from a Jupyter notebook.",
"_____no_output_____"
],
[
"<a id=\"data-exploration-spark\"></a>\n### Exploring Data using Spark DataFrames\n\nSpark is a distributed computing framework for data analytics.\nYou can easily run distributed Spark jobs on you platform cluster that use Spark DataFrames to access data files (objects), tables, or streams in the platform's data store.\nFor more information and examples, see the [spark-sql-analytics](spark-sql-analytics.ipynb) tutorial notebook.",
"_____no_output_____"
],
[
"<a id=\"data-exploration-v3io-frames-n-pandas\"></a>\n### Exploring Data Using V3IO Frames and pandas DataFrames\n\nIguazio's V3IO Frames open-source data-access library provides a unified high-performance DataFrames API for accessing NoSQL, stream, and time-series data in the platform's data store.\nThese DataFrames can also be used to analyze the data with pandas. \nFor details and examples, see the [frames](frames.ipynb) tutorial notebook.",
"_____no_output_____"
],
[
"<a id=\"data-exploration-sql\"></a>\n### Exploring Data Using SQL\n\nYou can run SQL statements (`SELECT` only) on top of NoSQL tables in the platform's data store.\nTo do this, you need to use the Jupyter `%sql` or `%%sql` IPython Jupyter magic followed by an SQL statement.\nThe platform supports standard ANSI SQL semantics.\nUnder the hood, the SQL statements are executed via [Presto](https://prestosql.io/), which is a distributed SQL engine designed from the ground up for fast analytics queries.\n\nIn the example in the following cell, as a preparation for the SQL query, the **stocks.csv** file that was ingested to the **users/<running user>/examples** platform data-container directory in the previous [Ingesting Files from Amazon S3 to the Platform](#ingest-from-amazon-s3) example is written to a **stocks_example_tab** NoSQL table in the same directory.\nThen, an SQL `SELECT` query is run on this table.\nYou can also find a similar example in the [getting-started example](#getting-started-example) in this notebook.",
"_____no_output_____"
]
],
[
[
"# Use V3IO Frames to convert the CSV file that was ingested in the AWS S3 data-collection example to a NoSQL table.\n# NOTE: Make sure to first create a V3IO Frames service from the \"Services\" page of the platform dashboard, and run the\n# \"Ingesting Files from Amazon S3 to the Platform File System Using curl\" example to create users/$V3IO_USERNAME/examples/stocks.csv.\nimport pandas as pd\nimport v3io_frames as v3f\nimport os\n\n# Create a V3IO Frames client for the \"users\" data container\nclient = v3f.Client(\"framesd:8081\", container=\"users\")\n\n# Full CSV file path\ncsv_path = os.path.join(\"/User\", \"examples\", \"stocks.csv\")\n# Relative NoSQL table path within the \"users\" container\nrel_nosql_table_path = os.path.join(os.getenv('V3IO_USERNAME'), \"examples\", \"stocks_example_tab\")\n\n# Read the CSV file into a Pandas DataFrame\ndf = pd.read_csv(csv_path, header=\"infer\")\n\n# Convert the CSV file to a NoSQL table\nclient.write(\"kv\", rel_nosql_table_path, df)",
"_____no_output_____"
],
[
"# Use Presto to query the NoSQL table that was created in the previous step\npresto_nosql_table_path = os.path.join('v3io.users.\"' + os.getenv('V3IO_USERNAME'), 'examples', 'stocks_example_tab\"')\n%sql select * from $presto_nosql_table_path limit 10",
"Done.\n"
]
],
[
[
"<a id=\"getting-started-example\"></a>\n## Data Collection and Exploration Getting-Started Example\n\nThis section demonstrates a data collection, ingestion, and exploration flow.\nFollow the tutorial by running the code cells in order of appearance:\n- [Step #1](#getting-started-example-step-ingest-csv) — a CSV file is read from an Amazon S3 bucket and saved into an examples data-container directory using curl.\n The examples directory is first created by using a file-system command.\n- [Step #2](#getting-started-example-step-convert-csv-to-nosql-table) — the ingested file is converted into a NoSQL table by using Spark DataFrames.\n- [Step #3](#getting-started-example-step-run-sql-queries) — a Presto SQL query is run on the NoSQL table.\n- [Step #4](#getting-started-example-step-convert-data-to-parquet) — the ingested CSV file is converted into a Parquet table by using Spark DataFrames.\n- [Step #5](#getting-started-example-step-browse-the-examples-dir) — the examples container directory is browsed by using local and Hadoop file-system commands.\n- At the end of the flow, you can optionally [delete](#getting-started-example-deleting-data) the examples directory using a file-system command.\n\nYou can find more information about this sample flow in the [Converting a CSV File to a NoSQL Table](https://www.iguazio.com/docs/latest-release/tutorials/getting-started/ingest-n-consume-files/#convert-csv-to-nosql) platform quick-start tutorial.\n\n> **Tip:** You can also browse the files and directories that you write to the \"users\" container in this tutorial from the platform dashboard: in the side navigation menu, select **Data**, and then select the **users** container from the table. On the container data page, select the **Browse** tab, and then use the side directory-navigation tree to browse the directories. Selecting a file or directory in the browse table displays its metadata.",
"_____no_output_____"
],
[
"<a id=\"getting-started-example-step-ingest-csv\"></a>\n### Step 1: Ingest a Sample CSV File from Amazon S3\n\nUse `curl` to download a sample stocks-data CSV file from the [Iguazio sample data-set](http://iguazio-sample-data.s3.amazonaws.com/) public Amazon S3 bucket.\nFor additional public data sets, check out [Registry of Open Data on AWS](https://registry.opendata.aws/).\n\n> **NOTE:** All the platform tutorial notebook examples store the data in an **examples** directory in the running-user directory of the predefined \"users\" container — **users/<running user>/examples**.\n> The running-user directory is automatically created by the Jupyter Notebook service.\n> The `V3IO_HOME` environment variable is used to reference the **users/<running user>** directory.\n> To save the data to a different root container directory or to a different container, you need to specify the data path in the local file-system commands as `/v3io/<container name>/<data path>`, and in Spark DataFrames or Hadoop FS commands as a fully qualified path of the format `v3io://<container name>/<table path>`.\n> For more information, see the [v3io-mount](#v3io-mount) and [running-user directory](#running-user-dir) information [Jupyter Notebook Basics](#jupyter-notebook-basics) section of this notebook.",
"_____no_output_____"
]
],
[
[
"%%sh\nDIR_PATH=\"/User/examples/\" # <=> \"/v3io/${V3IO_HOME}/examples/\" or \"/v3io/users/${V3IO_USERNAME}/examples/\"\nCSV_PATH=\"${DIR_PATH}stocks.csv\"\n\n# Create the examples directory\nmkdir -p ${DIR_PATH}\n\n# Download a sample stocks CSV file from the Iguazio sample data-set Amazon S3 bucket to the examples directory\ncurl -L \"iguazio-sample-data.s3.amazonaws.com/2018-03-26_BINS_XETR08.csv\" > ${CSV_PATH}",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 861k 100 861k 0 0 592k 0 0:00:01 0:00:01 --:--:-- 592k\n"
]
],
[
[
"<a id=\"getting-started-example-step-convert-csv-to-nosql-table\"></a>\n### Step 2: Convert the Sample CSV File to a NoSQL Table\n\nRead the sample **stocks.csv** file that you downloaded and ingested in the previous step into a Spark DataFrame, and write the data in NoSQL format to a new \"stocks_tab\" table in the same container directory (**users/<running user>/examples/stocks_tab**). \n\n> **Note**\n> - To use the Iguazio Spark Connector, set the DataFrame's data-source format to `io.iguaz.v3io.spark.sql.kv`.\n> - The data path in the Spark DataFrame is specified by using the `V3IO_HOME_URL` environment variable, which is set to `v3io://users/<running user>`.\n> See the [running-user directory](#running-user-dir) information.",
"_____no_output_____"
]
],
[
[
"import os\nfrom pyspark.sql import SparkSession\n\n# Example diretory path - a <running user>/examples directory in the \"users\" container\ndir_path = os.path.join(os.getenv(\"V3IO_HOME_URL\"), \"examples\")\n# CSV file path\ncsv_path = os.path.join(dir_path, \"stocks.csv\")\n# NoSQL table path\nnosql_table_path = os.path.join(dir_path, \"stocks_tab\")\n\n# Create a new Spark session\nspark = SparkSession.builder.appName(\"Iguazio data ingestion and preparation getting-started example\").getOrCreate()\n\n# Read the sample CSV file into a Spark DataFrame, and let Spark infer the schema of the data\ndf = spark.read.option(\"header\", \"true\").csv(csv_path, inferSchema=\"true\")\n\n# Show the DataFrame data\ndf.show()\n\n# Write the DataFrame data to a NoSQL table in a platform data container.\n# Define the \"ISIN\" column (attribute) as the table's primary key.\ndf.write.format(\"io.iguaz.v3io.spark.sql.kv\").mode(\"append\") \\\n .option(\"key\", \"ISIN\").option(\"allow-overwrite-schema\", \"true\") \\\n .save(nosql_table_path)\n\n# Display the table schema:\ndf.printSchema()",
"+------------+--------+--------------------+------------+--------+----------+-------------------+-----+----------+--------+--------+--------+------------+--------------+\n| ISIN|Mnemonic| SecurityDesc|SecurityType|Currency|SecurityID| Date| Time|StartPrice|MaxPrice|MinPrice|EndPrice|TradedVolume|NumberOfTrades|\n+------------+--------+--------------------+------------+--------+----------+-------------------+-----+----------+--------+--------+--------+------------+--------------+\n|CH0038389992| BBZA|BB BIOTECH NAM. ...|Common stock| EUR| 2504244|2018-03-26 00:00:00|08:00| 56.4| 56.4| 56.4| 56.4| 320| 4|\n|CH0038863350| NESR|NESTLE NAM. ...|Common stock| EUR| 2504245|2018-03-26 00:00:00|08:00| 63.04| 63.06| 63.0| 63.06| 314| 3|\n|LU0378438732| C001|COMSTAGE-DAX UCIT...| ETF| EUR| 2504271|2018-03-26 00:00:00|08:00| 113.42| 113.42| 113.42| 113.42| 100| 1|\n|LU0411075020| DBPD|XTR.SHORTDAX X2 D...| ETF| EUR| 2504272|2018-03-26 00:00:00|08:00| 4.1335| 4.1335| 4.1295| 4.13| 102993| 8|\n|LU0838782315| XDDX| XTR.DAX INCOME 1D| ETF| EUR| 2504277|2018-03-26 00:00:00|08:00| 105.14| 105.2| 105.14| 105.2| 239| 3|\n|DE000A0DJ6J9| S92|SMA SOLAR TECHNOL.AG|Common stock| EUR| 2504287|2018-03-26 00:00:00|08:00| 55.65| 55.65| 55.65| 55.65| 543| 3|\n|DE000A0D6554| NDX1| NORDEX SE O.N.|Common stock| EUR| 2504290|2018-03-26 00:00:00|08:00| 8.182| 8.21| 8.174| 8.21| 10941| 8|\n|DE000A0F5UE8| EXXU|IS.DJ CHINA OFFS....| ETF| EUR| 2504302|2018-03-26 00:00:00|08:00| 47.52| 47.52| 47.52| 47.52| 420| 1|\n|DE000A0HN5C6| DWNI|DEUTSCHE WOHNEN S...|Common stock| EUR| 2504314|2018-03-26 00:00:00|08:00| 36.2| 36.24| 36.2| 36.24| 580| 5|\n|DE000A0LD2U1| AOX|ALSTRIA OFFICE RE...|Common stock| EUR| 2504379|2018-03-26 00:00:00|08:00| 12.25| 12.25| 12.25| 12.25| 1728| 3|\n|DE000A0LR936| ST5| STEICO SE|Common stock| EUR| 2504382|2018-03-26 00:00:00|08:00| 22.35| 22.35| 22.35| 22.35| 334| 1|\n|DE000A0MZ4B0| DLX|DELIGNIT AG ...|Common stock| EUR| 2504390|2018-03-26 00:00:00|08:00| 10.3| 10.3| 10.3| 10.3| 850| 1|\n|DE000A0Q8NC8| ETLX|ETFS DAXGL.G.MIN....| ETF| EUR| 2504397|2018-03-26 00:00:00|08:00| 17.844| 17.844| 17.838| 17.838| 3085| 5|\n|DE000A0V9YU8| 4RT3|ETFS COM.SEC.DZ08...| ETC| EUR| 2504421|2018-03-26 00:00:00|08:00| 5.8895| 5.8895| 5.8895| 5.8895| 0| 1|\n|DE000A0WMPJ6| AIXA| AIXTRON SE NA O.N.|Common stock| EUR| 2504428|2018-03-26 00:00:00|08:00| 16.8| 16.8| 16.75| 16.755| 3329| 8|\n|DE000A0Z2XN6| RIB|RIB SOFTWARE SE ...|Common stock| EUR| 2504436|2018-03-26 00:00:00|08:00| 24.66| 24.66| 24.52| 24.52| 11741| 29|\n|DE000A0Z2ZZ5| FNTN| FREENET AG NA O.N.|Common stock| EUR| 2504438|2018-03-26 00:00:00|08:00| 24.41| 24.42| 24.41| 24.42| 695| 6|\n|DE000A1A6V48| KSC| KPS AG NA O.N.|Common stock| EUR| 2504441|2018-03-26 00:00:00|08:00| 9.15| 9.15| 9.15| 9.15| 73| 1|\n|DE000A1DAHH0| BNR| BRENNTAG AG NA O.N.|Common stock| EUR| 2504453|2018-03-26 00:00:00|08:00| 48.14| 48.14| 48.14| 48.14| 185| 2|\n|DE000A1EWWW0| ADS| ADIDAS AG NA O.N.|Common stock| EUR| 2504471|2018-03-26 00:00:00|08:00| 196.3| 196.35| 196.3| 196.35| 591| 12|\n+------------+--------+--------------------+------------+--------+----------+-------------------+-----+----------+--------+--------+--------+------------+--------------+\nonly showing top 20 rows\n\nroot\n |-- ISIN: string (nullable = true)\n |-- Mnemonic: string (nullable = true)\n |-- SecurityDesc: string (nullable = true)\n |-- SecurityType: string (nullable = true)\n |-- Currency: string (nullable = true)\n |-- SecurityID: integer (nullable = true)\n |-- Date: timestamp (nullable = true)\n |-- Time: string (nullable = true)\n |-- StartPrice: double (nullable = true)\n |-- MaxPrice: double (nullable = true)\n |-- MinPrice: double (nullable = true)\n |-- EndPrice: double (nullable = true)\n |-- TradedVolume: integer (nullable = true)\n |-- NumberOfTrades: integer (nullable = true)\n\n"
]
],
[
[
"<a id=\"getting-started-example-step-run-sql-queries\"></a>\n### Step 3: Run Interactive SQL Queries\n\nUse the `%sql` Jupyter magic to run an SQL queries on the \"stocks_tab\" table that was created in the previous step.\n(The queries is processed using Presto.)\nThe example runs a `SELECT` query that reads the first ten table items.",
"_____no_output_____"
]
],
[
[
"presto_nosql_table_path = os.path.join('v3io.users.\"' + os.getenv('V3IO_USERNAME'), 'examples', 'stocks_tab\"')",
"_____no_output_____"
],
[
"%sql select * from $presto_nosql_table_path limit 10",
"Done.\n"
],
[
"%sql select count(*) from $presto_nosql_table_path ",
"Done.\n"
]
],
[
[
"<a id=\"getting-started-example-step-convert-data-to-parquet\"></a>\n### Step 4: Convert the Data to a Parquet Table\n\nUse a Spark DataFrame `write` command to write the data in the Spark DaraFrame — which was created from the CSV file and used to create the NoSQL table in [Step 2](#getting-started-example-step-convert-csv-to-nosql-table) — to a new **users/<running user>/examples/stocks_prqt** Parquet table.",
"_____no_output_____"
]
],
[
[
"# Write the DataFrame data that was read from the CSV file in Step 2 to a Parquet table in a platform data container\nprqt_table_path = os.path.join(dir_path, \"stocks_prqt\")\ndf.write.mode('overwrite').parquet(prqt_table_path)",
"_____no_output_____"
]
],
[
[
"<a id=\"getting-started-example-step-browse-the-examples-dir\"></a>\n### Step 5: Browse the Example Container Directory\n\nUse a file-system bash-shell command to list the contents of the **users/<running user>/examples** data-container directory to which all the ingested data in the previous steps were saved.\nYou should see in this directory the **stocks.csv** file, **stocks_tab** NoSQL table directory, and **stocks_prqt** Parquet table directory that you created in the previous steps.\nThe following cells demonstrate how to issue the same command using the local file system and using Hadoop FS.",
"_____no_output_____"
]
],
[
[
"# List the contents of the users/<running user>/examples directory using a local file-system command\n!ls -lrt /User/examples\n# The following are equivalent commands that demonstrate different ways to reference your user home directory:\n#!ls -lrt /v3io/${V3IO_HOME}/examples\n#!ls -lrt /v3io/users/${V3IO_USERNAME}/examples",
"total 0\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 07:43 stocks_example_tab\n-rw-r--r-- 1 50 nogroup 882055 Mar 10 07:45 stocks.csv\ndrwxrwxrwx 2 50 nogroup 0 Mar 10 07:47 stocks_tab\ndrwxr-xr-x 2 50 nogroup 0 Mar 10 07:49 stocks_prqt\n-rw-r--r-- 1 50 nogroup 150996 Mar 10 08:38 parquet_example\n-rw-rw-r-- 1 50 nogroup 113629 Mar 10 08:48 userdata1.parquet\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 08:50 spark-output\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 08:51 multiple-parquet-files\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 09:18 family\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 09:19 family1\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 09:19 family2\n-rw-rw-r-- 1 50 nogroup 475 Mar 10 09:43 mLines.json\n-rw-rw-r-- 1 50 nogroup 131745 Mar 10 09:46 CoffeeTime.jpg\ndrwxrwxrwx 2 50 nogroup 0 Mar 10 09:47 mytable\ndrwxrwxrwx 2 50 nogroup 0 Mar 10 09:48 stocks_kv\ndrwxrwxrwx 2 50 nogroup 0 Mar 10 09:48 stocks_kv_partition\ndrwxr-xr-x 2 50 nogroup 0 Mar 10 09:52 stocks_parq\ndrwxrwxrwx 2 50 nogroup 0 Mar 10 09:52 weather\n-rw-r--r-- 1 50 nogroup 882055 Mar 10 11:29 demo.csv\ndrwxrwxr-x 2 50 nogroup 0 Mar 10 11:37 csvs\n"
],
[
"%%sh\n# List the contents of the users/<running user>/examples directory using an Hadoop FS command\nhadoop fs -ls ${V3IO_HOME_URL}/examples\n# The following are equivalent commands that demonstrate different ways to reference your user home directory:\n#hadoop fs -ls v3io://${V3IO_HOME}/examples\n#hadoop fs -ls v3io://users/${V3IO_USERNAME}/examples",
"Found 4 items\n-rw-r--r-- 1 55 root 882055 2020-01-16 09:00 v3io://users/iguazio/examples/stocks.csv\ndrwxrwxr-x - 55 root 0 2020-01-16 09:00 v3io://users/iguazio/examples/stocks_example_tab\ndrwxr-xr-x - 55 root 0 2020-01-16 09:01 v3io://users/iguazio/examples/stocks_prqt\ndrwxrwxrwx - 55 root 0 2020-01-16 09:01 v3io://users/iguazio/examples/stocks_tab\n"
]
],
[
[
"<a id=\"cleanup\"></a>\n## Cleanup\n\nPrior to exiting, release disk space, computation, and memory resources consumed by the active session:\n\n- [Delete Data](#delete-data)\n- [Release Spark Resources](#release-spark-resources)",
"_____no_output_____"
],
[
"<a id=\"delete-data\"></a>\n### Delete Data\n\nOptionally delete any of the directories or files that you created.\nSee the instructions in the [Creating and Deleting Container Directories](https://www.iguazio.com/docs/latest-release/tutorials/getting-started/containers/#create-delete-container-dirs) tutorial.\nThe following example uses a local file-system command to delete the entire contents of the **users/<running user>/examples** directory that was created in this example, but not the directory itself.",
"_____no_output_____"
]
],
[
[
"# Delete the contents of the examples directory:\n#!rm -rf /User/examples/*\n# You can also delete the examples directory iteself (and all its contents):\n#!rm -rf /User/examples/",
"_____no_output_____"
]
],
[
[
"<a id=\"release-spark-resources\"></a>\n### Release Spark Resources\n\nWhen you're done, run the following command to stop your Spark session and release its computation and memory resources:",
"_____no_output_____"
]
],
[
[
"spark.stop()",
"_____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",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb06b41b5b853b27cc3a73b6459c1db470b349c9 | 25,807 | ipynb | Jupyter Notebook | Credit Risk Evaluator.ipynb | yuqing8/Supervised-Machine-Learning-Homework---Predicting-Credit-Risk | d58174e1b7e0528e2942d47b9ab11dfade22242f | [
"ADSL"
] | null | null | null | Credit Risk Evaluator.ipynb | yuqing8/Supervised-Machine-Learning-Homework---Predicting-Credit-Risk | d58174e1b7e0528e2942d47b9ab11dfade22242f | [
"ADSL"
] | null | null | null | Credit Risk Evaluator.ipynb | yuqing8/Supervised-Machine-Learning-Homework---Predicting-Credit-Risk | d58174e1b7e0528e2942d47b9ab11dfade22242f | [
"ADSL"
] | null | null | null | 31.055355 | 778 | 0.363545 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom pathlib import Path",
"_____no_output_____"
],
[
"train_df = pd.read_csv(Path('Resources/2019loans.csv'))\ntest_df = pd.read_csv(Path('Resources/2020Q1loans.csv'))",
"_____no_output_____"
],
[
"train_df['debt_settlement_flag'].value_counts()",
"_____no_output_____"
],
[
"test_df['debt_settlement_flag'].value_counts()",
"_____no_output_____"
],
[
"test_df_cols=list(test_df.columns)",
"_____no_output_____"
],
[
"set(train_df_cols) == set(test_df_cols)",
"_____no_output_____"
],
[
"X = pd.get_dummies(train_df)\ny_train = X['loan_status_high_risk']\nX_train = X.drop([\"loan_status_low_risk\",\"loan_status_high_risk\"],axis=1)",
"_____no_output_____"
],
[
"X_train['debt_settlement_flag_Y']",
"_____no_output_____"
],
[
"y_train.value_counts()",
"_____no_output_____"
],
[
"y_test.value_counts()",
"_____no_output_____"
]
],
[
[
"# Processing test data",
"_____no_output_____"
]
],
[
[
"# add missing dummy variables to testing set\nX_test = pd.get_dummies(test_df)\ny_test = X_test['loan_status_high_risk']\nX_test = X_test.drop([\"loan_status_low_risk\",\"loan_status_high_risk\"],axis=1)\nX_test['debt_settlement_flag_Y'] = 0\nX_test",
"_____no_output_____"
],
[
"set(X_train.columns) - set(X_test.columns)",
"_____no_output_____"
]
],
[
[
"# Consider the models",
"_____no_output_____"
],
[
"I think the random Forest would perform better than logistic regression in this case. Because test dataset includes numerical value,such as installment, annual_inc,etc. \"Since Logistic Regression depends on a calculation based on ‘weights’, numerical encoding of categorical variables can lead the algorithm to treat certain categories are of higher importance compared to others, depending on the number assigned.\" -- https://medium.com/@bemali_61284/random-forest-vs-logistic-regression-16c0c8e2484c. On the other hand, \"by randomly selecting subsets of features, some trees of the forest can isolate more important features while increasing the overall accuracy of the result\".-- https://medium.com/@bemali_61284/random-forest-vs-logistic-regression-16c0c8e2484c.\n",
"_____no_output_____"
],
[
"# Fit a Logistic Regression",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression\nclassifier_lib = LogisticRegression(solver='liblinear', max_iter=10000)\nclassifier_lib",
"_____no_output_____"
],
[
"# Train the Logistic Regression model on the unscaled data and print the model score\nclassifier_lib.fit(X_train, y_train)",
"_____no_output_____"
],
[
"print(f\"Training Data Score: {classifier_lib.score(X_train, y_train)}\")\nprint(f\"Testing Data Score: {classifier_lib.score(X_test, y_test)}\")",
"Training Data Score: 0.7076354679802955\nTesting Data Score: 0.5676307954062101\n"
],
[
"# Train a Random Forest Classifier model and print the model score\nfrom sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(random_state=1, n_estimators=500).fit(X_train, y_train)\nprint(f'Training Score: {clf.score(X_train, y_train)}')\nprint(f'Training Score: {clf.score(X_test, y_test)}')",
"Training Score: 1.0\nTraining Score: 0.6154827732879625\n"
],
[
"# Scale the data\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)",
"_____no_output_____"
],
[
"# Train the Logistic Regression model on the scaled data and print the model score\nclassifier = LogisticRegression()\nclassifier.fit(X_train_scaled, y_train)\nprint(f\"Training Data Score: {classifier.score(X_train_scaled, y_train)}\")\nprint(f\"Testing Data Score: {classifier.score(X_test_scaled, y_test)}\")",
"Training Data Score: 0.7132183908045977\nTesting Data Score: 0.7201190982560612\n"
],
[
"# Train a Random Forest Classifier model on the scaled data and print the model score\nclf = RandomForestClassifier(random_state=1, n_estimators=500).fit(X_train_scaled, y_train)\nprint(f'Training Score: {clf.score(X_train_scaled, y_train)}')\nprint(f'Testing Score: {clf.score(X_test_scaled, y_test)}')",
"Training Score: 1.0\nTesting Score: 0.6165461505742237\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb06b51301fd4f834fe976a700b4a61ff396f74c | 122,506 | ipynb | Jupyter Notebook | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t | 12e0ece34da7b3461e866eb31004c018b2f202c9 | [
"Apache-2.0"
] | 84 | 2021-04-19T22:16:20.000Z | 2022-03-28T11:18:14.000Z | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t | 12e0ece34da7b3461e866eb31004c018b2f202c9 | [
"Apache-2.0"
] | 3 | 2021-05-10T23:01:41.000Z | 2021-12-31T19:32:42.000Z | notebooks/XLM_T_Playground.ipynb | ruanchaves/xlm-t | 12e0ece34da7b3461e866eb31004c018b2f202c9 | [
"Apache-2.0"
] | 12 | 2021-04-27T19:25:16.000Z | 2022-02-01T16:40:19.000Z | 41.668707 | 11,549 | 0.490213 | [
[
[
"# 1 - Installs and imports",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade pip\n!pip install sentencepiece\n!pip install transformers",
"Collecting pip\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/ac/cf/0cc542fc93de2f3b9b53cb979c7d1118cffb93204afb46299a9f858e113f/pip-21.1-py3-none-any.whl (1.5MB)\n\r\u001b[K |▏ | 10kB 23.5MB/s eta 0:00:01\r\u001b[K |▍ | 20kB 28.6MB/s eta 0:00:01\r\u001b[K |▋ | 30kB 23.7MB/s eta 0:00:01\r\u001b[K |▉ | 40kB 27.1MB/s eta 0:00:01\r\u001b[K |█ | 51kB 26.4MB/s eta 0:00:01\r\u001b[K |█▎ | 61kB 29.1MB/s eta 0:00:01\r\u001b[K |█▌ | 71kB 18.9MB/s eta 0:00:01\r\u001b[K |█▊ | 81kB 19.4MB/s eta 0:00:01\r\u001b[K |██ | 92kB 18.0MB/s eta 0:00:01\r\u001b[K |██▏ | 102kB 18.5MB/s eta 0:00:01\r\u001b[K |██▎ | 112kB 18.5MB/s eta 0:00:01\r\u001b[K |██▌ | 122kB 18.5MB/s eta 0:00:01\r\u001b[K |██▊ | 133kB 18.5MB/s eta 0:00:01\r\u001b[K |███ | 143kB 18.5MB/s eta 0:00:01\r\u001b[K |███▏ | 153kB 18.5MB/s eta 0:00:01\r\u001b[K |███▍ | 163kB 18.5MB/s eta 0:00:01\r\u001b[K |███▋ | 174kB 18.5MB/s eta 0:00:01\r\u001b[K |███▉ | 184kB 18.5MB/s eta 0:00:01\r\u001b[K |████ | 194kB 18.5MB/s eta 0:00:01\r\u001b[K |████▎ | 204kB 18.5MB/s eta 0:00:01\r\u001b[K |████▌ | 215kB 18.5MB/s eta 0:00:01\r\u001b[K |████▋ | 225kB 18.5MB/s eta 0:00:01\r\u001b[K |████▉ | 235kB 18.5MB/s eta 0:00:01\r\u001b[K |█████ | 245kB 18.5MB/s eta 0:00:01\r\u001b[K |█████▎ | 256kB 18.5MB/s eta 0:00:01\r\u001b[K |█████▌ | 266kB 18.5MB/s eta 0:00:01\r\u001b[K |█████▊ | 276kB 18.5MB/s eta 0:00:01\r\u001b[K |██████ | 286kB 18.5MB/s eta 0:00:01\r\u001b[K |██████▏ | 296kB 18.5MB/s eta 0:00:01\r\u001b[K |██████▍ | 307kB 18.5MB/s eta 0:00:01\r\u001b[K |██████▋ | 317kB 18.5MB/s eta 0:00:01\r\u001b[K |██████▊ | 327kB 18.5MB/s eta 0:00:01\r\u001b[K |███████ | 337kB 18.5MB/s eta 0:00:01\r\u001b[K |███████▏ | 348kB 18.5MB/s eta 0:00:01\r\u001b[K |███████▍ | 358kB 18.5MB/s eta 0:00:01\r\u001b[K |███████▋ | 368kB 18.5MB/s eta 0:00:01\r\u001b[K |███████▉ | 378kB 18.5MB/s eta 0:00:01\r\u001b[K |████████ | 389kB 18.5MB/s eta 0:00:01\r\u001b[K |████████▎ | 399kB 18.5MB/s eta 0:00:01\r\u001b[K |████████▌ | 409kB 18.5MB/s eta 0:00:01\r\u001b[K |████████▊ | 419kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████ | 430kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████ | 440kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████▎ | 450kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████▌ | 460kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████▊ | 471kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████ | 481kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████▏ | 491kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████▍ | 501kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████▋ | 512kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████▉ | 522kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████ | 532kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████▎ | 542kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████▍ | 552kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████▋ | 563kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████▉ | 573kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████ | 583kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████▎ | 593kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████▌ | 604kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████▊ | 614kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████ | 624kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████▏ | 634kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████▍ | 645kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████▌ | 655kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████▊ | 665kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████ | 675kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████▏ | 686kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████▍ | 696kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████▋ | 706kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████▉ | 716kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████ | 727kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████▎ | 737kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████▌ | 747kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████▊ | 757kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████▉ | 768kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████ | 778kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████▎ | 788kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████▌ | 798kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████▊ | 808kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████ | 819kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████▏ | 829kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████▍ | 839kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████▋ | 849kB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████▉ | 860kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████ | 870kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████▏ | 880kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████▍ | 890kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████▋ | 901kB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████▉ | 911kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████ | 921kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████▎ | 931kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████▌ | 942kB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████▊ | 952kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████ | 962kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████▏ | 972kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████▎ | 983kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████▌ | 993kB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████▊ | 1.0MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████ | 1.0MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▏ | 1.0MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▍ | 1.0MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▋ | 1.0MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▉ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▎ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▌ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▋ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▉ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▎ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▌ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▊ | 1.1MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▏ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▍ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▋ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▉ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▏ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▍ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▋ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▉ | 1.2MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▎ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▌ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▊ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▎ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▌ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▊ | 1.3MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▏ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▍ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▋ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▉ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▎ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▍ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▋ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▉ | 1.4MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████ | 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▎ | 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▌ | 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▊ | 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████ | 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▏| 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▍| 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▋| 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▊| 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 1.5MB 18.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 1.6MB 18.5MB/s \n\u001b[?25hInstalling collected packages: pip\n Found existing installation: pip 19.3.1\n Uninstalling pip-19.3.1:\n Successfully uninstalled pip-19.3.1\nSuccessfully installed pip-21.1\n\u001b[33mWARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/include/python3.7/UNKNOWN\nsysconfig: /usr/include/python3.7m\u001b[0m\n\u001b[33mWARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/bin\nsysconfig: /usr/bin\u001b[0m\n\u001b[33mWARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local\nsysconfig: /usr\u001b[0m\n\u001b[33mWARNING: Additional context:\nuser = False\nhome = None\nroot = None\nprefix = None\u001b[0m\nCollecting sentencepiece\n Downloading sentencepiece-0.1.95-cp37-cp37m-manylinux2014_x86_64.whl (1.2 MB)\n\u001b[K |████████████████████████████████| 1.2 MB 21.1 MB/s \n\u001b[?25hInstalling collected packages: sentencepiece\n\u001b[33m WARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/include/python3.7/sentencepiece\n sysconfig: /usr/include/python3.7m/sentencepiece\u001b[0m\n\u001b[33m WARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/bin\n sysconfig: /usr/bin\u001b[0m\n\u001b[33m WARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local\n sysconfig: /usr\u001b[0m\n\u001b[33m WARNING: Additional context:\n user = False\n home = None\n root = None\n prefix = None\u001b[0m\n\u001b[33mWARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/include/python3.7/UNKNOWN\nsysconfig: /usr/include/python3.7m\u001b[0m\n\u001b[33mWARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/bin\nsysconfig: /usr/bin\u001b[0m\n\u001b[33mWARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local\nsysconfig: /usr\u001b[0m\n\u001b[33mWARNING: Additional context:\nuser = False\nhome = None\nroot = None\nprefix = None\u001b[0m\nSuccessfully installed sentencepiece-0.1.95\n\u001b[33mWARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv\u001b[0m\n\u001b[33mWARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/include/python3.7/UNKNOWN\nsysconfig: /usr/include/python3.7m\u001b[0m\n\u001b[33mWARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/bin\nsysconfig: /usr/bin\u001b[0m\n\u001b[33mWARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local\nsysconfig: /usr\u001b[0m\n\u001b[33mWARNING: Additional context:\nuser = False\nhome = None\nroot = None\nprefix = None\u001b[0m\nCollecting transformers\n Downloading transformers-4.5.1-py3-none-any.whl (2.1 MB)\n\u001b[K |████████████████████████████████| 2.1 MB 19.1 MB/s \n\u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (1.19.5)\nCollecting sacremoses\n Downloading sacremoses-0.0.45-py3-none-any.whl (895 kB)\n\u001b[K |████████████████████████████████| 895 kB 51.9 MB/s \n\u001b[?25hCollecting tokenizers<0.11,>=0.10.1\n Downloading tokenizers-0.10.2-cp37-cp37m-manylinux2010_x86_64.whl (3.3 MB)\n\u001b[K |████████████████████████████████| 3.3 MB 70.2 MB/s \n\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers) (3.0.12)\nRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers) (4.41.1)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers) (3.10.1)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from transformers) (20.9)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (2019.12.20)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers) (3.4.1)\nRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers) (3.7.4.3)\nRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->transformers) (2.4.7)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2020.12.5)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.15.0)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.0.1)\nInstalling collected packages: tokenizers, sacremoses, transformers\n\u001b[33m WARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/include/python3.7/tokenizers\n sysconfig: /usr/include/python3.7m/tokenizers\u001b[0m\n\u001b[33m WARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/bin\n sysconfig: /usr/bin\u001b[0m\n\u001b[33m WARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local\n sysconfig: /usr\u001b[0m\n\u001b[33m WARNING: Additional context:\n user = False\n home = None\n root = None\n prefix = None\u001b[0m\n\u001b[33m WARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/include/python3.7/sacremoses\n sysconfig: /usr/include/python3.7m/sacremoses\u001b[0m\n\u001b[33m WARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/bin\n sysconfig: /usr/bin\u001b[0m\n\u001b[33m WARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local\n sysconfig: /usr\u001b[0m\n\u001b[33m WARNING: Additional context:\n user = False\n home = None\n root = None\n prefix = None\u001b[0m\n\u001b[33m WARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/lib/python3.7/dist-packages\n sysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33m WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/include/python3.7/transformers\n sysconfig: /usr/include/python3.7m/transformers\u001b[0m\n\u001b[33m WARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local/bin\n sysconfig: /usr/bin\u001b[0m\n\u001b[33m WARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\n distutils: /usr/local\n sysconfig: /usr\u001b[0m\n\u001b[33m WARNING: Additional context:\n user = False\n home = None\n root = None\n prefix = None\u001b[0m\n\u001b[33mWARNING: Value for scheme.platlib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.purelib does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/lib/python3.7/dist-packages\nsysconfig: /usr/lib/python3.7/site-packages\u001b[0m\n\u001b[33mWARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/include/python3.7/UNKNOWN\nsysconfig: /usr/include/python3.7m\u001b[0m\n\u001b[33mWARNING: Value for scheme.scripts does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local/bin\nsysconfig: /usr/bin\u001b[0m\n\u001b[33mWARNING: Value for scheme.data does not match. Please report this to <https://github.com/pypa/pip/issues/9617>\ndistutils: /usr/local\nsysconfig: /usr\u001b[0m\n\u001b[33mWARNING: Additional context:\nuser = False\nhome = None\nroot = None\nprefix = None\u001b[0m\nSuccessfully installed sacremoses-0.0.45 tokenizers-0.10.2 transformers-4.5.1\n\u001b[33mWARNING: Running pip as root will break packages and permissions. You should install packages reliably by using venv: https://pip.pypa.io/warnings/venv\u001b[0m\n"
],
[
"from transformers import AutoTokenizer, AutoModel, TFAutoModel, AutoConfig\nfrom transformers import AutoModelForSequenceClassification\nfrom transformers import TFAutoModelForSequenceClassification\nfrom transformers import pipeline\nimport numpy as np\nfrom scipy.spatial.distance import cosine\nfrom collections import defaultdict \nimport urllib\nimport numpy as np\nfrom scipy.special import softmax\nfrom sklearn.metrics import classification_report",
"_____no_output_____"
]
],
[
[
"# 2 - Fetch XLM-T model",
"_____no_output_____"
]
],
[
[
"MODEL = \"cardiffnlp/twitter-xlm-roberta-base\"\ntokenizer = AutoTokenizer.from_pretrained(MODEL)\nmodel = AutoModel.from_pretrained(MODEL)",
"_____no_output_____"
]
],
[
[
"# Use Cases",
"_____no_output_____"
],
[
"## 1 - Compute Tweet Similarity",
"_____no_output_____"
]
],
[
[
"def preprocess(text):\n new_text = []\n for t in text.split(\" \"):\n t = '@user' if t.startswith('@') and len(t) > 1 else t\n t = 'http' if t.startswith('http') else t\n new_text.append(t)\n return \" \".join(new_text)\n\ndef get_embedding(text):\n text = preprocess(text)\n encoded_input = tokenizer(text, return_tensors='pt')\n features = model(**encoded_input)\n features = features[0].detach().numpy() \n features_mean = np.mean(features[0], axis=0) \n return features_mean\n\nquery = \"Acabo de pedir pollo frito 🐣\" #spanish",
"_____no_output_____"
],
[
"tweets = [\"We had a great time! ⚽️\", # english\n \"We hebben een geweldige tijd gehad! ⛩\", # dutch\n \"Nous avons passé un bon moment! 🎥\", # french\n \"Ci siamo divertiti! 🍝\"] # italian\n\nd = defaultdict(int)\nfor tweet in tweets:\n sim = 1-cosine(get_embedding(query),get_embedding(tweet))\n d[tweet] = sim",
"_____no_output_____"
],
[
"print('Most similar to: ',query)\nprint('----------------------------------------')\nfor idx,x in enumerate(sorted(d.items(), key=lambda x:x[1], reverse=True)):\n print(idx+1,x[0])",
"Most similar to: Acabo de pedir pollo frito 🐣\n----------------------------------------\n1 Ci siamo divertiti! 🍝\n2 Nous avons passé un bon moment! 🎥\n3 We had a great time! ⚽️\n4 We hebben een geweldige tijd gehad! ⛩\n"
]
],
[
[
"## 2 - Simple inference example (with `pipelines`)",
"_____no_output_____"
]
],
[
[
"model_path = \"cardiffnlp/twitter-xlm-roberta-base-sentiment\"\nsentiment_task = pipeline(\"sentiment-analysis\", model=model_path, tokenizer=model_path)",
"_____no_output_____"
],
[
"sentiment_task(\"Huggingface es lo mejor! Awesome library 🤗😎\")",
"_____no_output_____"
]
],
[
[
"# 3 - Experiment on UMSAB",
"_____no_output_____"
],
[
"## Fetch dataset (Spanish)",
"_____no_output_____"
]
],
[
[
"language = 'spanish'\n\nfiles = \"\"\"test_labels.txt\ntest_text.txt\ntrain_labels.txt\ntrain_text.txt\nval_labels.txt\nval_text.txt\"\"\".split('\\n')\n\ndef fetch_data(language, files):\n dataset = defaultdict(list)\n for infile in files:\n thisdata = infile.split('/')[-1].replace('.txt','')\n dataset_url = f\"https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/{language}/{infile}\"\n print(f'Fetching from {dataset_url}')\n with urllib.request.urlopen(dataset_url) as f:\n for line in f:\n if thisdata.endswith('labels'):\n dataset[thisdata].append(int(line.strip().decode('utf-8')))\n else:\n dataset[thisdata].append(line.strip().decode('utf-8'))\n return dataset \n\ndataset = fetch_data(language, files)",
"Fetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/test_labels.txt\nFetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/test_text.txt\nFetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/train_labels.txt\nFetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/train_text.txt\nFetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/val_labels.txt\nFetching from https://raw.githubusercontent.com/cardiffnlp/xlm-t/main/data/sentiment/spanish/val_text.txt\n"
],
[
"dataset['train_text'][:3],dataset['train_labels'][:3]",
"_____no_output_____"
]
],
[
[
"## Run full experiment",
"_____no_output_____"
]
],
[
[
"# load multilingual sentiment classifier\nCUDA = True # set to true if using GPU (Runtime -> Change runtime Type -> GPU)\nBATCH_SIZE = 32\nMODEL = \"cardiffnlp/twitter-xlm-roberta-base-sentiment\"\ntokenizer = AutoTokenizer.from_pretrained(MODEL)\nconfig = AutoConfig.from_pretrained(MODEL)\nmodel = AutoModelForSequenceClassification.from_pretrained(MODEL)\nif CUDA:\n model = model.to('cuda')",
"_____no_output_____"
],
[
"# helper functions\ndef preprocess(corpus):\n outcorpus = []\n for text in corpus:\n new_text = []\n for t in text.split(\" \"):\n t = '@user' if t.startswith('@') and len(t) > 1 else t\n t = 'http' if t.startswith('http') else t\n new_text.append(t)\n new_text = \" \".join(new_text)\n outcorpus.append(new_text)\n return outcorpus\n\ndef predict(text, cuda):\n text = preprocess(text)\n encoded_input = tokenizer(text, return_tensors='pt', padding = True, truncation = True)\n if cuda:\n encoded_input.to('cuda')\n output = model(**encoded_input)\n scores = output[0].detach().cpu().numpy()\n else:\n output = model(**encoded_input)\n scores = output[0].detach().numpy()\n \n scores = softmax(scores, axis=-1)\n return scores",
"_____no_output_____"
],
[
"from torch.utils.data import DataLoader\ndl = DataLoader(dataset['test_text'], batch_size=BATCH_SIZE)\nall_preds = []\nfor idx,batch in enumerate(dl):\n if idx % 10 == 0:\n print('Batch ',idx+1,' of ',len(dl))\n text = preprocess(batch)\n scores = predict(text, CUDA)\n preds = np.argmax(scores, axis=-1)\n all_preds.extend(preds)",
"Asking to truncate to max_length but no maximum length is provided and the model has no predefined maximum length. Default to no truncation.\n"
],
[
"print(classification_report(dataset['test_labels'], all_preds))",
" precision recall f1-score support\n\n 0 0.70 0.80 0.75 290\n 1 0.62 0.55 0.58 290\n 2 0.75 0.74 0.75 290\n\n accuracy 0.70 870\n macro avg 0.69 0.70 0.69 870\nweighted avg 0.69 0.70 0.69 870\n\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb06bfcb4e8a4bced9bf3638314d5297a9ca18db | 5,931 | ipynb | Jupyter Notebook | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch | 48b5301ccfa24704a4240125d377b1448d5591d9 | [
"MIT"
] | null | null | null | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch | 48b5301ccfa24704a4240125d377b1448d5591d9 | [
"MIT"
] | null | null | null | docs/examples/mbs-two-sech-4pi.ipynb | amcdawes/maxwellbloch | 48b5301ccfa24704a4240125d377b1448d5591d9 | [
"MIT"
] | null | null | null | 24.109756 | 212 | 0.495869 | [
[
[
"# Two-Level: Sech Pulse 4π — Pulse Breakup",
"_____no_output_____"
],
[
"## Define the Problem\n\nFirst we need to define a sech pulse with the area we want. We'll fix the width of the pulse and the area to find the right amplitude.\n\nThe full-width at half maximum (FWHM) $t_s$ of the sech pulse is related to the FWHM of a Gaussian by a factor of $1/2.6339157938$. (See §3.2.2 of my [PhD thesis](https://github.com/tommyogden/phd-thesis)).",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nSECH_FWHM_CONV = 1./2.6339157938\nt_width = 1.0*SECH_FWHM_CONV # [τ]\nprint('t_width', t_width)",
"_____no_output_____"
],
[
"mb_solve_json = \"\"\"\n{\n \"atom\": {\n \"fields\": [\n {\n \"coupled_levels\": [[0, 1]],\n \"rabi_freq_t_args\": {\n \"n_pi\": 4.0,\n \"centre\": 0.0,\n \"width\": %f\n },\n \"rabi_freq_t_func\": \"sech\"\n }\n ],\n \"num_states\": 2\n },\n \"t_min\": -2.0,\n \"t_max\": 10.0,\n \"t_steps\": 240,\n \"z_min\": -0.5,\n \"z_max\": 1.5,\n \"z_steps\": 100,\n \"interaction_strengths\": [\n 10.0\n ],\n \"savefile\": \"mbs-two-sech-4pi\"\n}\n\"\"\"%(t_width)",
"_____no_output_____"
],
[
"from maxwellbloch import mb_solve\nmbs = mb_solve.MBSolve().from_json_str(mb_solve_json)",
"_____no_output_____"
]
],
[
[
"We'll just check that the pulse area is what we want.",
"_____no_output_____"
]
],
[
[
"print('The input pulse area is {0}'.format(\n np.trapz(mbs.Omegas_zt[0,0,:].real, mbs.tlist)/np.pi))",
"_____no_output_____"
],
[
"Omegas_zt, states_zt = mbs.mbsolve(recalc=False)",
"_____no_output_____"
]
],
[
[
"## Plot Output",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n\nsns.set_style('darkgrid')\nfig = plt.figure(1, figsize=(16, 6))\nax = fig.add_subplot(111)\ncmap_range = np.linspace(0.0, 3.0, 11)\ncf = ax.contourf(mbs.tlist, mbs.zlist, \n np.abs(mbs.Omegas_zt[0]/(2*np.pi)), \n cmap_range, cmap=plt.cm.Blues)\nax.set_title('Rabi Frequency ($\\Gamma / 2\\pi $)')\nax.set_xlabel('Time ($1/\\Gamma$)')\nax.set_ylabel('Distance ($L$)')\nfor y in [0.0, 1.0]:\n ax.axhline(y, c='grey', lw=1.0, ls='dotted')\nplt.colorbar(cf);",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(16, 5))\nax.plot(mbs.zlist, mbs.fields_area()[0]/np.pi)\nax.set_ylim([0.0, 8.0])\nax.set_xlabel('Distance ($L$)')\nax.set_ylabel('Pulse Area ($\\pi$)')",
"_____no_output_____"
]
],
[
[
"## Analysis\n\nThe $4 \\pi$ sech pulse breaks up into two $2 \\pi$ pulses, which travel at a speed according to their width.",
"_____no_output_____"
],
[
"## Movie",
"_____no_output_____"
]
],
[
[
"# C = 0.1 # speed of light\n# Y_MIN = 0.0 # Y-axis min\n# Y_MAX = 4.0 # y-axis max\n# ZOOM = 2 # level of linear interpolation\n# FPS = 60 # frames per second\n# ATOMS_ALPHA = 0.2 # Atom indicator transparency",
"_____no_output_____"
],
[
"# FNAME = \"images/mb-solve-two-sech-4pi\"\n# FNAME_JSON = FNAME + '.json'\n# with open(FNAME_JSON, \"w\") as f:\n# f.write(mb_solve_json)",
"_____no_output_____"
],
[
"# !make-mp4-fixed-frame.py -f $FNAME_JSON -c $C --fps $FPS --y-min $Y_MIN --y-max $Y_MAX \\\n# --zoom $ZOOM --atoms-alpha $ATOMS_ALPHA #--peak-line --c-line",
"_____no_output_____"
],
[
"# FNAME_MP4 = FNAME + '.mp4'\n# !make-gif-ffmpeg.sh -f $FNAME_MP4 --in-fps $FPS",
"_____no_output_____"
],
[
"# from IPython.display import Image\n# Image(url=FNAME_MP4 +'.gif', format='gif')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb06c629ed98fc598eeb31e1e07a6be1a6b1455d | 21,737 | ipynb | Jupyter Notebook | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 | 5266fa7464f5606c33b29f46de6b4917d2db34c4 | [
"MIT"
] | 6 | 2019-01-21T02:49:23.000Z | 2019-12-09T03:48:46.000Z | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 | 5266fa7464f5606c33b29f46de6b4917d2db34c4 | [
"MIT"
] | 4 | 2018-12-27T16:40:17.000Z | 2019-01-16T08:12:02.000Z | notebooks/Getting started - Baselines and submission.ipynb | maximiliense/GLC19 | 5266fa7464f5606c33b29f46de6b4917d2db34c4 | [
"MIT"
] | 6 | 2019-01-07T13:47:30.000Z | 2019-12-23T12:41:04.000Z | 26.411908 | 159 | 0.533744 | [
[
[
"This notebook presents some code to compute some basic baselines.\n\nIn particular, it shows how to:\n1. Use the provided validation set\n2. Compute the top-30 metric\n3. Save the predictions on the test in the right format for submission",
"_____no_output_____"
]
],
[
[
"%pylab inline --no-import-all\n\nimport os\nfrom pathlib import Path\n\nimport pandas as pd\n\n\n# Change this path to adapt to where you downloaded the data\nDATA_PATH = Path(\"data\")\n\n# Create the path to save submission files\nSUBMISSION_PATH = Path(\"submissions\")\nos.makedirs(SUBMISSION_PATH, exist_ok=True)",
"Populating the interactive namespace from numpy and matplotlib\n"
]
],
[
[
"We also load the official metric, top-30 error rate, for which we provide efficient implementations:",
"_____no_output_____"
]
],
[
[
"from GLC.metrics import top_30_error_rate\nhelp(top_30_error_rate)",
"Help on function top_30_error_rate in module GLC.metrics:\n\ntop_30_error_rate(y_true, y_score)\n Computes the top-30 error rate.\n \n Parameters\n ----------\n y_true: 1d array, [n_samples]\n True labels.\n y_score: 2d array, [n_samples, n_classes]\n Scores for each label.\n \n Returns\n -------\n float:\n Top-30 error rate value.\n \n Notes\n -----\n Complexity: :math:`O( n_\\text{samples} \\times n_\\text{classes} )`.\n\n"
],
[
"from GLC.metrics import top_k_error_rate_from_sets\nhelp(top_k_error_rate_from_sets)",
"Help on function top_k_error_rate_from_sets in module GLC.metrics:\n\ntop_k_error_rate_from_sets(y_true, s_pred)\n Computes the top-k error rate from predicted sets.\n \n Parameters\n ----------\n y_true: 1d array, [n_samples]\n True labels.\n s_pred: 2d array, [n_samples, k]\n Previously computed top-k sets for each sample.\n \n Returns\n -------\n float:\n Error rate value.\n\n"
]
],
[
[
"For submissions, we will also need to predict the top-30 sets for which we also provide an efficient implementation:",
"_____no_output_____"
]
],
[
[
"from GLC.metrics import predict_top_30_set\nhelp(predict_top_30_set)",
"Help on function predict_top_30_set in module GLC.metrics:\n\npredict_top_30_set(y_score)\n Predicts the top-30 sets from scores.\n \n Parameters\n ----------\n y_score: 2d array, [n_samples, n_classes]\n Scores for each sample and label.\n \n Returns\n -------\n 2d array, [n_samples, 30]:\n Predicted top-30 sets for each sample.\n \n Notes\n -----\n Complexity: :math:`O( n_\\text{samples} \\times n_\\text{classes} )`.\n\n"
]
],
[
[
"We also provide an utility function to generate submission files in the right format:",
"_____no_output_____"
]
],
[
[
"from GLC.submission import generate_submission_file\nhelp(generate_submission_file)",
"Help on function generate_submission_file in module GLC.submission:\n\ngenerate_submission_file(filename, observation_ids, s_pred)\n Generate submission file for Kaggle\n \n Parameters\n ----------\n filename : string\n Submission filename.\n observation_ids : 1d array-like\n Test observations ids\n s_pred : list of 1d array-like\n Set predictions for test observations.\n\n"
]
],
[
[
"# Observation data loading",
"_____no_output_____"
],
[
"We first need to load the observation data:",
"_____no_output_____"
]
],
[
[
"df_obs_fr = pd.read_csv(DATA_PATH / \"observations\" / \"observations_fr_train.csv\", sep=\";\", index_col=\"observation_id\")\ndf_obs_us = pd.read_csv(DATA_PATH / \"observations\" / \"observations_us_train.csv\", sep=\";\", index_col=\"observation_id\")\ndf_obs = pd.concat((df_obs_fr, df_obs_us))",
"_____no_output_____"
]
],
[
[
"Then, we retrieve the train/val split provided:",
"_____no_output_____"
]
],
[
[
"obs_id_train = df_obs.index[df_obs[\"subset\"] == \"train\"].values\nobs_id_val = df_obs.index[df_obs[\"subset\"] == \"val\"].values\n\ny_train = df_obs.loc[obs_id_train][\"species_id\"].values\ny_val = df_obs.loc[obs_id_val][\"species_id\"].values\n\nn_val = len(obs_id_val)\nprint(\"Validation set size: {} ({:.1%} of train observations)\".format(n_val, n_val / len(df_obs)))",
"Validation set size: 40080 (2.5% of train observations)\n"
]
],
[
[
"We also load the observation data for the test set:",
"_____no_output_____"
]
],
[
[
"df_obs_fr_test = pd.read_csv(DATA_PATH / \"observations\" / \"observations_fr_test.csv\", sep=\";\", index_col=\"observation_id\")\ndf_obs_us_test = pd.read_csv(DATA_PATH / \"observations\" / \"observations_us_test.csv\", sep=\";\", index_col=\"observation_id\")\n\ndf_obs_test = pd.concat((df_obs_fr_test, df_obs_us_test))\n\nobs_id_test = df_obs_test.index.values\n\nprint(\"Number of observations for testing: {}\".format(len(df_obs_test)))\n\ndf_obs_test.head()",
"Number of observations for testing: 36421\n"
]
],
[
[
"# Sample submission file\n\nIn this section, we will demonstrate how to generate the sample submission file provided.\n\nTo do so, we will use the function `generate_submission_file` from `GLC.submission`.",
"_____no_output_____"
],
[
"The sample submission consists in always predicting the first 30 species for all the test observations:",
"_____no_output_____"
]
],
[
[
"first_30_species = np.arange(30)\ns_pred = np.tile(first_30_species[None], (len(df_obs_test), 1))",
"_____no_output_____"
]
],
[
[
"We can then generate the associated submission file using:",
"_____no_output_____"
]
],
[
[
"generate_submission_file(SUBMISSION_PATH / \"sample_submission.csv\", df_obs_test.index, s_pred)",
"_____no_output_____"
]
],
[
[
"# Constant baseline: 30 most observed species\n\nThe first baseline consists in predicting the 30 most observed species on the train set which corresponds exactly to the \"Top-30 most present species\":",
"_____no_output_____"
]
],
[
[
"species_distribution = df_obs.loc[obs_id_train][\"species_id\"].value_counts(normalize=True)\ntop_30_most_observed = species_distribution.index.values[:30]",
"_____no_output_____"
]
],
[
[
"As expected, it does not perform very well on the validation set:",
"_____no_output_____"
]
],
[
[
"s_pred = np.tile(top_30_most_observed[None], (n_val, 1))\nscore = top_k_error_rate_from_sets(y_val, s_pred)\nprint(\"Top-30 error rate: {:.1%}\".format(score))",
"Top-30 error rate: 93.5%\n"
]
],
[
[
"We will however generate the associated submission file on the test using:",
"_____no_output_____"
]
],
[
[
"# Compute baseline on the test set\nn_test = len(df_obs_test)\ns_pred = np.tile(top_30_most_observed[None], (n_test, 1))\n\n# Generate the submission file\ngenerate_submission_file(SUBMISSION_PATH / \"constant_top_30_most_present_species_baseline.csv\", df_obs_test.index, s_pred)",
"_____no_output_____"
]
],
[
[
"# Random forest on environmental vectors\n\nA classical approach in ecology is to train Random Forests on environmental vectors.\n\nWe show here how to do so using [scikit-learn](https://scikit-learn.org/).\n\nWe start by loading the environmental vectors:",
"_____no_output_____"
]
],
[
[
"df_env = pd.read_csv(DATA_PATH / \"pre-extracted\" / \"environmental_vectors.csv\", sep=\";\", index_col=\"observation_id\")\n\nX_train = df_env.loc[obs_id_train].values\nX_val = df_env.loc[obs_id_val].values\nX_test = df_env.loc[obs_id_test].values",
"_____no_output_____"
]
],
[
[
"Then, we need to handle properly the missing values.\n\nFor instance, using `SimpleImputer`:",
"_____no_output_____"
]
],
[
[
"from sklearn.impute import SimpleImputer\nimp = SimpleImputer(\n missing_values=np.nan,\n strategy=\"constant\",\n fill_value=np.finfo(np.float32).min,\n)\nimp.fit(X_train)\n\nX_train = imp.transform(X_train)\nX_val = imp.transform(X_val)\nX_test = imp.transform(X_test)",
"_____no_output_____"
]
],
[
[
"We can now start training our Random Forest (as there are a lot of observations, over 1.8M, this can take a while):",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier\nest = RandomForestClassifier(n_estimators=16, max_depth=10, n_jobs=-1)\nest.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"As there are a lot of classes (over 17K), we need to be cautious when predicting the scores of the model.\n\nThis can easily take more than 5Go on the validation set.\n\nFor this reason, we will be predict the top-30 sets by batches using the following generic function:",
"_____no_output_____"
]
],
[
[
"def batch_predict(predict_func, X, batch_size=1024):\n res = predict_func(X[:1])\n n_samples, n_outputs, dtype = X.shape[0], res.shape[1], res.dtype\n \n preds = np.empty((n_samples, n_outputs), dtype=dtype)\n \n for i in range(0, len(X), batch_size):\n X_batch = X[i:i+batch_size]\n preds[i:i+batch_size] = predict_func(X_batch)\n \n return preds",
"_____no_output_____"
]
],
[
[
"We can know compute the top-30 error rate on the validation set:",
"_____no_output_____"
]
],
[
[
"def predict_func(X):\n y_score = est.predict_proba(X)\n s_pred = predict_top_30_set(y_score)\n return s_pred\n\ns_val = batch_predict(predict_func, X_val, batch_size=1024)\nscore_val = top_k_error_rate_from_sets(y_val, s_val)\nprint(\"Top-30 error rate: {:.1%}\".format(score_val))",
"Top-30 error rate: 80.4%\n"
]
],
[
[
"We now predict the top-30 sets on the test data and save them in a submission file:",
"_____no_output_____"
]
],
[
[
"# Compute baseline on the test set\ns_pred = batch_predict(predict_func, X_test, batch_size=1024)\n\n# Generate the submission file\ngenerate_submission_file(SUBMISSION_PATH / \"random_forest_on_environmental_vectors.csv\", df_obs_test.index, s_pred)",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb06cd5a5679e7093807655c40cd06b106f77750 | 16,997 | ipynb | Jupyter Notebook | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis | 5ca5b7c83adac880ae3441d28479fd27918dfb7e | [
"MIT"
] | null | null | null | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis | 5ca5b7c83adac880ae3441d28479fd27918dfb7e | [
"MIT"
] | null | null | null | Fund_of_Data_Analysis_Assessment.ipynb | pocathain08/Fund_of_Data_Analysis | 5ca5b7c83adac880ae3441d28479fd27918dfb7e | [
"MIT"
] | null | null | null | 30.190053 | 1,099 | 0.54745 | [
[
[
"## Tips Dataframe",
"_____no_output_____"
],
[
"- Loc:Desktop\\Fundamentals_of-Data_Analysis/Fund_of_Data_Analysis/",
"_____no_output_____"
]
],
[
[
"#import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns; sns.set()\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\nsns.set(rc={'figure.figsize':(10,8)})\nsns.set_style('white')",
"_____no_output_____"
]
],
[
[
"### Description",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(\"tips.csv\")",
"_____no_output_____"
],
[
"print (('The data has the following shape'), df.shape)\nprint (\"\\n\")\ndf.info()",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df = df.rename(columns={'total_bill': 'Bill', 'tip':'Tip', 'sex':'Gender', 'smoker':'Smoker', 'day':'Day','time':'Time', 'size': 'Party'})\ndf.head()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"df.plot(style = \"o\", ms=3, figsize = [10,5])\nplt.show()\n#Ref1: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.plotting.scatter_matrix.html\n#Ref2:http://jonathansoma.com/lede/algorithms-2017/classes/fuzziness-matplotlib/understand-df-plot-in-pandas/",
"_____no_output_____"
],
[
"color_list = ['red' if i=='Male' else 'green' for i in df.loc[:,'Gender']]\n\npd.plotting.scatter_matrix(df, alpha=0.9, c = color_list, figsize = [20,20],\n diagonal = 'hist', s = 100, marker = '.')\nplt.show()",
"_____no_output_____"
],
[
"df.groupby(['Gender', 'Party'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))\nplt.title('Tip amount by Party size and Gender')\nplt.ylabel('Tip Amount')",
"_____no_output_____"
],
[
"df['Tippc']=df.apply(lambda row: row.Tip / row.Bill, axis=1)\n# Ref: https://kaijento.github.io/2017/04/22/pandas-create-new-column-sum/\n# Tippc is the percent of the tip relative to the Bill",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.groupby(['Gender', 'Time'])['Tippc'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))\nplt.ylabel('Tip Amount as a percentage of the Bill')",
"_____no_output_____"
],
[
"#df2 = df(columns=['Gender', 'Time'])\n#df2 #.plot.bar()",
"_____no_output_____"
]
],
[
[
"### Linear Regression\n- Plot the Tips relative to the Bill amount.",
"_____no_output_____"
]
],
[
[
"df.plot(x='Bill', y='Tip', style='o') \nplt.title('Bill amount and Tip given') \nplt.xlabel('Bill') \nplt.ylabel('Tip') \nplt.show()",
"_____no_output_____"
]
],
[
[
"- Looking at where the dots, it would seem that the Tip amount increases relative to the Bill amount. It would seem that the Tip is approximate 20 % of the Bill amount. There are a few outliers that could skew the data.\n- I will try a few values for the slope and where it crosses the Y-axis. The slopes I will at will vary between 0.1 and 0.2. (I did try a number of other values, but for this analysis I will use the outlined values). ",
"_____no_output_____"
]
],
[
[
"# Plot w versus d with black dots.\ndf.plot(x='Bill', y='Tip', style='o')\n\n# Overlay some lines on the plot.\nx = np.arange(0.0, 50.0, 1.0)\nplt.plot(x, 0.125 * x + 0.5, 'r-', label=r\"$x/8 + 0.5$\")\nplt.plot(x, 0.2 * x + 0.5, 'g-', label=r\"$x/5 + 0.5$\")\nplt.plot(x, 0.1 * x + 0.0, 'b-', label=r\"$x/10 + 0.0$\")\n\n# Add a legend.\nplt.legend()\n\n# Add axis labels.\nplt.xlabel('Bill')\nplt.ylabel('Tips')\n# Adjust the plot range\nplt.ylim(0, 10)\n# Show the plot.\nplt.show()",
"_____no_output_____"
]
],
[
[
"- The red line seems to be the best fit. But I will investigate using the least square technique. In the above table, for every x, there is two values for y, one on the line and one on the dot. The following measures this distance and squares it (to account for negative values). The lease value is the best guess for the lines in the plot. ",
"_____no_output_____"
]
],
[
[
"B = df[\"Bill\"]\nT = df[\"Tip\"]\n\ncost = lambda m,c: np.sum([(T[i] - m * B[i] - c)**2 for i in range(B.size)])\n\nprint(\"Red line cost with m = %5.2f and c = %5.2f: is %8.2f\" % (0.125, 0.50, cost(0.125, 0.5)))\nprint(\"Green line cost with m = %5.2f and c = %5.2f: is %8.2f\" % (0.2, 0.5, cost(0.2, 0.5)))\nprint(\"Blue line cost with m = %5.2f and c = %5.2f: is %8.2f\" % (0.1, 0.0, cost(0.1, 0.0)))",
"_____no_output_____"
]
],
[
[
"### Minimising the cost",
"_____no_output_____"
]
],
[
[
"# Calculate the best values for m and c.\n\nB = df[\"Bill\"]\nT = df[\"Tip\"]\n\n# Calculate the best values for B and T.\nB_avg = df[\"Bill\"].mean()\nT_avg = df[\"Tip\"].mean()\n\nB_zero = B - B_avg\nT_zero = T - T_avg\n\nm = np.sum(B_zero * T_zero) / np.sum(B_zero * B_zero)\nc = T_avg - m * B_avg\n\nprint (\"m is %8.6f and c is %6.6f.\" % (m, c))\n\n\nx, y, x_avg, y_avg = B, T, B_avg, T_avg\nm2 = (np.sum(x * y) - y_avg * np.sum(x)) / (np.sum(x * x) - x_avg * np.sum(x))\nc2 = y_avg - m2 * x_avg\nm2, c2",
"_____no_output_____"
],
[
"np.polyfit(B, T, 1)",
"_____no_output_____"
]
],
[
[
"- The line the minimises the cost can now be superimposed on the data.",
"_____no_output_____"
]
],
[
[
"# Plot the best fit line.\nplt.plot(B, T, 'k.', label='Original data')\nplt.plot(B, m * B + c, 'b-', label='Best fit line')\n\n# Add axis labels and a legend.\nplt.xlabel('Bill')\nplt.ylabel('Tips')\nplt.legend()\n\nplt.ylim(0, 10)\n# Show the plot.\nplt.show()",
"_____no_output_____"
],
[
"cost = lambda m,c: np.sum([(T[i] - m * B[i] - c)**2 for i in range(B.size)])\n\nprint(\"Red line cost with m = %5.2f and c = %5.2f: is %8.2f\" % (0.105025, 0.920270, cost(0.11, 0.92)))",
"_____no_output_____"
]
],
[
[
"- In the case of linear regression, the cost function is the sum of the squares of the residuals (residuals being the difference between the dependent variable value and the value given by the model). The procedure finds for you the intercept and slope(s) that minimize the cost function.\n- This is why the linear regression method is also called “Least-squares regression”.\n- A line with slope = 0.11 and y-axia = 0.92: gives the lowest cost function, at 255.62.\n- So this equation best fits the line.",
"_____no_output_____"
]
],
[
[
"import statsmodels.api as sm\n\nX = df['Bill']\ny = df['Tip']\nX2 = sm.add_constant(X)\nest = sm.OLS(y, X2)\nest2 = est.fit()\nprint(est2.summary())",
"_____no_output_____"
]
],
[
[
"- Ref: https://towardsdatascience.com/the-complete-guide-to-linear-regression-in-python-3d3f8f06bf8\n- Looking at both coefficients, we have a p-value that is equal to 0. This means that there is a strong correlation between these coefficients and the target (Tip).\n- The R² value is equal to 0.45. Therefore, about 45% of the variability of Tips is explained by the Bill amount.",
"_____no_output_____"
],
[
"### Analysis\n- Analyse the relationship between the variables within the dataset.\n- The aim of this experiment is to determine what circumstances maxamises the Tip payable, this is done by minimising the Cost(m,c). Of course the data outlined above doesn't take into account, time, gender, smoker, so the model is not entirely accurate. ",
"_____no_output_____"
]
],
[
[
"plt.figure(1)\ndf.groupby(['Gender', 'Time'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))\nplt.ylabel('Tip Amount')\n\nplt.figure(2)\ndf.groupby(['Gender', 'Smoker'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))\nplt.ylabel('Tip Amount')\n\nplt.figure(3)\ndf.groupby(['Party', 'Time'])['Tip'].mean().unstack(level=0).plot(kind='bar', figsize=(10,5))\nplt.ylabel('Tip Amount')\n\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"- From the first three plots, it would seem that males are better tippers than females and that with the exeption of lunch, that size of the tip increases with the party amount. \n\n# End",
"_____no_output_____"
],
[
"## The following contains some code that was not needed but that I may come back to. ",
"_____no_output_____"
]
],
[
[
"B = df[\"Bill\"]\nT = df[\"Tip\"]\nP = df[\"Party\"]\nG = df['Gender']",
"_____no_output_____"
],
[
"#df.Gender = df.Gender.map({'Female':0,'Male':1})\n#df['Gender'] = df['Gender'].map(dict(zip(['Female','Male'],[0,1]))\ndf['Gender'] = (df['Gender'] == 'Female').astype(int)\ndf.head()\n",
"_____no_output_____"
],
[
"C = np.polyfit(P, T, 1)\nC",
"_____no_output_____"
],
[
"from statsmodels.formula.api import ols\n\nfit = ols('Tip ~ (Bill)', data=df).fit() \n\nfit.summary()",
"_____no_output_____"
],
[
"m = 0.71182064\nc = 1.16913303\n\ncost = lambda m,c: np.sum([(T[i] - m * P[i] - c)**2 for i in range(P.size)])\n\nprint(\"Red line cost with m = %5.2f and c = %5.2f: is %8.2f\" % (0.71182064, 1.16913303, cost(0.71182064, 1.16913303)))",
"_____no_output_____"
],
[
"X = df['Party']\ny = df['Tip']\nX2 = sm.add_constant(X)\nest = sm.OLS(y, X2)\nest2 = est.fit()\nprint(est2.summary())",
"_____no_output_____"
],
[
"import seaborn as sns\n\nimport sklearn.neighbors as nei\n# Plot the tips data set with a pair plot.\nsns.pairplot(df)",
"_____no_output_____"
]
],
[
[
"- https://www.accelebrate.com/blog/interpreting-results-from-linear-regression-is-the-data-appropriate",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb06db3c9e9f7fca9211f305cb52f132c9751534 | 275,127 | ipynb | Jupyter Notebook | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised | aff7080de43a8fafa46512b65b090451f9055b12 | [
"MIT"
] | 1 | 2020-04-29T11:17:54.000Z | 2020-04-29T11:17:54.000Z | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised | aff7080de43a8fafa46512b65b090451f9055b12 | [
"MIT"
] | null | null | null | Preprocessing Tutorial.ipynb | GAnagno/Unsupervised | aff7080de43a8fafa46512b65b090451f9055b12 | [
"MIT"
] | null | null | null | 248.75859 | 21,476 | 0.929378 | [
[
[
"# Preprocessing for deep learning",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"plt.style.use('ggplot')\nplt.rcParams['axes.facecolor'] ='w'\nplt.rcParams['axes.edgecolor'] = '#D6D6D6'\nplt.rcParams['axes.linewidth'] = 2",
"_____no_output_____"
]
],
[
[
"# 1. Background",
"_____no_output_____"
],
[
"## A. Variance and covariance",
"_____no_output_____"
],
[
"### Example 1.",
"_____no_output_____"
]
],
[
[
"A = np.array([[1, 3, 5], [5, 4, 1], [3, 8, 6]])\nprint(A)",
"[[1 3 5]\n [5 4 1]\n [3 8 6]]\n"
],
[
"print(np.cov(A, rowvar=False, bias=True))",
"[[ 2.66666667 0.66666667 -2.66666667]\n [ 0.66666667 4.66666667 2.33333333]\n [-2.66666667 2.33333333 4.66666667]]\n"
]
],
[
[
"### Finding the covariance matrix with the dot product",
"_____no_output_____"
]
],
[
[
"def calculateCovariance(X):\n meanX = np.mean(X, axis = 0)\n lenX = X.shape[0]\n X = X - meanX\n covariance = X.T.dot(X)/lenX\n return covariance",
"_____no_output_____"
],
[
"print(calculateCovariance(A))",
"[[ 2.66666667 0.66666667 -2.66666667]\n [ 0.66666667 4.66666667 2.33333333]\n [-2.66666667 2.33333333 4.66666667]]\n"
]
],
[
[
"## B. Visualize data and covariance matrices",
"_____no_output_____"
]
],
[
[
"def plotDataAndCov(data):\n ACov = np.cov(data, rowvar=False, bias=True)\n print('Covariance matrix:\\n', ACov)\n\n fig, ax = plt.subplots(nrows=1, ncols=2)\n fig.set_size_inches(10, 10)\n\n ax0 = plt.subplot(2, 2, 1)\n \n # Choosing the colors\n cmap = sns.color_palette(\"GnBu\", 10)\n sns.heatmap(ACov, cmap=cmap, vmin=0)\n\n ax1 = plt.subplot(2, 2, 2)\n \n # data can include the colors\n if data.shape[1]==3:\n c=data[:,2]\n else:\n c=\"#0A98BE\"\n ax1.scatter(data[:,0], data[:,1], c=c, s=40)\n \n # Remove the top and right axes from the data plot\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)",
"_____no_output_____"
]
],
[
[
"## C. Simulating data",
"_____no_output_____"
],
[
"### Uncorrelated data",
"_____no_output_____"
]
],
[
[
"np.random.seed(1234)\na1 = np.random.normal(2, 1, 300)\na2 = np.random.normal(1, 1, 300)\nA = np.array([a1, a2]).T\nA.shape",
"_____no_output_____"
],
[
"print(A[:10,:])",
"[[ 2.47143516 1.52704645]\n [ 0.80902431 1.7111124 ]\n [ 3.43270697 0.78245452]\n [ 1.6873481 3.63779121]\n [ 1.27941127 -0.74213763]\n [ 2.88716294 0.90556519]\n [ 2.85958841 2.43118375]\n [ 1.3634765 1.59275845]\n [ 2.01569637 1.1702969 ]\n [-0.24268495 -0.75170595]]\n"
],
[
"sns.distplot(A[:,0], color=\"#53BB04\")\nsns.distplot(A[:,1], color=\"#0A98BE\")\nplt.show()\nplt.close()",
"_____no_output_____"
],
[
"plotDataAndCov(A)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[ 0.95171641 -0.0447816 ]\n [-0.0447816 0.87959853]]\n"
]
],
[
[
"### Correlated data",
"_____no_output_____"
]
],
[
[
"np.random.seed(1234)\nb1 = np.random.normal(3, 1, 300)\nb2 = b1 + np.random.normal(7, 1, 300)/2.\nB = np.array([b1, b2]).T\nplotDataAndCov(B)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[0.95171641 0.92932561]\n [0.92932561 1.12683445]]\n"
]
],
[
[
"# 2. Preprocessing",
"_____no_output_____"
],
[
"## A. Mean normalization",
"_____no_output_____"
]
],
[
[
"def center(X):\n newX = X - np.mean(X, axis = 0)\n return newX",
"_____no_output_____"
],
[
"BCentered = center(B)\n\nprint('Before:\\n\\n')\n\nplotDataAndCov(B)\nplt.show()\nplt.close()\n\nprint('After:\\n\\n')\n\nplotDataAndCov(BCentered)\nplt.show()\nplt.close()",
"Before:\n\n\nCovariance matrix:\n [[0.95171641 0.92932561]\n [0.92932561 1.12683445]]\n"
]
],
[
[
"## B. Standardization",
"_____no_output_____"
]
],
[
[
"def standardize(X):\n newX = center(X)/np.std(X, axis = 0)\n return newX",
"_____no_output_____"
],
[
"np.random.seed(1234)\nc1 = np.random.normal(3, 1, 300)\nc2 = c1 + np.random.normal(7, 5, 300)/2.\nC = np.array([c1, c2]).T\n\nplotDataAndCov(C)\nplt.xlim(0, 15)\nplt.ylim(0, 15)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[0.95171641 0.83976242]\n [0.83976242 6.22529922]]\n"
],
[
"CStandardized = standardize(C)\n\nplotDataAndCov(CStandardized)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[1. 0.34500274]\n [0.34500274 1. ]]\n"
]
],
[
[
"## C. Whitening",
"_____no_output_____"
],
[
"### 1. Zero-centering",
"_____no_output_____"
]
],
[
[
"CCentered = center(C)\n\nplotDataAndCov(CCentered)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[0.95171641 0.83976242]\n [0.83976242 6.22529922]]\n"
]
],
[
[
"### 2. Decorrelate",
"_____no_output_____"
]
],
[
[
"def decorrelate(X):\n cov = X.T.dot(X)/float(X.shape[0])\n # Calculate the eigenvalues and eigenvectors of the covariance matrix\n eigVals, eigVecs = np.linalg.eig(cov)\n # Apply the eigenvectors to X\n decorrelated = X.dot(eigVecs)\n return decorrelated",
"_____no_output_____"
],
[
"plotDataAndCov(C)\nplt.show()\nplt.close()\n\nCDecorrelated = decorrelate(CCentered)\nplotDataAndCov(CDecorrelated)\nplt.xlim(-5,5)\nplt.ylim(-5,5)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[0.95171641 0.83976242]\n [0.83976242 6.22529922]]\n"
]
],
[
[
"### 3. Rescale the data",
"_____no_output_____"
]
],
[
[
"def whiten(X):\n cov = X.T.dot(X)/float(X.shape[0])\n # Calculate the eigenvalues and eigenvectors of the covariance matrix\n eigVals, eigVecs = np.linalg.eig(cov)\n # Apply the eigenvectors to X\n decorrelated = X.dot(eigVecs)\n # Rescale the decorrelated data\n whitened = decorrelated / np.sqrt(eigVals + 1e-5)\n return whitened",
"_____no_output_____"
],
[
"CWhitened = whiten(CCentered)\n\nplotDataAndCov(CWhitened)\nplt.xlim(-5,5)\nplt.ylim(-5,5)\nplt.show()\nplt.close()",
"Covariance matrix:\n [[9.99987823e-01 2.51650552e-17]\n [2.51650552e-17 9.99998427e-01]]\n"
]
],
[
[
"# 3. Image whitening",
"_____no_output_____"
]
],
[
[
"from keras.datasets import cifar10\n\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\nX_train.shape",
"Using TensorFlow backend.\n"
],
[
"X = X_train[:1000]\nprint(X.shape)",
"(1000, 32, 32, 3)\n"
],
[
"X = X.reshape(X.shape[0], X.shape[1]*X.shape[2]*X.shape[3])\nprint(X.shape)",
"(1000, 3072)\n"
],
[
"def plotImage(X):\n plt.rcParams[\"axes.grid\"] = False\n plt.figure(figsize=(1.5, 1.5))\n plt.imshow(X.reshape(32,32,3))\n plt.show()\n plt.close()",
"_____no_output_____"
],
[
"plotImage(X[12, :])",
"_____no_output_____"
],
[
"X_norm = X / 255.\nprint('X.min()', X_norm.min())\nprint('X.max()', X_norm.max())",
"X.min() 0.0\nX.max() 1.0\n"
],
[
"X_norm.mean(axis=0).shape",
"_____no_output_____"
],
[
"print(X_norm.mean(axis=0))",
"[0.5234 0.54323137 0.5274 ... 0.50369804 0.50011765 0.45227451]\n"
],
[
"X_norm = X_norm - X_norm.mean(axis=0)",
"_____no_output_____"
],
[
"print(X_norm.mean(axis=0))",
"[-5.30575583e-16 -5.98021632e-16 -4.23439062e-16 ... -1.81965554e-16\n -2.49800181e-16 3.98570066e-17]\n"
],
[
"cov = np.cov(X_norm, rowvar=True)",
"_____no_output_____"
],
[
"cov.shape",
"_____no_output_____"
],
[
"U,S,V = np.linalg.svd(cov)",
"_____no_output_____"
],
[
"print(U.shape, S.shape)",
"(1000, 1000) (1000,)\n"
],
[
"print(np.diag(S))\nprint('\\nshape:', np.diag(S).shape)",
"[[8.15846654e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 4.68234845e+00 0.00000000e+00 ... 0.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 2.41075267e+00 ... 0.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n ...\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 3.92727365e-05\n 0.00000000e+00 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00\n 3.52614473e-05 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00\n 0.00000000e+00 1.35907202e-15]]\n\nshape: (1000, 1000)\n"
],
[
"epsilon = 0.1\nX_ZCA = U.dot(np.diag(1.0/np.sqrt(S + epsilon))).dot(U.T).dot(X_norm)",
"_____no_output_____"
],
[
"plotImage(X[12, :])\nplotImage(X_ZCA[12, :])",
"_____no_output_____"
],
[
"X_ZCA_rescaled = (X_ZCA - X_ZCA.min()) / (X_ZCA.max() - X_ZCA.min())\nprint('min:', X_ZCA_rescaled.min())\nprint('max:', X_ZCA_rescaled.max())",
"min: 0.0\nmax: 1.0\n"
],
[
"plotImage(X[12, :])\nplotImage(X_ZCA_rescaled[12, :])",
"_____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",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb06dc46a44b57f005b56198380153de937f4aa4 | 12,430 | ipynb | Jupyter Notebook | notebooks/scalability.ipynb | veronicatozzo/regain | 5eaa9685eb34afa77abaf80a4e5764444bc95dd7 | [
"BSD-3-Clause"
] | null | null | null | notebooks/scalability.ipynb | veronicatozzo/regain | 5eaa9685eb34afa77abaf80a4e5764444bc95dd7 | [
"BSD-3-Clause"
] | null | null | null | notebooks/scalability.ipynb | veronicatozzo/regain | 5eaa9685eb34afa77abaf80a4e5764444bc95dd7 | [
"BSD-3-Clause"
] | null | null | null | 32.454308 | 172 | 0.523492 | [
[
[
"# Scalability\nThis notebook show the scalability analysis performed in the paper.\nWe compared our LTGL model with respect to state-of-the art software for graphical inference, such as LVGLASSO and TVGL.\n\n<font color='red'><b>Note</b></font>: GL is not included in the comparison, since it is based on coordinate descent and it does not have the eigenvalue decomposition.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nimport matlab\nimport matlab.engine\nimport pandas as pd\nimport numpy as np\nimport cPickle as pkl\nimport time\n\nfrom itertools import product\n\nfrom regain import datasets, utils\nfrom regain.covariance import latent_time_graph_lasso_",
"_____no_output_____"
],
[
"def ltgl_results(data_grid, K, K_obs, ells, **params):\n \n mdl = latent_time_graph_lasso_.LatentTimeGraphLasso(\n bypass_transpose=False, assume_centered=0, verbose=0, tol=1e-4, rtol=1e-4,\n max_iter=500, rho=1./ np.sqrt(data_grid.shape[0]))\n \n tic = time.time()\n ll = mdl.set_params(**params).fit(data_grid)\n tac = time.time()\n iterations = ll.n_iter_\n ss = utils.structure_error(K, ll.precision_)#, thresholding=1, eps=1e-5)\n MSE_observed = utils.error_norm(K_obs, ll.precision_ - ll.latent_)\n MSE_precision = utils.error_norm(K, ll.precision_)\n MSE_latent = utils.error_norm(ells, ll.latent_)\n mean_rank_error = utils.error_rank(ells, ll.latent_)\n \n res = dict(n_dim_obs=K.shape[1],\n time=tac-tic,\n iterations=iterations,\n MSE_precision=MSE_precision,\n MSE_observed=MSE_observed,\n MSE_latent=MSE_latent,\n mean_rank_error=mean_rank_error,\n note=None,\n estimator=ll)\n \n res = dict(res, **ss)\n return res\n\nimport sys; sys.path.append(\"/home/fede/src/TVGL\")\nfrom TVGL import TVGL\nfrom regain import utils; reload(utils)\nfrom regain.utils import suppress_stdout\n\ndef hallac_results(data_grid, K, K_obs, ells, beta, alpha):\n \n with suppress_stdout():\n tic = time.time()\n thetaSet, empCovSet, status, gvx = TVGL(\n np.vstack(data_grid.transpose(2,0,1)), data_grid.shape[0], lamb=alpha, beta=beta,\n indexOfPenalty=2)\n tac = time.time()\n\n if status != \"Optimal\":\n print (\"not converged\")\n precisions = np.array(thetaSet)\n ss = utils.structure_error(K, precisions)\n MSE_observed = None\n MSE_precision = utils.error_norm(K, precisions)\n MSE_latent = None\n mean_rank_error = None\n\n res = dict(n_dim_obs=K.shape[1],\n time=tac-tic,\n iterations=gvx.n_iter_,\n MSE_precision=MSE_precision,\n MSE_observed=MSE_observed,\n MSE_latent=MSE_latent,\n mean_rank_error=mean_rank_error,\n note=status,\n estimator=gvx)\n \n res = dict(res, **ss)\n return res",
"_____no_output_____"
],
[
"try:\n eng.quit()\nexcept:\n pass\neng = matlab.engine.start_matlab()\neng.addpath(r'/home/fede/src/slipguru/regain/regain/wrapper/lvglasso/',nargout=0)\n# eng.addpath(r'path/to/ADMM_B.m/',nargout=0)",
"_____no_output_____"
],
[
"def chandresekeran_results(data_grid, K, K_obs, ells, tau, alpha, **whatever):\n \n emp_list = np.array([empirical_covariance(x, assume_centered=True)\n for x in data_grid.transpose(2,0,1)]).transpose(1,2,0)\n \n n_samples = emp_list.shape[0]\n rho = 1./ np.sqrt(data_grid.shape[0])\n\n # 3. Matlab engine\n result = eng.LVGLASSO(matlab.double(emp_list.tolist()),float(alpha),float(tau),float(rho))\n ma_output = Bunch(**result)\n\n ma_output.R = np.array(ma_output.R)\n ma_output.S = np.array(ma_output.S)\n ma_output.L = np.array(ma_output.L)\n \n ss = utils.structure_error(K, ma_output.R + ma_output.L)#, thresholding=1, eps=1e-5)\n MSE_observed = utils.error_norm(K_obs, ma_output.R)\n MSE_precision = utils.error_norm(K, ma_output.R + ma_output.L)\n MSE_latent = utils.error_norm(ells, ma_output.L)\n mean_rank_error = utils.error_rank(ells, ma_output.L)\n \n res = dict(n_dim_obs=K.shape[1],\n time=ma_output.elapsed_time,\n iterations=np.max(ma_output.iter),\n MSE_precision=MSE_precision,\n MSE_observed=MSE_observed,\n MSE_latent=MSE_latent,\n mean_rank_error=mean_rank_error,\n note=None, estimator=ma_output)\n \n res = dict(res, **ss)\n return res",
"_____no_output_____"
],
[
"# prepare data\nn_times = [20, 50, 100]\nn_dims = np.sqrt(np.logspace(2,5,10)).astype(int)\n\nn_samples = 200\nn_dim_lat = 2\n\nnp.random.seed(42)\nwith suppress_stdout():\n data = {(dim,T) : datasets.make_dataset(\n mode='ma', n_samples=n_samples, n_dim_lat=n_dim_lat, n_dim_obs=dim, T=T, epsilon=1e-2)\n for dim, T in (product(n_dims, n_times))}",
"_____no_output_____"
],
[
"alpha = 1\ntau = 1\nbeta = 1\neta = 1\n\nmethods = ['LTGL', 'GL', 'LVGLASSO', 'TVGL']\nscores = sorted(['iterations', 'time', 'note'])\n\ncols = pd.MultiIndex.from_product([scores, n_dims], names=('score','dim'))\nrows = pd.MultiIndex.from_product([methods, n_times], names=('method','time'))\n\ndff = pd.DataFrame(columns=cols, index=rows)\nidx = pd.IndexSlice",
"_____no_output_____"
],
[
"for i, (k, res) in enumerate(sorted(data.items())):\n dim = k[0]\n print(\"Start with: dim=%d, T=%d (it %d)\" % (k[0],k[1], i))\n data_list = res.data\n K = res.thetas\n K_obs = res.thetas_observed\n ells = res.ells\n data_grid = np.array(data_list).transpose(1,2,0) # to use it later for grid search\n\n print(\"starting LTGL ...\\r\", end='')\n res_l = ltgl_results(data_grid, K, K_obs, ells, alpha=alpha, beta=beta, tau=tau, eta=eta)\n dff.loc[idx['LTGL', k[1]], idx[:, k[0]]] = [res_l[x] for x in scores]\n\n print(\"starting GL...\\r\", end='')\n res = glasso_results(data_grid, K, K_obs, ells, alpha=alpha)\n \n # Use this for the R-implementation \n # res = friedman_results(data_grid, K, K_obs, ells, alpha=alpha)\n dff.loc[idx['GL', k[1]], idx[:, k[0]]] = [res[x] for x in scores]\n \n print(\"starting LVGLASSO...\\r\", end='')\n res_c = chandresekeran_results(data_grid, K, K_obs, ells, tau=tau, alpha=alpha)\n dff.loc[idx['LVGLASSO', k[1]], idx[:, k[0]]] = [res_c[x] for x in scores]",
"_____no_output_____"
],
[
"df.to_pickle(\"scalability_no_hallac.pkl\")",
"_____no_output_____"
],
[
"logger = init_logger('scalability')",
"_____no_output_____"
]
],
[
[
"Since this is computationally expensive, we divide the results in two cells ...",
"_____no_output_____"
]
],
[
[
"for i, (k, res) in enumerate(sorted(data.items())):\n dim = k[0]\n logging.info(\"Start TVGL with: dim=%d, T=%d (it %d)\" % (k[0],k[1], i))\n data_list = res.data\n K = res.thetas\n K_obs = res.thetas_observed\n ells = res.ells\n data_grid = np.array(data_list).transpose(1,2,0) # to use it later for grid search\n \n try:\n# print(\"starting TVGL...\\r\", end='')\n res = hallac_results(data_grid, K, K_obs, ells, beta=beta, alpha=alpha)\n dff.loc[idx['TVGL', k[1]], idx[:, k[0]]] = [res[x] for x in scores]\n dff.to_pickle(\"scalability_hallac.pkl\")\n except:\n pass",
"_____no_output_____"
]
],
[
[
"## Plotting",
"_____no_output_____"
]
],
[
[
"# load pickle\nwith open(\"scalability.pkl\", 'rb') as f:\n df = pkl.load(f)\n\ndf.sortlevel(inplace=True)\n\nidx = pd.IndexSlice\nscores = df.columns.levels[0]\nn_dims = df.columns.levels[1]\nmethods = df.index.levels[0]\nn_times = df.index.levels[1]",
"_____no_output_____"
]
],
[
[
"Let's plot a horizontal figure.",
"_____no_output_____"
]
],
[
[
"style = ['-', '--', ':']\n\nf, ax = plt.subplots(1, len(n_times), sharey=True, figsize=(12,2), dpi=600)\n\nax[0].set_ylabel(\"seconds\")\n# ax[0].set_ylim([.1,None])\nfor i, t in enumerate(n_times):\n for j, m in enumerate([m for m in methods if m != 'GL']):\n if m == 'GL':\n continue\n ax[i].plot(n_dims * (n_dims + 1) * t, df.loc[idx[m, t], idx['time',:]].values, ls=style[j], label=m)\n\n ax[i].set_yscale('log')\n ax[i].set_xscale('log')\n ax[i].set_xlabel(r\"number of unknowns at T = %d\" % t)\n ax[i].grid('on')\n# ax[i].set_title(\"n_times: %d\" % t)\n # plt.xticks(range(4), ours.n_dim_obs)\nax[0].set_yticks([1, 10, 1e2, 1e3, 1e4])\nlgd = ax[1].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode=\"expand\", borderaxespad=0.)\nf.tight_layout()",
"_____no_output_____"
],
[
"f.savefig(\"scalability.pdf\", dpi=600, transparent=True, bbox_extra_artists=(lgd,), bbox_inches='tight')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb06e10843d928252edcf7fbc8dd87d015a8bc21 | 190,098 | ipynb | Jupyter Notebook | src/python/EfficientNet_Fine_Tuning.ipynb | mrr00b00t/rnap | 98d4f1183b179cfc04c719dc2f174bb0f6de56f6 | [
"MIT"
] | 1 | 2021-09-24T14:34:02.000Z | 2021-09-24T14:34:02.000Z | src/python/EfficientNet_Fine_Tuning.ipynb | mrr00b00t/efn-siim-covid19 | 98d4f1183b179cfc04c719dc2f174bb0f6de56f6 | [
"MIT"
] | null | null | null | src/python/EfficientNet_Fine_Tuning.ipynb | mrr00b00t/efn-siim-covid19 | 98d4f1183b179cfc04c719dc2f174bb0f6de56f6 | [
"MIT"
] | null | null | null | 85.668319 | 1,448 | 0.618086 | [
[
[
"## Organização do dataset",
"_____no_output_____"
]
],
[
[
"def dicom2png(input_file, output_file):\n try:\n ds = pydicom.dcmread(input_file)\n shape = ds.pixel_array.shape\n\n # Convert to float to avoid overflow or underflow losses.\n image_2d = ds.pixel_array.astype(float)\n\n # Rescaling grey scale between 0-255\n image_2d_scaled = (np.maximum(image_2d,0) / image_2d.max()) * 255.0\n\n # Convert to uint\n image_2d_scaled = np.uint8(image_2d_scaled)\n\n # Write the PNG file\n with open(output_file, 'wb') as png_file:\n w = png.Writer(shape[1], shape[0], greyscale=True)\n w.write(png_file, image_2d_scaled)\n except:\n print('Could not convert: ', input_file)",
"_____no_output_____"
],
[
"from google.colab import drive\n\ndrive.mount(\"/content/gdrive\", force_remount=True)",
"Mounted at /content/gdrive\n"
],
[
"import pandas as pd\nimport shutil\nimport glob\nfrom sklearn.model_selection import train_test_split\nimport os",
"_____no_output_____"
],
[
"study_level = pd.read_csv(\"gdrive/MyDrive/covid-dataset/train_study_level.csv\")\nimage_level = pd.read_csv(\"gdrive/MyDrive/covid-dataset/train_image_level.csv\")\n\nstudy_level['study_name'] = study_level['id'].apply(lambda x: x.replace('_study', ''))",
"_____no_output_____"
],
[
"df = pd.DataFrame()\n\ndf['image_name'] = image_level['id'].apply(lambda x: x.replace('_image', ''))\ndf['study_name'] = image_level['StudyInstanceUID']\n\nmerge = pd.merge(df, study_level, on='study_name')\n\nr0 = merge['Typical Appearance'].apply(lambda x: 'typical' if x == 1 else False)\nr1 = merge['Atypical Appearance'].apply(lambda x: 'atypical' if x == 1 else False)\nr2 = merge['Indeterminate Appearance'].apply(lambda x: 'indeterminate' if x == 1 else False)\n\nlabels = []\n\nfor a,b,c in zip(r0, r1, r2):\n if a != False:\n labels.append(a)\n continue\n if b != False:\n labels.append(b)\n continue\n if c != False:\n labels.append(c)\n continue\n\n labels.append('not recognized')\n\nmerge['label'] = labels",
"_____no_output_____"
],
[
"shutil.copy('gdrive/MyDrive/covid-dataset/nn_train_600.zip', './')",
"_____no_output_____"
],
[
"!unzip -qq nn_train_600.zip",
"_____no_output_____"
],
[
"img_df = pd.DataFrame()\n\npaths = glob.glob('./nn_train_600/**/*.png', recursive=True)\n\nimg_df['path'] = paths\nimg_df['image_name'] = img_df['path'].apply(lambda x: x.split('/')[-1].replace('.png', ''))\n\nfndf = pd.merge(merge, img_df, on='image_name')",
"_____no_output_____"
],
[
"X, y = fndf['path'], fndf['label']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)",
"_____no_output_____"
],
[
"os.makedirs('train/typical', exist_ok=True)\nos.makedirs('train/indeterminate', exist_ok=True)\nos.makedirs('train/atypical', exist_ok=True)\n\nos.makedirs('test/typical', exist_ok=True)\nos.makedirs('test/indeterminate', exist_ok=True)\nos.makedirs('test/atypical', exist_ok=True)",
"_____no_output_____"
],
[
"def distribute_images(_paths, _labels, _folder):\n for path, label in zip(_paths, _labels):\n shutil.copy(path, _folder + '/' + label)\n\ndistribute_images(X_train, y_train, 'train')\ndistribute_images(X_test, y_test, 'test')",
"_____no_output_____"
]
],
[
[
"## Fine-tuning EfficientNet",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6, EfficientNetB7\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers",
"_____no_output_____"
],
[
"try:\n tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection\n print(\"Running on TPU \", tpu.cluster_spec().as_dict()[\"worker\"])\n tf.config.experimental_connect_to_cluster(tpu)\n tf.tpu.experimental.initialize_tpu_system(tpu)\n strategy = tf.distribute.TPUStrategy(tpu)\nexcept ValueError:\n print(\"Not connected to a TPU runtime. Using CPU/GPU strategy\")\n strategy = tf.distribute.MirroredStrategy()",
"Not connected to a TPU runtime. Using CPU/GPU strategy\nINFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',)\n"
],
[
"batch_size = 64\nheight = 456\nwidth = 456\ninput_shape = (height, width, 3)",
"_____no_output_____"
],
[
"with strategy.scope():\n train_datagen = ImageDataGenerator(\n rescale=1,\n rotation_range=10,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n horizontal_flip=True,)\n\n # Note that the validation data should not be augmented!\n test_datagen = ImageDataGenerator(rescale=1)\n\n train_generator = train_datagen.flow_from_directory(\n # This is the target directory\n \"train\",\n # All images will be resized to target height and width.\n target_size=(height, width),\n batch_size=batch_size,\n # Since we use categorical_crossentropy loss, we need categorical labels\n class_mode='categorical')\n\n validation_generator = test_datagen.flow_from_directory(\n \"test\",\n target_size=(height, width),\n batch_size=batch_size,\n class_mode='categorical', shuffle=False)",
"Found 3382 images belonging to 3 classes.\nFound 846 images belonging to 3 classes.\n"
],
[
"with strategy.scope():\n model = models.Sequential()\n model.add(layers.Input(shape=(height, width, 3)))\n model.add(EfficientNetB7(include_top=True, weights=None, classes=3))\n model.compile(\n optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n\n model.summary()\n\n hist = model.fit_generator(\n train_generator,\n steps_per_epoch= 3382 // batch_size,\n epochs=20,\n validation_data=validation_generator,\n validation_steps= 846 // batch_size,\n verbose=1,)",
"Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nefficientnetb7 (Functional) (None, 3) 64105370 \n=================================================================\nTotal params: 64,105,370\nTrainable params: 63,794,643\nNon-trainable params: 310,727\n_________________________________________________________________\n"
],
[
"def build_model(num_classes):\n inputs = layers.Input(shape=(height, width, 3))\n x = inputs\n model = EfficientNetB5(include_top=False, input_tensor=x, weights=\"imagenet\")\n\n # Freeze the pretrained weights\n model.trainable = False\n\n # Rebuild top\n x = layers.GlobalAveragePooling2D(name=\"avg_pool\")(model.output)\n x = layers.BatchNormalization()(x)\n\n top_dropout_rate = 0.2\n x = layers.Dropout(top_dropout_rate, name=\"top_dropout\")(x)\n outputs = layers.Dense(num_classes, activation=\"softmax\", name=\"pred\")(x)\n\n # Compile\n model = tf.keras.Model(inputs, outputs, name=\"EfficientNet\")\n\n for layer in model.layers[-20:]:\n if not isinstance(layer, layers.BatchNormalization):\n layer.trainable = True\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)\n model.compile(\n optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n return model\n\n\nwith strategy.scope():\n model2 = build_model(3)\n\n model2.summary()\n\n checkpoint_filepath = 'gdrive/MyDrive/covid-dataset'\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_filepath,\n save_weights_only=True,\n monitor='val_accuracy',\n mode='max',\n save_best_only=True)\n\n hist = model2.fit_generator(\n train_generator,\n steps_per_epoch= 3382 // batch_size,\n epochs=50,\n validation_data=validation_generator,\n validation_steps= 846 // batch_size,\n verbose=1, callbacks=[model_checkpoint_callback])",
"Model: \"EfficientNet\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_2 (InputLayer) [(None, 456, 456, 3) 0 \n__________________________________________________________________________________________________\nrescaling_1 (Rescaling) (None, 456, 456, 3) 0 input_2[0][0] \n__________________________________________________________________________________________________\nnormalization_1 (Normalization) (None, 456, 456, 3) 7 rescaling_1[0][0] \n__________________________________________________________________________________________________\nstem_conv_pad (ZeroPadding2D) (None, 457, 457, 3) 0 normalization_1[0][0] \n__________________________________________________________________________________________________\nstem_conv (Conv2D) (None, 228, 228, 48) 1296 stem_conv_pad[0][0] \n__________________________________________________________________________________________________\nstem_bn (BatchNormalization) (None, 228, 228, 48) 192 stem_conv[0][0] \n__________________________________________________________________________________________________\nstem_activation (Activation) (None, 228, 228, 48) 0 stem_bn[0][0] \n__________________________________________________________________________________________________\nblock1a_dwconv (DepthwiseConv2D (None, 228, 228, 48) 432 stem_activation[0][0] \n__________________________________________________________________________________________________\nblock1a_bn (BatchNormalization) (None, 228, 228, 48) 192 block1a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock1a_activation (Activation) (None, 228, 228, 48) 0 block1a_bn[0][0] \n__________________________________________________________________________________________________\nblock1a_se_squeeze (GlobalAvera (None, 48) 0 block1a_activation[0][0] \n__________________________________________________________________________________________________\nblock1a_se_reshape (Reshape) (None, 1, 1, 48) 0 block1a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock1a_se_reduce (Conv2D) (None, 1, 1, 12) 588 block1a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock1a_se_expand (Conv2D) (None, 1, 1, 48) 624 block1a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock1a_se_excite (Multiply) (None, 228, 228, 48) 0 block1a_activation[0][0] \n block1a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock1a_project_conv (Conv2D) (None, 228, 228, 24) 1152 block1a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock1a_project_bn (BatchNormal (None, 228, 228, 24) 96 block1a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock1b_dwconv (DepthwiseConv2D (None, 228, 228, 24) 216 block1a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock1b_bn (BatchNormalization) (None, 228, 228, 24) 96 block1b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock1b_activation (Activation) (None, 228, 228, 24) 0 block1b_bn[0][0] \n__________________________________________________________________________________________________\nblock1b_se_squeeze (GlobalAvera (None, 24) 0 block1b_activation[0][0] \n__________________________________________________________________________________________________\nblock1b_se_reshape (Reshape) (None, 1, 1, 24) 0 block1b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock1b_se_reduce (Conv2D) (None, 1, 1, 6) 150 block1b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock1b_se_expand (Conv2D) (None, 1, 1, 24) 168 block1b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock1b_se_excite (Multiply) (None, 228, 228, 24) 0 block1b_activation[0][0] \n block1b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock1b_project_conv (Conv2D) (None, 228, 228, 24) 576 block1b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock1b_project_bn (BatchNormal (None, 228, 228, 24) 96 block1b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock1b_drop (Dropout) (None, 228, 228, 24) 0 block1b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock1b_add (Add) (None, 228, 228, 24) 0 block1b_drop[0][0] \n block1a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock1c_dwconv (DepthwiseConv2D (None, 228, 228, 24) 216 block1b_add[0][0] \n__________________________________________________________________________________________________\nblock1c_bn (BatchNormalization) (None, 228, 228, 24) 96 block1c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock1c_activation (Activation) (None, 228, 228, 24) 0 block1c_bn[0][0] \n__________________________________________________________________________________________________\nblock1c_se_squeeze (GlobalAvera (None, 24) 0 block1c_activation[0][0] \n__________________________________________________________________________________________________\nblock1c_se_reshape (Reshape) (None, 1, 1, 24) 0 block1c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock1c_se_reduce (Conv2D) (None, 1, 1, 6) 150 block1c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock1c_se_expand (Conv2D) (None, 1, 1, 24) 168 block1c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock1c_se_excite (Multiply) (None, 228, 228, 24) 0 block1c_activation[0][0] \n block1c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock1c_project_conv (Conv2D) (None, 228, 228, 24) 576 block1c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock1c_project_bn (BatchNormal (None, 228, 228, 24) 96 block1c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock1c_drop (Dropout) (None, 228, 228, 24) 0 block1c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock1c_add (Add) (None, 228, 228, 24) 0 block1c_drop[0][0] \n block1b_add[0][0] \n__________________________________________________________________________________________________\nblock2a_expand_conv (Conv2D) (None, 228, 228, 144 3456 block1c_add[0][0] \n__________________________________________________________________________________________________\nblock2a_expand_bn (BatchNormali (None, 228, 228, 144 576 block2a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock2a_expand_activation (Acti (None, 228, 228, 144 0 block2a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock2a_dwconv_pad (ZeroPadding (None, 229, 229, 144 0 block2a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock2a_dwconv (DepthwiseConv2D (None, 114, 114, 144 1296 block2a_dwconv_pad[0][0] \n__________________________________________________________________________________________________\nblock2a_bn (BatchNormalization) (None, 114, 114, 144 576 block2a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock2a_activation (Activation) (None, 114, 114, 144 0 block2a_bn[0][0] \n__________________________________________________________________________________________________\nblock2a_se_squeeze (GlobalAvera (None, 144) 0 block2a_activation[0][0] \n__________________________________________________________________________________________________\nblock2a_se_reshape (Reshape) (None, 1, 1, 144) 0 block2a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock2a_se_reduce (Conv2D) (None, 1, 1, 6) 870 block2a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock2a_se_expand (Conv2D) (None, 1, 1, 144) 1008 block2a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock2a_se_excite (Multiply) (None, 114, 114, 144 0 block2a_activation[0][0] \n block2a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock2a_project_conv (Conv2D) (None, 114, 114, 40) 5760 block2a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock2a_project_bn (BatchNormal (None, 114, 114, 40) 160 block2a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock2b_expand_conv (Conv2D) (None, 114, 114, 240 9600 block2a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2b_expand_bn (BatchNormali (None, 114, 114, 240 960 block2b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock2b_expand_activation (Acti (None, 114, 114, 240 0 block2b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock2b_dwconv (DepthwiseConv2D (None, 114, 114, 240 2160 block2b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock2b_bn (BatchNormalization) (None, 114, 114, 240 960 block2b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock2b_activation (Activation) (None, 114, 114, 240 0 block2b_bn[0][0] \n__________________________________________________________________________________________________\nblock2b_se_squeeze (GlobalAvera (None, 240) 0 block2b_activation[0][0] \n__________________________________________________________________________________________________\nblock2b_se_reshape (Reshape) (None, 1, 1, 240) 0 block2b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock2b_se_reduce (Conv2D) (None, 1, 1, 10) 2410 block2b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock2b_se_expand (Conv2D) (None, 1, 1, 240) 2640 block2b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock2b_se_excite (Multiply) (None, 114, 114, 240 0 block2b_activation[0][0] \n block2b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock2b_project_conv (Conv2D) (None, 114, 114, 40) 9600 block2b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock2b_project_bn (BatchNormal (None, 114, 114, 40) 160 block2b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock2b_drop (Dropout) (None, 114, 114, 40) 0 block2b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2b_add (Add) (None, 114, 114, 40) 0 block2b_drop[0][0] \n block2a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2c_expand_conv (Conv2D) (None, 114, 114, 240 9600 block2b_add[0][0] \n__________________________________________________________________________________________________\nblock2c_expand_bn (BatchNormali (None, 114, 114, 240 960 block2c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock2c_expand_activation (Acti (None, 114, 114, 240 0 block2c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock2c_dwconv (DepthwiseConv2D (None, 114, 114, 240 2160 block2c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock2c_bn (BatchNormalization) (None, 114, 114, 240 960 block2c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock2c_activation (Activation) (None, 114, 114, 240 0 block2c_bn[0][0] \n__________________________________________________________________________________________________\nblock2c_se_squeeze (GlobalAvera (None, 240) 0 block2c_activation[0][0] \n__________________________________________________________________________________________________\nblock2c_se_reshape (Reshape) (None, 1, 1, 240) 0 block2c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock2c_se_reduce (Conv2D) (None, 1, 1, 10) 2410 block2c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock2c_se_expand (Conv2D) (None, 1, 1, 240) 2640 block2c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock2c_se_excite (Multiply) (None, 114, 114, 240 0 block2c_activation[0][0] \n block2c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock2c_project_conv (Conv2D) (None, 114, 114, 40) 9600 block2c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock2c_project_bn (BatchNormal (None, 114, 114, 40) 160 block2c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock2c_drop (Dropout) (None, 114, 114, 40) 0 block2c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2c_add (Add) (None, 114, 114, 40) 0 block2c_drop[0][0] \n block2b_add[0][0] \n__________________________________________________________________________________________________\nblock2d_expand_conv (Conv2D) (None, 114, 114, 240 9600 block2c_add[0][0] \n__________________________________________________________________________________________________\nblock2d_expand_bn (BatchNormali (None, 114, 114, 240 960 block2d_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock2d_expand_activation (Acti (None, 114, 114, 240 0 block2d_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock2d_dwconv (DepthwiseConv2D (None, 114, 114, 240 2160 block2d_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock2d_bn (BatchNormalization) (None, 114, 114, 240 960 block2d_dwconv[0][0] \n__________________________________________________________________________________________________\nblock2d_activation (Activation) (None, 114, 114, 240 0 block2d_bn[0][0] \n__________________________________________________________________________________________________\nblock2d_se_squeeze (GlobalAvera (None, 240) 0 block2d_activation[0][0] \n__________________________________________________________________________________________________\nblock2d_se_reshape (Reshape) (None, 1, 1, 240) 0 block2d_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock2d_se_reduce (Conv2D) (None, 1, 1, 10) 2410 block2d_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock2d_se_expand (Conv2D) (None, 1, 1, 240) 2640 block2d_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock2d_se_excite (Multiply) (None, 114, 114, 240 0 block2d_activation[0][0] \n block2d_se_expand[0][0] \n__________________________________________________________________________________________________\nblock2d_project_conv (Conv2D) (None, 114, 114, 40) 9600 block2d_se_excite[0][0] \n__________________________________________________________________________________________________\nblock2d_project_bn (BatchNormal (None, 114, 114, 40) 160 block2d_project_conv[0][0] \n__________________________________________________________________________________________________\nblock2d_drop (Dropout) (None, 114, 114, 40) 0 block2d_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2d_add (Add) (None, 114, 114, 40) 0 block2d_drop[0][0] \n block2c_add[0][0] \n__________________________________________________________________________________________________\nblock2e_expand_conv (Conv2D) (None, 114, 114, 240 9600 block2d_add[0][0] \n__________________________________________________________________________________________________\nblock2e_expand_bn (BatchNormali (None, 114, 114, 240 960 block2e_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock2e_expand_activation (Acti (None, 114, 114, 240 0 block2e_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock2e_dwconv (DepthwiseConv2D (None, 114, 114, 240 2160 block2e_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock2e_bn (BatchNormalization) (None, 114, 114, 240 960 block2e_dwconv[0][0] \n__________________________________________________________________________________________________\nblock2e_activation (Activation) (None, 114, 114, 240 0 block2e_bn[0][0] \n__________________________________________________________________________________________________\nblock2e_se_squeeze (GlobalAvera (None, 240) 0 block2e_activation[0][0] \n__________________________________________________________________________________________________\nblock2e_se_reshape (Reshape) (None, 1, 1, 240) 0 block2e_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock2e_se_reduce (Conv2D) (None, 1, 1, 10) 2410 block2e_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock2e_se_expand (Conv2D) (None, 1, 1, 240) 2640 block2e_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock2e_se_excite (Multiply) (None, 114, 114, 240 0 block2e_activation[0][0] \n block2e_se_expand[0][0] \n__________________________________________________________________________________________________\nblock2e_project_conv (Conv2D) (None, 114, 114, 40) 9600 block2e_se_excite[0][0] \n__________________________________________________________________________________________________\nblock2e_project_bn (BatchNormal (None, 114, 114, 40) 160 block2e_project_conv[0][0] \n__________________________________________________________________________________________________\nblock2e_drop (Dropout) (None, 114, 114, 40) 0 block2e_project_bn[0][0] \n__________________________________________________________________________________________________\nblock2e_add (Add) (None, 114, 114, 40) 0 block2e_drop[0][0] \n block2d_add[0][0] \n__________________________________________________________________________________________________\nblock3a_expand_conv (Conv2D) (None, 114, 114, 240 9600 block2e_add[0][0] \n__________________________________________________________________________________________________\nblock3a_expand_bn (BatchNormali (None, 114, 114, 240 960 block3a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock3a_expand_activation (Acti (None, 114, 114, 240 0 block3a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock3a_dwconv_pad (ZeroPadding (None, 117, 117, 240 0 block3a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock3a_dwconv (DepthwiseConv2D (None, 57, 57, 240) 6000 block3a_dwconv_pad[0][0] \n__________________________________________________________________________________________________\nblock3a_bn (BatchNormalization) (None, 57, 57, 240) 960 block3a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock3a_activation (Activation) (None, 57, 57, 240) 0 block3a_bn[0][0] \n__________________________________________________________________________________________________\nblock3a_se_squeeze (GlobalAvera (None, 240) 0 block3a_activation[0][0] \n__________________________________________________________________________________________________\nblock3a_se_reshape (Reshape) (None, 1, 1, 240) 0 block3a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock3a_se_reduce (Conv2D) (None, 1, 1, 10) 2410 block3a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock3a_se_expand (Conv2D) (None, 1, 1, 240) 2640 block3a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock3a_se_excite (Multiply) (None, 57, 57, 240) 0 block3a_activation[0][0] \n block3a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock3a_project_conv (Conv2D) (None, 57, 57, 64) 15360 block3a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock3a_project_bn (BatchNormal (None, 57, 57, 64) 256 block3a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock3b_expand_conv (Conv2D) (None, 57, 57, 384) 24576 block3a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3b_expand_bn (BatchNormali (None, 57, 57, 384) 1536 block3b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock3b_expand_activation (Acti (None, 57, 57, 384) 0 block3b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock3b_dwconv (DepthwiseConv2D (None, 57, 57, 384) 9600 block3b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock3b_bn (BatchNormalization) (None, 57, 57, 384) 1536 block3b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock3b_activation (Activation) (None, 57, 57, 384) 0 block3b_bn[0][0] \n__________________________________________________________________________________________________\nblock3b_se_squeeze (GlobalAvera (None, 384) 0 block3b_activation[0][0] \n__________________________________________________________________________________________________\nblock3b_se_reshape (Reshape) (None, 1, 1, 384) 0 block3b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock3b_se_reduce (Conv2D) (None, 1, 1, 16) 6160 block3b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock3b_se_expand (Conv2D) (None, 1, 1, 384) 6528 block3b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock3b_se_excite (Multiply) (None, 57, 57, 384) 0 block3b_activation[0][0] \n block3b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock3b_project_conv (Conv2D) (None, 57, 57, 64) 24576 block3b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock3b_project_bn (BatchNormal (None, 57, 57, 64) 256 block3b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock3b_drop (Dropout) (None, 57, 57, 64) 0 block3b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3b_add (Add) (None, 57, 57, 64) 0 block3b_drop[0][0] \n block3a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3c_expand_conv (Conv2D) (None, 57, 57, 384) 24576 block3b_add[0][0] \n__________________________________________________________________________________________________\nblock3c_expand_bn (BatchNormali (None, 57, 57, 384) 1536 block3c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock3c_expand_activation (Acti (None, 57, 57, 384) 0 block3c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock3c_dwconv (DepthwiseConv2D (None, 57, 57, 384) 9600 block3c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock3c_bn (BatchNormalization) (None, 57, 57, 384) 1536 block3c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock3c_activation (Activation) (None, 57, 57, 384) 0 block3c_bn[0][0] \n__________________________________________________________________________________________________\nblock3c_se_squeeze (GlobalAvera (None, 384) 0 block3c_activation[0][0] \n__________________________________________________________________________________________________\nblock3c_se_reshape (Reshape) (None, 1, 1, 384) 0 block3c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock3c_se_reduce (Conv2D) (None, 1, 1, 16) 6160 block3c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock3c_se_expand (Conv2D) (None, 1, 1, 384) 6528 block3c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock3c_se_excite (Multiply) (None, 57, 57, 384) 0 block3c_activation[0][0] \n block3c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock3c_project_conv (Conv2D) (None, 57, 57, 64) 24576 block3c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock3c_project_bn (BatchNormal (None, 57, 57, 64) 256 block3c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock3c_drop (Dropout) (None, 57, 57, 64) 0 block3c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3c_add (Add) (None, 57, 57, 64) 0 block3c_drop[0][0] \n block3b_add[0][0] \n__________________________________________________________________________________________________\nblock3d_expand_conv (Conv2D) (None, 57, 57, 384) 24576 block3c_add[0][0] \n__________________________________________________________________________________________________\nblock3d_expand_bn (BatchNormali (None, 57, 57, 384) 1536 block3d_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock3d_expand_activation (Acti (None, 57, 57, 384) 0 block3d_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock3d_dwconv (DepthwiseConv2D (None, 57, 57, 384) 9600 block3d_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock3d_bn (BatchNormalization) (None, 57, 57, 384) 1536 block3d_dwconv[0][0] \n__________________________________________________________________________________________________\nblock3d_activation (Activation) (None, 57, 57, 384) 0 block3d_bn[0][0] \n__________________________________________________________________________________________________\nblock3d_se_squeeze (GlobalAvera (None, 384) 0 block3d_activation[0][0] \n__________________________________________________________________________________________________\nblock3d_se_reshape (Reshape) (None, 1, 1, 384) 0 block3d_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock3d_se_reduce (Conv2D) (None, 1, 1, 16) 6160 block3d_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock3d_se_expand (Conv2D) (None, 1, 1, 384) 6528 block3d_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock3d_se_excite (Multiply) (None, 57, 57, 384) 0 block3d_activation[0][0] \n block3d_se_expand[0][0] \n__________________________________________________________________________________________________\nblock3d_project_conv (Conv2D) (None, 57, 57, 64) 24576 block3d_se_excite[0][0] \n__________________________________________________________________________________________________\nblock3d_project_bn (BatchNormal (None, 57, 57, 64) 256 block3d_project_conv[0][0] \n__________________________________________________________________________________________________\nblock3d_drop (Dropout) (None, 57, 57, 64) 0 block3d_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3d_add (Add) (None, 57, 57, 64) 0 block3d_drop[0][0] \n block3c_add[0][0] \n__________________________________________________________________________________________________\nblock3e_expand_conv (Conv2D) (None, 57, 57, 384) 24576 block3d_add[0][0] \n__________________________________________________________________________________________________\nblock3e_expand_bn (BatchNormali (None, 57, 57, 384) 1536 block3e_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock3e_expand_activation (Acti (None, 57, 57, 384) 0 block3e_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock3e_dwconv (DepthwiseConv2D (None, 57, 57, 384) 9600 block3e_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock3e_bn (BatchNormalization) (None, 57, 57, 384) 1536 block3e_dwconv[0][0] \n__________________________________________________________________________________________________\nblock3e_activation (Activation) (None, 57, 57, 384) 0 block3e_bn[0][0] \n__________________________________________________________________________________________________\nblock3e_se_squeeze (GlobalAvera (None, 384) 0 block3e_activation[0][0] \n__________________________________________________________________________________________________\nblock3e_se_reshape (Reshape) (None, 1, 1, 384) 0 block3e_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock3e_se_reduce (Conv2D) (None, 1, 1, 16) 6160 block3e_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock3e_se_expand (Conv2D) (None, 1, 1, 384) 6528 block3e_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock3e_se_excite (Multiply) (None, 57, 57, 384) 0 block3e_activation[0][0] \n block3e_se_expand[0][0] \n__________________________________________________________________________________________________\nblock3e_project_conv (Conv2D) (None, 57, 57, 64) 24576 block3e_se_excite[0][0] \n__________________________________________________________________________________________________\nblock3e_project_bn (BatchNormal (None, 57, 57, 64) 256 block3e_project_conv[0][0] \n__________________________________________________________________________________________________\nblock3e_drop (Dropout) (None, 57, 57, 64) 0 block3e_project_bn[0][0] \n__________________________________________________________________________________________________\nblock3e_add (Add) (None, 57, 57, 64) 0 block3e_drop[0][0] \n block3d_add[0][0] \n__________________________________________________________________________________________________\nblock4a_expand_conv (Conv2D) (None, 57, 57, 384) 24576 block3e_add[0][0] \n__________________________________________________________________________________________________\nblock4a_expand_bn (BatchNormali (None, 57, 57, 384) 1536 block4a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4a_expand_activation (Acti (None, 57, 57, 384) 0 block4a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4a_dwconv_pad (ZeroPadding (None, 59, 59, 384) 0 block4a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4a_dwconv (DepthwiseConv2D (None, 29, 29, 384) 3456 block4a_dwconv_pad[0][0] \n__________________________________________________________________________________________________\nblock4a_bn (BatchNormalization) (None, 29, 29, 384) 1536 block4a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4a_activation (Activation) (None, 29, 29, 384) 0 block4a_bn[0][0] \n__________________________________________________________________________________________________\nblock4a_se_squeeze (GlobalAvera (None, 384) 0 block4a_activation[0][0] \n__________________________________________________________________________________________________\nblock4a_se_reshape (Reshape) (None, 1, 1, 384) 0 block4a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4a_se_reduce (Conv2D) (None, 1, 1, 16) 6160 block4a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4a_se_expand (Conv2D) (None, 1, 1, 384) 6528 block4a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4a_se_excite (Multiply) (None, 29, 29, 384) 0 block4a_activation[0][0] \n block4a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4a_project_conv (Conv2D) (None, 29, 29, 128) 49152 block4a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4a_project_bn (BatchNormal (None, 29, 29, 128) 512 block4a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4b_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4b_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4b_expand_activation (Acti (None, 29, 29, 768) 0 block4b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4b_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4b_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4b_activation (Activation) (None, 29, 29, 768) 0 block4b_bn[0][0] \n__________________________________________________________________________________________________\nblock4b_se_squeeze (GlobalAvera (None, 768) 0 block4b_activation[0][0] \n__________________________________________________________________________________________________\nblock4b_se_reshape (Reshape) (None, 1, 1, 768) 0 block4b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4b_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4b_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4b_se_excite (Multiply) (None, 29, 29, 768) 0 block4b_activation[0][0] \n block4b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4b_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4b_project_bn (BatchNormal (None, 29, 29, 128) 512 block4b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4b_drop (Dropout) (None, 29, 29, 128) 0 block4b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4b_add (Add) (None, 29, 29, 128) 0 block4b_drop[0][0] \n block4a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4c_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4b_add[0][0] \n__________________________________________________________________________________________________\nblock4c_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4c_expand_activation (Acti (None, 29, 29, 768) 0 block4c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4c_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4c_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4c_activation (Activation) (None, 29, 29, 768) 0 block4c_bn[0][0] \n__________________________________________________________________________________________________\nblock4c_se_squeeze (GlobalAvera (None, 768) 0 block4c_activation[0][0] \n__________________________________________________________________________________________________\nblock4c_se_reshape (Reshape) (None, 1, 1, 768) 0 block4c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4c_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4c_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4c_se_excite (Multiply) (None, 29, 29, 768) 0 block4c_activation[0][0] \n block4c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4c_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4c_project_bn (BatchNormal (None, 29, 29, 128) 512 block4c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4c_drop (Dropout) (None, 29, 29, 128) 0 block4c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4c_add (Add) (None, 29, 29, 128) 0 block4c_drop[0][0] \n block4b_add[0][0] \n__________________________________________________________________________________________________\nblock4d_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4c_add[0][0] \n__________________________________________________________________________________________________\nblock4d_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4d_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4d_expand_activation (Acti (None, 29, 29, 768) 0 block4d_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4d_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4d_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4d_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4d_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4d_activation (Activation) (None, 29, 29, 768) 0 block4d_bn[0][0] \n__________________________________________________________________________________________________\nblock4d_se_squeeze (GlobalAvera (None, 768) 0 block4d_activation[0][0] \n__________________________________________________________________________________________________\nblock4d_se_reshape (Reshape) (None, 1, 1, 768) 0 block4d_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4d_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4d_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4d_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4d_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4d_se_excite (Multiply) (None, 29, 29, 768) 0 block4d_activation[0][0] \n block4d_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4d_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4d_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4d_project_bn (BatchNormal (None, 29, 29, 128) 512 block4d_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4d_drop (Dropout) (None, 29, 29, 128) 0 block4d_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4d_add (Add) (None, 29, 29, 128) 0 block4d_drop[0][0] \n block4c_add[0][0] \n__________________________________________________________________________________________________\nblock4e_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4d_add[0][0] \n__________________________________________________________________________________________________\nblock4e_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4e_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4e_expand_activation (Acti (None, 29, 29, 768) 0 block4e_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4e_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4e_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4e_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4e_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4e_activation (Activation) (None, 29, 29, 768) 0 block4e_bn[0][0] \n__________________________________________________________________________________________________\nblock4e_se_squeeze (GlobalAvera (None, 768) 0 block4e_activation[0][0] \n__________________________________________________________________________________________________\nblock4e_se_reshape (Reshape) (None, 1, 1, 768) 0 block4e_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4e_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4e_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4e_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4e_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4e_se_excite (Multiply) (None, 29, 29, 768) 0 block4e_activation[0][0] \n block4e_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4e_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4e_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4e_project_bn (BatchNormal (None, 29, 29, 128) 512 block4e_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4e_drop (Dropout) (None, 29, 29, 128) 0 block4e_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4e_add (Add) (None, 29, 29, 128) 0 block4e_drop[0][0] \n block4d_add[0][0] \n__________________________________________________________________________________________________\nblock4f_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4e_add[0][0] \n__________________________________________________________________________________________________\nblock4f_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4f_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4f_expand_activation (Acti (None, 29, 29, 768) 0 block4f_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4f_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4f_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4f_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4f_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4f_activation (Activation) (None, 29, 29, 768) 0 block4f_bn[0][0] \n__________________________________________________________________________________________________\nblock4f_se_squeeze (GlobalAvera (None, 768) 0 block4f_activation[0][0] \n__________________________________________________________________________________________________\nblock4f_se_reshape (Reshape) (None, 1, 1, 768) 0 block4f_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4f_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4f_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4f_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4f_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4f_se_excite (Multiply) (None, 29, 29, 768) 0 block4f_activation[0][0] \n block4f_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4f_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4f_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4f_project_bn (BatchNormal (None, 29, 29, 128) 512 block4f_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4f_drop (Dropout) (None, 29, 29, 128) 0 block4f_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4f_add (Add) (None, 29, 29, 128) 0 block4f_drop[0][0] \n block4e_add[0][0] \n__________________________________________________________________________________________________\nblock4g_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4f_add[0][0] \n__________________________________________________________________________________________________\nblock4g_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block4g_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock4g_expand_activation (Acti (None, 29, 29, 768) 0 block4g_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock4g_dwconv (DepthwiseConv2D (None, 29, 29, 768) 6912 block4g_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock4g_bn (BatchNormalization) (None, 29, 29, 768) 3072 block4g_dwconv[0][0] \n__________________________________________________________________________________________________\nblock4g_activation (Activation) (None, 29, 29, 768) 0 block4g_bn[0][0] \n__________________________________________________________________________________________________\nblock4g_se_squeeze (GlobalAvera (None, 768) 0 block4g_activation[0][0] \n__________________________________________________________________________________________________\nblock4g_se_reshape (Reshape) (None, 1, 1, 768) 0 block4g_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock4g_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block4g_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock4g_se_expand (Conv2D) (None, 1, 1, 768) 25344 block4g_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock4g_se_excite (Multiply) (None, 29, 29, 768) 0 block4g_activation[0][0] \n block4g_se_expand[0][0] \n__________________________________________________________________________________________________\nblock4g_project_conv (Conv2D) (None, 29, 29, 128) 98304 block4g_se_excite[0][0] \n__________________________________________________________________________________________________\nblock4g_project_bn (BatchNormal (None, 29, 29, 128) 512 block4g_project_conv[0][0] \n__________________________________________________________________________________________________\nblock4g_drop (Dropout) (None, 29, 29, 128) 0 block4g_project_bn[0][0] \n__________________________________________________________________________________________________\nblock4g_add (Add) (None, 29, 29, 128) 0 block4g_drop[0][0] \n block4f_add[0][0] \n__________________________________________________________________________________________________\nblock5a_expand_conv (Conv2D) (None, 29, 29, 768) 98304 block4g_add[0][0] \n__________________________________________________________________________________________________\nblock5a_expand_bn (BatchNormali (None, 29, 29, 768) 3072 block5a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5a_expand_activation (Acti (None, 29, 29, 768) 0 block5a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5a_dwconv (DepthwiseConv2D (None, 29, 29, 768) 19200 block5a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5a_bn (BatchNormalization) (None, 29, 29, 768) 3072 block5a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5a_activation (Activation) (None, 29, 29, 768) 0 block5a_bn[0][0] \n__________________________________________________________________________________________________\nblock5a_se_squeeze (GlobalAvera (None, 768) 0 block5a_activation[0][0] \n__________________________________________________________________________________________________\nblock5a_se_reshape (Reshape) (None, 1, 1, 768) 0 block5a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5a_se_reduce (Conv2D) (None, 1, 1, 32) 24608 block5a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5a_se_expand (Conv2D) (None, 1, 1, 768) 25344 block5a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5a_se_excite (Multiply) (None, 29, 29, 768) 0 block5a_activation[0][0] \n block5a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5a_project_conv (Conv2D) (None, 29, 29, 176) 135168 block5a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5a_project_bn (BatchNormal (None, 29, 29, 176) 704 block5a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5b_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5b_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5b_expand_activation (Acti (None, 29, 29, 1056) 0 block5b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5b_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5b_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5b_activation (Activation) (None, 29, 29, 1056) 0 block5b_bn[0][0] \n__________________________________________________________________________________________________\nblock5b_se_squeeze (GlobalAvera (None, 1056) 0 block5b_activation[0][0] \n__________________________________________________________________________________________________\nblock5b_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5b_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5b_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5b_se_excite (Multiply) (None, 29, 29, 1056) 0 block5b_activation[0][0] \n block5b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5b_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5b_project_bn (BatchNormal (None, 29, 29, 176) 704 block5b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5b_drop (Dropout) (None, 29, 29, 176) 0 block5b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5b_add (Add) (None, 29, 29, 176) 0 block5b_drop[0][0] \n block5a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5c_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5b_add[0][0] \n__________________________________________________________________________________________________\nblock5c_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5c_expand_activation (Acti (None, 29, 29, 1056) 0 block5c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5c_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5c_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5c_activation (Activation) (None, 29, 29, 1056) 0 block5c_bn[0][0] \n__________________________________________________________________________________________________\nblock5c_se_squeeze (GlobalAvera (None, 1056) 0 block5c_activation[0][0] \n__________________________________________________________________________________________________\nblock5c_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5c_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5c_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5c_se_excite (Multiply) (None, 29, 29, 1056) 0 block5c_activation[0][0] \n block5c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5c_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5c_project_bn (BatchNormal (None, 29, 29, 176) 704 block5c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5c_drop (Dropout) (None, 29, 29, 176) 0 block5c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5c_add (Add) (None, 29, 29, 176) 0 block5c_drop[0][0] \n block5b_add[0][0] \n__________________________________________________________________________________________________\nblock5d_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5c_add[0][0] \n__________________________________________________________________________________________________\nblock5d_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5d_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5d_expand_activation (Acti (None, 29, 29, 1056) 0 block5d_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5d_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5d_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5d_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5d_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5d_activation (Activation) (None, 29, 29, 1056) 0 block5d_bn[0][0] \n__________________________________________________________________________________________________\nblock5d_se_squeeze (GlobalAvera (None, 1056) 0 block5d_activation[0][0] \n__________________________________________________________________________________________________\nblock5d_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5d_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5d_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5d_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5d_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5d_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5d_se_excite (Multiply) (None, 29, 29, 1056) 0 block5d_activation[0][0] \n block5d_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5d_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5d_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5d_project_bn (BatchNormal (None, 29, 29, 176) 704 block5d_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5d_drop (Dropout) (None, 29, 29, 176) 0 block5d_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5d_add (Add) (None, 29, 29, 176) 0 block5d_drop[0][0] \n block5c_add[0][0] \n__________________________________________________________________________________________________\nblock5e_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5d_add[0][0] \n__________________________________________________________________________________________________\nblock5e_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5e_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5e_expand_activation (Acti (None, 29, 29, 1056) 0 block5e_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5e_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5e_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5e_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5e_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5e_activation (Activation) (None, 29, 29, 1056) 0 block5e_bn[0][0] \n__________________________________________________________________________________________________\nblock5e_se_squeeze (GlobalAvera (None, 1056) 0 block5e_activation[0][0] \n__________________________________________________________________________________________________\nblock5e_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5e_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5e_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5e_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5e_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5e_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5e_se_excite (Multiply) (None, 29, 29, 1056) 0 block5e_activation[0][0] \n block5e_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5e_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5e_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5e_project_bn (BatchNormal (None, 29, 29, 176) 704 block5e_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5e_drop (Dropout) (None, 29, 29, 176) 0 block5e_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5e_add (Add) (None, 29, 29, 176) 0 block5e_drop[0][0] \n block5d_add[0][0] \n__________________________________________________________________________________________________\nblock5f_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5e_add[0][0] \n__________________________________________________________________________________________________\nblock5f_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5f_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5f_expand_activation (Acti (None, 29, 29, 1056) 0 block5f_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5f_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5f_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5f_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5f_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5f_activation (Activation) (None, 29, 29, 1056) 0 block5f_bn[0][0] \n__________________________________________________________________________________________________\nblock5f_se_squeeze (GlobalAvera (None, 1056) 0 block5f_activation[0][0] \n__________________________________________________________________________________________________\nblock5f_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5f_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5f_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5f_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5f_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5f_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5f_se_excite (Multiply) (None, 29, 29, 1056) 0 block5f_activation[0][0] \n block5f_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5f_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5f_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5f_project_bn (BatchNormal (None, 29, 29, 176) 704 block5f_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5f_drop (Dropout) (None, 29, 29, 176) 0 block5f_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5f_add (Add) (None, 29, 29, 176) 0 block5f_drop[0][0] \n block5e_add[0][0] \n__________________________________________________________________________________________________\nblock5g_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5f_add[0][0] \n__________________________________________________________________________________________________\nblock5g_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block5g_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock5g_expand_activation (Acti (None, 29, 29, 1056) 0 block5g_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock5g_dwconv (DepthwiseConv2D (None, 29, 29, 1056) 26400 block5g_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock5g_bn (BatchNormalization) (None, 29, 29, 1056) 4224 block5g_dwconv[0][0] \n__________________________________________________________________________________________________\nblock5g_activation (Activation) (None, 29, 29, 1056) 0 block5g_bn[0][0] \n__________________________________________________________________________________________________\nblock5g_se_squeeze (GlobalAvera (None, 1056) 0 block5g_activation[0][0] \n__________________________________________________________________________________________________\nblock5g_se_reshape (Reshape) (None, 1, 1, 1056) 0 block5g_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock5g_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block5g_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock5g_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block5g_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock5g_se_excite (Multiply) (None, 29, 29, 1056) 0 block5g_activation[0][0] \n block5g_se_expand[0][0] \n__________________________________________________________________________________________________\nblock5g_project_conv (Conv2D) (None, 29, 29, 176) 185856 block5g_se_excite[0][0] \n__________________________________________________________________________________________________\nblock5g_project_bn (BatchNormal (None, 29, 29, 176) 704 block5g_project_conv[0][0] \n__________________________________________________________________________________________________\nblock5g_drop (Dropout) (None, 29, 29, 176) 0 block5g_project_bn[0][0] \n__________________________________________________________________________________________________\nblock5g_add (Add) (None, 29, 29, 176) 0 block5g_drop[0][0] \n block5f_add[0][0] \n__________________________________________________________________________________________________\nblock6a_expand_conv (Conv2D) (None, 29, 29, 1056) 185856 block5g_add[0][0] \n__________________________________________________________________________________________________\nblock6a_expand_bn (BatchNormali (None, 29, 29, 1056) 4224 block6a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6a_expand_activation (Acti (None, 29, 29, 1056) 0 block6a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6a_dwconv_pad (ZeroPadding (None, 33, 33, 1056) 0 block6a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6a_dwconv (DepthwiseConv2D (None, 15, 15, 1056) 26400 block6a_dwconv_pad[0][0] \n__________________________________________________________________________________________________\nblock6a_bn (BatchNormalization) (None, 15, 15, 1056) 4224 block6a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6a_activation (Activation) (None, 15, 15, 1056) 0 block6a_bn[0][0] \n__________________________________________________________________________________________________\nblock6a_se_squeeze (GlobalAvera (None, 1056) 0 block6a_activation[0][0] \n__________________________________________________________________________________________________\nblock6a_se_reshape (Reshape) (None, 1, 1, 1056) 0 block6a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6a_se_reduce (Conv2D) (None, 1, 1, 44) 46508 block6a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6a_se_expand (Conv2D) (None, 1, 1, 1056) 47520 block6a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6a_se_excite (Multiply) (None, 15, 15, 1056) 0 block6a_activation[0][0] \n block6a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6a_project_conv (Conv2D) (None, 15, 15, 304) 321024 block6a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6a_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6b_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6b_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6b_expand_activation (Acti (None, 15, 15, 1824) 0 block6b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6b_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6b_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6b_activation (Activation) (None, 15, 15, 1824) 0 block6b_bn[0][0] \n__________________________________________________________________________________________________\nblock6b_se_squeeze (GlobalAvera (None, 1824) 0 block6b_activation[0][0] \n__________________________________________________________________________________________________\nblock6b_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6b_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6b_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6b_se_excite (Multiply) (None, 15, 15, 1824) 0 block6b_activation[0][0] \n block6b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6b_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6b_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6b_drop (Dropout) (None, 15, 15, 304) 0 block6b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6b_add (Add) (None, 15, 15, 304) 0 block6b_drop[0][0] \n block6a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6c_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6b_add[0][0] \n__________________________________________________________________________________________________\nblock6c_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6c_expand_activation (Acti (None, 15, 15, 1824) 0 block6c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6c_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6c_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6c_activation (Activation) (None, 15, 15, 1824) 0 block6c_bn[0][0] \n__________________________________________________________________________________________________\nblock6c_se_squeeze (GlobalAvera (None, 1824) 0 block6c_activation[0][0] \n__________________________________________________________________________________________________\nblock6c_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6c_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6c_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6c_se_excite (Multiply) (None, 15, 15, 1824) 0 block6c_activation[0][0] \n block6c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6c_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6c_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6c_drop (Dropout) (None, 15, 15, 304) 0 block6c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6c_add (Add) (None, 15, 15, 304) 0 block6c_drop[0][0] \n block6b_add[0][0] \n__________________________________________________________________________________________________\nblock6d_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6c_add[0][0] \n__________________________________________________________________________________________________\nblock6d_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6d_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6d_expand_activation (Acti (None, 15, 15, 1824) 0 block6d_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6d_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6d_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6d_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6d_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6d_activation (Activation) (None, 15, 15, 1824) 0 block6d_bn[0][0] \n__________________________________________________________________________________________________\nblock6d_se_squeeze (GlobalAvera (None, 1824) 0 block6d_activation[0][0] \n__________________________________________________________________________________________________\nblock6d_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6d_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6d_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6d_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6d_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6d_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6d_se_excite (Multiply) (None, 15, 15, 1824) 0 block6d_activation[0][0] \n block6d_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6d_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6d_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6d_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6d_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6d_drop (Dropout) (None, 15, 15, 304) 0 block6d_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6d_add (Add) (None, 15, 15, 304) 0 block6d_drop[0][0] \n block6c_add[0][0] \n__________________________________________________________________________________________________\nblock6e_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6d_add[0][0] \n__________________________________________________________________________________________________\nblock6e_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6e_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6e_expand_activation (Acti (None, 15, 15, 1824) 0 block6e_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6e_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6e_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6e_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6e_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6e_activation (Activation) (None, 15, 15, 1824) 0 block6e_bn[0][0] \n__________________________________________________________________________________________________\nblock6e_se_squeeze (GlobalAvera (None, 1824) 0 block6e_activation[0][0] \n__________________________________________________________________________________________________\nblock6e_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6e_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6e_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6e_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6e_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6e_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6e_se_excite (Multiply) (None, 15, 15, 1824) 0 block6e_activation[0][0] \n block6e_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6e_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6e_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6e_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6e_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6e_drop (Dropout) (None, 15, 15, 304) 0 block6e_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6e_add (Add) (None, 15, 15, 304) 0 block6e_drop[0][0] \n block6d_add[0][0] \n__________________________________________________________________________________________________\nblock6f_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6e_add[0][0] \n__________________________________________________________________________________________________\nblock6f_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6f_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6f_expand_activation (Acti (None, 15, 15, 1824) 0 block6f_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6f_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6f_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6f_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6f_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6f_activation (Activation) (None, 15, 15, 1824) 0 block6f_bn[0][0] \n__________________________________________________________________________________________________\nblock6f_se_squeeze (GlobalAvera (None, 1824) 0 block6f_activation[0][0] \n__________________________________________________________________________________________________\nblock6f_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6f_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6f_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6f_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6f_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6f_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6f_se_excite (Multiply) (None, 15, 15, 1824) 0 block6f_activation[0][0] \n block6f_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6f_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6f_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6f_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6f_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6f_drop (Dropout) (None, 15, 15, 304) 0 block6f_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6f_add (Add) (None, 15, 15, 304) 0 block6f_drop[0][0] \n block6e_add[0][0] \n__________________________________________________________________________________________________\nblock6g_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6f_add[0][0] \n__________________________________________________________________________________________________\nblock6g_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6g_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6g_expand_activation (Acti (None, 15, 15, 1824) 0 block6g_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6g_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6g_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6g_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6g_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6g_activation (Activation) (None, 15, 15, 1824) 0 block6g_bn[0][0] \n__________________________________________________________________________________________________\nblock6g_se_squeeze (GlobalAvera (None, 1824) 0 block6g_activation[0][0] \n__________________________________________________________________________________________________\nblock6g_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6g_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6g_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6g_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6g_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6g_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6g_se_excite (Multiply) (None, 15, 15, 1824) 0 block6g_activation[0][0] \n block6g_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6g_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6g_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6g_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6g_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6g_drop (Dropout) (None, 15, 15, 304) 0 block6g_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6g_add (Add) (None, 15, 15, 304) 0 block6g_drop[0][0] \n block6f_add[0][0] \n__________________________________________________________________________________________________\nblock6h_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6g_add[0][0] \n__________________________________________________________________________________________________\nblock6h_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6h_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6h_expand_activation (Acti (None, 15, 15, 1824) 0 block6h_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6h_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6h_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6h_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6h_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6h_activation (Activation) (None, 15, 15, 1824) 0 block6h_bn[0][0] \n__________________________________________________________________________________________________\nblock6h_se_squeeze (GlobalAvera (None, 1824) 0 block6h_activation[0][0] \n__________________________________________________________________________________________________\nblock6h_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6h_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6h_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6h_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6h_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6h_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6h_se_excite (Multiply) (None, 15, 15, 1824) 0 block6h_activation[0][0] \n block6h_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6h_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6h_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6h_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6h_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6h_drop (Dropout) (None, 15, 15, 304) 0 block6h_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6h_add (Add) (None, 15, 15, 304) 0 block6h_drop[0][0] \n block6g_add[0][0] \n__________________________________________________________________________________________________\nblock6i_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6h_add[0][0] \n__________________________________________________________________________________________________\nblock6i_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block6i_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock6i_expand_activation (Acti (None, 15, 15, 1824) 0 block6i_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock6i_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 45600 block6i_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock6i_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block6i_dwconv[0][0] \n__________________________________________________________________________________________________\nblock6i_activation (Activation) (None, 15, 15, 1824) 0 block6i_bn[0][0] \n__________________________________________________________________________________________________\nblock6i_se_squeeze (GlobalAvera (None, 1824) 0 block6i_activation[0][0] \n__________________________________________________________________________________________________\nblock6i_se_reshape (Reshape) (None, 1, 1, 1824) 0 block6i_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock6i_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block6i_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock6i_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block6i_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock6i_se_excite (Multiply) (None, 15, 15, 1824) 0 block6i_activation[0][0] \n block6i_se_expand[0][0] \n__________________________________________________________________________________________________\nblock6i_project_conv (Conv2D) (None, 15, 15, 304) 554496 block6i_se_excite[0][0] \n__________________________________________________________________________________________________\nblock6i_project_bn (BatchNormal (None, 15, 15, 304) 1216 block6i_project_conv[0][0] \n__________________________________________________________________________________________________\nblock6i_drop (Dropout) (None, 15, 15, 304) 0 block6i_project_bn[0][0] \n__________________________________________________________________________________________________\nblock6i_add (Add) (None, 15, 15, 304) 0 block6i_drop[0][0] \n block6h_add[0][0] \n__________________________________________________________________________________________________\nblock7a_expand_conv (Conv2D) (None, 15, 15, 1824) 554496 block6i_add[0][0] \n__________________________________________________________________________________________________\nblock7a_expand_bn (BatchNormali (None, 15, 15, 1824) 7296 block7a_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock7a_expand_activation (Acti (None, 15, 15, 1824) 0 block7a_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock7a_dwconv (DepthwiseConv2D (None, 15, 15, 1824) 16416 block7a_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock7a_bn (BatchNormalization) (None, 15, 15, 1824) 7296 block7a_dwconv[0][0] \n__________________________________________________________________________________________________\nblock7a_activation (Activation) (None, 15, 15, 1824) 0 block7a_bn[0][0] \n__________________________________________________________________________________________________\nblock7a_se_squeeze (GlobalAvera (None, 1824) 0 block7a_activation[0][0] \n__________________________________________________________________________________________________\nblock7a_se_reshape (Reshape) (None, 1, 1, 1824) 0 block7a_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock7a_se_reduce (Conv2D) (None, 1, 1, 76) 138700 block7a_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock7a_se_expand (Conv2D) (None, 1, 1, 1824) 140448 block7a_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock7a_se_excite (Multiply) (None, 15, 15, 1824) 0 block7a_activation[0][0] \n block7a_se_expand[0][0] \n__________________________________________________________________________________________________\nblock7a_project_conv (Conv2D) (None, 15, 15, 512) 933888 block7a_se_excite[0][0] \n__________________________________________________________________________________________________\nblock7a_project_bn (BatchNormal (None, 15, 15, 512) 2048 block7a_project_conv[0][0] \n__________________________________________________________________________________________________\nblock7b_expand_conv (Conv2D) (None, 15, 15, 3072) 1572864 block7a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock7b_expand_bn (BatchNormali (None, 15, 15, 3072) 12288 block7b_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock7b_expand_activation (Acti (None, 15, 15, 3072) 0 block7b_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock7b_dwconv (DepthwiseConv2D (None, 15, 15, 3072) 27648 block7b_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock7b_bn (BatchNormalization) (None, 15, 15, 3072) 12288 block7b_dwconv[0][0] \n__________________________________________________________________________________________________\nblock7b_activation (Activation) (None, 15, 15, 3072) 0 block7b_bn[0][0] \n__________________________________________________________________________________________________\nblock7b_se_squeeze (GlobalAvera (None, 3072) 0 block7b_activation[0][0] \n__________________________________________________________________________________________________\nblock7b_se_reshape (Reshape) (None, 1, 1, 3072) 0 block7b_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock7b_se_reduce (Conv2D) (None, 1, 1, 128) 393344 block7b_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock7b_se_expand (Conv2D) (None, 1, 1, 3072) 396288 block7b_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock7b_se_excite (Multiply) (None, 15, 15, 3072) 0 block7b_activation[0][0] \n block7b_se_expand[0][0] \n__________________________________________________________________________________________________\nblock7b_project_conv (Conv2D) (None, 15, 15, 512) 1572864 block7b_se_excite[0][0] \n__________________________________________________________________________________________________\nblock7b_project_bn (BatchNormal (None, 15, 15, 512) 2048 block7b_project_conv[0][0] \n__________________________________________________________________________________________________\nblock7b_drop (Dropout) (None, 15, 15, 512) 0 block7b_project_bn[0][0] \n__________________________________________________________________________________________________\nblock7b_add (Add) (None, 15, 15, 512) 0 block7b_drop[0][0] \n block7a_project_bn[0][0] \n__________________________________________________________________________________________________\nblock7c_expand_conv (Conv2D) (None, 15, 15, 3072) 1572864 block7b_add[0][0] \n__________________________________________________________________________________________________\nblock7c_expand_bn (BatchNormali (None, 15, 15, 3072) 12288 block7c_expand_conv[0][0] \n__________________________________________________________________________________________________\nblock7c_expand_activation (Acti (None, 15, 15, 3072) 0 block7c_expand_bn[0][0] \n__________________________________________________________________________________________________\nblock7c_dwconv (DepthwiseConv2D (None, 15, 15, 3072) 27648 block7c_expand_activation[0][0] \n__________________________________________________________________________________________________\nblock7c_bn (BatchNormalization) (None, 15, 15, 3072) 12288 block7c_dwconv[0][0] \n__________________________________________________________________________________________________\nblock7c_activation (Activation) (None, 15, 15, 3072) 0 block7c_bn[0][0] \n__________________________________________________________________________________________________\nblock7c_se_squeeze (GlobalAvera (None, 3072) 0 block7c_activation[0][0] \n__________________________________________________________________________________________________\nblock7c_se_reshape (Reshape) (None, 1, 1, 3072) 0 block7c_se_squeeze[0][0] \n__________________________________________________________________________________________________\nblock7c_se_reduce (Conv2D) (None, 1, 1, 128) 393344 block7c_se_reshape[0][0] \n__________________________________________________________________________________________________\nblock7c_se_expand (Conv2D) (None, 1, 1, 3072) 396288 block7c_se_reduce[0][0] \n__________________________________________________________________________________________________\nblock7c_se_excite (Multiply) (None, 15, 15, 3072) 0 block7c_activation[0][0] \n block7c_se_expand[0][0] \n__________________________________________________________________________________________________\nblock7c_project_conv (Conv2D) (None, 15, 15, 512) 1572864 block7c_se_excite[0][0] \n__________________________________________________________________________________________________\nblock7c_project_bn (BatchNormal (None, 15, 15, 512) 2048 block7c_project_conv[0][0] \n__________________________________________________________________________________________________\nblock7c_drop (Dropout) (None, 15, 15, 512) 0 block7c_project_bn[0][0] \n__________________________________________________________________________________________________\nblock7c_add (Add) (None, 15, 15, 512) 0 block7c_drop[0][0] \n block7b_add[0][0] \n__________________________________________________________________________________________________\ntop_conv (Conv2D) (None, 15, 15, 2048) 1048576 block7c_add[0][0] \n__________________________________________________________________________________________________\ntop_bn (BatchNormalization) (None, 15, 15, 2048) 8192 top_conv[0][0] \n__________________________________________________________________________________________________\ntop_activation (Activation) (None, 15, 15, 2048) 0 top_bn[0][0] \n__________________________________________________________________________________________________\navg_pool (GlobalAveragePooling2 (None, 2048) 0 top_activation[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 2048) 8192 avg_pool[0][0] \n__________________________________________________________________________________________________\ntop_dropout (Dropout) (None, 2048) 0 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\npred (Dense) (None, 3) 6147 top_dropout[0][0] \n==================================================================================================\nTotal params: 28,527,866\nTrainable params: 3,448,963\nNon-trainable params: 25,078,903\n__________________________________________________________________________________________________\n"
],
[
"def build_model(num_classes):\n inputs = layers.Input(shape=(height, width, 3))\n x = inputs\n model = EfficientNetB5(include_top=False, input_tensor=x, weights=\"imagenet\")\n\n # Freeze the pretrained weights\n model.trainable = False\n\n # Rebuild top\n x = layers.GlobalAveragePooling2D(name=\"avg_pool\")(model.output)\n x = layers.BatchNormalization()(x)\n\n top_dropout_rate = 0.2\n x = layers.Dropout(top_dropout_rate, name=\"top_dropout\")(x)\n outputs = layers.Dense(num_classes, activation=\"softmax\", name=\"pred\")(x)\n\n # Compile\n model = tf.keras.Model(inputs, outputs, name=\"EfficientNet\")\n\n for layer in model.layers[-20:]:\n if not isinstance(layer, layers.BatchNormalization):\n layer.trainable = True\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4)\n model.compile(\n optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n return model\n\nmodel2 = build_model(3)\nmodel2.load_weights('gdrive/MyDrive/covid-dataset')",
"_____no_output_____"
],
[
"model2.predict(validation_generator)",
"_____no_output_____"
],
[
"import numpy as np\n\n\nnp.unique(validation_generator.labels, \n return_counts=True)",
"_____no_output_____"
],
[
"model2.evaluate(validation_generator)",
"14/14 [==============================] - 44s 3s/step - loss: 0.8402 - accuracy: 0.6667\n"
],
[
"y_pred = model2.predict(validation_generator)",
"_____no_output_____"
],
[
"y_true, y_pred = validation_generator.classes, np.argmax(y_pred, axis=1)",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score\n\n\naccuracy_score(y_true, y_pred)",
"_____no_output_____"
],
[
"from sklearn.metrics import classification_report, confusion_matrix",
"_____no_output_____"
],
[
"indices_class = {v:k for k,v in validation_generator.class_indices.items()}\nindices_class\ntarget_names = ['atypical', 'indeterminate', 'typical']\ntarget_names",
"_____no_output_____"
],
[
"print('Confusion Matrix')\nprint(confusion_matrix(y_true, y_pred))",
"Confusion Matrix\n[[ 7 10 76]\n [ 4 47 156]\n [ 2 34 510]]\n"
],
[
"print('Precision: What proportion of positive identifications was actually correct?')\nprint('When it predicts a <Class> is true, it is correct <Precision> of the time.', '\\n')\n\nprint('Recall: What proportion of actual positives was identified correctly?')\nprint('Correctly identifies <Recall> of all true <Class>.', '\\n')\n\nprint('F1-SCORE: Combines the precision and recall of a classifier into a\\nsingle metric by taking their harmonic meany.')\n\n\nprint('Classification Report')\nprint(classification_report(y_true, y_pred, target_names=target_names))",
"Precision: What proportion of positive identifications was actually correct?\nWhen it predicts a <Class> is true, it is correct <Precision> of the time. \n\nRecall: What proportion of actual positives was identified correctly?\nCorrectly identifies <Recall> of all true <Class>. \n\nF1-SCORE: Combines the precision and recall of a classifier into a\nsingle metric by taking their harmonic meany.\nClassification Report\n precision recall f1-score support\n\n atypical 0.54 0.08 0.13 93\nindeterminate 0.52 0.23 0.32 207\n typical 0.69 0.93 0.79 546\n\n accuracy 0.67 846\n macro avg 0.58 0.41 0.41 846\n weighted avg 0.63 0.67 0.60 846\n\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"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",
"code"
]
] |
cb0701296ecdd07da1669b07b2f6f95f87198225 | 219,924 | ipynb | Jupyter Notebook | 可视化/tSNE等数据可视化.ipynb | NANBFTOP5/MOF | 72986df475c19bcd17cf921af7d2a23cc3e44f41 | [
"MIT"
] | null | null | null | 可视化/tSNE等数据可视化.ipynb | NANBFTOP5/MOF | 72986df475c19bcd17cf921af7d2a23cc3e44f41 | [
"MIT"
] | null | null | null | 可视化/tSNE等数据可视化.ipynb | NANBFTOP5/MOF | 72986df475c19bcd17cf921af7d2a23cc3e44f41 | [
"MIT"
] | null | null | null | 222.820669 | 12,188 | 0.847429 | [
[
[
"import nltk\nimport sklearn\n\nprint('The nltk version is {}.'.format(nltk.__version__))\nprint('The scikit-learn version is {}.'.format(sklearn.__version__))",
"The nltk version is 3.4.4.\nThe scikit-learn version is 0.21.2.\n"
],
[
"print(__doc__)\nfrom time import time\nimport pickle\n\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import offsetbox\nfrom sklearn import (manifold, datasets, decomposition, ensemble,\n discriminant_analysis, random_projection, neighbors)",
"Automatically created module for IPython interactive environment\n"
]
],
[
[
"读取test data做可视化",
"_____no_output_____"
]
],
[
[
"\ndigits = pd.read_csv('test_data_30.csv')\ndigits = digits.fillna(method='ffill')\n\nscaler = MinMaxScaler()\nX = scaler.fit_transform(digits.iloc[:,1:])\n\n#y = digits[:,-1]\nn_samples, n_features = X.shape\nn_neighbors = 5\n\nX = np.array(X)\n\ny = np.array([67,67,67,71,71,71,8,8,8,90,90,90,7,7,7,9,9,9,5,5,5,74,74,74,199,199,199,2,2,2])",
"_____no_output_____"
],
[
"'''t-SNE'''\ntsne = manifold.TSNE(n_components=2, init='pca', random_state=501)\nX_tsne = tsne.fit_transform(X)\n\nprint(\"Org data dimension is {}. Embedded data dimension is {}\".format(X.shape[-1], X_tsne.shape[-1]))\n\n'''嵌入空间可视化'''\nx_min, x_max = X_tsne.min(0), X_tsne.max(0)\nX_norm = (X_tsne - x_min) / (x_max - x_min) # 归一化\nplt.figure(figsize=(5, 5))\nfor i in range(X_norm.shape[0]):\n plt.text(X_norm[i, 0], X_norm[i, 1], str(y[i]), color=plt.cm.Set1(y[i]/ 270.), fontdict={'weight': 'bold', 'size': 9})\nplt.xticks([])\nplt.yticks([])\nplt.show()",
"Org data dimension is 2251. Embedded data dimension is 2\n"
],
[
"# ----------------------------------------------------------------------\n# Scale and visualize the embedding vectors\ndef plot_embedding(X, title=None):\n x_min, x_max = np.min(X, 0), np.max(X, 0)\n X = (X - x_min) / (x_max - x_min)\n\n plt.figure()\n ax = plt.subplot(111)\n for i in range(X.shape[0]):\n plt.text(X[i, 0], X[i, 1], str(y[i]),\n color=plt.cm.Set1(y[i] / 10.),\n fontdict={'weight': 'bold', 'size': 9})\n\n if hasattr(offsetbox, 'AnnotationBbox'):\n # only print thumbnails with matplotlib > 1.0\n shown_images = np.array([[1., 1.]]) # just something big\n for i in range(X.shape[0]):\n dist = np.sum((X[i] - shown_images) ** 2, 1)\n if np.min(dist) < 4e-3:\n # don't show points that are too close\n continue\n shown_images = np.r_[shown_images, [X[i]]]\n imagebox = offsetbox.AnnotationBbox(\n offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),\n X[i])\n ax.add_artist(imagebox)\n plt.xticks([]), plt.yticks([])\n if title is not None:\n plt.title(title)",
"_____no_output_____"
],
[
"# ----------------------------------------------------------------------\n# t-SNE embedding of the digits dataset\nprint(\"Computing t-SNE embedding\")\ntsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\nt0 = time()\nX_tsne = tsne.fit_transform(X)\n\nplot_embedding(X_tsne,\"t-SNE embedding of the digits (time %.2fs)\" %(time() - t0))",
"Computing t-SNE embedding\n"
],
[
"# ----------------------------------------------------------------------\n# Random 2D projection using a random unitary matrix\nprint(\"Computing random projection\")\nrp = random_projection.SparseRandomProjection(n_components=2, random_state=42)\nX_projected = rp.fit_transform(X)\nplot_embedding(X_projected, \"Random Projection of the digits\")",
"Computing random projection\n"
],
[
"#----------------------------------------------------------------------\n# Projection on to the first 2 principal components\n\nprint(\"Computing PCA projection\")\nt0 = time()\nX_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(X)\nplot_embedding(X_pca,\n \"Principal Components projection of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing PCA projection\n"
],
[
"# ----------------------------------------------------------------------\n# Projection on to the first 2 linear discriminant components\n\nprint(\"Computing Linear Discriminant Analysis projection\")\nX2 = X.copy()\nX2.flat[::X.shape[1] + 1] += 0.01 # Make X invertible\nt0 = time()\nX_lda = discriminant_analysis.LinearDiscriminantAnalysis(n_components=2).fit_transform(X2, y)\nplot_embedding(X_lda,\n \"Linear Discriminant projection of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing Linear Discriminant Analysis projection\n"
],
[
"# ----------------------------------------------------------------------\n# Isomap projection of the digits dataset\nprint(\"Computing Isomap projection\")\nt0 = time()\nX_iso = manifold.Isomap(n_neighbors, n_components=2).fit_transform(X)\nprint(\"Done.\")\nplot_embedding(X_iso,\n \"Isomap projection of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing Isomap projection\nDone.\n"
],
[
"# ----------------------------------------------------------------------\n# Locally linear embedding of the digits dataset\nprint(\"Computing LLE embedding\")\nclf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,\n method='standard')\nt0 = time()\nX_lle = clf.fit_transform(X)\nprint(\"Done. Reconstruction error: %g\" % clf.reconstruction_error_)\nplot_embedding(X_lle,\n \"Locally Linear Embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing LLE embedding\nDone. Reconstruction error: 0.000928688\n"
],
[
"# ----------------------------------------------------------------------\n# Modified Locally linear embedding of the digits dataset\nprint(\"Computing modified LLE embedding\")\nclf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,\n method='modified')\nt0 = time()\nX_mlle = clf.fit_transform(X)\nprint(\"Done. Reconstruction error: %g\" % clf.reconstruction_error_)\nplot_embedding(X_mlle,\n \"Modified Locally Linear Embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing modified LLE embedding\nDone. Reconstruction error: 0.00635904\n"
],
[
"print(X_mlle)",
"_____no_output_____"
],
[
"# ----------------------------------------------------------------------\n# HLLE embedding of the digits dataset\nprint(\"Computing Hessian LLE embedding\")\nclf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,\n method='hessian')\nt0 = time()\nX_hlle = clf.fit_transform(X)\nprint(\"Done. Reconstruction error: %g\" % clf.reconstruction_error_)\nplot_embedding(X_hlle,\n \"Hessian Locally Linear Embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing Hessian LLE embedding\n"
],
[
"# ----------------------------------------------------------------------\n# LTSA embedding of the digits dataset\nprint(\"Computing LTSA embedding\")\nclf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,\n method='ltsa')\nt0 = time()\nX_ltsa = clf.fit_transform(X)\nprint(\"Done. Reconstruction error: %g\" % clf.reconstruction_error_)\nplot_embedding(X_ltsa,\n \"Local Tangent Space Alignment of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing LTSA embedding\nDone. Reconstruction error: 9.52758e-05\n"
],
[
"# ----------------------------------------------------------------------\n# MDS embedding of the digits dataset\nprint(\"Computing MDS embedding\")\nclf = manifold.MDS(n_components=2, n_init=1, max_iter=100)\nt0 = time()\nX_mds = clf.fit_transform(X)\nprint(\"Done. Stress: %f\" % clf.stress_)\nplot_embedding(X_mds,\n \"MDS embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing MDS embedding\nDone. Stress: 6984.931050\n"
],
[
"# ----------------------------------------------------------------------\n# Random Trees embedding of the digits dataset\nprint(\"Computing Totally Random Trees embedding\")\nhasher = ensemble.RandomTreesEmbedding(n_estimators=200, random_state=0,\n max_depth=5)\nt0 = time()\nX_transformed = hasher.fit_transform(X)\npca = decomposition.TruncatedSVD(n_components=2)\nX_reduced = pca.fit_transform(X_transformed)\n\nplot_embedding(X_reduced,\n \"Random forest embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing Totally Random Trees embedding\n"
],
[
"# ----------------------------------------------------------------------\n# Spectral embedding of the digits dataset\nprint(\"Computing Spectral embedding\")\nembedder = manifold.SpectralEmbedding(n_components=2, random_state=0,\n eigen_solver=\"arpack\")\nt0 = time()\nX_se = embedder.fit_transform(X)\n\nplot_embedding(X_se,\n \"Spectral embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing Spectral embedding\n"
],
[
"# ----------------------------------------------------------------------\n# t-SNE embedding of the digits dataset\nprint(\"Computing t-SNE embedding\")\ntsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\nt0 = time()\nX_tsne = tsne.fit_transform(X)\n\nplot_embedding(X_tsne,\n \"t-SNE embedding of the digits (time %.2fs)\" %\n (time() - t0))",
"Computing t-SNE embedding\n"
],
[
"# ----------------------------------------------------------------------\n# NCA projection of the digits dataset\nprint(\"Computing NCA projection\")\nnca = neighbors.NeighborhoodComponentsAnalysis(n_components=2, random_state=0)\nt0 = time()\nX_nca = nca.fit_transform(X, y)\n\nplot_embedding(X_nca,\n \"NCA embedding of the digits (time %.2fs)\" %\n (time() - t0))\n\nplt.show()",
"Computing NCA projection\n"
],
[
"print(X_nca)",
"[[ 0.77519589 -11.86948318]\n [ 2.1333111 -11.93849311]\n [ 1.75364277 -11.79042791]\n [ 3.14564811 -1.69316209]\n [ 2.40127958 -0.80519923]\n [ 1.97806687 -2.43189793]\n [ 12.81251568 7.19804738]\n [ 12.97860066 2.02166839]\n [ 12.80743053 6.07193998]\n [ 12.7631689 2.73366925]\n [ 9.0357067 3.23900074]\n [ 6.96286259 1.73719881]\n [ 3.2318797 -7.36959206]\n [ 1.54670847 -6.24459689]\n [ 2.86143794 -7.20721701]\n [ -1.9587311 -4.59584526]\n [ -1.74996028 -4.16421597]\n [ -1.75023067 -4.35107539]\n [ 0.26007748 2.39342715]\n [ 0.09073584 2.63617363]\n [ 1.91961826 3.48414551]\n [ -2.0172029 -0.40592936]\n [ -1.39996054 -0.64877801]\n [ -2.52348758 -0.26431428]\n [ -9.27952782 0.40025519]\n [ -8.410033 0.58637005]\n [ -8.36510784 0.8424334 ]\n [ -7.58239639 8.20112043]\n [ -7.85021555 8.63751552]\n [ -6.6798695 6.78626759]]\n"
]
]
] | [
"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"
]
] |
cb070a8a8d9f90d3eecf7e540d0be8fb22aa9ee4 | 16,271 | ipynb | Jupyter Notebook | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 | cdd29b652ff16b0e0593367dcbb51ccbd54c659e | [
"MIT"
] | 1 | 2019-11-09T15:45:01.000Z | 2019-11-09T15:45:01.000Z | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 | cdd29b652ff16b0e0593367dcbb51ccbd54c659e | [
"MIT"
] | null | null | null | 10_entrada_y_salida_estandar.ipynb | Martinez-Gregorio-Hector/py101 | cdd29b652ff16b0e0593367dcbb51ccbd54c659e | [
"MIT"
] | null | null | null | 25.992013 | 406 | 0.498187 | [
[
[
"[](https://pythonista.io)",
"_____no_output_____"
],
[
"# Entrada y salida estándar.",
"_____no_output_____"
],
[
"En la actualidad existen muchas fuentes desde las que se puede obtener y desplegar la información que un sistema de cómputo consume, gestiona y genera. Sin embargo, para el intérprete de Python la salida por defecto (salida estándar) de datos es la terminal de texto y la entrada estándar es el teclado.\n\nEn el caso de las notebooks de *Jupyter*, cada celda de código representa a la entrada estándar mediante:\n\n```In[ ]:```\n\nY la salida estándar mediante:\n\n```Out[ ]:```",
"_____no_output_____"
],
[
"**Ejemplo:**",
"_____no_output_____"
]
],
[
[
" 3 * \"Hola\"",
"_____no_output_____"
]
],
[
[
"## Salida estándar con la funcion ```print()```.\n\nEn Python 3, la función ```print()``` se utiliza para desplegar información en la salida estándar.\n\nLa sintaxis es la siguiente:\n\n```\nprint(<expresión 1>, <expresión 2>, ...<expresión 3>)\n```\n\n* La función ```print()``` evalúa y despliega una o varias expresiones.\n* Si el resultado de la expresión es un objeto ```str```, este es desplegado sin los apóstrofes o las comillas que lo delimitan.",
"_____no_output_____"
],
[
"**Ejemplos:**",
"_____no_output_____"
],
[
"* La siguiente celda define el nombre ```a``` con valor igual a ```2```.",
"_____no_output_____"
]
],
[
[
"a = 2",
"_____no_output_____"
]
],
[
[
"* La siguiente celda evalúa la expresión ```a```, por lo que desplegará ```2```.",
"_____no_output_____"
]
],
[
[
"print(a)",
"_____no_output_____"
]
],
[
[
"* La siguiente celda desplegará el mensaje dentro del objeto ```\"Hola\"```.",
"_____no_output_____"
]
],
[
[
"print(\"Hola\")",
"_____no_output_____"
]
],
[
[
"* En la siguiente celda la función ```print()``` desplegará dos expresiones que corresponde cada una a un objeto de tipo ```str```. Cada objeto será desplegado separado por un espacio.\n\n* La salida será ```Hola Mundo```.",
"_____no_output_____"
]
],
[
[
"print(\"Hola\", \"Mundo\")",
"_____no_output_____"
]
],
[
[
"* En la siguiente celda la función ```print()``` desplegará el resultado de una expresión de concatenación entre dos objetos de tipo ```str```. El resultado es un objeto ```str```.\n\n* La salida será ```HolaMundo```.",
"_____no_output_____"
]
],
[
[
"print(\"Hola\" + \"Mundo\")",
"_____no_output_____"
]
],
[
[
"* En la siguiente celda la función ```print()``` desplegará tres expresiones que corresponden a:\n * El objeto ```'Tienes'``` de tipo ```str```.\n * El objeto ```2``` de tipo ```int``` ligado al nombre ```a```.\n * El objeto ```'buenos amigos'``` de tipo ```str```.\n\nCada expresión será desplegada separada por un espacio.\n\n* La salida será ```Tienes 2 buenos amigos.```.",
"_____no_output_____"
]
],
[
[
"print(\"Tienes\", a, \"buenos amigos.\")",
"_____no_output_____"
]
],
[
[
"* En la siguiente celda la función ```print()``` intentará desplegar el resultado de la expresión ```\"Tienes\" + a + \"buenos amigos.\"```, la cual no es correcta y generará un error de tipo ```TypeError```.",
"_____no_output_____"
]
],
[
[
"print(\"Tienes\" + a + \"buenos amigos.\")",
"_____no_output_____"
]
],
[
[
"### Despliegue con formato.\n\nPara intercalar valores dentro de un formato específico de texto se utiliza el caracter sobre-escritura definodo como el signo de porcentaje ```%``` seguido de algún caracter que definirá el modo de desplegar la expresión correspondiente.\n\n```\nprint(\"...%<caracter>...\" % expresión 1) \n```\n\n```\nprint(\"...%<caracter 1>...%<caracter n>...\" %(<expresión 1>,...<expresión n>))\n```\n\n\n\n|Caracter de escape|Modo de despliegue|\n|:----------------:|:----------------:|\n|```%s```|\tcadena de texto|\n|```%d```|\t entero|\n|```%o```|\t octal|\n|```%x```|\t hexadecimal|\n|```%f```|\t punto flotante|\n|```%e```|\t punto flotante en formato exponencial| \n\nEl uso de ```%s```, equivale a aplicar la función ```str()``` al valor a desplegar.",
"_____no_output_____"
],
[
"**Ejemplos:**",
"_____no_output_____"
]
],
[
[
"pi = 3.141592\nradio = 2",
"_____no_output_____"
],
[
"print(\"El perímetro de un círculo de radio %d es %f.\" % (radio, 2 * radio * pi))",
"_____no_output_____"
],
[
"print(\"El perímetro de un círculo de radio %d es %d.\" % (radio, 2 * radio * pi))",
"_____no_output_____"
],
[
"print(\"El perímetro de un circulo de radio %s es %s.\" % (radio, 2 * radio * pi))",
"_____no_output_____"
],
[
"print(\"El valor de pi es %f.\" % (pi))",
"_____no_output_____"
],
[
"print(\"El valor de pi es %e.\" % pi)",
"_____no_output_____"
]
],
[
[
"Para desplegar el signo de porcentaje ```%``` se utiliza ```%%```.",
"_____no_output_____"
],
[
"**Ejemplo:**",
"_____no_output_____"
]
],
[
[
"valor = 13\nporciento = 15\nporcentaje = (valor * porciento) / 100\nprint(\"El %d%% de %f es %f.\" % (porciento, valor, porcentaje))",
"_____no_output_____"
]
],
[
[
"#### Despliegue de cifras significativas.\n\nPara desplegar un número específico de cifras significativas de un valor de punto flotante, se añade un punto ```.``` y el número de cifras a desplegarse después del signo de porcentaje ```%``` y antes del carácter ```f``` o ```e```.\n\n```\n%.<n>f\n```",
"_____no_output_____"
],
[
"**Ejemplos:**",
"_____no_output_____"
]
],
[
[
"pi = 3.14169265\nradio = 2",
"_____no_output_____"
],
[
"print(\"El perímetro de un círculo de radio igual a %d es %f.\" % (radio, 2 * pi * radio))",
"_____no_output_____"
],
[
"print(\"El perímetro de un círculo de radio igual a %d es %.2f.\" % (radio, 2 * pi * radio))",
"_____no_output_____"
]
],
[
[
"### Caracteres de escape.\n\nExisten algunos caracteres que por su función o por la sintaxis de Python -tales como los apóstrofes, las comillas, los retornos de línea, etc.- que deben utilizar un \"caracter de escape\", para que puedan ser desplegados. Los caracteres de escape pueden ser introducidos después de una diagonal invertida ```\\```.\n\n|Secuencia|Despliegue|\n|:-------:|:--------:|\n|```\\n``` |Retorno de línea|\n|```\\t``` |Tabulador |\n|```\\\"``` |Comillas |\n|```\\'``` |Apóstrofe |\n|```\\\\``` |Diagonal invertida|\n|```\\xNN``` |Caracter que corresponde al número hexadecimal *NN* en ASCII|\n|```\\uNN``` |Caracter que corresponde al número hexadecimal *NN* en Unicode|",
"_____no_output_____"
],
[
"**Ejemplo:**",
"_____no_output_____"
]
],
[
[
"print(\"Primera línea.\\nSegunda línea\\t con tabulador.\")",
"_____no_output_____"
],
[
"print(\"Este es el signo de \\\"gato\\\" \\x23.\")",
"_____no_output_____"
],
[
"print(\"Beta: \\u00DF\")",
"_____no_output_____"
],
[
"print('I \\u2764 YOU!')",
"_____no_output_____"
]
],
[
[
"## Entrada estándar con la función ```input()```. \n\nLa función por defecto de entrada estándar para Python 3 es ```input()```.\n\nLa función ```input()``` captura los caracteres provenientes de entrada estándar (el teclado) hasta que se introduce un retorno de carro <kbd>Intro</kbd> y el contenido capturado es devuelto al intérprete como una cadena de texto. \n\nLa cadena de caracteres resultante puede ser almacenada como un objeto de tipo ```str``` mediante la asignación de un nombre.\n\nLa función permite desplegar un mensaje de tipo ```str``` como parámetro.\n\n``` \ninput(<objeto tipo str>)\n```",
"_____no_output_____"
],
[
"**Ejemplos:**",
"_____no_output_____"
]
],
[
[
"input()",
"_____no_output_____"
],
[
"texto = input()",
"_____no_output_____"
],
[
"type(texto)",
"_____no_output_____"
],
[
"texto",
"_____no_output_____"
],
[
"print(texto)",
"_____no_output_____"
],
[
"nombre = input(\"Escribe un nombre: \")\nprint(nombre)",
"_____no_output_____"
]
],
[
[
"## Entrada y salida estándar en Python 2.",
"_____no_output_____"
],
[
"\n### La función ```raw_input()```.\n\nLa sintaxis es la siguiente para Python 2:\n\n``` \nraw_input(<objeto tipo str>)\n```\n\n**Ejemplo:**\n\n``` python\n>>> raw_input()\nHola\n'Hola'\n>>> texto = raw_input()\nHola\n>>> type(texto)\n<type 'str'>\n>>> print texto\nHola\n>>> nombre = raw_input(\"Escribe un nombre: \")\nEscribe un nombre: Juan\n>>> print nombre\nJuan\n>>> \n```\n### La función ```input()``` en Python 2.\n\nAdemás de ```raw_input()```, existe la función ```input()```, la cual es semejante a ejecutar ```eval(raw_input())```.\n\nSi la expresión ingresada es correcta, La función ```input()``` puede regresar valores de diversos tipos, en vez de sólo cadenas de texto.\n\n**Ejemplo:**\n\n``` python\n>>> mensaje = \"Ingresa el texto: \"\n>>> valor = raw_input(mensaje)\nIngresa el texto: 35 + 21\n>>> type(valor)\n<type 'str'>\n>>> print valor\n35 + 21\n>>> valor = input(mensaje)\nIngresa el texto: 35 + 21\n>>> type(valor)\n<type 'int'>\n>>> print valor\n56\n>>> valor = input(mensaje)\nIngresa el texto: \"Hola\"\n>>> type(valor)\n<type 'str'>\n>>> print valor\nHola\n>>> valor = input(mensaje)\nIngresa el texto: Hola\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<string>\", line 1, in <module>\nNameError: name 'Hola' is not defined\n>>>\n```\n**NOTA:** La función ```input()```, tal como se usa en Python 2 tiene el potencial de generar diversos errores y es susceptible de vulnerabilidades de seguridad debido a que podría usarse para inyectar código malicioso. Es por eso por lo que en Python 3, ```input()``` se comporta como ```raw_input()``` y la función ```raw_input()``` fue desechada.",
"_____no_output_____"
]
],
[
[
"eval(input('Ingresa: '))",
"_____no_output_____"
]
],
[
[
"<p style=\"text-align: center\"><a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Licencia Creative Commons\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/80x15.png\" /></a><br />Esta obra está bajo una <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Licencia Creative Commons Atribución 4.0 Internacional</a>.</p>\n<p style=\"text-align: center\">© José Luis Chiquete Valdivieso. 2019.</p>",
"_____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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb070e688138868820d1be99988eff1ed33db0a9 | 50,644 | ipynb | Jupyter Notebook | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork | 0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1 | [
"MIT"
] | null | null | null | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork | 0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1 | [
"MIT"
] | null | null | null | MNS/.ipynb_checkpoints/MNS_CP2_Longren-checkpoint.ipynb | lcubelongren/BCCN_classwork | 0f5cf9e44bca54b5aba5aeb826586d1aaaa777d1 | [
"MIT"
] | null | null | null | 144.2849 | 23,444 | 0.875661 | [
[
[
"## Hopfield Network - Longren",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\nfrom IPython.display import set_matplotlib_formats\nset_matplotlib_formats('png', 'pdf')",
"_____no_output_____"
]
],
[
[
"## Tasks:",
"_____no_output_____"
]
],
[
[
"# 1. Store the patterns in the Hopfield network\n\n'pattern A'\nSA = [1,-1,1,-1]\n\n'pattern B'\nSB = [-1,1,1,1]\n\n'pattern C'\nSC = [-1,-1,-1,1]\n\nN = 3 #number of patterns\nK = 4 #number of units\n\nWA = np.zeros([K,K]) #empty weight matrix\nWB = np.zeros([K,K])\nWC = np.zeros([K,K])\n\ndef weight_int(W,S): #weight initialization\n \n for i in range(K): #for each row\n \n for j in range(K): #for each column\n \n W[i][j] = S[i] * S[j] #calculate weights for i != j\n W[j][j] = 0 #set weights i = j to zero\n \n return W\n\n\nWA = weight_int(WA,SA)\nprint('weights for pattern A:')\nprint(WA)\nWB = weight_int(WB,SB)\nprint('weights for pattern B:')\nprint(WB)\nWC = weight_int(WC,SC)\nprint('weights for pattern C:')\nprint(WC)\n",
"weights for pattern A:\n[[ 0. -1. 1. -1.]\n [-1. 0. -1. 1.]\n [ 1. -1. 0. -1.]\n [-1. 1. -1. 0.]]\nweights for pattern B:\n[[ 0. -1. -1. -1.]\n [-1. 0. 1. 1.]\n [-1. 1. 0. 1.]\n [-1. 1. 1. 0.]]\nweights for pattern C:\n[[ 0. 1. 1. -1.]\n [ 1. 0. 1. -1.]\n [ 1. 1. 0. -1.]\n [-1. -1. -1. 0.]]\n"
],
[
"# 1. Which of the patterns are stable states of the network dynamics?\n\nZ = np.zeros([K]) #empty input array\n\ndef unit_input(W,S): #apply stored pattern as input\n \n i = np.random.randint(0,4) #asynchronous update of units -- is this what is meant for choosing i?\n \n for j in range(K):\n\n Z[i] = np.sum(W[i][j] * S[j]) #new state Z\n \n #print(j,i,Z[i])\n \n if Z[i] >= 0:\n \n Z[i] = 1\n \n elif Z[i] < 0:\n \n Z[i] = -1 \n \n return Z\n\n\n#let's run the patterns again and see where they converges to\n\ncount = 50\n\ndef converge(W,S):\n \n print('original pattern:', S)\n \n for i in range(count):\n \n Zi = unit_input(W,S)\n \n return Zi\n\nZA = converge(WA,SA)\nprint('convergence of A:',ZA)\nZB = converge(WB,SB)\nprint('convergence of B:',ZB)\nZC = converge(WC,SC)\nprint('convergence of C:',ZC)\n",
"original pattern: [1, -1, 1, -1]\nconvergence of A: [ 1. -1. 1. 1.]\noriginal pattern: [-1, 1, 1, 1]\nconvergence of B: [-1. 1. 1. 1.]\noriginal pattern: [-1, -1, -1, 1]\nconvergence of C: [-1. -1. -1. 1.]\n"
]
],
[
[
"Analyzing the results of my code for the convergence of the patterns, we can see that according to mine there are two stable patterns, B & C, as they stick to the same pattern that was initially given after count=50 iterations. The other pattern, A, is not stable as it does not have the same value for S4 as was initially given.\nHowever I believe my result for A is incorrect, as from the analytical MNS course we learned that there are three possible states for the Hopfield Network: P, -P, and (1,1,...,1) for the convergence of the pattern. And only a change of sign on S4 does not match a possible pattern that the unstable state could converge to.",
"_____no_output_____"
]
],
[
[
"# 2. Calculate the energy function for the network\n\n#loop through iterations\n\nW = np.zeros([K,K])\nZ = np.zeros([K])\nE = np.zeros([K,K])\n\ncount = 5\n\ndef energy(W,S): #energy function\n \n for i in range(K):\n \n for j in range(K):\n \n E[i][j] = -1 * np.sum(W[i][j] * np.dot(Z[i],Z[j]))\n \n return E\n\nELA = np.empty(count) \nELB = np.empty(count) \nELC = np.empty(count) \n \ndef energy_loop(EL,W,S):\n \n W = weight_int(W,S)\n \n for i in range(count):\n \n Z = unit_input(W,S)\n \n energy(W,S)\n \n EL[i] = np.sum(E)\n\n return EL\n\nenergy_loop(ELA,WA,SA)\nenergy_loop(ELB,WB,SB)\nenergy_loop(ELC,WC,SC)\n#print(ELA)\n#print(ELB)\n#print(ELC)\n\nx = np.linspace(1,count,count)\nplt.plot(x,ELA)\nplt.plot(x,ELB)\nplt.plot(x,ELC)\nplt.minorticks_on()\nplt.grid()\nplt.xlabel('iteration')\nplt.ylabel('energy level')\nplt.title('Energy function')\nplt.legend(('A','B','C'))\nplt.show()",
"_____no_output_____"
]
],
[
[
"All three patterns should only have a decreasing energy, however pattern A is having troubles for me for some iterations.",
"_____no_output_____"
]
],
[
[
"# 3. Reuse the code to store and recall image patterns\n\n# 3.1 load the given images\nimages = np.load(r\"C:\\Users\\lcube\\Desktop\\jupyter\\BCCN\\MNS\\given\\images.npz\")\n\nim = []\nfor item in lst: #getting the file into a usable form (somehow)\n \n im.append(images[item]) #i know append isn't recommended, but it took me forever to find a way to processs the .npz\n \nim = np.array(im) #array of size 8 x 30 x 40\n#print(im[0][7][29][39])\n\n# 3.2 store the patterns into a weight matrix\n\n### i don't understand, why are we flattening it? shouldn't it work fine as the weights are 2 dimensional\n### or do we want to get it to an 8 x 1200 and go from there..\n\nim = [im[0][i].flatten() for i in range(7)] #flatten from 2 dimensions into vectors\nim = np.array(im)\n#print(im)\n#print(np.size(im[0]))\n\n### i know that it is recommended to be using matrix multiplication in order to calculate most things,\n### but i am not sure how to do that without iterating over i and j to pick out the value that is \n### being updated \n\nw = np.ones([8,1200])\n#print(w)\n\nfor i in range(8): #calculate the weight matrix with the patterns \n \n for j in range(1200):\n \n w[i][j] = im[0][i] * im[0][j] #calculate weights for i != j\n w[i][i] = 0 #set weights i = j to zero\n\nprint(w) #the weight matrix W = {w_ij}\n\n\n### i'm not sure how to use the input matrices of the image file in order to calculate what it is we want\n\n",
"[[0. 1. 1. ... 1. 1. 1.]\n [1. 0. 1. ... 1. 1. 1.]\n [1. 1. 0. ... 1. 1. 1.]\n ...\n [1. 1. 1. ... 1. 1. 1.]\n [1. 1. 1. ... 1. 1. 1.]\n [1. 1. 1. ... 1. 1. 1.]]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb0714cd86584ea1a857dc49432b27178f09d911 | 5,622 | ipynb | Jupyter Notebook | notebooks/data-ingestion/03-Upload-JSON-to-Azure-Search.ipynb | liamca/covid19search | 4c71c76f243684e7ea7baafd14b641f46481cb36 | [
"MIT"
] | 16 | 2020-05-06T15:49:07.000Z | 2022-03-25T04:09:41.000Z | notebooks/data-ingestion/03-Upload-JSON-to-Azure-Search.ipynb | liamca/covid19search | 4c71c76f243684e7ea7baafd14b641f46481cb36 | [
"MIT"
] | 2 | 2020-05-04T22:28:10.000Z | 2020-10-15T02:47:08.000Z | notebooks/data-ingestion/03-Upload-JSON-to-Azure-Search.ipynb | liamca/covid19search | 4c71c76f243684e7ea7baafd14b641f46481cb36 | [
"MIT"
] | 5 | 2020-04-30T15:34:05.000Z | 2021-04-12T03:53:58.000Z | 29.589474 | 184 | 0.475276 | [
[
[
"# Take all JSON from Blob Container and upload to Azure Search",
"_____no_output_____"
],
[
"import globals\n\nimport os\nimport pickle\n\nimport json\nimport requests\nfrom pprint import pprint\n\nfrom azure.storage.blob import BlockBlobService\n\nfrom joblib import Parallel, delayed",
"_____no_output_____"
],
[
"def processLocalFile(file_name):\n json_content = {}\n try:\n with open(file_name, 'r') as json_file:\n json_content = json.loads(json_file.read())\n docID = json_content[\"paper_id\"]\n title = json_content[\"metadata\"][\"title\"]\n\n body = {\"documents\": []}\n \n abstractContent = ''\n id_counter = 1\n if \"abstract\" in json_content:\n for c in json_content[\"abstract\"]:\n abstractContent += c[\"text\"] + ' '\n body[\"documents\"].append({\n \"language\": \"en\",\n \"id\": str(id_counter),\n \"text\": c[\"text\"]\n })\n id_counter += 1\n\n abstractContent = abstractContent.strip()\n\n body = ''\n if \"body_text\" in json_content:\n for c in json_content[\"body_text\"]:\n body += c[\"text\"] + ' '\n body = body.strip()\n\n contributors = []\n for c in json_content[\"metadata\"][\"authors\"]:\n midInitial = ''\n for mi in c[\"middle\"]:\n midInitial += mi + ' '\n if len(((c[\"first\"] + ' ' + midInitial + c[\"last\"]).strip())) > 2:\n contributors.append((c[\"first\"] + ' ' + midInitial + c[\"last\"]).strip()) \n\n return {\"@search.action\": \"mergeOrUpload\", \"docID\": docID, \"title\":title, \"abstractContent\": abstractContent, \"body\": body, \"contributors\": contributors}\n\n\n except Exception as ex:\n print (blob_name, \" - Error:\", str(ex))\n return \"Error\"\n\n",
"_____no_output_____"
],
[
"with open(os.path.join(globals.files_dir, 'new_files.pkl'), 'rb') as input:\n new_files = pickle.load(input)",
"_____no_output_____"
],
[
"print (str(len(new_files)), 'to upload...')",
"1941 to upload...\n"
],
[
"documents = {\"value\": []}\nfor json_file in new_files:\n # print (json_file[json_file.rindex('/')+1:].replace('.json', '').replace('.xml', ''))\n documents[\"value\"].append(processLocalFile(json_file))\n if len(documents[\"value\"]) == 100:\n print (\"Applying\", str(len(documents[\"value\"])), \"docs...\")\n url = globals.endpoint + \"indexes/\" + globals.indexName + \"/docs/index\" + globals.api_version\n response = requests.post(url, headers=globals.headers, json=documents)\n documents = {\"value\": []}\nif len(documents[\"value\"]) > 0:\n print (\"Applying\", str(len(documents[\"value\"])), \"docs...\")\n url = globals.endpoint + \"indexes/\" + globals.indexName + \"/docs/index\" + globals.api_version\n response = requests.post(url, headers=globals.headers, json=documents)\n",
"Applying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 100 docs...\nApplying 41 docs...\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb072b22179dd0e5f9024e39e6de082ccf7491b6 | 4,554 | ipynb | Jupyter Notebook | zynq-old/.ipynb_checkpoints/BRAM_Test-checkpoint.ipynb | chiro2001/zynqs | a9340a7d0e1376c991a7c21680e93c31a2acab1e | [
"MIT"
] | null | null | null | zynq-old/.ipynb_checkpoints/BRAM_Test-checkpoint.ipynb | chiro2001/zynqs | a9340a7d0e1376c991a7c21680e93c31a2acab1e | [
"MIT"
] | null | null | null | zynq-old/.ipynb_checkpoints/BRAM_Test-checkpoint.ipynb | chiro2001/zynqs | a9340a7d0e1376c991a7c21680e93c31a2acab1e | [
"MIT"
] | null | null | null | 64.140845 | 951 | 0.633289 | [
[
[
"from pynq import Overlay\noverlay = Overlay(\"bits/pynq_linux\")\noverlay.download()\n# help(overlay)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
cb0733bccb2c3845066e66e286cb7bdb253048ba | 471,099 | ipynb | Jupyter Notebook | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior | 840ab5b8fc27825f4b8876274389ab7c8bbb9f32 | [
"MIT"
] | 2 | 2022-02-21T06:58:35.000Z | 2022-02-21T07:00:25.000Z | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior | 840ab5b8fc27825f4b8876274389ab7c8bbb9f32 | [
"MIT"
] | null | null | null | 01_Schooling/schooling_power_analysis.ipynb | khakhalin/Xenopus-Behavior | 840ab5b8fc27825f4b8876274389ab7c8bbb9f32 | [
"MIT"
] | null | null | null | 724.767692 | 193,116 | 0.941375 | [
[
[
"# Schooling in Xenopus tadpoles: Power analysis\n\nThis is a supplementary notebook that generates some simulated data, and estimates the power analysis for a schooling protocol. The analysis subroutines are the same, or very close to ones from the actual notebook (**schooling_analysis**). The results of power analysis are given, and explained, in the text below, but can also be re-created by the reader, by re-running this notebook.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy.spatial\nimport scipy.stats as stats\nfrom typing import List,Tuple",
"_____no_output_____"
]
],
[
[
"## 1. Generate simulated data\n\nData is generated in the following format:\n\n Layout of Tadpole dataframe:\n x y tx ty\n 0 7.391 14.783 -0.159 -0.14\n 1 8.850 14.623 -0.180 -0.18\n 2 7.751 12.426 -0.260 -0.24\n\nwhere each line correponds to a \"tadpole\"; `x` and `y` columns give the position of the \"tadpole's head\" (virtual, in this case), and `tx` and `ty` are the positions of the \"tail\", relative to the \"head\". ",
"_____no_output_____"
]
],
[
[
"def simulate_data(ntads=10, schooling=0.5, alignment=0.6):\n \"\"\"Simulates tadpole distribution in the dish.\n n = how many tadpoles to have\n \n schooling = the probability of being in a school (simplistic, binary approach)\n r = aligment radius\n alignment = alignment coefficient (1-noise_level)\n \"\"\"\n \n R_DISH = 7\n TAD_LENGTH = 0.4\n N_ATTEMPTS = 20 # How many attempts to place each tadpole we would make\n JUMP = 1 # Jump, in cm, from one tadpole to another\n do_alignment = False # Whether we should align tadpoles to their neighbors. Too fancy?\n \n xy = np.zeros((ntads,2))\n tails = np.zeros((ntads,2))\n \n itad = 0\n while itad < ntads: # Simplified Bridson’s algorithm for Poisson-disc sampling\n if itad==0 or np.random.uniform()>schooling: # First point and non-schooled points placed at random\n drop = np.random.uniform(0, 2*R_DISH, 2)\n else:\n iparent = np.random.randint(itad)\n angle = np.random.uniform(0, 2*np.pi)\n d = np.random.uniform(JUMP, 2*JUMP)\n drop = xy[iparent,:] + np.array([np.cos(angle), np.sin(angle)])*d\n if np.sqrt((drop[0]-R_DISH)**2 + (drop[1]-R_DISH)**2) > R_DISH: # Outside of a dish, won't do\n continue\n good_point = True\n for iother in range(itad):\n if np.sqrt(np.sum(np.square(drop-xy[iother,:]))) < JUMP: # Too close to another dot; won't do\n good_point = False\n break\n if not good_point:\n continue\n xy[itad,:] = drop\n \n # Make the tadpole perpendicular to the radius\n tails[itad,:] = [xy[itad,1]-R_DISH, -xy[itad,0]+R_DISH]\n tails[itad,:] = tails[itad,:]/np.linalg.norm(tails[itad,:])*TAD_LENGTH\n if do_alignment: # Fancy mutual alignment; maybe don't use it, as it is too fancy?\n if itad>0:\n for iother in range(itad):\n d = np.linalg.norm(xy[itad,:]-xy[iother,:])\n tails[itad,:] += tails[iother,:]/(d**2)\n tails[itad,:] = tails[itad,:]/np.linalg.norm(tails[itad,:])*TAD_LENGTH\n angle = np.random.uniform(0, 2*np.pi)\n randotail = np.array([np.cos(angle), np.sin(angle)])*TAD_LENGTH\n tails[itad,:] = tails[itad,:]*alignment + randotail*(1-alignment)\n tails[itad,:] = tails[itad,:]/np.linalg.norm(tails[itad,:])*TAD_LENGTH\n # This code above with 3 normalizations in a row could have been prettier of course\n \n itad += 1\n \n return pd.DataFrame({'x':xy[:,0] , 'y':xy[:,1] , 'tx':tails[:,0] , 'ty':tails[:,1]}) \n\ndef arena_plot(t):\n for i in range(len(t)):\n plt.plot(t.x[i]+np.array([0, t.tx[i]]), t.y[i]+np.array([0, t.ty[i]]), 'r-')\n plt.plot(t.x, t.y, '.')\n plt.gca().add_artist(plt.Circle((7,7), 6.9, color='blue', fill=False, linestyle='-'))\n plt.xlim([0, 14])\n plt.ylim([0, 14])\n plt.axis('off')\n return\n\nschoolings = [1, 0.5, 0]\nalignments = [1, 0.5, 0]\nnames = ['Lawful', 'Neutral', 'Chaotic', 'good', 'neutral', 'evil']\nplt.figure(figsize=(9,9))\nfor i in range(3):\n for j in range(3):\n t = simulate_data(ntads=20, schooling=schoolings[i], alignment=alignments[j])\n plt.subplot(3,3,i*3+j+1)\n arena_plot(t)\n plt.title(f\"Schooling={schoolings[i]}, \\n alignment={alignments[j]}\")\n #plt.title(names[j] + ' ' + names[3+i])",
"_____no_output_____"
]
],
[
[
"## 2. Processing Tools\n\nAn exact copy of tools from the \"main notebook\" (as of 2020.08.01), except that instead of extracing tadpoles from real data, here we simulate this data. (So `exctractTads` function is not actually used).",
"_____no_output_____"
]
],
[
[
"def getNFrames(data):\n \"\"\"Returns the total number of frames.\"\"\"\n return max(data.Frame)+1\n\ndef extractTads(data,frame):\n \"\"\"Splits the data into XY position of each head, and _relative_ XY position of each tail.\"\"\"\n xy = data.loc[data.Frame==frame,['X','Y']].to_numpy()\n heads = xy[0::2,:]\n tails = xy[1::2,:]-heads\n return pd.DataFrame({'x':heads[:,0] , 'y':heads[:,1] , 'tx':tails[:,0] , 'ty':tails[:,1]}) \n\ndef findNeighbors(tads): # Returns a new data frame, for edges\n \"\"\"Triangulates the field, finds \"neighbors\". No thresholding of distance.\"\"\"\n xy = tads[['x','y']]\n tri = scipy.spatial.Delaunay(xy,qhull_options=\"QJ\").simplices # \"QJ\" is needed to retain\n # all tadpoles, including isolated ones\n listOfPairs = [] # Array of tuples to describe all pairs of points\n flip = lambda x: (x[1],x[0]) # A local function to flip tuples\n for i in range(tri.shape[0]): # Go through all edges of Delaunay triangles, include each one only once\n triangle = [tuple(tri[i,[0,1]]) , tuple(tri[i,[1,2]]) , tuple(tri[i,[2,0]])]\n for p in triangle:\n if p not in listOfPairs and flip(p) not in listOfPairs:\n listOfPairs += [p]\n out = pd.DataFrame({'i':[a for (a,b) in listOfPairs] , 'j':[b for (a,b) in listOfPairs]})\n return out\n\ndef findDistances(tads,pairs):\n \"\"\"Calculates distances between pairs of neighboring tadpoles.\"\"\"\n xy = tads[['x','y']].values\n dist = [np.linalg.norm(xy[p[0],]-xy[p[1],]) for p in pairs[['i','j']].values.tolist()]\n pairs['dist'] = dist\n return pairs\n\n# --- Test, for the first frame\ntads = simulate_data(ntads=20)\npairs = findNeighbors(tads)\npairs = findDistances(tads,pairs)\n\nprint('Layout of Tadpole dataframe:')\nprint(tads[:3])\nprint('\\nLayout of Pairs dataframe:')\nprint(pairs[:3])\n\n# Test figure with edge colors proportional to their distance\nfig = plt.figure()\nax = fig.add_subplot(111)\nxy = tads[['x','y']].values\nfor i in range(len(pairs)):\n p = pairs[['i','j']].values.tolist()[i]\n ax.plot([xy[p[0],0] , xy[p[1],0]],[xy[p[0],1] , xy[p[1],1]]) # Point\n ax.plot(*([xy[p[i],_] for i in range(2)] for _ in range(2)),\n color=np.array([1,0.5,0])*pairs['dist'].iloc[i]/pairs[['dist']].max().values*0.9) \n # The awkward construction above draws lines between neighboring tadpoles\nax.set_aspect('equal')",
"Layout of Tadpole dataframe:\n x y tx ty\n0 12.972282 9.730947 -0.111329 -0.384195\n1 11.880166 10.630500 0.391904 -0.080068\n2 6.528482 13.566266 0.391893 0.080126\n\nLayout of Pairs dataframe:\n i j dist\n0 19 5 2.737425\n1 5 7 1.183917\n2 7 19 3.604447\n"
]
],
[
[
"## 3. Tools to Process Angles\n\nExactly same as in the main notebook (as of 2020.08.01)",
"_____no_output_____"
]
],
[
[
"def findAngles(tads,pairs):\n '''Angles between pairs of tadpoles'''\n tails = tads[['tx','ty']].values # Go from pandas to lists, to utilize list comprehension\n norms = [np.linalg.norm(tails[i,]) for i in range(tails.shape[0])]\n angle = [np.arccos(np.dot(tails[p[0],],tails[p[1],])/(norms[p[0]]*norms[p[1]])) \n for p in pairs[['i','j']].values.tolist()]\n pairs['angle'] = np.array(angle)/np.pi*180\n return pairs\n\ndef niceTadFigure(ax,tads,pairs):\n \"\"\"Nice picture for troubleshooting.\"\"\"\n xy = tads[['x','y']].values\n tails = tads[['tx','ty']].values\n ang = pairs[['angle']].values\n for i in range(len(pairs)):\n p = pairs[['i','j']].values.tolist()[i]\n ax.plot(*([xy[p[i],_] for i in range(2)] for _ in range(2)),\n color=np.array([0.5,0.8,1])*(1-ang[i]/max(ang))) # Tadpole-tapole Edges\n for i in range(xy.shape[0]):\n nm = np.linalg.norm(tails[i,])\n ax.plot(xy[i,0]+[0,tails[i,0]/nm], xy[i,1]+[0,tails[i,1]/nm] , '-',color='red')\n ax.set_aspect('equal')\n ax.axis('off')\n\n# --- Test, for the first frame\npairs = findAngles(tads,pairs)\n \nfig = plt.figure()\nax = fig.add_subplot(111)\nniceTadFigure(ax,tads,pairs)\n#plt.savefig('crystal_pic.svg', format='svg')",
"_____no_output_____"
]
],
[
[
"## 4. Define full processor and dataset visualization\n\nThis function is adjusted to look like the procesisng function from the main notebook, but actually we call the simulation several times, to generate the \"frames\".",
"_____no_output_____"
]
],
[
[
"def processEverything(nsets=12, show_image=False, schooling=0.3, alignment=0.5):\n \"\"\"Process one full dataset.\"\"\"\n if show_image:\n fig = plt.figure(figsize=(10,10));\n\n fullDf = pd.DataFrame()\n for iframe in range(nsets):\n tads = simulate_data(ntads=20, schooling=schooling, alignment=alignment)\n pairs = findNeighbors(tads)\n pairs = findDistances(tads,pairs)\n angl = findAngles(tads,pairs)\n\n fullDf = fullDf.append(pd.DataFrame({'frame': [iframe]*len(pairs)}).join(pairs))\n\n if show_image:\n ax = fig.add_subplot(4,4,iframe+1)\n niceTadFigure(ax,tads,pairs)\n return fullDf\n \nout = processEverything(show_image=True)",
"_____no_output_____"
]
],
[
[
"## 5. Compare two different simulated datasets\n\nBelow, one dataset has high schooling coefficient (0.9), and perfect alignment (1.0), while the other has almost no schooling (0.1), and perfectly random orientation for all tadpoles (alignment=0.0).",
"_____no_output_____"
]
],
[
[
"# Prepare the data\nout = processEverything(show_image=False, schooling=0.9, alignment=1.0)\nout_treatment = processEverything(show_image=False, schooling=0.1, alignment=0.0)",
"_____no_output_____"
],
[
"def two_groups_plot(y1, y2, labels):\n \"\"\"A basic two-groups plot\"\"\"\n plt.plot(1+(np.random.uniform(size=y1.shape[0])-0.5)*0.3, y1, '.', alpha=0.2, zorder=-1)\n plt.plot(2+(np.random.uniform(size=y2.shape[0])-0.5)*0.3, y2, '.', alpha=0.2, zorder=-1)\n # Zorder is set to negative to hack around a bug in matplotlib that places errorbars below plots\n plt.errorbar(1, np.mean(y1), np.std(y1), color='k', marker='s', capsize=5)\n plt.errorbar(2, np.mean(y2), np.std(y2), color='k', marker='s', capsize=5)\n plt.xlim(0,3)\n plt.xticks(ticks=[1,2], labels=labels)\n\ndef compare_distances(out1,out2,labels):\n \"\"\"Visualizes distances, reports a stat test\"\"\"\n N_BINS = 10\n \n d = out1['dist'].values\n d2 = out2['dist'].values\n\n plt.figure(figsize=(9,4))\n ax = plt.subplot(121)\n two_groups_plot(d, d2, labels)\n plt.ylabel('Distance, cm')\n \n ax = plt.subplot(122)\n #plt.hist(d , bins=30, density=True, alpha=0.5);\n #plt.hist(d2, bins=30, density=True, alpha=0.5);\n y1,x1 = np.histogram(d, bins=N_BINS, density=True)\n y2,x2 = np.histogram(d2, bins=N_BINS, density=True)\n centers = lambda x: np.mean(np.vstack((x[:-1],x[1:])), axis=0) # Centers of each bin\n plt.plot(centers(x1),y1,'.-')\n plt.plot(centers(x2),y2,'.-')\n plt.xlabel('Distance, cm')\n plt.ylabel('Probability Density')\n plt.legend(labels, loc='upper right')\n\n print('Was the average inter-tadpole disctance different between two sets of data?')\n print('(were their clumping?)')\n test_results = stats.ttest_ind(d,d2)\n print('T-test: t = ', test_results.statistic, '; p-value = ',test_results.pvalue)\n\n print('\\nWas the distribution shape different between two sets??')\n test_results = scipy.stats.ks_2samp(d,d2)\n print('Kolmogorov-Smirnov test p-value = ',test_results.pvalue)\n\ncompare_distances(out, out_treatment, ['High Schooling','Low schooling'])\n#plt.savefig('distances.svg', format='svg')",
"Was the average inter-tadpole disctance different between two sets of data?\n(were their clumping?)\nT-test: t = -7.081288975811951 ; p-value = 2.4422756226026123e-12\n\nWas the distribution shape different between two sets??\nKolmogorov-Smirnov test p-value = 7.172521035283853e-31\n"
]
],
[
[
"As we can see, non-schooling tadpoles tend to be more uniformly distributed, so we observe more mid-distances and fewer low and high distances. (\"More uniformly\" doesn't mean that the distribution is actually uniform; it is expected to be closer to $χ^2$). Conversely, schooling tadpoles tend to be closer to each other.\n\nAs not all inter-tadpole distances were considered, but rather we rely on the Delaunay triangulation, the shape of the histogram may be rather peculiar, but it is OK. What matters is not the shape itself, but the fact that this shape is sensitive to the configuration of the swarm, as this means that it can be used to statistically compare swarms that were formed differently.",
"_____no_output_____"
]
],
[
[
"def compare_angles(out, out2, labels):\n \"\"\"Visualizes angles, reports a stat test.\"\"\"\n HIST_BIN = 30 # Histogram step, in degrees\n \n a = out['angle'].values\n a2 = out2['angle'].values\n\n #plt.hist(a , bins=np.arange(0,180+10,10), density=True, alpha=0.5);\n #plt.hist(a2, bins=np.arange(0,180+10,10), density=True, alpha=0.5);\n \n preset_bins = np.arange(0,180+HIST_BIN, HIST_BIN) \n y1,x1 = np.histogram(a, bins=preset_bins, density=True)\n y2,x2 = np.histogram(a2, bins=preset_bins, density=True)\n centers = lambda x: np.mean(np.vstack((x[:-1],x[1:])), axis=0) # Centers of each bin\n plt.plot(centers(x1),y1,'.-')\n plt.plot(centers(x2),y2,'.-')\n plt.xticks(np.arange(0,180+30,30))\n plt.xlabel('Angle, degrees')\n plt.ylabel('Probability Density')\n plt.legend(labels, loc='upper right')\n\n print('\\nWas the distribution of angles different between two sets?')\n test_results = scipy.stats.ks_2samp(a,a2)\n print('Kolmogorov-Smirnov test p-value = ',test_results.pvalue)\n \ncompare_angles(out, out_treatment, ['Alignment','No alignment'])\n#plt.savefig('angles.svg', format='svg')",
"\nWas the distribution of angles different between two sets?\nKolmogorov-Smirnov test p-value = 3.767828784543536e-73\n"
]
],
[
[
"As we can see, if tadpoles are oriented at random, the histogram of inter-tadpole angles is flat. If tadpoles school, the distribution of angles drops, as most tadpoles are co-oriented.",
"_____no_output_____"
],
[
"## 6. Power analysis",
"_____no_output_____"
]
],
[
[
"ntries = 50\n\nx = np.linspace(0, 1, 21)\ny = np.zeros((x.shape[0], 3))\nfor ival in range(len(x)):\n val = x[ival]\n print(f'{val:4.1f}', end=' ')\n count = np.array([0,0,0])\n for iattempt in range(ntries):\n print('.', end='')\n out1 = processEverything(show_image=False, schooling=0.5, alignment=0.5)\n out2 = processEverything(show_image=False, schooling=val, alignment=val)\n d = out1['dist'].values\n d2 = out2['dist'].values\n pttest = stats.ttest_ind(d,d2).pvalue\n pks = scipy.stats.ks_2samp(d,d2).pvalue\n pangles = scipy.stats.ks_2samp(out['angle'].values, out2['angle'].values).pvalue\n count[0] += 1*(pttest<0.05)\n count[1] += 1*(pks<0.05)\n count[2] += 1*(pangles<0.05)\n y[ival,:] = count/ntries\n print()",
" 0.0 ..................................................\n 0.1 ..................................................\n 0.1 ..................................................\n 0.2 ..................................................\n 0.2 ..................................................\n 0.2 ..................................................\n 0.3 ..................................................\n 0.4 ..................................................\n 0.4 ..................................................\n 0.5 ..................................................\n 0.5 ..................................................\n 0.6 ..................................................\n 0.6 ..................................................\n 0.7 ..................................................\n 0.7 ..................................................\n 0.8 ..................................................\n 0.8 ..................................................\n 0.9 ..................................................\n 0.9 ..................................................\n 1.0 ..................................................\n 1.0 ..................................................\n"
],
[
"plt.figure(figsize=(8,6));\nplt.plot(x,y);\nplt.legend(labels=[\"Distances, t-test\",\"Distances, KS-test\",\"Angles, KS-test\"], bbox_to_anchor=(1.3, 1));\nplt.xlabel('Coefficients for the 2nd set (1st is fixed at 0.5)');\nplt.ylabel('Test power');",
"_____no_output_____"
]
],
[
[
"For every point of the chart above, we compare two simulated datasets. One has the **schooling** coefficient (the probability of joining an existing school) set at 0.5, and the admixture of noise to tadpole orientation (**alignment** coefficient) also set at 0.5. For the other dataset, both parameters assume all values from 0 to 1 with a 0.05 step. The sizes of both datasets are the same as in our real experiments: 20 tadpoles, 12 photos. each simulation is repeated 50 times, to estimate the power 1-β of each of the tests (with α=0.05).\n\nWe can see that the angle analysis is much more sensitive, as even a change from 0.50 to 0.55 noise admixture is detected with >95% probability. Yet, the distribution of angles is also arguably more biologically involved, as it can depend on the function of the lateral line, and the distribution of currents in the bowl, while these currents may themselves be affected by the quality of schooling (non-schooling tadpoles won't create a current). To re-iterate, the test for co-alignment is very sensitive mathematically, but may be a bit messy biologically.\n\nThe tests of spatial clumping are almost exactly the other way around: they are easy to interpret (if the tadpoles stay together, then phenomenologially the DO schoo, regardless of the mechanism), but they are not that sensitive mathematically. For this sample size, we had to change the probability of \"not joining a school\" by about 30% to detect a difference with 80% power. We can also see that the t-test is more sensitive to this change than the Kolmogorov-Smirnov test, although this comparison may be sensitive to this particular implementation of a spatial model.",
"_____no_output_____"
]
]
] | [
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb073b3ff4f557b6630020fbdf40915e5e83dd86 | 23,440 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Multiple_Linear_Regression-checkpoint.ipynb | MelissaDjohan/NBA-Data-Science | 500108e392d033ce496d732763c1211a94053c19 | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/Multiple_Linear_Regression-checkpoint.ipynb | MelissaDjohan/NBA-Data-Science | 500108e392d033ce496d732763c1211a94053c19 | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/Multiple_Linear_Regression-checkpoint.ipynb | MelissaDjohan/NBA-Data-Science | 500108e392d033ce496d732763c1211a94053c19 | [
"Apache-2.0"
] | 1 | 2020-01-13T18:07:22.000Z | 2020-01-13T18:07:22.000Z | 32.510402 | 252 | 0.334343 | [
[
[
"%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport statsmodels.api as sm",
"_____no_output_____"
],
[
"from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"df = pd.read_csv(\"NBA_19_records.csv\")\ndf.head()",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"df = df[['salary_2019to2020','age', 'gp','min','pts','fg_prc','three_pnt_prc','ft_prc','reb','ast', 'tov','plusminus']]\ndf.head()",
"_____no_output_____"
],
[
"df = df.rename(columns={\"salary_2019to2020\":\"y\",\"age\":\"X1\", \"gp\":\"X2\",\"min\":\"X3\",\"pts\":\"X4\",\"fg_prc\":\"X5\",\"three_pnt_prc\":\"X6\",\"ft_prc\":\"X7\",\"reb\":\"X8\",\"ast\":\"X9\", \"tov\":\"X10\",\"plusminus\":\"X11\"})\ndf.head()",
"_____no_output_____"
],
[
"# test train split\n# linear regression (sklearn)\n# coefficients/weights",
"_____no_output_____"
],
[
"X = df.drop(columns=['y'])\ny = df['y']",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)",
"_____no_output_____"
],
[
"model = LinearRegression(normalize=True)",
"_____no_output_____"
],
[
"model.fit(X_train, y_train)",
"_____no_output_____"
],
[
"model.coef_",
"_____no_output_____"
],
[
"stat_model = sm.OLS(y,X)\nstat_result = stat_model.fit()\nprint(stat_result.summary())",
" OLS Regression Results \n=======================================================================================\nDep. Variable: y R-squared (uncentered): 0.809\nModel: OLS Adj. R-squared (uncentered): 0.802\nMethod: Least Squares F-statistic: 109.4\nDate: Thu, 09 Jan 2020 Prob (F-statistic): 2.88e-95\nTime: 21:30:53 Log-Likelihood: -5032.0\nNo. Observations: 295 AIC: 1.009e+04\nDf Residuals: 284 BIC: 1.013e+04\nDf Model: 11 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nX1 3.663e+05 8.11e+04 4.518 0.000 2.07e+05 5.26e+05\nX2 -751.7876 2.36e+04 -0.032 0.975 -4.72e+04 4.57e+04\nX3 -1.309e+05 1.07e+05 -1.225 0.221 -3.41e+05 7.93e+04\nX4 9.499e+05 1.49e+05 6.377 0.000 6.57e+05 1.24e+06\nX5 -1.921e+05 5.01e+04 -3.832 0.000 -2.91e+05 -9.34e+04\nX6 -7.953e+04 4.04e+04 -1.967 0.050 -1.59e+05 54.008\nX7 -1.021e+04 3.61e+04 -0.283 0.778 -8.13e+04 6.09e+04\nX8 8.26e+05 2.44e+05 3.388 0.001 3.46e+05 1.31e+06\nX9 1.576e+06 4.4e+05 3.578 0.000 7.09e+05 2.44e+06\nX10 -1.924e+06 1.38e+06 -1.391 0.165 -4.65e+06 7.99e+05\nX11 5.051e+05 1.43e+05 3.520 0.001 2.23e+05 7.88e+05\n==============================================================================\nOmnibus: 6.429 Durbin-Watson: 1.208\nProb(Omnibus): 0.040 Jarque-Bera (JB): 6.881\nSkew: 0.250 Prob(JB): 0.0321\nKurtosis: 3.556 Cond. No. 464.\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
],
[
"# scalar",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb073dc5ded84ced8a93761d9d09d3a068d4abdc | 59,315 | ipynb | Jupyter Notebook | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 53 | 2021-08-28T07:41:49.000Z | 2022-03-09T02:20:17.000Z | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 142 | 2021-07-27T07:23:10.000Z | 2021-08-25T14:57:24.000Z | Natural Language Processing/NLP/TextGenerationGPTNEO1_3B.ipynb | shreepad-nade/ds-seed | 93ddd3b73541f436b6832b94ca09f50872dfaf10 | [
"Apache-2.0"
] | 38 | 2021-07-27T04:54:08.000Z | 2021-08-23T02:27:20.000Z | 35.581884 | 287 | 0.49694 | [
[
[
"# Text Generation using GPT Neo 2.7B",
"_____no_output_____"
],
[
"This Code Template is for Text Generation task which is a problem associated to NLG(Natural Language Generation). In this Project GPT Neo 2.7B is utilized for Text Generation.GPT-Neo 1.3B is a transformer model designed using EleutherAI's replication of the GPT-3 architecture.",
"_____no_output_____"
],
[
"### Required Packages",
"_____no_output_____"
]
],
[
[
"!pip install transformers",
"_____no_output_____"
],
[
"from transformers import pipeline",
"_____no_output_____"
]
],
[
[
"### GPT Neo 1.3B\r\n\r\nGPT-Neo 1.3B is a transformer model designed using EleutherAI's replication of the GPT-3 architecture. GPT-Neo refers to the class of models, while 1.3B represents the number of parameters of this particular pre-trained model.\r\n\r\nYou can use this model directly with a pipeline for text generation. This example generates a different sequence each time it's run:\r\n",
"_____no_output_____"
]
],
[
[
"generator = pipeline('text-generation', model='EleutherAI/gpt-neo-1.3B')",
"_____no_output_____"
]
],
[
[
"### Text Generation",
"_____no_output_____"
]
],
[
[
"generator(\"How was your\", max_length=20, num_return_sequences=5)",
"Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb073dfd62a69920f3c425dcf8b01f98894a1920 | 3,058 | ipynb | Jupyter Notebook | ch08.ipynb | sejin8642/Handson | 790975de4fe4fa3d7086ddccada426183fe39af1 | [
"MIT"
] | null | null | null | ch08.ipynb | sejin8642/Handson | 790975de4fe4fa3d7086ddccada426183fe39af1 | [
"MIT"
] | null | null | null | ch08.ipynb | sejin8642/Handson | 790975de4fe4fa3d7086ddccada426183fe39af1 | [
"MIT"
] | null | null | null | 35.149425 | 402 | 0.661871 | [
[
[
"Many Machine Learning problems involve thousands or even millions of features for each training instance. Not only do all these features make training extremely slow, but they can also make it much harder to find a good solution, as we will see. This problem is often referred to as the *curse of dimensionality*.",
"_____no_output_____"
],
[
"Many dimensionality reduction algorithms work by modeling the manifold on which the training instances lie; this is called *Manifold Learning*. It relies on the *manifold assumption*, also called the *manifold hypothesis*, which holds that most real-world high-dimensional datasets lie close to a much lower-dimensional manifold. This assumption is very often empirically observed.",
"_____no_output_____"
],
[
"*Principal component analysis* (PCA) is the process of computing the principal components and using them to perform a change of basis on the data, sometimes using only the first few principal components and ignoring the rest.",
"_____no_output_____"
],
[
"You can use *SIngular Value Decomposition* (SVD) to find the principal components of a training set.\n\n$A = USV^{T}$\n\nU is an $m \\times n$ matrix, and $S$ and $V$ are $n \\times n$ matrices.",
"_____no_output_____"
],
[
"The mean squared distance between the original data and the reconstructed data (compressed and then decompressed) is called the *reconstruction error*.",
"_____no_output_____"
],
[
"*Locally Linear Embedding* (LLE) 8 is another powerful *nonlinear dimensionality reduction* (NLDR) technique. It is a Manifold Learning technique that does not rely on projections. In a nutshell, LLE works by first measuring how each training instance linearly relates to its closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where these local\nrelationships are best preserved (more details shortly). This approach makes it particularly good at unrolling twisted manifolds, especially when there is not too much noise.",
"_____no_output_____"
],
[
"Check out pg 231 and 232 for more details of LLE.",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb07417d88ab53e43dda24f67993a891e3b9d4b2 | 611,637 | ipynb | Jupyter Notebook | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml | 62e4b7f08c0d1ab5bd5360e959933b26edb70b47 | [
"MIT"
] | 39 | 2020-12-24T03:25:36.000Z | 2022-03-26T11:21:18.000Z | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml | 62e4b7f08c0d1ab5bd5360e959933b26edb70b47 | [
"MIT"
] | null | null | null | notebooks/OCR_from_Images_with_Transformers.ipynb | eugenesiow/practical-ml | 62e4b7f08c0d1ab5bd5360e959933b26edb70b47 | [
"MIT"
] | 9 | 2020-12-24T03:25:37.000Z | 2022-03-25T01:36:03.000Z | 204.972185 | 366,638 | 0.8838 | [
[
[
"# OCR (Optical Character Recognition) from Images with Transformers\n\n---\n\n[Github](https://github.com/eugenesiow/practical-ml/) | More Notebooks @ [eugenesiow/practical-ml](https://github.com/eugenesiow/practical-ml)\n\n---",
"_____no_output_____"
],
[
"Notebook to recognise text automaticaly from an input image with either handwritten or printed text.\n\n[Optical Character Recognition](https://paperswithcode.com/task/optical-character-recognition) is the task of converting images of typed, handwritten or printed text into machine-encoded text, whether from a scanned document, a photo of a document, a scene-photo (for example the text on signs and billboards in a landscape photo, license plates in cars...) or from subtitle text superimposed on an image (for example: from a television broadcast).\n\nThe [transformer models used](https://malaya-speech.readthedocs.io/en/latest/tts-singlish.html) are from Microsoft's TrOCR. The TrOCR models are encoder-decoder models, consisting of an image Transformer as encoder, and a text Transformer as decoder. We utilise the versions hosted on [huggingface.co](https://huggingface.co/models?search=microsoft/trocr) and use the awesome transformers library, for longevity and simplicity.\n\nThe notebook is structured as follows:\n* Setting up the Environment\n* Using the Model (Running Inference)",
"_____no_output_____"
],
[
"# Setting up the Environment",
"_____no_output_____"
],
[
"#### Dependencies and Runtime\n\nIf you're running this notebook in Google Colab, most of the dependencies are already installed and we don't need the GPU for this particular example. \n\nIf you decide to run this on many (>thousands) images and want the inference to go faster though, you can select `Runtime` > `Change Runtime Type` from the menubar. Ensure that `GPU` is selected as the `Hardware accelerator`.",
"_____no_output_____"
],
[
"We need to install huggingface `transformers` for this example to run, so execute the command below to setup the dependencies. We use the version compiled directly from the latest source (at the time of writing this is the only way to access the transforemrs TrOCR model code).",
"_____no_output_____"
]
],
[
[
"!pip install -q git+https://github.com/huggingface/transformers.git",
" Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n\u001b[K |████████████████████████████████| 3.3 MB 5.1 MB/s \n\u001b[K |████████████████████████████████| 596 kB 58.0 MB/s \n\u001b[K |████████████████████████████████| 895 kB 35.8 MB/s \n\u001b[K |████████████████████████████████| 56 kB 4.4 MB/s \n\u001b[?25h Building wheel for transformers (PEP 517) ... \u001b[?25l\u001b[?25hdone\n"
]
],
[
[
"# Using the Model (Running Inference)",
"_____no_output_____"
],
[
"Let's define a function for us to get images from the web. We execute this function to download an image with a line of handwritten text and display it.",
"_____no_output_____"
]
],
[
[
"import requests\nfrom IPython.display import display\nfrom PIL import Image\n\ndef show_image(url):\n img = Image.open(requests.get(url, stream=True).raw).convert(\"RGB\")\n display(img)\n return img\n\nhandwriting1 = show_image('https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg')",
"_____no_output_____"
]
],
[
[
"Now we want to load the model to recognise handwritten text.\n\nSpecifically we are running the following steps:\n\n* Load the processor, `TrOCRProcessor`, which processes our input image and converts it into a sequence of fixed-size patches (resolution 16x16), which are linearly embedded. The processor also adds absolute position embeddings and this sequence is fed to the layers of the Transformer encoder.\n* Load the model, `VisionEncoderDecoderModel`, which consists of the image encoder and the text decoder.\n* Define `ocr_image` function - We define the function for inferencing which takes our `src_img`, the input image we have downloaded. It will then run both the processor and the model inference and produce the output OCR text that has been recognised from the image.",
"_____no_output_____"
]
],
[
[
"import transformers\nfrom transformers import TrOCRProcessor, VisionEncoderDecoderModel\n\nprocessor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-handwritten')\nmodel = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-handwritten')\n\ndef ocr_image(src_img):\n pixel_values = processor(images=src_img, return_tensors=\"pt\").pixel_values\n generated_ids = model.generate(pixel_values)\n return processor.batch_decode(generated_ids, skip_special_tokens=True)[0]",
"_____no_output_____"
]
],
[
[
"We now run our `ocr_image` function on the line of handwritten text in the image we have downloaded previously (and stored in `handwriting1`).",
"_____no_output_____"
]
],
[
[
"ocr_image(handwriting1)",
"_____no_output_____"
]
],
[
[
"Lets try on another image with handwritten text.",
"_____no_output_____"
]
],
[
[
"ocr_image(show_image('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoolxi9yWGAT5SLZShv8vVd0bz47UWRzQC19fDTeE8GmGv_Rn-PCF1pP1rrUx8kOjA4gg&usqp=CAU'))",
"_____no_output_____"
],
[
"import transformers\nfrom transformers import TrOCRProcessor, VisionEncoderDecoderModel\n\nprint_processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-printed')\nprint_model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-printed')\n\ndef ocr_print_image(src_img):\n pixel_values = print_processor(images=src_img, return_tensors=\"pt\").pixel_values\n generated_ids = print_model.generate(pixel_values)\n return print_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]",
"_____no_output_____"
]
],
[
[
"We download an image with noisy printed text, a scanned receipt.",
"_____no_output_____"
]
],
[
[
"receipt = show_image('https://github.com/zzzDavid/ICDAR-2019-SROIE/raw/master/data/img/000.jpg')",
"_____no_output_____"
]
],
[
[
"As the model processes a line of text, we crop the image to include on of the lines of text in the receipt and send it to our model.",
"_____no_output_____"
]
],
[
[
"receipt_crop = receipt.crop((0, 80, receipt.size[0], 110))\ndisplay(receipt_crop)\nocr_print_image(receipt_crop)",
"_____no_output_____"
]
],
[
[
"More Notebooks @ [eugenesiow/practical-ml](https://github.com/eugenesiow/practical-ml) and do star or drop us some feedback on how to improve the notebooks on the [Github repo](https://github.com/eugenesiow/practical-ml/).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb07470f80a61825474f8ca2ba8f23e9dfdd91f1 | 7,908 | ipynb | Jupyter Notebook | notebook/probability.ipynb | kberkey/ccal | 92aa8372997dccec2908928f71a11b6c8327d7aa | [
"MIT"
] | null | null | null | notebook/probability.ipynb | kberkey/ccal | 92aa8372997dccec2908928f71a11b6c8327d7aa | [
"MIT"
] | null | null | null | notebook/probability.ipynb | kberkey/ccal | 92aa8372997dccec2908928f71a11b6c8327d7aa | [
"MIT"
] | null | null | null | 24.946372 | 93 | 0.489757 | [
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport plotly as pl",
"_____no_output_____"
],
[
"sys.path.insert(0, \"..\")\n\nimport ccal\n\nnp.random.random(20121020)\n\npl.offline.init_notebook_mode(connected=True)",
"_____no_output_____"
],
[
"df = pd.read_table(\"titanic.tsv\", index_col=0)\n\ndf = df[[\"sex\", \"age\", \"fare\", \"survived\"]].dropna()\n\ndf",
"_____no_output_____"
],
[
"sys.path.insert(0, \"../../nd_array\")\n\ng = np.asarray(df[\"sex\"] == \"male\", dtype=int)\n\ng_name = \"Gender\"\n\na = np.asarray(df[\"age\"])\n\na_name = \"Age\"\n\nf = ccal.log_nd_array(\n df[\"fare\"].values, shift_as_necessary_to_achieve_min_before_logging=\"0<\"\n)\n\nf_name = \"Fare\"\n\ns = np.asarray(df[\"survived\"])\n\ns_name = \"Survival\"\n\nccal.plot_distributions(\n (g, a, f, s),\n names=(g_name, a_name, f_name, s_name),\n title=\"Variable Distributions\",\n xaxis_title=\"Variable Value\",\n)",
"_____no_output_____"
],
[
"p_s1 = (s == 1).sum() / s.size\n\np_s1",
"_____no_output_____"
],
[
"grid_size = 32",
"_____no_output_____"
],
[
"p_s__g, p_s1__g = ccal.infer(\n (g, s), grid_size=grid_size, target=1, names=(g_name, s_name)\n)\n\np_s__a, p_s1__a = ccal.infer(\n (a, s), grid_size=grid_size, target=1, names=(a_name, s_name)\n)\n\np_s__f, p_s1__f = ccal.infer(\n (f, s), grid_size=grid_size, target=1, names=(f_name, s_name)\n)",
"_____no_output_____"
],
[
"p_s__a_f, p_s1__a_f = ccal.infer(\n (a, f, s), grid_size=grid_size, target=1, names=(a_name, f_name, s_name)\n)\n\np_s__a_f_naive, p_s1__a_f_naive = ccal.infer_assuming_independence(\n (a, f, s), grid_size=grid_size, target=1, names=(a_name, f_name, s_name)\n)",
"_____no_output_____"
],
[
"from sklearn.metrics import auc, roc_curve\n\nmaths = (\n \"P(S = 1 | G)\",\n \"P(S = 1 | A)\",\n \"P(S = 1 | F)\",\n \"P(S = 1 | A, F)\",\n \"P(S = 1 | A, F) (naive)\",\n)\n\nmath_roc = {math: {} for math in maths}\n\nfor math, p_s1__v, vs in zip(\n maths,\n (p_s1__g, p_s1__a, p_s1__f, p_s1__a_f, p_s1__a_f_naive),\n ((g,), (a,), (f,), (a, f), (a, f)),\n):\n\n p_s1__vv = np.full(s.size, np.nan)\n\n for i in range(s.size):\n\n coordinate = [\n [np.argmin(abs(np.linspace(v.min(), v.max(), grid_size) - v[i]))]\n for v in vs\n ]\n\n p_s1__vv[i] = p_s1__v[coordinate]\n\n fpr, tpr, t = roc_curve(s, ccal.normalize_nd_array(p_s1__vv, None, \"0-1\"))\n\n math_roc[math][\"fpr\"] = fpr\n\n math_roc[math][\"tpr\"] = tpr\n\n auc_ = auc(fpr, tpr)\n\n math_roc[math][\"auc\"] = auc_\n\n n_permutation_for_roc = 1000\n\n permuting_aucs = np.full(n_permutation_for_roc, np.nan)\n\n permuting_s = s.copy()\n\n for i in range(n_permutation_for_roc):\n\n np.random.shuffle(permuting_s)\n\n permuting_fpr, permuting_tpr, permuting_t = roc_curve(permuting_s, p_s1__vv)\n\n permuting_aucs[i] = auc(permuting_fpr, permuting_tpr)\n\n math_roc[math][\"p-value\"] = ccal.compute_empirical_p_value(\n auc_, permuting_aucs, \"great\"\n )",
"_____no_output_____"
],
[
"ccal.plot_bayesian_nomogram(\n s, 1, 0, grid_size, (p_s__g, p_s__a, p_s__f), (g_name, a_name, f_name)\n)",
"_____no_output_____"
],
[
"random_roc = np.linspace(0, 1, 16)\n\nccal.plot_points(\n (random_roc,) + tuple(math_roc[math][\"fpr\"] for math in maths),\n (random_roc,) + tuple(math_roc[math][\"tpr\"] for math in maths),\n names=(\"Random ROC\",)\n + tuple(\n \"{} | {:0.3f} | {:0.1e}\".format(\n math, math_roc[math][\"auc\"], math_roc[math][\"p-value\"]\n )\n for math in maths\n ),\n modes=(\"markers\",) + (\"markers + lines\",) * len(maths),\n title=\"ROC: G={}, A={}, F={}\".format(g_name, a_name, f_name),\n xaxis_title=\"False Positive Rate\",\n yaxis_title=\"True Positive Rate\",\n legend_orientation=\"h\",\n)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb0748f927da05a18e8008282f1df7d7501d24fa | 16,211 | ipynb | Jupyter Notebook | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels | c28e6479ace0f0965001c55fb652b2a431bbd158 | [
"BSD-3-Clause"
] | null | null | null | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels | c28e6479ace0f0965001c55fb652b2a431bbd158 | [
"BSD-3-Clause"
] | null | null | null | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels | c28e6479ace0f0965001c55fb652b2a431bbd158 | [
"BSD-3-Clause"
] | null | null | null | 29.104129 | 411 | 0.583924 | [
[
[
"# Regression Plots",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"from statsmodels.compat import lzip\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\n\nplt.rc(\"figure\", figsize=(16,8))\nplt.rc(\"font\", size=14)",
"_____no_output_____"
]
],
[
[
"## Duncan's Prestige Dataset",
"_____no_output_____"
],
[
"### Load the Data",
"_____no_output_____"
],
[
"We can use a utility function to load any R dataset available from the great <a href=\"https://vincentarelbundock.github.io/Rdatasets/\">Rdatasets package</a>.",
"_____no_output_____"
]
],
[
[
"prestige = sm.datasets.get_rdataset(\"Duncan\", \"carData\", cache=True).data",
"_____no_output_____"
],
[
"prestige.head()",
"_____no_output_____"
],
[
"prestige_model = ols(\"prestige ~ income + education\", data=prestige).fit()",
"_____no_output_____"
],
[
"print(prestige_model.summary())",
"_____no_output_____"
]
],
[
[
"### Influence plots",
"_____no_output_____"
],
[
"Influence plots show the (externally) studentized residuals vs. the leverage of each observation as measured by the hat matrix.\n\nExternally studentized residuals are residuals that are scaled by their standard deviation where \n\n$$var(\\hat{\\epsilon}_i)=\\hat{\\sigma}^2_i(1-h_{ii})$$\n\nwith\n\n$$\\hat{\\sigma}^2_i=\\frac{1}{n - p - 1 \\;\\;}\\sum_{j}^{n}\\;\\;\\;\\forall \\;\\;\\; j \\neq i$$\n\n$n$ is the number of observations and $p$ is the number of regressors. $h_{ii}$ is the $i$-th diagonal element of the hat matrix\n\n$$H=X(X^{\\;\\prime}X)^{-1}X^{\\;\\prime}$$\n\nThe influence of each point can be visualized by the criterion keyword argument. Options are Cook's distance and DFFITS, two measures of influence.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.influence_plot(prestige_model, criterion=\"cooks\")\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"As you can see there are a few worrisome observations. Both contractor and reporter have low leverage but a large residual. <br />\nRR.engineer has small residual and large leverage. Conductor and minister have both high leverage and large residuals, and, <br />\ntherefore, large influence.",
"_____no_output_____"
],
[
"### Partial Regression Plots (Duncan)",
"_____no_output_____"
],
[
"Since we are doing multivariate regressions, we cannot just look at individual bivariate plots to discern relationships. <br />\nInstead, we want to look at the relationship of the dependent variable and independent variables conditional on the other <br />\nindependent variables. We can do this through using partial regression plots, otherwise known as added variable plots. <br />\n\nIn a partial regression plot, to discern the relationship between the response variable and the $k$-th variable, we compute <br />\nthe residuals by regressing the response variable versus the independent variables excluding $X_k$. We can denote this by <br />\n$X_{\\sim k}$. We then compute the residuals by regressing $X_k$ on $X_{\\sim k}$. The partial regression plot is the plot <br />\nof the former versus the latter residuals. <br />\n\nThe notable points of this plot are that the fitted line has slope $\\beta_k$ and intercept zero. The residuals of this plot <br />\nare the same as those of the least squares fit of the original model with full $X$. You can discern the effects of the <br />\nindividual data values on the estimation of a coefficient easily. If obs_labels is True, then these points are annotated <br />\nwith their observation label. You can also see the violation of underlying assumptions such as homoskedasticity and <br />\nlinearity.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_partregress(\"prestige\", \"income\", [\"income\", \"education\"], data=prestige)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
],
[
"fig = sm.graphics.plot_partregress(\"prestige\", \"income\", [\"education\"], data=prestige)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"As you can see the partial regression plot confirms the influence of conductor, minister, and RR.engineer on the partial relationship between income and prestige. The cases greatly decrease the effect of income on prestige. Dropping these cases confirms this.",
"_____no_output_____"
]
],
[
[
"subset = ~prestige.index.isin([\"conductor\", \"RR.engineer\", \"minister\"])\nprestige_model2 = ols(\"prestige ~ income + education\", data=prestige, subset=subset).fit()\nprint(prestige_model2.summary())",
"_____no_output_____"
]
],
[
[
"For a quick check of all the regressors, you can use plot_partregress_grid. These plots will not label the <br />\npoints, but you can use them to identify problems and then use plot_partregress to get more information.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_partregress_grid(prestige_model)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Component-Component plus Residual (CCPR) Plots",
"_____no_output_____"
],
[
"The CCPR plot provides a way to judge the effect of one regressor on the <br />\nresponse variable by taking into account the effects of the other <br />\nindependent variables. The partial residuals plot is defined as <br />\n$\\text{Residuals} + B_iX_i \\text{ }\\text{ }$ versus $X_i$. The component adds $B_iX_i$ versus <br />\n$X_i$ to show where the fitted line would lie. Care should be taken if $X_i$ <br />\nis highly correlated with any of the other independent variables. If this <br />\nis the case, the variance evident in the plot will be an underestimate of <br />\nthe true variance.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_ccpr(prestige_model, \"education\")\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"As you can see the relationship between the variation in prestige explained by education conditional on income seems to be linear, though you can see there are some observations that are exerting considerable influence on the relationship. We can quickly look at more than one variable by using plot_ccpr_grid.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_ccpr_grid(prestige_model)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Single Variable Regression Diagnostics",
"_____no_output_____"
],
[
"The plot_regress_exog function is a convenience function that gives a 2x2 plot containing the dependent variable and fitted values with confidence intervals vs. the independent variable chosen, the residuals of the model vs. the chosen independent variable, a partial regression plot, and a CCPR plot. This function can be used for quickly checking modeling assumptions with respect to a single regressor.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_regress_exog(prestige_model, \"education\")\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Fit Plot",
"_____no_output_____"
],
[
"The plot_fit function plots the fitted values versus a chosen independent variable. It includes prediction confidence intervals and optionally plots the true dependent variable.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_fit(prestige_model, \"education\")\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"## Statewide Crime 2009 Dataset",
"_____no_output_____"
],
[
"Compare the following to http://www.ats.ucla.edu/stat/stata/webbooks/reg/chapter4/statareg_self_assessment_answers4.htm\n\nThough the data here is not the same as in that example. You could run that example by uncommenting the necessary cells below.",
"_____no_output_____"
]
],
[
[
"#dta = pd.read_csv(\"http://www.stat.ufl.edu/~aa/social/csv_files/statewide-crime-2.csv\")\n#dta = dta.set_index(\"State\", inplace=True).dropna()\n#dta.rename(columns={\"VR\" : \"crime\",\n# \"MR\" : \"murder\",\n# \"M\" : \"pctmetro\",\n# \"W\" : \"pctwhite\",\n# \"H\" : \"pcths\",\n# \"P\" : \"poverty\",\n# \"S\" : \"single\"\n# }, inplace=True)\n#\n#crime_model = ols(\"murder ~ pctmetro + poverty + pcths + single\", data=dta).fit()",
"_____no_output_____"
],
[
"dta = sm.datasets.statecrime.load_pandas().data",
"_____no_output_____"
],
[
"crime_model = ols(\"murder ~ urban + poverty + hs_grad + single\", data=dta).fit()\nprint(crime_model.summary())",
"_____no_output_____"
]
],
[
[
"### Partial Regression Plots (Crime Data)",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_partregress_grid(crime_model)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
],
[
"fig = sm.graphics.plot_partregress(\"murder\", \"hs_grad\", [\"urban\", \"poverty\", \"single\"], data=dta)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Leverage-Resid<sup>2</sup> Plot",
"_____no_output_____"
],
[
"Closely related to the influence_plot is the leverage-resid<sup>2</sup> plot.",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.plot_leverage_resid2(crime_model)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Influence Plot",
"_____no_output_____"
]
],
[
[
"fig = sm.graphics.influence_plot(crime_model)\nfig.tight_layout(pad=1.0)",
"_____no_output_____"
]
],
[
[
"### Using robust regression to correct for outliers.",
"_____no_output_____"
],
[
"Part of the problem here in recreating the Stata results is that M-estimators are not robust to leverage points. MM-estimators should do better with this examples.",
"_____no_output_____"
]
],
[
[
"from statsmodels.formula.api import rlm",
"_____no_output_____"
],
[
"rob_crime_model = rlm(\"murder ~ urban + poverty + hs_grad + single\", data=dta, \n M=sm.robust.norms.TukeyBiweight(3)).fit(conv=\"weights\")\nprint(rob_crime_model.summary())",
"_____no_output_____"
],
[
"#rob_crime_model = rlm(\"murder ~ pctmetro + poverty + pcths + single\", data=dta, M=sm.robust.norms.TukeyBiweight()).fit(conv=\"weights\")\n#print(rob_crime_model.summary())",
"_____no_output_____"
]
],
[
[
"There is not yet an influence diagnostics method as part of RLM, but we can recreate them. (This depends on the status of [issue #888](https://github.com/statsmodels/statsmodels/issues/808))",
"_____no_output_____"
]
],
[
[
"weights = rob_crime_model.weights\nidx = weights > 0\nX = rob_crime_model.model.exog[idx.values]\nww = weights[idx] / weights[idx].mean()\nhat_matrix_diag = ww*(X*np.linalg.pinv(X).T).sum(1)\nresid = rob_crime_model.resid\nresid2 = resid**2\nresid2 /= resid2.sum()\nnobs = int(idx.sum())\nhm = hat_matrix_diag.mean()\nrm = resid2.mean()",
"_____no_output_____"
],
[
"from statsmodels.graphics import utils\nfig, ax = plt.subplots(figsize=(16,8))\nax.plot(resid2[idx], hat_matrix_diag, 'o')\nax = utils.annotate_axes(range(nobs), labels=rob_crime_model.model.data.row_labels[idx], \n points=lzip(resid2[idx], hat_matrix_diag), offset_points=[(-5,5)]*nobs,\n size=\"large\", ax=ax)\nax.set_xlabel(\"resid2\")\nax.set_ylabel(\"leverage\")\nylim = ax.get_ylim()\nax.vlines(rm, *ylim)\nxlim = ax.get_xlim()\nax.hlines(hm, *xlim)\nax.margins(0,0)",
"_____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",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb074c3785b5bd75134534b64cc84e56e8d354e1 | 637,598 | ipynb | Jupyter Notebook | src/ssd512_train_da_losses-Copy1.ipynb | zhiqiangwan/LLFDA | 5cff3c60d87be917728d9b86782c96b1cc8d1d0e | [
"Apache-2.0"
] | null | null | null | src/ssd512_train_da_losses-Copy1.ipynb | zhiqiangwan/LLFDA | 5cff3c60d87be917728d9b86782c96b1cc8d1d0e | [
"Apache-2.0"
] | null | null | null | src/ssd512_train_da_losses-Copy1.ipynb | zhiqiangwan/LLFDA | 5cff3c60d87be917728d9b86782c96b1cc8d1d0e | [
"Apache-2.0"
] | null | null | null | 460.692197 | 296,364 | 0.914551 | [
[
[
"import sys\nsys.path.append('../')\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\nimport glob\n\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger, TensorBoard\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom models.da_ssd512_other_loss_metrics import ssd_512\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_geometric_ops import Resize\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation, SSDDataAugmentation_Siamese\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\n\n\nimg_height = 512 # Height of the model input images\nimg_width = 512 # Width of the model input images\nimg_channels = 3 # Number of color channels of the model input images\nmean_color = [123, 117, 104] # Per-channel mean of images. Do not change if use any of the pre-trained weights.\n# The color channel order in the original SSD is BGR,\n# so we'll have the model reverse the color channel order of the input images.\nswap_channels = [2, 1, 0]\n# The anchor box scaling factors used in the original SSD512 for the Pascal VOC datasets\n# scales_pascal =\n# The anchor box scaling factors used in the original SSD512 for the MS COCO datasets\nscales_coco = [0.07, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05]\nscales = scales_coco\naspect_ratios = [[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]] # The anchor box aspect ratios used in the original SSD512; the order matters\ntwo_boxes_for_ar1 = True\nsteps = [8, 16, 32, 64, 128, 256, 512] # Space between two adjacent anchor box center points for each predictor layer.\n# The offsets of the first anchor box center points from the top and left borders of the image\n# as a fraction of the step size for each predictor layer.\noffsets = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]\nclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\n# The variances by which the encoded target coordinates are divided as in the original implementation\nvariances = [0.1, 0.1, 0.2, 0.2]\nnormalize_coords = True\nModel_Build = 'New_Model' # 'Load_Model'\nOptimizer_Type = 'SGD' # 'Adam' #\n# Different batch_size will have different prediction loss.\nbatch_size = 8 # Change the batch size if you like, or if you run into GPU memory issues.\n# alpha_distance = 0.0001 # Coefficient for the distance between the source and target feature maps.\nloss_weights = [0.0005, 0.0005, 0.0] + [1.0]\n\n# 'SIM10K_to_VOC12_resize_400_800' # 'City_to_foggy0_01_resize_400_800' \nDatasetName = 'SIM10K_to_VOC07_resize_400_800' # 'SIM10K_to_City_resize_400_800' # # \nprocessed_dataset_path = './processed_dataset_h5/' + DatasetName\nif not os.path.exists(processed_dataset_path):\n os.makedirs(processed_dataset_path)\n\nif len(glob.glob(os.path.join(processed_dataset_path, '*.h5'))):\n Dataset_Build = 'Load_Dataset'\nelse:\n Dataset_Build = 'New_Dataset'\n\n# Define model callbacks.\ncheckpoint_path = '../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005'\n# checkpoint_path = '../trained_weights/denug'\nif not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n \nif DatasetName == 'SIM10K_to_VOC12_resize_400_800':\n resize_image_to = (400, 800)\n # The directories that contain the images.\n train_source_images_dir = '../../datasets/SIM10K/JPEGImages'\n train_target_images_dir = '../../datasets/VOCdevkit/VOC2012/JPEGImages'\n test_target_images_dir = '../../datasets/VOCdevkit/VOC2012/JPEGImages'\n\n # The directories that contain the annotations.\n train_annotation_dir = '../../datasets/SIM10K/Annotations'\n test_annotation_dir = '../../datasets/VOCdevkit/VOC2012/Annotations'\n\n # The paths to the image sets.\n train_source_image_set_filename = '../../datasets/SIM10K/ImageSets/Main/trainval10k.txt'\n # The trainset of VOC which has 'car' object is used as train_target.\n train_target_image_set_filename = '../../datasets/VOCdevkit/VOC2012_CAR/ImageSets/Main/train_target.txt'\n # The valset of VOC which has 'car' object is used as test.\n test_target_image_set_filename = '../../datasets/VOCdevkit/VOC2012_CAR/ImageSets/Main/test.txt'\n\n classes = ['background', 'car'] # Our model will produce predictions for these classes.\n train_classes = ['background', 'car', 'motorbike', 'person'] # The train_source dataset contains these classes.\n train_include_classes = [train_classes.index(one_class) for one_class in classes[1:]]\n # The test_target dataset contains these classes.\n val_classes = ['background', 'car',\n 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'cat',\n 'chair', 'cow', 'diningtable', 'dog',\n 'horse', 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\n val_include_classes = [val_classes.index(one_class) for one_class in classes[1:]]\n # Number of positive classes, 8 for domain Cityscapes, 20 for Pascal VOC, 80 for MS COCO, 1 for SIM10K\n n_classes = len(classes) - 1\n \nelif DatasetName == 'SIM10K_to_VOC07_resize_400_800':\n resize_image_to = (400, 800)\n # The directories that contain the images.\n train_source_images_dir = '../../datasets/SIM10K/JPEGImages'\n train_target_images_dir = '../../datasets/VOCdevkit/VOC2007/JPEGImages'\n test_target_images_dir = '../../datasets/VOCdevkit/VOC2007/JPEGImages'\n\n # The directories that contain the annotations.\n train_annotation_dir = '../../datasets/SIM10K/Annotations'\n test_annotation_dir = '../../datasets/VOCdevkit/VOC2007/Annotations'\n\n # The paths to the image sets.\n train_source_image_set_filename = '../../datasets/SIM10K/ImageSets/Main/trainval10k.txt'\n # The trainset of VOC which has 'car' object is used as train_target.\n train_target_image_set_filename = '../../datasets/VOCdevkit/VOC2007_CAR/ImageSets/Main/train_target.txt'\n # The valset of VOC which has 'car' object is used as test.\n test_target_image_set_filename = '../../datasets/VOCdevkit/VOC2007_CAR/ImageSets/Main/test.txt'\n\n classes = ['background', 'car'] # Our model will produce predictions for these classes.\n train_classes = ['background', 'car', 'motorbike', 'person'] # The train_source dataset contains these classes.\n train_include_classes = [train_classes.index(one_class) for one_class in classes[1:]]\n # The test_target dataset contains these classes.\n val_classes = ['background', 'car',\n 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'cat',\n 'chair', 'cow', 'diningtable', 'dog',\n 'horse', 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\n val_include_classes = [val_classes.index(one_class) for one_class in classes[1:]]\n # Number of positive classes, 8 for domain Cityscapes, 20 for Pascal VOC, 80 for MS COCO, 1 for SIM10K\n n_classes = len(classes) - 1\n\nelif DatasetName == 'SIM10K_to_City_resize_400_800':\n resize_image_to = (400, 800)\n # The directories that contain the images.\n train_source_images_dir = '../../datasets/SIM10K/JPEGImages'\n train_target_images_dir = '../../datasets/Cityscapes/JPEGImages'\n test_target_images_dir = '../../datasets/val_data_for_SIM10K_to_cityscapes/JPEGImages'\n\n # The directories that contain the annotations.\n train_annotation_dir = '../../datasets/SIM10K/Annotations'\n test_annotation_dir = '../../datasets/val_data_for_SIM10K_to_cityscapes/Annotations'\n\n # The paths to the image sets.\n train_source_image_set_filename = '../../datasets/SIM10K/ImageSets/Main/trainval10k.txt'\n train_target_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/train_source.txt'\n test_target_image_set_filename = '../../datasets/val_data_for_SIM10K_to_cityscapes/ImageSets/Main/test.txt'\n\n classes = ['background', 'car'] # Our model will produce predictions for these classes.\n train_classes = ['background', 'car', 'motorbike', 'person'] # The train_source dataset contains these classes.\n train_include_classes = [train_classes.index(one_class) for one_class in classes[1:]]\n # The test_target dataset contains these classes.\n val_classes = ['background', 'car']\n val_include_classes = 'all'\n # Number of positive classes, 8 for domain Cityscapes, 20 for Pascal VOC, 80 for MS COCO, 1 for SIM10K\n n_classes = len(classes) - 1\n\nelif DatasetName == 'City_to_foggy0_02_resize_400_800':\n resize_image_to = (400, 800)\n # Introduction of PascalVOC: https://arleyzhang.github.io/articles/1dc20586/\n # The directories that contain the images.\n train_source_images_dir = '../../datasets/Cityscapes/JPEGImages'\n train_target_images_dir = '../../datasets/Cityscapes/JPEGImages'\n test_target_images_dir = '../../datasets/Cityscapes/JPEGImages'\n\n # The directories that contain the annotations.\n train_annotation_dir = '../../datasets/Cityscapes/Annotations'\n test_annotation_dir = '../../datasets/Cityscapes/Annotations'\n\n # The paths to the image sets.\n train_source_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/train_source.txt'\n train_target_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/train_target.txt'\n test_target_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/test.txt'\n # Our model will produce predictions for these classes.\n classes = ['background',\n 'person', 'rider', 'car', 'truck',\n 'bus', 'train', 'motorcycle', 'bicycle']\n train_classes = classes\n train_include_classes = 'all'\n val_classes = classes\n val_include_classes = 'all'\n # Number of positive classes, 8 for domain Cityscapes, 20 for Pascal VOC, 80 for MS COCO, 1 for SIM10K\n n_classes = len(classes) - 1\n\nelif DatasetName == 'City_to_foggy0_01_resize_400_800':\n resize_image_to = (400, 800)\n # Introduction of PascalVOC: https://arleyzhang.github.io/articles/1dc20586/\n # The directories that contain the images.\n train_source_images_dir = '../../datasets/Cityscapes/JPEGImages'\n train_target_images_dir = '../../datasets/CITYSCAPES_beta_0_01/JPEGImages'\n test_target_images_dir = '../../datasets/CITYSCAPES_beta_0_01/JPEGImages'\n\n # The directories that contain the annotations.\n train_annotation_dir = '../../datasets/Cityscapes/Annotations'\n test_annotation_dir = '../../datasets/Cityscapes/Annotations'\n\n # The paths to the image sets.\n train_source_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/train_source.txt'\n train_target_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/train_target.txt'\n test_target_image_set_filename = '../../datasets/Cityscapes/ImageSets/Main/test.txt'\n # Our model will produce predictions for these classes.\n classes = ['background',\n 'person', 'rider', 'car', 'truck',\n 'bus', 'train', 'motorcycle', 'bicycle']\n train_classes = classes\n train_include_classes = 'all'\n val_classes = classes\n val_include_classes = 'all'\n # Number of positive classes, 8 for domain Cityscapes, 20 for Pascal VOC, 80 for MS COCO, 1 for SIM10K\n n_classes = len(classes) - 1\n\nelse:\n raise ValueError('Undefined dataset name.')",
"/usr/local/lib/python3.5/dist-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\nUsing TensorFlow backend.\n"
],
[
"if Model_Build == 'New_Model':\n # 1: Build the Keras model.\n\n K.clear_session() # Clear previous models from memory.\n\n import tensorflow as tf\n from keras.backend.tensorflow_backend import set_session\n \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU\n config.log_device_placement = True # to log device placement (on which device the operation ran)\n # (nothing gets printed in Jupyter, only if you run it standalone)\n sess = tf.Session(config=config)\n set_session(sess) # set this TensorFlow session as the default session for Keras\n\n model = ssd_512(image_size=(img_height, img_width, img_channels),\n n_classes=n_classes,\n mode='training',\n l2_regularization=0.0005,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n normalize_coords=normalize_coords,\n subtract_mean=mean_color,\n swap_channels=swap_channels)\n\n # 2: Load some weights into the model.\n\n # TODO: Set the path to the weights you want to load.\n weights_path = '../trained_weights/VGG_ILSVRC_16_layers_fc_reduced.h5'\n\n model.load_weights(weights_path, by_name=True)\n\n # 3: Instantiate an optimizer and the SSD loss function and compile the model.\n # If you want to follow the original Caffe implementation, use the preset SGD\n # optimizer, otherwise I'd recommend the commented-out Adam optimizer.\n\n if Optimizer_Type == 'SGD':\n Optimizer = SGD(lr=0.001, momentum=0.9, decay=0.0, nesterov=False)\n elif Optimizer_Type == 'Adam':\n Optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n else:\n raise ValueError('Undefined Optimizer_Type.')\n\n ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\n model.compile(optimizer=Optimizer, loss={'pool1_GAP_substract': ssd_loss.compute_distance_loss,\n 'pool2_GAP_substract': ssd_loss.compute_distance_loss,\n 'pool3_GAP_substract': ssd_loss.compute_distance_loss_source_only,\n 'predictions': ssd_loss.compute_loss},\n loss_weights={'pool1_GAP_substract': loss_weights[0],\n 'pool2_GAP_substract': loss_weights[1],\n 'pool3_GAP_substract': loss_weights[2],\n 'predictions': loss_weights[3]}) \n \n# if Source_Only:\n# model.compile(optimizer=Optimizer, loss={'pool1_GAP_substract': ssd_loss.compute_distance_loss_source_only,\n# 'pool2_GAP_substract': ssd_loss.compute_distance_loss_source_only,\n# 'pool3_GAP_substract': ssd_loss.compute_distance_loss_source_only,\n# 'predictions': ssd_loss.compute_loss},\n# loss_weights={'pool1_GAP_substract': loss_weights[0],\n# 'pool2_GAP_substract': loss_weights[1],\n# 'pool3_GAP_substract': loss_weights[2],\n# 'predictions': loss_weights[3]})\n# else:\n# model.compile(optimizer=Optimizer, loss={'pool1_GAP_substract': ssd_loss.compute_distance_loss,\n# 'pool2_GAP_substract': ssd_loss.compute_distance_loss,\n# 'pool3_GAP_substract': ssd_loss.compute_distance_loss,\n# 'predictions': ssd_loss.compute_loss},\n# loss_weights={'pool1_GAP_substract': loss_weights[0],\n# 'pool2_GAP_substract': loss_weights[1],\n# 'pool3_GAP_substract': loss_weights[2],\n# 'predictions': loss_weights[3]})\n\nelif Model_Build == 'Load_Model':\n # TODO: Set the path to the `.h5` file of the model to be loaded.\n model_path = '../trained_weights/VGG_ssd300_Cityscapes/epoch-23_loss-5.2110_val_loss-6.7452.h5'\n\n # We need to create an SSDLoss object in order to pass that to the model loader.\n ssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\n K.clear_session() # Clear previous models from memory.\n\n # import tensorflow as tf\n # from keras.backend.tensorflow_backend import set_session\n #\n # config = tf.ConfigProto()\n # config.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU\n # config.log_device_placement = True # to log device placement (on which device the operation ran)\n # # (nothing gets printed in Jupyter, only if you run it standalone)\n # sess = tf.Session(config=config)\n # set_session(sess) # set this TensorFlow session as the default session for Keras\n\n model = load_model(model_path, custom_objects={'AnchorBoxes': AnchorBoxes,\n 'L2Normalization': L2Normalization,\n 'compute_loss': ssd_loss.compute_loss,\n 'compute_distance_loss': ssd_loss.compute_distance_loss})\nelse:\n raise ValueError('Undefined Model_Build. Model_Build should be New_Model or Load_Model')",
"da_loss_metric is MMD\n"
],
[
"if Dataset_Build == 'New_Dataset':\n # 1: Instantiate two `DataGenerator` objects: One for training, one for validation.\n\n # Optional: If you have enough memory, consider loading the images into memory for the reasons explained above.\n\n train_dataset = DataGenerator(dataset='train', load_images_into_memory=False, hdf5_dataset_path=None)\n val_dataset = DataGenerator(dataset='val', load_images_into_memory=False, hdf5_dataset_path=None)\n\n # 2: Parse the image and label lists for the training and validation datasets. This can take a while.\n # images_dirs, image_set_filenames, and annotations_dirs should have the same length\n train_dataset.parse_xml(images_dirs=[train_source_images_dir],\n target_images_dirs=[train_target_images_dir],\n image_set_filenames=[train_source_image_set_filename],\n target_image_set_filenames=[train_target_image_set_filename],\n annotations_dirs=[train_annotation_dir],\n classes=train_classes,\n include_classes=train_include_classes,\n exclude_truncated=False,\n exclude_difficult=False,\n ret=False)\n\n val_dataset.parse_xml(images_dirs=[test_target_images_dir],\n image_set_filenames=[test_target_image_set_filename],\n annotations_dirs=[test_annotation_dir],\n classes=val_classes,\n include_classes=val_include_classes,\n exclude_truncated=False,\n exclude_difficult=True,\n ret=False)\n\n # Optional: Convert the dataset into an HDF5 dataset. This will require more disk space, but will\n # speed up the training. Doing this is not relevant in case you activated the `load_images_into_memory`\n # option in the constructor, because in that cas the images are in memory already anyway. If you don't\n # want to create HDF5 datasets, comment out the subsequent two function calls.\n\n # After create these h5 files, if you have resized the input image, you need to reload these files. Otherwise,\n # the images and the labels will not change.\n\n train_dataset.create_hdf5_dataset(file_path=os.path.join(processed_dataset_path, 'dataset_train.h5'),\n resize=resize_image_to,\n variable_image_size=True,\n verbose=True)\n\n val_dataset.create_hdf5_dataset(file_path=os.path.join(processed_dataset_path, 'dataset_test.h5'),\n resize=False,\n variable_image_size=True,\n verbose=True)\n\n train_dataset = DataGenerator(dataset='train',\n load_images_into_memory=False,\n hdf5_dataset_path=os.path.join(processed_dataset_path, 'dataset_train.h5'),\n filenames=train_source_image_set_filename,\n target_filenames=train_target_image_set_filename,\n filenames_type='text',\n images_dir=train_source_images_dir,\n target_images_dir=train_target_images_dir)\n\n val_dataset = DataGenerator(dataset='val',\n load_images_into_memory=False,\n hdf5_dataset_path=os.path.join(processed_dataset_path, 'dataset_test.h5'),\n filenames=test_target_image_set_filename,\n filenames_type='text',\n images_dir=test_target_images_dir)\n\nelif Dataset_Build == 'Load_Dataset':\n # 1: Instantiate two `DataGenerator` objects: One for training, one for validation.\n\n # Load dataset from the created h5 file.\n train_dataset = DataGenerator(dataset='train',\n load_images_into_memory=False,\n hdf5_dataset_path=os.path.join(processed_dataset_path, 'dataset_train.h5'),\n filenames=train_source_image_set_filename,\n target_filenames=train_target_image_set_filename,\n filenames_type='text',\n images_dir=train_source_images_dir,\n target_images_dir=train_target_images_dir)\n\n val_dataset = DataGenerator(dataset='val',\n load_images_into_memory=False,\n hdf5_dataset_path=os.path.join(processed_dataset_path, 'dataset_test.h5'),\n filenames=test_target_image_set_filename,\n filenames_type='text',\n images_dir=test_target_images_dir)\n\nelse:\n raise ValueError('Undefined Dataset_Build. Dataset_Build should be New_Dataset or Load_Dataset.')",
"Loading source labels: 100%|██████████| 10000/10000 [00:02<00:00, 4579.37it/s]\nLoading source image IDs: 100%|██████████| 10000/10000 [00:00<00:00, 10253.93it/s]\nLoading target image IDs: 100%|██████████| 761/761 [00:00<00:00, 10111.30it/s]\nLoading evaluation-neutrality annotations: 100%|██████████| 10000/10000 [00:01<00:00, 7276.55it/s]\nLoading source labels: 100%|██████████| 775/775 [00:00<00:00, 4142.02it/s]\nLoading source image IDs: 100%|██████████| 775/775 [00:00<00:00, 10693.45it/s]\nLoading target image IDs: 0it [00:00, ?it/s]\nLoading evaluation-neutrality annotations: 100%|██████████| 775/775 [00:00<00:00, 6625.03it/s]\n"
],
[
"# 4: Set the image transformations for pre-processing and data augmentation options.\n\n# For the training generator:\nssd_data_augmentation = SSDDataAugmentation_Siamese(img_height=img_height,\n img_width=img_width)\n\n# For the validation generator:\nconvert_to_3_channels = ConvertTo3Channels()\nresize = Resize(height=img_height, width=img_width)\n\n# 5: Instantiate an encoder that can encode ground truth labels into the format needed by the SSD loss function.\n\n# The encoder constructor needs the spatial dimensions of the model's predictor layers to create the anchor boxes.\npredictor_sizes = [model.get_layer('conv4_3_norm_mbox_conf').output_shape[1:3],\n model.get_layer('fc7_mbox_conf').output_shape[1:3],\n model.get_layer('conv6_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv7_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv8_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv9_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv10_2_mbox_conf').output_shape[1:3]]\n\nssd_input_encoder = SSDInputEncoder(img_height=img_height,\n img_width=img_width,\n n_classes=n_classes,\n predictor_sizes=predictor_sizes,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n matching_type='multi',\n pos_iou_threshold=0.5,\n neg_iou_limit=0.5,\n normalize_coords=normalize_coords)\n\n# 6: Create the generator handles that will be passed to Keras' `fit_generator()` function.\n# The input image and label are first processed by transformations. Then, the label will be further encoded by\n# ssd_input_encoder. The encoded labels are classId and offset to each anchor box.\ntrain_generator = train_dataset.generate(batch_size=batch_size,\n shuffle=True,\n transformations=[ssd_data_augmentation],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\nval_generator = val_dataset.generate(batch_size=batch_size,\n shuffle=False,\n transformations=[convert_to_3_channels,\n resize],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\n# Get the number of samples in the training and validations datasets.\ntrain_dataset_size = train_dataset.get_dataset_size()\nval_dataset_size = val_dataset.get_dataset_size()\n\nprint(\"Number of images in the training dataset:\\t{:>6}\".format(train_dataset_size))\nprint(\"Number of images in the validation dataset:\\t{:>6}\".format(val_dataset_size))",
"Number of images in the training dataset:\t 10000\nNumber of images in the validation dataset:\t 775\n"
],
[
"def lr_schedule(epoch):\n if epoch < 2:\n return 0.0005\n elif epoch < 50:\n return 0.001\n elif epoch < 70:\n return 0.0001\n else:\n return 0.00001\n\n# def lr_schedule(epoch):\n# if epoch < 50:\n# return 0.001\n# elif epoch < 60:\n# return 0.0001\n# else:\n# return 0.00001\n\n# TODO: Set the filepath under which you want to save the model.\nmodel_checkpoint = ModelCheckpoint(filepath=os.path.join(checkpoint_path, 'epoch-{epoch:02d}_loss-{loss:.4f}_val_loss-{val_loss:.4f}.h5'),\n monitor='val_loss',\n verbose=1,\n save_best_only=False,\n save_weights_only=True,\n mode='auto',\n period=1)\n\n# model_checkpoint.best to the best validation loss from the previous training\n# model_checkpoint.best = 4.83704\n\ncsv_logger = CSVLogger(filename=os.path.join(checkpoint_path, 'source_only_run2_training_log.csv'),\n separator=',',\n append=True)\n\nlearning_rate_scheduler = LearningRateScheduler(schedule=lr_schedule,\n verbose=1)\n\nterminate_on_nan = TerminateOnNaN()\n\nTensorBoard_monitor = TensorBoard(log_dir=checkpoint_path)\n\ncallbacks = [model_checkpoint,\n csv_logger,\n learning_rate_scheduler,\n terminate_on_nan,\n TensorBoard_monitor]",
"_____no_output_____"
],
[
"initial_epoch = 0\nfinal_epoch = 80\nsteps_per_epoch = 1000\n\nhistory = model.fit_generator(generator=train_generator,\n steps_per_epoch=steps_per_epoch,\n epochs=final_epoch,\n callbacks=callbacks,\n validation_data=val_generator,\n validation_steps=ceil(val_dataset_size/batch_size),\n initial_epoch=initial_epoch)",
"Epoch 1/80\n\nEpoch 00001: LearningRateScheduler setting learning rate to 0.0005.\n1000/1000 [==============================] - 764s 764ms/step - loss: 8.0732 - pool1_GAP_substract_loss: 4.3829 - pool2_GAP_substract_loss: 4.5753 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 4.7802 - val_loss: 7.5404 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 4.2660\n\nEpoch 00001: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-01_loss-8.0738_val_loss-7.5404.h5\nEpoch 2/80\n\nEpoch 00002: LearningRateScheduler setting learning rate to 0.0005.\n1000/1000 [==============================] - 751s 751ms/step - loss: 6.6101 - pool1_GAP_substract_loss: 4.3794 - pool2_GAP_substract_loss: 4.5548 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 3.3455 - val_loss: 7.4451 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 4.1993\n\nEpoch 00002: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-02_loss-6.6100_val_loss-7.4451.h5\nEpoch 3/80\n\nEpoch 00003: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 751s 751ms/step - loss: 6.5642 - pool1_GAP_substract_loss: 4.3688 - pool2_GAP_substract_loss: 4.5233 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 3.3395 - val_loss: 7.2254 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 4.0314\n\nEpoch 00003: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-03_loss-6.5644_val_loss-7.2254.h5\nEpoch 4/80\n\nEpoch 00004: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 755s 755ms/step - loss: 6.1032 - pool1_GAP_substract_loss: 4.3628 - pool2_GAP_substract_loss: 4.4990 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.9310 - val_loss: 7.1541 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 4.0126\n\nEpoch 00004: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-04_loss-6.1029_val_loss-7.1541.h5\nEpoch 5/80\n\nEpoch 00005: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 751s 751ms/step - loss: 5.8576 - pool1_GAP_substract_loss: 4.3661 - pool2_GAP_substract_loss: 4.4866 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.7376 - val_loss: 7.0706 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.9809\n\nEpoch 00005: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-05_loss-5.8575_val_loss-7.0706.h5\nEpoch 6/80\n\nEpoch 00006: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 750s 750ms/step - loss: 5.6307 - pool1_GAP_substract_loss: 4.3605 - pool2_GAP_substract_loss: 4.4752 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.5623 - val_loss: 6.8358 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.7975\n\nEpoch 00006: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-06_loss-5.6309_val_loss-6.8358.h5\nEpoch 7/80\n\nEpoch 00007: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 750s 750ms/step - loss: 5.4896 - pool1_GAP_substract_loss: 4.3493 - pool2_GAP_substract_loss: 4.4602 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.4720 - val_loss: 6.7712 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.7830\n\nEpoch 00007: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-07_loss-5.4897_val_loss-6.7712.h5\nEpoch 8/80\n\nEpoch 00008: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 753s 753ms/step - loss: 5.3152 - pool1_GAP_substract_loss: 4.3501 - pool2_GAP_substract_loss: 4.4571 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.3471 - val_loss: 6.6204 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.6815\n\nEpoch 00008: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-08_loss-5.3150_val_loss-6.6204.h5\nEpoch 9/80\n\nEpoch 00009: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 752s 752ms/step - loss: 5.2570 - pool1_GAP_substract_loss: 4.3428 - pool2_GAP_substract_loss: 4.4401 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.3381 - val_loss: 6.5395 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.6490\n\nEpoch 00009: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-09_loss-5.2578_val_loss-6.5395.h5\nEpoch 10/80\n\nEpoch 00010: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 750s 750ms/step - loss: 5.1515 - pool1_GAP_substract_loss: 4.3527 - pool2_GAP_substract_loss: 4.4425 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.2805 - val_loss: 6.5034 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.6605\n\nEpoch 00010: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-10_loss-5.1510_val_loss-6.5034.h5\nEpoch 11/80\n\nEpoch 00011: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 750s 750ms/step - loss: 5.0310 - pool1_GAP_substract_loss: 4.3319 - pool2_GAP_substract_loss: 4.4165 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.2070 - val_loss: 6.4585 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.6620\n\nEpoch 00011: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-11_loss-5.0313_val_loss-6.4585.h5\nEpoch 12/80\n\nEpoch 00012: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 750s 750ms/step - loss: 4.9537 - pool1_GAP_substract_loss: 4.3325 - pool2_GAP_substract_loss: 4.4112 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.1759 - val_loss: 6.5354 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.7849\n\nEpoch 00012: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-12_loss-4.9533_val_loss-6.5354.h5\nEpoch 13/80\n\nEpoch 00013: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 751s 751ms/step - loss: 4.8398 - pool1_GAP_substract_loss: 4.3267 - pool2_GAP_substract_loss: 4.4026 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.1074 - val_loss: 6.4410 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.7354\n\nEpoch 00013: saving model to ../trained_weights/SIM10K_to_VOC07/current/mmd_0_0005/epoch-13_loss-4.8401_val_loss-6.4410.h5\nEpoch 14/80\n\nEpoch 00014: LearningRateScheduler setting learning rate to 0.001.\n1000/1000 [==============================] - 751s 751ms/step - loss: 4.7809 - pool1_GAP_substract_loss: 4.3288 - pool2_GAP_substract_loss: 4.3950 - pool3_GAP_substract_loss: 0.0000e+00 - predictions_loss: 2.0931 - val_loss: 6.3156 - val_pool1_GAP_substract_loss: 1.0000e-04 - val_pool2_GAP_substract_loss: 1.0000e-04 - val_pool3_GAP_substract_loss: 0.0000e+00 - val_predictions_loss: 3.6537\n"
],
[
"# 1: Set the generator for the val_dataset or train_dataset predictions.\n\npredict_generator = train_dataset.generate(batch_size=batch_size,\n shuffle=True,\n transformations=[ssd_data_augmentation],\n label_encoder=None,\n returns={'processed_images',\n 'filenames',\n 'inverse_transform',\n 'original_images',\n 'original_labels'},\n keep_images_without_gt=False)\n\n# 2: Generate samples.\n\nbatch_images, batch_filenames, batch_inverse_transforms, batch_original_images, batch_original_labels = next(predict_generator)",
"_____no_output_____"
],
[
"batch_images, batch_filenames, batch_inverse_transforms, batch_original_images, batch_original_labels = next(predict_generator)",
"_____no_output_____"
],
[
"i = 1\nprint(\"Image:\", batch_filenames[i])\ncolors = plt.cm.hsv(np.linspace(0, 1, n_classes+1)).tolist()\n\nplt.figure(figsize=(20, 12))\nplt.imshow(batch_images[0][i])\nplt.show()\nplt.figure(figsize=(20, 12))\nplt.imshow(batch_images[1][i])\nplt.show()\n",
"Image: ../../datasets/SIM10K/JPEGImages/3386267\n"
],
[
"i = 0 # Which batch item to look at\n\nprint(\"Image:\", batch_filenames[i])\nprint()\nprint(\"Ground truth boxes:\\n\")\nprint(np.array(batch_original_labels[i]))\n\n# 3: Make predictions.\n\ny_pred = model.predict(batch_images)[-1]\n\n# Now let's decode the raw predictions in `y_pred`.\n\n# Had we created the model in 'inference' or 'inference_fast' mode,\n# then the model's final layer would be a `DecodeDetections` layer and\n# `y_pred` would already contain the decoded predictions,\n# but since we created the model in 'training' mode,\n# the model outputs raw predictions that still need to be decoded and filtered.\n# This is what the `decode_detections()` function is for.\n# It does exactly what the `DecodeDetections` layer would do,\n# but using Numpy instead of TensorFlow (i.e. on the CPU instead of the GPU).\n\n# `decode_detections()` with default argument values follows the procedure of the original SSD implementation:\n# First, a very low confidence threshold of 0.01 is applied to filter out the majority of the predicted boxes,\n# then greedy non-maximum suppression is performed per class with an intersection-over-union threshold of 0.45,\n# and out of what is left after that, the top 200 highest confidence boxes are returned.\n# Those settings are for precision-recall scoring purposes though.\n# In order to get some usable final predictions, we'll set the confidence threshold much higher, e.g. to 0.5,\n# since we're only interested in the very confident predictions.\n\n# 4: Decode the raw predictions in `y_pred`.\n\ny_pred_decoded = decode_detections(y_pred,\n confidence_thresh=0.35,\n iou_threshold=0.4,\n top_k=200,\n normalize_coords=normalize_coords,\n img_height=img_height,\n img_width=img_width)\n\n# We made the predictions on the resized images,\n# but we'd like to visualize the outcome on the original input images,\n# so we'll convert the coordinates accordingly.\n# Don't worry about that opaque `apply_inverse_transforms()` function below,\n# in this simple case it just applies `(* original_image_size / resized_image_size)` to the box coordinates.\n\n# 5: Convert the predictions for the original image.\n\ny_pred_decoded_inv = apply_inverse_transforms(y_pred_decoded, batch_inverse_transforms)\n\nnp.set_printoptions(precision=2, suppress=True, linewidth=90)\nprint(\"Predicted boxes:\\n\")\nprint(' class conf xmin ymin xmax ymax')\nprint(y_pred_decoded_inv[i])\n\n# Finally, let's draw the predicted boxes onto the image.\n# Each predicted box says its confidence next to the category name.\n# The ground truth boxes are also drawn onto the image in green for comparison.\n\n# 5: Draw the predicted boxes onto the image\n\n# Set the colors for the bounding boxes\ncolors = plt.cm.hsv(np.linspace(0, 1, n_classes+1)).tolist()\n\nplt.figure(figsize=(20, 12))\nplt.imshow(batch_original_images[i])\n\ncurrent_axis = plt.gca()\n\nfor box in batch_original_labels[i]:\n xmin = box[1]\n ymin = box[2]\n xmax = box[3]\n ymax = box[4]\n label = '{}'.format(classes[int(box[0])])\n current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color='green', fill=False, linewidth=2))\n current_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'facecolor': 'green', 'alpha': 1.0})\n\n# for box in y_pred_decoded_inv[i]:\n# xmin = box[2]\n# ymin = box[3]\n# xmax = box[4]\n# ymax = box[5]\n# color = colors[int(box[0])]\n# label = '{}: {:.2f}'.format(classes[int(box[0])], box[1])\n# current_axis.add_patch(plt.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, color=color, fill=False, linewidth=2))\n# current_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'facecolor': color, 'alpha': 1.0})",
"Image: ../../datasets/SIM10K/JPEGImages/3399675\n\nGround truth boxes:\n\n[[ 1 269 160 287 165]\n [ 1 407 0 721 240]\n [ 1 401 164 411 169]\n [ 1 342 163 349 168]\n [ 1 194 159 235 165]\n [ 1 158 157 199 166]]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb0754dbbdc7df28776bacddcd60b664af11bdfd | 272,930 | ipynb | Jupyter Notebook | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier | 79aa647cd5213a77b87c6cd2a28f9db5d24ec857 | [
"FTL",
"CNRI-Python"
] | null | null | null | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier | 79aa647cd5213a77b87c6cd2a28f9db5d24ec857 | [
"FTL",
"CNRI-Python"
] | null | null | null | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier | 79aa647cd5213a77b87c6cd2a28f9db5d24ec857 | [
"FTL",
"CNRI-Python"
] | null | null | null | 355.840939 | 232,004 | 0.912747 | [
[
[
"# Developing an AI application\n\nGoing forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. \n\nIn this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using [this dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html) of 102 flower categories, you can see a few examples below. \n\n<img src='assets/Flowers.png' width=500px>\n\nThe project is broken down into multiple steps:\n\n* Load and preprocess the image dataset\n* Train the image classifier on your dataset\n* Use the trained classifier to predict image content\n\nWe'll lead you through each part which you'll implement in Python.\n\nWhen you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.\n\nFirst up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here.",
"_____no_output_____"
]
],
[
[
"# Imports here\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets,transforms,models\nfrom workspace_utils import active_session\nfrom PIL import Image\nimport numpy as np\nimport seaborn as sb\nimport json",
"_____no_output_____"
]
],
[
[
"## Load the data\n\nHere you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks.\n\nThe validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size.\n\nThe pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1.\n ",
"_____no_output_____"
]
],
[
[
"data_dir = 'flowers'\ntrain_dir = data_dir + '/train'\nvalid_dir = data_dir + '/valid'\ntest_dir = data_dir + '/test'",
"_____no_output_____"
],
[
"# TODO: Define your transforms for the training, validation, and testing sets\ntrain_data_transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\nvalid_data_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\ntest_data_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n# TODO: Load the datasets with ImageFolder\nimage_datasets = {\"train\":datasets.ImageFolder(train_dir,transform=train_data_transforms),\n \"valid\":datasets.ImageFolder(valid_dir,transform=valid_data_transforms),\n \"test\":datasets.ImageFolder(test_dir,transform=test_data_transforms)}\n\n# TODO: Using the image datasets and the trainforms, define the dataloaders\ndataloader = {\"train\":torch.utils.data.DataLoader(image_datasets[\"train\"],batch_size=64,shuffle=True),\n \"valid\":torch.utils.data.DataLoader(image_datasets[\"valid\"],batch_size=64),\n \"test\":torch.utils.data.DataLoader(image_datasets[\"test\"],batch_size=64)}",
"_____no_output_____"
]
],
[
[
"### Label mapping\n\nYou'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers.",
"_____no_output_____"
]
],
[
[
"with open('cat_to_name.json', 'r') as f:\n cat_to_name = json.load(f)",
"_____no_output_____"
]
],
[
[
"# Building and training the classifier\n\nNow that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features.\n\nWe're going to leave this part up to you. Refer to [the rubric](https://review.udacity.com/#!/rubrics/1663/view) for guidance on successfully completing this section. Things you'll need to do:\n\n* Load a [pre-trained network](http://pytorch.org/docs/master/torchvision/models.html) (If you need a starting point, the VGG networks work great and are straightforward to use)\n* Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout\n* Train the classifier layers using backpropagation using the pre-trained network to get the features\n* Track the loss and accuracy on the validation set to determine the best hyperparameters\n\nWe've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!\n\nWhen training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project.\n\nOne last important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to\nGPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module.\n\n**Note for Workspace users:** If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with `ls -lh`), you should reduce the size of your hidden layers and train again.",
"_____no_output_____"
]
],
[
[
"# TODO: Build and train your network\n# Use GPU device\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#using Vgg pre training\nmodel= models.vgg11(pretrained=True)\n\n\n#Set disable Backdrop property for model parameters\nfor param in model.parameters():\n param.requires_grad= False\n\nmodel.classifier = nn.Sequential(nn.Linear(25088,4096),\n nn.ReLU(),\n nn.Dropout(p=0.5),\n nn.Linear(4096,102),\n nn.LogSoftmax(dim=1))\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.classifier.parameters(),lr=0.001)\nmodel.to(device)\n",
"Downloading: \"https://download.pytorch.org/models/vgg11-bbd30ac9.pth\" to /root/.torch/models/vgg11-bbd30ac9.pth\n100%|██████████| 531456000/531456000 [00:06<00:00, 86484829.89it/s]\n"
],
[
"#train the model\nepochs =5\nrunning_loss =0\ntrain_n=\"train\"\nvalid_n=\"valid\"\ncounter=5\nsteps=0\nwith active_session(): \n for e in range(epochs): \n for inputs,lables in dataloader[train_n]:\n steps+=1\n # move to the device\n inputs, lables = inputs.to(device),lables.to(device)\n #Setting Zero grad\n model.zero_grad()\n logps = model.forward(inputs)\n loss = criterion(logps,lables)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n\n if steps % counter == 0:\n validset_loss =0 \n accuracy =0\n model.eval()\n with torch.no_grad(): \n for inputs,lables in dataloader[valid_n]:\n inputs, lables = inputs.to(device),lables.to(device) \n logps = model.forward(inputs)\n valid_loss = criterion(logps,lables)\n validset_loss += valid_loss.item()\n\n #calculate accuracy for validation set\n ps = torch.exp(logps)\n top_p,top_class =ps.topk(1,dim=1)\n equal = top_class == lables.view(*top_class.shape)\n accuracy += torch.mean(equal.type(torch.FloatTensor)).item()\n\n print(f\"Epoch {e+1}/{epochs}.. \"\n f\"Train loss: {running_loss/len(dataloader[train_n]):.3f}..\"\n f\"Validation loss:{validset_loss/len(dataloader[valid_n]):.3f}..\"\n f\"Validation Accuracy :{accuracy/len(dataloader[valid_n]):.3f}..\")\n model.train()\n running_loss =0",
"Epoch 1/5.. Train loss: 0.453..Validation loss:8.617..Validation Accuracy :0.057..\nEpoch 1/5.. Train loss: 0.448..Validation loss:5.540..Validation Accuracy :0.189..\nEpoch 1/5.. Train loss: 0.256..Validation loss:3.558..Validation Accuracy :0.315..\nEpoch 1/5.. Train loss: 0.187..Validation loss:2.916..Validation Accuracy :0.320..\nEpoch 1/5.. Train loss: 0.160..Validation loss:2.548..Validation Accuracy :0.471..\nEpoch 1/5.. Train loss: 0.137..Validation loss:2.140..Validation Accuracy :0.522..\nEpoch 1/5.. Train loss: 0.128..Validation loss:1.789..Validation Accuracy :0.587..\nEpoch 1/5.. Train loss: 0.119..Validation loss:1.543..Validation Accuracy :0.643..\nEpoch 1/5.. Train loss: 0.111..Validation loss:1.361..Validation Accuracy :0.672..\nEpoch 1/5.. Train loss: 0.102..Validation loss:1.213..Validation Accuracy :0.690..\nEpoch 1/5.. Train loss: 0.090..Validation loss:1.122..Validation Accuracy :0.707..\nEpoch 1/5.. Train loss: 0.093..Validation loss:1.029..Validation Accuracy :0.718..\nEpoch 1/5.. Train loss: 0.091..Validation loss:1.023..Validation Accuracy :0.725..\nEpoch 1/5.. Train loss: 0.092..Validation loss:0.876..Validation Accuracy :0.768..\nEpoch 1/5.. Train loss: 0.082..Validation loss:0.896..Validation Accuracy :0.747..\nEpoch 1/5.. Train loss: 0.082..Validation loss:0.817..Validation Accuracy :0.780..\nEpoch 1/5.. Train loss: 0.083..Validation loss:0.854..Validation Accuracy :0.771..\nEpoch 1/5.. Train loss: 0.077..Validation loss:0.813..Validation Accuracy :0.788..\nEpoch 1/5.. Train loss: 0.075..Validation loss:0.830..Validation Accuracy :0.778..\nEpoch 1/5.. Train loss: 0.073..Validation loss:0.777..Validation Accuracy :0.784..\nEpoch 2/5.. Train loss: 0.068..Validation loss:0.812..Validation Accuracy :0.770..\nEpoch 2/5.. Train loss: 0.069..Validation loss:0.688..Validation Accuracy :0.813..\nEpoch 2/5.. Train loss: 0.068..Validation loss:0.616..Validation Accuracy :0.847..\nEpoch 2/5.. Train loss: 0.056..Validation loss:0.611..Validation Accuracy :0.840..\nEpoch 2/5.. Train loss: 0.064..Validation loss:0.616..Validation Accuracy :0.827..\nEpoch 2/5.. Train loss: 0.060..Validation loss:0.623..Validation Accuracy :0.838..\nEpoch 2/5.. Train loss: 0.058..Validation loss:0.651..Validation Accuracy :0.814..\nEpoch 2/5.. Train loss: 0.065..Validation loss:0.643..Validation Accuracy :0.807..\nEpoch 2/5.. Train loss: 0.069..Validation loss:0.610..Validation Accuracy :0.831..\nEpoch 2/5.. Train loss: 0.058..Validation loss:0.602..Validation Accuracy :0.833..\nEpoch 2/5.. Train loss: 0.058..Validation loss:0.546..Validation Accuracy :0.851..\nEpoch 2/5.. Train loss: 0.062..Validation loss:0.572..Validation Accuracy :0.831..\nEpoch 2/5.. Train loss: 0.059..Validation loss:0.557..Validation Accuracy :0.856..\nEpoch 2/5.. Train loss: 0.065..Validation loss:0.565..Validation Accuracy :0.840..\nEpoch 2/5.. Train loss: 0.059..Validation loss:0.581..Validation Accuracy :0.838..\nEpoch 2/5.. Train loss: 0.062..Validation loss:0.510..Validation Accuracy :0.864..\nEpoch 2/5.. Train loss: 0.053..Validation loss:0.529..Validation Accuracy :0.855..\nEpoch 2/5.. Train loss: 0.051..Validation loss:0.527..Validation Accuracy :0.860..\nEpoch 2/5.. Train loss: 0.059..Validation loss:0.506..Validation Accuracy :0.858..\nEpoch 2/5.. Train loss: 0.057..Validation loss:0.478..Validation Accuracy :0.873..\nEpoch 2/5.. Train loss: 0.048..Validation loss:0.468..Validation Accuracy :0.878..\nEpoch 3/5.. Train loss: 0.050..Validation loss:0.515..Validation Accuracy :0.864..\nEpoch 3/5.. Train loss: 0.058..Validation loss:0.524..Validation Accuracy :0.866..\nEpoch 3/5.. Train loss: 0.045..Validation loss:0.466..Validation Accuracy :0.878..\nEpoch 3/5.. Train loss: 0.054..Validation loss:0.496..Validation Accuracy :0.869..\nEpoch 3/5.. Train loss: 0.041..Validation loss:0.507..Validation Accuracy :0.864..\nEpoch 3/5.. Train loss: 0.049..Validation loss:0.541..Validation Accuracy :0.844..\nEpoch 3/5.. Train loss: 0.060..Validation loss:0.481..Validation Accuracy :0.865..\nEpoch 3/5.. Train loss: 0.055..Validation loss:0.469..Validation Accuracy :0.870..\nEpoch 3/5.. Train loss: 0.051..Validation loss:0.456..Validation Accuracy :0.874..\nEpoch 3/5.. Train loss: 0.055..Validation loss:0.526..Validation Accuracy :0.850..\nEpoch 3/5.. Train loss: 0.059..Validation loss:0.540..Validation Accuracy :0.861..\nEpoch 3/5.. Train loss: 0.054..Validation loss:0.494..Validation Accuracy :0.879..\nEpoch 3/5.. Train loss: 0.053..Validation loss:0.466..Validation Accuracy :0.886..\nEpoch 3/5.. Train loss: 0.048..Validation loss:0.467..Validation Accuracy :0.880..\nEpoch 3/5.. Train loss: 0.055..Validation loss:0.455..Validation Accuracy :0.873..\nEpoch 3/5.. Train loss: 0.056..Validation loss:0.463..Validation Accuracy :0.869..\nEpoch 3/5.. Train loss: 0.045..Validation loss:0.471..Validation Accuracy :0.879..\nEpoch 3/5.. Train loss: 0.056..Validation loss:0.440..Validation Accuracy :0.876..\nEpoch 3/5.. Train loss: 0.055..Validation loss:0.400..Validation Accuracy :0.890..\nEpoch 3/5.. Train loss: 0.050..Validation loss:0.418..Validation Accuracy :0.883..\nEpoch 4/5.. Train loss: 0.047..Validation loss:0.417..Validation Accuracy :0.889..\nEpoch 4/5.. Train loss: 0.050..Validation loss:0.443..Validation Accuracy :0.877..\nEpoch 4/5.. Train loss: 0.046..Validation loss:0.433..Validation Accuracy :0.884..\nEpoch 4/5.. Train loss: 0.050..Validation loss:0.440..Validation Accuracy :0.890..\nEpoch 4/5.. Train loss: 0.050..Validation loss:0.424..Validation Accuracy :0.894..\nEpoch 4/5.. Train loss: 0.044..Validation loss:0.381..Validation Accuracy :0.887..\nEpoch 4/5.. Train loss: 0.048..Validation loss:0.419..Validation Accuracy :0.883..\nEpoch 4/5.. Train loss: 0.044..Validation loss:0.430..Validation Accuracy :0.881..\nEpoch 4/5.. Train loss: 0.048..Validation loss:0.426..Validation Accuracy :0.893..\nEpoch 4/5.. Train loss: 0.051..Validation loss:0.387..Validation Accuracy :0.892..\nEpoch 4/5.. Train loss: 0.052..Validation loss:0.440..Validation Accuracy :0.872..\nEpoch 4/5.. Train loss: 0.050..Validation loss:0.458..Validation Accuracy :0.864..\nEpoch 4/5.. Train loss: 0.046..Validation loss:0.402..Validation Accuracy :0.876..\nEpoch 4/5.. Train loss: 0.054..Validation loss:0.380..Validation Accuracy :0.887..\nEpoch 4/5.. Train loss: 0.044..Validation loss:0.401..Validation Accuracy :0.884..\nEpoch 4/5.. Train loss: 0.046..Validation loss:0.370..Validation Accuracy :0.889..\nEpoch 4/5.. Train loss: 0.041..Validation loss:0.410..Validation Accuracy :0.879..\nEpoch 4/5.. Train loss: 0.056..Validation loss:0.382..Validation Accuracy :0.882..\nEpoch 4/5.. Train loss: 0.043..Validation loss:0.390..Validation Accuracy :0.893..\nEpoch 4/5.. Train loss: 0.043..Validation loss:0.385..Validation Accuracy :0.886..\nEpoch 4/5.. Train loss: 0.050..Validation loss:0.397..Validation Accuracy :0.884..\nEpoch 5/5.. Train loss: 0.043..Validation loss:0.417..Validation Accuracy :0.880..\nEpoch 5/5.. Train loss: 0.049..Validation loss:0.471..Validation Accuracy :0.876..\nEpoch 5/5.. Train loss: 0.052..Validation loss:0.424..Validation Accuracy :0.884..\nEpoch 5/5.. Train loss: 0.043..Validation loss:0.377..Validation Accuracy :0.888..\nEpoch 5/5.. Train loss: 0.039..Validation loss:0.375..Validation Accuracy :0.896..\nEpoch 5/5.. Train loss: 0.050..Validation loss:0.378..Validation Accuracy :0.891..\nEpoch 5/5.. Train loss: 0.049..Validation loss:0.389..Validation Accuracy :0.893..\nEpoch 5/5.. Train loss: 0.041..Validation loss:0.397..Validation Accuracy :0.891..\nEpoch 5/5.. Train loss: 0.041..Validation loss:0.375..Validation Accuracy :0.894..\nEpoch 5/5.. Train loss: 0.037..Validation loss:0.387..Validation Accuracy :0.902..\nEpoch 5/5.. Train loss: 0.044..Validation loss:0.387..Validation Accuracy :0.897..\nEpoch 5/5.. Train loss: 0.052..Validation loss:0.418..Validation Accuracy :0.887..\nEpoch 5/5.. Train loss: 0.046..Validation loss:0.413..Validation Accuracy :0.890..\nEpoch 5/5.. Train loss: 0.041..Validation loss:0.401..Validation Accuracy :0.882..\nEpoch 5/5.. Train loss: 0.043..Validation loss:0.423..Validation Accuracy :0.883..\nEpoch 5/5.. Train loss: 0.043..Validation loss:0.469..Validation Accuracy :0.887..\nEpoch 5/5.. Train loss: 0.048..Validation loss:0.444..Validation Accuracy :0.898..\nEpoch 5/5.. Train loss: 0.046..Validation loss:0.421..Validation Accuracy :0.891..\nEpoch 5/5.. Train loss: 0.044..Validation loss:0.423..Validation Accuracy :0.896..\nEpoch 5/5.. Train loss: 0.045..Validation loss:0.414..Validation Accuracy :0.890..\nEpoch 5/5.. Train loss: 0.055..Validation loss:0.382..Validation Accuracy :0.894..\n"
]
],
[
[
"## Testing your network\n\nIt's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well.",
"_____no_output_____"
]
],
[
[
"# TODO: Do validation on the test set\ndef testModel(model_to_test):\n test_loss=0\n accuracy =0\n test_n=\"test\"\n model_to_test.to(device)\n with torch.no_grad():\n model_to_test.eval()\n for inputs,lables in dataloader[test_n]:\n inputs,lables = inputs.to(device),lables.to(device)\n logps = model_to_test.forward(inputs)\n tloss=criterion(logps,lables)\n test_loss += tloss.item()\n #calculate accuracy for test set\n ps = torch.exp(logps)\n top_p,top_class = ps.topk(1,dim=1)\n equals = top_class == lables.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n print(f\"testloss:{test_loss/len(dataloader[test_n]):.3f}..\"\n #f\"Accuracy :{accuracy/len(dataloader[valid_n]):.3f}..\"\n f\"Test Accuracy:{accuracy/len(dataloader[test_n]):.3f}..\") \n model_to_test.train()",
"_____no_output_____"
],
[
"#test the model\ntestModel(model)",
"testloss:0.438..Test Accuracy:0.883..\n"
]
],
[
[
"## Save the checkpoint\n\nNow that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as an attribute which makes inference easier later on.\n\n```model.class_to_idx = image_datasets['train'].class_to_idx```\n\nRemember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now.",
"_____no_output_____"
]
],
[
[
"# TODO: Save the checkpoint\n#map class to idx\ncheckpoint_path = \"checkpoint.pth\"\nmodel.class_to_idx = image_datasets[\"train\"].class_to_idx \ncheckpoint={\"state_dict\":model.state_dict(),\n \"class_to_idx\":model.class_to_idx,\n \"architecture\":\"vgg11\",\n \"hidden_units\":4096,\n \"learning_rate\":\"0.001\",\n \"optimizer\":optimizer,\n \"epochs\":epochs}\ntorch.save(checkpoint,checkpoint_path)",
"_____no_output_____"
]
],
[
[
"## Loading the checkpoint\n\nAt this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.",
"_____no_output_____"
]
],
[
[
"# TODO: Write a function that loads a checkpoint and rebuilds the model\ndef load_checkpoint(filepath):\n checkpoint = torch.load(filepath)\n hidden_units = checkpoint[\"hidden_units\"]\n model = models.vgg11(pretrained=True)\n for param in model.parameters():\n param.requires_grad = False\n model.classifier = nn.Sequential(nn.Linear(25088,4096),\n nn.ReLU(),\n nn.Dropout(p=0.5),\n nn.Linear(4096,102),\n nn.LogSoftmax(dim=1))\n model.load_state_dict(checkpoint[\"state_dict\"])\n model.class_to_idx = checkpoint[\"class_to_idx\"]\n return model",
"_____no_output_____"
],
[
"#Test the loaded model\nsave_model = load_checkpoint(checkpoint_path)\ntestModel(save_model)",
"testloss:0.438..Test Accuracy:0.883..\n"
]
],
[
[
"# Inference for classification\n\nNow you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like \n\n```python\nprobs, classes = predict(image_path, model)\nprint(probs)\nprint(classes)\n> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]\n> ['70', '3', '45', '62', '55']\n```\n\nFirst you'll need to handle processing the input image such that it can be used in your network. \n\n## Image Preprocessing\n\nYou'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. \n\nFirst, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image.\n\nColor channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`.\n\nAs before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. \n\nAnd finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions.",
"_____no_output_____"
]
],
[
[
"def process_image(image_Path):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n \n # TODO: Process a PIL image for use in a PyTorch model\n img = Image.open(image_path)\n # Resize\n if img.size[0] > img.size[1]:\n img.thumbnail((10000, 256))\n else:\n img.thumbnail((256, 10000))\n # Crop \n left_margin = (img.width-224)/2\n bottom_margin = (img.height-224)/2\n right_margin = left_margin + 224\n top_margin = bottom_margin + 224\n img = img.crop((left_margin, bottom_margin, right_margin, \n top_margin))\n # Normalize\n img = np.array(img)/255\n mean = np.array([0.485, 0.456, 0.406]) #mean\n std = np.array([0.229, 0.224, 0.225]) #std\n img = (img - mean)/std\n \n # color channels to first dimension as expected by PyTorch\n img = img.transpose((2, 0, 1))\n \n return img",
"_____no_output_____"
]
],
[
[
"To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions).",
"_____no_output_____"
]
],
[
[
"def imshow(image, ax=None, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n if title:\n #plt.title(title)\n ax.set_title(title)\n \n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n \n ax.imshow(image)\n \n return ax",
"_____no_output_____"
]
],
[
[
"## Class Prediction\n\nOnce you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.\n\nTo get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well.\n\nAgain, this method should take a path to an image and a model checkpoint, then return the probabilities and classes.\n\n```python\nprobs, classes = predict(image_path, model)\nprint(probs)\nprint(classes)\n> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]\n> ['70', '3', '45', '62', '55']\n```",
"_____no_output_____"
]
],
[
[
"def predict(image_path, model, topk=5):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n \n # TODO: Implement the code to predict the class from an image file\n image = torch.from_numpy(process_image(image_path)).type(torch.FloatTensor)\n #Change the dimensions of an image\n image = image.unsqueeze(0)\n \n #Obtain Probabilities\n output = model.forward(image)\n ps = torch.exp(output)\n top_p,top_class = ps.topk(topk,dim=1)\n top_p = top_p.detach().numpy().tolist()[0]\n top_class = top_class.detach().numpy().tolist()[0]\n #get indices to class\n idx_to_Classes = {val:key for key,val in model.class_to_idx.items()}\n top_class = [idx_to_Classes[idx] for idx in iter(top_class)]\n return top_p,top_class",
"_____no_output_____"
]
],
[
[
"## Sanity Checking\n\nNow that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:\n\n<img src='assets/inference_example.png' width=300px>\n\nYou can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above.",
"_____no_output_____"
]
],
[
[
"# TODO: Display an image along with the top 5 classes\nimage_path = test_dir+\"/1/image_06743.jpg\"\nflower_num = image_path.split('/')[-2]\ntitle = cat_to_name[flower_num]\nmodel = load_checkpoint(checkpoint_path)\ntop_p,top_class = predict(image_path,model)\ntop_flowers = [cat_to_name[cl] for cl in top_class]\nplt.figure(figsize = (6,10))\nax = plt.subplot(2,1,1)\n#plot the image\nimage = process_image(image_path)\nimshow(image,ax,title=title)\n\nplt.subplot(2,1,2)\nsb.barplot(x=top_p, y=top_flowers, color=sb.color_palette()[0]);\nplt.show()\n",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb075b7685dd29492ab5bae2ee70d739c8203390 | 210,279 | ipynb | Jupyter Notebook | notebooks(colab)/Classic_models/KNN.ipynb | jswanglp/MyML | ea1510cc5c2dec9eb37e371a73234b3a228beca7 | [
"MIT"
] | 7 | 2019-05-04T13:57:52.000Z | 2021-12-31T03:39:58.000Z | notebooks(colab)/Classic_models/KNN.ipynb | jswanglp/MyML | ea1510cc5c2dec9eb37e371a73234b3a228beca7 | [
"MIT"
] | 19 | 2020-09-26T01:16:10.000Z | 2022-02-10T02:11:15.000Z | notebooks(colab)/Classic_models/KNN.ipynb | jswanglp/MyML | ea1510cc5c2dec9eb37e371a73234b3a228beca7 | [
"MIT"
] | 2 | 2019-06-02T05:10:35.000Z | 2020-09-19T07:24:43.000Z | 210,279 | 210,279 | 0.943432 | [
[
[
"# 初始化",
"_____no_output_____"
]
],
[
[
"#@markdown - **挂载** \nfrom google.colab import drive\ndrive.mount('GoogleDrive')",
"_____no_output_____"
],
[
"# #@markdown - **卸载**\n# !fusermount -u GoogleDrive",
"_____no_output_____"
]
],
[
[
"# 代码区",
"_____no_output_____"
]
],
[
[
"#@title K-近邻算法 { display-mode: \"both\" }\n# 该程序实现 k-NN 对三维随机数据的分类\n#@markdown [参考程序](https://github.com/wzyonggege/statistical-learning-method/blob/master/KNearestNeighbors/KNN.ipynb)\n# coding: utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D",
"_____no_output_____"
],
[
"#@markdown - **绑定数据**\nclass Bunch(dict): \n\tdef __init__(self,*args,**kwds): \n\t\tsuper(Bunch,self).__init__(*args,**kwds) \n\t\tself.__dict__ = self",
"_____no_output_____"
],
[
"#@markdown - **生成带标签随机数据函数**\ndef generate_random(sigma, N, mu1=[25., 25., 20], mu2=[30., 40., 30]): \n\tc = sigma.shape[-1] # 生成N行c维的随机测试数据\n\tX = np.zeros((N, c)) # 初始化X,N个样本 \n\ttarget = np.zeros((N,1))\n\tfor i in range(N): \n\t\tif np.random.random(1) < 0.5: # 生成0-1之间随机数 \n\t\t\tX[i, :] = np.random.multivariate_normal(mu1, sigma[0, :, :], 1) # 用第一个高斯模型生成3维数据 \n\t\t\ttarget[i] = 1\n\t\telse: \n\t\t\tX[i, :] = np.random.multivariate_normal(mu2, sigma[1, :, :], 1) # 用第二个高斯模型生成3维数据 \n\t\t\ttarget[i] = -1\n\treturn X, target",
"_____no_output_____"
],
[
"#@markdown - **KNN 类**\nclass KNN:\n def __init__(self, X_train, y_train, n_neighbors=3, p=2):\n \"\"\"\n parameter: n_neighbors 临近点个数, 最好选奇数\n parameter: p 距离度量\n \"\"\"\n if n_neighbors % 2 == 0:\n print('n_neighbors 最好为奇数!')\n self.n = n_neighbors\n self.p = p\n self.X_train = X_train\n self.y_train = y_train.flatten()\n \n def predict(self, X):\n # 取出n个点\n knn_list = []\n for i in range(self.n):\n dist = np.linalg.norm(X - self.X_train[i], ord=self.p)\n knn_list.append((dist, self.y_train[i]))\n \n # 遍历得到距离最近的 n 个点 \n for i in range(self.n, len(self.X_train)):\n max_index = knn_list.index(max(knn_list, key=lambda x: x[0]))\n dist = np.linalg.norm(X - self.X_train[i], ord=self.p)\n if knn_list[max_index][0] > dist:\n knn_list[max_index] = (dist, self.y_train[i])\n \n # 预测类别\n knn = np.array([k[-1] for k in knn_list])\n return np.sign(knn.sum()) if knn.sum() != 0 else 1\n \n def score(self, X_test, y_test):\n y_test = y_test.flatten()\n right_count = 0\n for X, y in zip(X_test, y_test):\n label = self.predict(X)\n if label == y:\n right_count += 1\n return right_count / X_test.shape[0]",
"_____no_output_____"
],
[
"#@markdown - **生成带标签的随机数据**\nk, N = 2, 400\n# 初始化方差,生成样本与标签\nsigma = np.zeros((k, 3, 3))\nfor i in range(k):\n\tsigma[i, :, :] = np.diag(np.random.randint(10, 25, size=(3, )))\nsample, target = generate_random(sigma, N)\nfeature_names = ['x_label', 'y_label', 'z_label'] # 特征数\ntarget_names = ['gaussian1', 'gaussian2', 'gaussian3', 'gaussian4'] # 类别\ndata = Bunch(sample=sample, feature_names=feature_names, target=target, target_names=target_names)\nsample_t, target_t = generate_random(sigma, N)\ndata_t = Bunch(sample=sample_t, target=target_t)",
"_____no_output_____"
],
[
"#@markdown - **模型训练**\nmodel = KNN(data.sample, target, n_neighbors=4, p=2)\nmodel.predict(data.sample[100])",
"n_neighbors 最好为奇数!\n"
],
[
"target.flatten()[100]",
"_____no_output_____"
],
[
"#@markdown - **测试集精度**\nacc = model.score(data_t.sample, data_t.target) * 100\nprint('Accuracy on testing set: {:.2f}%.'.format(acc))\ntar_test = np.array([model.predict(x) for x in data_t.sample], dtype=np.int8) + 1",
"Accuracy on testing set: 96.75%.\n"
],
[
"#@markdown - **显示 KNN 对测试数据的分类情况**\ntitles = ['Random training data', 'Classified testing data by KNN']\nTAR = [target, tar_test]\nDATA = [data.sample, data_t.sample]\nfig = plt.figure(1, figsize=(16, 8))\nfig.subplots_adjust(wspace=.01, hspace=.02)\nfor i, title, data_n, tar in zip([1, 2], titles, DATA, TAR):\n ax = fig.add_subplot(1, 2, i, projection='3d')\n if title == 'Random training data':\n ax.scatter(data_n[:,0], data_n[:,1], data_n[:,2], c='b', s=35, alpha=0.4, marker='o')\n else:\n color=['b','g', 'r']\n for j in range(N):\n ax.scatter(data_n[j, 0], data_n[j, 1], data_n[j, 2], c=color[tar[j]], s=35, alpha=0.4, marker='P')\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n ax.view_init(elev=20., azim=-25)\n ax.set_title(title, fontsize=14, y=0.01)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb077656c2870c9018d3c07cf1963d2fe913e6dd | 2,362 | ipynb | Jupyter Notebook | data2sql/.ipynb_checkpoints/data2sql-checkpoint.ipynb | rongxinyin/pge-adr | db4b993a3e634bbb9d59c319eeab4058ec9935e7 | [
"BSD-2-Clause"
] | 1 | 2019-02-10T05:53:11.000Z | 2019-02-10T05:53:11.000Z | data2sql/.ipynb_checkpoints/data2sql-checkpoint.ipynb | rongxinyin/pge-adr | db4b993a3e634bbb9d59c319eeab4058ec9935e7 | [
"BSD-2-Clause"
] | null | null | null | data2sql/.ipynb_checkpoints/data2sql-checkpoint.ipynb | rongxinyin/pge-adr | db4b993a3e634bbb9d59c319eeab4058ec9935e7 | [
"BSD-2-Clause"
] | null | null | null | 23.386139 | 99 | 0.527096 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb077b305469a48aeab6239020c566f4a5a49809 | 46,470 | ipynb | Jupyter Notebook | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook | cef63961ff0f28b9a9abeb3c23d6fc5d6bfafd54 | [
"MIT"
] | 6,753 | 2016-07-04T07:07:25.000Z | 2022-03-30T14:13:12.000Z | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook | cef63961ff0f28b9a9abeb3c23d6fc5d6bfafd54 | [
"MIT"
] | 139 | 2016-11-07T02:30:18.000Z | 2022-02-09T23:29:36.000Z | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook | cef63961ff0f28b9a9abeb3c23d6fc5d6bfafd54 | [
"MIT"
] | 2,693 | 2016-08-16T15:41:27.000Z | 2022-03-30T11:35:52.000Z | 72.046512 | 19,600 | 0.738563 | [
[
[
"# Implementing an LSTM RNN Model\n------------------------\nHere we implement an LSTM model on all a data set of Shakespeare works.\n\nWe start by loading the necessary libraries and resetting the default computational graph.",
"_____no_output_____"
]
],
[
[
"import os\nimport re\nimport string\nimport requests\nimport numpy as np\nimport collections\nimport random\nimport pickle\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()",
"_____no_output_____"
]
],
[
[
"We start a computational graph session.",
"_____no_output_____"
]
],
[
[
"sess = tf.Session()",
"_____no_output_____"
]
],
[
[
"Next, it is important to set the algorithm and data processing parameters.\n\n---------\nParameter : Descriptions\n - min_word_freq: Only attempt to model words that appear at least 5 times.\n - rnn_size: size of our RNN (equal to the embedding size)\n - epochs: Number of epochs to cycle through the data\n - batch_size: How many examples to train on at once\n - learning_rate: The learning rate or the convergence paramter\n - training_seq_len: The length of the surrounding word group (e.g. 10 = 5 on each side)\n - embedding_size: Must be equal to the rnn_size\n - save_every: How often to save the model\n - eval_every: How often to evaluate the model\n - prime_texts: List of test sentences",
"_____no_output_____"
]
],
[
[
"# Set RNN Parameters\nmin_word_freq = 5 # Trim the less frequent words off\nrnn_size = 128 # RNN Model size\nembedding_size = 100 # Word embedding size\nepochs = 10 # Number of epochs to cycle through data\nbatch_size = 100 # Train on this many examples at once\nlearning_rate = 0.001 # Learning rate\ntraining_seq_len = 50 # how long of a word group to consider \nembedding_size = rnn_size\nsave_every = 500 # How often to save model checkpoints\neval_every = 50 # How often to evaluate the test sentences\nprime_texts = ['thou art more', 'to be or not to', 'wherefore art thou']\n\n# Download/store Shakespeare data\ndata_dir = 'temp'\ndata_file = 'shakespeare.txt'\nmodel_path = 'shakespeare_model'\nfull_model_dir = os.path.join(data_dir, model_path)\n\n# Declare punctuation to remove, everything except hyphens and apostrophes\npunctuation = string.punctuation\npunctuation = ''.join([x for x in punctuation if x not in ['-', \"'\"]])\n\n# Make Model Directory\nif not os.path.exists(full_model_dir):\n os.makedirs(full_model_dir)\n\n# Make data directory\nif not os.path.exists(data_dir):\n os.makedirs(data_dir)",
"_____no_output_____"
]
],
[
[
"Download the data if we don't have it saved already. The data comes from the [Gutenberg Project](http://www.gutenberg.org])",
"_____no_output_____"
]
],
[
[
"print('Loading Shakespeare Data')\n# Check if file is downloaded.\nif not os.path.isfile(os.path.join(data_dir, data_file)):\n print('Not found, downloading Shakespeare texts from www.gutenberg.org')\n shakespeare_url = 'http://www.gutenberg.org/cache/epub/100/pg100.txt'\n # Get Shakespeare text\n response = requests.get(shakespeare_url)\n shakespeare_file = response.content\n # Decode binary into string\n s_text = shakespeare_file.decode('utf-8')\n # Drop first few descriptive paragraphs.\n s_text = s_text[7675:]\n # Remove newlines\n s_text = s_text.replace('\\r\\n', '')\n s_text = s_text.replace('\\n', '')\n \n # Write to file\n with open(os.path.join(data_dir, data_file), 'w') as out_conn:\n out_conn.write(s_text)\nelse:\n # If file has been saved, load from that file\n with open(os.path.join(data_dir, data_file), 'r') as file_conn:\n s_text = file_conn.read().replace('\\n', '')\n\n# Clean text\nprint('Cleaning Text')\ns_text = re.sub(r'[{}]'.format(punctuation), ' ', s_text)\ns_text = re.sub('\\s+', ' ', s_text ).strip().lower()\nprint('Done loading/cleaning.')",
"Loading Shakespeare Data\nCleaning Text\nDone loading/cleaning.\n"
]
],
[
[
"Define a function to build a word processing dictionary (word -> ix)",
"_____no_output_____"
]
],
[
[
"# Build word vocabulary function\ndef build_vocab(text, min_word_freq):\n word_counts = collections.Counter(text.split(' '))\n # limit word counts to those more frequent than cutoff\n word_counts = {key:val for key, val in word_counts.items() if val>min_word_freq}\n # Create vocab --> index mapping\n words = word_counts.keys()\n vocab_to_ix_dict = {key:(ix+1) for ix, key in enumerate(words)}\n # Add unknown key --> 0 index\n vocab_to_ix_dict['unknown']=0\n # Create index --> vocab mapping\n ix_to_vocab_dict = {val:key for key,val in vocab_to_ix_dict.items()}\n \n return(ix_to_vocab_dict, vocab_to_ix_dict)",
"_____no_output_____"
]
],
[
[
"Now we can build the index-vocabulary from the Shakespeare data.",
"_____no_output_____"
]
],
[
[
"# Build Shakespeare vocabulary\nprint('Building Shakespeare Vocab')\nix2vocab, vocab2ix = build_vocab(s_text, min_word_freq)\nvocab_size = len(ix2vocab) + 1\nprint('Vocabulary Length = {}'.format(vocab_size))\n# Sanity Check\nassert(len(ix2vocab) == len(vocab2ix))\n\n# Convert text to word vectors\ns_text_words = s_text.split(' ')\ns_text_ix = []\nfor ix, x in enumerate(s_text_words):\n try:\n s_text_ix.append(vocab2ix[x])\n except:\n s_text_ix.append(0)\ns_text_ix = np.array(s_text_ix)",
"Building Shakespeare Vocab\nVocabulary Length = 8009\n"
]
],
[
[
"We define the LSTM model. The methods of interest are the `__init__()` method, which defines all the model variables and operations, and the `sample()` method which takes in a sample word and loops through to generate text.",
"_____no_output_____"
]
],
[
[
"# Define LSTM RNN Model\nclass LSTM_Model():\n def __init__(self, embedding_size, rnn_size, batch_size, learning_rate,\n training_seq_len, vocab_size, infer_sample=False):\n self.embedding_size = embedding_size\n self.rnn_size = rnn_size\n self.vocab_size = vocab_size\n self.infer_sample = infer_sample\n self.learning_rate = learning_rate\n \n if infer_sample:\n self.batch_size = 1\n self.training_seq_len = 1\n else:\n self.batch_size = batch_size\n self.training_seq_len = training_seq_len\n \n self.lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.rnn_size)\n self.initial_state = self.lstm_cell.zero_state(self.batch_size, tf.float32)\n \n self.x_data = tf.placeholder(tf.int32, [self.batch_size, self.training_seq_len])\n self.y_output = tf.placeholder(tf.int32, [self.batch_size, self.training_seq_len])\n \n with tf.variable_scope('lstm_vars'):\n # Softmax Output Weights\n W = tf.get_variable('W', [self.rnn_size, self.vocab_size], tf.float32, tf.random_normal_initializer())\n b = tf.get_variable('b', [self.vocab_size], tf.float32, tf.constant_initializer(0.0))\n \n # Define Embedding\n embedding_mat = tf.get_variable('embedding_mat', [self.vocab_size, self.embedding_size],\n tf.float32, tf.random_normal_initializer())\n \n embedding_output = tf.nn.embedding_lookup(embedding_mat, self.x_data)\n rnn_inputs = tf.split(axis=1, num_or_size_splits=self.training_seq_len, value=embedding_output)\n rnn_inputs_trimmed = [tf.squeeze(x, [1]) for x in rnn_inputs]\n \n # If we are inferring (generating text), we add a 'loop' function\n # Define how to get the i+1 th input from the i th output\n def inferred_loop(prev, count):\n # Apply hidden layer\n prev_transformed = tf.matmul(prev, W) + b\n # Get the index of the output (also don't run the gradient)\n prev_symbol = tf.stop_gradient(tf.argmax(prev_transformed, 1))\n # Get embedded vector\n output = tf.nn.embedding_lookup(embedding_mat, prev_symbol)\n return(output)\n \n decoder = tf.contrib.legacy_seq2seq.rnn_decoder\n outputs, last_state = decoder(rnn_inputs_trimmed,\n self.initial_state,\n self.lstm_cell,\n loop_function=inferred_loop if infer_sample else None)\n # Non inferred outputs\n output = tf.reshape(tf.concat(axis=1, values=outputs), [-1, self.rnn_size])\n # Logits and output\n self.logit_output = tf.matmul(output, W) + b\n self.model_output = tf.nn.softmax(self.logit_output)\n \n loss_fun = tf.contrib.legacy_seq2seq.sequence_loss_by_example\n loss = loss_fun([self.logit_output],[tf.reshape(self.y_output, [-1])],\n [tf.ones([self.batch_size * self.training_seq_len])],\n self.vocab_size)\n self.cost = tf.reduce_sum(loss) / (self.batch_size * self.training_seq_len)\n self.final_state = last_state\n gradients, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tf.trainable_variables()), 4.5)\n optimizer = tf.train.AdamOptimizer(self.learning_rate)\n self.train_op = optimizer.apply_gradients(zip(gradients, tf.trainable_variables()))\n \n def sample(self, sess, words=ix2vocab, vocab=vocab2ix, num=10, prime_text='thou art'):\n state = sess.run(self.lstm_cell.zero_state(1, tf.float32))\n word_list = prime_text.split()\n for word in word_list[:-1]:\n x = np.zeros((1, 1))\n x[0, 0] = vocab[word]\n feed_dict = {self.x_data: x, self.initial_state:state}\n [state] = sess.run([self.final_state], feed_dict=feed_dict)\n\n out_sentence = prime_text\n word = word_list[-1]\n for n in range(num):\n x = np.zeros((1, 1))\n x[0, 0] = vocab[word]\n feed_dict = {self.x_data: x, self.initial_state:state}\n [model_output, state] = sess.run([self.model_output, self.final_state], feed_dict=feed_dict)\n sample = np.argmax(model_output[0])\n if sample == 0:\n break\n word = words[sample]\n out_sentence = out_sentence + ' ' + word\n return(out_sentence)",
"_____no_output_____"
]
],
[
[
"In order to use the same model (with the same trained variables), we need to share the variable scope between the trained model and the test model.",
"_____no_output_____"
]
],
[
[
"# Define LSTM Model\nlstm_model = LSTM_Model(embedding_size, rnn_size, batch_size, learning_rate,\n training_seq_len, vocab_size)\n\n# Tell TensorFlow we are reusing the scope for the testing\nwith tf.variable_scope(tf.get_variable_scope(), reuse=True):\n test_lstm_model = LSTM_Model(embedding_size, rnn_size, batch_size, learning_rate,\n training_seq_len, vocab_size, infer_sample=True)",
"_____no_output_____"
]
],
[
[
"We need to save the model, so we create a model saving operation.",
"_____no_output_____"
]
],
[
[
"# Create model saver\nsaver = tf.train.Saver(tf.global_variables())",
"_____no_output_____"
]
],
[
[
"Let's calculate how many batches are needed for each epoch and split up the data accordingly.",
"_____no_output_____"
]
],
[
[
"# Create batches for each epoch\nnum_batches = int(len(s_text_ix)/(batch_size * training_seq_len)) + 1\n# Split up text indices into subarrays, of equal size\nbatches = np.array_split(s_text_ix, num_batches)\n# Reshape each split into [batch_size, training_seq_len]\nbatches = [np.resize(x, [batch_size, training_seq_len]) for x in batches]",
"_____no_output_____"
]
],
[
[
"Initialize all the variables",
"_____no_output_____"
]
],
[
[
"# Initialize all variables\ninit = tf.global_variables_initializer()\nsess.run(init)",
"_____no_output_____"
]
],
[
[
"Training the model!",
"_____no_output_____"
]
],
[
[
"# Train model\ntrain_loss = []\niteration_count = 1\nfor epoch in range(epochs):\n # Shuffle word indices\n random.shuffle(batches)\n # Create targets from shuffled batches\n targets = [np.roll(x, -1, axis=1) for x in batches]\n # Run a through one epoch\n print('Starting Epoch #{} of {}.'.format(epoch+1, epochs))\n # Reset initial LSTM state every epoch\n state = sess.run(lstm_model.initial_state)\n for ix, batch in enumerate(batches):\n training_dict = {lstm_model.x_data: batch, lstm_model.y_output: targets[ix]}\n c, h = lstm_model.initial_state\n training_dict[c] = state.c\n training_dict[h] = state.h\n \n temp_loss, state, _ = sess.run([lstm_model.cost, lstm_model.final_state, lstm_model.train_op],\n feed_dict=training_dict)\n train_loss.append(temp_loss)\n \n # Print status every 10 gens\n if iteration_count % 10 == 0:\n summary_nums = (iteration_count, epoch+1, ix+1, num_batches+1, temp_loss)\n print('Iteration: {}, Epoch: {}, Batch: {} out of {}, Loss: {:.2f}'.format(*summary_nums))\n \n # Save the model and the vocab\n if iteration_count % save_every == 0:\n # Save model\n model_file_name = os.path.join(full_model_dir, 'model')\n saver.save(sess, model_file_name, global_step = iteration_count)\n print('Model Saved To: {}'.format(model_file_name))\n # Save vocabulary\n dictionary_file = os.path.join(full_model_dir, 'vocab.pkl')\n with open(dictionary_file, 'wb') as dict_file_conn:\n pickle.dump([vocab2ix, ix2vocab], dict_file_conn)\n \n if iteration_count % eval_every == 0:\n for sample in prime_texts:\n print(test_lstm_model.sample(sess, ix2vocab, vocab2ix, num=10, prime_text=sample))\n \n iteration_count += 1",
"Starting Epoch #1 of 10.\nIteration: 10, Epoch: 1, Batch: 10 out of 182, Loss: 9.90\n"
]
],
[
[
"Here is a plot of the training loss across the iterations.",
"_____no_output_____"
]
],
[
[
"# Plot loss over time\nplt.plot(train_loss, 'k-')\nplt.title('Sequence to Sequence Loss')\nplt.xlabel('Iterations')\nplt.ylabel('Loss')\nplt.show()",
"_____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"
]
] |
cb077dd11bc7afa7aa404a64d8d9ca214b1b0e95 | 4,113 | ipynb | Jupyter Notebook | ticker_list.ipynb | B0Ja/fin_data_eda | eec0743a60ccba3d37a83b17996a836361e16177 | [
"MIT"
] | null | null | null | ticker_list.ipynb | B0Ja/fin_data_eda | eec0743a60ccba3d37a83b17996a836361e16177 | [
"MIT"
] | null | null | null | ticker_list.ipynb | B0Ja/fin_data_eda | eec0743a60ccba3d37a83b17996a836361e16177 | [
"MIT"
] | null | null | null | 26.882353 | 112 | 0.382203 | [
[
[
"nse_list = ['ADANIPORTS.NS',\n 'ASIANPAINT.NS',\n 'AXISBANK.NS',\n 'BAJAJ-AUTO.NS',\n 'BAJFINANCE.NS',\n 'BAJAJFINSV.NS',\n 'BHARTIARTL.NS',\n 'INFRATEL.NS',\n 'BPCL.NS',\n 'BRITANNIA.NS',\n 'CIPLA.NS',\n 'COALINDIA.NS',\n 'DRREDDY.NS',\n 'EICHERMOT.NS',\n 'GAIL.NS',\n 'GRASIM.NS',\n 'HCLTECH.NS',\n 'HDFC.NS',\n 'HDFCBANK.NS',\n 'HEROMOTOCO.NS',\n 'HINDALCO.NS',\n 'HINDUNILVR.NS',\n 'ICICIBANK.NS',\n 'INDUSINDBK.NS',\n 'INFY.NS',\n 'IOC.NS',\n 'ITC.NS',\n 'JSWSTEEL.NS',\n 'KOTAKBANK.NS',\n 'LT.NS',\n 'M&M.NS',\n 'MARUTI.NS',\n 'NESTLEIND.NS',\n 'NTPC.NS',\n 'ONGC.NS',\n 'POWERGRID.NS',\n 'RELIANCE.NS',\n 'SHREECEM.NS',\n 'SBIN.NS',\n 'SUNPHARMA.NS',\n 'TCS.NS',\n 'TATAMOTORS.NS',\n 'TATASTEEL.NS',\n 'TECHM.NS',\n 'TITAN.NS',\n 'ULTRACEMCO.NS',\n 'UPL.NS',\n 'VEDL.NS',\n 'WIPRO.NS',\n 'ZEEL.NS']",
"_____no_output_____"
],
[
"nse_indices = [\"NIFTY 50\",\n \"NIFTY NEXT 50\",\n \"NIFTY100 LIQ 15\",\n \"NIFTY 100\",\n \"NIFTY 200\",\n \"NIFTY 500\",\n \"NIFTY MIDCAP 50\",\n \"NIFTY MIDCAP 100\",\n \"NIFTY SMALL 100\",\n \"NIFTY AUTO\",\n \"NIFTY BANK\",\n \"NIFTY ENERGY\",\n \"NIFTY FIN SERVICE\",\n \"NIFTY FMCG\",\n \"NIFTY IT\",\n \"NIFTY MEDIA\",\n \"NIFTY METAL\",\n \"NIFTY PHARMA\",\n \"NIFTY PSU BANK\",\n \"NIFTY REALTY\",\n \"NIFTY COMMODITIES\",\n \"NIFTY CONSUMPTION\",\n \"NIFTY CPSE\",\n \"NIFTY INFRA\",\n \"NIFTY MNC\",\n \"NIFTY PSE\",\n \"NIFTY SERV SECTOR\",\n \"NIFTY SHARIAH 25\",\n \"NIFTY50 SHARIAH\",\n \"NIFTY500 SHARIAH\",\n \"NIFTY100 EQUAL WEIGHT\",\n \"NIFTY50 USD\",\n \"NIFTY50 DIV POINT\",\n \"NIFTY DIV OPPS 50\",\n \"NIFTY ALPHA 50\",\n \"NIFTY HIGH BETA 50\",\n \"NIFTY LOW VOLATILITY 50\",\n \"NIFTY QUALITY 30\",\n \"NIFTY50 VALUE 20\",\n \"NIFTY GROWSECT 15\",\n \"NIFTY50 TR 2X LEV\",\n \"NIFTY50 TR 1X INV\", \n ]\n\n",
"_____no_output_____"
],
[
"nse_derivatives = [\"NIFTY BANK\", \"NIFTY INFRA\", \"NIFTY IT\", \"NIFTY MIDCAP 50\", \"NIFTY PSE\" ]\n\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
cb07865e71c512f0ecfee5ee4ad9cbc36b8b4afd | 21,690 | ipynb | Jupyter Notebook | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo | 64919dbc477a3b17f75fc9bf44e5368d7eb96581 | [
"Apache-2.0"
] | null | null | null | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo | 64919dbc477a3b17f75fc9bf44e5368d7eb96581 | [
"Apache-2.0"
] | 8 | 2020-11-30T15:04:16.000Z | 2021-03-07T04:16:40.000Z | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo | 64919dbc477a3b17f75fc9bf44e5368d7eb96581 | [
"Apache-2.0"
] | null | null | null | 28.614776 | 208 | 0.499769 | [
[
[
"咱们的基金是否存在着明显的周内效应呢?就是特定周几盈利高一些,让我们来验证一下吧。",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom datetime import datetime\nimport trdb2py\n\nisStaticImg = False\n\nwidth = 960\nheight = 768\n\npd.options.display.max_columns = None\npd.options.display.max_rows = None\n\ntrdb2cfg = trdb2py.loadConfig('./trdb2.yaml')",
"_____no_output_____"
]
],
[
[
"我们先指定一个特定的基金,特定的时间段来分析吧。",
"_____no_output_____"
]
],
[
[
"# 具体基金\n# asset = 'jrj.510310'\nasset = 'jqdata.000300_XSHG|1d'\n\n# 起始时间,0表示从最开始算起\n# tsStart = 0\ntsStart = int(trdb2py.str2timestamp('2013-05-01', '%Y-%m-%d'))\n\n# 结束时间,-1表示到现在为止\n# tsEnd = -1\ntsEnd = int(trdb2py.str2timestamp('2020-09-30', '%Y-%m-%d'))\n\n# 初始资金池\nparamsinit = trdb2py.trading2_pb2.InitParams(\n money=10000,\n)\n\n# 买入参数,用全部的钱来买入(也就是复利)\nparamsbuy = trdb2py.trading2_pb2.BuyParams(\n perHandMoney=1,\n)\n\n# 卖出参数,全部卖出\nparamssell = trdb2py.trading2_pb2.SellParams(\n perVolume=1,\n)\n\nlststart = [1, 2, 3, 4, 5]\nlsttitle = ['周一', '周二', '周三', '周四', '周五']",
"_____no_output_____"
]
],
[
[
"首先看看这个基金的基准表现,就是在开始时间就直接买入,然后一直持有,看具体的收益率。",
"_____no_output_____"
]
],
[
[
"# baseline \ns0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset), \n)\n \nbuy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='buyandhold',\n)\n\nparamsbuy = trdb2py.trading2_pb2.BuyParams(\n perHandMoney=1,\n)\n\nparamsinit = trdb2py.trading2_pb2.InitParams(\n money=10000,\n)\n\ns0.buy.extend([buy0])\ns0.paramsBuy.CopyFrom(paramsbuy)\ns0.paramsInit.CopyFrom(paramsinit) \np0 = trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='baseline',\n) \n\npnlBaseline = trdb2py.simTrading(trdb2cfg, p0)\ntrdb2py.showPNL(pnlBaseline, toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"那么策略基准线大概就是这样了,7年多的时间2.2倍。",
"_____no_output_____"
],
[
"接下来,先看看最简单的情况,就是特定周几买入,第二天就卖出,只持有1天。",
"_____no_output_____"
]
],
[
[
"lstparams = []\n\nfor i in range(0, 5):\n buy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[lststart[i]],\n )\n\n sell0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[trdb2py.nextWeekDay(lststart[i], 1)],\n )\n\n s0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset),\n )\n\n s0.buy.extend([buy0])\n s0.sell.extend([sell0])\n s0.paramsBuy.CopyFrom(paramsbuy)\n s0.paramsSell.CopyFrom(paramssell)\n s0.paramsInit.CopyFrom(paramsinit) \n lstparams.append(trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='{}买入持有{}天'.format(lsttitle[i], 1),\n ))\n \nlstpnl1 = trdb2py.simTradings(trdb2cfg, lstparams)\n\ntrdb2py.showPNLs(lstpnl1 + [pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"如果看曲线图不是很清楚的话,我们列表看看",
"_____no_output_____"
]
],
[
[
"dfpnl1b = trdb2py.buildPNLReport(lstpnl1 + [pnlBaseline])\n\ndfpnl1b[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False)",
"_____no_output_____"
]
],
[
[
"我看可以看到,虽然盈利都不如基线,但由于波动率降低了。\n\n特别是周一和周五,最大回撤都降低了50%以上,所以夏普都要高于基线。",
"_____no_output_____"
],
[
"上面的策略比较简单,因为有些节假日交易日,所以可能会出现买入了,但无法及时卖出的情况,下面我们换一个确定能卖出才买入的策略看看",
"_____no_output_____"
]
],
[
[
"def calcweekday2val2(wday, offday):\n if offday == 1:\n if wday == 5:\n return 3\n if offday == 2:\n if wday >= 4:\n return 4\n if offday == 3:\n if wday >= 3:\n return 5\n if offday == 4:\n if wday >= 2:\n return 6\n \n return offday\n",
"_____no_output_____"
],
[
"lstparams = []\n\nfor i in range(0, 5):\n buy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[lststart[i], calcweekday2val2(i + 1, 1)],\n )\n\n sell0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[trdb2py.nextWeekDay(lststart[i], 1)],\n )\n\n s0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset),\n )\n\n s0.buy.extend([buy0])\n s0.sell.extend([sell0])\n s0.paramsBuy.CopyFrom(paramsbuy)\n s0.paramsSell.CopyFrom(paramssell)\n s0.paramsInit.CopyFrom(paramsinit) \n lstparams.append(trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='{}买入持有{}天v2'.format(lsttitle[i], 1),\n ))\n \nlstpnl1t = trdb2py.simTradings(trdb2cfg, lstparams)\n\ntrdb2py.showPNLs(lstpnl1t + [pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
],
[
"dfpnl1b = trdb2py.buildPNLReport(lstpnl1 + lstpnl1t + [pnlBaseline])\n\ndfpnl1b[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False)",
"_____no_output_____"
]
],
[
[
"可以看到,虽然有一些差别,但其实影响有好有坏,下面我们还是按v2版的策略来吧",
"_____no_output_____"
],
[
"接下来看看胜率",
"_____no_output_____"
]
],
[
[
"# trdb2py.showBarWinRate4Month(lstpnl1t, valtype='abs', valoff=-0.5, toImg=isStaticImg, width=width, height=height)\n# trdb2py.showBarWinRate4Month(lstpnl1t, toImg=isStaticImg, width=width, height=height)\ntrdb2py.showBarWinRateInYears(lstpnl1t, toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"对于这种随机策略,胜率应该均匀分布在0.5左右的,可以分别看看每一条数据,会发现,周五和周一还是要稍高于0.5的,周二周三稍低于0.5。\n\n当然,这种策略交易比较频繁,次数足够,按月分布来看,没有明显的趋势,所以我们可以直接看整体汇总胜率。",
"_____no_output_____"
]
],
[
[
"wrmt = trdb2py.buildPNLWinRateInMonths(lstpnl1t)\n\nwrmt[0][['title', 'total']]",
"_____no_output_____"
]
],
[
[
"这里,我们对比一下纳指、标普、恒指、上证50、中证500、中小盘,可以得出以下结论:\n\n1. 和走势曲线关系不大,同样大趋势向上的纳指和中小盘,胜率也是能看出差异来的。\n2. 除了有明显高于0.5的以外,最好也能有明显低于0.5的,这样避开低于0.5的,持有高于0.5的,才能获得额外收益,最终明显超过基线。\n3. 纳指、标普、恒指 都没有明显的周内效应。\n4. A股普遍存在较明显的周内效应。\n5. 越是小盘股,周内效应越明显。",
"_____no_output_____"
]
],
[
[
"trdb2py.showBarWinRate4Month(lstpnl1t, toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"接下来,我们统计一下不同月份的胜率,发现,胜率最突出的还是周五买入持有1天,但这个在4月和9月胜率偏低,特别是4月。\n\n接下来看看4月的统计。",
"_____no_output_____"
]
],
[
[
"#trdb2py.showBarWinRateInMonths(lstpnl1t, valtype='abs', valoff=-0.5, month=8, toImg=isStaticImg, width=width, height=height)\ntrdb2py.showBarWinRateInMonths(lstpnl1t, month=4, toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"发现除了2015年和2020年以外,4月确实都是输的。\n\n但是,2015年和2020年4月其实都算是牛市了,不能这样简单的筛选。\n\n目前看来,没有特别的证据表明有明显的可供配合的月度效应。",
"_____no_output_____"
],
[
"如果能把周五、周一的增长叠加起来,是不是结果会更好一些呢\n\n干脆把持有1天到4天的情况,也就是从周一买周二卖,一直到 周一买周五卖,看看",
"_____no_output_____"
]
],
[
[
"lstparams = []\n\nfor day in range(1, 5):\n for i in range(0, 5):\n buy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[lststart[i], calcweekday2val2(i + 1, day)],\n )\n\n sell0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[trdb2py.nextWeekDay(lststart[i], day)],\n )\n\n s0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset),\n )\n\n s0.buy.extend([buy0])\n s0.sell.extend([sell0])\n s0.paramsBuy.CopyFrom(paramsbuy)\n s0.paramsSell.CopyFrom(paramssell)\n s0.paramsInit.CopyFrom(paramsinit) \n lstparams.append(trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='{}买入持有{}天v2'.format(lsttitle[i], day),\n ))\n \nlstpnl = trdb2py.simTradings(trdb2cfg, lstparams)\n\ntrdb2py.showPNLs(lstpnl + [pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
],
[
"dfpnl = trdb2py.buildPNLReport(lstpnl + [pnlBaseline])\n\ndfpnl[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False)",
"_____no_output_____"
]
],
[
[
"单看回报率,已经有明显超过基线的了,而且,最好的情况,夏普提升了近3倍",
"_____no_output_____"
],
[
"接下来,还能想到的,如果在下降的时候,定投买入,最终会不会也能获得额外收益呢?\n\n还是周一到周五一起测一下吧。",
"_____no_output_____"
]
],
[
[
"lstparams = []\n\nfor i in range(0, 5):\n buy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[lststart[i]],\n )\n\n s0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset),\n )\n \n paramsaip = trdb2py.trading2_pb2.AIPParams(\n money=10000,\n type=trdb2py.trading2_pb2.AIPTT_MONTHDAY,\n day=lststart[i],\n )\n\n s0.buy.extend([buy0])\n s0.paramsBuy.CopyFrom(paramsbuy)\n s0.paramsSell.CopyFrom(paramssell)\n s0.paramsInit.CopyFrom(paramsinit)\n s0.paramsAIP.CopyFrom(paramsaip)\n lstparams.append(trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='{}定投'.format(lsttitle[i], day),\n ))\n \nlstaippnl = trdb2py.simTradings(trdb2cfg, lstparams)\n\ntrdb2py.showPNLs(lstaippnl + [pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
]
],
[
[
"我们可以看到5条收益曲线几乎重合在一起,说明,特定周几购买,其实并没有差别。\n\n关于定投,后面会有更详细的测试,这里还是回到如何榨取周内效应的最大收益上。",
"_____no_output_____"
],
[
"我们还可以考虑加入均线策略,看看在均线上下方买入,是否有区别,其实如果均线粒度够大,一定程度上能将牛市和熊市区分开。\n\n这个运算量有点大,大概有24000种,我直接给出结论吧。",
"_____no_output_____"
]
],
[
[
"lstparams = []\n\nfor ema in range(5, 61): \n for sdo in range(1, 5):\n for sd in range(1, 6):\n buy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[sd, calcweekday2val2(sd, sdo)],\n )\n\n buy1 = trdb2py.trading2_pb2.CtrlCondition(\n name='indicatorsp',\n operators=['up'],\n strVals=['ema.{}'.format(ema)],\n )\n \n sell0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[trdb2py.nextWeekDay(sd, sdo)],\n )\n\n sell1 = trdb2py.trading2_pb2.CtrlCondition(\n name='ctrlconditionid',\n vals=[1],\n strVals=['buy'],\n ) \n \n for edo in range(1, 5):\n for ed in range(1, 6):\n\n buy2 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[ed, calcweekday2val2(ed, edo)],\n group=1,\n )\n\n buy3 = trdb2py.trading2_pb2.CtrlCondition(\n name='indicatorsp',\n operators=['down'],\n strVals=['ema.{}'.format(ema)],\n group=1, \n )\n\n sell2 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[trdb2py.nextWeekDay(ed, edo)],\n group=1, \n )\n\n sell3 = trdb2py.trading2_pb2.CtrlCondition(\n name='ctrlconditionid',\n vals=[2],\n strVals=['buy'],\n group=1, \n )\n \n\n s0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset),\n )\n\n s0.buy.extend([buy0, buy1, buy2, buy3])\n s0.sell.extend([sell0, sell1, sell2, sell3])\n s0.paramsBuy.CopyFrom(paramsbuy)\n s0.paramsSell.CopyFrom(paramssell) \n s0.paramsInit.CopyFrom(paramsinit) \n lstparams.append(trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='ema{}up{}持有{}天down{}持有{}天'.format(ema, lsttitle[sd-1], sdo, lsttitle[ed-1], edo),\n ))\n \nlstpnlmix = trdb2py.simTradings(trdb2cfg, lstparams, ignoreTotalReturn=4)\n\n# trdb2py.showPNLs(lstpnlmix + [pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____no_output_____"
],
[
"dfpnl = trdb2py.buildPNLReport(lstpnlmix + [pnlBaseline])\n\ndfpnl1 = dfpnl[dfpnl['totalReturns'] >= 1]\n\ndfpnl1[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False)",
"_____no_output_____"
],
[
"asset = 'jqdata.000300_XSHG|1d'\n# asset = 'jqdata.000905_XSHG|1d'\n# asset = 'jqdata.000932_XSHG|1d'\n\ns0 = trdb2py.trading2_pb2.Strategy(\n name=\"normal\",\n asset=trdb2py.str2asset(asset), \n)\n \nbuy0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[4, calcweekday2val2(4, 4)],\n)\n\nbuy1 = trdb2py.trading2_pb2.CtrlCondition(\n name='indicatorsp',\n operators=['up'],\n strVals=['ema.{}'.format(29)],\n)\n\nbuy2 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday2',\n vals=[1, calcweekday2val2(1, 4)],\n group=1,\n)\n\nbuy3 = trdb2py.trading2_pb2.CtrlCondition(\n name='indicatorsp',\n operators=['down'],\n strVals=['ema.29'],\n group=1, \n)\n\nsell0 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[3],\n)\n\nsell1 = trdb2py.trading2_pb2.CtrlCondition(\n name='ctrlconditionid',\n vals=[1],\n strVals=['buy'],\n)\n\nsell2 = trdb2py.trading2_pb2.CtrlCondition(\n name='weekday',\n vals=[5],\n group=1, \n)\n\nsell3 = trdb2py.trading2_pb2.CtrlCondition(\n name='ctrlconditionid',\n vals=[2],\n strVals=['buy'],\n group=1, \n)\n\nparamsbuy = trdb2py.trading2_pb2.BuyParams(\n perHandMoney=1,\n)\n\nparamsinit = trdb2py.trading2_pb2.InitParams(\n money=10000,\n)\n\ns0.buy.extend([buy0, buy1, buy2, buy3])\ns0.sell.extend([sell0, sell1, sell2, sell3])\ns0.paramsBuy.CopyFrom(paramsbuy)\ns0.paramsSell.CopyFrom(paramssell) \ns0.paramsInit.CopyFrom(paramsinit) \np0 = trdb2py.trading2_pb2.SimTradingParams(\n assets=[trdb2py.str2asset(asset)],\n startTs=tsStart,\n endTs=tsEnd,\n strategies=[s0],\n title='混合策略',\n) \n\npnlm = trdb2py.simTrading(trdb2cfg, p0)\n\ntrdb2py.showPNLs([pnlm, pnlBaseline], toImg=isStaticImg, width=width, height=height)",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb07b75759c7e1798ec606f400503ae6c09b27e2 | 3,753 | ipynb | Jupyter Notebook | notebook/RemoveDirtyLabel.ipynb | j20232/moco_image_pipeline | 997ae76e795548e75f95e862284c1fc0a3c7541a | [
"BSD-3-Clause"
] | 5 | 2020-03-18T14:36:12.000Z | 2022-01-26T09:36:11.000Z | notebook/RemoveDirtyLabel.ipynb | j20232/moco_image_pipeline | 997ae76e795548e75f95e862284c1fc0a3c7541a | [
"BSD-3-Clause"
] | null | null | null | notebook/RemoveDirtyLabel.ipynb | j20232/moco_image_pipeline | 997ae76e795548e75f95e862284c1fc0a3c7541a | [
"BSD-3-Clause"
] | null | null | null | 28.431818 | 135 | 0.547562 | [
[
[
"import pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder",
"_____no_output_____"
],
[
"ROOT_PATH = Path(\".\").resolve().parents[0] # please change here\n",
"_____no_output_____"
],
[
"def make_validation(ratio=0.2, random_state=1116):\n le = LabelEncoder()\n train_df = pd.read_csv(ROOT_PATH / \"input\" / \"bengaliai-cv19\" / \"train.csv\")\n le = le.fit(train_df['grapheme'])\n train_df['unique_label'] = le.transform(train_df['grapheme'])\n train_df = train_df.query(\"grapheme!='র্দ্র' and grapheme!='র্ত্রে' and grapheme!= 'র্ত্রী'\")\n train, valid = train_test_split(train_df, test_size=ratio, random_state=random_state, stratify=train_df[\"unique_label\"])\n out_train = train.set_index(\"image_id\")\n out_valid = valid.set_index(\"image_id\")\n print(\"train length: {} {}\".format(len(out_train), len(out_train) / len(train_df)))\n print(\"valid length: {} {}\".format(len(out_valid), len(out_valid) / len(train_df)))\n print(out_train[\"unique_label\"].nunique())\n print(out_valid[\"unique_label\"].nunique())\n print(\"-------------------\")\n out_train.to_csv(ROOT_PATH / \"input\" / \"bengaliai-cv19\" / \"moco_train2_{}.csv\".format(int(ratio * 100)))\n out_valid.to_csv(ROOT_PATH / \"input\" / \"bengaliai-cv19\" / \"moco_valid2_{}.csv\".format(int(ratio * 100)))",
"_____no_output_____"
],
[
"make_validation(0.20)\nmake_validation(0.15)\nmake_validation(0.10)",
"train length: 160315 0.7999990019661267\nvalid length: 40079 0.20000099803387328\n1292\n1292\n-------------------\ntrain length: 170334 0.8499955088475702\nvalid length: 30060 0.15000449115242973\n1292\n1292\n-------------------\ntrain length: 180354 0.8999970058983802\nvalid length: 20040 0.10000299410161981\n1292\n1292\n-------------------\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
cb07b871dff5bd513f443f0f94a7c7650a293080 | 65,200 | ipynb | Jupyter Notebook | prediction-model-aai.ipynb | dinesh13n/assignment-aai | 18a8931d7a86163a9ab9d7d49beee8fc8f2f5994 | [
"MIT"
] | null | null | null | prediction-model-aai.ipynb | dinesh13n/assignment-aai | 18a8931d7a86163a9ab9d7d49beee8fc8f2f5994 | [
"MIT"
] | null | null | null | prediction-model-aai.ipynb | dinesh13n/assignment-aai | 18a8931d7a86163a9ab9d7d49beee8fc8f2f5994 | [
"MIT"
] | null | null | null | 37.003405 | 149 | 0.351764 | [
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom application_logging.logger import AppLog\nfrom utils.common import read_config\nfrom utils.common import FileOperations\nfrom Data_Preprocessing.preprocessing import Preprocessor\nfrom Predict_Model.predictFromModel import prediction",
"_____no_output_____"
],
[
"# Set the display option None, so all the dataframe column would display.\npd.set_option('display.max_columns', None)",
"_____no_output_____"
],
[
"# Initialize logger object to capture the log in log file\nexecType = 'Prediction'\npredictionlog = AppLog(execType)\nlog = predictionlog.log(\"sLogger\")\n\n# Read parameter from the config.yaml\nconfig = read_config('config.yaml')\nprediction_file_path = config[\"prediction\"][\"prediction_file_path\"]",
"_____no_output_____"
],
[
"# Read training dataset\nobjPredictionFile = FileOperations(execType)\n_, Raw_Prediction_Data = objPredictionFile.ReadCSVData(filepath=prediction_file_path)\nRaw_Prediction_Data",
"_____no_output_____"
],
[
"# Check the data type for dataframe columns\nif (Raw_Prediction_Data.shape[1] == Raw_Prediction_Data.select_dtypes(include=np.number).shape[1]):\n print(\"All the column from dataframe is numeric data type, so no need to process for data type conversion\")\n log.info(\"All the column from dataframe is numeric data type, so no need to process for data type conversion\")",
"All the column from dataframe is numeric data type, so no need to process for data type conversion\n"
]
],
[
[
"### EDA on training dataset",
"_____no_output_____"
]
],
[
[
"#### check if dataframe has null value, then call KNN Imputer to Impute the appropriate value \n#### (Check the nearest 3 value to impute)\nobjPrediction = Preprocessor(execType)\nif Raw_Prediction_Data.isnull().values.any():\n log.info(\"Initiate to Impute null value for the null value columns\")\n Raw_Prediction_Data = objPrediction.impute_missing_values(Raw_Training_Data)\n log.info(\"Null value imputation done successfully\")\nelse:\n print (\"Dataset doesn't contain null value in any of the columns\")\n log.info(\"Dataset doesn't contain null value in any of the columns\")",
"Dataset doesn't contain null value in any of the columns\n"
],
[
"# Describe the dataset\nRaw_Prediction_Data.describe()",
"_____no_output_____"
],
[
"# Get the independent feature columns\ndataColumns=['X'+str(i) for i in range(1,58)]\nlen(dataColumns)",
"_____no_output_____"
]
],
[
[
"### Predict the Model",
"_____no_output_____"
]
],
[
[
"objTraining = prediction(execType)\n# X33 data has multicolinearity during preprocessing on traing data, so need to remove from prediction as well\nstatus = objTraining.predictionFromModel(Raw_Prediction_Data[dataColumns],dataColumns, ['X33'])",
"C:\\Users\\DineshNaik\\anaconda3\\lib\\site-packages\\pandas\\core\\frame.py:3607: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._set_item(key, value)\nC:\\Users\\DineshNaik\\anaconda3\\lib\\site-packages\\pandas\\core\\frame.py:3607: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._set_item(key, value)\nC:\\Users\\DineshNaik\\anaconda3\\lib\\site-packages\\pandas\\core\\frame.py:3607: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._set_item(key, value)\nC:\\Users\\DineshNaik\\anaconda3\\lib\\site-packages\\pandas\\core\\frame.py:3607: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self._set_item(key, value)\n"
],
[
"if status == 1:\n print (\"Successful End of Training\")\nelse:\n print (\"Unsuccessful End of Training\")",
"Successful End of Training\n"
]
],
[
[
"#### Prediction file is available in \"Prediction_Output_File/Predictions.csv\" path location.",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb07b991c539d07fbc17641c18e890a308f1da49 | 487,819 | ipynb | Jupyter Notebook | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop | 421e9b8b3941c825262e46fdf09243996e757992 | [
"Apache-2.0"
] | 1 | 2020-12-14T06:07:12.000Z | 2020-12-14T06:07:12.000Z | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | MaxCodeXTC/spark-nlp-workshop | 2a5c9ceceebe8783855b04759979216ce48be7bc | [
"Apache-2.0"
] | null | null | null | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | MaxCodeXTC/spark-nlp-workshop | 2a5c9ceceebe8783855b04759979216ce48be7bc | [
"Apache-2.0"
] | null | null | null | 108.66986 | 174,862 | 0.767391 | [
[
[
"",
"_____no_output_____"
],
[
"[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb)",
"_____no_output_____"
],
[
"# Spark NLP Basics and Pretrained Pipelines",
"_____no_output_____"
],
[
"## 0. Colab Setup",
"_____no_output_____"
]
],
[
[
"import os\n\n# Install java\n! apt-get update -qq\n! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null\n\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ[\"PATH\"] = os.environ[\"JAVA_HOME\"] + \"/bin:\" + os.environ[\"PATH\"]\n! java -version\n\n# Install pyspark\n! pip install --ignore-installed -q pyspark==2.4.4\n! pip install --ignore-installed -q spark-nlp==2.6.3-rc1",
"openjdk version \"1.8.0_265\"\nOpenJDK Runtime Environment (build 1.8.0_265-8u265-b01-0ubuntu2~18.04-b01)\nOpenJDK 64-Bit Server VM (build 25.265-b01, mixed mode)\n\u001b[K |████████████████████████████████| 133kB 2.8MB/s \n\u001b[?25h"
]
],
[
[
"\n#### **How to prevent Google Colab from disconnecting?**\n\nGoogle Colab notebooks have an idle timeout of 90 minutes and absolute timeout of 12 hours. This means, if user does not interact with his Google Colab notebook for more than 90 minutes, its instance is automatically terminated. Also, maximum lifetime of a Colab instance is **12 hours.**\n\nSet a javascript interval to click on the connect button every 60 seconds. Open developer-settings (in your web-browser) with Ctrl+Shift+I then click on console tab and type this on the console prompt. (for mac press Option+Command+I)\n\n",
"_____no_output_____"
]
],
[
[
"''' \n\nfunction ConnectButton(){\n console.log(\"Connect pushed\"); \n document.querySelector(\"#top-toolbar > colab-connect-button\").shadowRoot.querySelector(\"#connect\").click() \n}\nsetInterval(ConnectButton,60000);\n\n'''",
"_____no_output_____"
]
],
[
[
"## 1. Start Spark Session",
"_____no_output_____"
]
],
[
[
"import sparknlp\n\nspark = sparknlp.start()\n\n# params =>> gpu=False, spark23=False (start with spark 2.3)\n\nprint(\"Spark NLP version\", sparknlp.version())\n\nprint(\"Apache Spark version:\", spark.version)\n",
"Spark NLP version 2.6.3-rc1\nApache Spark version: 2.4.4\n"
]
],
[
[
"\n<b> if you want to work with Spark 2.3 </b>\n```\nimport os\n\n# Install java\n! apt-get update -qq\n! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null\n\n!wget -q https://archive.apache.org/dist/spark/spark-2.3.0/spark-2.3.0-bin-hadoop2.7.tgz\n\n!tar xf spark-2.3.0-bin-hadoop2.7.tgz\n!pip install -q findspark\n\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ[\"PATH\"] = os.environ[\"JAVA_HOME\"] + \"/bin:\" + os.environ[\"PATH\"]\nos.environ[\"SPARK_HOME\"] = \"/content/spark-2.3.0-bin-hadoop2.7\"\n! java -version\n\nimport findspark\nfindspark.init()\nfrom pyspark.sql import SparkSession\n\n! pip install --ignore-installed -q spark-nlp==2.5.5\nimport sparknlp\n\nspark = sparknlp.start(spark23=True)\n```",
"_____no_output_____"
],
[
"`sparknlp.start()` will start or get SparkSession with predefined parameters hardcoded in `spark-nlp/python/sparknlp/__init__.py`. here is what is going on under the hood when you run `sparknlp.start()` ",
"_____no_output_____"
]
],
[
[
"# https://github.com/JohnSnowLabs/spark-nlp/blob/master/python/sparknlp/__init__.py\n\nfrom pyspark.sql import SparkSession\n\ndef start(gpu=False, spark23=False):\n current_version=\"2.5.4\"\n maven_spark24 = \"com.johnsnowlabs.nlp:spark-nlp_2.11:{}\".format(current_version)\n maven_gpu_spark24 = \"com.johnsnowlabs.nlp:spark-nlp-gpu_2.11:{}\".format(current_version)\n maven_spark23 = \"com.johnsnowlabs.nlp:spark-nlp-spark23_2.11:{}\".format(current_version)\n maven_gpu_spark23 = \"com.johnsnowlabs.nlp:spark-nlp-gpu-spark23_2.11:{}\".format(current_version)\n\n builder = SparkSession.builder \\\n .appName(\"Spark NLP\") \\\n .master(\"local[*]\") \\\n .config(\"spark.driver.memory\", \"16G\") \\\n .config(\"spark.serializer\", \"org.apache.spark.serializer.KryoSerializer\") \\\n .config(\"spark.kryoserializer.buffer.max\", \"1000M\") \\\n .config(\"spark.driver.maxResultSize\", \"0\")\n if gpu and spark23:\n builder.config(\"spark.jars.packages\", maven_gpu_spark23)\n elif spark23:\n builder.config(\"spark.jars.packages\", maven_spark23)\n elif gpu:\n builder.config(\"spark.jars.packages\", maven_gpu_spark24)\n else:\n builder.config(\"spark.jars.packages\", maven_spark24)\n \n return builder.getOrCreate()\n",
"_____no_output_____"
]
],
[
[
"If you want to start `SparkSession` with your own parameters or you need to load the required jars/packages from your local disk, or you have no internet connection (that would be needed to pull the required packages from internet), you can skip `sparknlp.start()` and start your session manually as shown below.\n",
"_____no_output_____"
]
],
[
[
"\"\"\"\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName(\"Spark NLP Enterprise 2.4.5\") \\\n .master(\"local[8]\") \\\n .config(\"spark.driver.memory\",\"12G\") \\\n .config(\"spark.driver.maxResultSize\", \"2G\") \\\n .config(\"spark.serializer\", \"org.apache.spark.serializer.KryoSerializer\") \\\n .config(\"spark.kryoserializer.buffer.max\", \"800M\")\\\n .config(\"spark.jars\", \"{}spark-nlp-2.4.5.jar,{}spark-nlp-jsl-2.4.5.jar\".format(jar_path,jar_path)) \\\n .getOrCreate()\n \n\"\"\"",
"_____no_output_____"
]
],
[
[
"CPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-assembly-2.6.2.jar\n\nGPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-gpu-assembly-2.6.2.jar\n\nCPU on Apache Spark 2.3.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-spark23-assembly-2.6.2.jar\n\nGPU on Apache Spark 2.3.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-spark23-gpu-assembly-2.6.2.jar",
"_____no_output_____"
],
[
"## 2. Using Pretrained Pipelines",
"_____no_output_____"
],
[
"https://github.com/JohnSnowLabs/spark-nlp-models\n\nhttps://nlp.johnsnowlabs.com/models\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"from sparknlp.pretrained import PretrainedPipeline",
"_____no_output_____"
],
[
"testDoc = '''\nPeter is a very good persn.\nMy life in Russia is very intersting.\nJohn and Peter are brothrs. However they don't support each other that much.\nLucas Nogal Dunbercker is no longer happy. He has a good car though.\nEurope is very culture rich. There are huge churches! and big houses!\n'''",
"_____no_output_____"
]
],
[
[
"### Explain Document ML",
"_____no_output_____"
],
[
"**Stages**\n- DocumentAssembler\n- SentenceDetector\n- Tokenizer\n- Lemmatizer\n- Stemmer\n- Part of Speech\n- SpellChecker (Norvig)\n\n\n",
"_____no_output_____"
]
],
[
[
"pipeline = PretrainedPipeline('explain_document_ml', lang='en')\n",
"explain_document_ml download started this may take some time.\nApprox size to download 9.4 MB\n[OK!]\n"
],
[
"pipeline.model.stages",
"_____no_output_____"
],
[
"# Load pretrained pipeline from local disk:\n\npipeline_local = PretrainedPipeline.from_disk('/root/cache_pretrained/explain_document_ml_en_2.4.0_2.4_1580252705962')",
"_____no_output_____"
],
[
"%%time\n\nresult = pipeline.annotate(testDoc)",
"CPU times: user 35.6 ms, sys: 8.68 ms, total: 44.3 ms\nWall time: 1.34 s\n"
],
[
"result.keys()",
"_____no_output_____"
],
[
"result['sentence']",
"_____no_output_____"
],
[
"result['token']",
"_____no_output_____"
],
[
"list(zip(result['token'], result['pos']))",
"_____no_output_____"
],
[
"list(zip(result['token'], result['lemmas'], result['stems'], result['spell']))",
"_____no_output_____"
],
[
"import pandas as pd\n\ndf = pd.DataFrame({'token':result['token'], \n 'corrected':result['spell'], 'POS':result['pos'],\n 'lemmas':result['lemmas'], 'stems':result['stems']})\ndf",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"### Explain Document DL",
"_____no_output_____"
],
[
"**Stages**\n- DocumentAssembler\n- SentenceDetector\n- Tokenizer\n- NER (NER with GloVe 100D embeddings, CoNLL2003 dataset)\n- Lemmatizer\n- Stemmer\n- Part of Speech\n- SpellChecker (Norvig)\n",
"_____no_output_____"
]
],
[
[
"pipeline_dl = PretrainedPipeline('explain_document_dl', lang='en')\n",
"explain_document_dl download started this may take some time.\nApprox size to download 168.4 MB\n[OK!]\n"
],
[
"pipeline_dl.model.stages",
"_____no_output_____"
],
[
"pipeline_dl.model.stages[-2].getStorageRef()",
"_____no_output_____"
],
[
"pipeline_dl.model.stages[-2].getClasses()",
"_____no_output_____"
],
[
"%%time\n\nresult = pipeline_dl.annotate(testDoc)\n\nresult.keys()",
"CPU times: user 52.8 ms, sys: 18 ms, total: 70.8 ms\nWall time: 1.38 s\n"
],
[
"result.keys()",
"_____no_output_____"
],
[
"result['entities']",
"_____no_output_____"
],
[
"df = pd.DataFrame({'token':result['token'], 'ner_label':result['ner'],\n 'spell_corrected':result['checked'], 'POS':result['pos'],\n 'lemmas':result['lemma'], 'stems':result['stem']})\n\ndf",
"_____no_output_____"
]
],
[
[
"### Recognize Entities DL",
"_____no_output_____"
]
],
[
[
"recognize_entities = PretrainedPipeline('recognize_entities_dl', lang='en')\n",
"recognize_entities_dl download started this may take some time.\nApprox size to download 159 MB\n[OK!]\n"
],
[
"testDoc = '''\nPeter is a very good persn.\nMy life in Russia is very intersting.\nJohn and Peter are brothrs. However they don't support each other that much.\nLucas Nogal Dunbercker is no longer happy. He has a good car though.\nEurope is very culture rich. There are huge churches! and big houses!\n'''\n\nresult = recognize_entities.annotate(testDoc)\n\nlist(zip(result['token'], result['ner']))",
"_____no_output_____"
]
],
[
[
"### Clean Stop Words",
"_____no_output_____"
]
],
[
[
"clean_stop = PretrainedPipeline('clean_stop', lang='en')\n",
"clean_stop download started this may take some time.\nApprox size to download 12.4 KB\n[OK!]\n"
],
[
"\nresult = clean_stop.annotate(testDoc)\nresult.keys()",
"_____no_output_____"
],
[
"\n' '.join(result['cleanTokens'])",
"_____no_output_____"
]
],
[
[
"### Clean Slang ",
"_____no_output_____"
]
],
[
[
"clean_slang = PretrainedPipeline('clean_slang', lang='en')\n\nresult = clean_slang.annotate(' Whatsup bro, call me ASAP')\n\n' '.join(result['normal'])",
"clean_slang download started this may take some time.\nApprox size to download 21.8 KB\n[OK!]\n"
]
],
[
[
"### Spell Checker \n\n(Norvig Algo)\n\nref: https://norvig.com/spell-correct.html",
"_____no_output_____"
]
],
[
[
"spell_checker = PretrainedPipeline('check_spelling', lang='en')\n",
"check_spelling download started this may take some time.\nApprox size to download 892.6 KB\n[OK!]\n"
],
[
"testDoc = '''\nPeter is a very good persn.\nMy life in Russia is very intersting.\nJohn and Peter are brothrs. However they don't support each other that much.\nLucas Nogal Dunbercker is no longer happy. He has a good car though.\nEurope is very culture rich. There are huge churches! and big houses!\n'''\n\nresult = spell_checker.annotate(testDoc)\n\nresult.keys()",
"_____no_output_____"
],
[
"list(zip(result['token'], result['checked']))",
"_____no_output_____"
]
],
[
[
"### Spell Checker DL\n\nhttps://medium.com/spark-nlp/applying-context-aware-spell-checking-in-spark-nlp-3c29c46963bc",
"_____no_output_____"
]
],
[
[
"spell_checker_dl = PretrainedPipeline('check_spelling_dl', lang='en')\n",
"check_spelling_dl download started this may take some time.\nApprox size to download 112.1 MB\n[OK!]\n"
],
[
"text = 'We will go to swimming if the ueather is nice.'\n\nresult = spell_checker_dl.annotate(text)\n\nlist(zip(result['token'], result['checked']))",
"_____no_output_____"
],
[
"result.keys()",
"_____no_output_____"
],
[
"# check for the different occurrences of the word \"ueather\"\nexamples = ['We will go to swimming if the ueather is nice.',\\\n \"I have a black ueather jacket, so nice.\",\\\n \"I introduce you to my sister, she is called ueather.\"]\n\nresults = spell_checker_dl.annotate(examples)\n\nfor result in results:\n print (list(zip(result['token'], result['checked'])))",
"[('We', 'We'), ('will', 'will'), ('go', 'go'), ('to', 'to'), ('swimming', 'swimming'), ('if', 'if'), ('the', 'the'), ('ueather', 'weather'), ('is', 'is'), ('nice', 'nice'), ('.', '.')]\n[('I', 'I'), ('have', 'have'), ('a', 'a'), ('black', 'black'), ('ueather', 'leather'), ('jacket', 'jacket'), (',', ','), ('so', 'so'), ('nice', 'nice'), ('.', '.')]\n[('I', 'I'), ('introduce', 'introduce'), ('you', 'you'), ('to', 'to'), ('my', 'my'), ('sister', 'sister'), (',', ','), ('she', 'she'), ('is', 'is'), ('called', 'called'), ('ueather', 'Heather'), ('.', '.')]\n"
],
[
"for result in results:\n print (result['document'],'>>',[pairs for pairs in list(zip(result['token'], result['checked'])) if pairs[0]!=pairs[1]])",
"['We will go to swimming if the ueather is nice.'] >> [('ueather', 'weather')]\n['I have a black ueather jacket, so nice.'] >> [('ueather', 'leather')]\n['I introduce you to my sister, she is called ueather.'] >> [('ueather', 'Heather')]\n"
],
[
"# if we had tried the same with spell_checker (previous version)\n\nresults = spell_checker.annotate(examples)\n\nfor result in results:\n print (list(zip(result['token'], result['checked'])))",
"[('We', 'We'), ('will', 'will'), ('go', 'go'), ('to', 'to'), ('swimming', 'swimming'), ('if', 'if'), ('the', 'the'), ('ueather', 'weather'), ('is', 'is'), ('nice', 'nice'), ('.', '.')]\n[('I', 'I'), ('have', 'have'), ('a', 'a'), ('black', 'black'), ('ueather', 'weather'), ('jacket', 'jacket'), (',', ','), ('so', 'so'), ('nice', 'nice'), ('.', '.')]\n[('I', 'I'), ('introduce', 'introduce'), ('you', 'you'), ('to', 'to'), ('my', 'my'), ('sister', 'sister'), (',', ','), ('she', 'she'), ('is', 'is'), ('called', 'called'), ('ueather', 'weather'), ('.', '.')]\n"
]
],
[
[
"### Parsing a list of texts",
"_____no_output_____"
]
],
[
[
"testDoc_list = ['French author who helped pioner the science-fiction genre.',\n'Verne wrate about space, air, and underwater travel before navigable aircrast',\n'Practical submarines were invented, and before any means of space travel had been devised.']\n\ntestDoc_list",
"_____no_output_____"
],
[
"pipeline = PretrainedPipeline('explain_document_ml', lang='en')\n",
"explain_document_ml download started this may take some time.\nApprox size to download 9.4 MB\n[OK!]\n"
],
[
"result_list = pipeline.annotate(testDoc_list)\n\nlen (result_list)",
"_____no_output_____"
],
[
"result_list[0]",
"_____no_output_____"
]
],
[
[
"### Using fullAnnotate to get more details\n\n",
"_____no_output_____"
],
[
"```\nannotatorType: String, \nbegin: Int, \nend: Int, \nresult: String, (this is what annotate returns)\nmetadata: Map[String, String], \nembeddings: Array[Float]\n```",
"_____no_output_____"
]
],
[
[
"text = 'Peter Parker is a nice guy and lives in New York'",
"_____no_output_____"
],
[
"# pipeline_dl >> explain_document_dl\n\ndetailed_result = pipeline_dl.fullAnnotate(text)",
"_____no_output_____"
],
[
"detailed_result",
"_____no_output_____"
],
[
"detailed_result[0]['entities']",
"_____no_output_____"
],
[
"detailed_result[0]['entities'][0].result",
"_____no_output_____"
],
[
"chunks=[]\nentities=[]\nfor n in detailed_result[0]['entities']:\n \n chunks.append(n.result)\n entities.append(n.metadata['entity']) \n \ndf = pd.DataFrame({'chunks':chunks, 'entities':entities})\ndf ",
"_____no_output_____"
],
[
"tuples = []\n\nfor x,y,z in zip(detailed_result[0][\"token\"], detailed_result[0][\"pos\"], detailed_result[0][\"ner\"]):\n\n tuples.append((int(x.metadata['sentence']), x.result, x.begin, x.end, y.result, z.result))\n\ndf = pd.DataFrame(tuples, columns=['sent_id','token','start','end','pos', 'ner'])\n\ndf\n",
"_____no_output_____"
]
],
[
[
"### Use pretrained match_chunk Pipeline for Individual Noun Phrase",
"_____no_output_____"
],
[
"**Stages**\n- DocumentAssembler\n- SentenceDetector\n- Tokenizer\n- Part of Speech\n- Chunker\n\nPipeline:\n\n- The pipeline uses regex `<DT>?<JJ>*<NN>+`\n- which states that whenever the chunk finds an optional determiner (DT) followed by any number of adjectives (JJ) and then a noun (NN) then the Noun Phrase(NP) chunk should be formed.",
"_____no_output_____"
]
],
[
[
"pipeline = PretrainedPipeline('match_chunks', lang='en')\n",
"match_chunks download started this may take some time.\nApprox size to download 4.3 MB\n[OK!]\n"
],
[
"pipeline.model.stages",
"_____no_output_____"
],
[
"result = pipeline.annotate(\"The book has many chapters\") # single noun phrase",
"_____no_output_____"
],
[
"result",
"_____no_output_____"
],
[
"result['chunk']",
"_____no_output_____"
],
[
"result = pipeline.annotate(\"the little yellow dog barked at the cat\") #multiple noune phrases",
"_____no_output_____"
],
[
"result",
"_____no_output_____"
],
[
"result['chunk']",
"_____no_output_____"
]
],
[
[
"### Extract exact dates from referential date phrases",
"_____no_output_____"
]
],
[
[
"pipeline = PretrainedPipeline('match_datetime', lang='en')\n",
"match_datetime download started this may take some time.\nApprox size to download 12.9 KB\n[OK!]\n"
],
[
"result = pipeline.annotate(\"I saw him yesterday and he told me that he will visit us next week\")\n\nresult",
"_____no_output_____"
],
[
"detailed_result = pipeline.fullAnnotate(\"I saw him yesterday and he told me that he will visit us next week\")\n\ndetailed_result",
"_____no_output_____"
],
[
"tuples = []\n\nfor x in detailed_result[0][\"token\"]:\n\n tuples.append((int(x.metadata['sentence']), x.result, x.begin, x.end))\n\ndf = pd.DataFrame(tuples, columns=['sent_id','token','start','end'])\n\ndf",
"_____no_output_____"
]
],
[
[
"### Sentiment Analysis\n",
"_____no_output_____"
],
[
"#### Vivek algo\n\npaper: `Fast and accurate sentiment classification using an enhanced Naive Bayes model`\n\nhttps://arxiv.org/abs/1305.6143\n\ncode `https://github.com/vivekn/sentiment`",
"_____no_output_____"
]
],
[
[
"sentiment = PretrainedPipeline('analyze_sentiment', lang='en')",
"analyze_sentiment download started this may take some time.\nApprox size to download 4.9 MB\n[OK!]\n"
],
[
"result = sentiment.annotate(\"The movie I watched today was not a good one\")\n\nresult['sentiment']",
"_____no_output_____"
]
],
[
[
"#### DL version (trained on imdb)",
"_____no_output_____"
]
],
[
[
"sentiment_imdb = PretrainedPipeline('analyze_sentimentdl_use_imdb', lang='en')",
"analyze_sentimentdl_use_imdb download started this may take some time.\nApprox size to download 935.8 MB\n[OK!]\n"
],
[
"sentiment_imdb_glove = PretrainedPipeline('analyze_sentimentdl_glove_imdb', lang='en')",
"analyze_sentimentdl_glove_imdb download started this may take some time.\nApprox size to download 154.9 MB\n[OK!]\n"
],
[
"comment = '''\nIt's a very scary film but what impressed me was how true the film sticks to the original's tricks; it isn't filled with loud in-your-face jump scares, in fact, a lot of what makes this film scary is the slick cinematography and intricate shadow play. The use of lighting and creation of atmosphere is what makes this film so tense, which is why it's perfectly suited for those who like Horror movies but without the obnoxious gore.\n'''\nresult = sentiment_imdb_glove.annotate(comment)\n\nresult['sentiment']",
"_____no_output_____"
],
[
"sentiment_imdb_glove.fullAnnotate(comment)[0]['sentiment']",
"_____no_output_____"
]
],
[
[
"#### DL version (trained on twitter dataset)",
"_____no_output_____"
]
],
[
[
"sentiment_twitter = PretrainedPipeline('analyze_sentimentdl_use_twitter', lang='en')",
"analyze_sentimentdl_use_twitter download started this may take some time.\nApprox size to download 928.3 MB\n[OK!]\n"
],
[
"result = sentiment_twitter.annotate(\"The movie I watched today was not a good one\")\n\nresult['sentiment']",
"_____no_output_____"
],
[
"",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb07d546884cb0279d52d81844e18d00085714d0 | 23,906 | ipynb | Jupyter Notebook | PY0101EN-2-3-Sets.ipynb | vatsal30/Python | 0013d21aa69db6c57bba9e343c3e161bd66cb2ce | [
"MIT"
] | null | null | null | PY0101EN-2-3-Sets.ipynb | vatsal30/Python | 0013d21aa69db6c57bba9e343c3e161bd66cb2ce | [
"MIT"
] | null | null | null | PY0101EN-2-3-Sets.ipynb | vatsal30/Python | 0013d21aa69db6c57bba9e343c3e161bd66cb2ce | [
"MIT"
] | null | null | null | 22.638258 | 716 | 0.512047 | [
[
[
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n <a href=\"https://cocl.us/PY0101EN_edx_add_top\">\n <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png\" width=\"750\" align=\"center\">\n </a>\n</div>",
"_____no_output_____"
],
[
"<a href=\"https://cognitiveclass.ai/\">\n <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/CCLog.png\" width=\"200\" align=\"center\">\n</a>",
"_____no_output_____"
],
[
"<h1>Sets in Python</h1>",
"_____no_output_____"
],
[
"<p><strong>Welcome!</strong> This notebook will teach you about the sets in the Python Programming Language. By the end of this lab, you'll know the basics set operations in Python, including what it is, operations and logic operations.</p> ",
"_____no_output_____"
],
[
"<h2>Table of Contents</h2>\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n <ul>\n <li>\n <a href=\"#set\">Sets</a>\n <ul>\n <li><a href=\"content\">Set Content</a></li>\n <li><a href=\"op\">Set Operations</a></li>\n <li><a href=\"logic\">Sets Logic Operations</a></li>\n </ul>\n </li>\n <li>\n <a href=\"#quiz\">Quiz on Sets</a>\n </li>\n </ul>\n <p>\n Estimated time needed: <strong>20 min</strong>\n </p>\n</div>\n\n<hr>",
"_____no_output_____"
],
[
"<h2 id=\"set\">Sets</h2>",
"_____no_output_____"
],
[
"<h3 id=\"content\">Set Content</h3>",
"_____no_output_____"
],
[
"A set is a unique collection of objects in Python. You can denote a set with a curly bracket <b>{}</b>. Python will automatically remove duplicate items:",
"_____no_output_____"
]
],
[
[
"# Create a set\n\nset1 = {\"pop\", \"rock\", \"soul\", \"hard rock\", \"rock\", \"R&B\", \"rock\", \"disco\"}\nset1",
"_____no_output_____"
]
],
[
[
"The process of mapping is illustrated in the figure:",
"_____no_output_____"
],
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsUnique.png\" width=\"1100\" />",
"_____no_output_____"
],
[
" You can also create a set from a list as follows:",
"_____no_output_____"
]
],
[
[
"# Convert list to set\n\nalbum_list = [ \"Michael Jackson\", \"Thriller\", 1982, \"00:42:19\", \\\n \"Pop, Rock, R&B\", 46.0, 65, \"30-Nov-82\", None, 10.0]\nalbum_set = set(album_list) \nalbum_set",
"_____no_output_____"
]
],
[
[
"Now let us create a set of genres:",
"_____no_output_____"
]
],
[
[
"# Convert list to set\n\nmusic_genres = set([\"pop\", \"pop\", \"rock\", \"folk rock\", \"hard rock\", \"soul\", \\\n \"progressive rock\", \"soft rock\", \"R&B\", \"disco\"])\nmusic_genres",
"_____no_output_____"
]
],
[
[
"<h3 id=\"op\">Set Operations</h3> ",
"_____no_output_____"
],
[
"Let us go over set operations, as these can be used to change the set. Consider the set <b>A</b>:",
"_____no_output_____"
]
],
[
[
"# Sample set\n\nA = set([\"Thriller\", \"Back in Black\", \"AC/DC\"])\nA",
"_____no_output_____"
]
],
[
[
" We can add an element to a set using the <code>add()</code> method: ",
"_____no_output_____"
]
],
[
[
"# Add element to set\n\nA.add(\"NSYNC\")\nA",
"_____no_output_____"
]
],
[
[
" If we add the same element twice, nothing will happen as there can be no duplicates in a set:\n",
"_____no_output_____"
]
],
[
[
"# Try to add duplicate element to the set\n\nA.add(\"NSYNC\")\nA",
"_____no_output_____"
]
],
[
[
" We can remove an item from a set using the <code>remove</code> method:",
"_____no_output_____"
]
],
[
[
"# Remove the element from set\n\nA.remove(\"NSYNC\")\nA",
"_____no_output_____"
]
],
[
[
" We can verify if an element is in the set using the <code>in</code> command:",
"_____no_output_____"
]
],
[
[
"# Verify if the element is in the set\n\n\"AC/DC\" in A",
"_____no_output_____"
]
],
[
[
"<h3 id=\"logic\">Sets Logic Operations</h3>",
"_____no_output_____"
],
[
"Remember that with sets you can check the difference between sets, as well as the symmetric difference, intersection, and union:",
"_____no_output_____"
],
[
" Consider the following two sets:",
"_____no_output_____"
]
],
[
[
"# Sample Sets\n\nalbum_set1 = set([\"Thriller\", 'AC/DC', 'Back in Black'])\nalbum_set2 = set([ \"AC/DC\", \"Back in Black\", \"The Dark Side of the Moon\"])",
"_____no_output_____"
]
],
[
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsSamples.png\" width=\"650\" />",
"_____no_output_____"
]
],
[
[
"# Print two sets\n\nalbum_set1, album_set2",
"_____no_output_____"
]
],
[
[
"As both sets contain <b>AC/DC</b> and <b>Back in Black</b> we represent these common elements with the intersection of two circles.",
"_____no_output_____"
],
[
"<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsLogic.png\" width = \"650\" />",
"_____no_output_____"
],
[
"You can find the intersect of two sets as follow using <code>&</code>:",
"_____no_output_____"
]
],
[
[
"# Find the intersections\n\nintersection = album_set1 & album_set2\nintersection",
"_____no_output_____"
]
],
[
[
"You can find all the elements that are only contained in <code>album_set1</code> using the <code>difference</code> method:",
"_____no_output_____"
]
],
[
[
"# Find the difference in set1 but not set2\n\nalbum_set1.difference(album_set2) ",
"_____no_output_____"
]
],
[
[
"You only need to consider elements in <code>album_set1</code>; all the elements in <code>album_set2</code>, including the intersection, are not included.",
"_____no_output_____"
],
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsLeft.png\" width=\"650\" />",
"_____no_output_____"
],
[
"The elements in <code>album_set2</code> but not in <code>album_set1</code> is given by:",
"_____no_output_____"
]
],
[
[
"album_set2.difference(album_set1) ",
"_____no_output_____"
]
],
[
[
"<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsRight.png\" width=\"650\" />",
"_____no_output_____"
],
[
"You can also find the intersection of <code>album_list1</code> and <code>album_list2</code>, using the <code>intersection</code> method:",
"_____no_output_____"
]
],
[
[
"# Use intersection method to find the intersection of album_list1 and album_list2\n\nalbum_set1.intersection(album_set2) ",
"_____no_output_____"
]
],
[
[
" This corresponds to the intersection of the two circles:",
"_____no_output_____"
],
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsIntersect.png\" width=\"650\" />",
"_____no_output_____"
],
[
"The union corresponds to all the elements in both sets, which is represented by coloring both circles:",
"_____no_output_____"
],
[
"<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%202/Images/SetsUnion.png\" width=\"650\" />",
"_____no_output_____"
],
[
" The union is given by:",
"_____no_output_____"
]
],
[
[
"# Find the union of two sets\n\nalbum_set1.union(album_set2)",
"_____no_output_____"
]
],
[
[
"And you can check if a set is a superset or subset of another set, respectively, like this:",
"_____no_output_____"
]
],
[
[
"# Check if superset\n\nset(album_set1).issuperset(album_set2) ",
"_____no_output_____"
],
[
"# Check if subset\n\nset(album_set2).issubset(album_set1) ",
"_____no_output_____"
]
],
[
[
"Here is an example where <code>issubset()</code> and <code>issuperset()</code> return true:",
"_____no_output_____"
]
],
[
[
"# Check if subset\n\nset({\"Back in Black\", \"AC/DC\"}).issubset(album_set1) ",
"_____no_output_____"
],
[
"# Check if superset\n\nalbum_set1.issuperset({\"Back in Black\", \"AC/DC\"}) ",
"_____no_output_____"
]
],
[
[
"<hr>",
"_____no_output_____"
],
[
"<h2 id=\"quiz\">Quiz on Sets</h2>",
"_____no_output_____"
],
[
"Convert the list <code>['rap','house','electronic music', 'rap']</code> to a set:",
"_____no_output_____"
]
],
[
[
"# Write your code below and press Shift+Enter to execute\nset(['rap','house','electronic music','rap'])",
"_____no_output_____"
]
],
[
[
"Double-click __here__ for the solution.\n<!-- Your answer is below:\nset(['rap','house','electronic music','rap'])\n-->",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"Consider the list <code>A = [1, 2, 2, 1]</code> and set <code>B = set([1, 2, 2, 1])</code>, does <code>sum(A) = sum(B)</code> ",
"_____no_output_____"
]
],
[
[
"# Write your code below and press Shift+Enter to execute\nA=[1,2,2,1]\nB=set([1,2,2,1])\nprint(\"the sum of A is:\",sum(A))\nprint(\"the sum of B is:\",sum(B))\nsum(A)==sum(B)",
"the sum of A is: 6\nthe sum of B is: 3\n"
]
],
[
[
"Double-click __here__ for the solution.\n\n<!-- Your answer is below:\nA = [1, 2, 2, 1] \nB = set([1, 2, 2, 1])\nprint(\"the sum of A is:\", sum(A))\nprint(\"the sum of B is:\", sum(B))\n-->",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"Create a new set <code>album_set3</code> that is the union of <code>album_set1</code> and <code>album_set2</code>:",
"_____no_output_____"
]
],
[
[
"# Write your code below and press Shift+Enter to execute\n\nalbum_set1 = set([\"Thriller\", 'AC/DC', 'Back in Black'])\nalbum_set2 = set([ \"AC/DC\", \"Back in Black\", \"The Dark Side of the Moon\"])\nalbum_set3 = album_set1.union(album_set2)\nalbum_set3",
"_____no_output_____"
]
],
[
[
"Double-click __here__ for the solution.\n\n<!-- Your answer is below:\nalbum_set3 = album_set1.union(album_set2)\nalbum_set3\n-->",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"Find out if <code>album_set1</code> is a subset of <code>album_set3</code>:",
"_____no_output_____"
]
],
[
[
"# Write your code below and press Shift+Enter to execute\nalbum_set1.issubset(album_set3)",
"_____no_output_____"
]
],
[
[
"Double-click __here__ for the solution.\n\n<!-- Your answer is below:\nalbum_set1.issubset(album_set3)\n-->",
"_____no_output_____"
],
[
"<hr>\n<h2>The last exercise!</h2>\n<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n<hr>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n<h2>Get IBM Watson Studio free of charge!</h2>\n <p><a href=\"https://cocl.us/PY0101EN_edx_add_bbottom\"><img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/BottomAd.png\" width=\"750\" align=\"center\"></a></p>\n</div>",
"_____no_output_____"
],
[
"<h3>About the Authors:</h3> \n<p><a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a> is a Data Scientist at IBM, and holds a PhD in Electrical Engineering. His research focused on using Machine Learning, Signal Processing, and Computer Vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.</p>",
"_____no_output_____"
],
[
"Other contributors: <a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"<p>Copyright © 2018 IBM Developer Skills Network. This notebook and its source code are released under the terms of the <a href=\"https://cognitiveclass.ai/mit-license/\">MIT License</a>.</p>",
"_____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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb07e8f5d508b543b0243a735392220bd19f1965 | 1,654 | ipynb | Jupyter Notebook | docs/contents/tools/classes/openmm_Topology/to_string_pdb_text.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | docs/contents/tools/classes/openmm_Topology/to_string_pdb_text.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | docs/contents/tools/classes/openmm_Topology/to_string_pdb_text.ipynb | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | 20.170732 | 84 | 0.542322 | [
[
[
"# To string pdb_text",
"_____no_output_____"
]
],
[
[
"from molsysmt.tools import openmm_Topology",
"Warning: importing 'simtk.openmm' is deprecated. Import 'openmm' instead.\n"
],
[
"#openmm_Topology.to_string_pdb_text(item)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
cb07f313a1887cf4d9c9dd6a801d22623a76f768 | 52,023 | ipynb | Jupyter Notebook | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning | cd34194464d3b06cc23b4b91523684f0f01a92f0 | [
"MIT"
] | null | null | null | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning | cd34194464d3b06cc23b4b91523684f0f01a92f0 | [
"MIT"
] | null | null | null | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning | cd34194464d3b06cc23b4b91523684f0f01a92f0 | [
"MIT"
] | null | null | null | 35.462168 | 625 | 0.461411 | [
[
[
"# Exercise 4a\n## 2 Red Cards Study\n### 2.1 Loading and Cleaning the data",
"_____no_output_____"
]
],
[
[
"#Import libraries\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse.linalg import lsqr",
"_____no_output_____"
],
[
"#Load dataset\ndf = pd.read_csv(\"CrowdstormingDataJuly1st.csv\", sep=\",\", header=0)\nprint(df.columns)",
"Index(['playerShort', 'player', 'club', 'leagueCountry', 'birthday', 'height',\n 'weight', 'position', 'games', 'victories', 'ties', 'defeats', 'goals',\n 'yellowCards', 'yellowReds', 'redCards', 'photoID', 'rater1', 'rater2',\n 'refNum', 'refCountry', 'Alpha_3', 'meanIAT', 'nIAT', 'seIAT',\n 'meanExp', 'nExp', 'seExp'],\n dtype='object')\n"
]
],
[
[
"We sort out (irrelevant) features:\n- player (playerShort uniquely identifies the player, so player is not needed)\n- playerShort (the players' names are irrelevant for us, actually...)\n- photoID (is only needed if we want to classify the skin color by ourselves)\n- refCountry (we will assume that not the name of the referee country, but the values meanIAT and meanExp are the relevant features regarding the referee country)\n- nIAT, seIAT (we will just assume the IAT values are a good estimation of the actual value, so we are not interested in the sample size used to determine the IAT)\n- nExp, seExp (see above)\n- yellowCards (our examination is only about red cards, not about yellow cards)\n- club (this is a categorial feature with over 100 categories. The one-hot encoding would therefore create a large amount of new features which drastically increases the dimensionality of the problem. This extra effort is disproportionate to the importance of this feature for this question (maybe(!) some teams play more aggresive than others).)\n- birthday (We decided against this feature because the data set does not contain information about the date of every single game. This makes it impossible to find out if players get more red cards when they are at a certain age, because the data from this dataset refer to the complete career of the players.)\n- Alpha_3 (we neglect the nationality of the referee)\n- games (This is a redundant feature because the total number of games is given by the sum of victories, ties and defeats)",
"_____no_output_____"
]
],
[
[
"df = df.drop(labels=[\"player\", \"playerShort\", \"photoID\", \"refCountry\", \"nIAT\", \"seIAT\", \"nExp\", \"seExp\", \"yellowCards\", \"club\", \"birthday\", \"Alpha_3\", \"games\"], axis=1)\nprint(df.columns)",
"Index(['leagueCountry', 'height', 'weight', 'position', 'victories', 'ties',\n 'defeats', 'goals', 'yellowReds', 'redCards', 'rater1', 'rater2',\n 'refNum', 'meanIAT', 'meanExp'],\n dtype='object')\n"
]
],
[
[
"Next, we create new features out of existing ones or manipulate them:\n- rating (we take the mean of rater1 and rater2 as our own rating)\n- totalReds (we sum up the red and yellow-red cards to the total number of red cards and divide by the number of games, This is our response Y.)\n- leagueCountry (replace the name of the country by one-hot encoding)\n- refCount (counts the number of dyads for each referee. Relevant for later drops (see https://nbviewer.jupyter.org/github/mathewzilla/redcard/blob/master/Crowdstorming_visualisation.ipynb))\n- We summarize some categories in position (Goalkeeper, Back, Midfielder, Forward (don't know anything about football, hopefully this makes sense.))",
"_____no_output_____"
]
],
[
[
"#take mean of the two skin color ratings\ndf[\"rating\"] = (df[\"rater1\"] + df[\"rater2\"])/2\ndf = df.drop(labels=[\"rater1\", \"rater2\"], axis=1)\n\n#sum up red and yellow-red cards\ndf[\"percentageReds\"] = (df[\"redCards\"] + df[\"yellowReds\"])/(df[\"victories\"]+df[\"ties\"]+df[\"defeats\"])\ndf = df.drop(labels=[\"redCards\", \"yellowReds\"], axis=1)\n\n#onehot encoding for leagueCountry\nonehot = pd.get_dummies(df.leagueCountry, prefix=\"Country\")\ndf = df.drop(labels=[\"leagueCountry\"], axis=1)\ndf = pd.concat([df,onehot], axis=1, sort=False)\n\n#summarize positions and onehot encoding for positions\ndic = {\"Right Fullback\":\"Back\",\n \"Left Fullback\":\"Back\",\n \"Center Back\":\"Back\",\n \"Left Midfielder\":\"Midfielder\", \n \"Right Midfielder\":\"Midfielder\", \n \"Center Midfielder\":\"Midfielder\", \n \"Defensive Midfielder\":\"Midfielder\",\n \"Attacking Midfielder\":\"Midfielder\",\n \"Left Winger\":\"Forward\",\n \"Right Winger\":\"Forward\",\n \"Center Forward\":\"Forward\"}\ndf = df.replace({\"position\":dic})\nonehot = pd.get_dummies(df.position, prefix=\"Position\")\ndf = df.drop(labels=[\"position\"], axis=1)\ndf = pd.concat([df,onehot], axis=1, sort=False)\n\n\n#add a column which tracks how many games each ref is involved in\n#taken from https://nbviewer.jupyter.org/github/mathewzilla/redcard/blob/master/Crowdstorming_visualisation.ipynb\ndf['refCount']=0\nrefs=pd.unique(df['refNum'].values.ravel()) #list all unique ref IDs\n#for each ref, count their dyads\nfor r in refs:\n df.loc[df['refNum']==r,\"refCount\"]=len(df[df['refNum']==r]) ",
"_____no_output_____"
]
],
[
[
"Now we go on with preparing the data set:\n- remove rows that contain a NaN-value\n- remove rows where refCount<22 (for explanation see https://nbviewer.jupyter.org/github/mathewzilla/redcard/blob/master/Crowdstorming_visualisation.ipynb. After this we can remove the features \"refNum\" and \"refCount\" because these were only kept for this step.)\n- normalize the features ties, victories and defeats",
"_____no_output_____"
]
],
[
[
"#remove rows with NaN in \"rating\" \ndf = df.dropna(axis=0)\n\n#remove rows where the \"refCount\"<22\ndf = df.loc[df[\"refCount\"]>21].reset_index()\ndf = df.drop([\"refNum\", \"refCount\", \"index\"], axis=1)\n\n#normalize ties, victories and defeats\ndefeats = df[\"defeats\"]/(df[\"defeats\"]+df[\"ties\"]+df[\"victories\"])\nties = df[\"ties\"]/(df[\"defeats\"]+df[\"ties\"]+df[\"victories\"])\nvictories = df[\"victories\"]/(df[\"defeats\"]+df[\"ties\"]+df[\"victories\"])\ndf[\"defeats\"] = defeats\ndf[\"ties\"] = ties\ndf[\"victories\"] = victories\n",
"_____no_output_____"
]
],
[
[
"In the following tasks we want to apply the LSQR-algorithm. In the lecture we always assumed centralized features and responses. So our last step is to centralize our data. The responses are given by the values in the column \"totalReds\"",
"_____no_output_____"
]
],
[
[
"df_mean = df.apply(np.mean, axis=0)\ndf = df - df_mean",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
],
[
[
"### 2.2 Model Creation",
"_____no_output_____"
]
],
[
[
"#solve the problem using the lsqr algorithm (linear regression)\n#extract features and responses from the DataFrame\nY = df[\"percentageReds\"].to_numpy()\nX = df.drop(labels=[\"percentageReds\"], axis=1).to_numpy()\n\nclass LinearRegression():\n \n def __init__(self):\n self.beta = None\n\n #use lsqr algorithm\n def train(self, features, labels):\n self.beta = lsqr(features,labels)[0]\n\n def predict(self, x):\n x_mean = df_mean.drop(labels=[\"percentageReds\"])\n y_mean = df_mean[\"percentageReds\"]\n return y_mean + np.sum(self.beta*(x-x_mean)) \n\n#Test basic functionality\nregression = LinearRegression()\nregression.train(X,Y)\nregression.predict([180, 77, 1.4, 0.8, 1, 0.4, 0.35, 0.5, 1, 0.3, 0.15, 0.3, 0.25, 0.3, 0.21, 0.1, 0.35])",
"_____no_output_____"
],
[
"#solve the problem using regression forestsclass DecisionTree(Tree):\n# base classes\nclass Node:\n pass\n\nclass Tree:\n def __init__(self):\n self.root = Node()\n \n def find_leaf(self, x):\n node = self.root\n while hasattr(node, \"feature\"):\n j = node.feature\n if x[j] <= node.threshold:\n node = node.left\n else:\n node = node.right\n return node\n \nclass RegressionTree(Tree):\n def __init__(self):\n super(RegressionTree, self).__init__()\n \n def train(self, data, labels, n_min=500):\n '''\n data: the feature matrix for all digits\n labels: the corresponding ground-truth responses\n n_min: termination criterion (don't split if a node contains fewer instances)\n '''\n N, D = data.shape\n D_try = np.max([int(np.sqrt(D))-2, 0]) # how many features to consider for each split decision\n\n # initialize the root node\n self.root.data = data\n self.root.labels = labels\n \n stack = [self.root]\n while len(stack):\n node = stack.pop()\n n = node.data.shape[0] # number of instances in present node\n if (n >= n_min):\n #randomly choose D_try-2 features\n feature_indices = np.random.choice(D, D_try, replace=False)\n feature_indices = np.append(feature_indices, [0,1,8])\n #split the node into two\n left, right = make_regression_split_node(node, feature_indices)\n #put the two nodes on the stack\n stack.append(left)\n stack.append(right)\n else:\n make_regression_leaf_node(node)\n \n def predict(self, x):\n leaf = self.find_leaf(x)\n return leaf.response",
"_____no_output_____"
],
[
"def make_regression_split_node(node, feature_indices):\n '''\n node: the node to be split\n feature_indices: a numpy array of length 'D_try', containing the feature \n indices to be considered in the present split\n '''\n n, D = node.data.shape\n\n # find best feature j (among 'feature_indices') and best threshold t for the split\n #(mainly copied from \"density tree\")\n e_min = float(\"inf\")\n j_min, t_min = None, None\n\n for j in feature_indices:\n data_unique = np.sort(np.unique(node.data[:, j]))\n tj = (data_unique[1:] + data_unique[:-1])/2.0\n \n for t in tj:\n data_left = node.data[:, j].copy()\n labels_left = node.labels[data_left<=t].copy()\n data_left = data_left[data_left<=t]\n \n data_right = node.data[:, j].copy()\n labels_right = node.labels[data_right>t].copy()\n data_right = data_right[data_right>t]\n \n #compute mean label value on the left and right\n mean_left = np.mean(labels_left)\n mean_right = np.mean(labels_right)\n \n #compute sum of squared deviation from mean label\n measure_left = np.sum((labels_left - mean_left)**2)\n measure_right = np.sum((labels_right - mean_right)**2) \n \n #Compute decision rule\n measure = measure_left + measure_right\n \n # choose the best threshold that minimizes gini\n if measure < e_min:\n e_min = measure\n j_min = j\n t_min = t\n \n # create children\n left = Node()\n right = Node()\n \n \n X = node.data[:, j_min]\n \n # initialize 'left' and 'right' with the data subsets and labels\n # according to the optimal split found above\n left.data = node.data[X<=t_min]# data in left node\n left.labels = node.labels[X<=t_min] # corresponding labels\n right.data = node.data[X>t_min]\n right.labels = node.labels[X>t_min]\n\n # turn the current 'node' into a split node\n # (store children and split condition)\n node.left = left\n node.right = right\n node.feature = j_min\n node.threshold = t_min\n\n # return the children (to be placed on the stack)\n return left, right ",
"_____no_output_____"
],
[
"def make_regression_leaf_node(node):\n '''\n node: the node to become a leaf\n '''\n # compute and store leaf response\n node.response = np.mean(node.labels) + df_mean[\"percentageReds\"]",
"_____no_output_____"
],
[
"class RegressionForest():\n def __init__(self, n_trees):\n # create ensemble\n self.trees = [RegressionTree() for i in range(n_trees)]\n \n def train(self, data, labels, n_min=1000):\n for tree in self.trees:\n # train each tree, using a bootstrap sample of the data\n bootstrap_indices = np.random.choice(len(labels), len(labels))\n bootstrap_data = np.array([data[i] for i in bootstrap_indices])\n bootstrap_labels = np.array([labels[i] for i in bootstrap_indices])\n tree.train(bootstrap_data, bootstrap_labels, n_min=n_min)\n\n def predict(self, x):\n predictions = np.array([])\n for tree in self.trees:\n predictions = np.append(predictions, tree.predict(x))\n return np.mean(predictions)\n \n def merge(self, forest):\n self.trees = self.trees + forest.trees",
"_____no_output_____"
],
[
"#test of basic functionality\nY = df[\"percentageReds\"].to_numpy()\nX = df.drop(labels=[\"percentageReds\"], axis=1).to_numpy()\n\nforest = RegressionForest(n_trees=5)\nforest.train(X, Y, n_min=500)",
"_____no_output_____"
],
[
"#determine the error via cross validation\n\n#define function that determines the sum squared error\ndef compute_error(model, test_features, test_labels):\n mean_squared_error = 0\n n = len(test_features)\n \n for i in range(n):\n mean_squared_error = mean_squared_error + (test_labels[i] - model.predict(test_features[i]))**2\n \n return mean_squared_error/n\n\nY = df[\"percentageReds\"].to_numpy()\nX = df.drop(labels=[\"percentageReds\"], axis=1).to_numpy()\n\n#number of folds\nL = 10\n\n#create L folds\nN = len(X)\nindices = np.random.choice(N, N, replace=False)\nX_folds = np.array(np.array_split(X[indices], L), dtype=object) \nY_folds = np.array(np.array_split(Y[indices], L), dtype=object)\n\n#1. Linear Regression\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n regression = LinearRegression()\n regression.train(X_train,Y_train)\n error.append(compute_error(regression, X_test, Y_test))\nerror = np.mean(error)\n\n#print error\nprint(\"\\nerror rate, linear regression:\")\nprint(error)",
"0.0 %\n10.0 %\n20.0 %\n30.0 %\n40.0 %\n50.0 %\n60.0 %\n70.0 %\n80.0 %\n90.0 %\n\nerror rate, linear regression:\n0.005192709509021647\n"
],
[
"#2. Regression Forest\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n forest = RegressionForest(n_trees=5)\n forest.train(X_train,Y_train, n_min=500)\n error.append(compute_error(forest, X_test, Y_test))\nerror = np.mean(error)\n\n#print error\nprint(\"\\nerror rate, regression forest:\")\nprint(error)",
"0.0 %\n10.0 %\n20.0 %\n30.0 %\n40.0 %\n50.0 %\n60.0 %\n70.0 %\n80.0 %\n90.0 %\n\nerror rate, regression forest:\n0.005265575175396048\n"
]
],
[
[
"### 2.3 Answering the Research Question",
"_____no_output_____"
]
],
[
[
"#define function that shuffles the data in one column\ndef shuffle_data(features, feature_index):\n '''\n Shuffles the data in the column denoted by feature_index. All other data remain unchanged \n\n features: 2D array, each row stands for one instance, each column for one feature\n feature_index: the entries in the feature_index-th column will be shuffled randomly\n '''\n\n features = features.transpose()\n shuffled_feature = np.random.permutation(features[feature_index])\n features[feature_index] = shuffled_feature\n\n return features.transpose()",
"_____no_output_____"
],
[
"color_rating_index = 8 #index of the color rating in df\nL = 10 #number of folds\n\n#load csv-file where we save the mean squared errors\nerr_data = pd.read_csv(\"errors.txt\", sep=\",\", index_col=False) \n\n# load original data set\nY = df[\"percentageReds\"].to_numpy()\nX = df.drop(labels=[\"percentageReds\"], axis=1).to_numpy()\n\n#1. Linear Regression\n#shuffle data\nY_shuffled = Y\nX_shuffled = shuffle_data(X, 8)\n\n#create L folds\nN = len(X_shuffled)\nindices = np.random.choice(N, N, replace=False)\nX_folds = np.array(np.array_split(X_shuffled[indices], L), dtype=object) \nY_folds = np.array(np.array_split(Y_shuffled[indices], L), dtype=object)\n\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n regression = LinearRegression()\n regression.train(X_train,Y_train)\n error.append(compute_error(regression, X_test, Y_test))\nerror_lr = np.mean(error)\n\n#print error and save the value\nprint(\"\\nerror rate, linear regression:\")\nprint(error_lr)\n\n#2. Regression Tree\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n forest = RegressionForest(n_trees=5)\n forest.train(X_train,Y_train, n_min=500)\n error.append(compute_error(forest, X_test, Y_test))\nerror = np.mean(error)\n\n#print error and save the value\nprint(\"\\nerror rate, regression tree:\")\nprint(error)\nerr_data.loc[len(err_data)] = [error_lr, error]\n\nerr_data.to_csv(\"errors.txt\", sep=\",\", index=False)",
"0.0 %\n10.0 %\n20.0 %\n30.0 %\n40.0 %\n50.0 %\n60.0 %\n70.0 %\n80.0 %\n90.0 %\n\nerror rate, linear regression:\n0.005183430036888673\n0.0 %\n10.0 %\n20.0 %\n30.0 %\n40.0 %\n50.0 %\n60.0 %\n70.0 %\n80.0 %\n90.0 %\n\nerror rate, regression tree:\n0.005268014302182951\n"
]
],
[
[
"To obtain the following results we run the code from above several times. The first row stands for the results from the unshuffled dataset, the other rows from the shuffled datasets. One can see that the error of some of the rows corresponding to a dataset with shuffled color rating are lower than the error from the original dataset. So we can't find a skin color bias in red card decisions with a p-value of p=0.05. However, we have doubts if our code is completely correct: surprisingly the error for linear regression is always even lower, when you shuffle the color rating. We do not have an explanation for this.",
"_____no_output_____"
]
],
[
[
"err_data = pd.read_csv(\"errors.txt\", sep=\",\", index_col=False) \nerr_data",
"_____no_output_____"
]
],
[
[
"### 2.4 How to Lie With Statistics",
"_____no_output_____"
],
[
"We already found a choice of features that does not reveal a skin color bias. So we try to find a choice of features that shows such a bias. We choose the \"rating\" column as the only feature. We only apply the Linear Regression model to the data, because our task is to find one example of a choice of features that shows a skin color bias in one of the used models. ",
"_____no_output_____"
]
],
[
[
"Y = df[\"percentageReds\"].to_numpy()\nX = df[[\"rating\"]].to_numpy()\ndf_mean = df_mean[[\"rating\", \"percentageReds\"]]\n\n#number of folds\nL = 20\n\n#create L folds\nN = len(X)\nindices = np.random.choice(N, N, replace=False)\nX_folds = np.array(np.array_split(X[indices], L), dtype=object) \nY_folds = np.array(np.array_split(Y[indices], L), dtype=object)\n\n#1. Linear Regression\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n regression = LinearRegression()\n regression.train(X_train,Y_train)\n error.append(compute_error(regression, X_test, Y_test))\nerror = np.mean(error)\n\n#print error\nprint(\"\\nerror rate, linear regression:\")\nprint(error)\n",
"0.0 %\n5.0 %\n10.0 %\n15.0 %\n20.0 %\n25.0 %\n30.0 %\n35.0 %\n40.0 %\n45.0 %\n50.0 %\n55.00000000000001 %\n60.0 %\n65.0 %\n70.0 %\n75.0 %\n80.0 %\n85.0 %\n90.0 %\n95.0 %\n\nerror rate, linear regression:\n0.0052392309104625995\n"
],
[
"color_rating_index = 0 #index of the color rating in df\nL = 20 #number of folds\n\n#load csv-file where we save the mean squared errors\nerr_data = pd.read_csv(\"errorsLie.txt\", sep=\",\", index_col=False) \n\n# load original data set\nY = df[\"percentageReds\"].to_numpy()\nX = df[[\"rating\"]].to_numpy()\n\n#1. Linear Regression\n#shuffle data\nY_shuffled = Y\nX_shuffled = shuffle_data(X, color_rating_index)\n\n#create L folds\nN = len(X_shuffled)\nindices = np.random.choice(N, N, replace=False)\nX_folds = np.array(np.array_split(X_shuffled[indices], L), dtype=object) \nY_folds = np.array(np.array_split(Y_shuffled[indices], L), dtype=object)\n\nerror = []\nfor i in range(L):\n print(i/L*100, \"%\")\n #create training and test data\n X_train = np.concatenate(X_folds[np.arange(L)!=i], axis=0)\n Y_train = np.concatenate(Y_folds[np.arange(L)!=i], axis=0)\n X_test = X_folds[i]\n Y_test = Y_folds[i]\n \n #compute error\n regression = LinearRegression()\n regression.train(X_train,Y_train)\n error.append(compute_error(regression, X_test, Y_test))\nerror = np.mean(error)\n\n#print error and save the value\nprint(\"\\nerror rate, linear regression:\")\nprint(error)\n\nerr_data.loc[len(err_data)] = [error]\n\nerr_data.to_csv(\"errorsLie.txt\", sep=\",\", index=False)",
"0.0 %\n5.0 %\n10.0 %\n15.0 %\n20.0 %\n25.0 %\n30.0 %\n35.0 %\n40.0 %\n45.0 %\n50.0 %\n55.00000000000001 %\n60.0 %\n65.0 %\n70.0 %\n75.0 %\n80.0 %\n85.0 %\n90.0 %\n95.0 %\n\nerror rate, linear regression:\n0.005248877638861473\n"
]
],
[
[
"After running the code above 20 times we can find a skin color bias this time: The mean squared error for the shuffled data is always higher than the error for the original dataset.",
"_____no_output_____"
],
[
"### 2.5 Alternative Hypotheses",
"_____no_output_____"
],
[
"This exercise assumes that a correlation between the skin color and the probability to get a red card exists. We did not find such a correlation with our first choice of features. So we assume that the choice of features we used in 2.4 was \"better\". Two causal hypotheses for red cards would then be:\n1. Heavier players cause more fouls (because the opponent is more likely to fall). This leads to more red cards for players with more weight.\n2. Players in the position \"Back\" often have to stop an opponent player in the last moment (\"no matter what it costs\"). This leads to more red cards for players in the position \"Back\".\nIf one of these hypotheses is true, we should find a positive correlation between the position \"Back\"/weight and the color rating. \nThen we would typically expect a positive covariance for these quantities. Additionally, we would expect a positive covarance of the weight/\"Back\" and the probability for a red card",
"_____no_output_____"
]
],
[
[
"#compute covariance matrices\nY = df[\"percentageReds\"].to_numpy()\nX = df[\"weight\"].to_numpy()\nprint(np.cov(X,Y))\nY = df[\"rating\"].to_numpy()\nprint(np.cov(X,Y), \"\\n\")\n\nY = df[\"percentageReds\"].to_numpy()\nX = df[\"Position_Back\"].to_numpy()\nprint(np.cov(X,Y))\nY = df[\"rating\"].to_numpy()\nprint(np.cov(X,Y))",
"[[5.12806150e+01 3.60300072e-03]\n [3.60300072e-03 5.17986190e-03]]\n[[ 5.12806150e+01 -4.98876945e-02]\n [-4.98876945e-02 8.25710800e-02]] \n\n[[0.21255133 0.00071554]\n [0.00071554 0.00517986]]\n[[ 0.21255133 -0.00133118]\n [-0.00133118 0.08257108]]\n"
]
],
[
[
"In both cases one of our expectations is not met, which means that our hypotheses are rather not true.",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb0805cffa7eb4997d05ce305669131a372cfbc4 | 189,794 | ipynb | Jupyter Notebook | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed | db23e5d4f99c145ed889b7fc96f7c2239df78eef | [
"Apache-2.0"
] | 2 | 2021-07-28T15:26:40.000Z | 2021-07-29T04:14:35.000Z | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed | db23e5d4f99c145ed889b7fc96f7c2239df78eef | [
"Apache-2.0"
] | 1 | 2021-07-30T06:00:30.000Z | 2021-07-30T06:00:30.000Z | Classification/Random Forest/RandomForestClassifier.ipynb | PrajwalNimje1997/ds-seed | db23e5d4f99c145ed889b7fc96f7c2239df78eef | [
"Apache-2.0"
] | null | null | null | 277.071533 | 40,651 | 0.711197 | [
[
[
"# Random Forest Classification\n### Required Packages",
"_____no_output_____"
]
],
[
[
"import warnings\r\nimport numpy as np \r\nimport pandas as pd \r\nimport seaborn as se \r\nimport matplotlib.pyplot as plt \r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.ensemble import RandomForestClassifier \r\nfrom sklearn.metrics import classification_report,plot_confusion_matrix\r\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"### Initialization\n\nFilepath of CSV file",
"_____no_output_____"
]
],
[
[
"#filepath\r\nfile_path= \"\"",
"_____no_output_____"
]
],
[
[
"List of features which are required for model training .",
"_____no_output_____"
]
],
[
[
"#x_values\r\nfeatures=[]",
"_____no_output_____"
]
],
[
[
"Target feature for prediction.",
"_____no_output_____"
]
],
[
[
"#y_value\r\ntarget=''",
"_____no_output_____"
]
],
[
[
"### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(file_path)\r\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.",
"_____no_output_____"
]
],
[
[
"X = df[features]\r\nY = df[target]",
"_____no_output_____"
]
],
[
[
"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n",
"_____no_output_____"
]
],
[
[
"def NullClearner(df):\r\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\r\n df.fillna(df.mean(),inplace=True)\r\n return df\r\n elif(isinstance(df, pd.Series)):\r\n df.fillna(df.mode()[0],inplace=True)\r\n return df\r\n else:return df\r\ndef EncodeX(df):\r\n return pd.get_dummies(df)\r\ndef EncodeY(df):\r\n if len(df.unique())<=2:\r\n return df\r\n else:\r\n un_EncodedT=np.sort(pd.unique(df), axis=-1, kind='mergesort')\r\n df=LabelEncoder().fit_transform(df)\r\n EncodedT=[xi for xi in range(len(un_EncodedT))]\r\n print(\"Encoded Target: {} to {}\".format(un_EncodedT,EncodedT))\r\n return df",
"_____no_output_____"
],
[
"x=X.columns.to_list()\r\nfor i in x:\r\n X[i]=NullClearner(X[i])\r\nX=EncodeX(X)\r\nY=EncodeY(NullClearner(Y))\r\nX.head()",
"_____no_output_____"
]
],
[
[
"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.",
"_____no_output_____"
]
],
[
[
"f,ax = plt.subplots(figsize=(18, 18))\r\nmatrix = np.triu(X.corr())\r\nse.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)\r\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Distribution Of Target Variable",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10,6))\r\nse.countplot(Y)",
"_____no_output_____"
]
],
[
[
"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 123)#performing datasplitting",
"_____no_output_____"
]
],
[
[
"### Model\n\nA random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the <code>max_samples</code> parameter if <code>bootstrap=True</code> (default), otherwise the whole dataset is used to build each tree.\n\n#### Model Tuning Parameters\n\n 1. n_estimators : int, default=100\n> The number of trees in the forest.\n\n 2. criterion : {“gini”, “entropy”}, default=”gini”\n> The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain.\n\n 3. max_depth : int, default=None\n> The maximum depth of the tree.\n\n 4. max_features : {“auto”, “sqrt”, “log2”}, int or float, default=”auto”\n> The number of features to consider when looking for the best split:\n\n 5. bootstrap : bool, default=True\n> Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.\n\n 6. oob_score : bool, default=False\n> Whether to use out-of-bag samples to estimate the generalization accuracy.\n\n 7. n_jobs : int, default=None\n> The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. <code>None</code> means 1 unless in a joblib.parallel_backend context. <code>-1</code> means using all processors. See Glossary for more details.\n\n 8. random_state : int, RandomState instance or None, default=None\n> Controls both the randomness of the bootstrapping of the samples used when building trees (if <code>bootstrap=True</code>) and the sampling of the features to consider when looking for the best split at each node (if <code>max_features < n_features</code>).\n\n 9. verbose : int, default=0\n> Controls the verbosity when fitting and predicting.",
"_____no_output_____"
]
],
[
[
"# Build Model here\r\nmodel = RandomForestClassifier(n_jobs = -1,random_state = 123)\r\nmodel.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"#### Model Accuracy\n\nscore() method return the mean accuracy on the given test data and labels.\n\nIn multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.",
"_____no_output_____"
]
],
[
[
"print(\"Accuracy score {:.2f} %\\n\".format(model.score(X_test,y_test)*100))",
"Accuracy score 88.75 %\n\n"
]
],
[
[
"#### Confusion Matrix\n\nA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known.",
"_____no_output_____"
]
],
[
[
"plot_confusion_matrix(model,X_test,y_test,cmap=plt.cm.Blues)",
"_____no_output_____"
]
],
[
[
"#### Classification Report\nA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.\n\n* **where**:\n - Precision:- Accuracy of positive predictions.\n - Recall:- Fraction of positives that were correctly identified.\n - f1-score:- percent of positive predictions were correct\n - support:- Support is the number of actual occurrences of the class in the specified dataset.",
"_____no_output_____"
]
],
[
[
"print(classification_report(y_test,model.predict(X_test)))",
" precision recall f1-score support\n\n 0 0.94 0.88 0.91 50\n 1 0.82 0.90 0.86 30\n\n accuracy 0.89 80\n macro avg 0.88 0.89 0.88 80\nweighted avg 0.89 0.89 0.89 80\n\n"
]
],
[
[
"#### Feature Importances.\n\nThe Feature importance refers to techniques that assign a score to features based on how useful they are for making the prediction.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(8,6))\r\nn_features = len(X.columns)\r\nplt.barh(range(n_features), model.feature_importances_, align='center')\r\nplt.yticks(np.arange(n_features), X.columns)\r\nplt.xlabel(\"Feature importance\")\r\nplt.ylabel(\"Feature\")\r\nplt.ylim(-1, n_features)",
"_____no_output_____"
]
],
[
[
"#### Creator: Thilakraj Devadiga , Github: [Profile](https://github.com/Thilakraj1998)",
"_____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"
] | [
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb082adb61f82717f7a5d53404d282b70459bbeb | 453,969 | ipynb | Jupyter Notebook | predict/tf_sketchy.ipynb | judithfan/pix2svg | f026a330c5cfd6a2d27b4e244cfa3f3e57682c19 | [
"MIT"
] | 3 | 2019-03-22T02:07:29.000Z | 2021-07-19T19:30:19.000Z | predict/tf_sketchy.ipynb | judithfan/pix2svg | f026a330c5cfd6a2d27b4e244cfa3f3e57682c19 | [
"MIT"
] | null | null | null | predict/tf_sketchy.ipynb | judithfan/pix2svg | f026a330c5cfd6a2d27b4e244cfa3f3e57682c19 | [
"MIT"
] | 1 | 2021-07-19T19:30:20.000Z | 2021-07-19T19:30:20.000Z | 156.325413 | 105,952 | 0.868379 | [
[
[
"from __future__ import division\n\nimport numpy as np\nfrom numpy import *\n\nimport os\n\nimport tensorflow as tf\n\nimport PIL\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom skimage import data, io, filters\n\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\n\nimport pandas as pd",
"_____no_output_____"
],
[
"path_to_strokes = \"tiny/airplane.npy\"\nX = np.load(path_to_strokes)[()]",
"_____no_output_____"
],
[
"print('Example sketch has ', str(shape(X['airplane'][0][0])[0]), ' strokes')\nprint('Corresponds to photo: ', X['airplane'][1][0])\n\npath_to_source_photos = \"../tiny/photo/airplane/\"\nphoto = os.path.join(path_to_source_photos,'n02691156_10151.jpg')",
"('Example sketch has ', '169', ' strokes')\n('Corresponds to photo: ', 'n02691156_10151')\n"
],
[
"class TinyDataset():\n \"\"\"tiny airplane dataset of photos and sketches for pix2svg.\"\"\"\n\n def __init__(self, npy_file, root_dir, transform=None):\n \"\"\"\n Args:\n npy_file (string): Path to the numpy file with stroke-5 representation and corresponding photos.\n # to get stroke-5 representation of svg\n x['airplane'][0][5]\n # to get corresponding photos\n x['airplane'][1][5]\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.root_dir = root_dir\n self.stroke_dir = npy_file\n self.photo_dir = os.path.join(root_dir,'photo')\n self.strokes = np.load(npy_file)[()]\n self.transform = transform\n \n def __len__(self):\n return len(self.strokes['airplane'][0])\n\n def __getitem__(self, idx):\n img_name = os.path.join(self.photo_dir,'airplane',X['airplane'][1][idx]+ '.jpg')\n photo = io.imread(img_name)\n photo = photo.astype(float)\n strokes = self.strokes['airplane'][0][idx]\n sample = {'photo': photo, 'strokes': strokes,'name': X['airplane'][1][idx]+ '.jpg'}\n \n if self.transform:\n sample = self.transform(sample)\n\n return sample \n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, strokes, name = sample['photo'], sample['strokes'], sample['name']\n\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1)) \n return {'tensor': tf.divide(tf.stack(sample['photo']),255),\n 'strokes': strokes,\n 'name': name,\n 'photo': image} \n\ndef to_normal_strokes(big_stroke):\n \"\"\"Convert from stroke-5 format (from sketch-rnn paper) back to stroke-3.\"\"\"\n l = 0\n for i in range(len(big_stroke)):\n if big_stroke[i, 4] > 0:\n l = i\n break\n if l == 0:\n l = len(big_stroke)\n result = np.zeros((l, 3))\n result[:, 0:2] = big_stroke[0:l, 0:2]\n result[:, 2] = big_stroke[0:l, 3]\n return result \n \ndef strokes_to_lines(strokes):\n \"\"\"\n Convert stroke-3 format to polyline format.\n List contains sublist of continuous line segments (strokes). \n \"\"\"\n x = 0\n y = 0\n lines = []\n line = []\n for i in range(len(strokes)):\n if strokes[i, 2] == 1:\n x += float(strokes[i, 0])\n y += float(strokes[i, 1])\n line.append([x, y])\n lines.append(line)\n line = []\n else:\n x += float(strokes[i, 0])\n y += float(strokes[i, 1])\n line.append([x, y])\n return lines\n\ndef polyline_pathmaker(lines):\n x = []\n y = []\n\n codes = [Path.MOVETO] # start with moveto command always\n for i,l in enumerate(lines):\n for _i,_l in enumerate(l):\n x.append(_l[0])\n y.append(_l[1])\n if _i<len(l)-1:\n codes.append(Path.LINETO) # keep pen on page\n else:\n if i != len(lines)-1: # final vertex\n codes.append(Path.MOVETO)\n verts = zip(x,y) \n return verts, codes\n\ndef path_renderer(verts, codes):\n path = Path(verts, codes)\n patch = patches.PathPatch(path, facecolor='none', lw=2)\n ax.add_patch(patch)\n ax.set_xlim(0,max(max(verts)))\n ax.set_ylim(0,max(max(verts)))\n ax.axis('off')\n plt.gca().invert_yaxis() # y values increase as you go down in image\n plt.show()",
"_____no_output_____"
],
[
"%ls",
"batch_render_tiny_intermediates.ipynb \u001b[0m\u001b[01;34mMNIST_data\u001b[0m/\r\n\u001b[01;34mcheckpoints\u001b[0m/ \u001b[01;34mpix2svg\u001b[0m/\r\n\u001b[01;34mgenerative\u001b[0m/ README.md\r\nhelpers.py \u001b[01;34msketchy\u001b[0m/\r\nhelpers.pyc \u001b[01;35mtest.png\u001b[0m\r\n\u001b[01;34mipynb\u001b[0m/ tf_sketchy.ipynb\r\nLICENSE \u001b[01;34mtiny\u001b[0m/\r\nmdn.py \u001b[01;34m___tiny_intermediates\u001b[0m/\r\nmdn.pyc \u001b[01;34mtiny_intermediates\u001b[0m/\r\nmixture_density_network_tutorial.ipynb \u001b[01;34mtiny_intermediates_resized\u001b[0m/\r\n"
],
[
"## load in airplanes dataset\nairplanes = TinyDataset(npy_file='/home/jefan/ptsketchy/tiny/airplane.npy',root_dir='/home/jefan/ptsketchy/tiny',transform=None)",
"_____no_output_____"
],
[
"## display given photo and corresponding sketch from stroke-5 representation\ni = 100\nsample = airplanes[i]\nprint(i, sample['photo'].shape, sample['strokes'].shape)\n\nplt.figure()\nax = plt.subplot(121)\nax.set_title(sample['name'])\nax.axis('off')\nimg = np.reshape(sample['photo'],(256,256,3))\nplt.imshow(img,interpolation='nearest')\n\nax = plt.subplot(122)\nlines = strokes_to_lines(to_normal_strokes(sample['strokes']))\nverts,codes = polyline_pathmaker(lines)\npath_renderer(verts,codes)\n\nplt.show()",
"(100, (256, 256, 3), (99, 5))\n"
],
[
"# load in airplanes dataset\nairplanes = TinyDataset(npy_file='/home/jefan/ptsketchy/tiny/airplane.npy',\n root_dir='/home/jefan/ptsketchy/tiny',\n transform=ToTensor())",
"_____no_output_____"
],
[
"# load in features for photos\npath_to_features = 'sketchy/triplet_features'\nphoto_features = np.load(os.path.join(path_to_features,'photo_features.npy'))\nF = photo_features",
"_____no_output_____"
],
[
"# read in filenames and generate pandas dataframe with object labels\n_filenames = pd.read_csv(os.path.join(path_to_features,'photo_filenames.txt'),header=None,names=['filename'])\n\nfilenames = []\nfor i in range(len(_filenames)):\n filenames.append(_filenames[_filenames.index==i].values[0][0])\nfilenames = ['sketchy' + f[1:] for f in filenames]\npath = filenames\nobj = [f.split('/')[3] for f in filenames]\nimg = [f.split('/')[4] for f in filenames]\n\ndata = {'path': path,\n 'object': obj,\n 'filename': img}\nX = pd.DataFrame.from_dict(data)",
"_____no_output_____"
],
[
"# subset airplane features only\nmatches = X['object']=='airplane'\ninds = np.where(matches==True)\nX0 = X[matches]\nF0 = F[inds]",
"_____no_output_____"
],
[
"# construct (11094,1024) version of photo feature matrix, called PF, that matches indexing of the sketch feature matrix\nsketch_features = np.load('sketchy/airplane_features/airplane_sketch_features.npy')\n_sketch_filenames = pd.read_csv('sketchy/airplane_features/airplane_sketch_filenames.txt',header=None,names=['filename'])\nsketch_filenames = []\nfor i in range(len(_sketch_filenames)):\n sketch_filenames.append(_sketch_filenames[_sketch_filenames.index==i].values[0][0])\nPF = []\ninds = [] \nfor sf in sketch_filenames:\n q = sf.split('/')[2]+'.jpg'\n PF.append(F0[X0['filename']==q])\n inds.append(np.where(X0['filename']==q)[0][0])\nPF = np.squeeze(np.array(PF))\nSF = sketch_features\ninds = np.array(inds)\n\n## zip together/concatenate the photo and sketch features\n_F = np.hstack((PF,SF))",
"_____no_output_____"
],
[
"### now get a (11094,5) representation of the 'next stroke'\n### no wait, instead, just bump up the dimensionality of these feature matrices to fit that of \n### the (delta_x,delta_y) stroke representation\n### Strokes dataframe (\"S\") is of dimensionality (55855,5).\n### So, resize and re-index the feature matrix to match S. \n\nS = pd.read_csv('tiny/stroke_dataframe.csv')\nS1 = S\nphoto_dir = np.array([sf.split('/')[2] for sf in sketch_filenames]) # photo dir\nsketch_dir = np.array(map(int,[sf.split('/')[3] for sf in sketch_filenames])) # sketch dir\nstroke_png = np.array(map(int,[sf.split('/')[4].split('.')[0] for sf in sketch_filenames])) # stroke png\n\nF = []\nfor index, row in S.iterrows():\n # get ind of the original small (11094,5) matrix that corresponds to this row of S (55855,5)\n ind = np.intersect1d(np.intersect1d(np.where(photo_dir==row['photoID']),\n np.where(sketch_dir==row['sketchID'])),\n np.where(stroke_png==row['strokeID']))[0]\n F.append(_F[ind])\n \nF = np.array(F)\nF1 = F # protected F1 matrix",
"_____no_output_____"
]
],
[
[
"### convert strokes matrix from absolute to relative coordinates ",
"_____no_output_____"
]
],
[
[
"from copy import deepcopy\nunique_photos = np.unique(S1.photoID)\nr = pd.DataFrame(columns=list(S1.keys()))\n\nrun_this = False\nif run_this:\n for i, p in enumerate(unique_photos):\n print 'Processing ' + p + ': ' + str(i+1) + ' of ' + str(len(unique_photos)) + ' photos.'\n s1 = S1[S1.photoID==p]\n unique_sketches_of_photo = np.unique(s1.sketchID)\n for sketch in unique_sketches_of_photo:\n this_sketch = s1[s1.sketchID==sketch]\n for index, row in this_sketch.iterrows():\n _row = deepcopy(row)\n if index==min(this_sketch.index): # first stroke\n r = r.append(row)\n this_x = row.x\n this_y = row.y\n else:\n x_offset = _row.x-this_x\n y_offset = _row.y-this_y\n row.x = x_offset\n row.y = y_offset\n r = r.append(row)\n this_x = _row.x # hold onto current row so you can compute difference with next one\n this_y = _row.y\n # save out relative strokes matrix as S2\n S2 = r \n print 'Saving out stroke_dataframe_relative.csv'\n S2.to_csv('tiny/stroke_dataframe_relative.csv')",
"_____no_output_____"
],
[
"# check if S2 exists, if not, load it in\ntry:\n S2\nexcept:\n S2 = pd.read_csv('tiny/stroke_dataframe_relative.csv')\n \n# define S to either be ABSOLUTE strokes matrix (S1) or RELATIVE strokes matrix (S2)\nS = S2\n\n# generate 55855-long vector of photo indices\nprint 'generating list of photo indices based on X0'\ninds = [] \nfor index, row in S.iterrows():\n q = row['photoID']+'.jpg'\n inds.append(np.where(X0['filename']==q)[0][0])\ninds = np.array(inds)\n\n# generate random index to do train/val/test split\nprint 'generating random index to do train/val/test split'\n_idx = np.arange(len(X0))\nnp.random.seed(seed=0)\nnp.random.shuffle(_idx)\ntrain_len = int(len(_idx)*0.85)\nval_len = int(len(_idx)*0.05)\ntest_len = int(len(_idx*0.10))\n\n# indices of 100 photos that will go into train/val/test split\ntrain_inds = _idx[:train_len] \nval_inds = _idx[train_len:train_len+val_len]\ntest_inds = _idx[train_len+val_len:len(_idx)]\n\nprint 'constructing 55855 vectors that correspond to membership in train/val/test splits'\n# construct 55855 vectors that correspond to membership in train/val/test splits\ntrain_vec = np.zeros(len(F)).astype(bool)\nval_vec = np.zeros(len(F)).astype(bool)\ntest_vec = np.zeros(len(F)).astype(bool)\n\nfor i in train_inds:\n train_vec[inds==i] = True\nfor i in val_inds:\n val_vec[inds==i] = True \nfor i in test_inds:\n test_vec[inds==i] = True \n \nassert sum(train_vec)+ sum(val_vec) + sum(test_vec) == len(train_vec) \nprint ' '\nprint str(sum(train_vec)/len(train_vec) * len(F)) + ' sketch intermediates to train on.'\nprint str(sum(val_vec)/len(val_vec) * len(F)) + ' sketch intermediates to validate on.'\nprint str(sum(test_vec)/len(test_vec) * len(F)) + ' sketch intermediates to test on.' \nprint ' '\nprint 'Now actually splitting data.'\n# now actually split data\nF_train = F[train_vec]\nF_val = F[val_vec]\nF_test = F[test_vec]\n\nS_train = S[train_vec]\nS_val = S[val_vec]\nS_test = S[test_vec]\n\nS_train = S_train[['x', 'y', 'pen']].copy()\nS_val = S_val[['x', 'y', 'pen']].copy()\nS_test = S_test[['x', 'y', 'pen']].copy()",
"generating list of photo indices based on X0\ngenerating random index to do train/val/test split\nconstructing 55855 vectors that correspond to membership in train/val/test splits\n \n45041.0 sketch intermediates to train on.\n4185.0 sketch intermediates to validate on.\n6629.0 sketch intermediates to test on.\n \nNow actually splitting data.\n"
],
[
"## training helpers\ndef minibatch(data, minibatch_idx):\n return data[minibatch_idx] if type(data) is np.ndarray else [data[i] for i in minibatch_idx] \n\ndef minibatches(data, batch_size, shuffle=True):\n batches = [np.array(col) for col in zip(*data)]\n return get_minibatches(batches, batch_size, shuffle)\n\ndef get_minibatches(data, minibatch_size, shuffle=True):\n \"\"\"\n Iterates through the provided data one minibatch at at time. You can use this function to\n iterate through data in minibatches as follows:\n for inputs_minibatch in get_minibatches(inputs, minibatch_size):\n ...\n Or with multiple data sources:\n for inputs_minibatch, labels_minibatch in get_minibatches([inputs, labels], minibatch_size):\n ...\n Args:\n data: there are two possible values:\n - a list or numpy array\n - a list where each element is either a list or numpy array\n minibatch_size: the maximum number of items in a minibatch\n shuffle: whether to randomize the order of returned data\n Returns:\n minibatches: the return value depends on data:\n - If data is a list/array it yields the next minibatch of data.\n - If data a list of lists/arrays it returns the next minibatch of each element in the\n list. This can be used to iterate through multiple data sources\n (e.g., features and labels) at the same time.\n \"\"\"\n list_data = type(data) is list and (type(data[0]) is list or type(data[0]) is np.ndarray)\n data_size = len(data[0]) if list_data else len(data)\n indices = np.arange(data_size)\n if shuffle:\n np.random.shuffle(indices)\n for minibatch_start in np.arange(0, data_size, minibatch_size):\n minibatch_indices = indices[minibatch_start:minibatch_start + minibatch_size]\n yield [minibatch(d, minibatch_indices) for d in data] if list_data \\\n else minibatch(data, minibatch_indices), minibatch_indices\n\n# usage notes:\n# for m in get_minibatches([F_train,S_train.as_matrix()],batch_size,shuffle=True):\n# print len(m),m[0].shape,m[1].shape",
"_____no_output_____"
]
],
[
[
"### quality assurance make sure that image classification is working as advertised based on triplet features",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import svm\nfrom sklearn import linear_model\n\n# reminders:\n# S1 is stroke matrix\n# F1 is feature matrix\n# PF is photo-feature matrix\n# SF is sketch-feature matrix/\n\n\n# get np.array of source photo labels\nphotos = np.array([sf.split('/')[2] for sf in sketch_filenames])",
"_____no_output_____"
],
[
"\n## get image classification within airplane class\nrun_this = 1\nFEAT = SF_complete\nLABELS = photos_complete\nif run_this:\n # split sketch feature data for linear classification\n X_train, X_test, y_train, y_test = train_test_split(\n FEAT, LABELS, test_size=0.2, random_state=0)\n\n # check dimensionality of split data\n print 'dimensionality of train/test split'\n print X_train.shape, y_train.shape\n print X_test.shape, y_test.shape\n print ' '\n cval = True\n if cval==False:\n # compute linear classification accuracy (takes a minute or so to run)\n clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)\n clf.score(X_test, y_test) \n else:\n # compute linear classification accuracy (takes several minutes to run) \n# clf = svm.SVC(kernel='linear', C=1)\n clf = linear_model.LogisticRegression(penalty='l2')\n scores = cross_val_score(clf, FEAT, LABELS, cv=2)\n print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n ## SVM Accuracy: 0.41 (+/- 0.08) with cv=5 achieved on 6/26/17 on intermediate sketches\n ## softmax Accuracy: 0.43 (+/- 0.01) with cv=2 achieved on 9/11/17 ",
"dimensionality of train/test split\n(536, 1024) (536,)\n(135, 1024) (135,)\n \nAccuracy: 0.43 (+/- 0.01)\n"
]
],
[
[
"#### compute pairwise euclidean distances between sketches of same class vs. different class",
"_____no_output_____"
]
],
[
[
"### this was done on 9/11/17 in order to debug the vgg embedding",
"_____no_output_____"
],
[
"print 'Why are there fewer sketch intermediate files than total sketch files?'\nprint str(len(os.listdir('./tiny/sketch/airplane'))) + ' total sketch files.'\n\nall_sketches = os.listdir('./tiny/sketch/airplane')\nall_sketches_with_intermediates = [s.split('/')[-2]+'-'+s.split('/')[-1]+'.png' for s in sketch_folders]\nprint str(len(all_sketches_with_intermediates)) + ' sketch files after extracting intermediates.'\nmissing_ones = [i for i in all_sketches if i not in all_sketches_with_intermediates]",
"Why are there fewer sketch intermediate files than total sketch files?\n709 total sketch files.\n671 sketch files after extracting intermediates.\n"
],
[
"## get just complete sketches from each sketch folder\nsketch_folders = np.unique([os.path.dirname(s) for s in sketch_filenames])\ncomplete_paths = []\nSF_complete = []\nphotos_complete = []\nfor (j,s) in enumerate(sketch_folders):\n complete_sketch = str(max([int(i.split('.')[0]) for i \\\n in os.listdir(s)])) + '.png'\n complete_paths.append(os.path.join(os.path.dirname(s),complete_sketch))\n SF_complete.append(SF[j])\n photos_complete.append(os.path.dirname(s).split('/')[-1])\nSF_complete = np.array(SF_complete) \nphotos_complete = np.array(photos_complete)",
"_____no_output_____"
],
[
"from sklearn.metrics.pairwise import pairwise_distances\ndef rmse(x):\n return np.sqrt(np.sum(x**2))\n ",
"_____no_output_____"
],
[
"euc = pairwise_distances(SF_complete,metric='euclidean')\nprint euc.shape",
"(671, 671)\n"
],
[
"p_ind = 4\nfp = 20\nfig = plt.figure(figsize=(9,9))\nfor (_i,p_ind) in enumerate(np.arange(fp,fp+9)):\n unique_photos = np.unique(photos_complete)\n inds = np.where(photos_complete==unique_photos[p_ind])[0]\n start = inds[0]\n stop = inds[-1]\n\n # get within-photo sketch distances\n within_block = euc[start:stop+1,start:stop+1]\n assert len(within_block[np.triu_indices(len(within_block),k=1)])==(len(within_block)**2-len(within_block))/2\n within_distances = within_block[np.triu_indices(len(within_block),k=1)]\n\n # get between-photo sketch distances\n all_inds = np.arange(len(photos_complete))\n non_matches = [i for i in all_inds if i not in inds]\n _non_matches_shuff = np.random.RandomState(seed=0).permutation(non_matches)\n non_matches_shuff = _non_matches_shuff[:len(inds)]\n btw_distances = euc[start:stop+1,non_matches_shuff].flatten()\n\n # plot \n plt.subplot(3,3,_i+1)\n h = plt.hist(within_distances,bins=20,alpha=0.3)\n h = plt.hist(btw_distances,bins=20,alpha=0.3)\n plt.title(str(p_ind))\nplt.show()\n ",
"_____no_output_____"
],
[
"## get image classification within airplane class\nrun_this = 1\nFEAT = SF_complete\nLABELS = photos_complete\nif run_this:\n # split sketch feature data for linear classification\n X_train, X_test, y_train, y_test = train_test_split(\n FEAT, LABELS, test_size=0.2, random_state=0)\n\n # check dimensionality of split data\n print 'dimensionality of train/test split'\n print X_train.shape, y_train.shape\n print X_test.shape, y_test.shape\n print ' '\n cval = True\n if cval==False:\n # compute linear classification accuracy (takes a minute or so to run)\n clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)\n clf.score(X_test, y_test) \n else:\n # compute linear classification accuracy (takes several minutes to run) \n clf = svm.SVC(kernel='linear', C=1)\n scores = cross_val_score(clf, SF, photos, cv=5)\n print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n ## Accuracy: 0.41 (+/- 0.08) achieved on 6/26/17",
"_____no_output_____"
],
[
"from glob import glob\ndef list_files(path, ext='jpg'):\n result = [y for x in os.walk(path)\n for y in glob(os.path.join(x[0], '*.%s' % ext))]\n return result\n\n\nairplane_dir = '/home/jefan/full_sketchy_dataset/sketches/airplane'",
"_____no_output_____"
],
[
"airplane_paths = list_files(airplane_dir,ext='png')",
"_____no_output_____"
]
],
[
[
"### draft of model for single minibatch",
"_____no_output_____"
]
],
[
[
"RANDOM_SEED = 42\ntf.set_random_seed(RANDOM_SEED)\n\n# reset entire graph\ntf.reset_default_graph()\nsess = tf.InteractiveSession()\n\n# weight on offset loss\noffset_weight = 100.\n\n# learning rate\nlearning_rate = 0.01\n\n# get minibatch\nbatch_size = 10\nF_batch = F_train[:batch_size,:]\nS_batch = S_train.head(n=batch_size)\n\n# reserve numpy version \nF_batch_array = F_batch\nS_batch_array = S_batch.as_matrix().astype('float32')\n\n# convert to tensorflow tensor\nF_batch = tf.cast(tf.stack(F_batch,name='F_batch'),tf.float32)\nS_batch = tf.cast(tf.stack(S_batch.as_matrix().astype('float32'),name='S_batch'),tf.float32)\n\n# Layer's sizes\nx_size = F_batch.shape[1] # Number of input nodes: 2048 features and 1 bias\nh_size = 256 # Number of hidden nodes\ny_size = S_batch.shape[1] # Number of outcomes (x,y,pen)\n\n# Symbols\nX = tf.placeholder(\"float\", shape=[None, x_size])\ny = tf.placeholder(\"float\", shape=[None, y_size])\noutput = tf.placeholder(\"float\", shape=[None,y_size])\n\n# Weight initializations\nW1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW2 = tf.get_variable('W2', [h_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb2 = tf.get_variable('b2', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW3 = tf.get_variable('W3', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb3 = tf.get_variable('b3', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# forward propagation\nfc1 = tf.nn.relu(tf.nn.xw_plus_b(F_batch, W1, b1,name='fc1'))\nfc2 = tf.nn.relu(tf.nn.xw_plus_b(fc1, W2, b2,name='fc2'))\noutput = tf.nn.xw_plus_b(fc1, W3, b3,name='output')\n\nactual_offset = tf.slice(S_batch,[0,0],[batch_size,2])\nactual_pen = tf.slice(S_batch,[0,2],[batch_size,-1]) \npred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_weight)\npred_pen = tf.nn.softmax(tf.slice(output,[0,2],[batch_size,-1]))\n# currently doesn't properly handle the pen state loss\noffset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\npen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels = actual_pen,\n logits = pred_pen))\n\nloss = tf.add(offset_loss,pen_loss)\n\n# run backprop\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\n# # get predicted stroke vector\nstrokes = tf.concat([pred_offset, pred_pen],axis=1)\n\ntf.global_variables_initializer().run()\n\n\n# sess.close()",
"_____no_output_____"
],
[
"updates = sess.run([fc1,output,pred_offset,\n pred_pen,actual_offset, actual_pen,\n offset_loss,pen_loss,loss,\n train_op,strokes], feed_dict={X:F_batch_array,y:S_batch_array})",
"_____no_output_____"
],
[
"fc1 = updates[0]\noutput = updates[1]\npred_offset = updates[2]\npred_pen = updates[3]\nactual_offset = updates[4]\nactual_pen = updates[5]\noffset_loss = updates[6]\npen_loss = updates[7]\nloss = updates[8]\ntrain_op = updates[9]\nstrokes = updates[10]\n\n",
"_____no_output_____"
]
],
[
[
"### run multiple batches of MLP version",
"_____no_output_____"
]
],
[
[
"RANDOM_SEED = 42\ntf.set_random_seed(RANDOM_SEED)\n\n# reset entire graph\ntf.reset_default_graph()\n\n# weight on offset loss\noffset_weight = 0.1\n\n# amount to multiply predicted offset values by\noffset_multiplier = 100.\n\n# learning rate\nlearning_rate = 0.001\n\n# set batch size\nbatch_size = 10\n\n# epoch counter\nepoch_num = 0\n\n# feed in only current features, or also features on the next time step as well?\nnow_plus_next = True\n\n# initialize variables\nif now_plus_next:\n F = tf.placeholder(\"float\", shape=[None, 4096]) # features (input)\nelse:\n F = tf.placeholder(\"float\", shape=[None, 2048]) # features (input)\nS = tf.placeholder(\"float\", shape=[None, 3]) # strokes (output)\n\n# Layer's sizes\nx_size = F.shape[1] # Number of input nodes: 2048 features and 1 bias\nh_size = 256 # Number of hidden nodes\ny_size = S.shape[1] # Number of outcomes (x,y,pen)\n\noutput = tf.placeholder(\"float\", shape=[None,y_size])\n\n# convert to tensorflow tensor\nF = tf.cast(tf.stack(F,name='F'),tf.float32)\nS = tf.cast(tf.stack(S,name='S'),tf.float32)\n\n# Weight initializations\nW1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW2 = tf.get_variable('W2', [h_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb2 = tf.get_variable('b2', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW3 = tf.get_variable('W3', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb3 = tf.get_variable('b3', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# forward propagation\nfc1 = tf.nn.relu(tf.nn.xw_plus_b(F, W1, b1,name='fc1'))\nfc2 = tf.nn.relu(tf.nn.xw_plus_b(fc1, W2, b2,name='fc2'))\noutput = tf.nn.xw_plus_b(fc1, W3, b3,name='output')\n\nactual_offset = tf.slice(So,[0,0],[batch_size,2])\nactual_pen = tf.squeeze(tf.slice(So,[0,2],[batch_size,-1]))\npred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_multiplier)\npred_pen = tf.squeeze(tf.slice(output,[0,2],[batch_size,-1]))\n\noffset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\npen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels = actual_pen,\n logits = pred_pen))\n\nloss = tf.add(tf.multiply(offset_weight,offset_loss),pen_loss)\n\n# run backprop\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\n# saver\nsave = False\nsaver = tf.train.Saver()\n\n# get predicted stroke vector\nstrokes = tf.concat([pred_offset, tf.expand_dims(pred_pen,1)],axis=1)\n\n# run batches\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n for m,idx in get_minibatches([F_train,S_train.as_matrix().astype('float32')],batch_size,shuffle=True): \n \n if m[0].shape[0]==batch_size:\n F_batch = m[0]\n S_batch = m[1] \n \n # use idx to retrieve the features of the subsequent row in the feature matrix, so you\n # effectively feed in sketch_so_far and sketch_so_far_plus_next_xy, as well as pen (absolute?) location and state\n if (max(idx)<45040):\n F_batch_next = F_train[idx+1].shape \n F_now_plus_next = np.hstack((F_train[idx],F_train[idx+1]))\n \n if (now_plus_next) & (max(idx)<45040):\n updates = sess.run([offset_loss, pen_loss, loss, pred_offset], feed_dict={F:F_now_plus_next,S:S_batch})\n else:\n try:\n updates = sess.run([offset_loss, pen_loss, loss, pred_offset], feed_dict={F:F_batch,S:S_batch}) \n except:\n pass\n\n offset_loss_ = updates[0]\n pen_loss_ = updates[1]\n loss_ = updates[2]\n pred_offset_ = updates[3]\n\n if epoch_num%200==0:\n print \"Epoch: \" + str(epoch_num) + \" | Loss: \" + str(loss_) + \\\n \" | Offset loss: \" + str(offset_loss_) + \" | Pen loss: \" + str(pen_loss_)\n\n # save\n if save:\n saver.save(sess, 'checkpoints/pix2svg_train_0')\n \n # increment epoch number\n epoch_num += 1\n",
"_____no_output_____"
],
[
"## meeting notes\n# june 26: validate triplet network to make sure it does the task -- QA\n# does it take in pen location? put in pen location, pen state \n# put in sketch so far + (sketch so far +1)\n# delta x, delta y -- make sure the thing it spits out, after getting squashed by tanh, or whatever, is well centered\n",
"_____no_output_____"
]
],
[
[
"### simpler version that goes from last pen offset to next pen offset",
"_____no_output_____"
]
],
[
[
"## now try simpler version that just tries to predict the next offset based on previous offset \n\nRANDOM_SEED = 42\ntf.set_random_seed(RANDOM_SEED)\n\n# reset entire graph\ntf.reset_default_graph()\n\n# weight on offset loss\noffset_weight = 0.8\n\n# amount to multiply predicted offset values by\noffset_multiplier = 100.\n\n# learning rate\nlearning_rate = 0.001\n\n# set batch size\nbatch_size = 10\n\n# epoch counter\nepoch_num = 0\n\n# initialize variables\nSi = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input)\nSo = tf.placeholder(\"float\", shape=[None, 3]) # strokes (output)\n\n# Layer's sizes\nx_size = Si.shape[1] # Number of input nodes: x, y, state\nh_size = 256 # Number of hidden nodes\ny_size = So.shape[1] # Number of outcomes (x,y,pen)\n\noutput = tf.placeholder(\"float\", shape=[None,y_size])\n\n# convert to tensorflow tensor\nSi = tf.cast(tf.stack(Si,name='Si'),tf.float32)\nSo = tf.cast(tf.stack(So,name='So'),tf.float32)\n\n# Weight initializations\nW1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW2 = tf.get_variable('W2', [h_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb2 = tf.get_variable('b2', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW3 = tf.get_variable('W3', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb3 = tf.get_variable('b3', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# forward propagation\nfc1 = tf.nn.relu(tf.nn.xw_plus_b(Si, W1, b1,name='fc1'))\nfc2 = tf.nn.relu(tf.nn.xw_plus_b(fc1, W2, b2,name='fc2'))\noutput = tf.nn.xw_plus_b(fc1, W3, b3,name='output')\n\nactual_offset = tf.slice(So,[0,0],[batch_size,2])\nactual_pen = tf.squeeze(tf.slice(So,[0,2],[batch_size,-1]))\npred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_multiplier)\npred_pen = tf.squeeze(tf.slice(output,[0,2],[batch_size,-1]))\n\noffset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\npen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels = actual_pen,\n logits = pred_pen))\n\nloss = tf.add(tf.multiply(offset_weight,offset_loss),tf.multiply(1-offset_weight,pen_loss))\n\n# run backprop\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\n# saver\nsave = False\nsaver = tf.train.Saver()\n\n# get predicted stroke vector\nstrokes = tf.concat([pred_offset, tf.expand_dims(tf.round(tf.sigmoid(pred_pen)+1),1)],axis=1)\nStrokes = []\n\n# run batches\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n for m,idx in get_minibatches(S_train.as_matrix().astype('float32')[:len(S_train)-1],batch_size,shuffle=True): \n\n Si_batch = m # batch of current strokes \n \n if (max(idx)<45040):\n So_batch = S_train.iloc[idx+1].as_matrix().astype('float32')\n \n updates = sess.run([offset_loss, pen_loss, loss, pred_offset, actual_pen, pred_pen, strokes], feed_dict={Si:Si_batch,So:So_batch}) \n\n offset_loss_ = updates[0]\n pen_loss_ = updates[1]\n loss_ = updates[2]\n pred_offset_ = updates[3]\n actual_pen_ = updates[4]\n pred_pen_ = updates[5]\n strokes_ = updates[6]\n \n if epoch_num%200==0:\n print \"Epoch: \" + str(epoch_num) + \" | Loss: \" + str(loss_) + \\\n \" | Offset loss: \" + str(offset_loss_) + \" | Pen loss: \" + str(pen_loss_) \n\n # save\n if save:\n saver.save(sess, 'checkpoints/pix2svg_train_svg2svg_0')\n \n # increment epoch number\n epoch_num += 1\n",
"Epoch: 0 | Loss: 8250.34 | Offset loss: 10273.1 | Pen loss: 159.433\nEpoch: 200 | Loss: 5645.42 | Offset loss: 7020.43 | Pen loss: 145.378\nEpoch: 400 | Loss: 8678.95 | Offset loss: 10783.6 | Pen loss: 260.344\nEpoch: 600 | Loss: 4909.4 | Offset loss: 6119.17 | Pen loss: 70.3102\nEpoch: 800 | Loss: 7867.83 | Offset loss: 9817.23 | Pen loss: 70.2685\nEpoch: 1000 | Loss: 2980.32 | Offset loss: 3712.18 | Pen loss: 52.8845\nEpoch: 1200 | Loss: 6821.04 | Offset loss: 8498.8 | Pen loss: 110.025\nEpoch: 1400 | Loss: 8527.17 | Offset loss: 10632.4 | Pen loss: 106.13\nEpoch: 1600 | Loss: 6072.67 | Offset loss: 7574.29 | Pen loss: 66.2271\nEpoch: 1800 | Loss: 6337.97 | Offset loss: 7834.5 | Pen loss: 351.836\nEpoch: 2000 | Loss: 10150.8 | Offset loss: 12651.0 | Pen loss: 149.963\nEpoch: 2200 | Loss: 3221.87 | Offset loss: 4009.85 | Pen loss: 69.9651\nEpoch: 2400 | Loss: 7817.52 | Offset loss: 9739.13 | Pen loss: 131.052\nEpoch: 2600 | Loss: 2849.59 | Offset loss: 3548.3 | Pen loss: 54.7421\nEpoch: 2800 | Loss: 7948.94 | Offset loss: 9887.3 | Pen loss: 195.522\nEpoch: 3000 | Loss: 12629.5 | Offset loss: 15757.5 | Pen loss: 117.646\nEpoch: 3200 | Loss: 3830.88 | Offset loss: 4769.15 | Pen loss: 77.7746\nEpoch: 3400 | Loss: 4502.43 | Offset loss: 5598.59 | Pen loss: 117.814\nEpoch: 3600 | Loss: 13247.9 | Offset loss: 16517.6 | Pen loss: 168.919\nEpoch: 3800 | Loss: 6957.13 | Offset loss: 8674.43 | Pen loss: 87.9368\nEpoch: 4000 | Loss: 5322.95 | Offset loss: 6609.43 | Pen loss: 177.03\nEpoch: 4200 | Loss: 3501.16 | Offset loss: 4359.94 | Pen loss: 66.0247\nEpoch: 4400 | Loss: 3366.67 | Offset loss: 4193.48 | Pen loss: 59.4112\n"
],
[
"plt.scatter(strokes_[:,0],strokes_[:,1])\nplt.show()",
"_____no_output_____"
],
[
"### demo of the difference between the absolute pen position and the relative pen position\nplt.figure()\ninds = list(S[(S.photoID=='n02691156_10151') & (S.sketchID==0)].index)\nverts = zip(S1.loc[inds].x.values,S1.loc[inds].y.values)\ncodes = S1.loc[inds].pen.values\npath = Path(verts, codes)\npatch = patches.PathPatch(path, facecolor='none', lw=2)\nax = plt.subplot(121)\nax.add_patch(patch)\nax.set_xlim(0,600)\nax.set_ylim(0,600) \nax.axis('off')\nplt.gca().invert_yaxis() # y values increase as you go down in image\nplt.show()\n\ninds = list(S[(S.photoID=='n02691156_10151') & (S.sketchID==0)].index)\nverts = zip(S2.loc[inds].x.values,S2.loc[inds].y.values)\ncodes = S2.loc[inds].pen.values\npath = Path(verts, codes)\npatch = patches.PathPatch(path, facecolor='none', lw=2)\nax = plt.subplot(122)\nax.add_patch(patch)\nax.set_xlim(-200,200)\nax.set_ylim(-200,200) \nax.axis('off')\nplt.gca().invert_yaxis() # y values increase as you go down in image\nplt.show()",
"_____no_output_____"
]
],
[
[
"### predict next offset on basis of previous 4 offsets",
"_____no_output_____"
]
],
[
[
"RANDOM_SEED = 42\ntf.set_random_seed(RANDOM_SEED)\n\n# reset entire graph\ntf.reset_default_graph()\n\n# weight on offset loss\noffset_weight = 1.\n\n# amount to multiply predicted offset values by\noffset_multiplier = 100.\n\n# learning rate\nlearning_rate = 0.001\n\n# set batch size\nbatch_size = 10\n\n# epoch counter\nepoch_num = 0\n\n# initialize variables\nSi4 = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input) -- 4th to last\nSi3 = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input) -- 3rd to last\nSi2 = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input) -- 2nd to last\nSi1 = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input) -- previous one\nSo = tf.placeholder(\"float\", shape=[None, 3]) # strokes (output)\n\n# Layer's sizes\nx_size = Si1.shape[1]*4 # Number of input nodes: x, y, state\nh_size = 512 # Number of hidden nodes\ny_size = So.shape[1] # Number of outcomes (x,y,pen)\n\noutput = tf.placeholder(\"float\", shape=[None,y_size])\n\n# convert to tensorflow tensor\nSi4 = tf.cast(tf.stack(Si4,name='Si4'),tf.float32)\nSi3 = tf.cast(tf.stack(Si3,name='Si3'),tf.float32)\nSi2 = tf.cast(tf.stack(Si2,name='Si2'),tf.float32)\nSi1 = tf.cast(tf.stack(Si1,name='Si1'),tf.float32)\nSi = tf.concat([Si4,Si3,Si2,Si1],axis=1)\nSo = tf.cast(tf.stack(So,name='So'),tf.float32)\n\n# Weight initializations\nW1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW2 = tf.get_variable('W2', [h_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb2 = tf.get_variable('b2', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW3 = tf.get_variable('W3', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb3 = tf.get_variable('b3', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# forward propagation\nfc1 = tf.nn.relu(tf.nn.xw_plus_b(Si, W1, b1,name='fc1'))\nfc2 = tf.nn.relu(tf.nn.xw_plus_b(fc1, W2, b2,name='fc2'))\noutput = tf.nn.xw_plus_b(fc1, W3, b3,name='output')\n\nactual_offset = tf.slice(So,[0,0],[batch_size,2])\nactual_pen = tf.squeeze(tf.slice(So,[0,2],[batch_size,-1]))\npred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_multiplier)\npred_pen = tf.squeeze(tf.slice(output,[0,2],[batch_size,-1]))\n\noffset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\npen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels = actual_pen,\n logits = pred_pen))\n\nloss = tf.add(tf.multiply(offset_weight,offset_loss),tf.multiply(1-offset_weight,pen_loss))\n\n# run backprop\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\n# saver\nsave = False\nsaver = tf.train.Saver()\n\n# get predicted stroke vector\nstrokes = tf.concat([pred_offset, tf.expand_dims(tf.round(tf.sigmoid(pred_pen)+1),1)],axis=1)\nStrokes = []\n\n# run batches\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n for m,idx in get_minibatches(S_train.as_matrix().astype('float32')[:len(S_train)-1],batch_size,shuffle=True): \n\n Si1_batch = m # batch of current strokes \n Si2_batch = S_train.iloc[idx-1].as_matrix().astype('float32')\n Si3_batch = S_train.iloc[idx-2].as_matrix().astype('float32')\n Si4_batch = S_train.iloc[idx-3].as_matrix().astype('float32')\n \n if (max(idx)<45040):\n So_batch = S_train.iloc[idx+1].as_matrix().astype('float32')\n \n updates = sess.run([offset_loss, pen_loss, loss, \n pred_offset, actual_pen, pred_pen, strokes], \n feed_dict={Si1:Si1_batch,Si2:Si2_batch,Si3:Si3_batch,Si4:Si4_batch,\n So:So_batch}) \n\n offset_loss_ = updates[0]\n pen_loss_ = updates[1]\n loss_ = updates[2]\n pred_offset_ = updates[3]\n actual_pen_ = updates[4]\n pred_pen_ = updates[5]\n strokes_ = updates[6]\n \n if epoch_num%200==0:\n print \"Epoch: \" + str(epoch_num) + \" | Loss: \" + str(loss_) + \\\n \" | Offset loss: \" + str(offset_loss_) + \" | Pen loss: \" + str(pen_loss_) \n\n # save\n if save:\n saver.save(sess, 'checkpoints/pix2svg_train_svg2svg_0')\n \n # increment epoch number\n epoch_num += 1\n",
"_____no_output_____"
]
],
[
[
"### now trying to predict mixture of gaussians rather than naive nonlinear function... because pen offsets can't be modeled by any function\n\n",
"_____no_output_____"
],
[
"reverting to trying to predict next pen offset based on single most recent pen offset",
"_____no_output_____"
]
],
[
[
"## now trying to predict mixture of gaussians rather than naive nonlinear function... because pen offsets can't be modeled by any function\n\nimport mdn as mdn ## import mixture density network helpers\nreload(mdn)\n\nRANDOM_SEED = 42\ntf.set_random_seed(RANDOM_SEED)\n\n# reset entire graph\ntf.reset_default_graph()\n\n# weight on offset loss\noffset_weight = 0.8\n\n# amount to multiply predicted offset values by\noffset_multiplier = 100.\n\n# learning rate\nlearning_rate = 0.001\n\n# set batch size\nbatch_size = 10\n\n# epoch counter\nepoch_num = 0\n\n# initialize variables\nSi = tf.placeholder(\"float\", shape=[None, 3]) # strokes (input)\nSo = tf.placeholder(\"float\", shape=[None, 3]) # strokes (output) \nr_cost = tf.placeholder(\"float\", shape=[None])\nx1_data = tf.placeholder(\"float\",shape=[None])\nx2_data = tf.placeholder(\"float\",shape=[None])\npen_data = tf.placeholder(\"float\",shape=[None])\noffset_loss = tf.placeholder(\"float\",shape=[None])\nstate_loss = tf.placeholder(\"float\",shape=[None])\nrecon_loss = tf.placeholder(\"float\",shape=[None])\n\n# Layer's sizes\nx_size = Si.shape[1] # Number of input nodes: x, y, state\nh_size = 384 # Number of hidden nodes 6*64\n# y_size = So.shape[1] # Number of outcomes (x,y,pen)\ny_size = 8 ## split this into MDN parameters: first two elements are pen state logits (1 or 2), next 384/6 are for estimating the other parameters\n\noutput = tf.placeholder(\"float\", shape=[None,y_size])\n\n# # convert to tensorflow tensor\nSi = tf.cast(tf.stack(Si,name='Si'),tf.float32)\nSo = tf.cast(tf.stack(So,name='So'),tf.float32)\n\n# Weight initializations\nW1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW2 = tf.get_variable('W2', [h_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb2 = tf.get_variable('b2', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\nW3 = tf.get_variable('W3', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\nb3 = tf.get_variable('b3', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# forward propagation\nfc1 = tf.nn.relu(tf.nn.xw_plus_b(Si, W1, b1,name='fc1'))\nfc2 = tf.nn.relu(tf.nn.xw_plus_b(fc1, W2, b2,name='fc2'))\noutput = tf.nn.xw_plus_b(fc2, W3, b3,name='output')\n\n# get mixture distribution parameters\nout = mdn.get_mixture_coef(output)\n[o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_pen, o_pen_logits] = out ## each of these are the size of the batch\n\n# get target for prediction\ntarget = So # shape: (batch_size, 3) \n\n[x1_data, x2_data, pen_data] = tf.split(target, 3, 1)\nx1_data = tf.squeeze(x1_data) # shape (batch_size,) \nx2_data = tf.squeeze(x2_data) # shape (batch_size,) \npen_data = tf.squeeze(pen_data) # shape (batch_size,) \npen_data = tf.subtract(pen_data,1) # classes need to be in the range [0, num_classes-1]\n\n# compute reconstruction loss\noffset_loss, state_loss = mdn.get_lossfunc(o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr,\n o_pen_logits, x1_data, x2_data, pen_data)\noffset_loss = tf.squeeze(offset_loss)\nrecon_loss = tf.add(offset_loss,state_loss)\nloss = tf.reduce_sum(recon_loss,axis=0)\n\n# # run backprop\noptimizer = tf.train.AdamOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n for m,idx in get_minibatches(S_train.as_matrix().astype('float32')[:len(S_train)-1],batch_size,shuffle=True): \n\n Si_batch = m # batch of current strokes \n if (max(idx)<45040):\n So_batch = S_train.iloc[idx+1].as_matrix().astype('float32') \n \n results = sess.run([o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_pen, o_pen_logits, offset_loss, state_loss, recon_loss, loss], feed_dict={Si:Si_batch,So:So_batch}) \n \n _o_pi = results[0]\n _o_mu1 = results[1]\n _o_mu2 = results[2]\n _o_sigma1 = results[3]\n _o_sigma2 = results[4]\n _o_corr = results[5]\n _o_pen = results[6]\n _o_pen_logits = results[7] \n _offset_loss = results[8]\n _state_loss = results[9]\n _recon_loss = results[10]\n _loss = results[11]\n \n if epoch_num%100==0:\n print('Epoch Num: ', epoch_num, 'Reconstruction Loss:', _loss)\n \n epoch_num += 1",
"('Epoch Num: ', 0, 'Reconstruction Loss:', 142.40862)\n('Epoch Num: ', 100, 'Reconstruction Loss:', 146.73276)\n('Epoch Num: ', 200, 'Reconstruction Loss:', 143.53572)\n('Epoch Num: ', 300, 'Reconstruction Loss:', 146.30927)\n('Epoch Num: ', 400, 'Reconstruction Loss:', 143.62589)\n('Epoch Num: ', 500, 'Reconstruction Loss:', 142.88931)\n('Epoch Num: ', 600, 'Reconstruction Loss:', 143.24689)\n('Epoch Num: ', 700, 'Reconstruction Loss:', 144.42648)\n('Epoch Num: ', 800, 'Reconstruction Loss:', 144.39893)\n('Epoch Num: ', 900, 'Reconstruction Loss:', 91.308319)\n('Epoch Num: ', 1000, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 1100, 'Reconstruction Loss:', 143.09306)\n('Epoch Num: ', 1200, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 1300, 'Reconstruction Loss:', 145.02594)\n('Epoch Num: ', 1400, 'Reconstruction Loss:', 147.22566)\n('Epoch Num: ', 1500, 'Reconstruction Loss:', 147.19031)\n('Epoch Num: ', 1600, 'Reconstruction Loss:', 126.70847)\n('Epoch Num: ', 1700, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 1800, 'Reconstruction Loss:', 126.05428)\n('Epoch Num: ', 1900, 'Reconstruction Loss:', 136.02991)\n('Epoch Num: ', 2000, 'Reconstruction Loss:', 144.82986)\n('Epoch Num: ', 2100, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 2200, 'Reconstruction Loss:', 137.37674)\n('Epoch Num: ', 2300, 'Reconstruction Loss:', 134.56625)\n('Epoch Num: ', 2400, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 2500, 'Reconstruction Loss:', 146.08743)\n('Epoch Num: ', 2600, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 2700, 'Reconstruction Loss:', 141.49911)\n('Epoch Num: ', 2800, 'Reconstruction Loss:', 154.62381)\n('Epoch Num: ', 2900, 'Reconstruction Loss:', 122.30074)\n('Epoch Num: ', 3000, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 3100, 'Reconstruction Loss:', 146.26424)\n('Epoch Num: ', 3200, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 3300, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 3400, 'Reconstruction Loss:', 144.92764)\n('Epoch Num: ', 3500, 'Reconstruction Loss:', 139.46045)\n('Epoch Num: ', 3600, 'Reconstruction Loss:', 142.2424)\n('Epoch Num: ', 3700, 'Reconstruction Loss:', 146.02829)\n('Epoch Num: ', 3800, 'Reconstruction Loss:', 136.65732)\n('Epoch Num: ', 3900, 'Reconstruction Loss:', nan)\n('Epoch Num: ', 4000, 'Reconstruction Loss:', 143.90469)\n('Epoch Num: ', 4100, 'Reconstruction Loss:', 144.3707)\n('Epoch Num: ', 4200, 'Reconstruction Loss:', 144.22266)\n('Epoch Num: ', 4300, 'Reconstruction Loss:', 116.4599)\n('Epoch Num: ', 4400, 'Reconstruction Loss:', 144.01218)\n('Epoch Num: ', 4500, 'Reconstruction Loss:', nan)\n"
],
[
"a = tf.constant([2.,2.,1.,2.,2.,1.,1.,2.,1.,2.])\nb = tf.constant([1.,1.,1.,1.,1.,1.,1.,1.,1.,1.])\nc = tf.reshape(a,[-1,10]) \n### reshape with a -1 nests a tensor, so one that is originally of shape (10,) becomes (1,10)\nd = tf.split(c,10,1)\ne = tf.constant([-0.4])\n\nresult = tf.nn.softmax_cross_entropy_with_logits(labels=a,logits=b)\nsess = tf.InteractiveSession()\nsess.run(tf.initialize_all_variables())\nprint result.eval()\n\nprint a.eval(), a.get_shape()\nprint c.eval(), c.get_shape()\nprint tf.nn.softmax(c).eval()\nprint tf.nn.softmax(e).eval()\n\nsess.close()",
"WARNING:tensorflow:From <ipython-input-195-12c34c9f189d>:10: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.\nInstructions for updating:\nUse `tf.global_variables_initializer` instead.\n36.8414\n[ 2. 2. 1. 2. 2. 1. 1. 2. 1. 2.] (10,)\n[[ 2. 2. 1. 2. 2. 1. 1. 2. 1. 2.]] (1, 10)\n[[ 0.13384162 0.13384162 0.04923758 0.13384162 0.13384162 0.04923758\n 0.04923758 0.13384162 0.04923758 0.13384162]]\n[ 1.]\n"
],
[
"# NSAMPLE = 1000\nx_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T\nr_data = np.float32(np.random.normal(size=(NSAMPLE,1)))\ny_data = np.float32(np.sin(0.75*x_data)*7.0+x_data*0.5+r_data*1.0)\n\n# plt.figure(figsize=(8, 8))\n# plot_out = plt.plot(x_data,y_data,'ro',alpha=0.3)\n# plt.show()\n\n# temp_data = x_data\n# x_data = y_data\n# y_data = temp_data\n\n# plt.figure(figsize=(8, 8))\n# plot_out = plt.plot(x_data,y_data,'ro',alpha=0.3)\n# plt.show()",
"_____no_output_____"
],
[
"import mdn as mdn\n",
"_____no_output_____"
],
[
"mdn",
"_____no_output_____"
],
[
"x1 = tf.random_normal([1], mean=0, stddev=0.1)\nx2 = tf.random_normal([1], mean=1, stddev=0.1)\nmu1 = tf.constant(0., dtype=tf.float32)\nmu2 = tf.constant(1., dtype=tf.float32)\ns1 = tf.constant(1., dtype=tf.float32)\ns2 = tf.constant(1., dtype=tf.float32)\nrho = tf.constant(0., dtype=tf.float32)\nresult = mdn.tf_2d_normal(x1, x2, mu1, mu2, s1, s2, rho)\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\nprint x1.eval()\nprint x2.eval()\nprint result.eval()\nsess.close()",
"[ 0.02453992]\n[ 0.95884156]\n[ 0.1577232]\n"
],
[
"## self contained example of sinusoidal function fitting\nNSAMPLE = 1000\nx_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T\nr_data = np.float32(np.random.normal(size=(NSAMPLE,1)))\ny_data = np.float32(np.sin(0.75*x_data)*7.0+x_data*0.5+r_data*1.0)\n\nx = tf.placeholder(dtype=tf.float32, shape=[None,1])\ny = tf.placeholder(dtype=tf.float32, shape=[None,1])\n\nNHIDDEN = 20\nW = tf.Variable(tf.random_normal([1,NHIDDEN], stddev=1.0, dtype=tf.float32))\nb = tf.Variable(tf.random_normal([1,NHIDDEN], stddev=1.0, dtype=tf.float32))\n\nW_out = tf.Variable(tf.random_normal([NHIDDEN,1], stddev=1.0, dtype=tf.float32))\nb_out = tf.Variable(tf.random_normal([1,1], stddev=1.0, dtype=tf.float32))\n\nhidden_layer = tf.nn.tanh(tf.matmul(x, W) + b)\ny_out = tf.matmul(hidden_layer,W_out) + b_out\nlossfunc = tf.nn.l2_loss(y_out-y)\ntrain_op = tf.train.RMSPropOptimizer(learning_rate=0.1, decay=0.8).minimize(lossfunc)\n\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\nNEPOCH = 1000\nfor i in range(NEPOCH):\n sess.run(train_op,feed_dict={x: x_data, y: y_data})\n \nx_test = np.float32(np.arange(-10.5,10.5,0.1))\nx_test = x_test.reshape(x_test.size,1)\ny_test = sess.run(y_out,feed_dict={x: x_test})\n\nplt.figure(figsize=(8, 8))\nplt.plot(x_data,y_data,'ro', x_test,y_test,'bo',alpha=0.3)\nplt.show()\n\nsess.close() ",
"_____no_output_____"
],
[
"NHIDDEN = 24\nSTDEV = 0.5\nKMIX = 24 # number of mixtures\nNOUT = KMIX * 3 # pi, mu, stdev\n\nx = tf.placeholder(dtype=tf.float32, shape=[None,1], name=\"x\")\ny = tf.placeholder(dtype=tf.float32, shape=[None,1], name=\"y\")\n\nWh = tf.Variable(tf.random_normal([1,NHIDDEN], stddev=STDEV, dtype=tf.float32))\nbh = tf.Variable(tf.random_normal([1,NHIDDEN], stddev=STDEV, dtype=tf.float32))\n\nWo = tf.Variable(tf.random_normal([NHIDDEN,NOUT], stddev=STDEV, dtype=tf.float32))\nbo = tf.Variable(tf.random_normal([1,NOUT], stddev=STDEV, dtype=tf.float32))\n\nhidden_layer = tf.nn.tanh(tf.matmul(x, Wh) + bh)\noutput = tf.matmul(hidden_layer,Wo) + bo\n\ndef get_mixture_coef(output):\n out_pi = tf.placeholder(dtype=tf.float32, shape=[None,KMIX], name=\"mixparam\")\n out_sigma = tf.placeholder(dtype=tf.float32, shape=[None,KMIX], name=\"mixparam\")\n out_mu = tf.placeholder(dtype=tf.float32, shape=[None,KMIX], name=\"mixparam\")\n\n out_pi, out_sigma, out_mu = tf.split(output,3,1)\n\n max_pi = tf.reduce_max(out_pi, 1, keep_dims=True)\n out_pi = tf.subtract(out_pi, max_pi)\n\n out_pi = tf.exp(out_pi)\n\n normalize_pi = tf.reciprocal(tf.reduce_sum(out_pi, 1, keep_dims=True))\n out_pi = tf.multiply(normalize_pi, out_pi)\n\n out_sigma = tf.exp(out_sigma)\n\n return out_pi, out_sigma, out_mu\n\nout_pi, out_sigma, out_mu = get_mixture_coef(output)\n",
"Tensor(\"Mul_35:0\", shape=(?, 24), dtype=float32) Tensor(\"Exp_11:0\", shape=(?, 24), dtype=float32) Tensor(\"split_9:2\", shape=(?, 24), dtype=float32)\n"
],
[
"NSAMPLE = 2500\n\ny_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T\nr_data = np.float32(np.random.normal(size=(NSAMPLE,1))) # random noise\nx_data = np.float32(np.sin(0.75*y_data)*7.0+y_data*0.5+r_data*1.0)\n\noneDivSqrtTwoPI = 1 / math.sqrt(2*math.pi) # normalisation factor for gaussian, not needed.\ndef tf_normal(y, mu, sigma):\n result = tf.subtract(y, mu)\n result = tf.multiply(result,tf.reciprocal(sigma))\n result = -tf.square(result)/2\n return tf.multiply(tf.exp(result),tf.reciprocal(sigma))*oneDivSqrtTwoPI\n\ndef get_lossfunc(out_pi, out_sigma, out_mu, y):\n result = tf_normal(y, out_mu, out_sigma)\n result = tf.multiply(result, out_pi)\n result = tf.reduce_sum(result, 1, keep_dims=True)\n result = -tf.log(result)\n return tf.reduce_mean(result)\n\nlossfunc = get_lossfunc(out_pi, out_sigma, out_mu, y)\ntrain_op = tf.train.AdamOptimizer().minimize(lossfunc)\n\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\n\nNEPOCH = 10000\nloss = np.zeros(NEPOCH) # store the training progress here.\nfor i in range(NEPOCH):\n sess.run(train_op,feed_dict={x: x_data, y: y_data})\n loss[i] = sess.run(lossfunc, feed_dict={x: x_data, y: y_data})",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 8))\nplt.plot(np.arange(100, NEPOCH,1), loss[100:], 'r-')\nplt.show()",
"_____no_output_____"
],
[
"x_test = np.float32(np.arange(-15,15,0.1))\nNTEST = x_test.size\nx_test = x_test.reshape(NTEST,1) # needs to be a matrix, not a vector\n\ndef get_pi_idx(x, pdf):\n N = pdf.size\n accumulate = 0\n for i in range(0, N):\n accumulate += pdf[i]\n if (accumulate > x):\n return i\n print 'error with sampling ensemble'\n return -1\n\ndef generate_ensemble(out_pi, out_mu, out_sigma, M = 10):\n NTEST = x_test.size\n result = np.random.rand(NTEST, M) # initially random [0, 1]\n rn = np.random.randn(NTEST, M) # normal random matrix (0.0, 1.0)\n mu = 0\n std = 0\n idx = 0\n\n # transforms result into random ensembles\n for j in range(0, M): # mixtures\n for i in range(0, NTEST): # datapoints\n idx = get_pi_idx(result[i, j], out_pi[i])\n mu = out_mu[i, idx]\n std = out_sigma[i, idx]\n result[i, j] = mu + rn[i, j]*std\n return result",
"_____no_output_____"
],
[
"out_pi_test, out_sigma_test, out_mu_test = sess.run(get_mixture_coef(output), feed_dict={x: x_test})\n\ny_test = generate_ensemble(out_pi_test, out_mu_test, out_sigma_test)\n\nplt.figure(figsize=(8, 8))\nplt.plot(x_data,y_data,'ro', x_test,y_test,'bo',alpha=0.3)\nplt.show()\n",
"_____no_output_____"
],
[
"#####========================================================================\n\n# actual_offset = tf.slice(So,[0,0],[batch_size,2])\n# actual_pen = tf.squeeze(tf.slice(So,[0,2],[batch_size,-1]))\n\n# pred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_multiplier)\n# pred_pen = tf.squeeze(tf.slice(output,[0,2],[batch_size,-1]))\n\n# offset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\n# pen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n# labels = actual_pen,\n# logits = pred_pen))\n\n# loss = tf.add(tf.multiply(offset_weight,offset_loss),tf.multiply(1-offset_weight,pen_loss))\n\n# # run backprop\n# optimizer = tf.train.AdamOptimizer(learning_rate)\n# train_op = optimizer.minimize(loss)\n\n# # saver\n# save = False\n# saver = tf.train.Saver()\n\n# # get predicted stroke vector\n# strokes = tf.concat([pred_offset, tf.expand_dims(tf.round(tf.sigmoid(pred_pen_)+1),1)],axis=1)\n# Strokes = []\n\n# # run batches\n# with tf.Session() as sess:\n# tf.global_variables_initializer().run()\n# for m,idx in get_minibatches(S_train.as_matrix().astype('float32')[:len(S_train)-1],batch_size,shuffle=True): \n# Si_batch = m # batch of current strokes \n# if (max(idx)<45040):\n# So_batch = S_train.iloc[idx+1].as_matrix().astype('float32') \n# updates = sess.run([offset_loss, pen_loss, loss, pred_offset, actual_pen, pred_pen, strokes], feed_dict={Si:Si_batch,So:So_batch}) \n# offset_loss_ = updates[0]\n# pen_loss_ = updates[1]\n# loss_ = updates[2]\n# pred_offset_ = updates[3]\n# actual_pen_ = updates[4]\n# pred_pen_ = updates[5]\n# strokes_ = updates[6] \n# if epoch_num%200==0:\n# print \"Epoch: \" + str(epoch_num) + \" | Loss: \" + str(loss_) + \\\n# \" | Offset loss: \" + str(offset_loss_) + \" | Pen loss: \" + str(pen_loss_) \n# # save\n# if save:\n# saver.save(sess, 'checkpoints/pix2svg_train_svg2svg_0') \n# # increment epoch number\n# epoch_num += 1",
"_____no_output_____"
]
],
[
[
"### run rnn version",
"_____no_output_____"
]
],
[
[
"# RANDOM_SEED = 42\n# tf.set_random_seed(RANDOM_SEED)\n\n# # reset entire graph\n# tf.reset_default_graph()\n\n# # weight on offset loss\n# offset_weight = 1000.\n\n# # learning rate\n# learning_rate = 0.01\n\n# # set batch size\n# batch_size = 10\n\n# # epoch counter\n# epoch_num = 0\n\n# # max strokes\n# max_strokes = 200\n\n# # initialize variables\n# F = tf.placeholder(\"float\", shape=[None, 2048]) # features (input)\n# S = tf.placeholder(\"float\", shape=[None, 3]) # strokes (output)\n\n# # layer sizes\n# x_size = F.shape[1] # Number of input nodes: 2048 features and 1 bias\n# h_size = 512 # Number of hidden nodes\n# y_size = S.shape[1] # Number of outcomes (x,y,pen)\n\n# # rnn hyperparameters\n# rnn_hidden_size = 512 # number of rnn hidden units\n\n# output = tf.placeholder(\"float\", shape=[None,y_size])\n\n# # convert to tensorflow tensor\n# F = tf.cast(tf.stack(F,name='F'),tf.float32)\n# S = tf.cast(tf.stack(S,name='S'),tf.float32)\n\n# # Weight initializations\n# W1 = tf.get_variable('W1', [x_size, h_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\n# b1 = tf.get_variable('b1', [h_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n# W2 = tf.get_variable('W2', [h_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\n# b2 = tf.get_variable('b2', [y_size],initializer=tf.zeros_initializer(), dtype=tf.float32)\n\n# # forward propagation\n# # Run RNN and run linear layer to fit to correct size.\n\n# rnn_input = tf.nn.xw_plus_b(F, W1, b1,name='rnn_input')\n# cell = tf.contrib.rnn.BasicLSTMCell(rnn_hidden_size)\n# starting_state = cell.zero_state(batch_size=batch_size, dtype=tf.float32)\n# outputs, final_rnn_state = tf.contrib.rnn.static_rnn(cell, \n# [rnn_input]*max_strokes,\n# initial_state=starting_state,\n# dtype=tf.float32)\n# W_hy = tf.get_variable('W_hy', [rnn_hidden_size, y_size],initializer=tf.contrib.layers.xavier_initializer(), dtype=tf.float32)\n\n# preds = []\n# for output in outputs:\n# preds.append(tf.matmul(outputs, W_hy))\n\n\n# # output = tf.nn.xw_plus_b(fc1, W2, b2,name='output')\n\n# # actual_offset = tf.slice(S,[0,0],[batch_size,2])\n# # actual_pen = tf.slice(S,[0,2],[batch_size,-1]) \n# # pred_offset = tf.multiply(tf.slice(output,[0,0],[batch_size,2]),offset_weight)\n# # pred_pen = tf.nn.softmax(tf.slice(output,[0,2],[batch_size,-1]))\n\n# # offset_loss = tf.reduce_sum(tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(pred_offset,actual_offset)),axis=1)))\n# # pen_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n# # labels = actual_pen,\n# # logits = pred_pen))\n\n# # loss = tf.add(offset_loss,pen_loss)\n\n# # # run backprop\n# # optimizer = tf.train.AdamOptimizer(learning_rate)\n# # train_op = optimizer.minimize(loss)\n\n# # saver\n# save = False\n# saver = tf.train.Saver()\n\n# # # get predicted stroke vector\n# # strokes = tf.concat([pred_offset, pred_pen],axis=1)\n\n# # run batches\n# with tf.Session() as sess:\n# tf.global_variables_initializer().run()\n# for m in get_minibatches([F_train,S_train.as_matrix()],batch_size,shuffle=True):\n\n# if m[0].shape[0]==batch_size:\n# F_batch = m[0]\n# S_batch = m[1] \n\n# updates = sess.run([preds], feed_dict={F:F_batch,S:S_batch}) \n\n# preds_ = updates[0]\n\n# if epoch_num%200==0:\n# print \"Epoch: \" + str(epoch_num) \n\n# # save\n# if save:\n# saver.save(sess, 'checkpoints/pix2svg_train_rnn_0')\n \n# # increment epoch number\n# epoch_num += 1\n",
"_____no_output_____"
],
[
"# for epoch in range(50):\n# # Train with each examplea\n# for i in range(len(F_batch)):\n# sess.run(updates, feed_dict={X: F_batch[i: i + 1], y: S_batch[i: i + 1]})\n \n# loss = sess.run(output, feed_dict={X: F_batch, y: S_batch}) ",
"_____no_output_____"
],
[
"fig = plt.figure()\nim = plt.matshow(np.corrcoef(F_batch_array),vmin=0.5)\nplt.show()",
"_____no_output_____"
],
[
"sess.close()",
"_____no_output_____"
],
[
"# get minibatch\nbatch_size = 1500\nF_batch = F_train[:batch_size,:]\nS_batch = S_train.head(n=batch_size)\n\n# reserve numpy version \nF_batch_array = F_batch\nS_batch_array = S_batch.as_matrix()\n\nplt.matshow(np.corrcoef(F_batch_array))\nplt.show()",
"_____no_output_____"
],
[
"SF_ = SF[100:110,:]\nplt.matshow(np.corrcoef(SF_))\nplt.show()",
"_____no_output_____"
],
[
"PF_ = PF[:batch_size,:]\nplt.matshow(np.corrcoef(PF_))\nplt.show()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb0839d2ff2f9fad5d468d244539ebdeb2cc662c | 14,789 | ipynb | Jupyter Notebook | transformers_doc/tensorflow/benchmarks.ipynb | mwunderlich/notebooks | 0e7780ba3afed1a700ce54968273ecfdf6c25249 | [
"Apache-2.0"
] | 1 | 2022-01-30T06:40:35.000Z | 2022-01-30T06:40:35.000Z | transformers_doc/tensorflow/benchmarks.ipynb | Jimmy-INL/notebooks-2 | 7fb4452b4d3a084599bdb5167803bdd662c45125 | [
"Apache-2.0"
] | null | null | null | transformers_doc/tensorflow/benchmarks.ipynb | Jimmy-INL/notebooks-2 | 7fb4452b4d3a084599bdb5167803bdd662c45125 | [
"Apache-2.0"
] | null | null | null | 46.215625 | 329 | 0.514842 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb085a0faeb08897641ffdc44b1b50fdd52c53fd | 31,297 | ipynb | Jupyter Notebook | scb2pandas.ipynb | ostropunk/scb2pandas | dfc832c286754ae16dc465fc8750b071349e78ae | [
"MIT"
] | null | null | null | scb2pandas.ipynb | ostropunk/scb2pandas | dfc832c286754ae16dc465fc8750b071349e78ae | [
"MIT"
] | null | null | null | scb2pandas.ipynb | ostropunk/scb2pandas | dfc832c286754ae16dc465fc8750b071349e78ae | [
"MIT"
] | null | null | null | 78.635678 | 1,784 | 0.570821 | [
[
[
"import requests as rq\nimport json\nimport pandas as pd",
"_____no_output_____"
],
[
"class scb:\n def __init__(self, language='sv', levels=None, query=None):\n self.language = language\n self.url = 'http://api.scb.se/OV0104/v1/doris/{}/ssd/'.format(self.language)\n self.levels = None\n self.data = None\n self.dataframe = None\n self.variables = None\n self.table_name = None\n self.get_data(self.url, levels, query)\n \n def get_data(self, url, levels, query):\n if levels:\n print('Levels:')\n self.levels = levels\n for l in levels:\n print(l)\n url += l + '/'\n self.url = url\n with rq.get(url) as response:\n self.response = response\n self.data = response.json()\n if type(self.data) is list:\n #self.dataframe = pd.read_json(json.dumps(response.json()), orient='records')\n self.variables = None\n self.table_name = None\n self.dataframe = pd.read_json(response.content, orient='records')\n elif type(self.data) is dict:\n self.dataframe = None\n self.variables = self.data['variables']\n self.table_name = self.data['title']\n if query:\n self.query = {'query': [], \n 'response': {'format': 'json'}}\n for q in query:\n self.query['query'].append({'code': q['code'],\n 'selection': {'filter': \n 'item', \n 'values': q['values']}})\n with rq.post(url, json=self.query) as response:\n self.response = response\n self.data = response.json()\n index = []\n columns = []\n values = []\n \n for k in scbr.data['columns']:\n if k['type'] == 'c':\n columns.append(k['text'])\n \n \n for k in scbr.data['data']:\n index.append(k['key'])\n values.append(k['values'])\n \n self.dataframe = pd.read_json(\n json.dumps(\n {'index': index, \n 'columns':columns, \n 'data':values}), orient='split')\n \n else:\n self.dataframe = None\n \n# def set_query(self, )\n \n \n def __repr__(self):\n return str(self.data)",
"_____no_output_____"
],
[
"query = [{'code':'SNI2007', 'values':['J', 'Q']}, \n {'code': 'Storleksklass', 'values': ['SGR0',\n 'SGR1',\n 'SGR2',\n 'SGR3',\n 'SGR4',\n 'SGR5',\n 'SGR6',\n 'SGR7',\n 'SGR8']}, \n {'code': 'ContentsCode', 'values': ['000002YB']},\n {'code': 'Tid', 'values': ['2018', '2019']}]\n\nscbr = scb(levels=['NV', 'NV0101', 'FDBR07N'], query=query)\n",
"Levels:\nNV\nNV0101\nFDBR07N\nHas query: [{'code': 'SNI2007', 'values': ['J', 'Q']}, {'code': 'Storleksklass', 'values': ['SGR0', 'SGR1', 'SGR2', 'SGR3', 'SGR4', 'SGR5', 'SGR6', 'SGR7', 'SGR8']}, {'code': 'ContentsCode', 'values': ['000002YB']}, {'code': 'Tid', 'values': ['2018', '2019']}]\n"
],
[
"scbr.dataframe",
"_____no_output_____"
],
[
"# scbpd = pd.read_json(json.dumps({'index': [for k in scbr.data['columns'][0]]}), )\n\nindex = []\ncolumns = []\nvalues = []\n\nprint(scbr.data['columns'])\n\nfor k in scbr.data['columns']:\n if k['type'] == 'c':\n columns.append(k['text'])\n \nfor k in scbr.data['data']:\n index.append(k['key'][-1])\n values.append(k['values'])\n \n \njs = pd.read_json(json.dumps({'index': index, 'columns':columns, 'data':values}), orient='split')\njs",
"[{'code': 'NyckeltalSCB', 'text': 'typ av nyckeltal', 'type': 'd'}, {'code': 'Tid', 'text': 'månad', 'type': 't'}, {'code': '000001DE', 'text': 'Nyckeltal', 'type': 'c'}, {'code': '000001DD', 'text': 'Förändring mot föregående månad, procent', 'type': 'c'}, {'code': '000001D9', 'text': 'Förändring mot samma månad föregående år, procent', 'type': 'c'}]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb08691166b6cb75ca0cb6e6536b2a542aa75d8e | 5,492 | ipynb | Jupyter Notebook | TensorFlow-2.0/02-Tensorflow-Demo/01-HelloWorld.ipynb | silence1016/machine-learning | 1cb489f01d40c0b3036bd8d5e1b550b356f9a07c | [
"MIT"
] | 1 | 2020-03-19T10:04:14.000Z | 2020-03-19T10:04:14.000Z | TensorFlow-2.0/02-Tensorflow-Demo/01-HelloWorld.ipynb | silence1016/machine-learning | 1cb489f01d40c0b3036bd8d5e1b550b356f9a07c | [
"MIT"
] | null | null | null | TensorFlow-2.0/02-Tensorflow-Demo/01-HelloWorld.ipynb | silence1016/machine-learning | 1cb489f01d40c0b3036bd8d5e1b550b356f9a07c | [
"MIT"
] | null | null | null | 23.172996 | 81 | 0.493263 | [
[
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"tf.compat.v1.disable_eager_execution()",
"_____no_output_____"
],
[
"hw = tf.constant(\"Hello, TensorFLow!\")",
"_____no_output_____"
],
[
"# launch a Tensorflow Session\nsess = tf.compat.v1.Session()",
"_____no_output_____"
],
[
"print(sess.run(hw))",
"Hello, TensorFLow!\n"
],
[
"import tensorflow.compat.v1 as tf\ntf.disable_eager_execution()\nhw = tf.constant(\"Hello, TensorFLow!\")\nsess = tf.Session()\nprint(sess.run(hw))",
"Hello, TensorFLow!\n"
]
],
[
[
"### TensorFlow Mnist手写识别",
"_____no_output_____"
]
],
[
[
"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, optimizers, datasets",
"_____no_output_____"
],
[
"(x, y), (x_val, y_val) = datasets.mnist.load_data() \nx = tf.convert_to_tensor(x, dtype=tf.float32) / 255.\ny = tf.convert_to_tensor(y, dtype=tf.int32)\ny = tf.one_hot(y, depth=10)\nprint(x.shape, y.shape)\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x, y))\ntrain_dataset = train_dataset.batch(200)\n\nmodel = keras.Sequential([ \n layers.Dense(512, activation='relu'),\n layers.Dense(256, activation='relu'),\n layers.Dense(10)])\n\noptimizer = optimizers.SGD(learning_rate=0.001)",
"(60000, 28, 28) (60000, 10)\n"
],
[
"def train_epoch(epoch):\n\n # Step4.loop\n for step, (x, y) in enumerate(train_dataset):\n\n\n with tf.GradientTape() as tape:\n # [b, 28, 28] => [b, 784]\n x = tf.reshape(x, (-1, 28*28))\n # Step1. compute output\n # [b, 784] => [b, 10]\n out = model(x)\n # Step2. compute loss\n loss = tf.reduce_sum(tf.square(out - y)) / x.shape[0]\n\n # Step3. optimize and update w1, w2, w3, b1, b2, b3\n grads = tape.gradient(loss, model.trainable_variables)\n # w' = w - lr * grad\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n if step % 100 == 0:\n print(epoch, step, 'loss:', loss.numpy())",
"_____no_output_____"
],
[
"for epoch in range(10):\n train_epoch(epoch)",
"0 0 loss: 2.0240273\n0 100 loss: 0.9473155\n0 200 loss: 0.7345356\n1 0 loss: 0.69385874\n1 100 loss: 0.6878035\n1 200 loss: 0.56050974\n2 0 loss: 0.5645488\n2 100 loss: 0.5928352\n2 200 loss: 0.48700562\n3 0 loss: 0.49895468\n3 100 loss: 0.5390559\n3 200 loss: 0.44372237\n4 0 loss: 0.45752183\n4 100 loss: 0.5022621\n4 200 loss: 0.41399825\n5 0 loss: 0.42798957\n5 100 loss: 0.47416046\n5 200 loss: 0.39180848\n6 0 loss: 0.40511882\n6 100 loss: 0.45166504\n6 200 loss: 0.37404716\n7 0 loss: 0.3866536\n7 100 loss: 0.43284827\n7 200 loss: 0.35909376\n8 0 loss: 0.37125632\n8 100 loss: 0.4168091\n8 200 loss: 0.34640494\n9 0 loss: 0.35803282\n9 100 loss: 0.40296906\n9 200 loss: 0.33531845\n"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb086e9c24baf3cc8741ef2893314ba8365b722c | 22,759 | ipynb | Jupyter Notebook | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 0.16/_downloads/plot_brainstorm_auditory.ipynb | drammock/mne-tools.github.io | 5d3a104d174255644d8d5335f58036e32695e85d | [
"BSD-3-Clause"
] | null | null | null | 45.156746 | 993 | 0.597214 | [
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n# Brainstorm auditory tutorial dataset\n\n\nHere we compute the evoked from raw for the auditory Brainstorm\ntutorial dataset. For comparison, see [1]_ and the associated\n`brainstorm site <http://neuroimage.usc.edu/brainstorm/Tutorials/Auditory>`_.\n\nExperiment:\n\n - One subject, 2 acquisition runs 6 minutes each.\n - Each run contains 200 regular beeps and 40 easy deviant beeps.\n - Random ISI: between 0.7s and 1.7s seconds, uniformly distributed.\n - Button pressed when detecting a deviant with the right index finger.\n\nThe specifications of this dataset were discussed initially on the\n`FieldTrip bug tracker <http://bugzilla.fcdonders.nl/show_bug.cgi?id=2300>`_.\n\nReferences\n----------\n.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.\n Brainstorm: A User-Friendly Application for MEG/EEG Analysis.\n Computational Intelligence and Neuroscience, vol. 2011, Article ID\n 879716, 13 pages, 2011. doi:10.1155/2011/879716\n\n",
"_____no_output_____"
]
],
[
[
"# Authors: Mainak Jas <[email protected]>\n# Eric Larson <[email protected]>\n# Jaakko Leppakangas <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport pandas as pd\nimport numpy as np\n\nimport mne\nfrom mne import combine_evoked\nfrom mne.minimum_norm import apply_inverse\nfrom mne.datasets.brainstorm import bst_auditory\nfrom mne.io import read_raw_ctf\n\nprint(__doc__)",
"_____no_output_____"
]
],
[
[
"To reduce memory consumption and running time, some of the steps are\nprecomputed. To run everything from scratch change this to False. With\n``use_precomputed = False`` running time of this script can be several\nminutes even on a fast computer.\n\n",
"_____no_output_____"
]
],
[
[
"use_precomputed = True",
"_____no_output_____"
]
],
[
[
"The data was collected with a CTF 275 system at 2400 Hz and low-pass\nfiltered at 600 Hz. Here the data and empty room data files are read to\nconstruct instances of :class:`mne.io.Raw`.\n\n",
"_____no_output_____"
]
],
[
[
"data_path = bst_auditory.data_path()\n\nsubject = 'bst_auditory'\nsubjects_dir = op.join(data_path, 'subjects')\n\nraw_fname1 = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_AEF_20131218_01.ds')\nraw_fname2 = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_AEF_20131218_02.ds')\nerm_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_Noise_20131218_01.ds')",
"_____no_output_____"
]
],
[
[
"In the memory saving mode we use ``preload=False`` and use the memory\nefficient IO which loads the data on demand. However, filtering and some\nother functions require the data to be preloaded in the memory.\n\n",
"_____no_output_____"
]
],
[
[
"preload = not use_precomputed\nraw = read_raw_ctf(raw_fname1, preload=preload)\nn_times_run1 = raw.n_times\nmne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=preload)])\nraw_erm = read_raw_ctf(erm_fname, preload=preload)",
"_____no_output_____"
]
],
[
[
"Data channel array consisted of 274 MEG axial gradiometers, 26 MEG reference\nsensors and 2 EEG electrodes (Cz and Pz).\nIn addition:\n\n - 1 stim channel for marking presentation times for the stimuli\n - 1 audio channel for the sent signal\n - 1 response channel for recording the button presses\n - 1 ECG bipolar\n - 2 EOG bipolar (vertical and horizontal)\n - 12 head tracking channels\n - 20 unused channels\n\nThe head tracking channels and the unused channels are marked as misc\nchannels. Here we define the EOG and ECG channels.\n\n",
"_____no_output_____"
]
],
[
[
"raw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})\nif not use_precomputed:\n # Leave out the two EEG channels for easier computation of forward.\n raw.pick_types(meg=True, eeg=False, stim=True, misc=True, eog=True,\n ecg=True)",
"_____no_output_____"
]
],
[
[
"For noise reduction, a set of bad segments have been identified and stored\nin csv files. The bad segments are later used to reject epochs that overlap\nwith them.\nThe file for the second run also contains some saccades. The saccades are\nremoved by using SSP. We use pandas to read the data from the csv files. You\ncan also view the files with your favorite text editor.\n\n",
"_____no_output_____"
]
],
[
[
"annotations_df = pd.DataFrame()\noffset = n_times_run1\nfor idx in [1, 2]:\n csv_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'events_bad_0%s.csv' % idx)\n df = pd.read_csv(csv_fname, header=None,\n names=['onset', 'duration', 'id', 'label'])\n print('Events from run {0}:'.format(idx))\n print(df)\n\n df['onset'] += offset * (idx - 1)\n annotations_df = pd.concat([annotations_df, df], axis=0)\n\nsaccades_events = df[df['label'] == 'saccade'].values[:, :3].astype(int)\n\n# Conversion from samples to times:\nonsets = annotations_df['onset'].values / raw.info['sfreq']\ndurations = annotations_df['duration'].values / raw.info['sfreq']\ndescriptions = annotations_df['label'].values\n\nannotations = mne.Annotations(onsets, durations, descriptions)\nraw.annotations = annotations\ndel onsets, durations, descriptions",
"_____no_output_____"
]
],
[
[
"Here we compute the saccade and EOG projectors for magnetometers and add\nthem to the raw data. The projectors are added to both runs.\n\n",
"_____no_output_____"
]
],
[
[
"saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,\n reject_by_annotation=False)\n\nprojs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,\n desc_prefix='saccade')\nif use_precomputed:\n proj_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-eog-proj.fif')\n projs_eog = mne.read_proj(proj_fname)[0]\nelse:\n projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),\n n_mag=1, n_eeg=0)\nraw.add_proj(projs_saccade)\nraw.add_proj(projs_eog)\ndel saccade_epochs, saccades_events, projs_eog, projs_saccade # To save memory",
"_____no_output_____"
]
],
[
[
"Visually inspect the effects of projections. Click on 'proj' button at the\nbottom right corner to toggle the projectors on/off. EOG events can be\nplotted by adding the event list as a keyword argument. As the bad segments\nand saccades were added as annotations to the raw data, they are plotted as\nwell.\n\n",
"_____no_output_____"
]
],
[
[
"raw.plot(block=True)",
"_____no_output_____"
]
],
[
[
"Typical preprocessing step is the removal of power line artifact (50 Hz or\n60 Hz). Here we notch filter the data at 60, 120 and 180 to remove the\noriginal 60 Hz artifact and the harmonics. The power spectra are plotted\nbefore and after the filtering to show the effect. The drop after 600 Hz\nappears because the data was filtered during the acquisition. In memory\nsaving mode we do the filtering at evoked stage, which is not something you\nusually would do.\n\n",
"_____no_output_____"
]
],
[
[
"if not use_precomputed:\n meg_picks = mne.pick_types(raw.info, meg=True, eeg=False)\n raw.plot_psd(tmax=np.inf, picks=meg_picks)\n notches = np.arange(60, 181, 60)\n raw.notch_filter(notches, phase='zero-double', fir_design='firwin2')\n raw.plot_psd(tmax=np.inf, picks=meg_picks)",
"_____no_output_____"
]
],
[
[
"We also lowpass filter the data at 100 Hz to remove the hf components.\n\n",
"_____no_output_____"
]
],
[
[
"if not use_precomputed:\n raw.filter(None, 100., h_trans_bandwidth=0.5, filter_length='10s',\n phase='zero-double', fir_design='firwin2')",
"_____no_output_____"
]
],
[
[
"Epoching and averaging.\nFirst some parameters are defined and events extracted from the stimulus\nchannel (UPPT001). The rejection thresholds are defined as peak-to-peak\nvalues and are in T / m for gradiometers, T for magnetometers and\nV for EOG and EEG channels.\n\n",
"_____no_output_____"
]
],
[
[
"tmin, tmax = -0.1, 0.5\nevent_id = dict(standard=1, deviant=2)\nreject = dict(mag=4e-12, eog=250e-6)\n# find events\nevents = mne.find_events(raw, stim_channel='UPPT001')",
"_____no_output_____"
]
],
[
[
"The event timing is adjusted by comparing the trigger times on detected\nsound onsets on channel UADC001-4408.\n\n",
"_____no_output_____"
]
],
[
[
"sound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]\nonsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]\nmin_diff = int(0.5 * raw.info['sfreq'])\ndiffs = np.concatenate([[min_diff + 1], np.diff(onsets)])\nonsets = onsets[diffs > min_diff]\nassert len(onsets) == len(events)\ndiffs = 1000. * (events[:, 0] - onsets) / raw.info['sfreq']\nprint('Trigger delay removed (μ ± σ): %0.1f ± %0.1f ms'\n % (np.mean(diffs), np.std(diffs)))\nevents[:, 0] = onsets\ndel sound_data, diffs",
"_____no_output_____"
]
],
[
[
"We mark a set of bad channels that seem noisier than others. This can also\nbe done interactively with ``raw.plot`` by clicking the channel name\n(or the line). The marked channels are added as bad when the browser window\nis closed.\n\n",
"_____no_output_____"
]
],
[
[
"raw.info['bads'] = ['MLO52-4408', 'MRT51-4408', 'MLO42-4408', 'MLO43-4408']",
"_____no_output_____"
]
],
[
[
"The epochs (trials) are created for MEG channels. First we find the picks\nfor MEG and EOG channels. Then the epochs are constructed using these picks.\nThe epochs overlapping with annotated bad segments are also rejected by\ndefault. To turn off rejection by bad segments (as was done earlier with\nsaccades) you can use keyword ``reject_by_annotation=False``.\n\n",
"_____no_output_____"
]
],
[
[
"picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,\n exclude='bads')\n\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=reject, preload=False,\n proj=True)",
"_____no_output_____"
]
],
[
[
"We only use first 40 good epochs from each run. Since we first drop the bad\nepochs, the indices of the epochs are no longer same as in the original\nepochs collection. Investigation of the event timings reveals that first\nepoch from the second run corresponds to index 182.\n\n",
"_____no_output_____"
]
],
[
[
"epochs.drop_bad()\nepochs_standard = mne.concatenate_epochs([epochs['standard'][range(40)],\n epochs['standard'][182:222]])\nepochs_standard.load_data() # Resampling to save memory.\nepochs_standard.resample(600, npad='auto')\nepochs_deviant = epochs['deviant'].load_data()\nepochs_deviant.resample(600, npad='auto')\ndel epochs, picks",
"_____no_output_____"
]
],
[
[
"The averages for each conditions are computed.\n\n",
"_____no_output_____"
]
],
[
[
"evoked_std = epochs_standard.average()\nevoked_dev = epochs_deviant.average()\ndel epochs_standard, epochs_deviant",
"_____no_output_____"
]
],
[
[
"Typical preprocessing step is the removal of power line artifact (50 Hz or\n60 Hz). Here we lowpass filter the data at 40 Hz, which will remove all\nline artifacts (and high frequency information). Normally this would be done\nto raw data (with :func:`mne.io.Raw.filter`), but to reduce memory\nconsumption of this tutorial, we do it at evoked stage. (At the raw stage,\nyou could alternatively notch filter with :func:`mne.io.Raw.notch_filter`.)\n\n",
"_____no_output_____"
]
],
[
[
"for evoked in (evoked_std, evoked_dev):\n evoked.filter(l_freq=None, h_freq=40., fir_design='firwin')",
"_____no_output_____"
]
],
[
[
"Here we plot the ERF of standard and deviant conditions. In both conditions\nwe can see the P50 and N100 responses. The mismatch negativity is visible\nonly in the deviant condition around 100-200 ms. P200 is also visible around\n170 ms in both conditions but much stronger in the standard condition. P300\nis visible in deviant condition only (decision making in preparation of the\nbutton press). You can view the topographies from a certain time span by\npainting an area with clicking and holding the left mouse button.\n\n",
"_____no_output_____"
]
],
[
[
"evoked_std.plot(window_title='Standard', gfp=True, time_unit='s')\nevoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s')",
"_____no_output_____"
]
],
[
[
"Show activations as topography figures.\n\n",
"_____no_output_____"
]
],
[
[
"times = np.arange(0.05, 0.301, 0.025)\nevoked_std.plot_topomap(times=times, title='Standard', time_unit='s')\nevoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s')",
"_____no_output_____"
]
],
[
[
"We can see the MMN effect more clearly by looking at the difference between\nthe two conditions. P50 and N100 are no longer visible, but MMN/P200 and\nP300 are emphasised.\n\n",
"_____no_output_____"
]
],
[
[
"evoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal')\nevoked_difference.plot(window_title='Difference', gfp=True, time_unit='s')",
"_____no_output_____"
]
],
[
[
"Source estimation.\nWe compute the noise covariance matrix from the empty room measurement\nand use it for the other runs.\n\n",
"_____no_output_____"
]
],
[
[
"reject = dict(mag=4e-12)\ncov = mne.compute_raw_covariance(raw_erm, reject=reject)\ncov.plot(raw_erm.info)\ndel raw_erm",
"_____no_output_____"
]
],
[
[
"The transformation is read from a file. More information about coregistering\nthe data, see `ch_interactive_analysis` or\n:func:`mne.gui.coregistration`.\n\n",
"_____no_output_____"
]
],
[
[
"trans_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-trans.fif')\ntrans = mne.read_trans(trans_fname)",
"_____no_output_____"
]
],
[
[
"To save time and memory, the forward solution is read from a file. Set\n``use_precomputed=False`` in the beginning of this script to build the\nforward solution from scratch. The head surfaces for constructing a BEM\nsolution are read from a file. Since the data only contains MEG channels, we\nonly need the inner skull surface for making the forward solution. For more\ninformation: `CHDBBCEJ`, :func:`mne.setup_source_space`,\n`create_bem_model`, :func:`mne.bem.make_watershed_bem`.\n\n",
"_____no_output_____"
]
],
[
[
"if use_precomputed:\n fwd_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-meg-oct-6-fwd.fif')\n fwd = mne.read_forward_solution(fwd_fname)\nelse:\n src = mne.setup_source_space(subject, spacing='ico4',\n subjects_dir=subjects_dir, overwrite=True)\n model = mne.make_bem_model(subject=subject, ico=4, conductivity=[0.3],\n subjects_dir=subjects_dir)\n bem = mne.make_bem_solution(model)\n fwd = mne.make_forward_solution(evoked_std.info, trans=trans, src=src,\n bem=bem)\n\ninv = mne.minimum_norm.make_inverse_operator(evoked_std.info, fwd, cov)\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\ndel fwd",
"_____no_output_____"
]
],
[
[
"The sources are computed using dSPM method and plotted on an inflated brain\nsurface. For interactive controls over the image, use keyword\n``time_viewer=True``.\nStandard condition.\n\n",
"_____no_output_____"
]
],
[
[
"stc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM')\nbrain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.1, time_unit='s')\ndel stc_standard, brain",
"_____no_output_____"
]
],
[
[
"Deviant condition.\n\n",
"_____no_output_____"
]
],
[
[
"stc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM')\nbrain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.1, time_unit='s')\ndel stc_deviant, brain",
"_____no_output_____"
]
],
[
[
"Difference.\n\n",
"_____no_output_____"
]
],
[
[
"stc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM')\nbrain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.15, time_unit='s')",
"_____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",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"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"
]
] |
cb087147b257b87643840155b07e9d8141225656 | 4,769 | ipynb | Jupyter Notebook | Samples/OAuth PKCE flow from Python desktop/demo.ipynb | CamiloTerevinto/Blog | 99d1cd77d8d6971574fa2bbb74699f510ee36d29 | [
"MIT"
] | null | null | null | Samples/OAuth PKCE flow from Python desktop/demo.ipynb | CamiloTerevinto/Blog | 99d1cd77d8d6971574fa2bbb74699f510ee36d29 | [
"MIT"
] | null | null | null | Samples/OAuth PKCE flow from Python desktop/demo.ipynb | CamiloTerevinto/Blog | 99d1cd77d8d6971574fa2bbb74699f510ee36d29 | [
"MIT"
] | 1 | 2022-01-22T13:34:06.000Z | 2022-01-22T13:34:06.000Z | 32.442177 | 143 | 0.534494 | [
[
[
"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib import parse\nimport random\nimport string\nimport hashlib\nimport base64\nfrom typing import Any\nimport webbrowser\nimport requests\nfrom oauthlib.oauth2 import WebApplicationClient\n\n\nclass OAuthHttpServer(HTTPServer):\n def __init__(self, *args, **kwargs):\n HTTPServer.__init__(self, *args, **kwargs)\n self.authorization_code = \"\"\n\n\nclass OAuthHttpHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-Type\", \"text/html\")\n self.end_headers()\n self.wfile.write(\"<script type=\\\"application/javascript\\\">window.close();</script>\".encode(\"UTF-8\"))\n \n parsed = parse.urlparse(self.path)\n\n qs = parse.parse_qs(parsed.query)\n \n self.server.authorization_code = qs[\"code\"][0]\n\n\ndef generate_code() -> tuple[str, str]:\n rand = random.SystemRandom()\n code_verifier = ''.join(rand.choices(string.ascii_letters + string.digits, k=128))\n\n code_sha_256 = hashlib.sha256(code_verifier.encode('utf-8')).digest()\n b64 = base64.urlsafe_b64encode(code_sha_256)\n code_challenge = b64.decode('utf-8').replace('=', '')\n\n return (code_verifier, code_challenge)\n\n\ndef login(config: dict[str, Any]) -> str:\n with OAuthHttpServer(('', config[\"port\"]), OAuthHttpHandler) as httpd:\n client = WebApplicationClient(config[\"client_id\"])\n \n code_verifier, code_challenge = generate_code()\n\n auth_uri = client.prepare_request_uri(config[\"auth_uri\"], redirect_uri=config[\"redirect_uri\"], \n scope=config[\"scopes\"], state=\"test_doesnotmatter\", code_challenge= code_challenge, code_challenge_method = \"S256\" )\n\n webbrowser.open_new(auth_uri)\n\n httpd.handle_request()\n\n auth_code = httpd.authorization_code\n\n data = {\n \"code\": auth_code,\n \"client_id\": config[\"client_id\"],\n \"grant_type\": \"authorization_code\",\n \"scopes\": config[\"scopes\"],\n \"redirect_uri\": config[\"redirect_uri\"],\n \"code_verifier\": code_verifier\n }\n\n response = requests.post(config[\"token_uri\"], data=data, verify=False)\n\n access_token = response.json()[\"access_token\"]\n clear_output()\n\n print(\"Logged in successfully\")\n\n return access_token",
"_____no_output_____"
],
[
"from IPython.display import clear_output\n\nconfig = {\n \"port\": 8888,\n \"client_id\": \"python-nb\",\n \"redirect_uri\": f\"http://localhost:8888\",\n \"auth_uri\": \"https://localhost:44300/connect/authorize\",\n \"token_uri\": \"https://localhost:44300/connect/token\",\n \"scopes\": [ \"openid\", \"profile\", \"api\" ]\n}\n\naccess_token = login(config)\nheaders = { \"Authorization\": \"Bearer \" + access_token }",
"_____no_output_____"
],
[
"import json\n\nresponse = requests.get(\"https://localhost:44301/weatherforecast\", headers=headers, verify=False)\n\nprint(json.dumps(response.json(), indent=4))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
cb087ddf9f517b2f54f8ccf61d6bb961ba79e28a | 19,203 | ipynb | Jupyter Notebook | 01x_lazy.ipynb | fbidu/dask-tutorial | cc9235b4d4f731d955863c422cb7de27db13c9e9 | [
"BSD-3-Clause"
] | null | null | null | 01x_lazy.ipynb | fbidu/dask-tutorial | cc9235b4d4f731d955863c422cb7de27db13c9e9 | [
"BSD-3-Clause"
] | null | null | null | 01x_lazy.ipynb | fbidu/dask-tutorial | cc9235b4d4f731d955863c422cb7de27db13c9e9 | [
"BSD-3-Clause"
] | null | null | null | 31.688119 | 745 | 0.612717 | [
[
[
"<img src=\"images/dask_horizontal.svg\" align=\"right\" width=\"30%\">",
"_____no_output_____"
],
[
"# Lazy execution",
"_____no_output_____"
],
[
"Here we discuss some of the concepts behind dask, and lazy execution of code. You do not need to go through this material if you are eager to get on with the tutorial, but it may help understand the concepts underlying dask, how these things fit in with techniques you might already be using, and how to understand things that can go wrong.",
"_____no_output_____"
],
[
"## Prelude",
"_____no_output_____"
],
[
"As Python programmers, you probably already perform certain *tricks* to enable computation of larger-than-memory datasets, parallel execution or delayed/background execution. Perhaps with this phrasing, it is not clear what we mean, but a few examples should make things clearer. The point of Dask is to make simple things easy and complex things possible!\n\nAside from the [detailed introduction](http://dask.pydata.org/en/latest/), we can summarize the basics of Dask as follows:\n\n- process data that doesn't fit into memory by breaking it into blocks and specifying task chains\n- parallelize execution of tasks across cores and even nodes of a cluster\n- move computation to the data rather than the other way around, to minimize communication overhead\n\nAll of this allows you to get the most out of your computation resources, but program in a way that is very familiar: for-loops to build basic tasks, Python iterators, and the NumPy (array) and Pandas (dataframe) functions for multi-dimensional or tabular data, respectively.\n\nThe remainder of this notebook will take you through the first of these programming paradigms. This is more detail than some users will want, who can skip ahead to the iterator, array and dataframe sections; but there will be some data processing tasks that don't easily fit into those abstractions and need to fall back to the methods here.\n\nWe include a few examples at the end of the notebooks showing that the ideas behind how Dask is built are not actually that novel, and experienced programmers will have met parts of the design in other situations before. Those examples are left for the interested.",
"_____no_output_____"
],
[
"## Dask is a graph execution engine",
"_____no_output_____"
],
[
"Dask allows you to construct a prescription for the calculation you want to carry out. That may sound strange, but a simple example will demonstrate that you can achieve this while programming with perfectly ordinary Python functions and for-loops. We saw this in Chapter 02.",
"_____no_output_____"
]
],
[
[
"from dask import delayed\n\n@delayed\ndef inc(x):\n return x + 1\n\n@delayed\ndef add(x, y):\n return x + y",
"_____no_output_____"
]
],
[
[
"Here we have used the delayed annotation to show that we want these functions to operate lazily — to save the set of inputs and execute only on demand. `dask.delayed` is also a function which can do this, without the annotation, leaving the original function unchanged, e.g.,\n```python\n delayed_inc = delayed(inc)\n```",
"_____no_output_____"
]
],
[
[
"# this looks like ordinary code\nx = inc(15)\ny = inc(30)\ntotal = add(x, y)\n# incx, incy and total are all delayed objects. \n# They contain a prescription of how to execute",
"_____no_output_____"
]
],
[
[
"Calling a delayed function created a delayed object (`incx, incy, total`) - examine these interactively. Making these objects is somewhat equivalent to constructs like the `lambda` or function wrappers (see below). Each holds a simple dictionary describing the task graph, a full specification of how to carry out the computation.\n\nWe can visualize the chain of calculations that the object `total` corresponds to as follows; the circles are functions, rectangles are data/results.",
"_____no_output_____"
]
],
[
[
"total.visualize()",
"_____no_output_____"
]
],
[
[
"But so far, no functions have actually been executed. This demonstrated the division between the graph-creation part of Dask (`delayed()`, in this example) and the graph execution part of Dask.\n\nTo run the \"graph\" in the visualization, and actually get a result, do:",
"_____no_output_____"
]
],
[
[
"# execute all tasks\ntotal.compute()",
"_____no_output_____"
]
],
[
[
"**Why should you care about this?**\n\nBy building a specification of the calculation we want to carry out before executing anything, we can pass the specification to an *execution engine* for evaluation. In the case of Dask, this execution engine could be running on many nodes of a cluster, so you have access to the full number of CPU cores and memory across all the machines. Dask will intelligently execute your calculation with care for minimizing the amount of data held in memory, while parallelizing over the tasks that make up a graph. Notice that in the animated diagram below, where four workers are processing the (simple) graph, execution progresses vertically up the branches first, so that intermediate results can be expunged before moving onto a new branch.\n\nWith `delayed` and normal pythonic looped code, very complex graphs can be built up and passed on to Dask for execution. See a nice example of [simulated complex ETL](https://blog.dask.org/2017/01/24/dask-custom) work flow.\n\n",
"_____no_output_____"
],
[
"### Exercise",
"_____no_output_____"
],
[
"We will apply `delayed` to a real data processing task, albeit a simple one.\n\nConsider reading three CSV files with `pd.read_csv` and then measuring their total length. We will consider how you would do this with ordinary Python code, then build a graph for this process using delayed, and finally execute this graph using Dask, for a handy speed-up factor of more than two (there are only three inputs to parallelize over).",
"_____no_output_____"
]
],
[
[
"%run prep.py -d accounts",
"_____no_output_____"
],
[
"import pandas as pd\nimport os\nfilenames = [os.path.join('data', 'accounts.%d.csv' % i) for i in [0, 1, 2]]\nfilenames",
"_____no_output_____"
],
[
"%%time\n\n# normal, sequential code\na = pd.read_csv(filenames[0])\nb = pd.read_csv(filenames[1])\nc = pd.read_csv(filenames[2])\n\nna = len(a)\nnb = len(b)\nnc = len(c)\n\ntotal = sum([na, nb, nc])\nprint(total)",
"_____no_output_____"
]
],
[
[
"Your task is to recreate this graph again using the delayed function on the original Python code. The three functions you want to delay are `pd.read_csv`, `len` and `sum`.. ",
"_____no_output_____"
],
[
"```python\ndelayed_read_csv = delayed(pd.read_csv)\na = delayed_read_csv(filenames[0])\n...\n\ntotal = ...\n\n# execute\n%time total.compute() \n```",
"_____no_output_____"
]
],
[
[
"# your verbose code here",
"_____no_output_____"
]
],
[
[
"Next, repeat this using loops, rather than writing out all the variables.",
"_____no_output_____"
]
],
[
[
"# your concise code here",
"_____no_output_____"
],
[
"## verbose version\ndelayed_read_csv = delayed(pd.read_csv)\na = delayed_read_csv(filenames[0])\nb = delayed_read_csv(filenames[1])\nc = delayed_read_csv(filenames[2])\n\ndelayed_len = delayed(len)\nna = delayed_len(a)\nnb = delayed_len(b)\nnc = delayed_len(c)\n\ndelayed_sum = delayed(sum)\n\ntotal = delayed_sum([na, nb, nc])\n%time print(total.compute())\n\n\n## concise version\ncsvs = [delayed(pd.read_csv)(fn) for fn in filenames]\nlens = [delayed(len)(csv) for csv in csvs]\ntotal = delayed(sum)(lens)\n%time print(total.compute())\n",
"_____no_output_____"
]
],
[
[
"**Notes**\n\nDelayed objects support various operations:\n```python\n x2 = x + 1\n```",
"_____no_output_____"
],
[
"if `x` was a delayed result (like `total`, above), then so is `x2`. Supported operations include arithmetic operators, item or slice selection, attribute access and method calls - essentially anything that could be phrased as a `lambda` expression.\n\nOperations which are *not* supported include mutation, setter methods, iteration (for) and bool (predicate).",
"_____no_output_____"
],
[
"## Appendix: Further detail and examples",
"_____no_output_____"
],
[
"The following examples show that the kinds of things Dask does are not so far removed from normal Python programming when dealing with big data. These examples are **only meant for experts**, typical users can continue with the next notebook in the tutorial.",
"_____no_output_____"
],
[
"### Example 1: simple word count",
"_____no_output_____"
],
[
"This directory contains a file called `README.md`. How would you count the number of words in that file?\n\nThe simplest approach would be to load all the data into memory, split on whitespace and count the number of results. Here we use a regular expression to split words.",
"_____no_output_____"
]
],
[
[
"import re\nsplitter = re.compile('\\w+')\nwith open('README.md', 'r') as f:\n data = f.read()\nresult = len(splitter.findall(data))\nresult",
"_____no_output_____"
]
],
[
[
"The trouble with this approach is that it does not scale - if the file is very large, it, and the generated list of words, might fill up memory. We can easily avoid that, because we only need a simple sum, and each line is totally independent of the others. Now we evaluate each piece of data and immediately free up the space again, so we could perform this on arbitrarily-large files. Note that there is often a trade-off between time-efficiency and memory footprint: the following uses very little memory, but may be slower for files that do not fill a large faction of memory. In general, one would like chunks small enough not to stress memory, but big enough for efficient use of the CPU.",
"_____no_output_____"
]
],
[
[
"result = 0\nwith open('README.md', 'r') as f:\n for line in f:\n result += len(splitter.findall(line))\nresult",
"_____no_output_____"
]
],
[
[
"### Example 2: background execution",
"_____no_output_____"
],
[
"There are many tasks that take a while to complete, but don't actually require much of the CPU, for example anything that requires communication over a network, or input from a user. In typical sequential programming, execution would need to halt while the process completes, and then continue execution. That would be dreadful for a user experience (imagine the slow progress bar that locks up the application and cannot be canceled), and wasteful of time (the CPU could have been doing useful work in the meantime.\n\nFor example, we can launch processes and get their output as follows:\n```python\n import subprocess\n p = subprocess.Popen(command, stdout=subprocess.PIPE)\n p.returncode\n```",
"_____no_output_____"
],
[
"The task is run in a separate process, and the return-code will remain `None` until it completes, when it will change to `0`. To get the result back, we need `out = p.communicate()[0]` (which would block if the process was not complete).",
"_____no_output_____"
],
[
"Similarly, we can launch Python processes and threads in the background. Some methods allow mapping over multiple inputs and gathering the results, more on that later. The thread starts and the cell completes immediately, but the data associated with the download only appears in the queue object some time later.",
"_____no_output_____"
]
],
[
[
"# Edit sources.py to configure source locations\nimport sources\nsources.lazy_url",
"_____no_output_____"
],
[
"import threading\nimport queue\nimport urllib\n\ndef get_webdata(url, q):\n u = urllib.request.urlopen(url)\n # raise ValueError\n q.put(u.read())\n\nq = queue.Queue()\nt = threading.Thread(target=get_webdata, args=(sources.lazy_url, q))\nt.start()",
"_____no_output_____"
],
[
"# fetch result back into this thread. If the worker thread is not done, this would wait.\nq.get()",
"_____no_output_____"
]
],
[
[
"Consider: what would you see if there had been an exception within the `get_webdata` function? You could uncomment the `raise` line, above, and re-execute the two cells. What happens? Is there any way to debug the execution to find the root cause of the error?",
"_____no_output_____"
],
[
"### Example 3: delayed execution",
"_____no_output_____"
],
[
"There are many ways in Python to specify the computation you want to execute, but only run it *later*.",
"_____no_output_____"
]
],
[
[
"def add(x, y):\n return x + y\n\n# Sometimes we defer computations with strings\nx = 15\ny = 30\nz = \"add(x, y)\"\neval(z)",
"_____no_output_____"
],
[
"# we can use lambda or other \"closure\"\nx = 15\ny = 30\nz = lambda: add(x, y)\nz()",
"_____no_output_____"
],
[
"# A very similar thing happens in functools.partial\n\nimport functools\nz = functools.partial(add, x, y)\nz()",
"_____no_output_____"
],
[
"# Python generators are delayed execution by default\n# Many Python functions expect such iterable objects\n\ndef gen():\n res = x\n yield res\n res += y\n yield y\n\ng = gen()",
"_____no_output_____"
],
[
"# run once: we get one value and execution halts within the generator\n# run again and the execution completes\nnext(g)",
"_____no_output_____"
]
],
[
[
"### Dask graphs",
"_____no_output_____"
],
[
"Any Dask object, such as `total`, above, has an attribute which describes the calculations necessary to produce that result. Indeed, this is exactly the graph that we have been talking about, which can be visualized. We see that it is a simple dictionary, the keys are unique task identifiers, and the values are the functions and inputs for calculation.\n\n`delayed` is a handy mechanism for creating the Dask graph, but the adventerous may wish to play with the full fexibility afforded by building the graph dictionaries directly. Detailed information can be found [here](http://dask.pydata.org/en/latest/graphs.html).",
"_____no_output_____"
]
],
[
[
"total.dask",
"_____no_output_____"
],
[
"dict(total.dask)",
"_____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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cb08839c708be70d910cbd705a8e77b772a597a1 | 28,079 | ipynb | Jupyter Notebook | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge | cf25749a573c6a0093cbf25d0204d143baef7a6c | [
"ADSL"
] | null | null | null | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge | cf25749a573c6a0093cbf25d0204d143baef7a6c | [
"ADSL"
] | null | null | null | Mission_to_Mars/mission_to_mars.ipynb | ahowellgates/web-scraping-challenge | cf25749a573c6a0093cbf25d0204d143baef7a6c | [
"ADSL"
] | null | null | null | 46.642857 | 1,675 | 0.594003 | [
[
[
"# Setup",
"_____no_output_____"
]
],
[
[
"# Dependencies\nimport pandas as pd\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport requests",
"_____no_output_____"
]
],
[
[
"# Webscraping",
"_____no_output_____"
],
[
"## Nasa Mars News",
"_____no_output_____"
]
],
[
[
"# Setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)",
"\n\n====== WebDriver manager ======\nCurrent google-chrome version is 92.0.4515\nGet LATEST driver version for 92.0.4515\nGet LATEST driver version for 92.0.4515\nTrying to download new driver from https://chromedriver.storage.googleapis.com/92.0.4515.107/chromedriver_mac64.zip\nDriver has been saved in cache [/Users/ashleygates/.wdm/drivers/chromedriver/mac64/92.0.4515.107]\n"
],
[
"# URL of page to be scraped\nurl = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nsoup = BeautifulSoup(html, 'html.parser')",
"_____no_output_____"
],
[
"# Get a list of all news division and pick out the latest one\n\nresults = soup.find_all('div', class_='list_text')\nresult = results[0]\n\n\ntry:\n # Identify and return title and paragraph\n news_title = result.find('div', class_='content_title').a.text.strip()\n news_paragraph = result.find('div', class_='article_teaser_body').text.strip()\n \n # Print title and paragraph\n print(news_title)\n print(news_paragraph)\n\nexcept Exception as e: \n print(e)",
"Mars Perseverance Team Members to Be Recognized at Hispanic Heritage Awards\nThe three award recipients – Diana Trujillo, Christina Hernandez, and Clara O’Farrell – are engineers from the NASA rover team.\n"
],
[
"browser.quit()",
"_____no_output_____"
]
],
[
[
"## Mars Image",
"_____no_output_____"
]
],
[
[
"# Setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)",
"\n\n====== WebDriver manager ======\nCurrent google-chrome version is 92.0.4515\nGet LATEST driver version for 92.0.4515\nDriver [/Users/ashleygates/.wdm/drivers/chromedriver/mac64/92.0.4515.107/chromedriver] found in cache\n"
],
[
"# URL of page to be scraped\nurl = 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html'\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nsoup = BeautifulSoup(html, 'html.parser')",
"_____no_output_____"
],
[
"\nheader = soup.find('div', class_='header')",
"_____no_output_____"
],
[
"\nbrowser.links.find_by_partial_text('FULL IMAGE').click()\n\nhtml = browser.html\nsoup = BeautifulSoup(html, 'html.parser')\n\nimage_box = soup.find('div', class_='fancybox-inner')\nfeatured_image_url = url.replace('index.html', '') + image_box.img['src']\nfeatured_image_url",
"_____no_output_____"
],
[
"browser.quit()\n",
"_____no_output_____"
]
],
[
[
"## Mars Facts",
"_____no_output_____"
]
],
[
[
"\n# Setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)",
"\n\n====== WebDriver manager ======\nCurrent google-chrome version is 92.0.4515\nGet LATEST driver version for 92.0.4515\nDriver [/Users/ashleygates/.wdm/drivers/chromedriver/mac64/92.0.4515.107/chromedriver] found in cache\n"
],
[
"# URL of page to be scraped\nurl = 'https://space-facts.com/mars/'\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nsoup = BeautifulSoup(html, 'html.parser')\n",
"_____no_output_____"
],
[
"\ntables = pd.read_html(url)\ntable = tables[0]\ntable.columns = ['Key', 'Value']\ntable",
"_____no_output_____"
],
[
"\ntable.to_html()",
"_____no_output_____"
],
[
"browser.quit()\n",
"_____no_output_____"
]
],
[
[
"## Mars Hemispheres",
"_____no_output_____"
]
],
[
[
"\n# Setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)",
"\n\n====== WebDriver manager ======\nCurrent google-chrome version is 92.0.4515\nGet LATEST driver version for 92.0.4515\nDriver [/Users/ashleygates/.wdm/drivers/chromedriver/mac64/92.0.4515.107/chromedriver] found in cache\n"
],
[
"# URL of page to be scraped\nurl = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Create BeautifulSoup object; parse with 'html.parser'\nhtml = browser.html\nsoup = BeautifulSoup(html, 'html.parser')",
"_____no_output_____"
],
[
"images = soup.find_all('div', class_='description')\n\nimage_list = []\nfor image in images:\n image_dict = {}\n image_title = image.a.h3.text\n image_dict['title'] = image_title\n \n browser.links.find_by_partial_text(image_title).click()\n \n new_html = browser.html\n new_soup = BeautifulSoup(new_html, 'html.parser')\n \n download = new_soup.find('div', class_='downloads')\n original = download.find_all('li')[1].a['href']\n image_dict['img_url'] = original\n image_list.append(image_dict)\n \n browser.back()\n\nimage_list",
"_____no_output_____"
],
[
"browser.quit()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb08856351e61c2702f48960d82731d02c45a047 | 95,611 | ipynb | Jupyter Notebook | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree | 17bdd2df40fff71c44ac3a88f4243d95f24fb34d | [
"MIT"
] | 1 | 2020-06-29T00:38:28.000Z | 2020-06-29T00:38:28.000Z | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree | 17bdd2df40fff71c44ac3a88f4243d95f24fb34d | [
"MIT"
] | null | null | null | 3. SLAM/3. Landmark Detection and Tracking.ipynb | MohamedAskar/Computer-Vision-Nanodegree | 17bdd2df40fff71c44ac3a88f4243d95f24fb34d | [
"MIT"
] | null | null | null | 110.27797 | 31,060 | 0.808819 | [
[
[
"# Project 3: Implement SLAM \n\n---\n\n## Project Overview\n\nIn this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world!\n\nSLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research in the fields of robotics and autonomous systems. Since this localization and map-building relies on the visual sensing of landmarks, this is a computer vision problem. \n\nUsing what you've learned about robot motion, representations of uncertainty in motion and sensing, and localization techniques, you will be tasked with defining a function, `slam`, which takes in six parameters as input and returns the vector `mu`. \n> `mu` contains the (x,y) coordinate locations of the robot as it moves, and the positions of landmarks that it senses in the world\n\nYou can implement helper functions as you see fit, but your function must return `mu`. The vector, `mu`, should have (x, y) coordinates interlaced, for example, if there were 2 poses and 2 landmarks, `mu` will look like the following, where `P` is the robot position and `L` the landmark position:\n```\nmu = matrix([[Px0],\n [Py0],\n [Px1],\n [Py1],\n [Lx0],\n [Ly0],\n [Lx1],\n [Ly1]])\n```\n\nYou can see that `mu` holds the poses first `(x0, y0), (x1, y1), ...,` then the landmark locations at the end of the matrix; we consider a `nx1` matrix to be a vector.\n\n## Generating an environment\n\nIn a real SLAM problem, you may be given a map that contains information about landmark locations, and in this example, we will make our own data using the `make_data` function, which generates a world grid with landmarks in it and then generates data by placing a robot in that world and moving and sensing over some numer of time steps. The `make_data` function relies on a correct implementation of robot move/sense functions, which, at this point, should be complete and in the `robot_class.py` file. The data is collected as an instantiated robot moves and senses in a world. Your SLAM function will take in this data as input. So, let's first create this data and explore how it represents the movement and sensor measurements that our robot takes.\n\n---",
"_____no_output_____"
],
[
"## Create the world\n\nUse the code below to generate a world of a specified size with randomly generated landmark locations. You can change these parameters and see how your implementation of SLAM responds! \n\n`data` holds the sensors measurements and motion of your robot over time. It stores the measurements as `data[i][0]` and the motion as `data[i][1]`.\n\n#### Helper functions\n\nYou will be working with the `robot` class that may look familiar from the first notebook, \n\nIn fact, in the `helpers.py` file, you can read the details of how data is made with the `make_data` function. It should look very similar to the robot move/sense cycle you've seen in the first notebook.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom helpers import make_data\n\n# your implementation of slam should work with the following inputs\n# feel free to change these input values and see how it responds!\n\n# world parameters\nnum_landmarks = 5 # number of landmarks\nN = 20 # time steps\nworld_size = 100.0 # size of world (square)\n\n# robot parameters\nmeasurement_range = 50.0 # range at which we can sense landmarks\nmotion_noise = 2.0 # noise in robot motion\nmeasurement_noise = 2.0 # noise in the measurements\ndistance = 20.0 # distance by which robot (intends to) move each iteratation \n\n\n# make_data instantiates a robot, AND generates random landmarks for a given world size and number of landmarks\ndata = make_data(N, num_landmarks, world_size, measurement_range, motion_noise, measurement_noise, distance)",
" \nLandmarks: [[34, 47], [75, 78], [61, 26], [22, 23], [18, 28]]\nRobot: [x=4.99479 y=14.12768]\n"
]
],
[
[
"### A note on `make_data`\n\nThe function above, `make_data`, takes in so many world and robot motion/sensor parameters because it is responsible for:\n1. Instantiating a robot (using the robot class)\n2. Creating a grid world with landmarks in it\n\n**This function also prints out the true location of landmarks and the *final* robot location, which you should refer back to when you test your implementation of SLAM.**\n\nThe `data` this returns is an array that holds information about **robot sensor measurements** and **robot motion** `(dx, dy)` that is collected over a number of time steps, `N`. You will have to use *only* these readings about motion and measurements to track a robot over time and find the determine the location of the landmarks using SLAM. We only print out the true landmark locations for comparison, later.\n\n\nIn `data` the measurement and motion data can be accessed from the first and second index in the columns of the data array. See the following code for an example, where `i` is the time step:\n```\nmeasurement = data[i][0]\nmotion = data[i][1]\n```\n",
"_____no_output_____"
]
],
[
[
"# print out some stats about the data\ntime_step = 0\n\nprint('Example measurements: \\n', data[time_step][0])\nprint('\\n')\nprint('Example motion: \\n', data[time_step][1])",
"Example measurements: \n [(0, -15.805152385054228, -1.6297997068679546), (1, 24.73944299319771, 27.886589594025597), (2, 11.24343039872742, -23.753067256378262), (3, -29.045748066570592, -26.05459794794534), (4, -33.78771405750095, -23.207245892649965)]\n\n\nExample motion: \n [-19.96316170483412, -1.213332084239246]\n"
]
],
[
[
"Try changing the value of `time_step`, you should see that the list of measurements varies based on what in the world the robot sees after it moves. As you know from the first notebook, the robot can only sense so far and with a certain amount of accuracy in the measure of distance between its location and the location of landmarks. The motion of the robot always is a vector with two values: one for x and one for y displacement. This structure will be useful to keep in mind as you traverse this data in your implementation of slam.",
"_____no_output_____"
],
[
"## Initialize Constraints\n\nOne of the most challenging tasks here will be to create and modify the constraint matrix and vector: omega and xi. In the second notebook, you saw an example of how omega and xi could hold all the values the define the relationships between robot poses `xi` and landmark positions `Li` in a 1D world, as seen below, where omega is the blue matrix and xi is the pink vector.\n\n<img src='images/motion_constraint.png' width=50% height=50% />\n\n\nIn *this* project, you are tasked with implementing constraints for a 2D world. We are referring to robot poses as `Px, Py` and landmark positions as `Lx, Ly`, and one way to approach this challenge is to add *both* x and y locations in the constraint matrices.\n\n<img src='images/constraints2D.png' width=50% height=50% />\n\nYou may also choose to create two of each omega and xi (one for x and one for y positions).",
"_____no_output_____"
],
[
"### TODO: Write a function that initializes omega and xi\n\nComplete the function `initialize_constraints` so that it returns `omega` and `xi` constraints for the starting position of the robot. Any values that we do not yet know should be initialized with the value `0`. You may assume that our robot starts out in exactly the middle of the world with 100% confidence (no motion or measurement noise at this point). The inputs `N` time steps, `num_landmarks`, and `world_size` should give you all the information you need to construct intial constraints of the correct size and starting values.\n\n*Depending on your approach you may choose to return one omega and one xi that hold all (x,y) positions *or* two of each (one for x values and one for y); choose whichever makes most sense to you!*",
"_____no_output_____"
]
],
[
[
"def initialize_constraints(N, num_landmarks, world_size):\n ''' This function takes in a number of time steps N, number of landmarks, and a world_size,\n and returns initialized constraint matrices, omega and xi.'''\n \n ## Recommended: Define and store the size (rows/cols) of the constraint matrix in a variable\n num_poses = N\n rows = (num_poses * 2) + (num_landmarks * 2)\n cols = (num_poses * 2) + (num_landmarks * 2)\n initial_x = world_size/2\n initial_y = world_size/2\n Px_initial = 0\n Py_initial = 1\n \n ## TODO: Define the constraint matrix, Omega, with two initial \"strength\" values\n ## for the initial x, y location of our robot\n # omega = [0]\n omega = np.zeros(shape=(rows,cols))\n omega[Px_initial][Px_initial] = 1 \n omega[Py_initial][Py_initial] = 1 \n \n ## TODO: Define the constraint *vector*, xi\n ## you can assume that the robot starts out in the middle of the world with 100% confidence\n # xi = [0]\n xi = np.zeros(shape=(cols,1))\n xi[Px_initial] = initial_x \n xi[Py_initial] = initial_y \n \n return omega, xi\n ",
"_____no_output_____"
]
],
[
[
"### Test as you go\n\nIt's good practice to test out your code, as you go. Since `slam` relies on creating and updating constraint matrices, `omega` and `xi` to account for robot sensor measurements and motion, let's check that they initialize as expected for any given parameters.\n\nBelow, you'll find some test code that allows you to visualize the results of your function `initialize_constraints`. We are using the [seaborn](https://seaborn.pydata.org/) library for visualization.\n\n**Please change the test values of N, landmarks, and world_size and see the results**. Be careful not to use these values as input into your final smal function.\n\nThis code assumes that you have created one of each constraint: `omega` and `xi`, but you can change and add to this code, accordingly. The constraints should vary in size with the number of time steps and landmarks as these values affect the number of poses a robot will take `(Px0,Py0,...Pxn,Pyn)` and landmark locations `(Lx0,Ly0,...Lxn,Lyn)` whose relationships should be tracked in the constraint matrices. Recall that `omega` holds the weights of each variable and `xi` holds the value of the sum of these variables, as seen in Notebook 2. You'll need the `world_size` to determine the starting pose of the robot in the world and fill in the initial values for `xi`.",
"_____no_output_____"
]
],
[
[
"# import data viz resources\nimport matplotlib.pyplot as plt\nfrom pandas import DataFrame\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"# define a small N and world_size (small for ease of visualization)\nN_test = 5\nnum_landmarks_test = 2\nsmall_world = 10\n\n# initialize the constraints\ninitial_omega, initial_xi = initialize_constraints(N_test, num_landmarks_test, small_world)",
"_____no_output_____"
],
[
"# define figure size\nplt.rcParams[\"figure.figsize\"] = (10,7)\n\n# display omega\nsns.heatmap(DataFrame(initial_omega), cmap='Blues', annot=True, linewidths=.5)",
"_____no_output_____"
],
[
"# define figure size\nplt.rcParams[\"figure.figsize\"] = (1,7)\n\n# display xi\nsns.heatmap(DataFrame(initial_xi), cmap='Oranges', annot=True, linewidths=.5)",
"_____no_output_____"
]
],
[
[
"---\n## SLAM inputs \n\nIn addition to `data`, your slam function will also take in:\n* N - The number of time steps that a robot will be moving and sensing\n* num_landmarks - The number of landmarks in the world\n* world_size - The size (w/h) of your world\n* motion_noise - The noise associated with motion; the update confidence for motion should be `1.0/motion_noise`\n* measurement_noise - The noise associated with measurement/sensing; the update weight for measurement should be `1.0/measurement_noise`\n\n#### A note on noise\n\nRecall that `omega` holds the relative \"strengths\" or weights for each position variable, and you can update these weights by accessing the correct index in omega `omega[row][col]` and *adding/subtracting* `1.0/noise` where `noise` is measurement or motion noise. `Xi` holds actual position values, and so to update `xi` you'll do a similar addition process only using the actual value of a motion or measurement. So for a vector index `xi[row][0]` you will end up adding/subtracting one measurement or motion divided by their respective `noise`.\n\n### TODO: Implement Graph SLAM\n\nFollow the TODO's below to help you complete this slam implementation (these TODO's are in the recommended order), then test out your implementation! \n\n#### Updating with motion and measurements\n\nWith a 2D omega and xi structure as shown above (in earlier cells), you'll have to be mindful about how you update the values in these constraint matrices to account for motion and measurement constraints in the x and y directions. Recall that the solution to these matrices (which holds all values for robot poses `P` and landmark locations `L`) is the vector, `mu`, which can be computed at the end of the construction of omega and xi as the inverse of omega times xi: $\\mu = \\Omega^{-1}\\xi$\n\n**You may also choose to return the values of `omega` and `xi` if you want to visualize their final state!**",
"_____no_output_____"
]
],
[
[
"## TODO: Complete the code to implement SLAM\n\n## slam takes in 6 arguments and returns mu, \n## mu is the entire path traversed by a robot (all x,y poses) *and* all landmarks locations\ndef slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise):\n \n omega, xi = initialize_constraints(N, num_landmarks, world_size)\n\n # Iterate through each time step in the data \n for time_step in range(N-1):\n \n # Retrieve all the motion and measurement data for this time_step\n measurement = data[time_step][0]\n motion = data[time_step][1]\n \n dx = motion[0] # distance to be moved along x in this time_step\n dy = motion[1] # distance to be moved along y in this time_step\n\n '''Consider that the robot moves from (x0,y0) to (x1,y1) in this time_step'''\n \n # even-numbered columns of omega correspond to x values\n x0 = (time_step * 2) # x0 = 0,2,4,...\n x1 = x0 + 2 # x0 = 2,4,6,...\n \n # odd-numbered columns of omega correspond to y values\n y0 = x0 + 1 # y0 = 1,3,5,...\n y1 = y0 + 2 # y1 = 3,5,7,...\n \n # Update omega and xi to account for all measurements \n # Measurement noise taken into account\n for landmark in measurement:\n \n lm = landmark[0] # landmark id\n dx_lm = landmark[1] # separation along x from current position\n dy_lm = landmark[2] # separation along y from current position\n \n Lx0 = (N * 2) + (lm * 2) # even-numbered columns have x values of landmarks\n Ly0 = Lx0 + 1 # odd-numbered columns have y values of landmarks\n \n # update omega values corresponding to measurement between x0 and Lx0\n omega[ x0 ][ x0 ] += 1.0/measurement_noise\n omega[ Lx0 ][ Lx0 ] += 1.0/measurement_noise\n omega[ x0 ][ Lx0 ] += -1.0/measurement_noise\n omega[ Lx0 ][ x0 ] += -1.0/measurement_noise\n \n # update omega values corresponding to measurement between y0 and Ly0\n omega[ y0 ][ y0 ] += 1.0/measurement_noise\n omega[ Ly0 ][ Ly0 ] += 1.0/measurement_noise\n omega[ y0 ][ Ly0 ] += -1.0/measurement_noise\n omega[ Ly0 ][ y0 ] += -1.0/measurement_noise\n \n # update xi values corresponding to measurement between x0 and Lx0\n xi[x0] -= dx_lm/measurement_noise\n xi[Lx0] += dx_lm/measurement_noise\n \n # update xi values corresponding to measurement between y0 and Ly0\n xi[y0] -= dy_lm/measurement_noise\n xi[Ly0] += dy_lm/measurement_noise\n \n # Update omega and xi to account for motion from (x0,y0) to (x1,y1)\n # Motion noise taken into account\n omega[x0][x0] += 1.0/motion_noise\n omega[x1][x1] += 1.0/motion_noise\n omega[x0][x1] += -1.0/motion_noise\n omega[x1][x0] += -1.0/motion_noise\n \n omega[y0][y0] += 1.0/motion_noise\n omega[y1][y1] += 1.0/motion_noise\n omega[y0][y1] += -1.0/motion_noise\n omega[y1][y0] += -1.0/motion_noise\n \n xi[x0] -= dx/motion_noise\n xi[y0] -= dy/motion_noise\n \n xi[x1] += dx/motion_noise\n xi[y1] += dy/motion_noise\n \n # Compute the best estimate of poses and landmark positions\n # using the formula, omega_inverse * xi\n omega_inv = np.linalg.inv(np.matrix(omega))\n mu = omega_inv*xi\n \n return mu # return `mu`\n",
"_____no_output_____"
]
],
[
[
"## Helper functions\n\nTo check that your implementation of SLAM works for various inputs, we have provided two helper functions that will help display the estimated pose and landmark locations that your function has produced. First, given a result `mu` and number of time steps, `N`, we define a function that extracts the poses and landmarks locations and returns those as their own, separate lists. \n\nThen, we define a function that nicely print out these lists; both of these we will call, in the next step.\n",
"_____no_output_____"
]
],
[
[
"# a helper function that creates a list of poses and of landmarks for ease of printing\n# this only works for the suggested constraint architecture of interlaced x,y poses\ndef get_poses_landmarks(mu, N):\n # create a list of poses\n poses = []\n for i in range(N):\n poses.append((mu[2*i].item(), mu[2*i+1].item()))\n\n # create a list of landmarks\n landmarks = []\n for i in range(num_landmarks):\n landmarks.append((mu[2*(N+i)].item(), mu[2*(N+i)+1].item()))\n\n # return completed lists\n return poses, landmarks\n",
"_____no_output_____"
],
[
"def print_all(poses, landmarks):\n print('\\n')\n print('Estimated Poses:')\n for i in range(len(poses)):\n print('['+', '.join('%.3f'%p for p in poses[i])+']')\n print('\\n')\n print('Estimated Landmarks:')\n for i in range(len(landmarks)):\n print('['+', '.join('%.3f'%l for l in landmarks[i])+']')\n",
"_____no_output_____"
]
],
[
[
"## Run SLAM\n\nOnce you've completed your implementation of `slam`, see what `mu` it returns for different world sizes and different landmarks!\n\n### What to Expect\n\nThe `data` that is generated is random, but you did specify the number, `N`, or time steps that the robot was expected to move and the `num_landmarks` in the world (which your implementation of `slam` should see and estimate a position for. Your robot should also start with an estimated pose in the very center of your square world, whose size is defined by `world_size`.\n\nWith these values in mind, you should expect to see a result that displays two lists:\n1. **Estimated poses**, a list of (x, y) pairs that is exactly `N` in length since this is how many motions your robot has taken. The very first pose should be the center of your world, i.e. `[50.000, 50.000]` for a world that is 100.0 in square size.\n2. **Estimated landmarks**, a list of landmark positions (x, y) that is exactly `num_landmarks` in length. \n\n#### Landmark Locations\n\nIf you refer back to the printout of *exact* landmark locations when this data was created, you should see values that are very similar to those coordinates, but not quite (since `slam` must account for noise in motion and measurement).",
"_____no_output_____"
]
],
[
[
"# call your implementation of slam, passing in the necessary parameters\nmu = slam(data, N, num_landmarks, world_size, motion_noise, measurement_noise)\n\n# print out the resulting landmarks and poses\nif(mu is not None):\n # get the lists of poses and landmarks\n # and print them out\n poses, landmarks = get_poses_landmarks(mu, N)\n print_all(poses, landmarks)",
"\n\nEstimated Poses:\n[50.000, 50.000]\n[28.772, 50.255]\n[9.040, 48.680]\n[19.858, 30.140]\n[32.972, 12.416]\n[54.058, 17.762]\n[73.279, 23.062]\n[92.841, 26.185]\n[74.158, 29.875]\n[53.182, 33.724]\n[33.776, 36.440]\n[13.402, 41.439]\n[1.908, 58.052]\n[17.273, 45.079]\n[33.424, 32.976]\n[49.007, 21.488]\n[64.699, 8.518]\n[45.340, 9.972]\n[25.943, 11.801]\n[5.954, 12.454]\n\n\nEstimated Landmarks:\n[33.243, 47.304]\n[75.178, 77.209]\n[60.757, 26.507]\n[21.906, 22.860]\n[17.526, 27.894]\n"
]
],
[
[
"## Visualize the constructed world\n\nFinally, using the `display_world` code from the `helpers.py` file (which was also used in the first notebook), we can actually visualize what you have coded with `slam`: the final position of the robot and the positon of landmarks, created from only motion and measurement data!\n\n**Note that these should be very similar to the printed *true* landmark locations and final pose from our call to `make_data` early in this notebook.**",
"_____no_output_____"
]
],
[
[
"# import the helper function\nfrom helpers import display_world\n\n# Display the final world!\n\n# define figure size\nplt.rcParams[\"figure.figsize\"] = (20,20)\n\n# check if poses has been created\nif 'poses' in locals():\n # print out the last pose\n print('Last pose: ', poses[-1])\n # display the last position of the robot *and* the landmark positions\n display_world(int(world_size), poses[-1], landmarks)",
"Last pose: (5.954003287856551, 12.454091677416208)\n"
]
],
[
[
"### Question: How far away is your final pose (as estimated by `slam`) compared to the *true* final pose? Why do you think these poses are different?\n\nYou can find the true value of the final pose in one of the first cells where `make_data` was called. You may also want to look at the true landmark locations and compare them to those that were estimated by `slam`. Ask yourself: what do you think would happen if we moved and sensed more (increased N)? Or if we had lower/higher noise parameters.",
"_____no_output_____"
],
[
"**Answer**: (Write your answer here.)",
"_____no_output_____"
],
[
"## Testing\n\nTo confirm that your slam code works before submitting your project, it is suggested that you run it on some test data and cases. A few such cases have been provided for you, in the cells below. When you are ready, uncomment the test cases in the next cells (there are two test cases, total); your output should be **close-to or exactly** identical to the given results. If there are minor discrepancies it could be a matter of floating point accuracy or in the calculation of the inverse matrix.\n\n### Submit your project\n\nIf you pass these tests, it is a good indication that your project will pass all the specifications in the project rubric. Follow the submission instructions to officially submit!",
"_____no_output_____"
]
],
[
[
"# Here is the data and estimated outputs for test case 1\n\ntest_data1 = [[[[1, 19.457599255548065, 23.8387362100849], [2, -13.195807561967236, 11.708840328458608], [3, -30.0954905279171, 15.387879242505843]], [-12.2607279422326, -15.801093326936487]], [[[2, -0.4659930049620491, 28.088559771215664], [4, -17.866382374890936, -16.384904503932]], [-12.2607279422326, -15.801093326936487]], [[[4, -6.202512900833806, -1.823403210274639]], [-12.2607279422326, -15.801093326936487]], [[[4, 7.412136480918645, 15.388585962142429]], [14.008259661173426, 14.274756084260822]], [[[4, -7.526138813444998, -0.4563942429717849]], [14.008259661173426, 14.274756084260822]], [[[2, -6.299793150150058, 29.047830407717623], [4, -21.93551130411791, -13.21956810989039]], [14.008259661173426, 14.274756084260822]], [[[1, 15.796300959032276, 30.65769689694247], [2, -18.64370821983482, 17.380022987031367]], [14.008259661173426, 14.274756084260822]], [[[1, 0.40311325410337906, 14.169429532679855], [2, -35.069349468466235, 2.4945558982439957]], [14.008259661173426, 14.274756084260822]], [[[1, -16.71340983241936, -2.777000269543834]], [-11.006096015782283, 16.699276945166858]], [[[1, -3.611096830835776, -17.954019226763958]], [-19.693482634035977, 3.488085684573048]], [[[1, 18.398273354362416, -22.705102332550947]], [-19.693482634035977, 3.488085684573048]], [[[2, 2.789312482883833, -39.73720193121324]], [12.849049222879723, -15.326510824972983]], [[[1, 21.26897046581808, -10.121029799040915], [2, -11.917698965880655, -23.17711662602097], [3, -31.81167947898398, -16.7985673023331]], [12.849049222879723, -15.326510824972983]], [[[1, 10.48157743234859, 5.692957082575485], [2, -22.31488473554935, -5.389184118551409], [3, -40.81803984305378, -2.4703329790238118]], [12.849049222879723, -15.326510824972983]], [[[0, 10.591050242096598, -39.2051798967113], [1, -3.5675572049297553, 22.849456408289125], [2, -38.39251065320351, 7.288990306029511]], [12.849049222879723, -15.326510824972983]], [[[0, -3.6225556479370766, -25.58006865235512]], [-7.8874682868419965, -18.379005523261092]], [[[0, 1.9784503557879374, -6.5025974151499]], [-7.8874682868419965, -18.379005523261092]], [[[0, 10.050665232782423, 11.026385307998742]], [-17.82919359778298, 9.062000642947142]], [[[0, 26.526838150174818, -0.22563393232425621], [4, -33.70303936886652, 2.880339841013677]], [-17.82919359778298, 9.062000642947142]]]\n\n## Test Case 1\n##\n# Estimated Pose(s):\n# [50.000, 50.000]\n# [37.858, 33.921]\n# [25.905, 18.268]\n# [13.524, 2.224]\n# [27.912, 16.886]\n# [42.250, 30.994]\n# [55.992, 44.886]\n# [70.749, 59.867]\n# [85.371, 75.230]\n# [73.831, 92.354]\n# [53.406, 96.465]\n# [34.370, 100.134]\n# [48.346, 83.952]\n# [60.494, 68.338]\n# [73.648, 53.082]\n# [86.733, 38.197]\n# [79.983, 20.324]\n# [72.515, 2.837]\n# [54.993, 13.221]\n# [37.164, 22.283]\n\n\n# Estimated Landmarks:\n# [82.679, 13.435]\n# [70.417, 74.203]\n# [36.688, 61.431]\n# [18.705, 66.136]\n# [20.437, 16.983]\n\n\n### Uncomment the following three lines for test case 1 and compare the output to the values above ###\n\nmu_1 = slam(test_data1, 20, 5, 100.0, 2.0, 2.0)\nposes, landmarks = get_poses_landmarks(mu_1, 20)\nprint_all(poses, landmarks)",
"\n\nEstimated Poses:\n[50.000, 50.000]\n[37.973, 33.652]\n[26.185, 18.155]\n[13.745, 2.116]\n[28.097, 16.783]\n[42.384, 30.902]\n[55.831, 44.497]\n[70.857, 59.699]\n[85.697, 75.543]\n[74.011, 92.434]\n[53.544, 96.454]\n[34.525, 100.080]\n[48.623, 83.953]\n[60.197, 68.107]\n[73.778, 52.935]\n[87.132, 38.538]\n[80.303, 20.508]\n[72.798, 2.945]\n[55.245, 13.255]\n[37.416, 22.317]\n\n\nEstimated Landmarks:\n[82.956, 13.539]\n[70.495, 74.141]\n[36.740, 61.281]\n[18.698, 66.060]\n[20.635, 16.875]\n"
],
[
"# Here is the data and estimated outputs for test case 2\n\ntest_data2 = [[[[0, 26.543274387283322, -6.262538160312672], [3, 9.937396825799755, -9.128540360867689]], [18.92765331253674, -6.460955043986683]], [[[0, 7.706544739722961, -3.758467215445748], [1, 17.03954411948937, 31.705489938553438], [3, -11.61731288777497, -6.64964096716416]], [18.92765331253674, -6.460955043986683]], [[[0, -12.35130507136378, 2.585119104239249], [1, -2.563534536165313, 38.22159657838369], [3, -26.961236804740935, -0.4802312626141525]], [-11.167066095509824, 16.592065417497455]], [[[0, 1.4138633151721272, -13.912454837810632], [1, 8.087721200818589, 20.51845934354381], [3, -17.091723454402302, -16.521500551709707], [4, -7.414211721400232, 38.09191602674439]], [-11.167066095509824, 16.592065417497455]], [[[0, 12.886743222179561, -28.703968411636318], [1, 21.660953298391387, 3.4912891084614914], [3, -6.401401414569506, -32.321583037341625], [4, 5.034079343639034, 23.102207946092893]], [-11.167066095509824, 16.592065417497455]], [[[1, 31.126317672358578, -10.036784369535214], [2, -38.70878528420893, 7.4987265861424595], [4, 17.977218575473767, 6.150889254289742]], [-6.595520680493778, -18.88118393939265]], [[[1, 41.82460922922086, 7.847527392202475], [3, 15.711709540417502, -30.34633659912818]], [-6.595520680493778, -18.88118393939265]], [[[0, 40.18454208294434, -6.710999804403755], [3, 23.019508919299156, -10.12110867290604]], [-6.595520680493778, -18.88118393939265]], [[[3, 27.18579315312821, 8.067219022708391]], [-6.595520680493778, -18.88118393939265]], [[], [11.492663265706092, 16.36822198838621]], [[[3, 24.57154567653098, 13.461499960708197]], [11.492663265706092, 16.36822198838621]], [[[0, 31.61945290413707, 0.4272295085799329], [3, 16.97392299158991, -5.274596836133088]], [11.492663265706092, 16.36822198838621]], [[[0, 22.407381798735177, -18.03500068379259], [1, 29.642444125196995, 17.3794951934614], [3, 4.7969752441371645, -21.07505361639969], [4, 14.726069092569372, 32.75999422300078]], [11.492663265706092, 16.36822198838621]], [[[0, 10.705527984670137, -34.589764174299596], [1, 18.58772336795603, -0.20109708164787765], [3, -4.839806195049413, -39.92208742305105], [4, 4.18824810165454, 14.146847823548889]], [11.492663265706092, 16.36822198838621]], [[[1, 5.878492140223764, -19.955352450942357], [4, -7.059505455306587, -0.9740849280550585]], [19.628527845173146, 3.83678180657467]], [[[1, -11.150789592446378, -22.736641053247872], [4, -28.832815721158255, -3.9462962046291388]], [-19.841703647091965, 2.5113335861604362]], [[[1, 8.64427397916182, -20.286336970889053], [4, -5.036917727942285, -6.311739993868336]], [-5.946642674882207, -19.09548221169787]], [[[0, 7.151866679283043, -39.56103232616369], [1, 16.01535401373368, -3.780995345194027], [4, -3.04801331832137, 13.697362774960865]], [-5.946642674882207, -19.09548221169787]], [[[0, 12.872879480504395, -19.707592098123207], [1, 22.236710716903136, 16.331770792606406], [3, -4.841206109583004, -21.24604435851242], [4, 4.27111163223552, 32.25309748614184]], [-5.946642674882207, -19.09548221169787]]] \n\n\n## Test Case 2\n##\n# Estimated Pose(s):\n# [50.000, 50.000]\n# [69.035, 45.061]\n# [87.655, 38.971]\n# [76.084, 55.541]\n# [64.283, 71.684]\n# [52.396, 87.887]\n# [44.674, 68.948]\n# [37.532, 49.680]\n# [31.392, 30.893]\n# [24.796, 12.012]\n# [33.641, 26.440]\n# [43.858, 43.560]\n# [54.735, 60.659]\n# [65.884, 77.791]\n# [77.413, 94.554]\n# [96.740, 98.020]\n# [76.149, 99.586]\n# [70.211, 80.580]\n# [64.130, 61.270]\n# [58.183, 42.175]\n\n\n# Estimated Landmarks:\n# [76.777, 42.415]\n# [85.109, 76.850]\n# [13.687, 95.386]\n# [59.488, 39.149]\n# [69.283, 93.654]\n\n\n### Uncomment the following three lines for test case 2 and compare to the values above ###\n\nmu_2 = slam(test_data2, 20, 5, 100.0, 2.0, 2.0)\nposes, landmarks = get_poses_landmarks(mu_2, 20)\nprint_all(poses, landmarks)\n",
"\n\nEstimated Poses:\n[50.000, 50.000]\n[69.181, 45.665]\n[87.743, 39.703]\n[76.270, 56.311]\n[64.317, 72.176]\n[52.257, 88.154]\n[44.059, 69.401]\n[37.002, 49.918]\n[30.924, 30.955]\n[23.508, 11.419]\n[34.180, 27.133]\n[44.155, 43.846]\n[54.806, 60.920]\n[65.698, 78.546]\n[77.468, 95.626]\n[96.802, 98.821]\n[75.957, 99.971]\n[70.200, 81.181]\n[64.054, 61.723]\n[58.107, 42.628]\n\n\nEstimated Landmarks:\n[76.779, 42.887]\n[85.065, 77.438]\n[13.548, 95.652]\n[59.449, 39.595]\n[69.263, 94.240]\n"
]
]
] | [
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cb08916fe72a2fc4593d0fd026866618b646dd55 | 122,366 | ipynb | Jupyter Notebook | Assignments/DSCI_633_Assn_3.ipynb | niranjana1997/RIT-DSCI-633-FDS | 1e9a70a9fbfae1b87c8e0e9665160eeec44a8403 | [
"MIT"
] | null | null | null | Assignments/DSCI_633_Assn_3.ipynb | niranjana1997/RIT-DSCI-633-FDS | 1e9a70a9fbfae1b87c8e0e9665160eeec44a8403 | [
"MIT"
] | null | null | null | Assignments/DSCI_633_Assn_3.ipynb | niranjana1997/RIT-DSCI-633-FDS | 1e9a70a9fbfae1b87c8e0e9665160eeec44a8403 | [
"MIT"
] | null | null | null | 84.448585 | 55,134 | 0.708073 | [
[
[
"<a href=\"https://colab.research.google.com/github/niranjana1997/RIT-DSCI-633-FDS/blob/main/Assignments/DSCI_633_Assn_3.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"# Python ≥3.5 is required\nimport sys\n\n# Scikit-Learn ≥0.20 is required\nimport sklearn\n\n# Common imports\nimport numpy as np\nimport os\n\n# To plot pretty figures\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)",
"_____no_output_____"
],
[
"\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)",
"_____no_output_____"
],
[
"\nimport pandas as pd\n\ndef load_data(titanic_path):\n csv_path = os.path.join(titanic_path)\n return pd.read_csv(csv_path)",
"_____no_output_____"
],
[
"titanic_data = load_data(\"/content/train.csv\")\ntitanic_data.head() ",
"_____no_output_____"
],
[
"titanic_data.describe()",
"_____no_output_____"
],
[
"# Execrise: print the count of different values for \"ocean proximity\"",
"_____no_output_____"
],
[
"titanic_data.hist(bins=50, figsize=(20,15))\nsave_fig(\"attribute_histogram_plots\")\nplt.show()",
"Saving figure attribute_histogram_plots\n"
],
[
"titanic_1 = load_data(\"/content/train.csv\")\ntitanic_1.head(10)",
"_____no_output_____"
],
[
"titanic_2 = load_data(\"/content/test.csv\")\ntitanic_2.head(10)",
"_____no_output_____"
],
[
"df = pd.concat([titanic_1,titanic_2])",
"_____no_output_____"
],
[
"df = df[['PassengerId','Age','Pclass','Sex','Embarked','Survived']].copy()",
"_____no_output_____"
],
[
"df = df.dropna()",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder\n\n\n\nencoder = LabelEncoder()\ndf['Sex'] = encoder.fit_transform(df['Sex'])\ndf['Embarked'] = encoder.fit_transform(df['Sex'])\ndf = df.astype(int)\n",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:7: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n import sys\n"
],
[
"df.isnull().sum()",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"import seaborn as sns\n\nplot = sns.FacetGrid(df, 'Pclass', 'Sex')\nplot.map(plt.hist, 'Age', alpha=0.5, bins=10)\nplot.add_legend()",
"/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: row, col. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n"
],
[
"# Using train_test_split()\ndef split_train_test(data, test_ratio):\n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]",
"_____no_output_____"
],
[
"# delete\ntrain_set, test_set = split_train_test(df, 0.2)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\n\ntrain_set, test_set = train_test_split(df, test_size=0.2, random_state=42)",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"len(train_set)",
"_____no_output_____"
],
[
"len(test_set)",
"_____no_output_____"
],
[
"X_train = train_set.drop('Survived', axis=1)\nY_train = train_set['Survived']\nX_test = test_set.drop('PassengerId', axis=1).copy()\nX_train.shape, Y_train.shape, X_test.shape",
"_____no_output_____"
],
[
"log_reg = LogisticRegression()\nlog_reg.fit(X_train, Y_train)\nY_pred = log_reg.predict(X_test)\nscore = log_reg.score(X_train, Y_train)",
"_____no_output_____"
],
[
"score",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"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"
]
] |
cb0898284de97c6fc4ed64eecbab991d9e1110bb | 6,060 | ipynb | Jupyter Notebook | Lemmatization.ipynb | Yashdew/Natural-Language-Processing | ddf09391ccec27feb13d2f1fdffa39370f976faa | [
"MIT"
] | null | null | null | Lemmatization.ipynb | Yashdew/Natural-Language-Processing | ddf09391ccec27feb13d2f1fdffa39370f976faa | [
"MIT"
] | null | null | null | Lemmatization.ipynb | Yashdew/Natural-Language-Processing | ddf09391ccec27feb13d2f1fdffa39370f976faa | [
"MIT"
] | null | null | null | 40.671141 | 134 | 0.575248 | [
[
[
"import nltk",
"_____no_output_____"
],
[
"from nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords",
"_____no_output_____"
],
[
"paragraph = \"\"\"I have three visions for India. In 3000 years of our history, people from all over \n the world have come and invaded us, captured our lands, conquered our minds. \n From Alexander onwards, the Greeks, the Turks, the Moguls, the Portuguese, the British,\n the French, the Dutch, all of them came and looted us, took over what was ours. \n Yet we have not done this to any other nation. We have not conquered anyone. \n We have not grabbed their land, their culture, \n their history and tried to enforce our way of life on them. \n Why? Because we respect the freedom of others.That is why my \n first vision is that of freedom. I believe that India got its first vision of \n this in 1857, when we started the War of Independence. It is this freedom that\n we must protect and nurture and build on. If we are not free, no one will respect us.\n My second vision for India’s development. For fifty years we have been a developing nation.\n It is time we see ourselves as a developed nation. We are among the top 5 nations of the world\n in terms of GDP. We have a 10 percent growth rate in most areas. Our poverty levels are falling.\n Our achievements are being globally recognised today. Yet we lack the self-confidence to\n see ourselves as a developed nation, self-reliant and self-assured. Isn’t this incorrect?\n I have a third vision. India must stand up to the world. Because I believe that unless India \n stands up to the world, no one will respect us. Only strength respects strength. We must be \n strong not only as a military power but also as an economic power. Both must go hand-in-hand. \n My good fortune was to have worked with three great minds. Dr. Vikram Sarabhai of the Dept. of \n space, Professor Satish Dhawan, who succeeded him and Dr. Brahm Prakash, father of nuclear material.\n I was lucky to have worked with all three of them closely and consider this the great opportunity of my life. \n I see four milestones in my career\"\"\"",
"_____no_output_____"
],
[
"sentences = nltk.sent_tokenize(paragraph)\nlemmatizer = WordNetLemmatizer()",
"_____no_output_____"
],
[
"for i in range(len(sentences)):\n words = nltk.word_tokenize(sentences[i])\n words = [lemmatizer.lemmatize(word) for word in words if word not in set(stopwords.words('english'))]\n sentences[i] = ' '.join(words)\n ",
"_____no_output_____"
],
[
"sentences",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb089929403ee7885770a9e6cec735a3e7a03266 | 36,458 | ipynb | Jupyter Notebook | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic | b4ccaf49772d55f632a0995c411d1cc042d71903 | [
"MIT"
] | null | null | null | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic | b4ccaf49772d55f632a0995c411d1cc042d71903 | [
"MIT"
] | null | null | null | notebooks/BLS model/BLS model - intermolecular pressure.ipynb | scbao/pysonic | b4ccaf49772d55f632a0995c411d1cc042d71903 | [
"MIT"
] | null | null | null | 141.859922 | 16,600 | 0.879231 | [
[
[
"# Bilayer Sonophore model: pre-computation of intermolecular pressure\n\nProfiled simulations of the mechanical model in isolation reveal that the spatial integration of intermolecular pressure $P_M$ is by far the longest internal computation at each iteration. Hence, we seek to decrease its computational cost.\n\nLuckily, despite its complexity, this integrated pressure term depends solely on leaflet deflection and the nature of its profile is similar to that of its local counterpart.\n\nTherefore, a precomputing step is defined wherein a Lennard-Jones expression of the form:\n\n$\\tilde{P_M}(Z)= \\tilde{A_r} \\big[ \\big(\\frac{\\tilde{\\Delta^*}}{2 \\cdot Z + \\Delta(Q_m)}\\big)^\\tilde{x} - \\big(\\frac{\\tilde{\\Delta^*}}{2 \\cdot Z + \\Delta(Q_m)}\\big)^\\tilde{y} \\big]$\n\nis fitted to the integrated profile and then used as a new predictor of intermolecular pressure during the iterative numerical resolution.",
"_____no_output_____"
],
[
"### Imports",
"_____no_output_____"
]
],
[
[
"import logging\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PySONIC.utils import logger, rmse, rsquared\nfrom PySONIC.neurons import getPointNeuron\nfrom PySONIC.core import BilayerSonophore, PmCompMethod, AcousticDrive\nfrom PySONIC.constants import *\n\n# Set logging level\nlogger.setLevel(logging.INFO)",
"_____no_output_____"
]
],
[
[
"### Functions",
"_____no_output_____"
]
],
[
[
"def plotPmavg(bls, Z, fs=15):\n fig, ax = plt.subplots(figsize=(5, 3))\n for skey in ['right', 'top']:\n ax.spines[skey].set_visible(False)\n ax.set_xlabel('Z (nm)', fontsize=fs)\n ax.set_ylabel('Pressure (kPa)', fontsize=fs)\n ax.set_xticks([0, bls.a * 1e9])\n ax.set_xticklabels(['0', 'a'])\n ax.set_yticks([-10, 0, 40])\n ax.set_ylim([-10, 50])\n for item in ax.get_xticklabels() + ax.get_yticklabels():\n item.set_fontsize(fs)\n ax.plot(Z * 1e9, bls.v_PMavg(Z, bls.v_curvrad(Z), bls.surface(Z)) * 1e-3, label='$P_m$')\n ax.plot(Z * 1e9, bls.PMavgpred(Z) * 1e-3, label='$P_{m,approx}$')\n ax.axhline(y=0, color='k')\n ax.legend(fontsize=fs, frameon=False)\n fig.tight_layout()\n\ndef plotZprofiles(bls, US_source, Q, fs=15):\n # Run simulations with integrated and predicted intermolecular pressure\n t0 = time.perf_counter()\n data1, _ = bls.simulate(US_source, Qm, Pm_comp_method=PmCompMethod.direct)\n tcomp_direct = time.perf_counter() - t0\n print(f'computation time with direct Pm: {tcomp_direct} s')\n Z1 = data1['Z'].values[-NPC_DENSE:] * 1e9 # nm\n \n t0 = time.perf_counter()\n data2, _ = bls.simulate(US_source, Qm, Pm_comp_method=PmCompMethod.predict)\n tcomp_predict = time.perf_counter() - t0\n print(f'computation time with predicted Pm: {tcomp_predict} s')\n Z2 = data2['Z'].values[-NPC_DENSE:] * 1e9 # nm\n \n tcomp_ratio = tcomp_direct / tcomp_predict\n \n # Plot figure \n t = np.linspace(0, US_source.periodicity, US_source.nPerCycle) * 1e6 # us\n fig, ax = plt.subplots(figsize=(5, 3))\n for skey in ['right', 'top']:\n ax.spines[skey].set_visible(False)\n ax.set_xlabel('time (us)', fontsize=fs)\n ax.set_ylabel('Deflection (nm)', fontsize=fs)\n ax.set_xticks([t[0], t[-1]])\n for item in ax.get_xticklabels() + ax.get_yticklabels():\n item.set_fontsize(fs)\n \n ax.plot(t, Z1, label='$P_m$')\n ax.plot(t, Z2, label='$P_{m,approx}$')\n ax.axhline(y=0, color='k')\n ax.legend(fontsize=fs, frameon=False)\n fig.tight_layout()\n \n return fig, Z1, Z2, tcomp_ratio",
"_____no_output_____"
]
],
[
[
"### Parameters",
"_____no_output_____"
]
],
[
[
"pneuron = getPointNeuron('RS')\nbls = BilayerSonophore(32e-9, pneuron.Cm0, pneuron.Qm0)\nUS_source = AcousticDrive(500e3, 100e3)\nQm = pneuron.Qm0",
"_____no_output_____"
]
],
[
[
"### Profiles comparison over deflection range ",
"_____no_output_____"
]
],
[
[
"Z = np.linspace(-0.4 * bls.Delta_, bls.a, 1000)\nfig = plotPmavg(bls, Z)",
"_____no_output_____"
]
],
[
[
"### Error quantification over a typical acoustic cycle",
"_____no_output_____"
]
],
[
[
"fig, Z1, Z2, tcomp_ratio = plotZprofiles(bls, US_source, Qm)\nerror_Z = rmse(Z1, Z2)\nr2_Z = rsquared(Z1, Z2)\nerr_pct = error_Z / (Z1.max() - Z1.min()) * 1e2\nprint(f'Z-error: R2 = {r2_Z:.4f}, RMSE = {error_Z:.4f} nm ({err_pct:.4f}% dZ)')\nprint(f'computational boost: {tcomp_ratio:.1f}-fold')",
" 30/01/2020 17:15:24: BilayerSonophore(32.0 nm): simulation @ f = 500.00 kHz, A = 100.00 kPa, Q = -71.90 nC/cm2\n"
]
],
[
[
"As we can see, this simplification allows to reduce computation times by more than one order of magnitude, without significantly affecting the resulting deflection profiles.",
"_____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"
]
] |
cb0899c86336368463d4cc7da4d25072b3e95c69 | 119,017 | ipynb | Jupyter Notebook | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | python/nano/notebooks/pytorch/cifar10/nano-trainer-example.ipynb | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | 52.685702 | 518 | 0.538679 | [
[
[
"---\n## BigDL-Nano Resnet example on CIFAR10 dataset\n---\nThis example illustrates how to apply bigdl-nano optimizations on a image recognition case based on pytorch-lightning framework. The basic image recognition module is implemented with Lightning and trained on [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) image recognition Benchmark dataset.",
"_____no_output_____"
]
],
[
[
"from time import time\nimport os\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom pl_bolts.datamodules import CIFAR10DataModule\nfrom pl_bolts.transforms.dataset_normalizations import cifar10_normalization\nfrom pytorch_lightning import LightningModule, seed_everything\nfrom pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom torch.optim.lr_scheduler import OneCycleLR\nfrom torchmetrics.functional import accuracy\nfrom bigdl.nano.pytorch.trainer import Trainer\nfrom bigdl.nano.pytorch.vision import transforms",
"_____no_output_____"
]
],
[
[
"### CIFAR10 Data Module\n---\nImport the existing data module from bolts and modify the train and test transforms.\nYou could access [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) for a view of the whole dataset.\n",
"_____no_output_____"
]
],
[
[
"def prepare_data(data_path, batch_size, num_workers):\n train_transforms = transforms.Compose(\n [\n transforms.RandomCrop(32, 4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n cifar10_normalization()\n ]\n )\n\n test_transforms = transforms.Compose(\n [\n transforms.ToTensor(),\n cifar10_normalization()\n ]\n )\n cifar10_dm = CIFAR10DataModule(\n data_dir=data_path,\n batch_size=batch_size,\n num_workers=num_workers,\n train_transforms=train_transforms,\n test_transforms=test_transforms,\n val_transforms=test_transforms\n )\n return cifar10_dm",
"_____no_output_____"
]
],
[
[
"### Resnet\n---\nModify the pre-existing Resnet architecture from TorchVision. The pre-existing architecture is based on ImageNet images (224x224) as input. So we need to modify it for CIFAR10 images (32x32).",
"_____no_output_____"
]
],
[
[
"def create_model():\n model = torchvision.models.resnet18(pretrained=False, num_classes=10)\n model.conv1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n model.maxpool = nn.Identity()\n return model",
"_____no_output_____"
]
],
[
[
"### Lightning Module\n---\nCheck out the [configure_optimizers](https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html#configure-optimizers) method to use custom Learning Rate schedulers. The OneCycleLR with SGD will get you to around 92-93% accuracy in 20-30 epochs and 93-94% accuracy in 40-50 epochs. Feel free to experiment with different LR schedules from https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate",
"_____no_output_____"
]
],
[
[
"class LitResnet(LightningModule):\n def __init__(self, learning_rate=0.05, steps_per_epoch=45000 , batch_size=32):\n super().__init__()\n\n self.save_hyperparameters()\n self.model = create_model()\n\n def forward(self, x):\n out = self.model(x)\n return F.log_softmax(out, dim=1)\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n logits = self(x)\n loss = F.nll_loss(logits, y)\n self.log(\"train_loss\", loss)\n return loss\n\n def evaluate(self, batch, stage=None):\n x, y = batch\n logits = self(x)\n loss = F.nll_loss(logits, y)\n preds = torch.argmax(logits, dim=1)\n acc = accuracy(preds, y)\n\n if stage:\n self.log(f\"{stage}_loss\", loss, prog_bar=True)\n self.log(f\"{stage}_acc\", acc, prog_bar=True)\n\n def validation_step(self, batch, batch_idx):\n self.evaluate(batch, \"val\")\n\n def test_step(self, batch, batch_idx):\n self.evaluate(batch, \"test\")\n\n def configure_optimizers(self):\n optimizer = torch.optim.SGD(\n self.parameters(),\n lr=self.hparams.learning_rate,\n momentum=0.9,\n weight_decay=5e-4,\n )\n steps_per_epoch = self.hparams.steps_per_epoch // self.hparams.batch_size\n scheduler_dict = {\n \"scheduler\": OneCycleLR(\n optimizer,\n 0.1,\n epochs=self.trainer.max_epochs,\n steps_per_epoch=steps_per_epoch,\n ),\n \"interval\": \"step\",\n }\n return {\"optimizer\": optimizer, \"lr_scheduler\": scheduler_dict}",
"_____no_output_____"
],
[
"seed_everything(7)\nPATH_DATASETS = os.environ.get(\"PATH_DATASETS\", \".\")\nBATCH_SIZE = 32\nNUM_WORKERS = 0\ndata_module = prepare_data(PATH_DATASETS, BATCH_SIZE, NUM_WORKERS)\nEPOCHS = int(os.environ.get('FIT_EPOCHS', 30))",
"Global seed set to 7\n"
]
],
[
[
"### Train\nUse Trainer from bigdl.nano.pytorch.trainer for BigDL-Nano pytorch.\n\nThis Trainer extends PyTorch Lightning Trainer by adding various options to accelerate pytorch training.\n\n```\n :param num_processes: number of processes in distributed training. default: 4.\n :param use_ipex: whether we use ipex as accelerator for trainer. default: True.\n :param cpu_for_each_process: A list of length `num_processes`, each containing a list of\n indices of cpus each process will be using. default: None, and the cpu will be\n automatically and evenly distributed among processes.\n```\nThe next few cells show examples of different parameters.\n#### Single Process\n---",
"_____no_output_____"
]
],
[
[
"model = LitResnet(learning_rate=0.05)\nmodel.datamodule = data_module\ncheckpoint_callback = ModelCheckpoint(dirpath=\"checkpoints/\", save_top_k=1, monitor=\"val_loss\", filename=\"renet18_single_none\")\nbasic_trainer = Trainer(num_processes = 1,\n use_ipex = False,\n progress_bar_refresh_rate=10,\n max_epochs=EPOCHS,\n logger=TensorBoardLogger(\"lightning_logs/\", name=\"basic\"),\n callbacks=[LearningRateMonitor(logging_interval=\"step\"), checkpoint_callback])\nstart = time()\nbasic_trainer.fit(model, datamodule=data_module)\nbasic_fit_time = time() - start\noutputs = basic_trainer.test(model, datamodule=data_module)\nbasic_acc = outputs[0]['test_acc'] * 100",
"GPU available: False, used: False\nTPU available: False, using: 0 TPU cores\nIPU available: False, using: 0 IPUs\n"
]
],
[
[
"### Single Process with IPEX\n---",
"_____no_output_____"
]
],
[
[
"model = LitResnet(learning_rate=0.05)\nmodel.datamodule = data_module\ncheckpoint_callback = ModelCheckpoint(dirpath=\"checkpoints/\", save_top_k=1, monitor=\"val_loss\", filename=\"renet18_single_ipex\", save_weights_only=True)\nsingle_ipex_trainer = Trainer(num_processes=1,\n use_ipex = True,\n distributed_backend=\"subprocess\",\n progress_bar_refresh_rate=10,\n max_epochs=EPOCHS,\n logger=TensorBoardLogger(\"lightning_logs/\", name=\"single_ipex\"),\n callbacks=[LearningRateMonitor(logging_interval=\"step\"), checkpoint_callback])\nstart = time()\nsingle_ipex_trainer.fit(model, datamodule=data_module)\nsingle_ipex_fit_time = time() - start\noutputs = single_ipex_trainer.test(model, datamodule=data_module)\nsingle_ipex_acc = outputs[0]['test_acc'] * 100",
"/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/callbacks/model_checkpoint.py:446: UserWarning: Checkpoint directory checkpoints/ exists and is not empty.\n rank_zero_warn(f\"Checkpoint directory {dirpath} exists and is not empty.\")\nGPU available: False, used: False\nTPU available: False, using: 0 TPU cores\nIPU available: False, using: 0 IPUs\n/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/core/datamodule.py:424: LightningDeprecationWarning: DataModule.setup has already been called, so it will not be called again. In v1.6 this behavior will change to always call DataModule.setup.\n f\"DataModule.{name} has already been called, so it will not be called again. \"\n\n | Name | Type | Params\n---------------------------------\n0 | model | ResNet | 11.2 M\n---------------------------------\n11.2 M Trainable params\n0 Non-trainable params\n11.2 M Total params\n44.696 Total estimated model params size (MB)\n"
]
],
[
[
"### Multiple Processes with IPEX\n---",
"_____no_output_____"
]
],
[
[
"model = LitResnet(learning_rate=0.1, batch_size=64)\nmodel.datamodule = data_module\ncheckpoint_callback = ModelCheckpoint(dirpath=\"checkpoints/\", save_top_k=1, monitor=\"val_loss\", filename=\"renet18_multi_ipex\", save_weights_only=True)\nmulti_ipex_trainer = Trainer(num_processes=2,\n use_ipex=True,\n distributed_backend=\"subprocess\",\n progress_bar_refresh_rate=10,\n max_epochs=EPOCHS,\n logger=TensorBoardLogger(\"lightning_logs/\", name=\"multi_ipx\"),\n callbacks=[LearningRateMonitor(logging_interval=\"step\"), checkpoint_callback])\nstart = time()\nmulti_ipex_trainer.fit(model, datamodule=data_module)\nmulti_ipex_fit_time = time() - start\noutputs = multi_ipex_trainer.test(model, datamodule=data_module)\nmulti_ipex_acc = outputs[0]['test_acc'] * 100",
"/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/callbacks/model_checkpoint.py:446: UserWarning: Checkpoint directory checkpoints/ exists and is not empty.\n rank_zero_warn(f\"Checkpoint directory {dirpath} exists and is not empty.\")\n/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/plugins/training_type/ddp_spawn.py:75: LightningDeprecationWarning: Argument `num_nodes` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. Notice that it will be overriden by the trainer setting.\n \"Argument `num_nodes` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. \"\n/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/plugins/training_type/ddp_spawn.py:81: LightningDeprecationWarning: Argument `sync_batchnorm` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. Notice that it will be overriden by the trainer setting.\n \"Argument `sync_batchnorm` in `DDPSpawnPlugin` is deprecated in v1.4, and will be removed in v1.6. \"\n/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/trainer/connectors/accelerator_connector.py:685: UserWarning: Specified `Precision` and `TrainingType` plugins will be ignored, since an `Accelerator` instance was provided.\n \"Specified `Precision` and `TrainingType` plugins will be ignored,\"\nGPU available: False, used: False\nTPU available: False, using: 0 TPU cores\nIPU available: False, using: 0 IPUs\n/home/mingzhi/anaconda3/envs/nanoWithPytorch/lib/python3.7/site-packages/pytorch_lightning/core/datamodule.py:424: LightningDeprecationWarning: DataModule.setup has already been called, so it will not be called again. In v1.6 this behavior will change to always call DataModule.setup.\n f\"DataModule.{name} has already been called, so it will not be called again. \"\nGlobal seed set to 7\ninitializing ddp: GLOBAL_RANK: 0, MEMBER: 1/2\nGlobal seed set to 7\ninitializing ddp: GLOBAL_RANK: 1, MEMBER: 2/2\n----------------------------------------------------------------------------------------------------\ndistributed_backend=gloo\nAll DDP processes registered. Starting ddp with 2 processes\n----------------------------------------------------------------------------------------------------\n\n\n | Name | Type | Params\n---------------------------------\n0 | model | ResNet | 11.2 M\n---------------------------------\n11.2 M Trainable params\n0 Non-trainable params\n11.2 M Total params\n44.696 Total estimated model params size (MB)\n"
],
[
"template = \"\"\"\n| Precision | Fit Time(s) | Accuracy(%) |\n| Basic | {:5.2f} | {:5.2f} |\n| Single With Ipex | {:5.2f} | {:5.2f} |\n| Multiple With Ipex| {:5.2f} | {:5.2f} |\n\"\"\"\nsummary = template.format(\n basic_fit_time, basic_acc,\n single_ipex_fit_time, single_ipex_acc,\n multi_ipex_fit_time, multi_ipex_acc\n)\nprint(summary)",
"\n| Precision | Fit Time(s) | Accuracy(%) |\n| Basic | 4559.45 | 90.29 |\n| Single With Ipex | 4380.92 | 89.94 |\n| Multiple With Ipex| 2633.85 | 89.18 |\n\n"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb08b478e1dbfbf9b4f92de51c161d96e81feb05 | 375,435 | ipynb | Jupyter Notebook | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain | 73dbe66cd3c5a0d9cf5b2cb240c7c2fdd937c839 | [
"MIT"
] | 4 | 2021-02-24T15:02:35.000Z | 2022-01-18T19:24:27.000Z | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain | 73dbe66cd3c5a0d9cf5b2cb240c7c2fdd937c839 | [
"MIT"
] | 35 | 2020-11-06T17:51:08.000Z | 2021-10-14T01:47:16.000Z | cronjobs/transient_matching/modified_cnn_classify_data_gradCAM.ipynb | divijsharma18/timedomain | 73dbe66cd3c5a0d9cf5b2cb240c7c2fdd937c839 | [
"MIT"
] | 10 | 2020-03-13T20:34:15.000Z | 2021-09-23T13:35:27.000Z | 215.519518 | 162,828 | 0.874253 | [
[
[
"# Apply CNN Classifier to DESI Spectra and visualize results with gradCAM\n\nMini-SV2 tiles from February-March 2020:\n- https://desi.lbl.gov/trac/wiki/TargetSelectionWG/miniSV2\n\nSee also the DESI tile picker with (limited) SV0 tiles from March 2020:\n- https://desi.lbl.gov/svn/data/tiles/trunk/\n- https://desi.lbl.gov/svn/data/tiles/trunk/SV0.html",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('/global/homes/p/palmese/desi/timedomain/desitrip/py/') #Note:change this path as needed!\nsys.path.append('/global/homes/p/palmese/desi/timedomain/timedomain/')\n\nfrom desispec.io import read_spectra, write_spectra\nfrom desispec.spectra import Spectra\nfrom desispec.coaddition import coadd_cameras\n\nfrom desitarget.cmx.cmx_targetmask import cmx_mask\n\nfrom desitrip.preproc import rebin_flux, rescale_flux\nfrom desitrip.deltamag import delta_mag\n\nfrom astropy.io import fits\nfrom astropy.table import Table, vstack, hstack\n\nfrom glob import glob\nfrom datetime import date\n\nimport os\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom tensorflow import keras",
"_____no_output_____"
],
[
"mpl.rc('font', size=14)",
"_____no_output_____"
],
[
"# Set up BGS target bit selection.\ncmx_bgs_bits = '|'.join([_ for _ in cmx_mask.names() if 'BGS' in _])",
"_____no_output_____"
]
],
[
[
"## Select a Date & Tile from matches files",
"_____no_output_____"
]
],
[
[
"\nmatches_filename='matches_DECam.npy'\n\nfile_arr=np.load('matches_DECam.npy', allow_pickle=True)\n\nobsdates = file_arr[:,0]\ntile_ids = file_arr[:,1]\npetal_ids = file_arr[:,2]\ntarget_ids = file_arr[:,3]\ntamuids = file_arr[:,6]\n\n",
"_____no_output_____"
],
[
"# Access redux folder.\nzbfiles = []\ncafiles = []\n\nredux='/global/project/projectdirs/desi/spectro/redux/daily/tiles'\nfor tile_id, obsdate, petal_id, targetid in zip(tile_ids[:], obsdates[:], petal_ids[:], target_ids[:]):\n tile_id = int(tile_id)\n if obsdate < 20210301:\n print('Skipping files')\n continue\n elif obsdate < 20210503:\n prefix_in ='/'.join([redux, str(tile_id), str(obsdate)])\n else:\n prefix_in = '/'.join([redux, 'cumulative', str(tile_id),str(obsdate)])\n #print(prefix_in) \n if not os.path.isdir(prefix_in):\n print('{} does not exist.'.format(prefix_in))\n continue\n\n # List zbest and coadd files.\n # Data are stored by petal ID.\n if obsdate < 20210503:\n fileend = '-'.join((str(petal_id), str(tile_id), str(obsdate)))\n cafile=sorted(glob('{}/coadd-'.format(prefix_in) + fileend + '*.fits'))\n else:\n fileend = '-'.join((str(petal_id), str(tile_id)))\n cafile=sorted(glob('{}/spectra-'.format(prefix_in) + fileend + '*.fits'))\n #print(fileend)\n zbfile=sorted(glob('{}/zbest-'.format(prefix_in) + fileend + '*.fits'))\n \n zbfiles.extend(zbfile)\n cafiles.extend(cafile)\n ",
"_____no_output_____"
],
[
"print(len(zbfiles))\nprint(len(cafiles))\nprint(len(tile_ids))\nprint(len(obsdates))\nprint(len(petal_ids))",
"585\n585\n585\n585\n585\n"
]
],
[
[
"## Load the Keras Model\n\nLoad a model trained on real or simulated data using the native Keras output format. In the future this could be updated to just load the Keras weights.",
"_____no_output_____"
]
],
[
[
"tfmodel = '/global/homes/l/lehsani/timedomain/desitrip/docs/nb/models_9label_first/6_b65_e200_9label/b65_e200_9label_model'\n#tfmodel = '/global/homes/s/sybenzvi/desi/timedomain/desitrip/docs/nb/6label_cnn_restframe'\nif os.path.exists(tfmodel):\n classifier = keras.models.load_model(tfmodel)\nelse:\n classifier = None\n print('Sorry, could not find {}'.format(tfmodel))",
"_____no_output_____"
],
[
"if classifier is not None:\n classifier.summary()",
"Model: \"SNnet\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nInput_Spec (InputLayer) [(None, 150, 1)] 0 \n_________________________________________________________________\nconv1d_20 (Conv1D) (None, 150, 8) 48 \n_________________________________________________________________\nbatch_normalization_20 (Batc (None, 150, 8) 32 \n_________________________________________________________________\nactivation_20 (Activation) (None, 150, 8) 0 \n_________________________________________________________________\nmax_pooling1d_20 (MaxPooling (None, 75, 8) 0 \n_________________________________________________________________\nconv1d_21 (Conv1D) (None, 75, 16) 656 \n_________________________________________________________________\nbatch_normalization_21 (Batc (None, 75, 16) 64 \n_________________________________________________________________\nactivation_21 (Activation) (None, 75, 16) 0 \n_________________________________________________________________\nmax_pooling1d_21 (MaxPooling (None, 37, 16) 0 \n_________________________________________________________________\nconv1d_22 (Conv1D) (None, 37, 32) 2592 \n_________________________________________________________________\nbatch_normalization_22 (Batc (None, 37, 32) 128 \n_________________________________________________________________\nactivation_22 (Activation) (None, 37, 32) 0 \n_________________________________________________________________\nmax_pooling1d_22 (MaxPooling (None, 18, 32) 0 \n_________________________________________________________________\nconv1d_23 (Conv1D) (None, 18, 64) 10304 \n_________________________________________________________________\nbatch_normalization_23 (Batc (None, 18, 64) 256 \n_________________________________________________________________\nactivation_23 (Activation) (None, 18, 64) 0 \n_________________________________________________________________\nmax_pooling1d_23 (MaxPooling (None, 9, 64) 0 \n_________________________________________________________________\nflatten_5 (Flatten) (None, 576) 0 \n_________________________________________________________________\ndense_5 (Dense) (None, 256) 147712 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 256) 0 \n_________________________________________________________________\nOutput_Classes (Dense) (None, 9) 2313 \n=================================================================\nTotal params: 164,105\nTrainable params: 163,865\nNon-trainable params: 240\n_________________________________________________________________\n"
]
],
[
[
"## Loop Through Spectra and Classify",
"_____no_output_____"
]
],
[
[
"# Loop through zbest and coadd files for each petal.\n# Extract the fibermaps, ZBEST tables, and spectra.\n# Keep only BGS targets passing basic event selection.\nallzbest = None\nallfmap = None\nallwave = None\nallflux = None\nallivar = None\nallmask = None\nallres = None\nhandy_table = []\n\ncolor_string = 'brz'\ncount = 0\n\nfor cafile, zbfile, targetid, obsdate in zip(cafiles, zbfiles, target_ids, obsdates): # rows[:-1] IS TEMPORARY\n # Access data per petal.\n print(\"Accessing file number \",count)\n print(cafile,zbfile)\n zbest = Table.read(zbfile, 'ZBEST')\n idx_zbest = (zbest['TARGETID']==targetid)\n targetids = zbest[idx_zbest]['TARGETID']\n chi2 = zbest[idx_zbest]['CHI2']\n \n pspectra = read_spectra(cafile)\n if obsdate>20210503:\n select_nite = pspectra.fibermap['NIGHT'] == obsdate\n pspectra = pspectra[select_nite]\n \n cspectra = coadd_cameras(pspectra)\n fibermap = cspectra.fibermap\n idx_fibermap = (fibermap['TARGETID'] == targetid)\n \n ra = fibermap[idx_fibermap]['TARGET_RA'][0]\n dec = fibermap[idx_fibermap]['TARGET_DEC'][0]\n handy_table.append((targetid, tamuids[count], ra, dec, tile_ids[count], obsdate))\n #print(pspectra.flux)S\n\n # Apply standard event selection.\n #isTGT = fibermap['OBJTYPE'] == 'TGT'\n #isGAL = zbest['SPECTYPE'] == 'GALAXY'\n \n #& isGAL #isTGT #& isBGS\n #exp_id = fibermap['EXPID'] & select # first need to figure out all columns as this fails\n #print(select)\n count += 1\n\n # Accumulate spectrum data.\n if allzbest is None:\n allzbest = zbest[idx_zbest]\n allfmap = fibermap[idx_fibermap]\n allwave = cspectra.wave[color_string]\n allflux = cspectra.flux[color_string][idx_fibermap]\n allivar = cspectra.ivar[color_string][idx_fibermap]\n allmask = cspectra.mask[color_string][idx_fibermap]\n allres = cspectra.resolution_data[color_string][idx_fibermap]\n else:\n allzbest = vstack([allzbest, zbest[idx_zbest]])\n allfmap = vstack([allfmap, fibermap[idx_fibermap]])\n allflux = np.vstack([allflux, cspectra.flux[color_string][idx_fibermap]])\n allivar = np.vstack([allivar, cspectra.ivar[color_string][idx_fibermap]])\n allmask = np.vstack([allmask, cspectra.mask[color_string][idx_fibermap]])\n allres = np.vstack([allres, cspectra.resolution_data[color_string][idx_fibermap]])",
"Accessing file number 0\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-8-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-8-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.708 sec to read coadd-8-80662-20210322.fits at 2021-06-30T13:34:30.737716\nAccessing file number 1\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-4-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-4-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.773 sec to read coadd-4-80662-20210322.fits at 2021-06-30T13:34:39.606831\nAccessing file number 2\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-3-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-3-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.620 sec to read coadd-3-80662-20210322.fits at 2021-06-30T13:34:47.758002\nAccessing file number 3\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-7-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-7-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.620 sec to read coadd-7-80662-20210322.fits at 2021-06-30T13:34:55.634809\nAccessing file number 4\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-8-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-8-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.475 sec to read coadd-8-80662-20210322.fits at 2021-06-30T13:35:03.151848\nAccessing file number 5\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-4-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-4-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.424 sec to read coadd-4-80662-20210322.fits at 2021-06-30T13:35:10.920544\nAccessing file number 6\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-3-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-3-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.478 sec to read coadd-3-80662-20210322.fits at 2021-06-30T13:35:18.551072\nAccessing file number 7\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/coadd-7-80662-20210322.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80662/20210322/zbest-7-80662-20210322.fits\nINFO:spectra.py:261:read_spectra: iotime 0.450 sec to read coadd-7-80662-20210322.fits at 2021-06-30T13:35:26.263011\nAccessing file number 8\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80706/20210402/coadd-3-80706-20210402.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80706/20210402/zbest-3-80706-20210402.fits\nINFO:spectra.py:261:read_spectra: iotime 0.695 sec to read coadd-3-80706-20210402.fits at 2021-06-30T13:35:34.313475\nAccessing file number 9\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/80706/20210402/coadd-3-80706-20210402.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/80706/20210402/zbest-3-80706-20210402.fits\nINFO:spectra.py:261:read_spectra: iotime 0.466 sec to read coadd-3-80706-20210402.fits at 2021-06-30T13:35:42.242358\nAccessing file number 10\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/coadd-0-39-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/zbest-0-39-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.604 sec to read coadd-0-39-20210405.fits at 2021-06-30T13:35:49.884300\nAccessing file number 11\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/coadd-6-39-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/zbest-6-39-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.697 sec to read coadd-6-39-20210405.fits at 2021-06-30T13:35:58.298246\nAccessing file number 12\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/coadd-0-39-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/zbest-0-39-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.493 sec to read coadd-0-39-20210405.fits at 2021-06-30T13:36:05.945773\nAccessing file number 13\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/coadd-6-39-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/39/20210405/zbest-6-39-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.366 sec to read coadd-6-39-20210405.fits at 2021-06-30T13:36:13.687837\nAccessing file number 14\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-4-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-4-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.718 sec to read coadd-4-66-20210405.fits at 2021-06-30T13:36:21.598533\nAccessing file number 15\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-7-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-7-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.578 sec to read coadd-7-66-20210405.fits at 2021-06-30T13:36:28.937515\nAccessing file number 16\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-2-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-2-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.632 sec to read coadd-2-66-20210405.fits at 2021-06-30T13:36:36.667437\nAccessing file number 17\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-4-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-4-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.433 sec to read coadd-4-66-20210405.fits at 2021-06-30T13:36:44.466299\nAccessing file number 18\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-7-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-7-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.417 sec to read coadd-7-66-20210405.fits at 2021-06-30T13:36:51.869704\nAccessing file number 19\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/coadd-2-66-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210405/zbest-2-66-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.449 sec to read coadd-2-66-20210405.fits at 2021-06-30T13:36:58.619764\nAccessing file number 20\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.654 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:37:06.378446\nAccessing file number 21\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.418 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:37:13.924679\nAccessing file number 22\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.403 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:37:21.802560\nAccessing file number 23\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.424 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:37:29.699022\nAccessing file number 24\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-2-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-2-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.691 sec to read coadd-2-228-20210405.fits at 2021-06-30T13:37:37.835331\nAccessing file number 25\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-2-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-2-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.450 sec to read coadd-2-228-20210405.fits at 2021-06-30T13:37:45.812381\nAccessing file number 26\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-6-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-6-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.595 sec to read coadd-6-228-20210405.fits at 2021-06-30T13:37:53.218836\nAccessing file number 27\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-3-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-3-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.711 sec to read coadd-3-228-20210405.fits at 2021-06-30T13:38:00.974513\nAccessing file number 28\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-3-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-3-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.510 sec to read coadd-3-228-20210405.fits at 2021-06-30T13:38:08.649875\nAccessing file number 29\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-5-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-5-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.680 sec to read coadd-5-228-20210405.fits at 2021-06-30T13:38:16.827435\nAccessing file number 30\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-0-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-0-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.685 sec to read coadd-0-228-20210405.fits at 2021-06-30T13:38:24.787639\nAccessing file number 31\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/coadd-0-228-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210405/zbest-0-228-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.451 sec to read coadd-0-228-20210405.fits at 2021-06-30T13:38:32.960268\nAccessing file number 32\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.434 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:38:41.061506\nAccessing file number 33\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/coadd-8-136-20210405.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/136/20210405/zbest-8-136-20210405.fits\nINFO:spectra.py:261:read_spectra: iotime 0.512 sec to read coadd-8-136-20210405.fits at 2021-06-30T13:38:49.459426\nAccessing file number 34\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-4-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-4-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.683 sec to read coadd-4-66-20210406.fits at 2021-06-30T13:38:57.246280\nAccessing file number 35\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-7-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-7-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.641 sec to read coadd-7-66-20210406.fits at 2021-06-30T13:39:05.474911\nAccessing file number 36\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-2-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-2-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.563 sec to read coadd-2-66-20210406.fits at 2021-06-30T13:39:13.791519\nAccessing file number 37\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-4-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-4-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.522 sec to read coadd-4-66-20210406.fits at 2021-06-30T13:39:21.895056\nAccessing file number 38\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-7-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-7-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.381 sec to read coadd-7-66-20210406.fits at 2021-06-30T13:39:29.168191\nAccessing file number 39\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/coadd-2-66-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/66/20210406/zbest-2-66-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.406 sec to read coadd-2-66-20210406.fits at 2021-06-30T13:39:36.696961\nAccessing file number 40\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-5-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-5-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.486 sec to read coadd-5-217-20210406.fits at 2021-06-30T13:39:44.727759\nAccessing file number 41\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-3-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-3-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.413 sec to read coadd-3-217-20210406.fits at 2021-06-30T13:39:52.300388\nAccessing file number 42\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-2-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-2-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.481 sec to read coadd-2-217-20210406.fits at 2021-06-30T13:40:00.539653\nAccessing file number 43\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-3-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-3-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.457 sec to read coadd-3-217-20210406.fits at 2021-06-30T13:40:08.612323\nAccessing file number 44\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-2-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-2-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.424 sec to read coadd-2-217-20210406.fits at 2021-06-30T13:40:16.728707\nAccessing file number 45\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-5-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-5-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.493 sec to read coadd-5-217-20210406.fits at 2021-06-30T13:40:25.241886\nAccessing file number 46\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-5-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-5-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.585 sec to read coadd-5-217-20210406.fits at 2021-06-30T13:40:33.672467\nAccessing file number 47\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-2-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-2-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.454 sec to read coadd-2-217-20210406.fits at 2021-06-30T13:40:41.711082\nAccessing file number 48\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/coadd-3-217-20210406.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/217/20210406/zbest-3-217-20210406.fits\nINFO:spectra.py:261:read_spectra: iotime 0.424 sec to read coadd-3-217-20210406.fits at 2021-06-30T13:40:48.914246\nAccessing file number 49\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/coadd-6-28-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/zbest-6-28-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.486 sec to read coadd-6-28-20210407.fits at 2021-06-30T13:40:56.899244\nAccessing file number 50\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/coadd-8-28-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/zbest-8-28-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.520 sec to read coadd-8-28-20210407.fits at 2021-06-30T13:41:04.317340\nAccessing file number 51\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/coadd-6-28-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/zbest-6-28-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.443 sec to read coadd-6-28-20210407.fits at 2021-06-30T13:41:12.560307\nAccessing file number 52\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/coadd-8-28-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/28/20210407/zbest-8-28-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.537 sec to read coadd-8-28-20210407.fits at 2021-06-30T13:41:20.092360\nAccessing file number 53\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/coadd-3-56-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/zbest-3-56-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.447 sec to read coadd-3-56-20210407.fits at 2021-06-30T13:41:28.215149\nAccessing file number 54\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/coadd-3-56-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/zbest-3-56-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.409 sec to read coadd-3-56-20210407.fits at 2021-06-30T13:41:35.906306\nAccessing file number 55\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-3-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-3-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.478 sec to read coadd-3-67-20210407.fits at 2021-06-30T13:41:43.270359\nAccessing file number 56\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-6-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-6-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.456 sec to read coadd-6-67-20210407.fits at 2021-06-30T13:41:50.628323\nAccessing file number 57\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-5-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-5-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.500 sec to read coadd-5-67-20210407.fits at 2021-06-30T13:41:57.876617\nAccessing file number 58\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/40/20210407/coadd-6-40-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/40/20210407/zbest-6-40-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.464 sec to read coadd-6-40-20210407.fits at 2021-06-30T13:42:05.703946\nAccessing file number 59\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/40/20210407/coadd-3-40-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/40/20210407/zbest-3-40-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.465 sec to read coadd-3-40-20210407.fits at 2021-06-30T13:42:13.494953\nAccessing file number 60\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/coadd-3-56-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/zbest-3-56-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.425 sec to read coadd-3-56-20210407.fits at 2021-06-30T13:42:20.773373\nAccessing file number 61\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/coadd-3-56-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/56/20210407/zbest-3-56-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.438 sec to read coadd-3-56-20210407.fits at 2021-06-30T13:42:28.333492\nAccessing file number 62\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-3-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-3-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.405 sec to read coadd-3-67-20210407.fits at 2021-06-30T13:42:35.793389\nAccessing file number 63\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-6-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-6-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.506 sec to read coadd-6-67-20210407.fits at 2021-06-30T13:42:43.382789\nAccessing file number 64\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/coadd-5-67-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/67/20210407/zbest-5-67-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.456 sec to read coadd-5-67-20210407.fits at 2021-06-30T13:42:50.240367\nAccessing file number 65\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/148/20210407/coadd-9-148-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/148/20210407/zbest-9-148-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.434 sec to read coadd-9-148-20210407.fits at 2021-06-30T13:42:57.888443\nAccessing file number 66\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/148/20210407/coadd-9-148-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/148/20210407/zbest-9-148-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.443 sec to read coadd-9-148-20210407.fits at 2021-06-30T13:43:06.187210\nAccessing file number 67\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/272/20210407/coadd-2-272-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/272/20210407/zbest-2-272-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.423 sec to read coadd-2-272-20210407.fits at 2021-06-30T13:43:13.573214\nAccessing file number 68\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/272/20210407/coadd-2-272-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/272/20210407/zbest-2-272-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.412 sec to read coadd-2-272-20210407.fits at 2021-06-30T13:43:21.243458\nAccessing file number 69\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-8-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-8-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.459 sec to read coadd-8-245-20210407.fits at 2021-06-30T13:43:28.837766\nAccessing file number 70\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-3-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-3-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.447 sec to read coadd-3-245-20210407.fits at 2021-06-30T13:43:36.167853\nAccessing file number 71\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-3-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-3-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.435 sec to read coadd-3-245-20210407.fits at 2021-06-30T13:43:43.610625\nAccessing file number 72\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-8-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-8-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.392 sec to read coadd-8-245-20210407.fits at 2021-06-30T13:43:51.289571\nAccessing file number 73\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-8-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-8-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.362 sec to read coadd-8-245-20210407.fits at 2021-06-30T13:43:58.456890\nAccessing file number 74\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/coadd-3-245-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/245/20210407/zbest-3-245-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.414 sec to read coadd-3-245-20210407.fits at 2021-06-30T13:44:05.755824\nAccessing file number 75\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-3-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-3-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.733 sec to read coadd-3-255-20210407.fits at 2021-06-30T13:44:13.010192\nAccessing file number 76\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-2-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-2-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.813 sec to read coadd-2-255-20210407.fits at 2021-06-30T13:44:20.661193\nAccessing file number 77\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-6-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-6-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.728 sec to read coadd-6-255-20210407.fits at 2021-06-30T13:44:28.774040\nAccessing file number 78\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-6-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-6-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.430 sec to read coadd-6-255-20210407.fits at 2021-06-30T13:44:36.453473\nAccessing file number 79\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-0-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-0-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.617 sec to read coadd-0-255-20210407.fits at 2021-06-30T13:44:44.072893\nAccessing file number 80\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-8-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-8-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.623 sec to read coadd-8-255-20210407.fits at 2021-06-30T13:44:52.270294\nAccessing file number 81\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/coadd-8-255-20210407.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/255/20210407/zbest-8-255-20210407.fits\nINFO:spectra.py:261:read_spectra: iotime 0.365 sec to read coadd-8-255-20210407.fits at 2021-06-30T13:44:59.653136\nAccessing file number 82\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/coadd-1-246-20210408.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/zbest-1-246-20210408.fits\nINFO:spectra.py:261:read_spectra: iotime 0.702 sec to read coadd-1-246-20210408.fits at 2021-06-30T13:45:07.609513\nAccessing file number 83\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/coadd-8-246-20210408.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/zbest-8-246-20210408.fits\nINFO:spectra.py:261:read_spectra: iotime 0.672 sec to read coadd-8-246-20210408.fits at 2021-06-30T13:45:15.169483\nAccessing file number 84\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/coadd-1-246-20210408.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/zbest-1-246-20210408.fits\nINFO:spectra.py:261:read_spectra: iotime 0.475 sec to read coadd-1-246-20210408.fits at 2021-06-30T13:45:23.461001\nAccessing file number 85\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/coadd-8-246-20210408.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/246/20210408/zbest-8-246-20210408.fits\nINFO:spectra.py:261:read_spectra: iotime 0.418 sec to read coadd-8-246-20210408.fits at 2021-06-30T13:45:31.020451\nAccessing file number 86\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/29/20210409/coadd-8-29-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/29/20210409/zbest-8-29-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.656 sec to read coadd-8-29-20210409.fits at 2021-06-30T13:45:39.073575\nAccessing file number 87\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/29/20210409/coadd-8-29-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/29/20210409/zbest-8-29-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.365 sec to read coadd-8-29-20210409.fits at 2021-06-30T13:45:46.801283\nAccessing file number 88\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/coadd-5-219-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/zbest-5-219-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.669 sec to read coadd-5-219-20210409.fits at 2021-06-30T13:45:55.052312\nAccessing file number 89\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/coadd-3-219-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/zbest-3-219-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.676 sec to read coadd-3-219-20210409.fits at 2021-06-30T13:46:02.682698\nAccessing file number 90\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/coadd-5-219-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/zbest-5-219-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.519 sec to read coadd-5-219-20210409.fits at 2021-06-30T13:46:10.382427\nAccessing file number 91\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/coadd-3-219-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/219/20210409/zbest-3-219-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.405 sec to read coadd-3-219-20210409.fits at 2021-06-30T13:46:18.213648\nAccessing file number 92\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/247/20210409/coadd-8-247-20210409.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/247/20210409/zbest-8-247-20210409.fits\nINFO:spectra.py:261:read_spectra: iotime 0.646 sec to read coadd-8-247-20210409.fits at 2021-06-30T13:46:26.394188\nAccessing file number 93\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.628 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:46:33.741464\nAccessing file number 94\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.622 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:46:41.878966\nAccessing file number 95\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.442 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:46:49.415898\nAccessing file number 96\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.520 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:46:56.907812\nAccessing file number 97\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.470 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:47:04.442160\nAccessing file number 98\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.412 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:47:11.921968\nAccessing file number 99\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-8-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-8-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.702 sec to read coadd-8-41-20210410.fits at 2021-06-30T13:47:20.198078\nAccessing file number 100\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-3-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-3-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.671 sec to read coadd-3-41-20210410.fits at 2021-06-30T13:47:28.787484\nAccessing file number 101\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-5-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-5-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.654 sec to read coadd-5-41-20210410.fits at 2021-06-30T13:47:36.749665\nAccessing file number 102\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.464 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:47:44.459839\nAccessing file number 103\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.434 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:47:51.982649\nAccessing file number 104\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.475 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:47:59.665622\nAccessing file number 105\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.383 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:48:07.071563\nAccessing file number 106\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-3-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-3-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.413 sec to read coadd-3-30-20210410.fits at 2021-06-30T13:48:14.697195\nAccessing file number 107\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/coadd-1-30-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/30/20210410/zbest-1-30-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.449 sec to read coadd-1-30-20210410.fits at 2021-06-30T13:48:22.351733\nAccessing file number 108\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-8-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-8-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.411 sec to read coadd-8-41-20210410.fits at 2021-06-30T13:48:30.064921\nAccessing file number 109\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-3-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-3-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.392 sec to read coadd-3-41-20210410.fits at 2021-06-30T13:48:37.457648\nAccessing file number 110\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/coadd-5-41-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/41/20210410/zbest-5-41-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.382 sec to read coadd-5-41-20210410.fits at 2021-06-30T13:48:45.260688\nAccessing file number 111\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/220/20210410/coadd-2-220-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/220/20210410/zbest-2-220-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.728 sec to read coadd-2-220-20210410.fits at 2021-06-30T13:48:53.250290\nAccessing file number 112\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/coadd-0-275-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/zbest-0-275-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.780 sec to read coadd-0-275-20210410.fits at 2021-06-30T13:49:01.294275\nAccessing file number 113\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/coadd-0-275-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/zbest-0-275-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.472 sec to read coadd-0-275-20210410.fits at 2021-06-30T13:49:09.620725\nAccessing file number 114\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/coadd-0-275-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/zbest-0-275-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.408 sec to read coadd-0-275-20210410.fits at 2021-06-30T13:49:17.065008\nAccessing file number 115\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/coadd-0-275-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/275/20210410/zbest-0-275-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.434 sec to read coadd-0-275-20210410.fits at 2021-06-30T13:49:25.079353\nAccessing file number 116\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/248/20210410/coadd-4-248-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/248/20210410/zbest-4-248-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.997 sec to read coadd-4-248-20210410.fits at 2021-06-30T13:49:33.237440\nAccessing file number 117\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/256/20210410/coadd-4-256-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/256/20210410/zbest-4-256-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.877 sec to read coadd-4-256-20210410.fits at 2021-06-30T13:49:41.457028\nAccessing file number 118\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-9-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-9-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 1.406 sec to read coadd-9-282-20210410.fits at 2021-06-30T13:49:50.531305\nAccessing file number 119\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-9-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-9-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.490 sec to read coadd-9-282-20210410.fits at 2021-06-30T13:49:58.908204\nAccessing file number 120\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-3-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-3-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.854 sec to read coadd-3-282-20210410.fits at 2021-06-30T13:50:06.863714\nAccessing file number 121\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-3-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-3-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.495 sec to read coadd-3-282-20210410.fits at 2021-06-30T13:50:14.436777\nAccessing file number 122\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-1-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-1-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.899 sec to read coadd-1-282-20210410.fits at 2021-06-30T13:50:22.173392\nAccessing file number 123\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-4-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-4-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.788 sec to read coadd-4-282-20210410.fits at 2021-06-30T13:50:30.248710\nAccessing file number 124\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/coadd-5-282-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/282/20210410/zbest-5-282-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.702 sec to read coadd-5-282-20210410.fits at 2021-06-30T13:50:38.200782\nAccessing file number 125\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-6-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-6-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.679 sec to read coadd-6-228-20210410.fits at 2021-06-30T13:50:47.018194\nAccessing file number 126\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-3-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-3-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.767 sec to read coadd-3-228-20210410.fits at 2021-06-30T13:50:54.907362\nAccessing file number 127\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-3-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-3-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.468 sec to read coadd-3-228-20210410.fits at 2021-06-30T13:51:02.714419\nAccessing file number 128\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-2-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-2-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.737 sec to read coadd-2-228-20210410.fits at 2021-06-30T13:51:10.392483\nAccessing file number 129\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-2-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-2-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.474 sec to read coadd-2-228-20210410.fits at 2021-06-30T13:51:19.090634\nAccessing file number 130\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-5-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-5-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.794 sec to read coadd-5-228-20210410.fits at 2021-06-30T13:51:28.028222\nAccessing file number 131\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-0-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-0-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.645 sec to read coadd-0-228-20210410.fits at 2021-06-30T13:51:36.506414\nAccessing file number 132\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/coadd-0-228-20210410.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210410/zbest-0-228-20210410.fits\nINFO:spectra.py:261:read_spectra: iotime 0.466 sec to read coadd-0-228-20210410.fits at 2021-06-30T13:51:44.472024\nAccessing file number 133\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/42/20210412/coadd-7-42-20210412.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/42/20210412/zbest-7-42-20210412.fits\nINFO:spectra.py:261:read_spectra: iotime 0.638 sec to read coadd-7-42-20210412.fits at 2021-06-30T13:51:52.924532\nAccessing file number 134\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/42/20210412/coadd-9-42-20210412.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/42/20210412/zbest-9-42-20210412.fits\nINFO:spectra.py:261:read_spectra: iotime 0.731 sec to read coadd-9-42-20210412.fits at 2021-06-30T13:52:01.406976\nAccessing file number 135\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/coadd-4-221-20210412.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/zbest-4-221-20210412.fits\nINFO:spectra.py:261:read_spectra: iotime 0.708 sec to read coadd-4-221-20210412.fits at 2021-06-30T13:52:09.074032\nAccessing file number 136\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/coadd-4-221-20210412.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/zbest-4-221-20210412.fits\nINFO:spectra.py:261:read_spectra: iotime 0.471 sec to read coadd-4-221-20210412.fits at 2021-06-30T13:52:16.379548\nAccessing file number 137\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/coadd-4-221-20210412.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/221/20210412/zbest-4-221-20210412.fits\nINFO:spectra.py:261:read_spectra: iotime 0.429 sec to read coadd-4-221-20210412.fits at 2021-06-30T13:52:23.577258\nAccessing file number 138\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/43/20210413/coadd-1-43-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/43/20210413/zbest-1-43-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.728 sec to read coadd-1-43-20210413.fits at 2021-06-30T13:52:31.730805\nAccessing file number 139\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/coadd-1-283-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/zbest-1-283-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.727 sec to read coadd-1-283-20210413.fits at 2021-06-30T13:52:39.840943\nAccessing file number 140\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/coadd-7-283-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/zbest-7-283-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.712 sec to read coadd-7-283-20210413.fits at 2021-06-30T13:52:47.758490\nAccessing file number 141\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/coadd-8-283-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/283/20210413/zbest-8-283-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.720 sec to read coadd-8-283-20210413.fits at 2021-06-30T13:52:55.292019\nAccessing file number 142\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/coadd-7-257-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/zbest-7-257-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.779 sec to read coadd-7-257-20210413.fits at 2021-06-30T13:53:03.598213\nAccessing file number 143\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/coadd-3-257-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/zbest-3-257-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.679 sec to read coadd-3-257-20210413.fits at 2021-06-30T13:53:12.036219\nAccessing file number 144\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/coadd-2-257-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/257/20210413/zbest-2-257-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.708 sec to read coadd-2-257-20210413.fits at 2021-06-30T13:53:20.066247\nAccessing file number 145\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/277/20210413/coadd-4-277-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/277/20210413/zbest-4-277-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.723 sec to read coadd-4-277-20210413.fits at 2021-06-30T13:53:28.130957\nAccessing file number 146\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/277/20210413/coadd-4-277-20210413.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/277/20210413/zbest-4-277-20210413.fits\nINFO:spectra.py:261:read_spectra: iotime 0.471 sec to read coadd-4-277-20210413.fits at 2021-06-30T13:53:35.743529\nAccessing file number 147\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/coadd-2-284-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/zbest-2-284-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.745 sec to read coadd-2-284-20210414.fits at 2021-06-30T13:53:43.938496\nAccessing file number 148\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/coadd-0-284-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/zbest-0-284-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.678 sec to read coadd-0-284-20210414.fits at 2021-06-30T13:53:51.744106\nAccessing file number 149\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/coadd-0-284-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/zbest-0-284-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.480 sec to read coadd-0-284-20210414.fits at 2021-06-30T13:54:00.554508\nAccessing file number 150\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/coadd-0-284-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/zbest-0-284-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.563 sec to read coadd-0-284-20210414.fits at 2021-06-30T13:54:08.976099\nAccessing file number 151\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/coadd-9-284-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/284/20210414/zbest-9-284-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.784 sec to read coadd-9-284-20210414.fits at 2021-06-30T13:54:17.318877\nAccessing file number 152\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/coadd-9-258-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/zbest-9-258-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.738 sec to read coadd-9-258-20210414.fits at 2021-06-30T13:54:25.747079\nAccessing file number 153\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/coadd-4-258-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/zbest-4-258-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.730 sec to read coadd-4-258-20210414.fits at 2021-06-30T13:54:34.035224\nAccessing file number 154\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/coadd-6-258-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/zbest-6-258-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.764 sec to read coadd-6-258-20210414.fits at 2021-06-30T13:54:42.920131\nAccessing file number 155\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/coadd-7-258-20210414.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/258/20210414/zbest-7-258-20210414.fits\nINFO:spectra.py:261:read_spectra: iotime 0.821 sec to read coadd-7-258-20210414.fits at 2021-06-30T13:54:51.275678\nAccessing file number 156\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/43/20210415/coadd-1-43-20210415.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/43/20210415/zbest-1-43-20210415.fits\nINFO:spectra.py:261:read_spectra: iotime 0.749 sec to read coadd-1-43-20210415.fits at 2021-06-30T13:54:59.149613\nAccessing file number 157\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210415/coadd-4-68-20210415.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210415/zbest-4-68-20210415.fits\nINFO:spectra.py:261:read_spectra: iotime 0.670 sec to read coadd-4-68-20210415.fits at 2021-06-30T13:55:07.154219\nAccessing file number 158\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210415/coadd-8-68-20210415.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210415/zbest-8-68-20210415.fits\nINFO:spectra.py:261:read_spectra: iotime 0.665 sec to read coadd-8-68-20210415.fits at 2021-06-30T13:55:14.696673\nAccessing file number 159\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/coadd-5-59-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/zbest-5-59-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.651 sec to read coadd-5-59-20210416.fits at 2021-06-30T13:55:22.838875\nAccessing file number 160\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/coadd-5-59-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/zbest-5-59-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.425 sec to read coadd-5-59-20210416.fits at 2021-06-30T13:55:30.600359\nAccessing file number 161\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/coadd-5-59-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/zbest-5-59-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.502 sec to read coadd-5-59-20210416.fits at 2021-06-30T13:55:38.767218\nAccessing file number 162\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/coadd-5-59-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/59/20210416/zbest-5-59-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.534 sec to read coadd-5-59-20210416.fits at 2021-06-30T13:55:47.169176\nAccessing file number 163\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210416/coadd-8-68-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210416/zbest-8-68-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.712 sec to read coadd-8-68-20210416.fits at 2021-06-30T13:55:56.056285\nAccessing file number 164\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210416/coadd-4-68-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/68/20210416/zbest-4-68-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.710 sec to read coadd-4-68-20210416.fits at 2021-06-30T13:56:03.927975\nAccessing file number 165\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/coadd-1-44-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/zbest-1-44-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.627 sec to read coadd-1-44-20210416.fits at 2021-06-30T13:56:12.095906\nAccessing file number 166\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/coadd-5-44-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/zbest-5-44-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.681 sec to read coadd-5-44-20210416.fits at 2021-06-30T13:56:20.134799\nAccessing file number 167\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/coadd-6-44-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/44/20210416/zbest-6-44-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.600 sec to read coadd-6-44-20210416.fits at 2021-06-30T13:56:28.369579\nAccessing file number 168\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/222/20210416/coadd-2-222-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/222/20210416/zbest-2-222-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.766 sec to read coadd-2-222-20210416.fits at 2021-06-30T13:56:36.255307\nAccessing file number 169\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/278/20210416/coadd-9-278-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/278/20210416/zbest-9-278-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.655 sec to read coadd-9-278-20210416.fits at 2021-06-30T13:56:43.742054\nAccessing file number 170\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-6-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-6-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.657 sec to read coadd-6-228-20210416.fits at 2021-06-30T13:56:51.661587\nAccessing file number 171\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-2-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-2-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.713 sec to read coadd-2-228-20210416.fits at 2021-06-30T13:56:59.517621\nAccessing file number 172\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-2-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-2-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.381 sec to read coadd-2-228-20210416.fits at 2021-06-30T13:57:07.355972\nAccessing file number 173\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-3-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-3-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.924 sec to read coadd-3-228-20210416.fits at 2021-06-30T13:57:15.634633\nAccessing file number 174\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-3-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-3-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.423 sec to read coadd-3-228-20210416.fits at 2021-06-30T13:57:22.606728\nAccessing file number 175\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-0-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-0-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.846 sec to read coadd-0-228-20210416.fits at 2021-06-30T13:57:30.813700\nAccessing file number 176\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-0-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-0-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.451 sec to read coadd-0-228-20210416.fits at 2021-06-30T13:57:38.302820\nAccessing file number 177\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/coadd-5-228-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/228/20210416/zbest-5-228-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.743 sec to read coadd-5-228-20210416.fits at 2021-06-30T13:57:46.624195\nAccessing file number 178\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/259/20210416/coadd-1-259-20210416.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/259/20210416/zbest-1-259-20210416.fits\nINFO:spectra.py:261:read_spectra: iotime 0.692 sec to read coadd-1-259-20210416.fits at 2021-06-30T13:57:54.532217\nAccessing file number 179\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/45/20210417/coadd-7-45-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/45/20210417/zbest-7-45-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.786 sec to read coadd-7-45-20210417.fits at 2021-06-30T13:58:02.968567\nAccessing file number 180\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/45/20210417/coadd-6-45-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/45/20210417/zbest-6-45-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.684 sec to read coadd-6-45-20210417.fits at 2021-06-30T13:58:10.735652\nAccessing file number 181\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/60/20210417/coadd-8-60-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/60/20210417/zbest-8-60-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.713 sec to read coadd-8-60-20210417.fits at 2021-06-30T13:58:19.320576\nAccessing file number 182\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/60/20210417/coadd-8-60-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/60/20210417/zbest-8-60-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.464 sec to read coadd-8-60-20210417.fits at 2021-06-30T13:58:26.898531\nAccessing file number 183\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/150/20210417/coadd-8-150-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/150/20210417/zbest-8-150-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.599 sec to read coadd-8-150-20210417.fits at 2021-06-30T13:58:35.327301\nAccessing file number 184\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/coadd-4-223-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/zbest-4-223-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.651 sec to read coadd-4-223-20210417.fits at 2021-06-30T13:58:43.390517\nAccessing file number 185\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/coadd-4-223-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/zbest-4-223-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.558 sec to read coadd-4-223-20210417.fits at 2021-06-30T13:58:51.009297\nAccessing file number 186\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/coadd-4-223-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/zbest-4-223-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.536 sec to read coadd-4-223-20210417.fits at 2021-06-30T13:58:59.513464\nAccessing file number 187\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/coadd-4-223-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/223/20210417/zbest-4-223-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.463 sec to read coadd-4-223-20210417.fits at 2021-06-30T13:59:08.746434\nAccessing file number 188\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/coadd-4-229-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/zbest-4-229-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.803 sec to read coadd-4-229-20210417.fits at 2021-06-30T13:59:18.041720\nAccessing file number 189\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/coadd-5-229-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/zbest-5-229-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.835 sec to read coadd-5-229-20210417.fits at 2021-06-30T13:59:27.196694\nAccessing file number 190\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/coadd-9-229-20210417.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210417/zbest-9-229-20210417.fits\nINFO:spectra.py:261:read_spectra: iotime 0.804 sec to read coadd-9-229-20210417.fits at 2021-06-30T13:59:36.382712\nAccessing file number 191\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/150/20210418/coadd-8-150-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/150/20210418/zbest-8-150-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.847 sec to read coadd-8-150-20210418.fits at 2021-06-30T13:59:45.185156\nAccessing file number 192\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/coadd-4-229-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/zbest-4-229-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.790 sec to read coadd-4-229-20210418.fits at 2021-06-30T13:59:53.853849\nAccessing file number 193\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/coadd-9-229-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/zbest-9-229-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.799 sec to read coadd-9-229-20210418.fits at 2021-06-30T14:00:02.451596\nAccessing file number 194\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/coadd-5-229-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/229/20210418/zbest-5-229-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.780 sec to read coadd-5-229-20210418.fits at 2021-06-30T14:00:11.180129\nAccessing file number 195\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/286/20210418/coadd-1-286-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/286/20210418/zbest-1-286-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.749 sec to read coadd-1-286-20210418.fits at 2021-06-30T14:00:20.298807\nAccessing file number 196\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/260/20210418/coadd-5-260-20210418.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/260/20210418/zbest-5-260-20210418.fits\nINFO:spectra.py:261:read_spectra: iotime 0.897 sec to read coadd-5-260-20210418.fits at 2021-06-30T14:00:29.299134\nAccessing file number 197\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.871 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:00:38.352585\nAccessing file number 198\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.518 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:00:47.519408\nAccessing file number 199\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.530 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:00:55.982741\nAccessing file number 200\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.515 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:01:04.789361\nAccessing file number 201\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.436 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:01:13.368229\nAccessing file number 202\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/coadd-8-252-20210419.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/252/20210419/zbest-8-252-20210419.fits\nINFO:spectra.py:261:read_spectra: iotime 0.477 sec to read coadd-8-252-20210419.fits at 2021-06-30T14:01:21.761250\nAccessing file number 203\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/coadd-8-230-20210420.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/zbest-8-230-20210420.fits\nINFO:spectra.py:261:read_spectra: iotime 0.825 sec to read coadd-8-230-20210420.fits at 2021-06-30T14:01:31.029315\nAccessing file number 204\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/coadd-9-230-20210420.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/zbest-9-230-20210420.fits\nINFO:spectra.py:261:read_spectra: iotime 0.751 sec to read coadd-9-230-20210420.fits at 2021-06-30T14:01:40.203324\nAccessing file number 205\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/coadd-3-230-20210420.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/230/20210420/zbest-3-230-20210420.fits\nINFO:spectra.py:261:read_spectra: iotime 0.719 sec to read coadd-3-230-20210420.fits at 2021-06-30T14:01:48.876402\nAccessing file number 206\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/286/20210420/coadd-1-286-20210420.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/286/20210420/zbest-1-286-20210420.fits\nINFO:spectra.py:261:read_spectra: iotime 0.747 sec to read coadd-1-286-20210420.fits at 2021-06-30T14:01:57.327340\nAccessing file number 207\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/260/20210429/coadd-5-260-20210429.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/260/20210429/zbest-5-260-20210429.fits\nINFO:spectra.py:261:read_spectra: iotime 0.880 sec to read coadd-5-260-20210429.fits at 2021-06-30T14:02:06.323104\nAccessing file number 208\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/61/20210430/coadd-3-61-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/61/20210430/zbest-3-61-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.980 sec to read coadd-3-61-20210430.fits at 2021-06-30T14:02:15.495079\nAccessing file number 209\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/46/20210430/coadd-6-46-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/46/20210430/zbest-6-46-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.777 sec to read coadd-6-46-20210430.fits at 2021-06-30T14:02:24.091671\nAccessing file number 210\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-0-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-0-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.776 sec to read coadd-0-231-20210430.fits at 2021-06-30T14:02:32.814281\nAccessing file number 211\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-2-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-2-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.828 sec to read coadd-2-231-20210430.fits at 2021-06-30T14:02:42.449670\nAccessing file number 212\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-1-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-1-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.846 sec to read coadd-1-231-20210430.fits at 2021-06-30T14:02:51.383235\nAccessing file number 213\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-7-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-7-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.904 sec to read coadd-7-231-20210430.fits at 2021-06-30T14:03:00.564605\nAccessing file number 214\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-3-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-3-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.810 sec to read coadd-3-231-20210430.fits at 2021-06-30T14:03:09.410505\nAccessing file number 215\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/coadd-3-231-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/231/20210430/zbest-3-231-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.568 sec to read coadd-3-231-20210430.fits at 2021-06-30T14:03:18.102266\nAccessing file number 216\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/coadd-9-287-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/zbest-9-287-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.867 sec to read coadd-9-287-20210430.fits at 2021-06-30T14:03:28.424657\nAccessing file number 217\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/coadd-9-287-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/zbest-9-287-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.619 sec to read coadd-9-287-20210430.fits at 2021-06-30T14:03:37.622164\nAccessing file number 218\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/coadd-3-287-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/zbest-3-287-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.745 sec to read coadd-3-287-20210430.fits at 2021-06-30T14:03:46.837822\nAccessing file number 219\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/coadd-8-287-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/zbest-8-287-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.702 sec to read coadd-8-287-20210430.fits at 2021-06-30T14:03:55.699098\nAccessing file number 220\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/coadd-2-287-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/287/20210430/zbest-2-287-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.755 sec to read coadd-2-287-20210430.fits at 2021-06-30T14:04:04.466684\nAccessing file number 221\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-0-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-0-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.592 sec to read coadd-0-261-20210430.fits at 2021-06-30T14:04:12.697868\nAccessing file number 222\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-6-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-6-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.845 sec to read coadd-6-261-20210430.fits at 2021-06-30T14:04:21.280247\nAccessing file number 223\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-6-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-6-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.439 sec to read coadd-6-261-20210430.fits at 2021-06-30T14:04:28.679808\nAccessing file number 224\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-2-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-2-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.698 sec to read coadd-2-261-20210430.fits at 2021-06-30T14:04:36.696919\nAccessing file number 225\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-4-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-4-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.722 sec to read coadd-4-261-20210430.fits at 2021-06-30T14:04:44.872499\nAccessing file number 226\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-7-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-7-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.630 sec to read coadd-7-261-20210430.fits at 2021-06-30T14:04:52.100169\nAccessing file number 227\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-7-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-7-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.467 sec to read coadd-7-261-20210430.fits at 2021-06-30T14:05:00.163459\nAccessing file number 228\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.812 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:05:08.434963\nAccessing file number 229\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.431 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:05:16.278097\nAccessing file number 230\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.460 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:05:25.219158\nAccessing file number 231\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-2-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-2-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.500 sec to read coadd-2-261-20210430.fits at 2021-06-30T14:05:34.813217\nAccessing file number 232\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.656 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:05:44.096003\nAccessing file number 233\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.549 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:05:53.578143\nAccessing file number 234\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-8-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-8-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.517 sec to read coadd-8-261-20210430.fits at 2021-06-30T14:06:02.365153\nAccessing file number 235\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-0-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-0-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.574 sec to read coadd-0-261-20210430.fits at 2021-06-30T14:06:11.526853\nAccessing file number 236\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-4-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-4-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.695 sec to read coadd-4-261-20210430.fits at 2021-06-30T14:06:21.595849\nAccessing file number 237\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-7-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-7-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.619 sec to read coadd-7-261-20210430.fits at 2021-06-30T14:06:30.748385\nAccessing file number 238\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-7-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-7-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.559 sec to read coadd-7-261-20210430.fits at 2021-06-30T14:06:40.299854\nAccessing file number 239\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-6-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-6-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.676 sec to read coadd-6-261-20210430.fits at 2021-06-30T14:06:49.120777\nAccessing file number 240\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/coadd-6-261-20210430.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/261/20210430/zbest-6-261-20210430.fits\nINFO:spectra.py:261:read_spectra: iotime 0.545 sec to read coadd-6-261-20210430.fits at 2021-06-30T14:06:59.276587\nAccessing file number 241\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/47/20210501/coadd-6-47-20210501.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/47/20210501/zbest-6-47-20210501.fits\nINFO:spectra.py:261:read_spectra: iotime 0.909 sec to read coadd-6-47-20210501.fits at 2021-06-30T14:07:09.514228\nAccessing file number 242\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/47/20210501/coadd-5-47-20210501.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/47/20210501/zbest-5-47-20210501.fits\nINFO:spectra.py:261:read_spectra: iotime 0.946 sec to read coadd-5-47-20210501.fits at 2021-06-30T14:07:19.456868\nAccessing file number 243\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/71/20210501/coadd-5-71-20210501.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/71/20210501/zbest-5-71-20210501.fits\nINFO:spectra.py:261:read_spectra: iotime 0.787 sec to read coadd-5-71-20210501.fits at 2021-06-30T14:07:29.737038\nAccessing file number 244\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/71/20210501/coadd-9-71-20210501.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/71/20210501/zbest-9-71-20210501.fits\nINFO:spectra.py:261:read_spectra: iotime 0.771 sec to read coadd-9-71-20210501.fits at 2021-06-30T14:07:40.989445\nAccessing file number 245\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/48/20210502/coadd-6-48-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/48/20210502/zbest-6-48-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.819 sec to read coadd-6-48-20210502.fits at 2021-06-30T14:07:51.343497\nAccessing file number 246\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/48/20210502/coadd-6-48-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/48/20210502/zbest-6-48-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.534 sec to read coadd-6-48-20210502.fits at 2021-06-30T14:08:01.110038\nAccessing file number 247\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/151/20210502/coadd-2-151-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/151/20210502/zbest-2-151-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.912 sec to read coadd-2-151-20210502.fits at 2021-06-30T14:08:10.582789\nAccessing file number 248\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/151/20210502/coadd-1-151-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/151/20210502/zbest-1-151-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.784 sec to read coadd-1-151-20210502.fits at 2021-06-30T14:08:20.614689\nAccessing file number 249\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-5-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-5-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.757 sec to read coadd-5-525-20210502.fits at 2021-06-30T14:08:30.625913\nAccessing file number 250\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-3-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-3-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.800 sec to read coadd-3-525-20210502.fits at 2021-06-30T14:08:39.726518\nAccessing file number 251\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-8-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-8-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.818 sec to read coadd-8-525-20210502.fits at 2021-06-30T14:08:49.346403\nAccessing file number 252\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-0-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-0-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.836 sec to read coadd-0-525-20210502.fits at 2021-06-30T14:08:59.396137\nAccessing file number 253\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-6-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-6-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.805 sec to read coadd-6-525-20210502.fits at 2021-06-30T14:09:10.101026\nAccessing file number 254\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-5-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-5-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.598 sec to read coadd-5-525-20210502.fits at 2021-06-30T14:09:20.310699\nAccessing file number 255\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-3-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-3-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.557 sec to read coadd-3-525-20210502.fits at 2021-06-30T14:09:29.159374\nAccessing file number 256\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-8-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-8-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.417 sec to read coadd-8-525-20210502.fits at 2021-06-30T14:09:37.953992\nAccessing file number 257\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-0-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-0-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.479 sec to read coadd-0-525-20210502.fits at 2021-06-30T14:09:45.908100\nAccessing file number 258\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/coadd-6-525-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/525/20210502/zbest-6-525-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.457 sec to read coadd-6-525-20210502.fits at 2021-06-30T14:09:54.484855\nAccessing file number 259\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-8-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-8-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.729 sec to read coadd-8-288-20210502.fits at 2021-06-30T14:10:03.362689\nAccessing file number 260\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-7-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-7-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.930 sec to read coadd-7-288-20210502.fits at 2021-06-30T14:10:12.947907\nAccessing file number 261\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-9-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-9-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.871 sec to read coadd-9-288-20210502.fits at 2021-06-30T14:10:22.011313\nAccessing file number 262\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-9-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-9-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.509 sec to read coadd-9-288-20210502.fits at 2021-06-30T14:10:31.393787\nAccessing file number 263\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-9-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-9-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.407 sec to read coadd-9-288-20210502.fits at 2021-06-30T14:10:39.047762\nAccessing file number 264\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-5-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-5-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.898 sec to read coadd-5-288-20210502.fits at 2021-06-30T14:10:48.672686\nAccessing file number 265\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-2-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-2-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 1.439 sec to read coadd-2-288-20210502.fits at 2021-06-30T14:10:59.084084\nAccessing file number 266\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/coadd-2-288-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/288/20210502/zbest-2-288-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.526 sec to read coadd-2-288-20210502.fits at 2021-06-30T14:11:08.194639\nAccessing file number 267\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-1-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-1-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 1.410 sec to read coadd-1-253-20210502.fits at 2021-06-30T14:11:17.692520\nAccessing file number 268\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-1-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-1-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.590 sec to read coadd-1-253-20210502.fits at 2021-06-30T14:11:26.553859\nAccessing file number 269\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-2-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-2-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.698 sec to read coadd-2-253-20210502.fits at 2021-06-30T14:11:36.214609\nAccessing file number 270\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-6-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-6-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.684 sec to read coadd-6-253-20210502.fits at 2021-06-30T14:11:45.162230\nAccessing file number 271\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-4-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-4-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 1.387 sec to read coadd-4-253-20210502.fits at 2021-06-30T14:11:55.054483\nAccessing file number 272\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/coadd-8-253-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/253/20210502/zbest-8-253-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 2.438 sec to read coadd-8-253-20210502.fits at 2021-06-30T14:12:06.291808\nAccessing file number 273\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/coadd-8-262-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/zbest-8-262-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 2.941 sec to read coadd-8-262-20210502.fits at 2021-06-30T14:12:18.489927\nAccessing file number 274\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/coadd-8-262-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/zbest-8-262-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.593 sec to read coadd-8-262-20210502.fits at 2021-06-30T14:12:27.215978\nAccessing file number 275\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/coadd-8-262-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/zbest-8-262-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.759 sec to read coadd-8-262-20210502.fits at 2021-06-30T14:12:37.191422\nAccessing file number 276\n/global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/coadd-8-262-20210502.fits /global/project/projectdirs/desi/spectro/redux/daily/tiles/262/20210502/zbest-8-262-20210502.fits\nINFO:spectra.py:261:read_spectra: iotime 0.566 sec to read coadd-8-262-20210502.fits at 2021-06-30T14:12:45.585784\n"
],
[
"# Apply the DESITRIP preprocessing to selected spectra.\nrewave, reflux, reivar = rebin_flux(allwave, allflux, allivar, allzbest['Z'],\n minwave=2500., maxwave=9500., nbins=150,\n log=True, clip=True)\nrsflux = rescale_flux(reflux)",
"_____no_output_____"
],
[
"# Run the classifier on the spectra.\n# The output layer uses softmax activation to produce an array of label probabilities.\n# The classification is based on argmax(pred).\npred = classifier.predict(rsflux)",
"_____no_output_____"
],
[
"allflux.shape",
"_____no_output_____"
],
[
"pred.shape",
"_____no_output_____"
],
[
"ymax = np.max(pred, axis=1)\n#print(ymax)\n#handy_table.pop(0)\nprint('targetid', '(ra, dec)', 'tileid', 'obsdate', 'row - prob', sep=\", \")\nfor i in range(len(ymax)):\n print(handy_table[i], \"-\", round(ymax[i],2)) #print(handy_table)",
"targetid, (ra, dec), tileid, obsdate, row - prob\n(3.9627775677566664e+16, 'A202105271202386m003059', 180.66086203637735, -0.5165692138224015, 80662.0, 20210322) - 1.0\n(3.962779377598477e+16, 'A202105271157013p001239', 179.25560988523048, 0.21083938338370498, 80662.0, 20210322) - 0.55\n(3.9627787723605544e+16, 'A202105241154142p000516', 178.55932415934348, 0.08774781941575753, 80662.0, 20210322) - 0.98\n(3.962779380954067e+16, 'A202105241205187p001233', 181.3279471304242, 0.20924468670759178, 80662.0, 20210322) - 0.82\n(3.9627775677566664e+16, 'A202105271202386m003059', 180.66086203637735, -0.5165692138224015, 80662.0, 20210322) - 1.0\n"
],
[
"fig, ax = plt.subplots(1,1, figsize=(6,4), tight_layout=True)\nax.hist(ymax, bins=np.linspace(0,1,51))\nax.set(xlabel='$\\max{(y_\\mathrm{pred})}$',\n ylabel='count');\n #title='Tile {}, {}'.format(tile_id, obsdate));",
"_____no_output_____"
]
],
[
[
"### Selection on Classifier Output\n\nTo be conservative we can select only spectra where the classifier is very confident in its output, e.g., ymax > 0.99. See the [CNN training notebook](https://github.com/desihub/timedomain/blob/master/desitrip/docs/nb/cnn_multilabel-restframe.ipynb) for the motivation behind this cut.",
"_____no_output_____"
]
],
[
[
"idx = np.argwhere(ymax > 0.0) #0.99\nlabels = np.argmax(pred, axis=1)",
"_____no_output_____"
],
[
"idx.shape\nlabel_names = ['Galaxy',\n 'SN Ia',\n 'SN Ib',\n 'SN Ib/c',\n 'SN Ic',\n 'SN IIn',\n 'SN IIL/P',\n 'SN IIP',\n 'KN']",
"_____no_output_____"
]
],
[
[
"### Save spectra and classification to file",
"_____no_output_____"
]
],
[
[
"# Save classification info to a table.\nclassification = Table()\nclassification['TARGETID'] = allfmap[idx]['TARGETID']\nclassification['CNNPRED'] = pred[idx]\nclassification['CNNLABEL'] = label_names_arr[labels[idx]]\n\n# Merge the classification and redrock fit to the fibermap.\n#Temporary fix for candidate mismatch\nfmap = hstack([allfmap[idx], allzbest[idx], classification])\nfmap['TARGETID_1'].name='TARGETID'\nfmap.remove_columns(['TARGETID_2','TARGETID_3']) \n\n# Pack data into Spectra and write to FITS.\ncand_spectra = Spectra(bands=['brz'],\n wave={'brz' : allwave},\n flux={'brz' : allflux[idx]},\n ivar={'brz' : allivar[idx]},\n mask={'brz' : allmask[idx]},\n resolution_data={'brz' : allres[idx]},\n fibermap=fmap\n )\n\noutfits = 'DECam_transient_spectra.fits'\nwrite_spectra(outfits, cand_spectra)\nprint('Output file saved in {}'.format(outfits))\n",
"6\n"
]
],
[
[
"### GradCAM action happens here\n\nAdapting from https://keras.io/examples/vision/grad_cam/",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nlast_conv_layer_name = \"conv1d_23\"\nclassifier_layer_names = [\n\"batch_normalization_23\",\n\"activation_23\",\n\"max_pooling1d_23\",\n\"flatten_5\",\n\"dense_5\",\n\"dropout_5\",\n\"Output_Classes\"\n]",
"_____no_output_____"
],
[
"def make_gradcam_heatmap(\n img_array, model, last_conv_layer_name, classifier_layer_names\n):\n # First, we create a model that maps the input image to the activations\n # of the last conv layer\n last_conv_layer = model.get_layer(last_conv_layer_name)\n last_conv_layer_model = keras.Model(model.inputs, last_conv_layer.output)\n\n # Second, we create a model that maps the activations of the last conv\n # layer to the final class predictions\n classifier_input = keras.Input(shape=last_conv_layer.output.shape[1:])\n x = classifier_input\n for layer_name in classifier_layer_names:\n #print(layer_name,x.shape)\n x = model.get_layer(layer_name)(x)\n classifier_model = keras.Model(classifier_input, x)\n\n # Then, we compute the gradient of the top predicted class for our input image\n # with respect to the activations of the last conv layer\n with tf.GradientTape() as tape:\n # Compute activations of the last conv layer and make the tape watch it\n last_conv_layer_output = last_conv_layer_model(img_array)\n tape.watch(last_conv_layer_output)\n # Compute class predictions\n preds = classifier_model(last_conv_layer_output)\n top_pred_index = tf.argmax(preds[0])\n top_class_channel = preds[:, top_pred_index]\n\n # This is the gradient of the top predicted class with regard to\n # the output feature map of the last conv layer\n grads = tape.gradient(top_class_channel, last_conv_layer_output)\n # This is a vector where each entry is the mean intensity of the gradient\n # over a specific feature map channel\n pooled_grads = tf.reduce_mean(grads, axis=(0, 1))\n #print(grads.shape,pooled_grads.shape)\n\n # We multiply each channel in the feature map array\n # by \"how important this channel is\" with regard to the top predicted class\n last_conv_layer_output = last_conv_layer_output.numpy()[0]\n pooled_grads = pooled_grads.numpy()\n for i in range(pooled_grads.shape[-1]):\n last_conv_layer_output[:, i] *= pooled_grads[i]\n\n # The channel-wise mean of the resulting feature map\n # is our heatmap of class activation\n heatmap = np.mean(last_conv_layer_output, axis=-1)\n\n #We apply ReLU here and select only elements>0\n # For visualization purpose, we will also normalize the heatmap between 0 & 1\n heatmap = np.maximum(heatmap, 0) / np.max(heatmap)\n return heatmap",
"_____no_output_____"
]
],
[
[
"### Apply GradCAM to all spectra classified as transients\n",
"_____no_output_____"
]
],
[
[
"#allzbest = allzbest[1:] #TEMP\n#allzbest.pprint_all()\n#print(labels.shape)\n#print(labels)\n#print(rewave.shape)\n#print(rsflux.shape)",
"_____no_output_____"
],
[
"preprocess_input = keras.applications.xception.preprocess_input\ndecode_predictions = keras.applications.xception.decode_predictions\n\n# Loop over all and create a bunch of 16x16 plots\n\nfig, axes = plt.subplots(4,4, figsize=(15,10), sharex=True, sharey=True,\n gridspec_kw={'wspace':0, 'hspace':0})\n\nfor j, ax in zip(selection[:16], axes.flatten()):\n myarr=rsflux[j,:] \n #print()\n\n # Print what the top predicted class is\n preds = classifier.predict(myarr)\n #print(\"Predicted:\", preds)\n\n # Generate class activation heatmap\n heatmap = make_gradcam_heatmap(\n myarr, classifier, last_conv_layer_name, classifier_layer_names\n )\n\n color='blue'\n rewave_nbin_inblock=rewave.shape[0]/float(heatmap.shape[0])\n first_bin=0\n for i in range(1,heatmap.shape[0]+1):\n alpha=np.min([1,heatmap[i-1]+0.2])\n last_bin=int(i*rewave_nbin_inblock)\n if (i==1):\n ax.plot(rewave[first_bin:last_bin+1], myarr[0,first_bin:last_bin+1],c=color,alpha=alpha,\\\n label = str(allzbest[j[0]]['TARGETID']) + \"\\n\" +\n label_names[labels[j[0]]] + \n '\\nz={:.2f}'.format(allzbest[j[0]]['Z']) +\n '\\ntype={}'.format(allzbest[j[0]]['SPECTYPE']) +\n '\\nprob={:.2f}'.format(ymax[j[0]]))\n else:\n ax.plot(rewave[first_bin:last_bin+1], myarr[0,first_bin:last_bin+1],c=color,alpha=alpha)\n first_bin=last_bin\n ax.legend(fontsize=10)",
"_____no_output_____"
]
],
[
[
"### Plot spectra of objects classified as transients\nPlot observed spectra",
"_____no_output_____"
]
],
[
[
"testwave, testflux, testivar = rebin_flux(allwave, allflux, allivar,\n minwave=2500., maxwave=9500., nbins=150,\n log=True, clip=True)",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(4,4, figsize=(15,10), sharex=True, sharey=True,\n gridspec_kw={'wspace':0, 'hspace':0})\n\nfor j, ax in zip(selection, axes.flatten()):\n ax.plot(testwave, testflux[j[0]], alpha=0.7, label='label: '+label_names[labels[j[0]]] +# Just this for single plot with [0] on testflux, label_names, allzbest\n '\\nz={:.2f}'.format(allzbest[j[0]]['Z'])) # +\n #'\\nobsdate={}'.format(obsdates[j[0]]) +\n #'\\ntile id: {}'.format(tile_ids[j[0]]) +\n #'\\npetal id: {}'.format(petal_ids[j[0]]))\n \n ax.set(xlim=(3500,9900),ylim=(-0.1,4))\n #ax.fill_between([5600,6000],[-0.1,-0.1],[4,4],alpha=0.1,color='blue')\n #ax.fill_between([7400,7800],[-0.1,-0.1],[4,4],alpha=0.1,color='blue')\n ax.legend(fontsize=10)\n \n#for k in [0,1,2]:\n# axes[k,0].set(ylabel=r'flux [erg s$^{-1}$ cm$^{-1}$ $\\AA^{-1}$]')\n# axes[2,k].set(xlabel=r'$\\lambda_\\mathrm{obs}$ [$\\AA$]', xlim=(3500,9900))\n \nfig.tight_layout();\n#filename = \"spectra_plots/all_spectra_TAMU_ylim\"\n#plt.savefig(filename)",
"_____no_output_____"
]
],
[
[
"### For plotting individual plots",
"_____no_output_____"
]
],
[
[
"# Save to FITS files rather than PNG, see cnn_classify_data.py\n# See line 404 - 430, 'Save Classification info to file'\n#https://github.com/desihub/timedomain/blob/ab7257a4ed232875f5769cbb11c21f483ceccc5e/cronjobs/cnn_classify_data.py#L404\n\nfor j in selection:\n plt.plot(testwave, testflux[j[0]], alpha=0.7, label='label: '+ label_names[labels[j[0]]] + # Just this for single plot with [0] on testflux, label_names, allzbest\n #'\\nz={:.2f}'.format(allzbest[j[0]]['Z']) +\n '\\nprob={:.2f}'.format(ymax[j[0]]))\n #'\\nobsdate={}'.format(obsdates[j[0]]) +\n #'\\ntile id: {}'.format(tile_ids[j[0]]) +\n #'\\npetal id: {}'.format(petal_ids[j[0]]))\n \n plt.xlim(3500, 9900)\n #plt.ylim(-0.1, 50)\n #ax.fill_between([5600,6000],[-0.1,-0.1],[4,4],alpha=0.1,color='blue')\n #ax.fill_between([7400,7800],[-0.1,-0.1],[4,4],alpha=0.1,color='blue')\n plt.legend(fontsize=10)\n filename = \"spectra_plots/\"+\"_\".join((\"TAMU\", \"spectra\", str(allzbest[j[0]]['TARGETID']), str(obsdates[j[0]]), str(tile_ids[j[0]]), str(petal_ids[j[0]]), label_names[labels[j[0]]].replace(\" \", \"-\").replace(\"/\",\"-\")))\n #filename = \"spectra_plots/\"+\"_\".join((\"TAMU\", \"spectra\", str(obsdates[j[0]+1]), str(tile_ids[j[0]+1]), str(petal_ids[j[0]+1]), label_names[labels[j[0]]].replace(\" \", \"-\"))) # temp\n #plt.show();\n #print(filename)\n plt.savefig(filename)\n plt.clf()\n \n#for k in [0,1,2]:\n# axes[k,0].set(ylabel=r'flux [erg s$^{-1}$ cm$^{-1}$ $\\AA^{-1}$]')\n# axes[2,k].set(xlabel=r'$\\lambda_\\mathrm{obs}$ [$\\AA$]', xlim=(3500,9900))\n \n#fig.tight_layout();\n#filename = \"spectra_plots/all_spectra_TAMU_ylim\"\n#filename = \"_\".join((\"spectra\", str(obsdate), str(tile_id), label_names[labels[0]].replace(\" \", \"-\")))\n#plt.savefig(filename)",
"_____no_output_____"
]
],
[
[
"### Reading files in parallel\n\nDoes not work",
"_____no_output_____"
]
],
[
[
"# Loop through zbest and coadd files for each petal.\n# Extract the fibermaps, ZBEST tables, and spectra.\n# Keep only BGS targets passing basic event selection.\nallzbest = None\nallfmap = None\nallwave = None\nallflux = None\nallivar = None\nallmask = None\nallres = None\nhandy_table = []\n\nfrom joblib import Parallel, delayed\n\nnjobs=40\ncolor_string = 'brz'\n\ndef get_spectra(cafile, zbfile,targetid,tamuid,obsdate,tileid): \n # Access data per petal.\n print(\"Accessing file number \",count)\n print(cafile,zbfile)\n zbest = Table.read(zbfile, 'ZBEST')\n idx_zbest = (zbest['TARGETID']==targetid)\n targetids = zbest[idx_zbest]['TARGETID']\n chi2 = zbest[idx_zbest]['CHI2']\n \n pspectra = read_spectra(cafile)\n if obsdate>20210503:\n select_nite = pspectra.fibermap['NIGHT'] == obsdate\n pspectra = pspectra[select_nite]\n cspectra = coadd_cameras(pspectra)\n \n fibermap = cspectra.fibermap\n idx_fibermap = (fibermap['TARGETID'] == targetid)\n \n ra = fibermap[idx_fibermap]['TARGET_RA'][0]\n dec = fibermap[idx_fibermap]['TARGET_DEC'][0]\n \n return allzbest,allfmap, allwave, allflux, allivar, allmask, allres\n\n \nallzbest,allfmap, allwave, allflux, allivar, allmask, allres = \\\n Parallel(n_jobs=njobs)(delayed(get_spectra)(cafile, zbfile,targetid,tamuid,obsdate,tileid) \\\n for cafile, zbfile,targetid,tamuid,obsdate,tileid in zip(cafiles, zbfiles, target_ids,tamuids, obsdates,tile_ids)) \n\n",
"_____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",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb08b9e970ac542f29370412252f081445ebc3cf | 457,313 | ipynb | Jupyter Notebook | Code/Sentiment-Analysis.ipynb | jerielizabeth/REL560-SDA-Periodicals | 4782b37f27345095d4fe475c2d3b8285db458d4d | [
"MIT"
] | null | null | null | Code/Sentiment-Analysis.ipynb | jerielizabeth/REL560-SDA-Periodicals | 4782b37f27345095d4fe475c2d3b8285db458d4d | [
"MIT"
] | null | null | null | Code/Sentiment-Analysis.ipynb | jerielizabeth/REL560-SDA-Periodicals | 4782b37f27345095d4fe475c2d3b8285db458d4d | [
"MIT"
] | null | null | null | 127.991324 | 45,232 | 0.696296 | [
[
[
"!pip install vaderSentiment",
"Requirement already satisfied: vaderSentiment in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (3.3.2)\nRequirement already satisfied: requests in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from vaderSentiment) (2.26.0)\nRequirement already satisfied: idna<4,>=2.5 in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from requests->vaderSentiment) (3.2)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from requests->vaderSentiment) (1.26.7)\nRequirement already satisfied: certifi>=2017.4.17 in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from requests->vaderSentiment) (2021.10.8)\nRequirement already satisfied: charset-normalizer~=2.0.0 in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from requests->vaderSentiment) (2.0.4)\n"
],
[
"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\n# Initialize VADER so we can use it later\nsentimentAnalyser = SentimentIntensityAnalyzer()",
"_____no_output_____"
],
[
"import pandas as pd\npd.options.display.max_colwidth = 400",
"_____no_output_____"
],
[
"# Read in text file\ntext = open(\"../Data/Periodical-text-files-single-pages/AmSn18860101-V01-01-page-1.txt\").read()\n# Replace line breaks with spaces\ntext = text.replace('\\n', ' ')",
"_____no_output_____"
],
[
"!pip install nltk",
"Requirement already satisfied: nltk in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (3.6.5)\r\nRequirement already satisfied: click in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from nltk) (8.0.3)\r\nRequirement already satisfied: joblib in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from nltk) (1.1.0)\r\nRequirement already satisfied: regex>=2021.8.3 in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from nltk) (2021.8.3)\r\nRequirement already satisfied: tqdm in /Users/jacobbarrett/opt/anaconda3/lib/python3.9/site-packages (from nltk) (4.62.3)\r\n"
],
[
"import nltk\nnltk.download('punkt')",
"[nltk_data] Downloading package punkt to\n[nltk_data] /Users/jacobbarrett/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n"
],
[
"nltk.sent_tokenize(text)",
"_____no_output_____"
],
[
"for number, sentence in enumerate(nltk.sent_tokenize(text)):\n print(number, sentence)",
"0 \" Corrupted freemen are the worst of slaves.\"\n1 VOLUME 1.\n2 OAKLAND, CALIFORNIA, JANUARY, 1886.\n3 NUMBER 1.\n4 Entered at the Post-office in Oakland.\n5 \"A Christian Nation.\"\n6 THE idea which is advocated by some, that this may be made a Christian nation by simply making a change in the Constitution, was thus pertinently commented upon by the Janesville, Wis., Gazette:Š \" But independent of the question as to what extent we are a Christian nation, it may well be doubted whether, if the gentlemen wile .are agitating this question should succeed, they would not do society a very great injury.\n7 Such measures aro but the initiatory steps which ul-timately lead to restrictions of religious freedom, and to committing the Government to meas-ures which are as foreign to its powers and purposes as would be its action if it should undertake to determine a disputed question of theology.\"\n8 An Unprofitable Alliance.\n9 IN regard to the supposed benefit of the church by State patronage, or an alliance be-tween the Church and the State, Lord Macaulay speaks as follows.\n10 These words are worthy of careful consideration:Š \"The ark of God was never taken till it was surrounded by the arms of earthly defenders.\n11 In captivity, its sanctity Was sufficient to vindi-cate it from insult, and to lay the hostile fiend prostrate on the threshold of his own temple.\n12 The real security of Christianity is to be found in its Ł benevolent morality, in its exquisite adaptation to the human heart, in the facility with which its scheme accommodates itself to the capacity of every human intellect, in the consolation which it bears to theŁ house of mourning, in the light with which it brightens the great mystery of the grave.\n13 To such a system it can bring no addition of dignity or of strength, that it is part and parcel of the com-mon law.\n14 \"The whole history of Christianity shows, that she is in far greater danger of being cor-rupted by the alliance of power, than of being crushed by its opposition.\n15 Those who thrust temporal sovereignty upon her treat her as their prototypes treated her author.\n16 They bow the knee, and spit upon her; they cry,\" Hail I \" and smite her on the cheek; they put a scepter in her hand, but it is a fragile reed; they crown her, but it is with thorns; they cover with pur-ple the wounds which their own hands have in-flicted on her; and inscribe magnificent titles over the cross on which they have fixed her to perish in ignominy and pain\".ŠEssay on Southey's Colloquies.\n17 The American Sentinel.\n18 IT is well known that there is a large and influential association in the United States, bear-ing the name of the \"National Reform Associ-ation.\"\n19 It is popularly known as the \"Religious Amendment Party,\" because it is endeavoring to secure a religious amendment to the Consti-tution of the United States.\n20 As stated by the world, its object is \"to put God in the Constitu-tion.\"\n21 According to its own avowal its aim is to procureŠ \"Such an amendment to the Constitution of the United States (or its preamble) as will suitably acknowledge Almighty God as the author of the nation's existence, and the ulti-mate source of its authority, Jesus Christ as its.\n22 Ruler, and the Bible as the supreme rule of its conduct, and thus indicate that this is a Chris-tian nation, and place all Christian laws, insti-tutions, and usages, on an undeniable legal basis in the fundamental law of the land.\"\n23 The president of .this association is Hon.\n24 Felix R. Brunot, who has held that position almost from its origin.\n25 Its present list of vice-presidents, to the number of two hundred, embraces bishops of churches, judges in the highest courts in the land, governors, and repre- sentative men in various secular positions, pres- idents of colleges, doctors of divinity, and professors of theology in large numbers.\n26 In fact there is no other association in the land which can boast such an array of names of eminent and influential men.\n27 It employs its agents and lecturers, who are presenting their cause to the churches and to the people, and who almost everywhere report unbounded suc-cess in their efforts.\n28 It has also a paper, the Christian Statesman, as its organ to advocate its cause.\n29 While there are many people in the land who are opposed to, or look with suspicion upon, the movements of this party, there is no paper pub-lished in the United States, which has for its distinct object the vindication of the rights of American citizens, which, we solemnly believe, are threatened by the actions and aims of this association.\n30 That light may be disseminated on this subject, we have commenced the publi- cation of THE AMERICAN SENTINEL.\n31 That such a paper as this is needed, we think we can make apparent to every individual who will read our paper, who will hold prejudice in abeyance, and examine our reasons with candor.\n32 While so many really think they are doing God service in their efforts to change the form of our Government, and we are willing to give them credit for thinking so, we are aware that they will look with disfavor upon our work; and some, who do not understand our motives or our reasons, will be ready to class us, and all who indorse our positions, with the base of the earth, assuming that we are striking at the foundations of morality and religion.\n33 But they are much mistaken in their estimate.\n34 We promise to do or say nothing against the plainest principles of morality and religion.\n35 So far from that, we shall try to set before our readers the true relation of morality and religion, and show that this relation is not correctly pre-sented by this \"amendment party.\"\n36 But the objector will say: \" There can be no harm in recognizing Jesus Christ as the Ruler of the nation, and his laws as the rule of our lives.\"\n37 We know that this plea is plausibleŠwe may say it is taking with nearly all religious people.\n38 Yet it is specious; plausible in the eyes of those only who have not examined the subject in its bearings, or have not traced the end to which it necessarily leads.\n39 Let us notice some of the things which must attend the suc-cess of their efforts, and some principles bearing on the subject:- 1.\n40 The Constitution of the United States must be so amended as to permit laws to be made which shall legalize the laws and institutions of Christianity, or of that which they may claim is Christianity.\n41 They ask that these laws, in- stitutions, and usages shall be \"put on a legal basis.\"\n42 Of course to be put on a legal basis they must be made matters of legal enforce-ment.\n43 That this is the object of that associa tion, real and avowed, we promise to clearly show.\n44 2.\n45 To carry this amendment into effect, any person who refuses to obey the laws and usages of Christianity must be subjected to penalties for his neglect or disobedience.\n46 As no law can exist without a penalty, no institutions or usages can be placed on a legal basis without author-izing penalties for their enforcement.\n47 This is undeniable.\n48 3.\n49 A person can be convicted of a misde-meanor only before a court of justice, on the text of the law and the hearing of evidence.\n50 4.\n51 The court is necessarily constituted the judge and exponent of the law; and, therefore, if disagreement arises as to the meaning of the law, or as to what constitutes a misdemeanor in the premises, the court is the authority, and the sole authority, to which appeal must be made.\n52 5.\n53 And, therefore, if a question arises as to what is or what is not Christian law, usage, or institution, it must be determined by a court of justice!\n54 Or, if it be said that it need not be left to the decision of a civil court, but such ques-tions may be referred to an ecclesiastical court, Ł -11e An2eFieal2 Betio e1.\n55 PUBLIBIIED MONTHLY, TIIB PACIFIC PRESS PUBLISHING COMPANY, OAKLAND, CAL.\n"
],
[
"# Break text into sentences\nsentences = nltk.sent_tokenize(text)\n\n# Make empty list\nsentence_scores = []\n# Get each sentence and sentence number, which is what enumerate does\nfor number, sentence in enumerate(sentences):\n # Use VADER to calculate sentiment\n scores = sentimentAnalyser.polarity_scores(sentence)\n # Make dictionary and append it to the previously empty list\n sentence_scores.append({'sentence': sentence, 'sentence_number': number+1, 'sentiment_score': scores['compound']})",
"_____no_output_____"
],
[
"pd.DataFrame(sentence_scores)",
"_____no_output_____"
],
[
"# Assign DataFrame to variable red_df\nAmSn18860101_V01_01_page_1_df = pd.DataFrame(sentence_scores)\n\n# Sort by the column \"sentiment_score\" and slice for first 10 values\nAmSn18860101_V01_01_page_1_df.sort_values(by='sentiment_score')[:10]",
"_____no_output_____"
],
[
"# Sort by the column \"sentiment_score,\" this time in descending order, and slice for first 10 values\nAmSn18860101_V01_01_page_1_df.sort_values(by='sentiment_score', ascending=False)[:10]",
"_____no_output_____"
],
[
"AmSn18860101_V01_01_page_1_df['sentiment_score'].plot();",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nax = AmSn18860101_V01_01_page_1_df['sentiment_score'].plot(x='sentence_number', y='sentiment_score', kind='line',\n figsize=(10,5), rot=90, title='Sentiment in \"AmSn18860101-V01-01-page-1\"')\n\n# Plot a horizontal line at 0\nplt.axhline(y=0, color='orange', linestyle='-');",
"_____no_output_____"
],
[
"# Get averages for a rolling window, then plot\nAmSn18860101_V01_01_page_1_df.rolling(5)['sentiment_score'].mean().plot(x='sentence_number', y='sentiment_score', kind='line',\n figsize=(10,5), rot=90, title='Sentiment in \"AmSn18860101-V01-01-page-1\"')\n\n# Plot a horizontal line at 0\nplt.axhline(y=0, color='orange', linestyle='-');",
"_____no_output_____"
],
[
"#Time to create a loop and do it with all of the documents",
"_____no_output_____"
],
[
"with open(\"../Data/Periodical-topic-model-output/top_doc_list.txt\", \"r\") as f:\n pope_docs = f.read().split(\"\\n\")",
"_____no_output_____"
],
[
"pope_docs",
"_____no_output_____"
],
[
"directory = \"../Data/Periodical-text-files-single-pages/\"",
"_____no_output_____"
],
[
"import os\n# Make empty list\nsentence_scores = []\n\nfor doc in pope_docs[:-1]:\n text = open(os.path.join(directory, f\"{doc}.txt\")).read()\n # Replace line breaks with spaces\n text = text.replace('\\n', ' ')\n # Break text into sentences\n sentences = nltk.sent_tokenize(text)\n\n\n # Get each sentence and sentence number, which is what enumerate does\n for number, sentence in enumerate(sentences):\n # Use VADER to calculate sentiment\n scores = sentimentAnalyser.polarity_scores(sentence)\n # Make dictionary and append it to the previously empty list\n sentence_scores.append({'sentence': sentence, 'sentence_number': number+1, 'sentiment_score': scores['compound'], 'doc_id': doc})",
"_____no_output_____"
],
[
"sentence_scores",
"_____no_output_____"
],
[
"# Assign DataFrame to variable red_df\npope_docs_df = pd.DataFrame(sentence_scores)\n\n# Sort by the column \"sentiment_score\" and slice for first 10 values\npope_docs_df.sort_values(by='sentiment_score')[:10]",
"_____no_output_____"
],
[
"# Sort by the column \"sentiment_score,\" this time in descending order, and slice for first 10 values\npope_docs_df.sort_values(by='sentiment_score', ascending=False)[:10]",
"_____no_output_____"
],
[
"pope_docs_df[pope_docs_df[\"doc_id\"]==\"SOL19030212-V18-07-page-13\"]",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"# Adjust the display settings to see more rows\npd.options.display.max_rows = 100",
"_____no_output_____"
],
[
"pope_docs_df",
"_____no_output_____"
],
[
"pope_docs_df.dtypes",
"_____no_output_____"
],
[
"pope_docs_total_df = pope_docs_df.groupby('doc_id')['sentiment_score'].mean()",
"_____no_output_____"
],
[
"pope_docs_total_df\n\nfinal_pope_docs_df = pope_docs_total_df.sort_values(ascending=False)\n\nfinal_pope_docs_df\n\n#It would be really cool to figure out how to sort this but Stack Overflow did not help me SOS",
"_____no_output_____"
],
[
"final_pope_docs_sorted_df = pd.DataFrame({'doc_id':final_pope_docs_df.index, 'sentiment_score':final_pope_docs_df.values})",
"_____no_output_____"
],
[
"# Read in text file\ntext = open(\"../Data/Periodical-text-files-single-pages/SOL19030212-V18-07-page-13.txt\").read()\n# Replace line breaks with spaces\ntext = text.replace('\\n', ' ')",
"_____no_output_____"
],
[
"nltk.sent_tokenize(text)",
"_____no_output_____"
],
[
"for number, sentence in enumerate(nltk.sent_tokenize(text)):\n print(number, sentence)",
"0 THE SUPREMACY OF THE PAPACY 109 While the council had been disposing of John, ambassadors from Gregory XII.\n1 had arrived.\n2 They were sent by Gregory \" to resign the pontificate in his name, and all right and title to that .\n3 dignity.\"\n4 But they came not to the council: Pope Gregory XII.\n5 would not recognize the legitimacy of a council convened by Pope John XXIII.\n6 Therefore, these messen-gers were commissioned to the emperor, and were empowered to treat with him.\n7 They were directed to inform the em-peror that if he and the heads of the na-tions would allow the council to be con-voked anew by Pope Gregory XII., then Pope Gregory XII.\n8 would recognize it as lawful council, but not otherwise.\n9 To this the emperor and the heads of the na-tions agreed.\n10 Accordingly, at the fourteenth session, July 4, 1415, one of Gregory's nuncios took the chair, and from Gregory read two bulls : the one convoking the Council of Constance, and, when thus convoked, owning it as a lawful council: the other empowering this nuncio to act as Pope Gregory's proxy, and, in that character, to submit to the decisions of the council when lawfully convoked as Gregory's council.\n11 When the bulls had been thus read, the council was declared convoked in the name of Pope Gregory XII.\n12 Then the proxy announced to the council that.\n13 Gregory XII.\n14 was ready to sacrifice his dignity to the peace of the Church, and to submit to their disposal of him as they should see.\n15 fit.\n16 Then the regular president of the coun-cil took the chair, and the emperor his throne.\n17 A third bull from Gregory was then read, giving his proxy full power to resign the papal dignity in his name.\n18 Then the renunciation of Gregory was made by the proxy in the following words : I. Charles Malatesta, vicar of Rimini, gov-ernor of Romagna for our most holy father in Christ Lord Pope, Gregory XII., and general of the holy Roman Church, being authorized by the full power that has just now been read, and has been received by me from our said Lord Pope Gregory, compelled by no violence, but only animated with an ardent desire of procuring the peace and union of the Church, do, in the name of the Father, Son, and Holy Ghost, effectually and really renounce for my master Pope Gregory XII.\n19 the possession of, and all right and title to, the papacy, which he legally enjoys, and do actually resign it in the piesence of our Lord Jesus Christ, and of this general council, which represents the Roman Church and the Church Universal.\n20 This act of resignation of Pope Greg-ory XII.\n21 was received with thunderous applause by the council.\n22 The Te Deum was sung, and mighty commendations were bestowed upon Gregory.\n23 Then the council decreed that Benedict XIII.\n24 Łshould be required in like manner to re-sign within ten days after he received the notice of the council ; and that if he did not resign within that time, he should be declared \" a notorious schismatic, and an obstinate and incorrigible heretic; and as such be deprived of all honor and dig-nity, and cast out of the Church.\"\n25 Ł The council next decreed that Gregory \" should retain the dignity of cardinal-bishop so long as he lived ; that he should be first in rank after the pope, unless some alteration should be judged expe-dient, with respect to this article, upon the resignation of Peter de Luna ; and that he should be perpetual legate of the Marches of Ancona, and enjoy undis-turbed all the honors, privileges, and emoluments annexed to that dignity.\n26 The council granted him besides a full and unlimited absolution from all the ir-regularities he might have been guilty of during his pontificate, exempted him from giving an account of his past con-duct, or any part of it, to any person whatever, and forbade any to be raised to the pontificate till they had promised upon oath to observe this decree, not-withstanding all the canons, constitu-\n"
],
[
"# Break text into sentences\nsentences = nltk.sent_tokenize(text)\n\n# Make empty list\nsentence_scores = []\n# Get each sentence and sentence number, which is what enumerate does\nfor number, sentence in enumerate(sentences):\n # Use VADER to calculate sentiment\n scores = sentimentAnalyser.polarity_scores(sentence)\n # Make dictionary and append it to the previously empty list\n sentence_scores.append({'sentence': sentence, 'sentence_number': number+1, 'sentiment_score': scores['compound']})",
"_____no_output_____"
],
[
"pd.DataFrame(sentence_scores)",
"_____no_output_____"
],
[
"# Assign DataFrame to variable red_df\nSOL19030212_V18_07_page_13_df = pd.DataFrame(sentence_scores)",
"_____no_output_____"
],
[
"SOL19030212_V18_07_page_13_df['sentiment_score'].plot();",
"_____no_output_____"
],
[
"ax = SOL19030212_V18_07_page_13_df['sentiment_score'].plot(x='sentence_number', y='sentiment_score', kind='line',\n figsize=(10,5), rot=90, title='Sentiment in SOL19030212-V18-07-page-13')\n\n# Plot a horizontal line at 0\nplt.axhline(y=0, color='orange', linestyle='-');",
"_____no_output_____"
],
[
"# Get averages for a rolling window, then plot\nSOL19030212_V18_07_page_13_df.rolling(5)['sentiment_score'].mean().plot(x='sentence_number', y='sentiment_score', kind='line',\n figsize=(10,5), rot=90, title='Sentiment in \"Sentiment in SOL19030212-V18-07-page-13\"')\n\n# Plot a horizontal line at 0\nplt.axhline(y=0, color='orange', linestyle='-');",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb08bb181fb6235586dabf615eeb0215eb4df198 | 150,590 | ipynb | Jupyter Notebook | Data_Science/Matplotlib/3D/3D_Superficie.ipynb | maledicente/cursos | 00ace48da7e48b04485e4ca97b3ca9ba5f33a283 | [
"MIT"
] | 1 | 2021-05-03T22:59:38.000Z | 2021-05-03T22:59:38.000Z | Data_Science/Matplotlib/3D/3D_Superficie.ipynb | maledicente/cursos | 00ace48da7e48b04485e4ca97b3ca9ba5f33a283 | [
"MIT"
] | null | null | null | Data_Science/Matplotlib/3D/3D_Superficie.ipynb | maledicente/cursos | 00ace48da7e48b04485e4ca97b3ca9ba5f33a283 | [
"MIT"
] | null | null | null | 649.094828 | 61,088 | 0.955183 | [
[
[
"# Matplotlib - Gráfico de superfície 3D",
"_____no_output_____"
],
[
"* Criando gráficos de scatter 3D com a biblioteca MatPlotLib\n",
"_____no_output_____"
],
[
"* Importando bibliotecas",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"* Criando variáveis X e Y",
"_____no_output_____"
]
],
[
[
"X = np.linspace(-5,5,11)\nY = np.linspace(-5,5,11)",
"_____no_output_____"
]
],
[
[
"* Convertendo variáveis X e Y para malha",
"_____no_output_____"
]
],
[
[
"X, Y = np.meshgrid(X, Y)",
"_____no_output_____"
]
],
[
[
"* Criando variável Z",
"_____no_output_____"
]
],
[
[
"Z = X**2 + Y**2",
"_____no_output_____"
]
],
[
[
"* Gráfico 3D",
"_____no_output_____"
]
],
[
[
"from matplotlib import cm\nfrom mpl_toolkits.mplot3d import axes3d",
"_____no_output_____"
],
[
"fig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(X,Y,Z)\nax.set_xlabel('Eixo X')\nax.set_ylabel('Eixo Y')\nax.set_zlabel('Eixo Z')\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"* Usando mapa de cores",
"_____no_output_____"
]
],
[
[
"fig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(X,Y,Z, cmap=cm.coolwarm, antialiased=False)\nax.set_xlabel('Eixo X')\nax.set_ylabel('Eixo Y')\nax.set_zlabel('Eixo Z')\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"* Barra de cores",
"_____no_output_____"
]
],
[
[
"fig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, antialiased=False)\nax.set_xlabel('Eixo X')\nax.set_ylabel('Eixo Y')\nax.set_zlabel('Eixo Z')\nfig.colorbar(surf, shrink=0.5, aspect=5)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb08ca62c6e3921ecf79b3ea8b17fd4d87c4d67e | 273,817 | ipynb | Jupyter Notebook | matrix_factorization/04 - LambdaRank.ipynb | Howl24/fs-ranking-prediction | 8570d2c77d1eff9962fda9e8a7ebf48f8a343c84 | [
"MIT"
] | 5 | 2018-09-05T16:31:56.000Z | 2020-04-13T13:45:57.000Z | matrix_factorization/04 - LambdaRank.ipynb | Howl24/fs-ranking-prediction | 8570d2c77d1eff9962fda9e8a7ebf48f8a343c84 | [
"MIT"
] | null | null | null | matrix_factorization/04 - LambdaRank.ipynb | Howl24/fs-ranking-prediction | 8570d2c77d1eff9962fda9e8a7ebf48f8a343c84 | [
"MIT"
] | 1 | 2020-02-15T06:44:51.000Z | 2020-02-15T06:44:51.000Z | 131.327098 | 129,532 | 0.736061 | [
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport os\nimport numpy as np, pandas as pd\nimport matplotlib.pyplot as plt, seaborn as sns\nfrom tqdm import tqdm, tqdm_notebook\nfrom pathlib import Path\n# pd.set_option('display.max_columns', 1000)\n# pd.set_option('display.max_rows', 400)\nsns.set()\n\nos.chdir('..')",
"_____no_output_____"
],
[
"from sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom project.ranker.ranker import RankingPredictor",
"_____no_output_____"
],
[
"%%time\nrp = Pipeline([\n ('scale', StandardScaler()),\n ('estimator', RankingPredictor(\"ma_100\", n_neighbors=15)),\n])\ndf_mf, df_rank, df_scores, df_fold_scores = rp.named_steps['estimator'].get_data()",
"CPU times: user 54.9 s, sys: 3.67 s, total: 58.5 s\nWall time: 58.3 s\n"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, _, y_train, _, y_scores_train, _ = train_test_split(df_mf.values,\n df_rank.values,\n df_scores.values,\n test_size=0)\nX_train.shape, y_train.shape",
"_____no_output_____"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nparams = {'objective': 'lambdarank', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.2977 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0370 | Val_ACCLoss: 0.0682 | Trn_NDCG: 0.7352 | Val_NDCG: 0.7133\nFold 2 | #Est: 6 | Trn_Spearman: 0.3516 | Val_Spearman: 0.2408 | Trn_ACCLoss: 0.0152 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.7980 | Val_NDCG: 0.5778\nFold 3 | #Est: 24 | Trn_Spearman: 0.4100 | Val_Spearman: 0.2582 | Trn_ACCLoss: 0.0124 | Val_ACCLoss: 0.0797 | Trn_NDCG: 0.8507 | Val_NDCG: 0.5944\nFold 4 | #Est: 3 | Trn_Spearman: 0.3758 | Val_Spearman: 0.0321 | Trn_ACCLoss: 0.0202 | Val_ACCLoss: 0.0715 | Trn_NDCG: 0.7622 | Val_NDCG: 0.5557\nFold 5 | #Est: 23 | Trn_Spearman: 0.4199 | Val_Spearman: 0.0513 | Trn_ACCLoss: 0.0098 | Val_ACCLoss: 0.1202 | Trn_NDCG: 0.8485 | Val_NDCG: 0.5623\nFold 6 | #Est: 23 | Trn_Spearman: 0.4028 | Val_Spearman: 0.1877 | Trn_ACCLoss: 0.0153 | Val_ACCLoss: 0.0274 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6443\nFold 7 | #Est: 98 | Trn_Spearman: 0.4237 | Val_Spearman: -0.0339 | Trn_ACCLoss: 0.0053 | Val_ACCLoss: 0.0589 | Trn_NDCG: 0.8892 | Val_NDCG: 0.6646\nFold 8 | #Est: 52 | Trn_Spearman: 0.4716 | Val_Spearman: 0.1035 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.8511 | Val_NDCG: 0.6041\nFold 9 | #Est: 7 | Trn_Spearman: 0.3647 | Val_Spearman: 0.1749 | Trn_ACCLoss: 0.0257 | Val_ACCLoss: 0.0741 | Trn_NDCG: 0.7735 | Val_NDCG: 0.6904\nFold 10 | #Est: 32 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.0822 | Trn_NDCG: 0.8327 | Val_NDCG: 0.6078\nFold 11 | #Est: 75 | Trn_Spearman: 0.4180 | Val_Spearman: 0.0623 | Trn_ACCLoss: 0.0025 | Val_ACCLoss: 0.0993 | Trn_NDCG: 0.8924 | Val_NDCG: 0.6075\nFold 12 | #Est: 55 | Trn_Spearman: 0.4494 | Val_Spearman: -0.0412 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.1466 | Trn_NDCG: 0.8528 | Val_NDCG: 0.4944\nFold 13 | #Est: 31 | Trn_Spearman: 0.4381 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0234 | Trn_NDCG: 0.8155 | Val_NDCG: 0.7176\nFold 14 | #Est: 4 | Trn_Spearman: 0.3779 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0285 | Val_ACCLoss: 0.1033 | Trn_NDCG: 0.7459 | Val_NDCG: 0.5450\nFold 15 | #Est: 3 | Trn_Spearman: 0.3799 | Val_Spearman: -0.0696 | Trn_ACCLoss: 0.0344 | Val_ACCLoss: 0.0624 | Trn_NDCG: 0.7565 | Val_NDCG: 0.5779\nFold 16 | #Est: 1 | Trn_Spearman: 0.1842 | Val_Spearman: -0.1969 | Trn_ACCLoss: 0.0824 | Val_ACCLoss: 0.1143 | Trn_NDCG: 0.6376 | Val_NDCG: 0.6499\nFold 17 | #Est: 1 | Trn_Spearman: 0.2285 | Val_Spearman: 0.0998 | Trn_ACCLoss: 0.0586 | Val_ACCLoss: 0.1439 | Trn_NDCG: 0.6725 | Val_NDCG: 0.6038\nFold 18 | #Est: 6 | Trn_Spearman: 0.4104 | Val_Spearman: 0.4011 | Trn_ACCLoss: 0.0160 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8123 | Val_NDCG: 0.7021\nFold 19 | #Est: 40 | Trn_Spearman: 0.3539 | Val_Spearman: 0.4277 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.0647 | Trn_NDCG: 0.8295 | Val_NDCG: 0.7018\nFold 20 | #Est: 9 | Trn_Spearman: 0.3601 | Val_Spearman: 0.0476 | Trn_ACCLoss: 0.0262 | Val_ACCLoss: 0.0706 | Trn_NDCG: 0.7186 | Val_NDCG: 0.6437\n\nTrn_Spearman: 0.3754 +/-0.0685 | Val_Spearman: 0.1151 +/-0.1560\nTrn_ACCLoss: 0.0221 +/-0.0189 | Val_ACCLoss: 0.0799 +/-0.0321\nTrn_NDCG: 0.7944 +/-0.0667 | Val_NDCG: 0.6229 +/-0.0610\n\nCPU times: user 33.1 s, sys: 132 ms, total: 33.2 s\nWall time: 3.97 s\n"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=10, random_state=42)\nparams = {'objective': 'lambdarank', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.2977 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0370 | Val_ACCLoss: 0.0682 | Trn_NDCG: 0.7352 | Val_NDCG: 0.7133\nFold 2 | #Est: 6 | Trn_Spearman: 0.3516 | Val_Spearman: 0.2408 | Trn_ACCLoss: 0.0152 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.7980 | Val_NDCG: 0.5778\nFold 3 | #Est: 24 | Trn_Spearman: 0.4100 | Val_Spearman: 0.2582 | Trn_ACCLoss: 0.0124 | Val_ACCLoss: 0.0797 | Trn_NDCG: 0.8507 | Val_NDCG: 0.5944\nFold 4 | #Est: 3 | Trn_Spearman: 0.3758 | Val_Spearman: 0.0321 | Trn_ACCLoss: 0.0202 | Val_ACCLoss: 0.0715 | Trn_NDCG: 0.7622 | Val_NDCG: 0.5557\nFold 5 | #Est: 23 | Trn_Spearman: 0.4199 | Val_Spearman: 0.0513 | Trn_ACCLoss: 0.0098 | Val_ACCLoss: 0.1202 | Trn_NDCG: 0.8485 | Val_NDCG: 0.5623\nFold 6 | #Est: 23 | Trn_Spearman: 0.4028 | Val_Spearman: 0.1877 | Trn_ACCLoss: 0.0153 | Val_ACCLoss: 0.0274 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6443\nFold 7 | #Est: 98 | Trn_Spearman: 0.4237 | Val_Spearman: -0.0339 | Trn_ACCLoss: 0.0053 | Val_ACCLoss: 0.0589 | Trn_NDCG: 0.8892 | Val_NDCG: 0.6646\nFold 8 | #Est: 52 | Trn_Spearman: 0.4716 | Val_Spearman: 0.1035 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.8511 | Val_NDCG: 0.6041\nFold 9 | #Est: 7 | Trn_Spearman: 0.3647 | Val_Spearman: 0.1749 | Trn_ACCLoss: 0.0257 | Val_ACCLoss: 0.0741 | Trn_NDCG: 0.7735 | Val_NDCG: 0.6904\nFold 10 | #Est: 32 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.0822 | Trn_NDCG: 0.8327 | Val_NDCG: 0.6078\nFold 11 | #Est: 75 | Trn_Spearman: 0.4180 | Val_Spearman: 0.0623 | Trn_ACCLoss: 0.0025 | Val_ACCLoss: 0.0993 | Trn_NDCG: 0.8924 | Val_NDCG: 0.6075\nFold 12 | #Est: 55 | Trn_Spearman: 0.4494 | Val_Spearman: -0.0412 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.1466 | Trn_NDCG: 0.8528 | Val_NDCG: 0.4944\nFold 13 | #Est: 31 | Trn_Spearman: 0.4381 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0234 | Trn_NDCG: 0.8155 | Val_NDCG: 0.7176\nFold 14 | #Est: 4 | Trn_Spearman: 0.3779 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0285 | Val_ACCLoss: 0.1033 | Trn_NDCG: 0.7459 | Val_NDCG: 0.5450\nFold 15 | #Est: 3 | Trn_Spearman: 0.3799 | Val_Spearman: -0.0696 | Trn_ACCLoss: 0.0344 | Val_ACCLoss: 0.0624 | Trn_NDCG: 0.7565 | Val_NDCG: 0.5779\nFold 16 | #Est: 1 | Trn_Spearman: 0.1842 | Val_Spearman: -0.1969 | Trn_ACCLoss: 0.0824 | Val_ACCLoss: 0.1143 | Trn_NDCG: 0.6376 | Val_NDCG: 0.6499\nFold 17 | #Est: 1 | Trn_Spearman: 0.2285 | Val_Spearman: 0.0998 | Trn_ACCLoss: 0.0586 | Val_ACCLoss: 0.1439 | Trn_NDCG: 0.6725 | Val_NDCG: 0.6038\nFold 18 | #Est: 6 | Trn_Spearman: 0.4104 | Val_Spearman: 0.4011 | Trn_ACCLoss: 0.0160 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8123 | Val_NDCG: 0.7021\nFold 19 | #Est: 40 | Trn_Spearman: 0.3539 | Val_Spearman: 0.4277 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.0647 | Trn_NDCG: 0.8295 | Val_NDCG: 0.7018\nFold 20 | #Est: 9 | Trn_Spearman: 0.3601 | Val_Spearman: 0.0476 | Trn_ACCLoss: 0.0262 | Val_ACCLoss: 0.0706 | Trn_NDCG: 0.7186 | Val_NDCG: 0.6437\nFold 21 | #Est: 60 | Trn_Spearman: 0.3778 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0122 | Val_ACCLoss: 0.1078 | Trn_NDCG: 0.8318 | Val_NDCG: 0.5535\nFold 22 | #Est: 1 | Trn_Spearman: 0.2628 | Val_Spearman: 0.2198 | Trn_ACCLoss: 0.0669 | Val_ACCLoss: 0.1249 | Trn_NDCG: 0.6445 | Val_NDCG: 0.6153\nFold 23 | #Est: 52 | Trn_Spearman: 0.4349 | Val_Spearman: 0.2134 | Trn_ACCLoss: 0.0135 | Val_ACCLoss: 0.0468 | Trn_NDCG: 0.8563 | Val_NDCG: 0.6696\nFold 24 | #Est: 36 | Trn_Spearman: 0.4032 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0149 | Val_ACCLoss: 0.0464 | Trn_NDCG: 0.8526 | Val_NDCG: 0.6677\nFold 25 | #Est: 1 | Trn_Spearman: 0.2209 | Val_Spearman: -0.0495 | Trn_ACCLoss: 0.0624 | Val_ACCLoss: 0.1216 | Trn_NDCG: 0.6817 | Val_NDCG: 0.6449\nFold 26 | #Est: 4 | Trn_Spearman: 0.3976 | Val_Spearman: 0.4075 | Trn_ACCLoss: 0.0169 | Val_ACCLoss: 0.0242 | Trn_NDCG: 0.7857 | Val_NDCG: 0.6520\nFold 27 | #Est: 2 | Trn_Spearman: 0.3708 | Val_Spearman: -0.0156 | Trn_ACCLoss: 0.0256 | Val_ACCLoss: 0.0855 | Trn_NDCG: 0.7964 | Val_NDCG: 0.5927\nFold 28 | #Est: 1 | Trn_Spearman: 0.2192 | Val_Spearman: 0.2372 | Trn_ACCLoss: 0.0723 | Val_ACCLoss: 0.0982 | Trn_NDCG: 0.6689 | Val_NDCG: 0.6555\nFold 29 | #Est: 9 | Trn_Spearman: 0.3267 | Val_Spearman: 0.0183 | Trn_ACCLoss: 0.0178 | Val_ACCLoss: 0.1399 | Trn_NDCG: 0.7991 | Val_NDCG: 0.6864\nFold 30 | #Est: 18 | Trn_Spearman: 0.3497 | Val_Spearman: -0.0943 | Trn_ACCLoss: 0.0418 | Val_ACCLoss: 0.1127 | Trn_NDCG: 0.7791 | Val_NDCG: 0.5346\nFold 31 | #Est: 91 | Trn_Spearman: 0.4447 | Val_Spearman: 0.3095 | Trn_ACCLoss: 0.0144 | Val_ACCLoss: 0.0260 | Trn_NDCG: 0.8703 | Val_NDCG: 0.7076\nFold 32 | #Est: 13 | Trn_Spearman: 0.4318 | Val_Spearman: 0.1429 | Trn_ACCLoss: 0.0108 | Val_ACCLoss: 0.0668 | Trn_NDCG: 0.8136 | Val_NDCG: 0.6144\nFold 33 | #Est: 1 | Trn_Spearman: 0.2437 | Val_Spearman: 0.1071 | Trn_ACCLoss: 0.0688 | Val_ACCLoss: 0.1413 | Trn_NDCG: 0.6365 | Val_NDCG: 0.6710\nFold 34 | #Est: 1 | Trn_Spearman: 0.3167 | Val_Spearman: 0.0082 | Trn_ACCLoss: 0.0508 | Val_ACCLoss: 0.0655 | Trn_NDCG: 0.6925 | Val_NDCG: 0.6735\nFold 35 | #Est: 38 | Trn_Spearman: 0.3790 | Val_Spearman: 0.0861 | Trn_ACCLoss: 0.0100 | Val_ACCLoss: 0.3138 | Trn_NDCG: 0.8478 | Val_NDCG: 0.5705\nFold 36 | #Est: 4 | Trn_Spearman: 0.4094 | Val_Spearman: 0.0943 | Trn_ACCLoss: 0.0227 | Val_ACCLoss: 0.1079 | Trn_NDCG: 0.7505 | Val_NDCG: 0.5889\nFold 37 | #Est: 3 | Trn_Spearman: 0.3219 | Val_Spearman: -0.0348 | Trn_ACCLoss: 0.0386 | Val_ACCLoss: 0.1317 | Trn_NDCG: 0.7387 | Val_NDCG: 0.6238\nFold 38 | #Est: 24 | Trn_Spearman: 0.4008 | Val_Spearman: 0.0870 | Trn_ACCLoss: 0.0221 | Val_ACCLoss: 0.0373 | Trn_NDCG: 0.7758 | Val_NDCG: 0.7051\nFold 39 | #Est: 4 | Trn_Spearman: 0.3569 | Val_Spearman: 0.0064 | Trn_ACCLoss: 0.0358 | Val_ACCLoss: 0.0441 | Trn_NDCG: 0.7604 | Val_NDCG: 0.5526\nFold 40 | #Est: 105 | Trn_Spearman: 0.4469 | Val_Spearman: 0.0394 | Trn_ACCLoss: 0.0051 | Val_ACCLoss: 0.0370 | Trn_NDCG: 0.8639 | Val_NDCG: 0.6662\nFold 41 | #Est: 5 | Trn_Spearman: 0.3441 | Val_Spearman: -0.0687 | Trn_ACCLoss: 0.0373 | Val_ACCLoss: 0.0730 | Trn_NDCG: 0.7518 | Val_NDCG: 0.6030\nFold 42 | #Est: 1 | Trn_Spearman: 0.2843 | Val_Spearman: 0.0751 | Trn_ACCLoss: 0.0539 | Val_ACCLoss: 0.1883 | Trn_NDCG: 0.6870 | Val_NDCG: 0.5750\nFold 43 | #Est: 1 | Trn_Spearman: 0.3315 | Val_Spearman: 0.1447 | Trn_ACCLoss: 0.0433 | Val_ACCLoss: 0.0440 | Trn_NDCG: 0.6863 | Val_NDCG: 0.5904\nFold 44 | #Est: 2 | Trn_Spearman: 0.3651 | Val_Spearman: 0.1905 | Trn_ACCLoss: 0.0237 | Val_ACCLoss: 0.1633 | Trn_NDCG: 0.7548 | Val_NDCG: 0.5536\nFold 45 | #Est: 1 | Trn_Spearman: 0.2765 | Val_Spearman: 0.2427 | Trn_ACCLoss: 0.0495 | Val_ACCLoss: 0.0927 | Trn_NDCG: 0.7088 | Val_NDCG: 0.6300\nFold 46 | #Est: 8 | Trn_Spearman: 0.4069 | Val_Spearman: -0.0788 | Trn_ACCLoss: 0.0283 | Val_ACCLoss: 0.0805 | Trn_NDCG: 0.7909 | Val_NDCG: 0.5859\nFold 47 | #Est: 2 | Trn_Spearman: 0.3201 | Val_Spearman: -0.1630 | Trn_ACCLoss: 0.0420 | Val_ACCLoss: 0.0781 | Trn_NDCG: 0.7306 | Val_NDCG: 0.5506\nFold 48 | #Est: 11 | Trn_Spearman: 0.4253 | Val_Spearman: 0.2729 | Trn_ACCLoss: 0.0177 | Val_ACCLoss: 0.1332 | Trn_NDCG: 0.7835 | Val_NDCG: 0.6049\nFold 49 | #Est: 1 | Trn_Spearman: 0.2274 | Val_Spearman: 0.2949 | Trn_ACCLoss: 0.0654 | Val_ACCLoss: 0.0783 | Trn_NDCG: 0.6392 | Val_NDCG: 0.7203\nFold 50 | #Est: 72 | Trn_Spearman: 0.4289 | Val_Spearman: 0.0531 | Trn_ACCLoss: 0.0106 | Val_ACCLoss: 0.0222 | Trn_NDCG: 0.8512 | Val_NDCG: 0.6045\nFold 51 | #Est: 50 | Trn_Spearman: 0.4146 | Val_Spearman: 0.2070 | Trn_ACCLoss: 0.0148 | Val_ACCLoss: 0.0142 | Trn_NDCG: 0.8046 | Val_NDCG: 0.6315\nFold 52 | #Est: 29 | Trn_Spearman: 0.4085 | Val_Spearman: 0.0559 | Trn_ACCLoss: 0.0185 | Val_ACCLoss: 0.1595 | Trn_NDCG: 0.8026 | Val_NDCG: 0.5616\nFold 53 | #Est: 13 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0549 | Trn_ACCLoss: 0.0147 | Val_ACCLoss: 0.0169 | Trn_NDCG: 0.8016 | Val_NDCG: 0.6721\nFold 54 | #Est: 25 | Trn_Spearman: 0.3760 | Val_Spearman: -0.1310 | Trn_ACCLoss: 0.0097 | Val_ACCLoss: 0.0812 | Trn_NDCG: 0.8251 | Val_NDCG: 0.5539\nFold 55 | #Est: 14 | Trn_Spearman: 0.4192 | Val_Spearman: -0.0211 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0823 | Trn_NDCG: 0.8201 | Val_NDCG: 0.6643\nFold 56 | #Est: 5 | Trn_Spearman: 0.4012 | Val_Spearman: -0.0119 | Trn_ACCLoss: 0.0203 | Val_ACCLoss: 0.1222 | Trn_NDCG: 0.8009 | Val_NDCG: 0.5544\nFold 57 | #Est: 8 | Trn_Spearman: 0.3993 | Val_Spearman: 0.0632 | Trn_ACCLoss: 0.0234 | Val_ACCLoss: 0.0556 | Trn_NDCG: 0.7780 | Val_NDCG: 0.6107\nFold 58 | #Est: 1 | Trn_Spearman: 0.3205 | Val_Spearman: -0.0110 | Trn_ACCLoss: 0.0407 | Val_ACCLoss: 0.1170 | Trn_NDCG: 0.7091 | Val_NDCG: 0.5368\nFold 59 | #Est: 55 | Trn_Spearman: 0.4195 | Val_Spearman: -0.1328 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.2943 | Trn_NDCG: 0.8148 | Val_NDCG: 0.4998\nFold 60 | #Est: 1 | Trn_Spearman: 0.2482 | Val_Spearman: 0.2143 | Trn_ACCLoss: 0.0775 | Val_ACCLoss: 0.0576 | Trn_NDCG: 0.6614 | Val_NDCG: 0.6679\nFold 61 | #Est: 2 | Trn_Spearman: 0.3733 | Val_Spearman: 0.0018 | Trn_ACCLoss: 0.0314 | Val_ACCLoss: 0.0635 | Trn_NDCG: 0.7634 | Val_NDCG: 0.6352\nFold 62 | #Est: 2 | Trn_Spearman: 0.3156 | Val_Spearman: 0.1493 | Trn_ACCLoss: 0.0578 | Val_ACCLoss: 0.0620 | Trn_NDCG: 0.7024 | Val_NDCG: 0.6215\nFold 63 | #Est: 4 | Trn_Spearman: 0.3557 | Val_Spearman: -0.0311 | Trn_ACCLoss: 0.0253 | Val_ACCLoss: 0.1228 | Trn_NDCG: 0.7615 | Val_NDCG: 0.5825\nFold 64 | #Est: 2 | Trn_Spearman: 0.3340 | Val_Spearman: 0.0485 | Trn_ACCLoss: 0.0437 | Val_ACCLoss: 0.0763 | Trn_NDCG: 0.6885 | Val_NDCG: 0.5861\nFold 65 | #Est: 57 | Trn_Spearman: 0.4374 | Val_Spearman: 0.0128 | Trn_ACCLoss: 0.0158 | Val_ACCLoss: 0.0227 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6927\nFold 66 | #Est: 4 | Trn_Spearman: 0.3704 | Val_Spearman: 0.2024 | Trn_ACCLoss: 0.0296 | Val_ACCLoss: 0.2691 | Trn_NDCG: 0.7471 | Val_NDCG: 0.6197\nFold 67 | #Est: 24 | Trn_Spearman: 0.4042 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.0190 | Val_ACCLoss: 0.2183 | Trn_NDCG: 0.7937 | Val_NDCG: 0.5438\nFold 68 | #Est: 3 | Trn_Spearman: 0.4385 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0174 | Val_ACCLoss: 0.0918 | Trn_NDCG: 0.7617 | Val_NDCG: 0.5756\nFold 69 | #Est: 19 | Trn_Spearman: 0.4127 | Val_Spearman: 0.2125 | Trn_ACCLoss: 0.0051 | Val_ACCLoss: 0.0699 | Trn_NDCG: 0.8683 | Val_NDCG: 0.7338\nFold 70 | #Est: 71 | Trn_Spearman: 0.4433 | Val_Spearman: 0.0046 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.8569 | Val_NDCG: 0.6213\nFold 71 | #Est: 1 | Trn_Spearman: 0.2540 | Val_Spearman: -0.0366 | Trn_ACCLoss: 0.0568 | Val_ACCLoss: 0.1257 | Trn_NDCG: 0.6517 | Val_NDCG: 0.6321\nFold 72 | #Est: 18 | Trn_Spearman: 0.4117 | Val_Spearman: 0.1465 | Trn_ACCLoss: 0.0046 | Val_ACCLoss: 0.0581 | Trn_NDCG: 0.8568 | Val_NDCG: 0.6511\nFold 73 | #Est: 18 | Trn_Spearman: 0.3821 | Val_Spearman: -0.0513 | Trn_ACCLoss: 0.0227 | Val_ACCLoss: 0.0650 | Trn_NDCG: 0.8010 | Val_NDCG: 0.5485\nFold 74 | #Est: 138 | Trn_Spearman: 0.4231 | Val_Spearman: 0.2454 | Trn_ACCLoss: 0.0031 | Val_ACCLoss: 0.0341 | Trn_NDCG: 0.8780 | Val_NDCG: 0.6483\nFold 75 | #Est: 30 | Trn_Spearman: 0.3965 | Val_Spearman: 0.2143 | Trn_ACCLoss: 0.0092 | Val_ACCLoss: 0.1294 | Trn_NDCG: 0.8482 | Val_NDCG: 0.6396\nFold 76 | #Est: 37 | Trn_Spearman: 0.4200 | Val_Spearman: 0.3672 | Trn_ACCLoss: 0.0090 | Val_ACCLoss: 0.0627 | Trn_NDCG: 0.8345 | Val_NDCG: 0.6548\nFold 77 | #Est: 2 | Trn_Spearman: 0.3740 | Val_Spearman: 0.0989 | Trn_ACCLoss: 0.0303 | Val_ACCLoss: 0.1676 | Trn_NDCG: 0.7296 | Val_NDCG: 0.6018\nFold 78 | #Est: 5 | Trn_Spearman: 0.3719 | Val_Spearman: 0.2701 | Trn_ACCLoss: 0.0414 | Val_ACCLoss: 0.0331 | Trn_NDCG: 0.7444 | Val_NDCG: 0.6145\nFold 79 | #Est: 19 | Trn_Spearman: 0.4021 | Val_Spearman: 0.0769 | Trn_ACCLoss: 0.0077 | Val_ACCLoss: 0.0497 | Trn_NDCG: 0.8508 | Val_NDCG: 0.5838\nFold 80 | #Est: 19 | Trn_Spearman: 0.4119 | Val_Spearman: -0.0916 | Trn_ACCLoss: 0.0182 | Val_ACCLoss: 0.1047 | Trn_NDCG: 0.8188 | Val_NDCG: 0.5693\nFold 81 | #Est: 43 | Trn_Spearman: 0.4315 | Val_Spearman: 0.1667 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0806 | Trn_NDCG: 0.8628 | Val_NDCG: 0.5431\nFold 82 | #Est: 22 | Trn_Spearman: 0.4451 | Val_Spearman: 0.0833 | Trn_ACCLoss: 0.0102 | Val_ACCLoss: 0.1245 | Trn_NDCG: 0.8292 | Val_NDCG: 0.6168\nFold 83 | #Est: 27 | Trn_Spearman: 0.3944 | Val_Spearman: 0.0220 | Trn_ACCLoss: 0.0133 | Val_ACCLoss: 0.0487 | Trn_NDCG: 0.8317 | Val_NDCG: 0.6277\nFold 84 | #Est: 27 | Trn_Spearman: 0.4166 | Val_Spearman: 0.1832 | Trn_ACCLoss: 0.0117 | Val_ACCLoss: 0.0791 | Trn_NDCG: 0.8308 | Val_NDCG: 0.5824\nFold 85 | #Est: 40 | Trn_Spearman: 0.3544 | Val_Spearman: 0.1429 | Trn_ACCLoss: 0.0029 | Val_ACCLoss: 0.0719 | Trn_NDCG: 0.8612 | Val_NDCG: 0.6174\nFold 86 | #Est: 8 | Trn_Spearman: 0.3588 | Val_Spearman: 0.3260 | Trn_ACCLoss: 0.0216 | Val_ACCLoss: 0.0579 | Trn_NDCG: 0.7623 | Val_NDCG: 0.6468\nFold 87 | #Est: 1 | Trn_Spearman: 0.2125 | Val_Spearman: -0.1474 | Trn_ACCLoss: 0.0725 | Val_ACCLoss: 0.0721 | Trn_NDCG: 0.6504 | Val_NDCG: 0.5962\nFold 88 | #Est: 15 | Trn_Spearman: 0.3826 | Val_Spearman: 0.2894 | Trn_ACCLoss: 0.0198 | Val_ACCLoss: 0.0371 | Trn_NDCG: 0.8302 | Val_NDCG: 0.7045\nFold 89 | #Est: 78 | Trn_Spearman: 0.4296 | Val_Spearman: 0.1209 | Trn_ACCLoss: 0.0028 | Val_ACCLoss: 0.0744 | Trn_NDCG: 0.8764 | Val_NDCG: 0.5674\nFold 90 | #Est: 21 | Trn_Spearman: 0.4109 | Val_Spearman: 0.1969 | Trn_ACCLoss: 0.0163 | Val_ACCLoss: 0.1158 | Trn_NDCG: 0.8194 | Val_NDCG: 0.6708\nFold 91 | #Est: 2 | Trn_Spearman: 0.3628 | Val_Spearman: -0.1374 | Trn_ACCLoss: 0.0315 | Val_ACCLoss: 0.2593 | Trn_NDCG: 0.7492 | Val_NDCG: 0.5761\nFold 92 | #Est: 61 | Trn_Spearman: 0.4345 | Val_Spearman: 0.1126 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.1008 | Trn_NDCG: 0.8682 | Val_NDCG: 0.6008\nFold 93 | #Est: 27 | Trn_Spearman: 0.3767 | Val_Spearman: -0.0174 | Trn_ACCLoss: 0.0211 | Val_ACCLoss: 0.0612 | Trn_NDCG: 0.8023 | Val_NDCG: 0.6404\nFold 94 | #Est: 22 | Trn_Spearman: 0.3681 | Val_Spearman: 0.0238 | Trn_ACCLoss: 0.0210 | Val_ACCLoss: 0.0637 | Trn_NDCG: 0.8038 | Val_NDCG: 0.4970\nFold 95 | #Est: 1 | Trn_Spearman: 0.2120 | Val_Spearman: -0.1273 | Trn_ACCLoss: 0.0687 | Val_ACCLoss: 0.1474 | Trn_NDCG: 0.6416 | Val_NDCG: 0.5514\nFold 96 | #Est: 6 | Trn_Spearman: 0.3799 | Val_Spearman: 0.0147 | Trn_ACCLoss: 0.0248 | Val_ACCLoss: 0.1061 | Trn_NDCG: 0.7867 | Val_NDCG: 0.6024\nFold 97 | #Est: 31 | Trn_Spearman: 0.4008 | Val_Spearman: 0.0092 | Trn_ACCLoss: 0.0175 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8407 | Val_NDCG: 0.5898\nFold 98 | #Est: 23 | Trn_Spearman: 0.3503 | Val_Spearman: -0.2134 | Trn_ACCLoss: 0.0135 | Val_ACCLoss: 0.1751 | Trn_NDCG: 0.8154 | Val_NDCG: 0.5536\nFold 99 | #Est: 20 | Trn_Spearman: 0.4177 | Val_Spearman: 0.3031 | Trn_ACCLoss: 0.0087 | Val_ACCLoss: 0.0695 | Trn_NDCG: 0.8309 | Val_NDCG: 0.7726\nFold 100 | #Est: 40 | Trn_Spearman: 0.4366 | Val_Spearman: 0.2115 | Trn_ACCLoss: 0.0082 | Val_ACCLoss: 0.1031 | Trn_NDCG: 0.8460 | Val_NDCG: 0.5841\n\nTrn_Spearman: 0.3714 +/-0.0634 | Val_Spearman: 0.0922 +/-0.1403\nTrn_ACCLoss: 0.0254 +/-0.0194 | Val_ACCLoss: 0.0921 +/-0.0564\nTrn_NDCG: 0.7845 +/-0.0671 | Val_NDCG: 0.6157 +/-0.0555\n\nCPU times: user 2min 27s, sys: 764 ms, total: 2min 28s\nWall time: 18 s\n"
],
[
"from project.ranker.ltr_rankers import wide2long\nX, y = wide2long(X_train, y_train)\nX.shape, y.shape",
"_____no_output_____"
],
[
"from scipy.stats import rankdata\ny_pred = np.array([rankdata(models[0].predict(wide2long(x_[None,:], y_[None,:])[0]), \n method='ordinal') for x_, y_ in zip(X_train, y_train)])\ny_pred.shape",
"_____no_output_____"
],
[
"13 - y_train[0] + 1",
"_____no_output_____"
],
[
"y_pred[0]",
"_____no_output_____"
],
[
"from scipy.stats import spearmanr\nspearmanr(13 - y_train[0] + 1, y_pred[0])",
"_____no_output_____"
]
],
[
[
"## Ranking, Regression, Classification",
"_____no_output_____"
]
],
[
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nparams = {'objective': 'lambdarank', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.2977 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0370 | Val_ACCLoss: 0.0682 | Trn_NDCG: 0.7352 | Val_NDCG: 0.7133\nFold 2 | #Est: 6 | Trn_Spearman: 0.3516 | Val_Spearman: 0.2408 | Trn_ACCLoss: 0.0152 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.7980 | Val_NDCG: 0.5778\nFold 3 | #Est: 24 | Trn_Spearman: 0.4100 | Val_Spearman: 0.2582 | Trn_ACCLoss: 0.0124 | Val_ACCLoss: 0.0797 | Trn_NDCG: 0.8507 | Val_NDCG: 0.5944\nFold 4 | #Est: 3 | Trn_Spearman: 0.3758 | Val_Spearman: 0.0321 | Trn_ACCLoss: 0.0202 | Val_ACCLoss: 0.0715 | Trn_NDCG: 0.7622 | Val_NDCG: 0.5557\nFold 5 | #Est: 23 | Trn_Spearman: 0.4199 | Val_Spearman: 0.0513 | Trn_ACCLoss: 0.0098 | Val_ACCLoss: 0.1202 | Trn_NDCG: 0.8485 | Val_NDCG: 0.5623\nFold 6 | #Est: 23 | Trn_Spearman: 0.4028 | Val_Spearman: 0.1877 | Trn_ACCLoss: 0.0153 | Val_ACCLoss: 0.0274 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6443\nFold 7 | #Est: 98 | Trn_Spearman: 0.4237 | Val_Spearman: -0.0339 | Trn_ACCLoss: 0.0053 | Val_ACCLoss: 0.0589 | Trn_NDCG: 0.8892 | Val_NDCG: 0.6646\nFold 8 | #Est: 52 | Trn_Spearman: 0.4716 | Val_Spearman: 0.1035 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.8511 | Val_NDCG: 0.6041\nFold 9 | #Est: 7 | Trn_Spearman: 0.3647 | Val_Spearman: 0.1749 | Trn_ACCLoss: 0.0257 | Val_ACCLoss: 0.0741 | Trn_NDCG: 0.7735 | Val_NDCG: 0.6904\nFold 10 | #Est: 32 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.0822 | Trn_NDCG: 0.8327 | Val_NDCG: 0.6078\nFold 11 | #Est: 75 | Trn_Spearman: 0.4180 | Val_Spearman: 0.0623 | Trn_ACCLoss: 0.0025 | Val_ACCLoss: 0.0993 | Trn_NDCG: 0.8924 | Val_NDCG: 0.6075\nFold 12 | #Est: 55 | Trn_Spearman: 0.4494 | Val_Spearman: -0.0412 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.1466 | Trn_NDCG: 0.8528 | Val_NDCG: 0.4944\nFold 13 | #Est: 31 | Trn_Spearman: 0.4381 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0234 | Trn_NDCG: 0.8155 | Val_NDCG: 0.7176\nFold 14 | #Est: 4 | Trn_Spearman: 0.3779 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0285 | Val_ACCLoss: 0.1033 | Trn_NDCG: 0.7459 | Val_NDCG: 0.5450\nFold 15 | #Est: 3 | Trn_Spearman: 0.3799 | Val_Spearman: -0.0696 | Trn_ACCLoss: 0.0344 | Val_ACCLoss: 0.0624 | Trn_NDCG: 0.7565 | Val_NDCG: 0.5779\nFold 16 | #Est: 1 | Trn_Spearman: 0.1842 | Val_Spearman: -0.1969 | Trn_ACCLoss: 0.0824 | Val_ACCLoss: 0.1143 | Trn_NDCG: 0.6376 | Val_NDCG: 0.6499\nFold 17 | #Est: 1 | Trn_Spearman: 0.2285 | Val_Spearman: 0.0998 | Trn_ACCLoss: 0.0586 | Val_ACCLoss: 0.1439 | Trn_NDCG: 0.6725 | Val_NDCG: 0.6038\nFold 18 | #Est: 6 | Trn_Spearman: 0.4104 | Val_Spearman: 0.4011 | Trn_ACCLoss: 0.0160 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8123 | Val_NDCG: 0.7021\nFold 19 | #Est: 40 | Trn_Spearman: 0.3539 | Val_Spearman: 0.4277 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.0647 | Trn_NDCG: 0.8295 | Val_NDCG: 0.7018\nFold 20 | #Est: 9 | Trn_Spearman: 0.3601 | Val_Spearman: 0.0476 | Trn_ACCLoss: 0.0262 | Val_ACCLoss: 0.0706 | Trn_NDCG: 0.7186 | Val_NDCG: 0.6437\n\nTrn_Spearman: 0.3754 +/-0.0685 | Val_Spearman: 0.1151 +/-0.1560\nTrn_ACCLoss: 0.0221 +/-0.0189 | Val_ACCLoss: 0.0799 +/-0.0321\nTrn_NDCG: 0.7944 +/-0.0667 | Val_NDCG: 0.6229 +/-0.0610\n\nCPU times: user 37.3 s, sys: 192 ms, total: 37.5 s\nWall time: 4.46 s\n"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nparams = {'objective': 'regression', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.4294 | Val_Spearman: 0.3901 | Trn_ACCLoss: 0.0621 | Val_ACCLoss: 0.1853 | Trn_NDCG: 0.6465 | Val_NDCG: 0.6706\nFold 2 | #Est: 72 | Trn_Spearman: 0.5380 | Val_Spearman: 0.2903 | Trn_ACCLoss: 0.0387 | Val_ACCLoss: 0.1764 | Trn_NDCG: 0.7101 | Val_NDCG: 0.6252\nFold 3 | #Est: 30 | Trn_Spearman: 0.4639 | Val_Spearman: 0.1951 | Trn_ACCLoss: 0.0622 | Val_ACCLoss: 0.1125 | Trn_NDCG: 0.6839 | Val_NDCG: 0.5400\nFold 4 | #Est: 32 | Trn_Spearman: 0.4380 | Val_Spearman: 0.2601 | Trn_ACCLoss: 0.0456 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.6749 | Val_NDCG: 0.7206\nFold 5 | #Est: 15 | Trn_Spearman: 0.4373 | Val_Spearman: 0.0595 | Trn_ACCLoss: 0.0644 | Val_ACCLoss: 0.1327 | Trn_NDCG: 0.6335 | Val_NDCG: 0.5640\nFold 6 | #Est: 1 | Trn_Spearman: 0.2000 | Val_Spearman: -0.0568 | Trn_ACCLoss: 0.1398 | Val_ACCLoss: 0.0802 | Trn_NDCG: 0.5635 | Val_NDCG: 0.5381\nFold 7 | #Est: 3 | Trn_Spearman: 0.4399 | Val_Spearman: 0.0330 | Trn_ACCLoss: 0.0576 | Val_ACCLoss: 0.2797 | Trn_NDCG: 0.6632 | Val_NDCG: 0.5569\nFold 8 | #Est: 3 | Trn_Spearman: 0.3663 | Val_Spearman: 0.2161 | Trn_ACCLoss: 0.0908 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.6498 | Val_NDCG: 0.5777\nFold 9 | #Est: 1 | Trn_Spearman: 0.1851 | Val_Spearman: 0.1044 | Trn_ACCLoss: 0.1345 | Val_ACCLoss: 0.0799 | Trn_NDCG: 0.5629 | Val_NDCG: 0.5489\nFold 10 | #Est: 2 | Trn_Spearman: 0.3590 | Val_Spearman: 0.3315 | Trn_ACCLoss: 0.0841 | Val_ACCLoss: 0.1031 | Trn_NDCG: 0.6447 | Val_NDCG: 0.6456\nFold 11 | #Est: 1 | Trn_Spearman: 0.1913 | Val_Spearman: 0.0339 | Trn_ACCLoss: 0.1311 | Val_ACCLoss: 0.1860 | Trn_NDCG: 0.5565 | Val_NDCG: 0.5674\nFold 12 | #Est: 8 | Trn_Spearman: 0.4718 | Val_Spearman: 0.1493 | Trn_ACCLoss: 0.0408 | Val_ACCLoss: 0.2328 | Trn_NDCG: 0.6833 | Val_NDCG: 0.5897\nFold 13 | #Est: 1 | Trn_Spearman: 0.1909 | Val_Spearman: 0.0311 | Trn_ACCLoss: 0.1221 | Val_ACCLoss: 0.0504 | Trn_NDCG: 0.5691 | Val_NDCG: 0.5300\nFold 14 | #Est: 56 | Trn_Spearman: 0.4244 | Val_Spearman: 0.0897 | Trn_ACCLoss: 0.0699 | Val_ACCLoss: 0.0947 | Trn_NDCG: 0.6596 | Val_NDCG: 0.5096\nFold 15 | #Est: 1 | Trn_Spearman: 0.1867 | Val_Spearman: 0.0907 | Trn_ACCLoss: 0.1239 | Val_ACCLoss: 0.0639 | Trn_NDCG: 0.5598 | Val_NDCG: 0.6149\nFold 16 | #Est: 1 | Trn_Spearman: 0.1951 | Val_Spearman: -0.0366 | Trn_ACCLoss: 0.1288 | Val_ACCLoss: 0.1045 | Trn_NDCG: 0.5715 | Val_NDCG: 0.4773\nFold 17 | #Est: 14 | Trn_Spearman: 0.4290 | Val_Spearman: 0.3288 | Trn_ACCLoss: 0.0627 | Val_ACCLoss: 0.1061 | Trn_NDCG: 0.6674 | Val_NDCG: 0.7336\nFold 18 | #Est: 39 | Trn_Spearman: 0.4523 | Val_Spearman: 0.2024 | Trn_ACCLoss: 0.0571 | Val_ACCLoss: 0.2177 | Trn_NDCG: 0.6681 | Val_NDCG: 0.6221\nFold 19 | #Est: 26 | Trn_Spearman: 0.4142 | Val_Spearman: 0.3864 | Trn_ACCLoss: 0.0856 | Val_ACCLoss: 0.0742 | Trn_NDCG: 0.6351 | Val_NDCG: 0.6306\nFold 20 | #Est: 9 | Trn_Spearman: 0.3944 | Val_Spearman: 0.1520 | Trn_ACCLoss: 0.0904 | Val_ACCLoss: 0.1073 | Trn_NDCG: 0.6087 | Val_NDCG: 0.5774\n\nTrn_Spearman: 0.3603 +/-0.1163 | Val_Spearman: 0.1625 +/-0.1328\nTrn_ACCLoss: 0.0846 +/-0.0330 | Val_ACCLoss: 0.1245 +/-0.0647\nTrn_NDCG: 0.6306 +/-0.0483 | Val_NDCG: 0.5920 +/-0.0648\n\nCPU times: user 26.9 s, sys: 132 ms, total: 27 s\nWall time: 2.94 s\n"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nparams = {'objective': 'binary', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 1 | Trn_Spearman: -0.0954 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.1136 | Val_ACCLoss: 0.1499 | Trn_NDCG: 0.5295 | Val_NDCG: 0.5097\nFold 2 | #Est: 1 | Trn_Spearman: -0.0900 | Val_Spearman: -0.0110 | Trn_ACCLoss: 0.1129 | Val_ACCLoss: 0.1561 | Trn_NDCG: 0.5317 | Val_NDCG: 0.4901\nFold 3 | #Est: 1 | Trn_Spearman: -0.0665 | Val_Spearman: -0.2225 | Trn_ACCLoss: 0.1216 | Val_ACCLoss: 0.0782 | Trn_NDCG: 0.5195 | Val_NDCG: 0.5999\nFold 4 | #Est: 1 | Trn_Spearman: -0.0980 | Val_Spearman: 0.0604 | Trn_ACCLoss: 0.1218 | Val_ACCLoss: 0.0761 | Trn_NDCG: 0.5231 | Val_NDCG: 0.5679\nFold 5 | #Est: 1 | Trn_Spearman: -0.0736 | Val_Spearman: -0.1593 | Trn_ACCLoss: 0.1107 | Val_ACCLoss: 0.1763 | Trn_NDCG: 0.5227 | Val_NDCG: 0.5713\nFold 6 | #Est: 1 | Trn_Spearman: -0.0648 | Val_Spearman: -0.2381 | Trn_ACCLoss: 0.1159 | Val_ACCLoss: 0.1295 | Trn_NDCG: 0.5292 | Val_NDCG: 0.5131\nFold 7 | #Est: 1 | Trn_Spearman: -0.1095 | Val_Spearman: 0.1639 | Trn_ACCLoss: 0.1209 | Val_ACCLoss: 0.0838 | Trn_NDCG: 0.5358 | Val_NDCG: 0.4532\nFold 8 | #Est: 1 | Trn_Spearman: -0.0979 | Val_Spearman: 0.0595 | Trn_ACCLoss: 0.1249 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.5292 | Val_NDCG: 0.5126\nFold 9 | #Est: 1 | Trn_Spearman: -0.0696 | Val_Spearman: -0.1951 | Trn_ACCLoss: 0.1212 | Val_ACCLoss: 0.0812 | Trn_NDCG: 0.5300 | Val_NDCG: 0.5056\nFold 10 | #Est: 1 | Trn_Spearman: -0.0561 | Val_Spearman: -0.3168 | Trn_ACCLoss: 0.1088 | Val_ACCLoss: 0.1932 | Trn_NDCG: 0.5248 | Val_NDCG: 0.5521\nFold 11 | #Est: 1 | Trn_Spearman: -0.1212 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.1238 | Val_ACCLoss: 0.0584 | Trn_NDCG: 0.5374 | Val_NDCG: 0.4386\nFold 12 | #Est: 1 | Trn_Spearman: -0.0899 | Val_Spearman: -0.0119 | Trn_ACCLoss: 0.1215 | Val_ACCLoss: 0.0787 | Trn_NDCG: 0.5364 | Val_NDCG: 0.4475\nFold 13 | #Est: 1 | Trn_Spearman: -0.0759 | Val_Spearman: -0.1383 | Trn_ACCLoss: 0.1230 | Val_ACCLoss: 0.0650 | Trn_NDCG: 0.5197 | Val_NDCG: 0.5979\nFold 14 | #Est: 1 | Trn_Spearman: -0.0601 | Val_Spearman: -0.2802 | Trn_ACCLoss: 0.1182 | Val_ACCLoss: 0.1087 | Trn_NDCG: 0.5209 | Val_NDCG: 0.5870\nFold 15 | #Est: 1 | Trn_Spearman: -0.0733 | Val_Spearman: -0.1621 | Trn_ACCLoss: 0.1222 | Val_ACCLoss: 0.0723 | Trn_NDCG: 0.5222 | Val_NDCG: 0.5758\nFold 16 | #Est: 1 | Trn_Spearman: -0.0590 | Val_Spearman: -0.2903 | Trn_ACCLoss: 0.1162 | Val_ACCLoss: 0.1269 | Trn_NDCG: 0.5244 | Val_NDCG: 0.5562\nFold 17 | #Est: 1 | Trn_Spearman: -0.0719 | Val_Spearman: -0.1740 | Trn_ACCLoss: 0.1040 | Val_ACCLoss: 0.2365 | Trn_NDCG: 0.5288 | Val_NDCG: 0.5162\nFold 18 | #Est: 1 | Trn_Spearman: -0.0790 | Val_Spearman: -0.1108 | Trn_ACCLoss: 0.1096 | Val_ACCLoss: 0.1862 | Trn_NDCG: 0.5284 | Val_NDCG: 0.5198\nFold 19 | #Est: 1 | Trn_Spearman: -0.0657 | Val_Spearman: -0.2299 | Trn_ACCLoss: 0.1099 | Val_ACCLoss: 0.1834 | Trn_NDCG: 0.5230 | Val_NDCG: 0.5683\nFold 20 | #Est: 1 | Trn_Spearman: -0.1254 | Val_Spearman: 0.3068 | Trn_ACCLoss: 0.1240 | Val_ACCLoss: 0.0562 | Trn_NDCG: 0.5342 | Val_NDCG: 0.4680\n\nTrn_Spearman: -0.0821 +/-0.0199 | Val_Spearman: -0.0821 +/-0.1790\nTrn_ACCLoss: 0.1172 +/-0.0061 | Val_ACCLoss: 0.1172 +/-0.0545\nTrn_NDCG: 0.5275 +/-0.0055 | Val_NDCG: 0.5275 +/-0.0495\n\nCPU times: user 8.68 s, sys: 40 ms, total: 8.72 s\nWall time: 1.39 s\n"
]
],
[
[
"## 10 runs - 10 folds",
"_____no_output_____"
]
],
[
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=10, random_state=42)\nparams = {'objective': 'lambdarank', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.2977 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0370 | Val_ACCLoss: 0.0682 | Trn_NDCG: 0.7352 | Val_NDCG: 0.7133\nFold 2 | #Est: 6 | Trn_Spearman: 0.3516 | Val_Spearman: 0.2408 | Trn_ACCLoss: 0.0152 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.7980 | Val_NDCG: 0.5778\nFold 3 | #Est: 24 | Trn_Spearman: 0.4100 | Val_Spearman: 0.2582 | Trn_ACCLoss: 0.0124 | Val_ACCLoss: 0.0797 | Trn_NDCG: 0.8507 | Val_NDCG: 0.5944\nFold 4 | #Est: 3 | Trn_Spearman: 0.3758 | Val_Spearman: 0.0321 | Trn_ACCLoss: 0.0202 | Val_ACCLoss: 0.0715 | Trn_NDCG: 0.7622 | Val_NDCG: 0.5557\nFold 5 | #Est: 23 | Trn_Spearman: 0.4199 | Val_Spearman: 0.0513 | Trn_ACCLoss: 0.0098 | Val_ACCLoss: 0.1202 | Trn_NDCG: 0.8485 | Val_NDCG: 0.5623\nFold 6 | #Est: 23 | Trn_Spearman: 0.4028 | Val_Spearman: 0.1877 | Trn_ACCLoss: 0.0153 | Val_ACCLoss: 0.0274 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6443\nFold 7 | #Est: 98 | Trn_Spearman: 0.4237 | Val_Spearman: -0.0339 | Trn_ACCLoss: 0.0053 | Val_ACCLoss: 0.0589 | Trn_NDCG: 0.8892 | Val_NDCG: 0.6646\nFold 8 | #Est: 52 | Trn_Spearman: 0.4716 | Val_Spearman: 0.1035 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.8511 | Val_NDCG: 0.6041\nFold 9 | #Est: 7 | Trn_Spearman: 0.3647 | Val_Spearman: 0.1749 | Trn_ACCLoss: 0.0257 | Val_ACCLoss: 0.0741 | Trn_NDCG: 0.7735 | Val_NDCG: 0.6904\nFold 10 | #Est: 32 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.0822 | Trn_NDCG: 0.8327 | Val_NDCG: 0.6078\nFold 11 | #Est: 75 | Trn_Spearman: 0.4180 | Val_Spearman: 0.0623 | Trn_ACCLoss: 0.0025 | Val_ACCLoss: 0.0993 | Trn_NDCG: 0.8924 | Val_NDCG: 0.6075\nFold 12 | #Est: 55 | Trn_Spearman: 0.4494 | Val_Spearman: -0.0412 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.1466 | Trn_NDCG: 0.8528 | Val_NDCG: 0.4944\nFold 13 | #Est: 31 | Trn_Spearman: 0.4381 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0234 | Trn_NDCG: 0.8155 | Val_NDCG: 0.7176\nFold 14 | #Est: 4 | Trn_Spearman: 0.3779 | Val_Spearman: 0.0137 | Trn_ACCLoss: 0.0285 | Val_ACCLoss: 0.1033 | Trn_NDCG: 0.7459 | Val_NDCG: 0.5450\nFold 15 | #Est: 3 | Trn_Spearman: 0.3799 | Val_Spearman: -0.0696 | Trn_ACCLoss: 0.0344 | Val_ACCLoss: 0.0624 | Trn_NDCG: 0.7565 | Val_NDCG: 0.5779\nFold 16 | #Est: 1 | Trn_Spearman: 0.1842 | Val_Spearman: -0.1969 | Trn_ACCLoss: 0.0824 | Val_ACCLoss: 0.1143 | Trn_NDCG: 0.6376 | Val_NDCG: 0.6499\nFold 17 | #Est: 1 | Trn_Spearman: 0.2285 | Val_Spearman: 0.0998 | Trn_ACCLoss: 0.0586 | Val_ACCLoss: 0.1439 | Trn_NDCG: 0.6725 | Val_NDCG: 0.6038\nFold 18 | #Est: 6 | Trn_Spearman: 0.4104 | Val_Spearman: 0.4011 | Trn_ACCLoss: 0.0160 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8123 | Val_NDCG: 0.7021\nFold 19 | #Est: 40 | Trn_Spearman: 0.3539 | Val_Spearman: 0.4277 | Trn_ACCLoss: 0.0099 | Val_ACCLoss: 0.0647 | Trn_NDCG: 0.8295 | Val_NDCG: 0.7018\nFold 20 | #Est: 9 | Trn_Spearman: 0.3601 | Val_Spearman: 0.0476 | Trn_ACCLoss: 0.0262 | Val_ACCLoss: 0.0706 | Trn_NDCG: 0.7186 | Val_NDCG: 0.6437\nFold 21 | #Est: 60 | Trn_Spearman: 0.3778 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0122 | Val_ACCLoss: 0.1078 | Trn_NDCG: 0.8318 | Val_NDCG: 0.5535\nFold 22 | #Est: 1 | Trn_Spearman: 0.2628 | Val_Spearman: 0.2198 | Trn_ACCLoss: 0.0669 | Val_ACCLoss: 0.1249 | Trn_NDCG: 0.6445 | Val_NDCG: 0.6153\nFold 23 | #Est: 52 | Trn_Spearman: 0.4349 | Val_Spearman: 0.2134 | Trn_ACCLoss: 0.0135 | Val_ACCLoss: 0.0468 | Trn_NDCG: 0.8563 | Val_NDCG: 0.6696\nFold 24 | #Est: 36 | Trn_Spearman: 0.4032 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0149 | Val_ACCLoss: 0.0464 | Trn_NDCG: 0.8526 | Val_NDCG: 0.6677\nFold 25 | #Est: 1 | Trn_Spearman: 0.2209 | Val_Spearman: -0.0495 | Trn_ACCLoss: 0.0624 | Val_ACCLoss: 0.1216 | Trn_NDCG: 0.6817 | Val_NDCG: 0.6449\nFold 26 | #Est: 4 | Trn_Spearman: 0.3976 | Val_Spearman: 0.4075 | Trn_ACCLoss: 0.0169 | Val_ACCLoss: 0.0242 | Trn_NDCG: 0.7857 | Val_NDCG: 0.6520\nFold 27 | #Est: 2 | Trn_Spearman: 0.3708 | Val_Spearman: -0.0156 | Trn_ACCLoss: 0.0256 | Val_ACCLoss: 0.0855 | Trn_NDCG: 0.7964 | Val_NDCG: 0.5927\nFold 28 | #Est: 1 | Trn_Spearman: 0.2192 | Val_Spearman: 0.2372 | Trn_ACCLoss: 0.0723 | Val_ACCLoss: 0.0982 | Trn_NDCG: 0.6689 | Val_NDCG: 0.6555\nFold 29 | #Est: 9 | Trn_Spearman: 0.3267 | Val_Spearman: 0.0183 | Trn_ACCLoss: 0.0178 | Val_ACCLoss: 0.1399 | Trn_NDCG: 0.7991 | Val_NDCG: 0.6864\nFold 30 | #Est: 18 | Trn_Spearman: 0.3497 | Val_Spearman: -0.0943 | Trn_ACCLoss: 0.0418 | Val_ACCLoss: 0.1127 | Trn_NDCG: 0.7791 | Val_NDCG: 0.5346\nFold 31 | #Est: 91 | Trn_Spearman: 0.4447 | Val_Spearman: 0.3095 | Trn_ACCLoss: 0.0144 | Val_ACCLoss: 0.0260 | Trn_NDCG: 0.8703 | Val_NDCG: 0.7076\nFold 32 | #Est: 13 | Trn_Spearman: 0.4318 | Val_Spearman: 0.1429 | Trn_ACCLoss: 0.0108 | Val_ACCLoss: 0.0668 | Trn_NDCG: 0.8136 | Val_NDCG: 0.6144\nFold 33 | #Est: 1 | Trn_Spearman: 0.2437 | Val_Spearman: 0.1071 | Trn_ACCLoss: 0.0688 | Val_ACCLoss: 0.1413 | Trn_NDCG: 0.6365 | Val_NDCG: 0.6710\nFold 34 | #Est: 1 | Trn_Spearman: 0.3167 | Val_Spearman: 0.0082 | Trn_ACCLoss: 0.0508 | Val_ACCLoss: 0.0655 | Trn_NDCG: 0.6925 | Val_NDCG: 0.6735\nFold 35 | #Est: 38 | Trn_Spearman: 0.3790 | Val_Spearman: 0.0861 | Trn_ACCLoss: 0.0100 | Val_ACCLoss: 0.3138 | Trn_NDCG: 0.8478 | Val_NDCG: 0.5705\nFold 36 | #Est: 4 | Trn_Spearman: 0.4094 | Val_Spearman: 0.0943 | Trn_ACCLoss: 0.0227 | Val_ACCLoss: 0.1079 | Trn_NDCG: 0.7505 | Val_NDCG: 0.5889\nFold 37 | #Est: 3 | Trn_Spearman: 0.3219 | Val_Spearman: -0.0348 | Trn_ACCLoss: 0.0386 | Val_ACCLoss: 0.1317 | Trn_NDCG: 0.7387 | Val_NDCG: 0.6238\nFold 38 | #Est: 24 | Trn_Spearman: 0.4008 | Val_Spearman: 0.0870 | Trn_ACCLoss: 0.0221 | Val_ACCLoss: 0.0373 | Trn_NDCG: 0.7758 | Val_NDCG: 0.7051\nFold 39 | #Est: 4 | Trn_Spearman: 0.3569 | Val_Spearman: 0.0064 | Trn_ACCLoss: 0.0358 | Val_ACCLoss: 0.0441 | Trn_NDCG: 0.7604 | Val_NDCG: 0.5526\nFold 40 | #Est: 105 | Trn_Spearman: 0.4469 | Val_Spearman: 0.0394 | Trn_ACCLoss: 0.0051 | Val_ACCLoss: 0.0370 | Trn_NDCG: 0.8639 | Val_NDCG: 0.6662\nFold 41 | #Est: 5 | Trn_Spearman: 0.3441 | Val_Spearman: -0.0687 | Trn_ACCLoss: 0.0373 | Val_ACCLoss: 0.0730 | Trn_NDCG: 0.7518 | Val_NDCG: 0.6030\nFold 42 | #Est: 1 | Trn_Spearman: 0.2843 | Val_Spearman: 0.0751 | Trn_ACCLoss: 0.0539 | Val_ACCLoss: 0.1883 | Trn_NDCG: 0.6870 | Val_NDCG: 0.5750\nFold 43 | #Est: 1 | Trn_Spearman: 0.3315 | Val_Spearman: 0.1447 | Trn_ACCLoss: 0.0433 | Val_ACCLoss: 0.0440 | Trn_NDCG: 0.6863 | Val_NDCG: 0.5904\nFold 44 | #Est: 2 | Trn_Spearman: 0.3651 | Val_Spearman: 0.1905 | Trn_ACCLoss: 0.0237 | Val_ACCLoss: 0.1633 | Trn_NDCG: 0.7548 | Val_NDCG: 0.5536\nFold 45 | #Est: 1 | Trn_Spearman: 0.2765 | Val_Spearman: 0.2427 | Trn_ACCLoss: 0.0495 | Val_ACCLoss: 0.0927 | Trn_NDCG: 0.7088 | Val_NDCG: 0.6300\nFold 46 | #Est: 8 | Trn_Spearman: 0.4069 | Val_Spearman: -0.0788 | Trn_ACCLoss: 0.0283 | Val_ACCLoss: 0.0805 | Trn_NDCG: 0.7909 | Val_NDCG: 0.5859\nFold 47 | #Est: 2 | Trn_Spearman: 0.3201 | Val_Spearman: -0.1630 | Trn_ACCLoss: 0.0420 | Val_ACCLoss: 0.0781 | Trn_NDCG: 0.7306 | Val_NDCG: 0.5506\nFold 48 | #Est: 11 | Trn_Spearman: 0.4253 | Val_Spearman: 0.2729 | Trn_ACCLoss: 0.0177 | Val_ACCLoss: 0.1332 | Trn_NDCG: 0.7835 | Val_NDCG: 0.6049\nFold 49 | #Est: 1 | Trn_Spearman: 0.2274 | Val_Spearman: 0.2949 | Trn_ACCLoss: 0.0654 | Val_ACCLoss: 0.0783 | Trn_NDCG: 0.6392 | Val_NDCG: 0.7203\nFold 50 | #Est: 72 | Trn_Spearman: 0.4289 | Val_Spearman: 0.0531 | Trn_ACCLoss: 0.0106 | Val_ACCLoss: 0.0222 | Trn_NDCG: 0.8512 | Val_NDCG: 0.6045\nFold 51 | #Est: 50 | Trn_Spearman: 0.4146 | Val_Spearman: 0.2070 | Trn_ACCLoss: 0.0148 | Val_ACCLoss: 0.0142 | Trn_NDCG: 0.8046 | Val_NDCG: 0.6315\nFold 52 | #Est: 29 | Trn_Spearman: 0.4085 | Val_Spearman: 0.0559 | Trn_ACCLoss: 0.0185 | Val_ACCLoss: 0.1595 | Trn_NDCG: 0.8026 | Val_NDCG: 0.5616\nFold 53 | #Est: 13 | Trn_Spearman: 0.3896 | Val_Spearman: 0.0549 | Trn_ACCLoss: 0.0147 | Val_ACCLoss: 0.0169 | Trn_NDCG: 0.8016 | Val_NDCG: 0.6721\nFold 54 | #Est: 25 | Trn_Spearman: 0.3760 | Val_Spearman: -0.1310 | Trn_ACCLoss: 0.0097 | Val_ACCLoss: 0.0812 | Trn_NDCG: 0.8251 | Val_NDCG: 0.5539\nFold 55 | #Est: 14 | Trn_Spearman: 0.4192 | Val_Spearman: -0.0211 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.0823 | Trn_NDCG: 0.8201 | Val_NDCG: 0.6643\nFold 56 | #Est: 5 | Trn_Spearman: 0.4012 | Val_Spearman: -0.0119 | Trn_ACCLoss: 0.0203 | Val_ACCLoss: 0.1222 | Trn_NDCG: 0.8009 | Val_NDCG: 0.5544\nFold 57 | #Est: 8 | Trn_Spearman: 0.3993 | Val_Spearman: 0.0632 | Trn_ACCLoss: 0.0234 | Val_ACCLoss: 0.0556 | Trn_NDCG: 0.7780 | Val_NDCG: 0.6107\nFold 58 | #Est: 1 | Trn_Spearman: 0.3205 | Val_Spearman: -0.0110 | Trn_ACCLoss: 0.0407 | Val_ACCLoss: 0.1170 | Trn_NDCG: 0.7091 | Val_NDCG: 0.5368\nFold 59 | #Est: 55 | Trn_Spearman: 0.4195 | Val_Spearman: -0.1328 | Trn_ACCLoss: 0.0119 | Val_ACCLoss: 0.2943 | Trn_NDCG: 0.8148 | Val_NDCG: 0.4998\nFold 60 | #Est: 1 | Trn_Spearman: 0.2482 | Val_Spearman: 0.2143 | Trn_ACCLoss: 0.0775 | Val_ACCLoss: 0.0576 | Trn_NDCG: 0.6614 | Val_NDCG: 0.6679\nFold 61 | #Est: 2 | Trn_Spearman: 0.3733 | Val_Spearman: 0.0018 | Trn_ACCLoss: 0.0314 | Val_ACCLoss: 0.0635 | Trn_NDCG: 0.7634 | Val_NDCG: 0.6352\nFold 62 | #Est: 2 | Trn_Spearman: 0.3156 | Val_Spearman: 0.1493 | Trn_ACCLoss: 0.0578 | Val_ACCLoss: 0.0620 | Trn_NDCG: 0.7024 | Val_NDCG: 0.6215\nFold 63 | #Est: 4 | Trn_Spearman: 0.3557 | Val_Spearman: -0.0311 | Trn_ACCLoss: 0.0253 | Val_ACCLoss: 0.1228 | Trn_NDCG: 0.7615 | Val_NDCG: 0.5825\nFold 64 | #Est: 2 | Trn_Spearman: 0.3340 | Val_Spearman: 0.0485 | Trn_ACCLoss: 0.0437 | Val_ACCLoss: 0.0763 | Trn_NDCG: 0.6885 | Val_NDCG: 0.5861\nFold 65 | #Est: 57 | Trn_Spearman: 0.4374 | Val_Spearman: 0.0128 | Trn_ACCLoss: 0.0158 | Val_ACCLoss: 0.0227 | Trn_NDCG: 0.8131 | Val_NDCG: 0.6927\nFold 66 | #Est: 4 | Trn_Spearman: 0.3704 | Val_Spearman: 0.2024 | Trn_ACCLoss: 0.0296 | Val_ACCLoss: 0.2691 | Trn_NDCG: 0.7471 | Val_NDCG: 0.6197\nFold 67 | #Est: 24 | Trn_Spearman: 0.4042 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.0190 | Val_ACCLoss: 0.2183 | Trn_NDCG: 0.7937 | Val_NDCG: 0.5438\nFold 68 | #Est: 3 | Trn_Spearman: 0.4385 | Val_Spearman: 0.1484 | Trn_ACCLoss: 0.0174 | Val_ACCLoss: 0.0918 | Trn_NDCG: 0.7617 | Val_NDCG: 0.5756\nFold 69 | #Est: 19 | Trn_Spearman: 0.4127 | Val_Spearman: 0.2125 | Trn_ACCLoss: 0.0051 | Val_ACCLoss: 0.0699 | Trn_NDCG: 0.8683 | Val_NDCG: 0.7338\nFold 70 | #Est: 71 | Trn_Spearman: 0.4433 | Val_Spearman: 0.0046 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.8569 | Val_NDCG: 0.6213\nFold 71 | #Est: 1 | Trn_Spearman: 0.2540 | Val_Spearman: -0.0366 | Trn_ACCLoss: 0.0568 | Val_ACCLoss: 0.1257 | Trn_NDCG: 0.6517 | Val_NDCG: 0.6321\nFold 72 | #Est: 18 | Trn_Spearman: 0.4117 | Val_Spearman: 0.1465 | Trn_ACCLoss: 0.0046 | Val_ACCLoss: 0.0581 | Trn_NDCG: 0.8568 | Val_NDCG: 0.6511\nFold 73 | #Est: 18 | Trn_Spearman: 0.3821 | Val_Spearman: -0.0513 | Trn_ACCLoss: 0.0227 | Val_ACCLoss: 0.0650 | Trn_NDCG: 0.8010 | Val_NDCG: 0.5485\nFold 74 | #Est: 138 | Trn_Spearman: 0.4231 | Val_Spearman: 0.2454 | Trn_ACCLoss: 0.0031 | Val_ACCLoss: 0.0341 | Trn_NDCG: 0.8780 | Val_NDCG: 0.6483\nFold 75 | #Est: 30 | Trn_Spearman: 0.3965 | Val_Spearman: 0.2143 | Trn_ACCLoss: 0.0092 | Val_ACCLoss: 0.1294 | Trn_NDCG: 0.8482 | Val_NDCG: 0.6396\nFold 76 | #Est: 37 | Trn_Spearman: 0.4200 | Val_Spearman: 0.3672 | Trn_ACCLoss: 0.0090 | Val_ACCLoss: 0.0627 | Trn_NDCG: 0.8345 | Val_NDCG: 0.6548\nFold 77 | #Est: 2 | Trn_Spearman: 0.3740 | Val_Spearman: 0.0989 | Trn_ACCLoss: 0.0303 | Val_ACCLoss: 0.1676 | Trn_NDCG: 0.7296 | Val_NDCG: 0.6018\nFold 78 | #Est: 5 | Trn_Spearman: 0.3719 | Val_Spearman: 0.2701 | Trn_ACCLoss: 0.0414 | Val_ACCLoss: 0.0331 | Trn_NDCG: 0.7444 | Val_NDCG: 0.6145\nFold 79 | #Est: 19 | Trn_Spearman: 0.4021 | Val_Spearman: 0.0769 | Trn_ACCLoss: 0.0077 | Val_ACCLoss: 0.0497 | Trn_NDCG: 0.8508 | Val_NDCG: 0.5838\nFold 80 | #Est: 19 | Trn_Spearman: 0.4119 | Val_Spearman: -0.0916 | Trn_ACCLoss: 0.0182 | Val_ACCLoss: 0.1047 | Trn_NDCG: 0.8188 | Val_NDCG: 0.5693\nFold 81 | #Est: 43 | Trn_Spearman: 0.4315 | Val_Spearman: 0.1667 | Trn_ACCLoss: 0.0094 | Val_ACCLoss: 0.0806 | Trn_NDCG: 0.8628 | Val_NDCG: 0.5431\nFold 82 | #Est: 22 | Trn_Spearman: 0.4451 | Val_Spearman: 0.0833 | Trn_ACCLoss: 0.0102 | Val_ACCLoss: 0.1245 | Trn_NDCG: 0.8292 | Val_NDCG: 0.6168\nFold 83 | #Est: 27 | Trn_Spearman: 0.3944 | Val_Spearman: 0.0220 | Trn_ACCLoss: 0.0133 | Val_ACCLoss: 0.0487 | Trn_NDCG: 0.8317 | Val_NDCG: 0.6277\nFold 84 | #Est: 27 | Trn_Spearman: 0.4166 | Val_Spearman: 0.1832 | Trn_ACCLoss: 0.0117 | Val_ACCLoss: 0.0791 | Trn_NDCG: 0.8308 | Val_NDCG: 0.5824\nFold 85 | #Est: 40 | Trn_Spearman: 0.3544 | Val_Spearman: 0.1429 | Trn_ACCLoss: 0.0029 | Val_ACCLoss: 0.0719 | Trn_NDCG: 0.8612 | Val_NDCG: 0.6174\nFold 86 | #Est: 8 | Trn_Spearman: 0.3588 | Val_Spearman: 0.3260 | Trn_ACCLoss: 0.0216 | Val_ACCLoss: 0.0579 | Trn_NDCG: 0.7623 | Val_NDCG: 0.6468\nFold 87 | #Est: 1 | Trn_Spearman: 0.2125 | Val_Spearman: -0.1474 | Trn_ACCLoss: 0.0725 | Val_ACCLoss: 0.0721 | Trn_NDCG: 0.6504 | Val_NDCG: 0.5962\nFold 88 | #Est: 15 | Trn_Spearman: 0.3826 | Val_Spearman: 0.2894 | Trn_ACCLoss: 0.0198 | Val_ACCLoss: 0.0371 | Trn_NDCG: 0.8302 | Val_NDCG: 0.7045\nFold 89 | #Est: 78 | Trn_Spearman: 0.4296 | Val_Spearman: 0.1209 | Trn_ACCLoss: 0.0028 | Val_ACCLoss: 0.0744 | Trn_NDCG: 0.8764 | Val_NDCG: 0.5674\nFold 90 | #Est: 21 | Trn_Spearman: 0.4109 | Val_Spearman: 0.1969 | Trn_ACCLoss: 0.0163 | Val_ACCLoss: 0.1158 | Trn_NDCG: 0.8194 | Val_NDCG: 0.6708\nFold 91 | #Est: 2 | Trn_Spearman: 0.3628 | Val_Spearman: -0.1374 | Trn_ACCLoss: 0.0315 | Val_ACCLoss: 0.2593 | Trn_NDCG: 0.7492 | Val_NDCG: 0.5761\nFold 92 | #Est: 61 | Trn_Spearman: 0.4345 | Val_Spearman: 0.1126 | Trn_ACCLoss: 0.0110 | Val_ACCLoss: 0.1008 | Trn_NDCG: 0.8682 | Val_NDCG: 0.6008\nFold 93 | #Est: 27 | Trn_Spearman: 0.3767 | Val_Spearman: -0.0174 | Trn_ACCLoss: 0.0211 | Val_ACCLoss: 0.0612 | Trn_NDCG: 0.8023 | Val_NDCG: 0.6404\nFold 94 | #Est: 22 | Trn_Spearman: 0.3681 | Val_Spearman: 0.0238 | Trn_ACCLoss: 0.0210 | Val_ACCLoss: 0.0637 | Trn_NDCG: 0.8038 | Val_NDCG: 0.4970\nFold 95 | #Est: 1 | Trn_Spearman: 0.2120 | Val_Spearman: -0.1273 | Trn_ACCLoss: 0.0687 | Val_ACCLoss: 0.1474 | Trn_NDCG: 0.6416 | Val_NDCG: 0.5514\nFold 96 | #Est: 6 | Trn_Spearman: 0.3799 | Val_Spearman: 0.0147 | Trn_ACCLoss: 0.0248 | Val_ACCLoss: 0.1061 | Trn_NDCG: 0.7867 | Val_NDCG: 0.6024\nFold 97 | #Est: 31 | Trn_Spearman: 0.4008 | Val_Spearman: 0.0092 | Trn_ACCLoss: 0.0175 | Val_ACCLoss: 0.0600 | Trn_NDCG: 0.8407 | Val_NDCG: 0.5898\nFold 98 | #Est: 23 | Trn_Spearman: 0.3503 | Val_Spearman: -0.2134 | Trn_ACCLoss: 0.0135 | Val_ACCLoss: 0.1751 | Trn_NDCG: 0.8154 | Val_NDCG: 0.5536\nFold 99 | #Est: 20 | Trn_Spearman: 0.4177 | Val_Spearman: 0.3031 | Trn_ACCLoss: 0.0087 | Val_ACCLoss: 0.0695 | Trn_NDCG: 0.8309 | Val_NDCG: 0.7726\nFold 100 | #Est: 40 | Trn_Spearman: 0.4366 | Val_Spearman: 0.2115 | Trn_ACCLoss: 0.0082 | Val_ACCLoss: 0.1031 | Trn_NDCG: 0.8460 | Val_NDCG: 0.5841\n\nTrn_Spearman: 0.3714 +/-0.0634 | Val_Spearman: 0.0922 +/-0.1403\nTrn_ACCLoss: 0.0254 +/-0.0194 | Val_ACCLoss: 0.0921 +/-0.0564\nTrn_NDCG: 0.7845 +/-0.0671 | Val_NDCG: 0.6157 +/-0.0555\n\nCPU times: user 2min 17s, sys: 712 ms, total: 2min 18s\nWall time: 17 s\n"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=10, random_state=42)\nparams = {'objective': 'regression', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 2 | Trn_Spearman: 0.4294 | Val_Spearman: 0.3901 | Trn_ACCLoss: 0.0621 | Val_ACCLoss: 0.1853 | Trn_NDCG: 0.6465 | Val_NDCG: 0.6706\nFold 2 | #Est: 72 | Trn_Spearman: 0.5380 | Val_Spearman: 0.2903 | Trn_ACCLoss: 0.0387 | Val_ACCLoss: 0.1764 | Trn_NDCG: 0.7101 | Val_NDCG: 0.6252\nFold 3 | #Est: 30 | Trn_Spearman: 0.4639 | Val_Spearman: 0.1951 | Trn_ACCLoss: 0.0622 | Val_ACCLoss: 0.1125 | Trn_NDCG: 0.6839 | Val_NDCG: 0.5400\nFold 4 | #Est: 32 | Trn_Spearman: 0.4380 | Val_Spearman: 0.2601 | Trn_ACCLoss: 0.0456 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.6749 | Val_NDCG: 0.7206\nFold 5 | #Est: 15 | Trn_Spearman: 0.4373 | Val_Spearman: 0.0595 | Trn_ACCLoss: 0.0644 | Val_ACCLoss: 0.1327 | Trn_NDCG: 0.6335 | Val_NDCG: 0.5640\nFold 6 | #Est: 1 | Trn_Spearman: 0.2000 | Val_Spearman: -0.0568 | Trn_ACCLoss: 0.1398 | Val_ACCLoss: 0.0802 | Trn_NDCG: 0.5635 | Val_NDCG: 0.5381\nFold 7 | #Est: 3 | Trn_Spearman: 0.4399 | Val_Spearman: 0.0330 | Trn_ACCLoss: 0.0576 | Val_ACCLoss: 0.2797 | Trn_NDCG: 0.6632 | Val_NDCG: 0.5569\nFold 8 | #Est: 3 | Trn_Spearman: 0.3663 | Val_Spearman: 0.2161 | Trn_ACCLoss: 0.0908 | Val_ACCLoss: 0.0537 | Trn_NDCG: 0.6498 | Val_NDCG: 0.5777\nFold 9 | #Est: 1 | Trn_Spearman: 0.1851 | Val_Spearman: 0.1044 | Trn_ACCLoss: 0.1345 | Val_ACCLoss: 0.0799 | Trn_NDCG: 0.5629 | Val_NDCG: 0.5489\nFold 10 | #Est: 2 | Trn_Spearman: 0.3590 | Val_Spearman: 0.3315 | Trn_ACCLoss: 0.0841 | Val_ACCLoss: 0.1031 | Trn_NDCG: 0.6447 | Val_NDCG: 0.6456\nFold 11 | #Est: 1 | Trn_Spearman: 0.1913 | Val_Spearman: 0.0339 | Trn_ACCLoss: 0.1311 | Val_ACCLoss: 0.1860 | Trn_NDCG: 0.5565 | Val_NDCG: 0.5674\nFold 12 | #Est: 8 | Trn_Spearman: 0.4718 | Val_Spearman: 0.1493 | Trn_ACCLoss: 0.0408 | Val_ACCLoss: 0.2328 | Trn_NDCG: 0.6833 | Val_NDCG: 0.5897\nFold 13 | #Est: 1 | Trn_Spearman: 0.1909 | Val_Spearman: 0.0311 | Trn_ACCLoss: 0.1221 | Val_ACCLoss: 0.0504 | Trn_NDCG: 0.5691 | Val_NDCG: 0.5300\nFold 14 | #Est: 56 | Trn_Spearman: 0.4244 | Val_Spearman: 0.0897 | Trn_ACCLoss: 0.0699 | Val_ACCLoss: 0.0947 | Trn_NDCG: 0.6596 | Val_NDCG: 0.5096\nFold 15 | #Est: 1 | Trn_Spearman: 0.1867 | Val_Spearman: 0.0907 | Trn_ACCLoss: 0.1239 | Val_ACCLoss: 0.0639 | Trn_NDCG: 0.5598 | Val_NDCG: 0.6149\nFold 16 | #Est: 1 | Trn_Spearman: 0.1951 | Val_Spearman: -0.0366 | Trn_ACCLoss: 0.1288 | Val_ACCLoss: 0.1045 | Trn_NDCG: 0.5715 | Val_NDCG: 0.4773\nFold 17 | #Est: 14 | Trn_Spearman: 0.4290 | Val_Spearman: 0.3288 | Trn_ACCLoss: 0.0627 | Val_ACCLoss: 0.1061 | Trn_NDCG: 0.6674 | Val_NDCG: 0.7336\nFold 18 | #Est: 39 | Trn_Spearman: 0.4523 | Val_Spearman: 0.2024 | Trn_ACCLoss: 0.0571 | Val_ACCLoss: 0.2177 | Trn_NDCG: 0.6681 | Val_NDCG: 0.6221\nFold 19 | #Est: 26 | Trn_Spearman: 0.4142 | Val_Spearman: 0.3864 | Trn_ACCLoss: 0.0856 | Val_ACCLoss: 0.0742 | Trn_NDCG: 0.6351 | Val_NDCG: 0.6306\nFold 20 | #Est: 9 | Trn_Spearman: 0.3944 | Val_Spearman: 0.1520 | Trn_ACCLoss: 0.0904 | Val_ACCLoss: 0.1073 | Trn_NDCG: 0.6087 | Val_NDCG: 0.5774\nFold 21 | #Est: 5 | Trn_Spearman: 0.4792 | Val_Spearman: 0.2518 | Trn_ACCLoss: 0.0510 | Val_ACCLoss: 0.2838 | Trn_NDCG: 0.6968 | Val_NDCG: 0.6159\nFold 22 | #Est: 1 | Trn_Spearman: 0.1886 | Val_Spearman: 0.0604 | Trn_ACCLoss: 0.1312 | Val_ACCLoss: 0.1446 | Trn_NDCG: 0.5635 | Val_NDCG: 0.5112\nFold 23 | #Est: 47 | Trn_Spearman: 0.4187 | Val_Spearman: 0.1932 | Trn_ACCLoss: 0.0731 | Val_ACCLoss: 0.1317 | Trn_NDCG: 0.6394 | Val_NDCG: 0.5542\nFold 24 | #Est: 37 | Trn_Spearman: 0.4594 | Val_Spearman: 0.0229 | Trn_ACCLoss: 0.0714 | Val_ACCLoss: 0.0879 | Trn_NDCG: 0.6398 | Val_NDCG: 0.5863\nFold 25 | #Est: 1 | Trn_Spearman: 0.2008 | Val_Spearman: -0.0595 | Trn_ACCLoss: 0.1223 | Val_ACCLoss: 0.1455 | Trn_NDCG: 0.5707 | Val_NDCG: 0.4843\nFold 26 | #Est: 18 | Trn_Spearman: 0.4121 | Val_Spearman: 0.3773 | Trn_ACCLoss: 0.0623 | Val_ACCLoss: 0.0197 | Trn_NDCG: 0.6753 | Val_NDCG: 0.6645\nFold 27 | #Est: 2 | Trn_Spearman: 0.4366 | Val_Spearman: 0.2784 | Trn_ACCLoss: 0.0589 | Val_ACCLoss: 0.0529 | Trn_NDCG: 0.6768 | Val_NDCG: 0.6990\nFold 28 | #Est: 3 | Trn_Spearman: 0.4013 | Val_Spearman: 0.2280 | Trn_ACCLoss: 0.0662 | Val_ACCLoss: 0.1661 | Trn_NDCG: 0.6543 | Val_NDCG: 0.5212\nFold 29 | #Est: 31 | Trn_Spearman: 0.4369 | Val_Spearman: 0.0934 | Trn_ACCLoss: 0.0471 | Val_ACCLoss: 0.1033 | Trn_NDCG: 0.7096 | Val_NDCG: 0.6488\nFold 30 | #Est: 63 | Trn_Spearman: 0.4299 | Val_Spearman: 0.0476 | Trn_ACCLoss: 0.0577 | Val_ACCLoss: 0.0688 | Trn_NDCG: 0.6531 | Val_NDCG: 0.5522\nFold 31 | #Est: 12 | Trn_Spearman: 0.4363 | Val_Spearman: 0.2784 | Trn_ACCLoss: 0.0726 | Val_ACCLoss: 0.0442 | Trn_NDCG: 0.6747 | Val_NDCG: 0.6540\nFold 32 | #Est: 2 | Trn_Spearman: 0.4048 | Val_Spearman: 0.2811 | Trn_ACCLoss: 0.0774 | Val_ACCLoss: 0.0684 | Trn_NDCG: 0.6346 | Val_NDCG: 0.6650\nFold 33 | #Est: 34 | Trn_Spearman: 0.4172 | Val_Spearman: -0.0101 | Trn_ACCLoss: 0.0736 | Val_ACCLoss: 0.1727 | Trn_NDCG: 0.6601 | Val_NDCG: 0.5502\nFold 34 | #Est: 4 | Trn_Spearman: 0.4671 | Val_Spearman: 0.1896 | Trn_ACCLoss: 0.0493 | Val_ACCLoss: 0.0847 | Trn_NDCG: 0.6715 | Val_NDCG: 0.6369\nFold 35 | #Est: 1 | Trn_Spearman: 0.1674 | Val_Spearman: 0.2711 | Trn_ACCLoss: 0.1136 | Val_ACCLoss: 0.3335 | Trn_NDCG: 0.5521 | Val_NDCG: 0.6050\nFold 36 | #Est: 2 | Trn_Spearman: 0.4131 | Val_Spearman: 0.0330 | Trn_ACCLoss: 0.0918 | Val_ACCLoss: 0.1454 | Trn_NDCG: 0.6363 | Val_NDCG: 0.4855\nFold 37 | #Est: 1 | Trn_Spearman: 0.1636 | Val_Spearman: 0.3004 | Trn_ACCLoss: 0.1223 | Val_ACCLoss: 0.0907 | Trn_NDCG: 0.5663 | Val_NDCG: 0.5868\nFold 38 | #Est: 39 | Trn_Spearman: 0.4001 | Val_Spearman: 0.4029 | Trn_ACCLoss: 0.0695 | Val_ACCLoss: 0.0625 | Trn_NDCG: 0.6477 | Val_NDCG: 0.6868\nFold 39 | #Est: 147 | Trn_Spearman: 0.5192 | Val_Spearman: 0.1419 | Trn_ACCLoss: 0.0570 | Val_ACCLoss: 0.0421 | Trn_NDCG: 0.7128 | Val_NDCG: 0.5951\nFold 40 | #Est: 1 | Trn_Spearman: 0.1952 | Val_Spearman: -0.0870 | Trn_ACCLoss: 0.0991 | Val_ACCLoss: 0.0764 | Trn_NDCG: 0.5802 | Val_NDCG: 0.4961\nFold 41 | #Est: 4 | Trn_Spearman: 0.4252 | Val_Spearman: 0.3095 | Trn_ACCLoss: 0.0660 | Val_ACCLoss: 0.1120 | Trn_NDCG: 0.6662 | Val_NDCG: 0.6089\nFold 42 | #Est: 1 | Trn_Spearman: 0.1658 | Val_Spearman: 0.2995 | Trn_ACCLoss: 0.1203 | Val_ACCLoss: 0.2379 | Trn_NDCG: 0.5483 | Val_NDCG: 0.6528\nFold 43 | #Est: 1 | Trn_Spearman: 0.2063 | Val_Spearman: -0.1007 | Trn_ACCLoss: 0.1249 | Val_ACCLoss: 0.1616 | Trn_NDCG: 0.5712 | Val_NDCG: 0.5278\nFold 44 | #Est: 1 | Trn_Spearman: 0.1563 | Val_Spearman: 0.3956 | Trn_ACCLoss: 0.1336 | Val_ACCLoss: 0.1026 | Trn_NDCG: 0.5503 | Val_NDCG: 0.6519\nFold 45 | #Est: 37 | Trn_Spearman: 0.4250 | Val_Spearman: 0.1630 | Trn_ACCLoss: 0.0694 | Val_ACCLoss: 0.0448 | Trn_NDCG: 0.6611 | Val_NDCG: 0.5716\nFold 46 | #Est: 5 | Trn_Spearman: 0.4994 | Val_Spearman: -0.0192 | Trn_ACCLoss: 0.0282 | Val_ACCLoss: 0.0748 | Trn_NDCG: 0.6893 | Val_NDCG: 0.6391\nFold 47 | #Est: 24 | Trn_Spearman: 0.3981 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0619 | Val_ACCLoss: 0.0378 | Trn_NDCG: 0.6627 | Val_NDCG: 0.5918\nFold 48 | #Est: 1 | Trn_Spearman: 0.1842 | Val_Spearman: 0.0467 | Trn_ACCLoss: 0.1336 | Val_ACCLoss: 0.2136 | Trn_NDCG: 0.5641 | Val_NDCG: 0.4883\nFold 49 | #Est: 5 | Trn_Spearman: 0.3616 | Val_Spearman: 0.3141 | Trn_ACCLoss: 0.0808 | Val_ACCLoss: 0.0882 | Trn_NDCG: 0.6229 | Val_NDCG: 0.6206\nFold 50 | #Est: 2 | Trn_Spearman: 0.4124 | Val_Spearman: 0.0018 | Trn_ACCLoss: 0.0701 | Val_ACCLoss: 0.0534 | Trn_NDCG: 0.6312 | Val_NDCG: 0.5486\nFold 51 | #Est: 42 | Trn_Spearman: 0.3959 | Val_Spearman: 0.2115 | Trn_ACCLoss: 0.0690 | Val_ACCLoss: 0.0161 | Trn_NDCG: 0.6275 | Val_NDCG: 0.6463\nFold 52 | #Est: 63 | Trn_Spearman: 0.4126 | Val_Spearman: 0.4075 | Trn_ACCLoss: 0.0465 | Val_ACCLoss: 0.0324 | Trn_NDCG: 0.6946 | Val_NDCG: 0.7602\nFold 53 | #Est: 4 | Trn_Spearman: 0.4090 | Val_Spearman: 0.2289 | Trn_ACCLoss: 0.0651 | Val_ACCLoss: 0.0867 | Trn_NDCG: 0.6469 | Val_NDCG: 0.5741\nFold 54 | #Est: 33 | Trn_Spearman: 0.4494 | Val_Spearman: 0.2738 | Trn_ACCLoss: 0.0708 | Val_ACCLoss: 0.0997 | Trn_NDCG: 0.6772 | Val_NDCG: 0.5661\nFold 55 | #Est: 4 | Trn_Spearman: 0.4569 | Val_Spearman: 0.0485 | Trn_ACCLoss: 0.0640 | Val_ACCLoss: 0.1628 | Trn_NDCG: 0.6692 | Val_NDCG: 0.5115\nFold 56 | #Est: 1 | Trn_Spearman: 0.1719 | Val_Spearman: 0.2527 | Trn_ACCLoss: 0.1397 | Val_ACCLoss: 0.0829 | Trn_NDCG: 0.5519 | Val_NDCG: 0.6283\nFold 57 | #Est: 13 | Trn_Spearman: 0.4167 | Val_Spearman: 0.1868 | Trn_ACCLoss: 0.0621 | Val_ACCLoss: 0.0484 | Trn_NDCG: 0.6549 | Val_NDCG: 0.6158\nFold 58 | #Est: 32 | Trn_Spearman: 0.4762 | Val_Spearman: 0.3342 | Trn_ACCLoss: 0.0558 | Val_ACCLoss: 0.0524 | Trn_NDCG: 0.6796 | Val_NDCG: 0.5929\nFold 59 | #Est: 1 | Trn_Spearman: 0.1928 | Val_Spearman: -0.0641 | Trn_ACCLoss: 0.1336 | Val_ACCLoss: 0.4097 | Trn_NDCG: 0.5603 | Val_NDCG: 0.4599\nFold 60 | #Est: 5 | Trn_Spearman: 0.3822 | Val_Spearman: 0.0540 | Trn_ACCLoss: 0.0859 | Val_ACCLoss: 0.1522 | Trn_NDCG: 0.6376 | Val_NDCG: 0.5011\nFold 61 | #Est: 1 | Trn_Spearman: 0.1786 | Val_Spearman: 0.2115 | Trn_ACCLoss: 0.1433 | Val_ACCLoss: 0.0538 | Trn_NDCG: 0.5618 | Val_NDCG: 0.5446\nFold 62 | #Est: 1 | Trn_Spearman: 0.1843 | Val_Spearman: 0.0971 | Trn_ACCLoss: 0.1157 | Val_ACCLoss: 0.1189 | Trn_NDCG: 0.5659 | Val_NDCG: 0.5270\nFold 63 | #Est: 9 | Trn_Spearman: 0.3995 | Val_Spearman: 0.1877 | Trn_ACCLoss: 0.0748 | Val_ACCLoss: 0.0730 | Trn_NDCG: 0.6398 | Val_NDCG: 0.5954\nFold 64 | #Est: 1 | Trn_Spearman: 0.1814 | Val_Spearman: 0.1703 | Trn_ACCLoss: 0.1441 | Val_ACCLoss: 0.0757 | Trn_NDCG: 0.5583 | Val_NDCG: 0.5585\nFold 65 | #Est: 1 | Trn_Spearman: 0.1741 | Val_Spearman: 0.2289 | Trn_ACCLoss: 0.1379 | Val_ACCLoss: 0.0928 | Trn_NDCG: 0.5542 | Val_NDCG: 0.5996\nFold 66 | #Est: 21 | Trn_Spearman: 0.3726 | Val_Spearman: 0.1804 | Trn_ACCLoss: 0.0735 | Val_ACCLoss: 0.1322 | Trn_NDCG: 0.6371 | Val_NDCG: 0.5376\nFold 67 | #Est: 1 | Trn_Spearman: 0.1711 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.1291 | Val_ACCLoss: 0.2142 | Trn_NDCG: 0.5556 | Val_NDCG: 0.5954\nFold 68 | #Est: 11 | Trn_Spearman: 0.4613 | Val_Spearman: 0.1758 | Trn_ACCLoss: 0.0587 | Val_ACCLoss: 0.1070 | Trn_NDCG: 0.6816 | Val_NDCG: 0.6084\nFold 69 | #Est: 45 | Trn_Spearman: 0.4783 | Val_Spearman: 0.0687 | Trn_ACCLoss: 0.0641 | Val_ACCLoss: 0.1304 | Trn_NDCG: 0.6721 | Val_NDCG: 0.5994\nFold 70 | #Est: 1 | Trn_Spearman: 0.1903 | Val_Spearman: 0.0797 | Trn_ACCLoss: 0.1273 | Val_ACCLoss: 0.1955 | Trn_NDCG: 0.5659 | Val_NDCG: 0.5522\nFold 71 | #Est: 19 | Trn_Spearman: 0.4343 | Val_Spearman: -0.0440 | Trn_ACCLoss: 0.0694 | Val_ACCLoss: 0.0412 | Trn_NDCG: 0.6441 | Val_NDCG: 0.5842\nFold 72 | #Est: 2 | Trn_Spearman: 0.3941 | Val_Spearman: 0.1502 | Trn_ACCLoss: 0.0881 | Val_ACCLoss: 0.0902 | Trn_NDCG: 0.6125 | Val_NDCG: 0.5059\nFold 73 | #Est: 6 | Trn_Spearman: 0.4864 | Val_Spearman: 0.3929 | Trn_ACCLoss: 0.0506 | Val_ACCLoss: 0.0989 | Trn_NDCG: 0.6966 | Val_NDCG: 0.6883\nFold 74 | #Est: 1 | Trn_Spearman: 0.1808 | Val_Spearman: 0.1392 | Trn_ACCLoss: 0.1249 | Val_ACCLoss: 0.0657 | Trn_NDCG: 0.5683 | Val_NDCG: 0.5135\nFold 75 | #Est: 15 | Trn_Spearman: 0.4948 | Val_Spearman: 0.2179 | Trn_ACCLoss: 0.0426 | Val_ACCLoss: 0.1704 | Trn_NDCG: 0.6902 | Val_NDCG: 0.6459\nFold 76 | #Est: 7 | Trn_Spearman: 0.4420 | Val_Spearman: 0.0971 | Trn_ACCLoss: 0.0513 | Val_ACCLoss: 0.0877 | Trn_NDCG: 0.6785 | Val_NDCG: 0.6533\nFold 77 | #Est: 1 | Trn_Spearman: 0.1916 | Val_Spearman: 0.0650 | Trn_ACCLoss: 0.1145 | Val_ACCLoss: 0.3445 | Trn_NDCG: 0.5641 | Val_NDCG: 0.4956\nFold 78 | #Est: 2 | Trn_Spearman: 0.4301 | Val_Spearman: 0.2949 | Trn_ACCLoss: 0.0702 | Val_ACCLoss: 0.0999 | Trn_NDCG: 0.6726 | Val_NDCG: 0.5831\nFold 79 | #Est: 1 | Trn_Spearman: 0.1386 | Val_Spearman: 0.5082 | Trn_ACCLoss: 0.1252 | Val_ACCLoss: 0.0284 | Trn_NDCG: 0.5369 | Val_NDCG: 0.8095\nFold 80 | #Est: 30 | Trn_Spearman: 0.4377 | Val_Spearman: 0.0650 | Trn_ACCLoss: 0.0524 | Val_ACCLoss: 0.0936 | Trn_NDCG: 0.6915 | Val_NDCG: 0.5581\nFold 81 | #Est: 35 | Trn_Spearman: 0.4612 | Val_Spearman: 0.2592 | Trn_ACCLoss: 0.0734 | Val_ACCLoss: 0.0920 | Trn_NDCG: 0.6620 | Val_NDCG: 0.6066\nFold 82 | #Est: 2 | Trn_Spearman: 0.4015 | Val_Spearman: 0.0412 | Trn_ACCLoss: 0.0967 | Val_ACCLoss: 0.2400 | Trn_NDCG: 0.6259 | Val_NDCG: 0.5077\nFold 83 | #Est: 61 | Trn_Spearman: 0.5126 | Val_Spearman: 0.1401 | Trn_ACCLoss: 0.0421 | Val_ACCLoss: 0.0332 | Trn_NDCG: 0.6973 | Val_NDCG: 0.6805\nFold 84 | #Est: 3 | Trn_Spearman: 0.4245 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.0849 | Val_ACCLoss: 0.1066 | Trn_NDCG: 0.6328 | Val_NDCG: 0.5756\nFold 85 | #Est: 5 | Trn_Spearman: 0.4296 | Val_Spearman: 0.2463 | Trn_ACCLoss: 0.0483 | Val_ACCLoss: 0.0810 | Trn_NDCG: 0.6912 | Val_NDCG: 0.6315\nFold 86 | #Est: 2 | Trn_Spearman: 0.4614 | Val_Spearman: 0.1090 | Trn_ACCLoss: 0.0663 | Val_ACCLoss: 0.1035 | Trn_NDCG: 0.6462 | Val_NDCG: 0.6075\nFold 87 | #Est: 2 | Trn_Spearman: 0.3869 | Val_Spearman: 0.1172 | Trn_ACCLoss: 0.0900 | Val_ACCLoss: 0.0777 | Trn_NDCG: 0.6308 | Val_NDCG: 0.5043\nFold 88 | #Est: 1 | Trn_Spearman: 0.1692 | Val_Spearman: 0.2665 | Trn_ACCLoss: 0.1173 | Val_ACCLoss: 0.1208 | Trn_NDCG: 0.5632 | Val_NDCG: 0.5544\nFold 89 | #Est: 11 | Trn_Spearman: 0.4914 | Val_Spearman: 0.0833 | Trn_ACCLoss: 0.0269 | Val_ACCLoss: 0.0994 | Trn_NDCG: 0.7090 | Val_NDCG: 0.5231\nFold 90 | #Est: 1 | Trn_Spearman: 0.1746 | Val_Spearman: 0.1969 | Trn_ACCLoss: 0.1363 | Val_ACCLoss: 0.1664 | Trn_NDCG: 0.5612 | Val_NDCG: 0.5422\nFold 91 | #Est: 1 | Trn_Spearman: 0.1821 | Val_Spearman: 0.1447 | Trn_ACCLoss: 0.1072 | Val_ACCLoss: 0.2122 | Trn_NDCG: 0.5679 | Val_NDCG: 0.5486\nFold 92 | #Est: 1 | Trn_Spearman: 0.1857 | Val_Spearman: 0.1154 | Trn_ACCLoss: 0.1373 | Val_ACCLoss: 0.1006 | Trn_NDCG: 0.5650 | Val_NDCG: 0.5031\nFold 93 | #Est: 25 | Trn_Spearman: 0.4125 | Val_Spearman: 0.2894 | Trn_ACCLoss: 0.0719 | Val_ACCLoss: 0.1006 | Trn_NDCG: 0.6364 | Val_NDCG: 0.6730\nFold 94 | #Est: 1 | Trn_Spearman: 0.2027 | Val_Spearman: -0.0925 | Trn_ACCLoss: 0.1306 | Val_ACCLoss: 0.0949 | Trn_NDCG: 0.5636 | Val_NDCG: 0.5570\nFold 95 | #Est: 3 | Trn_Spearman: 0.4013 | Val_Spearman: 0.2390 | Trn_ACCLoss: 0.0587 | Val_ACCLoss: 0.0586 | Trn_NDCG: 0.6462 | Val_NDCG: 0.6503\nFold 96 | #Est: 33 | Trn_Spearman: 0.4265 | Val_Spearman: 0.3727 | Trn_ACCLoss: 0.0749 | Val_ACCLoss: 0.0518 | Trn_NDCG: 0.6450 | Val_NDCG: 0.7014\nFold 97 | #Est: 31 | Trn_Spearman: 0.4552 | Val_Spearman: 0.1090 | Trn_ACCLoss: 0.0501 | Val_ACCLoss: 0.0944 | Trn_NDCG: 0.6621 | Val_NDCG: 0.5655\nFold 98 | #Est: 41 | Trn_Spearman: 0.4863 | Val_Spearman: 0.1841 | Trn_ACCLoss: 0.0530 | Val_ACCLoss: 0.1314 | Trn_NDCG: 0.6918 | Val_NDCG: 0.6665\nFold 99 | #Est: 1 | Trn_Spearman: 0.1877 | Val_Spearman: 0.0998 | Trn_ACCLoss: 0.1330 | Val_ACCLoss: 0.2187 | Trn_NDCG: 0.5610 | Val_NDCG: 0.5454\nFold 100 | #Est: 5 | Trn_Spearman: 0.3858 | Val_Spearman: 0.3214 | Trn_ACCLoss: 0.0704 | Val_ACCLoss: 0.0790 | Trn_NDCG: 0.6350 | Val_NDCG: 0.6177\n\nTrn_Spearman: 0.3531 +/-0.1215 | Val_Spearman: 0.1699 +/-0.1319\nTrn_ACCLoss: 0.0847 +/-0.0324 | Val_ACCLoss: 0.1166 +/-0.0723\nTrn_NDCG: 0.6294 +/-0.0510 | Val_NDCG: 0.5891 +/-0.0665\n\nCPU times: user 2min 4s, sys: 752 ms, total: 2min 5s\nWall time: 13.7 s\n"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=10, random_state=42)\nparams = {'objective': 'binary', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train.shape[1] - y_train + 1, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 1 | Trn_Spearman: -0.0954 | Val_Spearman: 0.0375 | Trn_ACCLoss: 0.1136 | Val_ACCLoss: 0.1499 | Trn_NDCG: 0.5295 | Val_NDCG: 0.5097\nFold 2 | #Est: 1 | Trn_Spearman: -0.0900 | Val_Spearman: -0.0110 | Trn_ACCLoss: 0.1129 | Val_ACCLoss: 0.1561 | Trn_NDCG: 0.5317 | Val_NDCG: 0.4901\nFold 3 | #Est: 1 | Trn_Spearman: -0.0665 | Val_Spearman: -0.2225 | Trn_ACCLoss: 0.1216 | Val_ACCLoss: 0.0782 | Trn_NDCG: 0.5195 | Val_NDCG: 0.5999\nFold 4 | #Est: 1 | Trn_Spearman: -0.0980 | Val_Spearman: 0.0604 | Trn_ACCLoss: 0.1218 | Val_ACCLoss: 0.0761 | Trn_NDCG: 0.5231 | Val_NDCG: 0.5679\nFold 5 | #Est: 1 | Trn_Spearman: -0.0736 | Val_Spearman: -0.1593 | Trn_ACCLoss: 0.1107 | Val_ACCLoss: 0.1763 | Trn_NDCG: 0.5227 | Val_NDCG: 0.5713\nFold 6 | #Est: 1 | Trn_Spearman: -0.0648 | Val_Spearman: -0.2381 | Trn_ACCLoss: 0.1159 | Val_ACCLoss: 0.1295 | Trn_NDCG: 0.5292 | Val_NDCG: 0.5131\nFold 7 | #Est: 1 | Trn_Spearman: -0.1095 | Val_Spearman: 0.1639 | Trn_ACCLoss: 0.1209 | Val_ACCLoss: 0.0838 | Trn_NDCG: 0.5358 | Val_NDCG: 0.4532\nFold 8 | #Est: 1 | Trn_Spearman: -0.0979 | Val_Spearman: 0.0595 | Trn_ACCLoss: 0.1249 | Val_ACCLoss: 0.0480 | Trn_NDCG: 0.5292 | Val_NDCG: 0.5126\nFold 9 | #Est: 1 | Trn_Spearman: -0.0696 | Val_Spearman: -0.1951 | Trn_ACCLoss: 0.1212 | Val_ACCLoss: 0.0812 | Trn_NDCG: 0.5300 | Val_NDCG: 0.5056\nFold 10 | #Est: 1 | Trn_Spearman: -0.0561 | Val_Spearman: -0.3168 | Trn_ACCLoss: 0.1088 | Val_ACCLoss: 0.1932 | Trn_NDCG: 0.5248 | Val_NDCG: 0.5521\nFold 11 | #Est: 1 | Trn_Spearman: -0.1212 | Val_Spearman: 0.2692 | Trn_ACCLoss: 0.1238 | Val_ACCLoss: 0.0584 | Trn_NDCG: 0.5374 | Val_NDCG: 0.4386\nFold 12 | #Est: 1 | Trn_Spearman: -0.0899 | Val_Spearman: -0.0119 | Trn_ACCLoss: 0.1215 | Val_ACCLoss: 0.0787 | Trn_NDCG: 0.5364 | Val_NDCG: 0.4475\nFold 13 | #Est: 1 | Trn_Spearman: -0.0759 | Val_Spearman: -0.1383 | Trn_ACCLoss: 0.1230 | Val_ACCLoss: 0.0650 | Trn_NDCG: 0.5197 | Val_NDCG: 0.5979\nFold 14 | #Est: 1 | Trn_Spearman: -0.0601 | Val_Spearman: -0.2802 | Trn_ACCLoss: 0.1182 | Val_ACCLoss: 0.1087 | Trn_NDCG: 0.5209 | Val_NDCG: 0.5870\nFold 15 | #Est: 1 | Trn_Spearman: -0.0733 | Val_Spearman: -0.1621 | Trn_ACCLoss: 0.1222 | Val_ACCLoss: 0.0723 | Trn_NDCG: 0.5222 | Val_NDCG: 0.5758\nFold 16 | #Est: 1 | Trn_Spearman: -0.0590 | Val_Spearman: -0.2903 | Trn_ACCLoss: 0.1162 | Val_ACCLoss: 0.1269 | Trn_NDCG: 0.5244 | Val_NDCG: 0.5562\nFold 17 | #Est: 1 | Trn_Spearman: -0.0719 | Val_Spearman: -0.1740 | Trn_ACCLoss: 0.1040 | Val_ACCLoss: 0.2365 | Trn_NDCG: 0.5288 | Val_NDCG: 0.5162\nFold 18 | #Est: 1 | Trn_Spearman: -0.0790 | Val_Spearman: -0.1108 | Trn_ACCLoss: 0.1096 | Val_ACCLoss: 0.1862 | Trn_NDCG: 0.5284 | Val_NDCG: 0.5198\nFold 19 | #Est: 1 | Trn_Spearman: -0.0657 | Val_Spearman: -0.2299 | Trn_ACCLoss: 0.1099 | Val_ACCLoss: 0.1834 | Trn_NDCG: 0.5230 | Val_NDCG: 0.5683\nFold 20 | #Est: 1 | Trn_Spearman: -0.1254 | Val_Spearman: 0.3068 | Trn_ACCLoss: 0.1240 | Val_ACCLoss: 0.0562 | Trn_NDCG: 0.5342 | Val_NDCG: 0.4680\nFold 21 | #Est: 1 | Trn_Spearman: -0.0986 | Val_Spearman: 0.0659 | Trn_ACCLoss: 0.1201 | Val_ACCLoss: 0.0918 | Trn_NDCG: 0.5254 | Val_NDCG: 0.5471\nFold 22 | #Est: 1 | Trn_Spearman: -0.0648 | Val_Spearman: -0.2381 | Trn_ACCLoss: 0.1130 | Val_ACCLoss: 0.1553 | Trn_NDCG: 0.5285 | Val_NDCG: 0.5191\nFold 23 | #Est: 1 | Trn_Spearman: -0.0836 | Val_Spearman: -0.0687 | Trn_ACCLoss: 0.1184 | Val_ACCLoss: 0.1070 | Trn_NDCG: 0.5324 | Val_NDCG: 0.4842\nFold 24 | #Est: 1 | Trn_Spearman: -0.0746 | Val_Spearman: -0.1502 | Trn_ACCLoss: 0.1135 | Val_ACCLoss: 0.1508 | Trn_NDCG: 0.5309 | Val_NDCG: 0.4970\nFold 25 | #Est: 1 | Trn_Spearman: -0.0718 | Val_Spearman: -0.1749 | Trn_ACCLoss: 0.1082 | Val_ACCLoss: 0.1983 | Trn_NDCG: 0.5283 | Val_NDCG: 0.5205\nFold 26 | #Est: 1 | Trn_Spearman: -0.0739 | Val_Spearman: -0.1566 | Trn_ACCLoss: 0.1212 | Val_ACCLoss: 0.0817 | Trn_NDCG: 0.5222 | Val_NDCG: 0.5761\nFold 27 | #Est: 1 | Trn_Spearman: -0.0981 | Val_Spearman: 0.0614 | Trn_ACCLoss: 0.1240 | Val_ACCLoss: 0.0564 | Trn_NDCG: 0.5292 | Val_NDCG: 0.5125\nFold 28 | #Est: 1 | Trn_Spearman: -0.0823 | Val_Spearman: -0.0806 | Trn_ACCLoss: 0.1147 | Val_ACCLoss: 0.1397 | Trn_NDCG: 0.5230 | Val_NDCG: 0.5686\nFold 29 | #Est: 1 | Trn_Spearman: -0.0758 | Val_Spearman: -0.1392 | Trn_ACCLoss: 0.1155 | Val_ACCLoss: 0.1332 | Trn_NDCG: 0.5315 | Val_NDCG: 0.4924\nFold 30 | #Est: 1 | Trn_Spearman: -0.0979 | Val_Spearman: 0.0595 | Trn_ACCLoss: 0.1238 | Val_ACCLoss: 0.0581 | Trn_NDCG: 0.5242 | Val_NDCG: 0.5580\nFold 31 | #Est: 1 | Trn_Spearman: -0.1199 | Val_Spearman: 0.2573 | Trn_ACCLoss: 0.1240 | Val_ACCLoss: 0.0567 | Trn_NDCG: 0.5376 | Val_NDCG: 0.4367\nFold 32 | #Est: 1 | Trn_Spearman: -0.0756 | Val_Spearman: -0.1410 | Trn_ACCLoss: 0.1222 | Val_ACCLoss: 0.0724 | Trn_NDCG: 0.5196 | Val_NDCG: 0.5987\nFold 33 | #Est: 1 | Trn_Spearman: -0.0687 | Val_Spearman: -0.2033 | Trn_ACCLoss: 0.1076 | Val_ACCLoss: 0.2044 | Trn_NDCG: 0.5231 | Val_NDCG: 0.5678\nFold 34 | #Est: 1 | Trn_Spearman: -0.0945 | Val_Spearman: 0.0293 | Trn_ACCLoss: 0.1248 | Val_ACCLoss: 0.0493 | Trn_NDCG: 0.5335 | Val_NDCG: 0.4737\nFold 35 | #Est: 1 | Trn_Spearman: -0.0936 | Val_Spearman: 0.0211 | Trn_ACCLoss: 0.1028 | Val_ACCLoss: 0.2469 | Trn_NDCG: 0.5320 | Val_NDCG: 0.4879\nFold 36 | #Est: 1 | Trn_Spearman: -0.0847 | Val_Spearman: -0.0595 | Trn_ACCLoss: 0.1195 | Val_ACCLoss: 0.0972 | Trn_NDCG: 0.5311 | Val_NDCG: 0.4958\nFold 37 | #Est: 1 | Trn_Spearman: -0.0758 | Val_Spearman: -0.1392 | Trn_ACCLoss: 0.1162 | Val_ACCLoss: 0.1266 | Trn_NDCG: 0.5240 | Val_NDCG: 0.5592\nFold 38 | #Est: 1 | Trn_Spearman: -0.0798 | Val_Spearman: -0.1035 | Trn_ACCLoss: 0.1107 | Val_ACCLoss: 0.1760 | Trn_NDCG: 0.5295 | Val_NDCG: 0.5101\nFold 39 | #Est: 1 | Trn_Spearman: -0.0578 | Val_Spearman: -0.3013 | Trn_ACCLoss: 0.1225 | Val_ACCLoss: 0.0697 | Trn_NDCG: 0.5250 | Val_NDCG: 0.5502\nFold 40 | #Est: 1 | Trn_Spearman: -0.0711 | Val_Spearman: -0.1813 | Trn_ACCLoss: 0.1221 | Val_ACCLoss: 0.0732 | Trn_NDCG: 0.5200 | Val_NDCG: 0.5954\nFold 41 | #Est: 1 | Trn_Spearman: -0.0933 | Val_Spearman: 0.0183 | Trn_ACCLoss: 0.1249 | Val_ACCLoss: 0.0479 | Trn_NDCG: 0.5279 | Val_NDCG: 0.5241\nFold 42 | #Est: 1 | Trn_Spearman: -0.0645 | Val_Spearman: -0.2408 | Trn_ACCLoss: 0.1085 | Val_ACCLoss: 0.1958 | Trn_NDCG: 0.5241 | Val_NDCG: 0.5582\nFold 43 | #Est: 1 | Trn_Spearman: -0.1272 | Val_Spearman: 0.3233 | Trn_ACCLoss: 0.1277 | Val_ACCLoss: 0.0232 | Trn_NDCG: 0.5383 | Val_NDCG: 0.4309\nFold 44 | #Est: 1 | Trn_Spearman: -0.0612 | Val_Spearman: -0.2711 | Trn_ACCLoss: 0.1002 | Val_ACCLoss: 0.2707 | Trn_NDCG: 0.5230 | Val_NDCG: 0.5680\nFold 45 | #Est: 1 | Trn_Spearman: -0.0906 | Val_Spearman: -0.0064 | Trn_ACCLoss: 0.1134 | Val_ACCLoss: 0.1516 | Trn_NDCG: 0.5316 | Val_NDCG: 0.4915\nFold 46 | #Est: 1 | Trn_Spearman: -0.1033 | Val_Spearman: 0.1081 | Trn_ACCLoss: 0.1271 | Val_ACCLoss: 0.0281 | Trn_NDCG: 0.5309 | Val_NDCG: 0.4976\nFold 47 | #Est: 1 | Trn_Spearman: -0.0770 | Val_Spearman: -0.1282 | Trn_ACCLoss: 0.1221 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.5241 | Val_NDCG: 0.5582\nFold 48 | #Est: 1 | Trn_Spearman: -0.0770 | Val_Spearman: -0.1282 | Trn_ACCLoss: 0.1169 | Val_ACCLoss: 0.1200 | Trn_NDCG: 0.5348 | Val_NDCG: 0.4626\nFold 49 | #Est: 1 | Trn_Spearman: -0.0626 | Val_Spearman: -0.2582 | Trn_ACCLoss: 0.1113 | Val_ACCLoss: 0.1711 | Trn_NDCG: 0.5203 | Val_NDCG: 0.5926\nFold 50 | #Est: 1 | Trn_Spearman: -0.0648 | Val_Spearman: -0.2381 | Trn_ACCLoss: 0.1202 | Val_ACCLoss: 0.0909 | Trn_NDCG: 0.5204 | Val_NDCG: 0.5917\nFold 51 | #Est: 1 | Trn_Spearman: -0.0758 | Val_Spearman: -0.1392 | Trn_ACCLoss: 0.1203 | Val_ACCLoss: 0.0899 | Trn_NDCG: 0.5178 | Val_NDCG: 0.6153\nFold 52 | #Est: 1 | Trn_Spearman: -0.0500 | Val_Spearman: -0.3718 | Trn_ACCLoss: 0.0974 | Val_ACCLoss: 0.2955 | Trn_NDCG: 0.5219 | Val_NDCG: 0.5787\nFold 53 | #Est: 1 | Trn_Spearman: -0.1010 | Val_Spearman: 0.0879 | Trn_ACCLoss: 0.1162 | Val_ACCLoss: 0.1264 | Trn_NDCG: 0.5328 | Val_NDCG: 0.4802\nFold 54 | #Est: 1 | Trn_Spearman: -0.0672 | Val_Spearman: -0.2170 | Trn_ACCLoss: 0.1183 | Val_ACCLoss: 0.1076 | Trn_NDCG: 0.5277 | Val_NDCG: 0.5266\nFold 55 | #Est: 1 | Trn_Spearman: -0.0938 | Val_Spearman: 0.0229 | Trn_ACCLoss: 0.1234 | Val_ACCLoss: 0.0613 | Trn_NDCG: 0.5344 | Val_NDCG: 0.4656\nFold 56 | #Est: 1 | Trn_Spearman: -0.0737 | Val_Spearman: -0.1584 | Trn_ACCLoss: 0.1166 | Val_ACCLoss: 0.1227 | Trn_NDCG: 0.5308 | Val_NDCG: 0.4983\nFold 57 | #Est: 1 | Trn_Spearman: -0.0842 | Val_Spearman: -0.0632 | Trn_ACCLoss: 0.1250 | Val_ACCLoss: 0.0472 | Trn_NDCG: 0.5229 | Val_NDCG: 0.5692\nFold 58 | #Est: 1 | Trn_Spearman: -0.0760 | Val_Spearman: -0.1374 | Trn_ACCLoss: 0.1159 | Val_ACCLoss: 0.1295 | Trn_NDCG: 0.5279 | Val_NDCG: 0.5241\nFold 59 | #Est: 1 | Trn_Spearman: -0.1030 | Val_Spearman: 0.1053 | Trn_ACCLoss: 0.1173 | Val_ACCLoss: 0.1169 | Trn_NDCG: 0.5320 | Val_NDCG: 0.4878\nFold 60 | #Est: 1 | Trn_Spearman: -0.0968 | Val_Spearman: 0.0495 | Trn_ACCLoss: 0.1219 | Val_ACCLoss: 0.0753 | Trn_NDCG: 0.5273 | Val_NDCG: 0.5296\nFold 61 | #Est: 1 | Trn_Spearman: -0.0861 | Val_Spearman: -0.0467 | Trn_ACCLoss: 0.1209 | Val_ACCLoss: 0.0844 | Trn_NDCG: 0.5238 | Val_NDCG: 0.5609\nFold 62 | #Est: 1 | Trn_Spearman: -0.0838 | Val_Spearman: -0.0668 | Trn_ACCLoss: 0.1133 | Val_ACCLoss: 0.1523 | Trn_NDCG: 0.5223 | Val_NDCG: 0.5746\nFold 63 | #Est: 1 | Trn_Spearman: -0.0756 | Val_Spearman: -0.1410 | Trn_ACCLoss: 0.1189 | Val_ACCLoss: 0.1023 | Trn_NDCG: 0.5291 | Val_NDCG: 0.5132\nFold 64 | #Est: 1 | Trn_Spearman: -0.0828 | Val_Spearman: -0.0760 | Trn_ACCLoss: 0.1200 | Val_ACCLoss: 0.0921 | Trn_NDCG: 0.5283 | Val_NDCG: 0.5203\nFold 65 | #Est: 1 | Trn_Spearman: -0.0638 | Val_Spearman: -0.2473 | Trn_ACCLoss: 0.1142 | Val_ACCLoss: 0.1444 | Trn_NDCG: 0.5216 | Val_NDCG: 0.5811\nFold 66 | #Est: 1 | Trn_Spearman: -0.0745 | Val_Spearman: -0.1511 | Trn_ACCLoss: 0.1020 | Val_ACCLoss: 0.2546 | Trn_NDCG: 0.5301 | Val_NDCG: 0.5042\nFold 67 | #Est: 1 | Trn_Spearman: -0.0865 | Val_Spearman: -0.0430 | Trn_ACCLoss: 0.1211 | Val_ACCLoss: 0.0829 | Trn_NDCG: 0.5277 | Val_NDCG: 0.5262\nFold 68 | #Est: 1 | Trn_Spearman: -0.0836 | Val_Spearman: -0.0687 | Trn_ACCLoss: 0.1247 | Val_ACCLoss: 0.0499 | Trn_NDCG: 0.5343 | Val_NDCG: 0.4669\nFold 69 | #Est: 1 | Trn_Spearman: -0.0864 | Val_Spearman: -0.0440 | Trn_ACCLoss: 0.1231 | Val_ACCLoss: 0.0643 | Trn_NDCG: 0.5256 | Val_NDCG: 0.5454\nFold 70 | #Est: 1 | Trn_Spearman: -0.0983 | Val_Spearman: 0.0632 | Trn_ACCLoss: 0.1141 | Val_ACCLoss: 0.1452 | Trn_NDCG: 0.5325 | Val_NDCG: 0.4827\nFold 71 | #Est: 1 | Trn_Spearman: -0.0753 | Val_Spearman: -0.1438 | Trn_ACCLoss: 0.1159 | Val_ACCLoss: 0.1292 | Trn_NDCG: 0.5276 | Val_NDCG: 0.5269\nFold 72 | #Est: 1 | Trn_Spearman: -0.0994 | Val_Spearman: 0.0733 | Trn_ACCLoss: 0.1206 | Val_ACCLoss: 0.0869 | Trn_NDCG: 0.5278 | Val_NDCG: 0.5254\nFold 73 | #Est: 1 | Trn_Spearman: -0.1159 | Val_Spearman: 0.2216 | Trn_ACCLoss: 0.1207 | Val_ACCLoss: 0.0862 | Trn_NDCG: 0.5306 | Val_NDCG: 0.5000\nFold 74 | #Est: 1 | Trn_Spearman: -0.0582 | Val_Spearman: -0.2976 | Trn_ACCLoss: 0.1193 | Val_ACCLoss: 0.0987 | Trn_NDCG: 0.5146 | Val_NDCG: 0.6440\nFold 75 | #Est: 1 | Trn_Spearman: -0.0904 | Val_Spearman: -0.0082 | Trn_ACCLoss: 0.1131 | Val_ACCLoss: 0.1545 | Trn_NDCG: 0.5363 | Val_NDCG: 0.4483\nFold 76 | #Est: 1 | Trn_Spearman: -0.0719 | Val_Spearman: -0.1740 | Trn_ACCLoss: 0.1163 | Val_ACCLoss: 0.1260 | Trn_NDCG: 0.5304 | Val_NDCG: 0.5015\nFold 77 | #Est: 1 | Trn_Spearman: -0.0940 | Val_Spearman: 0.0247 | Trn_ACCLoss: 0.1196 | Val_ACCLoss: 0.0956 | Trn_NDCG: 0.5337 | Val_NDCG: 0.4726\nFold 78 | #Est: 1 | Trn_Spearman: -0.0762 | Val_Spearman: -0.1355 | Trn_ACCLoss: 0.1200 | Val_ACCLoss: 0.0924 | Trn_NDCG: 0.5248 | Val_NDCG: 0.5525\nFold 79 | #Est: 1 | Trn_Spearman: -0.0497 | Val_Spearman: -0.3745 | Trn_ACCLoss: 0.1032 | Val_ACCLoss: 0.2437 | Trn_NDCG: 0.5231 | Val_NDCG: 0.5672\nFold 80 | #Est: 1 | Trn_Spearman: -0.0905 | Val_Spearman: -0.0073 | Trn_ACCLoss: 0.1237 | Val_ACCLoss: 0.0592 | Trn_NDCG: 0.5265 | Val_NDCG: 0.5371\nFold 81 | #Est: 1 | Trn_Spearman: -0.0535 | Val_Spearman: -0.3397 | Trn_ACCLoss: 0.1162 | Val_ACCLoss: 0.1263 | Trn_NDCG: 0.5204 | Val_NDCG: 0.5915\nFold 82 | #Est: 1 | Trn_Spearman: -0.0870 | Val_Spearman: -0.0385 | Trn_ACCLoss: 0.1215 | Val_ACCLoss: 0.0789 | Trn_NDCG: 0.5319 | Val_NDCG: 0.4882\nFold 83 | #Est: 1 | Trn_Spearman: -0.0870 | Val_Spearman: -0.0385 | Trn_ACCLoss: 0.1221 | Val_ACCLoss: 0.0731 | Trn_NDCG: 0.5300 | Val_NDCG: 0.5056\nFold 84 | #Est: 1 | Trn_Spearman: -0.0738 | Val_Spearman: -0.1575 | Trn_ACCLoss: 0.1133 | Val_ACCLoss: 0.1530 | Trn_NDCG: 0.5264 | Val_NDCG: 0.5378\nFold 85 | #Est: 1 | Trn_Spearman: -0.0892 | Val_Spearman: -0.0183 | Trn_ACCLoss: 0.1150 | Val_ACCLoss: 0.1374 | Trn_NDCG: 0.5288 | Val_NDCG: 0.5164\nFold 86 | #Est: 1 | Trn_Spearman: -0.0903 | Val_Spearman: -0.0092 | Trn_ACCLoss: 0.1092 | Val_ACCLoss: 0.1898 | Trn_NDCG: 0.5306 | Val_NDCG: 0.5005\nFold 87 | #Est: 1 | Trn_Spearman: -0.0511 | Val_Spearman: -0.3617 | Trn_ACCLoss: 0.1200 | Val_ACCLoss: 0.0924 | Trn_NDCG: 0.5175 | Val_NDCG: 0.6181\nFold 88 | #Est: 1 | Trn_Spearman: -0.0711 | Val_Spearman: -0.1813 | Trn_ACCLoss: 0.1097 | Val_ACCLoss: 0.1847 | Trn_NDCG: 0.5173 | Val_NDCG: 0.6196\nFold 89 | #Est: 1 | Trn_Spearman: -0.1336 | Val_Spearman: 0.3810 | Trn_ACCLoss: 0.1294 | Val_ACCLoss: 0.0076 | Trn_NDCG: 0.5396 | Val_NDCG: 0.4195\nFold 90 | #Est: 1 | Trn_Spearman: -0.0849 | Val_Spearman: -0.0577 | Trn_ACCLoss: 0.1159 | Val_ACCLoss: 0.1293 | Trn_NDCG: 0.5330 | Val_NDCG: 0.4781\nFold 91 | #Est: 1 | Trn_Spearman: -0.0722 | Val_Spearman: -0.1712 | Trn_ACCLoss: 0.1186 | Val_ACCLoss: 0.1049 | Trn_NDCG: 0.5195 | Val_NDCG: 0.5999\nFold 92 | #Est: 1 | Trn_Spearman: -0.0811 | Val_Spearman: -0.0916 | Trn_ACCLoss: 0.1133 | Val_ACCLoss: 0.1529 | Trn_NDCG: 0.5315 | Val_NDCG: 0.4918\nFold 93 | #Est: 1 | Trn_Spearman: -0.0800 | Val_Spearman: -0.1016 | Trn_ACCLoss: 0.1207 | Val_ACCLoss: 0.0860 | Trn_NDCG: 0.5239 | Val_NDCG: 0.5605\nFold 94 | #Est: 1 | Trn_Spearman: -0.0698 | Val_Spearman: -0.1932 | Trn_ACCLoss: 0.1219 | Val_ACCLoss: 0.0754 | Trn_NDCG: 0.5252 | Val_NDCG: 0.5489\nFold 95 | #Est: 1 | Trn_Spearman: -0.0766 | Val_Spearman: -0.1319 | Trn_ACCLoss: 0.1157 | Val_ACCLoss: 0.1306 | Trn_NDCG: 0.5204 | Val_NDCG: 0.5917\nFold 96 | #Est: 1 | Trn_Spearman: -0.0732 | Val_Spearman: -0.1630 | Trn_ACCLoss: 0.1222 | Val_ACCLoss: 0.0727 | Trn_NDCG: 0.5246 | Val_NDCG: 0.5538\nFold 97 | #Est: 1 | Trn_Spearman: -0.0960 | Val_Spearman: 0.0421 | Trn_ACCLoss: 0.1231 | Val_ACCLoss: 0.0642 | Trn_NDCG: 0.5331 | Val_NDCG: 0.4779\nFold 98 | #Est: 1 | Trn_Spearman: -0.0732 | Val_Spearman: -0.1630 | Trn_ACCLoss: 0.1046 | Val_ACCLoss: 0.2312 | Trn_NDCG: 0.5293 | Val_NDCG: 0.5115\nFold 99 | #Est: 1 | Trn_Spearman: -0.1014 | Val_Spearman: 0.0916 | Trn_ACCLoss: 0.1154 | Val_ACCLoss: 0.1341 | Trn_NDCG: 0.5383 | Val_NDCG: 0.4309\nFold 100 | #Est: 1 | Trn_Spearman: -0.0980 | Val_Spearman: 0.0604 | Trn_ACCLoss: 0.1169 | Val_ACCLoss: 0.1203 | Trn_NDCG: 0.5297 | Val_NDCG: 0.5085\n\nTrn_Spearman: -0.0821 +/-0.0170 | Val_Spearman: -0.0821 +/-0.1533\nTrn_ACCLoss: 0.1172 +/-0.0064 | Val_ACCLoss: 0.1172 +/-0.0573\nTrn_NDCG: 0.5275 +/-0.0054 | Val_NDCG: 0.5275 +/-0.0486\n\nCPU times: user 39.2 s, sys: 184 ms, total: 39.4 s\nWall time: 6.42 s\n"
],
[
"# LambdaRank\nTrn_Spearman: 0.3714 +/-0.0634 | Val_Spearman: 0.0922 +/-0.1403\nTrn_ACCLoss: 0.0254 +/-0.0194 | Val_ACCLoss: 0.0921 +/-0.0564\nTrn_NDCG: 0.7845 +/-0.0671 | Val_NDCG: 0.6157 +/-0.0555\n\n# Regression \nTrn_Spearman: 0.3531 +/-0.1215 | Val_Spearman: 0.1699 +/-0.1319\nTrn_ACCLoss: 0.0847 +/-0.0324 | Val_ACCLoss: 0.1166 +/-0.0723\nTrn_NDCG: 0.6294 +/-0.0510 | Val_NDCG: 0.5891 +/-0.0665\n \n# Binary Classification \nTrn_Spearman: -0.0821 +/-0.0170 | Val_Spearman: -0.0821 +/-0.1533\nTrn_ACCLoss: 0.1172 +/-0.0064 | Val_ACCLoss: 0.1172 +/-0.0573\nTrn_NDCG: 0.5275 +/-0.0054 | Val_NDCG: 0.5275 +/-0.0486 ",
"_____no_output_____"
]
],
[
[
"## New ranking",
"_____no_output_____"
]
],
[
[
"%%time\nfrom sklearn.model_selection import train_test_split\nrp = Pipeline([\n ('scale', StandardScaler()),\n ('estimator', RankingPredictor(\"ma_100\", n_neighbors=15)),\n])\ndf_mf, df_rank, df_scores, _ = rp.named_steps['estimator'].get_data()\n\ndf_mf = df_mf.sort_index()\ndf_rank = df_rank.sort_index()\ndf_scores = df_scores.sort_index()\n\nX_train, _, y_train, _, y_scores_train, _ = train_test_split(df_mf.values,\n df_rank.values,\n df_scores.values,\n test_size=0,\n random_state=42)\nprint(X_train.shape, y_train.shape, y_scores_train.shape)",
"(60, 39) (60, 13) (60, 13)\nCPU times: user 56 s, sys: 2.85 s, total: 58.8 s\nWall time: 58.6 s\n"
],
[
"df_mf.head()",
"_____no_output_____"
],
[
"df_rank.head()",
"_____no_output_____"
],
[
"df_scores.head()",
"_____no_output_____"
],
[
"%%time\nimport lightgbm\nfrom project.ranker.ltr_rankers import cv_lgbm\nfrom sklearn.model_selection import RepeatedKFold\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nparams = {'objective': 'lambdarank', \n 'metric': 'ndcg', \n 'learning_rate': 1e-3,\n# 'num_leaves': 50,\n 'ndcg_at': y_train.shape[1],\n 'min_data_in_leaf': 3,\n 'min_sum_hessian_in_leaf': 1e-4}\nresults, models = cv_lgbm(lightgbm, X_train, y_train, y_scores_train, kfolds, \n params, num_rounds=1000, early_stopping_rounds=50, verbose_eval=False)",
"Fold 1 | #Est: 167 | Trn_Spearman: 0.4662 | Val_Spearman: 0.2747 | Trn_ACCLoss: 0.2572 | Val_ACCLoss: 0.1465 | Trn_NDCG: 0.8668 | Val_NDCG: 0.6631\nFold 2 | #Est: 137 | Trn_Spearman: 0.4648 | Val_Spearman: 0.2253 | Trn_ACCLoss: 0.2722 | Val_ACCLoss: 0.1327 | Trn_NDCG: 0.9006 | Val_NDCG: 0.5868\nFold 3 | #Est: 6 | Trn_Spearman: 0.4247 | Val_Spearman: 0.0174 | Trn_ACCLoss: 0.2028 | Val_ACCLoss: 0.1647 | Trn_NDCG: 0.7852 | Val_NDCG: 0.5847\nFold 4 | #Est: 63 | Trn_Spearman: 0.4522 | Val_Spearman: 0.2701 | Trn_ACCLoss: 0.2423 | Val_ACCLoss: 0.2671 | Trn_NDCG: 0.8327 | Val_NDCG: 0.5628\nFold 5 | #Est: 4 | Trn_Spearman: 0.3730 | Val_Spearman: 0.3407 | Trn_ACCLoss: 0.2036 | Val_ACCLoss: 0.2660 | Trn_NDCG: 0.7445 | Val_NDCG: 0.6464\nFold 6 | #Est: 43 | Trn_Spearman: 0.4259 | Val_Spearman: 0.0907 | Trn_ACCLoss: 0.2504 | Val_ACCLoss: 0.1931 | Trn_NDCG: 0.8214 | Val_NDCG: 0.6560\nFold 7 | #Est: 4 | Trn_Spearman: 0.4192 | Val_Spearman: 0.0092 | Trn_ACCLoss: 0.2336 | Val_ACCLoss: 0.0744 | Trn_NDCG: 0.7496 | Val_NDCG: 0.6592\nFold 8 | #Est: 14 | Trn_Spearman: 0.4334 | Val_Spearman: 0.0348 | Trn_ACCLoss: 0.2304 | Val_ACCLoss: 0.0999 | Trn_NDCG: 0.7608 | Val_NDCG: 0.6758\nFold 9 | #Est: 18 | Trn_Spearman: 0.3990 | Val_Spearman: 0.1190 | Trn_ACCLoss: 0.1936 | Val_ACCLoss: 0.1961 | Trn_NDCG: 0.8087 | Val_NDCG: 0.6304\nFold 10 | #Est: 41 | Trn_Spearman: 0.4022 | Val_Spearman: 0.2509 | Trn_ACCLoss: 0.2409 | Val_ACCLoss: 0.1032 | Trn_NDCG: 0.8001 | Val_NDCG: 0.6127\nFold 11 | #Est: 66 | Trn_Spearman: 0.4504 | Val_Spearman: 0.1777 | Trn_ACCLoss: 0.2620 | Val_ACCLoss: 0.1066 | Trn_NDCG: 0.8499 | Val_NDCG: 0.6192\nFold 12 | #Est: 6 | Trn_Spearman: 0.4024 | Val_Spearman: 0.0220 | Trn_ACCLoss: 0.2146 | Val_ACCLoss: 0.0657 | Trn_NDCG: 0.7931 | Val_NDCG: 0.5731\nFold 13 | #Est: 43 | Trn_Spearman: 0.4089 | Val_Spearman: 0.3269 | Trn_ACCLoss: 0.2333 | Val_ACCLoss: 0.2097 | Trn_NDCG: 0.8249 | Val_NDCG: 0.6853\nFold 14 | #Est: 18 | Trn_Spearman: 0.4160 | Val_Spearman: 0.0623 | Trn_ACCLoss: 0.2285 | Val_ACCLoss: 0.1349 | Trn_NDCG: 0.8121 | Val_NDCG: 0.7047\nFold 15 | #Est: 6 | Trn_Spearman: 0.4202 | Val_Spearman: 0.1758 | Trn_ACCLoss: 0.2088 | Val_ACCLoss: 0.1618 | Trn_NDCG: 0.7918 | Val_NDCG: 0.6754\nFold 16 | #Est: 2 | Trn_Spearman: 0.3657 | Val_Spearman: 0.1722 | Trn_ACCLoss: 0.2059 | Val_ACCLoss: 0.1520 | Trn_NDCG: 0.7194 | Val_NDCG: 0.6312\nFold 17 | #Est: 26 | Trn_Spearman: 0.4662 | Val_Spearman: 0.2976 | Trn_ACCLoss: 0.2284 | Val_ACCLoss: 0.2533 | Trn_NDCG: 0.8003 | Val_NDCG: 0.6006\nFold 18 | #Est: 2 | Trn_Spearman: 0.3893 | Val_Spearman: 0.1886 | Trn_ACCLoss: 0.2061 | Val_ACCLoss: 0.1739 | Trn_NDCG: 0.7242 | Val_NDCG: 0.6353\nFold 19 | #Est: 1 | Trn_Spearman: 0.3803 | Val_Spearman: 0.0440 | Trn_ACCLoss: 0.1959 | Val_ACCLoss: 0.1144 | Trn_NDCG: 0.6768 | Val_NDCG: 0.5945\nFold 20 | #Est: 93 | Trn_Spearman: 0.4458 | Val_Spearman: 0.1951 | Trn_ACCLoss: 0.2276 | Val_ACCLoss: 0.3127 | Trn_NDCG: 0.8885 | Val_NDCG: 0.6832\n\nTrn_Spearman: 0.4203 +/-0.0300 | Val_Spearman: 0.1647 +/-0.1065\nTrn_ACCLoss: 0.2269 +/-0.0222 | Val_ACCLoss: 0.1664 +/-0.0666\nTrn_NDCG: 0.7976 +/-0.0557 | Val_NDCG: 0.6340 +/-0.0403\n\nCPU times: user 30.6 s, sys: 220 ms, total: 30.8 s\nWall time: 3.72 s\n"
],
[
"from sklearn.model_selection import KFold\nfrom project.ranker.ltr_rankers import cv_random\nfrom project.ranker.ranker import RandomRankingPredictor\n\nrr = RandomRankingPredictor()\nkfolds = RepeatedKFold(10, n_repeats=2, random_state=42)\nresults = cv_random(rr, X_train, y_train, y_scores_train, kfolds)",
"Fold 1 | Trn_Spearman: -0.0295 | Val_Spearman: 0.0467 | Trn_ACCLoss: 0.1602 | Val_ACCLoss: 0.0378\nFold 2 | Trn_Spearman: 0.0124 | Val_Spearman: -0.1795 | Trn_ACCLoss: 0.1825 | Val_ACCLoss: 0.0615\nFold 3 | Trn_Spearman: 0.0582 | Val_Spearman: 0.2042 | Trn_ACCLoss: 0.1225 | Val_ACCLoss: 0.3269\nFold 4 | Trn_Spearman: 0.0050 | Val_Spearman: -0.0824 | Trn_ACCLoss: 0.1041 | Val_ACCLoss: 0.1993\nFold 5 | Trn_Spearman: 0.0092 | Val_Spearman: 0.2216 | Trn_ACCLoss: 0.1195 | Val_ACCLoss: 0.2870\nFold 6 | Trn_Spearman: -0.0287 | Val_Spearman: -0.0934 | Trn_ACCLoss: 0.1191 | Val_ACCLoss: 0.2107\nFold 7 | Trn_Spearman: -0.0011 | Val_Spearman: 0.1493 | Trn_ACCLoss: 0.1530 | Val_ACCLoss: 0.0948\nFold 8 | Trn_Spearman: -0.0122 | Val_Spearman: -0.1117 | Trn_ACCLoss: 0.1244 | Val_ACCLoss: 0.0897\nFold 9 | Trn_Spearman: 0.0403 | Val_Spearman: 0.0549 | Trn_ACCLoss: 0.1592 | Val_ACCLoss: 0.1748\nFold 10 | Trn_Spearman: 0.0078 | Val_Spearman: 0.0311 | Trn_ACCLoss: 0.1244 | Val_ACCLoss: 0.0343\nFold 11 | Trn_Spearman: 0.0374 | Val_Spearman: -0.2234 | Trn_ACCLoss: 0.1570 | Val_ACCLoss: 0.0316\nFold 12 | Trn_Spearman: -0.0041 | Val_Spearman: -0.1035 | Trn_ACCLoss: 0.1482 | Val_ACCLoss: 0.0370\nFold 13 | Trn_Spearman: 0.0270 | Val_Spearman: -0.0330 | Trn_ACCLoss: 0.1406 | Val_ACCLoss: 0.2403\nFold 14 | Trn_Spearman: 0.0256 | Val_Spearman: -0.1593 | Trn_ACCLoss: 0.1384 | Val_ACCLoss: 0.0682\nFold 15 | Trn_Spearman: -0.0015 | Val_Spearman: 0.1456 | Trn_ACCLoss: 0.1213 | Val_ACCLoss: 0.1118\nFold 16 | Trn_Spearman: -0.0163 | Val_Spearman: -0.1557 | Trn_ACCLoss: 0.1533 | Val_ACCLoss: 0.0683\nFold 17 | Trn_Spearman: 0.0038 | Val_Spearman: 0.1548 | Trn_ACCLoss: 0.1501 | Val_ACCLoss: 0.2567\nFold 18 | Trn_Spearman: 0.0237 | Val_Spearman: -0.1566 | Trn_ACCLoss: 0.1261 | Val_ACCLoss: 0.0323\nFold 19 | Trn_Spearman: 0.0171 | Val_Spearman: -0.0897 | Trn_ACCLoss: 0.1524 | Val_ACCLoss: 0.1820\nFold 20 | Trn_Spearman: -0.0765 | Val_Spearman: -0.1062 | Trn_ACCLoss: 0.1056 | Val_ACCLoss: 0.2298\n\nTrn_Spearman: 0.0049 +/-0.0287 | Val_Spearman: -0.0243 +/-0.1356\nTrn_ACCLoss: 0.1381 +/-0.0202 | Val_ACCLoss: 0.1387 +/-0.0941\n\n"
],
[
"lightgbm.plot_importance(models[0], figsize=(5,10))",
"_____no_output_____"
],
[
"from project.ranker.ltr_rankers import wide2long\nX, y = wide2long(X_train, y_train)\nX.shape, y.shape",
"_____no_output_____"
],
[
"X_train[0]",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb08d654d524abeedd7208ef0420a03153834016 | 31,463 | ipynb | Jupyter Notebook | multiview.ipynb | kbogas/Cascada | e5c614bd9251c73c95fbf8d7634b96166cf5234e | [
"MIT"
] | null | null | null | multiview.ipynb | kbogas/Cascada | e5c614bd9251c73c95fbf8d7634b96166cf5234e | [
"MIT"
] | null | null | null | multiview.ipynb | kbogas/Cascada | e5c614bd9251c73c95fbf8d7634b96166cf5234e | [
"MIT"
] | null | null | null | 43.218407 | 376 | 0.519404 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport itertools\n\nimport sklearn\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom brew.base import Ensemble, EnsembleClassifier\nfrom brew.stacking.stacker import EnsembleStack, EnsembleStackClassifier\nfrom brew.combination.combiner import Combiner\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n\n\nfrom mlxtend.data import wine_data, iris_data\n\nfrom mlxtend.plotting import plot_decision_regions\n\n\nfrom sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom itertools import combinations\nimport random\nrandom.seed(10)\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom progress.bar import Bar\n\nimport sys, time\ntry:\n from IPython.core.display import clear_output\n have_ipython = True\nexcept ImportError:\n have_ipython = False\n\nclass ProgressBar:\n def __init__(self, iterations):\n self.iterations = iterations\n self.prog_bar = '[]'\n self.fill_char = '*'\n self.width = 40\n self.__update_amount(0)\n if have_ipython:\n self.animate = self.animate_ipython\n else:\n self.animate = self.animate_noipython\n\n def animate_ipython(self, iter):\n try:\n pass\n #clear_output()\n except Exception:\n # terminal IPython has no clear_output\n pass\n print '\\r', self,\n #sys.stdout.flush()\n self.update_iteration(iter + 1)\n\n def update_iteration(self, elapsed_iter):\n self.__update_amount((elapsed_iter / float(self.iterations)) * 100.0)\n self.prog_bar += ' %d of %s complete' % (elapsed_iter, self.iterations)\n\n def __update_amount(self, new_amount):\n percent_done = int(round((new_amount / 100.0) * 100.0))\n all_full = self.width - 2\n num_hashes = int(round((percent_done / 100.0) * all_full))\n self.prog_bar = '[' + self.fill_char * num_hashes + ' ' * (all_full - num_hashes) + ']'\n pct_place = (len(self.prog_bar) / 2) - len(str(percent_done))\n pct_string = '%d%%' % percent_done\n self.prog_bar = self.prog_bar[0:pct_place] + \\\n (pct_string + self.prog_bar[pct_place + len(pct_string):])\n\n def __str__(self):\n return str(self.prog_bar)\n\n\n\n\nclass Multiviewer(BaseEstimator, TransformerMixin):\n \n def __init__(self, max_level=3, num_at_each_level=4, base_estimator=ExtraTreesClassifier(n_estimators=50)):\n self.max_level = max_level\n self.base_estimator = base_estimator\n self.num_at_each_level = num_at_each_level\n self.estimators = []\n self.estim_features = []\n self.classes_ = None\n \n def fit(self, X, y):\n if self.max_level > X.shape[1]:\n print \"Max level of feature combinations can't be bigger than num of features\"\n print \"%d > %d\" % (self.max_level, X.shape[1])\n raise ValueError\n if not(isinstance(self.num_at_each_level, list)):\n self.num_at_each_level = [self.num_at_each_level for i in xrange(1, self.max_level)]\n self.num_at_each_level = [X.shape[1]] + self.num_at_each_level \n #print self.num_at_each_level\n self.classes_ = list(set(y))\n rang = np.arange(X.shape[1])\n total = 0\n for i in xrange(1, self.max_level+1):\n total += i* self.num_at_each_level[i-1]\n print \"Will create %d trees!\" % total\n cc = 0\n bar =ProgressBar(total)\n for level in xrange(self.max_level):\n #print [comb for comb in combinations(rang, level+1)]\n wanted_feature_sets = get_cols(rang, level+1, self.num_at_each_level[level] )\n for wanted_features in wanted_feature_sets:\n c = sklearn.clone(self.base_estimator)\n c.fit(X[:, wanted_features], y)\n self.estimators.append(c)\n #print self.estimators[-1].n_features_\n self.estim_features.append(wanted_features)\n bar.animate(cc)\n cc += 1\n #bar.finish()\n return self\n \n def predict(self, X):\n if not(isinstance(X, np.ndarray)):\n X = np.array(X)\n print X.shape\n print X.shape[0]\n predictions = np.empty((X.shape[0], len(self.estimators)))\n for i, est in enumerate(self.estimators):\n# print est.n_features_\n# print i, self.estim_features[i]\n# print X.shape\n# print X[:, self.estim_features[i]].shape\n predictions[:, i] = est.predict(X[:, self.estim_features[i]])\n final_pred = []\n #print predictions\n for sample in xrange(X.shape[0]):\n votes = []\n for i, mod_vote in enumerate(predictions[sample,:]):\n votes.extend([predictions[sample, i] for j in xrange(1)])\n final_pred.append(most_common(votes))\n return np.array(final_pred).reshape(-1,)\n \ndef get_cols(iterable, level_, total_times_):\n wanted = [random.sample(iterable, k=level_) for time in xrange(total_times_)]\n return wanted\n\ndef most_common(lst):\n return max(set(lst), key=lst.count)\n\n\n\n# Loading some example data\nX, y = wine_data()\n#X, y = iris_data()\n#X = X[:,[0, 2]]\n\n\nprint('Dimensions: %s x %s' % (X.shape[0], X.shape[1]))\nprint('1st row', X[0])\n\n\n\n\n# Initializing Classifiersa\nclf1 = LogisticRegression(random_state=0)\nclf2 = RandomForestClassifier(random_state=0)\nclf3 = SVC(random_state=0, probability=True)\nmu = Multiviewer(max_level=3, num_at_each_level=[10, 10, 10])\n# Creating Ensemble\nensemble = Ensemble([clf1, clf2, clf3])\neclf = EnsembleClassifier(ensemble=ensemble, combiner=Combiner('mean'))\n# Creating Stacking\nlayer_1 = Ensemble([clf1, clf2, clf3])\nlayer_2 = Ensemble([sklearn.clone(clf1)])\n\nstack = EnsembleStack(cv=3)\n\nstack.add_layer(layer_1)\nstack.add_layer(layer_2)\n\nsclf = EnsembleStackClassifier(stack)\n\nclf_list = [clf1, clf2, clf3, eclf, sclf, mu]\nlbl_list = ['Logistic Regression', 'Random Forest', 'RBF kernel SVM', 'Ensemble', 'Stacking', 'MULTIVIEWER']\n\n\n\n# WARNING, WARNING, WARNING\n# brew requires classes from 0 to N, no skipping allowed\nd = {yi : i for i, yi in enumerate(set(y))}\ny = np.array([d[yi] for yi in y])\n\n# Plotting Decision Regions\n#gs = gridspec.GridSpec(2, 3)\n#fig = plt.figure(figsize=(10, 8))\n\nitt = itertools.product([0, 1, 2], repeat=2)\n\nfrom sklearn.model_selection import train_test_split\nsplit = 0.2\nX_train, X_cv, y_train, y_cv = train_test_split(X, y, test_size=split, stratify=y, random_state=100)\n\nfor clf, lab, grd in zip(clf_list, lbl_list, itt):\n clf.fit(X_train, y_train)\n# ax = plt.subplot(gs[grd[0], grd[1]])\n# fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)\n# plt.title(lab)\n print \"Results for: %s\" % lab\n pred = clf.predict(X_cv)\n print accuracy_score(y_cv, pred, normalize=True)\n print confusion_matrix(y_cv, pred, labels=list(set(y)))\n print classification_report(y_cv, pred, labels=list(set(y)))\n\n#plt.show()",
"/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n"
],
[
"clf1.fit(X_train, y_train)\nclf1.predict(X_cv).shape",
"_____no_output_____"
],
[
"from sklearn.base import TransformerMixin, BaseEstimator\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom itertools import combinations\nimport random\nrandom.seed(10)\n\nclass Multiviewer(BaseEstimator, TransformerMixin):\n \n def __init__(self, max_level=3, num_at_each_level=4, base_estimator=ExtraTreesClassifier(n_estimators=50)):\n self.max_level = max_level\n self.base_estimator = base_estimator\n self.num_at_each_level = num_at_each_level\n self.estimators = []\n self.estim_features = []\n self.classes_ = None\n \n def fit(self, X, y):\n if self.max_level > X.shape[1]:\n print \"Max level of feature combinations can't be bigger than num of features\"\n print \"%d > %d\" % (self.max_level, X.shape[1])\n raise ValueError\n if not(isinstance(self.num_at_each_level, list)):\n self.num_at_each_level = [self.num_at_each_level for i in xrange(1, self.max_level)]\n self.num_at_each_level = [X.shape[1]] + self.num_at_each_level \n #print self.num_at_each_level\n self.classes_ = list(set(y))\n rang = np.arange(X.shape[1])\n total = 0\n for i in xrange(1, self.max_level+1):\n total += i* self.num_at_each_level[i-1]\n print \"Will create %d trees!\" % total\n cc = 0\n bar =ProgressBar(total)\n for level in xrange(self.max_level):\n #print [comb for comb in combinations(rang, level+1)]\n wanted_feature_sets = get_cols(rang, level+1, self.num_at_each_level[level])\n print wanted_feature_sets\n for wanted_features in wanted_feature_sets:\n c = sklearn.clone(self.base_estimator)\n c.fit(X[:, wanted_features], y)\n self.estimators.append(c)\n #print self.estimators[-1].n_features_\n self.estim_features.append(wanted_features)\n bar.animate(cc)\n cc += 1\n #bar.finish()\n return self\n \n def predict(self, X):\n if not(isinstance(X, np.ndarray)):\n X = np.array(X)\n print X.shape\n print X.shape[0]\n predictions = np.empty((X.shape[0], len(self.estimators)))\n for i, est in enumerate(self.estimators):\n# print est.n_features_\n# print i, self.estim_features[i]\n# print X.shape\n# print X[:, self.estim_features[i]].shape\n predictions[:, i] = est.predict(X[:, self.estim_features[i]])\n final_pred = []\n #print predictions\n for sample in xrange(X.shape[0]):\n votes = []\n for i, mod_vote in enumerate(predictions[sample,:]):\n votes.extend([predictions[sample, i] for j in xrange(1)])\n final_pred.append(most_common(votes))\n return np.array(final_pred).reshape(-1,)\n \ndef get_cols(iterable, level_, total_times_):\n wanted = [random.sample(iterable, k=level_) for time in xrange(total_times_)]\n return wanted\n\ndef most_common(lst):\n return max(set(lst), key=lst.count)",
"_____no_output_____"
],
[
"print X.shape[1]\nmu = Multiviewer(max_level=4)\nmu.fit(X,y)\npred = mu.predict(X_cv)\nprint accuracy_score(y_cv, pred, normalize=True)\nprint confusion_matrix(y_cv, pred, labels=list(set(y)))\nprint classification_report(y_cv, pred, labels=list(set(y)))",
"13\nWill create 49 trees!\n[[1], [2], [2], [1], [12], [11], [6], [9], [9], [6], [5], [8], [7]]\n[********* 24% ] 12 of 49 complete [[3, 4], [8, 7], [2, 7], [11, 10]]\n[************* 33% ] 16 of 49 complete [[8, 0, 4], [1, 0, 2], [5, 9, 6], [3, 8, 5]]\n[**************** 41% ] 20 of 49 complete [[6, 3, 4, 11], [9, 5, 4, 10], [6, 8, 7, 11], [5, 9, 10, 11]]\n[*****************49% ] 24 of 49 complete (36, 13)\n36\n1.0\n[[12 0 0]\n [ 0 14 0]\n [ 0 0 10]]\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 12\n 1 1.00 1.00 1.00 14\n 2 1.00 1.00 1.00 10\n\navg / total 1.00 1.00 1.00 36\n\n"
],
[
"mu.estimators",
"_____no_output_____"
],
[
"rang = np.arange(X.shape[1])",
"_____no_output_____"
],
[
"from itertools import combinations\nimport random\nrandom.seed(10)\nss = random.sample([comb for comb in combinations(rang, 2)],2)\n",
"_____no_output_____"
],
[
"X[:, ss[1]].shape",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb08da63bdb8b24c719a7c61c559b6287101c589 | 358,787 | ipynb | Jupyter Notebook | tSNE.ipynb | FelixArokia/AAAML | 06642c0c70b147d418c3decd6821ffacc5824bae | [
"MIT"
] | 2 | 2022-03-10T03:26:07.000Z | 2022-03-10T16:49:54.000Z | tSNE.ipynb | FelixArokia/AAAML | 06642c0c70b147d418c3decd6821ffacc5824bae | [
"MIT"
] | null | null | null | tSNE.ipynb | FelixArokia/AAAML | 06642c0c70b147d418c3decd6821ffacc5824bae | [
"MIT"
] | null | null | null | 629.450877 | 233,866 | 0.692924 | [
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom sklearn import datasets\nfrom sklearn import manifold\n\n%matplotlib inline",
"_____no_output_____"
],
[
"## ??datasets.fetch_openml",
"_____no_output_____"
],
[
"pixel_values, targets = datasets.fetch_openml('mnist_784', version=1, return_X_y=True)",
"_____no_output_____"
]
],
[
[
"#### There are ```70,000``` images of size ```28 x 28``` in flattened form",
"_____no_output_____"
]
],
[
[
"pixel_values.shape",
"_____no_output_____"
]
],
[
[
"#### Viewing the first image",
"_____no_output_____"
]
],
[
[
"pixel_values[0, :].shape",
"_____no_output_____"
],
[
"single_image = pixel_values[0, :]\nsingle_image = single_image.reshape(28,28)\nsingle_image.shape",
"_____no_output_____"
],
[
"plt.imshow(single_image, cmap = 'gray')",
"_____no_output_____"
]
],
[
[
"### tSNE",
"_____no_output_____"
]
],
[
[
"tsne = manifold.TSNE(n_components=2, random_state=42)",
"_____no_output_____"
],
[
"transformed_data = tsne.fit_transform(pixel_values[:3000, :])",
"_____no_output_____"
],
[
"transformed_data",
"_____no_output_____"
],
[
"transformed_data.shape",
"_____no_output_____"
],
[
"tsne = np.column_stack(transformed_data)\ntsne.shape",
"_____no_output_____"
],
[
"print('transformed_data shape: ', transformed_data.shape)\nprint('targets shape : ', targets[:3000].shape)\ntsne = np.column_stack((transformed_data, targets[:3000]))\ntsne",
"transformed_data shape: (3000, 2)\ntargets shape : (3000,)\n"
],
[
"tsne_df = pd.DataFrame(tsne, columns=[\"d1\", \"d2\", \"targets\"])",
"_____no_output_____"
],
[
"tsne_df.head()",
"_____no_output_____"
],
[
"tsne_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 3000 entries, 0 to 2999\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 d1 3000 non-null object\n 1 d2 3000 non-null object\n 2 targets 3000 non-null object\ndtypes: object(3)\nmemory usage: 70.4+ KB\n"
],
[
"tsne_df.loc[:, \"targets\"] = tsne_df.targets.astype(int)",
"_____no_output_____"
]
],
[
[
"#### sns visuals",
"_____no_output_____"
]
],
[
[
"grid = sns.FacetGrid(tsne_df, hue=\"targets\", size=8)\ngrid.map(plt.scatter, \"d1\", \"d2\").add_legend()",
"/Users/felix/.pyenv/versions/3.6.9/lib/python3.6/site-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code.\n warnings.warn(msg, UserWarning)\n"
]
],
[
[
"### Altair visuals",
"_____no_output_____"
]
],
[
[
"import altair as alt\nsource = tsne_df\nsource['targets'] = source['targets'].astype(str)\n\nalt.Chart(source).mark_circle().encode(\n alt.X('d1', scale=alt.Scale(zero=False)),\n alt.Y('d2', scale=alt.Scale(zero=False, padding=1)),\n color='targets'\n)",
"_____no_output_____"
],
[
"### how to get cluster id from tsne ?",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb08e54c5502bbf6ed1ce87316c26c3c79c4d247 | 7,841 | ipynb | Jupyter Notebook | basicFun.ipynb | helah20/Python | 25b3c375c217e949746de07c83ca726dc7e17d26 | [
"Apache-2.0"
] | null | null | null | basicFun.ipynb | helah20/Python | 25b3c375c217e949746de07c83ca726dc7e17d26 | [
"Apache-2.0"
] | null | null | null | basicFun.ipynb | helah20/Python | 25b3c375c217e949746de07c83ca726dc7e17d26 | [
"Apache-2.0"
] | 1 | 2021-01-07T12:57:03.000Z | 2021-01-07T12:57:03.000Z | 26.489865 | 1,024 | 0.419589 | [
[
[
"<a href=\"https://colab.research.google.com/github/helah20/Python/blob/main/basicFun.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"# Create a text file, or copy the code snippets into a Python file\r\n#1\r\ndef a():\r\n return 5\r\nprint(a())\r\n",
"5\n"
],
[
"#2\r\ndef a():\r\n return 5\r\nprint(a()+a())\r\n",
"10\n"
],
[
"#3\r\ndef a():\r\n return 5\r\n return 10\r\nprint(a())\r\n\r\n",
"5\n"
],
[
"#4\r\ndef a():\r\n return 5\r\n print(10)\r\nprint(a())\r\n",
"5\n"
],
[
"#5\r\ndef a():\r\n print(5)\r\nx = a()\r\nprint(x)\r\n",
"5\nNone\n"
],
[
"#6\r\ndef a(b,c):\r\n print(b+c)\r\nprint(a(1,2) + a(2,3))\r\n",
"3\n5\n"
],
[
"#7\r\ndef a(b,c):\r\n return str(b)+str(c)\r\nprint(a(2,5))",
"25\n"
],
[
"#8\r\ndef a():\r\n b = 100\r\n print(b)\r\n if b < 10:\r\n return 5\r\n else:\r\n return 10\r\n return 7\r\nprint(a())",
"100\n10\n"
],
[
"#9\r\ndef a(b,c):\r\n if b<c:\r\n return 7\r\n else:\r\n return 14\r\n return 3\r\nprint(a(2,3))\r\nprint(a(5,3))\r\nprint(a(2,3) + a(5,3))",
"7\n14\n21\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb08f9e00cb3b3fba9df4dce5c373c7d72325daf | 39,857 | ipynb | Jupyter Notebook | 2020_hwdig/catboost.ipynb | guangweis/Competition_coll | 90edbe3924e7730117b980c185c61ba14d7fa686 | [
"MIT"
] | null | null | null | 2020_hwdig/catboost.ipynb | guangweis/Competition_coll | 90edbe3924e7730117b980c185c61ba14d7fa686 | [
"MIT"
] | null | null | null | 2020_hwdig/catboost.ipynb | guangweis/Competition_coll | 90edbe3924e7730117b980c185c61ba14d7fa686 | [
"MIT"
] | null | null | null | 36.399087 | 216 | 0.578719 | [
[
[
"import pickle\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm_notebook\nimport time\nimport gc\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nimport torch\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nimport torch.nn as nn\nfrom torch.utils.data import Dataset,DataLoader\nimport torch.nn.functional as F\nimport sklearn\nfrom sklearn.model_selection import StratifiedKFold,KFold\nfrom sklearn.metrics import roc_curve \nimport time\nimport os\nimport itertools\nimport random\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nfrom scipy.special import erfinv\nfrom collections import OrderedDict\nfrom math import sqrt\nimport numpy as np\nfrom torch.optim import lr_scheduler\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport catboost as cbt\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer",
"_____no_output_____"
],
[
"from category_encoders.ordinal import OrdinalEncoder\nfrom category_encoders.woe import WOEEncoder\nfrom category_encoders.target_encoder import TargetEncoder as Encoder\nfrom category_encoders.sum_coding import SumEncoder\nfrom category_encoders.m_estimate import MEstimateEncoder\nfrom category_encoders.leave_one_out import LeaveOneOutEncoder\nfrom category_encoders.helmert import HelmertEncoder\nfrom category_encoders.cat_boost import CatBoostEncoder\nfrom category_encoders import CountEncoder\nfrom category_encoders.one_hot import OneHotEncoder",
"_____no_output_____"
],
[
"def seed_everything(seed=42):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\nseed_everything()",
"_____no_output_____"
],
[
"def reduce_mem(df):\n starttime = time.time()\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n start_mem = df.memory_usage().sum() / 1024**2\n for col in df.columns:\n col_type = df[col].dtypes\n if col_type in numerics:\n c_min = df[col].min()\n c_max = df[col].max()\n if pd.isnull(c_min) or pd.isnull(c_max):\n continue\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64)\n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n end_mem = df.memory_usage().sum() / 1024**2\n print('-- Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction),time spend:{:2.2f} min'.format(end_mem,\n 100*(start_mem-end_mem)/start_mem,\n (time.time()-starttime)/60))\n return df",
"_____no_output_____"
],
[
"\ndef lower_sample_data_by_sample(df,percent=1,rs=42):\n most_data = df[df['label'] == 0] # 多数类别的样本\n minority_data = df[df['label'] == 1] # 少数类别的样本 \n #随机采样most_data中的数据\n lower_data=most_data.sample(n=int(percent*len(minority_data)),replace=False,random_state=rs,axis=0) \n return (pd.concat([lower_data,minority_data]))",
"_____no_output_____"
],
[
"def get_mask_train(df,samp):\n if random.random()<samp:\n return -1\n else :\n return df",
"_____no_output_____"
],
[
"#--------------------------------------------------数据预处理--------------------------------------------------#",
"_____no_output_____"
],
[
"columns = [ 'uid', 'task_id', 'adv_id', 'creat_type_cd', 'adv_prim_id',\n 'dev_id', 'inter_type_cd', 'slot_id', 'spread_app_id', 'tags',\n 'app_first_class', 'app_second_class', 'age', 'city', 'city_rank',\n 'device_name', 'device_size', 'career', 'gender', 'net_type',\n 'residence', 'his_app_size', 'his_on_shelf_time', 'app_score',\n 'emui_dev', 'list_time', 'device_price', 'up_life_duration',\n 'up_membership_grade', 'membership_life_duration', 'consume_purchase',\n 'communication_onlinerate', 'communication_avgonline_30d', 'indu_name',\n 'pt_d']",
"_____no_output_____"
],
[
"# 读取数据集\ntrain_df = reduce_mem(pd.read_csv('train_data.csv',sep='|'))\n\ntest_df = pd.read_csv('test_data_B.csv',sep='|')",
"_____no_output_____"
],
[
"def get_tfidf(train,test,key1,key2):\n \n train_tif = pd.DataFrame(train[[key1, key2]].groupby([key1])[key2].apply(list))\n train_tif.reset_index(inplace=True)\n train_key1= train_tif[key1].values\n train_key2 = train_tif[key2].values.tolist()\n train_key2_list = []\n for seq in train_key2:\n sentences = []\n for word in seq:\n sentences.append(str(word))\n train_key2_list.append(' '.join(sentences))\n \n\n tfidf_vec = TfidfVectorizer() \n train_tfidf_matrix = tfidf_vec.fit_transform(train_key2_list).toarray()\n\n test_tif = pd.DataFrame(test[[key1, key2]].groupby([key1])[key2].apply(list))\n test_tif.reset_index(inplace=True)\n test_key1= test_tif[key1].values\n test_key2 = test_tif[key2].values.tolist()\n test_key2_list = []\n for seq in test_key2:\n sentences = []\n for word in seq:\n sentences.append(str(word))\n test_key2_list.append(' '.join(sentences))\n test_tfidf_matrix = tfidf_vec.transform(test_key2_list).toarray()\n assert train_tfidf_matrix.shape[1]==test_tfidf_matrix.shape[1]\n \n train_tfidf_agmax = np.argmax(train_tfidf_matrix,axis=1)\n train_tfidf_max = np.max(train_tfidf_matrix,axis=1)\n train_tfidf_mean = np.mean(train_tfidf_matrix,axis=1)\n train_tfidf_std = np.std(train_tfidf_matrix,axis=1)\n \n test_tfidf_agmax = np.argmax(test_tfidf_matrix,axis=1)\n test_tfidf_max = np.max(test_tfidf_matrix,axis=1)\n test_tfidf_mean = np.mean(test_tfidf_matrix,axis=1)\n test_tfidf_std = np.std(test_tfidf_matrix,axis=1)\n \n print('train_tfidf_agmax.shape:')\n print(train_tfidf_agmax.shape)\n \n print('train_tfidf_mean.shape:')\n print(train_tfidf_mean.shape)\n \n print('test_tfidf_agmax.shape:')\n print(test_tfidf_agmax.shape)\n \n print('test_tfidf_mean.shape:')\n print(test_tfidf_mean.shape)\n return train_tif,test_tif,train_tfidf_agmax,train_tfidf_max,train_tfidf_mean,train_tfidf_std,test_tfidf_agmax,test_tfidf_max,test_tfidf_mean,test_tfidf_std",
"_____no_output_____"
],
[
"# 无用列\ndrop_cols = ['pt_d','label','communication_onlinerate','index','id','K']\n\n# 选择类别特征\ncat_cols = [ 'uid', 'task_id', 'adv_id', 'creat_type_cd', 'adv_prim_id',\n 'dev_id', 'inter_type_cd', 'slot_id', 'spread_app_id', 'tags',\n 'app_first_class', 'app_second_class', 'age', 'city', 'city_rank',\n 'device_name', 'device_size', 'career', 'gender', 'net_type',\n 'residence', 'his_app_size', 'his_on_shelf_time', 'app_score',\n 'emui_dev', 'list_time', 'device_price', 'up_life_duration',\n 'up_membership_grade', 'membership_life_duration', 'consume_purchase'\n , 'communication_avgonline_30d', 'indu_name',\n ]\nMASK = 'MASK'\nmiss_col1 = ['task_id', 'adv_id','uid']\nmiss_col2 = ['adv_prim_id','dev_id' ]#, 'device_size','spread_app_id','indu_name']",
"_____no_output_____"
],
[
"for col in tqdm_notebook( miss_col1):\n train_df[col] = train_df[col].apply(lambda x :get_mask_train(x,0.1))\nfor col in tqdm_notebook(miss_col2):\n train_df[col] = train_df[col].apply(lambda x :get_mask_train(x,0.05))",
"_____no_output_____"
],
[
"for col in tqdm_notebook( miss_col1):\n mask_list = list(set(test_df[col].values)-set(train_df[col].values))\n print(len(mask_list)/len(set(test_df[col].values)))\n test_df[col] = test_df[col].replace(mask_list,-1)\nfor col in tqdm_notebook(miss_col2):\n mask_list = list(set(test_df[col].values)-set(train_df[col].values))\n print(len(mask_list)/len(set(test_df[col].values)))\n\n test_df[col] = test_df[col].replace(mask_list,-1)",
"_____no_output_____"
],
[
"train_df.reset_index(drop=True,inplace=True)",
"_____no_output_____"
],
[
"user_col = ['uid','age','city','city_rank','career','gender','residence','communication_avgonline_30d','consume_purchase','membership_life_duration','up_membership_grade','up_life_duration']\nad_col = ['task_id','adv_id','creat_type_cd','adv_prim_id','dev_id','slot_id','spread_app_id','tags','app_first_class','app_second_class','indu_name','inter_type_cd']\nphone_col = ['device_name','device_size','net_type','emui_dev','device_price']\napp_col = ['his_app_size','his_on_shelf_time','app_score','list_time']",
"_____no_output_____"
],
[
"\ntrain_tif_uid1,test_tif_uid1,train_tfidf_agmax,train_tfidf_max,train_tfidf_mean,train_tfidf_std,test_tfidf_agmax,test_tfidf_max,test_tfidf_mean,test_tfidf_std = get_tfidf(train_df , test_df, 'uid','task_id')\ntrain_tif_uid1 = train_tif_uid1.drop('task_id',axis=1)\ntrain_tif_uid1['uid'+'task_id'+'tf_argmax'] = train_tfidf_agmax\ntrain_tif_uid1['uid'+'task_id'+'max'] = train_tfidf_max\ntrain_tif_uid1['uid'+'task_id'+'mean'] = train_tfidf_mean\ntrain_tif_uid1['uid'+'task_id'+'std'] = train_tfidf_std\n\ntrain_tif_uid2,test_tif,train_tfidf_agmax,train_tfidf_max,train_tfidf_mean,train_tfidf_std,test_tfidf_agmax,test_tfidf_max,test_tfidf_mean,test_tfidf_std = get_tfidf(train_df , test_df, 'uid','adv_id')\ntrain_tif_uid2 = train_tif_uid2.drop('adv_id',axis=1)\ntrain_tif_uid2['uid'+'adv_id'+'tf_argmax'] = train_tfidf_agmax\ntrain_tif_uid2['uid'+'adv_id'+'max'] = train_tfidf_max\ntrain_tif_uid2['uid'+'adv_id'+'mean'] = train_tfidf_mean\ntrain_tif_uid2['uid'+'adv_id'+'std'] = train_tfidf_std\n\ntrain_tif_uid3,test_tif,train_tfidf_agmax,train_tfidf_max,train_tfidf_mean,train_tfidf_std,test_tfidf_agmax,test_tfidf_max,test_tfidf_mean,test_tfidf_std = get_tfidf(train_df , test_df, 'uid','slot_id')\ntrain_tif_uid3 = train_tif_uid3.drop('slot_id',axis=1)\ntrain_tif_uid3['uid'+'slot_id'+'tf_argmax'] = train_tfidf_agmax\ntrain_tif_uid3['uid'+'slot_id'+'max'] = train_tfidf_max\ntrain_tif_uid3['uid'+'slot_id'+'mean'] = train_tfidf_mean\ntrain_tif_uid3['uid'+'slot_id'+'std'] = train_tfidf_std\n\ntrain_tif_uid4,test_tif,train_tfidf_agmax,train_tfidf_max,train_tfidf_mean,train_tfidf_std,test_tfidf_agmax,test_tfidf_max,test_tfidf_mean,test_tfidf_std = get_tfidf(train_df , test_df, 'uid','adv_prim_id')\ntrain_tif_uid4 = train_tif_uid4.drop('adv_prim_id',axis=1)\ntrain_tif_uid4['uid'+'adv_prim_id'+'tf_argmax'] = train_tfidf_agmax\ntrain_tif_uid4['uid'+'adv_prim_id'+'max'] = train_tfidf_max\ntrain_tif_uid4['uid'+'adv_prim_id'+'mean'] = train_tfidf_mean\ntrain_tif_uid4['uid'+'adv_prim_id'+'std'] = train_tfidf_std\n\n",
"_____no_output_____"
],
[
"def add_noise(series, noise_level):\n return series * (1 + noise_level * np.random.randn(len(series)))\n\ndef target_encode(trn_series=None, \n tst_series1=None, \n tst_series2 = None,\n target=None, \n min_samples_leaf=1, \n smoothing=1,\n noise_level=0):\n \"\"\"\n Smoothing is computed like in the following paper by Daniele Micci-Barreca\n https://kaggle2.blob.core.windows.net/forum-message-attachments/225952/7441/high%20cardinality%20categoricals.pdf\n trn_series : training categorical feature as a pd.Series\n tst_series : test categorical feature as a pd.Series\n target : target data as a pd.Series\n min_samples_leaf (int) : minimum samples to take category average into account\n smoothing (int) : smoothing effect to balance categorical average vs prior \n \"\"\" \n assert len(trn_series) == len(target)\n assert trn_series.name == tst_series1.name\n assert trn_series.name == tst_series2.name\n nui = trn_series.nunique()\n cou = len(trn_series)\n min_samples_leaf = min_samples_leaf*(cou/nui)\n print(min_samples_leaf)\n temp = pd.concat([trn_series, target], axis=1)\n # Compute target mean \n averages = temp.groupby(by=trn_series.name)[target.name].agg([\"mean\", \"count\"])\n # Compute smoothing\n smoothing = 1 / (1 + np.exp(-(averages[\"count\"] - min_samples_leaf) / smoothing))\n # Apply average function to all target data\n prior = target.mean()\n # The bigger the count the less full_avg is taken into account\n averages[target.name] = prior * (1 - smoothing) + averages[\"mean\"] * smoothing\n averages.drop([\"mean\", \"count\"], axis=1, inplace=True)\n # Apply averages to trn and tst series\n ft_trn_series = pd.merge(\n trn_series.to_frame(trn_series.name),\n averages.reset_index().rename(columns={'index': target.name, target.name: 'average'}),\n on=trn_series.name,\n how='left')['average'].rename(trn_series.name + '_mean').fillna(prior)\n # pd.merge does not keep the index so restore it\n ft_trn_series.index = trn_series.index \n ft_tst_series1 = pd.merge(\n tst_series1.to_frame(tst_series1.name),\n averages.reset_index().rename(columns={'index': target.name, target.name: 'average'}),\n on=tst_series1.name,\n how='left')['average'].rename(trn_series.name + '_mean').fillna(prior)\n \n ft_tst_series2 = pd.merge(\n tst_series2.to_frame(tst_series2.name),\n averages.reset_index().rename(columns={'index': target.name, target.name: 'average'}),\n on=tst_series2.name,\n how='left')['average'].rename(trn_series.name + '_mean').fillna(prior)\n # pd.merge does not keep the index so restore it\n ft_tst_series1.index = tst_series1.index\n ft_tst_series2.index = tst_series2.index\n return add_noise(ft_trn_series, noise_level).values, add_noise(ft_tst_series1, noise_level).values,add_noise(ft_tst_series2, noise_level).values\n",
"_____no_output_____"
],
[
"floder = StratifiedKFold(n_splits=5,random_state=42,shuffle=True)\n",
"_____no_output_____"
],
[
"test_df2 = test_df.copy()\ntest_df3 = test_df.copy()\ntest_df4 = test_df.copy()\ntest_df5 = test_df.copy()\ntest_df_list = [test_df , test_df2, test_df3, test_df4, test_df5]",
"_____no_output_____"
],
[
"train_df.reset_index(drop=True,inplace=True)",
"_____no_output_____"
],
[
"for col in tqdm_notebook(cat_cols):\n i = 1\n train_df[col + 'tar_enco'] = 0\n train_df['K'] = 0\n for k ,(tr_idx, oof_idx) in enumerate(StratifiedKFold(n_splits=5, random_state=2020, shuffle=True).split(train_df, train_df['label'])):\n print('fold{}'.format(i))\n i+=1\n trn_series = train_df.iloc[tr_idx][col]\n tst_series1 = train_df.iloc[oof_idx][col]\n tst_series2 = test_df_list[k][col]\n target = train_df.iloc[tr_idx].label\n train_targetencoding,oof_targetencoding,test_targetencoding = target_encode(trn_series, \n tst_series1, \n tst_series2,\n target, \n min_samples_leaf=0.2, \n smoothing=1,\n noise_level=0.0001)\n train_df.loc[oof_idx,col + 'tar_enco'] = oof_targetencoding\n train_df.loc[oof_idx,'K'] = k\n test_df_list[k][col + 'tar_enco'] = test_targetencoding\n train_df = reduce_mem(train_df)\n gc.collect()",
"_____no_output_____"
],
[
"train_df = reduce_mem(train_df)",
"_____no_output_____"
],
[
"test_df = test_df_list[0]",
"_____no_output_____"
],
[
"train_df",
"_____no_output_____"
],
[
"train_df = lower_sample_data_by_sample(train_df , 3,303).reset_index(drop=True)",
"_____no_output_____"
],
[
"train_df = train_df.merge(train_tif_uid1,on='uid',how='left')\ntrain_df = train_df.merge(train_tif_uid2,on='uid',how='left')\ntrain_df = train_df.merge(train_tif_uid3,on='uid',how='left')\ntrain_df = train_df.merge(train_tif_uid4,on='uid',how='left')\n# train_df = train_df.merge(train_tif_taskid1,on='uid',how='left')\n# train_df = train_df.merge(train_tif_taskid2,on='uid',how='left')\n# train_df = train_df.merge(train_tif_advid1,on='uid',how='left')\n# train_df = train_df.merge(train_tif_advid1,on='uid',how='left')\n\ntest_df = test_df.merge(train_tif_uid1,on='uid',how='left')\ntest_df = test_df.merge(train_tif_uid2,on='uid',how='left')\ntest_df = test_df.merge(train_tif_uid3,on='uid',how='left')\ntest_df = test_df.merge(train_tif_uid4,on='uid',how='left')\n# test_df = test_df.merge(train_tif_taskid1,on='uid',how='left')\n# test_df = test_df.merge(train_tif_taskid2,on='uid',how='left')\n# test_df = test_df.merge(train_tif_advid1,on='uid',how='left')\n# test_df = test_df.merge(train_tif_advid1,on='uid',how='left')\nfor i in range(5):\n test_df_list[i] = test_df_list[i].merge(train_tif_uid1,on='uid',how='left')\n test_df_list[i] = test_df_list[i].merge(train_tif_uid2,on='uid',how='left')\n test_df_list[i] = test_df_list[i].merge(train_tif_uid3,on='uid',how='left')\n test_df_list[i] = test_df_list[i].merge(train_tif_uid4,on='uid',how='left')\n# test_df_list[i] = test_df_list[i].merge(train_tif_taskid1,on='uid',how='left')\n# test_df_list[i] = test_df_list[i].merge(train_tif_taskid2,on='uid',how='left')\n# test_df_list[i] = test_df_list[i].merge(train_tif_advid1,on='uid',how='left')\n# test_df_list[i] = test_df_list[i].merge(train_tif_advid2,on='uid',how='left')\n\n\n",
"_____no_output_____"
],
[
"test_df",
"_____no_output_____"
],
[
"cl = CountEncoder()\nfor col in tqdm_notebook(cat_cols):\n cl = CountEncoder(cols=col)\n cl.fit(train_df[col])\n train_df[col + '_count'] = (cl.transform(train_df[col])).values\n test_df_list[0] = test_df_list[0].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[1] = test_df_list[1].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[2] = test_df_list[2].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[3] = test_df_list[3].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[4] = test_df_list[4].join(cl.transform(test_df[col]).add_suffix('_count'))\n ",
"_____no_output_____"
],
[
"cat_cols = cat_cols+['user_kme','ad_kme','uidtask_idtf_argmax']",
"_____no_output_____"
],
[
"dense_feature = [col for col in train_df.columns if col not in drop_cols+cat_cols]",
"_____no_output_____"
],
[
"train_df = reduce_mem(train_df)",
"_____no_output_____"
],
[
"for i in range(5):\n test_df_list[i].drop(['communication_onlinerate'],axis=1,inplace=True)\n test_df_list[i].fillna(0,inplace=True)\n test_df_list[i]['K'] = i",
"_____no_output_____"
],
[
"feature = cat_cols+dense_feature",
"_____no_output_____"
],
[
"estimator_ad= KMeans(n_clusters=500, random_state=42)\nestimator_user= KMeans(n_clusters=500, random_state=42)\n\nuser_col = ['age','city','city_rank','career','gender','residence']\nad_col = ['task_id','adv_id','creat_type_cd','adv_prim_id','dev_id','slot_id','spread_app_id','tags','app_first_class','app_second_class','indu_name','inter_type_cd']\n",
"_____no_output_____"
],
[
"#读取Model\nwith open('estimator.pickle', 'rb') as f:\n estimator_user = pickle.load(f)\n #测试读取后的Model",
"_____no_output_____"
],
[
"#读取Model\nwith open('estimator_ad.pickle', 'rb') as f:\n estimator_ad = pickle.load(f)\n #测试读取后的Model",
"_____no_output_____"
],
[
"ad_features = []\nfor col in train_df.columns:\n for c in ad_col:\n if c+'tar_enco' in col:\n ad_features.append(col)",
"_____no_output_____"
],
[
"user_features = []\nfor col in train_df.columns:\n for c in user_col:\n if c+'tar_enco' in col:\n user_features.append(col)",
"_____no_output_____"
],
[
"ad_pred =estimator_ad.predict(train_df[ad_features])\ntrain_df['ad_kme'] = ad_pred\nfor i,t in enumerate(test_df_list):\n test_df_list[i]['ad_kme'] = estimator_ad.predict(t[ad_features])",
"_____no_output_____"
],
[
"user_pred =estimator_user.predict(train_df[user_features])\ntrain_df['user_kme'] = user_pred\nfor i,t in enumerate(test_df_list):\n test_df_list[i]['user_kme'] = estimator_user.predict(t[user_features])",
"_____no_output_____"
],
[
"import pickle\nwith open('estimator_ad.pickle', 'wb') as f:\n pickle.dump(estimator_ad, f)\n\n\n",
"_____no_output_____"
],
[
"test_df['user_kme'] = estimator_user.predict(test_df[user_features])\ntest_df['ad_kme'] = estimator_ad.predict(test_df[ad_features])",
"_____no_output_____"
],
[
"test_df",
"_____no_output_____"
],
[
"for col in tqdm_notebook(['user_kme','ad_kme','uidtask_idtf_argmax','uidadv_idtf_argmax','uidslot_idtf_argmax','uidadv_prim_idtf_argmax']):\n cl = CountEncoder(cols=col)\n cl.fit(train_df[col])\n train_df[col + '_count'] = (cl.transform(train_df[col])).values\n test_df_list[0] = test_df_list[0].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[1] = test_df_list[1].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[2] = test_df_list[2].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[3] = test_df_list[3].join(cl.transform(test_df[col]).add_suffix('_count'))\n test_df_list[4] = test_df_list[4].join(cl.transform(test_df[col]).add_suffix('_count'))",
"_____no_output_____"
],
[
"for col in tqdm_notebook(['user_kme','ad_kme','uidtask_idtf_argmax','uidadv_idtf_argmax','uidslot_idtf_argmax','uidadv_prim_idtf_argmax']):\n i = 1\n train_df[col + 'tar_enco'] = 0\n train_df['K'] = 0\n for k ,(tr_idx, oof_idx) in enumerate(StratifiedKFold(n_splits=5, random_state=2020, shuffle=True).split(train_df, train_df['label'])):\n print('fold{}'.format(i))\n i+=1\n trn_series = train_df.iloc[tr_idx][col]\n tst_series1 = train_df.iloc[oof_idx][col]\n tst_series2 = test_df_list[k][col]\n target = train_df.iloc[tr_idx].label\n train_targetencoding,oof_targetencoding,test_targetencoding = target_encode(trn_series, \n tst_series1, \n tst_series2,\n target, \n min_samples_leaf=0.2, \n smoothing=1,\n noise_level=0.0001)\n train_df.loc[oof_idx,col + 'tar_enco'] = oof_targetencoding\n train_df.loc[oof_idx,'K'] = k\n test_df_list[k][col + 'tar_enco'] = test_targetencoding\n train_df = reduce_mem(train_df)\n gc.collect()",
"_____no_output_____"
],
[
"seed=1080\nis_shuffle=True",
"_____no_output_____"
],
[
"user_col = ['uid','age','city','city_rank','career','gender','residence','communication_avgonline_30d','consume_purchase','membership_life_duration','up_membership_grade','up_life_duration']\nad_col = ['task_id','adv_id','creat_type_cd','adv_prim_id','dev_id','slot_id','spread_app_id','tags','app_first_class','app_second_class','indu_name','inter_type_cd']\nphone_col = ['device_name','device_size','net_type','emui_dev','device_price']\napp_col = ['his_app_size','his_on_shelf_time','app_score','list_time']",
"_____no_output_____"
],
[
"train_df",
"_____no_output_____"
],
[
"#--------------------------------------------------模型训练----------------------------------------#",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\n\nfor k in tqdm_notebook(range(5)):\n t = train_df[train_df.K!=k].reset_index(drop=True)[user_col]\n t_label = train_df[train_df.K!=k].reset_index(drop=True).label.values\n v = train_df[train_df.K==k].reset_index(drop=True)[user_col]\n v_label = train_df[train_df.K==k].reset_index(drop=True).label.values\n \n RF_user = RandomForestClassifier(n_estimators=10, criterion='gini',n_jobs=-1, random_state=42, verbose=1)\n RF_user.fit(t,t_label)\n train_df.loc[train_df[train_df.K==k].index,'rf_user'] = RF_user.predict_proba(v)[:,1]\n test_df_list[k]['rf_user'] = RF_user.predict_proba(test_df_list[k][user_col])[:,1]\n\nfor k in tqdm_notebook(range(5)):\n t = train_df[train_df.K!=k].reset_index(drop=True)[ad_col]\n t_label = train_df[train_df.K!=k].reset_index(drop=True).label.values\n v = train_df[train_df.K==k].reset_index(drop=True)[ad_col]\n v_label = train_df[train_df.K==k].reset_index(drop=True).label.values\n \n RF_ad = RandomForestClassifier(n_estimators=10, criterion='gini',n_jobs=-1, random_state=42, verbose=1)\n RF_ad.fit(t,t_label)\n train_df.loc[train_df[train_df.K==k].index,'rf_ad'] = RF_ad.predict_proba(v)[:,1]\n test_df_list[k]['rf_ad'] = RF_ad.predict_proba(test_df_list[k][ad_col])[:,1]\n\nfor k in tqdm_notebook(range(5)):\n t = train_df[train_df.K!=k].reset_index(drop=True)[phone_col]\n t_label = train_df[train_df.K!=k].reset_index(drop=True).label.values\n v = train_df[train_df.K==k].reset_index(drop=True)[phone_col]\n v_label = train_df[train_df.K==k].reset_index(drop=True).label.values\n \n RF_phone = RandomForestClassifier(n_estimators=10, criterion='gini',n_jobs=-1, random_state=42, verbose=1)\n RF_phone.fit(t,t_label)\n train_df.loc[train_df[train_df.K==k].index,'rf_phone'] = RF_phone.predict_proba(v)[:,1]\n test_df_list[k]['rf_phone'] = RF_phone.predict_proba(test_df_list[k][phone_col])[:,1]\n \nfor k in tqdm_notebook(range(5)):\n t = train_df[train_df.K!=k].reset_index(drop=True)[app_col]\n t_label = train_df[train_df.K!=k].reset_index(drop=True).label.values\n v = train_df[train_df.K==k].reset_index(drop=True)[app_col]\n v_label = train_df[train_df.K==k].reset_index(drop=True).label.values\n \n RF_app = RandomForestClassifier(n_estimators=10, criterion='gini',n_jobs=-1, random_state=42, verbose=1)\n RF_app.fit(t,t_label)\n train_df.loc[train_df[train_df.K==k].index,'rf_app'] = RF_app.predict_proba(v)[:,1]\n test_df_list[k]['rf_app'] = RF_app.predict_proba(test_df_list[k][app_col])[:,1]",
"_____no_output_____"
],
[
"print(sklearn.metrics.roc_auc_score(train_df.label,train_df.rf_user))\nprint(sklearn.metrics.roc_auc_score(train_df.label,train_df.rf_ad))\nprint(sklearn.metrics.roc_auc_score(train_df.label,train_df.rf_phone))\nprint(sklearn.metrics.roc_auc_score(train_df.label,train_df.rf_app))",
"_____no_output_____"
],
[
"cat_cols",
"_____no_output_____"
],
[
"dense_feature = [col for col in train_df.columns if col not in drop_cols+cat_cols]",
"_____no_output_____"
],
[
"feature = cat_cols+dense_feature",
"_____no_output_____"
],
[
" feature_importance_df = pd.DataFrame()\n predicts = np.zeros(len(train_df))\n pred = np.zeros(len(test_df_list[0]))\n true = np.zeros(len(train_df))\n\n\n begin = 0\n for fold,k in enumerate(range(5)):\n \n #train = train_df[train_df.K!=k].reset_index(drop=True)[feature]\n t_label = train_df[train_df.K!=k].reset_index(drop=True).label\n #valid = train_df[train_df.K==k].reset_index(drop=True)[feature]\n te_label = train_df[train_df.K==k].reset_index(drop=True).label\n \n\n \n clf = cbt.CatBoostClassifier(iterations = 150, learning_rate = 0.3, depth =7, one_hot_max_size=5,use_best_model =True,\n loss_function = 'Logloss', eval_metric= \"AUC\",logging_level='Verbose',task_type='GPU',\n cat_features=cat_cols,)#counter_calc_method='Full',l2_leaf_reg = 10,)\n \n\n\n clf.fit(train_df[train_df.K!=k].reset_index(drop=True)[feature],t_label.astype('int32'),\n eval_set=(train_df[train_df.K==k].reset_index(drop=True)[feature], te_label.astype('int32'))\n ,plot=True,verbose=1,cat_features=cat_cols)\n# predicts[begin:over] = clf.predict_proba(train_df[train_df.K==k].reset_index(drop=True)[feature])[:,1]\n\n# true[begin:over] = te_label.values\n pred += (clf.predict_proba(test_df_list[fold][feature])[:,1])\n# begin+=len(train_df[train_df.K==k].reset_index(drop=True)[feature])\n gc.collect()\n print('--------------------')\n \n #print(sklearn.metrics.roc_auc_score(true,predicts))\n",
"_____no_output_____"
],
[
"feature_importance_df = pd.DataFrame()\nfeature_importance_df[\"importance\"] = clf.feature_importances_\nfeature_importance_df[\"feature\"] = feature",
"_____no_output_____"
],
[
"feature_importance_df.sort_values('importance',ascending=False)",
"_____no_output_____"
],
[
"#------------------------------模型预测----------------------------------------#",
"_____no_output_____"
],
[
"pred = pred/5",
"_____no_output_____"
],
[
"0.8320243359",
"_____no_output_____"
],
[
"(pred>0.5).sum()",
"_____no_output_____"
],
[
"pred",
"_____no_output_____"
],
[
"((pred-np.min(pred))/(np.max(pred)-np.min(pred)))",
"_____no_output_____"
],
[
"res = pd.DataFrame()\nres['id'] = test_df_list[0]['id'].astype('int32')\nres['probability'] = pred\nres.to_csv('5cv_catboost_baseline_target_encoding_.csv',index = False)",
"_____no_output_____"
],
[
"res",
"_____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",
"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"
]
] |
cb0914fa5392dae34f303d36a25bbc9e3c5612c0 | 8,856 | ipynb | Jupyter Notebook | sandbox/2.1.als.ipynb | dmitrii-davidov/retailhero-recomender-baseline | d207c146b048540df7ce83a17727b635743b78f6 | [
"MIT"
] | null | null | null | sandbox/2.1.als.ipynb | dmitrii-davidov/retailhero-recomender-baseline | d207c146b048540df7ce83a17727b635743b78f6 | [
"MIT"
] | null | null | null | sandbox/2.1.als.ipynb | dmitrii-davidov/retailhero-recomender-baseline | d207c146b048540df7ce83a17727b635743b78f6 | [
"MIT"
] | null | null | null | 25.894737 | 188 | 0.542231 | [
[
[
"import pandas as pd\nimport numpy as np\nimport json\nfrom scipy import sparse as sp\nfrom tqdm.notebook import tqdm\nfrom collections import defaultdict",
"_____no_output_____"
],
[
"!pip install implicit",
"WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.\nPlease see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.\nTo avoid this problem you can invoke Python with '-m pip' instead of running pip directly.\nCollecting implicit\n Downloading implicit-0.4.2.tar.gz (1.1 MB)\n\u001b[K |████████████████████████████████| 1.1 MB 97 kB/s eta 0:00:011 |██████████▋ | 368 kB 923 kB/s eta 0:00:01\n\u001b[?25hRequirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from implicit) (1.17.5)\nRequirement already satisfied: scipy>=0.16 in /opt/conda/lib/python3.7/site-packages (from implicit) (1.4.1)\nRequirement already satisfied: tqdm>=4.27 in /opt/conda/lib/python3.7/site-packages (from implicit) (4.42.0)\nBuilding wheels for collected packages: implicit\n Building wheel for implicit (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for implicit: filename=implicit-0.4.2-cp37-cp37m-linux_x86_64.whl size=3101814 sha256=deca4c35e0e276edcb12c09b82faa5f0f8dc673f24baed4fe992fed8a69563ab\n Stored in directory: /home/jovyan/.cache/pip/wheels/2f/ed/a0/bcad2756c8a99e49d6edaf830ab604e5691910df4dd7cec870\nSuccessfully built implicit\nInstalling collected packages: implicit\nSuccessfully installed implicit-0.4.2\n"
],
[
"import implicit",
"_____no_output_____"
],
[
"import sys\nsys.path.append('../')\n\nfrom src.utils import get_shard_path\nfrom src.utils import ProductEncoder, make_coo_row\nfrom src.metrics import normalized_average_precision",
"_____no_output_____"
],
[
"def make_coo_row(transaction_history, product_encoder: ProductEncoder):\n idx = []\n values = []\n\n items = []\n for trans in transaction_history:\n items.extend([i[\"product_id\"] for i in trans[\"products\"]])\n n_items = len(items)\n\n for pid in items:\n idx.append(product_encoder.toIdx(pid))\n values.append(1.0) # убираем нормировку\n \n\n return sp.coo_matrix(\n (np.array(values).astype(np.float32), ([0] * len(idx), idx)), shape=(1, product_encoder.num_products),\n )",
"_____no_output_____"
],
[
"product_encoder = ProductEncoder('../data/raw/products.csv')",
"_____no_output_____"
],
[
"valid_data = [json.loads(l) for l in open(get_shard_path(7))][:3000]",
"_____no_output_____"
],
[
"rows = []\nfor shard_id in range(4):\n for js in tqdm(json.loads(l) for l in open(get_shard_path(shard_id))):\n rows.append(make_coo_row(js[\"transaction_history\"], product_encoder))",
"_____no_output_____"
],
[
"X_sparse = sp.vstack(rows).tocsr()",
"_____no_output_____"
],
[
"X_sparse.shape",
"_____no_output_____"
]
],
[
[
"# ALS",
"_____no_output_____"
]
],
[
[
"model = implicit.als.AlternatingLeastSquares(factors=16, regularization=0.0, iterations=8)\nmodel.fit(X_sparse.T) # обязательный шаг",
"_____no_output_____"
],
[
"m_ap = []\nfor js in tqdm(valid_data):\n row_sparse = make_coo_row(js[\"transaction_history\"], product_encoder).tocsr()\n raw_recs = model.recommend(0, row_sparse, N=30, filter_already_liked_items=False, recalculate_user=True)\n recommended_items = product_encoder.toPid([x[0] for x in raw_recs])\n gt_items = js[\"target\"][0][\"product_ids\"]\n m_ap.append(normalized_average_precision(gt_items, recommended_items, k=30))\nprint(np.mean(m_ap))",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb091cd4ae697f322b8cbb278c138675c1a89a02 | 6,858 | ipynb | Jupyter Notebook | model/training.ipynb | dgobalak/NBA2KPredictions | d04cd66a5b34f4de21fd918fce1cf0ea29b80cf2 | [
"MIT",
"Unlicense"
] | null | null | null | model/training.ipynb | dgobalak/NBA2KPredictions | d04cd66a5b34f4de21fd918fce1cf0ea29b80cf2 | [
"MIT",
"Unlicense"
] | null | null | null | model/training.ipynb | dgobalak/NBA2KPredictions | d04cd66a5b34f4de21fd918fce1cf0ea29b80cf2 | [
"MIT",
"Unlicense"
] | null | null | null | 38.745763 | 2,396 | 0.469962 | [
[
[
"import pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nimport numpy as np\nimport seaborn as sns\nimport math\nimport pickle",
"_____no_output_____"
],
[
"'''\nPTS: Points per game\nFP: Fantasy points per game\nFGA: Field goals attempted per game\nFTM: Free throw makes per game\nMIN: Minutes per game\nrankings: NBA 2K rating\n'''\n# Importing CSV data into pandas dataframe\ndf = pd.read_csv(\"..\\data\\data.csv\")\n# Chose features that show linear behaviour when graphed against rankings\ndf = df[['PTS', 'FP', 'FGA', 'FTM', 'MIN', 'rankings']]\ndf.dropna()",
"_____no_output_____"
],
[
"X = np.array(df.drop(['rankings'], axis=1))\ny = np.array(df['rankings'])",
"_____no_output_____"
],
[
"# Scaled features down to [-1,1]\nscaler = preprocessing.StandardScaler()\nscaled_X = scaler.fit_transform(X)",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.5)",
"_____no_output_____"
],
[
"clf = LinearRegression()\nclf.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Compute various success metrics for regression\nr2 = r2_score(y_true=y_test, y_pred=clf.predict(X_test))\nmse = mean_squared_error(y_true=y_test, y_pred=clf.predict(X_test))\nrmse = math.sqrt(mse)\nprint(f\"R2: {r2}, MSE: {mse}, RMSE: {rmse}\")",
"R2: 0.881547999455247, MSE: 3.959240909539362, RMSE: 1.9897841364176572\n"
],
[
"with open('model.pkl', 'wb') as f:\n pickle.dump(clf, f)\n\nwith open('scaler.pkl', 'wb') as f:\n pickle.dump(scaler, f)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb093bc2545932e5de2f1f525bb0915e03b53042 | 61,915 | ipynb | Jupyter Notebook | tobi.ipynb | tobikuhlmann/Movie-recommendation-lab | 9db8046ffc5b5af35e1dbe6aa53e5aac57d44e74 | [
"Apache-2.0"
] | 1 | 2020-09-27T15:55:59.000Z | 2020-09-27T15:55:59.000Z | tobi.ipynb | tobikuhlmann/Movie-recommendation-lab | 9db8046ffc5b5af35e1dbe6aa53e5aac57d44e74 | [
"Apache-2.0"
] | null | null | null | tobi.ipynb | tobikuhlmann/Movie-recommendation-lab | 9db8046ffc5b5af35e1dbe6aa53e5aac57d44e74 | [
"Apache-2.0"
] | null | null | null | 64.42768 | 8,300 | 0.724477 | [
[
[
"# Codebuster STAT 535 Statistical Computing Project\n## Movie recommendation recommendation pipeline",
"_____no_output_____"
],
[
"##### Patrick's comments 11/9\n\n- Goal: Build a small real world deployment pipeline like it can be used in netflix / amazon \n- build / test with movie recommendation data set (model fitting, data preprocessing, evaluation)\n- Show that it also works with another dataset like product recommendation\n - Find data on UCI repo, kaggle, google search \n\n- Use scikit learn estimation: https://github.com/scikit-learn-contrib/project-template\n",
"_____no_output_____"
],
[
"## Literature\n\n- https://users.ece.cmu.edu/~dbatra/publications/assets/goel_batra_netflix.pdf\n- http://delivery.acm.org/10.1145/1460000/1454012/p11-park.pdf?ip=72.19.68.210&id=1454012&acc=ACTIVE%20SERVICE&key=73B3886B1AEFC4BB%2EB478147E31829731%2E4D4702B0C3E38B35%2E4D4702B0C3E38B35&__acm__=1543416754_7f92e0642e26e7ea732886879096c704\n- https://www.kaggle.com/prajitdatta/movielens-100k-dataset/kernels\n- https://medium.com/@james_aka_yale/the-4-recommendation-engines-that-can-predict-your-movie-tastes-bbec857b8223\n- https://www.kaggle.com/c/predict-movie-ratings\n- https://cseweb.ucsd.edu/classes/wi17/cse258-a/reports/a048.pdf\n- https://github.com/neilsummers/predict_movie_ratings/blob/master/movieratings.py\n- https://medium.com/@connectwithghosh/recommender-system-on-the-movielens-using-an-autoencoder-using-tensorflow-in-python-f13d3e8d600d\n### A few more\n- https://sci2s.ugr.es/keel/pdf/specific/congreso/xia_dong_06.pdf (Uses SMV for classification, then MF for recommendation)\n- https://www.kaggle.com/rounakbanik/movie-recommender-systems (Employs at least three Modules for recommendation)\n- http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.703.4954&rep=rep1&type=pdf (Close to what we need, but a little too involving)\n- https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0165868 (Uses SVM and correlation matrices...I have already tried the correlation approach, looks quite good, but how to quantify accuracy?)\n- https://www.quora.com/How-do-we-use-SVMs-in-a-collaborative-recommendation (A good thread on SVM)\n-http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python/ (A good tutorial on matrix factorizasion)",
"_____no_output_____"
],
[
"## Approach\n\n##### User profile cases: \n- ##### Case 0 rated movies: Supervised prediction with just user age, gender, and year of the movie\nIn case of cold-start: No user information available\n\n- ##### Case < 20 rated movies: Content-based recommender system\nContent-based recommendation information about users and their taste. As we can see in the preprocessing, most of the users only rated one to five movies, implying that we have incomplete user-profiles. I think content-based recommendation makes sense here, because we can recommend similar movies, but not other categories that a user might like because we can not identify similar users with an incomplete user profile.\n\n- ##### Case >=20 rated movies: Collaborative recommender system\nCollaborative filtering makes sense if you have a good user profile, which we assume we have if a user rated more or equal than 10 movies. With a good user profile we can identify similar users and make more sophisticated recommendations, e.g. movies from other genres.\n\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom scipy import interp\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\nfrom sklearn.model_selection import cross_val_predict, cross_val_score, cross_validate, StratifiedKFold\nfrom sklearn.metrics import classification_report,confusion_matrix, roc_curve, auc",
"_____no_output_____"
]
],
[
[
"## Data Understanding and Preprocessing\nGet a feeling for the dataset, its problems and conduct helpful preprocessing",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"allData.tsv\", sep='\\t')\nprint(f\"Shape: {df.shape}\")\nprint(df.dtypes)\ndf.head()",
"Shape: (31620, 10)\nuserID int64\nage int64\ngender object\nmovieID int64\nname object\nyear int64\ngenre1 object\ngenre2 object\ngenre3 object\nrating int64\ndtype: object\n"
],
[
"df.age.value_counts()",
"_____no_output_____"
]
],
[
[
"##### Histogram: Number of movies are rated by users\nMost users rated only up tp 5 movies",
"_____no_output_____"
]
],
[
[
"df.userID.value_counts().hist(bins=50)",
"_____no_output_____"
]
],
[
[
"##### Divide datasets for different recommendations (random forest, content based, collaborative based)\nIt can be useful to use content-based recommender systems for those users",
"_____no_output_____"
]
],
[
[
"df_split = df.copy()\ndf_split.set_index('userID', inplace=True)\n# set for content based recommendation with #ratings < 10\ndf_content = df_split[df.userID.value_counts()<10]\n\n# set for collaborative recommendation with #ratings >= 10\ndf_collaborative = df_split[df.userID.value_counts()>=10]",
"/Users/tobias/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:4: UserWarning: Boolean Series key will be reindexed to match DataFrame index.\n after removing the cwd from sys.path.\n/Users/tobias/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:7: UserWarning: Boolean Series key will be reindexed to match DataFrame index.\n import sys\n"
],
[
"df_content.index.value_counts().hist(bins=50)",
"_____no_output_____"
],
[
"df_collaborative.index.value_counts().hist(bins=50)",
"_____no_output_____"
]
],
[
[
"##### Transform numerical rating to binary\n- 1, if user rates movie 4 or 5\n- 0, if user rates movie less than 4",
"_____no_output_____"
]
],
[
[
"df['rating'].mask(df['rating'] < 4, 0, inplace=True)\ndf['rating'].mask(df['rating'] > 3, 1, inplace=True)",
"_____no_output_____"
]
],
[
[
"##### Check rating distribution",
"_____no_output_____"
]
],
[
[
"df['rating'].hist()",
"_____no_output_____"
]
],
[
[
"## Recommendation",
"_____no_output_____"
],
[
"##### Cold start: Gradient Boosting Classifier\nLogic: Treat every user as same, predicting rating over whole movie dataset \n\n- ##### Case 0 rated movies: Supervised prediction with just user age, gender, and year of the movie\nIn case of cold-start: No user information available",
"_____no_output_____"
]
],
[
[
"# Cross Validation to test and anticipate overfitting problem\ndef crossvalidate(clf, X,y):\n '''\n Calculate precision, recall, and roc_auc for a 10-fold cross validation run with passed classifier\n '''\n scores1 = cross_val_score(clf, X, y, cv=10, scoring='precision')\n scores2 = cross_val_score(clf, X, y, cv=10, scoring='recall')\n scores3 = cross_val_score(clf, X, y, cv=10, scoring='roc_auc')\n # The mean score and standard deviation of the score estimate\n print(\"Cross Validation Precision: %0.2f (+/- %0.2f)\" % (scores1.mean(), scores1.std()))\n print(\"Cross Validation Recall: %0.2f (+/- %0.2f)\" % (scores2.mean(), scores2.std()))\n print(\"Cross Validation roc_auc: %0.2f (+/- %0.2f)\" % (scores3.mean(), scores3.std()))",
"_____no_output_____"
],
[
"# Run classifier with cross-validation and plot ROC curves\n# from http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html\ndef get_crossval_roc(clfname, classifier,X,y):\n '''\n Run classifier with cross-validation and plot ROC curves\n '''\n n_samples, n_features = X.shape\n \n cv = StratifiedKFold(n_splits=6)\n\n tprs = []\n aucs = []\n mean_fpr = np.linspace(0, 1, 100)\n\n i = 0\n for train, test in cv.split(X, y):\n probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])\n # Compute ROC curve and area the curve\n fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])\n tprs.append(interp(mean_fpr, fpr, tpr))\n tprs[-1][0] = 0.0\n roc_auc = auc(fpr, tpr)\n aucs.append(roc_auc)\n plt.plot(fpr, tpr, lw=1, alpha=0.3,\n label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))\n\n i += 1\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n label='Chance', alpha=.8)\n\n mean_tpr = np.mean(tprs, axis=0)\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n std_auc = np.std(aucs)\n plt.plot(mean_fpr, mean_tpr, color='b',\n label=r'Mean ROC (AUC = %0.2f $\\pm$ %0.2f)' % (mean_auc, std_auc),\n lw=2, alpha=.8)\n\n std_tpr = np.std(tprs, axis=0)\n tprs_upper = np.minimum(mean_tpr + std_tpr, 1)\n tprs_lower = np.maximum(mean_tpr - std_tpr, 0)\n plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,\n label=r'$\\pm$ 1 std. dev.')\n\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example')\n plt.legend(loc=\"lower right\")\n plt.show()\n \n return",
"_____no_output_____"
]
],
[
[
"##### Preprocessing for boosted random forest classifier",
"_____no_output_____"
]
],
[
[
"# User information before any movie ratings\nX = df[['age', 'gender', 'year', 'genre1', 'genre2', 'genre3']]\ny = df['rating'].as_matrix()\n\n# Preprocessing\n# One hot encoding\ndummyvars = pd.get_dummies(X[['gender', 'genre1', 'genre2', 'genre3']])\n# append the dummy variables to df\nX = pd.concat([X[['age', 'year']], dummyvars], axis = 1).as_matrix()",
"_____no_output_____"
],
[
"print(\"GradientBoostingClassifier\")\ngbclf = GradientBoostingClassifier(n_estimators=100)\ngbclf.fit(X=X, y=y)\ngbclf.predict()\n#crossvalidate(gbclf,X,y)\n#get_crossval_roc(\"gbclf\",gbclf,X,y)",
"_____no_output_____"
]
],
[
[
"##### Content-based recommendation with tf-idf for user with <10 ratings\n\n- ##### Case < 10 rated movies: Content-based recommender system\nContent-based recommendation information about users and their taste. As we can see in the preprocessing, most of the users only rated one to five movies, implying that we have incomplete user-profiles. I think content-based recommendation makes sense here, because we can recommend similar movies, but not other categories that a user might like because we can not identify similar users with an incomplete user profile.\n\n- Code inspired by: https://medium.com/@james_aka_yale/the-4-recommendation-engines-that-can-predict-your-movie-tastes-bbec857b8223\n\n- Make recommendations based on similarity of movie genres, purely content based.",
"_____no_output_____"
]
],
[
[
"# import movies\nmovies = pd.read_csv(\"movies.tsv\", sep='\\t')\nprint(f\"Shape: {df.shape}\")\nmovies.head()",
"Shape: (31620, 10)\n"
],
[
"# Preprocessing\n# Strip space at the end of string\nmovies['name'] = movies['name'].str.rstrip()\n# Concat genres into one string\nmovies['genres_concat'] = movies[['genre1', 'genre2', 'genre3']].astype(str).apply(' '.join, axis=1)\n# Remove nans in string and strip spaces at the end\nmovies['genres_concat'] = movies['genres_concat'].str.replace('nan','').str.rstrip()\nmovies.head()",
"_____no_output_____"
],
[
"# Function that get movie recommendations based on the cosine similarity score of movie genres\ndef content_based_recommendation(movies, name, number_recommendations):\n '''\n Recommends number of similar movie based on movie title and similarity to movies in movie database\n \n @param movies: pandas dataframe with movie dataset with columns (movieID, name, genres_concat)\n @param name: movie title as string\n @param number_recommendations: number of recommendations returned as integer\n '''\n # Create tf_idf matrix sklearn TfidfVectorizer\n tf = TfidfVectorizer(analyzer='word',ngram_range=(1, 2),min_df=0, stop_words='english')\n tfidf_matrix = tf.fit_transform(movies['genres_concat'])\n \n # calculate similarity matrix with cosine distance of tf_idf values\n cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n \n # Build a 1-dimensional array with movie titles\n indices = pd.Series(movies.index, index=movies['name'])\n \n # Ranks movies according to similarity to requested movie\n idx = indices[name]\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:(number_recommendations+1)]\n movie_indices = [i[0] for i in sim_scores]\n return movies.name.iloc[movie_indices]",
"_____no_output_____"
]
],
[
[
"##### Test recommendations",
"_____no_output_____"
]
],
[
[
"content_based_recommendation(movies, 'Father of the Bride Part II', 5)",
"_____no_output_____"
]
],
[
[
"## Evaluation",
"_____no_output_____"
],
[
"## Ceate predictions for predict.csv",
"_____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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb093d4f2074c3a5ec0b81b4132a0455f9db66e6 | 11,318 | ipynb | Jupyter Notebook | writeups/coalescent/100runs_2016-04-26/analysis.ipynb | kdmurray91/kwip-experiments | 7a8e8778e0f5ae39d2dd123d9e4216a475d62ba0 | [
"MIT"
] | 1 | 2020-07-07T04:50:20.000Z | 2020-07-07T04:50:20.000Z | writeups/coalescent/100runs_2016-04-26/analysis.ipynb | kdmurray91/kwip-experiments | 7a8e8778e0f5ae39d2dd123d9e4216a475d62ba0 | [
"MIT"
] | null | null | null | writeups/coalescent/100runs_2016-04-26/analysis.ipynb | kdmurray91/kwip-experiments | 7a8e8778e0f5ae39d2dd123d9e4216a475d62ba0 | [
"MIT"
] | null | null | null | 27.011933 | 230 | 0.519791 | [
[
[
"from glob import glob\nfrom os import path\nimport re\nfrom skbio import DistanceMatrix\nimport pandas as pd\nimport numpy as np\n\nfrom kwipexpt import *\n%matplotlib inline\n%load_ext rpy2.ipython",
"_____no_output_____"
],
[
"%%R\nlibrary(tidyr)\nlibrary(dplyr, warn.conflicts=F, quietly=T)\nlibrary(ggplot2)",
"_____no_output_____"
]
],
[
[
"Calculate performance of kWIP\n=============================\n\nThe next bit of python code calculates the performance of kWIP against the distance between samples calulcated from the alignments of their genomes.\n\nThis code caluclates spearman's $\\rho$ between the off-diagonal elements of the triagnular distance matrices.\n\n",
"_____no_output_____"
]
],
[
[
"expts = list(map(lambda fp: path.basename(fp.rstrip('/')), glob('data/*/')))\nprint(\"Expts:\", *expts[:10], \"...\")",
"_____no_output_____"
],
[
"def process_expt(expt):\n expt_results = []\n \n def extract_info(filename):\n return re.search(r'kwip/(\\d\\.?\\d*)x-(0\\.\\d+)-(wip|ip).dist', filename).groups()\n \n # dict of scale: distance matrix, populated as we go\n truths = {}\n \n for distfile in glob(\"data/{}/kwip/*.dist\".format(expt)):\n cov, scale, metric = extract_info(distfile)\n if scale not in truths:\n genome_dist_path = 'data/{ex}/all_genomes-{sc}.dist'.format(ex=expt, sc=scale)\n truths[scale] = load_sample_matrix_to_runs(genome_dist_path)\n exptmat = DistanceMatrix.read(distfile)\n rho = spearmans_rho_distmats(exptmat, truths[scale])\n expt_results.append({\n \"coverage\": cov,\n \"scale\": scale,\n \"metric\": metric,\n \"rho\": rho,\n \"seed\": expt,\n })\n return expt_results\n\n#process_expt('3662')",
"_____no_output_____"
],
[
"results = []\nfor res in map(process_expt, expts):\n results.extend(res)\nresults = pd.DataFrame(results)",
"_____no_output_____"
]
],
[
[
"Statistical analysis\n====================\n\nIs done is R, as that's easier.\n\nBelow we see a summary and structure of the data",
"_____no_output_____"
]
],
[
[
"%%R -i results\n\nresults$coverage = as.numeric(as.character(results$coverage))\nresults$scale = as.numeric(as.character(results$scale))\n\nprint(summary(results))\nstr(results)",
"_____no_output_____"
]
],
[
[
"### Experiment design\n\nBelow we see the design of the experiment in terms of the two major variables.\n\nWe have a series (vertically) that, at 30x coverage, looks at the effect of genetic variation on performance. There is a second series that examines the effect of coverage at an average pairwise genetic distance of 0.001.\n\nThere are 100 replicates for each data point, performed as a separate bootstrap across the random creation of the tree and sampling of reads etc.",
"_____no_output_____"
]
],
[
[
"%%R\n\nggplot(results, aes(x=coverage, y=scale)) +\n geom_point() +\n scale_x_log10() +\n scale_y_log10() +\n theme_bw()",
"_____no_output_____"
]
],
[
[
"Effect of Coverage\n------------------\n\nHere we show the spread of data across the 100 reps as boxplots per metric and covreage level.\n\nI note that the weighted product seems slightly more variable, particularly at higher coverage. Though the median is nearly always higher",
"_____no_output_____"
]
],
[
[
"%%R\n\ndat = results %>%\n filter(scale==0.001, coverage<=30) %>%\n select(rho, metric, coverage)\n \ndat$coverage = as.factor(dat$coverage)\nggplot(dat, aes(x=coverage, y=rho, fill=metric)) +\n geom_boxplot(aes(fill=metric))\n ",
"_____no_output_____"
],
[
"%%R\n\n# AND AGAIN WITHOUT SUBSETTING\ndat = results %>%\n filter(scale==0.001) %>%\n select(rho, metric, coverage)\n \ndat$coverage = as.factor(dat$coverage)\nggplot(dat, aes(x=coverage, y=rho, fill=metric)) +\n geom_boxplot(aes(fill=metric))\n ",
"_____no_output_____"
],
[
"%%R\n\ndat = subset(results, scale==0.001 & coverage <=15, select=-scale)\nggplot(dat, aes(x=coverage, y=rho, colour=seed, linetype=metric)) +\n geom_line()",
"_____no_output_____"
],
[
"%%R\nsumm = results %>%\n filter(scale==0.001, coverage <= 50) %>%\n select(-scale) %>%\n group_by(coverage, metric) %>%\n summarise(rho_av=mean(rho), rho_err=sd(rho))\n \nggplot(summ, aes(x=coverage, y=rho_av, ymin=rho_av-rho_err, ymax=rho_av+rho_err, group=metric)) +\n geom_line(aes(linetype=metric)) +\n geom_ribbon(aes(fill=metric), alpha=0.2) +\n xlab('Genome Coverage') +\n ylab(expression(paste(\"Spearman's \", rho, \" +- SD\"))) +\n scale_x_log10()+\n ggtitle(\"Performance of WIP & IP\") +\n theme_bw()",
"_____no_output_____"
],
[
"%%R\nsem <- function(x) sqrt(var(x,na.rm=TRUE)/length(na.omit(x)))\nsumm = results %>%\n filter(scale==0.001) %>%\n select(-scale) %>%\n group_by(coverage, metric) %>%\n summarise(rho_av=mean(rho), rho_err=sem(rho))\n \nggplot(summ, aes(x=coverage, y=rho_av, ymin=rho_av-rho_err, ymax=rho_av+rho_err, group=metric)) +\n geom_line(aes(linetype=metric)) +\n geom_ribbon(aes(fill=metric), alpha=0.2) +\n xlab('Genome Coverage') +\n ylab(expression(paste(\"Spearman's \", rho))) +\n scale_x_log10()+\n theme_bw()",
"_____no_output_____"
],
[
"%%R\ncov_diff = results %>%\n filter(scale==0.001) %>%\n select(rho, metric, coverage, seed) %>%\n spread(metric, rho) %>%\n mutate(diff=wip-ip) %>%\n select(coverage, seed, diff) \nprint(summary(cov_diff))\n\np = ggplot(cov_diff, aes(x=coverage, y=diff, colour=seed)) +\n geom_line() +\n scale_x_log10() +\n ggtitle(\"Per expt difference in performance (wip - ip)\")\nprint(p)\n\nsumm = cov_diff %>%\n group_by(coverage) %>%\n summarise(diff_av=mean(diff), diff_sd=sd(diff))\n\nggplot(summ, aes(x=coverage, y=diff_av, ymin=diff_av-diff_sd, ymax=diff_av+diff_sd)) +\n geom_line() + \n geom_ribbon(alpha=0.2) +\n xlab('Genome Coverage') +\n ylab(expression(paste(\"Improvment in Spearman's \", rho, \" (wip - IP)\"))) +\n scale_x_log10() +\n theme_bw()",
"_____no_output_____"
],
[
"%%R\nvar = results %>%\n filter(coverage == 30) %>%\n select(-coverage)\nvar$scale = as.factor(var$scale)\nggplot(var, aes(x=scale, y=rho, fill=metric)) +\n geom_boxplot() +\n xlab('Mean pairwise variation') +\n ylab(expression(paste(\"Spearman's \", rho))) +\n #scale_x_log10()+\n theme_bw()\n",
"_____no_output_____"
],
[
"%%R\nsumm = results %>%\n filter(coverage == 30) %>%\n select(-coverage) %>%\n group_by(scale, metric) %>%\n summarise(rho_av=mean(rho), rho_sd=sd(rho))\nggplot(summ, aes(x=scale, y=rho_av, ymin=rho_av-rho_sd, ymax=rho_av+rho_sd, group=metric)) +\n geom_line(aes(linetype=metric)) +\n geom_ribbon(aes(fill=metric), alpha=0.2) +\n xlab('Mean pairwise variation') +\n ylab(expression(paste(\"Spearman's \", rho))) +\n scale_x_log10()+\n theme_bw()\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb094e94c705dac66c16b885f2c774db033ac3b9 | 8,983 | ipynb | Jupyter Notebook | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | mottiden/scipy_2015_sklearn_tutorial-master | da16ecb941cf459699964b271ccdeca34fcd2b53 | [
"CC0-1.0"
] | 659 | 2015-03-05T14:01:52.000Z | 2022-03-14T08:18:39.000Z | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | anhlbt/scipy_2015_sklearn_tutorial | be0a35724b9f0f0b92ea6c325ad5137176585b1c | [
"CC0-1.0"
] | 42 | 2015-03-05T19:44:28.000Z | 2017-07-18T19:53:37.000Z | notebooks/03.3 Case Study - Face Recognition with Eigenfaces.ipynb | anhlbt/scipy_2015_sklearn_tutorial | be0a35724b9f0f0b92ea6c325ad5137176585b1c | [
"CC0-1.0"
] | 398 | 2015-04-13T17:32:59.000Z | 2022-03-10T19:39:12.000Z | 27.725309 | 496 | 0.59813 | [
[
[
"# Example from Image Processing",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"Here we'll take a look at a simple facial recognition example.\nThis uses a dataset available within scikit-learn consisting of a\nsubset of the [Labeled Faces in the Wild](http://vis-www.cs.umass.edu/lfw/)\ndata. Note that this is a relatively large download (~200MB) so it may\ntake a while to execute.",
"_____no_output_____"
]
],
[
[
"from sklearn import datasets\nlfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4,\n data_home='datasets')\nlfw_people.data.shape",
"_____no_output_____"
]
],
[
[
"If you're on a unix-based system such as linux or Mac OSX, these shell commands\ncan be used to see the downloaded dataset:",
"_____no_output_____"
]
],
[
[
"!ls datasets",
"_____no_output_____"
],
[
"!du -sh datasets/lfw_home",
"_____no_output_____"
]
],
[
[
"Once again, let's visualize these faces to see what we're working with:",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(8, 6))\n# plot several images\nfor i in range(15):\n ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(lfw_people.images[i], cmap=plt.cm.bone)",
"_____no_output_____"
],
[
"import numpy as np\nplt.figure(figsize=(10, 2))\n\nunique_targets = np.unique(lfw_people.target)\ncounts = [(lfw_people.target == i).sum() for i in unique_targets]\n\nplt.xticks(unique_targets, lfw_people.target_names[unique_targets])\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=45, size=14)\n_ = plt.bar(unique_targets, counts)",
"_____no_output_____"
]
],
[
[
"One thing to note is that these faces have already been localized and scaled\nto a common size. This is an important preprocessing piece for facial\nrecognition, and is a process that can require a large collection of training\ndata. This can be done in scikit-learn, but the challenge is gathering a\nsufficient amount of training data for the algorithm to work\n\nFortunately, this piece is common enough that it has been done. One good\nresource is [OpenCV](http://opencv.willowgarage.com/wiki/FaceRecognition), the\n*Open Computer Vision Library*.",
"_____no_output_____"
],
[
"We'll perform a Support Vector classification of the images. We'll\ndo a typical train-test split on the images to make this happen:",
"_____no_output_____"
]
],
[
[
"from sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(\n lfw_people.data, lfw_people.target, random_state=0)\n\nprint(X_train.shape, X_test.shape)",
"_____no_output_____"
]
],
[
[
"## Preprocessing: Principal Component Analysis",
"_____no_output_____"
],
[
"1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable\nsize, while maintaining most of the information in the dataset. Here it is useful to use a variant\nof PCA called ``RandomizedPCA``, which is an approximation of PCA that can be much faster for large\ndatasets. We saw this method in the previous notebook, and will use it again here:",
"_____no_output_____"
]
],
[
[
"from sklearn import decomposition\npca = decomposition.RandomizedPCA(n_components=150, whiten=True,\n random_state=1999)\npca.fit(X_train)\nX_train_pca = pca.transform(X_train)\nX_test_pca = pca.transform(X_test)\nprint(X_train_pca.shape)\nprint(X_test_pca.shape)",
"_____no_output_____"
]
],
[
[
"These projected components correspond to factors in a linear combination of\ncomponent images such that the combination approaches the original face. In general, PCA can be a powerful technique for preprocessing that can greatly improve classification performance.",
"_____no_output_____"
],
[
"## Doing the Learning: Support Vector Machines",
"_____no_output_____"
],
[
"Now we'll perform support-vector-machine classification on this reduced dataset:",
"_____no_output_____"
]
],
[
[
"from sklearn import svm\nclf = svm.SVC(C=5., gamma=0.001)\nclf.fit(X_train_pca, y_train)",
"_____no_output_____"
]
],
[
[
"Finally, we can evaluate how well this classification did. First, we might plot a\nfew of the test-cases with the labels learned from the training set:",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(8, 6))\nfor i in range(15):\n ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(X_test[i].reshape((50, 37)), cmap=plt.cm.bone)\n y_pred = clf.predict(X_test_pca[i])[0]\n color = 'black' if y_pred == y_test[i] else 'red'\n ax.set_title(lfw_people.target_names[y_pred], fontsize='small', color=color)",
"_____no_output_____"
]
],
[
[
"The classifier is correct on an impressive number of images given the simplicity\nof its learning model! Using a linear classifier on 150 features derived from\nthe pixel-level data, the algorithm correctly identifies a large number of the\npeople in the images.\n\nAgain, we can\nquantify this effectiveness using ``clf.score``",
"_____no_output_____"
]
],
[
[
"print(clf.score(X_test_pca, y_test))",
"_____no_output_____"
]
],
[
[
"## Final Note",
"_____no_output_____"
],
[
"Here we have used PCA \"eigenfaces\" as a pre-processing step for facial recognition.\nThe reason we chose this is because PCA is a broadly-applicable technique, which can\nbe useful for a wide array of data types. For more details on the eigenfaces approach, see the original paper by [Turk and Penland, Eigenfaces for Recognition](http://www.face-rec.org/algorithms/PCA/jcn.pdf). Research in the field of facial recognition has moved much farther beyond this paper, and has shown specific feature extraction methods can be more effective. However, eigenfaces is a canonical example of machine learning \"in the wild\", and is a simple method with good results.",
"_____no_output_____"
]
]
] | [
"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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb0951d04b6b90a38fb99d15a411627cff263284 | 8,701 | ipynb | Jupyter Notebook | Assignment 1.ipynb | benarutochan/Internship-22- | ec59e265bb72d1e7197c7a97ad04f29b8ed227f3 | [
"Apache-2.0"
] | null | null | null | Assignment 1.ipynb | benarutochan/Internship-22- | ec59e265bb72d1e7197c7a97ad04f29b8ed227f3 | [
"Apache-2.0"
] | null | null | null | Assignment 1.ipynb | benarutochan/Internship-22- | ec59e265bb72d1e7197c7a97ad04f29b8ed227f3 | [
"Apache-2.0"
] | null | null | null | 21.537129 | 130 | 0.466268 | [
[
[
"### 1)Which of the following operators is used to calculate remainder in a division?\n\n### ANS-%",
"_____no_output_____"
]
],
[
[
"## 2)\n2/3",
"_____no_output_____"
],
[
"## 3)_\n6<<2",
"_____no_output_____"
],
[
"## 4)\n6&2",
"_____no_output_____"
],
[
"## 5)\n6|2",
"_____no_output_____"
]
],
[
[
"### 6)What does the finally keyword denotes in python?\n \n #### ANS-the finally block will be executed no matter if the try block raises an error or not.",
"_____no_output_____"
],
[
"### 7)What does raise keyword is used for in python?\n\n### ANS-A) It is used to raise an exception.",
"_____no_output_____"
],
[
"### 8)Which of the following is a common use case of yield keyword in python?\n\n### ANS- C) in defining a generator",
"_____no_output_____"
],
[
"### 9)Which of the following are the valid variable names?\n### A) _abc C) abc2 ",
"_____no_output_____"
],
[
"### 10) Which of the following are the keywords in python?\n\n### Ans-yield and raise.",
"_____no_output_____"
],
[
"### 11.\tWrite a python program to find the factorial of a number.",
"_____no_output_____"
]
],
[
[
"## For factors\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\nn=int(input(\"Input a number to compute the factiorial : \"))\nprint(factorial(n))\n",
"Input a number to compute the factiorial : 7\n5040\n"
]
],
[
[
"### 12) Write a python program to find whether a number is prime or composite.",
"_____no_output_____"
]
],
[
[
"num = int(input(\"Enter any number : \"))\nif num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n print(num, \"is NOT a prime number\")\n break\n else:\n print(num, \"is a PRIME number\")\nelif num == 0 or 1:\n print(num, \"is a neither prime NOR composite number\")\nelse:\n print(num, \"is NOT a prime number it is a COMPOSITE number\")",
"Enter any number : 15\n15 is NOT a prime number\n"
]
],
[
[
"### 13)Write a python program to check whether a given string is palindrome or not.",
"_____no_output_____"
]
],
[
[
"num=int(input(\"Enter a number:\"))\ntemp=num\nrev=0\nwhile(num>0):\n dig=num%10\n rev=rev*10+dig\n num=num//10\nif(temp==rev):\n print(\"The number is palindrome!\")\nelse:\n print(\"Not a palindrome!\")",
"Enter a number:145412\nNot a palindrome!\n"
],
[
"## for both number and alphabet which are pallindrome.\nstring=input((\"Enter a string:\"))\nif(string==string[::-1]):\n print(\"The string is a palindrome\")\nelse:\n print(\"Not a palindrome\")\n \n \n ",
"Enter a string:123456787654321\nThe string is a palindrome\n"
]
],
[
[
"### 14)Write a Python program to get the third side of right-angled triangle from two given sides.",
"_____no_output_____"
]
],
[
[
"def pythagoras(opposite_side,adjacent_side,hypotenuse):\n if opposite_side == str(\"x\"):\n return (\"Opposite = \" + str(((hypotenuse**2) - (adjacent_side**2))**0.5))\n elif adjacent_side == str(\"x\"):\n return (\"Adjacent = \" + str(((hypotenuse**2) - (opposite_side**2))**0.5))\n elif hypotenuse == str(\"x\"):\n return (\"Hypotenuse = \" + str(((opposite_side**2) + (adjacent_side**2))**0.5))\n else:\n return \"answer!\"\n \nprint(pythagoras(6,8,'x'))\nprint(pythagoras(6,'x',10))\nprint(pythagoras('x',8,10))\nprint(pythagoras(6,8,10))",
"Hypotenuse = 10.0\nAdjacent = 8.0\nOpposite = 6.0\nanswer!\n"
],
[
"## I dont understand this program mam. I tried ",
"_____no_output_____"
]
],
[
[
"### 15) Write a python program to print the frequency of each of the characters present in a given string.",
"_____no_output_____"
]
],
[
[
"def char_frequency(str1):\n dict = {}\n for n in str1:\n keys = dict.keys()\n if n in keys:\n dict[n] += 1\n else:\n dict[n] = 1\n return dict\nprint(char_frequency('lord of the ring and games of thrones'))\n",
"{'l': 1, 'o': 4, 'r': 3, 'd': 2, ' ': 7, 'f': 2, 't': 2, 'h': 2, 'e': 3, 'i': 1, 'n': 3, 'g': 2, 'a': 2, 'm': 1, 's': 2}\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.