with xml tags'\nxml_text.find('
","_____no_output_____"]],[["# IMPORT DATA FILES USED BY THIS NOTEBOOK\nimport os, requests\n\nfile_links = [(\"data/Stock_Data.csv\", \"https://jckantor.github.io/nbpages/data/Stock_Data.csv\")]\n\n# This cell has been added by nbpages. Run this cell to download data files required for this notebook.\n\nfor filepath, fileurl in file_links:\n stem, filename = os.path.split(filepath)\n if stem:\n if not os.path.exists(stem):\n os.mkdir(stem)\n if not os.path.isfile(filepath):\n with open(filepath, 'wb') as f:\n response = requests.get(fileurl)\n f.write(response.content)\n","_____no_output_____"]],[["# 2.4 Working with Data and Figures","_____no_output_____"],["## 2.4.1 Importing data\n\nThe following cell reads the data file `Stock_Data.csv` from the `data` subdirectory. The name of this file will appear in the data index.","_____no_output_____"]],[["import pandas as pd\n\ndf = pd.read_csv(\"data/Stock_Data.csv\")\ndf.head()","_____no_output_____"]],[["## 2.4.2 Creating and saving figures\n\nThe following cell creates a figure `Stock_Data.png` in the `figures` subdirectory. The name of this file will appear in the figures index.","_____no_output_____"]],[["%matplotlib inline\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style(\"darkgrid\")\nfig, ax = plt.subplots(2, 1, figsize=(8, 5))\n(df/df.iloc[0]).drop('VIX', axis=1).plot(ax=ax[0])\ndf['VIX'].plot(ax=ax[1])\nax[0].set_title('Normalized Indices')\nax[1].set_title('Volatility VIX')\nax[1].set_xlabel('Days')\nfig.tight_layout()\n\nif not os.path.exists(\"figures\"):\n os.mkdir(\"figures\")\nplt.savefig(\"figures/Stock_Data.png\")","_____no_output_____"]],[["\n< [2.3 Heirarchical Tagging](https://jckantor.github.io/nbpages/02.03-Heirarchical-Tagging.html) | [Contents](toc.html) | [Tag Index](tag_index.html) | [2.5 Lint](https://jckantor.github.io/nbpages/02.05-Lint.html) >
","_____no_output_____"]]],"string":"[\n [\n [\n \"\\n*This notebook contains material from [nbpages](https://jckantor.github.io/nbpages) by Jeffrey Kantor (jeff at nd.edu). The text is released under the\\n[CC-BY-NC-ND-4.0 license](https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode).\\nThe code is released under the [MIT license](https://opensource.org/licenses/MIT).*\",\n \"_____no_output_____\"\n ],\n [\n \"\\n< [2.3 Heirarchical Tagging](https://jckantor.github.io/nbpages/02.03-Heirarchical-Tagging.html) | [Contents](toc.html) | [Tag Index](tag_index.html) | [2.5 Lint](https://jckantor.github.io/nbpages/02.05-Lint.html) >
\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# IMPORT DATA FILES USED BY THIS NOTEBOOK\\nimport os, requests\\n\\nfile_links = [(\\\"data/Stock_Data.csv\\\", \\\"https://jckantor.github.io/nbpages/data/Stock_Data.csv\\\")]\\n\\n# This cell has been added by nbpages. Run this cell to download data files required for this notebook.\\n\\nfor filepath, fileurl in file_links:\\n stem, filename = os.path.split(filepath)\\n if stem:\\n if not os.path.exists(stem):\\n os.mkdir(stem)\\n if not os.path.isfile(filepath):\\n with open(filepath, 'wb') as f:\\n response = requests.get(fileurl)\\n f.write(response.content)\\n\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 2.4 Working with Data and Figures\",\n \"_____no_output_____\"\n ],\n [\n \"## 2.4.1 Importing data\\n\\nThe following cell reads the data file `Stock_Data.csv` from the `data` subdirectory. The name of this file will appear in the data index.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"import pandas as pd\\n\\ndf = pd.read_csv(\\\"data/Stock_Data.csv\\\")\\ndf.head()\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## 2.4.2 Creating and saving figures\\n\\nThe following cell creates a figure `Stock_Data.png` in the `figures` subdirectory. The name of this file will appear in the figures index.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"%matplotlib inline\\nimport os\\nimport matplotlib.pyplot as plt\\nimport seaborn as sns\\n\\nsns.set_style(\\\"darkgrid\\\")\\nfig, ax = plt.subplots(2, 1, figsize=(8, 5))\\n(df/df.iloc[0]).drop('VIX', axis=1).plot(ax=ax[0])\\ndf['VIX'].plot(ax=ax[1])\\nax[0].set_title('Normalized Indices')\\nax[1].set_title('Volatility VIX')\\nax[1].set_xlabel('Days')\\nfig.tight_layout()\\n\\nif not os.path.exists(\\\"figures\\\"):\\n os.mkdir(\\\"figures\\\")\\nplt.savefig(\\\"figures/Stock_Data.png\\\")\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"\\n< [2.3 Heirarchical Tagging](https://jckantor.github.io/nbpages/02.03-Heirarchical-Tagging.html) | [Contents](toc.html) | [Tag Index](tag_index.html) | [2.5 Lint](https://jckantor.github.io/nbpages/02.05-Lint.html) >
No community queries yet The top public SQL queries from the community will appear here once available.\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown","markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown"]],"string":"[\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ]\n]"}}},{"rowIdx":568,"cells":{"hexsha":{"kind":"string","value":"d019df1dc4e7ede43c002af6ef0c96410f3b182a"},"size":{"kind":"number","value":20629,"string":"20,629"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"homeworkdata/Homework_4_Paolo_Rivas_Legua.ipynb"},"max_stars_repo_name":{"kind":"string","value":"paolorivas/homeworkfoundations"},"max_stars_repo_head_hexsha":{"kind":"string","value":"1d92575bfe9213562b84ab66a44d892c7dbb855a"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"null"},"max_stars_repo_stars_event_min_datetime":{"kind":"null"},"max_stars_repo_stars_event_max_datetime":{"kind":"null"},"max_issues_repo_path":{"kind":"string","value":"homeworkdata/Homework_4_Paolo_Rivas_Legua.ipynb"},"max_issues_repo_name":{"kind":"string","value":"paolorivas/homeworkfoundations"},"max_issues_repo_head_hexsha":{"kind":"string","value":"1d92575bfe9213562b84ab66a44d892c7dbb855a"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"homeworkdata/Homework_4_Paolo_Rivas_Legua.ipynb"},"max_forks_repo_name":{"kind":"string","value":"paolorivas/homeworkfoundations"},"max_forks_repo_head_hexsha":{"kind":"string","value":"1d92575bfe9213562b84ab66a44d892c7dbb855a"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":28.8921568627,"string":"28.892157"},"max_line_length":{"kind":"number","value":416,"string":"416"},"alphanum_fraction":{"kind":"number","value":0.5426341558,"string":"0.542634"},"cells":{"kind":"list like","value":[[["# Homework #4\n\nThese problem sets focus on list comprehensions, string operations and regular expressions.\n\n## Problem set #1: List slices and list comprehensions\n\nLet's start with some data. The following cell contains a string with comma-separated integers, assigned to a variable called `numbers_str`:","_____no_output_____"]],[["numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'","_____no_output_____"]],[["In the following cell, complete the code with an expression that evaluates to a list of integers derived from the raw numbers in `numbers_str`, assigning the value of this expression to a variable `numbers`. If you do everything correctly, executing the cell should produce the output `985` (*not* `'985'`).","_____no_output_____"]],[["values = numbers_str.split(\",\")\nnumbers = [int(i) for i in values]\n# numbers\nmax(numbers)","_____no_output_____"]],[["Great! We'll be using the `numbers` list you created above in the next few problems.\n\nIn the cell below, fill in the square brackets so that the expression evaluates to a list of the ten largest values in `numbers`. Expected output:\n\n [506, 528, 550, 581, 699, 721, 736, 804, 855, 985]\n \n(Hint: use a slice.)","_____no_output_____"]],[["#test\nprint(sorted(numbers))\n","[7, 65, 68, 120, 171, 258, 279, 332, 436, 496, 506, 528, 550, 581, 699, 721, 736, 804, 855, 985]\n"],["sorted(numbers)[10:]","_____no_output_____"]],[["In the cell below, write an expression that evaluates to a list of the integers from `numbers` that are evenly divisible by three, *sorted in numerical order*. Expected output:\n\n [120, 171, 258, 279, 528, 699, 804, 855]","_____no_output_____"]],[["[i for i in sorted(numbers) if i%3 == 0]","_____no_output_____"]],[["Okay. You're doing great. Now, in the cell below, write an expression that evaluates to a list of the square roots of all the integers in `numbers` that are less than 100. In order to do this, you'll need to use the `sqrt` function from the `math` module, which I've already imported for you. Expected output:\n\n [2.6457513110645907, 8.06225774829855, 8.246211251235321]\n \n(These outputs might vary slightly depending on your platform.)","_____no_output_____"]],[["import math\nfrom math import sqrt","_____no_output_____"],["[math.sqrt(i) for i in sorted(numbers) if i < 100]","_____no_output_____"]],[["## Problem set #2: Still more list comprehensions\n\nStill looking good. Let's do a few more with some different data. In the cell below, I've defined a data structure and assigned it to a variable `planets`. It's a list of dictionaries, with each dictionary describing the characteristics of a planet in the solar system. Make sure to run the cell before you proceed.","_____no_output_____"]],[["planets = [\n {'diameter': 0.382,\n 'mass': 0.06,\n 'moons': 0,\n 'name': 'Mercury',\n 'orbital_period': 0.24,\n 'rings': 'no',\n 'type': 'terrestrial'},\n {'diameter': 0.949,\n 'mass': 0.82,\n 'moons': 0,\n 'name': 'Venus',\n 'orbital_period': 0.62,\n 'rings': 'no',\n 'type': 'terrestrial'},\n {'diameter': 1.00,\n 'mass': 1.00,\n 'moons': 1,\n 'name': 'Earth',\n 'orbital_period': 1.00,\n 'rings': 'no',\n 'type': 'terrestrial'},\n {'diameter': 0.532,\n 'mass': 0.11,\n 'moons': 2,\n 'name': 'Mars',\n 'orbital_period': 1.88,\n 'rings': 'no',\n 'type': 'terrestrial'},\n {'diameter': 11.209,\n 'mass': 317.8,\n 'moons': 67,\n 'name': 'Jupiter',\n 'orbital_period': 11.86,\n 'rings': 'yes',\n 'type': 'gas giant'},\n {'diameter': 9.449,\n 'mass': 95.2,\n 'moons': 62,\n 'name': 'Saturn',\n 'orbital_period': 29.46,\n 'rings': 'yes',\n 'type': 'gas giant'},\n {'diameter': 4.007,\n 'mass': 14.6,\n 'moons': 27,\n 'name': 'Uranus',\n 'orbital_period': 84.01,\n 'rings': 'yes',\n 'type': 'ice giant'},\n {'diameter': 3.883,\n 'mass': 17.2,\n 'moons': 14,\n 'name': 'Neptune',\n 'orbital_period': 164.8,\n 'rings': 'yes',\n 'type': 'ice giant'}]","_____no_output_____"]],[["Now, in the cell below, write a list comprehension that evaluates to a list of names of the planets that have a radius greater than four earth radii. Expected output:\n\n ['Jupiter', 'Saturn', 'Uranus']","_____no_output_____"]],[["earth_diameter = planets[2]['diameter']","_____no_output_____"],["#earth radius is = half diameter. In a multiplication equation the diameter value can be use as a parameter.\n[i['name'] for i in planets if i['diameter'] >= earth_diameter*4]","_____no_output_____"]],[["In the cell below, write a single expression that evaluates to the sum of the mass of all planets in the solar system. Expected output: `446.79`","_____no_output_____"]],[["mass_list = []\nfor planet in planets:\n outcome = planet['mass']\n mass_list.append(outcome)\ntotal = sum(mass_list)\ntotal","_____no_output_____"]],[["Good work. Last one with the planets. Write an expression that evaluates to the names of the planets that have the word `giant` anywhere in the value for their `type` key. Expected output:\n\n ['Jupiter', 'Saturn', 'Uranus', 'Neptune']","_____no_output_____"]],[["[i['name'] for i in planets if 'giant' in i['type']]","_____no_output_____"]],[["*EXTREME BONUS ROUND*: Write an expression below that evaluates to a list of the names of the planets in ascending order by their number of moons. (The easiest way to do this involves using the [`key` parameter of the `sorted` function](https://docs.python.org/3.5/library/functions.html#sorted), which we haven't yet discussed in class! That's why this is an EXTREME BONUS question.) Expected output:\n\n ['Mercury', 'Venus', 'Earth', 'Mars', 'Neptune', 'Uranus', 'Saturn', 'Jupiter']","_____no_output_____"]],[["#Done in class","_____no_output_____"]],[["## Problem set #3: Regular expressions","_____no_output_____"],["In the following section, we're going to do a bit of digital humanities. (I guess this could also be journalism if you were... writing an investigative piece about... early 20th century American poetry?) We'll be working with the following text, Robert Frost's *The Road Not Taken*. Make sure to run the following cell before you proceed.","_____no_output_____"]],[["import re\npoem_lines = ['Two roads diverged in a yellow wood,',\n 'And sorry I could not travel both',\n 'And be one traveler, long I stood',\n 'And looked down one as far as I could',\n 'To where it bent in the undergrowth;',\n '',\n 'Then took the other, as just as fair,',\n 'And having perhaps the better claim,',\n 'Because it was grassy and wanted wear;',\n 'Though as for that the passing there',\n 'Had worn them really about the same,',\n '',\n 'And both that morning equally lay',\n 'In leaves no step had trodden black.',\n 'Oh, I kept the first for another day!',\n 'Yet knowing how way leads on to way,',\n 'I doubted if I should ever come back.',\n '',\n 'I shall be telling this with a sigh',\n 'Somewhere ages and ages hence:',\n 'Two roads diverged in a wood, and I---',\n 'I took the one less travelled by,',\n 'And that has made all the difference.']","_____no_output_____"]],[["In the cell above, I defined a variable `poem_lines` which has a list of lines in the poem, and `import`ed the `re` library.\n\nIn the cell below, write a list comprehension (using `re.search()`) that evaluates to a list of lines that contain two words next to each other (separated by a space) that have exactly four characters. (Hint: use the `\\b` anchor. Don't overthink the \"two words in a row\" requirement.)\n\nExpected result:\n\n```\n['Then took the other, as just as fair,',\n 'Had worn them really about the same,',\n 'And both that morning equally lay',\n 'I doubted if I should ever come back.',\n 'I shall be telling this with a sigh']\n```","_____no_output_____"]],[["[line for line in poem_lines if re.search(r\"\\b\\w{4}\\b\\s\\b\\w{4}\\b\", line)]","_____no_output_____"]],[["Good! Now, in the following cell, write a list comprehension that evaluates to a list of lines in the poem that end with a five-letter word, regardless of whether or not there is punctuation following the word at the end of the line. (Hint: Try using the `?` quantifier. Is there an existing character class, or a way to *write* a character class, that matches non-alphanumeric characters?) Expected output:\n\n```\n['And be one traveler, long I stood',\n 'And looked down one as far as I could',\n 'And having perhaps the better claim,',\n 'Though as for that the passing there',\n 'In leaves no step had trodden black.',\n 'Somewhere ages and ages hence:']\n```","_____no_output_____"]],[["[line for line in poem_lines if re.search(r\"(?:\\s\\w{5}\\b$|\\s\\w{5}\\b[.:;,]$)\", line)]","_____no_output_____"]],[["Okay, now a slightly trickier one. In the cell below, I've created a string `all_lines` which evaluates to the entire text of the poem in one string. Execute this cell.","_____no_output_____"]],[["all_lines = \" \".join(poem_lines)","_____no_output_____"]],[["Now, write an expression that evaluates to all of the words in the poem that follow the word 'I'. (The strings in the resulting list should *not* include the `I`.) Hint: Use `re.findall()` and grouping! Expected output:\n\n ['could', 'stood', 'could', 'kept', 'doubted', 'should', 'shall', 'took']","_____no_output_____"]],[["[item[2:] for item in (re.findall(r\"\\bI\\b\\s\\b[a-z]{1,}\", all_lines))]","_____no_output_____"]],[["Finally, something super tricky. Here's a list of strings that contains a restaurant menu. Your job is to wrangle this plain text, slightly-structured data into a list of dictionaries.","_____no_output_____"]],[["entrees = [\n \"Yam, Rosemary and Chicken Bowl with Hot Sauce $10.95\",\n \"Lavender and Pepperoni Sandwich $8.49\",\n \"Water Chestnuts and Peas Power Lunch (with mayonnaise) $12.95 - v\",\n \"Artichoke, Mustard Green and Arugula with Sesame Oil over noodles $9.95 - v\",\n \"Flank Steak with Lentils And Tabasco Pepper With Sweet Chilli Sauce $19.95\",\n \"Rutabaga And Cucumber Wrap $8.49 - v\"\n]","_____no_output_____"]],[["You'll need to pull out the name of the dish and the price of the dish. The `v` after the hyphen indicates that the dish is vegetarian---you'll need to include that information in your dictionary as well. I've included the basic framework; you just need to fill in the contents of the `for` loop.\n\nExpected output:\n\n```\n[{'name': 'Yam, Rosemary and Chicken Bowl with Hot Sauce ',\n 'price': 10.95,\n 'vegetarian': False},\n {'name': 'Lavender and Pepperoni Sandwich ',\n 'price': 8.49,\n 'vegetarian': False},\n {'name': 'Water Chestnuts and Peas Power Lunch (with mayonnaise) ',\n 'price': 12.95,\n 'vegetarian': True},\n {'name': 'Artichoke, Mustard Green and Arugula with Sesame Oil over noodles ',\n 'price': 9.95,\n 'vegetarian': True},\n {'name': 'Flank Steak with Lentils And Tabasco Pepper With Sweet Chilli Sauce ',\n 'price': 19.95,\n 'vegetarian': False},\n {'name': 'Rutabaga And Cucumber Wrap ', 'price': 8.49, 'vegetarian': True}]\n```","_____no_output_____"]],[["menu = []\nfor dish in entrees:\n match = re.search(r\"^(.*) \\$(.*)\", dish) \n vegetarian = re.search(r\"v$\", match.group(2))\n price = re.search(r\"(?:\\d\\.\\d\\d|\\d\\d\\.\\d\\d)\", dish)\n if vegetarian == None:\n vegetarian = False\n else:\n vegetarian = True\n if match:\n dish = {\n 'name': match.group(1), 'price': price.group(), 'vegetarian': vegetarian\n }\n menu.append(dish)\nmenu","_____no_output_____"]],[["Great work! You are done. Go cavort in the sun, or whatever it is you students do when you're done with your homework","_____no_output_____"]]],"string":"[\n [\n [\n \"# Homework #4\\n\\nThese problem sets focus on list comprehensions, string operations and regular expressions.\\n\\n## Problem set #1: List slices and list comprehensions\\n\\nLet's start with some data. The following cell contains a string with comma-separated integers, assigned to a variable called `numbers_str`:\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"In the following cell, complete the code with an expression that evaluates to a list of integers derived from the raw numbers in `numbers_str`, assigning the value of this expression to a variable `numbers`. If you do everything correctly, executing the cell should produce the output `985` (*not* `'985'`).\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"values = numbers_str.split(\\\",\\\")\\nnumbers = [int(i) for i in values]\\n# numbers\\nmax(numbers)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Great! We'll be using the `numbers` list you created above in the next few problems.\\n\\nIn the cell below, fill in the square brackets so that the expression evaluates to a list of the ten largest values in `numbers`. Expected output:\\n\\n [506, 528, 550, 581, 699, 721, 736, 804, 855, 985]\\n \\n(Hint: use a slice.)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#test\\nprint(sorted(numbers))\\n\",\n \"[7, 65, 68, 120, 171, 258, 279, 332, 436, 496, 506, 528, 550, 581, 699, 721, 736, 804, 855, 985]\\n\"\n ],\n [\n \"sorted(numbers)[10:]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"In the cell below, write an expression that evaluates to a list of the integers from `numbers` that are evenly divisible by three, *sorted in numerical order*. Expected output:\\n\\n [120, 171, 258, 279, 528, 699, 804, 855]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"[i for i in sorted(numbers) if i%3 == 0]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Okay. You're doing great. Now, in the cell below, write an expression that evaluates to a list of the square roots of all the integers in `numbers` that are less than 100. In order to do this, you'll need to use the `sqrt` function from the `math` module, which I've already imported for you. Expected output:\\n\\n [2.6457513110645907, 8.06225774829855, 8.246211251235321]\\n \\n(These outputs might vary slightly depending on your platform.)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"import math\\nfrom math import sqrt\",\n \"_____no_output_____\"\n ],\n [\n \"[math.sqrt(i) for i in sorted(numbers) if i < 100]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## Problem set #2: Still more list comprehensions\\n\\nStill looking good. Let's do a few more with some different data. In the cell below, I've defined a data structure and assigned it to a variable `planets`. It's a list of dictionaries, with each dictionary describing the characteristics of a planet in the solar system. Make sure to run the cell before you proceed.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"planets = [\\n {'diameter': 0.382,\\n 'mass': 0.06,\\n 'moons': 0,\\n 'name': 'Mercury',\\n 'orbital_period': 0.24,\\n 'rings': 'no',\\n 'type': 'terrestrial'},\\n {'diameter': 0.949,\\n 'mass': 0.82,\\n 'moons': 0,\\n 'name': 'Venus',\\n 'orbital_period': 0.62,\\n 'rings': 'no',\\n 'type': 'terrestrial'},\\n {'diameter': 1.00,\\n 'mass': 1.00,\\n 'moons': 1,\\n 'name': 'Earth',\\n 'orbital_period': 1.00,\\n 'rings': 'no',\\n 'type': 'terrestrial'},\\n {'diameter': 0.532,\\n 'mass': 0.11,\\n 'moons': 2,\\n 'name': 'Mars',\\n 'orbital_period': 1.88,\\n 'rings': 'no',\\n 'type': 'terrestrial'},\\n {'diameter': 11.209,\\n 'mass': 317.8,\\n 'moons': 67,\\n 'name': 'Jupiter',\\n 'orbital_period': 11.86,\\n 'rings': 'yes',\\n 'type': 'gas giant'},\\n {'diameter': 9.449,\\n 'mass': 95.2,\\n 'moons': 62,\\n 'name': 'Saturn',\\n 'orbital_period': 29.46,\\n 'rings': 'yes',\\n 'type': 'gas giant'},\\n {'diameter': 4.007,\\n 'mass': 14.6,\\n 'moons': 27,\\n 'name': 'Uranus',\\n 'orbital_period': 84.01,\\n 'rings': 'yes',\\n 'type': 'ice giant'},\\n {'diameter': 3.883,\\n 'mass': 17.2,\\n 'moons': 14,\\n 'name': 'Neptune',\\n 'orbital_period': 164.8,\\n 'rings': 'yes',\\n 'type': 'ice giant'}]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Now, in the cell below, write a list comprehension that evaluates to a list of names of the planets that have a radius greater than four earth radii. Expected output:\\n\\n ['Jupiter', 'Saturn', 'Uranus']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"earth_diameter = planets[2]['diameter']\",\n \"_____no_output_____\"\n ],\n [\n \"#earth radius is = half diameter. In a multiplication equation the diameter value can be use as a parameter.\\n[i['name'] for i in planets if i['diameter'] >= earth_diameter*4]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"In the cell below, write a single expression that evaluates to the sum of the mass of all planets in the solar system. Expected output: `446.79`\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"mass_list = []\\nfor planet in planets:\\n outcome = planet['mass']\\n mass_list.append(outcome)\\ntotal = sum(mass_list)\\ntotal\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Good work. Last one with the planets. Write an expression that evaluates to the names of the planets that have the word `giant` anywhere in the value for their `type` key. Expected output:\\n\\n ['Jupiter', 'Saturn', 'Uranus', 'Neptune']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"[i['name'] for i in planets if 'giant' in i['type']]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"*EXTREME BONUS ROUND*: Write an expression below that evaluates to a list of the names of the planets in ascending order by their number of moons. (The easiest way to do this involves using the [`key` parameter of the `sorted` function](https://docs.python.org/3.5/library/functions.html#sorted), which we haven't yet discussed in class! That's why this is an EXTREME BONUS question.) Expected output:\\n\\n ['Mercury', 'Venus', 'Earth', 'Mars', 'Neptune', 'Uranus', 'Saturn', 'Jupiter']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#Done in class\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## Problem set #3: Regular expressions\",\n \"_____no_output_____\"\n ],\n [\n \"In the following section, we're going to do a bit of digital humanities. (I guess this could also be journalism if you were... writing an investigative piece about... early 20th century American poetry?) We'll be working with the following text, Robert Frost's *The Road Not Taken*. Make sure to run the following cell before you proceed.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"import re\\npoem_lines = ['Two roads diverged in a yellow wood,',\\n 'And sorry I could not travel both',\\n 'And be one traveler, long I stood',\\n 'And looked down one as far as I could',\\n 'To where it bent in the undergrowth;',\\n '',\\n 'Then took the other, as just as fair,',\\n 'And having perhaps the better claim,',\\n 'Because it was grassy and wanted wear;',\\n 'Though as for that the passing there',\\n 'Had worn them really about the same,',\\n '',\\n 'And both that morning equally lay',\\n 'In leaves no step had trodden black.',\\n 'Oh, I kept the first for another day!',\\n 'Yet knowing how way leads on to way,',\\n 'I doubted if I should ever come back.',\\n '',\\n 'I shall be telling this with a sigh',\\n 'Somewhere ages and ages hence:',\\n 'Two roads diverged in a wood, and I---',\\n 'I took the one less travelled by,',\\n 'And that has made all the difference.']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"In the cell above, I defined a variable `poem_lines` which has a list of lines in the poem, and `import`ed the `re` library.\\n\\nIn the cell below, write a list comprehension (using `re.search()`) that evaluates to a list of lines that contain two words next to each other (separated by a space) that have exactly four characters. (Hint: use the `\\\\b` anchor. Don't overthink the \\\"two words in a row\\\" requirement.)\\n\\nExpected result:\\n\\n```\\n['Then took the other, as just as fair,',\\n 'Had worn them really about the same,',\\n 'And both that morning equally lay',\\n 'I doubted if I should ever come back.',\\n 'I shall be telling this with a sigh']\\n```\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"[line for line in poem_lines if re.search(r\\\"\\\\b\\\\w{4}\\\\b\\\\s\\\\b\\\\w{4}\\\\b\\\", line)]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Good! Now, in the following cell, write a list comprehension that evaluates to a list of lines in the poem that end with a five-letter word, regardless of whether or not there is punctuation following the word at the end of the line. (Hint: Try using the `?` quantifier. Is there an existing character class, or a way to *write* a character class, that matches non-alphanumeric characters?) Expected output:\\n\\n```\\n['And be one traveler, long I stood',\\n 'And looked down one as far as I could',\\n 'And having perhaps the better claim,',\\n 'Though as for that the passing there',\\n 'In leaves no step had trodden black.',\\n 'Somewhere ages and ages hence:']\\n```\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"[line for line in poem_lines if re.search(r\\\"(?:\\\\s\\\\w{5}\\\\b$|\\\\s\\\\w{5}\\\\b[.:;,]$)\\\", line)]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Okay, now a slightly trickier one. In the cell below, I've created a string `all_lines` which evaluates to the entire text of the poem in one string. Execute this cell.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"all_lines = \\\" \\\".join(poem_lines)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Now, write an expression that evaluates to all of the words in the poem that follow the word 'I'. (The strings in the resulting list should *not* include the `I`.) Hint: Use `re.findall()` and grouping! Expected output:\\n\\n ['could', 'stood', 'could', 'kept', 'doubted', 'should', 'shall', 'took']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"[item[2:] for item in (re.findall(r\\\"\\\\bI\\\\b\\\\s\\\\b[a-z]{1,}\\\", all_lines))]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Finally, something super tricky. Here's a list of strings that contains a restaurant menu. Your job is to wrangle this plain text, slightly-structured data into a list of dictionaries.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"entrees = [\\n \\\"Yam, Rosemary and Chicken Bowl with Hot Sauce $10.95\\\",\\n \\\"Lavender and Pepperoni Sandwich $8.49\\\",\\n \\\"Water Chestnuts and Peas Power Lunch (with mayonnaise) $12.95 - v\\\",\\n \\\"Artichoke, Mustard Green and Arugula with Sesame Oil over noodles $9.95 - v\\\",\\n \\\"Flank Steak with Lentils And Tabasco Pepper With Sweet Chilli Sauce $19.95\\\",\\n \\\"Rutabaga And Cucumber Wrap $8.49 - v\\\"\\n]\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"You'll need to pull out the name of the dish and the price of the dish. The `v` after the hyphen indicates that the dish is vegetarian---you'll need to include that information in your dictionary as well. I've included the basic framework; you just need to fill in the contents of the `for` loop.\\n\\nExpected output:\\n\\n```\\n[{'name': 'Yam, Rosemary and Chicken Bowl with Hot Sauce ',\\n 'price': 10.95,\\n 'vegetarian': False},\\n {'name': 'Lavender and Pepperoni Sandwich ',\\n 'price': 8.49,\\n 'vegetarian': False},\\n {'name': 'Water Chestnuts and Peas Power Lunch (with mayonnaise) ',\\n 'price': 12.95,\\n 'vegetarian': True},\\n {'name': 'Artichoke, Mustard Green and Arugula with Sesame Oil over noodles ',\\n 'price': 9.95,\\n 'vegetarian': True},\\n {'name': 'Flank Steak with Lentils And Tabasco Pepper With Sweet Chilli Sauce ',\\n 'price': 19.95,\\n 'vegetarian': False},\\n {'name': 'Rutabaga And Cucumber Wrap ', 'price': 8.49, 'vegetarian': True}]\\n```\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"menu = []\\nfor dish in entrees:\\n match = re.search(r\\\"^(.*) \\\\$(.*)\\\", dish) \\n vegetarian = re.search(r\\\"v$\\\", match.group(2))\\n price = re.search(r\\\"(?:\\\\d\\\\.\\\\d\\\\d|\\\\d\\\\d\\\\.\\\\d\\\\d)\\\", dish)\\n if vegetarian == None:\\n vegetarian = False\\n else:\\n vegetarian = True\\n if match:\\n dish = {\\n 'name': match.group(1), 'price': price.group(), 'vegetarian': vegetarian\\n }\\n menu.append(dish)\\nmenu\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Great work! You are done. Go cavort in the sun, or whatever it is you students do when you're done with your homework\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"],["code"],["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"]],"string":"[\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ]\n]"}}},{"rowIdx":569,"cells":{"hexsha":{"kind":"string","value":"d019f6ff15f3d8162ba6446a1acfb2e3814ec143"},"size":{"kind":"number","value":440448,"string":"440,448"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"examples/prep_demo.ipynb"},"max_stars_repo_name":{"kind":"string","value":"NeuroDataDesign/pyprep"},"max_stars_repo_head_hexsha":{"kind":"string","value":"f97e7ec54acb5b5c80dec89d0d37e005877a8258"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2019-12-13T00:51:40.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2019-12-13T00:51:40.000Z"},"max_issues_repo_path":{"kind":"string","value":"examples/prep_demo.ipynb"},"max_issues_repo_name":{"kind":"string","value":"NeuroDataDesign/pyprep"},"max_issues_repo_head_hexsha":{"kind":"string","value":"f97e7ec54acb5b5c80dec89d0d37e005877a8258"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"number","value":3,"string":"3"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2019-11-26T14:46:25.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2020-03-21T05:59:33.000Z"},"max_forks_repo_path":{"kind":"string","value":"examples/prep_demo.ipynb"},"max_forks_repo_name":{"kind":"string","value":"NeuroDataDesign/pyprep"},"max_forks_repo_head_hexsha":{"kind":"string","value":"f97e7ec54acb5b5c80dec89d0d37e005877a8258"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":1262.0286532951,"string":"1,262.028653"},"max_line_length":{"kind":"number","value":420358,"string":"420,358"},"alphanum_fraction":{"kind":"number","value":0.9413006757,"string":"0.941301"},"cells":{"kind":"list like","value":[[["empty"]]],"string":"[\n [\n [\n \"empty\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["empty"],"string":"[\n \"empty\"\n]"},"cell_type_groups":{"kind":"list like","value":[["empty"]],"string":"[\n [\n \"empty\"\n ]\n]"}}},{"rowIdx":570,"cells":{"hexsha":{"kind":"string","value":"d019fe270b86f1379833e192ec59a8b984199ef5"},"size":{"kind":"number","value":9716,"string":"9,716"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"census/catboost/gcp_ai_platform/notebooks/catboost_census_notebook.ipynb"},"max_stars_repo_name":{"kind":"string","value":"jared-burns/machine_learning_examples"},"max_stars_repo_head_hexsha":{"kind":"string","value":"5ae0a5ba8e0395250fb4d40f77a5f03b5390c0bd"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":12,"string":"12"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2020-10-12T15:57:29.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2022-02-06T08:09:20.000Z"},"max_issues_repo_path":{"kind":"string","value":"census/catboost/gcp_ai_platform/notebooks/catboost_census_notebook.ipynb"},"max_issues_repo_name":{"kind":"string","value":"jared-burns/machine_learning_examples"},"max_issues_repo_head_hexsha":{"kind":"string","value":"5ae0a5ba8e0395250fb4d40f77a5f03b5390c0bd"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"number","value":1,"string":"1"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2021-05-21T14:43:09.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2021-05-21T14:43:09.000Z"},"max_forks_repo_path":{"kind":"string","value":"census/catboost/gcp_ai_platform/notebooks/catboost_census_notebook.ipynb"},"max_forks_repo_name":{"kind":"string","value":"jared-burns/machine_learning_examples"},"max_forks_repo_head_hexsha":{"kind":"string","value":"5ae0a5ba8e0395250fb4d40f77a5f03b5390c0bd"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"number","value":4,"string":"4"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2020-11-20T08:12:20.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2021-01-26T08:12:21.000Z"},"avg_line_length":{"kind":"number","value":29.3534743202,"string":"29.353474"},"max_line_length":{"kind":"number","value":165,"string":"165"},"alphanum_fraction":{"kind":"number","value":0.5839851791,"string":"0.583985"},"cells":{"kind":"list like","value":[[["Used https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/xgboost/notebooks/census_training/train.py as a starting point and adjusted to CatBoost","_____no_output_____"]],[["#Google Cloud Libraries\nfrom google.cloud import storage\n\n\n#System Libraries\nimport datetime\nimport subprocess\n\n#Data Libraries\nimport pandas as pd\nimport numpy as np\n\n#ML Libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\nfrom catboost import CatBoostClassifier, Pool, cv\nfrom catboost import CatBoost, Pool\n\n","_____no_output_____"],["from catboost.utils import get_gpu_device_count\nprint('I see %i GPU devices' % get_gpu_device_count())","I see 1 GPU devices\n"],["# Fill in your Cloud Storage bucket name\nBUCKET_ID = \"mchrestkha-demo-env-ml-examples\"\n\ncensus_data_filename = 'adult.data.csv'\n\n# Public bucket holding the census data\nbucket = storage.Client().bucket('cloud-samples-data')\n\n# Path to the data inside the public bucket\ndata_dir = 'ai-platform/census/data/'\n\n# Download the data\nblob = bucket.blob(''.join([data_dir, census_data_filename]))\nblob.download_to_filename(census_data_filename)\n","_____no_output_____"],["# these are the column labels from the census data files\nCOLUMNS = (\n 'age',\n 'workclass',\n 'fnlwgt',\n 'education',\n 'education-num',\n 'marital-status',\n 'occupation',\n 'relationship',\n 'race',\n 'sex',\n 'capital-gain',\n 'capital-loss',\n 'hours-per-week',\n 'native-country',\n 'income-level'\n)\n# categorical columns contain data that need to be turned into numerical values before being used by XGBoost\nCATEGORICAL_COLUMNS = (\n 'workclass',\n 'education',\n 'marital-status',\n 'occupation',\n 'relationship',\n 'race',\n 'sex',\n 'native-country'\n)\n\n# Load the training census dataset\nwith open(census_data_filename, 'r') as train_data:\n raw_training_data = pd.read_csv(train_data, header=None, names=COLUMNS)\n# remove column we are trying to predict ('income-level') from features list\nX = raw_training_data.drop('income-level', axis=1)\n# create training labels list\n#train_labels = (raw_training_data['income-level'] == ' >50K')\ny = raw_training_data['income-level']","_____no_output_____"],["# Since the census data set has categorical features, we need to convert\n# them to numerical values.\n# convert data in categorical columns to numerical values\nX_enc=X\nencoders = {col:LabelEncoder() for col in CATEGORICAL_COLUMNS}\nfor col in CATEGORICAL_COLUMNS:\n X_enc[col] = encoders[col].fit_transform(X[col])\n ","_____no_output_____"],["y_enc=LabelEncoder().fit_transform(y)","_____no_output_____"],["X_train, X_validation, y_train, y_validation = train_test_split(X_enc, y_enc, train_size=0.75, random_state=42)","_____no_output_____"],["print(type(y))\nprint(type(y_enc))","_____no_output_____"],["%%time\n\n#model = CatBoost({'iterations':50})\nmodel=CatBoostClassifier(\n od_type='Iter'\n#iterations=5000,\n#custom_loss=['Accuracy']\n)\nmodel.fit(\n X_train,y_train,eval_set=(X_validation, y_validation),\n\n verbose=50)\n\n# # load data into DMatrix object\n# dtrain = xgb.DMatrix(train_features, train_labels)\n# # train model\n# bst = xgb.train({}, dtrain, 20)","Learning rate set to 0.069772\n0:\tlearn: 0.6282687\ttest: 0.6273059\tbest: 0.6273059 (0)\ttotal: 11.3ms\tremaining: 11.2s\n50:\tlearn: 0.3021165\ttest: 0.3008721\tbest: 0.3008721 (50)\ttotal: 530ms\tremaining: 9.87s\n100:\tlearn: 0.2857407\ttest: 0.2886646\tbest: 0.2886646 (100)\ttotal: 1.03s\tremaining: 9.14s\n150:\tlearn: 0.2748276\ttest: 0.2825841\tbest: 0.2825841 (150)\ttotal: 1.53s\tremaining: 8.59s\n200:\tlearn: 0.2660846\ttest: 0.2787806\tbest: 0.2787806 (200)\ttotal: 2.02s\tremaining: 8.04s\n250:\tlearn: 0.2594067\ttest: 0.2771832\tbest: 0.2771832 (250)\ttotal: 2.52s\tremaining: 7.52s\nStopped by overfitting detector (20 iterations wait)\n\nbestTest = 0.2770424728\nbestIteration = 257\n\nShrink model to first 258 iterations.\nCPU times: user 9.63 s, sys: 788 ms, total: 10.4 s\nWall time: 2.85 s\n"],["# Export the model to a file\nfname = 'catboost_census_model.onnx'\nmodel.save_model(fname, format='onnx')\n\n# Upload the model to GCS\nbucket = storage.Client().bucket(BUCKET_ID)\nblob = bucket.blob('{}/{}'.format(\n datetime.datetime.now().strftime('census/catboost_model_dir/catboost_census_%Y%m%d_%H%M%S'),\n fname))\nblob.upload_from_filename(fname)","_____no_output_____"],["!gsutil ls gs://$BUCKET_ID/census/*","gs://mchrestkha-demo-env-ml-examples/census/catboost_census_20200525_212707/:\ngs://mchrestkha-demo-env-ml-examples/census/catboost_census_20200525_212707/
","_____no_output_____"],["# Goals\n\n\n### In the previous tutorial you studied the role of freezing models on a small dataset. \n\n\n### Understand the role of freezing models in transfer learning on a fairly large dataset\n\n\n### Why freeze/unfreeze base models in transfer learning\n\n\n### Use comparison feature to appropriately set this parameter on custom dataset\n\n\n### You will be using lego bricks dataset to train the classifiers","_____no_output_____"],["# What is freezing base network\n\n\n - To recap you have two parts in your network\n - One that already existed, the pretrained one, the base network\n - The new sub-network or a single layer you added\n\n\n -The hyper-parameter we can see here: Freeze base network\n - Freezing base network makes the base network untrainable\n - The base network now acts as a feature extractor and only the next half is trained\n - If you do not freeze the base network the entire network is trained","_____no_output_____"],["# Table of Contents\n\n\n## [Install](#0)\n\n\n## [Freeze Base network in densenet121 and train a classifier](#1)\n\n\n## [Unfreeze base network in densenet121 and train another classifier](#2)\n\n\n## [Compare both the experiment](#3)","_____no_output_____"],["\n# Install Monk","_____no_output_____"],["## Using pip (Recommended)\n\n - colab (gpu) \n - All bakcends: `pip install -U monk-colab`\n \n\n - kaggle (gpu) \n - All backends: `pip install -U monk-kaggle`\n \n\n - cuda 10.2\t\n - All backends: `pip install -U monk-cuda102`\n - Gluon bakcned: `pip install -U monk-gluon-cuda102`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda102`\n - Keras backend: `pip install -U monk-keras-cuda102`\n \n\n - cuda 10.1\t\n - All backend: `pip install -U monk-cuda101`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda101`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda101`\n\t - Keras backend: `pip install -U monk-keras-cuda101`\n \n\n - cuda 10.0\t\n - All backend: `pip install -U monk-cuda100`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda100`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda100`\n\t - Keras backend: `pip install -U monk-keras-cuda100`\n \n\n - cuda 9.2\t\n - All backend: `pip install -U monk-cuda92`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda92`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda92`\n\t - Keras backend: `pip install -U monk-keras-cuda92`\n \n\n - cuda 9.0\t\n - All backend: `pip install -U monk-cuda90`\n\t - Gluon bakcned: `pip install -U monk-gluon-cuda90`\n\t - Pytorch backend: `pip install -U monk-pytorch-cuda90`\n\t - Keras backend: `pip install -U monk-keras-cuda90`\n \n\n - cpu \t\t\n - All backend: `pip install -U monk-cpu`\n\t - Gluon bakcned: `pip install -U monk-gluon-cpu`\n\t - Pytorch backend: `pip install -U monk-pytorch-cpu`\n\t - Keras backend: `pip install -U monk-keras-cpu`","_____no_output_____"],["## Install Monk Manually (Not recommended)\n \n### Step 1: Clone the library\n - git clone https://github.com/Tessellate-Imaging/monk_v1.git\n \n \n \n \n### Step 2: Install requirements \n - Linux\n - Cuda 9.0\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu90.txt`\n - Cuda 9.2\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu92.txt`\n - Cuda 10.0\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu100.txt`\n - Cuda 10.1\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu101.txt`\n - Cuda 10.2\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu102.txt`\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Linux && pip install -r requirements_cpu.txt`\n \n \n - Windows\n - Cuda 9.0 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu90.txt`\n - Cuda 9.2 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu92.txt`\n - Cuda 10.0 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu100.txt`\n - Cuda 10.1 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu101.txt`\n - Cuda 10.2 (Experimental support)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu102.txt`\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Windows && pip install -r requirements_cpu.txt`\n \n \n - Mac\n - CPU (Non gpu system)\n - `cd monk_v1/installation/Mac && pip install -r requirements_cpu.txt`\n \n \n - Misc\n - Colab (GPU)\n - `cd monk_v1/installation/Misc && pip install -r requirements_colab.txt`\n - Kaggle (GPU)\n - `cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt`\n \n \n \n### Step 3: Add to system path (Required for every terminal or kernel run)\n - `import sys`\n - `sys.path.append(\"monk_v1/\");`","_____no_output_____"],["## Dataset - LEGO Classification\n - https://www.kaggle.com/joosthazelzet/lego-brick-images/","_____no_output_____"]],[["! wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\\1\\n/p')&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ\" -O skin_cancer_mnist_dataset.zip && rm -rf /tmp/cookies.txt","_____no_output_____"],["! unzip -qq skin_cancer_mnist_dataset.zip","_____no_output_____"]],[["# Imports","_____no_output_____"]],[["#Using pytorch backend \n\n# When installed using pip\nfrom monk.pytorch_prototype import prototype\n\n\n# When installed manually (Uncomment the following)\n#import os\n#import sys\n#sys.path.append(\"monk_v1/\");\n#sys.path.append(\"monk_v1/monk/\");\n#from monk.pytorch_prototype import prototype","_____no_output_____"]],[["\n# Freeze Base network in densenet121 and train a classifier","_____no_output_____"],["## Creating and managing experiments\n - Provide project name\n - Provide experiment name\n - For a specific data create a single project\n - Inside each project multiple experiments can be created\n - Every experiment can be have diferent hyper-parameters attached to it","_____no_output_____"]],[["gtf = prototype(verbose=1);\ngtf.Prototype(\"Project\", \"Freeze_Base_Network\");","Pytorch Version: 1.2.0\n\nExperiment Details\n Project: Project\n Experiment: Freeze_Base_Network\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/5_transfer_learning_params/2_freezing_base_network/workspace/Project/Freeze_Base_Network/\n\n"]],[["### This creates files and directories as per the following structure\n \n \n workspace\n |\n |--------Project\n |\n |\n |-----Freeze_Base_Network\n |\n |-----experiment-state.json\n |\n |-----output\n |\n |------logs (All training logs and graphs saved here)\n |\n |------models (all trained models saved here)\n ","_____no_output_____"],["## Set dataset and select the model","_____no_output_____"],["## Quick mode training\n\n - Using Default Function\n - dataset_path\n - model_name\n - freeze_base_network\n - num_epochs\n \n \n## Sample Dataset folder structure\n\n parent_directory\n |\n |\n |------cats\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on)\n |------dogs\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on) ","_____no_output_____"],["## Modifyable params \n - dataset_path: path to data\n - model_name: which pretrained model to use\n - freeze_base_network: Retrain already trained network or not\n - num_epochs: Number of epochs to train for","_____no_output_____"]],[["gtf.Default(dataset_path=\"skin_cancer_mnist_dataset/images\",\n path_to_csv=\"skin_cancer_mnist_dataset/train_labels.csv\",\n model_name=\"densenet121\", \n \n \n \n \n freeze_base_network=True, # Set this param as true\n \n \n \n num_epochs=5);\n\n#Read the summary generated once you run this cell. ","Dataset Details\n Train path: skin_cancer_mnist_dataset/images\n Val path: None\n CSV train path: skin_cancer_mnist_dataset/train_labels.csv\n CSV val path: None\n\nDataset Params\n Input Size: 224\n Batch Size: 4\n Data Shuffle: True\n Processors: 4\n Train-val split: 0.7\n Delimiter: ,\n\nPre-Composed Train Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nPre-Composed Val Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nDataset Numbers\n Num train images: 7010\n Num val images: 3005\n Num classes: 7\n\nModel Params\n Model name: densenet121\n Use Gpu: True\n Use pretrained: True\n Freeze base network: True\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: densenet121\n Num layers in model: 242\n Num trainable layers: 1\n\nOptimizer\n Name: sgd\n Learning rate: 0.01\n Params: {'lr': 0.01, 'momentum': 0, 'weight_decay': 0.0001, 'momentum_dampening_rate': 0, 'clipnorm': 0.0, 'clipvalue': 0.0}\n\n\n\nLearning rate scheduler\n Name: multisteplr\n Params: {'milestones': [2, 3], 'gamma': 0.1, 'last_epoch': -1}\n\nLoss\n Name: softmaxcrossentropy\n Params: {'weight': None, 'batch_axis': 0, 'axis_to_sum_over': -1, 'label_as_categories': True, 'label_smoothing': False}\n\nTraining params\n Num Epochs: 5\n\nDisplay params\n Display progress: True\n Display progress realtime: True\n Save Training logs: True\n Save Intermediate models: True\n Intermediate model prefix: intermediate_model_\n\n"]],[["## From the summary above\n\n - Model Params\n Model name: densenet121\n Use Gpu: True\n Use pretrained: True\n \n \n Freeze base network: True","_____no_output_____"],["## Another thing to notice from summary\n\n Model Details\n Loading pretrained model\n Model Loaded on device\n Model name: densenet121\n Num of potentially trainable layers: 242\n Num of actual trainable layers: 1\n \n\n### There are a total of 242 layers\n\n### Since we have freezed base network only 1 is trainable, the final layer","_____no_output_____"],["## Train the classifier","_____no_output_____"]],[["#Start Training\ngtf.Train();\n\n#Read the training summary generated once you run the cell and training is completed","Training Start\n Epoch 1/5\n ----------\n"]],[["### Best validation Accuracy achieved - 74.77 %\n(You may get a different result)","_____no_output_____"],["\n# Unfreeze Base network in densenet121 and train a classifier","_____no_output_____"],["## Creating and managing experiments\n - Provide project name\n - Provide experiment name\n - For a specific data create a single project\n - Inside each project multiple experiments can be created\n - Every experiment can be have diferent hyper-parameters attached to it","_____no_output_____"]],[["gtf = prototype(verbose=1);\ngtf.Prototype(\"Project\", \"Unfreeze_Base_Network\");","Pytorch Version: 1.2.0\n\nExperiment Details\n Project: Project\n Experiment: Unfreeze_Base_Network\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/5_transfer_learning_params/2_freezing_base_network/workspace/Project/Unfreeze_Base_Network/\n\n"]],[["### This creates files and directories as per the following structure\n \n \n workspace\n |\n |--------Project\n |\n |\n |-----Freeze_Base_Network (Previously created)\n |\n |-----experiment-state.json\n |\n |-----output\n |\n |------logs (All training logs and graphs saved here)\n |\n |------models (all trained models saved here)\n |\n |\n |-----Unfreeze_Base_Network (Created Now)\n |\n |-----experiment-state.json\n |\n |-----output\n |\n |------logs (All training logs and graphs saved here)\n |\n |------models (all trained models saved here)","_____no_output_____"],["## Set dataset and select the model","_____no_output_____"],["## Quick mode training\n\n - Using Default Function\n - dataset_path\n - model_name\n - freeze_base_network\n - num_epochs\n \n \n## Sample Dataset folder structure\n\n parent_directory\n |\n |\n |------cats\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on)\n |------dogs\n |\n |------img1.jpg\n |------img2.jpg\n |------.... (and so on)","_____no_output_____"],["## Modifyable params \n - dataset_path: path to data\n - model_name: which pretrained model to use\n - freeze_base_network: Retrain already trained network or not\n - num_epochs: Number of epochs to train for","_____no_output_____"]],[["gtf.Default(dataset_path=\"skin_cancer_mnist_dataset/images\",\n path_to_csv=\"skin_cancer_mnist_dataset/train_labels.csv\",\n model_name=\"densenet121\",\n \n \n \n freeze_base_network=False, # Set this param as false\n \n \n \n num_epochs=5);\n\n#Read the summary generated once you run this cell. ","Dataset Details\n Train path: skin_cancer_mnist_dataset/images\n Val path: None\n CSV train path: skin_cancer_mnist_dataset/train_labels.csv\n CSV val path: None\n\nDataset Params\n Input Size: 224\n Batch Size: 4\n Data Shuffle: True\n Processors: 4\n Train-val split: 0.7\n Delimiter: ,\n\nPre-Composed Train Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nPre-Composed Val Transforms\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\n\nDataset Numbers\n Num train images: 7010\n Num val images: 3005\n Num classes: 7\n\nModel Params\n Model name: densenet121\n Use Gpu: True\n Use pretrained: True\n Freeze base network: False\n\nModel Details\n Loading pretrained model\n Model Loaded on device\n Model name: densenet121\n Num layers in model: 242\n Num trainable layers: 242\n\nOptimizer\n Name: sgd\n Learning rate: 0.01\n Params: {'lr': 0.01, 'momentum': 0, 'weight_decay': 0.0001, 'momentum_dampening_rate': 0, 'clipnorm': 0.0, 'clipvalue': 0.0}\n\n\n\nLearning rate scheduler\n Name: multisteplr\n Params: {'milestones': [2, 3], 'gamma': 0.1, 'last_epoch': -1}\n\nLoss\n Name: softmaxcrossentropy\n Params: {'weight': None, 'batch_axis': 0, 'axis_to_sum_over': -1, 'label_as_categories': True, 'label_smoothing': False}\n\nTraining params\n Num Epochs: 5\n\nDisplay params\n Display progress: True\n Display progress realtime: True\n Save Training logs: True\n Save Intermediate models: True\n Intermediate model prefix: intermediate_model_\n\n"]],[["## From the summary above\n\n - Model Params\n Model name: densenet121\n Use Gpu: True\n Use pretrained: True\n \n \n Freeze base network: False","_____no_output_____"],["## Another thing to notice from summary\n\n Model Details\n Loading pretrained model\n Model Loaded on device\n Model name: densenet121\n Num of potentially trainable layers: 242\n Num of actual trainable layers: 242\n \n\n### There are a total of 242 layers\n\n### Since we have unfreezed base network all 242 layers are trainable including the final layer","_____no_output_____"],["## Train the classifier","_____no_output_____"]],[["#Start Training\ngtf.Train();\n\n#Read the training summary generated once you run the cell and training is completed","Training Start\n Epoch 1/5\n ----------\n"]],[["### Best Val Accuracy achieved - 81.33 %\n(You may get a different result)","_____no_output_____"],["\n# Compare both the experiment","_____no_output_____"]],[["# Invoke the comparison class\nfrom monk.compare_prototype import compare","_____no_output_____"]],[["### Creating and managing comparison experiments\n - Provide project name","_____no_output_____"]],[["# Create a project \ngtf = compare(verbose=1);\ngtf.Comparison(\"Compare-effect-of-freezing\");","Comparison: - Compare-effect-of-freezing\n"]],[["### This creates files and directories as per the following structure\n \n workspace\n |\n |--------comparison\n |\n |\n |-----Compare-effect-of-freezing\n |\n |------stats_best_val_acc.png\n |------stats_max_gpu_usage.png\n |------stats_training_time.png\n |------train_accuracy.png\n |------train_loss.png\n |------val_accuracy.png\n |------val_loss.png\n \n |\n |-----comparison.csv (Contains necessary details of all experiments)","_____no_output_____"],["### Add the experiments\n - First argument - Project name\n - Second argument - Experiment name","_____no_output_____"]],[["gtf.Add_Experiment(\"Project\", \"Freeze_Base_Network\");\ngtf.Add_Experiment(\"Project\", \"Unfreeze_Base_Network\");","Project - Project, Experiment - Freeze_Base_Network added\nProject - Project, Experiment - Unfreeze_Base_Network added\n"]],[["### Run Analysis","_____no_output_____"]],[["gtf.Generate_Statistics();","Generating statistics...\nGenerated\n\n"]],[["## Visualize and study comparison metrics","_____no_output_____"],["### Training Accuracy Curves","_____no_output_____"]],[["from IPython.display import Image\nImage(filename=\"workspace/comparison/Compare-effect-of-freezing/train_accuracy.png\") ","_____no_output_____"]],[["### Training Loss Curves","_____no_output_____"]],[["from IPython.display import Image\nImage(filename=\"workspace/comparison/Compare-effect-of-freezing/train_loss.png\") ","_____no_output_____"]],[["### Validation Accuracy Curves","_____no_output_____"]],[["from IPython.display import Image\nImage(filename=\"workspace/comparison/Compare-effect-of-freezing/val_accuracy.png\") ","_____no_output_____"]],[["### Validation loss curves","_____no_output_____"]],[["from IPython.display import Image\nImage(filename=\"workspace/comparison/Compare-effect-of-freezing/val_loss.png\") ","_____no_output_____"]],[["## Accuracies achieved on validation dataset\n\n### With freezing base network - 74.77 %\n### Without freezing base network - 81.33 %\n\n#### For this classifier, keeping the base network trainable seems to be a good option. Thus for other data it may result in overfitting the training data\n\n(You may get a different result)","_____no_output_____"]]],"string":"[\n [\n [\n \"
\",\n \"_____no_output_____\"\n ],\n [\n \"# Goals\\n\\n\\n### In the previous tutorial you studied the role of freezing models on a small dataset. \\n\\n\\n### Understand the role of freezing models in transfer learning on a fairly large dataset\\n\\n\\n### Why freeze/unfreeze base models in transfer learning\\n\\n\\n### Use comparison feature to appropriately set this parameter on custom dataset\\n\\n\\n### You will be using lego bricks dataset to train the classifiers\",\n \"_____no_output_____\"\n ],\n [\n \"# What is freezing base network\\n\\n\\n - To recap you have two parts in your network\\n - One that already existed, the pretrained one, the base network\\n - The new sub-network or a single layer you added\\n\\n\\n -The hyper-parameter we can see here: Freeze base network\\n - Freezing base network makes the base network untrainable\\n - The base network now acts as a feature extractor and only the next half is trained\\n - If you do not freeze the base network the entire network is trained\",\n \"_____no_output_____\"\n ],\n [\n \"# Table of Contents\\n\\n\\n## [Install](#0)\\n\\n\\n## [Freeze Base network in densenet121 and train a classifier](#1)\\n\\n\\n## [Unfreeze base network in densenet121 and train another classifier](#2)\\n\\n\\n## [Compare both the experiment](#3)\",\n \"_____no_output_____\"\n ],\n [\n \"\\n# Install Monk\",\n \"_____no_output_____\"\n ],\n [\n \"## Using pip (Recommended)\\n\\n - colab (gpu) \\n - All bakcends: `pip install -U monk-colab`\\n \\n\\n - kaggle (gpu) \\n - All backends: `pip install -U monk-kaggle`\\n \\n\\n - cuda 10.2\\t\\n - All backends: `pip install -U monk-cuda102`\\n - Gluon bakcned: `pip install -U monk-gluon-cuda102`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cuda102`\\n - Keras backend: `pip install -U monk-keras-cuda102`\\n \\n\\n - cuda 10.1\\t\\n - All backend: `pip install -U monk-cuda101`\\n\\t - Gluon bakcned: `pip install -U monk-gluon-cuda101`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cuda101`\\n\\t - Keras backend: `pip install -U monk-keras-cuda101`\\n \\n\\n - cuda 10.0\\t\\n - All backend: `pip install -U monk-cuda100`\\n\\t - Gluon bakcned: `pip install -U monk-gluon-cuda100`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cuda100`\\n\\t - Keras backend: `pip install -U monk-keras-cuda100`\\n \\n\\n - cuda 9.2\\t\\n - All backend: `pip install -U monk-cuda92`\\n\\t - Gluon bakcned: `pip install -U monk-gluon-cuda92`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cuda92`\\n\\t - Keras backend: `pip install -U monk-keras-cuda92`\\n \\n\\n - cuda 9.0\\t\\n - All backend: `pip install -U monk-cuda90`\\n\\t - Gluon bakcned: `pip install -U monk-gluon-cuda90`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cuda90`\\n\\t - Keras backend: `pip install -U monk-keras-cuda90`\\n \\n\\n - cpu \\t\\t\\n - All backend: `pip install -U monk-cpu`\\n\\t - Gluon bakcned: `pip install -U monk-gluon-cpu`\\n\\t - Pytorch backend: `pip install -U monk-pytorch-cpu`\\n\\t - Keras backend: `pip install -U monk-keras-cpu`\",\n \"_____no_output_____\"\n ],\n [\n \"## Install Monk Manually (Not recommended)\\n \\n### Step 1: Clone the library\\n - git clone https://github.com/Tessellate-Imaging/monk_v1.git\\n \\n \\n \\n \\n### Step 2: Install requirements \\n - Linux\\n - Cuda 9.0\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu90.txt`\\n - Cuda 9.2\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu92.txt`\\n - Cuda 10.0\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu100.txt`\\n - Cuda 10.1\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu101.txt`\\n - Cuda 10.2\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cu102.txt`\\n - CPU (Non gpu system)\\n - `cd monk_v1/installation/Linux && pip install -r requirements_cpu.txt`\\n \\n \\n - Windows\\n - Cuda 9.0 (Experimental support)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu90.txt`\\n - Cuda 9.2 (Experimental support)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu92.txt`\\n - Cuda 10.0 (Experimental support)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu100.txt`\\n - Cuda 10.1 (Experimental support)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu101.txt`\\n - Cuda 10.2 (Experimental support)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cu102.txt`\\n - CPU (Non gpu system)\\n - `cd monk_v1/installation/Windows && pip install -r requirements_cpu.txt`\\n \\n \\n - Mac\\n - CPU (Non gpu system)\\n - `cd monk_v1/installation/Mac && pip install -r requirements_cpu.txt`\\n \\n \\n - Misc\\n - Colab (GPU)\\n - `cd monk_v1/installation/Misc && pip install -r requirements_colab.txt`\\n - Kaggle (GPU)\\n - `cd monk_v1/installation/Misc && pip install -r requirements_kaggle.txt`\\n \\n \\n \\n### Step 3: Add to system path (Required for every terminal or kernel run)\\n - `import sys`\\n - `sys.path.append(\\\"monk_v1/\\\");`\",\n \"_____no_output_____\"\n ],\n [\n \"## Dataset - LEGO Classification\\n - https://www.kaggle.com/joosthazelzet/lego-brick-images/\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"! wget --load-cookies /tmp/cookies.txt \\\"https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\\\\1\\\\n/p')&id=1MRC58-oCdR1agFTWreDFqevjEOIWDnYZ\\\" -O skin_cancer_mnist_dataset.zip && rm -rf /tmp/cookies.txt\",\n \"_____no_output_____\"\n ],\n [\n \"! unzip -qq skin_cancer_mnist_dataset.zip\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# Imports\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#Using pytorch backend \\n\\n# When installed using pip\\nfrom monk.pytorch_prototype import prototype\\n\\n\\n# When installed manually (Uncomment the following)\\n#import os\\n#import sys\\n#sys.path.append(\\\"monk_v1/\\\");\\n#sys.path.append(\\\"monk_v1/monk/\\\");\\n#from monk.pytorch_prototype import prototype\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"\\n# Freeze Base network in densenet121 and train a classifier\",\n \"_____no_output_____\"\n ],\n [\n \"## Creating and managing experiments\\n - Provide project name\\n - Provide experiment name\\n - For a specific data create a single project\\n - Inside each project multiple experiments can be created\\n - Every experiment can be have diferent hyper-parameters attached to it\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf = prototype(verbose=1);\\ngtf.Prototype(\\\"Project\\\", \\\"Freeze_Base_Network\\\");\",\n \"Pytorch Version: 1.2.0\\n\\nExperiment Details\\n Project: Project\\n Experiment: Freeze_Base_Network\\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/5_transfer_learning_params/2_freezing_base_network/workspace/Project/Freeze_Base_Network/\\n\\n\"\n ]\n ],\n [\n [\n \"### This creates files and directories as per the following structure\\n \\n \\n workspace\\n |\\n |--------Project\\n |\\n |\\n |-----Freeze_Base_Network\\n |\\n |-----experiment-state.json\\n |\\n |-----output\\n |\\n |------logs (All training logs and graphs saved here)\\n |\\n |------models (all trained models saved here)\\n \",\n \"_____no_output_____\"\n ],\n [\n \"## Set dataset and select the model\",\n \"_____no_output_____\"\n ],\n [\n \"## Quick mode training\\n\\n - Using Default Function\\n - dataset_path\\n - model_name\\n - freeze_base_network\\n - num_epochs\\n \\n \\n## Sample Dataset folder structure\\n\\n parent_directory\\n |\\n |\\n |------cats\\n |\\n |------img1.jpg\\n |------img2.jpg\\n |------.... (and so on)\\n |------dogs\\n |\\n |------img1.jpg\\n |------img2.jpg\\n |------.... (and so on) \",\n \"_____no_output_____\"\n ],\n [\n \"## Modifyable params \\n - dataset_path: path to data\\n - model_name: which pretrained model to use\\n - freeze_base_network: Retrain already trained network or not\\n - num_epochs: Number of epochs to train for\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf.Default(dataset_path=\\\"skin_cancer_mnist_dataset/images\\\",\\n path_to_csv=\\\"skin_cancer_mnist_dataset/train_labels.csv\\\",\\n model_name=\\\"densenet121\\\", \\n \\n \\n \\n \\n freeze_base_network=True, # Set this param as true\\n \\n \\n \\n num_epochs=5);\\n\\n#Read the summary generated once you run this cell. \",\n \"Dataset Details\\n Train path: skin_cancer_mnist_dataset/images\\n Val path: None\\n CSV train path: skin_cancer_mnist_dataset/train_labels.csv\\n CSV val path: None\\n\\nDataset Params\\n Input Size: 224\\n Batch Size: 4\\n Data Shuffle: True\\n Processors: 4\\n Train-val split: 0.7\\n Delimiter: ,\\n\\nPre-Composed Train Transforms\\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\\n\\nPre-Composed Val Transforms\\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\\n\\nDataset Numbers\\n Num train images: 7010\\n Num val images: 3005\\n Num classes: 7\\n\\nModel Params\\n Model name: densenet121\\n Use Gpu: True\\n Use pretrained: True\\n Freeze base network: True\\n\\nModel Details\\n Loading pretrained model\\n Model Loaded on device\\n Model name: densenet121\\n Num layers in model: 242\\n Num trainable layers: 1\\n\\nOptimizer\\n Name: sgd\\n Learning rate: 0.01\\n Params: {'lr': 0.01, 'momentum': 0, 'weight_decay': 0.0001, 'momentum_dampening_rate': 0, 'clipnorm': 0.0, 'clipvalue': 0.0}\\n\\n\\n\\nLearning rate scheduler\\n Name: multisteplr\\n Params: {'milestones': [2, 3], 'gamma': 0.1, 'last_epoch': -1}\\n\\nLoss\\n Name: softmaxcrossentropy\\n Params: {'weight': None, 'batch_axis': 0, 'axis_to_sum_over': -1, 'label_as_categories': True, 'label_smoothing': False}\\n\\nTraining params\\n Num Epochs: 5\\n\\nDisplay params\\n Display progress: True\\n Display progress realtime: True\\n Save Training logs: True\\n Save Intermediate models: True\\n Intermediate model prefix: intermediate_model_\\n\\n\"\n ]\n ],\n [\n [\n \"## From the summary above\\n\\n - Model Params\\n Model name: densenet121\\n Use Gpu: True\\n Use pretrained: True\\n \\n \\n Freeze base network: True\",\n \"_____no_output_____\"\n ],\n [\n \"## Another thing to notice from summary\\n\\n Model Details\\n Loading pretrained model\\n Model Loaded on device\\n Model name: densenet121\\n Num of potentially trainable layers: 242\\n Num of actual trainable layers: 1\\n \\n\\n### There are a total of 242 layers\\n\\n### Since we have freezed base network only 1 is trainable, the final layer\",\n \"_____no_output_____\"\n ],\n [\n \"## Train the classifier\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#Start Training\\ngtf.Train();\\n\\n#Read the training summary generated once you run the cell and training is completed\",\n \"Training Start\\n Epoch 1/5\\n ----------\\n\"\n ]\n ],\n [\n [\n \"### Best validation Accuracy achieved - 74.77 %\\n(You may get a different result)\",\n \"_____no_output_____\"\n ],\n [\n \"\\n# Unfreeze Base network in densenet121 and train a classifier\",\n \"_____no_output_____\"\n ],\n [\n \"## Creating and managing experiments\\n - Provide project name\\n - Provide experiment name\\n - For a specific data create a single project\\n - Inside each project multiple experiments can be created\\n - Every experiment can be have diferent hyper-parameters attached to it\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf = prototype(verbose=1);\\ngtf.Prototype(\\\"Project\\\", \\\"Unfreeze_Base_Network\\\");\",\n \"Pytorch Version: 1.2.0\\n\\nExperiment Details\\n Project: Project\\n Experiment: Unfreeze_Base_Network\\n Dir: /home/abhi/Desktop/Work/tess_tool/gui/v0.3/finetune_models/Organization/development/v5.0_blocks/study_roadmap/change_post_num_layers/5_transfer_learning_params/2_freezing_base_network/workspace/Project/Unfreeze_Base_Network/\\n\\n\"\n ]\n ],\n [\n [\n \"### This creates files and directories as per the following structure\\n \\n \\n workspace\\n |\\n |--------Project\\n |\\n |\\n |-----Freeze_Base_Network (Previously created)\\n |\\n |-----experiment-state.json\\n |\\n |-----output\\n |\\n |------logs (All training logs and graphs saved here)\\n |\\n |------models (all trained models saved here)\\n |\\n |\\n |-----Unfreeze_Base_Network (Created Now)\\n |\\n |-----experiment-state.json\\n |\\n |-----output\\n |\\n |------logs (All training logs and graphs saved here)\\n |\\n |------models (all trained models saved here)\",\n \"_____no_output_____\"\n ],\n [\n \"## Set dataset and select the model\",\n \"_____no_output_____\"\n ],\n [\n \"## Quick mode training\\n\\n - Using Default Function\\n - dataset_path\\n - model_name\\n - freeze_base_network\\n - num_epochs\\n \\n \\n## Sample Dataset folder structure\\n\\n parent_directory\\n |\\n |\\n |------cats\\n |\\n |------img1.jpg\\n |------img2.jpg\\n |------.... (and so on)\\n |------dogs\\n |\\n |------img1.jpg\\n |------img2.jpg\\n |------.... (and so on)\",\n \"_____no_output_____\"\n ],\n [\n \"## Modifyable params \\n - dataset_path: path to data\\n - model_name: which pretrained model to use\\n - freeze_base_network: Retrain already trained network or not\\n - num_epochs: Number of epochs to train for\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf.Default(dataset_path=\\\"skin_cancer_mnist_dataset/images\\\",\\n path_to_csv=\\\"skin_cancer_mnist_dataset/train_labels.csv\\\",\\n model_name=\\\"densenet121\\\",\\n \\n \\n \\n freeze_base_network=False, # Set this param as false\\n \\n \\n \\n num_epochs=5);\\n\\n#Read the summary generated once you run this cell. \",\n \"Dataset Details\\n Train path: skin_cancer_mnist_dataset/images\\n Val path: None\\n CSV train path: skin_cancer_mnist_dataset/train_labels.csv\\n CSV val path: None\\n\\nDataset Params\\n Input Size: 224\\n Batch Size: 4\\n Data Shuffle: True\\n Processors: 4\\n Train-val split: 0.7\\n Delimiter: ,\\n\\nPre-Composed Train Transforms\\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\\n\\nPre-Composed Val Transforms\\n[{'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]\\n\\nDataset Numbers\\n Num train images: 7010\\n Num val images: 3005\\n Num classes: 7\\n\\nModel Params\\n Model name: densenet121\\n Use Gpu: True\\n Use pretrained: True\\n Freeze base network: False\\n\\nModel Details\\n Loading pretrained model\\n Model Loaded on device\\n Model name: densenet121\\n Num layers in model: 242\\n Num trainable layers: 242\\n\\nOptimizer\\n Name: sgd\\n Learning rate: 0.01\\n Params: {'lr': 0.01, 'momentum': 0, 'weight_decay': 0.0001, 'momentum_dampening_rate': 0, 'clipnorm': 0.0, 'clipvalue': 0.0}\\n\\n\\n\\nLearning rate scheduler\\n Name: multisteplr\\n Params: {'milestones': [2, 3], 'gamma': 0.1, 'last_epoch': -1}\\n\\nLoss\\n Name: softmaxcrossentropy\\n Params: {'weight': None, 'batch_axis': 0, 'axis_to_sum_over': -1, 'label_as_categories': True, 'label_smoothing': False}\\n\\nTraining params\\n Num Epochs: 5\\n\\nDisplay params\\n Display progress: True\\n Display progress realtime: True\\n Save Training logs: True\\n Save Intermediate models: True\\n Intermediate model prefix: intermediate_model_\\n\\n\"\n ]\n ],\n [\n [\n \"## From the summary above\\n\\n - Model Params\\n Model name: densenet121\\n Use Gpu: True\\n Use pretrained: True\\n \\n \\n Freeze base network: False\",\n \"_____no_output_____\"\n ],\n [\n \"## Another thing to notice from summary\\n\\n Model Details\\n Loading pretrained model\\n Model Loaded on device\\n Model name: densenet121\\n Num of potentially trainable layers: 242\\n Num of actual trainable layers: 242\\n \\n\\n### There are a total of 242 layers\\n\\n### Since we have unfreezed base network all 242 layers are trainable including the final layer\",\n \"_____no_output_____\"\n ],\n [\n \"## Train the classifier\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#Start Training\\ngtf.Train();\\n\\n#Read the training summary generated once you run the cell and training is completed\",\n \"Training Start\\n Epoch 1/5\\n ----------\\n\"\n ]\n ],\n [\n [\n \"### Best Val Accuracy achieved - 81.33 %\\n(You may get a different result)\",\n \"_____no_output_____\"\n ],\n [\n \"\\n# Compare both the experiment\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# Invoke the comparison class\\nfrom monk.compare_prototype import compare\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Creating and managing comparison experiments\\n - Provide project name\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# Create a project \\ngtf = compare(verbose=1);\\ngtf.Comparison(\\\"Compare-effect-of-freezing\\\");\",\n \"Comparison: - Compare-effect-of-freezing\\n\"\n ]\n ],\n [\n [\n \"### This creates files and directories as per the following structure\\n \\n workspace\\n |\\n |--------comparison\\n |\\n |\\n |-----Compare-effect-of-freezing\\n |\\n |------stats_best_val_acc.png\\n |------stats_max_gpu_usage.png\\n |------stats_training_time.png\\n |------train_accuracy.png\\n |------train_loss.png\\n |------val_accuracy.png\\n |------val_loss.png\\n \\n |\\n |-----comparison.csv (Contains necessary details of all experiments)\",\n \"_____no_output_____\"\n ],\n [\n \"### Add the experiments\\n - First argument - Project name\\n - Second argument - Experiment name\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf.Add_Experiment(\\\"Project\\\", \\\"Freeze_Base_Network\\\");\\ngtf.Add_Experiment(\\\"Project\\\", \\\"Unfreeze_Base_Network\\\");\",\n \"Project - Project, Experiment - Freeze_Base_Network added\\nProject - Project, Experiment - Unfreeze_Base_Network added\\n\"\n ]\n ],\n [\n [\n \"### Run Analysis\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"gtf.Generate_Statistics();\",\n \"Generating statistics...\\nGenerated\\n\\n\"\n ]\n ],\n [\n [\n \"## Visualize and study comparison metrics\",\n \"_____no_output_____\"\n ],\n [\n \"### Training Accuracy Curves\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"from IPython.display import Image\\nImage(filename=\\\"workspace/comparison/Compare-effect-of-freezing/train_accuracy.png\\\") \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Training Loss Curves\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"from IPython.display import Image\\nImage(filename=\\\"workspace/comparison/Compare-effect-of-freezing/train_loss.png\\\") \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Validation Accuracy Curves\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"from IPython.display import Image\\nImage(filename=\\\"workspace/comparison/Compare-effect-of-freezing/val_accuracy.png\\\") \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Validation loss curves\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"from IPython.display import Image\\nImage(filename=\\\"workspace/comparison/Compare-effect-of-freezing/val_loss.png\\\") \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## Accuracies achieved on validation dataset\\n\\n### With freezing base network - 74.77 %\\n### Without freezing base network - 81.33 %\\n\\n#### For this classifier, keeping the base network trainable seems to be a good option. Thus for other data it may result in overfitting the training data\\n\\n(You may get a different result)\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown","markdown","markdown","markdown","markdown","markdown","markdown","markdown"],["code","code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown","markdown","markdown","markdown"],["code"],["markdown","markdown","markdown"],["code"],["markdown","markdown","markdown"],["code"],["markdown","markdown","markdown","markdown"],["code"],["markdown","markdown","markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"]],"string":"[\n [\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ]\n]"}}},{"rowIdx":575,"cells":{"hexsha":{"kind":"string","value":"d01a350a5e178563189a383bb1f02b8fc40b66d9"},"size":{"kind":"number","value":4433,"string":"4,433"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"ipynb/Caesar Cipher.ipynb"},"max_stars_repo_name":{"kind":"string","value":"davzoku/pyground"},"max_stars_repo_head_hexsha":{"kind":"string","value":"983f3670915346a1a8c27fb563ac91bdb5b45cf9"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"null"},"max_stars_repo_stars_event_min_datetime":{"kind":"null"},"max_stars_repo_stars_event_max_datetime":{"kind":"null"},"max_issues_repo_path":{"kind":"string","value":"ipynb/Caesar Cipher.ipynb"},"max_issues_repo_name":{"kind":"string","value":"davzoku/pyground"},"max_issues_repo_head_hexsha":{"kind":"string","value":"983f3670915346a1a8c27fb563ac91bdb5b45cf9"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"ipynb/Caesar Cipher.ipynb"},"max_forks_repo_name":{"kind":"string","value":"davzoku/pyground"},"max_forks_repo_head_hexsha":{"kind":"string","value":"983f3670915346a1a8c27fb563ac91bdb5b45cf9"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":25.0451977401,"string":"25.045198"},"max_line_length":{"kind":"number","value":249,"string":"249"},"alphanum_fraction":{"kind":"number","value":0.5023685991,"string":"0.502369"},"cells":{"kind":"list like","value":[[["## Caesar Cipher\n\nA Caesar cipher, also known as shift cipher is one of the simplest and most widely known encryption techniques. \nIt is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. \n\n\n","_____no_output_____"],["Insert message to encrypt and shift (0<= S <=26) below.\n\nBy default, Caesar Cipher does a left shift of 3","_____no_output_____"]],[["msg = \"The quick brown fox jumps over the lazy dog 123 !@#\"\nshift = 3\n","_____no_output_____"],["def getmsg():\n processedmsg = ''\n for x in msg:\n if x.isalpha():\n num = ord(x)\n num += shift\n \n if x.isupper():\n if num > ord('Z'):\n num -= 26\n elif num < ord('A'):\n num += 26\n elif x.islower():\n if num > ord('z'):\n num -= 26\n elif num < ord('a'):\n num += 26\n \n processedmsg += chr(num)\n else:\n processedmsg += x\n return processedmsg","_____no_output_____"]],[["The for loop above inspects each letter in the message.\n\nchr(), character function takes an integer ordinal and returns a character. ie. chr(65) outputs 'A' based on the ASCII table\n\nord(), ordinal does the reverse. ie ord('A') gives 65.\n\nBased on the ASCII Table, 'Z' with a shift of 3 will give us ']', which is undesirable.\n\nThus, we need the if-else statements to perform a \"wraparound\". If num has a value large than the ordinal value of 'Z', subtract 26.\n\nIf num is less than 'a', add 26.\n\n**\"else:\n processedmsg += x'**\n \n concatenates any spaces, numbers etc that are not encrypted or decrypted.","_____no_output_____"]],[["encrypted=getmsg()\nprint(encrypted)\n","Wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj 123 !@#\n"]],[["Note that only alphabets are encrypted.\n\nTo decrypt, the algorithm is very similar.","_____no_output_____"]],[["shift=-shift\nmsg=encrypted\n\ndecrypted= getmsg()\nprint(decrypted)","The quick brown fox jumps over the lazy dog 123 !@#\n"]],[["By reversing the polarity of the shift key we can get back the plain text.\n\n## References\n[Invent with Python](http://inventwithpython.com/hacking/)\n\n\n","_____no_output_____"]]],"string":"[\n [\n [\n \"## Caesar Cipher\\n\\nA Caesar cipher, also known as shift cipher is one of the simplest and most widely known encryption techniques. \\nIt is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. \\n\\n\\n\",\n \"_____no_output_____\"\n ],\n [\n \"Insert message to encrypt and shift (0<= S <=26) below.\\n\\nBy default, Caesar Cipher does a left shift of 3\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"msg = \\\"The quick brown fox jumps over the lazy dog 123 !@#\\\"\\nshift = 3\\n\",\n \"_____no_output_____\"\n ],\n [\n \"def getmsg():\\n processedmsg = ''\\n for x in msg:\\n if x.isalpha():\\n num = ord(x)\\n num += shift\\n \\n if x.isupper():\\n if num > ord('Z'):\\n num -= 26\\n elif num < ord('A'):\\n num += 26\\n elif x.islower():\\n if num > ord('z'):\\n num -= 26\\n elif num < ord('a'):\\n num += 26\\n \\n processedmsg += chr(num)\\n else:\\n processedmsg += x\\n return processedmsg\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"The for loop above inspects each letter in the message.\\n\\nchr(), character function takes an integer ordinal and returns a character. ie. chr(65) outputs 'A' based on the ASCII table\\n\\nord(), ordinal does the reverse. ie ord('A') gives 65.\\n\\nBased on the ASCII Table, 'Z' with a shift of 3 will give us ']', which is undesirable.\\n\\nThus, we need the if-else statements to perform a \\\"wraparound\\\". If num has a value large than the ordinal value of 'Z', subtract 26.\\n\\nIf num is less than 'a', add 26.\\n\\n**\\\"else:\\n processedmsg += x'**\\n \\n concatenates any spaces, numbers etc that are not encrypted or decrypted.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"encrypted=getmsg()\\nprint(encrypted)\\n\",\n \"Wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj 123 !@#\\n\"\n ]\n ],\n [\n [\n \"Note that only alphabets are encrypted.\\n\\nTo decrypt, the algorithm is very similar.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"shift=-shift\\nmsg=encrypted\\n\\ndecrypted= getmsg()\\nprint(decrypted)\",\n \"The quick brown fox jumps over the lazy dog 123 !@#\\n\"\n ]\n ],\n [\n [\n \"By reversing the polarity of the shift key we can get back the plain text.\\n\\n## References\\n[Invent with Python](http://inventwithpython.com/hacking/)\\n\\n\\n\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown","markdown"],["code","code"],["markdown"],["code"],["markdown"],["code"],["markdown"]],"string":"[\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ]\n]"}}},{"rowIdx":576,"cells":{"hexsha":{"kind":"string","value":"d01a396c0be70303e8b36ed8df972d695a0f2c77"},"size":{"kind":"number","value":277854,"string":"277,854"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"code/first_step_with_tensorflow.ipynb"},"max_stars_repo_name":{"kind":"string","value":"kevinleeex/notes-for-mlcc"},"max_stars_repo_head_hexsha":{"kind":"string","value":"05ff5f502a0aaccc171b8edf5bc463ed848326b0"},"max_stars_repo_licenses":{"kind":"list like","value":["CC-BY-3.0","Apache-2.0"],"string":"[\n \"CC-BY-3.0\",\n \"Apache-2.0\"\n]"},"max_stars_count":{"kind":"number","value":3,"string":"3"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2018-11-26T03:17:05.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2021-12-07T16:08:33.000Z"},"max_issues_repo_path":{"kind":"string","value":"code/first_step_with_tensorflow.ipynb"},"max_issues_repo_name":{"kind":"string","value":"kevinleeex/notes-for-mlcc"},"max_issues_repo_head_hexsha":{"kind":"string","value":"05ff5f502a0aaccc171b8edf5bc463ed848326b0"},"max_issues_repo_licenses":{"kind":"list like","value":["CC-BY-3.0","Apache-2.0"],"string":"[\n \"CC-BY-3.0\",\n \"Apache-2.0\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"code/first_step_with_tensorflow.ipynb"},"max_forks_repo_name":{"kind":"string","value":"kevinleeex/notes-for-mlcc"},"max_forks_repo_head_hexsha":{"kind":"string","value":"05ff5f502a0aaccc171b8edf5bc463ed848326b0"},"max_forks_repo_licenses":{"kind":"list like","value":["CC-BY-3.0","Apache-2.0"],"string":"[\n \"CC-BY-3.0\",\n \"Apache-2.0\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":252.3651226158,"string":"252.365123"},"max_line_length":{"kind":"number","value":113556,"string":"113,556"},"alphanum_fraction":{"kind":"number","value":0.9028158673,"string":"0.902816"},"cells":{"kind":"list like","value":[[["## 使用TensorFlow的基本步骤\n以使用LinearRegression来预测房价为例。\n- 使用RMSE(均方根误差)评估模型预测的准确率\n- 通过调整超参数来提高模型的预测准确率","_____no_output_____"]],[["from __future__ import print_function\n\nimport math\n\nfrom IPython import display\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.python.data import Dataset\n\ntf.logging.set_verbosity(tf.logging.ERROR)\npd.options.display.max_rows = 10\npd.options.display.float_format = '{:.1f}'.format","/Users/kevin/.virtualenvs/py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6\n return f(*args, **kwds)\n"],["# 加载数据集\ncalifornia_housing_df = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\", sep=\",\")","_____no_output_____"],["# 将数据打乱\ncalifornia_housing_df = california_housing_df.reindex(np.random.permutation(california_housing_df.index))\n# 替换房价的单位为k\ncalifornia_housing_df['median_house_value'] /=1000.0\nprint(\"california house dataframe: \\n\", california_housing_df) # 根据pd设置,只显示10条数据,以及保留小数点后一位","california house dataframe: \n longitude latitude housing_median_age total_rooms total_bedrooms \\\n840 -117.1 32.7 29.0 1429.0 293.0 \n15761 -122.4 37.8 52.0 3260.0 1535.0 \n2964 -117.8 34.1 23.0 7079.0 1381.0 \n5005 -118.1 33.8 36.0 1074.0 188.0 \n9816 -119.7 36.5 29.0 1702.0 301.0 \n... ... ... ... ... ... \n1864 -117.3 34.7 28.0 1932.0 421.0 \n6257 -118.2 34.1 11.0 1281.0 418.0 \n4690 -118.1 34.1 52.0 1282.0 189.0 \n6409 -118.3 33.9 44.0 1103.0 265.0 \n11082 -121.0 38.7 5.0 5743.0 1074.0 \n\n population households median_income median_house_value \n840 1091.0 317.0 3.5 118.0 \n15761 3260.0 1457.0 0.9 500.0 \n2964 3205.0 1327.0 3.1 212.3 \n5005 496.0 196.0 4.6 217.4 \n9816 914.0 280.0 2.8 79.2 \n... ... ... ... ... \n1864 1156.0 404.0 1.9 55.6 \n6257 1584.0 330.0 2.9 153.1 \n4690 431.0 187.0 6.1 470.8 \n6409 760.0 247.0 1.7 99.6 \n11082 2651.0 962.0 4.1 172.5 \n\n[17000 rows x 9 columns]\n"]],[["### 检查数据","_____no_output_____"]],[["# 使用pd的describe方法来统计一些信息\ncalifornia_housing_df.describe()","_____no_output_____"]],[["### 构建模型\n我们将在这个例子中预测中位房价,将其作为学习的标签,使用房间总数作为输入特征。","_____no_output_____"],["#### 第1步:定义特征并配置特征列\n为了把数据导入TensorFlow,我们需要指定每个特征包含的数据类型。我们主要使用以下两种类型:\n- 分类数据: 一种文字数据。\n- 数值数据:一种数字(整数或浮点数)数据或希望视为数字的数据。\n\n在TF中我们使用**特征列**的结构来表示特征的数据类型。特征列仅存储对特征数据的描述,不包含特征数据本身。","_____no_output_____"]],[["# 定义输入特征\nkl_feature = california_housing_df[['total_rooms']]\n\n# 配置房间总数为数值特征列\nfeature_columns = [tf.feature_column.numeric_column('total_rooms')]","[_NumericColumn(key='total_rooms', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)]\n"]],[["#### 第2步: 定义目标","_____no_output_____"]],[["# 定义目标标签\ntargets = california_housing_df['median_house_value']","_____no_output_____"]],[["**梯度裁剪**是在应用梯度值之前设置其上限,梯度裁剪有助于确保数值稳定性,防止梯度爆炸。","_____no_output_____"],["#### 第3步:配置线性回归器","_____no_output_____"]],[["# 使用Linear Regressor配置线性回归模型,使用GradientDescentOptimizer优化器训练模型\nkl_optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001)\n# 使用clip_gradients_by_norm梯度裁剪我们的优化器,梯度裁剪可以确保我们的梯度大小在训练期间不会变得过大,梯度过大会导致梯度下降失败。\nkl_optimizer = tf.contrib.estimator.clip_gradients_by_norm(kl_optimizer, 5.0)\n\n# 使用我们的特征列和优化器配置线性回归模型\nhouse_linear_regressor = tf.estimator.LinearRegressor(feature_columns=feature_columns, optimizer=kl_optimizer)","_____no_output_____"]],[["#### 第4步:定义输入函数\n要将数据导入LinearRegressor,我们需要定义一个输入函数,让它告诉TF如何对数据进行预处理,以及在模型训练期间如何批处理、随机处理和重复数据。\n首先我们将Pandas特征数据转换成NumPy数组字典,然后利用Dataset API构建Dataset对象,拆分数据为batch_size的批数据,以按照指定周期数(num_epochs)进行重复,**注意:**如果默认值num_epochs=None传递到repeat(),输入数据会无限期重复。\nshuffle: Bool, 是否打乱数据\nbuffer_size: 指定shuffle从中随机抽样的数据集大小","_____no_output_____"]],[["def kl_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n \"\"\"使用单个特征训练房价预测模型\n Args:\n features: 特征DataFrame\n targets: 目标DataFrame\n batch_size: 批大小\n shuffle: Bool. 是否打乱数据\n Return:\n 下一个数据批次的元组(features, labels)\n \"\"\"\n # 把pandas数据转换成np.array构成的dict数据\n features = {key: np.array(value) for key, value in dict(features).items()}\n \n # 构建数据集,配置批和重复次数、\n ds = Dataset.from_tensor_slices((features, targets)) # 数据大小 2GB 限制\n ds = ds.batch(batch_size).repeat(num_epochs)\n \n # 打乱数据\n if shuffle:\n ds = ds.shuffle(buffer_size=10000) # buffer_size指随机抽样的数据集大小\n \n # 返回下一批次的数据\n features, labels = ds.make_one_shot_iterator().get_next()\n return features, labels","_____no_output_____"]],[["**注意:** 更详细的输入函数和Dataset API参考:[TF Developer's Guide](https://www.tensorflow.org/programmers_guide/datasets)","_____no_output_____"],["#### 第5步:训练模型\n在linear_regressor上调用train()来训练模型","_____no_output_____"]],[["_ = house_linear_regressor.train(input_fn=lambda: kl_input_fn(kl_feature, targets), steps=100)","_____no_output_____"]],[["#### 第6步:评估模型\n**注意:**训练误差可以衡量训练的模型与训练数据的拟合情况,但**不能**衡量模型泛化到新数据的效果,我们需要拆分数据来评估模型的泛化能力。","_____no_output_____"]],[["# 只做一次预测,所以把epoch设为1并关闭随机\nprediction_input_fn = lambda: kl_input_fn(kl_feature, targets, num_epochs=1, shuffle=False)\n\n# 调用predict进行预测\npredictions = house_linear_regressor.predict(input_fn=prediction_input_fn)\n\n# 把预测结果转换为numpy数组\npredictions = np.array([item['predictions'][0] for item in predictions])\n\n# 打印MSE和RMSE\nmean_squared_error = metrics.mean_squared_error(predictions, targets)\nroot_mean_squared_error = math.sqrt(mean_squared_error)\n\nprint(\"均方误差 %0.3f\" % mean_squared_error)\nprint(\"均方根误差: %0.3f\" % root_mean_squared_error)\n","均方误差 56367.025\n均方根误差: 237.417\n"],["min_house_value = california_housing_df['median_house_value'].min()\nmax_house_value = california_housing_df['median_house_value'].max()\nmin_max_diff = max_house_value- min_house_value\n\nprint(\"最低中位房价: %0.3f\" % min_house_value)\nprint(\"最高中位房价: %0.3f\" % max_house_value)\nprint(\"中位房价最低最高差值: %0.3f\" % min_max_diff)\nprint(\"均方根误差:%0.3f\" % root_mean_squared_error)","最低中位房价: 14.999\n最高中位房价: 500.001\n中位房价最低最高差值: 485.002\n均方根误差:237.417\n"]],[["由此结果可以看出模型的效果并不理想,我们可以使用一些基本的策略来降低误差。","_____no_output_____"]],[["calibration_data = pd.DataFrame()\ncalibration_data[\"predictions\"] = pd.Series(predictions)\ncalibration_data[\"targets\"] = pd.Series(targets)\ncalibration_data.describe()","_____no_output_____"],["# 我们可以可视化数据和我们学到的线,\nsample = california_housing_df.sample(n=300) # 得到均匀分布的sample数据df","_____no_output_____"],["# 得到房屋总数的最小最大值\nx_0 = sample[\"total_rooms\"].min()\nx_1 = sample[\"total_rooms\"].max()\n\n# 获得训练后的最终权重和偏差\nweight = house_linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0]\nbias = house_linear_regressor.get_variable_value('linear/linear_model/bias_weights')\n\n# 计算最低最高房间数(特征)对应的房价(标签)\ny_0 = weight * x_0 + bias\ny_1 = weight * x_1 +bias\n\n# 画图\nplt.plot([x_0,x_1], [y_0,y_1],c='r')\nplt.ylabel('median_house_value')\nplt.xlabel('total_rooms')\n\n# 画出散点图\nplt.scatter(sample[\"total_rooms\"], sample[\"median_house_value\"])\n\nplt.show()","_____no_output_____"]],[["### 模型调参\n以上代码封装调参","_____no_output_____"]],[["def train_model(learning_rate, steps, batch_size, input_feature=\"total_rooms\"):\n \"\"\"Trains a linear regression model of one feature.\n \n Args:\n learning_rate: A `float`, the learning rate.\n steps: A non-zero `int`, the total number of training steps. A training step\n consists of a forward and backward pass using a single batch.\n batch_size: A non-zero `int`, the batch size.\n input_feature: A `string` specifying a column from `california_housing_df`\n to use as input feature.\n \"\"\"\n \n periods = 10\n steps_per_period = steps / periods\n\n my_feature = input_feature\n my_feature_data = california_housing_df[[my_feature]]\n my_label = \"median_house_value\"\n targets = california_housing_df[my_label]\n\n # Create feature columns.\n feature_columns = [tf.feature_column.numeric_column(my_feature)]\n \n # Create input functions.\n training_input_fn = lambda:kl_input_fn(my_feature_data, targets, batch_size=batch_size)\n prediction_input_fn = lambda: kl_input_fn(my_feature_data, targets, num_epochs=1, shuffle=False)\n \n # Create a linear regressor object.\n my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n linear_regressor = tf.estimator.LinearRegressor(\n feature_columns=feature_columns,\n optimizer=my_optimizer\n )\n\n # Set up to plot the state of our model's line each period.\n plt.figure(figsize=(15, 6))\n plt.subplot(1, 2, 1)\n plt.title(\"Learned Line by Period\")\n plt.ylabel(my_label)\n plt.xlabel(my_feature)\n sample = california_housing_df.sample(n=300)\n plt.scatter(sample[my_feature], sample[my_label])\n colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]\n\n # Train the model, but do so inside a loop so that we can periodically assess\n # loss metrics.\n print(\"Training model...\")\n print(\"RMSE (on training data):\")\n root_mean_squared_errors = []\n for period in range (0, periods):\n # Train the model, starting from the prior state.\n linear_regressor.train(\n input_fn=training_input_fn,\n steps=steps_per_period\n )\n # Take a break and compute predictions.\n predictions = linear_regressor.predict(input_fn=prediction_input_fn)\n predictions = np.array([item['predictions'][0] for item in predictions])\n \n # Compute loss.\n root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(predictions, targets))\n # Occasionally print the current loss.\n print(\" period %02d : %0.2f\" % (period, root_mean_squared_error))\n # Add the loss metrics from this period to our list.\n root_mean_squared_errors.append(root_mean_squared_error)\n # Finally, track the weights and biases over time.\n # Apply some math to ensure that the data and line are plotted neatly.\n y_extents = np.array([0, sample[my_label].max()])\n \n weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]\n bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')\n\n x_extents = (y_extents - bias) / weight\n x_extents = np.maximum(np.minimum(x_extents,\n sample[my_feature].max()),\n sample[my_feature].min())\n y_extents = weight * x_extents + bias\n plt.plot(x_extents, y_extents, color=colors[period]) \n print(\"Model training finished.\")\n\n # Output a graph of loss metrics over periods.\n plt.subplot(1, 2, 2)\n plt.ylabel('RMSE')\n plt.xlabel('Periods')\n plt.title(\"Root Mean Squared Error vs. Periods\")\n plt.tight_layout()\n plt.plot(root_mean_squared_errors)\n\n # Output a table with calibration data.\n calibration_data = pd.DataFrame()\n calibration_data[\"predictions\"] = pd.Series(predictions)\n calibration_data[\"targets\"] = pd.Series(targets)\n display.display(calibration_data.describe())\n\n print(\"Final RMSE (on training data): %0.2f\" % root_mean_squared_error)","_____no_output_____"]],[["**练习1: 使RMSE不超过180**","_____no_output_____"]],[["train_model(learning_rate=0.00002, steps=500, batch_size=5)","Training model...\nRMSE (on training data):\n period 00 : 225.63\n period 01 : 214.42\n period 02 : 204.04\n period 03 : 194.97\n period 04 : 186.60\n period 05 : 180.80\n period 06 : 175.66\n period 07 : 171.74\n period 08 : 168.96\n period 09 : 167.23\nModel training finished.\n"]],[["### 模型调参的启发法\n> 不要死循规则\n\n- 训练误差应该稳步减小,刚开始是急剧减小,最终应随着训练收敛达到平稳状态。\n- 如果训练尚未收敛,尝试运行更长的时间。\n- 如果训练误差减小速度过慢,则提高学习速率也许有助于加快其减小速度。\n- 但有时如果学习速率过高,训练误差的减小速度反而会变慢。\n- 如果训练误差变化很大,尝试降低学习速率。\n- 较低的学习速率和较大的步数/较大的批量大小通常是不错的组合。\n- 批量大小过小也会导致不稳定情况。不妨先尝试 100 或 1000 等较大的值,然后逐渐减小值的大小,直到出现性能降低的情况。","_____no_output_____"],["**练习2:尝试其他特征**\n我们使用population特征替代。","_____no_output_____"]],[["train_model(learning_rate=0.00005, steps=500, batch_size=5, input_feature=\"population\")","Training model...\nRMSE (on training data):\n period 00 : 222.79\n period 01 : 209.51\n period 02 : 198.00\n period 03 : 189.59\n period 04 : 182.78\n period 05 : 179.35\n period 06 : 177.30\n period 07 : 176.11\n period 08 : 175.97\n period 09 : 176.51\nModel training finished.\n"]]],"string":"[\n [\n [\n \"## 使用TensorFlow的基本步骤\\n以使用LinearRegression来预测房价为例。\\n- 使用RMSE(均方根误差)评估模型预测的准确率\\n- 通过调整超参数来提高模型的预测准确率\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"from __future__ import print_function\\n\\nimport math\\n\\nfrom IPython import display\\nfrom matplotlib import cm\\nfrom matplotlib import gridspec\\nimport matplotlib.pyplot as plt\\nimport numpy as np\\nimport pandas as pd\\nfrom sklearn import metrics\\nimport tensorflow as tf\\nfrom tensorflow.python.data import Dataset\\n\\ntf.logging.set_verbosity(tf.logging.ERROR)\\npd.options.display.max_rows = 10\\npd.options.display.float_format = '{:.1f}'.format\",\n \"/Users/kevin/.virtualenvs/py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6\\n return f(*args, **kwds)\\n\"\n ],\n [\n \"# 加载数据集\\ncalifornia_housing_df = pd.read_csv(\\\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\\\", sep=\\\",\\\")\",\n \"_____no_output_____\"\n ],\n [\n \"# 将数据打乱\\ncalifornia_housing_df = california_housing_df.reindex(np.random.permutation(california_housing_df.index))\\n# 替换房价的单位为k\\ncalifornia_housing_df['median_house_value'] /=1000.0\\nprint(\\\"california house dataframe: \\\\n\\\", california_housing_df) # 根据pd设置,只显示10条数据,以及保留小数点后一位\",\n \"california house dataframe: \\n longitude latitude housing_median_age total_rooms total_bedrooms \\\\\\n840 -117.1 32.7 29.0 1429.0 293.0 \\n15761 -122.4 37.8 52.0 3260.0 1535.0 \\n2964 -117.8 34.1 23.0 7079.0 1381.0 \\n5005 -118.1 33.8 36.0 1074.0 188.0 \\n9816 -119.7 36.5 29.0 1702.0 301.0 \\n... ... ... ... ... ... \\n1864 -117.3 34.7 28.0 1932.0 421.0 \\n6257 -118.2 34.1 11.0 1281.0 418.0 \\n4690 -118.1 34.1 52.0 1282.0 189.0 \\n6409 -118.3 33.9 44.0 1103.0 265.0 \\n11082 -121.0 38.7 5.0 5743.0 1074.0 \\n\\n population households median_income median_house_value \\n840 1091.0 317.0 3.5 118.0 \\n15761 3260.0 1457.0 0.9 500.0 \\n2964 3205.0 1327.0 3.1 212.3 \\n5005 496.0 196.0 4.6 217.4 \\n9816 914.0 280.0 2.8 79.2 \\n... ... ... ... ... \\n1864 1156.0 404.0 1.9 55.6 \\n6257 1584.0 330.0 2.9 153.1 \\n4690 431.0 187.0 6.1 470.8 \\n6409 760.0 247.0 1.7 99.6 \\n11082 2651.0 962.0 4.1 172.5 \\n\\n[17000 rows x 9 columns]\\n\"\n ]\n ],\n [\n [\n \"### 检查数据\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 使用pd的describe方法来统计一些信息\\ncalifornia_housing_df.describe()\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### 构建模型\\n我们将在这个例子中预测中位房价,将其作为学习的标签,使用房间总数作为输入特征。\",\n \"_____no_output_____\"\n ],\n [\n \"#### 第1步:定义特征并配置特征列\\n为了把数据导入TensorFlow,我们需要指定每个特征包含的数据类型。我们主要使用以下两种类型:\\n- 分类数据: 一种文字数据。\\n- 数值数据:一种数字(整数或浮点数)数据或希望视为数字的数据。\\n\\n在TF中我们使用**特征列**的结构来表示特征的数据类型。特征列仅存储对特征数据的描述,不包含特征数据本身。\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 定义输入特征\\nkl_feature = california_housing_df[['total_rooms']]\\n\\n# 配置房间总数为数值特征列\\nfeature_columns = [tf.feature_column.numeric_column('total_rooms')]\",\n \"[_NumericColumn(key='total_rooms', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)]\\n\"\n ]\n ],\n [\n [\n \"#### 第2步: 定义目标\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 定义目标标签\\ntargets = california_housing_df['median_house_value']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"**梯度裁剪**是在应用梯度值之前设置其上限,梯度裁剪有助于确保数值稳定性,防止梯度爆炸。\",\n \"_____no_output_____\"\n ],\n [\n \"#### 第3步:配置线性回归器\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 使用Linear Regressor配置线性回归模型,使用GradientDescentOptimizer优化器训练模型\\nkl_optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001)\\n# 使用clip_gradients_by_norm梯度裁剪我们的优化器,梯度裁剪可以确保我们的梯度大小在训练期间不会变得过大,梯度过大会导致梯度下降失败。\\nkl_optimizer = tf.contrib.estimator.clip_gradients_by_norm(kl_optimizer, 5.0)\\n\\n# 使用我们的特征列和优化器配置线性回归模型\\nhouse_linear_regressor = tf.estimator.LinearRegressor(feature_columns=feature_columns, optimizer=kl_optimizer)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#### 第4步:定义输入函数\\n要将数据导入LinearRegressor,我们需要定义一个输入函数,让它告诉TF如何对数据进行预处理,以及在模型训练期间如何批处理、随机处理和重复数据。\\n首先我们将Pandas特征数据转换成NumPy数组字典,然后利用Dataset API构建Dataset对象,拆分数据为batch_size的批数据,以按照指定周期数(num_epochs)进行重复,**注意:**如果默认值num_epochs=None传递到repeat(),输入数据会无限期重复。\\nshuffle: Bool, 是否打乱数据\\nbuffer_size: 指定shuffle从中随机抽样的数据集大小\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"def kl_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\\n \\\"\\\"\\\"使用单个特征训练房价预测模型\\n Args:\\n features: 特征DataFrame\\n targets: 目标DataFrame\\n batch_size: 批大小\\n shuffle: Bool. 是否打乱数据\\n Return:\\n 下一个数据批次的元组(features, labels)\\n \\\"\\\"\\\"\\n # 把pandas数据转换成np.array构成的dict数据\\n features = {key: np.array(value) for key, value in dict(features).items()}\\n \\n # 构建数据集,配置批和重复次数、\\n ds = Dataset.from_tensor_slices((features, targets)) # 数据大小 2GB 限制\\n ds = ds.batch(batch_size).repeat(num_epochs)\\n \\n # 打乱数据\\n if shuffle:\\n ds = ds.shuffle(buffer_size=10000) # buffer_size指随机抽样的数据集大小\\n \\n # 返回下一批次的数据\\n features, labels = ds.make_one_shot_iterator().get_next()\\n return features, labels\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"**注意:** 更详细的输入函数和Dataset API参考:[TF Developer's Guide](https://www.tensorflow.org/programmers_guide/datasets)\",\n \"_____no_output_____\"\n ],\n [\n \"#### 第5步:训练模型\\n在linear_regressor上调用train()来训练模型\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"_ = house_linear_regressor.train(input_fn=lambda: kl_input_fn(kl_feature, targets), steps=100)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#### 第6步:评估模型\\n**注意:**训练误差可以衡量训练的模型与训练数据的拟合情况,但**不能**衡量模型泛化到新数据的效果,我们需要拆分数据来评估模型的泛化能力。\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# 只做一次预测,所以把epoch设为1并关闭随机\\nprediction_input_fn = lambda: kl_input_fn(kl_feature, targets, num_epochs=1, shuffle=False)\\n\\n# 调用predict进行预测\\npredictions = house_linear_regressor.predict(input_fn=prediction_input_fn)\\n\\n# 把预测结果转换为numpy数组\\npredictions = np.array([item['predictions'][0] for item in predictions])\\n\\n# 打印MSE和RMSE\\nmean_squared_error = metrics.mean_squared_error(predictions, targets)\\nroot_mean_squared_error = math.sqrt(mean_squared_error)\\n\\nprint(\\\"均方误差 %0.3f\\\" % mean_squared_error)\\nprint(\\\"均方根误差: %0.3f\\\" % root_mean_squared_error)\\n\",\n \"均方误差 56367.025\\n均方根误差: 237.417\\n\"\n ],\n [\n \"min_house_value = california_housing_df['median_house_value'].min()\\nmax_house_value = california_housing_df['median_house_value'].max()\\nmin_max_diff = max_house_value- min_house_value\\n\\nprint(\\\"最低中位房价: %0.3f\\\" % min_house_value)\\nprint(\\\"最高中位房价: %0.3f\\\" % max_house_value)\\nprint(\\\"中位房价最低最高差值: %0.3f\\\" % min_max_diff)\\nprint(\\\"均方根误差:%0.3f\\\" % root_mean_squared_error)\",\n \"最低中位房价: 14.999\\n最高中位房价: 500.001\\n中位房价最低最高差值: 485.002\\n均方根误差:237.417\\n\"\n ]\n ],\n [\n [\n \"由此结果可以看出模型的效果并不理想,我们可以使用一些基本的策略来降低误差。\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"calibration_data = pd.DataFrame()\\ncalibration_data[\\\"predictions\\\"] = pd.Series(predictions)\\ncalibration_data[\\\"targets\\\"] = pd.Series(targets)\\ncalibration_data.describe()\",\n \"_____no_output_____\"\n ],\n [\n \"# 我们可以可视化数据和我们学到的线,\\nsample = california_housing_df.sample(n=300) # 得到均匀分布的sample数据df\",\n \"_____no_output_____\"\n ],\n [\n \"# 得到房屋总数的最小最大值\\nx_0 = sample[\\\"total_rooms\\\"].min()\\nx_1 = sample[\\\"total_rooms\\\"].max()\\n\\n# 获得训练后的最终权重和偏差\\nweight = house_linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0]\\nbias = house_linear_regressor.get_variable_value('linear/linear_model/bias_weights')\\n\\n# 计算最低最高房间数(特征)对应的房价(标签)\\ny_0 = weight * x_0 + bias\\ny_1 = weight * x_1 +bias\\n\\n# 画图\\nplt.plot([x_0,x_1], [y_0,y_1],c='r')\\nplt.ylabel('median_house_value')\\nplt.xlabel('total_rooms')\\n\\n# 画出散点图\\nplt.scatter(sample[\\\"total_rooms\\\"], sample[\\\"median_house_value\\\"])\\n\\nplt.show()\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### 模型调参\\n以上代码封装调参\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"def train_model(learning_rate, steps, batch_size, input_feature=\\\"total_rooms\\\"):\\n \\\"\\\"\\\"Trains a linear regression model of one feature.\\n \\n Args:\\n learning_rate: A `float`, the learning rate.\\n steps: A non-zero `int`, the total number of training steps. A training step\\n consists of a forward and backward pass using a single batch.\\n batch_size: A non-zero `int`, the batch size.\\n input_feature: A `string` specifying a column from `california_housing_df`\\n to use as input feature.\\n \\\"\\\"\\\"\\n \\n periods = 10\\n steps_per_period = steps / periods\\n\\n my_feature = input_feature\\n my_feature_data = california_housing_df[[my_feature]]\\n my_label = \\\"median_house_value\\\"\\n targets = california_housing_df[my_label]\\n\\n # Create feature columns.\\n feature_columns = [tf.feature_column.numeric_column(my_feature)]\\n \\n # Create input functions.\\n training_input_fn = lambda:kl_input_fn(my_feature_data, targets, batch_size=batch_size)\\n prediction_input_fn = lambda: kl_input_fn(my_feature_data, targets, num_epochs=1, shuffle=False)\\n \\n # Create a linear regressor object.\\n my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\\n linear_regressor = tf.estimator.LinearRegressor(\\n feature_columns=feature_columns,\\n optimizer=my_optimizer\\n )\\n\\n # Set up to plot the state of our model's line each period.\\n plt.figure(figsize=(15, 6))\\n plt.subplot(1, 2, 1)\\n plt.title(\\\"Learned Line by Period\\\")\\n plt.ylabel(my_label)\\n plt.xlabel(my_feature)\\n sample = california_housing_df.sample(n=300)\\n plt.scatter(sample[my_feature], sample[my_label])\\n colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]\\n\\n # Train the model, but do so inside a loop so that we can periodically assess\\n # loss metrics.\\n print(\\\"Training model...\\\")\\n print(\\\"RMSE (on training data):\\\")\\n root_mean_squared_errors = []\\n for period in range (0, periods):\\n # Train the model, starting from the prior state.\\n linear_regressor.train(\\n input_fn=training_input_fn,\\n steps=steps_per_period\\n )\\n # Take a break and compute predictions.\\n predictions = linear_regressor.predict(input_fn=prediction_input_fn)\\n predictions = np.array([item['predictions'][0] for item in predictions])\\n \\n # Compute loss.\\n root_mean_squared_error = math.sqrt(\\n metrics.mean_squared_error(predictions, targets))\\n # Occasionally print the current loss.\\n print(\\\" period %02d : %0.2f\\\" % (period, root_mean_squared_error))\\n # Add the loss metrics from this period to our list.\\n root_mean_squared_errors.append(root_mean_squared_error)\\n # Finally, track the weights and biases over time.\\n # Apply some math to ensure that the data and line are plotted neatly.\\n y_extents = np.array([0, sample[my_label].max()])\\n \\n weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]\\n bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')\\n\\n x_extents = (y_extents - bias) / weight\\n x_extents = np.maximum(np.minimum(x_extents,\\n sample[my_feature].max()),\\n sample[my_feature].min())\\n y_extents = weight * x_extents + bias\\n plt.plot(x_extents, y_extents, color=colors[period]) \\n print(\\\"Model training finished.\\\")\\n\\n # Output a graph of loss metrics over periods.\\n plt.subplot(1, 2, 2)\\n plt.ylabel('RMSE')\\n plt.xlabel('Periods')\\n plt.title(\\\"Root Mean Squared Error vs. Periods\\\")\\n plt.tight_layout()\\n plt.plot(root_mean_squared_errors)\\n\\n # Output a table with calibration data.\\n calibration_data = pd.DataFrame()\\n calibration_data[\\\"predictions\\\"] = pd.Series(predictions)\\n calibration_data[\\\"targets\\\"] = pd.Series(targets)\\n display.display(calibration_data.describe())\\n\\n print(\\\"Final RMSE (on training data): %0.2f\\\" % root_mean_squared_error)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"**练习1: 使RMSE不超过180**\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"train_model(learning_rate=0.00002, steps=500, batch_size=5)\",\n \"Training model...\\nRMSE (on training data):\\n period 00 : 225.63\\n period 01 : 214.42\\n period 02 : 204.04\\n period 03 : 194.97\\n period 04 : 186.60\\n period 05 : 180.80\\n period 06 : 175.66\\n period 07 : 171.74\\n period 08 : 168.96\\n period 09 : 167.23\\nModel training finished.\\n\"\n ]\n ],\n [\n [\n \"### 模型调参的启发法\\n> 不要死循规则\\n\\n- 训练误差应该稳步减小,刚开始是急剧减小,最终应随着训练收敛达到平稳状态。\\n- 如果训练尚未收敛,尝试运行更长的时间。\\n- 如果训练误差减小速度过慢,则提高学习速率也许有助于加快其减小速度。\\n- 但有时如果学习速率过高,训练误差的减小速度反而会变慢。\\n- 如果训练误差变化很大,尝试降低学习速率。\\n- 较低的学习速率和较大的步数/较大的批量大小通常是不错的组合。\\n- 批量大小过小也会导致不稳定情况。不妨先尝试 100 或 1000 等较大的值,然后逐渐减小值的大小,直到出现性能降低的情况。\",\n \"_____no_output_____\"\n ],\n [\n \"**练习2:尝试其他特征**\\n我们使用population特征替代。\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"train_model(learning_rate=0.00005, steps=500, batch_size=5, input_feature=\\\"population\\\")\",\n \"Training model...\\nRMSE (on training data):\\n period 00 : 222.79\\n period 01 : 209.51\\n period 02 : 198.00\\n period 03 : 189.59\\n period 04 : 182.78\\n period 05 : 179.35\\n period 06 : 177.30\\n period 07 : 176.11\\n period 08 : 175.97\\n period 09 : 176.51\\nModel training finished.\\n\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"],["code","code","code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"],["markdown"],["code","code"],["markdown"],["code","code","code"],["markdown"],["code"],["markdown"],["code"],["markdown","markdown"],["code"]],"string":"[\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ]\n]"}}},{"rowIdx":577,"cells":{"hexsha":{"kind":"string","value":"d01a3bd9a87d591626b7607d11441e73cbe041df"},"size":{"kind":"number","value":526613,"string":"526,613"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"8 semester/CV/lab2.ipynb"},"max_stars_repo_name":{"kind":"string","value":"vladtsap/study"},"max_stars_repo_head_hexsha":{"kind":"string","value":"87bc1aae4db67fdc18d5203f4e2af1dee1220ec5"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2021-07-13T14:35:21.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2021-07-13T14:35:21.000Z"},"max_issues_repo_path":{"kind":"string","value":"8 semester/CV/lab2.ipynb"},"max_issues_repo_name":{"kind":"string","value":"vladtsap/study"},"max_issues_repo_head_hexsha":{"kind":"string","value":"87bc1aae4db67fdc18d5203f4e2af1dee1220ec5"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"8 semester/CV/lab2.ipynb"},"max_forks_repo_name":{"kind":"string","value":"vladtsap/study"},"max_forks_repo_head_hexsha":{"kind":"string","value":"87bc1aae4db67fdc18d5203f4e2af1dee1220ec5"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":526613,"string":"526,613"},"max_line_length":{"kind":"number","value":526613,"string":"526,613"},"alphanum_fraction":{"kind":"number","value":0.9626537894,"string":"0.962654"},"cells":{"kind":"list like","value":[[["!wget -c https://i.imgur.com/K74Rsq2.jpg -O painting.jpg\n!wget -c https://i.imgur.com/HnwPrgi.jpg -O painting_in_life.jpg","--2021-03-17 09:46:35-- https://i.imgur.com/K74Rsq2.jpg\nResolving i.imgur.com (i.imgur.com)... 199.232.64.193\nConnecting to i.imgur.com (i.imgur.com)|199.232.64.193|:443... connected.\nHTTP request sent, awaiting response... 416 Range Not Satisfiable\n\n The file is already fully retrieved; nothing to do.\n\n--2021-03-17 09:46:35-- https://i.imgur.com/HnwPrgi.jpg\nResolving i.imgur.com (i.imgur.com)... 199.232.64.193\nConnecting to i.imgur.com (i.imgur.com)|199.232.64.193|:443... connected.\nHTTP request sent, awaiting response... 416 Range Not Satisfiable\n\n The file is already fully retrieved; nothing to do.\n\n"],["import cv2 as cv\nimport matplotlib.pyplot as plt","_____no_output_____"],["img1 = cv.imread('painting.jpg', cv.IMREAD_GRAYSCALE) # queryImage\nimg2 = cv.imread('painting_in_life.jpg', cv.IMREAD_GRAYSCALE) # trainImage","_____no_output_____"],["# Initiate ORB detector\norb = cv.ORB_create()\n\n# find the keypoints and descriptors with ORB\nkp1, des1 = orb.detectAndCompute(img1, None)\nkp2, des2 = orb.detectAndCompute(img2, None)","_____no_output_____"],["# create BFMatcher object\n# bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True)\n# Match descriptors.\n# matches = bf.match(des1, des2)","_____no_output_____"],["def hamdist(x, y):\n diffs = 0\n\n if len(x) != len(y):\n return max(len(x), len(y))\n\n for ch1, ch2 in zip(x, y):\n if ch1 != ch2:\n diffs += 1\n\n return diffs\n\n\nmatches = []\nfor i, k1 in enumerate(des1):\n for j, k2 in enumerate(des2):\n matches.append(cv.DMatch(_distance=hamdist(k1, k2), _imgIdx=0, _queryIdx=i, _trainIdx=j))","_____no_output_____"],["# Sort them in the order of their distance.\nmatches = sorted(matches, key=lambda x: x.distance)\n\n# Draw first 10 matches.\nimg3 = cv.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\n\nplt.rcParams['figure.figsize'] = [20, 16]\nplt.imshow(img3), plt.show()","_____no_output_____"]]],"string":"[\n [\n [\n \"!wget -c https://i.imgur.com/K74Rsq2.jpg -O painting.jpg\\n!wget -c https://i.imgur.com/HnwPrgi.jpg -O painting_in_life.jpg\",\n \"--2021-03-17 09:46:35-- https://i.imgur.com/K74Rsq2.jpg\\nResolving i.imgur.com (i.imgur.com)... 199.232.64.193\\nConnecting to i.imgur.com (i.imgur.com)|199.232.64.193|:443... connected.\\nHTTP request sent, awaiting response... 416 Range Not Satisfiable\\n\\n The file is already fully retrieved; nothing to do.\\n\\n--2021-03-17 09:46:35-- https://i.imgur.com/HnwPrgi.jpg\\nResolving i.imgur.com (i.imgur.com)... 199.232.64.193\\nConnecting to i.imgur.com (i.imgur.com)|199.232.64.193|:443... connected.\\nHTTP request sent, awaiting response... 416 Range Not Satisfiable\\n\\n The file is already fully retrieved; nothing to do.\\n\\n\"\n ],\n [\n \"import cv2 as cv\\nimport matplotlib.pyplot as plt\",\n \"_____no_output_____\"\n ],\n [\n \"img1 = cv.imread('painting.jpg', cv.IMREAD_GRAYSCALE) # queryImage\\nimg2 = cv.imread('painting_in_life.jpg', cv.IMREAD_GRAYSCALE) # trainImage\",\n \"_____no_output_____\"\n ],\n [\n \"# Initiate ORB detector\\norb = cv.ORB_create()\\n\\n# find the keypoints and descriptors with ORB\\nkp1, des1 = orb.detectAndCompute(img1, None)\\nkp2, des2 = orb.detectAndCompute(img2, None)\",\n \"_____no_output_____\"\n ],\n [\n \"# create BFMatcher object\\n# bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True)\\n# Match descriptors.\\n# matches = bf.match(des1, des2)\",\n \"_____no_output_____\"\n ],\n [\n \"def hamdist(x, y):\\n diffs = 0\\n\\n if len(x) != len(y):\\n return max(len(x), len(y))\\n\\n for ch1, ch2 in zip(x, y):\\n if ch1 != ch2:\\n diffs += 1\\n\\n return diffs\\n\\n\\nmatches = []\\nfor i, k1 in enumerate(des1):\\n for j, k2 in enumerate(des2):\\n matches.append(cv.DMatch(_distance=hamdist(k1, k2), _imgIdx=0, _queryIdx=i, _trainIdx=j))\",\n \"_____no_output_____\"\n ],\n [\n \"# Sort them in the order of their distance.\\nmatches = sorted(matches, key=lambda x: x.distance)\\n\\n# Draw first 10 matches.\\nimg3 = cv.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\\n\\nplt.rcParams['figure.figsize'] = [20, 16]\\nplt.imshow(img3), plt.show()\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["code"],"string":"[\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["code","code","code","code","code","code","code"]],"string":"[\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":578,"cells":{"hexsha":{"kind":"string","value":"d01a43ff7ffd3c40bc38f05c6a62c0ecf9f63182"},"size":{"kind":"number","value":36711,"string":"36,711"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"ait_repository/test/tests/eval_metamorphic_test_tf1.13_0.1.ipynb"},"max_stars_repo_name":{"kind":"string","value":"ads-ad-itcenter/qunomon.forked"},"max_stars_repo_head_hexsha":{"kind":"string","value":"48d532692d353fe2d3946f62b227f834f9349034"},"max_stars_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_stars_count":{"kind":"number","value":16,"string":"16"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2020-11-18T05:43:55.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2021-11-27T14:43:26.000Z"},"max_issues_repo_path":{"kind":"string","value":"ait_repository/test/tests/eval_metamorphic_test_tf1.13_0.1.ipynb"},"max_issues_repo_name":{"kind":"string","value":"aistairc/qunomon"},"max_issues_repo_head_hexsha":{"kind":"string","value":"d4e9c5cb569b16addfbe6c33c73812065065a1df"},"max_issues_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_issues_count":{"kind":"number","value":1,"string":"1"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2022-03-23T07:55:54.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2022-03-23T13:24:11.000Z"},"max_forks_repo_path":{"kind":"string","value":"ait_repository/test/tests/eval_metamorphic_test_tf1.13_0.1.ipynb"},"max_forks_repo_name":{"kind":"string","value":"ads-ad-itcenter/qunomon.forked"},"max_forks_repo_head_hexsha":{"kind":"string","value":"48d532692d353fe2d3946f62b227f834f9349034"},"max_forks_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_forks_count":{"kind":"number","value":3,"string":"3"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2021-02-12T01:56:31.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2022-03-23T02:45:02.000Z"},"avg_line_length":{"kind":"number","value":48.4313984169,"string":"48.431398"},"max_line_length":{"kind":"number","value":746,"string":"746"},"alphanum_fraction":{"kind":"number","value":0.4910517284,"string":"0.491052"},"cells":{"kind":"list like","value":[[["# test note\n\n\n* jupyterはコンテナ起動すること\n* テストベッド一式起動済みであること\n","_____no_output_____"]],[["!pip install --upgrade pip\n!pip install --force-reinstall ../lib/ait_sdk-0.1.7-py3-none-any.whl","Requirement already satisfied: pip in /usr/local/lib/python3.6/dist-packages (21.0.1)\nCollecting pip\n Downloading pip-21.1.1-py3-none-any.whl (1.5 MB)\n\u001b[K |████████████████████████████████| 1.5 MB 4.0 MB/s eta 0:00:01\n\u001b[?25hInstalling collected packages: pip\n Attempting uninstall: pip\n Found existing installation: pip 21.0.1\n Uninstalling pip-21.0.1:\n Successfully uninstalled pip-21.0.1\nSuccessfully installed pip-21.1.1\nProcessing /workdir/root/lib/ait_sdk-0.1.7-py3-none-any.whl\nCollecting numpy<=1.19.3\n Downloading numpy-1.19.3-cp36-cp36m-manylinux2010_x86_64.whl (14.9 MB)\n\u001b[K |████████████████████████████████| 14.9 MB 2.8 MB/s eta 0:00:01 |███████▉ | 3.6 MB 3.7 MB/s eta 0:00:04 |███████████▎ | 5.2 MB 3.7 MB/s eta 0:00:03 |████████████████▌ | 7.6 MB 3.7 MB/s eta 0:00:02 |██████████████████▏ | 8.4 MB 3.7 MB/s eta 0:00:02 |███████████████████████████▍ | 12.7 MB 2.8 MB/s eta 0:00:01\n\u001b[?25hCollecting py-cpuinfo<=7.0.0\n Downloading py-cpuinfo-7.0.0.tar.gz (95 kB)\n\u001b[K |████████████████████████████████| 95 kB 4.1 MB/s eta 0:00:011\n\u001b[?25hCollecting keras<=2.4.3\n Downloading Keras-2.4.3-py2.py3-none-any.whl (36 kB)\nCollecting nbformat<=5.0.8\n Downloading nbformat-5.0.8-py3-none-any.whl (172 kB)\n\u001b[K |████████████████████████████████| 172 kB 10.6 MB/s eta 0:00:01\n\u001b[?25hCollecting psutil<=5.7.3\n Downloading psutil-5.7.3.tar.gz (465 kB)\n\u001b[K |████████████████████████████████| 465 kB 8.4 MB/s eta 0:00:01 |█████████████████████████▍ | 368 kB 8.4 MB/s eta 0:00:01\n\u001b[?25hCollecting nbconvert<=6.0.7\n Using cached nbconvert-6.0.7-py3-none-any.whl (552 kB)\nCollecting scipy>=0.14\n Downloading scipy-1.5.4-cp36-cp36m-manylinux1_x86_64.whl (25.9 MB)\n\u001b[K |████████████████████████████████| 25.9 MB 6.4 MB/s eta 0:00:01 |██▊ | 2.2 MB 6.3 MB/s eta 0:00:04 |█████▏ | 4.2 MB 6.3 MB/s eta 0:00:04 |███████████████▊ | 12.7 MB 6.5 MB/s eta 0:00:03 |██████████████████████▎ | 18.0 MB 5.8 MB/s eta 0:00:02 |█████████████████████████████▋ | 24.0 MB 6.4 MB/s eta 0:00:01\n\u001b[?25hCollecting h5py\n Downloading h5py-3.1.0-cp36-cp36m-manylinux1_x86_64.whl (4.0 MB)\n\u001b[K |████████████████████████████████| 4.0 MB 8.1 MB/s eta 0:00:01\n\u001b[?25hCollecting pyyaml\n Downloading PyYAML-5.4.1-cp36-cp36m-manylinux1_x86_64.whl (640 kB)\n\u001b[K |████████████████████████████████| 640 kB 6.3 MB/s eta 0:00:01\n\u001b[?25hCollecting testpath\n Using cached testpath-0.4.4-py2.py3-none-any.whl (163 kB)\nCollecting jupyterlab-pygments\n Using cached jupyterlab_pygments-0.1.2-py2.py3-none-any.whl (4.6 kB)\nCollecting mistune<2,>=0.8.1\n Using cached mistune-0.8.4-py2.py3-none-any.whl (16 kB)\nCollecting jinja2>=2.4\n Using cached Jinja2-2.11.3-py2.py3-none-any.whl (125 kB)\nCollecting jupyter-core\n Using cached jupyter_core-4.7.1-py3-none-any.whl (82 kB)\nCollecting pandocfilters>=1.4.1\n Using cached pandocfilters-1.4.3-py3-none-any.whl\nCollecting entrypoints>=0.2.2\n Using cached entrypoints-0.3-py2.py3-none-any.whl (11 kB)\nCollecting defusedxml\n Using cached defusedxml-0.7.1-py2.py3-none-any.whl (25 kB)\nCollecting traitlets>=4.2\n Using cached traitlets-4.3.3-py2.py3-none-any.whl (75 kB)\nCollecting bleach\n Using cached bleach-3.3.0-py2.py3-none-any.whl (283 kB)\nCollecting nbclient<0.6.0,>=0.5.0\n Using cached nbclient-0.5.3-py3-none-any.whl (82 kB)\nCollecting pygments>=2.4.1\n Downloading Pygments-2.9.0-py3-none-any.whl (1.0 MB)\n\u001b[K |████████████████████████████████| 1.0 MB 11.8 MB/s eta 0:00:01 |████████▌ | 266 kB 11.8 MB/s eta 0:00:01\n\u001b[?25hCollecting MarkupSafe>=0.23\n Using cached MarkupSafe-1.1.1-cp36-cp36m-manylinux2010_x86_64.whl (32 kB)\nCollecting jupyter-client>=6.1.5\n Using cached jupyter_client-6.1.12-py3-none-any.whl (112 kB)\nCollecting async-generator\n Using cached async_generator-1.10-py3-none-any.whl (18 kB)\nCollecting nest-asyncio\n Using cached nest_asyncio-1.5.1-py3-none-any.whl (5.0 kB)\nCollecting tornado>=4.1\n Using cached tornado-6.1-cp36-cp36m-manylinux2010_x86_64.whl (427 kB)\nCollecting python-dateutil>=2.1\n Using cached python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)\nCollecting pyzmq>=13\n Using cached pyzmq-22.0.3-cp36-cp36m-manylinux1_x86_64.whl (1.1 MB)\nCollecting ipython-genutils\n Using cached ipython_genutils-0.2.0-py2.py3-none-any.whl (26 kB)\nCollecting jsonschema!=2.5.0,>=2.4\n Using cached jsonschema-3.2.0-py2.py3-none-any.whl (56 kB)\nCollecting pyrsistent>=0.14.0\n Using cached pyrsistent-0.17.3-cp36-cp36m-linux_x86_64.whl\nCollecting importlib-metadata\n Downloading importlib_metadata-4.0.1-py3-none-any.whl (16 kB)\nCollecting attrs>=17.4.0\n Downloading attrs-21.2.0-py2.py3-none-any.whl (53 kB)\n\u001b[K |████████████████████████████████| 53 kB 2.0 MB/s eta 0:00:011\n\u001b[?25hCollecting setuptools\n Downloading setuptools-56.2.0-py3-none-any.whl (785 kB)\n\u001b[K |████████████████████████████████| 785 kB 5.5 MB/s eta 0:00:01 |███████████████████████████████▎| 768 kB 5.5 MB/s eta 0:00:01\n\u001b[?25hCollecting six>=1.11.0\n Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)\nCollecting decorator\n Downloading decorator-5.0.7-py3-none-any.whl (8.8 kB)\nCollecting packaging\n Using cached packaging-20.9-py2.py3-none-any.whl (40 kB)\nCollecting webencodings\n Using cached webencodings-0.5.1-py2.py3-none-any.whl (11 kB)\nCollecting cached-property\n Downloading cached_property-1.5.2-py2.py3-none-any.whl (7.6 kB)\nCollecting typing-extensions>=3.6.4\n Downloading typing_extensions-3.10.0.0-py3-none-any.whl (26 kB)\nCollecting zipp>=0.5\n Downloading zipp-3.4.1-py3-none-any.whl (5.2 kB)\nCollecting pyparsing>=2.0.2\n Using cached pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)\nBuilding wheels for collected packages: psutil, py-cpuinfo\n Building wheel for psutil (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for psutil: filename=psutil-5.7.3-cp36-cp36m-linux_x86_64.whl size=288610 sha256=add7bf93ebb9ecbd8650a6cf9469361f154e3e577a660725a014c35bae9e2b35\n Stored in directory: /root/.cache/pip/wheels/fa/ad/67/90bbaacdcfe970960dd5158397f23a6579b51d853720d7856d\n Building wheel for py-cpuinfo (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for py-cpuinfo: filename=py_cpuinfo-7.0.0-py3-none-any.whl size=20299 sha256=b2ec8e860f6c76a428e7e43a1be32903a0b2061998a1606cd0dd1d40219c59a1\n Stored in directory: /root/.cache/pip/wheels/46/6d/cc/73a126dc2e09fe56fcec0a7386d255762611fbed1c86d3bbcc\nSuccessfully built psutil py-cpuinfo\nInstalling collected packages: zipp, typing-extensions, six, ipython-genutils, decorator, traitlets, setuptools, pyrsistent, importlib-metadata, attrs, tornado, pyzmq, python-dateutil, pyparsing, jupyter-core, jsonschema, webencodings, pygments, packaging, numpy, nest-asyncio, nbformat, MarkupSafe, jupyter-client, cached-property, async-generator, testpath, scipy, pyyaml, pandocfilters, nbclient, mistune, jupyterlab-pygments, jinja2, h5py, entrypoints, defusedxml, bleach, py-cpuinfo, psutil, nbconvert, keras, ait-sdk\n Attempting uninstall: zipp\n Found existing installation: zipp 3.4.0\n Uninstalling zipp-3.4.0:\n Successfully uninstalled zipp-3.4.0\n Attempting uninstall: six\n Found existing installation: six 1.15.0\n Uninstalling six-1.15.0:\n Successfully uninstalled six-1.15.0\n Attempting uninstall: ipython-genutils\n Found existing installation: ipython-genutils 0.2.0\n Uninstalling ipython-genutils-0.2.0:\n Successfully uninstalled ipython-genutils-0.2.0\n Attempting uninstall: decorator\n Found existing installation: decorator 4.4.2\n Uninstalling decorator-4.4.2:\n Successfully uninstalled decorator-4.4.2\n Attempting uninstall: traitlets\n Found existing installation: traitlets 4.3.3\n Uninstalling traitlets-4.3.3:\n Successfully uninstalled traitlets-4.3.3\n Attempting uninstall: setuptools\n Found existing installation: setuptools 54.1.2\n Uninstalling setuptools-54.1.2:\n Successfully uninstalled setuptools-54.1.2\n Attempting uninstall: pyrsistent\n Found existing installation: pyrsistent 0.17.3\n Uninstalling pyrsistent-0.17.3:\n Successfully uninstalled pyrsistent-0.17.3\n Attempting uninstall: importlib-metadata\n Found existing installation: importlib-metadata 3.1.1\n Uninstalling importlib-metadata-3.1.1:\n Successfully uninstalled importlib-metadata-3.1.1\n Attempting uninstall: attrs\n Found existing installation: attrs 20.3.0\n Uninstalling attrs-20.3.0:\n Successfully uninstalled attrs-20.3.0\n Attempting uninstall: tornado\n Found existing installation: tornado 6.1\n Uninstalling tornado-6.1:\n Successfully uninstalled tornado-6.1\n Attempting uninstall: pyzmq\n Found existing installation: pyzmq 22.0.3\n Uninstalling pyzmq-22.0.3:\n Successfully uninstalled pyzmq-22.0.3\n Attempting uninstall: python-dateutil\n Found existing installation: python-dateutil 2.8.1\n Uninstalling python-dateutil-2.8.1:\n Successfully uninstalled python-dateutil-2.8.1\n Attempting uninstall: pyparsing\n Found existing installation: pyparsing 2.4.7\n Uninstalling pyparsing-2.4.7:\n Successfully uninstalled pyparsing-2.4.7\n Attempting uninstall: jupyter-core\n Found existing installation: jupyter-core 4.7.1\n Uninstalling jupyter-core-4.7.1:\n Successfully uninstalled jupyter-core-4.7.1\n Attempting uninstall: jsonschema\n Found existing installation: jsonschema 3.2.0\n Uninstalling jsonschema-3.2.0:\n Successfully uninstalled jsonschema-3.2.0\n Attempting uninstall: webencodings\n Found existing installation: webencodings 0.5.1\n Uninstalling webencodings-0.5.1:\n Successfully uninstalled webencodings-0.5.1\n Attempting uninstall: pygments\n Found existing installation: Pygments 2.8.1\n Uninstalling Pygments-2.8.1:\n Successfully uninstalled Pygments-2.8.1\n Attempting uninstall: packaging\n Found existing installation: packaging 20.9\n Uninstalling packaging-20.9:\n Successfully uninstalled packaging-20.9\n Attempting uninstall: numpy\n Found existing installation: numpy 1.18.5\n Uninstalling numpy-1.18.5:\n Successfully uninstalled numpy-1.18.5\n Attempting uninstall: nest-asyncio\n Found existing installation: nest-asyncio 1.5.1\n Uninstalling nest-asyncio-1.5.1:\n Successfully uninstalled nest-asyncio-1.5.1\n Attempting uninstall: nbformat\n Found existing installation: nbformat 5.1.2\n Uninstalling nbformat-5.1.2:\n Successfully uninstalled nbformat-5.1.2\n Attempting uninstall: MarkupSafe\n Found existing installation: MarkupSafe 1.1.1\n Uninstalling MarkupSafe-1.1.1:\n Successfully uninstalled MarkupSafe-1.1.1\n Attempting uninstall: jupyter-client\n Found existing installation: jupyter-client 6.1.12\n Uninstalling jupyter-client-6.1.12:\n Successfully uninstalled jupyter-client-6.1.12\n Attempting uninstall: async-generator\n Found existing installation: async-generator 1.10\n Uninstalling async-generator-1.10:\n Successfully uninstalled async-generator-1.10\n Attempting uninstall: testpath\n Found existing installation: testpath 0.4.4\n Uninstalling testpath-0.4.4:\n Successfully uninstalled testpath-0.4.4\n Attempting uninstall: scipy\n Found existing installation: scipy 1.4.1\n Uninstalling scipy-1.4.1:\n Successfully uninstalled scipy-1.4.1\n Attempting uninstall: pandocfilters\n Found existing installation: pandocfilters 1.4.3\n Uninstalling pandocfilters-1.4.3:\n Successfully uninstalled pandocfilters-1.4.3\n Attempting uninstall: nbclient\n Found existing installation: nbclient 0.5.3\n Uninstalling nbclient-0.5.3:\n Successfully uninstalled nbclient-0.5.3\n Attempting uninstall: mistune\n Found existing installation: mistune 0.8.4\n Uninstalling mistune-0.8.4:\n Successfully uninstalled mistune-0.8.4\n Attempting uninstall: jupyterlab-pygments\n Found existing installation: jupyterlab-pygments 0.1.2\n Uninstalling jupyterlab-pygments-0.1.2:\n Successfully uninstalled jupyterlab-pygments-0.1.2\n Attempting uninstall: jinja2\n Found existing installation: Jinja2 2.11.3\n Uninstalling Jinja2-2.11.3:\n Successfully uninstalled Jinja2-2.11.3\n Attempting uninstall: h5py\n Found existing installation: h5py 2.10.0\n Uninstalling h5py-2.10.0:\n Successfully uninstalled h5py-2.10.0\n Attempting uninstall: entrypoints\n Found existing installation: entrypoints 0.3\n Uninstalling entrypoints-0.3:\n Successfully uninstalled entrypoints-0.3\n Attempting uninstall: defusedxml\n Found existing installation: defusedxml 0.7.1\n Uninstalling defusedxml-0.7.1:\n Successfully uninstalled defusedxml-0.7.1\n Attempting uninstall: bleach\n Found existing installation: bleach 3.3.0\n Uninstalling bleach-3.3.0:\n Successfully uninstalled bleach-3.3.0\n Attempting uninstall: nbconvert\n Found existing installation: nbconvert 6.0.7\n Uninstalling nbconvert-6.0.7:\n Successfully uninstalled nbconvert-6.0.7\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ntensorflow 2.3.0 requires h5py<2.11.0,>=2.10.0, but you have h5py 3.1.0 which is incompatible.\ntensorflow 2.3.0 requires numpy<1.19.0,>=1.16.0, but you have numpy 1.19.3 which is incompatible.\ntensorflow 2.3.0 requires scipy==1.4.1, but you have scipy 1.5.4 which is incompatible.\u001b[0m\nSuccessfully installed MarkupSafe-1.1.1 ait-sdk-0.1.7 async-generator-1.10 attrs-21.2.0 bleach-3.3.0 cached-property-1.5.2 decorator-5.0.7 defusedxml-0.7.1 entrypoints-0.3 h5py-3.1.0 importlib-metadata-4.0.1 ipython-genutils-0.2.0 jinja2-2.11.3 jsonschema-3.2.0 jupyter-client-6.1.12 jupyter-core-4.7.1 jupyterlab-pygments-0.1.2 keras-2.4.3 mistune-0.8.4 nbclient-0.5.3 nbconvert-6.0.7 nbformat-5.0.8 nest-asyncio-1.5.1 numpy-1.19.3 packaging-20.9 pandocfilters-1.4.3 psutil-5.7.3 py-cpuinfo-7.0.0 pygments-2.9.0 pyparsing-2.4.7 pyrsistent-0.17.3 python-dateutil-2.8.1 pyyaml-5.4.1 pyzmq-22.0.3 scipy-1.5.4 setuptools-56.2.0 six-1.16.0 testpath-0.4.4 tornado-6.1 traitlets-4.3.3 typing-extensions-3.10.0.0 webencodings-0.5.1 zipp-3.4.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 pathlib import Path\nimport pprint\nfrom ait_sdk.test.hepler import Helper\nimport json","_____no_output_____"],["# settings cell\n\n# mounted dir\nroot_dir = Path('/workdir/root/ait')\n\nait_name='eval_metamorphic_test_tf1.13'\nait_version='0.1'\n\nait_full_name=f'{ait_name}_{ait_version}'\nait_dir = root_dir / ait_full_name\n\ntd_name=f'{ait_name}_test'\n\n# (dockerホスト側の)インベントリ登録用アセット格納ルートフォルダ\ncurrent_dir = %pwd\nwith open(f'{current_dir}/config.json', encoding='utf-8') as f:\n json_ = json.load(f)\n root_dir = json_['host_ait_root_dir']\n is_container = json_['is_container']\ninvenotory_root_dir = f'{root_dir}\\\\ait\\\\{ait_full_name}\\\\local_qai\\\\inventory'\n\n# entry point address\n# コンテナ起動かどうかでポート番号が変わるため、切り替える\nif is_container:\n backend_entry_point = 'http://host.docker.internal:8888/qai-testbed/api/0.0.1'\n ip_entry_point = 'http://host.docker.internal:8888/qai-ip/api/0.0.1'\nelse:\n backend_entry_point = 'http://host.docker.internal:5000/qai-testbed/api/0.0.1'\n ip_entry_point = 'http://host.docker.internal:6000/qai-ip/api/0.0.1'\n\n# aitのデプロイフラグ\n# 一度実施すれば、それ以降は実施しなくてOK\nis_init_ait = True\n\n# インベントリの登録フラグ\n# 一度実施すれば、それ以降は実施しなくてOK\nis_init_inventory = True\n","_____no_output_____"],["helper = Helper(backend_entry_point=backend_entry_point, \n ip_entry_point=ip_entry_point,\n ait_dir=ait_dir,\n ait_full_name=ait_full_name)","_____no_output_____"],["# health check\n\nhelper.get_bk('/health-check')\nhelper.get_ip('/health-check')","
\n\nSeu objetivo é encontrar a resposta de uma ou mais perguntas de acordo com uma lista de contextos distintos.\n\nA tabela de dados de entrada deve possuir uma coluna de contextos, em que cada linha representa um contexto diferente, e uma coluna de perguntas em que cada linha representa uma pergunta a ser realizada. Note que para cada pergunta serão utilizados todos os contextos fornecidos para realização da inferência, e portanto, podem haver bem mais contextos do que perguntas.\n\nObs: Este componente utiliza recursos da internet, portanto é importante estar conectado à rede para que este componente funcione corretamente.
\n### **Em caso de dúvidas, consulte os [tutoriais da PlatIAgro](https://platiagro.github.io/tutorials/).**","_____no_output_____"],["## Declaração de Classe para Predições em Tempo Real\n\nA tarefa de implantação cria um serviço REST para predições em tempo-real.
\nPara isso você deve criar uma classe `Model` que implementa o método `predict`.","_____no_output_____"]],[["%%writefile Model.py\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom reader import Reader\n\nclass Model:\n def __init__(self):\n self.loaded = False\n\n def load(self):\n \n # Load artifacts\n artifacts = joblib.load(\"/tmp/data/reader.joblib\")\n self.model_parameters = artifacts[\"model_parameters\"]\n self.inference_parameters = artifacts[\"inference_parameters\"]\n \n # Initialize reader\n self.reader = Reader(**self.model_parameters)\n \n # Set model loaded\n self.loaded = True\n print(\"Loaded model\")\n \n def class_names(self):\n column_names = list(self.inference_parameters['output_columns'])\n return column_names\n\n def predict(self, X, feature_names, meta=None):\n if not self.loaded:\n self.load()\n \n # Convert to dataframe\n if feature_names != []:\n df = pd.DataFrame(X, columns = feature_names)\n df = df[self.inference_parameters['input_columns']]\n else:\n df = pd.DataFrame(X, columns = self.inference_parameters['input_columns'])\n \n # Predict answers #\n\n # Iterate over dataset\n for idx, row in df.iterrows():\n\n # Get question\n question = row[self.inference_parameters['question_column_name']]\n\n # Get context\n context = row[self.inference_parameters['context_column_name']]\n\n # Make prediction\n answer, probability, _ = self.reader([question], [context])\n\n # Save to df\n df.at[idx, self.inference_parameters['answer_column_name']] = answer[0]\n df.at[idx, self.inference_parameters['proba_column_name']] = probability[0]\n\n # Retrieve Only Best Answer #\n\n # Initializate best df\n best_df = pd.DataFrame(columns=df.columns)\n\n # Get unique questions\n unique_questions = df[self.inference_parameters['question_column_name']].unique()\n\n # Iterate over each unique question\n for question in unique_questions:\n\n # Filter df\n question_df = df[df[self.inference_parameters['question_column_name']] == question]\n\n # Sort by score (descending)\n question_df = question_df.sort_values(by=self.inference_parameters['proba_column_name'], ascending=False).reset_index(drop=True)\n\n # Append best ansewer to output df\n best_df = pd.concat((best_df,pd.DataFrame(question_df.loc[0]).T)).reset_index(drop=True)\n \n if self.inference_parameters['keep_best'] == 'sim':\n return best_df.values\n else:\n return df.values","Overwriting Model.py\n"]]],"string":"[\n [\n [\n \"# Reader - Implantação\\n\\nEste componente utiliza um modelo de QA pré-treinado em Português com o dataset SQuAD v1.1, é um modelo de domínio público disponível em [Hugging Face](https://huggingface.co/pierreguillou/bert-large-cased-squad-v1.1-portuguese).
\\n\\nSeu objetivo é encontrar a resposta de uma ou mais perguntas de acordo com uma lista de contextos distintos.\\n\\nA tabela de dados de entrada deve possuir uma coluna de contextos, em que cada linha representa um contexto diferente, e uma coluna de perguntas em que cada linha representa uma pergunta a ser realizada. Note que para cada pergunta serão utilizados todos os contextos fornecidos para realização da inferência, e portanto, podem haver bem mais contextos do que perguntas.\\n\\nObs: Este componente utiliza recursos da internet, portanto é importante estar conectado à rede para que este componente funcione corretamente.
\\n### **Em caso de dúvidas, consulte os [tutoriais da PlatIAgro](https://platiagro.github.io/tutorials/).**\",\n \"_____no_output_____\"\n ],\n [\n \"## Declaração de Classe para Predições em Tempo Real\\n\\nA tarefa de implantação cria um serviço REST para predições em tempo-real.
\\nPara isso você deve criar uma classe `Model` que implementa o método `predict`.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"%%writefile Model.py\\n\\nimport joblib\\nimport numpy as np\\nimport pandas as pd\\nfrom reader import Reader\\n\\nclass Model:\\n def __init__(self):\\n self.loaded = False\\n\\n def load(self):\\n \\n # Load artifacts\\n artifacts = joblib.load(\\\"/tmp/data/reader.joblib\\\")\\n self.model_parameters = artifacts[\\\"model_parameters\\\"]\\n self.inference_parameters = artifacts[\\\"inference_parameters\\\"]\\n \\n # Initialize reader\\n self.reader = Reader(**self.model_parameters)\\n \\n # Set model loaded\\n self.loaded = True\\n print(\\\"Loaded model\\\")\\n \\n def class_names(self):\\n column_names = list(self.inference_parameters['output_columns'])\\n return column_names\\n\\n def predict(self, X, feature_names, meta=None):\\n if not self.loaded:\\n self.load()\\n \\n # Convert to dataframe\\n if feature_names != []:\\n df = pd.DataFrame(X, columns = feature_names)\\n df = df[self.inference_parameters['input_columns']]\\n else:\\n df = pd.DataFrame(X, columns = self.inference_parameters['input_columns'])\\n \\n # Predict answers #\\n\\n # Iterate over dataset\\n for idx, row in df.iterrows():\\n\\n # Get question\\n question = row[self.inference_parameters['question_column_name']]\\n\\n # Get context\\n context = row[self.inference_parameters['context_column_name']]\\n\\n # Make prediction\\n answer, probability, _ = self.reader([question], [context])\\n\\n # Save to df\\n df.at[idx, self.inference_parameters['answer_column_name']] = answer[0]\\n df.at[idx, self.inference_parameters['proba_column_name']] = probability[0]\\n\\n # Retrieve Only Best Answer #\\n\\n # Initializate best df\\n best_df = pd.DataFrame(columns=df.columns)\\n\\n # Get unique questions\\n unique_questions = df[self.inference_parameters['question_column_name']].unique()\\n\\n # Iterate over each unique question\\n for question in unique_questions:\\n\\n # Filter df\\n question_df = df[df[self.inference_parameters['question_column_name']] == question]\\n\\n # Sort by score (descending)\\n question_df = question_df.sort_values(by=self.inference_parameters['proba_column_name'], ascending=False).reset_index(drop=True)\\n\\n # Append best ansewer to output df\\n best_df = pd.concat((best_df,pd.DataFrame(question_df.loc[0]).T)).reset_index(drop=True)\\n \\n if self.inference_parameters['keep_best'] == 'sim':\\n return best_df.values\\n else:\\n return df.values\",\n \"Overwriting Model.py\\n\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code"],"string":"[\n \"markdown\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown","markdown"],["code"]],"string":"[\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\"\n ]\n]"}}},{"rowIdx":589,"cells":{"hexsha":{"kind":"string","value":"d01adf518daccca71b47da8482f0e2946bc01cab"},"size":{"kind":"number","value":164842,"string":"164,842"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"analysis/simulation/estimator_validation.ipynb"},"max_stars_repo_name":{"kind":"string","value":"yelabucsf/scrna-parameter-estimation"},"max_stars_repo_head_hexsha":{"kind":"string","value":"218ef38b87f8d777d5abcb04913212cbcb21ecb1"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":2,"string":"2"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2021-03-17T20:31:54.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2022-03-17T19:24:37.000Z"},"max_issues_repo_path":{"kind":"string","value":"analysis/simulation/estimator_validation.ipynb"},"max_issues_repo_name":{"kind":"string","value":"yelabucsf/scrna-parameter-estimation"},"max_issues_repo_head_hexsha":{"kind":"string","value":"218ef38b87f8d777d5abcb04913212cbcb21ecb1"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"number","value":1,"string":"1"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2021-08-23T20:55:07.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2021-08-23T20:55:07.000Z"},"max_forks_repo_path":{"kind":"string","value":"analysis/simulation/estimator_validation.ipynb"},"max_forks_repo_name":{"kind":"string","value":"yelabucsf/scrna-parameter-estimation"},"max_forks_repo_head_hexsha":{"kind":"string","value":"218ef38b87f8d777d5abcb04913212cbcb21ecb1"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"number","value":1,"string":"1"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2020-04-06T05:43:31.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2020-04-06T05:43:31.000Z"},"avg_line_length":{"kind":"number","value":170.291322314,"string":"170.291322"},"max_line_length":{"kind":"number","value":32536,"string":"32,536"},"alphanum_fraction":{"kind":"number","value":0.884798777,"string":"0.884799"},"cells":{"kind":"list like","value":[[["# Estimator validation\n\nThis notebook contains code to generate Figure 2 of the paper. \n\nThis notebook also serves to compare the estimates of the re-implemented scmemo with sceb package from Vasilis. \n","_____no_output_____"]],[["import pandas as pd\nimport matplotlib.pyplot as plt\nimport scanpy as sc\nimport scipy as sp\nimport itertools\nimport numpy as np\nimport scipy.stats as stats\nfrom scipy.integrate import dblquad\nimport seaborn as sns\nfrom statsmodels.stats.multitest import fdrcorrection\nimport imp\npd.options.display.max_rows = 999\npd.set_option('display.max_colwidth', -1)\nimport pickle as pkl\nimport time","_____no_output_____"],["import matplotlib as mpl\nmpl.rcParams['pdf.fonttype'] = 42\nmpl.rcParams['ps.fonttype'] = 42\n\nimport matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'x-small',\n 'axes.labelsize': 'medium',\n 'axes.titlesize':'medium',\n 'figure.titlesize':'medium',\n 'xtick.labelsize':'xx-small',\n 'ytick.labelsize':'xx-small'}\npylab.rcParams.update(params)\n","_____no_output_____"],["import sys\nsys.path.append('/data/home/Github/scrna-parameter-estimation/dist/schypo-0.0.0-py3.7.egg')\nimport schypo\nimport schypo.simulate as simulate","/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/scanpy/api/__init__.py:6: FutureWarning: \n\nIn a future version of Scanpy, `scanpy.api` will be removed.\nSimply use `import scanpy as sc` and `import scanpy.external as sce` instead.\n\n FutureWarning,\n"],["import sys\nsys.path.append('/data/home/Github/single_cell_eb/')\nsys.path.append('/data/home/Github/single_cell_eb/sceb/')\nimport scdd","_____no_output_____"],["data_path = '/data/parameter_estimation/'\nfig_path = '/data/home/Github/scrna-parameter-estimation/figures/fig3/'","_____no_output_____"]],[["### Check 1D estimates of `sceb` with `scmemo`\n\nUsing the Poisson model. The outputs should be identical, this is for checking the implementation. ","_____no_output_____"]],[["data = sp.sparse.csr_matrix(simulate.simulate_transcriptomes(100, 20))\nadata = sc.AnnData(data)\nsize_factors = scdd.dd_size_factor(adata)\nNr = data.sum(axis=1).mean()","_____no_output_____"],["_, M_dd = scdd.dd_1d_moment(adata, size_factor=scdd.dd_size_factor(adata), Nr=Nr)\nvar_scdd = scdd.M_to_var(M_dd)\nprint(var_scdd)","_____no_output_____"],["imp.reload(estimator)\nmean_scmemo, var_scmemo = estimator._poisson_1d(data, data.shape[0], estimator._estimate_size_factor(data))\nprint(var_scmemo)","_____no_output_____"],["df = pd.DataFrame()\ndf['size_factor'] = size_factors\ndf['inv_size_factor'] = 1/size_factors\ndf['inv_size_factor_sq'] = 1/size_factors**2\ndf['expr'] = data[:, 0].todense().A1\nprecomputed_size_factors = df.groupby('expr')['inv_size_factor'].mean(), df.groupby('expr')['inv_size_factor_sq'].mean()","_____no_output_____"],["imp.reload(estimator)\nexpr, count = np.unique(data[:, 0].todense().A1, return_counts=True)\nprint(estimator._poisson_1d((expr, count), data.shape[0], precomputed_size_factors))","[0.5217290008068085, 0.9860336223993191]\n"]],[["### Check 2D estimates of `sceb` and `scmemo`\n\nUsing the Poisson model. The outputs should be identical, this is for checking the implementation. ","_____no_output_____"]],[["data = sp.sparse.csr_matrix(simulate.simulate_transcriptomes(1000, 4))\nadata = sc.AnnData(data)\nsize_factors = scdd.dd_size_factor(adata)","_____no_output_____"],["mean_scdd, cov_scdd, corr_scdd = scdd.dd_covariance(adata, size_factors)\nprint(cov_scdd)","[[ 9.66801891 -1.45902975 -1.97166503 -10.13305759]\n [ -1.45902975 3.37530982 -0.83509601 -2.76389597]\n [ -1.97166503 -0.83509601 2.51976446 -2.9553916 ]\n [-10.13305759 -2.76389597 -2.9553916 1.48619472]]\n"],["imp.reload(estimator)\ncov_scmemo = estimator._poisson_cov(data, data.shape[0], size_factors, idx1=[0, 1, 2], idx2=[1, 2, 3])\nprint(cov_scmemo)","[[ -1.45902975 -1.97166503 -10.13305759]\n [ 3.37530982 -0.83509601 -2.76389597]\n [ -0.83509601 2.51976446 -2.9553916 ]]\n"],["expr, count = np.unique(data[:, :2].toarray(), return_counts=True, axis=0)\n\ndf = pd.DataFrame()\ndf['size_factor'] = size_factors\ndf['inv_size_factor'] = 1/size_factors\ndf['inv_size_factor_sq'] = 1/size_factors**2\ndf['expr1'] = data[:, 0].todense().A1\ndf['expr2'] = data[:, 1].todense().A1\n\nprecomputed_size_factors = df.groupby(['expr1', 'expr2'])['inv_size_factor'].mean(), df.groupby(['expr1', 'expr2'])['inv_size_factor_sq'].mean()","/home/ssm-user/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in true_divide\n \"\"\"\n/home/ssm-user/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:6: RuntimeWarning: divide by zero encountered in true_divide\n \n"],["cov_scmemo = estimator._poisson_cov((expr[:, 0], expr[:, 1], count), data.shape[0], size_factor=precomputed_size_factors)\nprint(cov_scmemo)","-1.4590297282462616\n"]],[["### Extract parameters from interferon dataset","_____no_output_____"]],[["adata = sc.read(data_path + 'interferon_filtered.h5ad')\nadata = adata[adata.obs.cell_type == 'CD4 T cells - ctrl']\ndata = adata.X.copy()\nrelative_data = data.toarray()/data.sum(axis=1)","_____no_output_____"],["q = 0.07\nx_param, z_param, Nc, good_idx = schypo.simulate.extract_parameters(adata.X, q=q, min_mean=q)","_____no_output_____"],["imp.reload(simulate)\n\ntranscriptome = simulate.simulate_transcriptomes(\n n_cells=10000, \n means=z_param[0],\n variances=z_param[1],\n corr=x_param[2],\n Nc=Nc)\nrelative_transcriptome = transcriptome/transcriptome.sum(axis=1).reshape(-1, 1)\n\nqs, captured_data = simulate.capture_sampling(transcriptome, q=q, q_sq=q**2+1e-10)","_____no_output_____"],["def qqplot(x, y, s=1):\n \n plt.scatter(\n np.quantile(x, np.linspace(0, 1, 1000)),\n np.quantile(y, np.linspace(0, 1, 1000)),\n s=s)\n\n plt.plot(x, x, lw=1, color='m')","_____no_output_____"],["plt.figure(figsize=(8, 2));\nplt.subplots_adjust(wspace=0.2);\n\nplt.subplot(1, 3, 1);\nsns.distplot(np.log(captured_data.mean(axis=0)), hist=False, label='Simulated')\nsns.distplot(np.log(data[:, good_idx].toarray().var(axis=0)), hist=False, label='Real')\nplt.xlabel('Log(mean)')\n\nplt.subplot(1, 3, 2);\nsns.distplot(np.log(captured_data.var(axis=0)), hist=False)\nsns.distplot(np.log(data[:, good_idx].toarray().var(axis=0)), hist=False)\nplt.xlabel('Log(variance)')\n\nplt.subplot(1, 3, 3);\nsns.distplot(np.log(captured_data.sum(axis=1)), hist=False)\nsns.distplot(np.log(data.toarray().sum(axis=1)), hist=False)\nplt.xlabel('Log(total UMI count)')\n\nplt.savefig(figpath + 'simulation_stats.png', bbox_inches='tight')","_____no_output_____"]],[["### Compare datasets generated by Poisson and hypergeometric processes","_____no_output_____"]],[["_, poi_captured = simulate.capture_sampling(transcriptome, q=q, process='poisson')\n_, hyper_captured = simulate.capture_sampling(transcriptome, q=q, process='hyper')","_____no_output_____"],["q_list = [0.05, 0.1, 0.2, 0.3, 0.5]","_____no_output_____"],["plt.figure(figsize=(8, 2))\nplt.subplots_adjust(wspace=0.3)\nfor idx, q in enumerate(q_list):\n \n _, poi_captured = simulate.capture_sampling(transcriptome, q=q, process='poisson')\n _, hyper_captured = simulate.capture_sampling(transcriptome, q=q, process='hyper')\n relative_poi_captured = poi_captured/poi_captured.sum(axis=1).reshape(-1, 1)\n relative_hyper_captured = hyper_captured/hyper_captured.sum(axis=1).reshape(-1, 1)\n \n poi_corr = np.corrcoef(relative_poi_captured, rowvar=False)\n hyper_corr = np.corrcoef(relative_hyper_captured, rowvar=False)\n\n sample_idx = np.random.choice(poi_corr.ravel().shape[0], 100000)\n \n plt.subplot(1, len(q_list), idx+1)\n plt.scatter(poi_corr.ravel()[sample_idx], hyper_corr.ravel()[sample_idx], s=1, alpha=1)\n plt.plot([-1, 1], [-1, 1], 'm', lw=1)\n# plt.xlim([-0.3, 0.4])\n# plt.ylim([-0.3, 0.4])\n \n if idx != 0:\n plt.yticks([])\n plt.title('q={}'.format(q))\nplt.savefig(figpath + 'poi_vs_hyp_sim_corr.png', bbox_inches='tight')","_____no_output_____"]],[["### Compare Poisson vs HG estimators","_____no_output_____"]],[["def compare_esimators(q, plot=False, true_data=None, var_q=1e-10):\n \n q_sq = var_q + q**2\n \n true_data = schypo.simulate.simulate_transcriptomes(1000, 1000, correlated=True) if true_data is None else true_data\n true_relative_data = true_data / true_data.sum(axis=1).reshape(-1, 1)\n\n qs, captured_data = schypo.simulate.capture_sampling(true_data, q, q_sq)\n Nr = captured_data.sum(axis=1).mean()\n captured_relative_data = captured_data/captured_data.sum(axis=1).reshape(-1, 1)\n adata = sc.AnnData(sp.sparse.csr_matrix(captured_data))\n sf = schypo.estimator._estimate_size_factor(adata.X, 'hyper_relative', total=True)\n\n good_idx = (captured_data.mean(axis=0) > q)\n\n # True moments\n m_true, v_true, corr_true = true_relative_data.mean(axis=0), true_relative_data.var(axis=0), np.corrcoef(true_relative_data, rowvar=False)\n rv_true = v_true/m_true**2#schypo.estimator._residual_variance(m_true, v_true, schypo.estimator._fit_mv_regressor(m_true, v_true))\n \n # Compute 1D moments\n m_obs, v_obs = captured_relative_data.mean(axis=0), captured_relative_data.var(axis=0)\n rv_obs = v_obs/m_obs**2#schypo.estimator._residual_variance(m_obs, v_obs, schypo.estimator._fit_mv_regressor(m_obs, v_obs))\n m_poi, v_poi = schypo.estimator._poisson_1d_relative(adata.X, size_factor=sf, n_obs=true_data.shape[0])\n rv_poi = v_poi/m_poi**2#schypo.estimator._residual_variance(m_poi, v_poi, schypo.estimator._fit_mv_regressor(m_poi, v_poi))\n m_hyp, v_hyp = schypo.estimator._hyper_1d_relative(adata.X, size_factor=sf, n_obs=true_data.shape[0], q=q)\n rv_hyp = v_hyp/m_hyp**2#schypo.estimator._residual_variance(m_hyp, v_hyp, schypo.estimator._fit_mv_regressor(m_hyp, v_hyp))\n\n # Compute 2D moments\n corr_obs = np.corrcoef(captured_relative_data, rowvar=False)\n# corr_obs = corr_obs[np.triu_indices(corr_obs.shape[0])]\n \n idx1 = np.array([i for i,j in itertools.combinations(range(adata.shape[1]), 2) if good_idx[i] and good_idx[j]])\n idx2 = np.array([j for i,j in itertools.combinations(range(adata.shape[1]), 2) if good_idx[i] and good_idx[j]])\n sample_idx = np.random.choice(idx1.shape[0], 10000)\n \n idx1 = idx1[sample_idx]\n idx2 = idx2[sample_idx]\n\n corr_true = corr_true[(idx1, idx2)]\n corr_obs = corr_obs[(idx1, idx2)]\n \n cov_poi = schypo.estimator._poisson_cov_relative(adata.X, n_obs=adata.shape[0], size_factor=sf, idx1=idx1, idx2=idx2)\n cov_hyp = schypo.estimator._hyper_cov_relative(adata.X, n_obs=adata.shape[0], size_factor=sf, idx1=idx1, idx2=idx2, q=q)\n corr_poi = schypo.estimator._corr_from_cov(cov_poi, v_poi[idx1], v_poi[idx2])\n corr_hyp = schypo.estimator._corr_from_cov(cov_hyp, v_hyp[idx1], v_hyp[idx2])\n\n corr_poi[np.abs(corr_poi) > 1] = np.nan\n corr_hyp[np.abs(corr_hyp) > 1] = np.nan\n\n mean_list = [m_obs, m_poi, m_hyp]\n var_list = [rv_obs, rv_poi, rv_hyp]\n corr_list = [corr_obs, corr_poi, corr_hyp]\n estimated_list = [mean_list, var_list, corr_list]\n true_list = [m_true, rv_true, corr_true]\n\n if plot:\n count = 0\n for j in range(3):\n for i in range(3):\n\n plt.subplot(3, 3, count+1)\n\n\n if i != 2:\n plt.scatter(\n np.log(true_list[i][good_idx]),\n np.log(estimated_list[i][j][good_idx]),\n s=0.1)\n plt.plot(np.log(true_list[i][good_idx]), np.log(true_list[i][good_idx]), linestyle='--', color='m')\n plt.xlim(np.log(true_list[i][good_idx]).min(), np.log(true_list[i][good_idx]).max())\n plt.ylim(np.log(true_list[i][good_idx]).min(), np.log(true_list[i][good_idx]).max())\n\n else:\n\n x = true_list[i]\n y = estimated_list[i][j]\n \n print(x.shape, y.shape)\n\n plt.scatter(\n x,\n y,\n s=0.1)\n plt.plot([-1, 1], [-1, 1],linestyle='--', color='m')\n plt.xlim(-1, 1);\n plt.ylim(-1, 1);\n \n# if not (i == j):\n# plt.yticks([]);\n# plt.xticks([]);\n \n if i == 1 or i == 0:\n \n print((np.log(true_list[i][good_idx]) > np.log(estimated_list[i][j][good_idx])).mean())\n\n count += 1\n else:\n return qs, good_idx, estimated_list, true_list","_____no_output_____"],["import matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'small',\n 'axes.labelsize': 'medium',\n 'axes.titlesize':'medium',\n 'figure.titlesize':'medium',\n 'xtick.labelsize':'xx-small',\n 'ytick.labelsize':'xx-small'}\npylab.rcParams.update(params)","_____no_output_____"]],[["imp.reload(simulate)\n\nq = 0.4\nplt.figure(figsize=(4, 4))\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\ntrue_data = simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1],\n corr=x_param[2],\n Nc=Nc)\ncompare_esimators(q, plot=True, true_data=true_data)\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_2.png', bbox_inches='tight')","_____no_output_____"]],[["true_data = schypo.simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1], Nc=Nc)","_____no_output_____"],["q = 0.025\nplt.figure(figsize=(4, 4))\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\ncompare_esimators(q, plot=True, true_data=true_data)\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_rv_2.5.png', bbox_inches='tight', dpi=1200)","/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:67: RuntimeWarning: invalid value encountered in log\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:94: RuntimeWarning: invalid value encountered in log\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:94: RuntimeWarning: invalid value encountered in greater\n"],["q = 0.4\nplt.figure(figsize=(4, 4))\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\ncompare_esimators(q, plot=True, true_data=true_data)\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_rv_40.png', bbox_inches='tight', dpi=1200)","/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n"],["def compute_mse(x, y, log=True):\n \n if log:\n return np.nanmean(np.abs(np.log(x)-np.log(y)))\n else:\n return np.nanmean(np.abs(x-y))\n\ndef concordance(x, y, log=True):\n \n if log:\n a = np.log(x)\n b = np.log(y)\n else:\n a = x\n b = y\n cond = np.isfinite(a) & np.isfinite(b)\n a = a[cond]\n b = b[cond]\n cmat = np.cov(a, b)\n return 2*cmat[0,1]/(cmat[0,0] + cmat[1,1] + (a.mean()-b.mean())**2)\n \nm_mse_list, v_mse_list, c_mse_list = [], [], []\n# true_data = schypo.simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1],\n# Nc=Nc)\nq_list = [0.01, 0.025, 0.1, 0.15, 0.3, 0.5, 0.7, 0.99]\nqs_list = []\nfor q in q_list:\n qs, good_idx, est, true = compare_esimators(q, plot=False, true_data=true_data)\n qs_list.append(qs)\n m_mse_list.append([concordance(x[good_idx], true[0][good_idx]) for x in est[0]])\n v_mse_list.append([concordance(x[good_idx], true[1][good_idx]) for x in est[1]])\n c_mse_list.append([concordance(x, true[2], log=False) for x in est[2]])\n \nm_mse_list, v_mse_list, c_mse_list = np.array(m_mse_list), np.array(v_mse_list), np.array(c_mse_list)","/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\n # This is added back by InteractiveShellApp.init_path()\n"],["import matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'small',\n 'axes.labelsize': 'medium',\n 'axes.titlesize':'medium',\n 'figure.titlesize':'medium',\n 'xtick.labelsize':'small',\n 'ytick.labelsize':'small'}\npylab.rcParams.update(params)\n\nplt.figure(figsize=(8, 3))\nplt.subplots_adjust(wspace=0.5)\n\nplt.subplot(1, 3, 1)\nplt.plot(q_list[1:], m_mse_list[:, 0][1:], '-o')\n# plt.legend(['Naive,\\nPoisson,\\nHG'])\nplt.ylabel('CCC log(mean)')\nplt.xlabel('overall UMI efficiency (q)')\n\nplt.subplot(1, 3, 2)\nplt.plot(q_list[2:], v_mse_list[:, 0][2:], '-o')\nplt.plot(q_list[2:], v_mse_list[:, 1][2:], '-o')\nplt.plot(q_list[2:], v_mse_list[:, 2][2:], '-o')\nplt.legend(['Naive', 'Poisson', 'HG'], ncol=3, loc='upper center', bbox_to_anchor=(0.4,1.15))\nplt.ylabel('CCC log(variance)')\nplt.xlabel('overall UMI efficiency (q)')\n\nplt.subplot(1, 3, 3)\nplt.plot(q_list[2:], c_mse_list[:, 0][2:], '-o')\nplt.plot(q_list[2:], c_mse_list[:, 1][2:], '-o')\nplt.plot(q_list[2:], c_mse_list[:, 2][2:], '-o')\n# plt.legend(['Naive', 'Poisson', 'HG'])\nplt.ylabel('CCC correlation')\nplt.xlabel('overall UMI efficiency (q)')\n\nplt.savefig(fig_path + 'poi_vs_hyper_rv_ccc.pdf', bbox_inches='tight')","_____no_output_____"],["plt.figure(figsize=(1, 1.3))\nplt.plot(q_list, v_mse_list[:, 0], '-o', ms=4)\nplt.plot(q_list, v_mse_list[:, 1], '-o', ms=4)\nplt.plot(q_list, v_mse_list[:, 2], '-o', ms=4)\n\nplt.savefig(fig_path + 'poi_vs_hyper_ccc_var_rv_inset.pdf', bbox_inches='tight')","_____no_output_____"],["plt.figure(figsize=(1, 1.3))\nplt.plot(q_list, c_mse_list[:, 0], '-o', ms=4)\nplt.plot(q_list, c_mse_list[:, 1], '-o', ms=4)\nplt.plot(q_list, c_mse_list[:, 2], '-o', ms=4)\nplt.savefig(fig_path + 'poi_vs_hyper_ccc_corr_inset.pdf', bbox_inches='tight')","_____no_output_____"]]],"string":"[\n [\n [\n \"# Estimator validation\\n\\nThis notebook contains code to generate Figure 2 of the paper. \\n\\nThis notebook also serves to compare the estimates of the re-implemented scmemo with sceb package from Vasilis. \\n\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"import pandas as pd\\nimport matplotlib.pyplot as plt\\nimport scanpy as sc\\nimport scipy as sp\\nimport itertools\\nimport numpy as np\\nimport scipy.stats as stats\\nfrom scipy.integrate import dblquad\\nimport seaborn as sns\\nfrom statsmodels.stats.multitest import fdrcorrection\\nimport imp\\npd.options.display.max_rows = 999\\npd.set_option('display.max_colwidth', -1)\\nimport pickle as pkl\\nimport time\",\n \"_____no_output_____\"\n ],\n [\n \"import matplotlib as mpl\\nmpl.rcParams['pdf.fonttype'] = 42\\nmpl.rcParams['ps.fonttype'] = 42\\n\\nimport matplotlib.pylab as pylab\\nparams = {'legend.fontsize': 'x-small',\\n 'axes.labelsize': 'medium',\\n 'axes.titlesize':'medium',\\n 'figure.titlesize':'medium',\\n 'xtick.labelsize':'xx-small',\\n 'ytick.labelsize':'xx-small'}\\npylab.rcParams.update(params)\\n\",\n \"_____no_output_____\"\n ],\n [\n \"import sys\\nsys.path.append('/data/home/Github/scrna-parameter-estimation/dist/schypo-0.0.0-py3.7.egg')\\nimport schypo\\nimport schypo.simulate as simulate\",\n \"/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/scanpy/api/__init__.py:6: FutureWarning: \\n\\nIn a future version of Scanpy, `scanpy.api` will be removed.\\nSimply use `import scanpy as sc` and `import scanpy.external as sce` instead.\\n\\n FutureWarning,\\n\"\n ],\n [\n \"import sys\\nsys.path.append('/data/home/Github/single_cell_eb/')\\nsys.path.append('/data/home/Github/single_cell_eb/sceb/')\\nimport scdd\",\n \"_____no_output_____\"\n ],\n [\n \"data_path = '/data/parameter_estimation/'\\nfig_path = '/data/home/Github/scrna-parameter-estimation/figures/fig3/'\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Check 1D estimates of `sceb` with `scmemo`\\n\\nUsing the Poisson model. The outputs should be identical, this is for checking the implementation. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"data = sp.sparse.csr_matrix(simulate.simulate_transcriptomes(100, 20))\\nadata = sc.AnnData(data)\\nsize_factors = scdd.dd_size_factor(adata)\\nNr = data.sum(axis=1).mean()\",\n \"_____no_output_____\"\n ],\n [\n \"_, M_dd = scdd.dd_1d_moment(adata, size_factor=scdd.dd_size_factor(adata), Nr=Nr)\\nvar_scdd = scdd.M_to_var(M_dd)\\nprint(var_scdd)\",\n \"_____no_output_____\"\n ],\n [\n \"imp.reload(estimator)\\nmean_scmemo, var_scmemo = estimator._poisson_1d(data, data.shape[0], estimator._estimate_size_factor(data))\\nprint(var_scmemo)\",\n \"_____no_output_____\"\n ],\n [\n \"df = pd.DataFrame()\\ndf['size_factor'] = size_factors\\ndf['inv_size_factor'] = 1/size_factors\\ndf['inv_size_factor_sq'] = 1/size_factors**2\\ndf['expr'] = data[:, 0].todense().A1\\nprecomputed_size_factors = df.groupby('expr')['inv_size_factor'].mean(), df.groupby('expr')['inv_size_factor_sq'].mean()\",\n \"_____no_output_____\"\n ],\n [\n \"imp.reload(estimator)\\nexpr, count = np.unique(data[:, 0].todense().A1, return_counts=True)\\nprint(estimator._poisson_1d((expr, count), data.shape[0], precomputed_size_factors))\",\n \"[0.5217290008068085, 0.9860336223993191]\\n\"\n ]\n ],\n [\n [\n \"### Check 2D estimates of `sceb` and `scmemo`\\n\\nUsing the Poisson model. The outputs should be identical, this is for checking the implementation. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"data = sp.sparse.csr_matrix(simulate.simulate_transcriptomes(1000, 4))\\nadata = sc.AnnData(data)\\nsize_factors = scdd.dd_size_factor(adata)\",\n \"_____no_output_____\"\n ],\n [\n \"mean_scdd, cov_scdd, corr_scdd = scdd.dd_covariance(adata, size_factors)\\nprint(cov_scdd)\",\n \"[[ 9.66801891 -1.45902975 -1.97166503 -10.13305759]\\n [ -1.45902975 3.37530982 -0.83509601 -2.76389597]\\n [ -1.97166503 -0.83509601 2.51976446 -2.9553916 ]\\n [-10.13305759 -2.76389597 -2.9553916 1.48619472]]\\n\"\n ],\n [\n \"imp.reload(estimator)\\ncov_scmemo = estimator._poisson_cov(data, data.shape[0], size_factors, idx1=[0, 1, 2], idx2=[1, 2, 3])\\nprint(cov_scmemo)\",\n \"[[ -1.45902975 -1.97166503 -10.13305759]\\n [ 3.37530982 -0.83509601 -2.76389597]\\n [ -0.83509601 2.51976446 -2.9553916 ]]\\n\"\n ],\n [\n \"expr, count = np.unique(data[:, :2].toarray(), return_counts=True, axis=0)\\n\\ndf = pd.DataFrame()\\ndf['size_factor'] = size_factors\\ndf['inv_size_factor'] = 1/size_factors\\ndf['inv_size_factor_sq'] = 1/size_factors**2\\ndf['expr1'] = data[:, 0].todense().A1\\ndf['expr2'] = data[:, 1].todense().A1\\n\\nprecomputed_size_factors = df.groupby(['expr1', 'expr2'])['inv_size_factor'].mean(), df.groupby(['expr1', 'expr2'])['inv_size_factor_sq'].mean()\",\n \"/home/ssm-user/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in true_divide\\n \\\"\\\"\\\"\\n/home/ssm-user/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:6: RuntimeWarning: divide by zero encountered in true_divide\\n \\n\"\n ],\n [\n \"cov_scmemo = estimator._poisson_cov((expr[:, 0], expr[:, 1], count), data.shape[0], size_factor=precomputed_size_factors)\\nprint(cov_scmemo)\",\n \"-1.4590297282462616\\n\"\n ]\n ],\n [\n [\n \"### Extract parameters from interferon dataset\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"adata = sc.read(data_path + 'interferon_filtered.h5ad')\\nadata = adata[adata.obs.cell_type == 'CD4 T cells - ctrl']\\ndata = adata.X.copy()\\nrelative_data = data.toarray()/data.sum(axis=1)\",\n \"_____no_output_____\"\n ],\n [\n \"q = 0.07\\nx_param, z_param, Nc, good_idx = schypo.simulate.extract_parameters(adata.X, q=q, min_mean=q)\",\n \"_____no_output_____\"\n ],\n [\n \"imp.reload(simulate)\\n\\ntranscriptome = simulate.simulate_transcriptomes(\\n n_cells=10000, \\n means=z_param[0],\\n variances=z_param[1],\\n corr=x_param[2],\\n Nc=Nc)\\nrelative_transcriptome = transcriptome/transcriptome.sum(axis=1).reshape(-1, 1)\\n\\nqs, captured_data = simulate.capture_sampling(transcriptome, q=q, q_sq=q**2+1e-10)\",\n \"_____no_output_____\"\n ],\n [\n \"def qqplot(x, y, s=1):\\n \\n plt.scatter(\\n np.quantile(x, np.linspace(0, 1, 1000)),\\n np.quantile(y, np.linspace(0, 1, 1000)),\\n s=s)\\n\\n plt.plot(x, x, lw=1, color='m')\",\n \"_____no_output_____\"\n ],\n [\n \"plt.figure(figsize=(8, 2));\\nplt.subplots_adjust(wspace=0.2);\\n\\nplt.subplot(1, 3, 1);\\nsns.distplot(np.log(captured_data.mean(axis=0)), hist=False, label='Simulated')\\nsns.distplot(np.log(data[:, good_idx].toarray().var(axis=0)), hist=False, label='Real')\\nplt.xlabel('Log(mean)')\\n\\nplt.subplot(1, 3, 2);\\nsns.distplot(np.log(captured_data.var(axis=0)), hist=False)\\nsns.distplot(np.log(data[:, good_idx].toarray().var(axis=0)), hist=False)\\nplt.xlabel('Log(variance)')\\n\\nplt.subplot(1, 3, 3);\\nsns.distplot(np.log(captured_data.sum(axis=1)), hist=False)\\nsns.distplot(np.log(data.toarray().sum(axis=1)), hist=False)\\nplt.xlabel('Log(total UMI count)')\\n\\nplt.savefig(figpath + 'simulation_stats.png', bbox_inches='tight')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Compare datasets generated by Poisson and hypergeometric processes\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"_, poi_captured = simulate.capture_sampling(transcriptome, q=q, process='poisson')\\n_, hyper_captured = simulate.capture_sampling(transcriptome, q=q, process='hyper')\",\n \"_____no_output_____\"\n ],\n [\n \"q_list = [0.05, 0.1, 0.2, 0.3, 0.5]\",\n \"_____no_output_____\"\n ],\n [\n \"plt.figure(figsize=(8, 2))\\nplt.subplots_adjust(wspace=0.3)\\nfor idx, q in enumerate(q_list):\\n \\n _, poi_captured = simulate.capture_sampling(transcriptome, q=q, process='poisson')\\n _, hyper_captured = simulate.capture_sampling(transcriptome, q=q, process='hyper')\\n relative_poi_captured = poi_captured/poi_captured.sum(axis=1).reshape(-1, 1)\\n relative_hyper_captured = hyper_captured/hyper_captured.sum(axis=1).reshape(-1, 1)\\n \\n poi_corr = np.corrcoef(relative_poi_captured, rowvar=False)\\n hyper_corr = np.corrcoef(relative_hyper_captured, rowvar=False)\\n\\n sample_idx = np.random.choice(poi_corr.ravel().shape[0], 100000)\\n \\n plt.subplot(1, len(q_list), idx+1)\\n plt.scatter(poi_corr.ravel()[sample_idx], hyper_corr.ravel()[sample_idx], s=1, alpha=1)\\n plt.plot([-1, 1], [-1, 1], 'm', lw=1)\\n# plt.xlim([-0.3, 0.4])\\n# plt.ylim([-0.3, 0.4])\\n \\n if idx != 0:\\n plt.yticks([])\\n plt.title('q={}'.format(q))\\nplt.savefig(figpath + 'poi_vs_hyp_sim_corr.png', bbox_inches='tight')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"### Compare Poisson vs HG estimators\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"def compare_esimators(q, plot=False, true_data=None, var_q=1e-10):\\n \\n q_sq = var_q + q**2\\n \\n true_data = schypo.simulate.simulate_transcriptomes(1000, 1000, correlated=True) if true_data is None else true_data\\n true_relative_data = true_data / true_data.sum(axis=1).reshape(-1, 1)\\n\\n qs, captured_data = schypo.simulate.capture_sampling(true_data, q, q_sq)\\n Nr = captured_data.sum(axis=1).mean()\\n captured_relative_data = captured_data/captured_data.sum(axis=1).reshape(-1, 1)\\n adata = sc.AnnData(sp.sparse.csr_matrix(captured_data))\\n sf = schypo.estimator._estimate_size_factor(adata.X, 'hyper_relative', total=True)\\n\\n good_idx = (captured_data.mean(axis=0) > q)\\n\\n # True moments\\n m_true, v_true, corr_true = true_relative_data.mean(axis=0), true_relative_data.var(axis=0), np.corrcoef(true_relative_data, rowvar=False)\\n rv_true = v_true/m_true**2#schypo.estimator._residual_variance(m_true, v_true, schypo.estimator._fit_mv_regressor(m_true, v_true))\\n \\n # Compute 1D moments\\n m_obs, v_obs = captured_relative_data.mean(axis=0), captured_relative_data.var(axis=0)\\n rv_obs = v_obs/m_obs**2#schypo.estimator._residual_variance(m_obs, v_obs, schypo.estimator._fit_mv_regressor(m_obs, v_obs))\\n m_poi, v_poi = schypo.estimator._poisson_1d_relative(adata.X, size_factor=sf, n_obs=true_data.shape[0])\\n rv_poi = v_poi/m_poi**2#schypo.estimator._residual_variance(m_poi, v_poi, schypo.estimator._fit_mv_regressor(m_poi, v_poi))\\n m_hyp, v_hyp = schypo.estimator._hyper_1d_relative(adata.X, size_factor=sf, n_obs=true_data.shape[0], q=q)\\n rv_hyp = v_hyp/m_hyp**2#schypo.estimator._residual_variance(m_hyp, v_hyp, schypo.estimator._fit_mv_regressor(m_hyp, v_hyp))\\n\\n # Compute 2D moments\\n corr_obs = np.corrcoef(captured_relative_data, rowvar=False)\\n# corr_obs = corr_obs[np.triu_indices(corr_obs.shape[0])]\\n \\n idx1 = np.array([i for i,j in itertools.combinations(range(adata.shape[1]), 2) if good_idx[i] and good_idx[j]])\\n idx2 = np.array([j for i,j in itertools.combinations(range(adata.shape[1]), 2) if good_idx[i] and good_idx[j]])\\n sample_idx = np.random.choice(idx1.shape[0], 10000)\\n \\n idx1 = idx1[sample_idx]\\n idx2 = idx2[sample_idx]\\n\\n corr_true = corr_true[(idx1, idx2)]\\n corr_obs = corr_obs[(idx1, idx2)]\\n \\n cov_poi = schypo.estimator._poisson_cov_relative(adata.X, n_obs=adata.shape[0], size_factor=sf, idx1=idx1, idx2=idx2)\\n cov_hyp = schypo.estimator._hyper_cov_relative(adata.X, n_obs=adata.shape[0], size_factor=sf, idx1=idx1, idx2=idx2, q=q)\\n corr_poi = schypo.estimator._corr_from_cov(cov_poi, v_poi[idx1], v_poi[idx2])\\n corr_hyp = schypo.estimator._corr_from_cov(cov_hyp, v_hyp[idx1], v_hyp[idx2])\\n\\n corr_poi[np.abs(corr_poi) > 1] = np.nan\\n corr_hyp[np.abs(corr_hyp) > 1] = np.nan\\n\\n mean_list = [m_obs, m_poi, m_hyp]\\n var_list = [rv_obs, rv_poi, rv_hyp]\\n corr_list = [corr_obs, corr_poi, corr_hyp]\\n estimated_list = [mean_list, var_list, corr_list]\\n true_list = [m_true, rv_true, corr_true]\\n\\n if plot:\\n count = 0\\n for j in range(3):\\n for i in range(3):\\n\\n plt.subplot(3, 3, count+1)\\n\\n\\n if i != 2:\\n plt.scatter(\\n np.log(true_list[i][good_idx]),\\n np.log(estimated_list[i][j][good_idx]),\\n s=0.1)\\n plt.plot(np.log(true_list[i][good_idx]), np.log(true_list[i][good_idx]), linestyle='--', color='m')\\n plt.xlim(np.log(true_list[i][good_idx]).min(), np.log(true_list[i][good_idx]).max())\\n plt.ylim(np.log(true_list[i][good_idx]).min(), np.log(true_list[i][good_idx]).max())\\n\\n else:\\n\\n x = true_list[i]\\n y = estimated_list[i][j]\\n \\n print(x.shape, y.shape)\\n\\n plt.scatter(\\n x,\\n y,\\n s=0.1)\\n plt.plot([-1, 1], [-1, 1],linestyle='--', color='m')\\n plt.xlim(-1, 1);\\n plt.ylim(-1, 1);\\n \\n# if not (i == j):\\n# plt.yticks([]);\\n# plt.xticks([]);\\n \\n if i == 1 or i == 0:\\n \\n print((np.log(true_list[i][good_idx]) > np.log(estimated_list[i][j][good_idx])).mean())\\n\\n count += 1\\n else:\\n return qs, good_idx, estimated_list, true_list\",\n \"_____no_output_____\"\n ],\n [\n \"import matplotlib.pylab as pylab\\nparams = {'legend.fontsize': 'small',\\n 'axes.labelsize': 'medium',\\n 'axes.titlesize':'medium',\\n 'figure.titlesize':'medium',\\n 'xtick.labelsize':'xx-small',\\n 'ytick.labelsize':'xx-small'}\\npylab.rcParams.update(params)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"imp.reload(simulate)\\n\\nq = 0.4\\nplt.figure(figsize=(4, 4))\\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\\ntrue_data = simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1],\\n corr=x_param[2],\\n Nc=Nc)\\ncompare_esimators(q, plot=True, true_data=true_data)\\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_2.png', bbox_inches='tight')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"true_data = schypo.simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1], Nc=Nc)\",\n \"_____no_output_____\"\n ],\n [\n \"q = 0.025\\nplt.figure(figsize=(4, 4))\\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\\ncompare_esimators(q, plot=True, true_data=true_data)\\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_rv_2.5.png', bbox_inches='tight', dpi=1200)\",\n \"/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:67: RuntimeWarning: invalid value encountered in log\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:94: RuntimeWarning: invalid value encountered in log\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:94: RuntimeWarning: invalid value encountered in greater\\n\"\n ],\n [\n \"q = 0.4\\nplt.figure(figsize=(4, 4))\\nplt.subplots_adjust(wspace=0.5, hspace=0.5)\\ncompare_esimators(q, plot=True, true_data=true_data)\\nplt.savefig(fig_path + 'poi_vs_hyper_scatter_rv_40.png', bbox_inches='tight', dpi=1200)\",\n \"/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n\"\n ],\n [\n \"def compute_mse(x, y, log=True):\\n \\n if log:\\n return np.nanmean(np.abs(np.log(x)-np.log(y)))\\n else:\\n return np.nanmean(np.abs(x-y))\\n\\ndef concordance(x, y, log=True):\\n \\n if log:\\n a = np.log(x)\\n b = np.log(y)\\n else:\\n a = x\\n b = y\\n cond = np.isfinite(a) & np.isfinite(b)\\n a = a[cond]\\n b = b[cond]\\n cmat = np.cov(a, b)\\n return 2*cmat[0,1]/(cmat[0,0] + cmat[1,1] + (a.mean()-b.mean())**2)\\n \\nm_mse_list, v_mse_list, c_mse_list = [], [], []\\n# true_data = schypo.simulate.simulate_transcriptomes(n_cells=10000, means=z_param[0], variances=z_param[1],\\n# Nc=Nc)\\nq_list = [0.01, 0.025, 0.1, 0.15, 0.3, 0.5, 0.7, 0.99]\\nqs_list = []\\nfor q in q_list:\\n qs, good_idx, est, true = compare_esimators(q, plot=False, true_data=true_data)\\n qs_list.append(qs)\\n m_mse_list.append([concordance(x[good_idx], true[0][good_idx]) for x in est[0]])\\n v_mse_list.append([concordance(x[good_idx], true[1][good_idx]) for x in est[1]])\\n c_mse_list.append([concordance(x, true[2], log=False) for x in est[2]])\\n \\nm_mse_list, v_mse_list, c_mse_list = np.array(m_mse_list), np.array(v_mse_list), np.array(c_mse_list)\",\n \"/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:48: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:47: RuntimeWarning: invalid value encountered in greater\\n/data/home/anaconda3/envs/single_cell/lib/python3.7/site-packages/ipykernel_launcher.py:11: RuntimeWarning: invalid value encountered in log\\n # This is added back by InteractiveShellApp.init_path()\\n\"\n ],\n [\n \"import matplotlib.pylab as pylab\\nparams = {'legend.fontsize': 'small',\\n 'axes.labelsize': 'medium',\\n 'axes.titlesize':'medium',\\n 'figure.titlesize':'medium',\\n 'xtick.labelsize':'small',\\n 'ytick.labelsize':'small'}\\npylab.rcParams.update(params)\\n\\nplt.figure(figsize=(8, 3))\\nplt.subplots_adjust(wspace=0.5)\\n\\nplt.subplot(1, 3, 1)\\nplt.plot(q_list[1:], m_mse_list[:, 0][1:], '-o')\\n# plt.legend(['Naive,\\\\nPoisson,\\\\nHG'])\\nplt.ylabel('CCC log(mean)')\\nplt.xlabel('overall UMI efficiency (q)')\\n\\nplt.subplot(1, 3, 2)\\nplt.plot(q_list[2:], v_mse_list[:, 0][2:], '-o')\\nplt.plot(q_list[2:], v_mse_list[:, 1][2:], '-o')\\nplt.plot(q_list[2:], v_mse_list[:, 2][2:], '-o')\\nplt.legend(['Naive', 'Poisson', 'HG'], ncol=3, loc='upper center', bbox_to_anchor=(0.4,1.15))\\nplt.ylabel('CCC log(variance)')\\nplt.xlabel('overall UMI efficiency (q)')\\n\\nplt.subplot(1, 3, 3)\\nplt.plot(q_list[2:], c_mse_list[:, 0][2:], '-o')\\nplt.plot(q_list[2:], c_mse_list[:, 1][2:], '-o')\\nplt.plot(q_list[2:], c_mse_list[:, 2][2:], '-o')\\n# plt.legend(['Naive', 'Poisson', 'HG'])\\nplt.ylabel('CCC correlation')\\nplt.xlabel('overall UMI efficiency (q)')\\n\\nplt.savefig(fig_path + 'poi_vs_hyper_rv_ccc.pdf', bbox_inches='tight')\",\n \"_____no_output_____\"\n ],\n [\n \"plt.figure(figsize=(1, 1.3))\\nplt.plot(q_list, v_mse_list[:, 0], '-o', ms=4)\\nplt.plot(q_list, v_mse_list[:, 1], '-o', ms=4)\\nplt.plot(q_list, v_mse_list[:, 2], '-o', ms=4)\\n\\nplt.savefig(fig_path + 'poi_vs_hyper_ccc_var_rv_inset.pdf', bbox_inches='tight')\",\n \"_____no_output_____\"\n ],\n [\n \"plt.figure(figsize=(1, 1.3))\\nplt.plot(q_list, c_mse_list[:, 0], '-o', ms=4)\\nplt.plot(q_list, c_mse_list[:, 1], '-o', ms=4)\\nplt.plot(q_list, c_mse_list[:, 2], '-o', ms=4)\\nplt.savefig(fig_path + 'poi_vs_hyper_ccc_corr_inset.pdf', bbox_inches='tight')\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","raw","code"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"raw\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"],["code","code","code","code","code"],["markdown"],["code","code","code","code","code"],["markdown"],["code","code","code","code","code"],["markdown"],["code","code","code","code","code"],["markdown"],["code","code","code"],["markdown"],["code","code"],["raw"],["code","code","code","code","code","code","code"]],"string":"[\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"raw\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":590,"cells":{"hexsha":{"kind":"string","value":"d01ae92fb89aaa9b968a6b5d1950273fd2dffb3a"},"size":{"kind":"number","value":1389,"string":"1,389"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"homework/homework-for-week-14-regex_BLANK.ipynb"},"max_stars_repo_name":{"kind":"string","value":"sandeepmj/fall21-students-practical-python"},"max_stars_repo_head_hexsha":{"kind":"string","value":"d808afc955ce07fb5d9593069f88db819c0f1c45"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"null"},"max_stars_repo_stars_event_min_datetime":{"kind":"null"},"max_stars_repo_stars_event_max_datetime":{"kind":"null"},"max_issues_repo_path":{"kind":"string","value":"homework/homework-for-week-14-regex_BLANK.ipynb"},"max_issues_repo_name":{"kind":"string","value":"sandeepmj/fall21-students-practical-python"},"max_issues_repo_head_hexsha":{"kind":"string","value":"d808afc955ce07fb5d9593069f88db819c0f1c45"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"homework/homework-for-week-14-regex_BLANK.ipynb"},"max_forks_repo_name":{"kind":"string","value":"sandeepmj/fall21-students-practical-python"},"max_forks_repo_head_hexsha":{"kind":"string","value":"d808afc955ce07fb5d9593069f88db819c0f1c45"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"number","value":1,"string":"1"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2021-11-01T01:41:39.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2021-11-01T01:41:39.000Z"},"avg_line_length":{"kind":"number","value":22.0476190476,"string":"22.047619"},"max_line_length":{"kind":"number","value":133,"string":"133"},"alphanum_fraction":{"kind":"number","value":0.558675306,"string":"0.558675"},"cells":{"kind":"list like","value":[[["## Find key data points from multiple documents\n\nDownload these documents.\n\nThey all have an identical structure to them.\n\nUsing regex, capture and export as a CSV the following data points in all the documents:\n\n- The case number.\n- Whether the decision was to accept or reject the appeal.\n- The request date.\n- The decision date.\n- Source file name\n\n\n","_____no_output_____"]]],"string":"[\n [\n [\n \"## Find key data points from multiple documents\\n\\nDownload these documents.\\n\\nThey all have an identical structure to them.\\n\\nUsing regex, capture and export as a CSV the following data points in all the documents:\\n\\n- The case number.\\n- Whether the decision was to accept or reject the appeal.\\n- The request date.\\n- The decision date.\\n- Source file name\\n\\n\\n\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown"],"string":"[\n \"markdown\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"]],"string":"[\n [\n \"markdown\"\n ]\n]"}}},{"rowIdx":591,"cells":{"hexsha":{"kind":"string","value":"d01afa40a330e5820d065066efaaaf0cb02c25a7"},"size":{"kind":"number","value":93372,"string":"93,372"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"notebooks/Dataset D - Contraceptive Method Choice/Synthetic data evaluation/Utility/TRTR and TSTR Results Comparison.ipynb"},"max_stars_repo_name":{"kind":"string","value":"Vicomtech/STDG-evaluation-metrics"},"max_stars_repo_head_hexsha":{"kind":"string","value":"4662c2cc60f7941723a876a6032b411e40f5ec62"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":4,"string":"4"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2021-08-20T18:21:09.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2022-01-12T09:30:29.000Z"},"max_issues_repo_path":{"kind":"string","value":"notebooks/Dataset D - Contraceptive Method Choice/Synthetic data evaluation/Utility/TRTR and TSTR Results Comparison.ipynb"},"max_issues_repo_name":{"kind":"string","value":"Vicomtech/STDG-evaluation-metrics"},"max_issues_repo_head_hexsha":{"kind":"string","value":"4662c2cc60f7941723a876a6032b411e40f5ec62"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"null"},"max_issues_repo_issues_event_min_datetime":{"kind":"null"},"max_issues_repo_issues_event_max_datetime":{"kind":"null"},"max_forks_repo_path":{"kind":"string","value":"notebooks/Dataset D - Contraceptive Method Choice/Synthetic data evaluation/Utility/TRTR and TSTR Results Comparison.ipynb"},"max_forks_repo_name":{"kind":"string","value":"Vicomtech/STDG-evaluation-metrics"},"max_forks_repo_head_hexsha":{"kind":"string","value":"4662c2cc60f7941723a876a6032b411e40f5ec62"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":276.2485207101,"string":"276.248521"},"max_line_length":{"kind":"number","value":66872,"string":"66,872"},"alphanum_fraction":{"kind":"number","value":0.9059353982,"string":"0.905935"},"cells":{"kind":"list like","value":[[["# TRTR and TSTR Results Comparison","_____no_output_____"]],[["#import libraries\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\npd.set_option('precision', 4)","_____no_output_____"]],[["## 1. Create empty dataset to save metrics differences","_____no_output_____"]],[["DATA_TYPES = ['Real','GM','SDV','CTGAN','WGANGP']\nSYNTHESIZERS = ['GM','SDV','CTGAN','WGANGP']\nml_models = ['RF','KNN','DT','SVM','MLP']","_____no_output_____"]],[["## 2. Read obtained results when TRTR and TSTR","_____no_output_____"]],[["FILEPATHS = {'Real' : 'RESULTS/models_results_real.csv',\n 'GM' : 'RESULTS/models_results_gm.csv',\n 'SDV' : 'RESULTS/models_results_sdv.csv',\n 'CTGAN' : 'RESULTS/models_results_ctgan.csv',\n 'WGANGP' : 'RESULTS/models_results_wgangp.csv'}","_____no_output_____"],["#iterate over all datasets filepaths and read each dataset\nresults_all = dict()\nfor name, path in FILEPATHS.items() :\n results_all[name] = pd.read_csv(path, index_col='model')\nresults_all","_____no_output_____"]],[["## 3. Calculate differences of models","_____no_output_____"]],[["metrics_diffs_all = dict()\nreal_metrics = results_all['Real']\ncolumns = ['data','accuracy_diff','precision_diff','recall_diff','f1_diff']\nmetrics = ['accuracy','precision','recall','f1']\n\nfor name in SYNTHESIZERS :\n syn_metrics = results_all[name]\n metrics_diffs_all[name] = pd.DataFrame(columns = columns)\n for model in ml_models :\n real_metrics_model = real_metrics.loc[model]\n syn_metrics_model = syn_metrics.loc[model]\n data = [model]\n for m in metrics :\n data.append(abs(real_metrics_model[m] - syn_metrics_model[m]))\n metrics_diffs_all[name] = metrics_diffs_all[name].append(pd.DataFrame([data], columns = columns))\nmetrics_diffs_all","_____no_output_____"]],[["## 4. Compare absolute differences","_____no_output_____"],["### 4.1. Barplots for each metric","_____no_output_____"]],[["metrics = ['accuracy', 'precision', 'recall', 'f1']\nmetrics_diff = ['accuracy_diff', 'precision_diff', 'recall_diff', 'f1_diff']\ncolors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple']\n\nbarwidth = 0.15\n\nfig, axs = plt.subplots(nrows=1, ncols=4, figsize=(15, 2.5))\naxs_idxs = range(4)\nidx = dict(zip(metrics + metrics_diff,axs_idxs))\n\nfor i in range(0,len(metrics)) :\n data = dict()\n y_pos = dict()\n y_pos[0] = np.arange(len(ml_models))\n ax = axs[idx[metrics[i]]]\n \n for k in range(0,len(DATA_TYPES)) :\n generator_data = results_all[DATA_TYPES[k]] \n data[k] = [0, 0, 0, 0, 0]\n \n for p in range(0,len(ml_models)) :\n data[k][p] = generator_data[metrics[i]].iloc[p]\n \n ax.bar(y_pos[k], data[k], color=colors[k], width=barwidth, edgecolor='white', label=DATA_TYPES[k])\n y_pos[k+1] = [x + barwidth for x in y_pos[k]]\n \n ax.set_xticks([r + barwidth*2 for r in range(len(ml_models))])\n ax.set_xticklabels([])\n ax.set_xticklabels(ml_models, fontsize=10)\n ax.set_title(metrics[i], fontsize=12)\n \nax.legend(DATA_TYPES, ncol=5, bbox_to_anchor=(-0.3, -0.2))\nfig.tight_layout()\n#fig.suptitle('Models performance comparisson Boxplots (TRTR and TSTR) \\n Dataset F - Indian Liver Patient', fontsize=18)\nfig.savefig('RESULTS/MODELS_METRICS_BARPLOTS.svg', bbox_inches='tight')","_____no_output_____"],["metrics = ['accuracy_diff', 'precision_diff', 'recall_diff', 'f1_diff']\ncolors = ['tab:orange', 'tab:green', 'tab:red', 'tab:purple']\n\nfig, axs = plt.subplots(nrows=1, ncols=4, figsize=(15,2.5))\naxs_idxs = range(4)\nidx = dict(zip(metrics,axs_idxs))\n\nfor i in range(0,len(metrics)) :\n data = dict()\n ax = axs[idx[metrics[i]]]\n \n for k in range(0,len(SYNTHESIZERS)) :\n generator_data = metrics_diffs_all[SYNTHESIZERS[k]] \n data[k] = [0, 0, 0, 0, 0]\n \n for p in range(0,len(ml_models)) :\n data[k][p] = generator_data[metrics[i]].iloc[p]\n \n ax.plot(data[k], 'o-', color=colors[k], label=SYNTHESIZERS[k])\n \n ax.set_xticks(np.arange(len(ml_models)))\n ax.set_xticklabels(ml_models, fontsize=10)\n ax.set_title(metrics[i], fontsize=12)\n ax.set_ylim(bottom=-0.01, top=0.28)\n ax.grid()\n \nax.legend(SYNTHESIZERS, ncol=5, bbox_to_anchor=(-0.4, -0.2))\nfig.tight_layout()\n#fig.suptitle('Models performance comparisson Boxplots (TRTR and TSTR) \\n Dataset F - Indian Liver Patient', fontsize=18)\nfig.savefig('RESULTS/MODELS_METRICS_DIFFERENCES.svg', bbox_inches='tight')","_____no_output_____"]]],"string":"[\n [\n [\n \"# TRTR and TSTR Results Comparison\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"#import libraries\\nimport warnings\\nwarnings.filterwarnings(\\\"ignore\\\")\\nimport numpy as np\\nimport pandas as pd\\nfrom matplotlib import pyplot as plt\\n\\npd.set_option('precision', 4)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## 1. Create empty dataset to save metrics differences\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"DATA_TYPES = ['Real','GM','SDV','CTGAN','WGANGP']\\nSYNTHESIZERS = ['GM','SDV','CTGAN','WGANGP']\\nml_models = ['RF','KNN','DT','SVM','MLP']\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## 2. Read obtained results when TRTR and TSTR\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"FILEPATHS = {'Real' : 'RESULTS/models_results_real.csv',\\n 'GM' : 'RESULTS/models_results_gm.csv',\\n 'SDV' : 'RESULTS/models_results_sdv.csv',\\n 'CTGAN' : 'RESULTS/models_results_ctgan.csv',\\n 'WGANGP' : 'RESULTS/models_results_wgangp.csv'}\",\n \"_____no_output_____\"\n ],\n [\n \"#iterate over all datasets filepaths and read each dataset\\nresults_all = dict()\\nfor name, path in FILEPATHS.items() :\\n results_all[name] = pd.read_csv(path, index_col='model')\\nresults_all\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## 3. Calculate differences of models\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"metrics_diffs_all = dict()\\nreal_metrics = results_all['Real']\\ncolumns = ['data','accuracy_diff','precision_diff','recall_diff','f1_diff']\\nmetrics = ['accuracy','precision','recall','f1']\\n\\nfor name in SYNTHESIZERS :\\n syn_metrics = results_all[name]\\n metrics_diffs_all[name] = pd.DataFrame(columns = columns)\\n for model in ml_models :\\n real_metrics_model = real_metrics.loc[model]\\n syn_metrics_model = syn_metrics.loc[model]\\n data = [model]\\n for m in metrics :\\n data.append(abs(real_metrics_model[m] - syn_metrics_model[m]))\\n metrics_diffs_all[name] = metrics_diffs_all[name].append(pd.DataFrame([data], columns = columns))\\nmetrics_diffs_all\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"## 4. Compare absolute differences\",\n \"_____no_output_____\"\n ],\n [\n \"### 4.1. Barplots for each metric\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"metrics = ['accuracy', 'precision', 'recall', 'f1']\\nmetrics_diff = ['accuracy_diff', 'precision_diff', 'recall_diff', 'f1_diff']\\ncolors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple']\\n\\nbarwidth = 0.15\\n\\nfig, axs = plt.subplots(nrows=1, ncols=4, figsize=(15, 2.5))\\naxs_idxs = range(4)\\nidx = dict(zip(metrics + metrics_diff,axs_idxs))\\n\\nfor i in range(0,len(metrics)) :\\n data = dict()\\n y_pos = dict()\\n y_pos[0] = np.arange(len(ml_models))\\n ax = axs[idx[metrics[i]]]\\n \\n for k in range(0,len(DATA_TYPES)) :\\n generator_data = results_all[DATA_TYPES[k]] \\n data[k] = [0, 0, 0, 0, 0]\\n \\n for p in range(0,len(ml_models)) :\\n data[k][p] = generator_data[metrics[i]].iloc[p]\\n \\n ax.bar(y_pos[k], data[k], color=colors[k], width=barwidth, edgecolor='white', label=DATA_TYPES[k])\\n y_pos[k+1] = [x + barwidth for x in y_pos[k]]\\n \\n ax.set_xticks([r + barwidth*2 for r in range(len(ml_models))])\\n ax.set_xticklabels([])\\n ax.set_xticklabels(ml_models, fontsize=10)\\n ax.set_title(metrics[i], fontsize=12)\\n \\nax.legend(DATA_TYPES, ncol=5, bbox_to_anchor=(-0.3, -0.2))\\nfig.tight_layout()\\n#fig.suptitle('Models performance comparisson Boxplots (TRTR and TSTR) \\\\n Dataset F - Indian Liver Patient', fontsize=18)\\nfig.savefig('RESULTS/MODELS_METRICS_BARPLOTS.svg', bbox_inches='tight')\",\n \"_____no_output_____\"\n ],\n [\n \"metrics = ['accuracy_diff', 'precision_diff', 'recall_diff', 'f1_diff']\\ncolors = ['tab:orange', 'tab:green', 'tab:red', 'tab:purple']\\n\\nfig, axs = plt.subplots(nrows=1, ncols=4, figsize=(15,2.5))\\naxs_idxs = range(4)\\nidx = dict(zip(metrics,axs_idxs))\\n\\nfor i in range(0,len(metrics)) :\\n data = dict()\\n ax = axs[idx[metrics[i]]]\\n \\n for k in range(0,len(SYNTHESIZERS)) :\\n generator_data = metrics_diffs_all[SYNTHESIZERS[k]] \\n data[k] = [0, 0, 0, 0, 0]\\n \\n for p in range(0,len(ml_models)) :\\n data[k][p] = generator_data[metrics[i]].iloc[p]\\n \\n ax.plot(data[k], 'o-', color=colors[k], label=SYNTHESIZERS[k])\\n \\n ax.set_xticks(np.arange(len(ml_models)))\\n ax.set_xticklabels(ml_models, fontsize=10)\\n ax.set_title(metrics[i], fontsize=12)\\n ax.set_ylim(bottom=-0.01, top=0.28)\\n ax.grid()\\n \\nax.legend(SYNTHESIZERS, ncol=5, bbox_to_anchor=(-0.4, -0.2))\\nfig.tight_layout()\\n#fig.suptitle('Models performance comparisson Boxplots (TRTR and TSTR) \\\\n Dataset F - Indian Liver Patient', fontsize=18)\\nfig.savefig('RESULTS/MODELS_METRICS_DIFFERENCES.svg', bbox_inches='tight')\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"],["code"],["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code"],["markdown","markdown"],["code","code"]],"string":"[\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\",\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":592,"cells":{"hexsha":{"kind":"string","value":"d01b06191b0028e3ed7c2abbef73c36feb48fc99"},"size":{"kind":"number","value":720959,"string":"720,959"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"research_notebooks/generate_regression_sp.ipynb"},"max_stars_repo_name":{"kind":"string","value":"carolinesadlerr/wiggum"},"max_stars_repo_head_hexsha":{"kind":"string","value":"e9b80fcdb8d50c6dd8ee3f75b9054e07b15a6163"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"number","value":5,"string":"5"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2020-04-04T23:00:15.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2021-09-05T21:47:43.000Z"},"max_issues_repo_path":{"kind":"string","value":"research_notebooks/generate_regression_sp.ipynb"},"max_issues_repo_name":{"kind":"string","value":"carolinesadlerr/wiggum"},"max_issues_repo_head_hexsha":{"kind":"string","value":"e9b80fcdb8d50c6dd8ee3f75b9054e07b15a6163"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"number","value":62,"string":"62"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2019-12-02T19:08:35.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2022-03-30T21:30:42.000Z"},"max_forks_repo_path":{"kind":"string","value":"research_notebooks/generate_regression_sp.ipynb"},"max_forks_repo_name":{"kind":"string","value":"carolinesadlerr/wiggum"},"max_forks_repo_head_hexsha":{"kind":"string","value":"e9b80fcdb8d50c6dd8ee3f75b9054e07b15a6163"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"number","value":3,"string":"3"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2021-02-19T16:06:29.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2022-03-06T22:25:58.000Z"},"avg_line_length":{"kind":"number","value":523.9527616279,"string":"523.952762"},"max_line_length":{"kind":"number","value":52004,"string":"52,004"},"alphanum_fraction":{"kind":"number","value":0.9379437666,"string":"0.937944"},"cells":{"kind":"list like","value":[[["# Generating Simpson's Paradox\n\nWe have been maually setting, but now we should also be able to generate it more programatically. his notebook will describe how we develop some functions that will be included in the `sp_data_util` package.","_____no_output_____"]],[["# %load code/env\n# standard imports we use throughout the project\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\nimport wiggum as wg\nimport sp_data_util as spdata\nfrom sp_data_util import sp_plot","_____no_output_____"]],[["We have been thinking of SP hrough gaussian mixture data, so we'll first work wih that. To cause SP we need he clusters to have an opposite trend of the per cluster covariance. ","_____no_output_____"]],[["# setup\nr_clusters = -.6 # correlation coefficient of clusters\ncluster_spread = .8 # pearson correlation of means\np_sp_clusters = .5 # portion of clusters with SP \nk = 5 # number of clusters\ncluster_size = [2,3]\ndomain_range = [0, 20, 0, 20]\nN = 200 # number of points\np_clusters = [1.0/k]*k","_____no_output_____"],["# keep all means in the middle 80%\nmu_trim = .2\n\n# sample means\ncenter = [np.mean(domain_range[:2]),np.mean(domain_range[2:])]\nmu_transform = np.repeat(np.diff(domain_range)[[0,2]]*(mu_trim),2)\nmu_transform[[1,3]] = mu_transform[[1,3]]*-1 # sign flip every other\nmu_domain = [d + m_t for d, m_t in zip(domain_range,mu_transform)]\ncorr = [[1, cluster_spread],[cluster_spread,1]]\nd = np.sqrt(np.diag(np.diff(mu_domain)[[0,2]]))\ncov = np.dot(d,corr).dot(d)\n# sample a lot of means, just for vizualization\n# mu = np.asarray([np.random.uniform(*mu_domain[:2],size=k*5), # uniform in x\n# np.random.uniform(*mu_domain[2:],size=k*5)]).T # uniform in y\nmu = np.random.multivariate_normal(center, cov,k*50)\nsns.regplot(mu[:,0], mu[:,1])\nplt.axis(domain_range);\n# mu","_____no_output_____"]],[["However independent sampling isn't really very uniform and we'd like to ensure the clusters are more spread out, so we can use some post processing to thin out close ones. ","_____no_output_____"]],[["mu_thin = [mu[0]] # keep the first one\np_dist = [1]\n\n# we'll use a gaussian kernel around each to filter and only the closest point matters\ndist = lambda mu_c,x: stats.norm.pdf(min(np.sum(np.square(mu_c -x),axis=1)))\n\nfor m in mu:\n p_keep = 1- dist(mu_thin,m)\n if p_keep > .99:\n mu_thin.append(m)\n p_dist.append(p_keep)\n\nmu_thin = np.asarray(mu_thin)\nsns.regplot(mu_thin[:,0], mu_thin[:,1])\nplt.axis(domain_range)","_____no_output_____"]],[["Now, we can sample points on top of that, also we'll only use the first k","_____no_output_____"]],[["sns.regplot(mu_thin[:k,0], mu_thin[:k,1])\nplt.axis(domain_range)","_____no_output_____"]],[["Keeping only a few, we can end up with ones in the center, but if we sort them by the distance to the ones previously selected, we get them spread out a little more","_____no_output_____"]],[["\n# sort by distance\nmu_sort, p_sort = zip(*sorted(zip(mu_thin,p_dist),\n key = lambda x: x[1], reverse =True))\n\nmu_sort = np.asarray(mu_sort)\nsns.regplot(mu_sort[:k,0], mu_sort[:k,1])\nplt.axis(domain_range)","_____no_output_____"],["# cluster covariance\ncluster_corr = np.asarray([[1,r_clusters],[r_clusters,1]])\ncluster_std = np.diag(np.sqrt(cluster_size))\ncluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std)\n\n# sample from a GMM\nz = np.random.choice(k,N,p_clusters)\n\nx = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_cov) for z_i in z])\n\n# make a dataframe\nlatent_df = pd.DataFrame(data=x,\n columns = ['x1', 'x2'])\n\n# code cluster as color and add it a column to the dataframe\nlatent_df['color'] = z\n\nsp_plot(latent_df,'x1','x2','color')","_____no_output_____"]],[["We might not want all of the clusters to have the reveral though, so we can also sample the covariances","_____no_output_____"]],[["# cluster covariance\ncluster_std = np.diag(np.sqrt(cluster_size))\ncluster_corr_sp = np.asarray([[1,r_clusters],[r_clusters,1]]) # correlation with sp\ncluster_cov_sp = np.dot(cluster_std,cluster_corr_sp).dot(cluster_std) #cov with sp\ncluster_corr = np.asarray([[1,-r_clusters],[-r_clusters,1]]) #correlation without sp\ncluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std) #cov wihtout sp\n\ncluster_covs = [cluster_corr_sp, cluster_corr]\n# sample the[0,1] k times\nc_sp = np.random.choice(2,k,p=[p_sp_clusters,1-p_sp_clusters])\n\n\n# sample from a GMM\nz = np.random.choice(k,N,p_clusters)\n\nx = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_covs[c_sp[z_i]]) for z_i in z])\n\n# make a dataframe\nlatent_df = pd.DataFrame(data=x,\n columns = ['x1', 'x2'])\n\n# code cluster as color and add it a column to the dataframe\nlatent_df['color'] = z\n\nsp_plot(latent_df,'x1','x2','color')","_____no_output_____"],["[p_sp_clusters,1-p_sp_clusters]","_____no_output_____"],["c_sp","_____no_output_____"]],[["We'll call this construction of SP `geometric_2d_gmm_sp` and it's included in the `sp_data_utils` module now, so it can be called as follows. We'll change the portion of clusters with SP to 1, to ensure that all are SP. ","_____no_output_____"]],[["type(r_clusters)\ntype(cluster_size)\ntype(cluster_spread)\ntype(p_sp_clusters)\ntype(domain_range)\ntype(p_clusters)","_____no_output_____"],["p_sp_clusters = .9\nsp_df2 = spdata.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread,\n p_sp_clusters, domain_range,k,N,p_clusters)\nsp_plot(sp_df2,'x1','x2','color')","_____no_output_____"]],[["With this, we can start to see how the parameters control a little","_____no_output_____"]],[["# setup\nr_clusters = -.4 # correlation coefficient of clusters\ncluster_spread = .8 # pearson correlation of means\np_sp_clusters = .6 # portion of clusters with SP \nk = 5 # number of clusters\ncluster_size = [4,4]\ndomain_range = [0, 20, 0, 20]\nN = 200 # number of points\np_clusters = [.5, .2, .1, .1, .1]\n\nsp_df3 = spdata.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread,\n p_sp_clusters, domain_range,k,N,p_clusters)\nsp_plot(sp_df3,'x1','x2','color')","_____no_output_____"]],[["We might want to add multiple views, so we added a function that takes the same parameters or lists to allow each view to have different parameters. We'll look first at just two views with the same parameters, both as one another and as above","_____no_output_____"]],[["\nmany_sp_df = spdata.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\n domain_range,k,N,p_clusters)\n\nsp_plot(many_sp_df,'x1','x2','A')\nsp_plot(many_sp_df,'x3','x4','B')\nmany_sp_df.head()","200\n4\n"]],[["We can also look at the pairs of variables that we did not design SP into and see that they have vey different structure","_____no_output_____"]],[["# f, ax_grid = plt.subplots(2,2) # , fig_size=(10,10)\n\nsp_plot(many_sp_df,'x1','x4','A')\nsp_plot(many_sp_df,'x2','x4','B')\nsp_plot(many_sp_df,'x2','x3','B')\nsp_plot(many_sp_df,'x1','x3','B')","_____no_output_____"]],[["And we can set up the views to be different from one another by design","_____no_output_____"]],[["# setup\nr_clusters = [.8, -.2] # correlation coefficient of clusters\ncluster_spread = [.8, .2] # pearson correlation of means\np_sp_clusters = [.6, 1] # portion of clusters with SP \nk = [5,3] # number of clusters\ncluster_size = [4,4]\ndomain_range = [0, 20, 0, 20]\nN = 200 # number of points\np_clusters = [[.5, .2, .1, .1, .1],[1.0/3]*3]\n\n\nmany_sp_df_diff = spdata.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\n domain_range,k,N,p_clusters)\n\nsp_plot(many_sp_df_diff,'x1','x2','A')\nsp_plot(many_sp_df_diff,'x3','x4','B')\nmany_sp_df.head()","200\n4\n"]],[["And we can run our detection algorithm on this as well.","_____no_output_____"]],[["many_sp_df_diff_result = wg.detect_simpsons_paradox(many_sp_df_diff)\nmany_sp_df_diff_result","_____no_output_____"]],[["We designed in SP to occur between attributes `x1` and `x2` with respect to `A` and 2 & 3 in grouby by B, for portions fo the subgroups. We detect other occurences. It can be interesting to exmine trends between the deisnged and spontaneous occurences of SP, so ","_____no_output_____"]],[["designed_SP = [('x1','x2','A'),('x3','x4','B')]","_____no_output_____"],["des = []\nfor i,r in enumerate(many_sp_df_diff_result[['attr1','attr2','groupbyAttr']].values):\n if tuple(r) in designed_SP:\n des.append(i)","_____no_output_____"],["many_sp_df_diff_result['designed'] = 'no'\nmany_sp_df_diff_result.loc[des,'designed'] = 'yes'\nmany_sp_df_diff_result.head()","_____no_output_____"],["r_clusters = -.9 # correlation coefficient of clusters\ncluster_spread = .6 # pearson correlation of means\np_sp_clusters = .5 # portion of clusters with SP \nk = 5 # number of clusters\ncluster_size = [5,5]\ndomain_range = [0, 20, 0, 20]\nN = 200 # number of points\np_clusters = [1.0/k]*k\n\nmany_sp_df_diff = spdata.geometric_indep_views_gmm_sp(3,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\n domain_range,k,N,p_clusters)\n\nsp_plot(many_sp_df_diff,'x1','x2','A')\nsp_plot(many_sp_df_diff,'x3','x4','B')\nsp_plot(many_sp_df_diff,'x3','x4','A')\nmany_sp_df_diff.head()","200\n6\n"]]],"string":"[\n [\n [\n \"# Generating Simpson's Paradox\\n\\nWe have been maually setting, but now we should also be able to generate it more programatically. his notebook will describe how we develop some functions that will be included in the `sp_data_util` package.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# %load code/env\\n# standard imports we use throughout the project\\nimport numpy as np\\nimport pandas as pd\\nimport seaborn as sns\\nimport scipy.stats as stats\\nimport matplotlib.pyplot as plt\\n\\nimport wiggum as wg\\nimport sp_data_util as spdata\\nfrom sp_data_util import sp_plot\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"We have been thinking of SP hrough gaussian mixture data, so we'll first work wih that. To cause SP we need he clusters to have an opposite trend of the per cluster covariance. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# setup\\nr_clusters = -.6 # correlation coefficient of clusters\\ncluster_spread = .8 # pearson correlation of means\\np_sp_clusters = .5 # portion of clusters with SP \\nk = 5 # number of clusters\\ncluster_size = [2,3]\\ndomain_range = [0, 20, 0, 20]\\nN = 200 # number of points\\np_clusters = [1.0/k]*k\",\n \"_____no_output_____\"\n ],\n [\n \"# keep all means in the middle 80%\\nmu_trim = .2\\n\\n# sample means\\ncenter = [np.mean(domain_range[:2]),np.mean(domain_range[2:])]\\nmu_transform = np.repeat(np.diff(domain_range)[[0,2]]*(mu_trim),2)\\nmu_transform[[1,3]] = mu_transform[[1,3]]*-1 # sign flip every other\\nmu_domain = [d + m_t for d, m_t in zip(domain_range,mu_transform)]\\ncorr = [[1, cluster_spread],[cluster_spread,1]]\\nd = np.sqrt(np.diag(np.diff(mu_domain)[[0,2]]))\\ncov = np.dot(d,corr).dot(d)\\n# sample a lot of means, just for vizualization\\n# mu = np.asarray([np.random.uniform(*mu_domain[:2],size=k*5), # uniform in x\\n# np.random.uniform(*mu_domain[2:],size=k*5)]).T # uniform in y\\nmu = np.random.multivariate_normal(center, cov,k*50)\\nsns.regplot(mu[:,0], mu[:,1])\\nplt.axis(domain_range);\\n# mu\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"However independent sampling isn't really very uniform and we'd like to ensure the clusters are more spread out, so we can use some post processing to thin out close ones. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"mu_thin = [mu[0]] # keep the first one\\np_dist = [1]\\n\\n# we'll use a gaussian kernel around each to filter and only the closest point matters\\ndist = lambda mu_c,x: stats.norm.pdf(min(np.sum(np.square(mu_c -x),axis=1)))\\n\\nfor m in mu:\\n p_keep = 1- dist(mu_thin,m)\\n if p_keep > .99:\\n mu_thin.append(m)\\n p_dist.append(p_keep)\\n\\nmu_thin = np.asarray(mu_thin)\\nsns.regplot(mu_thin[:,0], mu_thin[:,1])\\nplt.axis(domain_range)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Now, we can sample points on top of that, also we'll only use the first k\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"sns.regplot(mu_thin[:k,0], mu_thin[:k,1])\\nplt.axis(domain_range)\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"Keeping only a few, we can end up with ones in the center, but if we sort them by the distance to the ones previously selected, we get them spread out a little more\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"\\n# sort by distance\\nmu_sort, p_sort = zip(*sorted(zip(mu_thin,p_dist),\\n key = lambda x: x[1], reverse =True))\\n\\nmu_sort = np.asarray(mu_sort)\\nsns.regplot(mu_sort[:k,0], mu_sort[:k,1])\\nplt.axis(domain_range)\",\n \"_____no_output_____\"\n ],\n [\n \"# cluster covariance\\ncluster_corr = np.asarray([[1,r_clusters],[r_clusters,1]])\\ncluster_std = np.diag(np.sqrt(cluster_size))\\ncluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std)\\n\\n# sample from a GMM\\nz = np.random.choice(k,N,p_clusters)\\n\\nx = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_cov) for z_i in z])\\n\\n# make a dataframe\\nlatent_df = pd.DataFrame(data=x,\\n columns = ['x1', 'x2'])\\n\\n# code cluster as color and add it a column to the dataframe\\nlatent_df['color'] = z\\n\\nsp_plot(latent_df,'x1','x2','color')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"We might not want all of the clusters to have the reveral though, so we can also sample the covariances\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# cluster covariance\\ncluster_std = np.diag(np.sqrt(cluster_size))\\ncluster_corr_sp = np.asarray([[1,r_clusters],[r_clusters,1]]) # correlation with sp\\ncluster_cov_sp = np.dot(cluster_std,cluster_corr_sp).dot(cluster_std) #cov with sp\\ncluster_corr = np.asarray([[1,-r_clusters],[-r_clusters,1]]) #correlation without sp\\ncluster_cov = np.dot(cluster_std,cluster_corr).dot(cluster_std) #cov wihtout sp\\n\\ncluster_covs = [cluster_corr_sp, cluster_corr]\\n# sample the[0,1] k times\\nc_sp = np.random.choice(2,k,p=[p_sp_clusters,1-p_sp_clusters])\\n\\n\\n# sample from a GMM\\nz = np.random.choice(k,N,p_clusters)\\n\\nx = np.asarray([np.random.multivariate_normal(mu_sort[z_i],cluster_covs[c_sp[z_i]]) for z_i in z])\\n\\n# make a dataframe\\nlatent_df = pd.DataFrame(data=x,\\n columns = ['x1', 'x2'])\\n\\n# code cluster as color and add it a column to the dataframe\\nlatent_df['color'] = z\\n\\nsp_plot(latent_df,'x1','x2','color')\",\n \"_____no_output_____\"\n ],\n [\n \"[p_sp_clusters,1-p_sp_clusters]\",\n \"_____no_output_____\"\n ],\n [\n \"c_sp\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"We'll call this construction of SP `geometric_2d_gmm_sp` and it's included in the `sp_data_utils` module now, so it can be called as follows. We'll change the portion of clusters with SP to 1, to ensure that all are SP. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"type(r_clusters)\\ntype(cluster_size)\\ntype(cluster_spread)\\ntype(p_sp_clusters)\\ntype(domain_range)\\ntype(p_clusters)\",\n \"_____no_output_____\"\n ],\n [\n \"p_sp_clusters = .9\\nsp_df2 = spdata.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread,\\n p_sp_clusters, domain_range,k,N,p_clusters)\\nsp_plot(sp_df2,'x1','x2','color')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"With this, we can start to see how the parameters control a little\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# setup\\nr_clusters = -.4 # correlation coefficient of clusters\\ncluster_spread = .8 # pearson correlation of means\\np_sp_clusters = .6 # portion of clusters with SP \\nk = 5 # number of clusters\\ncluster_size = [4,4]\\ndomain_range = [0, 20, 0, 20]\\nN = 200 # number of points\\np_clusters = [.5, .2, .1, .1, .1]\\n\\nsp_df3 = spdata.geometric_2d_gmm_sp(r_clusters,cluster_size,cluster_spread,\\n p_sp_clusters, domain_range,k,N,p_clusters)\\nsp_plot(sp_df3,'x1','x2','color')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"We might want to add multiple views, so we added a function that takes the same parameters or lists to allow each view to have different parameters. We'll look first at just two views with the same parameters, both as one another and as above\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"\\nmany_sp_df = spdata.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\\n domain_range,k,N,p_clusters)\\n\\nsp_plot(many_sp_df,'x1','x2','A')\\nsp_plot(many_sp_df,'x3','x4','B')\\nmany_sp_df.head()\",\n \"200\\n4\\n\"\n ]\n ],\n [\n [\n \"We can also look at the pairs of variables that we did not design SP into and see that they have vey different structure\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# f, ax_grid = plt.subplots(2,2) # , fig_size=(10,10)\\n\\nsp_plot(many_sp_df,'x1','x4','A')\\nsp_plot(many_sp_df,'x2','x4','B')\\nsp_plot(many_sp_df,'x2','x3','B')\\nsp_plot(many_sp_df,'x1','x3','B')\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"And we can set up the views to be different from one another by design\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"# setup\\nr_clusters = [.8, -.2] # correlation coefficient of clusters\\ncluster_spread = [.8, .2] # pearson correlation of means\\np_sp_clusters = [.6, 1] # portion of clusters with SP \\nk = [5,3] # number of clusters\\ncluster_size = [4,4]\\ndomain_range = [0, 20, 0, 20]\\nN = 200 # number of points\\np_clusters = [[.5, .2, .1, .1, .1],[1.0/3]*3]\\n\\n\\nmany_sp_df_diff = spdata.geometric_indep_views_gmm_sp(2,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\\n domain_range,k,N,p_clusters)\\n\\nsp_plot(many_sp_df_diff,'x1','x2','A')\\nsp_plot(many_sp_df_diff,'x3','x4','B')\\nmany_sp_df.head()\",\n \"200\\n4\\n\"\n ]\n ],\n [\n [\n \"And we can run our detection algorithm on this as well.\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"many_sp_df_diff_result = wg.detect_simpsons_paradox(many_sp_df_diff)\\nmany_sp_df_diff_result\",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"We designed in SP to occur between attributes `x1` and `x2` with respect to `A` and 2 & 3 in grouby by B, for portions fo the subgroups. We detect other occurences. It can be interesting to exmine trends between the deisnged and spontaneous occurences of SP, so \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"designed_SP = [('x1','x2','A'),('x3','x4','B')]\",\n \"_____no_output_____\"\n ],\n [\n \"des = []\\nfor i,r in enumerate(many_sp_df_diff_result[['attr1','attr2','groupbyAttr']].values):\\n if tuple(r) in designed_SP:\\n des.append(i)\",\n \"_____no_output_____\"\n ],\n [\n \"many_sp_df_diff_result['designed'] = 'no'\\nmany_sp_df_diff_result.loc[des,'designed'] = 'yes'\\nmany_sp_df_diff_result.head()\",\n \"_____no_output_____\"\n ],\n [\n \"r_clusters = -.9 # correlation coefficient of clusters\\ncluster_spread = .6 # pearson correlation of means\\np_sp_clusters = .5 # portion of clusters with SP \\nk = 5 # number of clusters\\ncluster_size = [5,5]\\ndomain_range = [0, 20, 0, 20]\\nN = 200 # number of points\\np_clusters = [1.0/k]*k\\n\\nmany_sp_df_diff = spdata.geometric_indep_views_gmm_sp(3,r_clusters,cluster_size,cluster_spread,p_sp_clusters,\\n domain_range,k,N,p_clusters)\\n\\nsp_plot(many_sp_df_diff,'x1','x2','A')\\nsp_plot(many_sp_df_diff,'x3','x4','B')\\nsp_plot(many_sp_df_diff,'x3','x4','A')\\nmany_sp_df_diff.head()\",\n \"200\\n6\\n\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code","markdown","code"],"string":"[\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\",\n \"markdown\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code","code"],["markdown"],["code","code","code"],["markdown"],["code","code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code"],["markdown"],["code","code","code","code"]],"string":"[\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":593,"cells":{"hexsha":{"kind":"string","value":"d01b14a083d171ac99efceb0a49d5077a7228da6"},"size":{"kind":"number","value":6235,"string":"6,235"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"notebooks/real_video_test.ipynb"},"max_stars_repo_name":{"kind":"string","value":"quinngroup/ornet-reu-2018"},"max_stars_repo_head_hexsha":{"kind":"string","value":"75af0532448b2235d9295f02278a98414dc3fb4f"},"max_stars_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_stars_count":{"kind":"null"},"max_stars_repo_stars_event_min_datetime":{"kind":"null"},"max_stars_repo_stars_event_max_datetime":{"kind":"null"},"max_issues_repo_path":{"kind":"string","value":"notebooks/real_video_test.ipynb"},"max_issues_repo_name":{"kind":"string","value":"quinngroup/ornet-reu-2018"},"max_issues_repo_head_hexsha":{"kind":"string","value":"75af0532448b2235d9295f02278a98414dc3fb4f"},"max_issues_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_issues_count":{"kind":"number","value":11,"string":"11"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2018-06-14T15:45:41.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2018-07-10T19:30:25.000Z"},"max_forks_repo_path":{"kind":"string","value":"notebooks/real_video_test.ipynb"},"max_forks_repo_name":{"kind":"string","value":"quinngroup/ornet-reu-2018"},"max_forks_repo_head_hexsha":{"kind":"string","value":"75af0532448b2235d9295f02278a98414dc3fb4f"},"max_forks_repo_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":26.875,"string":"26.875"},"max_line_length":{"kind":"number","value":166,"string":"166"},"alphanum_fraction":{"kind":"number","value":0.5246190858,"string":"0.524619"},"cells":{"kind":"list like","value":[[["import unittest\nimport numpy as np\nimport sys\nsys.path.insert(0, '/Users/mojtaba/Downloads/ornet-reu-2018-master-2/src')\nimport raster_scan2 as raster_scan\nimport read_video","_____no_output_____"],["class RasterTest(unittest.TestCase):\n\n def manual_scan(self, video):\n \"\"\"\n Manual, loop-based implementation of raster scanning.\n (reference implementation)\n \"\"\"\n frames, height, width = video.shape\n raster = np.zeros(shape = (frames, height * width))\n\n for index, frame in enumerate(video):\n raster[index] = frame.flatten()\n\n return raster\n\n def test_rasterscan1(self):\n y = np.arange(18).reshape((3, 3, 2))\n yt = self.manual_scan(y)\n yp = raster_scan.raster_scan(y)\n np.testing.assert_array_equal(yp, yt)\n\n\n # Add another function (e.g., test_rasterscan_real) that uses read_video to read in a full video, \n # creates a ground-truth, and then uses raster_scan2 to generate a prediction. \n \n def test_rasterscan_real(self):\n y = read_video.read_video('/Users/mojtaba/Desktop/OrNet Project/DAT VIDEOS/LLO/DsRed2-HeLa_2_21_LLO_Cell0.mov')\n y = np.array(y[1:])\n # Because of the output format of \"read_video\" module, we need to slice the \"y\"\n y = y[0,:,:,:]\n yt = self.manual_scan(y)\n yp = raster_scan.raster_scan(y)\n np.testing.assert_array_equal(yp, yt)","_____no_output_____"],["if __name__ == '__main__':\n unittest.main(argv=['first-arg-is-ignored'], exit=False)","./Users/mojtaba/anaconda3/lib/python3.6/site-packages/skimage/util/dtype.py:122: UserWarning: Possible precision loss when converting from float64 to uint8\n .format(dtypeobj_in, dtypeobj_out))\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py:338: ResourceWarning: unclosed file <_io.BufferedWriter name=61>\n self._proc = None\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py:338: ResourceWarning: unclosed file <_io.BufferedReader name=62>\n self._proc = None\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:27: ResourceWarning: unclosed file <_io.BufferedReader name=64>\n.\n----------------------------------------------------------------------\nRan 2 tests in 16.702s\n\nOK\n"]],[["# Here I'm going to test the details of the function that we are going to write for real video testing. ","_____no_output_____"]],[["y = read_video.read_video('/Users/mojtaba/Desktop/OrNet Project/DAT VIDEOS/LLO/DsRed2-HeLa_2_21_LLO_Cell0.mov')\ny2 = np.array(y[1:])\ny2.shape\n","/Users/mojtaba/anaconda3/lib/python3.6/site-packages/skimage/util/dtype.py:122: UserWarning: Possible precision loss when converting from float64 to uint8\n .format(dtypeobj_in, dtypeobj_out))\n"],["y3 = y2[0,:,:,:]\ny3.shape","_____no_output_____"],["def manual_scan(self, video):\n \"\"\"\n Manual, loop-based implementation of raster scanning.\n (reference implementation)\n \"\"\"\n frames, height, width = video.shape\n raster = np.zeros(shape = (frames, height * width))\n\n for index, frame in enumerate(video):\n raster[index] = frame.flatten()\n\n return raster","_____no_output_____"],["yt = manual_scan(_, y3)\nyt.shape","_____no_output_____"],["yp = raster_scan.raster_scan(y3)\nyp.shape","_____no_output_____"]]],"string":"[\n [\n [\n \"import unittest\\nimport numpy as np\\nimport sys\\nsys.path.insert(0, '/Users/mojtaba/Downloads/ornet-reu-2018-master-2/src')\\nimport raster_scan2 as raster_scan\\nimport read_video\",\n \"_____no_output_____\"\n ],\n [\n \"class RasterTest(unittest.TestCase):\\n\\n def manual_scan(self, video):\\n \\\"\\\"\\\"\\n Manual, loop-based implementation of raster scanning.\\n (reference implementation)\\n \\\"\\\"\\\"\\n frames, height, width = video.shape\\n raster = np.zeros(shape = (frames, height * width))\\n\\n for index, frame in enumerate(video):\\n raster[index] = frame.flatten()\\n\\n return raster\\n\\n def test_rasterscan1(self):\\n y = np.arange(18).reshape((3, 3, 2))\\n yt = self.manual_scan(y)\\n yp = raster_scan.raster_scan(y)\\n np.testing.assert_array_equal(yp, yt)\\n\\n\\n # Add another function (e.g., test_rasterscan_real) that uses read_video to read in a full video, \\n # creates a ground-truth, and then uses raster_scan2 to generate a prediction. \\n \\n def test_rasterscan_real(self):\\n y = read_video.read_video('/Users/mojtaba/Desktop/OrNet Project/DAT VIDEOS/LLO/DsRed2-HeLa_2_21_LLO_Cell0.mov')\\n y = np.array(y[1:])\\n # Because of the output format of \\\"read_video\\\" module, we need to slice the \\\"y\\\"\\n y = y[0,:,:,:]\\n yt = self.manual_scan(y)\\n yp = raster_scan.raster_scan(y)\\n np.testing.assert_array_equal(yp, yt)\",\n \"_____no_output_____\"\n ],\n [\n \"if __name__ == '__main__':\\n unittest.main(argv=['first-arg-is-ignored'], exit=False)\",\n \"./Users/mojtaba/anaconda3/lib/python3.6/site-packages/skimage/util/dtype.py:122: UserWarning: Possible precision loss when converting from float64 to uint8\\n .format(dtypeobj_in, dtypeobj_out))\\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py:338: ResourceWarning: unclosed file <_io.BufferedWriter name=61>\\n self._proc = None\\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/imageio/plugins/ffmpeg.py:338: ResourceWarning: unclosed file <_io.BufferedReader name=62>\\n self._proc = None\\n/Users/mojtaba/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:27: ResourceWarning: unclosed file <_io.BufferedReader name=64>\\n.\\n----------------------------------------------------------------------\\nRan 2 tests in 16.702s\\n\\nOK\\n\"\n ]\n ],\n [\n [\n \"# Here I'm going to test the details of the function that we are going to write for real video testing. \",\n \"_____no_output_____\"\n ]\n ],\n [\n [\n \"y = read_video.read_video('/Users/mojtaba/Desktop/OrNet Project/DAT VIDEOS/LLO/DsRed2-HeLa_2_21_LLO_Cell0.mov')\\ny2 = np.array(y[1:])\\ny2.shape\\n\",\n \"/Users/mojtaba/anaconda3/lib/python3.6/site-packages/skimage/util/dtype.py:122: UserWarning: Possible precision loss when converting from float64 to uint8\\n .format(dtypeobj_in, dtypeobj_out))\\n\"\n ],\n [\n \"y3 = y2[0,:,:,:]\\ny3.shape\",\n \"_____no_output_____\"\n ],\n [\n \"def manual_scan(self, video):\\n \\\"\\\"\\\"\\n Manual, loop-based implementation of raster scanning.\\n (reference implementation)\\n \\\"\\\"\\\"\\n frames, height, width = video.shape\\n raster = np.zeros(shape = (frames, height * width))\\n\\n for index, frame in enumerate(video):\\n raster[index] = frame.flatten()\\n\\n return raster\",\n \"_____no_output_____\"\n ],\n [\n \"yt = manual_scan(_, y3)\\nyt.shape\",\n \"_____no_output_____\"\n ],\n [\n \"yp = raster_scan.raster_scan(y3)\\nyp.shape\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["code","markdown","code"],"string":"[\n \"code\",\n \"markdown\",\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["code","code","code"],["markdown"],["code","code","code","code","code"]],"string":"[\n [\n \"code\",\n \"code\",\n \"code\"\n ],\n [\n \"markdown\"\n ],\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":594,"cells":{"hexsha":{"kind":"string","value":"d01b1b726ee498864abc91342a69848e2ddeca21"},"size":{"kind":"number","value":43894,"string":"43,894"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb"},"max_stars_repo_name":{"kind":"string","value":"Amirosimani/amazon-sagemaker-examples"},"max_stars_repo_head_hexsha":{"kind":"string","value":"bc35e7a9da9e2258e77f98098254c2a8e308041a"},"max_stars_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_stars_count":{"kind":"number","value":2610,"string":"2,610"},"max_stars_repo_stars_event_min_datetime":{"kind":"string","value":"2020-10-01T14:14:53.000Z"},"max_stars_repo_stars_event_max_datetime":{"kind":"string","value":"2022-03-31T18:02:31.000Z"},"max_issues_repo_path":{"kind":"string","value":"scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb"},"max_issues_repo_name":{"kind":"string","value":"Amirosimani/amazon-sagemaker-examples"},"max_issues_repo_head_hexsha":{"kind":"string","value":"bc35e7a9da9e2258e77f98098254c2a8e308041a"},"max_issues_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_issues_count":{"kind":"number","value":1959,"string":"1,959"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2020-09-30T20:22:42.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2022-03-31T23:58:37.000Z"},"max_forks_repo_path":{"kind":"string","value":"scientific_details_of_algorithms/lda_topic_modeling/LDA-Science.ipynb"},"max_forks_repo_name":{"kind":"string","value":"Amirosimani/amazon-sagemaker-examples"},"max_forks_repo_head_hexsha":{"kind":"string","value":"bc35e7a9da9e2258e77f98098254c2a8e308041a"},"max_forks_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_forks_count":{"kind":"number","value":2052,"string":"2,052"},"max_forks_repo_forks_event_min_datetime":{"kind":"string","value":"2020-09-30T22:11:46.000Z"},"max_forks_repo_forks_event_max_datetime":{"kind":"string","value":"2022-03-31T23:02:51.000Z"},"avg_line_length":{"kind":"number","value":40.0858447489,"string":"40.085845"},"max_line_length":{"kind":"number","value":888,"string":"888"},"alphanum_fraction":{"kind":"number","value":0.628263544,"string":"0.628264"},"cells":{"kind":"list like","value":[[["# A Scientific Deep Dive Into SageMaker LDA\n\n1. [Introduction](#Introduction)\n1. [Setup](#Setup)\n1. [Data Exploration](#DataExploration)\n1. [Training](#Training)\n1. [Inference](#Inference)\n1. [Epilogue](#Epilogue)","_____no_output_____"],["# Introduction\n***\n\nAmazon SageMaker LDA is an unsupervised learning algorithm that attempts to describe a set of observations as a mixture of distinct categories. Latent Dirichlet Allocation (LDA) is most commonly used to discover a user-specified number of topics shared by documents within a text corpus. Here each observation is a document, the features are the presence (or occurrence count) of each word, and the categories are the topics. Since the method is unsupervised, the topics are not specified up front, and are not guaranteed to align with how a human may naturally categorize documents. The topics are learned as a probability distribution over the words that occur in each document. Each document, in turn, is described as a mixture of topics.\n\nThis notebook is similar to **LDA-Introduction.ipynb** but its objective and scope are a different. We will be taking a deeper dive into the theory. The primary goals of this notebook are,\n\n* to understand the LDA model and the example dataset,\n* understand how the Amazon SageMaker LDA algorithm works,\n* interpret the meaning of the inference output.\n\nFormer knowledge of LDA is not required. However, we will run through concepts rather quickly and at least a foundational knowledge of mathematics or machine learning is recommended. Suggested references are provided, as appropriate.","_____no_output_____"]],[["%matplotlib inline\n\nimport os, re, tarfile\n\nimport boto3\nimport matplotlib.pyplot as plt\nimport mxnet as mx\nimport numpy as np\n\nnp.set_printoptions(precision=3, suppress=True)\n\n# some helpful utility functions are defined in the Python module\n# \"generate_example_data\" located in the same directory as this\n# notebook\nfrom generate_example_data import (\n generate_griffiths_data,\n match_estimated_topics,\n plot_lda,\n plot_lda_topics,\n)\n\n# accessing the SageMaker Python SDK\nimport sagemaker\nfrom sagemaker.amazon.common import RecordSerializer\nfrom sagemaker.serializers import CSVSerializer\nfrom sagemaker.deserializers import JSONDeserializer","_____no_output_____"]],[["# Setup\n\n***\n\n*This notebook was created and tested on an ml.m4.xlarge notebook instance.*\n\nWe first need to specify some AWS credentials; specifically data locations and access roles. This is the only cell of this notebook that you will need to edit. In particular, we need the following data:\n\n* `bucket` - An S3 bucket accessible by this account.\n * Used to store input training data and model data output.\n * Should be withing the same region as this notebook instance, training, and hosting.\n* `prefix` - The location in the bucket where this notebook's input and and output data will be stored. (The default value is sufficient.)\n* `role` - The IAM Role ARN used to give training and hosting access to your data.\n * See documentation on how to create these.\n * The script below will try to determine an appropriate Role ARN.","_____no_output_____"]],[["from sagemaker import get_execution_role\n\nrole = get_execution_role()\n\nbucket = sagemaker.Session().default_bucket()\nprefix = \"sagemaker/DEMO-lda-science\"\n\n\nprint(\"Training input/output will be stored in {}/{}\".format(bucket, prefix))\nprint(\"\\nIAM Role: {}\".format(role))","_____no_output_____"]],[["## The LDA Model\n\nAs mentioned above, LDA is a model for discovering latent topics describing a collection of documents. In this section we will give a brief introduction to the model. Let,\n\n* $M$ = the number of *documents* in a corpus\n* $N$ = the average *length* of a document.\n* $V$ = the size of the *vocabulary* (the total number of unique words)\n\nWe denote a *document* by a vector $w \\in \\mathbb{R}^V$ where $w_i$ equals the number of times the $i$th word in the vocabulary occurs within the document. This is called the \"bag-of-words\" format of representing a document.\n\n$$\n\\underbrace{w}_{\\text{document}} = \\overbrace{\\big[ w_1, w_2, \\ldots, w_V \\big] }^{\\text{word counts}},\n\\quad\nV = \\text{vocabulary size}\n$$\n\nThe *length* of a document is equal to the total number of words in the document: $N_w = \\sum_{i=1}^V w_i$.\n\nAn LDA model is defined by two parameters: a topic-word distribution matrix $\\beta \\in \\mathbb{R}^{K \\times V}$ and a Dirichlet topic prior $\\alpha \\in \\mathbb{R}^K$. In particular, let,\n\n$$\\beta = \\left[ \\beta_1, \\ldots, \\beta_K \\right]$$\n\nbe a collection of $K$ *topics* where each topic $\\beta_k \\in \\mathbb{R}^V$ is represented as probability distribution over the vocabulary. One of the utilities of the LDA model is that a given word is allowed to appear in multiple topics with positive probability. The Dirichlet topic prior is a vector $\\alpha \\in \\mathbb{R}^K$ such that $\\alpha_k > 0$ for all $k$.","_____no_output_____"],["# Data Exploration\n\n---\n\n## An Example Dataset\n\nBefore explaining further let's get our hands dirty with an example dataset. The following synthetic data comes from [1] and comes with a very useful visual interpretation.\n\n> [1] Thomas Griffiths and Mark Steyvers. *Finding Scientific Topics.* Proceedings of the National Academy of Science, 101(suppl 1):5228-5235, 2004.","_____no_output_____"]],[["print(\"Generating example data...\")\nnum_documents = 6000\nknown_alpha, known_beta, documents, topic_mixtures = generate_griffiths_data(\n num_documents=num_documents, num_topics=10\n)\nnum_topics, vocabulary_size = known_beta.shape\n\n\n# separate the generated data into training and tests subsets\nnum_documents_training = int(0.9 * num_documents)\nnum_documents_test = num_documents - num_documents_training\n\ndocuments_training = documents[:num_documents_training]\ndocuments_test = documents[num_documents_training:]\n\ntopic_mixtures_training = topic_mixtures[:num_documents_training]\ntopic_mixtures_test = topic_mixtures[num_documents_training:]\n\nprint(\"documents_training.shape = {}\".format(documents_training.shape))\nprint(\"documents_test.shape = {}\".format(documents_test.shape))","_____no_output_____"]],[["Let's start by taking a closer look at the documents. Note that the vocabulary size of these data is $V = 25$. The average length of each document in this data set is 150. (See `generate_griffiths_data.py`.)","_____no_output_____"]],[["print(\"First training document =\\n{}\".format(documents_training[0]))\nprint(\"\\nVocabulary size = {}\".format(vocabulary_size))\nprint(\"Length of first document = {}\".format(documents_training[0].sum()))","_____no_output_____"],["average_document_length = documents.sum(axis=1).mean()\nprint(\"Observed average document length = {}\".format(average_document_length))","_____no_output_____"]],[["The example data set above also returns the LDA parameters,\n\n$$(\\alpha, \\beta)$$\n\nused to generate the documents. Let's examine the first topic and verify that it is a probability distribution on the vocabulary.","_____no_output_____"]],[["print(\"First topic =\\n{}\".format(known_beta[0]))\n\nprint(\n \"\\nTopic-word probability matrix (beta) shape: (num_topics, vocabulary_size) = {}\".format(\n known_beta.shape\n )\n)\nprint(\"\\nSum of elements of first topic = {}\".format(known_beta[0].sum()))","_____no_output_____"]],[["Unlike some clustering algorithms, one of the versatilities of the LDA model is that a given word can belong to multiple topics. The probability of that word occurring in each topic may differ, as well. This is reflective of real-world data where, for example, the word *\"rover\"* appears in a *\"dogs\"* topic as well as in a *\"space exploration\"* topic.\n\nIn our synthetic example dataset, the first word in the vocabulary belongs to both Topic #1 and Topic #6 with non-zero probability.","_____no_output_____"]],[["print(\"Topic #1:\\n{}\".format(known_beta[0]))\nprint(\"Topic #6:\\n{}\".format(known_beta[5]))","_____no_output_____"]],[["Human beings are visual creatures, so it might be helpful to come up with a visual representation of these documents.\n\nIn the below plots, each pixel of a document represents a word. The greyscale intensity is a measure of how frequently that word occurs within the document. Below we plot the first few documents of the training set reshaped into 5x5 pixel grids.","_____no_output_____"]],[["%matplotlib inline\n\nfig = plot_lda(documents_training, nrows=3, ncols=4, cmap=\"gray_r\", with_colorbar=True)\nfig.suptitle(\"$w$ - Document Word Counts\")\nfig.set_dpi(160)","_____no_output_____"]],[["When taking a close look at these documents we can see some patterns in the word distributions suggesting that, perhaps, each topic represents a \"column\" or \"row\" of words with non-zero probability and that each document is composed primarily of a handful of topics.\n\nBelow we plots the *known* topic-word probability distributions, $\\beta$. Similar to the documents we reshape each probability distribution to a $5 \\times 5$ pixel image where the color represents the probability of that each word occurring in the topic.","_____no_output_____"]],[["%matplotlib inline\n\nfig = plot_lda(known_beta, nrows=1, ncols=10)\nfig.suptitle(r\"Known $\\beta$ - Topic-Word Probability Distributions\")\nfig.set_dpi(160)\nfig.set_figheight(2)","_____no_output_____"]],[["These 10 topics were used to generate the document corpus. Next, we will learn about how this is done.","_____no_output_____"],["## Generating Documents\n\nLDA is a generative model, meaning that the LDA parameters $(\\alpha, \\beta)$ are used to construct documents word-by-word by drawing from the topic-word distributions. In fact, looking closely at the example documents above you can see that some documents sample more words from some topics than from others.\n\nLDA works as follows: given \n\n* $M$ documents $w^{(1)}, w^{(2)}, \\ldots, w^{(M)}$,\n* an average document length of $N$,\n* and an LDA model $(\\alpha, \\beta)$.\n\n**For** each document, $w^{(m)}$:\n* sample a topic mixture: $\\theta^{(m)} \\sim \\text{Dirichlet}(\\alpha)$\n* **For** each word $n$ in the document:\n * Sample a topic $z_n^{(m)} \\sim \\text{Multinomial}\\big( \\theta^{(m)} \\big)$\n * Sample a word from this topic, $w_n^{(m)} \\sim \\text{Multinomial}\\big( \\beta_{z_n^{(m)}} \\; \\big)$\n * Add to document\n\nThe [plate notation](https://en.wikipedia.org/wiki/Plate_notation) for the LDA model, introduced in [2], encapsulates this process pictorially.\n\n\n\n> [2] David M Blei, Andrew Y Ng, and Michael I Jordan. Latent Dirichlet Allocation. Journal of Machine Learning Research, 3(Jan):993–1022, 2003.","_____no_output_____"],["## Topic Mixtures\n\nFor the documents we generated above lets look at their corresponding topic mixtures, $\\theta \\in \\mathbb{R}^K$. The topic mixtures represent the probablility that a given word of the document is sampled from a particular topic. For example, if the topic mixture of an input document $w$ is,\n\n$$\\theta = \\left[ 0.3, 0.2, 0, 0.5, 0, \\ldots, 0 \\right]$$\n\nthen $w$ is 30% generated from the first topic, 20% from the second topic, and 50% from the fourth topic. In particular, the words contained in the document are sampled from the first topic-word probability distribution 30% of the time, from the second distribution 20% of the time, and the fourth disribution 50% of the time.\n\n\nThe objective of inference, also known as scoring, is to determine the most likely topic mixture of a given input document. Colloquially, this means figuring out which topics appear within a given document and at what ratios. We will perform infernece later in the [Inference](#Inference) section.\n\nSince we generated these example documents using the LDA model we know the topic mixture generating them. Let's examine these topic mixtures.","_____no_output_____"]],[["print(\"First training document =\\n{}\".format(documents_training[0]))\nprint(\"\\nVocabulary size = {}\".format(vocabulary_size))\nprint(\"Length of first document = {}\".format(documents_training[0].sum()))","_____no_output_____"],["print(\"First training document topic mixture =\\n{}\".format(topic_mixtures_training[0]))\nprint(\"\\nNumber of topics = {}\".format(num_topics))\nprint(\"sum(theta) = {}\".format(topic_mixtures_training[0].sum()))","_____no_output_____"]],[["We plot the first document along with its topic mixture. We also plot the topic-word probability distributions again for reference.","_____no_output_____"]],[["%matplotlib inline\n\nfig, (ax1, ax2) = plt.subplots(2, 1)\n\nax1.matshow(documents[0].reshape(5, 5), cmap=\"gray_r\")\nax1.set_title(r\"$w$ - Document\", fontsize=20)\nax1.set_xticks([])\nax1.set_yticks([])\n\ncax2 = ax2.matshow(topic_mixtures[0].reshape(1, -1), cmap=\"Reds\", vmin=0, vmax=1)\ncbar = fig.colorbar(cax2, orientation=\"horizontal\")\nax2.set_title(r\"$\\theta$ - Topic Mixture\", fontsize=20)\nax2.set_xticks([])\nax2.set_yticks([])\n\nfig.set_dpi(100)","_____no_output_____"],["%matplotlib inline\n\n# pot\nfig = plot_lda(known_beta, nrows=1, ncols=10)\nfig.suptitle(r\"Known $\\beta$ - Topic-Word Probability Distributions\")\nfig.set_dpi(160)\nfig.set_figheight(1.5)","_____no_output_____"]],[["Finally, let's plot several documents with their corresponding topic mixtures. We can see how topics with large weight in the document lead to more words in the document within the corresponding \"row\" or \"column\".","_____no_output_____"]],[["%matplotlib inline\n\nfig = plot_lda_topics(documents_training, 3, 4, topic_mixtures=topic_mixtures)\nfig.suptitle(r\"$(w,\\theta)$ - Documents with Known Topic Mixtures\")\nfig.set_dpi(160)","_____no_output_____"]],[["# Training\n\n***\n\nIn this section we will give some insight into how AWS SageMaker LDA fits an LDA model to a corpus, create an run a SageMaker LDA training job, and examine the output trained model.","_____no_output_____"],["## Topic Estimation using Tensor Decompositions\n\nGiven a document corpus, Amazon SageMaker LDA uses a spectral tensor decomposition technique to determine the LDA model $(\\alpha, \\beta)$ which most likely describes the corpus. See [1] for a primary reference of the theory behind the algorithm. The spectral decomposition, itself, is computed using the CPDecomp algorithm described in [2].\n\nThe overall idea is the following: given a corpus of documents $\\mathcal{W} = \\{w^{(1)}, \\ldots, w^{(M)}\\}, \\; w^{(m)} \\in \\mathbb{R}^V,$ we construct a statistic tensor,\n\n$$T \\in \\bigotimes^3 \\mathbb{R}^V$$\n\nsuch that the spectral decomposition of the tensor is approximately the LDA parameters $\\alpha \\in \\mathbb{R}^K$ and $\\beta \\in \\mathbb{R}^{K \\times V}$ which maximize the likelihood of observing the corpus for a given number of topics, $K$,\n\n$$T \\approx \\sum_{k=1}^K \\alpha_k \\; (\\beta_k \\otimes \\beta_k \\otimes \\beta_k)$$\n\nThis statistic tensor encapsulates information from the corpus such as the document mean, cross correlation, and higher order statistics. For details, see [1].\n\n\n> [1] Animashree Anandkumar, Rong Ge, Daniel Hsu, Sham Kakade, and Matus Telgarsky. *\"Tensor Decompositions for Learning Latent Variable Models\"*, Journal of Machine Learning Research, 15:2773–2832, 2014.\n>\n> [2] Tamara Kolda and Brett Bader. *\"Tensor Decompositions and Applications\"*. SIAM Review, 51(3):455–500, 2009.\n\n\n","_____no_output_____"],["## Store Data on S3\n\nBefore we run training we need to prepare the data.\n\nA SageMaker training job needs access to training data stored in an S3 bucket. Although training can accept data of various formats we convert the documents MXNet RecordIO Protobuf format before uploading to the S3 bucket defined at the beginning of this notebook.","_____no_output_____"]],[["# convert documents_training to Protobuf RecordIO format\nrecordio_protobuf_serializer = RecordSerializer()\nfbuffer = recordio_protobuf_serializer.serialize(documents_training)\n\n# upload to S3 in bucket/prefix/train\nfname = \"lda.data\"\ns3_object = os.path.join(prefix, \"train\", fname)\nboto3.Session().resource(\"s3\").Bucket(bucket).Object(s3_object).upload_fileobj(fbuffer)\n\ns3_train_data = \"s3://{}/{}\".format(bucket, s3_object)\nprint(\"Uploaded data to S3: {}\".format(s3_train_data))","_____no_output_____"]],[["Next, we specify a Docker container containing the SageMaker LDA algorithm. For your convenience, a region-specific container is automatically chosen for you to minimize cross-region data communication","_____no_output_____"]],[["from sagemaker.image_uris import retrieve\n\nregion_name = boto3.Session().region_name\ncontainer = retrieve(\"lda\", boto3.Session().region_name)\n\nprint(\"Using SageMaker LDA container: {} ({})\".format(container, region_name))","_____no_output_____"]],[["## Training Parameters\n\nParticular to a SageMaker LDA training job are the following hyperparameters:\n\n* **`num_topics`** - The number of topics or categories in the LDA model.\n * Usually, this is not known a priori.\n * In this example, howevever, we know that the data is generated by five topics.\n\n* **`feature_dim`** - The size of the *\"vocabulary\"*, in LDA parlance.\n * In this example, this is equal 25.\n\n* **`mini_batch_size`** - The number of input training documents.\n\n* **`alpha0`** - *(optional)* a measurement of how \"mixed\" are the topic-mixtures.\n * When `alpha0` is small the data tends to be represented by one or few topics.\n * When `alpha0` is large the data tends to be an even combination of several or many topics.\n * The default value is `alpha0 = 1.0`.\n\nIn addition to these LDA model hyperparameters, we provide additional parameters defining things like the EC2 instance type on which training will run, the S3 bucket containing the data, and the AWS access role. Note that,\n\n* Recommended instance type: `ml.c4`\n* Current limitations:\n * SageMaker LDA *training* can only run on a single instance.\n * SageMaker LDA does not take advantage of GPU hardware.\n * (The Amazon AI Algorithms team is working hard to provide these capabilities in a future release!)","_____no_output_____"],["Using the above configuration create a SageMaker client and use the client to create a training job.","_____no_output_____"]],[["session = sagemaker.Session()\n\n# specify general training job information\nlda = sagemaker.estimator.Estimator(\n container,\n role,\n output_path=\"s3://{}/{}/output\".format(bucket, prefix),\n instance_count=1,\n instance_type=\"ml.c4.2xlarge\",\n sagemaker_session=session,\n)\n\n# set algorithm-specific hyperparameters\nlda.set_hyperparameters(\n num_topics=num_topics,\n feature_dim=vocabulary_size,\n mini_batch_size=num_documents_training,\n alpha0=1.0,\n)\n\n# run the training job on input data stored in S3\nlda.fit({\"train\": s3_train_data})","_____no_output_____"]],[["If you see the message\n\n> `===== Job Complete =====`\n\nat the bottom of the output logs then that means training sucessfully completed and the output LDA model was stored in the specified output path. You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the \"Jobs\" tab and select training job matching the training job name, below:","_____no_output_____"]],[["print(\"Training job name: {}\".format(lda.latest_training_job.job_name))","_____no_output_____"]],[["## Inspecting the Trained Model\n\nWe know the LDA parameters $(\\alpha, \\beta)$ used to generate the example data. How does the learned model compare the known one? In this section we will download the model data and measure how well SageMaker LDA did in learning the model.\n\nFirst, we download the model data. SageMaker will output the model in \n\n> `s3://
Source:\\\n \\\n World Happiness Report',\n geo = dict(\n showframe = False,\n showcoastlines = False,\n projection = dict(\n type = 'Mercator'\n )\n )\n)\n\n#Create World Map Plot \nfig = dict(data = data, layout = layout)\npy.iplot(fig, validate=False, filename='d3-world-map')\n","_____no_output_____"],["df1 = pd.read_excel('whr.xlsx', sheetname='Figure2.2 WHR 2017')\n\n#Stacked Bar Plot \ntrace1 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: GDP per capita'], \n orientation = 'h', \n width = .5, \n name = 'GDP per Capita', \n marker=dict(\n color='rgb(140,101,211)'\n )\n)\ntrace2 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: Social support'], \n orientation = 'h', \n width = .5, \n name = 'Social Support', \n marker=dict(\n color='rgb(154,147,236)'\n )\n)\ntrace3 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: Healthy life expectancy'], \n orientation = 'h', \n width = .5,\n name = 'Healthy Life Expectancy', \n marker=dict(\n color='rgb(0,82,165)'\n )\n)\ntrace4 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: Freedom to make life choices'], \n orientation = 'h', \n width = .5, \n name = 'Freedom to Make Life Choices', \n marker=dict(\n color='rgb(129,203,248)'\n )\n)\ntrace5 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: Generosity'], \n orientation = 'h', \n width = .5, \n name = 'Generosity', \n marker=dict(\n color='rgb(65,179,247)'\n )\n)\ntrace6 = go.Bar(\n y = df1['Country'],\n x = df1['Explained by: Perceptions of corruption'], \n orientation = 'h', \n width = .5, \n name = 'Perceptions on Corruption', \n marker=dict(\n color='rgb(115, 235, 174)'\n )\n)\n\n\ndata = [trace1, trace2, trace3, trace4, trace5, trace6]\nlayout = go.Layout(\n title = 'Factor Makeup of Happiness Scores',\n barmode ='stack', \n autosize = False,\n width = 800,\n height = 1500,\n yaxis = dict(\n tickfont = dict(\n size = 6,\n color = 'black')),\n xaxis = dict(\n tickfont = dict(\n size = 10, \n color = 'black'))\n)\n\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig, filename='stacked-horizontal-bar')","_____no_output_____"],["import plotly.plotly as py\nfrom plotly.grid_objs import Grid, Column\nfrom plotly.figure_factory import *\n\nimport pandas as pd\nimport time\n\nxls_file = pd.ExcelFile('Internet_Usage.xls')\nxls_file\ndataset = xls_file.parse('Sheet1')\ndataset.head()","_____no_output_____"],["years_from_col = set(dataset['year'])\nyears_ints = sorted(list(years_from_col))\nyears = [str(year) for year in years_ints]\n\n\n# make list of continents\ncontinents = []\nfor continent in dataset['continent']:\n if continent not in continents: \n continents.append(continent)\n\ncolumns = []\n# make grid\nfor year in years:\n for continent in continents:\n dataset_by_year = dataset[dataset['year'] == int(year)]\n dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent]\n for col_name in dataset_by_year_and_cont:\n # each column name is unique\n column_name = '{year}_{continent}_{header}_gapminder_grid'.format(\n year=year, continent=continent, header=col_name\n )\n a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name)\n columns.append(a_column)\n\n# upload grid\ngrid = Grid(columns)\nurl = py.grid_ops.upload(grid, 'gapminder_grid'+str(time.time()), auto_open=False)\nurl","_____no_output_____"],["figure = {\n 'data': [],\n 'layout': {},\n 'frames': [],\n 'config': {'scrollzoom': True}\n}\n\n# fill in most of layout\nfigure['layout']['xaxis'] = {'range': [2, 8], 'title': 'World Happiness Score', 'gridcolor': '#FFFFFF'}\nfigure['layout']['yaxis'] = {'range': [0,100],'title': 'Internet Usage % of Pop.', 'gridcolor': '#FFFFFF'}\nfigure['layout']['hovermode'] = 'closest'\nfigure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)'","_____no_output_____"],["sliders_dict = {\n 'active': 0,\n 'yanchor': 'top',\n 'xanchor': 'left',\n 'currentvalue': {\n 'font': {'size': 20},\n 'prefix': 'Year:',\n 'visible': True,\n 'xanchor': 'right'\n },\n 'transition': {'duration': 300, 'easing': 'cubic-in-out'},\n 'pad': {'b': 10, 't': 50},\n 'len': 0.9,\n 'x': 0.1,\n 'y': 0,\n 'steps': []\n}\n","_____no_output_____"],["figure['layout']['updatemenus'] = [\n {\n 'buttons': [\n {\n 'args': [None, {'frame': {'duration': 500, 'redraw': False},\n 'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],\n 'label': 'Play',\n 'method': 'animate'\n },\n {\n 'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',\n 'transition': {'duration': 0}}],\n 'label': 'Pause',\n 'method': 'animate'\n }\n ],\n 'direction': 'left',\n 'pad': {'r': 10, 't': 87},\n 'showactive': False,\n 'type': 'buttons',\n 'x': 0.1,\n 'xanchor': 'right',\n 'y': 0,\n 'yanchor': 'top'\n }\n]\n\ncustom_colors = {\n 'Asia': 'rgb(171, 99, 250)',\n 'Europe': 'rgb(230, 99, 250)',\n 'Africa': 'rgb(99, 110, 250)',\n 'Americas': 'rgb(25, 211, 243)',\n 'Oceania': 'rgb(50, 170, 255)'\n}","_____no_output_____"],["col_name_template = '{year}_{continent}_{header}_gapminder_grid'\nyear = 2007\nfor continent in continents:\n data_dict = {\n 'xsrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='lifeExp'\n )),\n 'ysrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='gdpPercap'\n )),\n 'mode': 'markers',\n 'textsrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='country'\n )),\n 'marker': {\n 'sizemode': 'area',\n 'sizeref': 2000,\n 'sizesrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='pop'\n )),\n 'color': custom_colors[continent]\n },\n 'name': continent\n }\n figure['data'].append(data_dict)","_____no_output_____"],["for year in years:\n frame = {'data': [], 'name': str(year)}\n for continent in continents:\n data_dict = {\n 'xsrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='lifeExp'\n )),\n 'ysrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='gdpPercap'\n )),\n 'mode': 'markers',\n 'textsrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='country'\n )),\n 'marker': {\n 'sizemode': 'area',\n 'sizeref': 2000,\n 'sizesrc': grid.get_column_reference(col_name_template.format(\n year=year, continent=continent, header='pop'\n )),\n 'color': custom_colors[continent]\n },\n 'name': continent\n }\n frame['data'].append(data_dict)\n\n figure['frames'].append(frame)\n slider_step = {'args': [\n [year],\n {'frame': {'duration': 300, 'redraw': False},\n 'mode': 'immediate',\n 'transition': {'duration': 300}}\n ],\n 'label': year,\n 'method': 'animate'}\n sliders_dict['steps'].append(slider_step)\n\nfigure['layout']['sliders'] = [sliders_dict]","_____no_output_____"],["py.icreate_animations(figure, 'gapminder_example'+str(time.time()))","_____no_output_____"]]],"string":"[\n [\n [\n \"##World Map Plotly \\n\\n#Import Plotly Lib and Set up Credentials with personal account\\n!pip install plotly \\n\\nimport plotly\\n\\nplotly.tools.set_credentials_file(username='igleonaitis', api_key='If6Wh3xWNmdNioPzOZZo')\\nplotly.tools.set_config_file(world_readable=True,\\n sharing='public')\\nimport plotly.plotly as py\\nfrom plotly.graph_objs import *\\nimport plotly.graph_objs as go\\nimport pandas as pd\",\n \"Requirement already satisfied: plotly in /opt/conda/lib/python3.6/site-packages\\nRequirement already satisfied: requests in /opt/conda/lib/python3.6/site-packages (from plotly)\\nRequirement already satisfied: six in /opt/conda/lib/python3.6/site-packages (from plotly)\\nRequirement already satisfied: nbformat>=4.2 in /opt/conda/lib/python3.6/site-packages (from plotly)\\nRequirement already satisfied: pytz in /opt/conda/lib/python3.6/site-packages (from plotly)\\nRequirement already satisfied: decorator>=4.0.6 in /opt/conda/lib/python3.6/site-packages (from plotly)\\n\"\n ],\n [\n \"#Import WHR 2017 data set \\ndf = pd.read_excel('whr.xlsx', sheetname='Figure2.2 WHR 2017')\\n\\n#Set Up World Map Plot\\n\\nscl = [[0,'rgb(140,101,211)'],[0.25,'rgb(154,147,236)'],\\n [0.50,'rgb(0,82,165)'],[0.75,'rgb(129,203,248)'],\\n [1,'rgb(65,179,247)']]\\n\\n\\ndata = [ dict(\\n type = 'choropleth',\\n locationmode = 'country names',\\n locations = df['Country'],\\n z = df['Happiness score'],\\n text = df['Country'],\\n colorscale = scl,\\n autocolorscale = False,\\n reversescale = False,\\n marker = dict(\\n line = dict (\\n color = 'rgb(180,180,180)',\\n width = 0.5\\n ) ),\\n colorbar = dict(\\n autotick = False,\\n tickprefix = False,\\n title = 'World Happiness Score'),\\n ) ]\\n\\nlayout = dict(\\n title = '2017 National Happiness Scores GDP
Source:\\\\\\n \\\\\\n World Happiness Report',\\n geo = dict(\\n showframe = False,\\n showcoastlines = False,\\n projection = dict(\\n type = 'Mercator'\\n )\\n )\\n)\\n\\n#Create World Map Plot \\nfig = dict(data = data, layout = layout)\\npy.iplot(fig, validate=False, filename='d3-world-map')\\n\",\n \"_____no_output_____\"\n ],\n [\n \"df1 = pd.read_excel('whr.xlsx', sheetname='Figure2.2 WHR 2017')\\n\\n#Stacked Bar Plot \\ntrace1 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: GDP per capita'], \\n orientation = 'h', \\n width = .5, \\n name = 'GDP per Capita', \\n marker=dict(\\n color='rgb(140,101,211)'\\n )\\n)\\ntrace2 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: Social support'], \\n orientation = 'h', \\n width = .5, \\n name = 'Social Support', \\n marker=dict(\\n color='rgb(154,147,236)'\\n )\\n)\\ntrace3 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: Healthy life expectancy'], \\n orientation = 'h', \\n width = .5,\\n name = 'Healthy Life Expectancy', \\n marker=dict(\\n color='rgb(0,82,165)'\\n )\\n)\\ntrace4 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: Freedom to make life choices'], \\n orientation = 'h', \\n width = .5, \\n name = 'Freedom to Make Life Choices', \\n marker=dict(\\n color='rgb(129,203,248)'\\n )\\n)\\ntrace5 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: Generosity'], \\n orientation = 'h', \\n width = .5, \\n name = 'Generosity', \\n marker=dict(\\n color='rgb(65,179,247)'\\n )\\n)\\ntrace6 = go.Bar(\\n y = df1['Country'],\\n x = df1['Explained by: Perceptions of corruption'], \\n orientation = 'h', \\n width = .5, \\n name = 'Perceptions on Corruption', \\n marker=dict(\\n color='rgb(115, 235, 174)'\\n )\\n)\\n\\n\\ndata = [trace1, trace2, trace3, trace4, trace5, trace6]\\nlayout = go.Layout(\\n title = 'Factor Makeup of Happiness Scores',\\n barmode ='stack', \\n autosize = False,\\n width = 800,\\n height = 1500,\\n yaxis = dict(\\n tickfont = dict(\\n size = 6,\\n color = 'black')),\\n xaxis = dict(\\n tickfont = dict(\\n size = 10, \\n color = 'black'))\\n)\\n\\nfig = go.Figure(data=data, layout=layout)\\npy.iplot(fig, filename='stacked-horizontal-bar')\",\n \"_____no_output_____\"\n ],\n [\n \"import plotly.plotly as py\\nfrom plotly.grid_objs import Grid, Column\\nfrom plotly.figure_factory import *\\n\\nimport pandas as pd\\nimport time\\n\\nxls_file = pd.ExcelFile('Internet_Usage.xls')\\nxls_file\\ndataset = xls_file.parse('Sheet1')\\ndataset.head()\",\n \"_____no_output_____\"\n ],\n [\n \"years_from_col = set(dataset['year'])\\nyears_ints = sorted(list(years_from_col))\\nyears = [str(year) for year in years_ints]\\n\\n\\n# make list of continents\\ncontinents = []\\nfor continent in dataset['continent']:\\n if continent not in continents: \\n continents.append(continent)\\n\\ncolumns = []\\n# make grid\\nfor year in years:\\n for continent in continents:\\n dataset_by_year = dataset[dataset['year'] == int(year)]\\n dataset_by_year_and_cont = dataset_by_year[dataset_by_year['continent'] == continent]\\n for col_name in dataset_by_year_and_cont:\\n # each column name is unique\\n column_name = '{year}_{continent}_{header}_gapminder_grid'.format(\\n year=year, continent=continent, header=col_name\\n )\\n a_column = Column(list(dataset_by_year_and_cont[col_name]), column_name)\\n columns.append(a_column)\\n\\n# upload grid\\ngrid = Grid(columns)\\nurl = py.grid_ops.upload(grid, 'gapminder_grid'+str(time.time()), auto_open=False)\\nurl\",\n \"_____no_output_____\"\n ],\n [\n \"figure = {\\n 'data': [],\\n 'layout': {},\\n 'frames': [],\\n 'config': {'scrollzoom': True}\\n}\\n\\n# fill in most of layout\\nfigure['layout']['xaxis'] = {'range': [2, 8], 'title': 'World Happiness Score', 'gridcolor': '#FFFFFF'}\\nfigure['layout']['yaxis'] = {'range': [0,100],'title': 'Internet Usage % of Pop.', 'gridcolor': '#FFFFFF'}\\nfigure['layout']['hovermode'] = 'closest'\\nfigure['layout']['plot_bgcolor'] = 'rgb(223, 232, 243)'\",\n \"_____no_output_____\"\n ],\n [\n \"sliders_dict = {\\n 'active': 0,\\n 'yanchor': 'top',\\n 'xanchor': 'left',\\n 'currentvalue': {\\n 'font': {'size': 20},\\n 'prefix': 'Year:',\\n 'visible': True,\\n 'xanchor': 'right'\\n },\\n 'transition': {'duration': 300, 'easing': 'cubic-in-out'},\\n 'pad': {'b': 10, 't': 50},\\n 'len': 0.9,\\n 'x': 0.1,\\n 'y': 0,\\n 'steps': []\\n}\\n\",\n \"_____no_output_____\"\n ],\n [\n \"figure['layout']['updatemenus'] = [\\n {\\n 'buttons': [\\n {\\n 'args': [None, {'frame': {'duration': 500, 'redraw': False},\\n 'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],\\n 'label': 'Play',\\n 'method': 'animate'\\n },\\n {\\n 'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',\\n 'transition': {'duration': 0}}],\\n 'label': 'Pause',\\n 'method': 'animate'\\n }\\n ],\\n 'direction': 'left',\\n 'pad': {'r': 10, 't': 87},\\n 'showactive': False,\\n 'type': 'buttons',\\n 'x': 0.1,\\n 'xanchor': 'right',\\n 'y': 0,\\n 'yanchor': 'top'\\n }\\n]\\n\\ncustom_colors = {\\n 'Asia': 'rgb(171, 99, 250)',\\n 'Europe': 'rgb(230, 99, 250)',\\n 'Africa': 'rgb(99, 110, 250)',\\n 'Americas': 'rgb(25, 211, 243)',\\n 'Oceania': 'rgb(50, 170, 255)'\\n}\",\n \"_____no_output_____\"\n ],\n [\n \"col_name_template = '{year}_{continent}_{header}_gapminder_grid'\\nyear = 2007\\nfor continent in continents:\\n data_dict = {\\n 'xsrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='lifeExp'\\n )),\\n 'ysrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='gdpPercap'\\n )),\\n 'mode': 'markers',\\n 'textsrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='country'\\n )),\\n 'marker': {\\n 'sizemode': 'area',\\n 'sizeref': 2000,\\n 'sizesrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='pop'\\n )),\\n 'color': custom_colors[continent]\\n },\\n 'name': continent\\n }\\n figure['data'].append(data_dict)\",\n \"_____no_output_____\"\n ],\n [\n \"for year in years:\\n frame = {'data': [], 'name': str(year)}\\n for continent in continents:\\n data_dict = {\\n 'xsrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='lifeExp'\\n )),\\n 'ysrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='gdpPercap'\\n )),\\n 'mode': 'markers',\\n 'textsrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='country'\\n )),\\n 'marker': {\\n 'sizemode': 'area',\\n 'sizeref': 2000,\\n 'sizesrc': grid.get_column_reference(col_name_template.format(\\n year=year, continent=continent, header='pop'\\n )),\\n 'color': custom_colors[continent]\\n },\\n 'name': continent\\n }\\n frame['data'].append(data_dict)\\n\\n figure['frames'].append(frame)\\n slider_step = {'args': [\\n [year],\\n {'frame': {'duration': 300, 'redraw': False},\\n 'mode': 'immediate',\\n 'transition': {'duration': 300}}\\n ],\\n 'label': year,\\n 'method': 'animate'}\\n sliders_dict['steps'].append(slider_step)\\n\\nfigure['layout']['sliders'] = [sliders_dict]\",\n \"_____no_output_____\"\n ],\n [\n \"py.icreate_animations(figure, 'gapminder_example'+str(time.time()))\",\n \"_____no_output_____\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["code"],"string":"[\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["code","code","code","code","code","code","code","code","code","code","code"]],"string":"[\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}},{"rowIdx":599,"cells":{"hexsha":{"kind":"string","value":"d01b458aef43dd1337482e9b30957cbd8bac1624"},"size":{"kind":"number","value":50861,"string":"50,861"},"ext":{"kind":"string","value":"ipynb"},"lang":{"kind":"string","value":"Jupyter Notebook"},"max_stars_repo_path":{"kind":"string","value":"training/Training_edges_hog_gray.ipynb"},"max_stars_repo_name":{"kind":"string","value":"OpenGridMap/power-grid-detection"},"max_stars_repo_head_hexsha":{"kind":"string","value":"221fcf0461dc869c8c64b11fa48596f83c20e1c8"},"max_stars_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_stars_count":{"kind":"null"},"max_stars_repo_stars_event_min_datetime":{"kind":"null"},"max_stars_repo_stars_event_max_datetime":{"kind":"null"},"max_issues_repo_path":{"kind":"string","value":"training/Training_edges_hog_gray.ipynb"},"max_issues_repo_name":{"kind":"string","value":"OpenGridMap/power-grid-detection"},"max_issues_repo_head_hexsha":{"kind":"string","value":"221fcf0461dc869c8c64b11fa48596f83c20e1c8"},"max_issues_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_issues_count":{"kind":"number","value":1,"string":"1"},"max_issues_repo_issues_event_min_datetime":{"kind":"string","value":"2018-07-22T22:43:27.000Z"},"max_issues_repo_issues_event_max_datetime":{"kind":"string","value":"2018-07-22T22:43:27.000Z"},"max_forks_repo_path":{"kind":"string","value":"training/Training_edges_hog_gray.ipynb"},"max_forks_repo_name":{"kind":"string","value":"OpenGridMap/power-grid-detection"},"max_forks_repo_head_hexsha":{"kind":"string","value":"221fcf0461dc869c8c64b11fa48596f83c20e1c8"},"max_forks_repo_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"max_forks_count":{"kind":"null"},"max_forks_repo_forks_event_min_datetime":{"kind":"null"},"max_forks_repo_forks_event_max_datetime":{"kind":"null"},"avg_line_length":{"kind":"number","value":85.7689713322,"string":"85.768971"},"max_line_length":{"kind":"number","value":1362,"string":"1,362"},"alphanum_fraction":{"kind":"number","value":0.5497139262,"string":"0.549714"},"cells":{"kind":"list like","value":[[["from __future__ import print_function\n\nimport os\nimport sys\nimport numpy as np\n\nfrom keras.optimizers import SGD\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\n\nsys.path.append(os.path.join(os.getcwd(), os.pardir))\n\nimport config\n\nfrom utils.dataset.data_generator import DataGenerator\nfrom models.cnn3 import cnn","Using Theano backend.\nUsing gpu device 1: GeForce GTX 680 (CNMeM is disabled, cuDNN 5005)\n"],["lr=0.001\nn_epochs=500\nbatch_size=32\ninput_shape=(140, 140, 3)\n\nname = 'cnn_140_edges_hog_grey_lr_%f_nesterov' % lr","_____no_output_____"],["print('loading model...')\nmodel = cnn(input_shape=input_shape)\nmodel.summary()\n\noptimizer = SGD(lr=lr, clipnorm=1., clipvalue=0.5, nesterov=True)\n\nprint('compiling model...')\nmodel.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])\nprint('done.')\n\ncsv_logger = CSVLogger('%s_training.log' % name)\nbest_model_checkpointer = ModelCheckpoint(filepath=(\"./%s_training_weights_best.hdf5\" % name), verbose=1,\n save_best_only=True)\n\ncurrent_model_checkpointer = ModelCheckpoint(filepath=(\"./%s_training_weights_current.hdf5\" % name), verbose=0)","loading model...\n____________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n====================================================================================================\ninput_1 (InputLayer) (None, 140, 140, 3) 0 \n____________________________________________________________________________________________________\nconvolution2d_1 (Convolution2D) (None, 140, 140, 128) 18944 input_1[0][0] \n____________________________________________________________________________________________________\nactivation_1 (Activation) (None, 140, 140, 128) 0 convolution2d_1[0][0] \n____________________________________________________________________________________________________\nmaxpooling2d_1 (MaxPooling2D) (None, 70, 70, 128) 0 activation_1[0][0] \n____________________________________________________________________________________________________\nconvolution2d_2 (Convolution2D) (None, 70, 70, 64) 204864 maxpooling2d_1[0][0] \n____________________________________________________________________________________________________\nactivation_2 (Activation) (None, 70, 70, 64) 0 convolution2d_2[0][0] \n____________________________________________________________________________________________________\nmaxpooling2d_2 (MaxPooling2D) (None, 35, 35, 64) 0 activation_2[0][0] \n____________________________________________________________________________________________________\nconvolution2d_3 (Convolution2D) (None, 35, 35, 64) 36928 maxpooling2d_2[0][0] \n____________________________________________________________________________________________________\nactivation_3 (Activation) (None, 35, 35, 64) 0 convolution2d_3[0][0] \n____________________________________________________________________________________________________\nmaxpooling2d_3 (MaxPooling2D) (None, 17, 17, 64) 0 activation_3[0][0] \n____________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 18496) 0 maxpooling2d_3[0][0] \n____________________________________________________________________________________________________\ndense_1 (Dense) (None, 1024) 18940928 flatten_1[0][0] \n____________________________________________________________________________________________________\ndense_2 (Dense) (None, 1024) 1049600 dense_1[0][0] \n____________________________________________________________________________________________________\ndense_3 (Dense) (None, 512) 524800 dense_2[0][0] \n____________________________________________________________________________________________________\ndense_4 (Dense) (None, 2) 1026 dense_3[0][0] \n____________________________________________________________________________________________________\nactivation_4 (Activation) (None, 2) 0 dense_4[0][0] \n====================================================================================================\nTotal params: 20777090\n____________________________________________________________________________________________________\ncompiling model...\ndone.\n"],["print('Initializing data generators...')\ntrain_data_gen = DataGenerator(dataset_file=config.train_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\nvalidation_data_gen = DataGenerator(dataset_file=config.validation_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\ntest_data_gen = DataGenerator(dataset_file=config.test_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\nprint('done.')","Initializing data generators...\ndone.\n"],["print('Fitting model...')\nhistory = model.fit_generator(train_data_gen,\n nb_epoch=n_epochs,\n samples_per_epoch=train_data_gen.n_batches * batch_size,\n validation_data=validation_data_gen,\n nb_val_samples=validation_data_gen.n_samples,\n verbose=1,\n callbacks=[csv_logger, best_model_checkpointer, current_model_checkpointer])\nprint('done.')","Fitting model...\nEpoch 1/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6842 - acc: 0.6566Epoch 00000: val_loss improved from inf to 0.67410, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 383s - loss: 0.6842 - acc: 0.6563 - val_loss: 0.6741 - val_acc: 0.6734\nEpoch 2/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6676 - acc: 0.6650Epoch 00001: val_loss improved from 0.67410 to 0.65905, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.6677 - acc: 0.6647 - val_loss: 0.6590 - val_acc: 0.6725\nEpoch 3/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6552 - acc: 0.6650Epoch 00002: val_loss improved from 0.65905 to 0.64789, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.6553 - acc: 0.6647 - val_loss: 0.6479 - val_acc: 0.6721\nEpoch 4/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6461 - acc: 0.6650Epoch 00003: val_loss improved from 0.64789 to 0.64012, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 382s - loss: 0.6463 - acc: 0.6647 - val_loss: 0.6401 - val_acc: 0.6708\nEpoch 5/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6390 - acc: 0.6650Epoch 00004: val_loss improved from 0.64012 to 0.63145, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 383s - loss: 0.6392 - acc: 0.6647 - val_loss: 0.6315 - val_acc: 0.6743\nEpoch 6/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6315 - acc: 0.6650Epoch 00005: val_loss improved from 0.63145 to 0.62386, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.6317 - acc: 0.6647 - val_loss: 0.6239 - val_acc: 0.6725\nEpoch 7/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6199 - acc: 0.6650Epoch 00006: val_loss improved from 0.62386 to 0.60869, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.6201 - acc: 0.6647 - val_loss: 0.6087 - val_acc: 0.6734\nEpoch 8/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5970 - acc: 0.6650Epoch 00007: val_loss improved from 0.60869 to 0.58061, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.5971 - acc: 0.6647 - val_loss: 0.5806 - val_acc: 0.6710\nEpoch 9/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5553 - acc: 0.6785Epoch 00008: val_loss improved from 0.58061 to 0.53442, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.5555 - acc: 0.6782 - val_loss: 0.5344 - val_acc: 0.7088\nEpoch 10/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5123 - acc: 0.7105Epoch 00009: val_loss improved from 0.53442 to 0.49943, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.5126 - acc: 0.7102 - val_loss: 0.4994 - val_acc: 0.7326\nEpoch 11/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4847 - acc: 0.7317Epoch 00010: val_loss improved from 0.49943 to 0.48177, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4850 - acc: 0.7315 - val_loss: 0.4818 - val_acc: 0.7476\nEpoch 12/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4708 - acc: 0.7444Epoch 00011: val_loss improved from 0.48177 to 0.47363, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 382s - loss: 0.4711 - acc: 0.7441 - val_loss: 0.4736 - val_acc: 0.7548\nEpoch 13/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4637 - acc: 0.7512Epoch 00012: val_loss improved from 0.47363 to 0.46965, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4640 - acc: 0.7509 - val_loss: 0.4696 - val_acc: 0.7597\nEpoch 14/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4594 - acc: 0.7546Epoch 00013: val_loss improved from 0.46965 to 0.46501, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4597 - acc: 0.7542 - val_loss: 0.4650 - val_acc: 0.7647\nEpoch 15/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4566 - acc: 0.7571Epoch 00014: val_loss improved from 0.46501 to 0.46349, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4569 - acc: 0.7568 - val_loss: 0.4635 - val_acc: 0.7650\nEpoch 16/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4546 - acc: 0.7588Epoch 00015: val_loss improved from 0.46349 to 0.46234, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4550 - acc: 0.7585 - val_loss: 0.4623 - val_acc: 0.7678\nEpoch 17/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4530 - acc: 0.7603Epoch 00016: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4533 - acc: 0.7600 - val_loss: 0.4636 - val_acc: 0.7672\nEpoch 18/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4517 - acc: 0.7611Epoch 00017: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4520 - acc: 0.7608 - val_loss: 0.4634 - val_acc: 0.7687\nEpoch 19/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4505 - acc: 0.7616Epoch 00018: val_loss improved from 0.46234 to 0.46121, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4508 - acc: 0.7613 - val_loss: 0.4612 - val_acc: 0.7698\nEpoch 20/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4494 - acc: 0.7618Epoch 00019: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4498 - acc: 0.7615 - val_loss: 0.4615 - val_acc: 0.7696\nEpoch 21/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4485 - acc: 0.7621Epoch 00020: val_loss improved from 0.46121 to 0.45922, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4488 - acc: 0.7619 - val_loss: 0.4592 - val_acc: 0.7691\nEpoch 22/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4476 - acc: 0.7620Epoch 00021: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4479 - acc: 0.7618 - val_loss: 0.4592 - val_acc: 0.7685\nEpoch 23/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4467 - acc: 0.7623Epoch 00022: val_loss improved from 0.45922 to 0.45754, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4471 - acc: 0.7620 - val_loss: 0.4575 - val_acc: 0.7687\nEpoch 24/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4459 - acc: 0.7622Epoch 00023: val_loss improved from 0.45754 to 0.45556, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4463 - acc: 0.7619 - val_loss: 0.4556 - val_acc: 0.7687\nEpoch 25/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4452 - acc: 0.7624Epoch 00024: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4456 - acc: 0.7621 - val_loss: 0.4590 - val_acc: 0.7667\nEpoch 26/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4445 - acc: 0.7629Epoch 00025: val_loss improved from 0.45556 to 0.45485, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4448 - acc: 0.7626 - val_loss: 0.4548 - val_acc: 0.7683\nEpoch 27/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4439 - acc: 0.7631Epoch 00026: val_loss improved from 0.45485 to 0.45355, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4442 - acc: 0.7628 - val_loss: 0.4536 - val_acc: 0.7685\nEpoch 28/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4433 - acc: 0.7633Epoch 00027: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4436 - acc: 0.7630 - val_loss: 0.4544 - val_acc: 0.7683\nEpoch 29/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4427 - acc: 0.7636Epoch 00028: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4431 - acc: 0.7633 - val_loss: 0.4539 - val_acc: 0.7669\nEpoch 30/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4421 - acc: 0.7639Epoch 00029: val_loss improved from 0.45355 to 0.45310, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4424 - acc: 0.7636 - val_loss: 0.4531 - val_acc: 0.7678\nEpoch 31/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4415 - acc: 0.7642Epoch 00030: val_loss did not improve\n10496/10496 [==============================] - 381s - loss: 0.4419 - acc: 0.7639 - val_loss: 0.4549 - val_acc: 0.7665\nEpoch 32/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4410 - acc: 0.7640Epoch 00031: val_loss improved from 0.45310 to 0.45002, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 382s - loss: 0.4414 - acc: 0.7637 - val_loss: 0.4500 - val_acc: 0.7678\nEpoch 33/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4405 - acc: 0.7640Epoch 00032: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4409 - acc: 0.7637 - val_loss: 0.4517 - val_acc: 0.7669\nEpoch 34/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4400 - acc: 0.7642Epoch 00033: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4404 - acc: 0.7640 - val_loss: 0.4529 - val_acc: 0.7654\nEpoch 35/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4396 - acc: 0.7643Epoch 00034: val_loss improved from 0.45002 to 0.44926, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4399 - acc: 0.7641 - val_loss: 0.4493 - val_acc: 0.7667\nEpoch 36/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4391 - acc: 0.7644Epoch 00035: val_loss did not improve\n10496/10496 [==============================] - 382s - loss: 0.4395 - acc: 0.7642 - val_loss: 0.4505 - val_acc: 0.7661\nEpoch 37/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4386 - acc: 0.7645Epoch 00036: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4390 - acc: 0.7642 - val_loss: 0.4522 - val_acc: 0.7652\nEpoch 38/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4382 - acc: 0.7648Epoch 00037: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4385 - acc: 0.7645 - val_loss: 0.4501 - val_acc: 0.7652\nEpoch 39/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4377 - acc: 0.7648Epoch 00038: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4380 - acc: 0.7646 - val_loss: 0.4541 - val_acc: 0.7636\nEpoch 40/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4372 - acc: 0.7648Epoch 00039: val_loss improved from 0.44926 to 0.44773, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4376 - acc: 0.7646 - val_loss: 0.4477 - val_acc: 0.7665\nEpoch 41/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4367 - acc: 0.7651Epoch 00040: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4371 - acc: 0.7648 - val_loss: 0.4492 - val_acc: 0.7656\nEpoch 42/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4363 - acc: 0.7654Epoch 00041: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4366 - acc: 0.7651 - val_loss: 0.4479 - val_acc: 0.7663\nEpoch 43/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4358 - acc: 0.7655Epoch 00042: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4362 - acc: 0.7652 - val_loss: 0.4517 - val_acc: 0.7643\nEpoch 44/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4354 - acc: 0.7657Epoch 00043: val_loss improved from 0.44773 to 0.44724, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4358 - acc: 0.7654 - val_loss: 0.4472 - val_acc: 0.7665\nEpoch 45/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4349 - acc: 0.7657Epoch 00044: val_loss improved from 0.44724 to 0.44713, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4353 - acc: 0.7654 - val_loss: 0.4471 - val_acc: 0.7661\nEpoch 46/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4345 - acc: 0.7657Epoch 00045: val_loss improved from 0.44713 to 0.44694, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4349 - acc: 0.7655 - val_loss: 0.4469 - val_acc: 0.7676\nEpoch 47/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4343 - acc: 0.7658Epoch 00046: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4347 - acc: 0.7656 - val_loss: 0.4470 - val_acc: 0.7667\nEpoch 48/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4339 - acc: 0.7658Epoch 00047: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4343 - acc: 0.7656 - val_loss: 0.4478 - val_acc: 0.7661\nEpoch 49/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4335 - acc: 0.7660Epoch 00048: val_loss improved from 0.44694 to 0.44408, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4339 - acc: 0.7657 - val_loss: 0.4441 - val_acc: 0.7683\nEpoch 50/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4328 - acc: 0.7660Epoch 00049: val_loss did not improve\n10496/10496 [==============================] - 382s - loss: 0.4332 - acc: 0.7657 - val_loss: 0.4448 - val_acc: 0.7674\nEpoch 51/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4324 - acc: 0.7663Epoch 00050: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4328 - acc: 0.7661 - val_loss: 0.4442 - val_acc: 0.7674\nEpoch 52/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4320 - acc: 0.7666Epoch 00051: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4324 - acc: 0.7663 - val_loss: 0.4467 - val_acc: 0.7654\nEpoch 53/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4318 - acc: 0.7666Epoch 00052: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4321 - acc: 0.7664 - val_loss: 0.4468 - val_acc: 0.7658\nEpoch 54/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4312 - acc: 0.7669Epoch 00053: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4315 - acc: 0.7666 - val_loss: 0.4455 - val_acc: 0.7667\nEpoch 55/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4308 - acc: 0.7670Epoch 00054: val_loss did not improve\n10496/10496 [==============================] - 380s - loss: 0.4312 - acc: 0.7668 - val_loss: 0.4460 - val_acc: 0.7661\nEpoch 56/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4306 - acc: 0.7674Epoch 00055: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4309 - acc: 0.7671 - val_loss: 0.4442 - val_acc: 0.7678\nEpoch 57/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4302 - acc: 0.7674Epoch 00056: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4305 - acc: 0.7672 - val_loss: 0.4447 - val_acc: 0.7676\nEpoch 58/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4298 - acc: 0.7674Epoch 00057: val_loss improved from 0.44408 to 0.44340, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 381s - loss: 0.4301 - acc: 0.7671 - val_loss: 0.4434 - val_acc: 0.7689\nEpoch 59/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4292 - acc: 0.7674Epoch 00058: val_loss improved from 0.44340 to 0.44193, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4295 - acc: 0.7671 - val_loss: 0.4419 - val_acc: 0.7689\nEpoch 60/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4288 - acc: 0.7675Epoch 00059: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4291 - acc: 0.7672 - val_loss: 0.4461 - val_acc: 0.7667\nEpoch 61/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4283 - acc: 0.7676Epoch 00060: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4287 - acc: 0.7674 - val_loss: 0.4421 - val_acc: 0.7685\nEpoch 62/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4280 - acc: 0.7677Epoch 00061: val_loss improved from 0.44193 to 0.44081, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4283 - acc: 0.7674 - val_loss: 0.4408 - val_acc: 0.7694\nEpoch 63/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4275 - acc: 0.7678Epoch 00062: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4279 - acc: 0.7675 - val_loss: 0.4420 - val_acc: 0.7687\nEpoch 64/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4272 - acc: 0.7681Epoch 00063: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4275 - acc: 0.7678 - val_loss: 0.4416 - val_acc: 0.7680\nEpoch 65/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4268 - acc: 0.7679Epoch 00064: val_loss improved from 0.44081 to 0.44063, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 385s - loss: 0.4271 - acc: 0.7676 - val_loss: 0.4406 - val_acc: 0.7694\nEpoch 66/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4264 - acc: 0.7681Epoch 00065: val_loss did not improve\n10496/10496 [==============================] - 380s - loss: 0.4268 - acc: 0.7679 - val_loss: 0.4428 - val_acc: 0.7685\nEpoch 67/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4260 - acc: 0.7682Epoch 00066: val_loss improved from 0.44063 to 0.43819, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 381s - loss: 0.4264 - acc: 0.7680 - val_loss: 0.4382 - val_acc: 0.7696\nEpoch 68/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4257 - acc: 0.7683Epoch 00067: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4260 - acc: 0.7681 - val_loss: 0.4401 - val_acc: 0.7687\nEpoch 69/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4253 - acc: 0.7683Epoch 00068: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4257 - acc: 0.7681 - val_loss: 0.4415 - val_acc: 0.7683\nEpoch 70/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4250 - acc: 0.7685Epoch 00069: val_loss improved from 0.43819 to 0.43792, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 380s - loss: 0.4253 - acc: 0.7683 - val_loss: 0.4379 - val_acc: 0.7687\nEpoch 71/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4246 - acc: 0.7686Epoch 00070: val_loss did not improve\n10496/10496 [==============================] - 382s - loss: 0.4249 - acc: 0.7684 - val_loss: 0.4392 - val_acc: 0.7685\nEpoch 72/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4242 - acc: 0.7690Epoch 00071: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4245 - acc: 0.7687 - val_loss: 0.4414 - val_acc: 0.7674\nEpoch 73/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4238 - acc: 0.7688Epoch 00072: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4241 - acc: 0.7686 - val_loss: 0.4394 - val_acc: 0.7674\nEpoch 74/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4235 - acc: 0.7690Epoch 00073: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4239 - acc: 0.7687 - val_loss: 0.4432 - val_acc: 0.7656\nEpoch 75/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4231 - acc: 0.7691Epoch 00074: val_loss improved from 0.43792 to 0.43680, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4235 - acc: 0.7689 - val_loss: 0.4368 - val_acc: 0.7691\nEpoch 76/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4227 - acc: 0.7688Epoch 00075: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4231 - acc: 0.7686 - val_loss: 0.4382 - val_acc: 0.7676\nEpoch 77/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4224 - acc: 0.7689Epoch 00076: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4227 - acc: 0.7686 - val_loss: 0.4375 - val_acc: 0.7689\nEpoch 78/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4222 - acc: 0.7689Epoch 00077: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4226 - acc: 0.7687 - val_loss: 0.4410 - val_acc: 0.7672\nEpoch 79/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4219 - acc: 0.7689Epoch 00078: val_loss improved from 0.43680 to 0.43653, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4222 - acc: 0.7686 - val_loss: 0.4365 - val_acc: 0.7694\nEpoch 80/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4216 - acc: 0.7692Epoch 00079: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4219 - acc: 0.7689 - val_loss: 0.4365 - val_acc: 0.7685\nEpoch 81/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4212 - acc: 0.7692Epoch 00080: val_loss improved from 0.43653 to 0.43650, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4216 - acc: 0.7689 - val_loss: 0.4365 - val_acc: 0.7694\nEpoch 82/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4209 - acc: 0.7694Epoch 00081: val_loss did not improve\n10496/10496 [==============================] - 380s - loss: 0.4212 - acc: 0.7691 - val_loss: 0.4366 - val_acc: 0.7691\nEpoch 83/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4206 - acc: 0.7694Epoch 00082: val_loss did not improve\n10496/10496 [==============================] - 378s - loss: 0.4209 - acc: 0.7692 - val_loss: 0.4374 - val_acc: 0.7685\nEpoch 84/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4203 - acc: 0.7697Epoch 00083: val_loss improved from 0.43650 to 0.43378, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 379s - loss: 0.4206 - acc: 0.7695 - val_loss: 0.4338 - val_acc: 0.7707\nEpoch 85/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4200 - acc: 0.7696Epoch 00084: val_loss did not improve\n10496/10496 [==============================] - 378s - loss: 0.4203 - acc: 0.7694 - val_loss: 0.4344 - val_acc: 0.7707\nEpoch 86/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4197 - acc: 0.7696Epoch 00085: val_loss did not improve\n10496/10496 [==============================] - 378s - loss: 0.4201 - acc: 0.7694 - val_loss: 0.4339 - val_acc: 0.7702\nEpoch 87/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4194 - acc: 0.7700Epoch 00086: val_loss did not improve\n10496/10496 [==============================] - 378s - loss: 0.4197 - acc: 0.7698 - val_loss: 0.4368 - val_acc: 0.7676\nEpoch 88/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4191 - acc: 0.7701Epoch 00087: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4195 - acc: 0.7699 - val_loss: 0.4367 - val_acc: 0.7680\nEpoch 89/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4188 - acc: 0.7702Epoch 00088: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4192 - acc: 0.7700 - val_loss: 0.4354 - val_acc: 0.7683\nEpoch 90/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4186 - acc: 0.7702Epoch 00089: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4189 - acc: 0.7700 - val_loss: 0.4362 - val_acc: 0.7676\nEpoch 91/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4181 - acc: 0.7700Epoch 00090: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4185 - acc: 0.7698 - val_loss: 0.4344 - val_acc: 0.7700\nEpoch 92/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4178 - acc: 0.7703Epoch 00091: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4182 - acc: 0.7701 - val_loss: 0.4347 - val_acc: 0.7691\nEpoch 93/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4176 - acc: 0.7705Epoch 00092: val_loss improved from 0.43378 to 0.43366, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4180 - acc: 0.7702 - val_loss: 0.4337 - val_acc: 0.7696\nEpoch 94/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4173 - acc: 0.7705Epoch 00093: val_loss improved from 0.43366 to 0.43235, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4177 - acc: 0.7702 - val_loss: 0.4323 - val_acc: 0.7696\nEpoch 95/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4170 - acc: 0.7708Epoch 00094: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4174 - acc: 0.7706 - val_loss: 0.4364 - val_acc: 0.7680\nEpoch 96/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4167 - acc: 0.7710Epoch 00095: val_loss did not improve\n10496/10496 [==============================] - 379s - loss: 0.4171 - acc: 0.7708 - val_loss: 0.4327 - val_acc: 0.7689\nEpoch 97/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4164 - acc: 0.7710Epoch 00096: val_loss improved from 0.43235 to 0.43148, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4168 - acc: 0.7708 - val_loss: 0.4315 - val_acc: 0.7698\nEpoch 98/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4162 - acc: 0.7714Epoch 00097: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4166 - acc: 0.7712 - val_loss: 0.4328 - val_acc: 0.7698\nEpoch 99/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4159 - acc: 0.7711Epoch 00098: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4162 - acc: 0.7709 - val_loss: 0.4322 - val_acc: 0.7696\nEpoch 100/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4156 - acc: 0.7712Epoch 00099: val_loss improved from 0.43148 to 0.43118, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 379s - loss: 0.4160 - acc: 0.7710 - val_loss: 0.4312 - val_acc: 0.7711\nEpoch 101/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4154 - acc: 0.7710Epoch 00100: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4157 - acc: 0.7708 - val_loss: 0.4332 - val_acc: 0.7702\nEpoch 102/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4151 - acc: 0.7715Epoch 00101: val_loss improved from 0.43118 to 0.42933, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\n10496/10496 [==============================] - 378s - loss: 0.4155 - acc: 0.7713 - val_loss: 0.4293 - val_acc: 0.7720\nEpoch 103/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4149 - acc: 0.7718Epoch 00102: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4152 - acc: 0.7716 - val_loss: 0.4316 - val_acc: 0.7709\nEpoch 104/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4146 - acc: 0.7719Epoch 00103: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4149 - acc: 0.7717 - val_loss: 0.4329 - val_acc: 0.7705\nEpoch 105/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4143 - acc: 0.7719Epoch 00104: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4146 - acc: 0.7717 - val_loss: 0.4294 - val_acc: 0.7711\nEpoch 106/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4142 - acc: 0.7720Epoch 00105: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4145 - acc: 0.7718 - val_loss: 0.4307 - val_acc: 0.7711\nEpoch 107/500\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4137 - acc: 0.7720Epoch 00106: val_loss did not improve\n10496/10496 [==============================] - 377s - loss: 0.4141 - acc: 0.7718 - val_loss: 0.4330 - val_acc: 0.7698\nEpoch 108/500\n 9216/10496 [=========================>....] - ETA: 43s - loss: 0.4120 - acc: 0.7731"],["print('Evaluating model...')\nscore = model.evaluate_generator(test_data_gen, val_samples=test_data_gen.n_samples)\nprint('done.')\n\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])","Evaluating model...\ndone.\nTest score: 0.423118899406\nTest accuracy: 0.766065140845\n"]]],"string":"[\n [\n [\n \"from __future__ import print_function\\n\\nimport os\\nimport sys\\nimport numpy as np\\n\\nfrom keras.optimizers import SGD\\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\\n\\nsys.path.append(os.path.join(os.getcwd(), os.pardir))\\n\\nimport config\\n\\nfrom utils.dataset.data_generator import DataGenerator\\nfrom models.cnn3 import cnn\",\n \"Using Theano backend.\\nUsing gpu device 1: GeForce GTX 680 (CNMeM is disabled, cuDNN 5005)\\n\"\n ],\n [\n \"lr=0.001\\nn_epochs=500\\nbatch_size=32\\ninput_shape=(140, 140, 3)\\n\\nname = 'cnn_140_edges_hog_grey_lr_%f_nesterov' % lr\",\n \"_____no_output_____\"\n ],\n [\n \"print('loading model...')\\nmodel = cnn(input_shape=input_shape)\\nmodel.summary()\\n\\noptimizer = SGD(lr=lr, clipnorm=1., clipvalue=0.5, nesterov=True)\\n\\nprint('compiling model...')\\nmodel.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])\\nprint('done.')\\n\\ncsv_logger = CSVLogger('%s_training.log' % name)\\nbest_model_checkpointer = ModelCheckpoint(filepath=(\\\"./%s_training_weights_best.hdf5\\\" % name), verbose=1,\\n save_best_only=True)\\n\\ncurrent_model_checkpointer = ModelCheckpoint(filepath=(\\\"./%s_training_weights_current.hdf5\\\" % name), verbose=0)\",\n \"loading model...\\n____________________________________________________________________________________________________\\nLayer (type) Output Shape Param # Connected to \\n====================================================================================================\\ninput_1 (InputLayer) (None, 140, 140, 3) 0 \\n____________________________________________________________________________________________________\\nconvolution2d_1 (Convolution2D) (None, 140, 140, 128) 18944 input_1[0][0] \\n____________________________________________________________________________________________________\\nactivation_1 (Activation) (None, 140, 140, 128) 0 convolution2d_1[0][0] \\n____________________________________________________________________________________________________\\nmaxpooling2d_1 (MaxPooling2D) (None, 70, 70, 128) 0 activation_1[0][0] \\n____________________________________________________________________________________________________\\nconvolution2d_2 (Convolution2D) (None, 70, 70, 64) 204864 maxpooling2d_1[0][0] \\n____________________________________________________________________________________________________\\nactivation_2 (Activation) (None, 70, 70, 64) 0 convolution2d_2[0][0] \\n____________________________________________________________________________________________________\\nmaxpooling2d_2 (MaxPooling2D) (None, 35, 35, 64) 0 activation_2[0][0] \\n____________________________________________________________________________________________________\\nconvolution2d_3 (Convolution2D) (None, 35, 35, 64) 36928 maxpooling2d_2[0][0] \\n____________________________________________________________________________________________________\\nactivation_3 (Activation) (None, 35, 35, 64) 0 convolution2d_3[0][0] \\n____________________________________________________________________________________________________\\nmaxpooling2d_3 (MaxPooling2D) (None, 17, 17, 64) 0 activation_3[0][0] \\n____________________________________________________________________________________________________\\nflatten_1 (Flatten) (None, 18496) 0 maxpooling2d_3[0][0] \\n____________________________________________________________________________________________________\\ndense_1 (Dense) (None, 1024) 18940928 flatten_1[0][0] \\n____________________________________________________________________________________________________\\ndense_2 (Dense) (None, 1024) 1049600 dense_1[0][0] \\n____________________________________________________________________________________________________\\ndense_3 (Dense) (None, 512) 524800 dense_2[0][0] \\n____________________________________________________________________________________________________\\ndense_4 (Dense) (None, 2) 1026 dense_3[0][0] \\n____________________________________________________________________________________________________\\nactivation_4 (Activation) (None, 2) 0 dense_4[0][0] \\n====================================================================================================\\nTotal params: 20777090\\n____________________________________________________________________________________________________\\ncompiling model...\\ndone.\\n\"\n ],\n [\n \"print('Initializing data generators...')\\ntrain_data_gen = DataGenerator(dataset_file=config.train_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\\nvalidation_data_gen = DataGenerator(dataset_file=config.validation_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\\ntest_data_gen = DataGenerator(dataset_file=config.test_data_file, batch_size=batch_size, preprocessing='edges_hog_gray')\\nprint('done.')\",\n \"Initializing data generators...\\ndone.\\n\"\n ],\n [\n \"print('Fitting model...')\\nhistory = model.fit_generator(train_data_gen,\\n nb_epoch=n_epochs,\\n samples_per_epoch=train_data_gen.n_batches * batch_size,\\n validation_data=validation_data_gen,\\n nb_val_samples=validation_data_gen.n_samples,\\n verbose=1,\\n callbacks=[csv_logger, best_model_checkpointer, current_model_checkpointer])\\nprint('done.')\",\n \"Fitting model...\\nEpoch 1/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6842 - acc: 0.6566Epoch 00000: val_loss improved from inf to 0.67410, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 383s - loss: 0.6842 - acc: 0.6563 - val_loss: 0.6741 - val_acc: 0.6734\\nEpoch 2/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6676 - acc: 0.6650Epoch 00001: val_loss improved from 0.67410 to 0.65905, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.6677 - acc: 0.6647 - val_loss: 0.6590 - val_acc: 0.6725\\nEpoch 3/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6552 - acc: 0.6650Epoch 00002: val_loss improved from 0.65905 to 0.64789, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.6553 - acc: 0.6647 - val_loss: 0.6479 - val_acc: 0.6721\\nEpoch 4/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6461 - acc: 0.6650Epoch 00003: val_loss improved from 0.64789 to 0.64012, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 382s - loss: 0.6463 - acc: 0.6647 - val_loss: 0.6401 - val_acc: 0.6708\\nEpoch 5/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6390 - acc: 0.6650Epoch 00004: val_loss improved from 0.64012 to 0.63145, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 383s - loss: 0.6392 - acc: 0.6647 - val_loss: 0.6315 - val_acc: 0.6743\\nEpoch 6/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6315 - acc: 0.6650Epoch 00005: val_loss improved from 0.63145 to 0.62386, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.6317 - acc: 0.6647 - val_loss: 0.6239 - val_acc: 0.6725\\nEpoch 7/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.6199 - acc: 0.6650Epoch 00006: val_loss improved from 0.62386 to 0.60869, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.6201 - acc: 0.6647 - val_loss: 0.6087 - val_acc: 0.6734\\nEpoch 8/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5970 - acc: 0.6650Epoch 00007: val_loss improved from 0.60869 to 0.58061, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.5971 - acc: 0.6647 - val_loss: 0.5806 - val_acc: 0.6710\\nEpoch 9/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5553 - acc: 0.6785Epoch 00008: val_loss improved from 0.58061 to 0.53442, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.5555 - acc: 0.6782 - val_loss: 0.5344 - val_acc: 0.7088\\nEpoch 10/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.5123 - acc: 0.7105Epoch 00009: val_loss improved from 0.53442 to 0.49943, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.5126 - acc: 0.7102 - val_loss: 0.4994 - val_acc: 0.7326\\nEpoch 11/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4847 - acc: 0.7317Epoch 00010: val_loss improved from 0.49943 to 0.48177, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4850 - acc: 0.7315 - val_loss: 0.4818 - val_acc: 0.7476\\nEpoch 12/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4708 - acc: 0.7444Epoch 00011: val_loss improved from 0.48177 to 0.47363, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 382s - loss: 0.4711 - acc: 0.7441 - val_loss: 0.4736 - val_acc: 0.7548\\nEpoch 13/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4637 - acc: 0.7512Epoch 00012: val_loss improved from 0.47363 to 0.46965, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4640 - acc: 0.7509 - val_loss: 0.4696 - val_acc: 0.7597\\nEpoch 14/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4594 - acc: 0.7546Epoch 00013: val_loss improved from 0.46965 to 0.46501, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4597 - acc: 0.7542 - val_loss: 0.4650 - val_acc: 0.7647\\nEpoch 15/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4566 - acc: 0.7571Epoch 00014: val_loss improved from 0.46501 to 0.46349, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4569 - acc: 0.7568 - val_loss: 0.4635 - val_acc: 0.7650\\nEpoch 16/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4546 - acc: 0.7588Epoch 00015: val_loss improved from 0.46349 to 0.46234, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4550 - acc: 0.7585 - val_loss: 0.4623 - val_acc: 0.7678\\nEpoch 17/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4530 - acc: 0.7603Epoch 00016: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4533 - acc: 0.7600 - val_loss: 0.4636 - val_acc: 0.7672\\nEpoch 18/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4517 - acc: 0.7611Epoch 00017: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4520 - acc: 0.7608 - val_loss: 0.4634 - val_acc: 0.7687\\nEpoch 19/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4505 - acc: 0.7616Epoch 00018: val_loss improved from 0.46234 to 0.46121, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4508 - acc: 0.7613 - val_loss: 0.4612 - val_acc: 0.7698\\nEpoch 20/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4494 - acc: 0.7618Epoch 00019: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4498 - acc: 0.7615 - val_loss: 0.4615 - val_acc: 0.7696\\nEpoch 21/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4485 - acc: 0.7621Epoch 00020: val_loss improved from 0.46121 to 0.45922, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4488 - acc: 0.7619 - val_loss: 0.4592 - val_acc: 0.7691\\nEpoch 22/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4476 - acc: 0.7620Epoch 00021: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4479 - acc: 0.7618 - val_loss: 0.4592 - val_acc: 0.7685\\nEpoch 23/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4467 - acc: 0.7623Epoch 00022: val_loss improved from 0.45922 to 0.45754, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4471 - acc: 0.7620 - val_loss: 0.4575 - val_acc: 0.7687\\nEpoch 24/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4459 - acc: 0.7622Epoch 00023: val_loss improved from 0.45754 to 0.45556, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4463 - acc: 0.7619 - val_loss: 0.4556 - val_acc: 0.7687\\nEpoch 25/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4452 - acc: 0.7624Epoch 00024: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4456 - acc: 0.7621 - val_loss: 0.4590 - val_acc: 0.7667\\nEpoch 26/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4445 - acc: 0.7629Epoch 00025: val_loss improved from 0.45556 to 0.45485, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4448 - acc: 0.7626 - val_loss: 0.4548 - val_acc: 0.7683\\nEpoch 27/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4439 - acc: 0.7631Epoch 00026: val_loss improved from 0.45485 to 0.45355, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4442 - acc: 0.7628 - val_loss: 0.4536 - val_acc: 0.7685\\nEpoch 28/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4433 - acc: 0.7633Epoch 00027: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4436 - acc: 0.7630 - val_loss: 0.4544 - val_acc: 0.7683\\nEpoch 29/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4427 - acc: 0.7636Epoch 00028: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4431 - acc: 0.7633 - val_loss: 0.4539 - val_acc: 0.7669\\nEpoch 30/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4421 - acc: 0.7639Epoch 00029: val_loss improved from 0.45355 to 0.45310, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4424 - acc: 0.7636 - val_loss: 0.4531 - val_acc: 0.7678\\nEpoch 31/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4415 - acc: 0.7642Epoch 00030: val_loss did not improve\\n10496/10496 [==============================] - 381s - loss: 0.4419 - acc: 0.7639 - val_loss: 0.4549 - val_acc: 0.7665\\nEpoch 32/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4410 - acc: 0.7640Epoch 00031: val_loss improved from 0.45310 to 0.45002, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 382s - loss: 0.4414 - acc: 0.7637 - val_loss: 0.4500 - val_acc: 0.7678\\nEpoch 33/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4405 - acc: 0.7640Epoch 00032: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4409 - acc: 0.7637 - val_loss: 0.4517 - val_acc: 0.7669\\nEpoch 34/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4400 - acc: 0.7642Epoch 00033: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4404 - acc: 0.7640 - val_loss: 0.4529 - val_acc: 0.7654\\nEpoch 35/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4396 - acc: 0.7643Epoch 00034: val_loss improved from 0.45002 to 0.44926, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4399 - acc: 0.7641 - val_loss: 0.4493 - val_acc: 0.7667\\nEpoch 36/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4391 - acc: 0.7644Epoch 00035: val_loss did not improve\\n10496/10496 [==============================] - 382s - loss: 0.4395 - acc: 0.7642 - val_loss: 0.4505 - val_acc: 0.7661\\nEpoch 37/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4386 - acc: 0.7645Epoch 00036: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4390 - acc: 0.7642 - val_loss: 0.4522 - val_acc: 0.7652\\nEpoch 38/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4382 - acc: 0.7648Epoch 00037: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4385 - acc: 0.7645 - val_loss: 0.4501 - val_acc: 0.7652\\nEpoch 39/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4377 - acc: 0.7648Epoch 00038: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4380 - acc: 0.7646 - val_loss: 0.4541 - val_acc: 0.7636\\nEpoch 40/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4372 - acc: 0.7648Epoch 00039: val_loss improved from 0.44926 to 0.44773, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4376 - acc: 0.7646 - val_loss: 0.4477 - val_acc: 0.7665\\nEpoch 41/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4367 - acc: 0.7651Epoch 00040: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4371 - acc: 0.7648 - val_loss: 0.4492 - val_acc: 0.7656\\nEpoch 42/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4363 - acc: 0.7654Epoch 00041: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4366 - acc: 0.7651 - val_loss: 0.4479 - val_acc: 0.7663\\nEpoch 43/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4358 - acc: 0.7655Epoch 00042: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4362 - acc: 0.7652 - val_loss: 0.4517 - val_acc: 0.7643\\nEpoch 44/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4354 - acc: 0.7657Epoch 00043: val_loss improved from 0.44773 to 0.44724, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4358 - acc: 0.7654 - val_loss: 0.4472 - val_acc: 0.7665\\nEpoch 45/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4349 - acc: 0.7657Epoch 00044: val_loss improved from 0.44724 to 0.44713, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4353 - acc: 0.7654 - val_loss: 0.4471 - val_acc: 0.7661\\nEpoch 46/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4345 - acc: 0.7657Epoch 00045: val_loss improved from 0.44713 to 0.44694, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4349 - acc: 0.7655 - val_loss: 0.4469 - val_acc: 0.7676\\nEpoch 47/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4343 - acc: 0.7658Epoch 00046: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4347 - acc: 0.7656 - val_loss: 0.4470 - val_acc: 0.7667\\nEpoch 48/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4339 - acc: 0.7658Epoch 00047: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4343 - acc: 0.7656 - val_loss: 0.4478 - val_acc: 0.7661\\nEpoch 49/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4335 - acc: 0.7660Epoch 00048: val_loss improved from 0.44694 to 0.44408, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4339 - acc: 0.7657 - val_loss: 0.4441 - val_acc: 0.7683\\nEpoch 50/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4328 - acc: 0.7660Epoch 00049: val_loss did not improve\\n10496/10496 [==============================] - 382s - loss: 0.4332 - acc: 0.7657 - val_loss: 0.4448 - val_acc: 0.7674\\nEpoch 51/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4324 - acc: 0.7663Epoch 00050: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4328 - acc: 0.7661 - val_loss: 0.4442 - val_acc: 0.7674\\nEpoch 52/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4320 - acc: 0.7666Epoch 00051: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4324 - acc: 0.7663 - val_loss: 0.4467 - val_acc: 0.7654\\nEpoch 53/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4318 - acc: 0.7666Epoch 00052: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4321 - acc: 0.7664 - val_loss: 0.4468 - val_acc: 0.7658\\nEpoch 54/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4312 - acc: 0.7669Epoch 00053: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4315 - acc: 0.7666 - val_loss: 0.4455 - val_acc: 0.7667\\nEpoch 55/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4308 - acc: 0.7670Epoch 00054: val_loss did not improve\\n10496/10496 [==============================] - 380s - loss: 0.4312 - acc: 0.7668 - val_loss: 0.4460 - val_acc: 0.7661\\nEpoch 56/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4306 - acc: 0.7674Epoch 00055: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4309 - acc: 0.7671 - val_loss: 0.4442 - val_acc: 0.7678\\nEpoch 57/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4302 - acc: 0.7674Epoch 00056: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4305 - acc: 0.7672 - val_loss: 0.4447 - val_acc: 0.7676\\nEpoch 58/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4298 - acc: 0.7674Epoch 00057: val_loss improved from 0.44408 to 0.44340, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 381s - loss: 0.4301 - acc: 0.7671 - val_loss: 0.4434 - val_acc: 0.7689\\nEpoch 59/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4292 - acc: 0.7674Epoch 00058: val_loss improved from 0.44340 to 0.44193, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4295 - acc: 0.7671 - val_loss: 0.4419 - val_acc: 0.7689\\nEpoch 60/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4288 - acc: 0.7675Epoch 00059: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4291 - acc: 0.7672 - val_loss: 0.4461 - val_acc: 0.7667\\nEpoch 61/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4283 - acc: 0.7676Epoch 00060: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4287 - acc: 0.7674 - val_loss: 0.4421 - val_acc: 0.7685\\nEpoch 62/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4280 - acc: 0.7677Epoch 00061: val_loss improved from 0.44193 to 0.44081, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4283 - acc: 0.7674 - val_loss: 0.4408 - val_acc: 0.7694\\nEpoch 63/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4275 - acc: 0.7678Epoch 00062: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4279 - acc: 0.7675 - val_loss: 0.4420 - val_acc: 0.7687\\nEpoch 64/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4272 - acc: 0.7681Epoch 00063: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4275 - acc: 0.7678 - val_loss: 0.4416 - val_acc: 0.7680\\nEpoch 65/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4268 - acc: 0.7679Epoch 00064: val_loss improved from 0.44081 to 0.44063, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 385s - loss: 0.4271 - acc: 0.7676 - val_loss: 0.4406 - val_acc: 0.7694\\nEpoch 66/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4264 - acc: 0.7681Epoch 00065: val_loss did not improve\\n10496/10496 [==============================] - 380s - loss: 0.4268 - acc: 0.7679 - val_loss: 0.4428 - val_acc: 0.7685\\nEpoch 67/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4260 - acc: 0.7682Epoch 00066: val_loss improved from 0.44063 to 0.43819, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 381s - loss: 0.4264 - acc: 0.7680 - val_loss: 0.4382 - val_acc: 0.7696\\nEpoch 68/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4257 - acc: 0.7683Epoch 00067: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4260 - acc: 0.7681 - val_loss: 0.4401 - val_acc: 0.7687\\nEpoch 69/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4253 - acc: 0.7683Epoch 00068: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4257 - acc: 0.7681 - val_loss: 0.4415 - val_acc: 0.7683\\nEpoch 70/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4250 - acc: 0.7685Epoch 00069: val_loss improved from 0.43819 to 0.43792, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 380s - loss: 0.4253 - acc: 0.7683 - val_loss: 0.4379 - val_acc: 0.7687\\nEpoch 71/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4246 - acc: 0.7686Epoch 00070: val_loss did not improve\\n10496/10496 [==============================] - 382s - loss: 0.4249 - acc: 0.7684 - val_loss: 0.4392 - val_acc: 0.7685\\nEpoch 72/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4242 - acc: 0.7690Epoch 00071: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4245 - acc: 0.7687 - val_loss: 0.4414 - val_acc: 0.7674\\nEpoch 73/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4238 - acc: 0.7688Epoch 00072: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4241 - acc: 0.7686 - val_loss: 0.4394 - val_acc: 0.7674\\nEpoch 74/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4235 - acc: 0.7690Epoch 00073: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4239 - acc: 0.7687 - val_loss: 0.4432 - val_acc: 0.7656\\nEpoch 75/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4231 - acc: 0.7691Epoch 00074: val_loss improved from 0.43792 to 0.43680, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4235 - acc: 0.7689 - val_loss: 0.4368 - val_acc: 0.7691\\nEpoch 76/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4227 - acc: 0.7688Epoch 00075: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4231 - acc: 0.7686 - val_loss: 0.4382 - val_acc: 0.7676\\nEpoch 77/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4224 - acc: 0.7689Epoch 00076: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4227 - acc: 0.7686 - val_loss: 0.4375 - val_acc: 0.7689\\nEpoch 78/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4222 - acc: 0.7689Epoch 00077: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4226 - acc: 0.7687 - val_loss: 0.4410 - val_acc: 0.7672\\nEpoch 79/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4219 - acc: 0.7689Epoch 00078: val_loss improved from 0.43680 to 0.43653, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4222 - acc: 0.7686 - val_loss: 0.4365 - val_acc: 0.7694\\nEpoch 80/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4216 - acc: 0.7692Epoch 00079: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4219 - acc: 0.7689 - val_loss: 0.4365 - val_acc: 0.7685\\nEpoch 81/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4212 - acc: 0.7692Epoch 00080: val_loss improved from 0.43653 to 0.43650, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4216 - acc: 0.7689 - val_loss: 0.4365 - val_acc: 0.7694\\nEpoch 82/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4209 - acc: 0.7694Epoch 00081: val_loss did not improve\\n10496/10496 [==============================] - 380s - loss: 0.4212 - acc: 0.7691 - val_loss: 0.4366 - val_acc: 0.7691\\nEpoch 83/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4206 - acc: 0.7694Epoch 00082: val_loss did not improve\\n10496/10496 [==============================] - 378s - loss: 0.4209 - acc: 0.7692 - val_loss: 0.4374 - val_acc: 0.7685\\nEpoch 84/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4203 - acc: 0.7697Epoch 00083: val_loss improved from 0.43650 to 0.43378, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 379s - loss: 0.4206 - acc: 0.7695 - val_loss: 0.4338 - val_acc: 0.7707\\nEpoch 85/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4200 - acc: 0.7696Epoch 00084: val_loss did not improve\\n10496/10496 [==============================] - 378s - loss: 0.4203 - acc: 0.7694 - val_loss: 0.4344 - val_acc: 0.7707\\nEpoch 86/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4197 - acc: 0.7696Epoch 00085: val_loss did not improve\\n10496/10496 [==============================] - 378s - loss: 0.4201 - acc: 0.7694 - val_loss: 0.4339 - val_acc: 0.7702\\nEpoch 87/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4194 - acc: 0.7700Epoch 00086: val_loss did not improve\\n10496/10496 [==============================] - 378s - loss: 0.4197 - acc: 0.7698 - val_loss: 0.4368 - val_acc: 0.7676\\nEpoch 88/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4191 - acc: 0.7701Epoch 00087: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4195 - acc: 0.7699 - val_loss: 0.4367 - val_acc: 0.7680\\nEpoch 89/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4188 - acc: 0.7702Epoch 00088: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4192 - acc: 0.7700 - val_loss: 0.4354 - val_acc: 0.7683\\nEpoch 90/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4186 - acc: 0.7702Epoch 00089: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4189 - acc: 0.7700 - val_loss: 0.4362 - val_acc: 0.7676\\nEpoch 91/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4181 - acc: 0.7700Epoch 00090: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4185 - acc: 0.7698 - val_loss: 0.4344 - val_acc: 0.7700\\nEpoch 92/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4178 - acc: 0.7703Epoch 00091: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4182 - acc: 0.7701 - val_loss: 0.4347 - val_acc: 0.7691\\nEpoch 93/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4176 - acc: 0.7705Epoch 00092: val_loss improved from 0.43378 to 0.43366, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4180 - acc: 0.7702 - val_loss: 0.4337 - val_acc: 0.7696\\nEpoch 94/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4173 - acc: 0.7705Epoch 00093: val_loss improved from 0.43366 to 0.43235, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4177 - acc: 0.7702 - val_loss: 0.4323 - val_acc: 0.7696\\nEpoch 95/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4170 - acc: 0.7708Epoch 00094: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4174 - acc: 0.7706 - val_loss: 0.4364 - val_acc: 0.7680\\nEpoch 96/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4167 - acc: 0.7710Epoch 00095: val_loss did not improve\\n10496/10496 [==============================] - 379s - loss: 0.4171 - acc: 0.7708 - val_loss: 0.4327 - val_acc: 0.7689\\nEpoch 97/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4164 - acc: 0.7710Epoch 00096: val_loss improved from 0.43235 to 0.43148, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4168 - acc: 0.7708 - val_loss: 0.4315 - val_acc: 0.7698\\nEpoch 98/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4162 - acc: 0.7714Epoch 00097: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4166 - acc: 0.7712 - val_loss: 0.4328 - val_acc: 0.7698\\nEpoch 99/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4159 - acc: 0.7711Epoch 00098: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4162 - acc: 0.7709 - val_loss: 0.4322 - val_acc: 0.7696\\nEpoch 100/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4156 - acc: 0.7712Epoch 00099: val_loss improved from 0.43148 to 0.43118, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 379s - loss: 0.4160 - acc: 0.7710 - val_loss: 0.4312 - val_acc: 0.7711\\nEpoch 101/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4154 - acc: 0.7710Epoch 00100: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4157 - acc: 0.7708 - val_loss: 0.4332 - val_acc: 0.7702\\nEpoch 102/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4151 - acc: 0.7715Epoch 00101: val_loss improved from 0.43118 to 0.42933, saving model to ./cnn_140_edges_hog_grey_lr_0.001000_nesterov_training_weights_best.hdf5\\n10496/10496 [==============================] - 378s - loss: 0.4155 - acc: 0.7713 - val_loss: 0.4293 - val_acc: 0.7720\\nEpoch 103/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4149 - acc: 0.7718Epoch 00102: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4152 - acc: 0.7716 - val_loss: 0.4316 - val_acc: 0.7709\\nEpoch 104/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4146 - acc: 0.7719Epoch 00103: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4149 - acc: 0.7717 - val_loss: 0.4329 - val_acc: 0.7705\\nEpoch 105/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4143 - acc: 0.7719Epoch 00104: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4146 - acc: 0.7717 - val_loss: 0.4294 - val_acc: 0.7711\\nEpoch 106/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4142 - acc: 0.7720Epoch 00105: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4145 - acc: 0.7718 - val_loss: 0.4307 - val_acc: 0.7711\\nEpoch 107/500\\n10464/10496 [============================>.] - ETA: 1s - loss: 0.4137 - acc: 0.7720Epoch 00106: val_loss did not improve\\n10496/10496 [==============================] - 377s - loss: 0.4141 - acc: 0.7718 - val_loss: 0.4330 - val_acc: 0.7698\\nEpoch 108/500\\n 9216/10496 [=========================>....] - ETA: 43s - loss: 0.4120 - acc: 0.7731\"\n ],\n [\n \"print('Evaluating model...')\\nscore = model.evaluate_generator(test_data_gen, val_samples=test_data_gen.n_samples)\\nprint('done.')\\n\\nprint('Test score:', score[0])\\nprint('Test accuracy:', score[1])\",\n \"Evaluating model...\\ndone.\\nTest score: 0.423118899406\\nTest accuracy: 0.766065140845\\n\"\n ]\n ]\n]"},"cell_types":{"kind":"list like","value":["code"],"string":"[\n \"code\"\n]"},"cell_type_groups":{"kind":"list like","value":[["code","code","code","code","code","code"]],"string":"[\n [\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\",\n \"code\"\n ]\n]"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":5,"numItemsPerPage":100,"numTotalItems":1459454,"offset":500,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjQ5OTEwMiwic3ViIjoiL2RhdGFzZXRzL2JpZ2NvZGUvanVweXRlci1wYXJzZWQiLCJleHAiOjE3NTY1MDI3MDIsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.1oFinipY7mmrt28CkM3IzffHupnii7pUa7f4_RvMZLImbFqzz1V2_CWr130fSvJYebBDdj-EnvcxvoZ1gpQuBA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">