hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cba24735fb52dee83a47527722901a6d708f83b6
| 24,743 |
ipynb
|
Jupyter Notebook
|
notebooks/1.0-adm-load-data-2012.ipynb
|
aryamccarthy/ANES
|
29c56f8c46fd4e8b6725f329cb609f4f14a8acb0
|
[
"MIT"
] | 1 |
2017-04-18T22:46:02.000Z
|
2017-04-18T22:46:02.000Z
|
notebooks/1.0-adm-load-data-2012.ipynb
|
aryamccarthy/ANES
|
29c56f8c46fd4e8b6725f329cb609f4f14a8acb0
|
[
"MIT"
] | 1 |
2017-07-17T20:28:24.000Z
|
2017-07-17T20:28:24.000Z
|
notebooks/1.0-adm-load-data-2012.ipynb
|
aryamccarthy/ANES
|
29c56f8c46fd4e8b6725f329cb609f4f14a8acb0
|
[
"MIT"
] | null | null | null | 32.772185 | 117 | 0.37744 |
[
[
[
"# Load and preprocess 2012 data\n\nWe will, over time, look over other years. Our current goal is to explore the features of a single year.\n\n---",
"_____no_output_____"
]
],
[
[
"%pylab --no-import-all inline\nimport pandas as pd",
"Populating the interactive namespace from numpy and matplotlib\n"
]
],
[
[
"## Load the data.\n\n---\n\nIf this fails, be sure that you've saved your own data in the prescribed location, then retry.",
"_____no_output_____"
]
],
[
[
"file = \"../data/interim/2012data.dta\"\ndf_rawest = pd.read_stata(file)",
"_____no_output_____"
],
[
"good_columns = [#'campfin_limcorp', # \"Should gov be able to limit corporate contributions\"\n 'pid_x', # Your own party identification\n \n 'abortpre_4point', # Abortion\n 'trad_adjust', # Moral Relativism\n 'trad_lifestyle', # \"Newer\" lifetyles\n 'trad_tolerant', # Moral tolerance\n 'trad_famval', # Traditional Families\n 'gayrt_discstd_x', # Gay Job Discrimination\n 'gayrt_milstd_x', # Gay Military Service\n \n 'inspre_self', # National health insurance\n 'guarpr_self', # Guaranteed Job\n 'spsrvpr_ssself', # Services/Spending\n \n 'aa_work_x', # Affirmative Action ( Should this be aapost_hire_x? )\n 'resent_workway', \n 'resent_slavery', \n 'resent_deserve',\n 'resent_try',\n]\n\ndf_raw = df_rawest[good_columns]",
"_____no_output_____"
]
],
[
[
"## Clean the data\n---",
"_____no_output_____"
]
],
[
[
"def convert_to_int(s):\n \"\"\"Turn ANES data entry into an integer.\n \n >>> convert_to_int(\"1. Govt should provide many fewer services\")\n 1\n >>> convert_to_int(\"2\")\n 2\n \"\"\"\n try:\n return int(s.partition('.')[0])\n except ValueError:\n warnings.warn(\"Couldn't convert: \"+s)\n return np.nan\n except AttributeError:\n return s\n\ndef negative_to_nan(value):\n \"\"\"Convert negative values to missing.\n \n ANES codes various non-answers as negative numbers.\n For instance, if a question does not pertain to the \n respondent.\n \"\"\"\n return value if value >= 0 else np.nan\n\ndef lib1_cons2_neutral3(x):\n \"\"\"Rearrange questions where 3 is neutral.\"\"\"\n return -3 + x if x != 1 else x\n\ndef liblow_conshigh(x):\n \"\"\"Reorder questions where the liberal response is low.\"\"\"\n return -x\n\ndef dem_edu_special_treatment(x):\n \"\"\"Eliminate negative numbers and {95. Other}\"\"\"\n return np.nan if x == 95 or x <0 else x\n\ndf = df_raw.applymap(convert_to_int)\ndf = df.applymap(negative_to_nan)\n\ndf.abortpre_4point = df.abortpre_4point.apply(lambda x: np.nan if x not in {1, 2, 3, 4} else -x)\n\ndf.loc[:, 'trad_lifestyle'] = df.trad_lifestyle.apply(lambda x: -x) # 1: moral relativism, 5: no relativism\ndf.loc[:, 'trad_famval'] = df.trad_famval.apply(lambda x: -x) # Tolerance. 1: tolerance, 7: not\n\ndf.loc[:, 'spsrvpr_ssself'] = df.spsrvpr_ssself.apply(lambda x: -x)\n\ndf.loc[:, 'resent_workway'] = df.resent_workway.apply(lambda x: -x)\ndf.loc[:, 'resent_try'] = df.resent_try.apply(lambda x: -x)\n\n\ndf.rename(inplace=True, columns=dict(zip(\n good_columns,\n [\"PartyID\",\n \n \"Abortion\",\n \"MoralRelativism\",\n \"NewerLifestyles\",\n \"MoralTolerance\",\n \"TraditionalFamilies\",\n \"GayJobDiscrimination\",\n \"GayMilitaryService\",\n\n \"NationalHealthInsurance\",\n \"StandardOfLiving\",\n \"ServicesVsSpending\",\n\n \"AffirmativeAction\",\n \"RacialWorkWayUp\",\n \"RacialGenerational\",\n \"RacialDeserve\",\n \"RacialTryHarder\",\n ]\n)))",
"_____no_output_____"
],
[
"print(\"Variables now available: df\")",
"Variables now available: df\n"
],
[
"df_rawest.pid_x.value_counts()",
"_____no_output_____"
],
[
"df.PartyID.value_counts()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.to_csv(\"../data/processed/2012.csv\")",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba2546f6459d76749337a2d1703b044f0a1f39c
| 34,406 |
ipynb
|
Jupyter Notebook
|
5 Sequence Models/4 Operations_on_word_vectors_v2a.ipynb
|
pratikpc/Deep-Learning-Specialization-Andrew-Ng
|
63a13cd6e204744f8f4e7b5ab0e867b3ff4c77a1
|
[
"Apache-2.0"
] | null | null | null |
5 Sequence Models/4 Operations_on_word_vectors_v2a.ipynb
|
pratikpc/Deep-Learning-Specialization-Andrew-Ng
|
63a13cd6e204744f8f4e7b5ab0e867b3ff4c77a1
|
[
"Apache-2.0"
] | null | null | null |
5 Sequence Models/4 Operations_on_word_vectors_v2a.ipynb
|
pratikpc/Deep-Learning-Specialization-Andrew-Ng
|
63a13cd6e204744f8f4e7b5ab0e867b3ff4c77a1
|
[
"Apache-2.0"
] | null | null | null | 39.231471 | 608 | 0.559089 |
[
[
[
"# Operations on word vectors\n\nWelcome to your first assignment of this week! \n\nBecause word embeddings are very computationally expensive to train, most ML practitioners will load a pre-trained set of embeddings. \n\n**After this assignment you will be able to:**\n\n- Load pre-trained word vectors, and measure similarity using cosine similarity\n- Use word embeddings to solve word analogy problems such as Man is to Woman as King is to ______. \n- Modify word embeddings to reduce their gender bias \n\n",
"_____no_output_____"
],
[
"## <font color='darkblue'>Updates</font>\n\n#### If you were working on the notebook before this update...\n* The current notebook is version \"2a\".\n* You can find your original work saved in the notebook with the previous version name (\"v2\") \n* To view the file directory, go to the menu \"File->Open\", and this will open a new tab that shows the file directory.\n\n#### List of updates\n* cosine_similarity\n * Additional hints.\n* complete_analogy\n * Replaces the list of input words with a set, and sets it outside the for loop (to follow best practices in coding).\n* Spelling, grammar and wording corrections.",
"_____no_output_____"
],
[
"Let's get started! Run the following cell to load the packages you will need.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom w2v_utils import *",
"Using TensorFlow backend.\n"
]
],
[
[
"#### Load the word vectors\n* For this assignment, we will use 50-dimensional GloVe vectors to represent words. \n* Run the following cell to load the `word_to_vec_map`. ",
"_____no_output_____"
]
],
[
[
"words, word_to_vec_map = read_glove_vecs('../../readonly/glove.6B.50d.txt')",
"_____no_output_____"
]
],
[
[
"You've loaded:\n- `words`: set of words in the vocabulary.\n- `word_to_vec_map`: dictionary mapping words to their GloVe vector representation.\n\n#### Embedding vectors versus one-hot vectors\n* Recall from the lesson videos that one-hot vectors do not do a good job of capturing the level of similarity between words (every one-hot vector has the same Euclidean distance from any other one-hot vector).\n* Embedding vectors such as GloVe vectors provide much more useful information about the meaning of individual words. \n* Lets now see how you can use GloVe vectors to measure the similarity between two words. ",
"_____no_output_____"
],
[
"# 1 - Cosine similarity\n\nTo measure the similarity between two words, we need a way to measure the degree of similarity between two embedding vectors for the two words. Given two vectors $u$ and $v$, cosine similarity is defined as follows: \n\n$$\\text{CosineSimilarity(u, v)} = \\frac {u \\cdot v} {||u||_2 ||v||_2} = cos(\\theta) \\tag{1}$$\n\n* $u \\cdot v$ is the dot product (or inner product) of two vectors\n* $||u||_2$ is the norm (or length) of the vector $u$\n* $\\theta$ is the angle between $u$ and $v$. \n* The cosine similarity depends on the angle between $u$ and $v$. \n * If $u$ and $v$ are very similar, their cosine similarity will be close to 1.\n * If they are dissimilar, the cosine similarity will take a smaller value. \n\n<img src=\"images/cosine_sim.png\" style=\"width:800px;height:250px;\">\n<caption><center> **Figure 1**: The cosine of the angle between two vectors is a measure their similarity</center></caption>\n\n**Exercise**: Implement the function `cosine_similarity()` to evaluate the similarity between word vectors.\n\n**Reminder**: The norm of $u$ is defined as $ ||u||_2 = \\sqrt{\\sum_{i=1}^{n} u_i^2}$\n\n#### Additional Hints\n* You may find `np.dot`, `np.sum`, or `np.sqrt` useful depending upon the implementation that you choose.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: cosine_similarity\n\ndef cosine_similarity(u, v):\n \"\"\"\n Cosine similarity reflects the degree of similarity between u and v\n \n Arguments:\n u -- a word vector of shape (n,) \n v -- a word vector of shape (n,)\n\n Returns:\n cosine_similarity -- the cosine similarity between u and v defined by the formula above.\n \"\"\"\n \n distance = 0.0\n \n ### START CODE HERE ###\n # Compute the dot product between u and v (≈1 line)\n dot = np.dot(u,v)\n # Compute the L2 norm of u (≈1 line)\n norm_u = np.sqrt(np.sum(np.square(u)))\n \n # Compute the L2 norm of v (≈1 line)\n norm_v = np.sqrt(np.sum(np.square(v)))\n # Compute the cosine similarity defined by formula (1) (≈1 line)\n cosine_similarity = dot/(norm_u*norm_v)\n ### END CODE HERE ###\n \n return cosine_similarity",
"_____no_output_____"
],
[
"father = word_to_vec_map[\"father\"]\nmother = word_to_vec_map[\"mother\"]\nball = word_to_vec_map[\"ball\"]\ncrocodile = word_to_vec_map[\"crocodile\"]\nfrance = word_to_vec_map[\"france\"]\nitaly = word_to_vec_map[\"italy\"]\nparis = word_to_vec_map[\"paris\"]\nrome = word_to_vec_map[\"rome\"]\n\nprint(\"cosine_similarity(father, mother) = \", cosine_similarity(father, mother))\nprint(\"cosine_similarity(ball, crocodile) = \",cosine_similarity(ball, crocodile))\nprint(\"cosine_similarity(france - paris, rome - italy) = \",cosine_similarity(france - paris, rome - italy))",
"cosine_similarity(father, mother) = 0.890903844289\ncosine_similarity(ball, crocodile) = 0.274392462614\ncosine_similarity(france - paris, rome - italy) = -0.675147930817\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **cosine_similarity(father, mother)** =\n </td>\n <td>\n 0.890903844289\n </td>\n </tr>\n <tr>\n <td>\n **cosine_similarity(ball, crocodile)** =\n </td>\n <td>\n 0.274392462614\n </td>\n </tr>\n <tr>\n <td>\n **cosine_similarity(france - paris, rome - italy)** =\n </td>\n <td>\n -0.675147930817\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"#### Try different words!\n* After you get the correct expected output, please feel free to modify the inputs and measure the cosine similarity between other pairs of words! \n* Playing around with the cosine similarity of other inputs will give you a better sense of how word vectors behave.",
"_____no_output_____"
],
[
"## 2 - Word analogy task\n\n* In the word analogy task, we complete the sentence: \n <font color='brown'>\"*a* is to *b* as *c* is to **____**\"</font>. \n\n* An example is: \n <font color='brown'> '*man* is to *woman* as *king* is to *queen*' </font>. \n\n* We are trying to find a word *d*, such that the associated word vectors $e_a, e_b, e_c, e_d$ are related in the following manner: \n $e_b - e_a \\approx e_d - e_c$\n* We will measure the similarity between $e_b - e_a$ and $e_d - e_c$ using cosine similarity. \n\n**Exercise**: Complete the code below to be able to perform word analogies!",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: complete_analogy\n\ndef complete_analogy(word_a, word_b, word_c, word_to_vec_map):\n \"\"\"\n Performs the word analogy task as explained above: a is to b as c is to ____. \n \n Arguments:\n word_a -- a word, string\n word_b -- a word, string\n word_c -- a word, string\n word_to_vec_map -- dictionary that maps words to their corresponding vectors. \n \n Returns:\n best_word -- the word such that v_b - v_a is close to v_best_word - v_c, as measured by cosine similarity\n \"\"\"\n \n # convert words to lowercase\n word_a, word_b, word_c = word_a.lower(), word_b.lower(), word_c.lower()\n \n ### START CODE HERE ###\n # Get the word embeddings e_a, e_b and e_c (≈1-3 lines)\n e_a, e_b, e_c = word_to_vec_map[word_a],word_to_vec_map[word_b],word_to_vec_map[word_c]\n ### END CODE HERE ###\n \n words = word_to_vec_map.keys()\n max_cosine_sim = -100 # Initialize max_cosine_sim to a large negative number\n best_word = None # Initialize best_word with None, it will help keep track of the word to output\n\n # to avoid best_word being one of the input words, skip the input words\n # place the input words in a set for faster searching than a list\n # We will re-use this set of input words inside the for-loop\n input_words_set = set([word_a, word_b, word_c])\n \n # loop over the whole word vector set\n for w in words: \n # to avoid best_word being one of the input words, skip the input words\n if w in input_words_set:\n continue\n \n ### START CODE HERE ###\n # Compute cosine similarity between the vector (e_b - e_a) and the vector ((w's vector representation) - e_c) (≈1 line)\n cosine_sim = cosine_similarity(e_b - e_a, word_to_vec_map[w] - e_c)\n \n # If the cosine_sim is more than the max_cosine_sim seen so far,\n # then: set the new max_cosine_sim to the current cosine_sim and the best_word to the current word (≈3 lines)\n if cosine_sim > max_cosine_sim:\n max_cosine_sim = cosine_sim\n best_word = w\n ### END CODE HERE ###\n \n return best_word",
"_____no_output_____"
]
],
[
[
"Run the cell below to test your code, this may take 1-2 minutes.",
"_____no_output_____"
]
],
[
[
"triads_to_try = [('italy', 'italian', 'spain'), ('india', 'delhi', 'japan'), ('man', 'woman', 'boy'), ('small', 'smaller', 'large')]\nfor triad in triads_to_try:\n print ('{} -> {} :: {} -> {}'.format( *triad, complete_analogy(*triad,word_to_vec_map)))",
"italy -> italian :: spain -> spanish\nindia -> delhi :: japan -> tokyo\nman -> woman :: boy -> girl\nsmall -> smaller :: large -> larger\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **italy -> italian** ::\n </td>\n <td>\n spain -> spanish\n </td>\n </tr>\n <tr>\n <td>\n **india -> delhi** ::\n </td>\n <td>\n japan -> tokyo\n </td>\n </tr>\n <tr>\n <td>\n **man -> woman ** ::\n </td>\n <td>\n boy -> girl\n </td>\n </tr>\n <tr>\n <td>\n **small -> smaller ** ::\n </td>\n <td>\n large -> larger\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"* Once you get the correct expected output, please feel free to modify the input cells above to test your own analogies. \n* Try to find some other analogy pairs that do work, but also find some where the algorithm doesn't give the right answer:\n * For example, you can try small->smaller as big->?.",
"_____no_output_____"
],
[
"### Congratulations!\n\nYou've come to the end of the graded portion of the assignment. Here are the main points you should remember:\n\n- Cosine similarity is a good way to compare the similarity between pairs of word vectors.\n - Note that L2 (Euclidean) distance also works.\n- For NLP applications, using a pre-trained set of word vectors is often a good way to get started.\n- Even though you have finished the graded portions, we recommend you take a look at the rest of this notebook to learn about debiasing word vectors.\n\nCongratulations on finishing the graded portions of this notebook! \n",
"_____no_output_____"
],
[
"## 3 - Debiasing word vectors (OPTIONAL/UNGRADED) ",
"_____no_output_____"
],
[
"In the following exercise, you will examine gender biases that can be reflected in a word embedding, and explore algorithms for reducing the bias. In addition to learning about the topic of debiasing, this exercise will also help hone your intuition about what word vectors are doing. This section involves a bit of linear algebra, though you can probably complete it even without being an expert in linear algebra, and we encourage you to give it a shot. This portion of the notebook is optional and is not graded. \n\nLets first see how the GloVe word embeddings relate to gender. You will first compute a vector $g = e_{woman}-e_{man}$, where $e_{woman}$ represents the word vector corresponding to the word *woman*, and $e_{man}$ corresponds to the word vector corresponding to the word *man*. The resulting vector $g$ roughly encodes the concept of \"gender\". (You might get a more accurate representation if you compute $g_1 = e_{mother}-e_{father}$, $g_2 = e_{girl}-e_{boy}$, etc. and average over them. But just using $e_{woman}-e_{man}$ will give good enough results for now.) \n",
"_____no_output_____"
]
],
[
[
"g = word_to_vec_map['woman'] - word_to_vec_map['man']\nprint(g)",
"[-0.087144 0.2182 -0.40986 -0.03922 -0.1032 0.94165\n -0.06042 0.32988 0.46144 -0.35962 0.31102 -0.86824\n 0.96006 0.01073 0.24337 0.08193 -1.02722 -0.21122\n 0.695044 -0.00222 0.29106 0.5053 -0.099454 0.40445\n 0.30181 0.1355 -0.0606 -0.07131 -0.19245 -0.06115\n -0.3204 0.07165 -0.13337 -0.25068714 -0.14293 -0.224957\n -0.149 0.048882 0.12191 -0.27362 -0.165476 -0.20426\n 0.54376 -0.271425 -0.10245 -0.32108 0.2516 -0.33455\n -0.04371 0.01258 ]\n"
]
],
[
[
"Now, you will consider the cosine similarity of different words with $g$. Consider what a positive value of similarity means vs a negative cosine similarity. ",
"_____no_output_____"
]
],
[
[
"print ('List of names and their similarities with constructed vector:')\n\n# girls and boys name\nname_list = ['john', 'marie', 'sophie', 'ronaldo', 'priya', 'rahul', 'danielle', 'reza', 'katy', 'yasmin']\n\nfor w in name_list:\n print (w, cosine_similarity(word_to_vec_map[w], g))",
"List of names and their similarities with constructed vector:\njohn -0.23163356146\nmarie 0.315597935396\nsophie 0.318687898594\nronaldo -0.312447968503\npriya 0.17632041839\nrahul -0.169154710392\ndanielle 0.243932992163\nreza -0.079304296722\nkaty 0.283106865957\nyasmin 0.233138577679\n"
]
],
[
[
"As you can see, female first names tend to have a positive cosine similarity with our constructed vector $g$, while male first names tend to have a negative cosine similarity. This is not surprising, and the result seems acceptable. \n\nBut let's try with some other words.",
"_____no_output_____"
]
],
[
[
"print('Other words and their similarities:')\nword_list = ['lipstick', 'guns', 'science', 'arts', 'literature', 'warrior','doctor', 'tree', 'receptionist', \n 'technology', 'fashion', 'teacher', 'engineer', 'pilot', 'computer', 'singer']\nfor w in word_list:\n print (w, cosine_similarity(word_to_vec_map[w], g))",
"Other words and their similarities:\nlipstick 0.276919162564\nguns -0.18884855679\nscience -0.0608290654093\narts 0.00818931238588\nliterature 0.0647250443346\nwarrior -0.209201646411\ndoctor 0.118952894109\ntree -0.0708939917548\nreceptionist 0.330779417506\ntechnology -0.131937324476\nfashion 0.0356389462577\nteacher 0.179209234318\nengineer -0.0803928049452\npilot 0.00107644989919\ncomputer -0.103303588739\nsinger 0.185005181365\n"
]
],
[
[
"Do you notice anything surprising? It is astonishing how these results reflect certain unhealthy gender stereotypes. For example, \"computer\" is closer to \"man\" while \"literature\" is closer to \"woman\". Ouch! \n\nWe'll see below how to reduce the bias of these vectors, using an algorithm due to [Boliukbasi et al., 2016](https://arxiv.org/abs/1607.06520). Note that some word pairs such as \"actor\"/\"actress\" or \"grandmother\"/\"grandfather\" should remain gender specific, while other words such as \"receptionist\" or \"technology\" should be neutralized, i.e. not be gender-related. You will have to treat these two types of words differently when debiasing.\n\n### 3.1 - Neutralize bias for non-gender specific words \n\nThe figure below should help you visualize what neutralizing does. If you're using a 50-dimensional word embedding, the 50 dimensional space can be split into two parts: The bias-direction $g$, and the remaining 49 dimensions, which we'll call $g_{\\perp}$. In linear algebra, we say that the 49 dimensional $g_{\\perp}$ is perpendicular (or \"orthogonal\") to $g$, meaning it is at 90 degrees to $g$. The neutralization step takes a vector such as $e_{receptionist}$ and zeros out the component in the direction of $g$, giving us $e_{receptionist}^{debiased}$. \n\nEven though $g_{\\perp}$ is 49 dimensional, given the limitations of what we can draw on a 2D screen, we illustrate it using a 1 dimensional axis below. \n\n<img src=\"images/neutral.png\" style=\"width:800px;height:300px;\">\n<caption><center> **Figure 2**: The word vector for \"receptionist\" represented before and after applying the neutralize operation. </center></caption>\n\n**Exercise**: Implement `neutralize()` to remove the bias of words such as \"receptionist\" or \"scientist\". Given an input embedding $e$, you can use the following formulas to compute $e^{debiased}$: \n\n$$e^{bias\\_component} = \\frac{e \\cdot g}{||g||_2^2} * g\\tag{2}$$\n$$e^{debiased} = e - e^{bias\\_component}\\tag{3}$$\n\nIf you are an expert in linear algebra, you may recognize $e^{bias\\_component}$ as the projection of $e$ onto the direction $g$. If you're not an expert in linear algebra, don't worry about this.\n\n<!-- \n**Reminder**: a vector $u$ can be split into two parts: its projection over a vector-axis $v_B$ and its projection over the axis orthogonal to $v$:\n$$u = u_B + u_{\\perp}$$\nwhere : $u_B = $ and $ u_{\\perp} = u - u_B $\n!--> ",
"_____no_output_____"
]
],
[
[
"def neutralize(word, g, word_to_vec_map):\n \"\"\"\n Removes the bias of \"word\" by projecting it on the space orthogonal to the bias axis. \n This function ensures that gender neutral words are zero in the gender subspace.\n \n Arguments:\n word -- string indicating the word to debias\n g -- numpy-array of shape (50,), corresponding to the bias axis (such as gender)\n word_to_vec_map -- dictionary mapping words to their corresponding vectors.\n \n Returns:\n e_debiased -- neutralized word vector representation of the input \"word\"\n \"\"\"\n \n ### START CODE HERE ###\n # Select word vector representation of \"word\". Use word_to_vec_map. (≈ 1 line)\n e = word_to_vec_map[word]\n \n # Compute e_biascomponent using the formula given above. (≈ 1 line)\n e_biascomponent = np.dot(np.dot(e,g), g)/np.dot(g.T, g)\n \n # Neutralize e by subtracting e_biascomponent from it \n # e_debiased should be equal to its orthogonal projection. (≈ 1 line)\n e_debiased = e - e_biascomponent\n ### END CODE HERE ###\n \n return e_debiased",
"_____no_output_____"
],
[
"e = \"receptionist\"\nprint(\"cosine similarity between \" + e + \" and g, before neutralizing: \", cosine_similarity(word_to_vec_map[\"receptionist\"], g))\n\ne_debiased = neutralize(\"receptionist\", g, word_to_vec_map)\nprint(\"cosine similarity between \" + e + \" and g, after neutralizing: \", cosine_similarity(e_debiased, g))",
"cosine similarity between receptionist and g, before neutralizing: 0.330779417506\ncosine similarity between receptionist and g, after neutralizing: 5.84103233224e-18\n"
]
],
[
[
"**Expected Output**: The second result is essentially 0, up to numerical rounding (on the order of $10^{-17}$).\n\n\n<table>\n <tr>\n <td>\n **cosine similarity between receptionist and g, before neutralizing:** :\n </td>\n <td>\n 0.330779417506\n </td>\n </tr>\n <tr>\n <td>\n **cosine similarity between receptionist and g, after neutralizing:** :\n </td>\n <td>\n -3.26732746085e-17\n </tr>\n</table>",
"_____no_output_____"
],
[
"### 3.2 - Equalization algorithm for gender-specific words\n\nNext, lets see how debiasing can also be applied to word pairs such as \"actress\" and \"actor.\" Equalization is applied to pairs of words that you might want to have differ only through the gender property. As a concrete example, suppose that \"actress\" is closer to \"babysit\" than \"actor.\" By applying neutralizing to \"babysit\" we can reduce the gender-stereotype associated with babysitting. But this still does not guarantee that \"actor\" and \"actress\" are equidistant from \"babysit.\" The equalization algorithm takes care of this. \n\nThe key idea behind equalization is to make sure that a particular pair of words are equi-distant from the 49-dimensional $g_\\perp$. The equalization step also ensures that the two equalized steps are now the same distance from $e_{receptionist}^{debiased}$, or from any other work that has been neutralized. In pictures, this is how equalization works: \n\n<img src=\"images/equalize10.png\" style=\"width:800px;height:400px;\">\n\n\nThe derivation of the linear algebra to do this is a bit more complex. (See Bolukbasi et al., 2016 for details.) But the key equations are: \n\n$$ \\mu = \\frac{e_{w1} + e_{w2}}{2}\\tag{4}$$ \n\n$$ \\mu_{B} = \\frac {\\mu \\cdot \\text{bias_axis}}{||\\text{bias_axis}||_2^2} *\\text{bias_axis}\n\\tag{5}$$ \n\n$$\\mu_{\\perp} = \\mu - \\mu_{B} \\tag{6}$$\n\n$$ e_{w1B} = \\frac {e_{w1} \\cdot \\text{bias_axis}}{||\\text{bias_axis}||_2^2} *\\text{bias_axis}\n\\tag{7}$$ \n$$ e_{w2B} = \\frac {e_{w2} \\cdot \\text{bias_axis}}{||\\text{bias_axis}||_2^2} *\\text{bias_axis}\n\\tag{8}$$\n\n\n$$e_{w1B}^{corrected} = \\sqrt{ |{1 - ||\\mu_{\\perp} ||^2_2} |} * \\frac{e_{\\text{w1B}} - \\mu_B} {||(e_{w1} - \\mu_{\\perp}) - \\mu_B||} \\tag{9}$$\n\n\n$$e_{w2B}^{corrected} = \\sqrt{ |{1 - ||\\mu_{\\perp} ||^2_2} |} * \\frac{e_{\\text{w2B}} - \\mu_B} {||(e_{w2} - \\mu_{\\perp}) - \\mu_B||} \\tag{10}$$\n\n$$e_1 = e_{w1B}^{corrected} + \\mu_{\\perp} \\tag{11}$$\n$$e_2 = e_{w2B}^{corrected} + \\mu_{\\perp} \\tag{12}$$\n\n\n**Exercise**: Implement the function below. Use the equations above to get the final equalized version of the pair of words. Good luck!",
"_____no_output_____"
]
],
[
[
"def equalize(pair, bias_axis, word_to_vec_map):\n \"\"\"\n Debias gender specific words by following the equalize method described in the figure above.\n \n Arguments:\n pair -- pair of strings of gender specific words to debias, e.g. (\"actress\", \"actor\") \n bias_axis -- numpy-array of shape (50,), vector corresponding to the bias axis, e.g. gender\n word_to_vec_map -- dictionary mapping words to their corresponding vectors\n \n Returns\n e_1 -- word vector corresponding to the first word\n e_2 -- word vector corresponding to the second word\n \"\"\"\n \n ### START CODE HERE ###\n # Step 1: Select word vector representation of \"word\". Use word_to_vec_map. (≈ 2 lines)\n w1, w2 = None\n e_w1, e_w2 = None\n \n # Step 2: Compute the mean of e_w1 and e_w2 (≈ 1 line)\n mu = None\n\n # Step 3: Compute the projections of mu over the bias axis and the orthogonal axis (≈ 2 lines)\n mu_B = None\n mu_orth = None\n\n # Step 4: Use equations (7) and (8) to compute e_w1B and e_w2B (≈2 lines)\n e_w1B = None\n e_w2B = None\n \n # Step 5: Adjust the Bias part of e_w1B and e_w2B using the formulas (9) and (10) given above (≈2 lines)\n corrected_e_w1B = None\n corrected_e_w2B = None\n\n # Step 6: Debias by equalizing e1 and e2 to the sum of their corrected projections (≈2 lines)\n e1 = None\n e2 = None\n \n ### END CODE HERE ###\n \n return e1, e2",
"_____no_output_____"
],
[
"print(\"cosine similarities before equalizing:\")\nprint(\"cosine_similarity(word_to_vec_map[\\\"man\\\"], gender) = \", cosine_similarity(word_to_vec_map[\"man\"], g))\nprint(\"cosine_similarity(word_to_vec_map[\\\"woman\\\"], gender) = \", cosine_similarity(word_to_vec_map[\"woman\"], g))\nprint()\ne1, e2 = equalize((\"man\", \"woman\"), g, word_to_vec_map)\nprint(\"cosine similarities after equalizing:\")\nprint(\"cosine_similarity(e1, gender) = \", cosine_similarity(e1, g))\nprint(\"cosine_similarity(e2, gender) = \", cosine_similarity(e2, g))",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\ncosine similarities before equalizing:\n<table>\n <tr>\n <td>\n **cosine_similarity(word_to_vec_map[\"man\"], gender)** =\n </td>\n <td>\n -0.117110957653\n </td>\n </tr>\n <tr>\n <td>\n **cosine_similarity(word_to_vec_map[\"woman\"], gender)** =\n </td>\n <td>\n 0.356666188463\n </td>\n </tr>\n</table>\n\ncosine similarities after equalizing:\n<table>\n <tr>\n <td>\n **cosine_similarity(u1, gender)** =\n </td>\n <td>\n -0.700436428931\n </td>\n </tr>\n <tr>\n <td>\n **cosine_similarity(u2, gender)** =\n </td>\n <td>\n 0.700436428931\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"Please feel free to play with the input words in the cell above, to apply equalization to other pairs of words. \n\nThese debiasing algorithms are very helpful for reducing bias, but are not perfect and do not eliminate all traces of bias. For example, one weakness of this implementation was that the bias direction $g$ was defined using only the pair of words _woman_ and _man_. As discussed earlier, if $g$ were defined by computing $g_1 = e_{woman} - e_{man}$; $g_2 = e_{mother} - e_{father}$; $g_3 = e_{girl} - e_{boy}$; and so on and averaging over them, you would obtain a better estimate of the \"gender\" dimension in the 50 dimensional word embedding space. Feel free to play with such variants as well. \n ",
"_____no_output_____"
],
[
"### Congratulations\n\nYou have come to the end of this notebook, and have seen a lot of the ways that word vectors can be used as well as modified. \n\nCongratulations on finishing this notebook! \n",
"_____no_output_____"
],
[
"**References**:\n- The debiasing algorithm is from Bolukbasi et al., 2016, [Man is to Computer Programmer as Woman is to\nHomemaker? Debiasing Word Embeddings](https://papers.nips.cc/paper/6228-man-is-to-computer-programmer-as-woman-is-to-homemaker-debiasing-word-embeddings.pdf)\n- The GloVe word embeddings were due to Jeffrey Pennington, Richard Socher, and Christopher D. Manning. (https://nlp.stanford.edu/projects/glove/)\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cba2561c314d4a87f8f9c06a32b44b9a8baffd57
| 143,988 |
ipynb
|
Jupyter Notebook
|
BERT_tweet.ipynb
|
bernardpg/tweet_sentiment-analysis
|
80d35a1222a014f9cb41cff9c6f114ea027afef9
|
[
"MIT"
] | null | null | null |
BERT_tweet.ipynb
|
bernardpg/tweet_sentiment-analysis
|
80d35a1222a014f9cb41cff9c6f114ea027afef9
|
[
"MIT"
] | null | null | null |
BERT_tweet.ipynb
|
bernardpg/tweet_sentiment-analysis
|
80d35a1222a014f9cb41cff9c6f114ea027afef9
|
[
"MIT"
] | null | null | null | 57.160778 | 19,242 | 0.561811 |
[
[
[
"## Versions of used packages\n\nWe will check PyTorch version to make sure everything work properly.\n\nWe use `python 3.6.9`, `torch==1.6.0`",
"_____no_output_____"
]
],
[
[
"!python --version\n!pip freeze | grep torch",
"Python 3.6.9\ntorch==1.7.0+cu101\ntorchsummary==1.5.1\ntorchtext==0.3.1\ntorchvision==0.8.1+cu101\n"
],
[
"!pip install transformers",
"Collecting transformers\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/50/0c/7d5950fcd80b029be0a8891727ba21e0cd27692c407c51261c3c921f6da3/transformers-4.1.1-py3-none-any.whl (1.5MB)\n\u001b[K |████████████████████████████████| 1.5MB 9.1MB/s \n\u001b[?25hCollecting tokenizers==0.9.4\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/0f/1c/e789a8b12e28be5bc1ce2156cf87cb522b379be9cadc7ad8091a4cc107c4/tokenizers-0.9.4-cp36-cp36m-manylinux2010_x86_64.whl (2.9MB)\n\u001b[K |████████████████████████████████| 2.9MB 30.6MB/s \n\u001b[?25hRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers) (0.8)\nRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers) (3.0.12)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers) (2019.12.20)\nRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from transformers) (1.19.4)\nRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers) (4.41.1)\nCollecting sacremoses\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/7d/34/09d19aff26edcc8eb2a01bed8e98f13a1537005d31e95233fd48216eed10/sacremoses-0.0.43.tar.gz (883kB)\n\u001b[K |████████████████████████████████| 890kB 52.1MB/s \n\u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers) (20.8)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2020.12.5)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (1.15.0)\nRequirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (1.0.0)\nRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers) (2.4.7)\nBuilding wheels for collected packages: sacremoses\n Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for sacremoses: filename=sacremoses-0.0.43-cp36-none-any.whl size=893261 sha256=2ac20aa0b025098bd43103773bcefe91c9c1803fec45f620138aa5e025b5cdac\n Stored in directory: /root/.cache/pip/wheels/29/3c/fd/7ce5c3f0666dab31a50123635e6fb5e19ceb42ce38d4e58f45\nSuccessfully built sacremoses\nInstalling collected packages: tokenizers, sacremoses, transformers\nSuccessfully installed sacremoses-0.0.43 tokenizers-0.9.4 transformers-4.1.1\n"
]
],
[
[
"## Error handling\n\n**RuntimeError: CUDA out of memory...**\n> 發生原因可能為讀取的 batch 過大或是記憶體未釋放乾淨。若縮小 batch size 後仍出現錯誤請按照以下步驟重新載入 colab。\n\n1. Click 「Runtime」\n2. Click 「Factor reset runtime」\n3. Click 「Reconnect」\n4. Reload all chunk\n\n",
"_____no_output_____"
],
[
"## Get Data\n\n請先到共用雲端硬碟將檔案`flower_data.zip`,建立捷徑到自己的雲端硬碟中。\n\n> 操作步驟\n1. 點開雲端[連結](https://drive.google.com/file/d/1rTfeCpKXoQXI978QiTWC-AI1vwGvd5SU/view?usp=sharing)\n2. 點選右上角「新增雲端硬碟捷徑」\n3. 點選「我的雲端硬碟」\n4. 點選「新增捷徑」\n\n完成以上流程會在你的雲端硬碟中建立一個檔案的捷徑,接著我們在colab中取得權限即可使用。",
"_____no_output_____"
],
[
"執行此段後點選出現的連結,允許授權後,複製授權碼,貼在空格中後按下ENTER,即完成與雲端硬碟連結。",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"!unzip -qq ./drive/My\\ Drive/twitter_sentiment.zip",
"_____no_output_____"
]
],
[
[
"## Loading the dataset\n",
"_____no_output_____"
],
[
"### Custom dataset\n\n繼承自定義資料集的框架 `torch.utils.data.Dataset`,主要實現 `__getitem__()` 和 `__len__()` 這兩個方法。\n\n常使用來做到設定資料位址、設定讀取方式、子資料集的標籤和轉換條件...等。\n\nSee [torch.utils.data.Dataset](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) for more details",
"_____no_output_____"
]
],
[
[
"import csv\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nimport torchtext\r\n#from torchtext.datasets import text_classification\r\nfrom transformers import BertModel, BertTokenizer\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')",
"_____no_output_____"
]
],
[
[
"# sentence to word \r\nstep 1 分割\r\n\r\nstpe 2 放上token \r\n\r\nstep 3 設定最大詞句需要多少\r\n\r\nstep 4 segment 區分不同句子\r\n",
"_____no_output_____"
]
],
[
[
"class Twitter(torch.utils.data.Dataset):\n def __init__(self, csv_file, mode='train', transform=None):\n \n self.mode = mode # 'train', 'val' or 'test'\n self.data_list = []\n self.labels = []\n self.transform = transform \n with open(csv_file, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n self.data_list.append(row['text'])\n if mode != 'test':\n self.labels.append(row['sentiment_label'])\n\n def __getitem__(self, index):\n #self.data_list[index] = str(self.data_list[index])\n encoded_dict = tokenizer.encode_plus(self.data_list[index],add_special_tokens=True,max_length=64,\n pad_to_max_length=True,return_attention_mask=True,return_tensors='pt')\n sentence = encoded_dict['input_ids'].flatten()\n atten_mask= encoded_dict['attention_mask'].flatten()\n seg_ids =encoded_dict['token_type_ids'].flatten()\n #seg_ids = [0 for _ in range(len(sentence))]\n #sentence = tokenizer.tokenize(self.data_list[index])\n #sentence = ['[CLS]']+sentence+['[SEP]']\n #seg_ids = torch.tensor(seg_ids).unsqueeze(0)\n if self.mode == 'test':\n\n return sentence,atten_mask,seg_ids,self.data_list[index]\n label = torch.tensor(int(self.labels[index]))\n #MAX_sentence =128 #一句最大128\n #padded_sentence = sentence + ['[PAD]' for _ in range(128 - len(sentence))]\n #attn_mask = [1 if token != '[PAD]' else 0 for token in padded_sentence]\n # 有單詞為1 無單詞為0\n #seg_ids = [0 for _ in range(len(sentence))] #切割不同句子\n #token_ids = tokenizer.convert_tokens_to_ids(padded_sentence)\n #token_ids = torch.tensor(token_ids).unsqueeze(0)\n #atten_mask = torch.tensor(attn_mask).unsqueeze(0)\n return sentence,atten_mask,seg_ids,label\n\n def __len__(self):\n return len(self.data_list)",
"_____no_output_____"
]
],
[
[
"### Instantiate dataset\n\nLet's instantiate three `FlowerData` class.\n+ dataset_train: for training.\n+ dataset_val: for validation.\n+ dataset_test: for tesing.",
"_____no_output_____"
]
],
[
[
"dataset_train = Twitter('./twitter_sentiment/train.csv', mode='train')#, transform=transforms_train)\r\ndataset_val = Twitter('./twitter_sentiment/val.csv', mode='val')#, transform=transforms_test)\r\ndataset_test = Twitter('./twitter_sentiment/test.csv', mode='test')#, transform=transforms_test)",
"_____no_output_____"
],
[
"print(\"The first token's shape in dataset_train :\", dataset_train.__getitem__(1)[0])\r\nprint(\"There are\", dataset_train.__len__(), \"twitter text in dataset_train.\")",
"Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precisely by providing a specific strategy to `truncation`.\n"
]
],
[
[
"### `DataLoader`\n\n`torch.utils.data.DataLoader` define how to sample from `dataset` and some other function like:\n+ `shuffle` : set to `True` to have the data reshuffled at every epoch\n+ `batch_size` : how many samples per batch to load\n\nSee [torch.utils.data.DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) for more details",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import DataLoader\n\n# 設定batch數量\nbatchSizeNums = 64\n\ntrain_loader = DataLoader(dataset_train, batch_size=batchSizeNums, shuffle=True)\nval_loader = DataLoader(dataset_val, batch_size=batchSizeNums, shuffle=False)\ntest_loader = DataLoader(dataset_test, batch_size=batchSizeNums, shuffle=False)",
"_____no_output_____"
]
],
[
[
"Finally! We have made all data prepared. \nLet's go develop our model.",
"_____no_output_____"
],
[
"#Deploy model",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn \r\nimport torch.nn.functional as F\r\nfrom transformers import BertModel, BertTokenizer,BertForSequenceClassification,BertConfig\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\nnum_labels=3\r\nconfig = BertConfig.from_pretrained(\"bert-base-uncased\", num_labels=num_labels)\r\nmodel = BertForSequenceClassification.from_pretrained('bert-base-uncased',config=config)\r\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased')#, config=config)\r\n\"\"\"\r\nclass SentimentClassifier(nn.Module):\r\n\r\n def __init__(self, n_classes):\r\n super(SentimentClassifier, self).__init__()\r\n self.bert = BertModel.from_pretrained(\"bert-base-uncased\")\r\n self.drop = nn.Dropout(p=0.3)\r\n self.out = nn.Linear(self.bert.config.hidden_size,num_labels)\r\n \r\n def forward(self, input_ids, attention_mask):\r\n _, pooled_output = self.bert(\r\n input_ids=input_ids,\r\n attention_mask=attention_mask\r\n )\r\n #output = self.drop(pooled_output)\r\n return self.out(pooled_output)\r\n\"\"\"\r\n#model=SentimentClassifier(3)\r\nmodel.to(device)\r\n",
"_____no_output_____"
]
],
[
[
"### Define loss and optimizer",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.optim as optim\n################################################################################\n# TODO: Define loss and optmizer functions\n# Try any loss or optimizer function and learning rate to get better result\n# hint: torch.nn and torch.optim\n################################################################################\ncriterion = nn.CrossEntropyLoss()\n#optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\nlearning_rate=1e-5\nweight_decay = 1e-2\nno_decay = ['bias', 'LayerNorm.weight']\noptimizer_grouped_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': weight_decay},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n]\noptimizer = optim.AdamW(optimizer_grouped_parameters, lr=learning_rate)\n#optimizer = optim.Adam(bert_model.parameters(), lr=1e-5)\n################################################################################\n# End of your code\n################################################################################\ncriterion = criterion.cuda()",
"_____no_output_____"
]
],
[
[
"### Train the model",
"_____no_output_____"
],
[
"#### Train function\nLet's define train function. \nIt will iterate input data 1 epoch and update model with optmizer. \nFinally, calculate mean loss and total accuracy.\n\nHint: [torch.max()](https://pytorch.org/docs/stable/generated/torch.max.html#torch-max)",
"_____no_output_____"
]
],
[
[
"# Early Stopping\n# 來源: https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py\nimport numpy as np\nimport torch\n\nclass EarlyStopping:\n \"\"\"Early stops the training if validation loss doesn't improve after a given patience.\"\"\"\n def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt', trace_func=print):\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved.\n Default: 7\n verbose (bool): If True, prints a message for each validation loss improvement. \n Default: False\n delta (float): Minimum change in the monitored quantity to qualify as an improvement.\n Default: 0\n path (str): Path for the checkpoint to be saved to.\n Default: 'checkpoint.pt'\n trace_func (function): trace print function.\n Default: print \n \"\"\"\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_min = np.Inf\n self.delta = delta\n self.path = path\n self.trace_func = trace_func\n def __call__(self, val_loss, model):\n\n score = -val_loss\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n elif score < self.best_score + self.delta:\n self.counter += 1\n self.trace_func(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n self.counter = 0\n\n def save_checkpoint(self, val_loss, model):\n '''Saves model when validation loss decrease.'''\n if self.verbose:\n self.trace_func(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n torch.save(model.state_dict(), self.path)\n self.val_loss_min = val_loss",
"_____no_output_____"
],
[
"# mix up寫法\n# https://www.kaggle.com/c/bengaliai-cv19/discussion/128592\n# !pip install torchtoolbox\n# from torchtoolbox.tools import mixup_data, mixup_criterion",
"_____no_output_____"
],
[
"def train(input_data, model, criterion, optimizer):\n '''\n Argement:\n input_data -- iterable data, typr torch.utils.data.Dataloader is prefer\n model -- nn.Module, model contain forward to predict output\n criterion -- loss function, used to evaluate goodness of model\n optimizer -- optmizer function, method for weight updating\n token_ids,atten_mask,seg_ids,label\n '''\n model.train()\n loss_list = []\n total_count = 0\n acc_count = 0\n for i, data in enumerate(input_data, 0):\n token_ids,atten_mask,labels = data[0].cuda(),data[1].cuda(),data[3].cuda()\n #print(token_ids.size())\n labels = labels.unsqueeze(1)\n #print(atten_mask.size())\n #print(labels.size())\n ########################################################################\n # TODO: Forward, backward and optimize\n # 1. zero the parameter gradients\n # 2. process input through the network\n # 3. compute the loss\n # 4. propagate gradients back into the network’s parameters\n # 5. Update the weights of the network\n ########################################################################\n optimizer.zero_grad()\n outputs = model(token_ids,attention_mask=atten_mask,labels=labels)\n train_loss = outputs.loss#criterion(outputs.loss,labels)\n train_loss.backward()\n optimizer.step()\n ########################################################################\n # End of your code\n ########################################################################\n\n\n ########################################################################\n # TODO: Get the counts of correctly classified images\n # 1. get the model predicted result\n # 2. sum the number of this batch predicted images\n # 3. sum the number of correctly classified\n # 4. save this batch's loss into loss_list\n # dimension of outputs: [batch_size, number of classes]\n # Hint 1: use outputs.data to get no auto_grad\n # Hint 2: use torch.max()\n ########################################################################\n y_pred_prob = outputs[1]\n y_pred_label = y_pred_prob.argmax(dim=1)\n #_, predicted = torch.max(outputs[1], 1)\n #print(y_pred_label)\n #print(labels)\n total_count += len(labels)\n acc_count += (y_pred_label == labels).int().sum()\n loss_list.append(train_loss.item())\n ########################################################################\n # End of your code\n ########################################################################\n\n # Compute this epoch accuracy and loss\n acc = acc_count / total_count\n loss = sum(loss_list) / len(loss_list)\n return acc, loss",
"_____no_output_____"
]
],
[
[
"#### Validate function\nNext part is validate function. \nIt works as training function without optmizer and weight-updating part.",
"_____no_output_____"
]
],
[
[
"def val(input_data, model, criterion):\n model.eval()\n \n loss_list = []\n total_count = 0\n acc_count = 0\n with torch.no_grad():\n for data in input_data:\n token_ids,atten_mask,labels = data[0].cuda(),data[1].cuda(),data[3].cuda()\n labels = labels.unsqueeze(1)\n\n ####################################################################\n # TODO: Get the predicted result and loss\n # 1. process input through the network\n # 2. compute the loss\n # 3. get the model predicted result\n # 4. get the counts of correctly classified images\n # 5. save this batch's loss into loss_list attention_mask=atten_mask,\n ####################################################################\n outputs = model(token_ids,attention_mask=atten_mask,labels=labels)\n val_loss = outputs.loss#criterion(outputs,labels)\n y_pred_prob = outputs[1]\n y_pred_label = y_pred_prob.argmax(dim=1)\n #predicted = torch.max(outputs, 1)[1]\n total_count += len(labels)\n acc_count += (y_pred_label == labels).int().sum()\n loss_list.append(val_loss.item())\n ####################################################################\n # End of your code\n ####################################################################\n\n acc = acc_count / total_count\n loss = sum(loss_list) / len(loss_list)\n return acc, loss",
"_____no_output_____"
]
],
[
[
"#### Training in a loop\nCall train and test function in a loop. \nTake a break and wait.",
"_____no_output_____"
]
],
[
[
"################################################################################\n# You can adjust those hyper parameters to loop for max_epochs times #\n################################################################################\nmax_epochs = 4\nlog_interval = 2 # print acc and loss in per log_interval time\nearly_stopping_patience = 30\n################################################################################\n# End of your code #\n################################################################################\ntrain_acc_list = []\ntrain_loss_list = []\nval_acc_list = []\nval_loss_list = []\n\n# initialize the early_stopping object\nearly_stopping = EarlyStopping(patience=early_stopping_patience, verbose=False)\n\nfor epoch in range(1, max_epochs + 1):\n train_acc, train_loss = train(train_loader,model, criterion, optimizer)\n val_acc, val_loss = val(val_loader, model, criterion)\n\n train_acc_list.append(train_acc)\n train_loss_list.append(train_loss)\n val_acc_list.append(val_acc)\n val_loss_list.append(val_loss)\n\n if epoch % log_interval == 0:\n print('=' * 20, 'Epoch', epoch, '=' * 20)\n print('Train Acc: {:.6f} Train Loss: {:.6f}'.format(train_acc, train_loss))\n print(' Val Acc: {:.6f} Val Loss: {:.6f}'.format(val_acc, val_loss))\n \n # 判斷是否達到Early Stopping\n early_stopping(val_loss, model)\n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n\n# load the last checkpoint with the best model\nmodel.load_state_dict(torch.load('checkpoint.pt'))",
"Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precisely by providing a specific strategy to `truncation`.\n/usr/local/lib/python3.6/dist-packages/transformers/tokenization_utils_base.py:2179: FutureWarning: The `pad_to_max_length` argument is deprecated and will be removed in a future version, use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or use `padding='max_length'` to pad to a max length. In this case, you can give a specific length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).\n FutureWarning,\n"
]
],
[
[
"#### Visualize accuracy and loss",
"_____no_output_____"
]
],
[
[
"best_epoch = val_loss_list.index(min(val_loss_list))\nprint('Early Stopping Epoch:', best_epoch)\nprint('Train Acc: {:.6f} Train Loss: {:.6f}'.format(train_acc_list[best_epoch], train_loss_list[best_epoch]))\nprint(' Val Acc: {:.6f} Val Loss: {:.6f}'.format(val_acc_list[best_epoch], val_loss_list[best_epoch]))",
"Early Stopping Epoch: 1\nTrain Acc: 30.586748 Train Loss: 0.405914\n Val Acc: 30.256830 Val Loss: 0.406030\n"
],
[
"import matplotlib.pyplot as plt\n\nplt.figure(figsize=(12, 4))\nplt.plot(range(len(train_loss_list)), train_loss_list)\nplt.plot(range(len(val_loss_list)), val_loss_list, c='r')\nplt.legend(['train', 'val'])\nplt.title('Loss')\nplt.axvline(best_epoch, linestyle='--', color='r',label='Early Stopping Checkpoint')\nplt.show()\n\nplt.figure(figsize=(12, 4))\nplt.plot(range(len(train_acc_list)), train_acc_list)\nplt.plot(range(len(val_acc_list)), val_acc_list, c='r')\nplt.legend(['train', 'val'])\nplt.title('Acc')\nplt.axvline(best_epoch, linestyle='--', color='r',label='Early Stopping Checkpoint')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Predict Result\n\n預測`test`並將結果上傳至Kaggle。[**連結**](https://www.kaggle.com/t/a16786b7da97419f9ba90b495dab08aa)\n\n執行完畢此區的程式碼後,會將`test`預測完的結果存下來。\n\n上傳流程\n1. 點選左側選單最下方的資料夾圖示\n2. 右鍵「result.csv」\n3. 點選「Download」\n4. 至連結網頁點選「Submit Predictions」\n5. 將剛剛下載的檔案上傳\n6. 系統會計算並公布其中70%資料的正確率",
"_____no_output_____"
]
],
[
[
"def predict(input_data, model):\n model.eval()\n output_list = []\n text = []\n with torch.no_grad():\n for data in input_data:\n token_ids,atten_mask,segments_tensors,senten= data[0].cuda(),data[1].cuda(),data[2].cuda(),data[3]\n print(segments_tensors)\n #labels = labels.unsqueeze(1)\n #segments_tensors = segments_tensors.flatten()\n outputs = model(token_ids,token_type_ids=segments_tensors,attention_mask=atten_mask)\n y_pred_prob = outputs[0]\n y_pred_label = y_pred_prob.argmax(dim=1)\n #outputs = model(images)\n #_, predicted = torch.max(outputs.data, 1)\n output_list.extend(y_pred_label.to('cpu').numpy().tolist())\n for r in (senten):\n text.append(r)\n return output_list,text",
"_____no_output_____"
],
[
"output_csv,text = predict(test_loader, model)\nwith open('result.csv', 'w', newline='') as csvFile:\n writer = csv.DictWriter(csvFile, fieldnames=['index','sentiment_label'])\n writer.writeheader()\n idx = 0\n #'text' :text[idx] ,\n for result in output_csv:\n writer.writerow({'index':idx,'sentiment_label':result})\n idx+=1\n",
"/usr/local/lib/python3.6/dist-packages/transformers/tokenization_utils_base.py:2179: FutureWarning: The `pad_to_max_length` argument is deprecated and will be removed in a future version, use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or use `padding='max_length'` to pad to a max length. In this case, you can give a specific length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).\n FutureWarning,\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cba2570f51489d145e62f74307e96d463aea0e62
| 6,478 |
ipynb
|
Jupyter Notebook
|
Chapter7/Fig7_1_H2_groundstate.ipynb
|
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
|
6d19cd4a517126e0f4737ba0f338117098224d92
|
[
"CC0-1.0",
"CC-BY-4.0"
] | 10 |
2021-04-20T07:26:10.000Z
|
2022-02-24T11:02:47.000Z
|
Chapter7/Fig7_1_H2_groundstate.ipynb
|
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
|
6d19cd4a517126e0f4737ba0f338117098224d92
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
Chapter7/Fig7_1_H2_groundstate.ipynb
|
CambridgeUniversityPress/Interstellar-and-Intergalactic-Medium
|
6d19cd4a517126e0f4737ba0f338117098224d92
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | 29.18018 | 172 | 0.555418 |
[
[
[
"# Molecular Hydrogen H<sub>2</sub> Ground State\n\nFigure 7.1 from Chapter 7 of *Interstellar and Intergalactic Medium* by Ryden & Pogge, 2021, \nCambridge University Press.\n\nPlot the ground state potential of the H<sub>2</sub> molecule (E vs R) and the bound vibration levels.\n\nUses files with the H<sub>2</sub> potential curves tabulated by [Sharp, 1971, Atomic Data, 2, 119](https://ui.adsabs.harvard.edu/abs/1971AD......2..119S/abstract).\n\nAll of the data files used are in the H2 subfolder that should accompany this notebook.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter\n\nimport warnings\nwarnings.filterwarnings('ignore',category=UserWarning, append=True)",
"_____no_output_____"
]
],
[
[
"## Standard Plot Format\n\nSetup the standard plotting format and make the plot. Fonts and resolution adopted follow CUP style.",
"_____no_output_____"
]
],
[
[
"figName = 'Fig7_1' \n\n# graphic aspect ratio = width/height\n\naspect = 4.0/3.0 # 4:3\n\n# Text width in inches - don't change, this is defined by the print layout\n\ntextWidth = 6.0 # inches\n\n# output format and resolution\n\nfigFmt = 'png'\ndpi = 600\n\n# Graphic dimensions \n\nplotWidth = dpi*textWidth\nplotHeight = plotWidth/aspect\naxisFontSize = 10\nlabelFontSize = 8\nlwidth = 0.5\naxisPad = 5\nwInches = textWidth \nhInches = wInches/aspect\n\n# Plot filename\n\nplotFile = f'{figName}.{figFmt}'\n\n# LaTeX is used throughout for markup of symbols, Times-Roman serif font\n\nplt.rc('text', usetex=True)\nplt.rc('font', **{'family':'serif','serif':['Times-Roman'],'weight':'bold','size':'16'})\n\n# Font and line weight defaults for axes\n\nmatplotlib.rc('axes',linewidth=lwidth)\nmatplotlib.rcParams.update({'font.size':axisFontSize})\n\n# axis and label padding\n\nplt.rcParams['xtick.major.pad'] = f'{axisPad}'\nplt.rcParams['ytick.major.pad'] = f'{axisPad}'\nplt.rcParams['axes.labelpad'] = f'{axisPad}'",
"_____no_output_____"
]
],
[
[
"## H<sub>2</sub> energy level potential data \n\nH$_2$ $^{1}\\Sigma_{g}^{+}$ ground state data from Sharp 1971:\n\nPotential curve: H2_1Sigma_g+_potl.dat:\n * interproton distance, r, in Angstroms\n * potential energy, V(r), in eV\n \nVibrational levels: H2_1Sigma_g+_v.dat:\n * v = vibrational quantum number\n * eV = energy in eV\n * Rmin = minimum inter-proton distance in Angstroms\n * Rmax = maximum inter-proton distance in Angstroms",
"_____no_output_____"
]
],
[
[
"potlFile = './H2/H2_1Sigma_g+_potl.dat'\nvibFile = './H2/H2_1Sigma_g+_v.dat'\n\ndata = pd.read_csv(potlFile,sep=r'\\s+')\ngsR = np.array(data['R']) # radius in Angstroms\ngsE = np.array(data['eV']) # energy in eV\n\ndata = pd.read_csv(vibFile,sep=r'\\s+')\nv = np.array(data['v']) # vibrational quantum number\nvE = np.array(data['eV'])\nrMin = np.array(data['Rmin'])\nrMax = np.array(data['Rmax'])\n\n# plotting limits\n\nminR = 0.0\nmaxR = 5.0\nminE = -0.5\nmaxE = 6.0\n\n# Put labels on the vibrational levels?\n\nlabel_v = True",
"_____no_output_____"
]
],
[
[
"### Make the Plot\n\nPlot the ground-state potential curve as a thick black line, then draw the vibrational energy levels.",
"_____no_output_____"
]
],
[
[
"fig,ax = plt.subplots()\n\nfig.set_dpi(dpi)\nfig.set_size_inches(wInches,hInches,forward=True)\n\nax.tick_params('both',length=6,width=lwidth,which='major',direction='in',top='on',right='on')\nax.tick_params('both',length=3,width=lwidth,which='minor',direction='in',top='on',right='on')\n\n\nplt.xlim(minR,maxR)\nax.xaxis.set_major_locator(MultipleLocator(1))\nplt.xlabel(r'Distance between protons r [\\AA]',fontsize=axisFontSize)\n\nplt.ylim(minE,maxE)\nax.yaxis.set_major_locator(MultipleLocator(1.0))\nplt.ylabel(r'Potential energy V(r) [eV]',fontsize=axisFontSize)\n\n# plot the curves\n\nplt.plot(gsR,gsE,'-',color='black',lw=1.5,zorder=10)\n\nfor i in range(len(v)):\n plt.plot([rMin[i],rMax[i]],[vE[i],vE[i]],'-',color='black',lw=0.5,zorder=9)\n if v[i]==0:\n plt.text(rMin[i]-0.05,vE[i],rf'$v={v[i]}$',ha='right',va='center',fontsize=labelFontSize)\n elif v[i]==13:\n plt.text(rMin[i]-0.05,vE[i],rf'${v[i]}$',ha='right',va='center',fontsize=labelFontSize)\n\n# plot and file\n\nplt.plot()\nplt.savefig(plotFile,bbox_inches='tight',facecolor='white')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba25dec32af2779456cc6a160d25ae8368e9ef7
| 1,030,092 |
ipynb
|
Jupyter Notebook
|
notebooks/C15_LC18_yields.ipynb
|
aemerick/galaxy_analysis
|
a47c41e000a9b4fa5bad768010fb5ee03ed79e13
|
[
"MIT"
] | 1 |
2021-01-15T15:33:05.000Z
|
2021-01-15T15:33:05.000Z
|
notebooks/C15_LC18_yields.ipynb
|
aemerick/galaxy_analysis
|
a47c41e000a9b4fa5bad768010fb5ee03ed79e13
|
[
"MIT"
] | null | null | null |
notebooks/C15_LC18_yields.ipynb
|
aemerick/galaxy_analysis
|
a47c41e000a9b4fa5bad768010fb5ee03ed79e13
|
[
"MIT"
] | 1 |
2020-11-29T00:15:25.000Z
|
2020-11-29T00:15:25.000Z
| 1,259.281174 | 297,440 | 0.9509 |
[
[
[
"%matplotlib inline\nimport numpy as np\nimport sygma\nimport matplotlib.pyplot as plt\nfrom galaxy_analysis.plot.plot_styles import *\n\nimport galaxy_analysis.utilities.convert_abundances as ca\n\n\ndef plot_settings():\n fsize = 21\n rc('text',usetex=False)\n rc('font',size=fsize)\n return",
"_____no_output_____"
],
[
"sygma.sygma?",
"_____no_output_____"
],
[
"s = {}\nmetallicities = np.flip(np.array([0.02, 0.01, 0.006, 0.001, 0.0001]))\n\nfor z in metallicities:\n print(z)\n s[z] = sygma.sygma(iniZ = z, sn1a_on=False, #sn1a_rate='maoz',\n #iniabu_table = 'yield_tables/iniabu/iniab1.0E-02GN93.ppn',\n imf_yields_range=[1,25],\n table = 'yield_tables/agb_and_massive_stars_C15_LC18_R_mix_resampled.txt',\n mgal = 1.0)\n",
"0.0001\nSYGMA run in progress..\n SYGMA run completed - Run time: 0.17s\n0.001\nSYGMA run in progress..\n SYGMA run completed - Run time: 0.21s\n0.006\nSYGMA run in progress..\n SYGMA run completed - Run time: 0.16s\n0.01\nSYGMA run in progress..\n SYGMA run completed - Run time: 0.18s\n0.02\nSYGMA run in progress..\n SYGMA run completed - Run time: 0.16s\n"
],
[
"yields = {}\nyields_agb = {}\nyields_no_agb = {}\nfor z in metallicities:\n yields[z] = {}\n yields_agb[z] = {}\n yields_no_agb[z] = {}\n for i,e in enumerate(s[z].history.elements):\n index = s[z].history.elements.index(e)\n yields[z][e] = np.array(s[z].history.ism_elem_yield)[:,index]\n yields_agb[z][e] = np.array(s[z].history.ism_elem_yield_agb)[:,index]\n yields_no_agb[z][e] = yields[z][e] - yields_agb[z][e]\n",
"_____no_output_____"
],
[
"for z in metallicities:\n print(np.array(s[0.0001].history.",
"_____no_output_____"
],
[
"colors = {0.0001: 'C0',\n 0.001 : 'C1',\n 0.01 : 'C2',\n 0.02 : 'C3'}\n\n\ncolors = {}\nfor i,z in enumerate(metallicities):\n colors[z] = magma((i+1)/(1.0*np.size(metallicities)+1))",
"_____no_output_____"
],
[
"colors",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Ca','Mn','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(5*3,5*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.001,0.01]: # metallicities:\n \n label = z\n \n ax.plot(s[z].history.age[1:]/1.0E9, np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'O':\n ax.legend(loc='lower right')\n \n count += 1\n ax.set_xlim(0,2.0)\n \n #ax.semilogy()\n ax.set_ylim(-0.5,0.5)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('Time (Gyr)')\n all_ax[(i,0)].set_ylabel(r'[X/H] - [X/H]$_{0.0001}$')\n\n \nfig.savefig(\"X_H_lowz_comparison.png\")",
"/home/aemerick/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:19: RuntimeWarning: invalid value encountered in true_divide\n"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Ca','Mn','Fe','Sr','Ba']\n\ndenom = 'Mg'\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(5*3,5*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.0001,0.001,0.01]: # metallicities:\n \n label = z\n \n yvals = ca.abundance_ratio_array(e,\n yields_no_agb[z][e][1:], \n denom, yields_no_agb[z][denom][1:],input_type='mass')\n \n yvals2 = ca.abundance_ratio_array(e,\n yields_no_agb[0.0001][e][1:], \n denom, yields_no_agb[0.0001][denom][1:],input_type='mass')\n \n if z == 0.0001 and e == 'Ca': \n print(yvals)\n ax.plot(s[z].history.age[1:]/1.0E9, yvals,# - yvals2,\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n ax.set_ylim(-1,1)\n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'O':\n ax.legend(loc='lower right')\n \n count += 1\n ax.set_xlim(0,0.250)\n ax.plot(ax.get_xlim(),[0.0,0.0],lw=2,ls='--',color='black')\n \n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('Time (Gyr)')\n all_ax[(i,0)].set_ylabel(r'[X/Fe] - [X/Fe]$_{0.0001}$')\n\nfig.savefig(\"X_Mg.png\") \n#fig.savefig(\"X_Fe_lowz_comparison.png\")",
"/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n/home/aemerick/code/galaxy_analysis/utilities/convert_abundances.py:122: RuntimeWarning: invalid value encountered in double_scalars\n aratio = np.log10(x1_abund / x2_abund) - (x1_solar - x2_solar) # np.log10( x1_solar / x2_solar)\n"
],
[
"s1 = s[0.001]",
"_____no_output_____"
],
[
"np.array(s1.history.sn1a_numbers)[ (s1.history.age/ 1.0E9 < 1.1)] * 5.0E4",
"_____no_output_____"
],
[
"def wd_mass(mproj, model = 'salaris'):\n \n if np.size(mproj) == 1:\n mproj = np.array([mproj])\n \n wd = np.zeros(np.size(mproj))\n \n \n if model == 'salaris':\n wd[mproj < 4.0] = 0.134 * mproj[mproj < 4.0] + 0.331\n wd[mproj >= 4.0] = 0.047 * mproj[mproj >= 4.0] + 0.679\n elif model == 'mist':\n wd[mproj < 2.85] = 0.08*mproj[mproj<2.85]+0.489\n select=(mproj>2.85)*(mproj<3.6)\n wd[select]=0.187*mproj[select]+0.184\n select=(mproj>3.6)\n wd[select]=0.107*mproj[select]+0.471\n \n return wd\n",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Si','Ca','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(6*3,6*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in metallicities: #[0.0001,0.001,0.01,0.02]: # metallicities:\n \n label = \"Z=%.4f\"%(z)\n \n y = 1.0E4 * 1.0E6 * (yields[z][e][1:] - yields[z][e][:-1]) / (s[z].history.age[1:] - s[z].history.age[:-1])\n \n ax.plot(np.log10(s[z].history.age[1:]/1.0E6), y,\n #np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'Ba':\n ax.legend(loc='upper right')\n \n count += 1\n ax.set_xlim(0.8,4.2)\n \n #ax.semilogx()\n ax.semilogy()\n \n ax.set_ylim(2.0E-9,12.0)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('log(Time [Myr])')\n all_ax[(i,0)].set_ylabel(r'Rate [M$_{\\odot}$ / (10$^4$ M$_{\\odot}$) / Myr]')\n\n \nfig.savefig(\"C15_LC18_yields_rate.png\")",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Si','Ca','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(6*3,6*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.0001,0.001,0.01,0.02]: # metallicities:\n \n label = \"Z=%.4f\"%(z)\n \n #y = 1.0E4 * 1.0E6 * (yields[z][e][1:] - yields[z][e][:-1]) / (s[z].history.age[1:] - s[z].history.age[:-1])\n y = yields[z][e][1:]\n ax.plot(np.log10(s[z].history.age[1:]/1.0E6), y,\n #np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'Ba':\n ax.legend(loc='upper right')\n \n count += 1\n ax.set_xlim(0.8,4.2)\n \n #ax.semilogx()\n ax.semilogy()\n \n ax.set_ylim(1.0E-5,2.0E-2)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('log(Time [Myr])')\n all_ax[(i,0)].set_ylabel(r'Yield [M$_{\\odot}$]') #/ (10$^4$ M$_{\\odot}$)]')\n\n \nfig.savefig(\"C15_LC18_yields_total.png\")",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Si','Ca','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(6*3,6*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.0001,0.001,0.01,0.02]: # metallicities:\n \n label = \"Z=%.4f\"%(z)\n \n #y = 1.0E4 * 1.0E6 * (yields[z][e][1:] - yields[z][e][:-1]) / (s[z].history.age[1:] - s[z].history.age[:-1])\n y = 1.0E4 * yields[z][e][1:]\n ax.plot(np.log10(s[z].history.age[1:]/1.0E6), y,\n #np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'Ba':\n ax.legend(loc='upper right')\n \n count += 1\n ax.set_xlim(0.8,4.2)\n \n #ax.semilogx()\n ax.semilogy()\n \n ax.set_ylim(1.0E-6,1.0E3)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('log(Time [Myr])')\n all_ax[(i,0)].set_ylabel(r'Yield [M$_{\\odot}$ / (10$^4$ M$_{\\odot}$)]')\n\n \nfig.savefig(\"C15_LC18_yields_total.png\")",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Si','Ca','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(6*3,6*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.0001,0.001,0.01,0.02]: # metallicities:\n \n label = \"Z=%.4f\"%(z)\n \n #y = 1.0E4 * 1.0E6 * (yields[z][e][1:] - yields[z][e][:-1]) / (s[z].history.age[1:] - s[z].history.age[:-1])\n y = yields[z][e][1:] / yields[z][e][-1]\n ax.plot(np.log10(s[z].history.age[1:]/1.0E6), y,\n #np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'O':\n ax.legend(loc='lower right')\n \n count += 1\n ax.set_xlim(0.8,4.2)\n \n #ax.semilogx()\n #ax.semilogy()\n \n ax.set_ylim(0,1.0)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('log(Time [Myr])')\n all_ax[(i,0)].set_ylabel(r'Cumulative Fraction')\n\n \nfig.savefig(\"C15_LC18_yields_fraction.png\")",
"_____no_output_____"
],
[
"plot_settings()\n\nplot_elements = ['C','N','O','Mg','Si','Ca','Fe','Sr','Ba']\n\nfig, all_ax = plt.subplots(3,3,sharex=True,sharey=True)\nfig.subplots_adjust(wspace=0,hspace=0)\nfig.set_size_inches(6*3,6*3)\n\ncount = 0\nfor ax2 in all_ax:\n for ax in ax2:\n \n e = plot_elements[count]\n \n for z in [0.0001,0.001,0.01,0.02]: # metallicities:\n \n label = \"Z=%.4f\"%(z)\n \n y = 1.0E6 * (yields[z][e][1:] - yields[z][e][:-1]) / (s[z].history.age[1:] - s[z].history.age[:-1]) / yields[z][e][-1]\n \n ax.plot(np.log10(s[z].history.age[1:]/1.0E6), y,\n #np.log10(yields_no_agb[z][e][1:] / yields_no_agb[0.0001][e][1:]),\n lw = 3, color = colors[z], label = label)\n \n \n \n # ax.semilogy()\n #ax.set_ylim(0,2)\n \n \n xy=(0.1,0.1)\n ax.annotate(e,xy,xy,xycoords='axes fraction')\n \n if e == 'Ba':\n ax.legend(loc='upper right')\n \n count += 1\n ax.set_xlim(0.8,4.2)\n \n #ax.semilogx()\n ax.semilogy()\n \n ax.set_ylim(1.0E-5,1.0E-1)\n ax.plot(ax.get_xlim(), [0,0], lw=2,ls='--',color='black')\n \nfor i in np.arange(3):\n all_ax[(2,i)].set_xlabel('log(Time [Myr])')\n all_ax[(i,0)].set_ylabel(r'Fractional Rate [Myr$^{-1}$]')\n\n \nfig.savefig(\"C15_LC18_yields_fractional_rate.png\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba265b6d504907d69fa63b4c361f57d28cfbb04
| 115,058 |
ipynb
|
Jupyter Notebook
|
Bone_Detection.ipynb
|
Rajeev064/Bone-Anomaly-Detection
|
087a466050dde2114373c64621515ff5061ed9ed
|
[
"MIT"
] | 1 |
2021-05-13T06:30:30.000Z
|
2021-05-13T06:30:30.000Z
|
Bone_Detection.ipynb
|
Rajeev064/Bone-Anomaly-Detection
|
087a466050dde2114373c64621515ff5061ed9ed
|
[
"MIT"
] | null | null | null |
Bone_Detection.ipynb
|
Rajeev064/Bone-Anomaly-Detection
|
087a466050dde2114373c64621515ff5061ed9ed
|
[
"MIT"
] | null | null | null | 85.672375 | 28,022 | 0.722914 |
[
[
[
"import tensorflow as tf\nimport numpy as np\nimport keras\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nimport os\nimport cv2\nimport random\nimport keras.backend as K\nimport sklearn\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Input, BatchNormalization, GlobalAveragePooling2D\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.experimental import CosineDecay\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.applications import EfficientNetB3\nfrom tensorflow.keras.layers.experimental.preprocessing import RandomCrop,CenterCrop, RandomRotation\n%matplotlib inline",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"ROOT_DIR = '/content/drive/MyDrive/Broner'\ntrain_data = pd.read_csv('/content/drive/MyDrive/Broner/MURA-v1.1/train_path_label.csv' , dtype=str)\ntest_data = pd.read_csv('/content/drive/MyDrive/Broner/MURA-v1.1/valid_path_label.csv' , dtype=str)\ntrain_data\n",
"_____no_output_____"
],
[
"train_shoulder = train_data[:1300]\ntrain_humerus = train_data[8379:9651]\ntrain_forearm = train_data[29940:31265]\n \ntest_shoulder = test_data[1708:2100]\ntest_forearm = test_data[659:960]\ntest_humerus = test_data[1420:1708]",
"_____no_output_____"
],
[
"def change_class(df,val):\n for i in range(len(df)):\n df['label'] = val\n return df\ntemp = change_class(train_shoulder,'0')\ntype(temp['label'][0])",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n"
],
[
"train_shoulder = change_class(train_shoulder,'0')\ntrain_humerus = change_class(train_humerus,'1')\ntrain_forearm = change_class(train_forearm,'2')\n\ntest_shoulder = change_class(test_shoulder,'0')\ntest_humerus = change_class(test_humerus,'1')\ntest_forearm = change_class(test_forearm,'2')",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n"
],
[
"train_data = pd.concat([train_shoulder , train_forearm , train_humerus] , ignore_index=True)\ntrain_data",
"_____no_output_____"
],
[
"test_data = pd.concat([test_shoulder , test_forearm , test_humerus] , ignore_index=True)\ntest_data",
"_____no_output_____"
],
[
"train_data = train_data.sample(frac = 1)\ntest_data = test_data.sample(frac = 1)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nx_train , x_val , y_train , y_val = train_test_split(train_data['0'] , train_data['label'] , test_size = 0.2 , random_state=42 , stratify=train_data['label'])",
"_____no_output_____"
],
[
"val_data = pd.DataFrame()\nval_data['0']=x_val\nval_data['label']=y_val\nval_data.reset_index(inplace=True,drop=True)\nval_data",
"_____no_output_____"
],
[
"print(len(train_data) , len(test_data) , len(val_data))",
"3897 981 780\n"
],
[
"def preproc(image):\n image = image/255.\n image[:,:,0] = (image[:,:,0]-0.485)/0.229\n image[:,:,1] = (image[:,:,1]-0.456)/0.224\n image[:,:,2] = (image[:,:,2]-0.406)/0.225\n return image",
"_____no_output_____"
],
[
"train_datagen = keras.preprocessing.image.ImageDataGenerator(\n preprocessing_function = preproc,\n rotation_range=20,\n horizontal_flip=True,\n zoom_range = 0.15,\n validation_split = 0.1)\n\ntest_datagen = keras.preprocessing.image.ImageDataGenerator(\n preprocessing_function = preproc) ",
"_____no_output_____"
],
[
"train_generator=train_datagen.flow_from_dataframe(\ndataframe=train_data,\ndirectory=ROOT_DIR, \nx_col=\"0\",\ny_col=\"label\",\nsubset=\"training\",\nbatch_size=128,\nseed=42,\nshuffle=True,\nclass_mode=\"sparse\",\ntarget_size=(320,320))\n \nvalid_generator=train_datagen.flow_from_dataframe(\ndataframe=train_data,\ndirectory=ROOT_DIR,\nx_col=\"0\",\ny_col=\"label\",\nsubset=\"validation\",\nbatch_size=128,\nseed=42,\nshuffle=True,\nclass_mode=\"sparse\",\ntarget_size=(320,320))",
"Found 3508 validated image filenames belonging to 3 classes.\nFound 389 validated image filenames belonging to 3 classes.\n"
],
[
"from tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dropout, Flatten, Dense, Activation, Convolution2D, MaxPooling2D",
"_____no_output_____"
],
[
"# TARGET_SIZE = 320\n# cnn = Sequential()\n# cnn.add(Convolution2D(filters=32, kernel_size=5, padding =\"same\", input_shape=(TARGET_SIZE, TARGET_SIZE, 3), activation='relu'))\n# cnn.add(MaxPooling2D(pool_size=(3,3)))\n\n# cnn.add(Convolution2D(filters=64, kernel_size=3, padding =\"same\",activation='relu'))\n# cnn.add(MaxPooling2D(pool_size=(3,3)))\n\n# cnn.add(Convolution2D(filters=128, kernel_size=3, padding =\"same\",activation='relu'))\n# cnn.add(MaxPooling2D(pool_size=(3,3)))\n\n# cnn.add(Flatten())\n# cnn.add(Dense(100, activation='relu'))\n# cnn.add(Dropout(0.5))\n# cnn.add(Dense(3, activation='softmax'))\n# cnn.summary()\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers import Dropout\ndef make_model(metrics = None): \n \n base_model = keras.applications.InceptionResNetV2(input_shape=(*[320,320], 3),\n include_top=False,\n weights='imagenet')\n \n base_model.trainable = False\n \n model = tf.keras.Sequential([\n base_model,\n keras.layers.GlobalAveragePooling2D(),\n keras.layers.Dense(512),\n BatchNormalization(),\n keras.layers.Activation('relu'),\n Dropout(0.5),\n keras.layers.Dense(256),\n BatchNormalization(),\n keras.layers.Activation('relu'),\n Dropout(0.4),\n keras.layers.Dense(128),\n BatchNormalization(),\n keras.layers.Activation('relu'),\n Dropout(0.3),\n keras.layers.Dense(64),\n BatchNormalization(),\n keras.layers.Activation('relu'),\n keras.layers.Dense(3, activation='softmax')\n ])\n \n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),\n loss='sparse_categorical_crossentropy',\n metrics=metrics)\n \n return model",
"_____no_output_____"
],
[
"# def exponential_decay(lr0):\n# def exponential_decay_fn(epoch):\n# if epoch>5 and epoch%3==0:\n# return lr0 * tf.math.exp(-0.1)\n# else:\n# return lr0\n# return exponential_decay_fn\n\n# exponential_decay_fn = exponential_decay(0.01)\n# lr_scheduler = tf.keras.callbacks.LearningRateScheduler(exponential_decay_fn)\n\n# checkpoint_cb = tf.keras.callbacks.ModelCheckpoint(\"/content/drive/MyDrive/Broner/bone.h5\",\n# save_best_only=True)\ncheckpoint_path = \"/content/drive/MyDrive/Broner/best.hdf5\"\ncp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n monitor='val_sparse_categorical_accuracy',\n save_best_only=True, \n save_weights_only=True,\n mode='max', \n verbose=1)",
"_____no_output_____"
],
[
"model = make_model(metrics=['sparse_categorical_accuracy'])\nmodel.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninception_resnet_v2 (Functio (None, 8, 8, 1536) 54336736 \n_________________________________________________________________\nglobal_average_pooling2d_1 ( (None, 1536) 0 \n_________________________________________________________________\ndense_5 (Dense) (None, 512) 786944 \n_________________________________________________________________\nbatch_normalization_410 (Bat (None, 512) 2048 \n_________________________________________________________________\nactivation_410 (Activation) (None, 512) 0 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 512) 0 \n_________________________________________________________________\ndense_6 (Dense) (None, 256) 131328 \n_________________________________________________________________\nbatch_normalization_411 (Bat (None, 256) 1024 \n_________________________________________________________________\nactivation_411 (Activation) (None, 256) 0 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 256) 0 \n_________________________________________________________________\ndense_7 (Dense) (None, 128) 32896 \n_________________________________________________________________\nbatch_normalization_412 (Bat (None, 128) 512 \n_________________________________________________________________\nactivation_412 (Activation) (None, 128) 0 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_8 (Dense) (None, 64) 8256 \n_________________________________________________________________\nbatch_normalization_413 (Bat (None, 64) 256 \n_________________________________________________________________\nactivation_413 (Activation) (None, 64) 0 \n_________________________________________________________________\ndense_9 (Dense) (None, 3) 195 \n=================================================================\nTotal params: 55,300,195\nTrainable params: 961,539\nNon-trainable params: 54,338,656\n_________________________________________________________________\n"
],
[
"# cnn = model",
"_____no_output_____"
],
[
"LR = 0.0005\nEPOCHS=20\n\nSTEPS=train_generator.n//train_generator.batch_size\nVALID_STEPS=valid_generator.n//valid_generator.batch_size\n# cnn.compile(\n# optimizer=tf.keras.optimizers.Adam(learning_rate=LR),\n# loss='sparse_categorical_crossentropy',\n# metrics=['sparse_categorical_accuracy'])",
"_____no_output_____"
],
[
"# checkpoint_path = \"/content/drive/MyDrive/Broner/best.hdf5\"\n# cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n# monitor='val_sparse_categorical_accuracy',\n# save_best_only=True, \n# save_weights_only=True,\n# mode='max', \n# verbose=1)",
"_____no_output_____"
],
[
"history = model.fit_generator(\n train_generator,\n steps_per_epoch=STEPS,\n epochs=EPOCHS,\n validation_data=valid_generator,\n callbacks=[cp_callback],\n validation_steps=VALID_STEPS)",
"/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1844: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n warnings.warn('`Model.fit_generator` is deprecated and '\n"
],
[
"model.save('/content/drive/MyDrive/Broner/model.h5')",
"_____no_output_____"
],
[
"plt.plot(history.history['sparse_categorical_accuracy'])\nplt.plot(history.history['val_sparse_categorical_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()",
"_____no_output_____"
],
[
"from keras.models import load_model\nimport h5py\nfrom keras.preprocessing import image \nm = load_model('/content/drive/MyDrive/Broner/model.h5')",
"_____no_output_____"
],
[
"def new_answer(img):\n arr = np.empty(5, dtype=int)\n # img = image.load_img(path,target_size=(320,320))\n img_tensor = image.img_to_array(img)\n img_tensor = np.expand_dims(img_tensor,axis = 0)\n img_tensor /= 255\n img_tensor[:,:,0] = (img_tensor[:,:,0]-0.485)/0.229\n img_tensor[:,:,1] = (img_tensor[:,:,1]-0.456)/0.224\n img_tensor[:,:,2] = (img_tensor[:,:,2]-0.406)/0.225\n ans = m.predict(img_tensor)\n return np.argmax(ans),ans",
"_____no_output_____"
],
[
"img = cv2.imread('/content/drive/MyDrive/Broner/MURA-v1.1/valid/XR_SHOULDER/patient11187/study1_negative/image1.png')\nresized = cv2.resize(img, (320,320))\nnew_answer(resized)\n#Shoulder = '0' Humerus = '1' Forearm = '2'",
"_____no_output_____"
],
[
"import seaborn as sns\nsns.set_theme(style=\"darkgrid\")\nax = sns.countplot(x=\"label\", data=train_data)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba26869a632e3c31183fcf35cb754a00198867b
| 484,348 |
ipynb
|
Jupyter Notebook
|
Script/kaggle_home_price_prediction.ipynb
|
maviator/Kaggle_home_price_prediction
|
f1c69c12339a55537e0f8da5d6e8a00ff0ad8511
|
[
"MIT"
] | null | null | null |
Script/kaggle_home_price_prediction.ipynb
|
maviator/Kaggle_home_price_prediction
|
f1c69c12339a55537e0f8da5d6e8a00ff0ad8511
|
[
"MIT"
] | null | null | null |
Script/kaggle_home_price_prediction.ipynb
|
maviator/Kaggle_home_price_prediction
|
f1c69c12339a55537e0f8da5d6e8a00ff0ad8511
|
[
"MIT"
] | null | null | null | 145.493542 | 89,370 | 0.854522 |
[
[
[
"# Kaggle Home price prediction",
"_____no_output_____"
],
[
"### by Mohtadi Ben Fraj",
"_____no_output_____"
],
[
"#### In this version, we find the most correlated variables with 'SalePrice' and them in our Sklearn models",
"_____no_output_____"
]
],
[
[
"# Handle table-like data and matrices\nimport numpy as np\nimport pandas as pd\n\n# Modelling Algorithms\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n\n# Modelling Helpers\nfrom sklearn.preprocessing import Imputer , Normalizer , scale, StandardScaler\nfrom sklearn.cross_validation import train_test_split , StratifiedKFold\nfrom sklearn.feature_selection import RFECV\n\n# Stats helpers\nfrom scipy.stats import norm\nfrom scipy import stats\n\n# Visualisation\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pylab\nimport seaborn as sns\n\n# Configure visualisations\n%matplotlib inline\nmpl.style.use( 'ggplot' )\nsns.set_style( 'white' )\npylab.rcParams[ 'figure.figsize' ] = 8 , 6",
"/home/maviator/anaconda2/lib/python2.7/site-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n"
]
],
[
[
"## Load train and test data",
"_____no_output_____"
]
],
[
[
"# get home price train & test csv files as a DataFrame\ntrain = pd.read_csv(\"../Data/train.csv\")\ntest = pd.read_csv(\"../Data/test.csv\")\nfull = train.append(test, ignore_index=True)\nprint (train.shape, test.shape, full.shape)",
"((1460, 81), (1459, 80), (2919, 81))\n"
],
[
"train.head()",
"_____no_output_____"
],
[
"test.head()",
"_____no_output_____"
],
[
"train.columns",
"_____no_output_____"
]
],
[
[
"## Exploring 'SalePrice'",
"_____no_output_____"
]
],
[
[
"train.SalePrice.hist()",
"_____no_output_____"
]
],
[
[
"## 'SalePrice' correlation matrix",
"_____no_output_____"
]
],
[
[
"#correlation matrix\ncorrmat = train.corr()\n\n#saleprice correlation matrix\nk = 10 #number of variables for heatmap\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\ncm = np.corrcoef(train[cols].values.T)\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)\nplt.show()",
"_____no_output_____"
]
],
[
[
"From this correlation map we can make the following interpretations:\n- 'GarageCars' and 'GarageArea' are highly correlated which makes sense. Therefore choosing only one of them is sufficient. Since 'GarageCars' has higher correlation with 'SalePrice', we eliminate 'GarageArea'\n- '1stFlrSF' and 'TotalBsmtSF' are highly correlated. Therefore choosing only one of them is reasonable. We keep 'TotalBsmtSF' since it's more correlated with 'SalePrice'\n- 'TotRmsAbvGrd' and 'GrLivArea' are highly correlated and therefore we will keep only 'GrLivArea'.\nWe keep the following variables: 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt'",
"_____no_output_____"
]
],
[
[
"col = ['OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF',\n 'FullBath', 'YearBuilt'\n ]",
"_____no_output_____"
],
[
"train_selected = train[col]\ntest_selected = test[col]\nprint train_selected.shape, test_selected.shape",
"(1460, 6) (1459, 6)\n"
]
],
[
[
"## Missing Data",
"_____no_output_____"
]
],
[
[
"#missing data in train_selected data\ntotal = train_selected.isnull().sum().sort_values(ascending=False)\npercent = (train_selected.isnull().sum()/train_selected.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(6)",
"_____no_output_____"
],
[
"#missing data in test_selected data\ntotal = test_selected.isnull().sum().sort_values(ascending=False)\npercent = (test_selected.isnull().sum()/test_selected.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(6)",
"_____no_output_____"
]
],
[
[
"Only 1 entry has missing values for the 'TotalBsmtSF' and 'GarageCars'. We will fill them with -1",
"_____no_output_____"
]
],
[
[
"test_selected.TotalBsmtSF.fillna(0, inplace=True);\ntest_selected.GarageCars.fillna(0, inplace=True);",
"/home/maviator/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py:3295: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self._update_inplace(new_data)\n"
]
],
[
[
"Make sure Test data has no more missing data",
"_____no_output_____"
]
],
[
[
"#missing data in test data\ntotal = test_selected.isnull().sum().sort_values(ascending=False)\npercent = (test_selected.isnull().sum()/test_selected.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(6)",
"_____no_output_____"
]
],
[
[
"## Categorical Features",
"_____no_output_____"
],
[
"### In this section, we will explore the categorical features in our dataset and find out which ones can be relevant to improve the accuracy of our prediction",
"_____no_output_____"
],
[
"### 1. MSSubClass: Identifies the type of dwelling involved in the sale",
"_____no_output_____"
]
],
[
[
"train.MSSubClass.isnull().sum()",
"_____no_output_____"
],
[
"#box plot MSSubClass/saleprice\nvar = 'MSSubClass'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
]
],
[
[
"Some observations:\n- Newer built houses (1946 and newer) are more expensive\n- 2 story properties are more expensive than 1 or 1-1/2 story properties\n\nFirst option that we can do is to map each choice to a binary feature. This will result in 16 additional features\n\nSecond option is to replacce all 16 features with more higher level binary representation. For example: newer or older than 1946, 1 or 1-1/2 story property, 2 or 2-1/2 story property, PUD",
"_____no_output_____"
],
[
"### 1.a First option",
"_____no_output_____"
]
],
[
[
"ms_sub_class_train = pd.get_dummies(train.MSSubClass, prefix='MSSubClass')\nms_sub_class_train.shape",
"_____no_output_____"
]
],
[
[
"According to the features description, there is 16 possible values for 'MSSubClass', we only got 15 which means one value is never present in the train data. To solve this, we need to find that value and add a column with zeros to our features",
"_____no_output_____"
]
],
[
[
"ms_sub_class_train.head()",
"_____no_output_____"
]
],
[
[
"The missing value is 150. So we will add a column with label 'MSSubClass_150'",
"_____no_output_____"
]
],
[
[
"ms_sub_class_train['MSSubClass_150'] = 0\nms_sub_class_train.head()",
"_____no_output_____"
]
],
[
[
"Let's do the same thing for the test data",
"_____no_output_____"
]
],
[
[
"ms_sub_class_test = pd.get_dummies(test.MSSubClass, prefix='MSSubClass')\nms_sub_class_test.shape",
"_____no_output_____"
],
[
"ms_sub_class_test.head()",
"_____no_output_____"
]
],
[
[
"For the test data we have all 16 values so no columns need to be added",
"_____no_output_____"
],
[
"### 2. MSZoning: Identifies the general zoning classification of the sale",
"_____no_output_____"
]
],
[
[
"#box plot MSSubClass/saleprice\nvar = 'MSZoning'\ndata =pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"ms_zoning_train = pd.get_dummies(train.MSZoning, prefix='MSZoning')\nms_zoning_train.shape",
"_____no_output_____"
],
[
"ms_zoning_train.head()",
"_____no_output_____"
],
[
"ms_zoning_test = pd.get_dummies(test.MSZoning, prefix='MSZoning')\nms_zoning_test.shape",
"_____no_output_____"
]
],
[
[
"### 3. Street: Type of road access to property",
"_____no_output_____"
]
],
[
[
"var = 'Street'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"# Transform Street into binary values 0 and 1\nstreet_train = pd.Series(np.where(train.Street == 'Pave', 1, 0), name='Street')\nstreet_train.shape",
"_____no_output_____"
],
[
"street_train.head()",
"_____no_output_____"
],
[
"street_test = pd.Series(np.where(test.Street == 'Pave', 1, 0), name='Street')\nstreet_test.shape",
"_____no_output_____"
],
[
"street_test.head()",
"_____no_output_____"
]
],
[
[
"### 4. Alley: Type of alley access to property",
"_____no_output_____"
]
],
[
[
"var = 'Alley'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"alley_train = pd.get_dummies(train.Alley, prefix='Alley')\nalley_train.shape",
"_____no_output_____"
],
[
"alley_train.head()",
"_____no_output_____"
],
[
"alley_test = pd.get_dummies(test.Alley, prefix='Alley')\nalley_test.shape",
"_____no_output_____"
]
],
[
[
"### 5. LotShape: General shape of property",
"_____no_output_____"
]
],
[
[
"train.LotShape.isnull().sum()",
"_____no_output_____"
],
[
"var = 'LotShape'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"lot_shape_train = pd.get_dummies(train.LotShape, prefix='LotShape')\nlot_shape_train.shape",
"_____no_output_____"
],
[
"lot_shape_test = pd.get_dummies(test.LotShape, prefix='LotShape')\nlot_shape_test.shape",
"_____no_output_____"
],
[
"lot_shape_test.head()",
"_____no_output_____"
]
],
[
[
"### 6. LandContour: Flatness of the property",
"_____no_output_____"
]
],
[
[
"train.LandContour.isnull().sum()",
"_____no_output_____"
],
[
"var = 'LandContour'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"land_contour_train = pd.get_dummies(train.LandContour, prefix='LandContour')\nland_contour_train.shape",
"_____no_output_____"
],
[
"land_contour_test = pd.get_dummies(test.LandContour, prefix='LandContour')\nland_contour_test.shape",
"_____no_output_____"
]
],
[
[
"### 7. Utilities: Type of utilities available",
"_____no_output_____"
]
],
[
[
"train.Utilities.isnull().sum()",
"_____no_output_____"
],
[
"var = 'Utilities'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
]
],
[
[
"### 8. LotConfig: Lot configuration",
"_____no_output_____"
]
],
[
[
"train.LotConfig.isnull().sum()",
"_____no_output_____"
],
[
"var = 'LotConfig'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
]
],
[
[
"### 9. LandSlope: Slope of property",
"_____no_output_____"
]
],
[
[
"train.LandSlope.isnull().sum()",
"_____no_output_____"
],
[
"var = 'LandSlope'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(8, 6))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
]
],
[
[
"### 10. Neighborhood: Physical locations within Ames city limits",
"_____no_output_____"
]
],
[
[
"train.Neighborhood.isnull().sum()",
"_____no_output_____"
],
[
"var = 'Neighborhood'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(20, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"neighborhood_train = pd.get_dummies(train.Neighborhood, prefix='N')\nneighborhood_train.shape",
"_____no_output_____"
],
[
"neighborhood_test = pd.get_dummies(test.Neighborhood, prefix='N')\nneighborhood_test.shape",
"_____no_output_____"
]
],
[
[
"### 11. Condition1: Proximity to various conditions",
"_____no_output_____"
]
],
[
[
"train.Condition1.isnull().sum()",
"_____no_output_____"
],
[
"var = 'Condition1'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(20, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
]
],
[
[
"### 12. BldgType: Type of dwelling",
"_____no_output_____"
]
],
[
[
"train.BldgType.isnull().sum()",
"_____no_output_____"
],
[
"var = 'BldgType'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(20, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"bldgtype_train = pd.get_dummies(train.BldgType, prefix='Bldg')\nbldgtype_train.shape",
"_____no_output_____"
],
[
"bldgtype_test = pd.get_dummies(test.BldgType, prefix='Bldg')\nbldgtype_test.shape",
"_____no_output_____"
]
],
[
[
"### 13. BsmtCond: Evaluates the general condition of the basement",
"_____no_output_____"
]
],
[
[
"train.BsmtCond.isnull().sum()",
"_____no_output_____"
],
[
"var = 'BsmtCond'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(20, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"bsmtCond_train = pd.get_dummies(train.BsmtCond, prefix='Bldg')\nbsmtCond_train.shape",
"_____no_output_____"
],
[
"bsmtCond_test = pd.get_dummies(test.BsmtCond, prefix='Bldg')\nbsmtCond_test.shape",
"_____no_output_____"
]
],
[
[
"### 14. SaleCondition: Condition of sale",
"_____no_output_____"
]
],
[
[
"train.SaleCondition.isnull().sum()",
"_____no_output_____"
],
[
"var = 'SaleCondition'\ndata = pd.concat([train['SalePrice'], train[var]], axis=1)\nf, ax = plt.subplots(figsize=(20, 10))\nfig = sns.boxplot(x=var, y=\"SalePrice\", data=data)\nfig.axis(ymin=0, ymax=800000);",
"_____no_output_____"
],
[
"saleCond_train = pd.get_dummies(train.SaleCondition, prefix='saleCond')\nsaleCond_train.shape",
"_____no_output_____"
],
[
"saleCond_test = pd.get_dummies(test.SaleCondition, prefix='saleCond')\nsaleCond_test.shape",
"_____no_output_____"
]
],
[
[
"## Concatenate features",
"_____no_output_____"
],
[
"Let's concatenate the additional features for the train and test data",
"_____no_output_____"
],
[
"Features to choose from:\n- ms_sub_class\n- ms_zoning\n- street\n- ms_alley\n- lot_shape\n- land_contour\n- neighborhood\n- bldgtype\n- bsmtCond\n- saleCond",
"_____no_output_____"
]
],
[
[
"train_selected = pd.concat([train_selected,\n ms_zoning_train,\n alley_train,\n land_contour_train], axis=1)\ntrain_selected.shape",
"_____no_output_____"
],
[
"test_selected = pd.concat([test_selected,\n ms_zoning_test,\n alley_test,\n land_contour_test], axis=1)\ntest_selected.shape",
"_____no_output_____"
]
],
[
[
"## Train, validation split",
"_____no_output_____"
]
],
[
[
"#train_selected_y = train.SalePrice\ntrain_selected_y = np.log1p(train[\"SalePrice\"])\ntrain_selected_y.head()",
"_____no_output_____"
],
[
"train_x, valid_x, train_y, valid_y = train_test_split(train_selected, \n train_selected_y,\n train_size=0.7)\ntrain_x.shape, valid_x.shape, train_y.shape, valid_y.shape, test_selected.shape",
"_____no_output_____"
]
],
[
[
"## Modelling",
"_____no_output_____"
]
],
[
[
"model = RandomForestRegressor(n_estimators=100)\n#model = SVC()\n#model = GradientBoostingRegressor()\n#model = KNeighborsClassifier(n_neighbors = 3)\n#model = GaussianNB()\n#model = LogisticRegression()",
"_____no_output_____"
],
[
"model.fit(train_x, train_y)",
"_____no_output_____"
],
[
"# Score the model\nprint (model.score(train_x, train_y), model.score(valid_x, valid_y))",
"(0.92115737905682393, 0.84029051291273027)\n"
],
[
"model.fit(train_selected, train_selected_y)",
"_____no_output_____"
]
],
[
[
"## Submission",
"_____no_output_____"
]
],
[
[
"test_y = model.predict(test_selected)\ntest_y = np.expm1(test_y)\ntest_id = test.Id\ntest_submit = pd.DataFrame({'Id': test_id, 'SalePrice': test_y})\ntest_submit.shape\ntest_submit.head()\ntest_submit.to_csv('house_price_pred_log.csv', index=False)",
"_____no_output_____"
]
],
[
[
"## Remarks",
"_____no_output_____"
],
[
"- Using the correlation method, we were able to go from 36 variables to only 6. Performance wise the score dropped from 0.22628 to 0.22856 using a Random Forest model. I believe we can further improve it by analysing the categorical variables.\n\n- Using binary variables for the categorical feature 'MSSubClass' seemed to decrease the performance of the prediction\n\n- Using binary variable for the categorical feature 'MSZoning' improved the error of the model from 0.22628 to 0.21959.\n\n- Using binary variable for the categorical feature 'Street' decreased the perdormance of the model\n\n- Using binary variable for the categorical feature 'Alley' improved the error of the model from 0.21959 to 0.21904.\n\n- Using binary variable for the categorical feature 'LotShape' decreased the performance of the model.\n\n- Using binary variable for the categorical feature 'LandContour' improved the error from 0.21904 to 0.21623.\n\n- Using binary variable for the categorical feature 'Neighborhood' decreased the performance of the model.\n\n- Using binary variable for the categorical feature 'Building type' decreased the performance of the model.\n\n- Using the binary variable of the categorical feature 'BsmntCond' decreased the performance of the model.\n\n- Using the binary variable fot the categorical feature 'SaleCondition' decreased the performance of the model.\n\n- Never, EVER, use a classification model for regression!!! Changed RandomForestClassifier to RandomForestRegressor and improved error from 0.21623 to 0.16517\n\n- Applied log+1 to 'SalePrice' to remove skewness. Error improved from 0.16517 to 0.16083",
"_____no_output_____"
],
[
"## Credits",
"_____no_output_____"
],
[
"Many of the analysis and core snippets are from this very detailed post: https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python",
"_____no_output_____"
],
[
"## Links",
"_____no_output_____"
],
[
"- Are categorical variables getting lost in your random forests? (https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cba26aa2e764846bf31cdf33f6d8fc0ff3ac2148
| 19,736 |
ipynb
|
Jupyter Notebook
|
docs/examples/general/reinterpret.ipynb
|
szkarpinski/DALI
|
999379b7ed2145f5da2de9f2dca566b3912fb366
|
[
"ECL-2.0",
"Apache-2.0"
] | 2 |
2022-02-17T19:54:05.000Z
|
2022-02-17T19:54:08.000Z
|
docs/examples/general/reinterpret.ipynb
|
hugo213/DALI
|
999379b7ed2145f5da2de9f2dca566b3912fb366
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
docs/examples/general/reinterpret.ipynb
|
hugo213/DALI
|
999379b7ed2145f5da2de9f2dca566b3912fb366
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 30.885759 | 382 | 0.460681 |
[
[
[
"# Reinterpreting Tensors\n\nSometimes the data in tensors needs to be interpreted as if it had different type or shape. For example, reading a binary file into memory produces a flat tensor of byte-valued data, which the application code may want to interpret as an array of data of specific shape and possibly different type.\n\nDALI provides the following operations which affect tensor metadata (shape, type, layout):\n* reshape\n* reinterpret\n* squeeze\n* expand_dims\n\nThsese operations neither modify nor copy the data - the output tensor is just another view of the same region of memory, making these operations very cheap.\n\n## Fixed Output Shape\n\nThis example demonstrates the simplest use of the `reshape` operation, assigning a new fixed shape to an existing tensor.\n\nFirst, we'll import DALI and other necessary modules, and define a utility for displaying the data, which will be used throughout this tutorial.",
"_____no_output_____"
]
],
[
[
"import nvidia.dali as dali\nimport nvidia.dali.fn as fn\nfrom nvidia.dali import pipeline_def\nimport nvidia.dali.types as types\nimport numpy as np\n\ndef show_result(outputs, names=[\"Input\", \"Output\"], formatter=None):\n if not isinstance(outputs, tuple):\n return show_result((outputs,))\n \n outputs = [out.as_cpu() if hasattr(out, \"as_cpu\") else out for out in outputs]\n\n for i in range(len(outputs[0])):\n print(f\"---------------- Sample #{i} ----------------\")\n for o, out in enumerate(outputs):\n a = np.array(out[i])\n s = \"x\".join(str(x) for x in a.shape)\n title = names[o] if names is not None and o < len(names) else f\"Output #{o}\"\n l = out.layout()\n if l: l += ' '\n print(f\"{title} ({l}{s})\")\n np.set_printoptions(formatter=formatter)\n print(a)\n \ndef rand_shape(dims, lo, hi):\n return list(np.random.randint(lo, hi, [dims]))",
"_____no_output_____"
]
],
[
[
"Now let's define out pipeline - it takes data from an external source and returns it both in original form and reshaped to a fixed square shape `[5, 5]`. Additionally, output tensors' layout is set to HW",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example1(input_data):\n np.random.seed(1234)\n inp = fn.external_source(input_data, batch=False, dtype=types.INT32)\n return inp, fn.reshape(inp, shape=[5, 5], layout=\"HW\")\n\npipe1 = example1(lambda: np.random.randint(0, 10, size=[25], dtype=np.int32))\npipe1.build()\nshow_result(pipe1.run())",
"---------------- Sample #0 ----------------\nInput (25)\n[3 6 5 4 8 9 1 7 9 6 8 0 5 0 9 6 2 0 5 2 6 3 7 0 9]\nOutput (HW 5x5)\n[[3 6 5 4 8]\n [9 1 7 9 6]\n [8 0 5 0 9]\n [6 2 0 5 2]\n [6 3 7 0 9]]\n---------------- Sample #1 ----------------\nInput (25)\n[0 3 2 3 1 3 1 3 7 1 7 4 0 5 1 5 9 9 4 0 9 8 8 6 8]\nOutput (HW 5x5)\n[[0 3 2 3 1]\n [3 1 3 7 1]\n [7 4 0 5 1]\n [5 9 9 4 0]\n [9 8 8 6 8]]\n---------------- Sample #2 ----------------\nInput (25)\n[6 3 1 2 5 2 5 6 7 4 3 5 6 4 6 2 4 2 7 9 7 7 2 9 7]\nOutput (HW 5x5)\n[[6 3 1 2 5]\n [2 5 6 7 4]\n [3 5 6 4 6]\n [2 4 2 7 9]\n [7 7 2 9 7]]\n"
]
],
[
[
"As we can see, the numbers from flat input tensors have been rearranged into 5x5 matrices.\n\n## Reshape with Wildcards\n\nLet's now consider a more advanced use case. Imagine you have some flattened array that represents a fixed number of columns, but the number of rows is free to vary from sample to sample. In that case, you can put a wildcard dimension by specifying its shape as `-1`. Whe using wildcards, the output is resized so that the total number of elements is the same as in the input.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example2(input_data):\n np.random.seed(12345)\n inp = fn.external_source(input_data, batch=False, dtype=types.INT32)\n return inp, fn.reshape(inp, shape=[-1, 5])\n\npipe2 = example2(lambda: np.random.randint(0, 10, size=[5*np.random.randint(3, 10)], dtype=np.int32))\npipe2.build()\nshow_result(pipe2.run())",
"---------------- Sample #0 ----------------\nInput (25)\n[5 1 4 9 5 2 1 6 1 9 7 6 0 2 9 1 2 6 7 7 7 8 7 1 7]\nOutput (5x5)\n[[5 1 4 9 5]\n [2 1 6 1 9]\n [7 6 0 2 9]\n [1 2 6 7 7]\n [7 8 7 1 7]]\n---------------- Sample #1 ----------------\nInput (35)\n[0 3 5 7 3 1 5 2 5 3 8 5 2 5 3 0 6 8 0 5 6 8 9 2 2 2 9 7 5 7 1 0 9 3 0]\nOutput (7x5)\n[[0 3 5 7 3]\n [1 5 2 5 3]\n [8 5 2 5 3]\n [0 6 8 0 5]\n [6 8 9 2 2]\n [2 9 7 5 7]\n [1 0 9 3 0]]\n---------------- Sample #2 ----------------\nInput (30)\n[0 6 2 1 5 8 6 5 1 0 5 8 2 9 4 7 9 5 2 4 8 2 5 6 5 9 6 1 9 5]\nOutput (6x5)\n[[0 6 2 1 5]\n [8 6 5 1 0]\n [5 8 2 9 4]\n [7 9 5 2 4]\n [8 2 5 6 5]\n [9 6 1 9 5]]\n"
]
],
[
[
"## Removing and Adding Unit Dimensions\n\nThere are two dedicated operators `squeeze` and `expand_dims` which can be used for removing and adding dimensions with unit extent. The following example demonstrates the removal of a redundant dimension as well as adding two new dimensions.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example_squeeze_expand(input_data):\n np.random.seed(4321)\n inp = fn.external_source(input_data, batch=False, layout=\"CHW\", dtype=types.INT32)\n squeezed = fn.squeeze(inp, axes=[0])\n expanded = fn.expand_dims(squeezed, axes=[0, 3], new_axis_names=\"FC\")\n return inp, fn.squeeze(inp, axes=[0]), expanded\n\ndef single_channel_generator():\n return np.random.randint(0, 10,\n size=[1]+rand_shape(2, 1, 7),\n dtype=np.int32)\n\npipe_squeeze_expand = example_squeeze_expand(single_channel_generator)\npipe_squeeze_expand.build()\nshow_result(pipe_squeeze_expand.run())",
"---------------- Sample #0 ----------------\nInput (CHW 1x6x3)\n[[[8 2 1]\n [7 5 9]\n [2 4 6]\n [0 8 6]\n [5 3 1]\n [1 6 1]]]\nOutput (HW 6x3)\n[[8 2 1]\n [7 5 9]\n [2 4 6]\n [0 8 6]\n [5 3 1]\n [1 6 1]]\nOutput #2 (FHWC 1x6x3x1)\n[[[[8]\n [2]\n [1]]\n\n [[7]\n [5]\n [9]]\n\n [[2]\n [4]\n [6]]\n\n [[0]\n [8]\n [6]]\n\n [[5]\n [3]\n [1]]\n\n [[1]\n [6]\n [1]]]]\n---------------- Sample #1 ----------------\nInput (CHW 1x2x2)\n[[[6 9]\n [0 9]]]\nOutput (HW 2x2)\n[[6 9]\n [0 9]]\nOutput #2 (FHWC 1x2x2x1)\n[[[[6]\n [9]]\n\n [[0]\n [9]]]]\n---------------- Sample #2 ----------------\nInput (CHW 1x2x6)\n[[[4 4 6 6 6 3]\n [8 2 1 7 9 7]]]\nOutput (HW 2x6)\n[[4 4 6 6 6 3]\n [8 2 1 7 9 7]]\nOutput #2 (FHWC 1x2x6x1)\n[[[[4]\n [4]\n [6]\n [6]\n [6]\n [3]]\n\n [[8]\n [2]\n [1]\n [7]\n [9]\n [7]]]]\n"
]
],
[
[
"## Rearranging Dimensions\n\nReshape allows you to swap, insert or remove dimenions. The argument `src_dims` allows you to specify which source dimension is used for a given output dimension. You can also insert a new dimension by specifying -1 as a source dimension index.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example_reorder(input_data):\n np.random.seed(4321)\n inp = fn.external_source(input_data, batch=False, dtype=types.INT32)\n return inp, fn.reshape(inp, src_dims=[1,0])\n\npipe_reorder = example_reorder(lambda: np.random.randint(0, 10,\n size=rand_shape(2, 1, 7),\n dtype=np.int32))\npipe_reorder.build()\nshow_result(pipe_reorder.run())",
"---------------- Sample #0 ----------------\nInput (6x3)\n[[8 2 1]\n [7 5 9]\n [2 4 6]\n [0 8 6]\n [5 3 1]\n [1 6 1]]\nOutput (3x6)\n[[8 2 1 7 5 9]\n [2 4 6 0 8 6]\n [5 3 1 1 6 1]]\n---------------- Sample #1 ----------------\nInput (2x2)\n[[6 9]\n [0 9]]\nOutput (2x2)\n[[6 9]\n [0 9]]\n---------------- Sample #2 ----------------\nInput (2x6)\n[[4 4 6 6 6 3]\n [8 2 1 7 9 7]]\nOutput (6x2)\n[[4 4]\n [6 6]\n [6 3]\n [8 2]\n [1 7]\n [9 7]]\n"
]
],
[
[
"## Adding and Removing Dimensions\n\nDimensions can be added or removed by specifying `src_dims` argument or by using dedicated `squeeze` and `expand_dims` operators.\n\nThe following example reinterprets single-channel data from CHW to HWC layout by discarding the leading dimension and adding a new trailing dimension. It also specifies the output layout.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example_remove_add(input_data):\n np.random.seed(4321)\n inp = fn.external_source(input_data, batch=False, layout=\"CHW\", dtype=types.INT32)\n return inp, fn.reshape(inp,\n src_dims=[1,2,-1], # select HW and add a new one at the end\n layout=\"HWC\") # specify the layout string\n\npipe_remove_add = example_remove_add(lambda: np.random.randint(0, 10, [1,4,3], dtype=np.int32))\npipe_remove_add.build()\nshow_result(pipe_remove_add.run())",
"---------------- Sample #0 ----------------\nInput (CHW 1x4x3)\n[[[2 8 2]\n [1 7 5]\n [9 2 4]\n [6 0 8]]]\nOutput (HWC 4x3x1)\n[[[2]\n [8]\n [2]]\n\n [[1]\n [7]\n [5]]\n\n [[9]\n [2]\n [4]]\n\n [[6]\n [0]\n [8]]]\n---------------- Sample #1 ----------------\nInput (CHW 1x4x3)\n[[[6 5 3]\n [1 1 6]\n [1 1 9]\n [6 9 0]]]\nOutput (HWC 4x3x1)\n[[[6]\n [5]\n [3]]\n\n [[1]\n [1]\n [6]]\n\n [[1]\n [1]\n [9]]\n\n [[6]\n [9]\n [0]]]\n---------------- Sample #2 ----------------\nInput (CHW 1x4x3)\n[[[9 9 5]\n [4 4 6]\n [6 6 3]\n [8 2 1]]]\nOutput (HWC 4x3x1)\n[[[9]\n [9]\n [5]]\n\n [[4]\n [4]\n [6]]\n\n [[6]\n [6]\n [3]]\n\n [[8]\n [2]\n [1]]]\n"
]
],
[
[
"## Relative Shape\n\nThe output shape may be calculated in relative terms, with a new extent being a multiple of a source extent.\nFor example, you may want to combine two subsequent rows into one - doubling the number of columns and halving the number of rows. The use of relative shape can be combined with dimension rearranging, in which case the new output extent is a multiple of a _different_ source extent.\n\nThe example below reinterprets the input as having twice as many _columns_ as the input had _rows_.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example_rel_shape(input_data):\n np.random.seed(1234)\n inp = fn.external_source(input_data, batch=False, dtype=types.INT32)\n return inp, fn.reshape(inp,\n rel_shape=[0.5, 2],\n src_dims=[1,0])\n\npipe_rel_shape = example_rel_shape(\n lambda: np.random.randint(0, 10,\n [np.random.randint(1,7), 2*np.random.randint(1,5)],\n dtype=np.int32))\n\npipe_rel_shape.build()\nshow_result(pipe_rel_shape.run())",
"---------------- Sample #0 ----------------\nInput (4x6)\n[[5 4 8 9 1 7]\n [9 6 8 0 5 0]\n [9 6 2 0 5 2]\n [6 3 7 0 9 0]]\nOutput (3x8)\n[[5 4 8 9 1 7 9 6]\n [8 0 5 0 9 6 2 0]\n [5 2 6 3 7 0 9 0]]\n---------------- Sample #1 ----------------\nInput (4x6)\n[[3 1 3 1 3 7]\n [1 7 4 0 5 1]\n [5 9 9 4 0 9]\n [8 8 6 8 6 3]]\nOutput (3x8)\n[[3 1 3 1 3 7 1 7]\n [4 0 5 1 5 9 9 4]\n [0 9 8 8 6 8 6 3]]\n---------------- Sample #2 ----------------\nInput (2x6)\n[[5 2 5 6 7 4]\n [3 5 6 4 6 2]]\nOutput (3x4)\n[[5 2 5 6]\n [7 4 3 5]\n [6 4 6 2]]\n"
]
],
[
[
"## Reinterpreting Data Type\n\nThe `reinterpret` operation can view the data as if it was of different type. When a new shape is not specified, the innermost dimension is resized accordingly.",
"_____no_output_____"
]
],
[
[
"@pipeline_def(device_id=0, num_threads=4, batch_size=3)\ndef example_reinterpret(input_data):\n np.random.seed(1234)\n inp = fn.external_source(input_data, batch=False, dtype=types.UINT8)\n return inp, fn.reinterpret(inp, dtype=dali.types.UINT32)\n\npipe_reinterpret = example_reinterpret(\n lambda:\n np.random.randint(0, 255,\n [np.random.randint(1,7), 4*np.random.randint(1,5)],\n dtype=np.uint8))\n\npipe_reinterpret.build()\n\ndef hex_bytes(x):\n f = f\"0x{{:0{2*x.nbytes}x}}\"\n return f.format(x)\n\nshow_result(pipe_reinterpret.run(), formatter={'int':hex_bytes})",
"---------------- Sample #0 ----------------\nInput (4x12)\n[[0x35 0xdc 0x5d 0xd1 0xcc 0xec 0x0e 0x70 0x74 0x5d 0xb3 0x9c]\n [0x98 0x42 0x0d 0xc9 0xf9 0xd7 0x77 0xc5 0x8f 0x7e 0xac 0xc7]\n [0xb1 0xda 0x54 0xdc 0x17 0xa1 0xc8 0x45 0xe9 0x24 0x90 0x26]\n [0x9a 0x5c 0xc6 0x46 0x1e 0x20 0xd2 0x32 0xab 0x7e 0x47 0xcd]]\nOutput (4x3)\n[[0xd15ddc35 0x700eeccc 0x9cb35d74]\n [0xc90d4298 0xc577d7f9 0xc7ac7e8f]\n [0xdc54dab1 0x45c8a117 0x269024e9]\n [0x46c65c9a 0x32d2201e 0xcd477eab]]\n---------------- Sample #1 ----------------\nInput (5x4)\n[[0x1a 0x1f 0x3d 0xe0]\n [0x76 0x35 0xbb 0x1d]\n [0xba 0xe9 0x99 0x5b]\n [0x78 0xe8 0x4d 0x03]\n [0x70 0x37 0x41 0x80]]\nOutput (5x1)\n[[0xe03d1f1a]\n [0x1dbb3576]\n [0x5b99e9ba]\n [0x034de878]\n [0x80413770]]\n---------------- Sample #2 ----------------\nInput (5x8)\n[[0x50 0x6d 0xbd 0x54 0xc9 0xa3 0x73 0xb6]\n [0x7f 0xc9 0x79 0xcd 0xf6 0xc0 0xc8 0x5e]\n [0xfe 0x09 0x27 0x19 0xaf 0x8d 0xaa 0x8f]\n [0x32 0x96 0x55 0x0e 0xf0 0x0e 0xca 0x80]\n [0xfb 0x56 0x52 0x71 0x4c 0x54 0x86 0x03]]\nOutput (5x2)\n[[0x54bd6d50 0xb673a3c9]\n [0xcd79c97f 0x5ec8c0f6]\n [0x192709fe 0x8faa8daf]\n [0x0e559632 0x80ca0ef0]\n [0x715256fb 0x0386544c]]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba26d2470504e12f3624705d87d0bc3a4689247
| 538,271 |
ipynb
|
Jupyter Notebook
|
birth-death moves for RJMC of GMMs.ipynb
|
jchodera/maxentile-notebooks
|
6e8ca4e3d9dbd1623ea926395d06740a30d9111d
|
[
"MIT"
] | null | null | null |
birth-death moves for RJMC of GMMs.ipynb
|
jchodera/maxentile-notebooks
|
6e8ca4e3d9dbd1623ea926395d06740a30d9111d
|
[
"MIT"
] | null | null | null |
birth-death moves for RJMC of GMMs.ipynb
|
jchodera/maxentile-notebooks
|
6e8ca4e3d9dbd1623ea926395d06740a30d9111d
|
[
"MIT"
] | null | null | null | 129.143714 | 42,948 | 0.85514 |
[
[
[
"# RJMC for GMMs:\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom autograd import numpy as np\nnp.random.seed(0)\nfrom scipy.stats import norm\nfrom scipy.stats import dirichlet\nfrom scipy.special import logsumexp\n\ndef gaussian_mixture_log_likelihood(X, means, stdevs, weights):\n component_log_pdfs = np.array([norm.logpdf(X, loc=mean, scale=stdev) + np.log(weight) for ((mean, stdev), weight) in zip(zip(means, stdevs), weights)])\n return np.sum(logsumexp(component_log_pdfs, 0))\n\nfrom scipy.stats import norm, invgamma\nfrom scipy.special import logsumexp\n\ndef unpack(theta):\n assert(len(theta) % 3 == 0)\n n = int(len(theta) / 3)\n means, stdevs, weights = np.array(theta[:n]), np.array(theta[n:2*n]), np.array(theta[2*n:])\n return means, stdevs, weights\n\ndef log_prior(theta):\n means, stdevs, weights = unpack(theta)\n log_prior_on_means = np.sum(norm.logpdf(means, scale=20))\n log_prior_on_variances = np.sum(invgamma.logpdf((stdevs**2), 1.0))\n #log_prior_on_weights = dirichlet.logpdf(weights, np.ones(len(weights)))\n #log_prior_on_weights = np.sum(np.log(weights))\n log_prior_on_weights = 0 # removing the prior on weights to see if this is the culprit...\n return log_prior_on_means + log_prior_on_variances + log_prior_on_weights\n\ndef flat_log_p(theta):\n means, stdevs, weights = unpack(theta)\n if np.min(stdevs) <= 0.001: return - np.inf\n log_likelihood = gaussian_mixture_log_likelihood(X=data, means=means,\n stdevs=stdevs,\n weights=weights)\n \n return log_likelihood + log_prior(theta)\n\n#n_components = 10\n#true_means = np.random.rand(n_components) * 10 - 5\n#true_stdevs = np.random.rand(n_components) * 0.2\n#true_weights = np.random.rand(n_components)**2\n#true_weights /= np.sum(true_weights)\n\nn_data = 300\ndata = np.zeros(n_data)\n#for i in range(n_data):\n# component = np.random.choice(np.arange(n_components), p=true_weights)\n# #component = np.random.randint(n_components)\n# data[i] = norm.rvs(loc=true_means[component], scale=true_stdevs[component])\n\n#n_components = 10\n#true_means = np.linspace(-5,5,n_components)\n#true_stdevs = np.random.rand(n_components)*0.5\n#true_weights = np.random.rand(n_components)\n#true_weights /= np.sum(true_weights)\n#n_data = 300\n#data = np.zeros(n_data)\n#for i in range(n_data):\n# component = np.random.randint(n_components)\n# data[i] = norm.rvs(loc=true_means[component], scale=true_stdevs[component])\n \n \n \nn_components = 3\ntrue_means = [-5.0,0.0,5.0]\ntrue_stdevs = np.ones(n_components)\ntrue_weights = np.ones(n_components) / 3\nn_data = 300\ndata = np.zeros(n_data)\nfor i in range(n_data):\n component = np.random.randint(n_components)\n data[i] = norm.rvs(loc=true_means[component], scale=true_stdevs[component])\n\n\nplt.figure(figsize=(6,6))\n\nax = plt.subplot(111)\n \nplt.hist(data, bins=50, normed=True, alpha=0.5);\nx = np.linspace(-8,8, 1000)\ny_tot = np.zeros(x.shape)\nfor i in range(n_components):\n \n y = norm.pdf(x, loc=true_means[i], scale=true_stdevs[i]) * true_weights[i]\n plt.plot(x, y, '--', color='grey',)\n plt.fill_between(x, y, color='grey' ,alpha=0.2)\n y_tot += y\nplt.plot(x,y_tot, color='blue',)\nplt.yticks([])\n\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\nplt.title(\"data: {} points sampled from {} mixture components\".format(n_data, n_components))\nplt.ylabel('probability density')\nplt.xlabel('x')\nplt.xticks([-8,0,8])",
"_____no_output_____"
],
[
"np.mean(data), np.std(data)",
"_____no_output_____"
],
[
"max_components = 50\nmean_perturbation_scale = 5.0\nstdev_perturbation_scale = 2.0\n\ndef reversible_birth_death_move(theta, parents):\n \n means, stdevs, weights = unpack(theta)\n means, stdevs, weights = map(np.array, (means, stdevs, weights))\n \n sum_weights_before = np.sum(weights)\n n_components = len(means)\n \n # decide whether to create a new component\n if n_components == 1:\n birth_probability = 1.0\n log_prob_forward_over_reverse = np.log(1.0 / 0.5) # F: 100% chance of \"birth\" move, R: 50% chance\n elif n_components == max_components:\n birth_probability = 0.0\n log_prob_forward_over_reverse = np.log(1.0 / 0.5) # F: 100% chance of \"death\" move, R: 50% chance\n else:\n birth_probability = 0.5\n log_prob_forward_over_reverse = np.log(1.0 / 1.0) # 0\n death_probability = 1.0 - birth_probability\n \n if np.random.rand() < birth_probability:\n (means, stdevs, weights, parents_prime), log_jac_u_term = reversible_birth_move(means, stdevs, weights, parents)\n else:\n (means, stdevs, weights, parents_prime), log_jac_u_term = reversible_death_move(means, stdevs, weights, parents)\n assert(len(means) == len(stdevs))\n theta_prime = np.array(means + stdevs + weights)\n \n sum_weights_after = np.sum(weights)\n assert(np.isclose(sum_weights_before, sum_weights_after))\n return theta_prime, parents_prime, log_jac_u_term - log_prob_forward_over_reverse\n \nfrom scipy.stats import uniform, norm\nu_1_distribution = uniform(0, 1)\nu_2_distribution = norm(0, 1)\nu_3_distribution = norm(0, 1)\n\n\ndef reversible_birth_move(means, stdevs, weights, parents):\n # make local copies to be extra sure we're not accidentally overwriting...\n means, stdevs, weights, parents = map(list, (means, stdevs, weights, parents))\n \n # draw all the random numbers we're going to use\n i = np.random.randint(len(means)) # choose a parent component at random\n u_1 = u_1_distribution.rvs()\n u_2 = u_2_distribution.rvs()\n u_3 = u_3_distribution.rvs()\n \n # compute the log probability density of all the random numbers we drew\n log_prob_u = np.log(1.0 / len(means)) + u_1_distribution.logpdf(u_1) + u_2_distribution.logpdf(u_2) + u_3_distribution.logpdf(u_3)\n \n # compute the parameters of the new mixture component\n weight_new = weights[i] * u_1\n mean_new = (u_2 * mean_perturbation_scale) + means[i]\n stdev_new = (u_3 * stdev_perturbation_scale) + stdevs[i]\n \n # compute log determinant of the jacobian\n log_jacobian_determinant = np.log(weights[i]) + np.log(mean_perturbation_scale) + np.log(stdev_perturbation_scale)\n \n # subtract the new mixture component's weight from its parent\n weights[i] -= weight_new\n \n # update means, stdevs, weights, parents\n means.append(mean_new)\n stdevs.append(stdev_new)\n weights.append(weight_new)\n parents.append(i)\n \n return (means, stdevs, weights, parents), (log_jacobian_determinant - log_prob_u)\n\ndef mmc_move(theta, parents):\n \"\"\"Standard Metropolis Monte Carlo move.\n \n (Contributed by JDC)\n \"\"\" \n theta_prime = np.array(theta)\n parents_prime = list(parents)\n \n n = int(len(theta) / 3)\n \n SIGMA_MEAN = 0.05\n SIGMA_STDDEV = 0.05\n SIGMA_WEIGHT = 0.05\n \n # different proposal sizes for mean, stdev, weight\n i = np.random.randint(n)\n j = np.random.randint(n)\n delta_mean = SIGMA_MEAN * np.random.randn()\n delta_stddev = SIGMA_STDDEV * np.random.randn()\n delta_weight = SIGMA_WEIGHT * np.random.randn()\n \n theta_prime[i] += delta_mean\n theta_prime[n+i] += delta_stddev\n theta_prime[2*n+i] += delta_weight\n theta_prime[2*n+j] -= delta_weight\n \n log_jac_u_term = 0.0\n if np.any(theta_prime[n:2*n] <= 0.0) or np.any(theta_prime[2*n:] <= 0.0) or not np.isclose(np.sum(theta_prime[2*n:]), 1.0):\n # Force reject\n #print(theta_prime)\n log_jac_u_term = - np.inf\n \n return theta_prime, parents_prime, log_jac_u_term\n \ndef reversible_death_move(means, stdevs, weights, parents):\n # make local copies to be extra sure we're not accidentally overwriting...\n means, stdevs, weights, parents = map(list, (means, stdevs, weights, parents))\n \n # draw all the random numbers we're going to use\n i = np.random.randint(1, len(means)) # choose a component at random to remove, except component 0\n \n # compute the log probability density of all the random numbers we drew\n log_prob_u = np.log(1.0 / (len(means) - 1))\n \n # and also the log probability density of the random numbers we would have drawn?\n weight_new = weights[i]\n mean_new = means[i]\n stdev_new = stdevs[i]\n u_1 = weight_new / weights[parents[i]]\n u_2 = (mean_new - means[parents[i]] ) / mean_perturbation_scale\n u_3 = (stdev_new - stdevs[parents[i]]) / stdev_perturbation_scale\n log_prob_u += u_1_distribution.logpdf(u_1) + u_2_distribution.logpdf(u_2) + u_3_distribution.logpdf(u_3)\n \n # also I think we need to compute the jacobian determinant of the inverse\n inv_log_jacobian_determinant = np.log(weights[parents[i]]) + np.log(mean_perturbation_scale) + np.log(stdev_perturbation_scale)\n log_jacobian_determinant = - inv_log_jacobian_determinant\n \n # remove this mixture component, and re-allocate its weight to its parent\n weights[parents[i]] += weights[i]\n \n # update the parent list, so that any j whose parent just got deleted is assigned a new parent\n for j in range(1, len(parents)):\n if parents[j] == i:\n parents[j] = parents[i]\n \n # wait, this is almost certainly wrong, because the indices will change...\n _ = means.pop(i)\n _ = stdevs.pop(i)\n _ = weights.pop(i)\n _ = parents.pop(i)\n \n # fix indices\n for j in range(1, len(parents)):\n if parents[j] > i:\n parents[j] -= 1\n \n return (means, stdevs, weights, parents), (log_jacobian_determinant - log_prob_u)\n\nfrom tqdm import tqdm\ndef rjmcmc_w_parents(theta, parents, n_steps=10000):\n \n traj = [(theta, parents)]\n old_log_p = flat_log_p(theta)\n acceptance_probabilities = []\n \n for t in tqdm(range(n_steps)):\n # generate proposal\n if np.random.rand() < 0.05:\n theta_prime, parents_prime, log_jac_u_term = reversible_birth_death_move(theta, parents)\n else:\n theta_prime, parents_prime, log_jac_u_term = mmc_move(theta, parents) \n \n new_log_p = flat_log_p(theta_prime)\n log_prob_ratio = new_log_p - old_log_p\n if not np.isfinite(new_log_p):\n A = 0\n #print(RuntimeWarning(\"new_log_p isn't finite: theta = {}, parents = {}\".format(theta_prime, parents_prime)))\n else:\n A = min(1.0, np.exp(log_prob_ratio + log_jac_u_term))\n \n if np.random.rand() < A:\n theta = theta_prime\n parents = parents_prime\n old_log_p = new_log_p\n \n if len(theta) != len(traj[-1][0]):\n prev_dim = int(len(traj[-1][0]) / 3)\n current_dim = int(len(theta) / 3)\n assert(len(theta) % 3 == 0)\n\n print('{}: accepted a cross-model jump! # components: {} --> {}'.format(t, prev_dim, current_dim))\n traj.append((theta, parents))\n acceptance_probabilities.append(A)\n return traj, acceptance_probabilities",
"_____no_output_____"
],
[
"np.random.seed(0)\ninit_n_components = 1\ninit_means = np.random.randn(init_n_components)\ninit_stdevs = np.random.rand(init_n_components) + 1\ninit_weights = np.random.rand(init_n_components)\ninit_weights /= np.sum(init_weights)\ninit_theta = np.hstack([init_means, init_stdevs, init_weights])\ninit_parents = [None] + list(range(init_n_components - 1))\ntraj, acceptance_probabilities = rjmcmc_w_parents(init_theta, init_parents, n_steps=100000)",
" 0%| | 132/100000 [00:00<01:16, 1312.57it/s]/Users/joshuafass/anaconda/lib/python3.6/site-packages/autograd/tracer.py:48: RuntimeWarning: invalid value encountered in log\n return f_raw(*args, **kwargs)\n 0%| | 247/100000 [00:00<01:19, 1256.99it/s]"
],
[
"plt.plot([a for a in acceptance_probabilities], '.')",
"_____no_output_____"
],
[
"plt.hist(acceptance_probabilities, bins=50);",
"_____no_output_____"
],
[
"n_components_traj = [len(t[0]) / 3 for t in traj]\nax = plt.subplot(111)\nplt.plot(n_components_traj)\nplt.hlines(n_components, 0, len(traj), linestyles='--')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.ylabel('# components')\nplt.xlabel('iteration')\nplt.title(r'birth-death RJMC trace $k$' + '\\n(mixture weights ' + r'$w_i$ free)')\n#plt.xscale('log')\nplt.savefig('birth-death-n-components-starting-from-1.jpg', dpi=300)",
"_____no_output_____"
],
[
"plt.figure(figsize=(6,6))\n\nburned_in = n_components_traj[1000:]\n\ncounts = np.bincount(burned_in)\nn_components_range = list(range(len(counts)))\n\nax = plt.subplot(111)\n\nplt.bar(n_components_range, counts / sum(counts))\nplt.xlabel(r'# of components ($k$)')\nplt.ylabel(r'$p(k)$')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.title(r'birth-death RJMC estimated marginal distribution of $k$' + '\\n(mixture weights ' + r'$w_i$ free)')\nplt.xticks(n_components_range)\nplt.yticks([])\nplt.savefig('birth-death-marginals-starting-from-1.jpg', dpi=300)",
"_____no_output_____"
],
[
"change_points = list(np.arange(1, len(n_components_traj))[np.diff(n_components_traj) != 0])\ntrajs = []\nfor (start, end) in list(zip([0] + change_points, change_points + [len(traj)])):\n trajs.append(np.array([t[0] for t in traj[start:end]]))",
"_____no_output_____"
],
[
"plt.figure(figsize=(6,6))\nax = plt.subplot(2, 1, 1)\nfor i in range(len(trajs)):\n x_init = sum([len(t) for t in trajs[:i]])\n x_end = x_init + len(trajs[i])\n n_components = int(trajs[i].shape[1] / 3)\n plt.plot(np.arange(x_init, x_end), trajs[i][:,:n_components], color='blue')\nplt.ylim(-6,6)\nplt.yticks([-5,0,5])\nplt.xticks([0,50000,100000])\nplt.xlabel('iteration')\nplt.ylabel(r'mixture component means ($x$)')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\n\nax = plt.subplot(2, 1, 2, sharex=ax)\nplt.plot(n_components_traj)\nplt.xlabel('iteration')\nplt.ylabel(r'# components')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\nplt.savefig('birth-death-branching-1.jpg', dpi=600, bbox_inches='tight')",
"_____no_output_____"
],
[
"np.random.seed(1)\ninit_n_components = 50\ninit_means = np.random.randn(init_n_components)\ninit_stdevs = np.random.rand(init_n_components) + 1\ninit_weights = np.random.rand(init_n_components)\ninit_weights /= np.sum(init_weights)\ninit_theta = np.hstack([init_means, init_stdevs, init_weights])\ninit_parents = [None] + list(range(init_n_components - 1))\ntraj, acceptance_probabilities = rjmcmc_w_parents(init_theta, init_parents, n_steps=100000)",
" 0%| | 0/100000 [00:00<?, ?it/s]/Users/joshuafass/anaconda/lib/python3.6/site-packages/autograd/tracer.py:48: RuntimeWarning: invalid value encountered in log\n return f_raw(*args, **kwargs)\n 0%| | 27/100000 [00:00<12:37, 131.91it/s]"
],
[
"n_components_traj = [len(t[0]) / 3 for t in traj]\nax = plt.subplot(111)\nplt.plot(n_components_traj)\nplt.hlines(n_components, 0, len(traj), linestyles='--')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.ylabel('# components')\nplt.xlabel('iteration')\nplt.title(r'birth-death RJMC trace $k$' + '\\n(mixture weights ' + r'$w_i$ free)')\n#plt.xscale('log')\nplt.savefig('birth-death-n-components-starting-from-50.jpg', dpi=300)",
"_____no_output_____"
],
[
"plt.figure(figsize=(6,6))\n\nburned_in = n_components_traj[10000:]\n\ncounts = np.bincount(burned_in)\nn_components_range = list(range(len(counts)))\n\nax = plt.subplot(111)\n\nplt.bar(n_components_range, counts / sum(counts))\nplt.xlabel(r'# of components ($k$)')\nplt.ylabel(r'$p(k)$')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\nplt.title(r'birth-death RJMC estimated marginal distribution of $k$' + '\\n(mixture weights ' + r'$w_i$ free)')\nplt.xticks(n_components_range)\nplt.yticks([])\nplt.savefig('birth-death-marginals-starting-from-50.jpg', dpi=300)",
"_____no_output_____"
],
[
"change_points = list(np.arange(1, len(n_components_traj))[np.diff(n_components_traj) != 0])\ntrajs = []\nfor (start, end) in list(zip([0] + change_points, change_points + [len(traj)])):\n trajs.append(np.array([t[0] for t in traj[start:end]]))",
"_____no_output_____"
],
[
"plt.figure(figsize=(6,6))\nax = plt.subplot(2, 1, 1)\nfor i in range(len(trajs)):\n x_init = sum([len(t) for t in trajs[:i]])\n x_end = x_init + len(trajs[i])\n n_components = int(trajs[i].shape[1] / 3)\n plt.plot(np.arange(x_init, x_end), trajs[i][:,:n_components], color='blue')\nplt.ylim(-6,6)\nplt.yticks([-5,0,5])\nplt.xticks([0,50000,100000])\nplt.xlabel('iteration')\nplt.ylabel(r'mixture component means ($x$)')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\n\nax = plt.subplot(2, 1, 2, sharex=ax)\nplt.plot(n_components_traj)\nplt.xlabel('iteration')\nplt.ylabel(r'# components')\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\nplt.savefig('birth-death-branching-50.jpg', dpi=600, bbox_inches='tight')",
"_____no_output_____"
],
[
"trees = [t[-1] for t in traj[1000:]]",
"_____no_output_____"
],
[
"for _ in range(20):\n print(trees[np.random.randint(len(trees))])",
"[None, 0, 0]\n[None]\n[None, 0]\n[None, 0]\n[None, 0]\n[None]\n[None, 0]\n[None]\n[None]\n[None]\n[None, 0]\n[None, 0, 1]\n[None, 0]\n[None]\n[None, 0]\n[None, 0]\n[None]\n[None, 0]\n[None, 0, 0, 0]\n[None]\n"
],
[
"import networkx as nx",
"_____no_output_____"
],
[
"def parent_list_to_graph(parent_list):\n \n graph = nx.DiGraph()\n \n for i in range(1, len(parent_list)):\n graph.add_edge(parent_list[i], i)\n return graph",
"_____no_output_____"
],
[
"g = parent_list_to_graph(trees[-1])\ng.nodes()",
"_____no_output_____"
],
[
"for t in trees[:10]:\n g = parent_list_to_graph(t)\n plt.figure()\n nx.draw(g, pos=nx.drawing.spring_layout(g))",
"_____no_output_____"
],
[
"log_posterior = np.array([flat_log_p(t[0]) for t in traj])\nlog_prior = np.array([log_prior(t[0]) for t in traj])\nlog_likelihood = log_posterior - log_prior",
"_____no_output_____"
],
[
"plt.plot(log_prior, label='prior')\nplt.plot(log_likelihood, label='likelihood')\nplt.plot(log_posterior, label='posterior')\nplt.legend(loc='best')\nplt.ylabel('log probability')\nplt.xlabel('iteration')\nplt.xscale('log')\n\nplt.savefig('birth-death-log-posterior.jpg', dpi=300)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba274592748517ad0eab7b8cf4fb8eb64391eac
| 159,220 |
ipynb
|
Jupyter Notebook
|
ldaFig3.ipynb
|
PedroMDuarte/hubbard-lda3
|
485b290c7bff97143f6f865b88131620f63282d7
|
[
"Unlicense",
"MIT"
] | 2 |
2020-12-20T03:05:02.000Z
|
2021-01-18T13:50:33.000Z
|
ldaFig3.ipynb
|
liangjj/hubbard-lda3
|
47c3257140da265cd9e74be1a8a04b45844cba48
|
[
"Unlicense",
"MIT"
] | null | null | null |
ldaFig3.ipynb
|
liangjj/hubbard-lda3
|
47c3257140da265cd9e74be1a8a04b45844cba48
|
[
"Unlicense",
"MIT"
] | 6 |
2015-04-24T08:18:27.000Z
|
2021-02-06T12:26:31.000Z
| 211.167109 | 47,069 | 0.861318 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cba27cf364e3b299774940778f4ce67e8bd8ab0b
| 441,423 |
ipynb
|
Jupyter Notebook
|
land/Land_S2_CLC_processing.ipynb
|
GermanoGuerrini/wekeo-jupyter-lab
|
cf50d2d83b9c2a5175b351425a0f2b94c4a19872
|
[
"MIT"
] | 1 |
2021-12-28T19:21:05.000Z
|
2021-12-28T19:21:05.000Z
|
land/Land_S2_CLC_processing.ipynb
|
dnzengou/wekeo-jupyter-lab
|
cf50d2d83b9c2a5175b351425a0f2b94c4a19872
|
[
"MIT"
] | null | null | null |
land/Land_S2_CLC_processing.ipynb
|
dnzengou/wekeo-jupyter-lab
|
cf50d2d83b9c2a5175b351425a0f2b94c4a19872
|
[
"MIT"
] | null | null | null | 435.328402 | 402,756 | 0.937627 |
[
[
[
"<img src='./img/LogoWekeo_Copernicus_RGB_0.png' align='right' width='20%'></img>",
"_____no_output_____"
],
[
"# Tutorial on basic land applications (data processing) Version 2",
"_____no_output_____"
],
[
"In this tutorial we will use the WEkEO Jupyterhub to access and analyse data from the Copernicus Sentinel-2 and products from the [Copernicus Land Monitoring Service (CLMS)](https://land.copernicus.eu/). \nA region in northern Corsica has been selected as it contains representative landscape features and process elements which can be used to demonstrate the capabilities and strengths of Copernicus space component and services.\nThe tutorial comprises the following steps:\n1. Search and download data: We will select and download a Sentinel-2 scene and the CLMS CORINE Land Cover (CLC) data from their original archive locations via WEkEO using the Harmonised Data Access (HAD) API.\n2.\t[Read and view Sentinel-2 data](#load_sentinel2): Once downloaded, we will read and view the Sentinel-2 data in geographic coordinates as true colour image.\n3.\t[Process and view Sentinel-2 data as a vegetation and other spectral indices](#sentinel2_ndvi): We will see how the vegetation density and health can be assessed from optical EO data to support crop and landscape management practices.\n4.\t[Read and view the CLC data](#display_clc): Display the thematic CLC data with the correct legend.\n5.\t[CLC2018 burnt area in the Sentinel-2 NDVI data](#CLC_burn_NDVI): The two products give different results, but they can be combined to provide more information.\n\nNOTE - This Jupyter Notebook contains additonal processing to demonstrate further functionality during the training debrief.\n\n<img src='./img/Intro_banner.jpg' align='center' width='100%'></img>",
"_____no_output_____"
],
[
"## <a id='load_sentinel2'></a>2. Load required Sentinel-2 bands and True Color image at 10 m spatial resolution",
"_____no_output_____"
],
[
"Before we begin we must prepare our environment. This includes importing the various python libraries that we will need.",
"_____no_output_____"
],
[
"### Load required libraries",
"_____no_output_____"
]
],
[
[
"import os\nimport rasterio as rio\nfrom rasterio import plot\nfrom rasterio.mask import mask\nfrom rasterio.plot import show_hist\nimport matplotlib.pyplot as plt\nimport geopandas as gpd\nfrom rasterio.plot import show\nfrom rasterio.plot import plotting_extent\nimport zipfile\nfrom matplotlib import rcParams\nfrom pathlib import Path\nimport numpy as np\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib import cm\nfrom matplotlib import colors\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom IPython.core.display import HTML\nfrom rasterio.warp import calculate_default_transform, reproject, Resampling\nimport scipy.ndimage",
"_____no_output_____"
]
],
[
[
"The Sentinel-2 Multiple Spectral Imager (MSI) records 13 spectral bands across the visible and infrared portions of the electromagnetic spectrum at different spatial resolutions from 10 m to 60 m depending on their operation and use. There are currently two Sentinel-2 satellites in suitably phased orbits to give a revisit period of 5 days at the Equator and 2-3 days at European latitudes. Being an optical sensor they are of course also affected by cloud cover and illumination conditions. The two satellites have been fully operational since 2017 and record continuously over land and the adjacent coastal sea areas. Their specification represents a continuation and upgrade of the US Landsat system which has archive data stretching back to the mid 1980s.\n\n<img src='./img/S2_band_comp.png' align='center' width='50%'></img>\n\nFor this training session we will only need a composite true colour image (made up of the blue green and red bands) and the individual bands for red (665 nm) and near infrared (833 nm). The cell below loads the required data.",
"_____no_output_____"
]
],
[
[
"#Download folder\ndownload_dir_path = os.path.join(os.getcwd(), 'data/from_wekeo')\ndata_path = os.path.join(os.getcwd(), 'data')\n\nR10 = os.path.join(download_dir_path, 'S2A_MSIL2A_20170802T101031_N0205_R022_T32TNN_20170802T101051.SAFE/GRANULE/L2A_T32TNN_A011030_20170802T101051/IMG_DATA/R10m') #10 meters resolution folder\nb3 = rio.open(R10+'/L2A_T32TNN_20170802T101031_B03_10m.jp2') #green\nb4 = rio.open(R10+'/L2A_T32TNN_20170802T101031_B04_10m.jp2') #red\nb8 = rio.open(R10+'/L2A_T32TNN_20170802T101031_B08_10m.jp2') #near infrared \nTCI = rio.open(R10+'/L2A_T32TNN_20170802T101031_TCI_10m.jp2') #true color",
"_____no_output_____"
]
],
[
[
"### Display True Color and False Colour Infrared images",
"_____no_output_____"
],
[
"The true colour image for the Sentinel-2 data downloaded in the previous JN can be displayed as a plot to show we have the required area and assess other aspects such as the presence of cloud, cloud shadow, etc. \n\nIn this case we selected region of northern Corsica showing the area around Bastia and the Tyrrhenian Sea out to the Italian island of Elba in the east. The area has typical Mediterranean vegetation with mountainous semi natural habitats and urban and agricultural areas along the coasts.\n\nThe cell below displays the true colour image in its native WGS-84 coordinate reference system.\n\nThe right hand plot shows the same image in false colour infrared format (FCIR). In this format the green band is displayed as blue, red as green and near infrared as red. Vegetated areas appear red and water is black.",
"_____no_output_____"
]
],
[
[
"fig, (ax, ay) = plt.subplots(1,2, figsize=(21,7))\nshow(TCI.read(), ax=ax, transform=TCI.transform, title = \"TRUE COLOR\")\nax.set_ylabel(\"Northing (m)\") # (WGS 84 / UTM zone 32N)\nax.set_xlabel(\"Easting (m)\")\nax.ticklabel_format(axis = 'both', style = 'plain')\n\n\n# Function to normalize false colour infrared image \ndef normalize(array):\n \"\"\"Normalizes numpy arrays into scale 0.0 - 1.0\"\"\"\n array_min, array_max = array.min(), array.max() \n return ((array - array_min)/(array_max - array_min))\n\nnir = b8.read(1)\nred = b4.read(1)\ngreen = b3.read(1)\nnirn = normalize(scipy.ndimage.zoom(nir,0.5))\nredn = normalize(scipy.ndimage.zoom(red,0.5))\ngreenn = normalize(scipy.ndimage.zoom(green,0.5))\nFCIR = np.dstack((nirn, redn, greenn))\nFCIR = np.moveaxis(FCIR.squeeze(),-1,0)\nshow(FCIR, ax=ay, transform=TCI.transform, title = \"FALSE COLOR INFRARED\")\nay.set_ylabel(\"Northing (m)\") # (WGS 84 / UTM zone 32N)\nay.set_xlabel(\"Easting (m)\")\nay.ticklabel_format(axis = 'both', style = 'plain')",
"_____no_output_____"
]
],
[
[
"## <a id='sentinel2_ndvi'></a>3. Process and view Sentinel-2 data as vegetation and other spectral indices",
"_____no_output_____"
],
[
"Vegetation status is a combination of a number of properties of the vegetation related to growth, density, health and environmental factors. By making measurements of surface reflectance in the red and near infrared (NIR) parts of the spectrum optical instruments can summarise crop status through a vegetation index. The red region is related to chlorophyll absorption and the NIR is related to multiple scattering within leaf structures, therefore low red and high NIR represent healthy / dense vegetation. These values are summarised in the commonly used Normalised Difference Vegetation Index (NDVI).\n\n<img src='./img/ndvi.jpg' align='center' width='20%'></img>\n\nWe will examine a small subset of the full image were we know differences in vegetation will be present due to natural and anthropogenic processes and calculate the NDVI to show how its value changes. \n\nWe will also calculate a second spectral index, the Normalised Difference Water Index (NDWI), which emphasises water surfaces to compare to NDVI.\n\nTo do this we'll first load some vector datasets for an area of interest (AOI) and some field boundaries.",
"_____no_output_____"
],
[
"### Open Vector Data",
"_____no_output_____"
]
],
[
[
"path_shp = os.path.join(os.getcwd(), 'shp')\naoi = gpd.read_file(os.path.join(path_shp, 'WEkEO-Land-AOI-201223.shp'))\nLPSI = gpd.read_file(os.path.join(path_shp, 'LPIS-AOI-201223.shp'))",
"_____no_output_____"
]
],
[
[
"### Check CRS of Vector Data",
"_____no_output_____"
],
[
"Before we can use the vector data we must check the coordinate reference system (CRS) and then transpose them to the same CRS as the Sentinel-2 data. In this case we require all the data to be in the WGS 84 / UTM zone 32N CRS with the EPSG code of 32632.",
"_____no_output_____"
]
],
[
[
"print(aoi.crs)\nprint(LPSI.crs)\naoi_proj = aoi.to_crs(epsg=32632) #convert to WGS 84 / UTM zone 32N (Sentinel-2 crs)\nLPIS_proj = LPSI.to_crs(epsg=32632)\nprint(\"conversion to S2 NDVI crs:\")\nprint(aoi_proj.crs)\nprint(LPIS_proj.crs)",
"epsg:4326\nepsg:2154\nconversion to S2 NDVI crs:\nepsg:32632\nepsg:32632\n"
]
],
[
[
"### Calculate NDVI from red and near infrared bands",
"_____no_output_____"
],
[
"First step is to calculate the NDVI for the whole image using some straightforward band maths and write out the result to a geoTIFF file.",
"_____no_output_____"
]
],
[
[
"nir = b8.read()\nred = b4.read()\nndvi = (nir.astype(float)-red.astype(float))/(nir+red)\n\nmeta = b4.meta \nmeta.update(driver='GTiff')\nmeta.update(dtype=rio.float32)\nwith rio.open(os.path.join(data_path, 'S2_NDVI.tif'), 'w', **meta) as dst:\n dst.write(ndvi.astype(rio.float32))",
"_____no_output_____"
]
],
[
[
"### Calculate NDWI from green and near infrared bands",
"_____no_output_____"
],
[
"The new step is to calculate the NDWI for the whole image using some straightforward band maths and write out the result to a geoTIFF file.",
"_____no_output_____"
]
],
[
[
"nir = b8.read()\ngreen = b3.read()\nndwi = (green.astype(float) - nir.astype(float))/(nir+green)\n\nmeta = b3.meta \nmeta.update(driver='GTiff')\nmeta.update(dtype=rio.float32)\nwith rio.open(os.path.join(data_path, 'S2_NDWI.tif'), 'w', **meta) as dst:\n dst.write(ndwi.astype(rio.float32))",
"_____no_output_____"
]
],
[
[
"### Crop the extent of the NDVI and NDWI images to the AOI",
"_____no_output_____"
],
[
"The file produced in the previous step is then cropped using the AOI geometry. ",
"_____no_output_____"
]
],
[
[
"with rio.open(os.path.join(data_path, \"S2_NDVI.tif\")) as src:\n out_image, out_transform = mask(src, aoi_proj.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform})\n \nwith rio.open(os.path.join(data_path, \"S2_NDVI_masked.tif\"), \"w\", **out_meta) as dest:\n dest.write(out_image) \n \nwith rio.open(os.path.join(data_path, \"S2_NDWI.tif\")) as src:\n out_image, out_transform = mask(src, aoi_proj.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform})\n \nwith rio.open(os.path.join(data_path, \"S2_NDWI_masked.tif\"), \"w\", **out_meta) as dest:\n dest.write(out_image) ",
"_____no_output_____"
]
],
[
[
"### Display NDVI and NDWI for the AOI",
"_____no_output_____"
],
[
"The AOI represents an area of northern Corsica centred on the town of Bagnasca. To the west are mountains dominated by forests and woodlands of evergreen sclerophyll oaks which tend to give high values of NDVI intersperse by areas of grassland or bare ground occuring naturally or as a consequnce of forest fires. The patterns are more irregular and follow the terrain and hydrological features. The lowlands to east have been clear of forest for agriculture shown by a fine scale mosaic of regular geometric features representing crop fields with diffrerent NDVIs or the presence of vegetated boundary features. The lower values of NDVI (below zero) in the east are associated with the sea and the large lagoon of the Réserve naturelle de l'étang de Biguglia.\n\nAs expected the NDWI gives high values for the open sea and lagoon areas of the image. Interestingly there are relatively high values for some of the fields in the coastal plane suggesting they may be flooded or irrigated. The bare surfaces have NDWI values below zero and the vegetated areas are lower still.\n\nThe colour map used to display the NDVI uses a ramp from blue to green to emphasise the increasing density and vigour of vegetation at high NDVI values. If distinction are not so clear the cmap value can be change from \"BuGn\" or \"RdBu\" to something more appropriate with reference to the the available colour maps at [Choosing Colormaps in Matplotlib](https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html).",
"_____no_output_____"
]
],
[
[
"ndvi_aoi = rio.open(os.path.join(data_path, 'S2_NDVI_masked.tif'))\n\nfig, (az, ay) = plt.subplots(1,2, figsize=(21, 7))\n\n# use imshow so that we have something to map the colorbar to\nimage_hidden_1 = az.imshow(ndvi_aoi.read(1), \n cmap='BuGn')\n\n# LPIS_proj.plot(ax=ax, facecolor='none', edgecolor='k')\n\nimage = show(ndvi_aoi, ax=az, cmap='BuGn', transform=ndvi_aoi.transform, title =\"NDVI\")\n\nfig.colorbar(image_hidden_1, ax=az)\naz.set_ylabel(\"Northing (m)\") #(WGS 84 / UTM zone 32N)\naz.set_xlabel(\"Easting (m)\")\naz.ticklabel_format(axis = 'both', style = 'plain')\n\nndwi_aoi = rio.open(os.path.join(data_path, 'S2_NDWI_masked.tif'))\n\n# use imshow so that we have something to map the colorbar to\nimage_hidden_1 = ay.imshow(ndwi_aoi.read(1), \n cmap='RdBu')\n\n# LPIS_proj.plot(ax=ax, facecolor='none', edgecolor='k')\n\nimage = show(ndwi_aoi, ax=ay, cmap='RdBu', transform=ndwi_aoi.transform, title =\"NDWI\")\n\nfig.colorbar(image_hidden_1, ax=ay)\nay.set_ylabel(\"Northing (m)\") #(WGS 84 / UTM zone 32N)\nay.set_xlabel(\"Easting (m)\")\nay.ticklabel_format(axis = 'both', style = 'plain')",
"_____no_output_____"
]
],
[
[
"### Histogram of NDVI values",
"_____no_output_____"
],
[
"If the NDVI values for the area are summarised as a histogram the two main levels of vegetation density / vigour become apprent. On the left of the plot there is a peak between NDVI values of -0.1 and 0.3 for the water and unvegetated areas together (with the water generally lower) and on the right the peak around an NDVI value of 0.8 is the dense forest and vigorous crops. The region in between shows spare vegetation, grassland and crops that are yet to mature. \n\nIn the NDWI histogram there are multiple peaks representing the sea and lagoons, bare surfaes and vegetation respectively. The NDVI and NDWI can be used in combination to characterise regons within satellite images.",
"_____no_output_____"
]
],
[
[
"fig, axhist = plt.subplots(1,1)\nshow_hist(ndvi_aoi, bins=100, masked=False, title='Histogram of NDVI values', facecolor = 'g', ax =axhist)\naxhist.set_xlabel('NDVI')\naxhist.set_ylabel('number of pixels')\nplt.gca().get_legend().remove()\n\nfig, axhist = plt.subplots(1,1)\nshow_hist(ndwi_aoi, bins=100, masked=False, title='Histogram of NDWI values', facecolor = 'b', ax =axhist)\naxhist.set_xlabel('NDWI')\naxhist.set_ylabel('number of pixels')\nplt.gca().get_legend().remove()",
"_____no_output_____"
]
],
[
[
"### NDVI index on a cultivation pattern area",
"_____no_output_____"
],
[
"We can look in more detail at the agricultural area to see the patterns in the NDVI values caused by differential crop density and growth. As before we load a vector file containing an AOI, subset the original Sentinel-2 NDVI image. This time we over lay a set of field boundaries from the Land Parcel Information System (LPIS) which highlight some of the management units.\n\nThis analysis gives us a representation of the biophysical properties of the surface at the time of image acquisition. ",
"_____no_output_____"
]
],
[
[
"#Load shapefile of the AOIs\n\ncult_zoom = gpd.read_file(os.path.join(path_shp, 'complex_cultivation_patterns_zoom.shp'))\n\n#Subset the Sentinel-2 NDVI image\n\nwith rio.open(os.path.join(data_path, \"S2_NDVI.tif\")) as src:\n out_image, out_transform = mask(src, cult_zoom.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform})\n \nwith rio.open(os.path.join(data_path, \"NDVI_cultivation_area.tif\"), \"w\", **out_meta) as dest:\n dest.write(out_image.astype(rio.float32))\n \n#Display the results with the LPIS\n\nrcParams['axes.titlepad'] = 20 \n\nsrc_cult = rio.open(os.path.join(data_path, \"NDVI_cultivation_area.tif\"))\n\nfig, axg = plt.subplots(figsize=(21, 7))\n\nimage_hidden_1 = axg.imshow(src_cult.read(1), \n cmap='BuGn')\n\nLPIS_proj.plot(ax=axg, facecolor='none', edgecolor='k')\n\nshow(src_cult, ax=axg, cmap='BuGn', transform=src_cult.transform, title='NDVI - Complex cultivation patterns')\n\nfig.colorbar(image_hidden_1, ax=axg)\n\naxg.set_ylabel(\"Northing (m)\") #(WGS 84 / UTM zone 32N)\naxg.set_xlabel(\"Easting (m)\")\n\nplt.subplots_adjust(bottom=0.1, right=0.6, top=0.9)\naxg.ticklabel_format(axis = 'both', style = 'plain')",
"_____no_output_____"
]
],
[
[
"## <a id='display_clc'></a>4. Read and view the CLC data",
"_____no_output_____"
],
[
"The CORINE Land Cover (CLC) inventory has been produced at a European level in 1990, 2000, 2006, 2012, and 2018. It records land cover and land use in 44 classes with a Minimum Mapping Unit (MMU) of 25 hectares (ha) and a minimum feature width of 100 m. The time series of status maps are complemented by change layers, which highlight changes between the land cover land use classes with an MMU of 5 ha. The Eionet network of National Reference Centres Land Cover (NRC/LC) produce the CLC databases at Member State level, which are coordinated and integrated by EEA. CLC is produced by the majority of countries by visual interpretation of high spatial resolution satellite imagery (10 - 30 m spatial resolution). In a few countries semi-automatic solutions are applied, using national in-situ data, satellite image processing, GIS integration and generalisation. CLC has a wide variety of applications, underpinning various policies in the domains of environment, but also agriculture, transport, spatial planning etc.",
"_____no_output_____"
],
[
"### Crop the extent of the Corine Land Cover 2018 (CLC 2018) to the AOI and display",
"_____no_output_____"
],
[
"As with the Sentinel-2 data it is necesasary to crop the pan-European CLC2018 dataset to be able to review it at the local level. ",
"_____no_output_____"
],
[
"### Set up paths to data",
"_____no_output_____"
]
],
[
[
"#path to Corine land cover 2018\nland_cover_dir = Path(os.path.join(download_dir_path,'u2018_clc2018_v2020_20u1_raster100m/DATA/'))\nlegend_dir = Path(os.path.join(download_dir_path,'u2018_clc2018_v2020_20u1_raster100m/Legend/'))\n\n#path to the colormap\ntxt_filename = legend_dir/'CLC2018_CLC2018_V2018_20_QGIS.txt'",
"_____no_output_____"
]
],
[
[
"### Re-project vector files to the same coordinate system of the CLC 2018",
"_____no_output_____"
]
],
[
[
"aoi_3035 = aoi.to_crs(epsg=3035) # EPSG:3035 (ETRS89-extended / LAEA Europe)",
"_____no_output_____"
]
],
[
[
"### Write CLC 2018 subset",
"_____no_output_____"
]
],
[
[
"with rio.open(str(land_cover_dir)+'/U2018_CLC2018_V2020_20u1.tif') as src:\n out_image, out_transform = mask(src, aoi_3035.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform,\n \"dtype\": \"int8\",\n \"nodata\":0\n })\n \nwith rio.open(\"CLC_masked/Corine_masked.tif\", \"w\", **out_meta) as dest:\n dest.write(out_image)",
"_____no_output_____"
]
],
[
[
"### Set up the legend for the CLC data",
"_____no_output_____"
],
[
"As the CLC data is thematic in nature we must set up a legend to be displayed with the results showing the colour, code and definition of each land cover / land use class.",
"_____no_output_____"
],
[
"### Read CLC 2018 legend",
"_____no_output_____"
],
[
"A text file is availabe which contains the details of the CLC nomenclature for building the legend when displaying CLC.",
"_____no_output_____"
]
],
[
[
"### Create colorbar\ndef parse_line(line):\n _, r, g, b, a, descr = line.split(',')\n return (int(r), int(g), int(b), int(a)), descr.split('\\n')[0]\n\nwith open(txt_filename, 'r') as txtf:\n lines = txtf.readlines()\n\nlegend = {nline+1: parse_line(line) for nline, line in enumerate(lines[:-1])}\nlegend[0] = parse_line(lines[-1])\n\n#print code and definition of each land cover / land use class\ndef parse_line_class_list(line):\n class_id, r, g, b, a, descr = line.split(',')\n return (int(class_id), int(r), int(g), int(b), int(a)), descr.split('\\n')[0]\n\nwith open(txt_filename, 'r') as txtf:\n lines = txtf.readlines()\n\nlegend_class = {nline+1: parse_line_class_list(line) for nline, line in enumerate(lines[:-1])}\nlegend_class[0] = parse_line_class_list(lines[-1])\n\nprint('Level 3 classes')\nfor k, v in sorted(legend_class.items()):\n print(f'{v[0][0]}\\t{v[1]}')",
"_____no_output_____"
]
],
[
[
"### Build the legend for the CLC 2018 in the area of interest",
"_____no_output_____"
],
[
"As less than half of the CLC classes are present in the AOI an area specific legend will be built to simplify interpretation.",
"_____no_output_____"
]
],
[
[
"#open CLC 2018 subset\ncover_land = rio.open(\"CLC_masked/Corine_masked.tif\")\n\narray_rast = cover_land.read(1)\n\n#Set no data value to 0\narray_rast[array_rast == -128] = 0\n\nclass_aoi = list(np.unique(array_rast))\nlegend_aoi = dict((k, legend[k]) for k in class_aoi if k in legend)\n\nclasses_list =[]\nnumber_list = []\nfor k, v in sorted(legend_aoi.items()):\n #print(f'{k}:\\t{v[1]}')\n classes_list.append(v[1])\n number_list.append(k)\n\nclass_dict = dict(zip(classes_list,number_list))\n\n#create the colobar\ncorine_cmap_aoi= ListedColormap([np.array(v[0]).astype(float)/255.0 for k, v in sorted(legend_aoi.items())])\n\n# Map the values in [0, 22]\nnew_dict = dict()\nfor i, v in enumerate(class_dict.items()):\n new_dict[v[1]] = (v[0], i)\n\nfun = lambda x : new_dict[x][1]\nmatrix = map(np.vectorize(fun), array_rast)\nmatrix = np.matrix(list(matrix))",
"_____no_output_____"
]
],
[
[
"### Display the CLC2018 data for the AOI",
"_____no_output_____"
],
[
"The thematic nature and the 100 m spatial resolution of the CLC2018 give a very different view of the landscape compared to the Sentinel-2 data. CLC2018 offers a greater information content as it is a combination of multiple images, ancillary data and human interpretation while Sentinel-2 offers great spatial information for one instance in time. \n\nThe separation of the mountains with woodland habitats and the coastal planes with agriculture can be clearly seen marked by a line of urban areas. The mountains are dominated by deciduous woodland, sclerophyllous vegetation and transitional scrub. The coastal planes consist of various types of agricultural land associated with small field farming practices.\n\nThe most striking feature of the CLC2018 data is a large burnt area which resulted from a major forest fire in July 2017.",
"_____no_output_____"
]
],
[
[
"#plot\nfig2, axs2 = plt.subplots(figsize=(10,10),sharey=True)\nshow(matrix, ax=axs2, cmap=corine_cmap_aoi, transform = cover_land.transform, title = \"Corine Land Cover 2018\")\nnorm = colors.BoundaryNorm(np.arange(corine_cmap_aoi.N + 1), corine_cmap_aoi.N + 1)\ncb = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=corine_cmap_aoi), ax=axs2, fraction=0.03)\ncb.set_ticks([x+.5 for x in range(-1,22)]) # move the marks to the middle\ncb.set_ticklabels(list(class_dict.keys())) # label the colors\naxs2.ticklabel_format(axis = 'both', style = 'plain')\naxs2.set_ylabel(\"Northing (m)\") #EPSG:3035 (ETRS89-extended / LAEA Europe)\naxs2.set_xlabel(\"Easting (m)\")",
"_____no_output_____"
]
],
[
[
"## <a id='CLC_burn_NDVI'></a>5. CLC2018 burnt area in the Sentinel-2 NDVI data",
"_____no_output_____"
],
[
"The area of the burn will have a very low NDVI compared to the surounding unburnt vegetation. The boundary of the burn can be easily seen as well as remnants of the original vegetation which have survived the burn.",
"_____no_output_____"
]
],
[
[
"#Load shapefile of the AOIs and check the crs\n\nburnt_aoi = gpd.read_file(os.path.join(path_shp, 'burnt_area.shp'))\nprint(\"vector file crs:\")\nprint(burnt_aoi.crs)\n\nburnt_aoi_32632 = burnt_aoi.to_crs(epsg=32632) #Sentinel-2 NDVI crs\nprint(\"conversion to S2 NDVI crs:\")\nprint(burnt_aoi_32632.crs)",
"_____no_output_____"
]
],
[
[
"### Crop the extent of the NDVI image for burnt area",
"_____no_output_____"
]
],
[
[
"with rio.open(os.path.join(data_path, 'S2_NDVI_masked.tif')) as src:\n out_image, out_transform = mask(src, burnt_aoi_32632.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform})\n \nwith rio.open(os.path.join(data_path, \"NDVI_burnt_area.tif\"), \"w\", **out_meta) as dest:\n dest.write(out_image)\n",
"_____no_output_____"
]
],
[
[
"### Crop the extent of the CLC 2018 for burnt area",
"_____no_output_____"
]
],
[
[
"#open CLC 2018 subset\n\ncover_land = rio.open(\"CLC_masked/Corine_masked.tif\")\n\nprint(cover_land.crs) #CLC 2018 crs\nburn_aoi_3035 = burnt_aoi.to_crs(epsg=3035) #conversion to CLC 2018 crs\n\nwith rio.open(str(land_cover_dir)+'/U2018_CLC2018_V2020_20u1.tif') as src:\n out_image, out_transform = mask(src, burn_aoi_3035.geometry,crop=True)\n out_meta = src.meta.copy()\n out_meta.update({\"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\"width\": out_image.shape[2],\n \"transform\": out_transform,\n \"dtype\": \"int8\",\n \"nodata\":0\n })\n \nwith rio.open(\"CLC_masked/Corine_burnt_area.tif\", \"w\", **out_meta) as dest:\n dest.write(out_image)",
"_____no_output_____"
],
[
"# Re-project S2 NDVI image to CLC 2018 crs\n\nclc_2018_burnt_aoi = rio.open(\"CLC_masked/Corine_burnt_area.tif\")\ndst_crs = clc_2018_burnt_aoi.crs\n\n\nwith rio.open(os.path.join(data_path, \"NDVI_burnt_area.tif\")) as src:\n transform, width, height = calculate_default_transform(\n src.crs, dst_crs, src.width, src.height, *src.bounds)\n kwargs = src.meta.copy()\n kwargs.update({\n 'crs': dst_crs,\n 'transform': transform,\n 'width': width,\n 'height': height\n })\n\n with rio.open(os.path.join(data_path, \"NDVI_burnt_area_EPSG_3035.tif\"), 'w', **kwargs) as dst:\n reproject(source=rio.band(src,1),\n destination=rio.band(dst,1),\n src_transform=src.transform,\n src_crs=src.crs,\n dst_transform=transform,\n dst_crs=dst_crs,\n resampling=Resampling.nearest)",
"_____no_output_____"
]
],
[
[
"### Display NDVI index on the AOIs",
"_____no_output_____"
]
],
[
[
"# Build the legend for the CLC 2018 in the area of interest\n\narray_rast_b = clc_2018_burnt_aoi.read(1)\n\n#Set no data value to 0\narray_rast_b[array_rast_b == -128] = 0\n\nclass_aoi_b = list(np.unique(array_rast_b))\nlegend_aoi_b = dict((k, legend[k]) for k in class_aoi_b if k in legend)\nclasses_list_b =[]\nnumber_list_b = []\n\nfor k, v in sorted(legend_aoi_b.items()):\n #print(f'{k}:\\t{v[1]}')\n classes_list_b.append(v[1])\n number_list_b.append(k)\n\nclass_dict_b = dict(zip(classes_list_b,number_list_b))\n#create the colobar\ncorine_cmap_aoi_b= ListedColormap([np.array(v[0]).astype(float)/255.0 for k, v in sorted(legend_aoi_b.items())])\n\n# Map the values in [0, 22]\nnew_dict_b = dict()\nfor i, v in enumerate(class_dict_b.items()):\n new_dict_b[v[1]] = (v[0], i)\n\nfun_b = lambda x : new_dict_b[x][1]\nmatrix_b = map(np.vectorize(fun_b), array_rast_b)\nmatrix_b = np.matrix(list(matrix_b))\n\n\n#Plot\n\nrcParams['axes.titlepad'] = 20 \nsrc_burnt = rio.open(os.path.join(data_path, \"NDVI_burnt_area_EPSG_3035.tif\"))\n\nfig_b, (axr_b, axg_b) = plt.subplots(1,2, figsize=(25, 8))\n\nimage_hidden_1_b = axr_b.imshow(src_burnt.read(1), \n cmap='BuGn')\n\nshow(src_burnt, ax=axr_b, cmap='BuGn', transform=src_burnt.transform, title='NDVI - Burnt area')\nshow(matrix_b, ax=axg_b, cmap=corine_cmap_aoi_b, transform=clc_2018_burnt_aoi.transform, title='CLC 2018 - Burnt area')\n\nfig_b.colorbar(image_hidden_1_b, ax=axr_b)\nplt.tight_layout(h_pad=1.0)\n\nnorm = colors.BoundaryNorm(np.arange(corine_cmap_aoi_b.N + 1), corine_cmap_aoi_b.N + 1)\ncb = plt.colorbar(cm.ScalarMappable(norm=norm, cmap=corine_cmap_aoi_b), ax=axg_b, fraction=0.03)\ncb.set_ticks([x+.5 for x in range(-1,6)]) # move the marks to the middle\ncb.set_ticklabels(list(class_dict_b.keys())) # label the colors\naxg_b.ticklabel_format(axis = 'both', style = 'plain')\n\n\naxr_b.set_ylabel(\"Northing (m)\") #(WGS 84 / UTM zone 32N)\naxr_b.set_xlabel(\"Easting (m)\")\naxg_b.set_ylabel(\"Northing (m)\") #(WGS 84 / UTM zone 32N)\naxg_b.set_xlabel(\"Easting (m)\")\n\naxr_b.ticklabel_format(axis = 'both', style = 'plain')\naxg_b.ticklabel_format(axis = 'both', style = 'plain')\nplt.tight_layout(h_pad=1.0)\n",
"_____no_output_____"
]
],
[
[
"<hr>",
"_____no_output_____"
],
[
"<p><img src='./img/all_partners_wekeo_2.png' align='left' alt='Logo EU Copernicus' width='100%'></img></p>",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cba2833593849e5803d67d1cddb1b58d5bee68b2
| 335,222 |
ipynb
|
Jupyter Notebook
|
examples/ConsumptionSaving/example_ConsLaborModel.ipynb
|
zhongliz/HARK
|
20df1344f81a8a5af6d25397d414d64bd1efa48f
|
[
"Apache-2.0"
] | null | null | null |
examples/ConsumptionSaving/example_ConsLaborModel.ipynb
|
zhongliz/HARK
|
20df1344f81a8a5af6d25397d414d64bd1efa48f
|
[
"Apache-2.0"
] | null | null | null |
examples/ConsumptionSaving/example_ConsLaborModel.ipynb
|
zhongliz/HARK
|
20df1344f81a8a5af6d25397d414d64bd1efa48f
|
[
"Apache-2.0"
] | null | null | null | 580.974003 | 47,724 | 0.946638 |
[
[
[
"from HARK.ConsumptionSaving.ConsLaborModel import (\n LaborIntMargConsumerType,\n init_labor_lifecycle,\n)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import process_time",
"_____no_output_____"
],
[
"mystr = lambda number: \"{:.4f}\".format(number) # Format numbers as strings",
"_____no_output_____"
],
[
"do_simulation = True",
"_____no_output_____"
],
[
"# Make and solve a labor intensive margin consumer i.e. a consumer with utility for leisure\nLaborIntMargExample = LaborIntMargConsumerType(verbose=0)\nLaborIntMargExample.cycles = 0",
"_____no_output_____"
],
[
"t_start = process_time()\nLaborIntMargExample.solve()\nt_end = process_time()\nprint(\n \"Solving a labor intensive margin consumer took \"\n + str(t_end - t_start)\n + \" seconds.\"\n)",
"Solving a labor intensive margin consumer took 0.7272719999999997 seconds.\n"
],
[
"t = 0\nbMin_orig = 0.0\nbMax = 100.0",
"_____no_output_____"
],
[
"# Plot the consumption function at various transitory productivity shocks\nTranShkSet = LaborIntMargExample.TranShkGrid[t]\nbMin = bMin_orig\nB = np.linspace(bMin, bMax, 300)\nbMin = bMin_orig\nfor Shk in TranShkSet:\n B_temp = B + LaborIntMargExample.solution[t].bNrmMin(Shk)\n C = LaborIntMargExample.solution[t].cFunc(B_temp, Shk * np.ones_like(B_temp))\n plt.plot(B_temp, C)\n bMin = np.minimum(bMin, B_temp[0])\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Normalized consumption level\")\nplt.xlim(bMin, bMax - bMin_orig + bMin)\nplt.ylim(0.0, None)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the marginal consumption function at various transitory productivity shocks\nTranShkSet = LaborIntMargExample.TranShkGrid[t]\nbMin = bMin_orig\nB = np.linspace(bMin, bMax, 300)\nfor Shk in TranShkSet:\n B_temp = B + LaborIntMargExample.solution[t].bNrmMin(Shk)\n C = LaborIntMargExample.solution[t].cFunc.derivativeX(\n B_temp, Shk * np.ones_like(B_temp)\n )\n plt.plot(B_temp, C)\n bMin = np.minimum(bMin, B_temp[0])\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Marginal propensity to consume\")\nplt.xlim(bMin, bMax - bMin_orig + bMin)\nplt.ylim(0.0, 1.0)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the labor function at various transitory productivity shocks\nTranShkSet = LaborIntMargExample.TranShkGrid[t]\nbMin = bMin_orig\nB = np.linspace(0.0, bMax, 300)\nfor Shk in TranShkSet:\n B_temp = B + LaborIntMargExample.solution[t].bNrmMin(Shk)\n Lbr = LaborIntMargExample.solution[t].LbrFunc(B_temp, Shk * np.ones_like(B_temp))\n bMin = np.minimum(bMin, B_temp[0])\n plt.plot(B_temp, Lbr)\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Labor supply\")\nplt.xlim(bMin, bMax - bMin_orig + bMin)\nplt.ylim(0.0, 1.0)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the marginal value function at various transitory productivity shocks\npseudo_inverse = True\nTranShkSet = LaborIntMargExample.TranShkGrid[t]\nbMin = bMin_orig\nB = np.linspace(0.0, bMax, 300)\nfor Shk in TranShkSet:\n B_temp = B + LaborIntMargExample.solution[t].bNrmMin(Shk)\n if pseudo_inverse:\n vP = LaborIntMargExample.solution[t].vPfunc.cFunc(\n B_temp, Shk * np.ones_like(B_temp)\n )\n else:\n vP = LaborIntMargExample.solution[t].vPfunc(B_temp, Shk * np.ones_like(B_temp))\n bMin = np.minimum(bMin, B_temp[0])\n plt.plot(B_temp, vP)\nplt.xlabel(\"Beginning of period bank balances\")\nif pseudo_inverse:\n plt.ylabel(\"Pseudo inverse marginal value\")\nelse:\n plt.ylabel(\"Marginal value\")\nplt.xlim(bMin, bMax - bMin_orig + bMin)\nplt.ylim(0.0, None)\nplt.show()",
"_____no_output_____"
],
[
"if do_simulation:\n t_start = process_time()\n LaborIntMargExample.T_sim = 120 # Set number of simulation periods\n LaborIntMargExample.track_vars = [\"bNrmNow\", \"cNrmNow\"]\n LaborIntMargExample.initializeSim()\n LaborIntMargExample.simulate()\n t_end = process_time()\n print(\n \"Simulating \"\n + str(LaborIntMargExample.AgentCount)\n + \" intensive-margin labor supply consumers for \"\n + str(LaborIntMargExample.T_sim)\n + \" periods took \"\n + mystr(t_end - t_start)\n + \" seconds.\"\n )\n\n N = LaborIntMargExample.AgentCount\n CDF = np.linspace(0.0, 1, N)\n\n plt.plot(np.sort(LaborIntMargExample.cNrmNow), CDF)\n plt.xlabel(\n \"Consumption cNrm in \" + str(LaborIntMargExample.T_sim) + \"th simulated period\"\n )\n plt.ylabel(\"Cumulative distribution\")\n plt.xlim(0.0, None)\n plt.ylim(0.0, 1.0)\n plt.show()\n\n plt.plot(np.sort(LaborIntMargExample.LbrNow), CDF)\n plt.xlabel(\n \"Labor supply Lbr in \" + str(LaborIntMargExample.T_sim) + \"th simulated period\"\n )\n plt.ylabel(\"Cumulative distribution\")\n plt.xlim(0.0, 1.0)\n plt.ylim(0.0, 1.0)\n plt.show()\n\n plt.plot(np.sort(LaborIntMargExample.aNrmNow), CDF)\n plt.xlabel(\n \"End-of-period assets aNrm in \"\n + str(LaborIntMargExample.T_sim)\n + \"th simulated period\"\n )\n plt.ylabel(\"Cumulative distribution\")\n plt.xlim(0.0, 20.0)\n plt.ylim(0.0, 1.0)\n plt.show()",
"Simulating 10000 intensive-margin labor supply consumers for 120 periods took 1.7132 seconds.\n"
],
[
"# Make and solve a labor intensive margin consumer with a finite lifecycle\nLifecycleExample = LaborIntMargConsumerType(**init_labor_lifecycle)\nLifecycleExample.cycles = (\n 1 # Make this consumer live a sequence of periods exactly once\n)",
"_____no_output_____"
],
[
"start_time = process_time()\nLifecycleExample.solve()\nend_time = process_time()\nprint(\n \"Solving a lifecycle labor intensive margin consumer took \"\n + str(end_time - start_time)\n + \" seconds.\"\n)\nLifecycleExample.unpack('cFunc')",
"Solving a lifecycle labor intensive margin consumer took 0.05799699999999941 seconds.\n"
],
[
"bMax = 20.0",
"_____no_output_____"
],
[
"# Plot the consumption function in each period of the lifecycle, using median shock\nB = np.linspace(0.0, bMax, 300)\nb_min = np.inf\nb_max = -np.inf\nfor t in range(LifecycleExample.T_cycle):\n TranShkSet = LifecycleExample.TranShkGrid[t]\n Shk = TranShkSet[int(len(TranShkSet) // 2)] # Use the median shock, more or less\n B_temp = B + LifecycleExample.solution[t].bNrmMin(Shk)\n C = LifecycleExample.solution[t].cFunc(B_temp, Shk * np.ones_like(B_temp))\n plt.plot(B_temp, C)\n b_min = np.minimum(b_min, B_temp[0])\n b_max = np.maximum(b_min, B_temp[-1])\nplt.title(\"Consumption function across periods of the lifecycle\")\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Normalized consumption level\")\nplt.xlim(b_min, b_max)\nplt.ylim(0.0, None)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the marginal consumption function in each period of the lifecycle, using median shock\nB = np.linspace(0.0, bMax, 300)\nb_min = np.inf\nb_max = -np.inf\nfor t in range(LifecycleExample.T_cycle):\n TranShkSet = LifecycleExample.TranShkGrid[t]\n Shk = TranShkSet[int(len(TranShkSet) // 2)] # Use the median shock, more or less\n B_temp = B + LifecycleExample.solution[t].bNrmMin(Shk)\n MPC = LifecycleExample.solution[t].cFunc.derivativeX(\n B_temp, Shk * np.ones_like(B_temp)\n )\n plt.plot(B_temp, MPC)\n b_min = np.minimum(b_min, B_temp[0])\n b_max = np.maximum(b_min, B_temp[-1])\nplt.title(\"Marginal consumption function across periods of the lifecycle\")\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Marginal propensity to consume\")\nplt.xlim(b_min, b_max)\nplt.ylim(0.0, 1.0)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the labor supply function in each period of the lifecycle, using median shock\nB = np.linspace(0.0, bMax, 300)\nb_min = np.inf\nb_max = -np.inf\nfor t in range(LifecycleExample.T_cycle):\n TranShkSet = LifecycleExample.TranShkGrid[t]\n Shk = TranShkSet[int(len(TranShkSet) // 2)] # Use the median shock, more or less\n B_temp = B + LifecycleExample.solution[t].bNrmMin(Shk)\n L = LifecycleExample.solution[t].LbrFunc(B_temp, Shk * np.ones_like(B_temp))\n plt.plot(B_temp, L)\n b_min = np.minimum(b_min, B_temp[0])\n b_max = np.maximum(b_min, B_temp[-1])\nplt.title(\"Labor supply function across periods of the lifecycle\")\nplt.xlabel(\"Beginning of period bank balances\")\nplt.ylabel(\"Labor supply\")\nplt.xlim(b_min, b_max)\nplt.ylim(0.0, 1.01)\nplt.show()",
"_____no_output_____"
],
[
"# Plot the marginal value function at various transitory productivity shocks\npseudo_inverse = True\nTranShkSet = LifecycleExample.TranShkGrid[t]\nB = np.linspace(0.0, bMax, 300)\nb_min = np.inf\nb_max = -np.inf\nfor t in range(LifecycleExample.T_cycle):\n TranShkSet = LifecycleExample.TranShkGrid[t]\n Shk = TranShkSet[int(len(TranShkSet) / 2)] # Use the median shock, more or less\n B_temp = B + LifecycleExample.solution[t].bNrmMin(Shk)\n if pseudo_inverse:\n vP = LifecycleExample.solution[t].vPfunc.cFunc(\n B_temp, Shk * np.ones_like(B_temp)\n )\n else:\n vP = LifecycleExample.solution[t].vPfunc(B_temp, Shk * np.ones_like(B_temp))\n plt.plot(B_temp, vP)\n b_min = np.minimum(b_min, B_temp[0])\n b_max = np.maximum(b_min, B_temp[-1])\nplt.xlabel(\"Beginning of period bank balances\")\nif pseudo_inverse:\n plt.ylabel(\"Pseudo inverse marginal value\")\nelse:\n plt.ylabel(\"Marginal value\")\nplt.title(\"Marginal value across periods of the lifecycle\")\nplt.xlim(b_min, b_max)\nplt.ylim(0.0, None)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba2835c660f634a2d301f2b6895e5bdf7ea8d9e
| 948,903 |
ipynb
|
Jupyter Notebook
|
master.ipynb
|
cpglenn/m5-forecasting-accuracy
|
1763d47f90b7792583455aa3bce03fca29e48341
|
[
"MIT"
] | null | null | null |
master.ipynb
|
cpglenn/m5-forecasting-accuracy
|
1763d47f90b7792583455aa3bce03fca29e48341
|
[
"MIT"
] | null | null | null |
master.ipynb
|
cpglenn/m5-forecasting-accuracy
|
1763d47f90b7792583455aa3bce03fca29e48341
|
[
"MIT"
] | null | null | null | 609.44316 | 236,244 | 0.935831 |
[
[
[
"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom statsmodels.distributions.empirical_distribution import ECDF\nfrom datetime import date, datetime, timedelta, timezone\n%matplotlib inline\n\n#set default plotting styles\nsns.set(rc={'figure.figsize':(15, 6)})\nsns.set_style(\"dark\")\nfig_dims = (15, 6)",
"_____no_output_____"
],
[
"print(os.getcwd())\nsales_train_validation = pd.read_csv(\"./datasets/sales_train_validation.csv\")\nsales_train_validation.head()",
"/Users/christopherglenn/Dev/m5-forecasting-accuracy\n"
],
[
"master = sales_train_validation.melt(id_vars=['id', 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id'], var_name='d')",
"_____no_output_____"
],
[
"calendar = pd.read_csv(\"./datasets/calendar.csv\")\ntemp = calendar[['date', 'd']]\ntemp\n#calendar.set_index('date', inplace=True)\n#temp = pd.DataFrame(calendar['d'])",
"_____no_output_____"
],
[
"master = pd.merge(master, temp, on='d', how='inner')",
"_____no_output_____"
],
[
"master['date'] = pd.to_datetime(master['date'])\nmaster = master.rename(columns={'value': 'unit_sales'})\nmaster.head()",
"_____no_output_____"
],
[
"calendar = pd.read_csv(\"./datasets/calendar.csv\")\ncalendar['date'] = pd.to_datetime(calendar['date'])\nmaster = pd.merge(master, calendar, on='date', how='left')\nmaster.head()",
"_____no_output_____"
],
[
"id_sales = master.groupby(['date', 'id'])['unit_sales'].agg('sum')\nid_sales",
"_____no_output_____"
],
[
"store_sales = master.groupby(['date', 'store_id'], as_index=False)['unit_sales'].agg('sum')\nstore_sales = pd.DataFrame(store_sales)\nstore_sales['date'] = pd.to_datetime(store_sales['date'])\nstore_sales",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=fig_dims)\nsns.lineplot(data=store_sales, \n x='date', \n y='unit_sales', \n hue='store_id', \n ax=ax, \n alpha=0.6)\nplt.show()",
"_____no_output_____"
],
[
"df2 = store_sales\ndf2 = df2.set_index('date')\n# fig, ax = plt.subplots(figsize=fig_dims)\n# sns.relplot(x=\"date\", \n# y=\"unit_sales\",\n# hue=\"store_id\", \n# row=\"store_id\",\n# facet_kws=dict(sharex=True),\n# kind=\"reg\", \n# legend=\"full\", \n# data=store_sales)\n# sns.lmplot(x='date',\n# y='unit_sales',\n# hue='store_id', \n# data=store_sales)\n#sns.regplot(x=\"date\", y=\"unit_sales\", data=store_sales)\n#sns.lmplot(x=\"date\", y=\"unit_sales\", hue=\"store_id\", data=store_sales)",
"_____no_output_____"
],
[
"df2.loc[:, 'unit_sales'].plot(linewidth=0.5)\nplt.show()",
"_____no_output_____"
],
[
"sns.violinplot(data=store_sales,\n x='store_id', \n y='unit_sales', \n inner=None)\nplt.show()",
"_____no_output_____"
],
[
"sns.boxplot(data=store_sales, \n x='store_id', \n y='unit_sales')\nplt.show()",
"_____no_output_____"
],
[
"stores = master['store_id'].unique()\nfor store in stores:\n temp = store_sales[store_sales['store_id'] == store]\n sns.kdeplot(temp['unit_sales'], cumulative=True)\n plt.title('{0} - CDF'.format(store))\n plt.show()",
"_____no_output_____"
],
[
"stores = master['store_id'].unique()\nfor store in stores:\n temp = store_sales[store_sales['store_id'] == store]\n sns.kdeplot(temp['unit_sales'])\n plt.title('{0} - CDF'.format(store))\n plt.show()",
"_____no_output_____"
],
[
"master.head()\n#sns.heatmap(master.corr(), square=True, cmap='RdYlGn')",
"_____no_output_____"
],
[
"from sklearn.linear_model import Lasso\nX = master.drop('unit_sales', axis=1).values\ny = master['unit_sales'].values\nlasso = Lasso(alpha=0.4, normalize=True)\nlasso.fit(X, y)\nlasso_coef = lasso.coef_\nprint(lasso_coef)\n\n# Plot the coefficients\nplt.plot(range(len(master.columns)), lasso_coef)\nplt.xticks(range(len(master.columns)), master.columns.values, rotation=60)\nplt.margins(0.02)\nplt.show()",
"_____no_output_____"
],
[
"master.columns",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba28abc86935b5b4bb02bf23e84353bd52a3068
| 1,014 |
ipynb
|
Jupyter Notebook
|
tteste.ipynb
|
IsraelAugustods/teste1
|
d6ccf718c8b117dd76dd6da9a5b92fe131269fe3
|
[
"MIT"
] | null | null | null |
tteste.ipynb
|
IsraelAugustods/teste1
|
d6ccf718c8b117dd76dd6da9a5b92fe131269fe3
|
[
"MIT"
] | null | null | null |
tteste.ipynb
|
IsraelAugustods/teste1
|
d6ccf718c8b117dd76dd6da9a5b92fe131269fe3
|
[
"MIT"
] | null | null | null | 17.789474 | 48 | 0.511834 |
[
[
[
"print('Vem comigo vou contigo')",
"Vem comigo vou contigo\n"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cba2a8b1941095648a003390e7398da937067910
| 9,403 |
ipynb
|
Jupyter Notebook
|
5 - synthetic-data-applications/time-series/missing-values-imputation/2_Factors.ipynb
|
ydataai/Blog
|
7994727deb1e1ca35e06c6fe4680482920b95855
|
[
"MIT"
] | null | null | null |
5 - synthetic-data-applications/time-series/missing-values-imputation/2_Factors.ipynb
|
ydataai/Blog
|
7994727deb1e1ca35e06c6fe4680482920b95855
|
[
"MIT"
] | null | null | null |
5 - synthetic-data-applications/time-series/missing-values-imputation/2_Factors.ipynb
|
ydataai/Blog
|
7994727deb1e1ca35e06c6fe4680482920b95855
|
[
"MIT"
] | null | null | null | 26.487324 | 166 | 0.545252 |
[
[
[
"# Factors\nThis notebook calculates the factors used to add seasonality patterns to reconstructed data.\n\nFactors are multiplicative scalars applied for a numerical feature for each groupby value (e.g. average monthly windspeed ratio as percentage of annual average)",
"_____no_output_____"
],
[
"## 0 - Setup",
"_____no_output_____"
],
[
"### 0.1 - Imports\nLoad the necessary dependencies.",
"_____no_output_____"
]
],
[
[
"%%capture\nfrom ydata.connectors import GCSConnector\nfrom ydata.utils.formats import read_json\nfrom typing import List\nfrom pandas import concat",
"_____no_output_____"
]
],
[
[
"## 0.2 - Auxiliary Functions\nThe auxiliary functions are custom-designed utilities developed for the use case.",
"_____no_output_____"
]
],
[
[
"from factors import save_json",
"_____no_output_____"
]
],
[
[
"## 1 - Load Data",
"_____no_output_____"
]
],
[
[
"# Load the credentials\ncredentials = read_json('gcs_credentials.json')\n\n# Create the connector for Google Cloud Storage\nconnector = GCSConnector('ydatasynthetic', gcs_credentials=credentials)",
"_____no_output_____"
]
],
[
[
"## 2 - Calculate Factors\nCalculate the average windspeed per month for meters in relevant provinces.",
"_____no_output_____"
]
],
[
[
"YEARS = [2018, 2019, 2020, 2021]",
"_____no_output_____"
],
[
"# Internal IDs that identify stations which are in the same provinces\n\nmeter_ids = read_json('meter_ids.json')",
"_____no_output_____"
],
[
"def get_monthly_avg_per_year(connector: GCSConnector, meter_ids: List, years=YEARS):\n \"Calculates the monthly factor over the anual average, per year, for meters within same provinces as the original data.\"\n\n # create a map of each month to corresponding index\n meses = ['january', 'february', 'march', 'april', 'may', 'june', 'july',\n 'august', 'september', 'october', 'november', 'december']\n\n months = {k : v for (k, v) in zip(meses, range(1, len(meses) + 1))}\n\n factors = [] # will contain a Series of monthly averages over anual, per each year\n\n for year in years:\n filepath = f'gs://pipelines_artifacts/wind_measurements_pipeline/data/df_for_factors_{str(year)}.csv'\n df = connector.read_file(filepath, assume_missing=True).to_pandas().set_index('name_station') # read the yearly monthly averages\n df = df[df.index.isin(meter_ids)] # filter for meters in same provinces\n df = df.dropna() # drop the missing values\n for month in months.keys(): # calculate factor as ratio of monthly average\n df[month] = df[month] / df['yearly'] # over the anual average\n factors.append(df[months.keys()].mean().copy())\n\n # Aggregate data\n agg_data = concat(factors, axis=1)\n agg_data.columns = years\n agg_data = agg_data.rename(index=months)\n agg_data['avg'] = agg_data.mean(axis=1)\n return agg_data",
"_____no_output_____"
],
[
"factors = get_monthly_avg_per_year(connector=connector, meter_ids=meter_ids)",
"_____no_output_____"
]
],
[
[
"## 3 - Store Data\nSave factors as a JSON of windspeed factor per each month.",
"_____no_output_____"
]
],
[
[
"# Store the average per month of year\nsave_json({'windspeed': factors['avg'].to_dict()}, 'df_factors_2018_2021.json')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba2a956f8fae00652753605f6a61fcc8326d600
| 4,772 |
ipynb
|
Jupyter Notebook
|
datasets/Cohen_2006/process_Cohen_datasets_local.ipynb
|
terrymyc/automated-systematic-review-datasets
|
111272846d92b548f08d42e7cf8a6c2274aaeb4a
|
[
"MIT"
] | 24 |
2020-07-02T12:14:05.000Z
|
2022-03-30T23:07:26.000Z
|
datasets/Cohen_2006/process_Cohen_datasets_local.ipynb
|
terrymyc/automated-systematic-review-datasets
|
111272846d92b548f08d42e7cf8a6c2274aaeb4a
|
[
"MIT"
] | 33 |
2020-02-20T10:24:32.000Z
|
2022-03-22T14:08:41.000Z
|
datasets/Cohen_2006/process_Cohen_datasets_local.ipynb
|
terrymyc/automated-systematic-review-datasets
|
111272846d92b548f08d42e7cf8a6c2274aaeb4a
|
[
"MIT"
] | 10 |
2020-07-24T11:47:51.000Z
|
2022-03-06T04:35:57.000Z
| 33.843972 | 146 | 0.628248 |
[
[
[
"import numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\n# visualization\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator",
"_____no_output_____"
]
],
[
[
"## Read and clean datasets",
"_____no_output_____"
]
],
[
[
"def clean_Cohen_datasets(path):\n \"\"\"Read local raw datasets and clean them\"\"\"\n \n # read datasets\n df = pd.read_csv(path)\n \n # rename columns\n df.rename(columns={\"abstracts\":\"abstract\", \"label1\":\"label_abstract_screening\", \"label2\":\"label_included\"}, inplace=True)\n \n # recode inclusion indicators\n df.label_abstract_screening = np.where(df.label_abstract_screening == \"I\", 1, 0)\n df.label_included = np.where(df.label_included == \"I\", 1, 0)\n \n # add record id\n df.insert(0, \"record_id\", df.index + 1)\n \n return df",
"_____no_output_____"
],
[
"df_ACEInhibitors = clean_Cohen_datasets(\"raw/ACEInhibitors.csv\")\ndf_ADHD = clean_Cohen_datasets(\"raw/ADHD.csv\")\ndf_Antihistamines = clean_Cohen_datasets(\"raw/Antihistamines.csv\")\ndf_AtypicalAntipsychotics = clean_Cohen_datasets(\"raw/AtypicalAntipsychotics.csv\")\ndf_BetaBlockers = clean_Cohen_datasets(\"raw/BetaBlockers.csv\")\ndf_CalciumChannelBlockers = clean_Cohen_datasets(\"raw/CalciumChannelBlockers.csv\")\ndf_Estrogens = clean_Cohen_datasets(\"raw/Estrogens.csv\")\ndf_NSAIDS = clean_Cohen_datasets(\"raw/NSAIDS.csv\")\ndf_Opiods = clean_Cohen_datasets(\"raw/Opiods.csv\")\ndf_OralHypoglycemics = clean_Cohen_datasets(\"raw/OralHypoglycemics.csv\")\ndf_ProtonPumpInhibitors = clean_Cohen_datasets(\"raw/ProtonPumpInhibitors.csv\")\ndf_SkeletalMuscleRelaxants = clean_Cohen_datasets(\"raw/SkeletalMuscleRelaxants.csv\")\ndf_Statins = clean_Cohen_datasets(\"raw/Statins.csv\")\ndf_Triptans = clean_Cohen_datasets(\"raw/Triptans.csv\")\ndf_UrinaryIncontinence = clean_Cohen_datasets(\"raw/UrinaryIncontinence.csv\")",
"_____no_output_____"
]
],
[
[
"## Export datasets",
"_____no_output_____"
]
],
[
[
"Path(\"output/local\").mkdir(parents=True, exist_ok=True)\ndf_ACEInhibitors.to_csv(\"output/local/ACEInhibitors.csv\", index=False)\ndf_ADHD.to_csv(\"output/local/ADHD.csv\", index=False)\ndf_Antihistamines.to_csv(\"output/local/Antihistamines.csv\", index=False)\ndf_AtypicalAntipsychotics.to_csv(\"output/local/AtypicalAntipsychotics.csv\", index=False)\ndf_BetaBlockers.to_csv(\"output/local/BetaBlockers.csv\", index=False)\ndf_CalciumChannelBlockers.to_csv(\"output/local/CalciumChannelBlockers.csv\", index=False)\ndf_Estrogens.to_csv(\"output/local/Estrogens.csv\", index=False)\ndf_NSAIDS.to_csv(\"output/local/NSAIDS.csv\", index=False)\ndf_Opiods.to_csv(\"output/local/Opiods.csv\", index=False)\ndf_OralHypoglycemics.to_csv(\"output/local/OralHypoglycemics.csv\", index=False)\ndf_ProtonPumpInhibitors.to_csv(\"output/local/ProtonPumpInhibitors.csv\", index=False)\ndf_SkeletalMuscleRelaxants.to_csv(\"output/local/SkeletalMuscleRelaxants.csv\", index=False)\ndf_Statins.to_csv(\"output/local/Statins.csv\", index=False)\ndf_Triptans.to_csv(\"output/local/Triptans.csv\", index=False)\ndf_UrinaryIncontinence.to_csv(\"output/local/UrinaryIncontinence.csv\", index=False)",
"_____no_output_____"
]
],
[
[
"## Dataset statistics",
"_____no_output_____"
],
[
"See `process_Cohen_datasets_online.ipynb`.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cba2ba2d2c813491df809f0b8fa68c1c8e32bba8
| 1,449 |
ipynb
|
Jupyter Notebook
|
Notebook/Quickhull.ipynb
|
cc7768/CHull2d.jl
|
8a3d6bb0e36c7e99bf79fe6e4cba286f53ebdb02
|
[
"MIT"
] | 7 |
2016-06-01T17:54:49.000Z
|
2021-10-03T14:32:28.000Z
|
Notebook/Quickhull.ipynb
|
cc7768/CHull2d.jl
|
8a3d6bb0e36c7e99bf79fe6e4cba286f53ebdb02
|
[
"MIT"
] | 3 |
2016-01-22T22:11:23.000Z
|
2016-11-28T16:17:33.000Z
|
Notebook/Quickhull.ipynb
|
cc7768/CHull2d.jl
|
8a3d6bb0e36c7e99bf79fe6e4cba286f53ebdb02
|
[
"MIT"
] | 2 |
2016-07-13T15:52:34.000Z
|
2019-12-31T23:54:59.000Z
| 28.411765 | 404 | 0.616977 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cba2c6ca4ff170886d6edb8cc40056451afcb739
| 315,224 |
ipynb
|
Jupyter Notebook
|
2_3_3_Exploracion_visual_de_datos.ipynb
|
jpabloglez/Master_IA_Sanidad
|
0477c36d49716aa174db9f7760637f7b6c923dd8
|
[
"MIT"
] | null | null | null |
2_3_3_Exploracion_visual_de_datos.ipynb
|
jpabloglez/Master_IA_Sanidad
|
0477c36d49716aa174db9f7760637f7b6c923dd8
|
[
"MIT"
] | null | null | null |
2_3_3_Exploracion_visual_de_datos.ipynb
|
jpabloglez/Master_IA_Sanidad
|
0477c36d49716aa174db9f7760637f7b6c923dd8
|
[
"MIT"
] | null | null | null | 733.07907 | 180,818 | 0.941413 |
[
[
[
"<a href=\"https://colab.research.google.com/github/jpabloglez/Master_IA_Sanidad/blob/main/2_3_3_Exploracion_visual_de_datos.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Exploración de datos",
"_____no_output_____"
],
[
"## Conjunto de datos de Diabetes",
"_____no_output_____"
]
],
[
[
"\"\"\"\nEn este cuaderno trabajaremos con el Diabetes Dataset de Sci-Kit Learn\nhttps://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset\nY utilizaremos la librería Seaborn para la visualización de datos\nhttps://seaborn.pydata.org/\n\"\"\"\n\ndiabetes = Diabetes.get_tabular_dataset()\ndiabetes_df = diabetes.to_pandas_dataframe()\n\nprint(\"INFO\", diabetes_df.info())\n\nfrom sklearn.datasets import load_diabetes\nimport pandas as pd\nimport seaborn as sns\nsns.set_style(\"whitegrid\") # muestra la cuadrícula de posición en los gráficos\nimport matplotlib.pyplot as plt\npd.set_option('display.max_columns', None) # Esta opción permite que se muestren\n# todas las columnas en el dataset\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\ndata = load_diabetes()\ndf = pd.DataFrame(data=data.data, columns=data.feature_names)\n\nprint(df.describe())\nprint(\"\\n\", 50 * \"*\", \"\\n Descripción del dataset: \\n\\n\",data.DESCR)",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 442 entries, 0 to 441\nData columns (total 11 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 AGE 442 non-null int64 \n 1 SEX 442 non-null int64 \n 2 BMI 442 non-null float64\n 3 BP 442 non-null float64\n 4 S1 442 non-null int64 \n 5 S2 442 non-null float64\n 6 S3 442 non-null float64\n 7 S4 442 non-null float64\n 8 S5 442 non-null float64\n 9 S6 442 non-null int64 \n 10 Y 442 non-null int64 \ndtypes: float64(6), int64(5)\nmemory usage: 38.1 KB\nINFO None\n age sex bmi bp s1 \\\ncount 4.420000e+02 4.420000e+02 4.420000e+02 4.420000e+02 4.420000e+02 \nmean -3.634285e-16 1.308343e-16 -8.045349e-16 1.281655e-16 -8.835316e-17 \nstd 4.761905e-02 4.761905e-02 4.761905e-02 4.761905e-02 4.761905e-02 \nmin -1.072256e-01 -4.464164e-02 -9.027530e-02 -1.123996e-01 -1.267807e-01 \n25% -3.729927e-02 -4.464164e-02 -3.422907e-02 -3.665645e-02 -3.424784e-02 \n50% 5.383060e-03 -4.464164e-02 -7.283766e-03 -5.670611e-03 -4.320866e-03 \n75% 3.807591e-02 5.068012e-02 3.124802e-02 3.564384e-02 2.835801e-02 \nmax 1.107267e-01 5.068012e-02 1.705552e-01 1.320442e-01 1.539137e-01 \n\n s2 s3 s4 s5 s6 \ncount 4.420000e+02 4.420000e+02 4.420000e+02 4.420000e+02 4.420000e+02 \nmean 1.327024e-16 -4.574646e-16 3.777301e-16 -3.830854e-16 -3.412882e-16 \nstd 4.761905e-02 4.761905e-02 4.761905e-02 4.761905e-02 4.761905e-02 \nmin -1.156131e-01 -1.023071e-01 -7.639450e-02 -1.260974e-01 -1.377672e-01 \n25% -3.035840e-02 -3.511716e-02 -3.949338e-02 -3.324879e-02 -3.317903e-02 \n50% -3.819065e-03 -6.584468e-03 -2.592262e-03 -1.947634e-03 -1.077698e-03 \n75% 2.984439e-02 2.931150e-02 3.430886e-02 3.243323e-02 2.791705e-02 \nmax 1.987880e-01 1.811791e-01 1.852344e-01 1.335990e-01 1.356118e-01 \n\n ************************************************** \n Descripción del dataset: \n\n .. _diabetes_dataset:\n\nDiabetes dataset\n----------------\n\nTen baseline variables, age, sex, body mass index, average blood\npressure, and six blood serum measurements were obtained for each of n =\n442 diabetes patients, as well as the response of interest, a\nquantitative measure of disease progression one year after baseline.\n\n**Data Set Characteristics:**\n\n :Number of Instances: 442\n\n :Number of Attributes: First 10 columns are numeric predictive values\n\n :Target: Column 11 is a quantitative measure of disease progression one year after baseline\n\n :Attribute Information:\n - age age in years\n - sex\n - bmi body mass index\n - bp average blood pressure\n - s1 tc, total serum cholesterol\n - s2 ldl, low-density lipoproteins\n - s3 hdl, high-density lipoproteins\n - s4 tch, total cholesterol / HDL\n - s5 ltg, possibly log of serum triglycerides level\n - s6 glu, blood sugar level\n\nNote: Each of these 10 feature variables have been mean centered and scaled by the standard deviation times `n_samples` (i.e. the sum of squares of each column totals 1).\n\nSource URL:\nhttps://www4.stat.ncsu.edu/~boos/var.select/diabetes.html\n\nFor more information see:\nBradley Efron, Trevor Hastie, Iain Johnstone and Robert Tibshirani (2004) \"Least Angle Regression,\" Annals of Statistics (with discussion), 407-499.\n(https://web.stanford.edu/~hastie/Papers/LARS/LeastAngle_2002.pdf)\n"
],
[
"# El método DESCR del dataset nos permite ampliar la información sobre el dataset de trabajo\n# Vamos a renombrar las columnas siguiendo la nomenclatura de las variables clínicas\ndf = df.rename(columns={'s1': 'tc', 's2': 'ldl', 's3': 'hdl', 's4': 'tch', 's5': 'ltg', 's6': 'glu'})\nprint(df)\n# Nota, como habrás observado, este dataset ha sido previamente normalizado \n# para facilitar la aplicación de ciertos modelos de aprendizaje automático",
" age sex bmi bp tc ldl hdl \\\n0 0.038076 0.050680 0.061696 0.021872 -0.044223 -0.034821 -0.043401 \n1 -0.001882 -0.044642 -0.051474 -0.026328 -0.008449 -0.019163 0.074412 \n2 0.085299 0.050680 0.044451 -0.005671 -0.045599 -0.034194 -0.032356 \n3 -0.089063 -0.044642 -0.011595 -0.036656 0.012191 0.024991 -0.036038 \n4 0.005383 -0.044642 -0.036385 0.021872 0.003935 0.015596 0.008142 \n.. ... ... ... ... ... ... ... \n437 0.041708 0.050680 0.019662 0.059744 -0.005697 -0.002566 -0.028674 \n438 -0.005515 0.050680 -0.015906 -0.067642 0.049341 0.079165 -0.028674 \n439 0.041708 0.050680 -0.015906 0.017282 -0.037344 -0.013840 -0.024993 \n440 -0.045472 -0.044642 0.039062 0.001215 0.016318 0.015283 -0.028674 \n441 -0.045472 -0.044642 -0.073030 -0.081414 0.083740 0.027809 0.173816 \n\n tch ltg glu \n0 -0.002592 0.019908 -0.017646 \n1 -0.039493 -0.068330 -0.092204 \n2 -0.002592 0.002864 -0.025930 \n3 0.034309 0.022692 -0.009362 \n4 -0.002592 -0.031991 -0.046641 \n.. ... ... ... \n437 -0.002592 0.031193 0.007207 \n438 0.034309 -0.018118 0.044485 \n439 -0.011080 -0.046879 0.015491 \n440 0.026560 0.044528 -0.025930 \n441 -0.039493 -0.004220 0.003064 \n\n[442 rows x 10 columns]\n"
]
],
[
[
"## Gráfico de dispersión",
"_____no_output_____"
]
],
[
[
"# Veámos la cómo se relacionan los niveles de LDL y el Índice de Masa Corporal (BMI)\nfig = plt.figure(1, figsize=(15,5))\nfig.add_subplot(121)\nsns.scatterplot(data=data, x=df['bmi'], y=df['ldl'], palette='Pastel1', legend='full')\nplt.xlabel('BMI')\nplt.ylabel('LDL')\n\n# Para evaluar la separación entre datos, necesitaríamos etiqueta categórica para \n# cada variable, hagamos una dummy\nimport numpy as np\nclass_l = np.random.randint(2, size=len(df['bmi'].values))\ndf_l = df\ndf_l['class'] = class_l\nfig.add_subplot(122)\nsns.scatterplot(data=df_l, x=df_l['bmi'], y=df_l['ldl'], palette='Pastel1', legend='full', hue='class')\n# Como vemos, al haber utilizado una distribución aleatoria los datos aparecen mezclados",
"_____no_output_____"
]
],
[
[
"## Gráficos de cajas",
"_____no_output_____"
]
],
[
[
"# Por legibilidad y para reducir el tiempo de ejecución \n# reducimos el dataset a las siguientes tres variables\ndf_s = df[['age', 'bmi', 'ldl']]\nsns.boxplot(data=df_s)",
"_____no_output_____"
]
],
[
[
"## Gráficos de distribución",
"_____no_output_____"
]
],
[
[
"from scipy.stats import norm # Usamos la función normal de scipy stats para\n# ajustar el histograma de la distribución\npars = norm.fit(df['bmi'].values)\nsns.distplot(df['bmi'], kde=False, fit=norm, fit_kws={'color': 'r', 'linewidth': 2.5})\nplt.title(\"Mean: {:.2f}, Sigma: {:.2f}\".format(pars[0], pars[1]))",
"_____no_output_____"
]
],
[
[
"## Gráficos de pares",
"_____no_output_____"
]
],
[
[
"df_l = df_l[['age', 'bmi', 'ldl', 'class']]\nsns.pairplot(df_l, palette='Pastel1', hue='class')\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba2c6e28bb58eeb59c04137f6cd54aec308fd53
| 714,977 |
ipynb
|
Jupyter Notebook
|
python homework/Thermodynamics.ipynb
|
LesnyakVlad/DAFE_Python_914
|
bdbe2722c71d8b74d8f7dc2f57cd3efb434e9e10
|
[
"Unlicense"
] | null | null | null |
python homework/Thermodynamics.ipynb
|
LesnyakVlad/DAFE_Python_914
|
bdbe2722c71d8b74d8f7dc2f57cd3efb434e9e10
|
[
"Unlicense"
] | 7 |
2021-05-08T22:02:59.000Z
|
2021-05-13T22:44:27.000Z
|
python homework/Thermodynamics.ipynb
|
LesnyakVlad/DAFE_Python_914
|
bdbe2722c71d8b74d8f7dc2f57cd3efb434e9e10
|
[
"Unlicense"
] | 13 |
2021-02-13T07:32:10.000Z
|
2021-05-15T09:09:08.000Z
| 87.802653 | 3,968 | 0.816467 |
[
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML",
"_____no_output_____"
],
[
"N = 10\nk = 1.38*10**(-23)\nm = 6.645*10**(-27)\nT = 5000\ndt = 0.0001\n\nxmin = 0.\nxmax = 10.\nymin = 0.\nymax = 10.",
"_____no_output_____"
],
[
"def f():\n global T,N,k,m,dt, xmin, xmax, ymin, ymax\n Vav = np.sqrt(3*k*T/m/N)\n vx = np.random.uniform(-Vav,Vav,N)\n vy = np.sqrt((-1)*(vx**2 - Vav**2))\n x = np.random.uniform(xmin, xmax, N)\n y = np.random.uniform(ymin, ymax, N)\n yield (x,y)\n while(True):\n for i in range(N): \n if (x[i] <= xmin or x[i] >= xmax):\n vx[i] = (-1)*vx[i]\n x[i] += vx[i]*dt \n else:\n \tx[i] += vx[i]*dt\n \n if (y[i] <= ymin or y[i] >= ymax):\n vy[i] = (-1)*vy[i]\n y[i] += vy[i]*dt\n yield (x,y)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))\nline = ax.scatter([], [], lw = 2)\ngen = f()",
"_____no_output_____"
],
[
"def init():\n global xmin, xmax, ymin, ymax\n ax.clear()\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n line = ax.scatter([], [], lw = 2)\n return line,",
"_____no_output_____"
],
[
"def animate(i):\n global xmin, xmax, ymin, ymax, gen\n xy = next(gen)\n ax.clear()\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n line = ax.scatter([xy[0]], [xy[1]], lw = 2)\n return line,",
"_____no_output_____"
],
[
"ani = animation.FuncAnimation(\n fig, animate, init_func=init, interval=10)\n\nHTML(ani.to_jshtml())",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba2d5b8f17dc410b77b2b460469df257e2d8e06
| 5,641 |
ipynb
|
Jupyter Notebook
|
Games/.ipynb_checkpoints/ 'Tower of Hanoi' using recursion-checkpoint.ipynb
|
AkashKV-1998/Program
|
a78694f7501a268c9bb1cf663a63e10aa5b5b8d2
|
[
"Apache-2.0"
] | null | null | null |
Games/.ipynb_checkpoints/ 'Tower of Hanoi' using recursion-checkpoint.ipynb
|
AkashKV-1998/Program
|
a78694f7501a268c9bb1cf663a63e10aa5b5b8d2
|
[
"Apache-2.0"
] | null | null | null |
Games/.ipynb_checkpoints/ 'Tower of Hanoi' using recursion-checkpoint.ipynb
|
AkashKV-1998/Program
|
a78694f7501a268c9bb1cf663a63e10aa5b5b8d2
|
[
"Apache-2.0"
] | null | null | null | 27.383495 | 182 | 0.568693 |
[
[
[
"# To solve 'Tower of Hanoi' using recursion",
"_____no_output_____"
],
[
"______",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
" Source pillar Helper pillar Destination pillar",
"_____no_output_____"
],
[
"Let the number of disk $(n)$ be 3, and the first piller is source, middle piller is helper piller, and last pillar is destination pillar",
"_____no_output_____"
],
[
"The objective is to move the entire disk to destination pillar, obeying the following rules:\n\n1) Only one disk can be moved at a time.\n\n2) Each move consists of taking the upper disk from one of the pillar and move to another pillar.\n\n3) No bigger disk may be placed on top of a smaller disk.",
"_____no_output_____"
],
[
"Now,",
"_____no_output_____"
],
[
"When we consider only 3 disks on source pillar. We can complete the task within $2^3-1= 7$ moves",
"_____no_output_____"
],
[
"Steps should be followed to move the disk from source pillar to destination pillar:\n\nStep 1 - Move top disk or smaller disk to destination pillar\n\nStep 2 - Move second disk or second largest disk to helper pillar\n\nStep 3 - Move the smaller disk from destination pillar to helper pillar\n\nNow, the bigger disk remains at source pillar and other disks is in helper pillar. When we consider n = 3 we can say that n-1 (i.e, 3-1 = 2) disks is moved to helper pillar.\n\nStep 4 - Move the bigger disk from source to destination pillar\n\nStep 5 - Now move the smaller disk from helper pillar to source pillar\n\nStep 6 - Move the second bigger disk from helper pillar to destination pillar \n\nStep 7 - Finally move smaller disk from source pillar to destination pillar\n\n\nSo, Now the task is completed and by considering steps 5, 6 and 7 we can say that n-1 disk is moved to destination pillar",
"_____no_output_____"
],
[
"### Recursive Algorithm for 'Tower of Hanoi':",
"_____no_output_____"
],
[
"By understanding above steps we can write algorithm for recursion. They are:\n\nStep 1 - Move (n-1) disk to helper pillar\n\nStep 2 - Move bigger disk from source pillar to destination pilar\n\nStep 3 - Move (n-1) disk to destination pillar",
"_____no_output_____"
],
[
"### PROGRAM:",
"_____no_output_____"
]
],
[
[
"def Tower_of_hanoi(n , source_pillar, destination_pillar, helper_pillar):\n\n# Base case: If only one disk is in source pillar. Then we can directly move disk from source pillar to distination pillar\n\n if n == 1: \n \n print (\"Move disk 1 from\", source_pillar,\"to\",destination_pillar)\n return\n \n# Or if there is no disk in source pillar:\n\n elif n == 0:\n print(\"No disk in Tower of Hanoi\")\n return\n \n Tower_of_hanoi(n-1, source_pillar, helper_pillar, destination_pillar) \n print (\"Move disk\",n,\"from\", source_pillar,\"to\",destination_pillar)\n Tower_of_hanoi(n-1, helper_pillar, destination_pillar, source_pillar)",
"_____no_output_____"
],
[
"n = int(input(\"Number of disk in Tower of Hanoi: \"))\n\nprint()\nTower_of_hanoi(n, 'source pillar', 'destination pillar', 'helper pillar')\nprint()\nprint(\"Task Completed!\")",
"Number of disk in Tower of Hanoi: 3\n\nMove disk 1 from source pillar to destination pillar\nMove disk 2 from source pillar to helper pillar\nMove disk 1 from destination pillar to helper pillar\nMove disk 3 from source pillar to destination pillar\nMove disk 1 from helper pillar to source pillar\nMove disk 2 from helper pillar to destination pillar\nMove disk 1 from source pillar to destination pillar\n\nTask Completed!\n"
]
],
[
[
"_____",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cba2e3b768bbcb07ceebe0b762ddb4432c718b81
| 145,182 |
ipynb
|
Jupyter Notebook
|
radspots/lc_fit.ipynb
|
bmorris3/rms
|
4239e488f6fae9869782ffbac9f39747b58afdda
|
[
"MIT"
] | 1 |
2018-02-13T19:51:47.000Z
|
2018-02-13T19:51:47.000Z
|
radspots/lc_fit.ipynb
|
bmorris3/rms
|
4239e488f6fae9869782ffbac9f39747b58afdda
|
[
"MIT"
] | null | null | null |
radspots/lc_fit.ipynb
|
bmorris3/rms
|
4239e488f6fae9869782ffbac9f39747b58afdda
|
[
"MIT"
] | null | null | null | 435.981982 | 62,252 | 0.937981 |
[
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.time import Time\nimport astropy.units as u\n\nfrom rms import Planet",
"_____no_output_____"
],
[
"times, spotted_lc, spotless_lc = np.loadtxt('ring.txt', unpack=True)",
"_____no_output_____"
],
[
"d = Planet(per=4.049959, inc=90, a=39.68, t0=0, \n rp=(0.3566/100)**0.5, lam=0, ecc=0, w=90)\n\nt14 = d.per/np.pi * np.arcsin( np.sqrt((1 + d.rp)**2 - d.b**2) / np.sin(np.radians(d.inc)) / d.a)\nt23 = d.per/np.pi * np.arcsin( np.sqrt((1 - d.rp)**2 - d.b**2) / np.sin(np.radians(d.inc)) / d.a)\n\n# plt.plot(times, spotted_lc - spotless_lc)\nplt.plot(times, spotless_lc)\n\nplt.plot(times, spotted_lc)\n\nfor i in [1, -1]:\n plt.axvline(i*t14/2, color='k')\n plt.axvline(i*t23/2, color='k')",
"_____no_output_____"
],
[
"from scipy.optimize import fmin_l_bfgs_b\nfrom batman import TransitModel\nfrom copy import deepcopy\n\nd.limb_dark = 'quadratic'\nd.u = [0.2, 0.1]\nd.fp = 0\n\ndef transit_model(times, rprs, params):\n trial_params = deepcopy(params)\n params.rp = rprs\n m = TransitModel(params, times, supersample_factor=7, \n exp_time=times[1]-times[0])\n lc = m.light_curve(params)\n return lc\n\ndef chi2(p, times, y, params):\n rprs = p[0]\n return np.sum((transit_model(times, rprs, params) - y)**2)",
"_____no_output_____"
],
[
"initp =[d.rp]\nd0 = fmin_l_bfgs_b(chi2, initp, approx_grad=True, \n args=(times, spotless_lc, d), \n bounds=[[0, 0.5]])[0][0]",
"_____no_output_____"
],
[
"mask_in_transit = (times > 0.5*(t14 + t23)/2) | (times < -0.5*(t14 + t23)/2)\n# mask_in_transit = (times > t23/2) | (times < -t23/2)\n\nbounds = [[0.5 * d.rp, 1.5 * d.rp]]\nd1 = fmin_l_bfgs_b(chi2, initp, approx_grad=True, \n args=(times[mask_in_transit], spotless_lc[mask_in_transit], d), \n bounds=bounds)[0][0]",
"_____no_output_____"
],
[
"d2 = fmin_l_bfgs_b(chi2, initp, approx_grad=True, \n args=(times, spotted_lc, d), \n bounds=bounds)[0][0]",
"_____no_output_____"
],
[
"d3 = fmin_l_bfgs_b(chi2, initp, approx_grad=True, \n args=(times[mask_in_transit], spotted_lc[mask_in_transit], d), \n bounds=bounds)[0][0]",
"_____no_output_____"
],
[
"print(\"unspotted full LC \\t = {0}\\nunspotted only OOT \\t = {1}\\nspotted full LC \"\n \"\\t = {2}\\nspotted only OOT \\t = {3}\".format(d0, d1, d2, d3))",
"unspotted full LC \t = 0.059722442725377724\nunspotted only OOT \t = 0.060050693857455595\nspotted full LC \t = 0.05500006086848168\nspotted only OOT \t = 0.056389741043236255\n"
],
[
"fractional_err = [(d0-d.rp)/d.rp, (d1-d.rp)/d.rp, (d2-d.rp)/d.rp, (d3-d.rp)/d.rp]\nprint(\"unspotted full LC \\t = {0}\\nunspotted only OOT \\t = {1}\\nspotted full LC \"\n \"\\t = {2}\\nspotted only OOT \\t = {3}\".format(*fractional_err))",
"unspotted full LC \t = 0.00010798142267347136\nunspotted only OOT \t = 0.005604852650993289\nspotted full LC \t = -0.07897270534904278\nspotted only OOT \t = -0.05570121525296991\n"
],
[
"fig, ax = plt.subplots(1, 2, figsize=(10, 4), sharey='row', sharex=True)\n\nax[0].plot(times, spotless_lc, label='unspotted')\nax[0].plot(times, spotted_lc, label='spotted')\n\nax[1].scatter(times[mask_in_transit], spotted_lc[mask_in_transit], label='obs', zorder=-10, \n s=5, color='k')\nax[1].scatter(times[~mask_in_transit], spotted_lc[~mask_in_transit], label='obs masked', zorder=-10, \n s=5, color='gray')\nax[1].plot(times, transit_model(times, d2, d), label='fit: full')\nax[1].plot(times, transit_model(times, d3, d), label='fit: $T_{1,1.5}$+$T_{3.5,4}$')\n\n# ax[1, 1].scatter(range(2), fractional_err[2:])\n\n\nfor axis in fig.axes:\n axis.grid(ls=':')\n for s in ['right', 'top']:\n axis.spines[s].set_visible(False)\n axis.legend()\nfig.savefig('ringofspots.pdf', bbox_inches='tight')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(2, 1, figsize=(5, 8))\nax[0].plot(times, spotless_lc, label='Spotless')\nax[0].plot(times, spotted_lc, label='Spotted')\n\nfrom scipy.signal import savgol_filter\n\nfiltered = savgol_filter(spotted_lc, 101, 2, deriv=2)\n\nn = len(times)//2\nmins = [np.argmin(filtered[:n]), n + np.argmin(filtered[n:])]\nmaxes = [np.argmax(filtered[:n]), n + np.argmax(filtered[n:])]\n\nax[1].plot(times, filtered)\n\n# t14 = -1*np.diff(times[mins])[0]\n# t23 = -1*np.diff(times[maxes])[0]\n\nax[1].scatter(times[mins], filtered[mins], color='k', zorder=10)\nax[1].scatter(times[maxes], filtered[maxes], color='k', zorder=10)\n\nfor ts, c in zip([times[mins], times[maxes]], ['k', 'gray']):\n for t in ts:\n ax[0].axvline(t, ls='--', color=c, zorder=-10)\n ax[1].axvline(t, ls='--', color=c, zorder=-10)\n\nfor axis in fig.axes:\n axis.grid(ls=':')\n for s in ['right', 'top']:\n axis.spines[s].set_visible(False)\n axis.legend()\n \nax[0].set_ylabel('$\\mathcal{F}$', fontsize=20)\nax[1].set_ylabel('$\\ddot{\\mathcal{F}}$', fontsize=20)\nax[1].set_xlabel('Time [d]')\nfig.savefig('savgol.pdf', bbox_inches='tight')\nplt.show()",
"_____no_output_____"
],
[
"one_plus_k = np.sqrt((np.sin(t14*np.pi/d.per) * np.sin(np.radians(d.inc)) * d.a)**2 + d.b**2)\none_minus_k = np.sqrt((np.sin(t23*np.pi/d.per) * np.sin(np.radians(d.inc)) * d.a)**2 + d.b**2)",
"_____no_output_____"
],
[
"k = (one_plus_k - one_minus_k)/2\n\nprint((k - d.rp)/d.rp)",
"-1.16198247407e-15\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba2eff29e939947324b76df736debdd806db3e3
| 26,730 |
ipynb
|
Jupyter Notebook
|
18cse023assignment2pandas.ipynb
|
SADDAM-HUSSAIN-code/DMDW-LAB2
|
ea96b0d2f486b5b638368f0f7545cb4249c1c17d
|
[
"Apache-2.0"
] | null | null | null |
18cse023assignment2pandas.ipynb
|
SADDAM-HUSSAIN-code/DMDW-LAB2
|
ea96b0d2f486b5b638368f0f7545cb4249c1c17d
|
[
"Apache-2.0"
] | null | null | null |
18cse023assignment2pandas.ipynb
|
SADDAM-HUSSAIN-code/DMDW-LAB2
|
ea96b0d2f486b5b638368f0f7545cb4249c1c17d
|
[
"Apache-2.0"
] | null | null | null | 26.703297 | 238 | 0.347999 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"data=[1,2,3,4,5]\ndf=pd.DataFrame(data)\ndf",
"_____no_output_____"
],
[
"data=[['Alex',10],['Bob',15],['Marley',20]]\ndf=pd.DataFrame(data)\ndf",
"_____no_output_____"
],
[
"s = pd.Series([1, 3, 5, np.nan, 6, 8])\ns",
"_____no_output_____"
],
[
"dates = pd.date_range('20130101', periods=6)\ndates",
"_____no_output_____"
],
[
"df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))\ndf",
"_____no_output_____"
],
[
"df2 = pd.DataFrame({'A': 1.,'B': pd.Timestamp('20130102'),'C': pd.Series(1, index=list(range(4)), dtype='float32'),'D': np.array([3] * 4, dtype='int32'),'E': pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),'F': 'foo'})\ndf2",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.tail(3)",
"_____no_output_____"
],
[
"df.index",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"df.to_numpy()",
"_____no_output_____"
],
[
"df2.to_numpy()",
"_____no_output_____"
],
[
"df2.describe()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
],
[
"df.T",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba2f5818a3f768d58e84e69922154abb430d715
| 13,351 |
ipynb
|
Jupyter Notebook
|
Week06.ipynb
|
1712307/DevC-08-2019
|
99b28b320bfb4e5910e93c34fc4a4671f6aafc27
|
[
"MIT"
] | null | null | null |
Week06.ipynb
|
1712307/DevC-08-2019
|
99b28b320bfb4e5910e93c34fc4a4671f6aafc27
|
[
"MIT"
] | null | null | null |
Week06.ipynb
|
1712307/DevC-08-2019
|
99b28b320bfb4e5910e93c34fc4a4671f6aafc27
|
[
"MIT"
] | null | null | null | 24.862197 | 497 | 0.420718 |
[
[
[
"[Bag of Words Meets Bags of Popcorn](https://www.kaggle.com/c/word2vec-nlp-tutorial/data)\n======\n\n## Data Set\n\nThe labeled data set consists of 50,000 IMDB movie reviews, specially selected for sentiment analysis. The sentiment of reviews is binary, meaning the IMDB rating < 5 results in a sentiment score of 0, and rating >=7 have a sentiment score of 1. No individual movie has more than 30 reviews. The 25,000 review labeled training set does not include any of the same movies as the 25,000 review test set. In addition, there are another 50,000 IMDB reviews provided without any rating labels.\n\n## File descriptions\n\nlabeledTrainData - The labeled training set. The file is tab-delimited and has a header row followed by 25,000 rows containing an id, sentiment, and text for each review.\n## Data fields\n\n* id - Unique ID of each review\n* sentiment - Sentiment of the review; 1 for positive reviews and 0 for negative reviews\n* review - Text of the review\n\n## Objective\nObjective of this dataset is base on **review** we predict **sentiment** (positive or negative) so X is **review** column and y is **sentiment** column",
"_____no_output_____"
],
[
"## 1. Load Dataset\nwe only forcus on \"labeledTrainData.csv\" file\n\nLet's first of all have a look at the data.\n\n[Click here to download dataset](https://s3-ap-southeast-1.amazonaws.com/ml101-khanhnguyen/week3/assignment/labeledTrainData.tsv)",
"_____no_output_____"
]
],
[
[
"# Import pandas, numpy\nimport pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"# Read dataset with extra params sep='\\t', encoding=\"latin-1\"\ndf = pd.read_csv('labeledTrainData.tsv',sep='\\t',encoding=\"latin-1\")\ndf.head()",
"_____no_output_____"
]
],
[
[
"## 2. Preprocessing",
"_____no_output_____"
]
],
[
[
"import nltk\nnltk.download()",
"showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml\n"
],
[
"from nltk.corpus import brown\nbrown.words()",
"_____no_output_____"
],
[
"from nltk.corpus import stopwords \nstop = stopwords.words('english')",
"_____no_output_____"
],
[
"stop",
"_____no_output_____"
],
[
"import re\ndef preprocessor(text):\n text = re.sub('<[^>]*>', '', text)\n emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', text)\n text = (re.sub('[\\W]+', ' ', text.lower()) + ' ' + ' '.join(emoticons).replace('-', ''))\n return text",
"_____no_output_____"
],
[
"#test the function preprocessor()\nprint(preprocessor('With all this stuff going down at the moment #$::? )'))",
"with all this stuff going down at the moment \n"
],
[
"from nltk.stem import PorterStemmer\n#split a text into list of words\ndef tokenizer(text): \n return text.split()\n\n\ndef tokenizer_porter(text):\n token = [porter.stem(word) for word in text.split()]\n return token\n",
"_____no_output_____"
],
[
"# split the dataset in train and test\nfrom sklearn.model_selection import train_test_split\nX = df['review']\ny = df['sentiment']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\n",
"_____no_output_____"
]
],
[
[
"## 3. Create Model and Train \n\nUsing **Pipeline** to concat **tfidf** step and **LogisticRegression** step",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_extraction.text import TfidfVectorizer\ntfidf = TfidfVectorizer(stop_words=stop,\n tokenizer=tokenizer_porter,\n preprocessor=preprocessor)",
"_____no_output_____"
],
[
"# Import Pipeline, LogisticRegression, TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\n\nclf = Pipeline([('vect', tfidf),\n ('clf', LogisticRegression(random_state=0))])\nclf.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"## 4. Evaluate Model",
"_____no_output_____"
],
[
"## 5. Export Model ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cba2fc26f93abbdd7da8e38826b7660b81805481
| 236,964 |
ipynb
|
Jupyter Notebook
|
9_Validate_3D_CNN_xVal_wb_mwp1_CAT12_MNI_AIBL.ipynb
|
kashikoiga13/InteractiveVis
|
84f82ccfa0f9562d92d5cd00b00fee480314d714
|
[
"MIT"
] | null | null | null |
9_Validate_3D_CNN_xVal_wb_mwp1_CAT12_MNI_AIBL.ipynb
|
kashikoiga13/InteractiveVis
|
84f82ccfa0f9562d92d5cd00b00fee480314d714
|
[
"MIT"
] | null | null | null |
9_Validate_3D_CNN_xVal_wb_mwp1_CAT12_MNI_AIBL.ipynb
|
kashikoiga13/InteractiveVis
|
84f82ccfa0f9562d92d5cd00b00fee480314d714
|
[
"MIT"
] | null | null | null | 350.020679 | 23,324 | 0.925799 |
[
[
[
"# Import data from Excel sheet\nimport pandas as pd\ndf = pd.read_excel('aibl_ptdemog_final.xlsx', sheet_name='aibl_ptdemog_final')\n#print(df)\nsid = df['RID']\ngrp = df['DXCURREN']\nage = df['age']\nsex = df['PTGENDER(1=Female)']\ntiv = df['Total'] # TIV\nfield = df['field_strength']\ngrpbin = (grp > 1) # 1=CN, ...",
"_____no_output_____"
],
[
"# Scan for nifti file names\nimport glob\ndataAIBL = sorted(glob.glob('mwp1_MNI_AIBL/*.nii.gz'))\ndataFiles = dataAIBL\nnumfiles = len(dataFiles)\nprint('Found ', str(numfiles), ' nifti files')",
"Found 606 nifti files\n"
],
[
"# Match covariate information\nimport re\nimport numpy as np\nfrom pandas import DataFrame\nfrom keras.utils import to_categorical\ndebug = False\ncov_idx = [-1] * numfiles # list; array: np.full((numfiles, 1), -1, dtype=int)\nprint('Matching covariates for loaded files ...')\nfor i,id in enumerate(sid):\n p = [j for j,x in enumerate(dataFiles) if re.search('_%d_MR_' % id, x)] # extract ID numbers from filename, translate to Excel row index\n if len(p)==0:\n if debug: print('Did not find %04d' % id) # did not find Excel sheet subject ID in loaded file selection\n else:\n if debug: print('Found %04d in %s: %s' % (id, p[0], dataFiles[p[0]]))\n cov_idx[p[0]] = i # store Excel index i for data file index p[0]\nprint('Checking for scans not found in Excel sheet: ', sum(x<0 for x in cov_idx))\n\nlabels = pd.DataFrame({'Group':grpbin}).iloc[cov_idx, :]\nlabels = to_categorical(np.asarray(labels)) # use grps to access original labels\ngrps = pd.DataFrame({'Group':grp, 'RID':sid}).iloc[cov_idx, :]",
"Using TensorFlow backend.\n"
],
[
"# Load original data from disk\nimport h5py\nhf = h5py.File('orig_images_AIBL_wb_mwp1_CAT12_MNI.hdf5', 'r')\nhf.keys # read keys\nimages = np.array(hf.get('images'))\nhf.close()\nprint(images.shape)",
"(606, 100, 100, 120, 1)\n"
],
[
"# specify version of tensorflow\n#%tensorflow_version 1.x # <- use this for Google colab\nimport tensorflow as tf\n# downgrade to specific version\n#!pip install tensorflow-gpu==1.15\n#import tensorflow as tf\nprint(tf.__version__)\n\n# disable tensorflow deprecation warnings\nimport logging\nlogging.getLogger('tensorflow').disabled=True",
"1.15.4\n"
],
[
"# helper function to obtain performance result values\ndef get_values(conf_matrix):\n assert conf_matrix.shape==(2,2)\n tn, fp, fn, tp = conf_matrix.ravel()\n sen = tp / (tp+fn)\n spec = tn / (fp+tn)\n ppv = tp / (tp+fp)\n npv = tn / (tn+fn)\n f1 = 2 * ((ppv * sen) / (ppv + sen))\n bacc = (spec + sen) / 2\n return bacc, sen, spec, ppv, npv, f1",
"_____no_output_____"
],
[
"# validation\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nimport keras\nfrom keras import models\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix\n\nacc_AD, acc_MCI, auc_AD, auc_MCI = [], [], [], []\nbacc_AD, bacc_MCI = [], []\nsen_AD, sen_MCI, spec_AD, spec_MCI = [], [], [], []\nppv_AD, ppv_MCI, npv_AD, npv_MCI = [], [], [], []\nf1_AD, f1_MCI = [], []\n\nnum_kfold = 10 # number of cross-validation loops equal to number of models\nbatch_size = 20\n\nfor k in range(num_kfold):\n print('validating model model_rawdat_checkpoints/rawmodel_wb_cv%d.best.hdf5' % (k+1))\n mymodel = models.load_model('model_rawdat_checkpoints/rawmodel_wb_cv%d.best.hdf5' % (k+1))\n \n # calculate area under the curve\n # AUC as optimization function during training: https://stackoverflow.com/questions/41032551/how-to-compute-receiving-operating-characteristic-roc-and-auc-in-keras\n pred = mymodel.predict(images, batch_size=batch_size)\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n acc = dict()\n for i in range(2): # classes dummy vector: 0 - CN, 1 - MCI/AD\n fpr[i], tpr[i], _ = roc_curve(labels[:, i], pred[:,i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n # Plot the ROC curve\n plt.figure()\n plt.plot(fpr[1], tpr[1], color='darkorange', label='ROC curve (area = %0.2f)' % roc_auc[1])\n plt.plot([0, 1], [0, 1], color='navy', linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n plt.legend(loc=\"lower right\")\n plt.show()\n \n # redo AUC for binary comparison: AD vs. HC and MCI vs. HC\n for i in [2,3]:\n grpi = np.equal(grps.Group.to_numpy(dtype=np.int), np.ones((grps.shape[0],), dtype=np.int)*i)\n grp1 = np.equal(grps.Group.to_numpy(dtype=np.int), np.ones((grps.shape[0],), dtype=np.int))\n grpidx = np.logical_or(grpi, grp1)\n fpr[i], tpr[i], _ = roc_curve(labels[grpidx, 1], pred[grpidx, 1])\n roc_auc[i] = auc(fpr[i], tpr[i])\n acc[i] = np.mean((labels[grpidx, 1] == np.round(pred[grpidx, 1])).astype(int))*100\n\n print('AUC for MCI vs. CN = %0.3f' % roc_auc[2])\n print('AUC for AD vs. CN = %0.3f' % roc_auc[3])\n print('Acc for MCI vs. CN = %0.1f' % acc[2])\n print('Acc for AD vs. CN = %0.1f' % acc[3])\n auc_AD.append(roc_auc[3])\n auc_MCI.append(roc_auc[2])\n acc_AD.append(acc[3])\n acc_MCI.append(acc[2])\n \n print('confusion matrix')\n confmat = confusion_matrix(grps.Group, np.round(pred[:, 1]))\n bacc, sen, spec, ppv, npv, f1 = get_values(confmat[(1,2),0:2]) # MCI\n bacc_MCI.append(bacc); sen_MCI.append(sen); spec_MCI.append(spec); ppv_MCI.append(ppv); npv_MCI.append(npv); f1_MCI.append(f1)\n bacc, sen, spec, ppv, npv, f1 = get_values(confmat[(1,3),0:2]) # AD\n bacc_AD.append(bacc); sen_AD.append(sen); spec_AD.append(spec); ppv_AD.append(ppv); npv_AD.append(npv); f1_AD.append(f1)\n print(confmat[1:4,0:2])",
"validating model model_rawdat_checkpoints/rawmodel_wb_cv1.best.hdf5\n"
],
[
"# print model performance summary\nfrom statistics import mean,stdev\n\nprint('Mean AUC for MCI vs. CN = %0.3f +/- %0.3f' % (mean(auc_MCI), stdev(auc_MCI)))\nprint('Mean AUC for AD vs. CN = %0.3f +/- %0.3f' % (mean(auc_AD), stdev(auc_AD)))\nprint('Mean Acc for MCI vs. CN = %0.3f +/- %0.3f' % (mean(acc_MCI), stdev(acc_MCI)))\nprint('Mean Acc for AD vs. CN = %0.3f +/- %0.3f' % (mean(acc_AD), stdev(acc_AD)))\nprint('Mean Bacc for MCI vs. CN = %0.3f +/- %0.3f' % (mean(bacc_MCI), stdev(bacc_MCI)))\nprint('Mean Bacc for AD vs. CN = %0.3f +/- %0.3f' % (mean(bacc_AD), stdev(bacc_AD)))\nprint('Mean Sen for MCI vs. CN = %0.3f +/- %0.3f' % (mean(sen_MCI), stdev(sen_MCI)))\nprint('Mean Sen for AD vs. CN = %0.3f +/- %0.3f' % (mean(sen_AD), stdev(sen_AD)))\nprint('Mean Spec for MCI vs. CN = %0.3f +/- %0.3f' % (mean(spec_MCI), stdev(spec_MCI)))\nprint('Mean Spec for AD vs. CN = %0.3f +/- %0.3f' % (mean(spec_AD), stdev(spec_AD)))\nprint('Mean PPV for MCI vs. CN = %0.3f +/- %0.3f' % (mean(ppv_MCI), stdev(ppv_MCI)))\nprint('Mean PPV for AD vs. CN = %0.3f +/- %0.3f' % (mean(ppv_AD), stdev(ppv_AD)))\nprint('Mean NPV for MCI vs. CN = %0.3f +/- %0.3f' % (mean(npv_MCI), stdev(npv_MCI)))\nprint('Mean NPV for AD vs. CN = %0.3f +/- %0.3f' % (mean(npv_AD), stdev(npv_AD)))\nprint('Mean F1 for MCI vs. CN = %0.3f +/- %0.3f' % (mean(f1_MCI), stdev(f1_MCI)))\nprint('Mean F1 for AD vs. CN = %0.3f +/- %0.3f' % (mean(f1_AD), stdev(f1_AD)))",
"Mean AUC for MCI vs. CN = 0.713 +/- 0.016\nMean AUC for AD vs. CN = 0.924 +/- 0.006\nMean Acc for MCI vs. CN = 66.875 +/- 10.536\nMean Acc for AD vs. CN = 70.980 +/- 12.637\nMean Bacc for MCI vs. CN = 0.648 +/- 0.032\nMean Bacc for AD vs. CN = 0.802 +/- 0.063\nMean Sen for MCI vs. CN = 0.616 +/- 0.093\nMean Sen for AD vs. CN = 0.924 +/- 0.025\nMean Spec for MCI vs. CN = 0.680 +/- 0.147\nMean Spec for AD vs. CN = 0.680 +/- 0.147\nMean PPV for MCI vs. CN = 0.308 +/- 0.050\nMean PPV for AD vs. CN = 0.306 +/- 0.069\nMean NPV for MCI vs. CN = 0.892 +/- 0.008\nMean NPV for AD vs. CN = 0.985 +/- 0.003\nMean F1 for MCI vs. CN = 0.403 +/- 0.035\nMean F1 for AD vs. CN = 0.455 +/- 0.081\n"
],
[
"results = pd.DataFrame({'AUC_MCI':auc_MCI, 'Acc_MCI':acc_MCI, 'Bacc_MCI':bacc_MCI, 'f1_MCI':f1_MCI,\n 'sen_MCI':sen_MCI, 'spec_MCI':spec_MCI, 'ppv_MCI':ppv_MCI, 'npv_MCI':npv_MCI,\n 'AUC_AD':auc_AD, 'Acc_AD':acc_AD, 'Bacc_AD':bacc_AD, 'f1_AD':f1_AD,\n 'sen_AD':sen_AD, 'spec_AD':spec_AD, 'ppv_AD':ppv_AD, 'npv_AD':npv_AD})\nprint(results)\nresults.to_csv('results_xval_rawdat_AIBL_checkpoints.csv')",
" AUC_MCI Acc_MCI Bacc_MCI f1_MCI sen_MCI spec_MCI ppv_MCI \\\n0 0.727400 74.448529 0.668899 0.432653 0.552083 0.785714 0.355705 \n1 0.730469 73.529412 0.683780 0.446154 0.604167 0.763393 0.353659 \n2 0.711937 72.610294 0.653646 0.411067 0.541667 0.765625 0.331210 \n3 0.684198 70.588235 0.657738 0.411765 0.583333 0.732143 0.318182 \n4 0.703241 45.772059 0.576637 0.331066 0.760417 0.392857 0.211594 \n5 0.705264 68.198529 0.647321 0.397213 0.593750 0.700893 0.298429 \n6 0.705729 74.632353 0.649554 0.410256 0.500000 0.799107 0.347826 \n7 0.723656 69.669118 0.676711 0.429066 0.645833 0.707589 0.321244 \n8 0.738142 70.404412 0.656622 0.410256 0.583333 0.729911 0.316384 \n9 0.702846 48.897059 0.607887 0.353488 0.791667 0.424107 0.227545 \n\n npv_MCI AUC_AD Acc_AD Bacc_AD f1_AD sen_AD spec_AD \\\n0 0.891139 0.929111 80.000000 0.844470 0.523364 0.903226 0.785714 \n1 0.900000 0.926807 78.039216 0.833309 0.500000 0.903226 0.763393 \n2 0.886305 0.929111 78.235294 0.834425 0.502242 0.903226 0.765625 \n3 0.891304 0.914639 75.490196 0.825749 0.476987 0.919355 0.732143 \n4 0.884422 0.911182 46.078431 0.672235 0.300254 0.951613 0.392857 \n5 0.889518 0.923531 72.941176 0.818188 0.456693 0.935484 0.700893 \n6 0.881773 0.924611 80.980392 0.843102 0.531401 0.887097 0.799107 \n7 0.903134 0.928103 73.529412 0.821537 0.462151 0.935484 0.707589 \n8 0.891008 0.928823 75.490196 0.832697 0.481328 0.935484 0.729911 \n9 0.904762 0.920813 49.019608 0.695925 0.315789 0.967742 0.424107 \n\n ppv_AD npv_AD \n0 0.368421 0.983240 \n1 0.345679 0.982759 \n2 0.347826 0.982808 \n3 0.322034 0.984985 \n4 0.178248 0.983240 \n5 0.302083 0.987421 \n6 0.379310 0.980822 \n7 0.306878 0.987539 \n8 0.324022 0.987915 \n9 0.188679 0.989583 \n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba300dd154aaf2eca06a3b972df2de0053137ea
| 57,021 |
ipynb
|
Jupyter Notebook
|
chapters/chapter_1/PyTorch_Basics.ipynb
|
TRBoom/PyTorchNLPBook
|
3ace692a8076e559bf4115e92ae5c932acb9956c
|
[
"Apache-2.0"
] | null | null | null |
chapters/chapter_1/PyTorch_Basics.ipynb
|
TRBoom/PyTorchNLPBook
|
3ace692a8076e559bf4115e92ae5c932acb9956c
|
[
"Apache-2.0"
] | null | null | null |
chapters/chapter_1/PyTorch_Basics.ipynb
|
TRBoom/PyTorchNLPBook
|
3ace692a8076e559bf4115e92ae5c932acb9956c
|
[
"Apache-2.0"
] | null | null | null | 57,021 | 57,021 | 0.60618 |
[
[
[
"# PyTorch Basics",
"_____no_output_____"
]
],
[
[
"import torch\nimport numpy as np\ntorch.manual_seed(1234)",
"_____no_output_____"
]
],
[
[
"## Tensors",
"_____no_output_____"
],
[
"* Scalar is a single number.\n* Vector is an array of numbers.\n* Matrix is a 2-D array of numbers.\n* Tensors are N-D arrays of numbers.",
"_____no_output_____"
],
[
"#### Creating Tensors",
"_____no_output_____"
],
[
"You can create tensors by specifying the shape as arguments. Here is a tensor with 5 rows and 3 columns",
"_____no_output_____"
]
],
[
[
"def describe(x):\n print(\"Type: {}\".format(x.type()))\n print(\"Shape/size: {}\".format(x.shape))\n print(\"Values: \\n{}\".format(x))",
"_____no_output_____"
],
[
"describe(torch.Tensor(2, 3))",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[ 3.1654e+09, 4.5635e-41, -5.4825e-21],\n [ 3.0718e-41, 4.4842e-44, 0.0000e+00]])\n"
],
[
"describe(torch.randn(2, 3))",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[ 0.0461, 0.4024, -1.0115],\n [ 0.2167, -0.6123, 0.5036]])\n"
]
],
[
[
"It's common in prototyping to create a tensor with random numbers of a specific shape.",
"_____no_output_____"
]
],
[
[
"x = torch.rand(2, 3)\ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0.7749, 0.8208, 0.2793],\n [0.6817, 0.2837, 0.6567]])\n"
]
],
[
[
"You can also initialize tensors of ones or zeros.",
"_____no_output_____"
]
],
[
[
"describe(torch.zeros(2, 3))\nx = torch.ones(2, 3)\ndescribe(x)\nx.fill_(5)\ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0., 0., 0.],\n [0., 0., 0.]])\nType: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[1., 1., 1.],\n [1., 1., 1.]])\nType: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[5., 5., 5.],\n [5., 5., 5.]])\n"
]
],
[
[
"Tensors can be initialized and then filled in place. \n\nNote: operations that end in an underscore (`_`) are in place operations.",
"_____no_output_____"
]
],
[
[
"x = torch.Tensor(3,4).fill_(5)\nprint(x.type())\nprint(x.shape)\nprint(x)",
"torch.FloatTensor\ntorch.Size([3, 4])\ntensor([[5., 5., 5., 5.],\n [5., 5., 5., 5.],\n [5., 5., 5., 5.]])\n"
]
],
[
[
"Tensors can be initialized from a list of lists",
"_____no_output_____"
]
],
[
[
"x = torch.Tensor([[1, 2,], \n [2, 4,]])\ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 2])\nValues: \ntensor([[1., 2.],\n [2., 4.]])\n"
]
],
[
[
"Tensors can be initialized from numpy matrices",
"_____no_output_____"
]
],
[
[
"npy = np.random.rand(2, 3)\ndescribe(torch.from_numpy(npy))\nprint(npy.dtype)",
"Type: torch.DoubleTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0.6938, 0.0125, 0.7894],\n [0.4493, 0.1734, 0.4403]], dtype=torch.float64)\nfloat64\n"
]
],
[
[
"#### Tensor Types",
"_____no_output_____"
],
[
"The FloatTensor has been the default tensor that we have been creating all along",
"_____no_output_____"
]
],
[
[
"import torch\nx = torch.arange(6).view(2, 3)\ndescribe(x)",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0, 1, 2],\n [3, 4, 5]])\n"
],
[
"x = torch.FloatTensor([[1, 2, 3], \n [4, 5, 6]])\ndescribe(x)\n\nx = x.long()\ndescribe(x)\n\nx = torch.tensor([[1, 2, 3], \n [4, 5, 6]], dtype=torch.int64)\ndescribe(x)\n\nx = x.float() \ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[1., 2., 3.],\n [4., 5., 6.]])\nType: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[1, 2, 3],\n [4, 5, 6]])\nType: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[1, 2, 3],\n [4, 5, 6]])\nType: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[1., 2., 3.],\n [4., 5., 6.]])\n"
],
[
"x = torch.randn(2, 3)\ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[ 1.5385, -0.9757, 1.5769],\n [ 0.3840, -0.6039, -0.5240]])\n"
],
[
"describe(torch.add(x, x))",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[ 3.0771, -1.9515, 3.1539],\n [ 0.7680, -1.2077, -1.0479]])\n"
],
[
"describe(x + x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[ 3.0771, -1.9515, 3.1539],\n [ 0.7680, -1.2077, -1.0479]])\n"
],
[
"x = torch.arange(6)\ndescribe(x)",
"Type: torch.LongTensor\nShape/size: torch.Size([6])\nValues: \ntensor([0, 1, 2, 3, 4, 5])\n"
],
[
"x = x.view(2, 3)\ndescribe(x)",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0, 1, 2],\n [3, 4, 5]])\n"
],
[
"describe(torch.sum(x, dim=0))\ndescribe(torch.sum(x, dim=1))",
"Type: torch.LongTensor\nShape/size: torch.Size([3])\nValues: \ntensor([3, 5, 7])\nType: torch.LongTensor\nShape/size: torch.Size([2])\nValues: \ntensor([ 3, 12])\n"
],
[
"describe(torch.transpose(x, 0, 1))",
"Type: torch.LongTensor\nShape/size: torch.Size([3, 2])\nValues: \ntensor([[0, 3],\n [1, 4],\n [2, 5]])\n"
],
[
"import torch\nx = torch.arange(6).view(2, 3)\ndescribe(x)\ndescribe(x[:1, :2])\ndescribe(x[0, 1])",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0, 1, 2],\n [3, 4, 5]])\nType: torch.LongTensor\nShape/size: torch.Size([1, 2])\nValues: \ntensor([[0, 1]])\nType: torch.LongTensor\nShape/size: torch.Size([])\nValues: \n1\n"
],
[
"indices = torch.LongTensor([0, 2])\ndescribe(torch.index_select(x, dim=1, index=indices))",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 2])\nValues: \ntensor([[0, 2],\n [3, 5]])\n"
],
[
"indices = torch.LongTensor([0, 0])\ndescribe(torch.index_select(x, dim=0, index=indices))",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0, 1, 2],\n [0, 1, 2]])\n"
],
[
"row_indices = torch.arange(2).long()\ncol_indices = torch.LongTensor([0, 1])\ndescribe(x[row_indices, col_indices])",
"Type: torch.LongTensor\nShape/size: torch.Size([2])\nValues: \ntensor([0, 4])\n"
]
],
[
[
"Long Tensors are used for indexing operations and mirror the `int64` numpy type",
"_____no_output_____"
]
],
[
[
"x = torch.LongTensor([[1, 2, 3], \n [4, 5, 6],\n [7, 8, 9]])\ndescribe(x)\nprint(x.dtype)\nprint(x.numpy().dtype)",
"Type: torch.LongTensor\nShape/size: torch.Size([3, 3])\nValues: \ntensor([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\ntorch.int64\nint64\n"
]
],
[
[
"You can convert a FloatTensor to a LongTensor",
"_____no_output_____"
]
],
[
[
"x = torch.FloatTensor([[1, 2, 3], \n [4, 5, 6],\n [7, 8, 9]])\nx = x.long()\ndescribe(x)",
"Type: torch.LongTensor\nShape/size: torch.Size([3, 3])\nValues: \ntensor([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n"
]
],
[
[
"### Special Tensor initializations",
"_____no_output_____"
],
[
"We can create a vector of incremental numbers",
"_____no_output_____"
]
],
[
[
"x = torch.arange(0, 10)\nprint(x)",
"tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n"
]
],
[
[
"Sometimes it's useful to have an integer-based arange for indexing",
"_____no_output_____"
]
],
[
[
"x = torch.arange(0, 10).long()\nprint(x)",
"tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n"
]
],
[
[
"## Operations\n\nUsing the tensors to do linear algebra is a foundation of modern Deep Learning practices",
"_____no_output_____"
],
[
"Reshaping allows you to move the numbers in a tensor around. One can be sure that the order is preserved. In PyTorch, reshaping is called `view`",
"_____no_output_____"
]
],
[
[
"x = torch.arange(0, 20)\n\nprint(x.view(1, 20))\nprint(x.view(2, 10))\nprint(x.view(4, 5))\nprint(x.view(5, 4))\nprint(x.view(10, 2))\nprint(x.view(20, 1))",
"tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,\n 18, 19]])\ntensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])\ntensor([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]])\ntensor([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11],\n [12, 13, 14, 15],\n [16, 17, 18, 19]])\ntensor([[ 0, 1],\n [ 2, 3],\n [ 4, 5],\n [ 6, 7],\n [ 8, 9],\n [10, 11],\n [12, 13],\n [14, 15],\n [16, 17],\n [18, 19]])\ntensor([[ 0],\n [ 1],\n [ 2],\n [ 3],\n [ 4],\n [ 5],\n [ 6],\n [ 7],\n [ 8],\n [ 9],\n [10],\n [11],\n [12],\n [13],\n [14],\n [15],\n [16],\n [17],\n [18],\n [19]])\n"
]
],
[
[
"We can use view to add size-1 dimensions, which can be useful for combining with other tensors. This is called broadcasting. ",
"_____no_output_____"
]
],
[
[
"x = torch.arange(12).view(3, 4)\ny = torch.arange(4).view(1, 4)\nz = torch.arange(3).view(3, 1)\n\nprint(x)\nprint(y)\nprint(z)\nprint(x + y)\nprint(x + z)",
"tensor([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\ntensor([[0, 1, 2, 3]])\ntensor([[0],\n [1],\n [2]])\ntensor([[ 0, 2, 4, 6],\n [ 4, 6, 8, 10],\n [ 8, 10, 12, 14]])\ntensor([[ 0, 1, 2, 3],\n [ 5, 6, 7, 8],\n [10, 11, 12, 13]])\n"
]
],
[
[
"Unsqueeze and squeeze will add and remove 1-dimensions.",
"_____no_output_____"
]
],
[
[
"x = torch.arange(12).view(3, 4)\nprint(x.shape)\n\nx = x.unsqueeze(dim=1)\nprint(x.shape)\n\nx = x.squeeze()\nprint(x.shape)",
"torch.Size([3, 4])\ntorch.Size([3, 1, 4])\ntorch.Size([3, 4])\n"
]
],
[
[
"all of the standard mathematics operations apply (such as `add` below)",
"_____no_output_____"
]
],
[
[
"x = torch.rand(3,4)\nprint(\"x: \\n\", x)\nprint(\"--\")\nprint(\"torch.add(x, x): \\n\", torch.add(x, x))\nprint(\"--\")\nprint(\"x+x: \\n\", x + x)",
"x: \n tensor([[0.6662, 0.3343, 0.7893, 0.3216],\n [0.5247, 0.6688, 0.8436, 0.4265],\n [0.9561, 0.0770, 0.4108, 0.0014]])\n--\ntorch.add(x, x): \n tensor([[1.3324, 0.6686, 1.5786, 0.6433],\n [1.0494, 1.3377, 1.6872, 0.8530],\n [1.9123, 0.1540, 0.8216, 0.0028]])\n--\nx+x: \n tensor([[1.3324, 0.6686, 1.5786, 0.6433],\n [1.0494, 1.3377, 1.6872, 0.8530],\n [1.9123, 0.1540, 0.8216, 0.0028]])\n"
]
],
[
[
"The convention of `_` indicating in-place operations continues:",
"_____no_output_____"
]
],
[
[
"x = torch.arange(12).reshape(3, 4)\nprint(x)\nprint(x.add_(x))",
"tensor([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\ntensor([[ 0, 2, 4, 6],\n [ 8, 10, 12, 14],\n [16, 18, 20, 22]])\n"
]
],
[
[
"There are many operations for which reduce a dimension. Such as sum:",
"_____no_output_____"
]
],
[
[
"x = torch.arange(12).reshape(3, 4)\nprint(\"x: \\n\", x)\nprint(\"---\")\nprint(\"Summing across rows (dim=0): \\n\", x.sum(dim=0))\nprint(\"---\")\nprint(\"Summing across columns (dim=1): \\n\", x.sum(dim=1))",
"x: \n tensor([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n---\nSumming across rows (dim=0): \n tensor([12, 15, 18, 21])\n---\nSumming across columns (dim=1): \n tensor([ 6, 22, 38])\n"
]
],
[
[
"#### Indexing, Slicing, Joining and Mutating",
"_____no_output_____"
]
],
[
[
"x = torch.arange(6).view(2, 3)\nprint(\"x: \\n\", x)\nprint(\"---\")\nprint(\"x[:2, :2]: \\n\", x[:2, :2])\nprint(\"---\")\nprint(\"x[0][1]: \\n\", x[0][1])\nprint(\"---\")\nprint(\"Setting [0][1] to be 8\")\nx[0][1] = 8\nprint(x)",
"x: \n tensor([[0, 1, 2],\n [3, 4, 5]])\n---\nx[:2, :2]: \n tensor([[0, 1],\n [3, 4]])\n---\nx[0][1]: \n tensor(1)\n---\nSetting [0][1] to be 8\ntensor([[0, 8, 2],\n [3, 4, 5]])\n"
]
],
[
[
"We can select a subset of a tensor using the `index_select`",
"_____no_output_____"
]
],
[
[
"x = torch.arange(9).view(3,3)\nprint(x)\n\nprint(\"---\")\nindices = torch.LongTensor([0, 2])\nprint(torch.index_select(x, dim=0, index=indices))\n\nprint(\"---\")\nindices = torch.LongTensor([0, 2])\nprint(torch.index_select(x, dim=1, index=indices))",
"tensor([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n---\ntensor([[0, 1, 2],\n [6, 7, 8]])\n---\ntensor([[0, 2],\n [3, 5],\n [6, 8]])\n"
]
],
[
[
"We can also use numpy-style advanced indexing:",
"_____no_output_____"
]
],
[
[
"x = torch.arange(9).view(3,3)\nindices = torch.LongTensor([0, 2])\n\nprint(x[indices])\nprint(\"---\")\nprint(x[indices, :])\nprint(\"---\")\nprint(x[:, indices])",
"tensor([[0, 1, 2],\n [6, 7, 8]])\n---\ntensor([[0, 1, 2],\n [6, 7, 8]])\n---\ntensor([[0, 2],\n [3, 5],\n [6, 8]])\n"
]
],
[
[
"We can combine tensors by concatenating them. First, concatenating on the rows",
"_____no_output_____"
]
],
[
[
"x = torch.arange(6).view(2,3)\ndescribe(x)\ndescribe(torch.cat([x, x], dim=0))\ndescribe(torch.cat([x, x], dim=1))\ndescribe(torch.stack([x, x]))",
"Type: torch.LongTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0, 1, 2],\n [3, 4, 5]])\nType: torch.LongTensor\nShape/size: torch.Size([4, 3])\nValues: \ntensor([[0, 1, 2],\n [3, 4, 5],\n [0, 1, 2],\n [3, 4, 5]])\nType: torch.LongTensor\nShape/size: torch.Size([2, 6])\nValues: \ntensor([[0, 1, 2, 0, 1, 2],\n [3, 4, 5, 3, 4, 5]])\nType: torch.LongTensor\nShape/size: torch.Size([2, 2, 3])\nValues: \ntensor([[[0, 1, 2],\n [3, 4, 5]],\n\n [[0, 1, 2],\n [3, 4, 5]]])\n"
]
],
[
[
"We can concentate along the first dimension.. the columns.",
"_____no_output_____"
]
],
[
[
"x = torch.arange(9).view(3,3)\n\nprint(x)\nprint(\"---\")\nnew_x = torch.cat([x, x, x], dim=1)\nprint(new_x.shape)\nprint(new_x)",
"tensor([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n---\ntorch.Size([3, 9])\ntensor([[0, 1, 2, 0, 1, 2, 0, 1, 2],\n [3, 4, 5, 3, 4, 5, 3, 4, 5],\n [6, 7, 8, 6, 7, 8, 6, 7, 8]])\n"
]
],
[
[
"We can also concatenate on a new 0th dimension to \"stack\" the tensors:",
"_____no_output_____"
]
],
[
[
"x = torch.arange(9).view(3,3)\nprint(x)\nprint(\"---\")\nnew_x = torch.stack([x, x, x])\nprint(new_x.shape)\nprint(new_x)",
"tensor([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n---\ntorch.Size([3, 3, 3])\ntensor([[[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]],\n\n [[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]],\n\n [[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]]])\n"
]
],
[
[
"#### Linear Algebra Tensor Functions",
"_____no_output_____"
],
[
"Transposing allows you to switch the dimensions to be on different axis. So we can make it so all the rows are columsn and vice versa. ",
"_____no_output_____"
]
],
[
[
"x = torch.arange(0, 12).view(3,4)\nprint(\"x: \\n\", x) \nprint(\"---\")\nprint(\"x.tranpose(1, 0): \\n\", x.transpose(1, 0))",
"x: \n tensor([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n---\nx.tranpose(1, 0): \n tensor([[ 0, 4, 8],\n [ 1, 5, 9],\n [ 2, 6, 10],\n [ 3, 7, 11]])\n"
]
],
[
[
"A three dimensional tensor would represent a batch of sequences, where each sequence item has a feature vector. It is common to switch the batch and sequence dimensions so that we can more easily index the sequence in a sequence model. \n\nNote: Transpose will only let you swap 2 axes. Permute (in the next cell) allows for multiple",
"_____no_output_____"
]
],
[
[
"batch_size = 3\nseq_size = 4\nfeature_size = 5\n\nx = torch.arange(batch_size * seq_size * feature_size).view(batch_size, seq_size, feature_size)\n\nprint(\"x.shape: \\n\", x.shape)\nprint(\"x: \\n\", x)\nprint(\"-----\")\n\nprint(\"x.transpose(1, 0).shape: \\n\", x.transpose(1, 0).shape)\nprint(\"x.transpose(1, 0): \\n\", x.transpose(1, 0))",
"x.shape: \n torch.Size([3, 4, 5])\nx: \n tensor([[[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]],\n\n [[20, 21, 22, 23, 24],\n [25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34],\n [35, 36, 37, 38, 39]],\n\n [[40, 41, 42, 43, 44],\n [45, 46, 47, 48, 49],\n [50, 51, 52, 53, 54],\n [55, 56, 57, 58, 59]]])\n-----\nx.transpose(1, 0).shape: \n torch.Size([4, 3, 5])\nx.transpose(1, 0): \n tensor([[[ 0, 1, 2, 3, 4],\n [20, 21, 22, 23, 24],\n [40, 41, 42, 43, 44]],\n\n [[ 5, 6, 7, 8, 9],\n [25, 26, 27, 28, 29],\n [45, 46, 47, 48, 49]],\n\n [[10, 11, 12, 13, 14],\n [30, 31, 32, 33, 34],\n [50, 51, 52, 53, 54]],\n\n [[15, 16, 17, 18, 19],\n [35, 36, 37, 38, 39],\n [55, 56, 57, 58, 59]]])\n"
]
],
[
[
"Permute is a more general version of tranpose:",
"_____no_output_____"
]
],
[
[
"batch_size = 3\nseq_size = 4\nfeature_size = 5\n\nx = torch.arange(batch_size * seq_size * feature_size).view(batch_size, seq_size, feature_size)\n\nprint(\"x.shape: \\n\", x.shape)\nprint(\"x: \\n\", x)\nprint(\"-----\")\n\nprint(\"x.permute(1, 0, 2).shape: \\n\", x.permute(1, 0, 2).shape)\nprint(\"x.permute(1, 0, 2): \\n\", x.permute(1, 0, 2))",
"x.shape: \n torch.Size([3, 4, 5])\nx: \n tensor([[[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19]],\n\n [[20, 21, 22, 23, 24],\n [25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34],\n [35, 36, 37, 38, 39]],\n\n [[40, 41, 42, 43, 44],\n [45, 46, 47, 48, 49],\n [50, 51, 52, 53, 54],\n [55, 56, 57, 58, 59]]])\n-----\nx.permute(1, 0, 2).shape: \n torch.Size([4, 3, 5])\nx.permute(1, 0, 2): \n tensor([[[ 0, 1, 2, 3, 4],\n [20, 21, 22, 23, 24],\n [40, 41, 42, 43, 44]],\n\n [[ 5, 6, 7, 8, 9],\n [25, 26, 27, 28, 29],\n [45, 46, 47, 48, 49]],\n\n [[10, 11, 12, 13, 14],\n [30, 31, 32, 33, 34],\n [50, 51, 52, 53, 54]],\n\n [[15, 16, 17, 18, 19],\n [35, 36, 37, 38, 39],\n [55, 56, 57, 58, 59]]])\n"
]
],
[
[
"Matrix multiplication is `mm`:",
"_____no_output_____"
]
],
[
[
"torch.randn(2, 3, requires_grad=True)",
"_____no_output_____"
],
[
"x1 = torch.arange(6).view(2, 3).float()\ndescribe(x1)\n\nx2 = torch.ones(3, 2)\nx2[:, 1] += 1\ndescribe(x2)\n\ndescribe(torch.mm(x1, x2))",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 3])\nValues: \ntensor([[0., 1., 2.],\n [3., 4., 5.]])\nType: torch.FloatTensor\nShape/size: torch.Size([3, 2])\nValues: \ntensor([[1., 2.],\n [1., 2.],\n [1., 2.]])\nType: torch.FloatTensor\nShape/size: torch.Size([2, 2])\nValues: \ntensor([[ 3., 6.],\n [12., 24.]])\n"
],
[
"x = torch.arange(0, 12).view(3,4).float()\nprint(x)\n\nx2 = torch.ones(4, 2)\nx2[:, 1] += 1\nprint(x2)\n\nprint(x.mm(x2))",
"tensor([[ 0., 1., 2., 3.],\n [ 4., 5., 6., 7.],\n [ 8., 9., 10., 11.]])\ntensor([[1., 2.],\n [1., 2.],\n [1., 2.],\n [1., 2.]])\ntensor([[ 6., 12.],\n [22., 44.],\n [38., 76.]])\n"
]
],
[
[
"See the [PyTorch Math Operations Documentation](https://pytorch.org/docs/stable/torch.html#math-operations) for more!",
"_____no_output_____"
],
[
"## Computing Gradients",
"_____no_output_____"
]
],
[
[
"x = torch.tensor([[2.0, 3.0]], requires_grad=True)\nz = 3 * x\nprint(z)",
"tensor([[6., 9.]], grad_fn=<MulBackward0>)\n"
]
],
[
[
"In this small snippet, you can see the gradient computations at work. We create a tensor and multiply it by 3. Then, we create a scalar output using `sum()`. A Scalar output is needed as the the loss variable. Then, called backward on the loss means it computes its rate of change with respect to the inputs. Since the scalar was created with sum, each position in z and x are independent with respect to the loss scalar. \n\nThe rate of change of x with respect to the output is just the constant 3 that we multiplied x by.",
"_____no_output_____"
]
],
[
[
"x = torch.tensor([[2.0, 3.0]], requires_grad=True)\nprint(\"x: \\n\", x)\nprint(\"---\")\nz = 3 * x\nprint(\"z = 3*x: \\n\", z)\nprint(\"---\")\n\nloss = z.sum()\nprint(\"loss = z.sum(): \\n\", loss)\nprint(\"---\")\n\nloss.backward()\n\nprint(\"after loss.backward(), x.grad: \\n\", x.grad)\n",
"x: \n tensor([[2., 3.]], requires_grad=True)\n---\nz = 3*x: \n tensor([[6., 9.]], grad_fn=<MulBackward0>)\n---\nloss = z.sum(): \n tensor(15., grad_fn=<SumBackward0>)\n---\nafter loss.backward(), x.grad: \n tensor([[3., 3.]])\n"
]
],
[
[
"### Example: Computing a conditional gradient\n\n$$ \\text{ Find the gradient of f(x) at x=1 } $$\n$$ {} $$\n$$ f(x)=\\left\\{\n\\begin{array}{ll}\n sin(x) \\text{ if } x>0 \\\\\n cos(x) \\text{ otherwise } \\\\\n\\end{array}\n\\right.$$",
"_____no_output_____"
]
],
[
[
"def f(x):\n if (x.data > 0).all():\n return torch.sin(x)\n else:\n return torch.cos(x)",
"_____no_output_____"
],
[
"x = torch.tensor([1.0], requires_grad=True)\ny = f(x)\ny.backward()\nprint(x.grad)",
"tensor([0.5403])\n"
]
],
[
[
"We could apply this to a larger vector too, but we need to make sure the output is a scalar:",
"_____no_output_____"
]
],
[
[
"x = torch.tensor([1.0, 0.5], requires_grad=True)\ny = f(x)\n# this is meant to break!\ny.backward()\nprint(x.grad)",
"_____no_output_____"
]
],
[
[
"Making the output a scalar:",
"_____no_output_____"
]
],
[
[
"x = torch.tensor([1.0, 0.5], requires_grad=True)\ny = f(x)\ny.sum().backward()\nprint(x.grad)",
"tensor([0.5403, 0.8776])\n"
]
],
[
[
"but there was an issue.. this isn't right for this edge case:",
"_____no_output_____"
]
],
[
[
"x = torch.tensor([1.0, -1], requires_grad=True)\ny = f(x)\ny.sum().backward()\nprint(x.grad)",
"tensor([-0.8415, 0.8415])\n"
],
[
"x = torch.tensor([-0.5, -1], requires_grad=True)\ny = f(x)\ny.sum().backward()\nprint(x.grad)",
"tensor([0.4794, 0.8415])\n"
]
],
[
[
"This is because we aren't doing the boolean computation and subsequent application of cos and sin on an elementwise basis. So, to solve this, it is common to use masking:",
"_____no_output_____"
]
],
[
[
"def f2(x):\n mask = torch.gt(x, 0).float()\n return mask * torch.sin(x) + (1 - mask) * torch.cos(x)\n\nx = torch.tensor([1.0, -1], requires_grad=True)\ny = f2(x)\ny.sum().backward()\nprint(x.grad)",
"tensor([0.5403, 0.8415])\n"
],
[
"def describe_grad(x):\n if x.grad is None:\n print(\"No gradient information\")\n else:\n print(\"Gradient: \\n{}\".format(x.grad))\n print(\"Gradient Function: {}\".format(x.grad_fn))",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"import torch\nx = torch.ones(2, 2, requires_grad=True)\ndescribe(x)\ndescribe_grad(x)\nprint(\"--------\")\n\ny = (x + 2) * (x + 5) + 3\ndescribe(y)\nz = y.mean()\ndescribe(z)\ndescribe_grad(x)\nprint(\"--------\")\nz.backward(create_graph=True, retain_graph=True)\ndescribe_grad(x)\nprint(\"--------\")\n",
"Type: torch.FloatTensor\nShape/size: torch.Size([2, 2])\nValues: \ntensor([[1., 1.],\n [1., 1.]], requires_grad=True)\nNo gradient information\n--------\nType: torch.FloatTensor\nShape/size: torch.Size([2, 2])\nValues: \ntensor([[21., 21.],\n [21., 21.]], grad_fn=<AddBackward0>)\nType: torch.FloatTensor\nShape/size: torch.Size([])\nValues: \n21.0\nNo gradient information\n--------\nGradient: \ntensor([[2.2500, 2.2500],\n [2.2500, 2.2500]], grad_fn=<CloneBackward>)\nGradient Function: None\n--------\n"
],
[
"x = torch.ones(2, 2, requires_grad=True)",
"_____no_output_____"
],
[
"y = x + 2",
"_____no_output_____"
],
[
"y.grad_fn",
"_____no_output_____"
]
],
[
[
"### CUDA Tensors",
"_____no_output_____"
],
[
"PyTorch's operations can seamlessly be used on the GPU or on the CPU. There are a couple basic operations for interacting in this way.",
"_____no_output_____"
]
],
[
[
"print(torch.cuda.is_available())",
"True\n"
],
[
"x = torch.rand(3,3)\ndescribe(x)",
"Type: torch.FloatTensor\nShape/size: torch.Size([3, 3])\nValues: \ntensor([[0.9149, 0.3993, 0.1100],\n [0.2541, 0.4333, 0.4451],\n [0.4966, 0.7865, 0.6604]])\n"
],
[
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)",
"cuda\n"
],
[
"x = torch.rand(3, 3).to(device)\ndescribe(x)\nprint(x.device)",
"Type: torch.cuda.FloatTensor\nShape/size: torch.Size([3, 3])\nValues: \ntensor([[0.1303, 0.3498, 0.3824],\n [0.8043, 0.3186, 0.2908],\n [0.4196, 0.3728, 0.3769]], device='cuda:0')\ncuda:0\n"
],
[
"cpu_device = torch.device(\"cpu\")",
"_____no_output_____"
],
[
"# this will break!\ny = torch.rand(3, 3)\nx + y",
"_____no_output_____"
],
[
"y = y.to(cpu_device)\nx = x.to(cpu_device)\nx + y",
"_____no_output_____"
],
[
"if torch.cuda.is_available(): # only is GPU is available\n a = torch.rand(3,3).to(device='cuda:0') # CUDA Tensor\n print(a)\n \n b = torch.rand(3,3).cuda()\n print(b)\n\n print(a + b)\n\n a = a.cpu() # Error expected\n print(a + b)",
"tensor([[0.5274, 0.6325, 0.0910],\n [0.2323, 0.7269, 0.1187],\n [0.3951, 0.7199, 0.7595]], device='cuda:0')\ntensor([[0.5311, 0.6449, 0.7224],\n [0.4416, 0.3634, 0.8818],\n [0.9874, 0.7316, 0.2814]], device='cuda:0')\ntensor([[1.0585, 1.2775, 0.8134],\n [0.6739, 1.0903, 1.0006],\n [1.3825, 1.4515, 1.0409]], device='cuda:0')\n"
]
],
[
[
"### Exercises\n\nSome of these exercises require operations not covered in the notebook. You will have to look at [the documentation](https://pytorch.org/docs/) (on purpose!)\n\n\n(Answers are at the bottom)",
"_____no_output_____"
],
[
"#### Exercise 1\n\nCreate a 2D tensor and then add a dimension of size 1 inserted at the 0th axis.",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 2\n\nRemove the extra dimension you just added to the previous tensor.",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 3\n\nCreate a random tensor of shape 5x3 in the interval [3, 7)",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 4\n\nCreate a tensor with values from a normal distribution (mean=0, std=1).",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 5\n\nRetrieve the indexes of all the non zero elements in the tensor torch.Tensor([1, 1, 1, 0, 1]).",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 6\n\nCreate a random tensor of size (3,1) and then horizonally stack 4 copies together.",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 7\n\nReturn the batch matrix-matrix product of two 3 dimensional matrices (a=torch.rand(3,4,5), b=torch.rand(3,5,4)).",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 8\n\nReturn the batch matrix-matrix product of a 3D matrix and a 2D matrix (a=torch.rand(3,4,5), b=torch.rand(5,4)).",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"Answers below",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"Answers still below.. Keep Going",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"#### Exercise 1\n\nCreate a 2D tensor and then add a dimension of size 1 inserted at the 0th axis.",
"_____no_output_____"
]
],
[
[
"a = torch.rand(3,3)\na = a.unsqueeze(0)\nprint(a)\nprint(a.shape)",
"_____no_output_____"
]
],
[
[
"#### Exercise 2 \n\nRemove the extra dimension you just added to the previous tensor.",
"_____no_output_____"
]
],
[
[
"a = a.squeeze(0)\nprint(a.shape)",
"_____no_output_____"
]
],
[
[
"#### Exercise 3\n\nCreate a random tensor of shape 5x3 in the interval [3, 7)",
"_____no_output_____"
]
],
[
[
"3 + torch.rand(5, 3) * 4",
"_____no_output_____"
]
],
[
[
"#### Exercise 4\n\nCreate a tensor with values from a normal distribution (mean=0, std=1).",
"_____no_output_____"
]
],
[
[
"a = torch.rand(3,3)\na.normal_(mean=0, std=1)",
"_____no_output_____"
]
],
[
[
"#### Exercise 5\n\nRetrieve the indexes of all the non zero elements in the tensor torch.Tensor([1, 1, 1, 0, 1]).",
"_____no_output_____"
]
],
[
[
"a = torch.Tensor([1, 1, 1, 0, 1])\ntorch.nonzero(a)",
"_____no_output_____"
]
],
[
[
"#### Exercise 6\n\nCreate a random tensor of size (3,1) and then horizonally stack 4 copies together.",
"_____no_output_____"
]
],
[
[
"a = torch.rand(3,1)\na.expand(3,4)",
"_____no_output_____"
]
],
[
[
"#### Exercise 7\n\nReturn the batch matrix-matrix product of two 3 dimensional matrices (a=torch.rand(3,4,5), b=torch.rand(3,5,4)).",
"_____no_output_____"
]
],
[
[
"a = torch.rand(3,4,5)\nb = torch.rand(3,5,4)\ntorch.bmm(a, b)",
"_____no_output_____"
]
],
[
[
"#### Exercise 8\n\nReturn the batch matrix-matrix product of a 3D matrix and a 2D matrix (a=torch.rand(3,4,5), b=torch.rand(5,4)).",
"_____no_output_____"
]
],
[
[
"a = torch.rand(3,4,5)\nb = torch.rand(5,4)\ntorch.bmm(a, b.unsqueeze(0).expand(a.size(0), *b.size()))",
"_____no_output_____"
]
],
[
[
"### END",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba310a136089707a714996b9ec2e881f6c5f845
| 6,909 |
ipynb
|
Jupyter Notebook
|
site/zh-cn/tutorials/quickstart/beginner.ipynb
|
ilyaspiridonov/docs-l10n
|
a061a44e40d25028d0a4458094e48ab717d3565c
|
[
"Apache-2.0"
] | 1 |
2021-09-23T09:56:29.000Z
|
2021-09-23T09:56:29.000Z
|
site/zh-cn/tutorials/quickstart/beginner.ipynb
|
ilyaspiridonov/docs-l10n
|
a061a44e40d25028d0a4458094e48ab717d3565c
|
[
"Apache-2.0"
] | null | null | null |
site/zh-cn/tutorials/quickstart/beginner.ipynb
|
ilyaspiridonov/docs-l10n
|
a061a44e40d25028d0a4458094e48ab717d3565c
|
[
"Apache-2.0"
] | 1 |
2020-06-23T07:43:49.000Z
|
2020-06-23T07:43:49.000Z
| 29.780172 | 260 | 0.508901 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# 初学者的 TensorFlow 2.0 教程",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://tensorflow.google.cn/tutorials/quickstart/beginner\"><img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\" />在 TensorFlow.org 观看</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/tutorials/quickstart/beginner.ipynb\"><img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\" />在 Google Colab 运行</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/tutorials/quickstart/beginner.ipynb\"><img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\" />在 GitHub 查看源代码</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/tutorials/quickstart/beginner.ipynb\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\" />下载笔记本</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"Note: 我们的 TensorFlow 社区翻译了这些文档。因为社区翻译是尽力而为, 所以无法保证它们是最准确的,并且反映了最新的\n[官方英文文档](https://tensorflow.google.cn/?hl=en)。如果您有改进此翻译的建议, 请提交 pull request 到\n[tensorflow/docs](https://github.com/tensorflow/docs) GitHub 仓库。要志愿地撰写或者审核译文,请加入\n[[email protected] Google Group](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-zh-cn)。",
"_____no_output_____"
],
[
"这是一个 [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) 笔记本文件。 Python程序可以直接在浏览器中运行,这是学习 Tensorflow 的绝佳方式。想要学习该教程,请点击此页面顶部的按钮,在Google Colab中运行笔记本。\n\n1. 在 Colab中, 连接到Python运行环境: 在菜单条的右上方, 选择 *CONNECT*。\n2. 运行所有的代码块: 选择 *Runtime* > *Run all*。",
"_____no_output_____"
],
[
"下载并安装 TensorFlow 2.0 测试版包。将 TensorFlow 载入你的程序:",
"_____no_output_____"
]
],
[
[
"# 安装 TensorFlow\n\nimport tensorflow as tf",
"_____no_output_____"
]
],
[
[
"载入并准备好 [MNIST 数据集](http://yann.lecun.com/exdb/mnist/)。将样本从整数转换为浮点数:",
"_____no_output_____"
]
],
[
[
"mnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0",
"_____no_output_____"
]
],
[
[
"将模型的各层堆叠起来,以搭建 `tf.keras.Sequential` 模型。为训练选择优化器和损失函数:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"训练并验证模型:",
"_____no_output_____"
]
],
[
[
"model.fit(x_train, y_train, epochs=5)\n\nmodel.evaluate(x_test, y_test, verbose=2)",
"_____no_output_____"
]
],
[
[
"现在,这个照片分类器的准确度已经达到 98%。想要了解更多,请阅读 [TensorFlow 教程](https://tensorflow.google.cn/tutorials/)。",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba31109df0523436141ebb61c8561bd4cf5a48b
| 990,925 |
ipynb
|
Jupyter Notebook
|
notebooks/dems_coreg_demo.ipynb
|
xinluo2018/Glacier-in-RGI1305
|
74468e7c9b438acdb5b6624efb0a8fa9c9634c19
|
[
"MIT"
] | null | null | null |
notebooks/dems_coreg_demo.ipynb
|
xinluo2018/Glacier-in-RGI1305
|
74468e7c9b438acdb5b6624efb0a8fa9c9634c19
|
[
"MIT"
] | null | null | null |
notebooks/dems_coreg_demo.ipynb
|
xinluo2018/Glacier-in-RGI1305
|
74468e7c9b438acdb5b6624efb0a8fa9c9634c19
|
[
"MIT"
] | 1 |
2021-11-23T05:56:38.000Z
|
2021-11-23T05:56:38.000Z
| 2,262.385845 | 498,002 | 0.961212 |
[
[
[
"## DEMs coregistration demo\n### Note: The data for co-registration should be utm projected.\n",
"_____no_output_____"
]
],
[
[
"import os\nroot_proj = '/Users/luo/OneDrive/GitHub/Glacier-in-RGI1305'\nos.chdir(root_proj)",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom utils.geotif_io import readTiff, writeTiff\nfrom utils.imgShow import imgShow\nfrom utils.crop_to_extent import crop_to_extent\nfrom utils.raster_vec import vec2mask\nimport pybob.coreg_tools as ct\nfrom pybob.GeoImg import GeoImg\n",
"_____no_output_____"
],
[
"path_srtm = 'data/dem-data/srtm-c/SRTMGL1_E_wkunlun_utm.tif' # master dem\npath_tandem = 'data/dem-data/tandem-x/dems_mosaic_wkunlun_utm.tif' # slave dem\npath_l8img = 'data/rsimg/l8_kunlun_20200914.tif'\npath_water_jrc = 'data/water_jrc/wkl_water_jrc_utm.tif' # jrc water map for water mask\npath_rgi_1305 = 'data/rgi60-wkunlun/rgi60_1305.gpkg' # rgi glacier data for glacier mask\n",
"_____no_output_____"
],
[
"srtm, srtm_info = readTiff(path_srtm) # master dem\ntandem, tandem_info = readTiff(path_tandem) # slave dem\nl8_img, l8_img_info = readTiff(path_l8img) \nwater_jrc, water_jrc_info = readTiff(path_water_jrc)\nprint('srtm shape:', srtm.shape, 'extent:', srtm_info['geoextent'])\nprint('tandem shape:', tandem.shape, 'extent', tandem_info['geoextent'])\nprint('water_jrc shape:', water_jrc.shape, 'extent', water_jrc_info['geoextent'])\n",
"srtm shape: (3507, 5552) extent: (419416.44565371965, 585976.4456537196, 3862741.200990109, 3967951.200990109)\ntandem shape: (1323, 2095) extent (419416.4456505731, 586024.4012380684, 3862737.9219186474, 3967951.442320679)\nwater_jrc shape: (4091, 6476) extent (419403.8461468267, 585958.2539156231, 3862780.053972968, 3967995.3229942997)\n"
],
[
"### Image alignment for the tandem data.\ntandem_align = crop_to_extent(path_img=path_tandem, \\\n extent=srtm_info['geoextent'], size_target=srtm.shape)\nprint('aligned tandem shape:', tandem_align.shape)\n",
"aligned tandem shape: (3507, 5552)\n"
]
],
[
[
"### Check dem image",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15,5))\nplt.subplot(1,3,1); imgShow(l8_img); plt.title('rs image')\nplt.subplot(1,3,2); plt.imshow(srtm, vmin=2000, vmax=7000); plt.title('srtm (master)')\nplt.subplot(1,3,3); plt.imshow(tandem_align, vmin=2000, vmax=7000); plt.title('aligned tandem (slave)')\n",
"_____no_output_____"
]
],
[
[
"### **1. Generate mask image.**",
"_____no_output_____"
]
],
[
[
"### -- 2.1. water mask\nwater_jrc_crop = crop_to_extent(path_img=path_water_jrc, \\\n extent=srtm_info['geoextent'], size_target=srtm.shape)\nwater_jrc_crop = np.ma.masked_where(water_jrc_crop>50, water_jrc_crop)\n### -- 2.2. glacier mask\nrgi60_mask = vec2mask(path_vec=path_rgi_1305, path_raster=path_srtm, path_save=None)\nrgi60_mask = np.ma.masked_equal(rgi60_mask, 1)\n### -- 2.3 merge the water and glacier masks\nmask = np.logical_or.reduce([water_jrc_crop.mask, rgi60_mask.mask])\nplt.imshow(mask); plt.title('water/glacier mask image')\nprint(mask.shape)\n",
"(3507, 5552)\n"
]
],
[
[
"### **2. Co-registration to srtm-c dem by using open-source pybob code.**\n##### Reference: Nuth and Kääb (2011) (https://www.the-cryosphere.net/5/271/2011/tc-5-271-2011.html)\n",
"_____no_output_____"
]
],
[
[
"srtm_geo = GeoImg(path_srtm) # master dem\ntandem_geo = srtm_geo.copy(new_raster=tandem_align)\nslope_geo = ct.get_slope(srtm_geo) # calculate slope from master DEM, scale is 111120 if using wgs84 projection\naspect_geo = ct.get_aspect(srtm_geo) # calculate aspect from master DEM\nprint(srtm_geo.img.shape, tandem_geo.img.shape)\n",
"(3507, 5552) (3507, 5552)\n"
],
[
"init_dh_geo = tandem_geo.copy(new_raster=tandem_geo.img-srtm_geo.img) # initial dem difference (a new GeoImg dataset)\n",
"_____no_output_____"
]
],
[
[
"### **2.1. co-registration and obtain the adjust values**",
"_____no_output_____"
]
],
[
[
"## --- 1. copy the slave_dem as the medium processing dem\ntandem_proc = tandem_geo.copy() # make a copy of the slave DEM\n## --- 2. pre-processing: data mask by provided mask data and the calculated outlier values; \n## xdata->masked aspect, ydata->masked dH, sdata->masked tan(a)\ndH, xdata, ydata, sdata = ct.preprocess(stable_mask=mask, slope=slope_geo.img, \\\n aspect=aspect_geo.img, master=srtm_geo, slave=tandem_proc)\nfig = ct.false_hillshade(dH, 'DEM difference before coregistration', clim=(-5, 5)) \n## --- 3. initial the shift values (will be updated during this process).\n## --- 4. co-registration, obtain the adjust values.\nxadj, yadj, zadj = ct.coreg_fitting(xdata, ydata, sdata, 'Iteration 1')\n",
"_____no_output_____"
]
],
[
[
"### **2.2. Rectify the original image with obtained shift values**",
"_____no_output_____"
]
],
[
[
"## update the shift values\nx_shift = y_shift = z_shift = 0\nx_shift += xadj; y_shift += yadj; z_shift += zadj\nprint('shift values (x,y,z):', x_shift, y_shift, z_shift)\n## --- 1. rectify the x and y. \ntandem_proc.shift(xadj, yadj) # rectify the slave dem in terms of x and y.\ntandem_proc = tandem_proc.reproject(srtm_geo) # re-align the grid of the slave DEMs after shifting\n## --- 2. rectify the z. \ntandem_proc = tandem_proc.copy(new_raster=tandem_proc.img + zadj) # shift the DEM in the z direction\nfinal_dh_geo = tandem_geo.copy(new_raster=tandem_proc.img - srtm_geo.img)\n\n",
"shift values (x,y,z): 3.0381334764306382 -3.039058643914944 1.1738292718830416\n"
]
],
[
[
"### **2.3. Co-registration with more iterations**",
"_____no_output_____"
]
],
[
[
"def dems_coreg(master_geo, slave_geo, mask_img, iteration=10):\n slope_geo = ct.get_slope(master_geo) # calculate slope from master DEM\n aspect_geo = ct.get_aspect(master_geo) # calculate aspect from master DEM\n slave_proc = slave_geo.copy() # make a copy of the slave DEM\n for i in range(iteration):\n x_shift = y_shift = z_shift = 0\n dH, xdata, ydata, sdata = ct.preprocess(stable_mask=mask_img, slope=slope_geo.img, \\\n aspect=aspect_geo.img, master=master_geo, slave=slave_proc) \n ## --- 1. calculate shift values.\n i_iter = 'Iteration '+str(i)\n xadj, yadj, zadj = ct.coreg_fitting(xdata, ydata, sdata, i_iter, plot=False)\n x_shift += xadj; y_shift += yadj; z_shift += zadj # update shift value\n ## --- 2. rectify original dem.\n slave_proc.shift(xadj, yadj) # rectify the slave dem in terms of x and y.\n slave_proc = slave_proc.reproject(master_geo) # re-align the grid of the slave DEMs after shifting\n slave_proc = slave_proc.copy(new_raster=slave_proc.img + zadj) # shift the DEM in the z direction\n print('shift values in iteration '+str(i)+' (x,y,z):', x_shift, y_shift, z_shift) \n return slave_proc\n\ntandem_coreg = dems_coreg(master_geo=srtm_geo, slave_geo=tandem_geo, mask_img=mask, iteration=10)\ninit_dh_geo = tandem_geo.copy(new_raster=tandem_geo.img-srtm_geo.img) # initial dem difference (GeoImg dataset)\nfinal_dh_geo = tandem_geo.copy(new_raster=tandem_coreg.img-srtm_geo.img) # initial dem difference\n",
"shift values in iteration 0 (x,y,z): 3.086826484301052 -3.4302253581665103 1.2375578399656502\nshift values in iteration 1 (x,y,z): 0.3078200682936388 -0.14352624005213052 -0.049469864415575146\nshift values in iteration 2 (x,y,z): 0.049933608038714695 0.1657092274843274 0.048265138731820915\nshift values in iteration 3 (x,y,z): -0.052875947456714714 -0.10146845626810419 -0.04805867509497533\nshift values in iteration 4 (x,y,z): 0.2035946531382787 -0.035162008263319146 0.005104704043471281\nshift values in iteration 5 (x,y,z): 0.32164326099987794 0.06764316069074304 0.013817387489440272\nshift values in iteration 6 (x,y,z): -0.10603275481660583 0.306496790019171 0.006532819981278867\nshift values in iteration 7 (x,y,z): -0.13930392177187972 -0.38585162475927354 -0.028815656054925455\nshift values in iteration 8 (x,y,z): -0.035097394999452046 -0.04861996835982455 0.02750472131483567\nshift values in iteration 9 (x,y,z): 0.031617633850804634 -0.044204663165592614 0.011223597622533863\n"
]
],
[
[
"### **Visualize the dems difference before and affter co-registration**",
"_____no_output_____"
]
],
[
[
"fig1 = plt.figure(figsize=(14,4))\nplt.subplot(1,2,1)\nplt.imshow(init_dh_geo.img, vmin=-10, vmax=10, cmap='RdYlBu')\ncb = plt.colorbar(fraction=0.03, pad=0.02); \n# cb.set_label('elevation difference (m)')\nplt.title('before co-registration')\n\nplt.subplot(1,2,2)\nplt.imshow(final_dh_geo.img, vmin=-10, vmax=10, cmap='RdYlBu')\ncb = plt.colorbar(fraction=0.03, pad=0.02); \ncb.set_label('elevation difference (m)')\nplt.title('after co-registration')\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba31d565178aac61ba31f698e5a991af5dcc250
| 124,699 |
ipynb
|
Jupyter Notebook
|
Notebooks/CreateFigures/Figures13_and_14.ipynb
|
HiRISE-MachineLearning/HiRISE-MachineLearning-Python
|
66b81ca24bf8828fbcb218da3359d05349e6c381
|
[
"0BSD"
] | null | null | null |
Notebooks/CreateFigures/Figures13_and_14.ipynb
|
HiRISE-MachineLearning/HiRISE-MachineLearning-Python
|
66b81ca24bf8828fbcb218da3359d05349e6c381
|
[
"0BSD"
] | null | null | null |
Notebooks/CreateFigures/Figures13_and_14.ipynb
|
HiRISE-MachineLearning/HiRISE-MachineLearning-Python
|
66b81ca24bf8828fbcb218da3359d05349e6c381
|
[
"0BSD"
] | null | null | null | 535.188841 | 76,236 | 0.944314 |
[
[
[
"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix,balanced_accuracy_score,roc_auc_score,roc_curve\nfrom p4tools import io",
"_____no_output_____"
],
[
"ResultsPath = '../../Data/SummaryResults/'\nFiguresPath = '../../Data/Figures/'\nif not os.path.isdir(FiguresPath):\n os.mkdir(FiguresPath)\n \nNumRepeats=3\n\nResultsList=[]\nfor Rep in range(NumRepeats):\n ResultsList.append(pd.read_csv(ResultsPath+'TileClassifier_LORO_final_repeat'+str(Rep)+'.csv'))\n \nY_true=ResultsList[-1]['GroundTruth'].astype('uint8')\n\nY_pred=ResultsList[0]['ClassifierConf'].values\nfor Rep in range(1,NumRepeats):\n Y_pred=Y_pred+ResultsList[Rep]['ClassifierConf'].values\nY_pred=Y_pred/NumRepeats\n\nResults_df = ResultsList[-1]\nResults_df['ClassifierConf']=Y_pred",
"_____no_output_____"
],
[
"Recall95PC_Threshold=0.24\n\nAUC = roc_auc_score(Y_true, Y_pred)\nconf_matrix = confusion_matrix(Y_true,Y_pred>Recall95PC_Threshold,labels=[0,1])\nSensitivity = conf_matrix[1,1]/(conf_matrix[1,0]+conf_matrix[1,1])\nSpecificity = conf_matrix[0,0]/(conf_matrix[0,0]+conf_matrix[0,1])\nPrecision = conf_matrix[1,1]/(conf_matrix[1,1]+conf_matrix[0,1])\nBalanced_accuracy = balanced_accuracy_score(Y_true, Y_pred>Recall95PC_Threshold)\n\nprint('Number of tiles classified in Leave-One-Region-Out Cross-Validation= ',Results_df.shape[0])\nprint('')\nprint('Confusion matrix = ')\nprint(conf_matrix)\nprint('')\nprint('sensitivity=',round(100*Sensitivity,2),'%')\nprint('Specificity=',round(100*Specificity,2),'%')\nprint('Precision=',round(100*Precision,2),'%')\nprint('AUC=',round(AUC,3))\nprint('Balanced Accuracy =',round(100*Balanced_accuracy))\n\n",
"Number of tiles classified in Leave-One-Region-Out Cross-Validation= 42904\n\nConfusion matrix = \n[[ 5388 4513]\n [ 1661 31342]]\n\nsensitivity= 94.97 %\nSpecificity= 54.42 %\nPrecision= 87.41 %\nAUC= 0.934\nBalanced Accuracy = 75\n"
],
[
"fig = plt.figure(figsize=(10,10))\nfpr, tpr, thresholds = roc_curve(Y_true, Y_pred)\nplt.plot(1-fpr,tpr,linewidth=3)\nplt.xlabel('Specificity',fontsize=20)\nplt.ylabel('Recall',fontsize=20)\n\nplt.plot(Specificity,Sensitivity,'og',linewidth=30,markersize=20)\n\nplt.text(0.5, 0.5, 'AUC='+str(round(AUC,2)), fontsize=20)\nplt.text(0.2, 0.9, '95% recall point at', fontsize=20,color='green')\nplt.text(0.2, 0.85, '54% specificity', fontsize=20,color='green')\n\n\nmatplotlib.rc('xtick', labelsize=20) \nmatplotlib.rc('ytick', labelsize=20)\n\nfig.tight_layout()\nplt.savefig(FiguresPath+'Figure13.pdf')\nplt.show()",
"_____no_output_____"
],
[
"#regions\nregion_names_df = io.get_region_names()\nregion_names_df = region_names_df.set_index('obsid')\nregion_names_df.at['ESP_012620_0975','roi_name'] = 'Buffalo'\nregion_names_df.at['ESP_012277_0975','roi_name'] = 'Buffalo'\nregion_names_df.at['ESP_012348_0975','roi_name'] = 'Taichung'\n\n#other meta data\nImageResults_df = io.get_meta_data()\nImageResults_df = ImageResults_df.set_index('OBSERVATION_ID')\nImageResults_df = pd.concat([ImageResults_df, region_names_df], axis=1, sort=False)\nImageResults_df=ImageResults_df.dropna()\nUniqueP4Regions = ImageResults_df['roi_name'].unique()\nprint(\"Number of P4 regions = \",len(UniqueP4Regions))\n\nBAs=[]\nfor ToLeaveOut in UniqueP4Regions:\n This_df = Results_df[Results_df['Region']==ToLeaveOut]\n y_true = This_df['GroundTruth'].values\n y_pred = This_df['ClassifierConf'].values\n Balanced_accuracy_cl = balanced_accuracy_score(y_true, y_pred>0.5)\n BAs.append(Balanced_accuracy_cl)\nregions_sorted=[x for y, x in sorted(zip(BAs,UniqueP4Regions))]\n\nfig=plt.figure(figsize=(15,15))\nplt.bar(regions_sorted,100*np.array(sorted(BAs)))\nax=fig.gca()\nax.set_xticks(np.arange(0,len(regions_sorted)))\nax.set_xticklabels(regions_sorted,rotation=90,fontsize=20)\nax.set_ylabel('Balanced Accuracy (%)',fontsize=30)\nmatplotlib.rc('xtick', labelsize=30) \nmatplotlib.rc('ytick', labelsize=30)\nfig.tight_layout()\nplt.savefig(FiguresPath+'Figure14.pdf')\nplt.show()",
"Number of P4 regions = 28\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
cba325d424489cb07a84968a9445fbe8c4920db4
| 82,397 |
ipynb
|
Jupyter Notebook
|
5_aug_pretrained.ipynb
|
gaeunkim0721/CNN-Cats-Dogs1
|
531491634534ae74052760098bec3669c629ba52
|
[
"MIT"
] | null | null | null |
5_aug_pretrained.ipynb
|
gaeunkim0721/CNN-Cats-Dogs1
|
531491634534ae74052760098bec3669c629ba52
|
[
"MIT"
] | null | null | null |
5_aug_pretrained.ipynb
|
gaeunkim0721/CNN-Cats-Dogs1
|
531491634534ae74052760098bec3669c629ba52
|
[
"MIT"
] | null | null | null | 93.209276 | 44,726 | 0.761775 |
[
[
[
"<a href=\"https://colab.research.google.com/github/JSJeong-me/CNN-Cats-Dogs/blob/main/5_aug_pretrained.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"!ls -l",
"total 8\ndrwx------ 5 root root 4096 Jan 24 20:23 drive\ndrwxr-xr-x 1 root root 4096 Jan 20 17:27 sample_data\n"
],
[
"!cp ./drive/MyDrive/training_data.zip .",
"_____no_output_____"
],
[
"!unzip training_data.zip\r\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img",
"_____no_output_____"
],
[
"IMG_DIM = (150, 150)\n\ntrain_files = glob.glob('training_data/*')\ntrain_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in train_files]\ntrain_imgs = np.array(train_imgs)\ntrain_labels = [fn.split('/')[1].split('.')[0].strip() for fn in train_files]\n\nvalidation_files = glob.glob('validation_data/*')\nvalidation_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in validation_files]\nvalidation_imgs = np.array(validation_imgs)\nvalidation_labels = [fn.split('/')[1].split('.')[0].strip() for fn in validation_files]\n\nprint('Train dataset shape:', train_imgs.shape, \n '\\tValidation dataset shape:', validation_imgs.shape)",
"Train dataset shape: (3000, 150, 150, 3) \tValidation dataset shape: (1000, 150, 150, 3)\n"
],
[
"train_imgs_scaled = train_imgs.astype('float32')\nvalidation_imgs_scaled = validation_imgs.astype('float32')\ntrain_imgs_scaled /= 255\nvalidation_imgs_scaled /= 255",
"_____no_output_____"
],
[
"batch_size = 50\nnum_classes = 2\nepochs = 150\ninput_shape = (150, 150, 3)\n\nfrom sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\nle.fit(train_labels)\n# encode wine type labels\ntrain_labels_enc = le.transform(train_labels)\nvalidation_labels_enc = le.transform(validation_labels)\n\nprint(train_labels[0:5], train_labels_enc[0:5])",
"['cat', 'cat', 'cat', 'dog', 'cat'] [0 0 0 1 0]\n"
],
[
"",
"_____no_output_____"
],
[
"train_datagen = ImageDataGenerator( zoom_range=0.3, rotation_range=50, # rescale=1./255,\r\n width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, \r\n horizontal_flip=True, fill_mode='nearest')\r\n\r\nval_datagen = ImageDataGenerator() # rescale=1./255\r\n\r\ntrain_generator = train_datagen.flow(train_imgs, train_labels_enc, batch_size=30)\r\nval_generator = val_datagen.flow(validation_imgs, validation_labels_enc, batch_size=20)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"\nfrom tensorflow.keras.applications import vgg16\nfrom tensorflow.keras.models import Model\nimport tensorflow.keras\n\nvgg = vgg16.VGG16(include_top=False, weights='imagenet',\n input_shape=input_shape)\n\noutput = vgg.layers[-1].output\noutput = tensorflow.keras.layers.Flatten()(output)\n\nvgg_model = Model(vgg.input, output)\nvgg_model.trainable = False\n\nfor layer in vgg_model.layers:\n layer.trainable = False\n\nvgg_model.summary()\n",
"_____no_output_____"
],
[
"vgg_model.trainable = True\r\n\r\nset_trainable = False\r\nfor layer in vgg_model.layers:\r\n if layer.name in ['block5_conv1', 'block4_conv1']:\r\n set_trainable = True\r\n if set_trainable:\r\n layer.trainable = True\r\n else:\r\n layer.trainable = False\r\n \r\nprint(\"Trainable layers:\", vgg_model.trainable_weights)",
"_____no_output_____"
],
[
"import pandas as pd\npd.set_option('max_colwidth', -1)\n\nlayers = [(layer, layer.name, layer.trainable) for layer in vgg_model.layers]\npd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])",
"/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n \n"
],
[
"",
"_____no_output_____"
],
[
"#print(\"Trainable layers:\", vgg_model.trainable_weights)",
"_____no_output_____"
],
[
"bottleneck_feature_example = vgg.predict(train_imgs_scaled[0:1])\nprint(bottleneck_feature_example.shape)\nplt.imshow(bottleneck_feature_example[0][:,:,0])",
"(1, 4, 4, 512)\n"
],
[
"def get_bottleneck_features(model, input_imgs):\n \n features = model.predict(input_imgs, verbose=0)\n return features",
"_____no_output_____"
],
[
"train_features_vgg = get_bottleneck_features(vgg_model, train_imgs_scaled)\nvalidation_features_vgg = get_bottleneck_features(vgg_model, validation_imgs_scaled)\n\nprint('Train Bottleneck Features:', train_features_vgg.shape, \n '\\tValidation Bottleneck Features:', validation_features_vgg.shape)",
"Train Bottleneck Features: (3000, 8192) \tValidation Bottleneck Features: (1000, 8192)\n"
],
[
"",
"_____no_output_____"
],
[
"from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayer\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras import optimizers\r\n\r\nmodel = Sequential()\r\nmodel.add(vgg_model)\r\nmodel.add(Dense(512, activation='relu', input_dim=input_shape))\r\nmodel.add(Dropout(0.3))\r\nmodel.add(Dense(512, activation='relu'))\r\nmodel.add(Dropout(0.3))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\n\r\nmodel.compile(loss='binary_crossentropy',\r\n optimizer=optimizers.RMSprop(lr=2e-5),\r\n metrics=['accuracy'])\r\n\r\nmodel.summary()",
"_____no_output_____"
],
[
"history = model.fit_generator(train_generator, epochs=30,\r\n validation_data=val_generator, verbose=1)",
"/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1844: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n warnings.warn('`Model.fit_generator` is deprecated and '\n"
],
[
"",
"_____no_output_____"
],
[
"f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\nt = f.suptitle('Pre-trained CNN (Transfer Learning) Performance', fontsize=12)\nf.subplots_adjust(top=0.85, wspace=0.3)\n\nepoch_list = list(range(1,31))\nax1.plot(epoch_list, history.history['accuracy'], label='Train Accuracy')\nax1.plot(epoch_list, history.history['val_accuracy'], label='Validation Accuracy')\nax1.set_xticks(np.arange(0, 31, 5))\nax1.set_ylabel('Accuracy Value')\nax1.set_xlabel('Epoch')\nax1.set_title('Accuracy')\nl1 = ax1.legend(loc=\"best\")\n\nax2.plot(epoch_list, history.history['loss'], label='Train Loss')\nax2.plot(epoch_list, history.history['val_loss'], label='Validation Loss')\nax2.set_xticks(np.arange(0, 31, 5))\nax2.set_ylabel('Loss Value')\nax2.set_xlabel('Epoch')\nax2.set_title('Loss')\nl2 = ax2.legend(loc=\"best\")",
"_____no_output_____"
],
[
"model.save('4-2-augpretrained_cnn.h5')",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba327e33496935b5c3492d8a5dff518b5f4df17
| 55,528 |
ipynb
|
Jupyter Notebook
|
dcookies.ipynb
|
robertoalotufo/ia870p3
|
aa3cca44dfb4f0323d5ccfcbe0ee336f30c23461
|
[
"BSD-2-Clause"
] | 5 |
2018-10-15T12:02:03.000Z
|
2022-02-11T12:47:12.000Z
|
dcookies.ipynb
|
robertoalotufo/ia870p3
|
aa3cca44dfb4f0323d5ccfcbe0ee336f30c23461
|
[
"BSD-2-Clause"
] | 1 |
2018-10-15T12:04:36.000Z
|
2019-01-25T12:04:35.000Z
|
dcookies.ipynb
|
robertoalotufo/ia870p3
|
aa3cca44dfb4f0323d5ccfcbe0ee336f30c23461
|
[
"BSD-2-Clause"
] | 4 |
2019-01-25T11:13:48.000Z
|
2020-12-20T01:42:33.000Z
| 213.569231 | 23,896 | 0.927532 |
[
[
[
"## mmdcookies\nDetect broken rounded biscuits.",
"_____no_output_____"
],
[
"## Description\nThe input image is a gray-scale image of two rounded-shaped biscuits. One of them is broken. The purpose is to detect the broken biscuit.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom PIL import Image\nimport ia870 as ia",
"_____no_output_____"
]
],
[
[
"# Reading\nThe input image is read",
"_____no_output_____"
]
],
[
[
"a_pil = Image.open('data/cookies.tif').convert('L')\na_pil",
"_____no_output_____"
],
[
"a = np.array (a_pil)",
"_____no_output_____"
]
],
[
[
"# Thresholding\nConvert to binary objects by thresholding ",
"_____no_output_____"
]
],
[
[
"b = ia.iathreshad(a, 100);\nImage.fromarray(b.astype(np.uint8)*255)",
"_____no_output_____"
]
],
[
[
"# Open tophat with large octagon disk\n\nThe tophat of the binary image by an octagon disk with a radius fits the good biscuit but does not fit in the broken biscuit can detect the broken one. ",
"_____no_output_____"
]
],
[
[
"c = ia.iaopenth(b,ia.iasedisk(55,'2D','OCTAGON'));\nImage.fromarray(c.astype(np.uint8)*255)",
"_____no_output_____"
]
],
[
[
"# Remove the residues\nClean the residues from the octagon disk and the rounded shaped biscuits by eliminating small connected regions ",
"_____no_output_____"
]
],
[
[
"d = ia.iaareaopen(c,400);\nImage.fromarray(d.astype(np.uint8)*255)",
"_____no_output_____"
]
],
[
[
"# Final display\nDisplay the detected broken biscuit ",
"_____no_output_____"
]
],
[
[
"Image.fromarray(ia.iagshow(a, d).transpose(1, 2, 0))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba3290f080a3df1b211eb8db7ac2bef48198620
| 310,114 |
ipynb
|
Jupyter Notebook
|
notebooks/CircuitModel_modified.ipynb
|
sgkang/PhysPropIP
|
cbe6042afd2a6f4f7bec5dbfaf0a6af37ad010ff
|
[
"MIT"
] | null | null | null |
notebooks/CircuitModel_modified.ipynb
|
sgkang/PhysPropIP
|
cbe6042afd2a6f4f7bec5dbfaf0a6af37ad010ff
|
[
"MIT"
] | 9 |
2015-11-18T03:34:05.000Z
|
2015-11-27T04:15:02.000Z
|
notebooks/CircuitModel_modified.ipynb
|
sgkang/PhysPropIP
|
cbe6042afd2a6f4f7bec5dbfaf0a6af37ad010ff
|
[
"MIT"
] | null | null | null | 146.073481 | 39,684 | 0.811634 |
[
[
[
"<img src=\"./img/Circuit.png\" style=\"width: 50%; height: 50%\"> </img>",
"_____no_output_____"
],
[
"<img src=\"./img/treqs.png\" style=\"width: 50%; height: 50%\"> </img>",
"_____no_output_____"
],
[
"$$ CPE_{x} = \\frac{1}{Q_x(\\imath\\omega)^{p_x}}, \\ x=H, M, L, E $$",
"_____no_output_____"
],
[
"$$ R(\\omega) = R_{\\infty}+\\sum_{x=H, M, L, E}\\frac{1}{\\frac{1}{R_x}+\\frac{1}{CPE_x(\\omega)}}$$",
"_____no_output_____"
],
[
"$$ R(\\omega) = R_{\\infty}+\\sum_{x=M, L}\\frac{1}{\\frac{1}{R_x}+\\frac{1}{CPE_x(\\omega)}}$$",
"_____no_output_____"
],
[
"- H: High frequency\n- M: Middle (possibly ",
"_____no_output_____"
]
],
[
[
"%pylab inline",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"data = pd.read_excel(\"../data/Kimberlite-2015-07-17.xls\")",
"_____no_output_____"
],
[
"data_active = data.loc[np.logical_and((data['Facies'] == 'XVK')|(data['Facies'] == 'PK')|(data['Facies'] == 'HK')|(data['Facies'] == 'VK'), data.notnull()['Rinf']==True)][[\"Facies\", \"Peregrine ID\", \"(Latitude)\", \"(Longitude)\", \"Depth (m)\",\"Mag Susc [SI]\",\"Resistivity [Ohm.m]\",\"Geometric Factor [m]\",\"Sat Geometric Dens [g/cc]\",\"Chargeability [ms]\",\"Rinf\",\"Ro\",\"Rh\",\"Qh\",\"Ph\", \"pRh\", \"pQh\",\"Rm\",\"Qm\",\"Pm\", \"pRm\", \"pQm\",\"Rl\",\"Ql\",\"Pl\", \"pRl\", \"pQl\",\"Re\",\"Qe\",\"Pe-f\",\"Pe-i\"]]",
"_____no_output_____"
],
[
"data_active",
"_____no_output_____"
],
[
"def CPEfun(Rx, Fx, px, freq):\n out = np.zeros_like(freq, dtype=complex128)\n out = 1./(1./Rx + Qx*(np.pi*2*freq*1j)**px)\n return out\ndef CPEfunElec(Rx, Qx, pex, pix, freq):\n out = np.zeros_like(freq, dtype=complex128)\n out = 1./(1./Rx + (1j)**pix*Qx*(np.pi*2*freq)**pex)\n return out\ndef CPEfunSeries(Rx, Qx, px, freq):\n out = np.zeros_like(freq, dtype=complex128)\n out = Rx + 1./(Qx*(np.pi*2*freq*1j)**px)\n return out\n\nf0peak = lambda R, Q, P: (R*Q)**(-1./P)/np.pi/2.\ntaupeak = lambda R, Q, P: (R*Q)**(1./P)\nrhoinf = lambda rhom, rhol, rho0: 1./(1./rho0+1./rhom+1./rhol)\ncharg = lambda rhoinf, rho0: (rho0-rhoinf) / rhoinf",
"_____no_output_____"
],
[
"def TKCColeColeParallel(frequency, PID, data):\n Rh, Qh, Ph = data[data[\"Peregrine ID\"]==PID]['pRh'].values[0], data[data[\"Peregrine ID\"]==PID]['pQh'].values[0], data[data[\"Peregrine ID\"]==PID]['Ph'].values[0]\n Rm, Qm, Pm = data[data[\"Peregrine ID\"]==PID]['pRm'].values[0], data[data[\"Peregrine ID\"]==PID]['pQm'].values[0], data[data[\"Peregrine ID\"]==PID]['Pm'].values[0]\n Rl, Ql, Pl = data[data[\"Peregrine ID\"]==PID]['pRl'].values[0], data[data[\"Peregrine ID\"]==PID]['pQl'].values[0], data[data[\"Peregrine ID\"]==PID]['Pl'].values[0] \n geom = data[data[\"Peregrine ID\"]==PID]['Geometric Factor [m]'].values[0]\n fpeakm = f0peak(Rm, Qm, Pm)\n fpeakl = f0peak(Rl, Ql, Pl)\n# geom = 1.\n rhom = CPEfunSeries(Rm, Qm, Pm, frequency)*geom\n rhol = CPEfunSeries(Rl, Ql, Pl, frequency)*geom\n rho0 = data[data[\"Peregrine ID\"]==PID]['Ro'].values[0]*geom\n rho = 1./(1./rho0+1./rhol)\n m = (rho.real[0]-rho.real[-1])/rho.real[0] \n rhoinf = rho0*(1.-m)\n fig, ax = plt.subplots(1, 2, figsize = (15, 3))\n ax[0].semilogx(frequency, rho.real, 'k-', lw=2)\n ax1 = ax[0].twinx()\n ax1.semilogx(frequency, (rho.imag), 'k--', lw=2)\n ax1.invert_yaxis()\n ax[0].grid(True)\n ax[1].plot(rho.real, rho.imag, 'k-')\n\n ax[1].invert_yaxis()\n ax[1].grid(True)\n\n \n print data[data[\"Peregrine ID\"]==PID]['Facies'].values[0], PID\n print \"R0 = \", rho0\n print \"Rinf = \", rhoinf\n print \"Chargeability = \", m \n print \"Taum = \", 1./fpeakm \n print \"Taul = \", 1./fpeakl \n print Pl, Ql, Rl, geom\n return ",
"_____no_output_____"
],
[
"data_active[data_active['Facies']=='PK']",
"_____no_output_____"
],
[
"frequency = np.logspace(-4, 8, 211)\nTKCColeColeParallel(frequency, \"K1P-0825\", data_active)",
"PK K1P-0825\nR0 = 20.4245150764\nRinf = 12.8845864142\nChargeability = 0.369160718581\nTaum = 9.96618085948\nTaul = 0.000206528713045\n0.6585 6.947e-07 1607 0.0217028106221\n"
],
[
"frequency = np.logspace(-4, 8, 211)\nTKCColeColeParallel(frequency, \"K1P-0807\", data_active)",
"PK K1P-0807\nR0 = 90.3895818681\nRinf = 90.337060378\nChargeability = 0.000581056898032\nTaum = 9.99210583466\nTaul = 0.00355078505315\n0.4117 7.58e-09 6070000 0.0254618540473\n"
],
[
"data_active[data_active['Facies']=='XVK']",
"_____no_output_____"
],
[
"TKCColeColeParallel(frequency, \"K2P-0031\", data_active)",
"XVK K2P-0031\nR0 = 15.6781923439\nRinf = 6.55792039201\nChargeability = 0.581717059713\nTaum = 9.93387042733\nTaul = 0.000116539775997\n0.6611 1.492e-06 499 0.0225682918438\n"
],
[
"data_active[data_active['Facies']=='HK']",
"_____no_output_____"
],
[
"TKCColeColeParallel(frequency, \"K1P-0591\", data_active)",
"HK K1P-0591\nR0 = 47.9557244624\nRinf = 37.6893424919\nChargeability = 0.21408042701\nTaum = 9.98159580655\nTaul = 0.000250332900856\n0.4269 1.992e-06 6645 0.0262053139139\n"
],
[
"data_active[data_active['Facies']=='VK']",
"_____no_output_____"
],
[
"TKCColeColeParallel(frequency, \"K1P-0589\", data_active)",
"VK K1P-0589\nR0 = 48.9613299999\nRinf = 31.9977236027\nChargeability = 0.346469476978\nTaum = 9.98711116994\nTaul = 0.000356711142256\n0.6791 3.152e-07 4150 0.0222450386188\n"
],
[
"RlPK = data_active[data_active['Facies']=='PK'][\"pRl\"].values[:]\nQlPK = data_active[data_active['Facies']=='PK'][\"pQl\"].values[:]\nPlPK = data_active[data_active['Facies']=='PK'][\"Pl\"].values[:]\nfpeakPK = f0peak(RlPK, QlPK, PlPK)\nrhoinfPK = rhoinf(data_active[data_active['Facies']=='PK'][\"Ro\"].values[:], data_active[data_active['Facies']=='PK'][\"pRm\"].values[:],data_active[data_active['Facies']=='PK'][\"pRl\"].values[:])\nmPK = charg(rhoinfPK, data_active[data_active['Facies']=='PK'][\"Ro\"].values[:])",
"_____no_output_____"
],
[
"RlXVK = data_active[data_active['Facies']=='XVK'][\"pRl\"].values[:]\nQlXVK = data_active[data_active['Facies']=='XVK'][\"pQl\"].values[:]\nPlXVK = data_active[data_active['Facies']=='XVK'][\"Pl\"].values[:]\nfpeakXVK = f0peak(RlXVK, QlXVK, PlXVK)\nrhoinfXVK = rhoinf(data_active[data_active['Facies']=='XVK'][\"Ro\"].values[:], data_active[data_active['Facies']=='XVK'][\"pRm\"].values[:],data_active[data_active['Facies']=='XVK'][\"pRl\"].values[:])\nmXVK = charg(rhoinfXVK, data_active[data_active['Facies']=='XVK'][\"Ro\"].values[:])",
"_____no_output_____"
],
[
"RlVK = data_active[data_active['Facies']=='VK'][\"pRl\"].values[:]\nQlVK = data_active[data_active['Facies']=='VK'][\"pQl\"].values[:]\nPlVK = data_active[data_active['Facies']=='VK'][\"Pl\"].values[:]\nfpeakVK = f0peak(RlVK, QlVK, PlVK)\nrhoinfVK = rhoinf(data_active[data_active['Facies']=='VK'][\"Ro\"].values[:], data_active[data_active['Facies']=='VK'][\"pRm\"].values[:],data_active[data_active['Facies']=='VK'][\"pRl\"].values[:])\nmVK = charg(rhoinfVK, data_active[data_active['Facies']=='VK'][\"Ro\"].values[:])",
"_____no_output_____"
],
[
"RlHK = data_active[data_active['Facies']=='HK'][\"pRl\"].values[:]\nQlHK = data_active[data_active['Facies']=='HK'][\"pQl\"].values[:]\nPlHK = data_active[data_active['Facies']=='HK'][\"Pl\"].values[:]\nfpeakHK = f0peak(RlHK, QlHK, PlHK)\nrhoinfHK = rhoinf(data_active[data_active['Facies']=='HK'][\"Ro\"].values[:], data_active[data_active['Facies']=='HK'][\"pRm\"].values[:],data_active[data_active['Facies']=='HK'][\"pRl\"].values[:])\nmHK = charg(rhoinfHK, data_active[data_active['Facies']=='HK'][\"Ro\"].values[:])",
"_____no_output_____"
],
[
"import matplotlib as mpl\nmpl.rcParams[\"font.size\"] = 16\nmpl.rcParams[\"text.usetex\"] = True",
"_____no_output_____"
],
[
"figsize(5,5)\nindactHK = 1./fpeakHK > 0.1\nplt.semilogx(1./fpeakXVK*1e6, mXVK, 'kx', ms = 15, lw=3)\nplt.semilogx(1./fpeakVK*1e6, mVK, 'bx', ms = 15)\nplt.semilogx(1./fpeakHK[~indactHK]*1e6, mHK[~indactHK], 'mx', ms = 15)\nplt.semilogx(1./fpeakPK*1e6, mPK, 'rx', ms = 15)\n\nylim(-0.1, 1.)\nxlim(1e-5*1e6, 1e-2*1e6)\nplt.grid(True)\nplt.ylabel(\"Chargeability \")\nplt.xlabel(\"Time constant (micro-s)\")\nplt.legend((\"XVK\", \"VK\", \"HK\", \"PK\"), bbox_to_anchor=(1.5, 1))",
"_____no_output_____"
],
[
"mus = 1e6\nplt.semilogx(1./fpeakXVK*mus, PlXVK,'ko')\nplt.semilogx(1./fpeakVK*mus, PlVK, 'bo')\nplt.semilogx(1./fpeakHK[~indactHK]*mus, PlHK[~indactHK], 'bo')\nplt.semilogx(1./fpeakPK*mus, PlPK, 'mo')\n\nylim(0., 1.)\nxlim(1e-5*mus, 1e-2*mus)\nplt.grid(True)\n# plt.legend((\"XVK\", \"VK\", \"HK\", \"PK\"), loc=4)\nplt.ylabel(\"Frequency dependency \")\nplt.xlabel(\"Time constant (micro-s)\")\nfigsize(5,5)",
"_____no_output_____"
],
[
"plt.semilogy(data_active[data_active[\"Facies\"]==\"XVK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"XVK\"][\"Resistivity [Ohm.m]\"], 'ko')\nplt.semilogy(data_active[data_active[\"Facies\"]==\"VK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"VK\"][\"Resistivity [Ohm.m]\"], 'bo')\nplt.semilogy(data_active[data_active[\"Facies\"]==\"HK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"HK\"][\"Resistivity [Ohm.m]\"], 'mo')\nplt.semilogy(data_active[data_active[\"Facies\"]==\"PK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"PK\"][\"Resistivity [Ohm.m]\"], 'ro')\nplt.grid(True)\nplt.legend((\"XVK\", \"VK\", \"HK\", \"PK\"), loc=4)\nplt.xlabel(\"Susceptibility (SI)\")\nplt.ylabel(\"Resistivity (ohm-m)\")\nfigsize(5,5)",
"_____no_output_____"
],
[
"plt.plot(data_active[data_active[\"Facies\"]==\"XVK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"XVK\"][\"Sat Geometric Dens [g/cc]\"], 'ko')\nplt.plot(data_active[data_active[\"Facies\"]==\"VK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"VK\"][\"Sat Geometric Dens [g/cc]\"], 'bo')\nplt.plot(data_active[data_active[\"Facies\"]==\"HK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"HK\"][\"Sat Geometric Dens [g/cc]\"], 'ro')\nplt.plot(data_active[data_active[\"Facies\"]==\"PK\"][\"Mag Susc [SI]\"], data_active[data_active[\"Facies\"]==\"PK\"][\"Sat Geometric Dens [g/cc]\"], 'go')\n\nplt.grid(True)\nplt.legend((\"XVK\", \"VK\", \"HK\", \"PK\"), loc=4)\nplt.xlabel(\"Susceptibility (SI)\")\nplt.ylabel(\"Density (g/cc)\")\nfigsize(5,5)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba334aa922f86b4f2ae79d7dd2f78b93f71b085
| 17,098 |
ipynb
|
Jupyter Notebook
|
01_gradients_and_matrices/DL_Lab_1.ipynb
|
samisnotinsane/deep-learning-soton
|
bba257627dce8d7ed726b7a581848e47c3aaf0e8
|
[
"MIT"
] | null | null | null |
01_gradients_and_matrices/DL_Lab_1.ipynb
|
samisnotinsane/deep-learning-soton
|
bba257627dce8d7ed726b7a581848e47c3aaf0e8
|
[
"MIT"
] | null | null | null |
01_gradients_and_matrices/DL_Lab_1.ipynb
|
samisnotinsane/deep-learning-soton
|
bba257627dce8d7ed726b7a581848e47c3aaf0e8
|
[
"MIT"
] | null | null | null | 60.416961 | 10,920 | 0.789274 |
[
[
[
"from typing import Tuple\nimport torch",
"_____no_output_____"
],
[
"def sgd_factorise(A: torch.Tensor, rank: int, num_epochs=1000, lr=0.01) -> Tuple[torch.Tensor, torch.Tensor]:\n m,n = A.shape\n u_hat = torch.rand(m, rank)\n v_hat = torch.rand(n, rank)\n err = torch.rand(num_epochs)\n for epoch in range(num_epochs):\n for r in range(m):\n for c in range(n):\n e = A[r][c] - u_hat[r] @ v_hat[c].T\n u_hat[r] = u_hat[r] + lr * e * v_hat[c]\n v_hat[c] = v_hat[c] + lr * e * u_hat[r]\n err[epoch] = e\n return (u_hat, v_hat, err)",
"_____no_output_____"
],
[
"A = torch.tensor(\n [[0.3374, 0.6005, 0.1735],\n [3.3359, 0.0492, 1.8374],\n [2.9407, 0.5301, 2.2620]]\n)",
"_____no_output_____"
],
[
"u, v, loss = sgd_factorise(A, rank=2)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.plot(loss)\nax.set_title('Reconstruction Error')",
"_____no_output_____"
],
[
"inp = [email protected]\nmy_loss = torch.nn.functional.mse_loss(input=inp, target=A, reduction='sum')\nmy_loss",
"_____no_output_____"
],
[
"U, S, V = torch.svd(A)\nS[2] = 0\n\nA_approx = U @ torch.diag(S) @ V.T\ntorch_loss = torch.nn.functional.mse_loss(A, A_approx, reduction='sum')",
"_____no_output_____"
],
[
"torch.norm(my_loss - torch_loss)",
"_____no_output_____"
],
[
"def sgd_factorise_masked(A: torch.tensor, M: torch.tensor, rank: int, num_epochs=1000, lr=0.01) -> Tuple[torch.Tensor, torch.Tensor]:\n m,n = A.shape\n u_hat = torch.rand(m, rank)\n v_hat = torch.rand(n, rank)\n for epoch in range(num_epochs):\n for r in range(m):\n for c in range(n):\n if M[r,c] == 1:\n e = A[r][c] - u_hat[r] @ v_hat[c].T\n u_hat[r] = u_hat[r] + lr * e * v_hat[c]\n v_hat[c] = v_hat[c] + lr * e * u_hat[r]\n return u_hat, v_hat",
"_____no_output_____"
],
[
"A = torch.tensor(\n [[0.3374, 0.6005, 0.1735],\n [0, 0.0492, 1.8374],\n [2.9407, 0, 2.2620]]\n)\nM = torch.tensor(\n [[1,1,1],\n [0,1,1],\n [1,0,1]]\n)\n\nU, V = sgd_factorise_masked(A, M, 2)\nprint('U @ V.T:\\n', [email protected])\nLOS = torch.nn.functional.mse_loss([email protected], target=A, reduction='sum')\nprint('LOS:', LOS)",
"U @ V.T:\n tensor([[0.3178, 0.0193, 0.2389],\n [2.3164, 0.1244, 1.8325],\n [2.9430, 0.1704, 2.2590]])\nLOS: tensor(5.7431)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba3389061424b1f49d38996a594d7dc10767c80
| 3,387 |
ipynb
|
Jupyter Notebook
|
data/Data Analysis/Vis.ipynb
|
jarrodized/nfl-fantasy-football
|
ad1ce22d1ab2a21dc1f7c8791edb75562631846a
|
[
"MIT"
] | null | null | null |
data/Data Analysis/Vis.ipynb
|
jarrodized/nfl-fantasy-football
|
ad1ce22d1ab2a21dc1f7c8791edb75562631846a
|
[
"MIT"
] | null | null | null |
data/Data Analysis/Vis.ipynb
|
jarrodized/nfl-fantasy-football
|
ad1ce22d1ab2a21dc1f7c8791edb75562631846a
|
[
"MIT"
] | null | null | null | 26.460938 | 107 | 0.537349 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport json\nimport sys\nfrom yahoo_oauth import OAuth2\nfrom json import dumps\nfrom pandas.io.json import json_normalize\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nimport matplotlib.cbook\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n%matplotlib inline",
"_____no_output_____"
],
[
"# import dictionary of Yahoo Manager Names to Real Life Nicknames\nwith open('../teams/team_mapping_initials.txt', 'r') as f:\n dict_init = dict(eval(f.read()))\nwith open('../teams/team_mapping_full.txt', 'r') as f:\n dict_full = dict(eval(f.read()))\n\n#Need to create mapping between Real Name and Initials, in form of new dictionary\ndict_full_init = {}\nfor name in dict_full:\n dict_full_init[dict_full[name]] = dict_init[name]\n\n# names--> manager initials\nnames = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12']\n#names = dict_init.keys()\n\nweeks = ['wk_1', 'wk_2', 'wk_3', 'wk_4', 'wk_5', 'wk_6', 'wk_7', 'wk_8',\n 'wk_9', 'wk_10', 'wk_11', 'wk_12', 'wk_13', 'wk_14', 'wk_15', 'wk_16']",
"_____no_output_____"
],
[
"week = 1\ndf_total_scores = pd.DataFrame()\ndf_total_scores = pd.DataFrame(columns=weeks, index = names)\nfor week in range(1,17):\n df_scores = pd.read_csv('./weekly_scores/wk_'+str(week)+'_scores.csv', index_col='Unnamed: 0')\n df_scores = df_scores.rename(columns=dict_full_init)\n \n week_id = 'wk_' + str(week)\n #df_total_scores[week_id] = pd.Series()\n positions = ['QB', 'WR1', 'WR2', 'WR3', 'RB1', 'RB2', 'TE', 'W/R/T','K', 'DEF']\n for manager in df_scores:\n df_total_scores.loc[manager, week_id] = df_scores.loc[positions, manager].sum()",
"_____no_output_____"
],
[
"#df_total_scores = df_total_scores.reset_index()\ndf_total_scores.replace(0, np.nan, inplace=True)\ndf_total_scores",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
cba34be0169ad0a52bdae0e6a7c9c70ab935f1f3
| 119,277 |
ipynb
|
Jupyter Notebook
|
notes/02_non_linear_equations.ipynb
|
gsarti/P1.4_seed
|
e09dc4381c5da0c5781e185d7bce69679b8fca66
|
[
"CC-BY-4.0"
] | 1 |
2018-11-08T07:53:28.000Z
|
2018-11-08T07:53:28.000Z
|
notes/02_non_linear_equations.ipynb
|
gsarti/P1.4_seed
|
e09dc4381c5da0c5781e185d7bce69679b8fca66
|
[
"CC-BY-4.0"
] | null | null | null |
notes/02_non_linear_equations.ipynb
|
gsarti/P1.4_seed
|
e09dc4381c5da0c5781e185d7bce69679b8fca66
|
[
"CC-BY-4.0"
] | 1 |
2019-01-26T11:41:55.000Z
|
2019-01-26T11:41:55.000Z
| 200.129195 | 28,672 | 0.910226 |
[
[
[
"# Nonlinear Equations\n\nWe want to find a root of the nonlinear function $f$ using different methods.\n\n1. Bisection method\n2. Newton method\n3. Chord method\n4. Secant method\n5. Fixed point iterations\n\n\n\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom numpy import *\nfrom matplotlib.pyplot import *\nimport sympy as sym\n",
"_____no_output_____"
],
[
"t = sym.symbols('t')\n\nf_sym = t/8. * (63.*t**4 - 70.*t**2. +15.) # Legendre polynomial of order 5\n\nf_prime_sym = sym.diff(f_sym,t)\n\nf = sym.lambdify(t, f_sym, 'numpy')\nf_prime = sym.lambdify(t,f_prime_sym, 'numpy')\n\nphi = lambda x : 63./70.*x**3 + 15./(70.*x)\n#phi = lambda x : 70.0/15.0*x**3 - 63.0/15.0*x**5\n#phi = lambda x : sqrt((63.*x**4 + 15.0)/70.)\n\n# Let's plot\nn = 1025\n\nx = linspace(-1,1,n)\nc = zeros_like(x)\n\n_ = plot(x,f(x))\n_ = plot(x,c)\n_ = grid()\n",
"_____no_output_____"
],
[
"# Initial data for the variuos algorithms\n\n# interval in which we seek the solution \na = 0.7\nb = 1.\n\n# initial points\nx0 = (a+b)/2.0\nx00 = b\n",
"_____no_output_____"
],
[
"# stopping criteria\neps = 1e-10\nn_max = 1000",
"_____no_output_____"
]
],
[
[
"## Bisection method\n\n$$\nx^k = \\frac{a^k+b^k}{2}\n$$\n```\n if (f(a_k) * f(x_k)) < 0:\n b_k1 = x_k\n a_k1 = a_k\n else:\n a_k1 = x_k\n b_k1 = b_k\n```",
"_____no_output_____"
]
],
[
[
"def bisect(f,a,b,eps,n_max):\n assert(f(a) * f(b) < 0)\n a_new = a\n b_new = b\n x = mean([a,b])\n err = eps + 1.\n errors = [err]\n it = 0\n while (err > eps and it < n_max):\n if ( f(a_new) * f(x) < 0 ):\n # root in (a_new,x)\n b_new = x\n else:\n # root in (x,b_new)\n a_new = x\n \n x_new = mean([a_new,b_new])\n \n #err = 0.5 *(b_new -a_new)\n err = abs(f(x_new))\n #err = abs(x-x_new)\n \n errors.append(err)\n x = x_new\n it += 1\n \n semilogy(errors)\n print(it)\n print(x)\n print(err)\n return errors\n \nerrors_bisect = bisect(f,a,b,eps,n_max) ",
"32\n0.9061798459501006\n7.857261621871514e-11\n"
],
[
"# is the number of iterations coherent with the theoretical estimation?",
"_____no_output_____"
]
],
[
[
"In order to find out other methods for solving non-linear equations, let's compute the Taylor's series of $f(x^k)$ up to the first order \n\n$$\nf(x^k) \\simeq f(x^k) + (x-x^k)f^{\\prime}(x^k)\n$$\nwhich suggests the following iterative scheme\n$$\nx^{k+1} = x^k - \\frac{f(x^k)}{f^{\\prime}(x^k)}\n$$\n\nThe following methods are obtained applying the above scheme where\n\n$$\nf^{\\prime}(x^k) \\approx q^k\n$$",
"_____no_output_____"
],
[
"## Newton's method\n$$\nq^k = f^{\\prime}(x^k)\n$$\n\n$$\nx^{k+1} = x^k - \\frac{f(x^k)}{q^k}\n$$",
"_____no_output_____"
]
],
[
[
"def newton(f,f_prime,x0,eps,n_max):\n x_new = x0\n err = eps + 1.\n errors = [err]\n it = 0\n while (err > eps and it < n_max):\n x_new = x_new - (f(x_new)/f_prime(x_new))\n err = abs(f(x_new))\n errors.append(err)\n it += 1\n semilogy(errors)\n print(it)\n print(x_new)\n print(err)\n return errors\n\n%time errors_newton = newton(f,f_prime,1.0,eps,n_max)",
"5\n0.9061798459386647\n5.633945684709343e-15\nCPU times: user 6.77 ms, sys: 10.1 ms, total: 16.8 ms\nWall time: 15.8 ms\n"
]
],
[
[
"## Chord method\n\n$$\nq^k \\equiv q = \\frac{f(b)-f(a)}{b-a}\n$$\n\n$$\nx^{k+1} = x^k - \\frac{f(x^k)}{q}\n$$",
"_____no_output_____"
]
],
[
[
"def chord(f,a,b,x0,eps,n_max):\n x_new = x0\n err = eps + 1.\n errors = [err]\n it = 0\n while (err > eps and it < n_max):\n x_new = x_new - (f(x_new)/((f(b) - f(a)) / (b - a)))\n err = abs(f(x_new))\n errors.append(err)\n it += 1\n semilogy(errors)\n print(it)\n print(x_new)\n print(err)\n return errors\n\nerrors_chord = chord (f,a,b,x0,eps,n_max)",
"31\n0.9061798459502479\n7.958511674322147e-11\n"
]
],
[
[
"## Secant method\n\n$$\nq^k = \\frac{f(x^k)-f(x^{k-1})}{x^k - x^{k-1}}\n$$\n\n$$\nx^{k+1} = x^k - \\frac{f(x^k)}{q^k}\n$$\n\nNote that this algorithm requirs **two** initial points",
"_____no_output_____"
]
],
[
[
"def secant(f,x0,x00,eps,n_max):\n xk = x00\n x_new = x0\n err = eps + 1.\n errors = [err]\n it = 0\n while (err > eps and it < n_max):\n temp = x_new\n x_new = x_new - (f(x_new)/((f(x_new)-f(xk))/(x_new - xk)))\n xk = temp\n err = abs(f(x_new))\n errors.append(err)\n it += 1\n semilogy(errors)\n print(it)\n print(x_new)\n print(err)\n return errors\n \nerrors_secant = secant(f,x0,x00,eps,n_max)",
"7\n0.906179845938664\n0.0\n"
]
],
[
[
"## Fixed point iterations\n\n$$\nf(x)=0 \\to x-\\phi(x)=0\n$$\n\n$$\nx^{k+1} = \\phi(x^k)\n$$",
"_____no_output_____"
]
],
[
[
"def fixed_point(phi,x0,eps,n_max):\n x_new = x0\n err = eps + 1.\n errors = [err]\n it = 0\n while (err > eps and it < n_max):\n x_new = phi(x_new)\n err = abs(f(x_new))\n errors.append(err)\n it += 1\n semilogy(errors)\n print(it)\n print(x_new)\n print(err)\n return errors\n\nerrors_fixed = fixed_point(phi,0.3,eps,n_max)\n ",
"11\n0.5384693101084483\n6.708269298482029e-12\n"
]
],
[
[
"## Comparison",
"_____no_output_____"
]
],
[
[
"# plot the error convergence for the methods\nloglog(errors_bisect, label='bisect')\nloglog(errors_chord, label='chord')\nloglog(errors_secant, label='secant')\nloglog(errors_newton, label ='newton')\nloglog(errors_fixed, label ='fixed')\n_ = legend()",
"_____no_output_____"
],
[
"# Let's compare the scipy implmentation of Newton's method with our..",
"_____no_output_____"
],
[
"import scipy.optimize as opt\n%time opt.newton(f, 1.0, f_prime, tol = eps)",
"CPU times: user 12 µs, sys: 11 µs, total: 23 µs\nWall time: 26.5 µs\n"
]
],
[
[
"We see that the scipy method is 1000 times slower than the `scipy` one",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cba34fd3e1611e58c06bf57844cf6f7298062afa
| 12,473 |
ipynb
|
Jupyter Notebook
|
M6_Python_for_Data_Science_AI_Development/Week3/files/3-1.2ExcecptionHandling.ipynb
|
cmaroblesg/IBM_DevOps-_and_Software_Engineering
|
b943be2e5774e2f54e5814ff9c7bd11c7a178d47
|
[
"MIT"
] | 2 |
2021-08-24T07:07:29.000Z
|
2021-08-31T14:06:11.000Z
|
3-1.2ExcecptionHandling.ipynb
|
jorgedroguett/Python-Basics-for-Data-Science
|
03ee06619173f49720cc147c398a851d7a2629ca
|
[
"MIT"
] | null | null | null |
3-1.2ExcecptionHandling.ipynb
|
jorgedroguett/Python-Basics-for-Data-Science
|
03ee06619173f49720cc147c398a851d7a2629ca
|
[
"MIT"
] | 1 |
2022-03-20T13:09:06.000Z
|
2022-03-20T13:09:06.000Z
| 12,473 | 12,473 | 0.670087 |
[
[
[
"<center>\n <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n",
"_____no_output_____"
],
[
"# **Exception Handling**\n\nEstimated time needed: **15** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Understand exceptions\n* Handle the exceptions\n",
"_____no_output_____"
],
[
"## Table of Contents\n",
"_____no_output_____"
],
[
"* What is an Exception?\n* Exception Handling\n",
"_____no_output_____"
],
[
"***\n",
"_____no_output_____"
],
[
"## What is an Exception?\n",
"_____no_output_____"
],
[
"In this section you will learn about what an exception is and see examples of them.\n",
"_____no_output_____"
],
[
"### Definition\n",
"_____no_output_____"
],
[
"An exception is an error that occurs during the execution of code. This error causes the code to raise an exception and if not prepared to handle it will halt the execution of the code.\n",
"_____no_output_____"
],
[
"### Examples\n",
"_____no_output_____"
],
[
"Run each piece of code and observe the exception raised\n",
"_____no_output_____"
]
],
[
[
"1/0",
"_____no_output_____"
]
],
[
[
"<code>ZeroDivisionError</code> occurs when you try to divide by zero.\n",
"_____no_output_____"
]
],
[
[
"y = a + 5",
"_____no_output_____"
]
],
[
[
"<code>NameError</code> -- in this case, it means that you tried to use the variable a when it was not defined.\n",
"_____no_output_____"
]
],
[
[
"a = [1, 2, 3]\na[10]",
"_____no_output_____"
]
],
[
[
"<code>IndexError</code> -- in this case, it occured because you tried to access data from a list using an index that does not exist for this list.\n",
"_____no_output_____"
],
[
"There are many more exceptions that are built into Python, here is a list of them [https://docs.python.org/3/library/exceptions.html](https://docs.python.org/3/library/exceptions.html?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n",
"_____no_output_____"
],
[
"## Exception Handling\n",
"_____no_output_____"
],
[
"In this section you will learn how to handle exceptions. You will understand how to make your program perform specified tasks instead of halting code execution when an exception is encountered.\n",
"_____no_output_____"
],
[
"### Try Except\n",
"_____no_output_____"
],
[
"A <code>try except</code> will allow you to execute code that might raise an exception and in the case of any exception or a specific one we can handle or catch the exception and execute specific code. This will allow us to continue the execution of our program even if there is an exception.\n\nPython tries to execute the code in the <code>try</code> block. In this case if there is any exception raised by the code in the <code>try</code> block, it will be caught and the code block in the <code>except</code> block will be executed. After that, the code that comes <em>after</em> the try except will be executed.\n",
"_____no_output_____"
]
],
[
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept:\n # code to execute if there is an exception\n \n# code that will still execute if there is an exception",
"_____no_output_____"
]
],
[
[
"### Try Except Example\n",
"_____no_output_____"
],
[
"In this example we are trying to divide a number given by the user, save the outcome in the variable <code>a</code>, and then we would like to print the result of the operation. When taking user input and dividing a number by it there are a couple of exceptions that can be raised. For example if we divide by zero. Try running the following block of code with <code>b</code> as a number. An exception will only be raised if <code>b</code> is zero.\n",
"_____no_output_____"
]
],
[
[
"a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\n print(\"Success a=\",a)\nexcept:\n print(\"There was an error\")\n \n",
"_____no_output_____"
]
],
[
[
"### Try Except Specific\n",
"_____no_output_____"
],
[
"A specific <code>try except</code> allows you to catch certain exceptions and also execute certain code depending on the exception. This is useful if you do not want to deal with some exceptions and the execution should halt. It can also help you find errors in your code that you might not be aware of. Furthermore, it can help you differentiate responses to different exceptions. In this case, the code after the try except might not run depending on the error.\n",
"_____no_output_____"
],
[
"<b>Do not run, just to illustrate:</b>\n",
"_____no_output_____"
]
],
[
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept (ZeroDivisionError, NameError):\n # code to execute if there is an exception of the given types\n \n# code that will execute if there is no exception or a one that we are handling",
"_____no_output_____"
],
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\n \n# code that will execute if there is no exception or a one that we are handling",
"_____no_output_____"
]
],
[
[
"You can also have an empty <code>except</code> at the end to catch an unexpected exception:\n",
"_____no_output_____"
],
[
"<b>Do not run, just to illustrate:</b>\n",
"_____no_output_____"
]
],
[
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\n \n# code that will execute if there is no exception or a one that we are handling",
"_____no_output_____"
]
],
[
[
"### Try Except Specific Example\n",
"_____no_output_____"
],
[
"This is the same example as above, but now we will add differentiated messages depending on the exception, letting the user know what is wrong with the input.\n",
"_____no_output_____"
]
],
[
[
"a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\n print(\"Success a=\",a)\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\n \n",
"_____no_output_____"
]
],
[
[
"### Try Except Else and Finally\n",
"_____no_output_____"
],
[
"<code>else</code> allows one to check if there was no exception when executing the try block. This is useful when we want to execute something only if there were no errors.\n",
"_____no_output_____"
],
[
"<b>do not run, just to illustrate</b>\n",
"_____no_output_____"
]
],
[
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\nelse:\n # code to execute if there is no exception\n \n# code that will execute if there is no exception or a one that we are handling",
"_____no_output_____"
]
],
[
[
"<code>finally</code> allows us to always execute something even if there is an exception or not. This is usually used to signify the end of the try except.\n",
"_____no_output_____"
]
],
[
[
"# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\nelse:\n # code to execute if there is no exception\nfinally:\n # code to execute at the end of the try except no matter what\n \n# code that will execute if there is no exception or a one that we are handling",
"_____no_output_____"
]
],
[
[
"### Try Except Else and Finally Example\n",
"_____no_output_____"
],
[
"You might have noticed that even if there is an error the value of <code>a</code> is always printed. Let's use the <code>else</code> and print the value of <code>a</code> only if there is no error.\n",
"_____no_output_____"
]
],
[
[
"a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"success a=\",a)",
"_____no_output_____"
]
],
[
[
"Now lets let the user know that we are done processing their answer. Using the <code>finally</code>, let's add a print.\n",
"_____no_output_____"
]
],
[
[
"a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"success a=\",a)\nfinally:\n print(\"Processing Complete\")",
"_____no_output_____"
]
],
[
[
"## Authors\n",
"_____no_output_____"
],
[
"<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01\" target=\"_blank\">Joseph Santarcangelo</a>\n",
"_____no_output_____"
],
[
"## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ---------------------------- |\n| 2020-09-02 | 2.0 | Simran | Template updates to the file |\n| | | | |\n| | | | |\n\n## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cba35252fba8bbe6984c93f409ff39bd6a6914ec
| 16,951 |
ipynb
|
Jupyter Notebook
|
PythonTheHardway.ipynb
|
NelsonBilber/py.thehardway
|
0e753cdea9207ac0410217685b710dac5b18284a
|
[
"MIT"
] | null | null | null |
PythonTheHardway.ipynb
|
NelsonBilber/py.thehardway
|
0e753cdea9207ac0410217685b710dac5b18284a
|
[
"MIT"
] | null | null | null |
PythonTheHardway.ipynb
|
NelsonBilber/py.thehardway
|
0e753cdea9207ac0410217685b710dac5b18284a
|
[
"MIT"
] | null | null | null | 21.985733 | 227 | 0.441685 |
[
[
[
"# python the hardway https://learnpythonthehardway.org/book/index.html\n\n# Exercise 1 - Hello world\nimport sys\nprint (\"Hello Snake\")\n",
"Hello Snake\n"
],
[
"# Exercise 2 - simple math operations\n \nprint (\"5 + 2 = \", 5 + 2)\nprint (\"5 > 2 ? \", 5 > 2)\nprint (\"7 / 4 = \", 7/4)\n# print (\"7 % 4 = \", 7%4)",
"5 + 2 = 7\n5 > 2 ? True\n7 / 4 = 1.75\n7 % 4 = 3\n"
],
[
"# Exercise 3 - variables and names\n\nmy_name = 'Zed A. Shaw'\nmy_age = 35 # not a lie\nmy_height = 74 # inches\nmy_weight = 180 # lbs\nmy_eyes = 'Blue'\nmy_teeth = 'White'\nmy_hair = 'Brown'\n\nprint (\"Let's talk about %s.\" % my_name)\nprint (\"He's %d inches tall.\" % my_height)\nprint (\"He's %d pounds heavy.\" % my_weight)\nprint (\"Actually that's not too heavy.\")\nprint (\"He's got %s eyes and %s hair.\" % (my_eyes, my_hair))\nprint (\"His teeth are usually %s depending on the coffee.\" % my_teeth)\n\n# this line is tricky, try to get it exactly right\nprint (\"If I add %d, %d, and %d I get %d.\" % ( my_age, my_height, my_weight, my_age + my_height + my_weight))",
"Let's talk about Zed A. Shaw.\nHe's 74 inches tall.\nHe's 180 pounds heavy.\nActually that's not too heavy.\nHe's got Blue eyes and Brown hair.\nHis teeth are usually White depending on the coffee.\nIf I add 35, 74, and 180 I get 289.\n"
],
[
" # Exercise 4 - input from console\n \nage = input()\nprint (\"What's your age ? \", age)\n",
"34\nWhat's your age ? 34\n"
],
[
"#Exercise 13 using parameters\n\nfrom sys import argv\n\nprogram_name = argv\nprint (\"second = \", program_name)",
"second = ['F:\\\\Anaconda3\\\\lib\\\\site-packages\\\\ipykernel\\\\__main__.py', '-f', 'C:\\\\Users\\\\NelsonRodrigues\\\\AppData\\\\Roaming\\\\jupyter\\\\runtime\\\\kernel-9576f747-9618-4c5d-bbd2-3530d8483a7a.json']\n"
],
[
"# Exercise 15 - Read files\n\nfrom sys import argv\n\nfile = open(\"t.txt\",\"r\")\nfor line in file:\n print(line.rstrip())\nfile.close()",
"This is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.\n"
],
[
"# Exercise 16 - Write file\n\nfrom sys import argv\n\nfile = open(\"t.txt\",\"r\")\nout = open(\"t2.txt\",\"w\")\nfor line in file:\n out_line = line.rstrip()\n print (out_line)\n out.write(out_line)\nfile.close()",
"This is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.\n"
],
[
"#Exercise 18 - functions\n\ndef print_two(*args):\n arg1, arg2 = args\n print (\"arg1: %r, arg2: %r\" % (arg1, arg2))\n \ndef print_twoV2(arg1, arg2):\n print (\"arg1: %r, arg2: %r\" % (arg1, arg2))\n \nprint_two(\"Zed\", \"Ned\") \nprint_twoV2(\"Zed\", \"Ned\")",
"arg1: 'Zed', arg2: 'Ned'\narg1: 'Zed', arg2: 'Ned'\n"
],
[
"# Exercise 19 - functions continue ...\n\ndef add(num1, num2):\n return (num1 + num2)\n\nprint (add(1,2))\nprint (add(5+5,10+10))\n ",
"3\n30\n"
],
[
"# Exercise 28 - Booleans\n\nTrue and True\nFalse and True\n\"test\" == \"test\"\n3 == 3 and (not (\"testing\" == \"testing\" or \"Python\" == \"Fun\"))",
"_____no_output_____"
],
[
"#Exercise 29 - If conditions\n\npeople = 30\ncars = 40\ntrucks = 15\n\nif cars > people:\n print (\"We should take the cars.\")\nelif cars < people:\n print (\"We should not take the cars.\")\nelse:\n print (\"We can't decide.\")\n ",
"We should take the cars.\n"
],
[
"# Exercise 32 - Loop and List\n\nnumbers = [1, 2, 3]\nchange = [1, 'pennies', 2, 'dimes', 3, 'quarters']\n\nfor num in numbers:\n print (num)\n \nfor i in change:\n print(\"I got %r\" % i)\n",
"1\n2\n3\nI got 1\nI got 'pennies'\nI got 2\nI got 'dimes'\nI got 3\nI got 'quarters'\n"
],
[
"# Exercise 33 - while loops\ni = 0\nnumbers = []\n\nwhile i < 6:\n print (\"At the top i is %d\" % i)\n numbers.append(i)\n\n i = i + 1\n print (\"Numbers now: \", numbers)\n print (\"At the bottom i is %d\" % i)\n\n\nprint (\"The numbers: \")\n\nfor num in numbers:\n print (num)",
"At the top i is 0\nNumbers now: [0]\nAt the bottom i is 1\nAt the top i is 1\nNumbers now: [0, 1]\nAt the bottom i is 2\nAt the top i is 2\nNumbers now: [0, 1, 2]\nAt the bottom i is 3\nAt the top i is 3\nNumbers now: [0, 1, 2, 3]\nAt the bottom i is 4\nAt the top i is 4\nNumbers now: [0, 1, 2, 3, 4]\nAt the bottom i is 5\nAt the top i is 5\nNumbers now: [0, 1, 2, 3, 4, 5]\nAt the bottom i is 6\nThe numbers: \n0\n1\n2\n3\n4\n5\n"
],
[
"# Exercise 34 - access list elems\n\nanimals = ['bear', \"wolf\"]\n\nanimals[1]\n",
"_____no_output_____"
],
[
"# Exercise 39 - Dictionaries\n\nstuff = {'name': 'Nelson', 'age' : 33}\n\nprint (stuff['name'])\n\n# create a mapping of state to abbreviation\nstates = {\n 'Oregon': 'OR',\n 'Florida': 'FL',\n 'California': 'CA',\n 'New York': 'NY',\n 'Michigan': 'MI'\n}\n\nprint (states)\n\n# create a basic set of states and some cities in them\ncities = {\n 'CA': 'San Francisco',\n 'MI': 'Detroit',\n 'FL': 'Jacksonville'\n}\n\nprint (\"Testing ....\", cities[states['California']])\n\n\n# print every state abbreviation\nfor state, abbrev in states.items():\n print (\"%s is abbreviated %s\" % (state, abbrev))\n",
"Nelson\n{'Oregon': 'OR', 'Florida': 'FL', 'New York': 'NY', 'California': 'CA', 'Michigan': 'MI'}\nTesting .... San Francisco\nOregon is abbreviated OR\nFlorida is abbreviated FL\nNew York is abbreviated NY\nCalifornia is abbreviated CA\nMichigan is abbreviated MI\n"
],
[
"# Exercise 40 - Object Oriented Programming\n\nclass Song(object):\n def __init__(self,lyrics):\n self.lyrics = lyrics\n \n def sing_me_a_song(self):\n for line in self.lyrics:\n print(line)\n \nhappy_bday = Song([\"tada ttttt tada ...\"]) \n\nhappy_bday.sing_me_a_song()\n\n",
"tada ttttt tada ...\n"
],
[
"## Animal is-a object (yes, sort of confusing) look at the extra credit\nclass Animal(object):\n pass\n\n## ??\nclass Dog(Animal):\n\n def __init__(self, name):\n ## ??\n self.name = name\n\n## ??\nclass Cat(Animal):\n\n def __init__(self, name):\n ## ??\n self.name = name\n\n## ??\nclass Person(object):\n\n def __init__(self, name):\n ## ??\n self.name = name\n\n ## Person has-a pet of some kind\n self.pet = None\n\n## ??\nclass Employee(Person):\n\n def __init__(self, name, salary):\n ## ?? hmm what is this strange magic?\n super(Employee, self).__init__(name)\n ## ??\n self.salary = salary\n\n## ??\nclass Fish(object):\n pass\n\n## ??\nclass Salmon(Fish):\n pass\n\n## ??\nclass Halibut(Fish):\n pass\n\n\n## rover is-a Dog\nrover = Dog(\"Rover\")\n\n## ??\nsatan = Cat(\"Satan\")\n\n## ??\nmary = Person(\"Mary\")\n\n## ??\nmary.pet = satan\n\n## ??\nfrank = Employee(\"Frank\", 120000)\n\n## ??\nfrank.pet = rover\n\n## ??\nflipper = Fish()\n\n## ??\ncrouse = Salmon()\n\n## ??\nharry = Halibut()",
"_____no_output_____"
],
[
"# Exercise 44 - Inheritance vs Composition\n\n\n\n#Implicit ineritance\nclass Parent(object):\n\n def implicit(self):\n print (\"PARENT implicit()\")\n\nclass Child(Parent):\n pass\n\ndad = Parent()\nson = Child()\n\ndad.implicit()\nson.implicit()\n\n\n\n#Override explicit\nclass Parent(object):\n\n def override(self):\n print (\"PARENT override()\")\n\nclass Child(Parent):\n\n def override(self):\n print (\"CHILD override()\")\n\ndad = Parent()\nson = Child()\n\ndad.override()\nson.override()\n\n\n# Altered \n\nclass Parent(object):\n\n def altered(self):\n print (\"PARENT altered()\")\n\nclass Child(Parent):\n\n def altered(self):\n print (\"CHILD, BEFORE PARENT altered()\")\n super(Child, self).altered()\n print (\"CHILD, AFTER PARENT altered()\")\n\ndad = Parent()\nson = Child()\n\ndad.altered()\nson.altered()",
"PARENT implicit()\nPARENT implicit()\nPARENT override()\nCHILD override()\nPARENT altered()\nCHILD, BEFORE PARENT altered()\nPARENT altered()\nCHILD, AFTER PARENT altered()\n"
],
[
"# Exercise 47 - Automated Testing\n\nfrom nose.tools import *\n\nclass Room(object):\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.paths = {}\n \n def go(self, direction):\n return self.paths.get(direction, None)\n \n def add_paths(self, paths):\n self.paths.update(paths)\n \n \ndef test_room():\n gold = Room(\"GoldRoom\",\n \"\"\"This room has gold in it you can grab. There's a\n door to the north.\"\"\")\n \n assert_equal(gold.name, \"GoldRoom\")\n assert_equal(gold.paths, {})\n ",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba363edf501502194f2a532e4b2ca9a28576dd5
| 150,281 |
ipynb
|
Jupyter Notebook
|
2020-01-beginner/course-material/py_class_1.ipynb
|
denistsoi/python-code-for-hk
|
ebc2d072e6f55f00bbe98f334a4eb97aa54334fa
|
[
"BSD-Source-Code"
] | null | null | null |
2020-01-beginner/course-material/py_class_1.ipynb
|
denistsoi/python-code-for-hk
|
ebc2d072e6f55f00bbe98f334a4eb97aa54334fa
|
[
"BSD-Source-Code"
] | 2 |
2020-03-31T11:20:18.000Z
|
2021-02-02T22:31:54.000Z
|
2020-01-beginner/course-material/py_class_1.ipynb
|
denistsoi/python-code-for-hk
|
ebc2d072e6f55f00bbe98f334a4eb97aa54334fa
|
[
"BSD-Source-Code"
] | null | null | null | 55.027829 | 78,433 | 0.770803 |
[
[
[
"<a href=\"https://colab.research.google.com/github/codeforhk/python_course/blob/master/py_class_1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"\n \n<img src=\"https://www.codefor.hk/wp-content/themes/DC_CUSTOM_THEME/img/logo-code-for-hk-logo.svg\" height=\"150\" width=\"150\" align=\"center\"/>\n<h1><center>Code For Hong Kong - Python class 1</center></h1>\n<h6><center>Written by Patrick Leung</center></h6>\n",
"_____no_output_____"
],
[
"# 0.0.0 Introduction\n",
"_____no_output_____"
],
[
"\n\n## 0.1.0 Course structure\n\n\n",
"_____no_output_____"
],
[
"### 0.1.1 Overview\n\n- You are expected to attend >75% of all classes in order to pass.\n- There will be a take home exercise after every class for you to complete during the week.\n- There will be an office hour on slack on Wednesday 7pm - 8pm, where our instructor will standby on slack to answer your question. (On other time during the week, you can also drop questions on the slack channel)\n- There will be an in-class test & challenges on every class, and there will be a final exam at the end of the course. \n- Your certificate will be graded as Distinction / Merit / Pass.\n",
"_____no_output_____"
],
[
"### 0.1.2 Course sylabus\n\n- Class 1: Basic Python Operations I (Variables, data structure, loops)\n- Class 2: Basic Python Operations II (Functions, libraries)\n- Class 3: Practical application of Python I (Document processing + Web scraping)\n- Class 4: Practical application of Python II ( More examples + Exam)",
"_____no_output_____"
],
[
"\n### 0.1.3 Install Anaconda\n\nFirst of all, you would need to install anaconda for this course. You would need to download python 3.7.\nAnaconda\n\nhttps://www.anaconda.com/distribution/#windows\n\n\nAnaconda is a python distribution. It aims to provide everything you need for python & data science \"out of the box\".\n\nIt includes:\n\n- The core python language\n- 100+ python \"packages\" (libraries)\n- Spyder (IDE/editor - like pycharm) and Jupyter\n\nFor window user, please install from this guide:\n\nhttps://www.datacamp.com/community/tutorials/installing-anaconda-windows\n\n\nFor mac user, please install from this guide:\n\nhttps://www.datacamp.com/community/tutorials/installing-anaconda-mac-os-x",
"_____no_output_____"
],
[
"<img src=\"https://www.codefor.hk/wp-content/themes/DC_CUSTOM_THEME/img/logo-code-for-hk-logo.svg\" height=\"150\" width=\"150\" align=\"center\"/>",
"_____no_output_____"
],
[
"# 1.0.0 Background of python",
"_____no_output_____"
],
[
"## 1.1.0 What is python?",
"_____no_output_____"
],
[
"* Widely used high-level, interpreted programming language for general-purpose programming\n* Created by Guido van Rossum and first released in 1991. \n* Python has a design philosophy that emphasizes code readability that allows programmers to express concepts in fewer lines of code than might be used in languages such as C++ or Java.\n* The language provides constructs intended to enable writing clear programs on both a small and large scale.",
"_____no_output_____"
],
[
"<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Guido_van_Rossum_OSCON_2006.jpg/440px-Guido_van_Rossum_OSCON_2006.jpg\" />\n\n",
"_____no_output_____"
],
[
"### 1.1.1 What is a programming language?",
"_____no_output_____"
],
[
"<img src=\"http://cdn.osxdaily.com/wp-content/uploads/2011/05/top-command-sorted-by-cpu-use-610x383.jpg\n\" />",
"_____no_output_____"
],
[
"### 1.1.2 Why do we need a computer to help out?",
"_____no_output_____"
],
[
"<img src=\"http://img.picturequotes.com/2/509/508709/one-good-thing-about-my-computer-it-never-asks-why-quote-1.jpg\" />\n\n",
"_____no_output_____"
],
[
"## 1.2.0 Why Python?\n\n- Python is very popular - meaning a lot of the functionality is already written as package, and you can copy/use other people's code for free!\n- Python is very beginner friendly\n- Python is powerful together with machine learning\n\nhttps://medium.freecodecamp.org/what-can-you-do-with-python-the-3-main-applications-518db9a68a78",
"_____no_output_____"
],
[
"<img src=\"https://cdn-images-1.medium.com/max/1600/1*_R4CyVH0DSXkJsoRk-Px_Q.png\" />\n\n",
"_____no_output_____"
],
[
"### 1.2.1 Python is a very popular language",
"_____no_output_____"
],
[
"https://www.economist.com/graphic-detail/2018/07/26/python-is-becoming-the-worlds-most-popular-coding-language",
"_____no_output_____"
],
[
"<img src=\"https://www.economist.com/sites/default/files/imagecache/1280-width/20180728_WOC883.png\" />\n",
"_____no_output_____"
],
[
"<img src=\"https://www.dotnetlanguages.net/wp-content/uploads/2018/05/Most-popular-programming-languages.png\" />",
"_____no_output_____"
],
[
"### 1.2.2 Python has a simple & elegant syntax\n\npython is a very clean & elegant language. Look how easy for it to write a program!",
"_____no_output_____"
],
[
"<img src=\"https://img.devrant.io/devrant/rant/r_672680_SGP4G.jpg\"/>",
"_____no_output_____"
],
[
"Python is meant to be a very elegant language. It even includes a poem built into it. Try to import your first library. \n\nTry to click \"shift enter\" after type \"import this\" in the box",
"_____no_output_____"
]
],
[
[
"import this",
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n"
]
],
[
[
"### 1.2.3 Python is good for machine learning\na nice language to do data analytics/ data science/ machine learning!",
"_____no_output_____"
],
[
"<img src=\"https://i.ytimg.com/vi/vISRn5qFrkM/maxresdefault.jpg\" />",
"_____no_output_____"
],
[
"<img src=\"https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Cheat+Sheets/content_pythonfordatascience.png\" />",
"_____no_output_____"
],
[
"### 1.2.4 Python 3 or Python 2?\n\n<img src=\"https://mk0learntocodew6bl5f.kinstacdn.com/wp-content/uploads/2014/06/python-2-vs-3-2018.png\" />\n\n\nhttps://learntocodewith.me/programming/python/python-2-vs-python-3/",
"_____no_output_____"
],
[
"## 1.3.0 Get familiar with the python tools",
"_____no_output_____"
],
[
"### 1.3.1 Jupyter notebook",
"_____no_output_____"
],
[
"Jupyter notebook is previously called IPython Notebook ( http://ipython.org/notebook.html ). It is a web based extension of iPython. It's very powerful and convenient and It allows you to mix code, annotation, text, figures into a single interactive document.\nIPython is included in all of the most popular python distributions, like Anaconda , or Canopy. If you have one of those distributions installed on your computer, you can already start using the notebook.",
"_____no_output_____"
],
[
"A simple youtube video to remind you how to open jupyter notebook\n\nhttps://www.youtube.com/watch?v=MJKVuzYZvo0",
"_____no_output_____"
],
[
"<img src=\"https://i.ytimg.com/vi/-MyjG00la2k/maxresdefault.jpg\" />\n\n",
"_____no_output_____"
],
[
"### 1.3.2 How to navigate within jupyter notebook? \n\nJupyter notebook is just a user-friendly way of coding in python. Every code is written in a \"block\"/\"cell\",\n",
"_____no_output_____"
],
[
"<img src=\"https://i.pinimg.com/originals/f5/7e/07/f57e074be4503a39f6d9d8d15f0e8aa5.png\" />",
"_____no_output_____"
],
[
"#### Example 1.3.2 - navigating the jupyter notebook",
"_____no_output_____"
],
[
"1) Click on the \"white edge\" next to any box to select the box",
"_____no_output_____"
]
],
[
[
"#click me (the white edge)! Now you selected me",
"_____no_output_____"
]
],
[
[
"2) While selecting a box, click \"a\" to create a box above, and \"b\" to create a box below",
"_____no_output_____"
]
],
[
[
"# click me (on the white edge, not the text!), and try type a to create a box above, and b to create a box below",
"_____no_output_____"
]
],
[
[
"3) To delete a box , click \"dd\" (dobule d)",
"_____no_output_____"
]
],
[
[
"# Try select me, and click \"dd\" to delete me!!",
"_____no_output_____"
]
],
[
[
"4) Realize there are \"text\" based box & \"code\" based box? Jupyter notebook has two type of \"box\" - those you see with a grey box are actually python code, while those with the entire white edge are so called the \"text\" box. all new box will be a \"code\" box automatically. To transform the \"code box\" to \"text box\", select the box & type m.",
"_____no_output_____"
]
],
[
[
"# Change me to a text box!",
"_____no_output_____"
]
],
[
[
"5) All good? Now that you know how to create a box, you should learn how to execute a code. There are 2 ways to execute the code - you can click \"shift enter\" to run a code & jump to a box below, or you can click \"ctrl enter\" to only execute the box",
"_____no_output_____"
]
],
[
[
"# I am a code box. Try execute me to run the code!\n1+1 # should be two!\nprint(\"one plus one is two! is two!\")",
"one plus one is two! is two!\n"
]
],
[
[
"6) Do you notice the number next to the box? It indicates the sequence of the box running. If a box has no number, it means it had not been executed.",
"_____no_output_____"
]
],
[
[
"## The box \"In []:\" on the right should be empty now. Once you ran it, a number will appear in it. \n##It means the box is executed! ",
"_____no_output_____"
]
],
[
[
"7) Sometimes python could crash - you would notice it when you see it is all frozen and you can't execute the code. The \"In []\" box will become \"In [*]\". If that happens, you could try to click \"stop\". If it's not working, click \"kernel\" & restart",
"_____no_output_____"
],
[
"<img src=\"https://storage.googleapis.com/bwdb/codeforhk/python_course/image/Screenshot%202019-02-15%20at%2012.59.47%20AM.png\" />",
"_____no_output_____"
]
],
[
[
"#This will freeze your python \n# while True:\n# #do nothing\n# #This will force python to keep calculating without stopping\n# 1+1\n# # If you click stop, an error message will appear below\n",
"_____no_output_____"
]
],
[
[
"8) Text can be created with markdown, as below:",
"_____no_output_____"
],
[
"Markdown are useful for lists, markup and formatting \n\n* *italics*\n* **bold**\n* `fixed_font`\n\n###### You can add titles of various size using \"#\" at the beginning of the line\n\n##### this has 5 \"#####\"",
"_____no_output_____"
],
[
"#### Exercise 1.3.2 - navigating the jupyter notebook",
"_____no_output_____"
],
[
"1) Try to create a box and execute 1 + 1\n\n2) Try to create a box and create a mark down (a text box) that shows your name\n\n",
"_____no_output_____"
]
],
[
[
"1+1",
"_____no_output_____"
]
],
[
[
"Hello world",
"_____no_output_____"
],
[
"3) Try to delete the box below:",
"_____no_output_____"
]
],
[
[
"# delete me!!",
"_____no_output_____"
]
],
[
[
"4) Try to execute the box below without error boxing",
"_____no_output_____"
]
],
[
[
"Try to execute me!",
"_____no_output_____"
]
],
[
[
"5) Try to execute the box to output the maths",
"_____no_output_____"
],
[
"1+1",
"_____no_output_____"
],
[
"### 1.3.3 How does native python works?",
"_____no_output_____"
],
[
"<img src=\"https://storage.googleapis.com/bwdb/codeforhk/python_course/image/Screenshot%202019-02-15%20at%209.04.05%20AM.png\" />",
"_____no_output_____"
],
[
"#### Exercise 1.3.3 How does native python works\n\n",
"_____no_output_____"
],
[
"1) For mac users, type \"command space\" & search for \"terminal\". Then type \"python3\" to get to your python terminal.\n\n2) For window uses, you would need to set your environmental variable to do so.\n\n3) Try to run \"helloworld.py\" by running \"python3 helloworld.py\"",
"_____no_output_____"
],
[
"### 1.3.4 How does Colab works?",
"_____no_output_____"
],
[
"<img src=\"https://miro.medium.com/max/1086/1*g_x1-5iYRn-SmdVucceiWw.png\" />\n\nColab is the \"Google doc\" equivalent of jupyter notebook, for while you can save your file on google drive, share it with your friends, and run it directly on the cloud.\n\nhttps://colab.research.google.com/drive/1Fx592qrAnfzJiHZ1XFuqDMc98FNQzF-x",
"_____no_output_____"
],
[
"### 1.3.5 How does Github works?",
"_____no_output_____"
],
[
"Github is a \"social network\" for developers (in a way). It is also a centre for vesion control - You can also think of it as the colaboration work for all developers",
"_____no_output_____"
],
[
"\n<img src=\"https://leanpub.com/site_images/git-flow/git-flow-nvie.png\" />",
"_____no_output_____"
],
[
"## 1.4.0 How does a computer/programming work?",
"_____no_output_____"
],
[
"### 1.4.1 Programming is all about problem solving",
"_____no_output_____"
],
[
"<img src=\"https://cs50.harvard.edu/college/2018/fall/weeks/0/notes/input_output.png\" />\n",
"_____no_output_____"
],
[
"### 1.4.2 Programming is to think about the steps\n\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"#### Example 1.4.2 Programming is to think about the steps \nHow do give instruction to computer to make a toast?",
"_____no_output_____"
],
[
"<img src=\"https://www.wikihow.com/images/thumb/4/45/Make-Buttered-Toast-Step-14-Version-2.jpg/aid599255-v4-728px-Make-Buttered-Toast-Step-14-Version-2.jpg\" />\n",
"_____no_output_____"
],
[
"define bread, peanut butter, jelly\n\n1) Get a piece of bread\n\n2) Spread peanut butter on it\n\n3) Get another piece of bread\n\n4) Spread jelly on it\n\n5) Put the two pieces of bread together\n\n6) Eat it!",
"_____no_output_____"
],
[
"#### Exercise 1.4.2 Programming is to think about the steps \n\nHow to give instruction to computer to make a tea?",
"_____no_output_____"
],
[
"<img src=\"http://m1.wish.co.uk/blog/wp-content/uploads/2014/10/lovetea.jpg\" />\n",
"_____no_output_____"
],
[
"#### Example 1.4.3 - solve problems in block-wise/step-wise approach\n\nTo make this into a code format, try to solve this\nhttps://studio.code.org/hoc/1",
"_____no_output_____"
],
[
"#### Exercise 1.4.3\n\nTry to complete challenge 2-5",
"_____no_output_____"
]
],
[
[
"for i in range(2,6):\n print('https://studio.code.org/hoc/'+str(i))",
"_____no_output_____"
]
],
[
[
"## Test 1.0.0\n\nhttps://goo.gl/forms/MNvu81mO1SOx7AVu2",
"_____no_output_____"
],
[
"<img src=\"https://www.codefor.hk/wp-content/themes/DC_CUSTOM_THEME/img/logo-code-for-hk-logo.svg\" height=\"150\" width=\"150\" align=\"center\"/>",
"_____no_output_____"
],
[
"# 2.0.0 Python basics\n\nTo start learning python, you would need to learn the syntax. You can think syntax as equivalent to grammar in natural language - it is the rule you write the language, so python understand you correctly!\n\nPython is an object oriented language - everything is stored as an object",
"_____no_output_____"
],
[
"<img src=\"http://www.lanl.gov/museum/events/calendar/2015/June/_images/dday.jpg\"/>\n",
"_____no_output_____"
],
[
"## 2.1.0 Understanding Python as an Object Oriented Language",
"_____no_output_____"
],
[
"Everything in Python is an object. Still, this begs the question. What is an object? You can think of it like a variables in mathematics. You can assign any value to this variable. E.g, you can assign:\n\n* x = 1\n* cristano_ronaldo = 'a footballer'\n* Ultimate_answer_for_everything = 42\n\nWhy do we want to do this? Because it is a clean and efficient way to manage a large amount of information, especially when the program starts to grow very large. It is sort of like the naming system for military operation or typhoon. For example, It is way cleaner to call it d-day than \"normandy landing in June 6 1944. \n\n* d_day = \"normandy landing in June 6 1944\"\n* hato = 'the #10 typhoon that hits macau in August 2017'\n\nIn python, it means any value can be assigned to a variable/object, or passed as an argument to a function. (Don't worry about function for now)\n\nThis is so important that I'm going to repeat it in case you missed it the first few times: everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.\n",
"_____no_output_____"
],
[
"### 2.1.1 Assign value to an object. \nUse \"=\" to assign a value to an object. Let's say we want to assign the value 1 to x, then execute the cell by CTRL+ENTER",
"_____no_output_____"
]
],
[
[
"#Let's say assign the value 1 to x, then execute the cell by CTRL+ENTER\nx = 1\n#From now on, python recognise x is equal to 1",
"_____no_output_____"
]
],
[
[
" Don't put x on the right & do it the other way round! 1=x would give you an error, because python thinks you are assigning x to the integer 1",
"_____no_output_____"
]
],
[
[
"# This will create an error, called \"SyntaxError\". It means python doesn't understand it! \n#(You should see this very often from now on)\n1 = x",
"_____no_output_____"
]
],
[
[
"The value executed will be stored in the memory. From now on x = 1. You can try execute the cell below, it should return 1, telling you the value of x is 1",
"_____no_output_____"
]
],
[
[
"x #try execute me!",
"_____no_output_____"
]
],
[
[
"<img src=\"https://tse1.mm.bing.net/th?id=OIP.I7QCS0SfLtoGA-q81cFbygEsEf&w=199&h=190&c=7&qlt=90&o=4&dpr=2&pid=1.7\"/>\n",
"_____no_output_____"
],
[
"### 2.1.2 Python is case-sensitive!\nTry wih capital X? What would you expect? Will the value be the same?",
"_____no_output_____"
]
],
[
[
"X",
"_____no_output_____"
]
],
[
[
"### 2.1.3 You can re-assign the value for an object. \nLet's try to assign another value for x",
"_____no_output_____"
]
],
[
[
"# You can assign anything to the variable. \nx = 'an expensive iphone'",
"_____no_output_____"
]
],
[
[
"### 2.1.4 The value of the object changes everytime you re-assign\n\nNow, try to execute x again on the cell below? You can also try to execute the cell 1.03 above. What would you expect?",
"_____no_output_____"
]
],
[
[
"x",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.1.4 \n\nWhat is the value of x?",
"_____no_output_____"
]
],
[
[
"x = 1\nx = 1 + x\nprint(x)\n#what is X now?",
"_____no_output_____"
]
],
[
[
"A Python Code Sample",
"_____no_output_____"
]
],
[
[
"x = 34 - 23 # These are discrete integers, x is a variable assinged to the math equation 34 - 23, = is an assignement operator \n #(Hash) here can be used to add comments, without affecting the code. Python won't read comments as part of the code\n\ny = \"Hello\" # This is an example of a string. The alphabets between \" \" are strings. \" Denotes that we are working with strings\n\nz = 3.45 # z is a variable where 3.45, a continous number, is assigned to it. In Python we call this type as floats\n\nif z == 3.45 or y == \"Hello\": # == is a comparison operator i.e. is z equal to 3.45 true? and is y equal to \"Hello\" true? In this\n # case yes. So we move down the if statement assigning x = x + 1 and y = y + \"World\" \n x = x + 1 # \"if\" statement is a loop where if the statement is true we move down the loop and execute the \n # code. Otherwise we stay out of the loop. Notice the indentation in the if loop. It clearly, shows\ny = y + \"World\" # if z == 3.45 or y == \"Hello\": we move into the loop to execute x = x + 1, y = y + \"World\"\n # Don't forget to put the \":\" at the end of the if statement, otherwise, Python will give you an\n # error\n # Python will give x = x + 1 a discrete value. That's one of the amazing features of Python, unlike\n # other computer languages, where it can indentify what type of variable you are trying to add an\n # integer to. In this case it knows x a is discrete value so it will condiser 1 to be a discrete \n # addition to x. With y = y + \"World\", python knows y is a string so \"World\" gets added to the\n # y string type.\nx = 1 #this is a comment \nx",
"_____no_output_____"
]
],
[
[
"### 2.1.5 How to seek help in python\n\nYou can use dir() or ? to seek help in python",
"_____no_output_____"
]
],
[
[
"## dir() gives information on the attributes of an object \ndir(wiki)\n## to learn more about something we can use help()\nhelp(wiki.replace)\n## or the fancy ipython version \"?\"\nwiki.replace?",
"_____no_output_____"
]
],
[
[
"## 2.2.0 Data type in python (Integer, Float, String)",
"_____no_output_____"
],
[
"### 2.2.1 integer\nInteger is literally, the integer, e.g 1,2,3,4. You can use type() to check the data type of the variable",
"_____no_output_____"
]
],
[
[
"y = 2\ntype(y)",
"_____no_output_____"
]
],
[
[
"You can also check the data type directly",
"_____no_output_____"
]
],
[
[
"type(2)",
"_____no_output_____"
]
],
[
[
"### 2.2.2 Float\nFloat is also a number. However float contains more information because it contains decimal place",
"_____no_output_____"
]
],
[
[
"z = 3.1416\ntype(z)",
"_____no_output_____"
]
],
[
[
"You can use int() to transform float to integer, or float() to transform integer to float",
"_____no_output_____"
]
],
[
[
"int(z)",
"_____no_output_____"
]
],
[
[
"### 2.2.3 String\nString can be any character you can find on the keyboard, as long as it can be bound within \" or '.",
"_____no_output_____"
]
],
[
[
"this_is_a_string = 'Patrick'\nthis_is_also_a_string = \"$%%^&*()njfnksdjfsdyftuy32uygsjdhfbmnasd\"\nnumber_can_also_be_string = \"123456\"",
"_____no_output_____"
],
[
"#Anything within a \" or ' will be a string\nmyname = \"Patrick\"\ntype(myname)",
"_____no_output_____"
]
],
[
[
"String can be concatenated by using +",
"_____no_output_____"
]
],
[
[
"#example\nfirstname = 'Cristiano'\nlastname = 'Ronaldo'\n\nfullname = firstname + lastname\nfullname",
"_____no_output_____"
]
],
[
[
"Remember, string tend to contain less information. It doesn't treat numbers inside a string as numbers. What would you expect to see below?",
"_____no_output_____"
]
],
[
[
"one = '1'\ntwo = '2'\none+two",
"_____no_output_____"
]
],
[
[
"You can use str() to transform float or int to string",
"_____no_output_____"
]
],
[
[
"float(one) + int(two)",
"_____no_output_____"
]
],
[
[
"<img src=\"http://ivl-net.eu/wp-content/uploads/2015/04/workshops-chalkboard.jpg\"/>\n",
"_____no_output_____"
],
[
"#### Example 2.2.3 - Work out your full name\n1. Try input your first name and last name in the variable, and work out your full name\n2. Now, realize there is no space between your name? Can you amend the code so there is a space?\n3. Type in your age, and assign it as integer to the age variable\n4. complete the code so it prints out \"[Yourname] is now [age] years old\".\ne.g Cristiano Ronadlo is now 32 years old",
"_____no_output_____"
]
],
[
[
"firstname = 'cristiano'\nlastname = 'ronaldo'\n\nfullname = firstname + lastname\nprint(fullname)\n\nage = 32\nprint(fullname + 'is now ' + str(age))",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.2.3 - Work out your full name",
"_____no_output_____"
]
],
[
[
"#exercise: Try input your first name and last name in the variable\n\nfirstname = 'Denis'\nlastname = 'Tsoi'\n\nfullname = firstname + lastname\nprint(fullname)\n\n#How do we add a space in between?\nfullname = firstname + \" \" + lastname\n\nage = 32\nprint(fullname + ' is now ' + str(age) + ' years old.')",
"_____no_output_____"
]
],
[
[
"### 2.2.4 Object can be of any data type\n\nTry execute the cell below",
"_____no_output_____"
]
],
[
[
"x = 1\nprint(x)\n\nhouse_price = 100\nprint(house_price)\n\ngirlfriend = 'pretty'\nprint(girlfriend)",
"_____no_output_____"
],
[
"girlfriend",
"_____no_output_____"
]
],
[
[
"### 2.2.5 Reserved words \n\nThere are a bunch of words that you are not allowed to use\nThis is because they have special meanings in python",
"_____no_output_____"
],
[
"https://www.programiz.com/python-programming/keywords-identifier",
"_____no_output_____"
]
],
[
[
"# Don't use these words!! They have special meanings\nFalse\nNone\nand\nif\nfor\nfrom\nimport\nas\nis\nin",
"_____no_output_____"
]
],
[
[
"## 2.3.0 Python mathematics operations",
"_____no_output_____"
],
[
"### 2.3.1 Sum",
"_____no_output_____"
],
[
"<img src=\"https://i-cdn.phonearena.com/images/article/98010-thumb/The-fall-2017-Apple-iPhone-lineup-we-now-have-8-iPhones-to-choose-from-more-than-ever-before.jpg\"/>",
"_____no_output_____"
],
[
"#### Example 2.2.1 ",
"_____no_output_____"
]
],
[
[
"#you can use it like a calculator. Try 6+7? you should be expecting 13?\n6+7",
"_____no_output_____"
],
[
"#Let's say I want to know how much to does it cost to the buy whole set of iphone\niphoneX = 9998\nairpods = 1288\nprice_for_new_iphone = iphoneX + airpods\nprice_for_new_iphone",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.2.1 - Cost of Samsung S8\nUsing the previous example, now that samsung s8 cost $5200. \n1. Assign 5200 to samsung_s8\n2. Assign 0 to normal_headphone (becoz we already have one)\n3. findout how much in total to buy samsung s8 & normal_headphone? asign it to variable called price_for_new_samsung",
"_____no_output_____"
]
],
[
[
"#Your code in here!\n\nsamsung_s8 = 5200\nnormal_headphone = 0\n\nprice_for_new_samsung = samsung_s8 + normal_headphone\nprice_for_new_samsung",
"_____no_output_____"
]
],
[
[
"### 2.3.2 Subtraction",
"_____no_output_____"
],
[
"<img src=\"http://na.signwiki.org/images/public/d/db/Subtraction.gif\"/>",
"_____no_output_____"
],
[
"#### Example 2.3.2",
"_____no_output_____"
]
],
[
[
"# You can also do calculation like excel\n6-7\n11-9",
"_____no_output_____"
],
[
"## read interactive input \na = input(\"enter the first number: \" )\nb = input(\"enter the second number: \")\n",
"_____no_output_____"
],
[
"#example\n\n#Assign 2017 to a variable called THISYEAR, \nTHISYEAR = 2019\n#Assign the year of your birthday to a variable called BIRTHYEAR\nBIRTHYEAR = 1987\n\n#work out your age by substracting BIRTHYEAR by THISYEAR\nage = THISYEAR-BIRTHYEAR\nprint(age)",
"_____no_output_____"
]
],
[
[
"<img src=\"http://cdn1.knowyourmobile.com/sites/knowyourmobilecom/files/styles/gallery_wide/public/2016/02/screen_shot_2016-02-22_at_4.48.09_pm.jpg?itok=H2I28t7Q\"/>\n\n",
"_____no_output_____"
],
[
"#### Exercise 2.3.2 - Iphone vs Samsung\nUsing the previous example, you have the price to buy samsung s8. Find out how much more expensive are iphone, compare to samsung?\n1. Create a new object called price_for_new_samsung\n2. we already have an object called price_for_new_iphone\n3. execute price_for_new_iphone - price_for_new_samsung, and assign to a variable called \"money_saved\"\n",
"_____no_output_____"
]
],
[
[
"#Your code in here!\nprice_for_new_samsung = 2000\nprice_for_new_iphone = 3000\n\nmoney_saved = price_for_new_iphone - price_for_new_samsung\nprint(money_saved)",
"_____no_output_____"
]
],
[
[
"### 2.3.3 multiplication",
"_____no_output_____"
],
[
"#### Example 2.3.3 ",
"_____no_output_____"
]
],
[
[
"7*6",
"_____no_output_____"
],
[
"#exercise\n\n#let's assign 7.8 to a variable called exchange_rate\nexchange_rate = 7.8\n#Assign 100 to a variable called usd\nusd = 100 \n\n#workout how much hkd is worth of 100 usd\nhkd = exchange_rate*usd\nprint(hkd)",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.2.3 - HKD & USD\nUsing the previous example, can you try to convert hkd back to usd?",
"_____no_output_____"
]
],
[
[
"#your code here!\ndef convert_hkd_to_usd(hkd):\n exchange_rate = 7.8\n return hkd / exchange_rate\n\nconvert_hkd_to_usd(780)",
"_____no_output_____"
]
],
[
[
"### 2.3.4 Divison",
"_____no_output_____"
]
],
[
[
"\n## note that we are doing calculation among integers\n6/7\n## let's make sure that the interpreter understands we want to use floating point\n6./7\n## You don't need to define the type of variable. The interpreter will guess.\na=6\nb=7\nprint(a*b , a+b, a-b, a/b) \n\n## As in the previous example, if one element is floating point, the interpreter will do an automatic cast\nprint \na=6. ## this is now float\nb=7\nprint(a*b , a+b, a-b, a/b) ",
"_____no_output_____"
]
],
[
[
"### 2.3.5 Logical operation in python\nPlay around with logic!",
"_____no_output_____"
],
[
" == means checking whether if they equal",
"_____no_output_____"
]
],
[
[
"x = 1\nx ==1 # Check if x equals one",
"_____no_output_____"
]
],
[
[
" != means check if they don't equal",
"_____no_output_____"
]
],
[
[
"!=1",
"_____no_output_____"
],
[
"## Some basic logic operators \na = 2 \nb = 3 \nprint \"a = \" ,a \nprint \"b = \" ,b\n\n## == stands for \"is equal to\" \n## be careful and do not confuse \n## == which is an operator that compares the two operand\n## with = , which is an assignment operator.\nprint \"a == b is \" , a == b \n\n## != \"not equal to\" \nprint \"a != b is \" , a != b \n\n## greater and smaller than\nprint \"a < b is \" , a < b \nprint \"a > b is \" , a > b\n\n## the basic boolean types.\nprint \"True is ... well ... \" , True\nprint \"...and obviously False is \" , False ",
"_____no_output_____"
]
],
[
[
" \">\" and \"<\" means bigger or smaller",
"_____no_output_____"
]
],
[
[
"iphone = 9000\nsamsung = 5000\niphone > samsung",
"_____no_output_____"
]
],
[
[
"#### Exercise 2.3.5 - check if 1 equals 1.0",
"_____no_output_____"
]
],
[
[
"x = 1\ny = 1.0\n\n#Your code here!\nx == y\n",
"_____no_output_____"
]
],
[
[
"## 2.4.0 Python string / text operations",
"_____no_output_____"
]
],
[
[
"## a string is just a sequence of characters within quotes \"\" or '' \nmystr1 = \"i am\"\nmystr2 = 'i am'\nmystr1==mystr2\n",
"_____no_output_____"
]
],
[
[
"### 2.4.1 String is just text \n\nPython can handle long text, or even an entire novel, or even the entire wikipedia!",
"_____no_output_____"
]
],
[
[
"wiki = \"Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991\"\nprint(wiki)",
"Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991\n"
]
],
[
[
"### 2.4.2 Indexing in string\n\nYou can navigate each letter in the string by using square brackets and index",
"_____no_output_____"
]
],
[
[
"print(wiki[3])\nprint(wiki[-1])\nprint(wiki[0:20])",
"h\n1\nPython is a widely u\n"
]
],
[
[
"### 2.4.3 String related functions\n\nSome very useful functions to find characters in strings",
"_____no_output_____"
]
],
[
[
"## manipulating strings is very easy \n\n## finding the location of a substring\nprint(wiki.find(\"Python\"))\n\n## changing to uppercase\nprint(wiki.upper())\n\n## replacing substrings\nprint(wiki.replace('high','low'))\n\n## these operations do not modify the original string\nprint(wiki)\n\n## we can count the occurrences of a letter\nprint(wiki.count('python') )\n\n#Lower change all the letters to lower case\nwiki.lower().count('python')\n\n## \"in\" returns a boolean\nprint(\"python\" in wiki)\nprint(\"language\" in wiki)\n\n## .split() separates fields \nprint(wiki.split())",
"0\nPYTHON IS A WIDELY USED HIGH-LEVEL PROGRAMMING LANGUAGE FOR GENERAL-PURPOSE PROGRAMMING, CREATED BY GUIDO VAN ROSSUM AND FIRST RELEASED IN 1991\nPython is a widely used low-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991\nPython is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991\n0\nFalse\nTrue\n['Python', 'is', 'a', 'widely', 'used', 'high-level', 'programming', 'language', 'for', 'general-purpose', 'programming,', 'created', 'by', 'Guido', 'van', 'Rossum', 'and', 'first', 'released', 'in', '1991']\n"
]
],
[
[
"#### Challenge 2.4.3 - Change the shape of the song \"Shape of you\"\n1. This is a popular song from Ed Sheeran called shape of you. You can listen to it from the youtube link (please wear your airpods, or plug in your earphone if you are not using iphone)\n2. Count the occurance of the word \"baby\"\n3. Count the number of words in the entire lyrics\n4. Replace \"Oh I oh I oh I oh I \" to something else\n\nhttps://www.azlyrics.com/lyrics/edsheeran/shapeofyou.html\n\n",
"_____no_output_____"
]
],
[
[
"from IPython.display import YouTubeVideo\n\nshape_of_you = \"The club isn't the best place to find a lover. So the bar is where I go (mmmm). Me and my friends at the table doing shots. Drinking fast and then we talk slow (mmmm). And you come over and start up a conversation with just me. And trust me I'll give it a chance now (mmmm). Take my hand, stop, put Van The Man on the jukebox. And then we start to dance. And now I'm singing like. . Girl, you know I want your love. Your love was handmade for somebody like me. Come on now, follow my lead. I may be crazy, don't mind me. Say, boy, let's not talk too much. Grab on my waist and put that body on me. Come on now, follow my lead. Come, come on now, follow my lead (mmmm). . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you. . One week in we let the story begin. We're going out on our first date (mmmm). You and me are thrifty, so go all you can eat. Fill up your bag and I fill up a plate (mmmm). We talk for hours and hours about the sweet and the sour. And how your family is doing okay (mmmm). And leave and get in a taxi, then kiss in the backseat. Tell the driver make the radio play. And I'm singing like. . Girl, you know I want your love. Your love was handmade for somebody like me. Come on now, follow my lead. I may be crazy, don't mind me. Say, boy, let's not talk too much. Grab on my waist and put that body on me. Come on now, follow my lead. Come, come on now, follow my lead (mmmm). . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you. . Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you\"\n#print(shape_of_you)\n(YouTubeVideo('JGwWNGJdvx8'))",
"_____no_output_____"
],
[
"#Your code here!\n# print(\"baby occurances\", shape_of_you.count(\"baby\"))\n# print(\"word occurances\", len(shape_of_you.split()))\n# shape_of_you.replace(\"Oh I oh I oh I oh I\", \"meep\")\n\ndef find_count_of_word_in_song(word, song):\n if word is None:\n raise Exception(\"Word is not provided\")\n elif song is None:\n raise Exception(\"Song is not provided\")\n return song.count(word)\n\n\nshape_of_you = \"The club isn't the best place to find a lover. So the bar is where I go (mmmm). Me and my friends at the table doing shots. Drinking fast and then we talk slow (mmmm). And you come over and start up a conversation with just me. And trust me I'll give it a chance now (mmmm). Take my hand, stop, put Van The Man on the jukebox. And then we start to dance. And now I'm singing like. . Girl, you know I want your love. Your love was handmade for somebody like me. Come on now, follow my lead. I may be crazy, don't mind me. Say, boy, let's not talk too much. Grab on my waist and put that body on me. Come on now, follow my lead. Come, come on now, follow my lead (mmmm). . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you. . One week in we let the story begin. We're going out on our first date (mmmm). You and me are thrifty, so go all you can eat. Fill up your bag and I fill up a plate (mmmm). We talk for hours and hours about the sweet and the sour. And how your family is doing okay (mmmm). And leave and get in a taxi, then kiss in the backseat. Tell the driver make the radio play. And I'm singing like. . Girl, you know I want your love. Your love was handmade for somebody like me. Come on now, follow my lead. I may be crazy, don't mind me. Say, boy, let's not talk too much. Grab on my waist and put that body on me. Come on now, follow my lead. Come, come on now, follow my lead (mmmm). . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Oh I oh I oh I oh I. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you. . Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. Come on, be my baby, come on. . I'm in love with the shape of you. We push and pull like a magnet do. Although my heart is falling too. I'm in love with your body. Last night you were in my room. And now my bedsheets smell like you. Every day discovering something brand new. I'm in love with your body. . Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Come on, be my baby, come on. Come on, be my baby, come on. I'm in love with your body. Every day discovering something brand new. I'm in love with the shape of you\"\nfind_count_of_word_in_song(\"baby\", shape_of_you)",
"_____no_output_____"
],
[
"\"100\" + \"100\"",
"_____no_output_____"
]
],
[
[
"<img src=\"https://www.codefor.hk/wp-content/themes/DC_CUSTOM_THEME/img/logo-code-for-hk-logo.svg\" height=\"150\" width=\"150\" align=\"center\"/>",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cba37cd0f11f230770c3de31d36d715092349c2c
| 7,222 |
ipynb
|
Jupyter Notebook
|
lessons/lesson3/data/2_Lists_and_Tuples.ipynb
|
jenniferbuz/sci_coding
|
80a36ca0664c33504d47811771f2870054a1cb73
|
[
"MIT"
] | null | null | null |
lessons/lesson3/data/2_Lists_and_Tuples.ipynb
|
jenniferbuz/sci_coding
|
80a36ca0664c33504d47811771f2870054a1cb73
|
[
"MIT"
] | null | null | null |
lessons/lesson3/data/2_Lists_and_Tuples.ipynb
|
jenniferbuz/sci_coding
|
80a36ca0664c33504d47811771f2870054a1cb73
|
[
"MIT"
] | 5 |
2018-11-05T19:29:42.000Z
|
2018-11-05T22:43:49.000Z
| 23.372168 | 327 | 0.547909 |
[
[
[
"## Lists\nA **List** is a common way to store a collection of objects in Python. Lists are defined with square brackets `[]` in Python.",
"_____no_output_____"
]
],
[
[
"# An empty list can be assigned to a variable and aded to later\nempty_list = []\n\n# Or a list can be initialized with a few elements\nfruits_list = ['apple', 'banana', 'orange', 'watermelon']\n\ntype(fruits_list)",
"_____no_output_____"
]
],
[
[
"Lists are *ordered*, meaning they can be indexed to access their elements, much like accessing characters in a **String**.",
"_____no_output_____"
]
],
[
[
"fruits_list[0]",
"_____no_output_____"
],
[
"fruits_list[1:3]",
"_____no_output_____"
]
],
[
[
"Lists are also *mutable*, meaning they can be changed in place, extended and shortened at will. ",
"_____no_output_____"
]
],
[
[
"# Let's replace apple with pear\nfruits_list[0] = 'pear'\nfruits_list",
"_____no_output_____"
]
],
[
[
"We can also append to lists with the `.append()` method to add an **element** to the end.",
"_____no_output_____"
]
],
[
[
"fruits_list.append('peach')\nfruits_list",
"_____no_output_____"
]
],
[
[
"Or we can remove and return the last element from a list with `pop()`.",
"_____no_output_____"
]
],
[
[
"fruits_list.pop()",
"_____no_output_____"
],
[
"# Notice that 'peach' is no longer in the fruits list\nfruits_list",
"_____no_output_____"
]
],
[
[
"To understand mutability, let's compare the list with an **immutable** collection of ordered elements, the **Tuple**. \n\n# Tuples\nTuples in Python are defined with `()` parentheses.",
"_____no_output_____"
]
],
[
[
"# Tuples are defined similarly to lists, but with () instead of []\nempty_tuple = ()\nfruits_tuple = ('apple', 'banana', 'orange', 'watermelon')\nfruits_tuple",
"_____no_output_____"
]
],
[
[
"Like the *ordered* **String** and **List**, the **Tuple** can be indexed to access its elements.",
"_____no_output_____"
]
],
[
[
"fruits_tuple[0]",
"_____no_output_____"
],
[
"fruits_tuple[1:3]",
"_____no_output_____"
]
],
[
[
"Unlike the *mutable* list, we get an error if we try to change the elements of the **Tuple** in place, or append to it.",
"_____no_output_____"
]
],
[
[
"fruits_tuple[0] = 'pear'",
"_____no_output_____"
],
[
"fruits_tuple.append('peach')",
"_____no_output_____"
]
],
[
[
"## Why would I ever use an inferior version of the list?\nTuples are less flexible than lists, but sometimes that is *exactly what you want* in your program. \n\nSay I have a bunch of *constants* and I want to make sure that they stay... constant. In that case, a tuple would be a better choice to store them than a list. Then if any future code tries to change or extend your tuple as if it were a list, it would throw an error and you'd know something was not behaving as expected.",
"_____no_output_____"
],
[
"## List methods\nLet's explore some useful **methods** of the **list**. We have already used the `.append()` and `.pop()` methods above. To see what methods are available, we can always use `help()`.",
"_____no_output_____"
]
],
[
[
"# Recall, underscores denote special methods reserved by Python\n# We can scroll past the _methods_ to append(...)\nhelp(list)",
"_____no_output_____"
]
],
[
[
"Let's try out the `.index()` and `.sort()` methods.",
"_____no_output_____"
]
],
[
[
"pets = ['dog', 'cat', 'snake', 'turtle', 'guinea pig']\n\n# Let's find out what index cat is at\npets.index('cat')",
"_____no_output_____"
],
[
"# Now let's try sorting the list\npets.sort()\npets",
"_____no_output_____"
]
],
[
[
"Sorting a list of strings rearranges them to be in alphabetical order. Lists are not restricted to holding strings, let's see what happens when we sort a list of **Int**.",
"_____no_output_____"
]
],
[
[
"ages = [12, 24, 37, 9, 71, 42, 5]\nages.sort()\nages",
"_____no_output_____"
]
],
[
[
"Sorting can be a very useful feature for ordering your data in Python. \n\nA useful built-in function that can be used to find the length of an ordered data structure is `len()`. It works on lists, tuples, strings and the like.",
"_____no_output_____"
]
],
[
[
"print(len(['H', 'E', 'L', 'L', 'O']), len((1, 2, 3, 4)), len('Hello'))",
"_____no_output_____"
]
],
[
[
"Great, you now know the basics of lists and tuples. Lastly, we will explore **sets** and **dictionaries**.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba3889d9d9252bd4e9c113b91e29b85a69f64b1
| 44,420 |
ipynb
|
Jupyter Notebook
|
codes/agglio_sigmoid_pre-activation_4b.ipynb
|
debojyoti23/agglio-1
|
391dd905bd0e1508f512cd8ed6e0fe96b1fd0d19
|
[
"MIT"
] | 1 |
2022-01-18T00:21:22.000Z
|
2022-01-18T00:21:22.000Z
|
codes/agglio_sigmoid_pre-activation_4b.ipynb
|
debojyoti23/agglio-1
|
391dd905bd0e1508f512cd8ed6e0fe96b1fd0d19
|
[
"MIT"
] | null | null | null |
codes/agglio_sigmoid_pre-activation_4b.ipynb
|
debojyoti23/agglio-1
|
391dd905bd0e1508f512cd8ed6e0fe96b1fd0d19
|
[
"MIT"
] | 2 |
2022-01-07T17:34:31.000Z
|
2022-01-07T17:44:18.000Z
| 44,420 | 44,420 | 0.91398 |
[
[
[
"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom agglio_lib import *",
"_____no_output_____"
],
[
"#-------------------------------Data Generation section---------------------------#\nn = 1000\nd = 50\nsigma=0.5\nw_radius = 10\nwAst = np.random.randn(d,1)\nX = getData(0, 1, n, d)/np.sqrt(d)\nw0 =w_radius*np.random.randn(d,1)/np.sqrt(d)\nipAst = np.matmul(X, wAst)\n# y = sigmoid(ipAst)\ny = sigmoid_noisy_pre(ipAst,sigma_noise=sigma)",
"_____no_output_____"
],
[
"#-----------AGGLIO-GD-------------#\nparams={}\nparams['algo']='AG_GD'\nparams['w0']=w0\nparams['wAst']=wAst\nobjVals_agd,distVals_agd,time_agd = cross_validate(X,y,params,cross_validation=True)",
"The best parameters are {'B_init': 0.1, 'B_step': 1.5, 'alpha': 50.75} with a score of -0.01\n"
],
[
"#-----------AGGLIO-SGD-------------#\nparams={}\nparams['algo']='AG_SGD'\nparams['w0']=w0\nparams['wAst']=wAst\nobjVals_agsgd,distVals_agsgd,time_agsgd = cross_validate(X,y,params,cross_validation=True)",
"The best parameters are {'B_init': 0.001, 'B_step': 1.2575, 'alpha': 56.44444444444444} with a score of -0.01\n"
],
[
"#-----------AGGLIO-SVRG-------------#\nparams={}\nparams['algo']='AG_SVRG'\nparams['w0']=w0\nparams['wAst']=wAst\nobjVals_agsvrg,distVals_agsvrg,time_agsvrg = cross_validate(X,y,params,cross_validation=True)",
"The best parameters are {'B_init': 0.01, 'B_step': 2.0, 'alpha': 134.0, 'temp_cap': 0.7} with a score of -0.01\n"
],
[
"#-----------AGGLIO-ADAM-------------#\n\nhparams['AG_ADAM']={}\nhparams['AG_ADAM']['alpha']=np.power(10.0, [0, -1, -2, -3]).tolist()\nhparams['AG_ADAM']['B_init']=np.power(10.0, [0, -1, -2, -3]).tolist()\nhparams['AG_ADAM']['B_step']=np.linspace(start=1.01, stop=3, num=5).tolist()\nhparams['AG_ADAM']['beta_1'] = [0.3, 0.5, 0.7, 0.9]\nhparams['AG_ADAM']['beta_2'] = [0.3, 0.5, 0.7, 0.9]\nhparams['AG_ADAM']['epsilon'] = np.power(10.0, [-3, -5, -8]).tolist()\n\nhparam = hparams['AG_ADAM']\n\n\ncv = ShuffleSplit( n_splits = 1, test_size = 0.3, random_state = 42 )\ngrid = GridSearchCV( AG_ADAM(), param_grid=hparam, refit = False, cv=cv) #, verbose=3\ngrid.fit( X, y.ravel(), w_init=w0.ravel(), w_star=wAst.ravel(), minibatch_size=50)\nbest = grid.best_params_\n\nprint(\"The best parameters are %s with a score of %0.2f\" % (grid.best_params_, grid.best_score_))",
"The best parameters are {'B_init': 0.001, 'B_step': 3.0, 'alpha': 0.1, 'beta_1': 0.7, 'beta_2': 0.3, 'epsilon': 0.001} with a score of -0.01\n"
],
[
"print(\"The best parameters are %s with a score of %0.2f\" % (grid.best_params_, grid.best_score_))\n\n#ag_adam = AG_ADAM(alpha= best[\"alpha\"], B_init=best['B_init'], B_step=best['B_step'], beta_1=best['beta_1'], beta_2=best['beta_2'] )\nag_adam = AG_ADAM(alpha= best[\"alpha\"], B_init=best['B_init'], B_step=best['B_step'], beta_1=best['beta_1'], beta_2=best['beta_2'], epsilon=best['epsilon'] )\nag_adam.fit( X, y.ravel(), w_init=w0.ravel(), w_star=wAst.ravel(), from google.colab import drive\ndrive.mount('/content/drive')\n%cd /cmax_iter=600 )\n\ndistVals_ag_adam = ag_adam.distVals\ntime_ag_adam=ag_adam.clock",
"The best parameters are {'B_init': 0.001, 'B_step': 3.0, 'alpha': 0.1, 'beta_1': 0.7, 'beta_2': 0.3, 'epsilon': 0.001} with a score of -0.01\n"
],
[
"plt.rcParams['pdf.fonttype'] = 42\nplt.rcParams['ps.fonttype'] = 42\n\nfig = plt.figure()\nplt.plot(time_agd, distVals_agd, label='AGGLIO-GD', color='#1b9e77', linewidth=3)\nplt.plot(time_agsgd, distVals_agsgd, label='AGGLIO-SGD', color='#5e3c99', linewidth=3)\nplt.plot(time_agsvrg, distVals_agsvrg, label='AGGLIO-SVRG', color='#d95f02', linewidth=3)\nplt.plot(time_ag_adam, distVals_ag_adam, label='AGGLIO-ADAM', color='#01665e', linewidth=3)\n\nplt.legend()\nplt.ylabel(\"$||w^t-w^*||_2$\",fontsize=12)\nplt.xlabel(\"Time\",fontsize=12)\nplt.grid()\nplt.yscale('log')\nplt.xlim(time_agd[0], time_agd[-1])\nplt.title(f'n={n}, d={d}, $\\sigma$ = {sigma}, pre-activation')\nplt.savefig('Agglio_pre-noise_sigmoid.pdf', dpi=300)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba39784cdd4dd243f3acde1519c47884406f887
| 92,013 |
ipynb
|
Jupyter Notebook
|
module2/LS_DS_232_assignment.ipynb
|
iesous-kurios/DS-Unit-2-Applied-Modeling
|
5cec246e1220cb5e81b8abed77d8d5b3ddf28742
|
[
"MIT"
] | 1 |
2019-12-05T03:08:57.000Z
|
2019-12-05T03:08:57.000Z
|
module2/LS_DS_232_assignment.ipynb
|
iesous-kurios/DS-Unit-2-Applied-Modeling
|
5cec246e1220cb5e81b8abed77d8d5b3ddf28742
|
[
"MIT"
] | null | null | null |
module2/LS_DS_232_assignment.ipynb
|
iesous-kurios/DS-Unit-2-Applied-Modeling
|
5cec246e1220cb5e81b8abed77d8d5b3ddf28742
|
[
"MIT"
] | null | null | null | 65.911891 | 42,700 | 0.766772 |
[
[
[
"Lambda School Data Science\n\n*Unit 2, Sprint 3, Module 2*\n\n---\n\n\n# Permutation & Boosting\n\nYou will use your portfolio project dataset for all assignments this sprint.\n\n## Assignment\n\nComplete these tasks for your project, and document your work.\n\n- [ ] If you haven't completed assignment #1, please do so first.\n- [ ] Continue to clean and explore your data. Make exploratory visualizations.\n- [ ] Fit a model. Does it beat your baseline? \n- [ ] Try xgboost.\n- [ ] Get your model's permutation importances.\n\nYou should try to complete an initial model today, because the rest of the week, we're making model interpretation visualizations.\n\nBut, if you aren't ready to try xgboost and permutation importances with your dataset today, that's okay. You can practice with another dataset instead. You may choose any dataset you've worked with previously.\n\nThe data subdirectory includes the Titanic dataset for classification and the NYC apartments dataset for regression. You may want to choose one of these datasets, because example solutions will be available for each.\n\n\n## Reading\n\nTop recommendations in _**bold italic:**_\n\n#### Permutation Importances\n- _**[Kaggle / Dan Becker: Machine Learning Explainability](https://www.kaggle.com/dansbecker/permutation-importance)**_\n- [Christoph Molnar: Interpretable Machine Learning](https://christophm.github.io/interpretable-ml-book/feature-importance.html)\n\n#### (Default) Feature Importances\n - [Ando Saabas: Selecting good features, Part 3, Random Forests](https://blog.datadive.net/selecting-good-features-part-iii-random-forests/)\n - [Terence Parr, et al: Beware Default Random Forest Importances](https://explained.ai/rf-importance/index.html)\n\n#### Gradient Boosting\n - [A Gentle Introduction to the Gradient Boosting Algorithm for Machine Learning](https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/)\n - _**[A Kaggle Master Explains Gradient Boosting](http://blog.kaggle.com/2017/01/23/a-kaggle-master-explains-gradient-boosting/)**_\n - [_An Introduction to Statistical Learning_](http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Seventh%20Printing.pdf) Chapter 8\n - [Gradient Boosting Explained](http://arogozhnikov.github.io/2016/06/24/gradient_boosting_explained.html)\n - _**[Boosting](https://www.youtube.com/watch?v=GM3CDQfQ4sw) (2.5 minute video)**_",
"_____no_output_____"
]
],
[
[
"# all imports needed for this sheet\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport category_encoders as ce\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.feature_selection import f_regression, SelectKBest\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import validation_curve\nfrom sklearn.tree import DecisionTreeRegressor\nimport xgboost as xgb\n\n%matplotlib inline\nimport seaborn as sns\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n",
"_____no_output_____"
],
[
"pip install category_encoders",
"Requirement already satisfied: category_encoders in /home/iesous-kurios/myenv/lib/python3.6/site-packages\nRequirement already satisfied: statsmodels>=0.6.1 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: scikit-learn>=0.20.0 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: pandas>=0.21.1 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: patsy>=0.4.1 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: numpy>=1.11.3 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: scipy>=0.19.0 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from category_encoders)\nRequirement already satisfied: joblib>=0.11 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from scikit-learn>=0.20.0->category_encoders)\nRequirement already satisfied: python-dateutil>=2.6.1 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from pandas>=0.21.1->category_encoders)\nRequirement already satisfied: pytz>=2017.2 in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from pandas>=0.21.1->category_encoders)\nRequirement already satisfied: six in /home/iesous-kurios/myenv/lib/python3.6/site-packages (from patsy>=0.4.1->category_encoders)\nNote: you may need to restart the kernel to use updated packages.\n"
],
[
"%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'\n !pip install category_encoders==2.*\n !pip install eli5\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'\n",
"_____no_output_____"
],
[
"df = pd.read_excel(DATA_PATH+'/Unit_2_project_data.xlsx')",
"_____no_output_____"
],
[
"exit_reasons = ['Rental by client with RRH or equivalent subsidy', \n 'Rental by client, no ongoing housing subsidy', \n 'Staying or living with family, permanent tenure', \n 'Rental by client, other ongoing housing subsidy',\n 'Permanent housing (other than RRH) for formerly homeless persons', \n 'Staying or living with friends, permanent tenure', \n 'Owned by client, with ongoing housing subsidy', \n 'Rental by client, VASH housing Subsidy'\n ]",
"_____no_output_____"
],
[
"# pull all exit destinations from main data file and sum up the totals of each destination, \n# placing them into new df for calculations\nexits = df['3.12 Exit Destination'].value_counts()",
"_____no_output_____"
],
[
" # create target column (multiple types of exits to perm)\ndf['perm_leaver'] = df['3.12 Exit Destination'].isin(exit_reasons)",
"_____no_output_____"
],
[
"# base case\ndf['perm_leaver'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# replace spaces with underscore\ndf.columns = df.columns.str.replace(' ', '_')",
"_____no_output_____"
],
[
"# see size of df prior to dropping empties\ndf.shape",
"_____no_output_____"
],
[
"# drop rows with no exit destination (current guests at time of report)\ndf = df.dropna(subset=['3.12_Exit_Destination'])",
"_____no_output_____"
],
[
"# shape of df after dropping current guests\ndf.shape",
"_____no_output_____"
],
[
"# verify no NaN in exit destination feature\ndf['3.12_Exit_Destination'].isna().value_counts()",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ntrain = df\n\n# Split train into train & val\ntrain, val = train_test_split(train, train_size=0.80, test_size=0.20, \n stratify=train['perm_leaver'], random_state=42)\n\ndef wrangle(X):\n \"\"\"Wrangle train, validate, and test sets in the same way\"\"\"\n \n # Prevent SettingWithCopyWarning\n X = X.copy()\n \n # drop any private information\n X = X.drop(columns=['3.1_FirstName', '3.1_LastName', '3.2_SocSecNo', \n '3.3_Birthdate', 'V5_Prior_Address'])\n \n # drop unusable columns\n X = X.drop(columns=['2.1_Organization_Name', '2.4_ProjectType',\n 'WorkSource_Referral_Most_Recent', 'YAHP_Referral_Most_Recent',\n 'SOAR_Enrollment_Determination_(Most_Recent)',\n 'R7_General_Health_Status', 'R8_Dental_Health_Status',\n 'R9_Mental_Health_Status', 'RRH_Date_Of_Move-In',\n 'RRH_In_Permanent_Housing', 'R10_Pregnancy_Due_Date',\n 'R10_Pregnancy_Status', 'R1_Referral_Source',\n 'R2_Date_Status_Determined', 'R2_Enroll_Status',\n 'R2_Reason_Why_No_Services_Funded', 'R2_Runaway_Youth',\n 'R3_Sexual_Orientation', '2.5_Utilization_Tracking_Method_(Invalid)',\n '2.2_Project_Name', '2.6_Federal_Grant_Programs', '3.16_Client_Location',\n '3.917_Stayed_Less_Than_90_Days', \n '3.917b_Stayed_in_Streets,_ES_or_SH_Night_Before', \n '3.917b_Stayed_Less_Than_7_Nights', '4.24_In_School_(Retired_Data_Element)',\n 'CaseChildren', 'ClientID', 'HEN-HP_Referral_Most_Recent',\n 'HEN-RRH_Referral_Most_Recent', 'Emergency_Shelter_|_Most_Recent_Enrollment',\n 'ProgramType', 'Days_Enrolled_Until_RRH_Date_of_Move-in',\n 'CurrentDate', 'Current_Age', 'Count_of_Bed_Nights_-_Entire_Episode',\n 'Bed_Nights_During_Report_Period'])\n \n # drop rows with no exit destination (current guests at time of report)\n X = X.dropna(subset=['3.12_Exit_Destination'])\n \n # remove columns to avoid data leakage\n X = X.drop(columns=['3.12_Exit_Destination', '5.9_Household_ID', '5.8_Personal_ID',\n '4.2_Income_Total_at_Exit', '4.3_Non-Cash_Benefit_Count_at_Exit'])\n \n # Drop needless feature\n unusable_variance = ['Enrollment_Created_By', '4.24_Current_Status_(Retired_Data_Element)']\n X = X.drop(columns=unusable_variance)\n\n # Drop columns with timestamp\n timestamp_columns = ['3.10_Enroll_Date', '3.11_Exit_Date', \n 'Date_of_Last_ES_Stay_(Beta)', 'Date_of_First_ES_Stay_(Beta)', \n 'Prevention_|_Most_Recent_Enrollment', 'PSH_|_Most_Recent_Enrollment', \n 'Transitional_Housing_|_Most_Recent_Enrollment', 'Coordinated_Entry_|_Most_Recent_Enrollment', \n 'Street_Outreach_|_Most_Recent_Enrollment', 'RRH_|_Most_Recent_Enrollment', \n 'SOAR_Eligibility_Determination_(Most_Recent)', 'Date_of_First_Contact_(Beta)',\n 'Date_of_Last_Contact_(Beta)', '4.13_Engagement_Date', '4.11_Domestic_Violence_-_When_it_Occurred',\n '3.917_Homeless_Start_Date']\n X = X.drop(columns=timestamp_columns)\n \n # return the wrangled dataframe\n return X\n\n",
"_____no_output_____"
],
[
"train = wrangle(train)\nval = wrangle(val)",
"_____no_output_____"
],
[
"train.columns",
"_____no_output_____"
],
[
"# Assign to X, y to avoid data leakage\nfeatures = ['3.15_Relationship_to_HoH', 'CaseMembers',\n '3.2_Social_Security_Quality', '3.3_Birthdate_Quality',\n 'Age_at_Enrollment', '3.4_Race', '3.5_Ethnicity', '3.6_Gender',\n '3.7_Veteran_Status', '3.8_Disabling_Condition_at_Entry',\n '3.917_Living_Situation', 'Length_of_Time_Homeless_(3.917_Approximate_Start)',\n '3.917_Times_Homeless_Last_3_Years', '3.917_Total_Months_Homeless_Last_3_Years', \n 'V5_Last_Permanent_Address', 'V5_State', 'V5_Zip', 'Municipality_(City_or_County)',\n '4.1_Housing_Status', '4.4_Covered_by_Health_Insurance', '4.11_Domestic_Violence',\n '4.11_Domestic_Violence_-_Currently_Fleeing_DV?', 'Household_Type', \n 'R4_Last_Grade_Completed', 'R5_School_Status',\n 'R6_Employed_Status', 'R6_Why_Not_Employed', 'R6_Type_of_Employment',\n 'R6_Looking_for_Work', '4.2_Income_Total_at_Entry',\n '4.3_Non-Cash_Benefit_Count', 'Barrier_Count_at_Entry',\n 'Chronic_Homeless_Status', 'Under_25_Years_Old',\n '4.10_Alcohol_Abuse_(Substance_Abuse)', '4.07_Chronic_Health_Condition',\n '4.06_Developmental_Disability', '4.10_Drug_Abuse_(Substance_Abuse)',\n '4.08_HIV/AIDS', '4.09_Mental_Health_Problem',\n '4.05_Physical_Disability'\n ]\ntarget = 'perm_leaver'\nX_train = train[features]\ny_train = train[target]\nX_val = val[features]\ny_val = val[target]",
"_____no_output_____"
],
[
"# Arrange data into X features matrix and y target vector\ntarget = 'perm_leaver'\nX_train = train.drop(columns=target)\ny_train = train[target]\nX_val = val.drop(columns=target)\ny_val = val[target]\n",
"_____no_output_____"
],
[
"from scipy.stats import randint, uniform\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparam_distributions = { \n 'n_estimators': randint(5, 500, 5), \n 'max_depth': [10, 15, 20, 50, 'None'], \n 'max_features': [.5, 1, 1.5, 2, 2.5, 3, 'sqrt', None],\n \n}\n\nsearch = RandomizedSearchCV(\n RandomForestRegressor(random_state=42), \n param_distributions=param_distributions, \n n_iter=20, \n cv=5, \n scoring='neg_mean_absolute_error', \n verbose=10, \n return_train_score=True, \n n_jobs=-1, \n random_state=42\n)\n\nsearch.fit(X_train, y_train);",
"Fitting 5 folds for each of 20 candidates, totalling 100 fits\n"
],
[
"import category_encoders as ce\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import GradientBoostingClassifier\n\n# Make pipeline!\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=100, n_jobs=-1, max_features=None, random_state=42\n )\n)\n\n# Fit on train, score on val\npipeline.fit(X_train, y_train)\ny_pred = pipeline.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred))",
"Validation Accuracy 0.744\n"
],
[
"# Get feature importances\nrf = pipeline.named_steps['randomforestclassifier']\nimportances = pd.Series(rf.feature_importances_, X_train.columns)\n\n# Plot feature importances\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nn = 20\nplt.figure(figsize=(10,n/2))\nplt.title(f'Top {n} features')\nimportances.sort_values()[-n:].plot.barh(color='grey');",
"_____no_output_____"
],
[
"# Make pipeline!\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n xgb.XGBClassifier(n_estimators=110, n_jobs=-1, num_parallel_tree=200,\n random_state=42\n )\n)\n# Fit on Train\npipeline.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Score on val\ny_pred = pipeline.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred))",
"_____no_output_____"
],
[
"# cross validation \n\nk = 3\nscores = cross_val_score(pipeline, X_train, y_train, cv=k, \n scoring='accuracy')\nprint(f'MAE for {k} folds:', -scores)",
"_____no_output_____"
],
[
"-scores.mean()",
"_____no_output_____"
],
[
"# get and plot feature importances\n\n# Linear models have coefficients whereas decision trees have \"Feature Importances\"\nimport matplotlib.pyplot as plt\n\nmodel = pipeline.named_steps['xgbclassifier']\nencoder = pipeline.named_steps['ordinalencoder']\nencoded_columns = encoder.transform(X_val).columns\nimportances = pd.Series(model.feature_importances_, encoded_columns)\nplt.figure(figsize=(10,30))\nimportances.sort_values().plot.barh(color='grey')",
"_____no_output_____"
],
[
"df['4.1_Housing_Status'].value_counts()",
"_____no_output_____"
],
[
"X_train.shape",
"_____no_output_____"
],
[
"X_train.columns",
"_____no_output_____"
],
[
"X_train.Days_Enrolled_in_Project.value_counts()",
"_____no_output_____"
],
[
"column = 'Days_Enrolled_in_Project'\n\n# Fit without column\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=250, random_state=42, n_jobs=-1)\n)\npipeline.fit(X_train.drop(columns=column), y_train)\nscore_without = pipeline.score(X_val.drop(columns=column), y_val)\nprint(f'Validation Accuracy without {column}: {score_without}')\n\n# Fit with column\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=250, random_state=42, n_jobs=-1)\n)\npipeline.fit(X_train, y_train)\nscore_with = pipeline.score(X_val, y_val)\nprint(f'Validation Accuracy with {column}: {score_with}')\n\n# Compare the error with & without column\nprint(f'Drop-Column Importance for {column}: {score_with - score_without}')",
"_____no_output_____"
],
[
"column = 'Days_Enrolled_in_Project'\n\n# Fit without column\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=250, max_depth=7, random_state=42, n_jobs=-1)\n)\npipeline.fit(X_train.drop(columns=column), y_train)\nscore_without = pipeline.score(X_val.drop(columns=column), y_val)\nprint(f'Validation Accuracy without {column}: {score_without}')\n\n# Fit with column\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=250, max_depth=7, random_state=42, n_jobs=-1)\n)\npipeline.fit(X_train, y_train)\nscore_with = pipeline.score(X_val, y_val)\nprint(f'Validation Accuracy with {column}: {score_with}')\n\n# Compare the error with & without column\nprint(f'Drop-Column Importance for {column}: {score_with - score_without}')",
"_____no_output_____"
],
[
"# Fit with all the data\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='most_frequent'), \n RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)\n)\npipeline.fit(X_train, y_train)\nscore_with = pipeline.score(X_val, y_val)\nprint(f'Validation Accuracy with {column}: {score_with}')",
"_____no_output_____"
],
[
"# Before: Sequence of features to be permuted\nfeature = 'Days_Enrolled_in_Project'\nX_val[feature].head()",
"_____no_output_____"
],
[
"# Before: Distribution of quantity\nX_val[feature].value_counts()",
"_____no_output_____"
],
[
"# Permute the dataset\nX_val_permuted = X_val.copy()\nX_val_permuted[feature] = np.random.permutation(X_val[feature])",
"_____no_output_____"
],
[
"# After: Sequence of features to be permuted\nX_val_permuted[feature].head()",
"_____no_output_____"
],
[
"# Distribution hasn't changed!\nX_val_permuted[feature].value_counts()",
"_____no_output_____"
],
[
"# Get the permutation importance\nscore_permuted = pipeline.score(X_val_permuted, y_val)\n\nprint(f'Validation Accuracy with {column} not permuted: {score_with}')\nprint(f'Validation Accuracy with {column} permuted: {score_permuted}')\nprint(f'Permutation Importance for {column}: {score_with - score_permuted}')",
"_____no_output_____"
],
[
"pipeline = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy='most_frequent')\n)\n\nX_train_transformed = pipeline.fit_transform(X_train)\nX_val_transformed = pipeline.transform(X_val)\n\nmodel = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)\nmodel.fit(X_train_transformed, y_train)",
"_____no_output_____"
],
[
"pip install eli5",
"_____no_output_____"
],
[
"import eli5\nfrom eli5.sklearn import PermutationImportance\n\npermuter = PermutationImportance(\n model,\n scoring='accuracy',\n n_iter=5,\n random_state=42\n)\npermuter.fit(X_val_transformed, y_val)",
"_____no_output_____"
],
[
"permuter.feature_importances_",
"_____no_output_____"
],
[
"eli5.show_weights(\n permuter,\n top=None,\n feature_names=X_val.columns.tolist()\n)",
"_____no_output_____"
],
[
"print('Shape before removing features:', X_train.shape)",
"_____no_output_____"
],
[
"minimum_importance = 0 \nmask = permuter.feature_importances_ > minimum_importance\nfeatures = X_train.columns[mask]\nX_train = X_train[features]",
"_____no_output_____"
],
[
"print('Shape after removing features:', X_train.shape)",
"_____no_output_____"
],
[
"X_val = X_val[features]\n\npipeline = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy='most_frequent'),\n RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)\n)\n\n# Fit on train, score on val\npipeline.fit(X_train, y_train)\nprint('Validation Accuracy:', pipeline.score(X_val, y_val))",
"_____no_output_____"
],
[
"from xgboost import XGBClassifier\n\npipeline = make_pipeline(\n ce.OrdinalEncoder(),\n XGBClassifier(n_estimators=100, random_state=42, n_jobs=-1)\n)\n\n# Fit on train, score on val\npipeline.fit(X_train, y_train)\nprint('Validation Accuracy:', pipeline.score(X_val, y_val))",
"_____no_output_____"
],
[
"encoder = ce.OrdinalEncoder()\nX_train_encoded = encoder.fit_transform(X_train)\nX_val_encoded = encoder.transform(X_val)\n\nmodel = XGBClassifier(n_estimators=1000, # <= 1000 trees, early stopping depency\n max_depth=7, # try deeper trees with high cardinality data\n learning_rate=0.1, # try higher learning rate\n random_state=42,\n num_class=1,\n n_jobs=-1)\n\neval_set = [(X_train_encoded, y_train),\n (X_val_encoded, y_val)]\n\n# Fit on train, score on val\nmodel.fit(X_train_encoded, y_train,\n eval_metric='auc',\n eval_set=eval_set, \n early_stopping_rounds=25)",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_absolute_error as mae\nresults = model.evals_result()\ntrain_error = results['validation_0']['auc']\nval_error = results['validation_1']['auc']\n\niterations = range(1, len(train_error) + 1)\n\nplt.figure(figsize=(10,7))\nplt.plot(iterations, train_error, label='Train')\nplt.plot(iterations, val_error, label='Validation')\nplt.title('XGBoost Validation Curve')\nplt.ylabel('Classification Error')\nplt.xlabel('Model Complexity (n_estimators)')\nplt.legend();",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba39cdf82b83a66d13378e6e906e3980456627a
| 1,055 |
ipynb
|
Jupyter Notebook
|
notebooks/03_kk_conflation_analysis/03_kk_azure_gcp.ipynb.ipynb
|
kabirkhan/cloud_compete_graph
|
95648644e7dd960544a7998950ea37ee76feebef
|
[
"MIT"
] | 1 |
2021-05-09T05:18:06.000Z
|
2021-05-09T05:18:06.000Z
|
notebooks/03_kk_conflation_analysis/03_kk_azure_gcp.ipynb.ipynb
|
kabirkhan/cloud_compete_graph
|
95648644e7dd960544a7998950ea37ee76feebef
|
[
"MIT"
] | null | null | null |
notebooks/03_kk_conflation_analysis/03_kk_azure_gcp.ipynb.ipynb
|
kabirkhan/cloud_compete_graph
|
95648644e7dd960544a7998950ea37ee76feebef
|
[
"MIT"
] | null | null | null | 17.583333 | 97 | 0.519431 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"base_path = '../../data'",
"_____no_output_____"
],
[
"azure_aws = pd.read_csv(f'{base_path}/processed/azure_aws_dedupe/data_matching_output.csv')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cba39f6dc0d4a8258775fe8fd5c5cd9a90d3c054
| 38,806 |
ipynb
|
Jupyter Notebook
|
lab03/Radiation balance of the Earth.ipynb
|
stefanik36/Physics-Simulations
|
3407b82e578493b802f42b3862bf53f7574a338b
|
[
"MIT"
] | null | null | null |
lab03/Radiation balance of the Earth.ipynb
|
stefanik36/Physics-Simulations
|
3407b82e578493b802f42b3862bf53f7574a338b
|
[
"MIT"
] | null | null | null |
lab03/Radiation balance of the Earth.ipynb
|
stefanik36/Physics-Simulations
|
3407b82e578493b802f42b3862bf53f7574a338b
|
[
"MIT"
] | null | null | null | 111.511494 | 15,196 | 0.860769 |
[
[
[
"import numpy as np\nfrom scipy.optimize import fsolve\n\n% matplotlib inline\nimport time\nimport pylab as pl\nfrom IPython import display\n\n# PSl – Power of solar radiation arriving to the Earth (short wave radiation)\n# Pz – Power of radiation emitted from Earth (long wave radiation)\n# A – mean albedo of the Earth surface\n# S – solar constant\n# PowZ – area of the Earth\n# sbc -Stefan-Boltzmann constant\n\n# PSl = S * (PowZ/4) *(1 - A)\n# Pz = sbc * (T**4) * PowZ\n# Pz = PSl\n\n# sbc * (T**4) * PowZ = S * (PowZ/4) *(1 - A)\n# (T**4) = (S * (PowZ/4) * (1 - A))/(sbc*PowZ) = (S * (1 - A))/(4 * sbc)\n",
"_____no_output_____"
],
[
"# Diagram methods\n\n\ndef doPlot(x, y, col):\n pl.plot(x, y, col, markersize=3)\n display.clear_output(wait=True)\n display.display(pl.gcf())\n time.sleep(0.1)\n\n\ndef setRanges():\n pl.xlim(S_range_left * 0.95, S_range_right * 1.05)\n pl.ylim(-80, 40)\n pl.xlabel('Fraction of solar constant value')\n pl.ylabel('Mean temperature in Celsius degrees')\n pl.title('Glacial-interglacial transition')\n\n\ndef changeColor(i, val):\n if i >= val:\n return 'b+'\n else:\n return 'ro'\n\n\n# Computation methods\n\ndef k_to_c(k):\n return k - 273.15\n\n# No atmosphere methods\n\n\ndef withoutAtmosphere(S, A, sbc):\n return pow((S * (1 - A)) / (4 * sbc), 0.25)\n\n# Taking atmosphere methods\n\n\ndef withAtmosphereEquations(p):\n Ts, Ta = p\n e1 = (-sw_ta) * (1 - sw_as) * S / 4 + c * (Ts - Ta) + sbc * (Ts ** 4) * (1 - lw_aa) - sbc * (Ta ** 4)\n e2 = -(1 - sw_aa - sw_ta + sw_as * sw_ta) * S / 4 - c * (Ts - Ta) - sbc * (Ts ** 4) * (\n 1 - lw_ta - lw_aa) + 2 * sbc * (Ta ** 4)\n return e1, e2\n\n\ndef withAtmosphere():\n return fsolve(withAtmosphereEquations, (0.0, 0.0))\n\n\ndef changeAs(t):\n if (t < Tc):\n return sw_as_init_r\n else:\n return sw_as_init\n",
"_____no_output_____"
],
[
"# Variable initiation\n\n# PSl = 0.0\n# Pz = 0.0\nA = 0.3\nS_init = 1366.0 # W/m 2\nS = S_init # W/m 2\n# PowZ = 0.0\nsbc = 5.67 * pow(10.0, -8) # W/m^2*K^4\n\n# Short-wave radiation\nsw_as_init = 0.19\nsw_as_init_r = 0.65\nsw_as = sw_as_init\nsw_ta = 0.53\nsw_aa = 0.30\n\n# Long-wave radiation\nlw_ta = 0.06\nlw_aa = 0.31\n\nc = 2.7 # Wm^-2 K^-1\n\n# S in range 0.8 to 1.2 S\nS_range_left = 0.4\nS_range_right = 1.4\nS_range_step = 0.01\n\nTc = -10 # C degrees \n\n# No atmosphere \nT = withoutAtmosphere(S, A, sbc)\nprint(\"No atmosphere in Celsius degrees: \" + str(k_to_c(T)) + \".\")\n\n# Taking atmosphere \nTs, Ta = withAtmosphere()\nprint(\"Mean temperature of the atmosphere in Celsius degrees \" + str(k_to_c(Ta)) + \".\")\nprint(\"Mean surface temperature in Celsius degrees \" + str(k_to_c(Ts)) + \".\")\n\nsetRanges()\n\narr = list(np.arange(S_range_left, S_range_right, S_range_step))\niterator = list(arr)\niterator.reverse()\niterator.extend(arr)\n\nsp1_val = None\nsp2_val = None\nsp1_frac = None\nsp2_frac = None\nsp1_temp = None\nsp2_temp = None\n\n# Main loop\nfor i in range(len(iterator)):\n S = iterator[i] * S_init\n Ts, Ta = withAtmosphere()\n TaC = k_to_c(Ta)\n TsC = k_to_c(Ts)\n sw_as = changeAs(TsC)\n\n if (sw_as != sw_as_init) and (sp1_val is None):\n sp1_val = S\n sp1_frac = iterator[i]\n sp1_temp = TsC\n\n if sw_as != sw_as_init:\n sp2_val = S\n sp2_frac = iterator[i]\n sp2_temp = TsC\n\n col = changeColor(i, len(iterator) / 2)\n doPlot(iterator[i], TsC, col)\n print(\"S: \" + str(S) + \" TaC: \" + str(TaC) + \" TsC: \" + str(TsC) + \" Ta: \" + str(Ta) + \" Ts: \" + str(Ts))\n\nprint(\"sp1_val: \" + str(sp1_val) + \" W/m^2 sp1_frac: \" + str(sp1_frac) + \" temp1: \" + str(sp1_temp))\nprint(\"sp2_val: \" + str(sp2_val) + \" W/m^2 sp2_frac: \" + str(sp2_frac) + \" temp2: \" + str(sp2_temp))\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cba3b26c0a07d79058199edc4608976089b55df2
| 20,182 |
ipynb
|
Jupyter Notebook
|
scratch_work/scratch.ipynb
|
tolga-sen/soccerprediction
|
418e9b684da0d6070fb9bfb8cdf2ac90188c7b77
|
[
"MIT"
] | null | null | null |
scratch_work/scratch.ipynb
|
tolga-sen/soccerprediction
|
418e9b684da0d6070fb9bfb8cdf2ac90188c7b77
|
[
"MIT"
] | null | null | null |
scratch_work/scratch.ipynb
|
tolga-sen/soccerprediction
|
418e9b684da0d6070fb9bfb8cdf2ac90188c7b77
|
[
"MIT"
] | null | null | null | 42.39916 | 1,822 | 0.592657 |
[
[
[
"from selenium import webdriver\nimport time\nimport numpy as np\n\nDRIVER = webdriver.Chrome()\n\ndef get_stats_from_window(driver, handle_number):\n driver.switch_to.window(handle_number)\n new_link = driver.current_url\n statistics1=new_link[:-7]+\"statistics;1\"\n time.sleep(2)\n\n try:\n driver.get(statistics1)\n time.sleep(2)\n login_form=driver.find_element_by_xpath('//div[@id=\"tab-statistics-1-statistic\"]')\n # if login_form:\n statistics1=login_form.text\n# print(statistics1)\n with open('half.txt', 'a') as f:\n f.write('-----')\n f.write(statistics1)\n f.write('-----')\n\n new_link = driver.current_url\n statistics2=new_link[:-7]+\"statistics;0\"\n# print(statistics2)\n driver.get(statistics2)\n time.sleep(2)\n login_form=driver.find_element_by_xpath('//div[@id=\"tab-statistics-0-statistic\"]')\n statistics2=login_form.text\n# print(statistics2)\n with open('end.txt', 'a') as f:\n f.write('-----')\n f.write(statistics2)\n f.write('-----')\n\n new_link = driver.current_url\n goals=new_link[:-12]+\"summary\"\n# print(goals)\n time.sleep(2)\n driver.get(goals)\n time.sleep(2)\n login_form=driver.find_element_by_xpath('//div[@id=\"summary-content\"]')\n goals=login_form.text\n# print(goals)\n with open('goal.txt', 'a') as f:\n f.write('-----')\n f.write(goals)\n f.write('-----')\n\n new_link = driver.current_url\n info=new_link[:-12]+\"summary\"\n# print(info)\n time.sleep(3)\n driver.get(info)\n time.sleep(3)\n login_form=driver.find_element_by_xpath('//td[@id=\"flashscore_column\"]')\n info=login_form.text\n# print(info)\n with open('info.txt', 'a') as f:\n f.write('-----')\n f.write(info)\n f.write('-----')\n\n except:\n print(\"No Statistics for this game!!!\")",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
]
],
[
[
"# DRIVER.get(\"https://www.soccerstand.com/match/rsmTAHhE/#match-summary\")\nDRIVER.get(\"https://www.soccerstand.com/match/8jTixcnk/#match-summary\")",
"_____no_output_____"
],
[
"game_info1 = DRIVER.find_elements_by_xpath('//td[@class=\"tname-home logo-enable\"]')\ngame_info2 = DRIVER.find_elements_by_xpath('//td[@class=\"tname-away logo-enable\"]')\n# game_info = '-'.join([i.text for i in game_info])\ngame_info1 = '-'.join([i.text for i in game_info1])\ngame_info2 = '-'.join([i.text for i in game_info2])\ngame_info = game_info1+'-'+game_info2\n#print(f'TESTING!!!:{game_info3}\\n\\n')\nprint(f'TESTING!!!:{game_info}\\n\\n')",
"TESTING!!!:Amiens-Lille\n\n\n"
],
[
"game_info3",
"_____no_output_____"
],
[
"game_info3 = '-'.join(game_info.split('\\n')[0].split()[::2])",
"_____no_output_____"
],
[
"game_info3",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
]
],
[
[
"DRIVER.get(\"https://www.soccerstand.com/team/amiens-sc/lKkBAsxF/results/\")\n\n# LOCATION = ELEMENT.location\n\ntime.sleep(2)\naction = webdriver.common.action_chains.ActionChains(DRIVER)\n# ELEMENT = DRIVER.find_element_by_class_name('basketball')\n# ELEMENT = DRIVER.find_element_by_class_name('padr')\nELEMENTS = DRIVER.find_elements_by_class_name('padr')\nELEMENTS2 = DRIVER.find_elements_by_class_name('padl')\n# ELEMENT = DRIVER.find_element_by_xpath('//td[@title=\"Click for match detail!\"]')\n# action.move_to_element(ELEMENT)\nprint('Done')",
"Done\n"
],
[
"for home,away in zip(ELEMENTS, ELEMENTS2):\n print(home.text, away.text)",
"Toulouse Amiens\nAmiens Nantes\nAmiens Lille \nNice Amiens \nAmiens (Fra) Leganes (Esp)\nMetz (Fra) Amiens (Fra)\nHull (Eng) Amiens (Fra)\nValenciennes (Fra) Amiens (Fra) \nBoulogne (Fra) Amiens (Fra)\nAmiens Guingamp\nMonaco Amiens\nAmiens Toulouse\nMontpellier Amiens\nAmiens Strasbourg\nNantes Amiens\nDijon Amiens \nAmiens St Etienne\nAmiens Bordeaux\nAngers Amiens\nAmiens Nimes\nReims Amiens\nAmiens Nice\nMarseille Amiens\nAmiens Caen\nRennes Amiens\nAmiens Lyon\nAmiens Lyon \nLille Amiens\nAmiens Paris SG\nAmiens Angers\nAmiens Valenciennes\nBordeaux Amiens\nAmiens Lyon \nGuingamp Amiens\nAmiens Monaco\nNimes Amiens\nAmiens Marseille\nToulouse Amiens\nNice Amiens\nMetz Amiens \nAmiens Nantes\nParis SG Amiens\nAmiens Dijon\n"
]
],
[
[
"### Observation: it actually matter if the xpath is on the screen! otherwise the automated software wont be able to click it.",
"_____no_output_____"
]
],
[
[
"# DRIVER.execute_script(\"arguments[0].scrollIntoView();\", ELEMENTS[0])\n# DRIVER.execute_script(\"$(arguments[0]).click();\", ELEMENTS[0])\n\n# print(f'There are {len(DRIVER.window_handles)} windows:')\n\n# start_window = DRIVER.window_handles[0] \n# current_window = DRIVER.window_handles[-1]\n# print(f'Starting window (main page): {start_window}')\n# print(f'Current window: {current_window}')\n\n# # get_stats_from_window(DRIVER, current_window)\n\n# DRIVER.switch_to.window(start_window)\n# DRIVER.close() #closes the current window\n\n\n# print(f'There are {len(DRIVER.window_handles)} windows:')\n\n# start_window = DRIVER.window_handles[0] \n# current_window = DRIVER.window_handles[-1]\n# print(f'Starting window (main page): {start_window}')\n# print(f'Current window: {current_window}')",
"_____no_output_____"
],
[
"for elem in ELEMENTS[:5]:\n \n time.sleep(3)\n# DRIVER.execute_script(\"arguments[0].scrollIntoView(true);\", e)\n print(elem, elem.text)\n# action.move_to_element(e).click().perform()\n# action.click(on_element=e)\n# action.perform()\n# get_stats_from_window(DRIVER, handle_number)\n# e.click()\n\n DRIVER.execute_script(\"arguments[0].scrollIntoView();\", elem)\n DRIVER.execute_script(\"$(arguments[0]).click();\", elem)\n \n start_window = DRIVER.window_handles[0]\n\n current_window = DRIVER.window_handles[-1]\n get_stats_from_window(DRIVER, current_window)\n print(f'Successfully wrote data....')\n DRIVER.close() #closes the current window\n DRIVER.switch_to.window(start_window)\n \n assert len(DRIVER.window_handles) == 1\n",
"_____no_output_____"
],
[
"# for i in ELEMENTS:\n# print(i.location_once_scrolled_into_view, i.text)",
"_____no_output_____"
],
[
"# action.move_to_element_with_offset(ELEMENT, 0, 0)\naction.move_to_element(ELEMENT)\naction.click()\naction.perform()",
"_____no_output_____"
],
[
"DRIVER.close()",
"_____no_output_____"
],
[
"HANDLES = DRIVER.window_handles\nprint(HANDLES)",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"pd.read_csv('info.txt', engine='python', sep='-----')",
"_____no_output_____"
],
[
"pd.read_csv('half.txt', header=None).head()",
"_____no_output_____"
],
[
"# pd.read_csv('goal.txt')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba3de82b3a51acbfff3b43f68bab41956398174
| 100,762 |
ipynb
|
Jupyter Notebook
|
notebooks/the-fc_parameters-extraction-dictionary.ipynb
|
cjen07/tsfresh
|
e6f5d3eb0cdc8c307a8781a839b5c05da29e8f06
|
[
"MIT"
] | 51 |
2019-02-01T19:43:37.000Z
|
2022-03-16T09:07:03.000Z
|
notebooks/the-fc_parameters-extraction-dictionary.ipynb
|
cjen07/tsfresh
|
e6f5d3eb0cdc8c307a8781a839b5c05da29e8f06
|
[
"MIT"
] | 2 |
2019-02-23T18:54:22.000Z
|
2019-11-09T01:30:32.000Z
|
notebooks/the-fc_parameters-extraction-dictionary.ipynb
|
cjen07/tsfresh
|
e6f5d3eb0cdc8c307a8781a839b5c05da29e8f06
|
[
"MIT"
] | 35 |
2019-02-08T02:00:31.000Z
|
2022-03-01T23:17:00.000Z
| 39.96906 | 267 | 0.380491 |
[
[
[
"from tsfresh.feature_extraction import extract_features\nfrom tsfresh.feature_extraction.settings import ComprehensiveFCParameters, MinimalFCParameters, EfficientFCParameters\nfrom tsfresh.feature_extraction.settings import from_columns\n\nimport numpy as np\nimport pandas as pd",
"/Users/mchrist/Documents/Research/tsfresh/venv/lib/python2.7/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n from pandas.core import datetools\n"
]
],
[
[
"This notebooks illustrates the `\"fc_parameters\"` or `\"kind_to_fc_parameters\"` dictionaries.\n\nFor a detailed explanation, see also http://tsfresh.readthedocs.io/en/latest/text/feature_extraction_settings.html",
"_____no_output_____"
],
[
"## Construct a time series container",
"_____no_output_____"
],
[
"We construct the time series container that includes two sensor time series, _\"temperature\"_ and _\"pressure\"_, for two devices _\"a\"_ and _\"b\"_",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\"id\": [\"a\", \"a\", \"b\", \"b\"], \"temperature\": [1,2,3,1], \"pressure\": [-1, 2, -1, 7]})\ndf",
"_____no_output_____"
]
],
[
[
"## The default_fc_parameters",
"_____no_output_____"
],
[
"Which features are calculated by tsfresh is controlled by a dictionary that contains a mapping from feature calculator names to their parameters. \nThis dictionary is called `fc_parameters`. It maps feature calculator names (=keys) to parameters (=values). As keys, always the same names as in the tsfresh.feature_extraction.feature_calculators module are used.\n\nIn the following we load an exemplary dictionary",
"_____no_output_____"
]
],
[
[
"settings_minimal = MinimalFCParameters() # only a few basic features\nsettings_minimal",
"_____no_output_____"
]
],
[
[
"This dictionary can passed to the extract method, resulting in a few basic time series beeing calculated:",
"_____no_output_____"
]
],
[
[
"X_tsfresh = extract_features(df, column_id=\"id\", default_fc_parameters = settings_minimal)\nX_tsfresh.head()",
"Feature Extraction: 100%|██████████| 4/4 [00:00<00:00, 16336.14it/s]\n"
]
],
[
[
"By using the settings_minimal as value of the default_fc_parameters parameter, those settings are used for all type of time series. In this case, the `settings_minimal` dictionary is used for both _\"temperature\"_ and _\"pressure\"_ time series.",
"_____no_output_____"
],
[
"Now, lets say we want to remove the length feature and prevent it from beeing calculated. We just delete it from the dictionary.",
"_____no_output_____"
]
],
[
[
"del settings_minimal[\"length\"]\nsettings_minimal",
"_____no_output_____"
]
],
[
[
"Now, if we extract features for this reduced dictionary, the length feature will not be calculated",
"_____no_output_____"
]
],
[
[
"X_tsfresh = extract_features(df, column_id=\"id\", default_fc_parameters = settings_minimal)\nX_tsfresh.head()",
"Feature Extraction: 100%|██████████| 4/4 [00:00<00:00, 1171.27it/s]\n"
]
],
[
[
"## The kind_to_fc_parameters",
"_____no_output_____"
],
[
"now, lets say we do not want to calculate the same features for both type of time series. Instead there should be different sets of features for each kind.\n\nTo do that, we can use the `kind_to_fc_parameters` parameter, which lets us finely specifiy which `fc_parameters` we want to use for which kind of time series:",
"_____no_output_____"
]
],
[
[
"fc_parameters_pressure = {\"length\": None, \n \"sum_values\": None}\n\nfc_parameters_temperature = {\"maximum\": None, \n \"minimum\": None}\n\nkind_to_fc_parameters = {\n \"temperature\": fc_parameters_temperature,\n \"pressure\": fc_parameters_pressure\n}\n\nprint(kind_to_fc_parameters)",
"{'pressure': {'length': None, 'sum_values': None}, 'temperature': {'minimum': None, 'maximum': None}}\n"
]
],
[
[
"So, in this case, for sensor _\"pressure\"_ both _\"max\"_ and _\"min\"_ are calculated. For the _\"temperature\"_ signal, the length and sum_values features are extracted instead.",
"_____no_output_____"
]
],
[
[
"X_tsfresh = extract_features(df, column_id=\"id\", kind_to_fc_parameters = kind_to_fc_parameters)\nX_tsfresh.head()",
"Feature Extraction: 100%|██████████| 4/4 [00:00<00:00, 1473.37it/s]\n"
]
],
[
[
"So, lets say we lost the kind_to_fc_parameters dictionary. Or we apply a feature selection algorithm to drop \nirrelevant feature columns, so our extraction settings contain irrelevant features. \n\nIn both cases, we can use the provided \"from_columns\" method to infer the creating dictionary from \nthe dataframe containing the features",
"_____no_output_____"
]
],
[
[
"recovered_settings = from_columns(X_tsfresh)\nrecovered_settings",
"_____no_output_____"
]
],
[
[
"Lets drop a column to show that the inferred settings dictionary really changes",
"_____no_output_____"
]
],
[
[
"X_tsfresh.iloc[:, 1:]",
"_____no_output_____"
],
[
"recovered_settings = from_columns(X_tsfresh.iloc[:, 1:])\nrecovered_settings",
"_____no_output_____"
]
],
[
[
"## More complex dictionaries",
"_____no_output_____"
],
[
"We provide custom fc_parameters dictionaries with greater sets of features.\n\nThe `EfficientFCParameters` contain features and parameters that should be calculated quite fastly:",
"_____no_output_____"
]
],
[
[
"settings_efficient = EfficientFCParameters()\nsettings_efficient",
"_____no_output_____"
]
],
[
[
"The `ComprehensiveFCParameters` are the biggest set of features. It will take the longest to calculate",
"_____no_output_____"
]
],
[
[
"settings_comprehensive = ComprehensiveFCParameters()\nsettings_comprehensive",
"_____no_output_____"
]
],
[
[
"You see those parameters as values in the fc_paramter dictionary? Those are the parameters of the feature extraction methods.\n\nIn detail, the value in a fc_parameters dicitonary can contain a list of dictionaries. Every dictionary in that list is one feature.\n\nSo, for example",
"_____no_output_____"
]
],
[
[
"settings_comprehensive['large_standard_deviation']",
"_____no_output_____"
]
],
[
[
"would trigger the calculation of 20 different 'large_standard_deviation' features, one for r=0.05, for n=0.10 up to r=0.95. Lets just take them and extract some features",
"_____no_output_____"
]
],
[
[
"settings_value_count = {'large_standard_deviation': settings_comprehensive['large_standard_deviation']}\nsettings_value_count",
"_____no_output_____"
],
[
"X_tsfresh = extract_features(df, column_id=\"id\", default_fc_parameters=settings_value_count)\nX_tsfresh.head()",
"Feature Extraction: 100%|██████████| 4/4 [00:00<00:00, 772.36it/s]\n"
]
],
[
[
"The nice thing is, we actually contain the parameters in the feature name, so it is possible to reconstruct \nhow the feature was calculated.",
"_____no_output_____"
]
],
[
[
"from_columns(X_tsfresh)",
"_____no_output_____"
]
],
[
[
"This means that you should never change a column name. Otherwise the information how it was calculated can get lost.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba3e61c6d7e97ed13fa88a1f759060c4d1714cf
| 533,556 |
ipynb
|
Jupyter Notebook
|
doc/documentation_notebooks/jet_model_phys_EC/Jet_example_phys_EC.ipynb
|
andreatramacere/jetset
|
4b7859622db9713b6ee243e2c12ec81321b372bf
|
[
"BSD-3-Clause"
] | 16 |
2019-02-11T06:58:43.000Z
|
2021-12-28T13:00:35.000Z
|
doc/documentation_notebooks/jet_model_phys_EC/Jet_example_phys_EC.ipynb
|
andreatramacere/jetset
|
4b7859622db9713b6ee243e2c12ec81321b372bf
|
[
"BSD-3-Clause"
] | 14 |
2019-04-14T14:49:55.000Z
|
2021-12-27T04:18:24.000Z
|
doc/documentation_notebooks/jet_model_phys_EC/Jet_example_phys_EC.ipynb
|
andreatramacere/jetset
|
4b7859622db9713b6ee243e2c12ec81321b372bf
|
[
"BSD-3-Clause"
] | 10 |
2019-02-25T14:53:28.000Z
|
2022-03-02T08:49:19.000Z
| 435.200653 | 113,584 | 0.923804 |
[
[
[
".. _jet_physical_guide_EC:",
"_____no_output_____"
]
],
[
[
"## External Compton\n",
"_____no_output_____"
]
],
[
[
"\nThe external Compton implementation gives you the possibility to use a double approach\n \n* transformation of the external fields to the blob rest frame Dermer and Schlickeiser (2002) [Dermer2002]_\n\n* transformation of the electron emitting distribution from the blob restframe to\n disk/BH restframe Dermer(1995)[Dermer95]_ and Georganopoulos, Kirk, and Mastichiadis (2001) [GKM01]_\n\nThe implemented external radiative fields are \n \n* Broad Line Region radiative field using the approach of Donea & Protheroe (2003)[Donea2003]_\n\n* Dusty torus implemented as a uniform BB field within `R_DT`\n\n* accretion disk (mono-energetic, single-temperature BB or a multi-temperature BB)\n\n* Cosmic Microwave Background (CMB)\n\nPlease read :ref:`jet_physical_guide_SSC` if you skipped it.",
"_____no_output_____"
]
],
[
[
"\n",
"_____no_output_____"
],
[
"### Broad Line Region\n",
"_____no_output_____"
]
],
[
[
".. image::jetset_EC_scheme.png\n :width: 400\n :alt: EC scheme\n",
"_____no_output_____"
]
],
[
[
"import jetset\nprint('tested on jetset',jetset.__version__)",
"tested on jetset 1.2.0rc4\n"
],
[
"from jetset.jet_model import Jet\nmy_jet=Jet(name='EC_example',electron_distribution='bkn',beaming_expr='bulk_theta')\nmy_jet.add_EC_component(['EC_BLR','EC_Disk'],disk_type='BB')\n",
"_____no_output_____"
]
],
[
[
"The `show_model` method provides, among other information, information concerning the accretion disk, in this case we use a mono temperature black body `BB` ",
"_____no_output_____"
]
],
[
[
"my_jet.show_model()",
"\n--------------------------------------------------------------------------------\njet model description\n--------------------------------------------------------------------------------\nname: EC_example \n\nelectrons distribution:\n type: bkn \n gamma energy grid size: 201\n gmin grid : 2.000000e+00\n gmax grid : 1.000000e+06\n normalization True\n log-values False\n\naccretion disk:\n disk Type: BB\n L disk: 1.000000e+45 (erg/s)\n T disk: 1.000000e+05 (K)\n nu peak disk: 8.171810e+15 (Hz)\n\nradiative fields:\n seed photons grid size: 100\n IC emission grid size: 100\n source emissivity lower bound : 1.000000e-120\n spectral components:\n name:Sum, state: on\n name:Sync, state: self-abs\n name:SSC, state: on\n name:EC_BLR, state: on\n name:Disk, state: on\n name:EC_Disk, state: on\nexternal fields transformation method: blob\n\nSED info:\n nu grid size jetkernel: 1000\n nu grid size: 500\n nu mix (Hz): 1.000000e+06\n nu max (Hz): 1.000000e+30\n\nflux plot lower bound : 1.000000e-120\n\n--------------------------------------------------------------------------------\n"
]
],
[
[
"### change Disk type",
"_____no_output_____"
],
[
"the disk type can be set as a more realistic multi temperature black body (MultiBB). In this case the `show_model` method provides physical parameters regarding the multi temperature black body accretion disk: \n\n- the Schwarzschild (Sw radius)\n\n- the Eddington luminosity (L Edd.)\n\n- the accretion rate (accr_rate)\n\n- the Eddington accretion rate (accr_rate Edd.)",
"_____no_output_____"
]
],
[
[
"my_jet.add_EC_component(['EC_BLR','EC_Disk'],disk_type='MultiBB')\nmy_jet.set_par('L_Disk',val=1E46)\nmy_jet.set_par('gmax',val=5E4)\nmy_jet.set_par('gmin',val=2.)\nmy_jet.set_par('R_H',val=3E17)\n\nmy_jet.set_par('p',val=1.5)\nmy_jet.set_par('p_1',val=3.2)\nmy_jet.set_par('R',val=3E15)\nmy_jet.set_par('B',val=1.5)\nmy_jet.set_par('z_cosm',val=0.6)\nmy_jet.set_par('BulkFactor',val=20)\nmy_jet.set_par('theta',val=1)\nmy_jet.set_par('gamma_break',val=5E2)\nmy_jet.set_N_from_nuLnu(nu_src=3E13,nuLnu_src=5E45)\nmy_jet.set_IC_nu_size(100)\nmy_jet.show_model()",
"\n--------------------------------------------------------------------------------\njet model description\n--------------------------------------------------------------------------------\nname: EC_example \n\nelectrons distribution:\n type: bkn \n gamma energy grid size: 201\n gmin grid : 2.000000e+00\n gmax grid : 5.000000e+04\n normalization True\n log-values False\n\naccretion disk:\n disk Type: MultiBB\n L disk: 1.000000e+46 (erg/s)\n T disk: 5.015768e+04 (K)\n nu peak disk: 4.098790e+15 (Hz)\n Sw radius 2.953539e+14 (cm)\n L Edd. 1.666723e+47 (erg/s)\n accr_rate: 2.205171e+00 (M_sun/yr)\n accr_rate Edd.: 3.675409e+01 (M_sun/yr)\n\nradiative fields:\n seed photons grid size: 100\n IC emission grid size: 100\n source emissivity lower bound : 1.000000e-120\n spectral components:\n name:Sum, state: on\n name:Sync, state: self-abs\n name:SSC, state: on\n name:EC_BLR, state: on\n name:Disk, state: on\n name:EC_Disk, state: on\nexternal fields transformation method: blob\n\nSED info:\n nu grid size jetkernel: 1000\n nu grid size: 500\n nu mix (Hz): 1.000000e+06\n nu max (Hz): 1.000000e+30\n\nflux plot lower bound : 1.000000e-120\n\n--------------------------------------------------------------------------------\n"
]
],
[
[
"now we set some parameter for the model",
"_____no_output_____"
]
],
[
[
"my_jet.eval()\n",
"_____no_output_____"
],
[
"p=my_jet.plot_model(frame='obs')\np.rescale(y_min=-13.5,y_max=-9.5,x_min=9,x_max=27)",
"_____no_output_____"
]
],
[
[
"### Dusty Torus",
"_____no_output_____"
]
],
[
[
"my_jet.add_EC_component('DT')\nmy_jet.show_model()",
"\n--------------------------------------------------------------------------------\njet model description\n--------------------------------------------------------------------------------\nname: EC_example \n\nelectrons distribution:\n type: bkn \n gamma energy grid size: 201\n gmin grid : 2.000000e+00\n gmax grid : 5.000000e+04\n normalization True\n log-values False\n\naccretion disk:\n disk Type: BB\n L disk: 1.000000e+46 (erg/s)\n T disk: 5.015768e+04 (K)\n nu peak disk: 4.098790e+15 (Hz)\n\nradiative fields:\n seed photons grid size: 100\n IC emission grid size: 100\n source emissivity lower bound : 1.000000e-120\n spectral components:\n name:Sum, state: on\n name:Sync, state: self-abs\n name:SSC, state: on\n name:EC_BLR, state: on\n name:Disk, state: on\n name:EC_Disk, state: on\n name:DT, state: on\nexternal fields transformation method: blob\n\nSED info:\n nu grid size jetkernel: 1000\n nu grid size: 500\n nu mix (Hz): 1.000000e+06\n nu max (Hz): 1.000000e+30\n\nflux plot lower bound : 1.000000e-120\n\n--------------------------------------------------------------------------------\n"
],
[
"my_jet.eval()\n",
"_____no_output_____"
],
[
"p=my_jet.plot_model()\np.rescale(y_min=-13.5,y_max=-9.5,x_min=9,x_max=27)",
"_____no_output_____"
],
[
"my_jet.add_EC_component('EC_DT')\nmy_jet.eval()\n",
"_____no_output_____"
],
[
"p=my_jet.plot_model()\np.rescale(y_min=-13.5,y_max=-9.5,x_min=9,x_max=27)",
"_____no_output_____"
],
[
"my_jet.save_model('test_EC_model.pkl')\nmy_jet=Jet.load_model('test_EC_model.pkl')",
"_____no_output_____"
]
],
[
[
"### Changing the external field transformation",
"_____no_output_____"
],
[
"Default method, is the transformation of the external photon field from the disk/BH frame to the relativistic blob",
"_____no_output_____"
]
],
[
[
"my_jet.set_external_field_transf('blob')",
"_____no_output_____"
]
],
[
[
"Alternatively, in the case of istropric fields as the CMB or the BLR and DT within the BLR radius, and DT radius, respectively, the it is possible to transform the the electron distribution, moving the blob to the disk/BH frame.",
"_____no_output_____"
]
],
[
[
"my_jet.set_external_field_transf('disk')",
"_____no_output_____"
]
],
[
[
"### External photon field energy density along the jet",
"_____no_output_____"
]
],
[
[
"def iso_field_transf(L,R,BulckFactor):\n beta=1.0 - 1/(BulckFactor*BulckFactor)\n return L/(4*np.pi*R*R*3E10)*BulckFactor*BulckFactor*(1+((beta**2)/3))\n\ndef external_iso_behind_transf(L,R,BulckFactor):\n beta=1.0 - 1/(BulckFactor*BulckFactor)\n return L/((4*np.pi*R*R*3E10)*(BulckFactor*BulckFactor*(1+beta)**2))\n",
"_____no_output_____"
]
],
[
[
"EC seed photon fields, in the Disk rest frame",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfig = plt.figure(figsize=(8,6))\nax=fig.subplots(1)\nN=50\nG=1\nR_range=np.logspace(13,25,N)\ny=np.zeros((8,N))\nmy_jet.set_verbosity(0)\nmy_jet.set_par('R_BLR_in',1E17)\nmy_jet.set_par('R_BLR_out',1.1E17)\nfor ID,R in enumerate(R_range):\n my_jet.set_par('R_H',val=R)\n my_jet.set_external_fields()\n my_jet.energetic_report(verbose=False)\n \n y[1,ID]=my_jet.energetic_dict['U_BLR_DRF']\n y[0,ID]=my_jet.energetic_dict['U_Disk_DRF']\n y[2,ID]=my_jet.energetic_dict['U_DT_DRF']\n \ny[4,:]=iso_field_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_DT.val,my_jet.parameters.R_DT.val,G)\ny[3,:]=iso_field_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_BLR.val,my_jet.parameters.R_BLR_in.val,G)\ny[5,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_BLR.val,R_range,G)\ny[6,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_DT.val,R_range,G)\ny[7,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative,R_range,G)\n\nax.plot(np.log10(R_range),np.log10(y[0,:]),label='Disk')\nax.plot(np.log10(R_range),np.log10(y[1,:]),'-',label='BLR')\nax.plot(np.log10(R_range),np.log10(y[2,:]),label='DT')\nax.plot(np.log10(R_range),np.log10(y[3,:]),'--',label='BLR uniform')\nax.plot(np.log10(R_range),np.log10(y[4,:]),'--',label='DT uniform')\nax.plot(np.log10(R_range),np.log10(y[5,:]),'--',label='BLR 1/R2')\nax.plot(np.log10(R_range),np.log10(y[6,:]),'--',label='DT 1/R2')\nax.plot(np.log10(R_range),np.log10(y[7,:]),'--',label='Disk 1/R2')\nax.set_xlabel('log(R_H) cm')\nax.set_ylabel('log(Uph) erg cm-3 s-1')\n\nax.legend()\n",
"_____no_output_____"
],
[
"%matplotlib inline\n\nfig = plt.figure(figsize=(8,6))\nax=fig.subplots(1)\n\nL_Disk=1E45\nN=50\nG=my_jet.parameters.BulkFactor.val\nR_range=np.logspace(15,22,N)\ny=np.zeros((8,N))\nmy_jet.set_par('L_Disk',val=L_Disk)\nmy_jet._blob.theta_n_int=100\nmy_jet._blob.l_n_int=100\nmy_jet._blob.theta_n_int=100\nmy_jet._blob.l_n_int=100\nfor ID,R in enumerate(R_range):\n my_jet.set_par('R_H',val=R)\n my_jet.set_par('R_BLR_in',1E17*(L_Disk/1E45)**.5)\n my_jet.set_par('R_BLR_out',1.1E17*(L_Disk/1E45)**.5)\n my_jet.set_par('R_DT',2.5E18*(L_Disk/1E45)**.5)\n my_jet.set_external_fields()\n my_jet.energetic_report(verbose=False)\n \n y[1,ID]=my_jet.energetic_dict['U_BLR']\n y[0,ID]=my_jet.energetic_dict['U_Disk']\n y[2,ID]=my_jet.energetic_dict['U_DT']\n \n\n\ny[4,:]=iso_field_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_DT.val,my_jet.parameters.R_DT.val,G)\ny[3,:]=iso_field_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_BLR.val,my_jet.parameters.R_BLR_in.val,G)\ny[5,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_BLR.val,R_range,G)\ny[6,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative*my_jet.parameters.tau_DT.val,R_range,G)\ny[7,:]=external_iso_behind_transf(my_jet._blob.L_Disk_radiative,R_range,G)\n\nax.plot(np.log10(R_range),np.log10(y[0,:]),label='Disk')\nax.plot(np.log10(R_range),np.log10(y[1,:]),'-',label='BLR')\nax.plot(np.log10(R_range),np.log10(y[2,:]),'-',label='DT')\nax.plot(np.log10(R_range),np.log10(y[3,:]),'--',label='BLR uniform')\nax.plot(np.log10(R_range),np.log10(y[4,:]),'--',label='DT uniform')\nax.plot(np.log10(R_range),np.log10(y[5,:]),'--',label='BLR 1/R2')\nax.plot(np.log10(R_range),np.log10(y[6,:]),'--',label='DT 1/R2')\nax.plot(np.log10(R_range),np.log10(y[7,:]),'--',label='Disk 1/R2')\nax.axvline(np.log10( my_jet.parameters.R_DT.val ))\nax.axvline(np.log10( my_jet.parameters.R_BLR_out.val))\n\nax.set_xlabel('log(R_H) cm')\nax.set_ylabel('log(Uph`) erg cm-3 s-1')\n\nax.legend()\n",
"_____no_output_____"
]
],
[
[
"### IC against the CMB",
"_____no_output_____"
]
],
[
[
"my_jet=Jet(name='test_equipartition',electron_distribution='lppl',beaming_expr='bulk_theta')\nmy_jet.set_par('R',val=1E21)\nmy_jet.set_par('z_cosm',val= 0.651)\nmy_jet.set_par('B',val=2E-5)\nmy_jet.set_par('gmin',val=50)\nmy_jet.set_par('gamma0_log_parab',val=35.0E3)\nmy_jet.set_par('gmax',val=30E5)\nmy_jet.set_par('theta',val=12.0)\nmy_jet.set_par('BulkFactor',val=3.5)\nmy_jet.set_par('s',val=2.58)\nmy_jet.set_par('r',val=0.42)\nmy_jet.set_N_from_nuFnu(5E-15,1E12)\nmy_jet.add_EC_component('EC_CMB')",
"_____no_output_____"
]
],
[
[
"We can now compare the different beaming pattern for the EC emission if the CMB, and realize that the beaming pattern is different. \nThis is very important in the case of radio galaxies. The `src` transformation is the one to use in the case of radio galaies or \nmisaligned AGNs, and gives a more accurate results.\nAnyhow, be careful that this works only for isotropic external fields, suchs as the CMB, or the BLR \nseed photons whitin the Dusty torus radius, and BLR radius, respectively\n",
"_____no_output_____"
]
],
[
[
"from jetset.plot_sedfit import PlotSED\np=PlotSED()\n\nmy_jet.set_external_field_transf('blob')\nc= ['k', 'g', 'r', 'c'] \nfor ID,theta in enumerate(np.linspace(2,20,4)):\n my_jet.parameters.theta.val=theta\n my_jet.eval()\n my_jet.plot_model(plot_obj=p,comp='Sum',label='blob, theta=%2.2f'%theta,line_style='--',color=c[ID])\n\nmy_jet.set_external_field_transf('disk')\nfor ID,theta in enumerate(np.linspace(2,20,4)):\n my_jet.parameters.theta.val=theta\n my_jet.eval()\n my_jet.plot_model(plot_obj=p,comp='Sum',label='disk, theta=%2.2f'%theta,line_style='',color=c[ID])\n\np.rescale(y_min=-17.5,y_max=-12.5,x_max=28)",
"_____no_output_____"
]
],
[
[
"## Equipartition",
"_____no_output_____"
],
[
"It is also possible to set our jet at the equipartition, that is achieved not using analytical approximation, but by numerically finding the equipartition value over a grid.\nWe have to provide the value of the observed flux (`nuFnu_obs`) at a given observed frequency (`nu_obs`), the minimum value of B (`B_min`), and the number of grid points (`N_pts`)\n",
"_____no_output_____"
]
],
[
[
"my_jet.parameters.theta.val=12\nB_min,b_grid,U_B,U_e=my_jet.set_B_eq(nuFnu_obs=5E-15,nu_obs=1E12,B_min=1E-9,N_pts=50,plot=True)\nmy_jet.show_pars()\n\nmy_jet.eval()\n",
"B grid min 1e-09\nB grid max 1.0\ngrid points 50\n"
],
[
"p=my_jet.plot_model()\np.rescale(y_min=-16.5,y_max=-13.5,x_max=28)",
"_____no_output_____"
]
]
] |
[
"raw",
"markdown",
"raw",
"markdown",
"raw",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"raw"
],
[
"markdown"
],
[
"raw"
],
[
"markdown",
"markdown"
],
[
"raw"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cba3fd646a9515ceacd97aadf2fc31e99095c6a0
| 109,050 |
ipynb
|
Jupyter Notebook
|
Data Visualization/6.Choosing Plot Types and Custom Styles.ipynb
|
nakshatra-garg/kaggle-learn-courses
|
c110792ae85cf343d606d13da86cc51c9e2bfdcf
|
[
"MIT"
] | null | null | null |
Data Visualization/6.Choosing Plot Types and Custom Styles.ipynb
|
nakshatra-garg/kaggle-learn-courses
|
c110792ae85cf343d606d13da86cc51c9e2bfdcf
|
[
"MIT"
] | null | null | null |
Data Visualization/6.Choosing Plot Types and Custom Styles.ipynb
|
nakshatra-garg/kaggle-learn-courses
|
c110792ae85cf343d606d13da86cc51c9e2bfdcf
|
[
"MIT"
] | null | null | null | 109,050 | 109,050 | 0.953682 |
[
[
[
"**This notebook is an exercise in the [Data Visualization](https://www.kaggle.com/learn/data-visualization) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/choosing-plot-types-and-custom-styles).**\n\n---\n",
"_____no_output_____"
],
[
"In this exercise, you'll explore different chart styles, to see which color combinations and fonts you like best!\n\n## Setup\n\nRun the next cell to import and configure the Python libraries that you need to complete the exercise.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\npd.plotting.register_matplotlib_converters()\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nprint(\"Setup Complete\")",
"Setup Complete\n"
]
],
[
[
"The questions below will give you feedback on your work. Run the following cell to set up our feedback system.",
"_____no_output_____"
]
],
[
[
"# Set up code checking\nimport os\nif not os.path.exists(\"../input/spotify.csv\"):\n os.symlink(\"../input/data-for-datavis/spotify.csv\", \"../input/spotify.csv\") \nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.data_viz_to_coder.ex6 import *\nprint(\"Setup Complete\")",
"Setup Complete\n"
]
],
[
[
"You'll work with a chart from the previous tutorial. Run the next cell to load the data.",
"_____no_output_____"
]
],
[
[
"# Path of the file to read\nspotify_filepath = \"../input/spotify.csv\"\n\n# Read the file into a variable spotify_data\nspotify_data = pd.read_csv(spotify_filepath, index_col=\"Date\", parse_dates=True)",
"_____no_output_____"
]
],
[
[
"# Try out seaborn styles\n\nRun the command below to try out the `\"dark\"` theme.",
"_____no_output_____"
]
],
[
[
"# Change the style of the figure\nsns.set_style(\"ticks\")\n\n# Line chart \nplt.figure(figsize=(12,6))\nsns.lineplot(data=spotify_data)\n\n# Mark the exercise complete after the code cell is run\nstep_1.check()",
"_____no_output_____"
]
],
[
[
"Now, try out different themes by amending the first line of code and running the code cell again. Remember the list of available themes:\n- `\"darkgrid\"`\n- `\"whitegrid\"`\n- `\"dark\"`\n- `\"white\"`\n- `\"ticks\"`\n\nThis notebook is your playground -- feel free to experiment as little or as much you wish here! The exercise is marked as complete after you run every code cell in the notebook at least once.\n\n## Keep going\n\nLearn about how to select and visualize your own datasets in the **[next tutorial](https://www.kaggle.com/alexisbcook/final-project)**!",
"_____no_output_____"
],
[
"---\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/161291) to chat with other Learners.*",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cba40691ed13840f23c5e7cf595adeb0313bd273
| 312,287 |
ipynb
|
Jupyter Notebook
|
Notebooks/Data Analysis.ipynb
|
BCHSI/NLP-Project
|
c5bf0feeb5f94a69808bfee8f193194e9949296d
|
[
"MIT"
] | null | null | null |
Notebooks/Data Analysis.ipynb
|
BCHSI/NLP-Project
|
c5bf0feeb5f94a69808bfee8f193194e9949296d
|
[
"MIT"
] | null | null | null |
Notebooks/Data Analysis.ipynb
|
BCHSI/NLP-Project
|
c5bf0feeb5f94a69808bfee8f193194e9949296d
|
[
"MIT"
] | null | null | null | 159.983094 | 105,952 | 0.802995 |
[
[
[
"from sklearn.linear_model import LogisticRegression\nimport csv\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn import utils\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix",
"_____no_output_____"
],
[
"df = pd.read_csv('data_1000.csv')\n\n# for i, row in df.iterrows():\n# integer = int(row['correct_answ'])\n# #result = row['cosine_sim']/2 + 0.5\n# #df.set_value(i,'cosine_sim', result)\n# df.set_value(i,'correct_answ', integer)\n\n\ndf.head(50)",
"_____no_output_____"
],
[
"df.boxplot(by='correct_answ', column=['bleu_score', 'levenstein_sim', 'cosine_sim', 'jaccard_sim'], \n grid=True, figsize=(15,15))",
"_____no_output_____"
],
[
"df.boxplot(by='hof_answ', column=['bleu_score', 'levenstein_sim', 'cosine_sim', 'jaccard_sim'], \n grid=True, figsize=(15,15))",
"_____no_output_____"
],
[
"similarities = [column for column in df.columns if 'sim' in column or 'score' in column]\ndf[similarities].hist(bins=50, figsize=(20,15))\nplt.show()",
"_____no_output_____"
],
[
"df['correct_answ'].value_counts()",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14,10))\ndf.plot(kind=\"scatter\", x=\"bleu_score\", y=\"correct_answ\",alpha=0.2, ax=axes[0,0])\ndf.plot(kind=\"scatter\", x=\"levenstein_sim\", y=\"correct_answ\",alpha=0.2, ax=axes[0,1])\ndf.plot(kind=\"scatter\", x=\"jaccard_sim\", y=\"correct_answ\",alpha=0.2, ax=axes[1,0])\ndf.plot(kind=\"scatter\", x=\"cosine_sim\", y=\"correct_answ\",alpha=0.2, ax=axes[1,1])",
"_____no_output_____"
],
[
"scatter_matrix(df[similarities], figsize=(14, 10))",
"_____no_output_____"
],
[
"corr_matrix = df.corr()\ncorr_matrix[\"correct_answ\"].sort_values(ascending=False)",
"_____no_output_____"
],
[
"lab_enc = preprocessing.LabelEncoder()\nencoded = lab_enc.fit_transform(np.array(df['cosine_sim']))\n\nclf = LogisticRegression(random_state=0).fit(np.array(df[similarities]), np.array(df['correct_answ']).reshape(-1,1))\npredicted = clf.predict(np.array(df.loc[:,similarities]))\nprint(predicted)",
"[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1]\n"
],
[
"from sklearn.ensemble import RandomForestRegressor\n\nforest_reg = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df[similarities]), np.array(df['correct_answ']).reshape(-1,1))\nrandom_for = np.around(forest_reg.predict(df[similarities]))\ndf['forest'] = random_for\nprint(df['correct_answ'].sub(random_for, axis=0).value_counts())\n\nforest_single = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df['cosine_sim']).reshape(-1,1), np.array(df['correct_answ']).reshape(-1,1))\nrandom_single_val = np.around(forest_reg.predict(np.array(df['cosine_sim']).reshape(-1,1)))\nprint(forest_reg.predict(np.array(df['cosine_sim']).reshape(-1,1)))\nprint('-----------------')\nprint(df['correct_answ'].sub(random_single_val, axis=0).value_counts())",
"c:\\users\\schaa\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\ipykernel_launcher.py:4: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n after removing the cwd from sys.path.\nc:\\users\\schaa\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\ipykernel_launcher.py:10: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n # Remove the CWD from sys.path while we load stuff.\n"
],
[
"forest_single = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df['levenstein_sim']).reshape(-1,1), np.array(df['correct_answ']).reshape(-1,1))\nrandom_single_val = np.around(forest_reg.predict(np.array(df['levenstein_sim']).reshape(-1,1)))\nprint(forest_reg.predict(np.array(df['levenstein_sim']).reshape(-1,1)))\nprint('-----------------')\nprint(df['correct_answ'].sub(random_single_val, axis=0).value_counts())",
"c:\\users\\schaa\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\ipykernel_launcher.py:2: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n \n"
],
[
"forest_single = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df['jaccard_sim']).reshape(-1,1), np.array(df['correct_answ']).reshape(-1,1))\nrandom_single_val = np.around(forest_reg.predict(np.array(df['jaccard_sim']).reshape(-1,1)))\nprint(forest_reg.predict(np.array(df['jaccard_sim']).reshape(-1,1)))\nprint('-----------------')\nprint(df['correct_answ'].sub(random_single_val, axis=0).value_counts())\n\nforest_single = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df['bleu_score']).reshape(-1,1), np.array(df['correct_answ']).reshape(-1,1))\nrandom_single_val = np.around(forest_reg.predict(np.array(df['bleu_score']).reshape(-1,1)))\nprint(df['correct_answ'].sub(random_single_val, axis=0).value_counts())",
"c:\\users\\schaa\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\ipykernel_launcher.py:2: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n \n"
],
[
"forest_reg = RandomForestRegressor(n_estimators=100, random_state=42)\nforest_reg.fit(np.array(df[['cosine_sim', 'levenstein_sim']]), np.array(df['correct_answ']).reshape(-1,1))\nrandom_for = np.around(forest_reg.predict(df[['cosine_sim','levenstein_sim']]))\nprint(df['correct_answ'].sub(random_for, axis=0).value_counts())",
"c:\\users\\schaa\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\ipykernel_launcher.py:2: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n \n"
],
[
"plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1)\nplt.axhline(.5, color='.5')\n\nplt.ylabel('y')\nplt.xlabel('X')\nplt.xticks(range(-5, 10))\nplt.yticks([0, 0.5, 1])\nplt.ylim(-.25, 1.25)\nplt.xlim(-4, 10)\nplt.legend(('Logistic Regression Model', 'Linear Regression Model'),\n loc=\"lower right\", fontsize='small')\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba40e35965794ddc4360c70867af067e1d7a324
| 70,531 |
ipynb
|
Jupyter Notebook
|
notebooks/archive/Multi_class_classification_with_Transformers.ipynb
|
dafrie/fin-disclosures-nlp
|
aa89013a1b3c621df261d70cad16aeef15c34d25
|
[
"MIT"
] | 2 |
2020-06-08T17:07:17.000Z
|
2020-06-25T16:04:38.000Z
|
notebooks/archive/Multi_class_classification_with_Transformers.ipynb
|
dafrie/fin-disclosures-nlp
|
aa89013a1b3c621df261d70cad16aeef15c34d25
|
[
"MIT"
] | 2 |
2020-05-11T17:37:59.000Z
|
2020-05-11T17:41:12.000Z
|
notebooks/archive/Multi_class_classification_with_Transformers.ipynb
|
dafrie/fin-disclosures-nlp
|
aa89013a1b3c621df261d70cad16aeef15c34d25
|
[
"MIT"
] | null | null | null | 31.153269 | 292 | 0.574797 |
[
[
[
"<a href=\"https://colab.research.google.com/github/dafrie/fin-disclosures-nlp/blob/master/Multi_class_classification_with_Transformers.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Multi-Class classification with Transformers",
"_____no_output_____"
],
[
"# Setup",
"_____no_output_____"
]
],
[
[
"# Load Google drive where the data and models are stored\nfrom google.colab import drive\ndrive.mount('/content/drive')",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"############################## CONFIG ##############################\nTASK = \"multi-class\" #@param [\"multi-class\"]\n\n# Set to true if fine-tuning should be enabled. Else it loads fine-tuned model\nENABLE_FINE_TUNING = True #@param {type:\"boolean\"}\n\n# See list here: https://huggingface.co/models\nTRANSFORMER_MODEL_NAME = 'distilbert-base-cased' #@param [\"bert-base-uncased\", \"bert-large-uncased\", \"albert-base-v2\", \"albert-large-v2\", \"albert-xlarge-v2\", \"albert-xxlarge-v2\", \"roberta-base\", \"roberta-large\", \"distilbert-base-uncased\", \"distilbert-base-cased\"]\n\n# The DataLoader needs to know our batch size for training. BERT Authors recommend 16 or 32, however this leads to an error due to not enough GPU memory\nBATCH_SIZE = 16 #@param [\"8\", \"16\", \"32\"] {type:\"raw\"}\nMAX_TOKEN_SIZE = 256 #@param [512,256,128] {type:\"raw\"}\nEPOCHS = 4 # @param [1,2,3,4] {type:\"raw\"}\nLEARNING_RATE = 2e-5\nWEIGHT_DECAY = 0.0 # TODO: Necessary?\n\n# Evaluation metric config. See for context: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html\nAVERAGING_STRATEGY = 'macro' #@param [\"micro\", \"macro\", \"weighted\"]\n\n# To make the notebook reproducible (not guaranteed for pytorch on different releases/platforms!)\nSEED_VALUE = 0\n\n# Enable comet-ml logging\nDISABLE_COMET_ML = True #@param {type:\"boolean\"}\n####################################################################\n\nfull_task_name = TASK\n\nparameters = {\n \"task\": TASK,\n \"enable_fine_tuning\": ENABLE_FINE_TUNING,\n \"model_type\": \"transformer\",\n \"model_name\": TRANSFORMER_MODEL_NAME,\n \"batch_size\": BATCH_SIZE,\n \"max_token_size\": MAX_TOKEN_SIZE,\n \"epochs\": EPOCHS,\n \"learning_rate\": LEARNING_RATE,\n \"weight_decay\": WEIGHT_DECAY,\n \"seed_value\": SEED_VALUE,\n}\n\n# TODO: This could then be used to send to cometml to keep track of experiments...",
"_____no_output_____"
]
],
[
[
"\n",
"_____no_output_____"
]
],
[
[
"# Install transformers library + datasets helper\n!pip install transformers --quiet\n!pip install datasets --quiet\n!pip install optuna --quiet\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport torch\nimport textwrap\nimport random\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score\nfrom transformers import logging, AutoTokenizer\n\nmodel_id = TRANSFORMER_MODEL_NAME\nprint(f\"Selected {TRANSFORMER_MODEL_NAME} as transformer model for the task...\")\n\n# Setup the models path\nsaved_models_path = \"/content/drive/My Drive/{YOUR_PROJECT_HERE}/models/finetuned_models/\"\nexpected_model_path = os.path.join(saved_models_path, TASK, model_id)\nhas_model_path = os.path.isdir(expected_model_path)\nmodel_checkpoint = TRANSFORMER_MODEL_NAME if ENABLE_FINE_TUNING else expected_model_path\n\n# Check if model exists\nif not ENABLE_FINE_TUNING:\n assert has_model_path, f\"No fine-tuned model found at '{expected_model_path}', you need first to fine-tune a model from a pretrained checkpoint by enabling the 'ENABLE_FINE_TUNING' flag!\"",
"\u001b[K |████████████████████████████████| 1.4MB 12.1MB/s \n\u001b[K |████████████████████████████████| 890kB 23.6MB/s \n\u001b[K |████████████████████████████████| 2.9MB 55.4MB/s \n\u001b[?25h Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n\u001b[K |████████████████████████████████| 163kB 13.7MB/s \n\u001b[K |████████████████████████████████| 245kB 32.1MB/s \n\u001b[K |████████████████████████████████| 17.7MB 200kB/s \n\u001b[K |████████████████████████████████| 266kB 18.1MB/s \n\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n\u001b[K |████████████████████████████████| 163kB 50.0MB/s \n\u001b[K |████████████████████████████████| 81kB 11.0MB/s \n\u001b[K |████████████████████████████████| 81kB 11.7MB/s \n\u001b[K |████████████████████████████████| 112kB 24.1MB/s \n\u001b[K |████████████████████████████████| 51kB 7.4MB/s \n\u001b[K |████████████████████████████████| 133kB 50.5MB/s \n\u001b[?25h Building wheel for optuna (PEP 517) ... \u001b[?25l\u001b[?25hdone\n Building wheel for PrettyTable (setup.py) ... \u001b[?25l\u001b[?25hdone\n Building wheel for pyperclip (setup.py) ... \u001b[?25l\u001b[?25hdone\nSelected distilbert-base-cased as transformer model for the task...\n"
]
],
[
[
"# Data loading",
"_____no_output_____"
]
],
[
[
"# Note: Uses https://huggingface.co/docs/datasets/package_reference/main_classes.html\nfrom datasets import DatasetDict, Dataset, load_dataset, Sequence, ClassLabel, Features, Value, concatenate_datasets\n\n# TODO: Adapt\ndoc_column = 'text' # Contains the text\nlabel_column = 'cro' # Needs to be an integer that represents the respective class\n\n# TODO: Load train/test data\ndf_train = pd.read_pickle(\"/content/drive/My Drive/fin-disclosures-nlp/data/labels/Firm_AnnualReport_Labels_Training.pkl\")\ndf_test = pd.read_pickle(\"/content/drive/My Drive/fin-disclosures-nlp/data/labels/Firm_AnnualReport_Labels_Test.pkl\")\n\ndf_train = df_train.query(f\"{label_column} == {label_column}\")\ndf_test = df_test.query(f\"{label_column} == {label_column}\")\n\ncategory_labels = df_train[label_column].unique().tolist()\nno_of_categories = len(category_labels)\n\n# TODO: Not sure if this step is necessary, but if you have the category in text and not integers\n# This assumes that there is t\ndf_train[label_column] = df_train[label_column].astype('category').cat.codes.to_numpy(copy=True)\ndf_test[label_column] = df_test[label_column].astype('category').cat.codes.to_numpy(copy=True)\n\ntrain_dataset = pd.DataFrame(df_train[[doc_column, label_column]].to_numpy(), columns=['text', 'labels'])\ntest_dataset = pd.DataFrame(df_test[[doc_column, label_column]].to_numpy(), columns=['text', 'labels'])\n\nfeatures = Features({'text': Value('string'), 'labels': ClassLabel(names=category_labels, num_classes=no_of_categories)})\n\n# Setup Hugginface Dataset\ntrain_dataset = Dataset.from_pandas(train_dataset, features=features)\ntest_dataset = Dataset.from_pandas(test_dataset, features=features)\n\ndataset = DatasetDict({ 'train': train_dataset, 'test': test_dataset })",
"_____no_output_____"
]
],
[
[
"## Tokenization",
"_____no_output_____"
]
],
[
[
"# Load the tokenizer.\ntokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)\n\n# Encode the whole dataset\ndef encode(data, max_len=MAX_TOKEN_SIZE):\n return tokenizer(data[\"text\"], truncation=True, padding='max_length', max_length=max_len)\n\ndataset = dataset.map(encode, batched=True)",
"_____no_output_____"
]
],
[
[
"## Validation set preparation",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import TensorDataset, random_split, DataLoader, RandomSampler, SequentialSampler\n\n# See here for this workaround: https://github.com/huggingface/datasets/issues/767\ndataset['train'], dataset['valid'] = dataset['train'].train_test_split(test_size=0.1, seed=SEED_VALUE).values()",
"_____no_output_____"
],
[
"dataset['train'].features",
"_____no_output_____"
]
],
[
[
"# Model Setup and Training",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score, precision_recall_fscore_support, roc_auc_score, matthews_corrcoef\nfrom transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer\nfrom transformers.trainer_pt_utils import nested_detach\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss\nfrom scipy.special import softmax \n\n# Check if GPU is available\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Sets the evaluation metric depending on the task\n# TODO: Set your evaluation metric! Needs to be also in the provided \"compute_metrics\" function below\nmetric_name = \"matthews_correlation\"\n\n# The training arguments\nargs = TrainingArguments(\n output_dir=f\"/content/models/{TASK}/{model_id}\",\n evaluation_strategy = \"epoch\",\n learning_rate = LEARNING_RATE,\n per_device_train_batch_size = BATCH_SIZE,\n per_device_eval_batch_size = BATCH_SIZE,\n num_train_epochs = EPOCHS,\n weight_decay = WEIGHT_DECAY,\n load_best_model_at_end = True,\n metric_for_best_model = metric_name,\n greater_is_better = True,\n seed = SEED_VALUE,\n)\n\n\ndef model_init():\n \"\"\"Model initialization. Disabels logging temporarily to avoid spamming messages and loads the pretrained or fine-tuned model\"\"\" \n logging.set_verbosity_error() # Workaround to hide warnings that the model weights are randomly set and fine-tuning is necessary (which we do later...)\n model = AutoModelForSequenceClassification.from_pretrained(\n model_checkpoint, # Load from model checkpoint, i.e. the pretrained model or a previously saved fine-tuned model\n num_labels = no_of_categories, # The number of different categories/labels\n output_attentions = False, # Whether the model returns attentions weights.\n output_hidden_states = False, # Whether the model returns all hidden-states.)\n )\n logging.set_verbosity_warning()\n return model\n\ndef compute_metrics(pred):\n \"\"\"Computes classification task metric\"\"\"\n labels = pred.label_ids\n preds = pred.predictions\n\n # Convert to probabilities\n preds_prob = softmax(preds, axis=1)\n \n # Convert to 0/1, i.e. set to 1 the class with the highest logit\n preds = preds.argmax(-1)\n\n precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average=AVERAGING_STRATEGY)\n acc = accuracy_score(labels, preds)\n matthews_corr = matthews_corrcoef(labels, preds)\n return {\n 'f1': f1,\n 'precision': precision,\n 'recall': recall,\n 'matthews_correlation': matthews_corr\n }\n\nclass CroTrainer(Trainer):\n # Note: If you need to do extra customization (like to alter the loss computation by adding weights), this can be done here\n pass\n\ntrainer = CroTrainer(\n model_init=model_init,\n args=args,\n train_dataset=dataset[\"train\"],\n eval_dataset=dataset[\"valid\"],\n tokenizer=tokenizer,\n compute_metrics=compute_metrics\n)\n\n# Only train if enabled, else we just want to load the model\nif ENABLE_FINE_TUNING:\n trainer.train()\n trainer.save_model()",
"_____no_output_____"
],
[
"eval_metrics = trainer.evaluate()\n# experiment.log_metrics(eval_metrics)",
"_____no_output_____"
],
[
"predict_result = trainer.predict(dataset['test'])",
"_____no_output_____"
],
[
"from sklearn.metrics import multilabel_confusion_matrix, classification_report\nfrom scipy.special import softmax \n\npreds = predict_result.predictions\nlabels = predict_result.label_ids\n\ntest_roc_auc = roc_auc_score(labels, preds, average=AVERAGING_STRATEGY)\nprint(\"Test ROC AuC: \", test_roc_auc)\n\npreds_prob = softmax(preds, axis=1)\nthreshold = 0.5\npreds_bool = (preds_prob > threshold)\n\nlabel_list = test_dataset.features['labels'].feature.names\nmultilabel_confusion_matrix(labels, preds_bool)\nprint(classification_report(labels, preds_bool, target_names=label_list))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cba41053743c69ba802a07a89aa876012836e2a2
| 31,582 |
ipynb
|
Jupyter Notebook
|
Russia_LSTM_10days_K7days.ipynb
|
Roshi986/COVID-19-modelling
|
5340fb0b46ea2fb0e023fe567ed99226fd58c387
|
[
"MIT"
] | null | null | null |
Russia_LSTM_10days_K7days.ipynb
|
Roshi986/COVID-19-modelling
|
5340fb0b46ea2fb0e023fe567ed99226fd58c387
|
[
"MIT"
] | 1 |
2020-09-01T16:08:59.000Z
|
2020-09-01T16:10:10.000Z
|
Russia_LSTM_10days_K7days.ipynb
|
Roshi986/COVID-19-modelling
|
5340fb0b46ea2fb0e023fe567ed99226fd58c387
|
[
"MIT"
] | null | null | null | 34.478166 | 123 | 0.499113 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport warnings\nimport os\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense\nfrom tensorflow.keras.layers import Bidirectional\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.compat.v1.keras.layers import TimeDistributed\nfrom tensorflow.keras.layers import Conv1D\nfrom tensorflow.keras.layers import MaxPooling1D\nfrom tensorflow.keras.layers import ConvLSTM2D\n\nwarnings.simplefilter('ignore')\n\ncountryName = 'Russia'\n\nnFeatures = 1\n\nnDaysMin = 10\nk = 7\n\nnValid = 10\nnTest = 10",
"_____no_output_____"
],
[
"dataDir = os.path.join('C:\\\\Users\\\\AMC\\\\Desktop\\\\Roshi\\\\Data')\nconfirmedFilename = 'confirmed_july.csv'\ndeathsFilename = 'deaths_july.csv'\nrecoveredFilename = 'recovered_july.csv'",
"_____no_output_____"
],
[
"confirmed = pd.read_csv(confirmedFilename)",
"_____no_output_____"
],
[
"confirmed.head()\n",
"_____no_output_____"
],
[
"# split a univariate sequence into samples\ndef split_sequence(sequence, n_steps, k):\n X, y = list(), list()\n for i in range(len(sequence)):\n # find the end of this pattern\n end_ix = i + n_steps\n # check if we are beyond the sequence\n if end_ix + k >= len(sequence):\n break\n # gather input and output parts of the pattern\n seq_x, seq_y = sequence[i:end_ix], sequence[end_ix:end_ix+k]\n X.append(seq_x)\n y.append(seq_y)\n return np.array(X), np.array(y)",
"_____no_output_____"
],
[
"def meanAbsolutePercentageError(yTrueList, yPredList):\n absErrorList = [np.abs(yTrue - yPred) for yTrue, yPred in zip(yTrueList, yPredList)]\n absPcErrorList = [absError/yTrue for absError, yTrue in zip(absErrorList, yTrueList)]\n MAPE = 100*np.mean(absPcErrorList)\n return MAPE\n\ndef meanAbsolutePercentageError_kDay(yTrueListList, yPredListList):\n # Store true and predictions for day 1 in a list, day 2 in a list and so on\n # Keep each list of these lists in a respective dict with key as day #\n yTrueForDayK = {}\n yPredForDayK = {}\n for i in range(len(yTrueListList[0])):\n yTrueForDayK[i] = []\n yPredForDayK[i] = []\n for yTrueList, yPredList in zip(yTrueListList, yPredListList):\n for i in range(len(yTrueList)):\n yTrueForDayK[i].append(yTrueList[i])\n yPredForDayK[i].append(yPredList[i])\n \n # Get MAPE for each day in a list\n MAPEList = []\n for i in yTrueForDayK.keys():\n MAPEList.append(meanAbsolutePercentageError(yTrueForDayK[i], yPredForDayK[i]))\n return np.mean(MAPEList)\n\ndef meanForecastError(yTrueList, yPredList):\n forecastErrors = [yTrue - yPred for yTrue, yPred in zip(yTrueList, yPredList)]\n MFE = np.mean(forecastErrors)\n return MFE\n\ndef meanAbsoluteError(yTrueList, yPredList):\n absErrorList = [np.abs(yTrue - yPred) for yTrue, yPred in zip(yTrueList, yPredList)]\n return np.mean(absErrorList)\n\ndef meanSquaredError(yTrueList, yPredList):\n sqErrorList = [np.square(yTrue - yPred) for yTrue, yPred in zip(yTrueList, yPredList)]\n return np.mean(sqErrorList)\n\ndef rootMeanSquaredError(yTrueList, yPredList):\n return np.sqrt(meanSquaredError(yTrueList, yPredList))\ndef medianSymmetricAccuracy(yTrueList, yPredList):\n '''https://helda.helsinki.fi//bitstream/handle/10138/312261/2017SW001669.pdf?sequence=1'''\n logAccRatioList = [np.abs(np.log(yPred/yTrue)) for yTrue, yPred in zip(yTrueList, yPredList)]\n MdSA = 100*(np.exp(np.median(logAccRatioList))-1)\n return MdSA\n\ndef medianSymmetricAccuracy_kDay(yTrueListList, yPredListList):\n # Store true and predictions for day 1 in a list, day 2 in a list and so on\n # Keep each list of these lists in a respective dict with key as day #\n yTrueForDayK = {}\n yPredForDayK = {}\n for i in range(len(yTrueListList[0])):\n yTrueForDayK[i] = []\n yPredForDayK[i] = []\n for yTrueList, yPredList in zip(yTrueListList, yPredListList):\n for i in range(len(yTrueList)):\n yTrueForDayK[i].append(yTrueList[i])\n yPredForDayK[i].append(yPredList[i])\n # Get MdSA for each day in a list\n MdSAList = []\n for i in yTrueForDayK.keys():\n MdSAList.append(medianSymmetricAccuracy(yTrueForDayK[i], yPredForDayK[i]))\n return(np.mean(MdSAList))",
"_____no_output_____"
],
[
"# Function to get all three frames for a given country\ndef getCountryCovidFrDict(countryName):\n countryCovidFrDict = {}\n for key in covidFrDict.keys():\n dataFr = covidFrDict[key]\n countryCovidFrDict[key] = dataFr[dataFr['Country/Region'] == countryName]\n return countryCovidFrDict",
"_____no_output_____"
],
[
"# Load all 3 csv files\ncovidFrDict = {}\ncovidFrDict['confirmed'] = pd.read_csv(confirmedFilename)\ncovidFrDict['deaths'] = pd.read_csv(deathsFilename)\ncovidFrDict['recovered'] = pd.read_csv(recoveredFilename)\n\ncountryCovidFrDict = getCountryCovidFrDict(countryName)\n\n# date list\ncolNamesList = list(countryCovidFrDict['confirmed'])\ndateList = [colName for colName in colNamesList if '/20' in colName]\ndataList = [countryCovidFrDict['confirmed'][date].iloc[0] for date in dateList]\ndataDict = dict(zip(dateList, dataList))\n\n# Only take time series from where the cases were >100\ndaysSince = 100\nnCasesGreaterDaysSinceList = []\ndatesGreaterDaysSinceList = []\n\nfor key in dataDict.keys():\n if dataDict[key] > daysSince:\n datesGreaterDaysSinceList.append(key)\n nCasesGreaterDaysSinceList.append(dataDict[key])\n \nXList, yList = split_sequence(nCasesGreaterDaysSinceList, nDaysMin, k)\n\nXTrainList = XList[0:len(XList)-(nValid + nTest)]\nXValidList = XList[len(XList)-(nValid+nTest):len(XList)-(nTest)]\nXTestList = XList[-nTest:]\n\nyTrain = yList[0:len(XList)-(nValid + nTest)]\nyValid = yList[len(XList)-(nValid+nTest):len(XList)-(nTest)]\nyTest = yList[-nTest:]\nprint('Total size of data points for LSTM:', len(yList))\nprint('Size of training set:', len(yTrain))\nprint('Size of validation set:', len(yValid))\nprint('Size of test set:', len(yTest))\n\n# Convert the list to matrix\nXTrain = XTrainList.reshape((XTrainList.shape[0], XTrainList.shape[1], nFeatures))\nXValid = XValidList.reshape((XValidList.shape[0], XValidList.shape[1], nFeatures))\nXTest = XTestList.reshape((XTestList.shape[0], XTestList.shape[1], nFeatures))",
"Total size of data points for LSTM: 117\nSize of training set: 97\nSize of validation set: 10\nSize of test set: 10\n"
]
],
[
[
"# Vanilla LSTM",
"_____no_output_____"
]
],
[
[
"nNeurons = 100 # number of neurones\nnFeatures = 1 # number of features\n\nbestValidMAPE = 100 # 100 validation for best MAPE\nbestSeed = -1\nfor seed in range(100):\n tf.random.set_seed(seed=seed)\n \n # define model\n model = Sequential()\n model.add(LSTM(nNeurons, activation='relu', input_shape=(nDaysMin, nFeatures)))\n model.add(Dense(1))\n opt = Adam(learning_rate=0.1)\n model.compile(optimizer=opt, loss='mse')\n\n # fit model\n history = model.fit(XTrain, yTrain[:,0], epochs=1000, verbose=0)\n\n yPredListList = []\n for day in range(nTest):\n yPredListList.append([])\n XValidNew = XValid.copy()\n for day in range(k):\n yPred = model.predict(np.float32(XValidNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XValidNew = np.delete(XValidNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XValidNew = np.append(XValidNew, yPred, axis=1)\n\n# for yTrue, yPred in zip(yTest, yPredList):\n# print(yTrue, yPred)\n MAPE = meanAbsolutePercentageError_kDay(yValid, yPredListList)\n print(seed, MAPE)\n if MAPE < bestValidMAPE:\n print('Updating best MAPE to {}...'.format(MAPE))\n bestValidMAPE = MAPE\n print('Updating best seed to {}...'.format(seed))\n bestSeed = seed\n\n# define model\nprint('Training model with best seed...')\ntf.random.set_seed(seed=bestSeed)\n\n#model = Sequential()\nmodel.add(LSTM(nNeurons, activation='relu', input_shape=(nDaysMin, nFeatures)))\nmodel.add(Dense(1))\nopt = Adam(learning_rate=0.1)\nmodel.compile(optimizer=opt, loss='mse')\n\n# fit model\nhistory = model.fit(XTrain, yTrain[:,0], validation_data = (XValid, yValid), epochs=1000, verbose=0)\n\n",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,5))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Valid'], loc='upper left')\nplt.show()",
"_____no_output_____"
],
[
"model.summary()",
"_____no_output_____"
],
[
"yPredListList = []\nfor day in range(nTest):\n yPredListList.append([])\nXTestNew = XTest.copy()\nfor day in range(k):\n yPred = model.predict(np.float32(XTestNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XTestNew = np.delete(XTestNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XTestNew = np.append(XTestNew, yPred, axis=1)\nMAPE = meanAbsolutePercentageError_kDay(yTest, yPredListList)\nprint('Test MAPE:', MAPE)\nMdSA = medianSymmetricAccuracy_kDay(yTest, yPredListList)\nprint('Test MdSA:', MdSA)\nMSE = meanSquaredError(yTest, yPredList)\nprint('Test MSE:', MSE)\nRMSE = rootMeanSquaredError(yTest, yPredList)\nprint('Test RMSE:', RMSE)\nyPredVanilla = yPredListList ",
"_____no_output_____"
]
],
[
[
"# Stacked LSTM",
"_____no_output_____"
]
],
[
[
"nNeurons = 50\nnFeatures = 1\n\nbestValidMAPE = 100\nbestSeed = -1\nfor seed in range(100):\n tf.random.set_seed(seed=seed)\n model = Sequential()\n model.add(LSTM(nNeurons, activation='relu', return_sequences=True, input_shape=(nDaysMin, nFeatures)))\n model.add(LSTM(nNeurons, activation='relu'))\n model.add(Dense(1))\n opt = Adam(learning_rate=0.1)\n model.compile(optimizer=opt, loss='mse')\n\n # fit model\n model.fit(XTrain, yTrain[:,0], epochs=1000, verbose=0)\n\n yPredListList = []\n for day in range(nTest):\n yPredListList.append([])\n XValidNew = XValid.copy()\n for day in range(k):\n yPred = model.predict(np.float32(XValidNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XValidNew = np.delete(XValidNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XValidNew = np.append(XValidNew, yPred, axis=1)\n\n# for yTrue, yPred in zip(yTest, yPredList):\n# print(yTrue, yPred)\n\n MAPE = meanAbsolutePercentageError_kDay(yValid, yPredListList)\n print(seed, MAPE)\n if MAPE < bestValidMAPE:\n print('Updating best MAPE to {}...'.format(MAPE))\n bestValidMAPE = MAPE\n print('Updating best seed to {}...'.format(seed))\n bestSeed = seed\n \n# define model\nprint('Training model with best seed...')\ntf.random.set_seed(seed=bestSeed)\nmodel = Sequential()\nmodel.add(LSTM(nNeurons, activation='relu', return_sequences=True, input_shape=(nDaysMin, nFeatures)))\nmodel.add(LSTM(nNeurons, activation='relu'))\nmodel.add(Dense(1))\nopt = Adam(learning_rate=0.1)\nmodel.compile(optimizer=opt, loss='mse')\nmodel.summary()\n\n# fit model\nhistory = model.fit(XTrain, yTrain[:,0], validation_data = (XValid, yValid), epochs=1000, verbose=0)",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,5))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Valid'], loc='upper left')\nplt.show()",
"_____no_output_____"
],
[
"yPredListList = []\nfor day in range(nTest):\n yPredListList.append([])\nXTestNew = XTest.copy()\nfor day in range(k):\n yPred = model.predict(np.float32(XTestNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XTestNew = np.delete(XTestNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XTestNew = np.append(XTestNew, yPred, axis=1)\n \nMAPE = meanAbsolutePercentageError_kDay(yTest, yPredListList)\nprint('Test MAPE:', MAPE)\nMdSA = medianSymmetricAccuracy_kDay(yTest, yPredListList)\nprint('Test MdSA:', MdSA)\nMSE = meanSquaredError(yTest, yPredListList)\nprint('Test MSE:', MSE)\nRMSE = rootMeanSquaredError(yTest, yPredListList)\nprint('Test RMSE:', RMSE)\nyPredStacked = yPredListList",
"_____no_output_____"
],
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"# Bi-directional LSTM",
"_____no_output_____"
]
],
[
[
"# define model\nnNeurons = 50\nnFeatures = 1\n\nbestValidMAPE = 100\nbestSeed = -1\nfor seed in range(100):\n tf.random.set_seed(seed=seed)\n model = Sequential()\n model.add(Bidirectional(LSTM(nNeurons, activation='relu'), input_shape=(nDaysMin, nFeatures)))\n model.add(Dense(1))\n opt = Adam(learning_rate=0.1)\n model.compile(optimizer=opt, loss='mse')\n\n # fit model\n history = model.fit(XTrain, yTrain[:,0], epochs=1000, verbose=0)\n\n yPredListList = []\n for day in range(nTest):\n yPredListList.append([])\n XValidNew = XValid.copy()\n for day in range(k):\n yPred = model.predict(np.float32(XValidNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XValidNew = np.delete(XValidNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XValidNew = np.append(XValidNew, yPred, axis=1)\n\n# for yTrue, yPred in zip(yTest, yPredList):\n# print(yTrue, yPred)\n MAPE = meanAbsolutePercentageError_kDay(yValid, yPredListList)\n print(seed, MAPE)\n if MAPE < bestValidMAPE:\n print('Updating best MAPE to {}...'.format(MAPE))\n bestValidMAPE = MAPE\n print('Updating best seed to {}...'.format(seed))\n bestSeed = seed\n# define model\nprint('Training model with best seed...')\ntf.random.set_seed(seed=bestSeed)\nmodel = Sequential()\nmodel.add(Bidirectional(LSTM(nNeurons, activation='relu'), input_shape=(nDaysMin, nFeatures)))\nmodel.add(Dense(1))\nopt = Adam(learning_rate=0.1)\nmodel.compile(optimizer=opt, loss='mse')\nmodel.summary()\n\n# fit model\nhistory = model.fit(XTrain, yTrain[:,0], validation_data = (XValid, yValid), epochs=1000, verbose=0)\n\n",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,5))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Valid'], loc='upper left')\nplt.show()",
"_____no_output_____"
],
[
"yPredListList = []\nfor day in range(nTest):\n yPredListList.append([])\nXTestNew = XTest.copy()\nfor day in range(k):\n yPred = model.predict(np.float32(XTestNew), verbose=0)\n for i in range(len(yPred)):\n yPredListList[i].append(yPred[i][0])\n XTestNew = np.delete(XTestNew, 0, axis=1)\n yPred = np.expand_dims(yPred, 2)\n XTestNew = np.append(XTestNew, yPred, axis=1)\n \nMAPE = meanAbsolutePercentageError_kDay(yTest, yPredListList)\nprint('Test MAPE:', MAPE)\nMdSA = medianSymmetricAccuracy_kDay(yTest, yPredListList)\nprint('Test MdSA:', MdSA)\nMSE = meanSquaredError(yTest, yPredListList)\nprint('Test MSE:', MSE)\nRMSE = rootMeanSquaredError(yTest, yPredListList)\nprint('Test RMSE:', RMSE)\nyPredBidirectional = yPredListList",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nfrom matplotlib.dates import DateFormatter\n#from statsmodels.tsa.statespace.sarimax import SARIMAX\n\n# Format y tick labels\ndef y_fmt(y, pos):\n decades = [1e9, 1e6, 1e3, 1e0, 1e-3, 1e-6, 1e-9 ]\n suffix = [\"G\", \"M\", \"k\", \"\" , \"m\" , \"u\", \"n\" ]\n if y == 0:\n return str(0)\n for i, d in enumerate(decades):\n if np.abs(y) >=d:\n val = y/float(d)\n signf = len(str(val).split(\".\")[1])\n if signf == 0:\n return '{val:d} {suffix}'.format(val=int(val), suffix=suffix[i])\n else:\n if signf == 1:\n if str(val).split(\".\")[1] == \"0\":\n return '{val:d} {suffix}'.format(val=int(round(val)), suffix=suffix[i]) \n tx = \"{\"+\"val:.{signf}f\".format(signf = signf) +\"} {suffix}\"\n return tx.format(val=val, suffix=suffix[i])\n\n #return y\n return y",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,10))\ndatesForPlottingList = datesGreaterDaysSinceList[-k:]\ngroundTruthList = nCasesGreaterDaysSinceList[-k:]\n\n\nplt.ylabel('Number of confirmed cases for Russia', fontsize=20)\nplt.plot(datesForPlottingList, groundTruthList, '-o', linewidth=3, label='Actual confirmed numbers');\nplt.plot(datesForPlottingList, yPredVanilla[-1], '-o', linewidth=3, label='Vanilla LSTM predictions');\nplt.plot(datesForPlottingList, yPredStacked[-1], '-o', linewidth=3, label='Stacked LSTM predictions');\nplt.plot(datesForPlottingList, yPredBidirectional[-1], '-o', linewidth=3, label='Bidirectional LSTM predictions');\nplt.xlabel('Date', fontsize=20);\nplt.legend(fontsize=14);\nplt.xticks(fontsize=16);\nplt.yticks(fontsize=16);\nax = plt.gca()\nax.yaxis.set_major_formatter(FuncFormatter(y_fmt))\n#date_form = DateFormatter(\"%d-%m\")\n#ax.xaxis.set_major_formatter(date_form)\n# plt.grid(axis='y')\nplt.savefig(os.path.join('Plots_10days_k7', 'predictions_{}.png'.format(countryName)), dpi=400)\nplt.savefig(os.path.join('Plots_10days_k7', 'predictions_{}.pdf'.format(countryName)), dpi=400)",
"_____no_output_____"
],
[
"datesForPlottingList\ngroundTruthList\nyPredVanilla",
"_____no_output_____"
],
[
"datesForPlottingList\ngroundTruthList\nyPredVanilla\nallvalues = {\n 'Date': ['7/22/20', '7/23/20', '7/24/20', '7/25/20', '7/26/20', '7/27/20', '7/28/20'],\n 'Actual':,\n 'Predicted_Vanilla': ,\n 'Predicted_Stacked': ,\n 'Predicted_BiLSTM' : }\n\nprint(allvalues)\nallvalues = pd.to_csv ('russia_10d_k7_predictions.csv')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba448d1ddd9b147c4d9dc14052fd1e7c6112e81
| 8,642 |
ipynb
|
Jupyter Notebook
|
Markdown_Guide.ipynb
|
coleman-word/DevOps-Notebooks
|
74777386bbaada2f93a7ccc7884d419b8d33b64d
|
[
"MIT"
] | null | null | null |
Markdown_Guide.ipynb
|
coleman-word/DevOps-Notebooks
|
74777386bbaada2f93a7ccc7884d419b8d33b64d
|
[
"MIT"
] | null | null | null |
Markdown_Guide.ipynb
|
coleman-word/DevOps-Notebooks
|
74777386bbaada2f93a7ccc7884d419b8d33b64d
|
[
"MIT"
] | null | null | null | 40.957346 | 246 | 0.538648 |
[
[
[
"[View in Colaboratory](https://colab.research.google.com/github/coleman-word/DevOps-Notebooks/blob/master/Markdown_Guide.ipynb)",
"_____no_output_____"
],
[
"Formatting text in Colaboratory: A guide to Colaboratory markdown\n===",
"_____no_output_____"
],
[
"## What is markdown?\n\nColaboratory has two types of cells: text and code. The text cells are formatted using a simple markup language called markdown, based on [the original](https://daringfireball.net/projects/markdown/syntax).\n\n## Quick reference\n\nTo see the markdown source, double-click a text cell, showing both the markdown source (above) and the rendered version (below). Above the markdown source there is a toolbar to assist editing.\n\nHeaders are created using \\#. Use multiple \\#\\#\\# for less emphasis. For example:\n>\\# This is equivalent to an <h1> tag\n\n>\\##### This is equivalent to an <h5> tag\n\nTo make text **bold** surround it with \\*\\*two asterisks\\*\\*. To make text *italic* use a \\*single asterisk\\* or \\_underscore\\_. \\\n_**Bold** inside italics_ and **vice-_versa_** also work. ~~Strikethrough~~ uses \\~\\~two tildes\\~\\~ while `monospace` (such as code) uses \\`backtick\\`.\n\nBlocks are indented with \\>, and multiple levels of indentation are indicated by repetition: \\>\\>\\> indents three levels.\n\nOrdered lists are created by typing any number followed by a period at the beginning of a line. Unordered lists are \\* or - at the beginning of a line. Lists can be nested by indenting using two spaces for each level of nesting.\n\n[Links](https://research.google.com/colaboratory) are created with \\[brackets around the linked text\\](and-parentheses-around-the-url.html). Naked URLs, like https://google.com, will automatically be linkified.\nAnother way to create links is using references, which look like [brackets around the linked text][an-arbitrary-reference-id] and then, later anywhere in the cell on its own line, \\[an-arbitrary-reference-id]: followed-by-a-URL.html\n\nA '!' character in front of a link turns it into an inline image link: !\\[Alt text]\\(link-to-an-image.png).\n\n$\\LaTeX$ equations are surrounded by `$`. For example, \\$$y = 0.1 x$\\$ for an inline equation. Double the `$` to set the contents off on its own centered line.\n\nHorizontal rules are created with three or more hyphens, underscores, or asterisks (\\-\\-\\-, \\_\\_\\_, or \\*\\*\\*) on their own line.\n\nTables are created using \\-\\-\\- for the boundary between the column header and columns and \\| between the columns.\n\nPlease see also [GitHub's documentation](https://help.github.com/articles/basic-writing-and-formatting-syntax/) for a similar (but not identical) version of markdown.",
"_____no_output_____"
],
[
"## Examples",
"_____no_output_____"
],
[
"Examples of markdown text with tags repeated, escaped the second time, to clarify their function:\n\n##### \\#\\#\\#\\#\\#This text is treated as an <h5> because it has five hashes at the beginning\n\n\\**italics*\\* and \\__italics_\\_\n\n**\\*\\*bold\\*\\***\n\n\\~\\~~~strikethrough~~\\~\\~\n\n\\``monospace`\\`\n\nNo indent\n>\\>One level of indentation\n>>\\>\\>Two levels of indentation\n\nAn ordered list:\n1. 1\\. One\n1. 1\\. Two\n1. 1\\. Three\n\nAn unordered list:\n* \\* One\n* \\* Two\n* \\* Three\n\nA naked URL: https://google.com\n\nLinked URL: \\[[Colaboratory](https://research.google.com/colaboratory)]\\(https://research.google.com/colaboratory)\n\nA linked URL using references:\n\n>\\[[Colaboratory][colaboratory-label]]\\[colaboratory-label]\n\n>\\[colaboratory-label]: https://research.google.com/colaboratory\n[colaboratory-label]: https://research.google.com/colaboratory\n\nAn inline image: !\\[Google's logo](https://www.google.com/images/logos/google_logo_41.png)\n>\n\nEquations:\n\n>\\$y=x^2\\$ $\\Rightarrow$ $y=x^2$\n\n>\\$e^{i\\\\pi} + 1 = 0\\$ $\\Rightarrow$ $e^{i\\pi} + 1 = 0$\n\n>\\$e^x=\\\\sum_{i=0}^\\\\infty \\\\frac{1}{i!}x^i\\$ $\\Rightarrow$ $e^x=\\sum_{i=0}^\\infty \\frac{1}{i!}x^i$\n\n>\\$\\\\frac{n!}{k!(n-k)!} = {n \\\\choose k}\\$ $\\Rightarrow$ $\\frac{n!}{k!(n-k)!} = {n \\choose k}$\n\nTables:\n>```\nFirst column name | Second column name\n--- | ---\nRow 1, Col 1 | Row 1, Col 2\nRow 2, Col 1 | Row 2, Col 2\n```\n\nbecomes:\n\n>First column name | Second column name\n>--- | ---\n>Row 1, Col 1 | Row 1, Col 2\n>Row 2, Col 1 | Row 2, Col 2\n\nHorizontal rule done with three dashes (\\-\\-\\-):\n\n---\n\n",
"_____no_output_____"
],
[
"## Differences between Colaboratory markdown and other markdown dialects\n\nColaboratory uses [marked.js](https://github.com/chjj/marked) and so is similar but not quite identical to the markdown used by Jupyter and Github.\n\nThe biggest differences are that Colaboratory supports (MathJax) $\\LaTeX$ equations like Jupyter, but does not allow HTML tags in the markdown unlike most other markdowns.\n\nSmaller differences are that Colaboratory does not support syntax highlighting in code blocks, nor does it support some GitHub additions like emojis and to-do checkboxes.\n\nIf HTML must be included in a Colaboratory notebook, see the [%%html magic](/notebooks/basic_features_overview.ipynb#scrollTo=qM4myQGfQboQ).",
"_____no_output_____"
],
[
"## Useful references",
"_____no_output_____"
],
[
"* [Github markdown basics](https://help.github.com/articles/markdown-basics/)\n* [Github flavored markdown](https://help.github.com/articles/github-flavored-markdown/)\n* [Original markdown spec: Syntax](http://daringfireball.net/projects/markdown/syntax)\n* [Original markdown spec: Basics](http://daringfireball.net/projects/markdown/basics)\n* [marked.js library used by Colaboratory](https://github.com/chjj/marked)\n* [LaTex mathematics for equations](https://en.wikibooks.org/wiki/LaTeX/Mathematics)",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cba455e40d68823b26ca9057896eb7bfefc86158
| 15,457 |
ipynb
|
Jupyter Notebook
|
nbs/112b_models.XResNet1dPlus.ipynb
|
raijinspecial/tsai
|
fe820fbf174a2c950ae7b5518f7f92de772faeed
|
[
"Apache-2.0"
] | 1 |
2021-09-16T04:35:38.000Z
|
2021-09-16T04:35:38.000Z
|
nbs/112b_models.XResNet1dPlus.ipynb
|
raijinspecial/tsai
|
fe820fbf174a2c950ae7b5518f7f92de772faeed
|
[
"Apache-2.0"
] | null | null | null |
nbs/112b_models.XResNet1dPlus.ipynb
|
raijinspecial/tsai
|
fe820fbf174a2c950ae7b5518f7f92de772faeed
|
[
"Apache-2.0"
] | 1 |
2021-08-12T20:45:07.000Z
|
2021-08-12T20:45:07.000Z
| 45.730769 | 2,820 | 0.626383 |
[
[
[
"# default_exp models.XResNet1dPlus",
"_____no_output_____"
]
],
[
[
"# XResNet1dPlus\n\n> This is a modified version of fastai's XResNet model in github. Changes include:\n* API is modified to match the default timeseriesAI's API.\n* (Optional) Uber's CoordConv 1d",
"_____no_output_____"
]
],
[
[
"#export\nfrom tsai.imports import *\nfrom tsai.models.layers import *\nfrom tsai.models.utils import *",
"_____no_output_____"
],
[
"#export\nclass XResNet1dPlus(nn.Sequential):\n @delegates(ResBlock1dPlus)\n def __init__(self, block, expansion, layers, fc_dropout=0.0, c_in=3, n_out=1000, stem_szs=(32,32,64),\n widen=1.0, sa=False, act_cls=defaults.activation, ks=3, stride=2, coord=False, **kwargs):\n store_attr('block,expansion,act_cls,ks')\n if ks % 2 == 0: raise Exception('kernel size has to be odd!')\n stem_szs = [c_in, *stem_szs]\n stem = [ConvBlock(stem_szs[i], stem_szs[i+1], ks=ks, coord=coord, stride=stride if i==0 else 1,\n act=act_cls)\n for i in range(3)]\n\n block_szs = [int(o*widen) for o in [64,128,256,512] +[256]*(len(layers)-4)]\n block_szs = [64//expansion] + block_szs\n blocks = self._make_blocks(layers, block_szs, sa, coord, stride, **kwargs)\n backbone = nn.Sequential(*stem, MaxPool(ks=ks, stride=stride, padding=ks//2, ndim=1), *blocks)\n head = nn.Sequential(AdaptiveAvgPool(sz=1, ndim=1), Flatten(), nn.Dropout(fc_dropout),\n nn.Linear(block_szs[-1]*expansion, n_out))\n super().__init__(OrderedDict([('backbone', backbone), ('head', head)]))\n self._init_cnn(self)\n\n def _make_blocks(self, layers, block_szs, sa, coord, stride, **kwargs):\n return [self._make_layer(ni=block_szs[i], nf=block_szs[i+1], blocks=l, coord=coord, \n stride=1 if i==0 else stride, sa=sa and i==len(layers)-4, **kwargs)\n for i,l in enumerate(layers)]\n\n def _make_layer(self, ni, nf, blocks, coord, stride, sa, **kwargs):\n return nn.Sequential(\n *[self.block(self.expansion, ni if i==0 else nf, nf, coord=coord, stride=stride if i==0 else 1,\n sa=sa and i==(blocks-1), act_cls=self.act_cls, ks=self.ks, **kwargs)\n for i in range(blocks)])\n \n def _init_cnn(self, m):\n if getattr(self, 'bias', None) is not None: nn.init.constant_(self.bias, 0)\n if isinstance(self, (nn.Conv1d,nn.Conv2d,nn.Conv3d,nn.Linear)): nn.init.kaiming_normal_(self.weight)\n for l in m.children(): self._init_cnn(l)",
"_____no_output_____"
],
[
"#export\ndef _xresnetplus(expansion, layers, **kwargs):\n return XResNet1dPlus(ResBlock1dPlus, expansion, layers, **kwargs)",
"_____no_output_____"
],
[
"#export\n@delegates(ResBlock)\ndef xresnet1d18plus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [2, 2, 2, 2], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d34plus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [3, 4, 6, 3], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d50plus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(4, [3, 4, 6, 3], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d101plus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(4, [3, 4, 23, 3], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d152plus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(4, [3, 8, 36, 3], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d18_deepplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [2,2,2,2,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d34_deepplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [3,4,6,3,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d50_deepplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(4, [3,4,6,3,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d18_deeperplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [2,2,1,1,1,1,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d34_deeperplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(1, [3,4,6,3,1,1,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)\n@delegates(ResBlock)\ndef xresnet1d50_deeperplus (c_in, c_out, act=nn.ReLU, **kwargs): return _xresnetplus(4, [3,4,6,3,1,1,1,1], c_in=c_in, n_out=c_out, act_cls=act, **kwargs)",
"_____no_output_____"
],
[
"net = xresnet1d18plus(3, 2, coord=True)\nx = torch.rand(32, 3, 50)\nnet(x)",
"_____no_output_____"
],
[
"bs, c_in, seq_len = 2, 4, 32\nc_out = 2\nx = torch.rand(bs, c_in, seq_len)\narchs = [\n xresnet1d18plus, xresnet1d34plus, xresnet1d50plus, \n xresnet1d18_deepplus, xresnet1d34_deepplus, xresnet1d50_deepplus, xresnet1d18_deeperplus,\n xresnet1d34_deeperplus, xresnet1d50_deeperplus\n# # Long test\n# xresnet1d101, xresnet1d152,\n]\nfor i, arch in enumerate(archs):\n print(i, arch.__name__)\n test_eq(arch(c_in, c_out, sa=True, act=Mish, coord=True)(x).shape, (bs, c_out))",
"0 xresnet1d18plus\n1 xresnet1d34plus\n2 xresnet1d50plus\n3 xresnet1d18_deepplus\n4 xresnet1d34_deepplus\n5 xresnet1d50_deepplus\n6 xresnet1d18_deeperplus\n7 xresnet1d34_deeperplus\n8 xresnet1d50_deeperplus\n"
],
[
"m = xresnet1d34plus(4, 2, act=Mish)\ntest_eq(len(get_layers(m, is_bn)), 38)\ntest_eq(check_weight(m, is_bn)[0].sum(), 22)",
"_____no_output_____"
],
[
"# hide\nout = create_scripts()\nbeep(out)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba463f0987e829e7dfb4c624acc43cb7495f0be
| 5,117 |
ipynb
|
Jupyter Notebook
|
Chapter05/gradflow/notebooks/random_custom_logging_model.ipynb
|
waltatgit/Machine-Learning-Engineering-with-MLflow
|
42887869d9528356572c104392122cac5cdbf62c
|
[
"MIT"
] | 49 |
2021-07-09T14:02:17.000Z
|
2022-03-27T14:16:11.000Z
|
Chapter05/gradflow/notebooks/random_custom_logging_model.ipynb
|
waltatgit/Machine-Learning-Engineering-with-MLflow
|
42887869d9528356572c104392122cac5cdbf62c
|
[
"MIT"
] | 11 |
2021-09-01T12:45:50.000Z
|
2022-03-02T18:10:50.000Z
|
Chapter05/gradflow/notebooks/random_custom_logging_model.ipynb
|
waltatgit/Machine-Learning-Engineering-with-MLflow
|
42887869d9528356572c104392122cac5cdbf62c
|
[
"MIT"
] | 31 |
2021-07-22T05:59:07.000Z
|
2022-03-31T20:54:35.000Z
| 29.923977 | 865 | 0.625366 |
[
[
[
"#Importing MLFlow",
"_____no_output_____"
]
],
[
[
"import mlflow\n",
"_____no_output_____"
]
],
[
[
"# Retrieve Data",
"_____no_output_____"
]
],
[
[
"class RandomPredictor(mlflow.pyfunc.PythonModel):\n def __init__(self):\n pass\n\n def fit(self):\n pass\n\n def predict(self, context, model_input):\n return model_input.apply(lambda column: random.randint(0,1))\n",
"_____no_output_____"
]
],
[
[
"# Set Experiment",
"_____no_output_____"
]
],
[
[
"\nmlflow.set_experiment(\"Baseline_Predictions\")",
"_____no_output_____"
]
],
[
[
"# Create model",
"_____no_output_____"
]
],
[
[
"mlflow.sklearn.autolog()\nmodel = LogisticRegression()",
"_____no_output_____"
]
],
[
[
"# Run the model",
"_____no_output_____"
]
],
[
[
"with mlflow.start_run(run_name='logistic_regression_model_baseline') as run:\n model.fit(X_train, y_train)\n preds = model.predict(X_test)\n y_pred = np.where(preds>0.5,1,0)\n f1 = f1_score(y_test, y_pred)\n mlflow.log_metric(key=\"f1_experiment_score\", value=f1)",
"2021/02/16 09:53:44 INFO mlflow.utils.autologging_utils: sklearn autologging will track hyperparameters, performance metrics, model artifacts, and lineage information for the current sklearn workflow to the MLflow run with ID '14a8e87829524ff8b9f3ab0f70366271'\n2021/02/16 09:53:45 WARNING mlflow.utils.autologging_utils: MLflow issued a warning during sklearn autologging: \"/opt/conda/lib/python3.7/site-packages/mlflow/models/signature.py:123: UserWarning: Hint: Inferred schema contains integer column(s). Integer columns in Python cannot represent missing values. If your input data contains missing values at inference time, it will be encoded as floats and will cause a schema enforcement error. The best way to avoid this problem is to infer the model schema based on a realistic data sample (training dataset) that includes missing values. Alternatively, you can declare integer columns as doubles (float64) whenever these columns may have missing values. See `Handling Integers With Missing Values <https://www.mlflow.org/docs/latest/models.html#handling-integers-with-missing-values>`_ for more details.\"\n2021/02/16 09:53:45 WARNING mlflow.utils.autologging_utils: MLflow issued a warning during sklearn autologging: \"/opt/conda/lib/python3.7/site-packages/mlflow/models/signature.py:124: UserWarning: Hint: Inferred schema contains integer column(s). Integer columns in Python cannot represent missing values. If your input data contains missing values at inference time, it will be encoded as floats and will cause a schema enforcement error. The best way to avoid this problem is to infer the model schema based on a realistic data sample (training dataset) that includes missing values. Alternatively, you can declare integer columns as doubles (float64) whenever these columns may have missing values. See `Handling Integers With Missing Values <https://www.mlflow.org/docs/latest/models.html#handling-integers-with-missing-values>`_ for more details.\"\n"
],
[
"f1",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cba489bc1fba06b92a8d23a27046838080f94b5a
| 20,731 |
ipynb
|
Jupyter Notebook
|
bikeshare/modelling.ipynb
|
pauchan/kaggle
|
66258c10703019c5c25a9b65fa8a89bce7a03d9d
|
[
"MIT"
] | null | null | null |
bikeshare/modelling.ipynb
|
pauchan/kaggle
|
66258c10703019c5c25a9b65fa8a89bce7a03d9d
|
[
"MIT"
] | null | null | null |
bikeshare/modelling.ipynb
|
pauchan/kaggle
|
66258c10703019c5c25a9b65fa8a89bce7a03d9d
|
[
"MIT"
] | null | null | null | 75.660584 | 7,092 | 0.817857 |
[
[
[
"# cleanup data and put them in the new csv files\n\nimport numpy as np\nimport scipy \nimport pandas as pd\nfrom sklearn import tree, ensemble, linear_model, svm, cross_validation, grid_search\nimport math\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\n%matplotlib inline\n\n## load test data (this one does not need any more preprocessing)\ntest = np.genfromtxt(\"data/clean/test.csv\",delimiter=\",\",skip_header=1)\n\n#A function to calculate Root Mean Squared Logarithmic Error (RMSLE)\ndef rmsle(y, y_pred):\n assert len(y) == len(y_pred)\n terms_to_sum = [(math.log(y_pred[i] + 1) - math.log(y[i] + 1)) ** 2.0 for i,pred in enumerate(y_pred)]\n return (sum(terms_to_sum) * (1.0/len(y))) ** 0.5\n\ndef normalize(x):\n return (x - x.mean()) / (x.max() - x.min())\n\n# combine results\ndef output_results(predictions):\n test_t = pd.read_csv(\"data/original/test.csv\")\n dates = test_t[\"datetime\"]\n predictions = np.maximum(predictions,0.0)\n results = pd.DataFrame(predictions)\n dates = pd.DataFrame(dates)\n x = pd.concat([dates,results],axis=1)\n x.columns = [\"datetime\",\"count\"]\n x.to_csv(\"data/result.csv\",delimiter=\",\",index=False)\n\n# set up two histograms to see how the distribution of variables \n# looks for the training and test labels\ndef hist_evaluate(train_lab, svr_pred):\n n, bins, patches = plt.hist(train_lab, 50, normed=1, facecolor='green', alpha=0.75)\n plt.show()\n\n n, bins, patches = plt.hist(svr_pred, 50, normed=1, facecolor='green', alpha=0.75)\n plt.show()",
"_____no_output_____"
],
[
"# import data to numpy\ndef process_train():\n train_comp = np.genfromtxt(\"data/clean/train.csv\",delimiter=\",\",skip_header=1)\n # split data into train and validation\n np.random.shuffle(train_comp)\n y = train_comp[:,0]\n x = np.delete(train_comp,0,1)\n return cross_validation.train_test_split(x,y, test_size=0.4, random_state=1)",
"_____no_output_____"
],
[
"(train,valid,train_lab,valid_lab) = process_train()",
"_____no_output_____"
],
[
"# first attempt - SVR with all parameters\n\nsvr = svm.SVR()\nsvr.fit(train,train_lab)\nsvr_pred = svr.predict(valid)\n",
"_____no_output_____"
],
[
"rmsle(valid_lab, svr_pred)\n# outputs around 1.43, terrible",
"_____no_output_____"
],
[
"# SVR with a limited columns\n# it might make sense to try to use smaller set of vars: 1,2,5\ntemp_train = train[:,[1,2,5,6]]\ntemp_valid = valid[:,[1,2,5,6]]\nparameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}\nsvr_min = svm.SVR()\nclf_svr_min = grid_search.GridSearchCV(svr_min,parameters)\nclf_svr_min.fit(temp_train,train_lab)\nsvr_min_pred = clf_svr_min.predict(temp_valid)",
"_____no_output_____"
],
[
"# SVR with a limited columns\n# result evaluation\n\nprint svr_min_pred.min()\nsvr_min_pred = np.maximum(svr_min_pred,0.0)\nprint rmsle(valid_lab, svr_min_pred)\nhist_evaluate(valid_lab, svr_min_pred)\n\n# result: 0.53",
"-1.99889322389\n0.535132859349\n"
],
[
"temp_test = test[:,[1,2,5,6]]\nsvr_min_test_predict = clf_svr_min.predict(temp_test)\noutput_results(svr_min_test_predict)",
"_____no_output_____"
],
[
"test[:,0]",
"_____no_output_____"
],
[
"# random forest classifier\n\nclf_forest = ensemble.RandomForestRegressor()\nclf_forest.fit(train,train_lab)\nsvr_pred_forest = clf_forest.predict(valid)\n\nprint svr_pred.min()\nprint svr_pred.max()\n\nrmsle(valid_lab, svr_pred)",
"1.0\n977.0\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba48b7af668557190fb6cbe2261295615b8cc00
| 20,637 |
ipynb
|
Jupyter Notebook
|
nbs/00_data.ipynb
|
BorjaRequena/AnDi-unicorns
|
0e8eae2bb66f55629458ad0c90e463c2be920b16
|
[
"Apache-2.0"
] | null | null | null |
nbs/00_data.ipynb
|
BorjaRequena/AnDi-unicorns
|
0e8eae2bb66f55629458ad0c90e463c2be920b16
|
[
"Apache-2.0"
] | null | null | null |
nbs/00_data.ipynb
|
BorjaRequena/AnDi-unicorns
|
0e8eae2bb66f55629458ad0c90e463c2be920b16
|
[
"Apache-2.0"
] | 2 |
2021-05-03T14:45:31.000Z
|
2021-11-05T14:08:23.000Z
| 39.610365 | 139 | 0.544701 |
[
[
[
"#export\nfrom pathlib import Path\nimport urllib.request as u_request\nfrom zipfile import ZipFile\nimport csv \nimport pandas as pd\nfrom andi import andi_datasets, normalize\nimport numpy as np\n\nfrom fastai.text.all import *",
"_____no_output_____"
],
[
"#hide\nfrom nbdev.showdoc import *",
"_____no_output_____"
],
[
"# default_exp data",
"_____no_output_____"
]
],
[
[
"# Data\n\n> Here we deal with the data acquisition and processing.",
"_____no_output_____"
],
[
"## Data acquirement",
"_____no_output_____"
]
],
[
[
"#export\nDATA_PATH = Path(\"../data\")",
"_____no_output_____"
],
[
"#export\ndef acquire_data(train=True, val=True):\n \"\"\"Obtains the train and validation datasets of the competition. \n The train url maight fail. Get it from https://drive.google.com/drive/folders/1RXziMCO4Y0Fmpm5bmjcpy-Genhzv4QJ4\"\"\"\n DATA_PATH.mkdir(exist_ok=True)\n \n train_url = (\"https://doc-4k-88-drive-data-export.googleusercontent.com/download/qh9kfuk2n3khcj0qvrn9t3a4j19nve1a/\" + \n \"rqpd3tajosn0gta5f9mmbbb1e4u8csnn/1599642000000/17390da5-4567-4189-8a62-1749e1b19b06/108540842544374891611/\" + \n \"ADt3v-N9HwRAxXINIFMKGcsrjzMlrvhOOYitRyphFom1Ma-CUUekLTkDp75fOegXlyeVVrTPjlnqDaK0g6iI7eDL9YJw91-\" + \n \"jiityR3iTfrysZP6hpGA62c4lkZbjGp_NJL-XSDUlPcwiVi5Hd5rFtH1YYP0tiiFCoJZsTT4akE8fjdrkZU7vaqFznxuyQDA8YGaiuYlKu\" + \n \"-F1HiAc9kG_k9EMgkMncNflNJtlugxH5pFcNDdrYiOzIINRIRivt5ScquQ_s4KyuV-zYOQ_g2_VYri8YAg0IqbBrcO-exlp5j-\" +\n \"t02GDh5JZKU3Hky5b70Z8brCL5lvK0SFAFIKOer45ZrFaACA3HGRNJg==?authuser=0&nonce=k5g7m53pp3cqq&user=\" + \n \"108540842544374891611&hash=m7kmrh87gmekjhrdcpbhuf1kj13ui0l2\")\n val_url = (\"https://competitions.codalab.org/my/datasets/download/7ea12913-dfcf-4a50-9f5d-8bf9666e9bb4\")\n\n if train: \n data = _download_bytes(train_url)\n _write_bytes(data, DATA_PATH)\n train_path = DATA_PATH/\"Development dataset for Training\"\n train_path.rename(train_path.parent/\"train\")\n \n if val: \n data = _download_bytes(val_url)\n _write_bytes(data, DATA_PATH)\n val_path = DATA_PATH/\"validation_for_scoring\"\n val_path.rename(val_path.parent/\"val\")\n \n rmtree(DATA_PATH/\"__MACOSX\")\n \ndef _download_bytes(url):\n \"Downloads data from `url` as bytes\"\n u = u_request.urlopen(url)\n data = u.read()\n u.close()\n return data\n\ndef _write_bytes(data, path):\n \"Saves `data` (bytes) into path.\"\n zip_path = _zip_bytes(data)\n _unzip_file(zip_path, new_path=path)\n\ndef _zip_bytes(data, path=None):\n \"Saves bytes data as .zip in `path`.\"\n if path is None: path = Path(\"../temp\")\n zip_path = path.with_suffix(\".zip\")\n with open(zip_path, \"wb\") as f:\n f.write(data)\n return zip_path\n \ndef _unzip_file(file_path, new_path=None, purge=True):\n \"Unzips file in `file_path` to `new_path`.\"\n if new_path is None: new_path = file_path.with_suffix(\"\")\n zip_path = file_path.with_suffix(\".zip\")\n with ZipFile(zip_path, 'r') as f:\n f.extractall(new_path)\n if purge: zip_path.unlink()\n \ndef rmtree(root):\n for p in root.iterdir():\n if p.is_dir(): rmtree(p)\n else: p.unlink()\n root.rmdir()",
"_____no_output_____"
],
[
"df = pd.DataFrame(columns=['dim', 'model', 'exp', 'x', 'len'], dtype=object)\nfor dim in range(1, 4):\n trajs = pd.read_pickle(DATA_PATH/f\"custom_val/dataset_{dim}D_task_2.pkl\")['dataset_og_t2']\n for traj in trajs:\n model, exp, x = traj[0], traj[1], traj[2:] \n x = tensor(x).view(dim,-1).T\n x = x[:torch.randint(10, 1000, (1,))]\n df = df.append({'dim': dim, 'model': model, 'exp': exp, 'x': x, 'len': len(x)}, ignore_index=True)\n \n df.to_pickle(DATA_PATH/f\"custom_val/custom_{dim}D.pkl\")",
"_____no_output_____"
]
],
[
[
"## Data conditioning",
"_____no_output_____"
]
],
[
[
"#export\ndef load_custom_data(dim=1, models=None, exps=None, path=None):\n \"Loads data from custom dataset.\"\n path = DATA_PATH/f\"custom{dim}.pkl\" if path is None else path\n df = pd.read_pickle(path)\n mod_mask = sum([df['model'] == m for m in models]) if models is not None else np.ones(df.shape[0], dtype=bool)\n exp_mask = sum([df['exp'] == e for e in exps]) if exps is not None else np.ones(df.shape[0], dtype=bool)\n mask = mod_mask & exp_mask \n return df[mask].reset_index(drop=True)\n \ndef load_data(task, dim=1, ds='train'):\n \"Loads 'train' or 'val' data of corresponding dimension.\"\n path = DATA_PATH/ds\n try: \n df = pd.read_pickle(path/f\"task{task}.pkl\")\n except: \n _txt2df(task, ds=[ds])\n df = pd.read_pickle(path/f\"task{task}.pkl\") \n return df[df['dim']==dim].reset_index(drop=True)\n\ndef _txt2df(task, ds=['train', 'val']):\n \"Extracts dataset and saves it in df form\"\n if 'train' in ds:\n df = pd.DataFrame(columns=['dim', 'y', 'x', 'len'], dtype=object)\n train_path = DATA_PATH/\"train\"\n if not (train_path/f\"task{task}.txt\").exists(): acquire_data(train=True, val=False)\n with open(train_path/f\"task{task}.txt\", \"r\") as D, open(train_path/f\"ref{task}.txt\") as Y:\n trajs = csv.reader(D, delimiter=\";\", lineterminator=\"\\n\", quoting=csv.QUOTE_NONNUMERIC)\n labels = csv.reader(Y, delimiter=\";\", lineterminator=\"\\n\", quoting=csv.QUOTE_NONNUMERIC)\n for t, y in zip(trajs, labels):\n dim, x = int(t[0]), t[1:]\n x = tensor(x).view(dim, -1).T\n label = tensor(y[1:]) if task is 3 else y[1]\n df = df.append({'dim': dim, 'y': label, 'x': x, 'len': len(x)}, ignore_index=True)\n\n df.to_pickle(train_path/f\"task{task}.pkl\")\n \n if 'val' in ds: \n df = pd.DataFrame(columns=['dim', 'x', 'len'], dtype=object)\n val_path = DATA_PATH/\"val\"\n task_path = val_path/f\"task{task}.txt\"\n if not task_path.exists(): acquire_data(train=False, val=True)\n with open(task_path, \"r\") as D:\n trajs = csv.reader(D, delimiter=\";\", lineterminator=\"\\n\", quoting=csv.QUOTE_NONNUMERIC)\n for t in trajs:\n dim, x = int(t[0]), t[1:]\n x = tensor(x).view(dim, -1).T\n df = df.append({'dim': dim, 'x': x, 'len': len(x)}, ignore_index=True)\n \n df['y'] = \"\"\n df.to_pickle(val_path/f\"task{task}.pkl\")",
"_____no_output_____"
]
],
[
[
"## Dataloaders",
"_____no_output_____"
]
],
[
[
"#export\ndef pad_trajectories(samples, pad_value=0, pad_first=True, backwards=False):\n \"Pads trajectories assuming shape (len, dim)\"\n max_len = max([s.shape[0] for s, _ in samples])\n if backwards: pad_first = not pad_first\n def _pad_sample(s):\n s = normalize_trajectory(s)\n diff = max_len - s.shape[0]\n pad = s.new_zeros((diff, s.shape[1])) + pad_value\n pad_s = torch.cat([pad, s] if pad_first else [s, pad])\n if backwards: pad_s = pad_s.flip(0)\n return pad_s\n return L((_pad_sample(s), y) for s, y in samples)\n\ndef normalize_trajectory(traj):\n \"Normalizes the trajectory displacements.\"\n n_traj = torch.zeros_like(traj)\n disp = traj[1:]-traj[:-1]\n n_traj[1:] = disp.div_(disp.std(0)).cumsum(0)\n return n_traj",
"_____no_output_____"
],
[
"#export\n@delegates(pad_trajectories)\ndef get_custom_dls(target='model', dim=1, models=None, exps=None, bs=128, split_pct=0.2, path=None, balance=False, **kwargs):\n \"Obtain `DataLoaders` from custom dataset filtered by `models` and `exps` to predict `target`.\"\n data = load_custom_data(dim=dim, models=models, exps=exps, path=path)\n if balance: data = _subsample_df(data)\n ds = L(zip(data['x'], data[target])) if target is 'exp' else L(zip(data['x'], data[target].astype(int)))\n sorted_dl = partial(SortedDL, before_batch=partial(pad_trajectories, **kwargs), shuffle=True)\n return get_dls_from_ds(ds, sorted_dl, split_pct=split_pct, bs=bs)\n \n@delegates(pad_trajectories)\ndef get_discriminative_dls(task, dim=1, bs=128, split_pct=0.2, ds='train', **kwargs):\n \"Obtain `DataLoaders` for classification/regression models.\"\n data = load_data(task, dim=dim, ds=ds)\n ds = L(zip(data['x'], data['y'])) if task==1 else L(zip(data['x'], data['y'].astype(int)))\n sorted_dl = partial(SortedDL, before_batch=partial(pad_trajectories, **kwargs), shuffle=True)\n return get_dls_from_ds(ds, sorted_dl, split_pct=split_pct, bs=bs)\n\n@delegates(SortedDL.__init__)\ndef get_turning_point_dls(task=3, dim=1, bs=128, split_pct=0.2, ds='train', **kwargs):\n \"Obtain `DataLoaders` to predict change points in trajecotries.\"\n data = load_data(task, dim=dim, ds=ds)\n ds = L(zip(data['x'], torch.stack(list(data['y'].values))[:, 0]))\n sorted_dl = partial(SortedDL, shuffle=True, **kwargs)\n return get_dls_from_ds(ds, sorted_dl, split_pct=split_pct, bs=bs)\n \n@delegates(pad_trajectories)\ndef get_1vall_dls(target=0, dim=1, models=None, exps=None, bs=128, split_pct=0.2, **kwargs):\n data = load_custom_data(dim=dim, models=models, exps=exps)\n x, y = data['x'], (data['model'] != target).astype(int)\n ds = L(zip(x, y)) \n sorted_dl = partial(SortedDL, before_batch=partial(pad_trajectories, **kwargs), shuffle=True)\n return get_dls_from_ds(ds, sorted_dl, split_pct=split_pct, bs=bs)\n \n@delegates(pad_trajectories)\ndef get_validation_dl(task, dim=1, bs=64, ds='val', **kwargs):\n \"Obtain `DataLoaders` for validation.\"\n data = load_data(task, dim=dim, ds=ds)\n ds = L(zip(data['x'], data['y']))\n return DataLoader(ds, bs=bs, before_batch=partial(pad_trajectories, **kwargs), device=default_device())\n\ndef get_dls_from_ds(ds, dl_type, split_pct=0.2, bs=128):\n idx = L(int(i) for i in torch.randperm(len(ds)))\n cut = int(len(ds)*split_pct)\n \n train_ds, val_ds = ds[idx[cut:]], ds[idx[:cut]]\n return DataLoaders.from_dsets(train_ds, val_ds, bs=bs, dl_type=dl_type, device=default_device())\n\ndef _subsample_df(df):\n \"Subsamples df to balance models\"\n models = df.model.unique()\n max_s = min([len(df[df.model==m]) for m in models])\n sub_dfs = [df[df.model==m].sample(frac=1)[:max_s] for m in models]\n return pd.concat(sub_dfs, ignore_index=True)",
"_____no_output_____"
],
[
"dls = get_discriminative_dls(task=1, dim=2)",
"_____no_output_____"
],
[
"x, y = dls.one_batch()\nx.shape, y.shape",
"_____no_output_____"
]
],
[
[
"## Custom dataset",
"_____no_output_____"
]
],
[
[
"#export\ndef create_custom_dataset(N, max_T=1000, min_T=10, dimensions=[1, 2, 3], save=True):\n ad = andi_datasets()\n exponents = np.arange(0.05, 2.01, 0.05)\n n_exp, n_models = len(exponents), len(ad.avail_models_name)\n # Trajectories per model and exponent. Arbitrarely chose to fulfill balanced classes\n N_per_model = np.ceil(1.6*N/5)\n subdif, superdif = n_exp//2, n_exp//2+1\n num_per_class = np.zeros((n_models, n_exp))\n num_per_class[:2,:subdif] = np.ceil(N_per_model/subdif) # ctrw, attm\n num_per_class[2, :] = np.ceil(N_per_model/(n_exp-1)) # fbm\n num_per_class[2, exponents == 2] = 0 # fbm can't be ballistic\n num_per_class[3, subdif:] = np.ceil((N_per_model/superdif)*0.8) # lw\n num_per_class[4, :] = np.ceil(N_per_model/n_exp) # sbm\n \n for dim in dimensions: \n dataset = ad.create_dataset(T=max_T, N=num_per_class, exponents=exponents, \n dimension=dim, models=np.arange(n_models)) \n\n # Normalize trajectories\n n_traj = dataset.shape[0]\n norm_trajs = normalize(dataset[:, 2:].reshape(n_traj*dim, max_T))\n dataset[:, 2:] = norm_trajs.reshape(dataset[:, 2:].shape)\n\n # Add localization error, Gaussian noise with sigma = [0.1, 0.5, 1]\n loc_error_amplitude = np.random.choice(np.array([0.1, 0.5, 1]), size=n_traj*dim)\n loc_error = (np.random.randn(n_traj*dim, int(max_T)).transpose()*loc_error_amplitude).transpose()\n dataset = ad.create_noisy_localization_dataset(dataset, dimension=dim, T=max_T, noise_func=loc_error)\n \n # Add random diffusion coefficients\n trajs = dataset[:, 2:].reshape(n_traj*dim, max_T)\n displacements = trajs[:, 1:] - trajs[:, :-1]\n # Get new diffusion coefficients and displacements\n diffusion_coefficients = np.random.randn(trajs.shape[0])\n new_displacements = (displacements.transpose()*diffusion_coefficients).transpose() \n # Generate new trajectories and add to dataset\n new_trajs = np.cumsum(new_displacements, axis=1)\n new_trajs = np.concatenate((np.zeros((new_trajs.shape[0], 1)), new_trajs), axis=1)\n dataset[:, 2:] = new_trajs.reshape(dataset[:, 2:].shape)\n \n df = pd.DataFrame(columns=['dim', 'model', 'exp', 'x', 'len'], dtype=object)\n for traj in dataset:\n mod, exp, x = int(traj[0]), traj[1], traj[2:]\n x = cut_trajectory(x, np.random.randint(min_T, max_T), dim=dim)\n x = tensor(x).view(dim, -1).T\n df = df.append({'dim': dim, 'model': mod, 'exp': exp, 'x': x, 'len': len(x)}, ignore_index=True)\n \n if save:\n DATA_PATH.mkdir(exist_ok=True)\n ds_path = DATA_PATH/f\"custom{dim}.pkl\"\n df.to_pickle(ds_path, protocol=pickle.HIGHEST_PROTOCOL)\n \n return df\n\ndef cut_trajectory(traj, t_cut, dim=1):\n \"Takes a trajectory and cuts it to `T_max` length.\"\n cut_traj = traj.reshape(dim, -1)[:, :t_cut]\n return cut_traj.reshape(1, -1)",
"_____no_output_____"
],
[
"df = create_custom_dataset(20, max_T=25, save=False)",
"/home/brequena/anaconda3/lib/python3.7/site-packages/andi/diffusion_models.py:189: RuntimeWarning: overflow encountered in power\n dt = (1-np.random.rand(T))**(-1/sigma)\n/home/brequena/anaconda3/lib/python3.7/site-packages/andi/diffusion_models.py:308: RuntimeWarning: overflow encountered in power\n dt = (1-np.random.rand(T))**(-1/sigma)\n"
]
],
[
[
"## Validation",
"_____no_output_____"
]
],
[
[
"#export\ndef validate_model(model, task, dim=1, bs=256, act=False, **kwargs):\n \"Validates model on specific task and dimension.\"\n val_dl = get_validation_dl(task, dim=dim, bs=bs, **kwargs)\n if act: return torch.cat([to_detach(model(batch)[0].softmax(1)) for batch, _ in val_dl]) \n else: return torch.cat([to_detach(model(batch)) for batch, _ in val_dl]) \n \n@delegates(validate_model)\ndef validate_task(models, task, dims, **kwargs):\n \"Validates `models` on task for `dims`.\"\n if not hasattr(models, '__iter__'): models = [models]\n if not hasattr(dims, '__iter__'): dims = [dims]\n if len(models) != len(dims): \n raise InputError(f\"There are {len(models)} models and {len(dims)} dimensions\")\n pred_path = DATA_PATH/\"preds\"\n pred_path.mkdir(exist_ok=True)\n task_path = pred_path/f\"task{task}.txt\"\n preds_dim = []\n for model, dim in zip(models, dims): preds_dim.append(validate_model(model, task, dim=dim, **kwargs))\n \n with open(task_path, \"w\") as f:\n for dim, preds in zip(dims, preds_dim):\n for pred in preds:\n f.write(f\"{int(dim)}; {';'.join(str(i.item()) for i in pred)}\\n\")",
"_____no_output_____"
]
],
[
[
"# Export-",
"_____no_output_____"
]
],
[
[
"#hide\nfrom nbdev.export import notebook2script\nnotebook2script()",
"Converted 00_data.ipynb.\nConverted 01_models.ipynb.\nConverted 02_prototypes.ipynb.\nConverted 03_utils.ipynb.\nConverted 04_analysis.ipynb.\nConverted index.ipynb.\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba49980aba56ce6f7c07a13a16e4aab510a58d4
| 92,489 |
ipynb
|
Jupyter Notebook
|
analysis_checking_autocorr/analysis_autocorr.ipynb
|
peterdsharpe/StockMarketAnalysis
|
b413cbf1e85595244c0f6e135d0fec7cf6eabe13
|
[
"MIT"
] | 3 |
2020-05-21T16:47:04.000Z
|
2021-11-26T07:03:16.000Z
|
analysis_checking_autocorr/analysis_autocorr.ipynb
|
peterdsharpe/StockMarketAnalysis
|
b413cbf1e85595244c0f6e135d0fec7cf6eabe13
|
[
"MIT"
] | null | null | null |
analysis_checking_autocorr/analysis_autocorr.ipynb
|
peterdsharpe/StockMarketAnalysis
|
b413cbf1e85595244c0f6e135d0fec7cf6eabe13
|
[
"MIT"
] | 1 |
2020-07-24T04:25:01.000Z
|
2020-07-24T04:25:01.000Z
| 637.855172 | 88,871 | 0.946415 |
[
[
[
"# Analysis: Checking Autocorr\nPeter Sharpe\n\nJust want to check that my autocorrelation functions are working right.\n\nImports and data setup:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport seaborn as sns\nsns.set(font_scale=1)\n\n\ndata = pd.read_csv(\n os.path.abspath(\"../data/sp_500_max.csv\"),\n sep=\",\"\n)\nclose = data[\"Close\"].values\n\ndaily_change = close[1:] / close[:-1]\ndaily_change_pct = (daily_change - 1) * 100",
"_____no_output_____"
]
],
[
[
"### Autocorrelation\n\n\"How much does the stock market performance today correlate with the stock market performance $x$ days from now?\"\n\nIf nonzero; this implies predictive power.",
"_____no_output_____"
]
],
[
[
"forecast_max_days = 50\n\n# def autocorr(x):\n# r2=np.fft.ifft(np.abs(np.fft.fft(x))**2).real\n# c=(r2/x.shape-np.mean(x)**2)/np.std(x)**2\n# return c[:len(x)//2][:forecast_max_days+1]\n\ndef autocorr(x):\n variance = np.var(x)\n x -= np.mean(x)\n autocorrs = []\n for lag in np.arange(forecast_max_days):\n overlap = x*x if lag == 0 else x[lag:]*x[:-lag]\n autocorrs.append(\n np.mean(overlap) / variance\n )\n return autocorrs\n\nautocorr_data=autocorr(daily_change_pct)\n# autocorr_data=autocorr(close)\n\nautocorr_x=np.arange(len(autocorr_data))\n\ndef make_autocorr():\n fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200)\n plt.errorbar(\n x=autocorr_x,\n y=autocorr_data,\n yerr = 1.96/np.sqrt(len(daily_change_pct)),\n fmt=\".\",\n label=\"Autocorrelation (95% conf. int.)\"\n )\n\ndef show_autocorr():\n plt.xlabel(r\"Days into the Future\")\n plt.ylabel(r\"Normalized Autocorrelation\")\n plt.title(r\"S&P500 Autocorrelation, 1950-2018\")\n plt.tight_layout()\n plt.legend()\n # plt.savefig(\"C:/Users/User/Downloads/temp.svg\")\n plt.show()\n\nmake_autocorr()\nshow_autocorr()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba4abe3b51f53c5a3e941e950654b1e36d873ab
| 9,239 |
ipynb
|
Jupyter Notebook
|
Lao_Word2Vec.ipynb
|
PyThaiNLP/lao-language
|
504370703fbd070bec94c16314d33397bf2da5d7
|
[
"Apache-2.0"
] | 1 |
2020-03-27T18:24:53.000Z
|
2020-03-27T18:24:53.000Z
|
Lao_Word2Vec.ipynb
|
PyThaiNLP/lao-language
|
504370703fbd070bec94c16314d33397bf2da5d7
|
[
"Apache-2.0"
] | null | null | null |
Lao_Word2Vec.ipynb
|
PyThaiNLP/lao-language
|
504370703fbd070bec94c16314d33397bf2da5d7
|
[
"Apache-2.0"
] | null | null | null | 25.312329 | 257 | 0.437493 |
[
[
[
"<a href=\"https://colab.research.google.com/github/PyThaiNLP/lao-language/blob/master/Lao_Word2Vec.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Lao Word Embedding using Word2Vec\n\nData from https://traces1.inria.fr/oscar/\n\nPython | Word Embedding using Word2Vec https://www.geeksforgeeks.org/python-word-embedding-using-word2vec/",
"_____no_output_____"
]
],
[
[
"!wget https://traces1.inria.fr/oscar/files/compressed-orig/lo.txt.gz",
"_____no_output_____"
],
[
"!gunzip lo.txt.gz",
"_____no_output_____"
],
[
"ls",
"_____no_output_____"
],
[
"ls -l --block-size=M lo.txt",
"_____no_output_____"
],
[
"!pip install pythainlp",
"_____no_output_____"
],
[
"!wget https://github.com/google/language-resources/raw/master/lo/data_sets/lo_spellcheck_dict.txt",
"_____no_output_____"
],
[
"import gensim \nfrom gensim.models import Word2Vec ",
"_____no_output_____"
],
[
"from pythainlp.tokenize import Tokenizer",
"_____no_output_____"
],
[
"lao_ws = Tokenizer(\"lo_spellcheck_dict.txt\", engine = \"mm\")",
"_____no_output_____"
],
[
"with open(\"lo.txt\", \"r\",encoding=\"utf-8-sig\") as f:\n s = [i.strip() for i in f.read().split('.')]",
"_____no_output_____"
],
[
"len(s)",
"_____no_output_____"
],
[
"from tqdm import tqdm\ndata = []",
"_____no_output_____"
],
[
"# iterate through each sentence in the file \nfor i in tqdm(s): \n temp = [] \n \n # tokenize the sentence into words \n for j in lao_ws.word_tokenize(i): \n temp.append(j.lower()) \n \n data.append(temp) ",
"100%|██████████| 367841/367841 [03:43<00:00, 1644.93it/s]\n"
],
[
"#CBOW model\nmodel = gensim.models.Word2Vec(data, min_count = 1, \n size = 300, window = 5) ",
"_____no_output_____"
],
[
"print(\"Cosine similarity between 'ວຽງຈັນ' \" +\n \"and 'ເມືອງ' - Skip Gram : \", \n model.wv.similarity('ວຽງຈັນ', 'ເມືອງ')) ",
"Cosine similarity between 'ວຽງຈັນ' and 'ເມືອງ' - Skip Gram : 0.18443461\n"
],
[
"# Skip Gram model \nmodel2 = gensim.models.Word2Vec(data, min_count = 1, size = 300, \n window = 5, sg = 1) ",
"_____no_output_____"
],
[
"print(\"Cosine similarity between 'ວຽງຈັນ' \" +\n \"and 'ເມືອງ' - Skip Gram : \", \n model2.wv.similarity('ວຽງຈັນ', 'ເມືອງ')) ",
"Cosine similarity between 'ວຽງຈັນ' and 'ເມືອງ' - Skip Gram : 0.35181516\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba4b573ef7c6cba2c46de454725c3a9a50ef4a2
| 103,738 |
ipynb
|
Jupyter Notebook
|
doc/source/data_frame_sim_test_analysis.ipynb
|
OpenSourceEconomics/soepy
|
4ff40292799e248e356d614c1a7141bd35a912c9
|
[
"MIT"
] | 12 |
2018-12-17T14:46:55.000Z
|
2022-03-28T21:15:33.000Z
|
doc/source/data_frame_sim_test_analysis.ipynb
|
OpenSourceEconomics/soepy
|
4ff40292799e248e356d614c1a7141bd35a912c9
|
[
"MIT"
] | 129 |
2019-02-18T08:49:39.000Z
|
2022-03-25T16:52:08.000Z
|
doc/source/data_frame_sim_test_analysis.ipynb
|
OpenSourceEconomics/soepy
|
4ff40292799e248e356d614c1a7141bd35a912c9
|
[
"MIT"
] | 6 |
2019-02-19T15:23:40.000Z
|
2022-03-28T21:16:00.000Z
| 104.89181 | 16,636 | 0.780187 |
[
[
[
"Simulation Demonstration\n=====================",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nimport soepy",
"_____no_output_____"
]
],
[
[
"In this notebook we present descriptive statistics of a series of simulated samples with the soepy toy model.\n\nsoepy is closely aligned to the model in Blundell et. al. (2016). Yet, we wish to use the soepy package for estimation based on the German SOEP. In this simulation demonstration, some parameter values are partially set close to the parameters estimated in the seminal paper of Blundell et. al. (2016). The remainder of the parameter values are altered such that simulated wage levels and employment choice probabilities (roughly) match the statistics observed in the SOEP Data. \n- the constants in the wage process gamma_0 equal are set to ensure alignment with SOEP data.\n- the returns to experience in the wage process gamma_1 are set close to the coefficient values on gamma0, Blundell Table VIII, p. 1733\n- the part-time experience accumulation parameter is set close to the coefficient on g(P), Blundell Table VIII, p. 1733,\n- the experience depreciation parameter delta is set close to the coefffient values on delta, Blundell Table VIII, p. 1733,\n- the disutility of part-time work parameter theta_p is set to ensure alignment with SOEP data,\n- the disutility of full-time work parameter theta_f is set to ensure alignment with SOEP data.\n\nTo ensure that some individuals also choose to be non-emplyed, we set the period wage for nonemployed to be equal to some fixed value, constant over all periods. We call this income in unemployment \"benefits\".",
"_____no_output_____"
]
],
[
[
"data_frame_baseline = soepy.simulate('toy_model_init_file_01_1000.yml')",
"_____no_output_____"
],
[
"data_frame_baseline.head(20)",
"_____no_output_____"
],
[
"#Determine the observed wage given period choice\ndef get_observed_wage (row):\n if row['Choice'] == 2:\n return row['Period Wage F']\n elif row['Choice'] ==1:\n return row['Period Wage P']\n elif row['Choice'] ==0:\n return row['Period Wage N']\n else:\n return np.nan\n\n# Add to data frame\ndata_frame_baseline['Wage Observed'] = data_frame_baseline.apply(\n lambda row: get_observed_wage (row),axis=1\n)\n\n# Determine the education level\ndef get_educ_level(row):\n if row[\"Years of Education\"] >= 10 and row[\"Years of Education\"] < 12:\n return 0\n elif row[\"Years of Education\"] >= 12 and row[\"Years of Education\"] < 16:\n return 1\n elif row[\"Years of Education\"] >= 16:\n return 2\n else:\n return np.nan\n\ndata_frame_baseline[\"Educ Level\"] = data_frame_baseline.apply(\n lambda row: get_educ_level(row), axis=1\n)",
"_____no_output_____"
]
],
[
[
"Descriptive statistics to look at:\n- average part-time, full-time and nonemployment rate - ideally close to population rates\n- frequency of each choice per period - ideally more often part-time in early periods, more full-time in later periods\n- frequency of each choice over all periods for individuals with different levels of education - ideally, lower educated more often unemployed and in part-time jobs\n- average period wages over all individuals - series for all periods\n- average period individuals over all individuals - series for all periods",
"_____no_output_____"
]
],
[
[
"# Average non-employment, part-time, and full-time rates over all periods and individuals\ndata_frame_baseline['Choice'].value_counts(normalize=True).plot(kind = 'bar')\ndata_frame_baseline['Choice'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# Average non-employment, part-time, and full-time rates per period\ndata_frame_baseline.groupby(['Period'])['Choice'].value_counts(normalize=True).unstack().plot(kind = 'bar', stacked = True)",
"_____no_output_____"
]
],
[
[
"As far as the evolution of choices over all agents and periods is concerned, we first observe a declining tendency of individuals to be unemployed as desired in a perfectly calibrated simulation. Second, individuals in our simulation tend to choose full-time and non-employment less often in the later periods of the model. Rates of part-time employment increase for the same period. ",
"_____no_output_____"
]
],
[
[
"# Average non-employment, part-time, and full-time rates for individuals with different level of education\ndata_frame_baseline.groupby(['Years of Education'])['Choice'].value_counts(normalize=True).unstack().plot(kind = 'bar', stacked = True)",
"_____no_output_____"
]
],
[
[
"As should be expected, the higher the education level of the individuals the lower the observed.",
"_____no_output_____"
]
],
[
[
"# Average wage for each period and choice\nfig,ax = plt.subplots()\n\n# Generate x axes values\nperiod = np.arange(1,31)\n\n# Generate plot lines\nax.plot(period,\n data_frame_baseline[data_frame_baseline['Choice'] == 2].groupby(['Period'])['Period Wage F'].mean(),\n color='green', label = 'F')\nax.plot(period,\n data_frame_baseline[data_frame_baseline['Choice'] == 1].groupby(['Period'])['Period Wage P'].mean(),\n color='orange', label = 'P')\nax.plot(period,\n data_frame_baseline[data_frame_baseline['Choice'] == 0].groupby(['Period'])['Period Wage N'].mean(), \n color='blue', label = 'N')\n\n# Plot settings\nax.set_xlabel(\"period\")\nax.set_ylabel(\"wage\")\nax.legend(loc='best')",
"_____no_output_____"
]
],
[
[
"The period wage of non-employment actually refers to the unemployment benefits individuals receive. The amount of the benefits is constant over time. Part-time and full-time wages rise as individuals gather more experience.",
"_____no_output_____"
]
],
[
[
"# Average wages by period\ndata_frame_baseline.groupby(['Period'])['Wage Observed'].mean().plot()",
"_____no_output_____"
]
],
[
[
"Comparative Statics\n------------------------",
"_____no_output_____"
],
[
"In the following, we discuss some comparative statics of the model.\n\nWhile changing other parameter values we wish to assume that the parameters central to the part-time penalty phenomenon studied in Blundell (2016) stay the same as in the benchmark specification:\n- part-time experience accumulation g_s1,2,3\n- experience depreciation delta\n\nComparative statics:\n\nParameters in the systematic wage govern the choice between employment (either part-time, or full-time) and nonemployment. They do not determine the choice between part-time and full-time employment since the systematic wage is equal for both options.\n- constnat in wage process gamma_0: lower/higher value of the coefficient implies that other components such as accumulated work experience and the productivity shock are relatively more/less important in determining the choice between employment and nonemployment. Decreasing the constant for individuals of a certain education level, e.g., low, results in these individuals choosing nonemployment more often.\n- return to experience gamma_1: lower value of the coefficient implies that accumulated work experience is less relevant in determining the wage in comparison to other factors such as the constant or the productivity shock. Higher coefficients should lead to agents persistently choosing employment versus non-employment.\n\nThe productivity shock:\n- productivity shock variances - the higher the variances, the more switching between occupational alternatives.\n\nRisk aversion:\n- risk aversion parameter mu: the more negative the risk aversion parameter, the more eager are agents to ensure themselves against productivity shoks through accumulation of experience. Therefore, lower values of the parameter are associated with higher rates of full-time employment.\n\nThe labor disutility parameters directly influence:\n- benefits - for higher benefits individuals of all education levels would choose non-employment more often\n- labor disutility for part-time theta_p - for a higher coefficient, individuals of all education levels would choose to work part-time more often\n- labor disutility for full-time theta_f - for a higher coefficient, individuals of all education levels would choose to work part-time more often",
"_____no_output_____"
],
[
"Finally, we illustrate one of the changes discussed above. In the alternative specifications the return to experience coefficient gamma_1 for the individuals with medium level of educations is increased from 0.157 to 0.195. As a result, experience accumulation matters more in the utility maximization. Therefore, individuals with medium level of education choose to be employed more often. Consequently, also aggregate levels of nonemployment are lower in the model.",
"_____no_output_____"
]
],
[
[
"data_frame_alternative = soepy.simulate('toy_model_init_file_01_1000.yml')",
"_____no_output_____"
],
[
"# Average non-employment, part-time, and full-time rates for individuals with different level of education\n[data_frame_alternative.groupby(['Years of Education'])['Choice'].value_counts(normalize=True),\ndata_frame_baseline.groupby(['Years of Education'])['Choice'].value_counts(normalize=True)]",
"_____no_output_____"
],
[
"# Average non-employment, part-time, and full-time rates for individuals with different level of education\ndata_frame_alternative.groupby(['Years of Education'])['Choice'].value_counts(normalize=True).unstack().plot(kind = 'bar', stacked = True)",
"_____no_output_____"
],
[
"# Average non-employment, part-time, and full-time rates over all periods and individuals\ndata_frame_alternative['Choice'].value_counts(normalize=True).plot(kind = 'bar')\ndata_frame_alternative['Choice'].value_counts(normalize=True)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cba4b8ff2a65efc1ea06c4afc05c4a550b34f206
| 8,669 |
ipynb
|
Jupyter Notebook
|
docs/source/Quickstart.ipynb
|
dschmitz89/simplenlopt
|
238000f6f799a2275b1b155046b3740ab5f23014
|
[
"Apache-2.0"
] | 1 |
2021-06-28T23:01:39.000Z
|
2021-06-28T23:01:39.000Z
|
docs/source/Quickstart.ipynb
|
dschmitz89/simplenlopt
|
238000f6f799a2275b1b155046b3740ab5f23014
|
[
"Apache-2.0"
] | 1 |
2021-07-13T19:00:23.000Z
|
2021-07-13T19:00:23.000Z
|
docs/source/Quickstart.ipynb
|
dschmitz89/simplenlopt
|
238000f6f799a2275b1b155046b3740ab5f23014
|
[
"Apache-2.0"
] | null | null | null | 35.674897 | 412 | 0.611259 |
[
[
[
"# Quickstart",
"_____no_output_____"
],
[
"In this tutorial, we will show how to solve a famous optimization problem, minimizing the Rosenbrock function, in simplenlopt. First, let's define the Rosenbrock function and plot it:\n\n$$\nf(x, y) = (1-x)^2+100(y-x^2)^2\n$$",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\ndef rosenbrock(pos):\n \n x, y = pos\n return (1-x)**2 + 100 * (y - x**2)**2\n\nxgrid = np.linspace(-2, 2, 500)\nygrid = np.linspace(-1, 3, 500)\n\nX, Y = np.meshgrid(xgrid, ygrid)\n\nZ = (1 - X)**2 + 100 * (Y -X**2)**2\n\nx0=np.array([-1.5, 2.25])\nf0 = rosenbrock(x0)\n\n#Plotly not rendering correctly on Readthedocs, but this shows how it is generated! Plot below is a PNG export\nimport plotly.graph_objects as go\nfig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y, cmax = 10, cmin = 0, showscale = False)])\nfig.update_layout(\n scene = dict(zaxis = dict(nticks=4, range=[0,10])))\nfig.add_scatter3d(x=[1], y=[1], z=[0], mode = 'markers', marker=dict(size=10, color='green'), name='Optimum')\nfig.add_scatter3d(x=[-1.5], y=[2.25], z=[f0], mode = 'markers', marker=dict(size=10, color='black'), name='Initial guess')\nfig.show()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"The crux of the Rosenbrock function is that the minimum indicated by the green dot is located in a very narrow, banana shaped valley with a small slope around the minimum. Local optimizers try to find the optimum by searching the parameter space starting from an initial guess. We place the initial guess shown in black on the other side of the banana. \n\nIn simplenlopt, local optimizers are called by the minimize function. It requires the objective function and a starting point. The algorithm is chosen by the method argument. Here, we will use the derivative-free Nelder-Mead algorithm. Objective functions must be of the form ``f(x, ...)`` where ``x`` represents a numpy array holding the parameters which are optimized.",
"_____no_output_____"
]
],
[
[
"import simplenlopt\n\ndef rosenbrock(pos):\n \n x, y = pos\n return (1-x)**2 + 100 * (y - x**2)**2\n\nres = simplenlopt.minimize(rosenbrock, x0, method = 'neldermead')\nprint(\"Position of optimum: \", res.x)\nprint(\"Function value at Optimum: \", res.fun)\nprint(\"Number of function evaluations: \", res.nfev)",
"Position of optimum: [0.99999939 0.9999988 ]\nFunction value at Optimum: 4.0813291938703456e-13\nNumber of function evaluations: 232\n"
]
],
[
[
"The optimization result is stored in a class whose main attributes are the position of the optimum and the function value at the optimum. The number of function evaluations is a measure of performance: the less function evaluations are required to find the minimum, the faster the optimization will be.\n\nNext, let's switch to a derivative based solver. For better performance, we also supply the analytical gradient which is passed to the jac argument.",
"_____no_output_____"
]
],
[
[
"def rosenbrock_grad(pos):\n \n x, y = pos\n dx = 2 * x -2 - 400 * x * (y-x**2)\n dy = 200 * (y-x**2)\n \n return dx, dy\n\nres_slsqp = simplenlopt.minimize(rosenbrock, x0, method = 'slsqp', jac = rosenbrock_grad)\nprint(\"Position of optimum: \", res_slsqp.x)\nprint(\"Function value at Optimum: \", res_slsqp.fun)\nprint(\"Number of function evaluations: \", res_slsqp.nfev)",
"Position of optimum: [1. 1.]\nFunction value at Optimum: 1.53954903146237e-20\nNumber of function evaluations: 75\n"
]
],
[
[
"As the SLSQP algorithm can use gradient information, it requires less function evaluations to find the minimum than the \nderivative-free Nelder-Mead algorithm. \n\nUnlike vanilla NLopt, simplenlopt automatically defaults to finite difference approximations of the gradient if it is \nnot provided:",
"_____no_output_____"
]
],
[
[
"res = simplenlopt.minimize(rosenbrock, x0, method = 'slsqp')\nprint(\"Position of optimum: \", res.x)\nprint(\"Function value at Optimum: \", res.fun)\nprint(\"Number of function evaluations: \", res.nfev)",
"Position of optimum: [0.99999999 0.99999999]\nFunction value at Optimum: 5.553224195710645e-17\nNumber of function evaluations: 75\n"
]
],
[
[
"As the finite differences are not as precise as the analytical gradient, the found optimal function value is higher than with analytical gradient information. In general, it is aways recommended to compute the gradient analytically or by automatic differentiation as the inaccuracies of finite differences can result in wrong results and bad performance.\n\nFor demonstration purposes, let's finally solve the problem with a global optimizer. Like in SciPy, each global optimizer is called by a dedicated function such as crs() for the Controlled Random Search algorithm. Instead of a starting point, the global optimizers require a region in which they seek to find the minimum. This region is provided as a list of (lower_bound, upper_bound) for each coordinate.",
"_____no_output_____"
]
],
[
[
"bounds = [(-2., 2.), (-2., 2.)]\nres_crs = simplenlopt.crs(rosenbrock, bounds)\nprint(\"Position of optimum: \", res_crs.x)\nprint(\"Function value at Optimum: \", res_crs.fun)\nprint(\"Number of function evaluations: \", res_crs.nfev)",
"Position of optimum: [1.00000198 1.00008434]\nFunction value at Optimum: 6.45980535135501e-07\nNumber of function evaluations: 907\n"
]
],
[
[
"Note that using a global optimizer is overkill for a small problem like the Rosenbrock function: it requires many more function\nevaluations than a local optimizer. Global optimization algorithms shine in case of complex, multimodal functions where local\noptimizers converge to local minima instead of the global minimum. Check the Global Optimization page for such an example. ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba4c785bd4a1be76ac419308a31a5981d211ea0
| 359,742 |
ipynb
|
Jupyter Notebook
|
data-visualization/seaborn/2_categorical_plots.ipynb
|
pbgnz/ds-ml
|
45cb4756e20aa5f4e4077437faee18633ca9a0e5
|
[
"MIT"
] | null | null | null |
data-visualization/seaborn/2_categorical_plots.ipynb
|
pbgnz/ds-ml
|
45cb4756e20aa5f4e4077437faee18633ca9a0e5
|
[
"MIT"
] | null | null | null |
data-visualization/seaborn/2_categorical_plots.ipynb
|
pbgnz/ds-ml
|
45cb4756e20aa5f4e4077437faee18633ca9a0e5
|
[
"MIT"
] | null | null | null | 455.946768 | 38,140 | 0.930139 |
[
[
[
"# Categorical Data Plots\n\nNow let's discuss using seaborn to plot categorical data! There are a few main plot types for this:\n\n* factorplot\n* boxplot\n* violinplot\n* stripplot\n* swarmplot\n* barplot\n* countplot\n\nLet's go through examples of each!",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"tips = sns.load_dataset('tips')\ntips.head()",
"_____no_output_____"
]
],
[
[
"## barplot and countplot\n\nThese very similar plots allow you to get aggregate data off a categorical feature in your data. **barplot** is a general plot that allows you to aggregate the categorical data based off some function, by default the mean:",
"_____no_output_____"
]
],
[
[
"sns.barplot(x='sex',y='total_bill',data=tips)",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"You can change the estimator object to your own function, that converts a vector to a scalar:",
"_____no_output_____"
]
],
[
[
"sns.barplot(x='sex',y='total_bill',data=tips,estimator=np.std)",
"_____no_output_____"
]
],
[
[
"### countplot\n\nThis is essentially the same as barplot except the estimator is explicitly counting the number of occurrences. Which is why we only pass the x value:",
"_____no_output_____"
]
],
[
[
"sns.countplot(x='sex',data=tips)",
"_____no_output_____"
]
],
[
[
"## boxplot and violinplot\n\nboxplots and violinplots are used to shown the distribution of categorical data. A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range.",
"_____no_output_____"
]
],
[
[
"sns.boxplot(x=\"day\", y=\"total_bill\", data=tips,palette='rainbow')",
"_____no_output_____"
],
[
"# Can do entire dataframe with orient='h'\nsns.boxplot(data=tips,palette='rainbow',orient='h')",
"_____no_output_____"
],
[
"sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",data=tips, palette=\"coolwarm\")",
"_____no_output_____"
]
],
[
[
"### violinplot\nA violin plot plays a similar role as a box and whisker plot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared. Unlike a box plot, in which all of the plot components correspond to actual datapoints, the violin plot features a kernel density estimation of the underlying distribution.",
"_____no_output_____"
]
],
[
[
"sns.violinplot(x=\"day\", y=\"total_bill\", data=tips,palette='rainbow')",
"_____no_output_____"
],
[
"sns.violinplot(x=\"day\", y=\"total_bill\", data=tips,hue='sex',palette='Set1')",
"_____no_output_____"
],
[
"sns.violinplot(x=\"day\", y=\"total_bill\", data=tips,hue='sex',split=True,palette='Set1')",
"_____no_output_____"
]
],
[
[
"## stripplot and swarmplot\nThe stripplot will draw a scatterplot where one variable is categorical. A strip plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution.\n\nThe swarmplot is similar to stripplot(), but the points are adjusted (only along the categorical axis) so that they don’t overlap. This gives a better representation of the distribution of values, although it does not scale as well to large numbers of observations (both in terms of the ability to show all the points and in terms of the computation needed to arrange them).",
"_____no_output_____"
]
],
[
[
"sns.stripplot(x=\"day\", y=\"total_bill\", data=tips)",
"_____no_output_____"
],
[
"sns.stripplot(x=\"day\", y=\"total_bill\", data=tips,jitter=True)",
"_____no_output_____"
],
[
"sns.stripplot(x=\"day\", y=\"total_bill\", data=tips,jitter=True,hue='sex',palette='Set1')",
"_____no_output_____"
],
[
"sns.stripplot(x=\"day\", y=\"total_bill\", data=tips,jitter=True,hue='sex',palette='Set1',split=True)",
"_____no_output_____"
],
[
"sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips)",
"_____no_output_____"
],
[
"sns.swarmplot(x=\"day\", y=\"total_bill\",hue='sex',data=tips, palette=\"Set1\", split=True)",
"_____no_output_____"
]
],
[
[
"### Combining Categorical Plots",
"_____no_output_____"
]
],
[
[
"sns.violinplot(x=\"tip\", y=\"day\", data=tips,palette='rainbow')\nsns.swarmplot(x=\"tip\", y=\"day\", data=tips,color='black',size=3)",
"_____no_output_____"
]
],
[
[
"## factorplot\n\nfactorplot is the most general form of a categorical plot. It can take in a **kind** parameter to adjust the plot type:",
"_____no_output_____"
]
],
[
[
"sns.factorplot(x='sex',y='total_bill',data=tips,kind='bar')",
"_____no_output_____"
]
],
[
[
"# Great Job!",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba4dfe93f64eed93126e8eb4314ea39341e16ee
| 588,187 |
ipynb
|
Jupyter Notebook
|
docs/lectures/lecture05/notes/cs109b_lab2_smooths_and_GAMs_2021.ipynb
|
DavidAssaraf106/2021-CS109B
|
502970bf8bb653222eade0ff42d1fc2c54d3fa74
|
[
"MIT"
] | 2 |
2021-02-06T02:56:05.000Z
|
2021-03-24T22:53:43.000Z
|
docs/lectures/lecture05/notes/cs109b_lab2_smooths_and_GAMs_2021.ipynb
|
DavidAssaraf106/2021-CS109B
|
502970bf8bb653222eade0ff42d1fc2c54d3fa74
|
[
"MIT"
] | null | null | null |
docs/lectures/lecture05/notes/cs109b_lab2_smooths_and_GAMs_2021.ipynb
|
DavidAssaraf106/2021-CS109B
|
502970bf8bb653222eade0ff42d1fc2c54d3fa74
|
[
"MIT"
] | null | null | null | 382.187784 | 52,644 | 0.931722 |
[
[
[
"# <img style=\"float: left; padding-right: 10px; width: 45px\" src=\"https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png\"> CS109B Data Science 2: Advanced Topics in Data Science \n## Lecture 5.5 - Smoothers and Generalized Additive Models - Model Fitting\n\n<div class=\"discussion\"><b>JUST A NOTEBOOK</b></div>\n\n**Harvard University**<br>\n**Spring 2021**<br>\n**Instructors:** Mark Glickman, Pavlos Protopapas, and Chris Tanner<br>\n**Lab Instructor:** Eleni Kaxiras<br><BR>\n*Content:* Eleni Kaxiras and Will Claybaugh\n\n---",
"_____no_output_____"
]
],
[
[
"## RUN THIS CELL TO PROPERLY HIGHLIGHT THE EXERCISES\nimport requests\nfrom IPython.core.display import HTML\nstyles = requests.get(\"https://raw.githubusercontent.com/Harvard-IACS/2019-CS109B/master/content/styles/cs109.css\").text\nHTML(styles)",
"_____no_output_____"
],
[
"import numpy as np\nfrom scipy.interpolate import interp1d\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n%matplotlib inline ",
"_____no_output_____"
]
],
[
[
"## Table of Contents\n\n* 1 - Overview - A Top View of LMs, GLMs, and GAMs to set the stage\n* 2 - A review of Linear Regression with `statsmodels`. Formulas.\n* 3 - Splines\n* 4 - Generative Additive Models with `pyGAM`\n* 5 - Smooting Splines using `csaps`",
"_____no_output_____"
],
[
"## Overview\n\n\n*image source: Dani Servén Marín (one of the developers of pyGAM)*",
"_____no_output_____"
],
[
"### A - Linear Models\n\nFirst we have the **Linear Models** which you know from 109a. These models are linear in the coefficients. Very *interpretable* but suffer from high bias because let's face it, few relationships in life are linear. Simple Linear Regression (defined as a model with one predictor) as well as Multiple Linear Regression (more than one predictors) are examples of LMs. Polynomial Regression extends the linear model by adding terms that are still linear for the coefficients but non-linear when it somes to the predictiors which are now raised in a power or multiplied between them.\n\n\n\n$$\n\\begin{aligned}\ny = \\beta{_0} + \\beta{_1}{x_1} & \\quad \\mbox{(simple linear regression)}\\\\\ny = \\beta{_0} + \\beta{_1}{x_1} + \\beta{_2}{x_2} + \\beta{_3}{x_3} & \\quad \\mbox{(multiple linear regression)}\\\\\ny = \\beta{_0} + \\beta{_1}{x_1} + \\beta{_2}{x_1^2} + \\beta{_3}{x_3^3} & \\quad \\mbox{(polynomial multiple regression)}\\\\\n\\end{aligned}\n$$",
"_____no_output_____"
],
[
"<div class=\"discussion\"><b>Questions to think about</b></div>\n\n - What does it mean for a model to be **interpretable**?\n - Are linear regression models interpretable? Are random forests? What about Neural Networks such as Feed Forward? \n - Do we always want interpretability? Describe cases where we do and cases where we do not care. \n",
"_____no_output_____"
],
[
"### B - Generalized Linear Models (GLMs)\n\n\n\n**Generalized Linear Models** is a term coined in the early 1970s by Nelder and Wedderburn for a class of models that includes both Linear Regression and Logistic Regression. A GLM fits one coefficient per feature (predictor). ",
"_____no_output_____"
],
[
"### C - Generalized Additive Models (GAMs)\n\nHastie and Tidshirani coined the term **Generalized Additive Models** in 1986 for a class of non-linear extensions to Generalized Linear Models.\n\n\n\n$$\n\\begin{aligned}\ny = \\beta{_0} + f_1\\left(x_1\\right) + f_2\\left(x_2\\right) + f_3\\left(x_3\\right) \\\\\ny = \\beta{_0} + f_1\\left(x_1\\right) + f_2\\left(x_2, x_3\\right) + f_3\\left(x_3\\right) & \\mbox{(with interaction terms)}\n\\end{aligned}\n$$\n\nIn practice we add splines and regularization via smoothing penalties to our GLMs. \n\n*image source: Dani Servén Marín*",
"_____no_output_____"
],
[
"### D - Basis Functions\n\nIn our models we can use various types of functions as \"basis\". \n- Monomials such as $x^2$, $x^4$ (**Polynomial Regression**)\n- Sigmoid functions (neural networks)\n- Fourier functions \n- Wavelets \n- **Regression splines** ",
"_____no_output_____"
],
[
"### 1 - Piecewise Polynomials a.k.a. Splines\n\nSplines are a type of piecewise polynomial interpolant. A spline of degree k is a piecewise polynomial that is continuously differentiable k − 1 times. \n\nSplines are the basis of CAD software and vector graphics including a lot of the fonts used in your computer. The name “spline” comes from a tool used by ship designers to draw smooth curves. Here is the letter $epsilon$ written with splines:\n\n\n\n*font idea inspired by Chris Rycroft (AM205)*\n\nIf the degree is 1 then we have a Linear Spline. If it is 3 then we have a Cubic spline. It turns out that cubic splines because they have a continous 2nd derivative (curvature) at the knots are very smooth to the eye. We do not need higher order than that. The Cubic Splines are usually Natural Cubic Splines which means they have the added constrain of the end points' second derivative = 0.\n\nWe will use the CubicSpline and the B-Spline as well as the Linear Spline.\n\n#### scipy.interpolate\n\nSee all the different splines that scipy.interpolate has to offer: https://docs.scipy.org/doc/scipy/reference/interpolate.html\n\nLet's use the simplest form which is interpolate on a set of points and then find the points between them.",
"_____no_output_____"
]
],
[
[
"from scipy.interpolate import splrep, splev\nfrom scipy.interpolate import BSpline, CubicSpline\nfrom scipy.interpolate import interp1d\n\n# define the range of the function\na = -1\nb = 1\n\n# define the number of knots \nnum_knots = 11\nknots = np.linspace(a,b,num_knots)\n\n# define the function we want to approximate\ny = 1/(1+25*(knots**2))\n\n# make a linear spline\nlinspline = interp1d(knots, y)\n\n# sample at these points to plot\nxx = np.linspace(a,b,1000)\nyy = 1/(1+25*(xx**2))\nplt.plot(knots,y,'*')\nplt.plot(xx, yy, label='true function')\nplt.plot(xx, linspline(xx), label='linear spline');\nplt.legend();",
"_____no_output_____"
]
],
[
[
"<div class=\"exercise\"><b>Exercise</b></div>\n\nThe Linear interpolation does not look very good. Fit a Cubic Spline and plot along the Linear to compare. Feel free to solve and then look at the solution.",
"_____no_output_____"
]
],
[
[
"# your answer here\n",
"_____no_output_____"
],
[
"# solution\n# define the range of the function\na = -1\nb = 1\n\n# define the knots \nnum_knots = 10\nx = np.linspace(a,b,num_knots)\n\n# define the function we want to approximate\ny = 1/(1+25*(x**2))\n\n# make the Cubic spline\ncubspline = CubicSpline(x, y)\n\nprint(f'Num knots in cubic spline: {num_knots}')\n\n# OR make a linear spline\nlinspline = interp1d(x, y)\n\n# plot\nxx = np.linspace(a,b,1000)\nyy = 1/(1+25*(xx**2))\n\nplt.plot(xx, yy, label='true function')\nplt.plot(x,y,'*', label='knots')\nplt.plot(xx, linspline(xx), label='linear');\nplt.plot(xx, cubspline(xx), label='cubic'); \nplt.legend();",
"Num knots in cubic spline: 10\n"
]
],
[
[
"<div class=\"discussion\"><b>Questions to think about</b></div>\n\n- Change the number of knots to 100 and see what happens. What would happen if we run a polynomial model of degree equal to the number of knots (a global one as in polynomial regression, not a spline)?\n- What makes a spline 'Natural'?",
"_____no_output_____"
]
],
[
[
"# Optional and Outside of the scope of this class: create the `epsilon` in the figure above\nx = np.array([1.,0.,-1.5,0.,-1.5,0.])\ny = np.array([1.5,1.,2.5,3,4,5])\nt = np.linspace(0,5,6)\nf = interp1d(t,x,kind='cubic')\ng = interp1d(t,y,kind='cubic')\ntplot = np.linspace(0,5,200)\nplt.plot(x,y, '*', f(tplot), g(tplot));",
"_____no_output_____"
]
],
[
[
"#### B-Splines (de Boor, 1978)\n\nOne way to construct a curve given a set of points is to *interpolate the points*, that is, to force the curve to pass through the points.\n\nA B-splines (Basis Splines) is defined by a set of **control points** and a set of **basis functions** that fit the function between these points. By choosing to have no smoothing factor we force the final B-spline to pass though all the points. If, on the other hand, we set a smothing factor, our function is more of an approximation with the control points as \"guidance\". The latter produced a smoother curve which is prefferable for drawing software. For more on Splines see: https://en.wikipedia.org/wiki/B-spline)\n\n\n\nWe will use [`scipy.splrep`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splrep.html#scipy.interpolate.splrep) to calulate the coefficients for the B-Spline and draw it. ",
"_____no_output_____"
],
[
"#### B-Spline with no smooting",
"_____no_output_____"
]
],
[
[
"from scipy.interpolate import splev, splrep\n\nx = np.linspace(0, 10, 10)\ny = np.sin(x)\n# (t,c,k) is a tuple containing the vector of knots, coefficients, degree of the spline\nt,c,k = splrep(x, y) \nx2 = np.linspace(0, 10, 200)\ny2 = BSpline(t,c,k)\nplt.plot(x, y, 'o', x2, y2(x2))\nplt.show()",
"_____no_output_____"
],
[
"from scipy.interpolate import splrep\nx = np.linspace(0, 10, 10)\ny = np.sin(x)\n\nt,c,k = splrep(x, y, k=3) # (tck) is a tuple containing the vector of knots, coefficients, degree of the spline\n# define the points to plot on (x2)\nprint(f'Knots ({len(t)} of them): {t}\\n')\nprint(f'B-Spline coefficients ({len(c)} of them): {c}\\n') \nprint(f'B-Spline degree {k}')\nx2 = np.linspace(0, 10, 100)\ny2 = BSpline(t, c, k)\nplt.figure(figsize=(10,5))\nplt.plot(x, y, 'o', label='true points')\nplt.plot(x2, y2(x2), label='B-Spline')\ntt = np.zeros(len(t))\nplt.plot(t, tt,'g*', label='knots eval by the function')\nplt.legend()\nplt.show()",
"Knots (14 of them): [ 0. 0. 0. 0. 2.22222222 3.33333333\n 4.44444444 5.55555556 6.66666667 7.77777778 10. 10.\n 10. 10. ]\n\nB-Spline coefficients (14 of them): [-4.94881722e-18 8.96543619e-01 1.39407154e+00 -2.36640266e-01\n -1.18324030e+00 -8.16301228e-01 4.57836125e-01 1.48720677e+00\n 1.64338775e-01 -5.44021111e-01 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00]\n\nB-Spline degree 3\n"
]
],
[
[
"<a id=splineparams></a> \n#### What do the tuple values returned by `scipy.splrep` mean?\n\n- The `t` variable is the array that contains the knots' position in the x axis. The length of this array is, of course, the number of knots.\n- The `c` variable is the array that holds the coefficients for the B-Spline. Its length should be the same as `t`.\n\nWe have `number_of_knots - 1` B-spline basis elements to the spline constructed via this method, and they are defined as follows:<BR><BR>\n$$\n\\begin{aligned}\nB_{i, 0}(x) = 1, \\textrm{if $t_i \\le x < t_{i+1}$, otherwise $0$,} \\\\ \\\\\nB_{i, k}(x) = \\frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)\n + \\frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)\n\\end{aligned}\n$$ \n- t $\\in [t_1, t_2, ..., t_]$ is the knot vector\n- c : are the spline coefficients\n- k : is the spline degree",
"_____no_output_____"
],
[
"#### B-Spline with smooting factor s",
"_____no_output_____"
]
],
[
[
"from scipy.interpolate import splev, splrep\nx = np.linspace(0, 10, 5)\ny = np.sin(x)\n\ns = 0.5 # add smoothing factor\ntask = 0 # task needs to be set to 0, which represents:\n# we are specifying a smoothing factor and thus only want\n# splrep() to find the optimal t and c\n\nt,c,k = splrep(x, y, task=task, s=s)\n\n# draw the line segments\nlinspline = interp1d(x, y)\n# define the points to plot on (x2)\nx2 = np.linspace(0, 10, 200)\ny2 = BSpline(t, c, k)\nplt.plot(x, y, 'o', x2, y2(x2))\nplt.plot(x2, linspline(x2))\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### B-Spline with given knots",
"_____no_output_____"
]
],
[
[
"x = np.linspace(0, 10, 100)\ny = np.sin(x)\nknots = np.quantile(x, [0.25, 0.5, 0.75])\nprint(knots)",
"[2.5 5. 7.5]\n"
],
[
"# calculate the B-Spline\nt,c,k = splrep(x, y, t=knots)",
"_____no_output_____"
],
[
"curve = BSpline(t,c,k)\ncurve",
"_____no_output_____"
],
[
"plt.scatter(x=x,y=y,c='grey', alpha=0.4)\nyknots = np.sin(knots)\nplt.scatter(knots, yknots, c='r')\nplt.plot(x,curve(x))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2 - GAMs\n\nhttps://readthedocs.org/projects/pygam/downloads/pdf/latest/\n\n#### Classification in `pyGAM`\n\nLet's get our (multivariate!) data, the `kyphosis` dataset, and the `LogisticGAM` model from `pyGAM` to do binary classification.\n\n- kyphosis - wherther a particular deformation was present post-operation\n- age - patient's age in months\n- number - the number of vertebrae involved in the operation\n- start - the number of the topmost vertebrae operated on",
"_____no_output_____"
]
],
[
[
"kyphosis = pd.read_csv(\"../data/kyphosis.csv\")\n\ndisplay(kyphosis.head())\ndisplay(kyphosis.describe(include='all'))\ndisplay(kyphosis.dtypes)",
"_____no_output_____"
],
[
"# convert the outcome in a binary form, 1 or 0\nkyphosis = pd.read_csv(\"../data/kyphosis.csv\")\nkyphosis[\"outcome\"] = 1*(kyphosis[\"Kyphosis\"] == \"present\")\nkyphosis.describe()",
"_____no_output_____"
],
[
"from pygam import LogisticGAM, s, f, l\n\nX = kyphosis[[\"Age\",\"Number\",\"Start\"]]\ny = kyphosis[\"outcome\"]\nkyph_gam = LogisticGAM().fit(X,y)",
"_____no_output_____"
]
],
[
[
"#### Outcome dependence on features\n\nTo help us see how the outcome depends on each feature, `pyGAM` has the `partial_dependence()` function.\n```\n pdep, confi = kyph_gam.partial_dependence(term=i, X=XX, width=0.95)\n```\nFor more on this see the : https://pygam.readthedocs.io/en/latest/api/logisticgam.html\n",
"_____no_output_____"
]
],
[
[
"res = kyph_gam.deviance_residuals(X,y)\nfor i, term in enumerate(kyph_gam.terms):\n if term.isintercept:\n continue\n\n XX = kyph_gam.generate_X_grid(term=i)\n pdep, confi = kyph_gam.partial_dependence(term=i, X=XX, width=0.95)\n pdep2, _ = kyph_gam.partial_dependence(term=i, X=X, width=0.95)\n plt.figure()\n plt.scatter(X.iloc[:,term.feature], pdep2 + res)\n plt.plot(XX[:, term.feature], pdep)\n plt.plot(XX[:, term.feature], confi, c='r', ls='--')\n plt.title(X.columns.values[term.feature])\n plt.show()",
"_____no_output_____"
]
],
[
[
"Notice that we did not specify the basis functions in the .fit(). `pyGAM` figures them out for us by using $s()$ (splines) for numerical variables and $f()$ for categorical features. If this is not what we want we can manually specify the basis functions, as follows: ",
"_____no_output_____"
]
],
[
[
"kyph_gam = LogisticGAM(s(0)+s(1)+s(2)).fit(X,y)",
"_____no_output_____"
],
[
"res = kyph_gam.deviance_residuals(X,y)\nfor i, term in enumerate(kyph_gam.terms):\n if term.isintercept:\n continue\n\n XX = kyph_gam.generate_X_grid(term=i)\n pdep, confi = kyph_gam.partial_dependence(term=i, X=XX, width=0.95)\n pdep2, _ = kyph_gam.partial_dependence(term=i, X=X, width=0.95)\n plt.figure()\n plt.scatter(X.iloc[:,term.feature], pdep2 + res)\n plt.plot(XX[:, term.feature], pdep)\n plt.plot(XX[:, term.feature], confi, c='r', ls='--')\n plt.title(X.columns.values[term.feature])\n plt.show()",
"_____no_output_____"
]
],
[
[
"#### Regression in `pyGAM`\n\nFor regression problems, we can use a `linearGAM` model. For this part we will use the `wages` dataset.\n\nhttps://pygam.readthedocs.io/en/latest/api/lineargam.html",
"_____no_output_____"
],
[
"#### The `wages` dataset\n\nLet's inspect another dataset that is included in `pyGAM` that notes the wages of people based on their age, year of employment and education.",
"_____no_output_____"
]
],
[
[
"# from the pyGAM documentation\nfrom pygam import LinearGAM, s, f\nfrom pygam.datasets import wage\n\nX, y = wage(return_X_y=True)\n\n## model\ngam = LinearGAM(s(0) + s(1) + f(2))\ngam.gridsearch(X, y)\n\n\n## plotting\nplt.figure();\nfig, axs = plt.subplots(1,3);\n\ntitles = ['year', 'age', 'education']\nfor i, ax in enumerate(axs):\n XX = gam.generate_X_grid(term=i)\n ax.plot(XX[:, i], gam.partial_dependence(term=i, X=XX))\n ax.plot(XX[:, i], gam.partial_dependence(term=i, X=XX, width=.95)[1], c='r', ls='--')\n if i == 0:\n ax.set_ylim(-30,30)\n ax.set_title(titles[i]);",
"100% (11 of 11) |########################| Elapsed Time: 0:00:00 Time: 0:00:00\n"
]
],
[
[
"### 3 - Smoothing Splines using csaps\n\n**Note**: this is the spline model that minimizes <BR>\n$MSE - \\lambda\\cdot\\text{wiggle penalty}$ $=$ $\\sum_{i=1}^N \\left(y_i - f(x_i)\\right)^2 - \\lambda \\int \\left(f''(t)\\right)^2 dt$, <BR>\nacross all possible functions $f$. ",
"_____no_output_____"
]
],
[
[
"from csaps import csaps\n\nnp.random.seed(1234)\n\nx = np.linspace(0,10,300000)\ny = np.sin(x*2*np.pi)*x + np.random.randn(len(x))\n\nxs = np.linspace(x[0], x[-1], 1000)\n\nys = csaps(x, y, xs, smooth=0.99)\nprint(ys.shape)\n\n#plt.plot(x, y, 'o', xs, ys, '-')\nplt.plot(x, y, 'o', xs, ys, '-')\nplt.show()",
"(1000,)\n"
]
],
[
[
"### 4 - Data fitting using pyGAM and Penalized B-Splines\n\nWhen we use a spline in pyGAM we are effectively using a penalized B-Spline with a regularization parameter $\\lambda$. E.g. \n```\nLogisticGAM(s(0)+s(1, lam=0.5)+s(2)).fit(X,y) \n```",
"_____no_output_____"
],
[
"Let's see how this smoothing works in `pyGAM`. We start by creating some arbitrary data and fitting them with a GAM.",
"_____no_output_____"
]
],
[
[
"X = np.linspace(0,10,500)\ny = np.sin(X*2*np.pi)*X + np.random.randn(len(X))\n\nplt.scatter(X,y);",
"_____no_output_____"
],
[
"# let's try a large lambda first and lots of splines\ngam = LinearGAM(lam=1e6, n_splines=50). fit(X,y)\nXX = gam.generate_X_grid(term=0)\nplt.scatter(X,y,alpha=0.3);\nplt.plot(XX, gam.predict(XX));",
"_____no_output_____"
]
],
[
[
"We see that the large $\\lambda$ forces a straight line, no flexibility. Let's see now what happens if we make it smaller.",
"_____no_output_____"
]
],
[
[
"# let's try a smaller lambda \ngam = LinearGAM(lam=1e2, n_splines=50). fit(X,y)\nXX = gam.generate_X_grid(term=0)\nplt.scatter(X,y,alpha=0.3);\nplt.plot(XX, gam.predict(XX));",
"_____no_output_____"
]
],
[
[
"There is some curvature there but still not a good fit. Let's try no penalty. That should have the line fit exactly.",
"_____no_output_____"
]
],
[
[
"# no penalty, let's try a 0 lambda \ngam = LinearGAM(lam=0, n_splines=50). fit(X,y)\nXX = gam.generate_X_grid(term=0)\nplt.scatter(X,y,alpha=0.3)\nplt.plot(XX, gam.predict(XX))",
"_____no_output_____"
]
],
[
[
"Yes, that is good. Now let's see what happens if we lessen the number of splines. The fit should not be as good.",
"_____no_output_____"
]
],
[
[
"# no penalty, let's try a 0 lambda \ngam = LinearGAM(lam=0, n_splines=10). fit(X,y)\nXX = gam.generate_X_grid(term=0)\nplt.scatter(X,y,alpha=0.3);\nplt.plot(XX, gam.predict(XX));",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba4e146f6c75b892b2906ce3f9fd7fa3f4d2834
| 154,643 |
ipynb
|
Jupyter Notebook
|
Eserc_Frutta_Ingrid.ipynb
|
MosesDastmard/fruit-recognizer
|
0e56844dbd610995c02ead6c1a61324c28dabe6f
|
[
"MIT"
] | null | null | null |
Eserc_Frutta_Ingrid.ipynb
|
MosesDastmard/fruit-recognizer
|
0e56844dbd610995c02ead6c1a61324c28dabe6f
|
[
"MIT"
] | null | null | null |
Eserc_Frutta_Ingrid.ipynb
|
MosesDastmard/fruit-recognizer
|
0e56844dbd610995c02ead6c1a61324c28dabe6f
|
[
"MIT"
] | null | null | null | 89.804297 | 15,776 | 0.698124 |
[
[
[
"## Applicazione del transfer learning con MobileNet_V2\nA high-quality, dataset of images containing fruits. The following fruits are included: Apples - (different varieties: Golden, Golden-Red, Granny Smith, Red, Red Delicious), Apricot, Avocado, Avocado ripe, Banana (Yellow, Red), Cactus fruit, Carambula, Cherry, Clementine, Cocos, Dates, Granadilla, Grape (Pink, White, White2), Grapefruit (Pink, White), Guava, Huckleberry, Kiwi, Kaki, Kumsquats, Lemon (normal, Meyer), Lime, Litchi, Mandarine, Mango, Maracuja, Nectarine, Orange, Papaya, Passion fruit, Peach, Pepino, Pear (different varieties, Abate, Monster, Williams), Pineapple, Pitahaya Red, Plum, Pomegranate, Quince, Raspberry, Salak, Strawberry, Tamarillo, Tangelo.\n\nTraining set size: 28736 images.\n\nValidation set size: 9673 images.\n\nNumber of classes: 60 (fruits).\n\nImage size: 100x100 pixels.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport keras\nfrom tensorflow.keras.layers import InputLayer, Input, ReLU\nfrom tensorflow.keras.layers import Reshape, MaxPooling2D, Cropping2D, BatchNormalization, AveragePooling2D\nfrom tensorflow.keras.layers import Conv2D, Dense, Flatten, Dropout, SeparableConv2D, DepthwiseConv2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import SGD, Adam\nfrom tensorflow.python.keras.utils import to_categorical\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.python.keras.preprocessing import image\nfrom skimage import transform\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom tensorflow.python.keras.applications.mobilenet_v2 import MobileNetV2\nfrom tensorflow.python.keras.models import Model, load_model\nfrom tensorflow.python.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.python.keras import backend as K",
"_____no_output_____"
]
],
[
[
"## Upload dataset to colab:\nWith the help of pydrive package it is possible to upload dataset which is a shared link on google drive directly to the colab. So no need to download the dataset and then upload it on google colab. It can be done right away. To proceed google need to authorize your account. Running below cell emarges a link that give you a code to authorize your google account to use google clould SDK. the last step is to copy and paste the code. Done!",
"_____no_output_____"
]
],
[
[
"# Google Drive Authentication\n!pip install pydrive\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\n\n# Authenticate and create the PyDrive client.\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)",
"Requirement already satisfied: pydrive in /usr/local/lib/python3.6/dist-packages (1.3.1)\nRequirement already satisfied: PyYAML>=3.0 in /usr/local/lib/python3.6/dist-packages (from pydrive) (3.13)\nRequirement already satisfied: oauth2client>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pydrive) (4.1.3)\nRequirement already satisfied: google-api-python-client>=1.2 in /usr/local/lib/python3.6/dist-packages (from pydrive) (1.6.7)\nRequirement already satisfied: six>=1.6.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=4.0.0->pydrive) (1.12.0)\nRequirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=4.0.0->pydrive) (4.0)\nRequirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=4.0.0->pydrive) (0.2.5)\nRequirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=4.0.0->pydrive) (0.11.3)\nRequirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client>=4.0.0->pydrive) (0.4.5)\nRequirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.2->pydrive) (3.0.0)\n"
]
],
[
[
"Each shared file on google drive has a unique id. This id can be found in the shareable link of the file. So instead of file link we must use id to be capable upload the file to colab.",
"_____no_output_____"
]
],
[
[
"# Download a file from shareable Link on Elearning\nfile_id = '1wJw2Ugn0L0DZIs_3_oZ0KNoOFTFxOsFS'\ndownloaded = drive.CreateFile({'id': file_id})\ndownloaded.GetContentFile('FRUTTA.rar')\n",
"_____no_output_____"
]
],
[
[
"The uploaded file is a .rar extention file. The rarfile package can extract(unrar) file. ",
"_____no_output_____"
]
],
[
[
"# Unrar file on colab\n!pip install rarfile\nimport rarfile\nrf = rarfile.RarFile('FRUTTA.rar')\nrf.extractall(path = 'FRUTTA')",
"Collecting rarfile\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/de/a4/8b4abc72310da6fa53b6de8de1019e0516885d05369d6c91cba23476abe5/rarfile-3.0.tar.gz (110kB)\n\u001b[K |████████████████████████████████| 112kB 2.8MB/s \n\u001b[?25hBuilding wheels for collected packages: rarfile\n Building wheel for rarfile (setup.py) ... \u001b[?25l\u001b[?25hdone\n Stored in directory: /root/.cache/pip/wheels/dc/84/da/8aff50941f548db5384b076d5a6a6afea0cd12672e0326edc4\nSuccessfully built rarfile\nInstalling collected packages: rarfile\nSuccessfully installed rarfile-3.0\n"
]
],
[
[
"### Change the path of directories!!!",
"_____no_output_____"
]
],
[
[
"# Setting path location for validation, traing and testing images\nvalidationPath = 'FRUTTA/Validation'\ntrainPath = 'FRUTTA/Training'",
"_____no_output_____"
]
],
[
[
"### Plot an image, for example E:/Training/Cocos/15_100.jpg",
"_____no_output_____"
],
[
"To show an image directly readed from the disk, IPython module is needed. However there are several ways to do that. ",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image as image_show\nimage_show('FRUTTA/Training/Cocos/15_100.jpg', width = 200, height = 200)",
"_____no_output_____"
]
],
[
[
"### Now you define the functions ables to read mini-batch of data",
"_____no_output_____"
]
],
[
[
"# Making an image data generator object with augmentation for training\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n rotation_range=30,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True, \n fill_mode='nearest')",
"_____no_output_____"
],
[
"# Making an image data generator object with no augmentation for validation\ntest_datagen = ImageDataGenerator(rescale=1./255)",
"_____no_output_____"
]
],
[
[
"### why train_datagen and test_datagen are different? answer . . .\n\nThe idea for manipulating the train data set using rotation, zoom, width/height shift, flipping and process such like is that to expose the model with all probably possible samples that it may deal with on prediction/classification phase. So to streghten the model and getting the most information from train data, we manipulate the samples in train set such that the manipulated samples also can be valid and possible samples as part of train set. But if we do the same process on validation and test sets we will increase the correlation between train and validation/test sets that is in conflict with the assumtion that sample are independent. That causes generally more accuracy on validation and test sets which is not real. To recap, it is recommended that do manipulation just on seen data rather than unseen data. ",
"_____no_output_____"
],
[
"The beloved keras package make it easy to read image from the disk and convert it directly to a generator. we can do it with flow_from_directory method.",
"_____no_output_____"
]
],
[
[
"# Using the generator with batch size 32 for training directory\ntrain_generator = train_datagen.flow_from_directory(trainPath, \n target_size=(128, 128),\n batch_size=64,\n class_mode='categorical')",
"Found 28736 images belonging to 60 classes.\n"
],
[
"# Using the generator with batch size 17 for validation directory\nvalidation_generator = test_datagen.flow_from_directory(validationPath,\n target_size=(128, 128),\n batch_size=64,\n class_mode='categorical')",
"Found 9673 images belonging to 60 classes.\n"
]
],
[
[
"### you can control the dimensions of the generator outputs",
"_____no_output_____"
]
],
[
[
"validation_generator[0][0].shape",
"_____no_output_____"
]
],
[
[
"Since on training phase for each epoch once gradian descend algorithm run on each mini-batch. we set the mini-batch to 64. But for validation there is no significant diffrence for small or large mini-batch size as it is only used to derive validation metrices. ",
"_____no_output_____"
]
],
[
[
"print(\"Number of batches in validation generator is\", len(validation_generator))\nprint(\"Number of batches in train generator is\", len(train_generator))\n",
"Number of batches in validation generator is 152\nNumber of batches in train generator is 449\n"
],
[
"validation_generator[0][1].shape",
"_____no_output_____"
]
],
[
[
"### Now you need to define your model . . .\nthe default definition of MobileNet_V2 is:\n\nMobileNetV2(input_shape=None, alpha=1.0, depth_multiplier=1, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000)\n\nbut you have a different number of classes . . . . .",
"_____no_output_____"
],
[
"# Using MobileNetV2:\nIt is possible to use a pre-trained model such as MobileNetV2 and the keras package enable us to modify the model to 60 class",
"_____no_output_____"
],
[
"MobileNetV2 is a deep CNN model with 20 sequentional layers that is trained to classify 1000 classes. In this project we only have 60 classes, So the top layer are dropped must be substitute with final output layers which includes usually GlobalAveraging and Dense layer. First the a look at the MobileNetV2 as a base model that is shown below: ",
"_____no_output_____"
]
],
[
[
"base_model = MobileNetV2(weights='imagenet', include_top=False)\nprint(base_model.summary())",
"WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\n"
]
],
[
[
"### Define what layers you want to train . . .",
"_____no_output_____"
],
[
"In order to use a pre-trained model like MobileNetV2 for only 60 classes we can keep the layers freezed and just only drop the last layers which is done setting top_layer=False.\nIn below code the last two layers were removed and substituted with an average pooling and a dense layer. Adding up the base model and trainable layers, the new model summarize as below. It can be seen that the shape of each output layer is None that stem from dropping top layer in base model causes the model to train with different input shape.",
"_____no_output_____"
]
],
[
[
"x = base_model.output\nx = GlobalAveragePooling2D()(x)\npredictions = Dense(60, activation = 'softmax')(x)\nmodel_mnv2 = Model(inputs = base_model.input, outputs = predictions)\nprint(model_mnv2.summary())",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, None, None, 3 0 \n__________________________________________________________________________________________________\nConv1_pad (ZeroPadding2D) (None, None, None, 3 0 input_1[0][0] \n__________________________________________________________________________________________________\nConv1 (Conv2D) (None, None, None, 3 864 Conv1_pad[0][0] \n__________________________________________________________________________________________________\nbn_Conv1 (BatchNormalizationV1) (None, None, None, 3 128 Conv1[0][0] \n__________________________________________________________________________________________________\nConv1_relu (ReLU) (None, None, None, 3 0 bn_Conv1[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise (Depthw (None, None, None, 3 288 Conv1_relu[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_BN (Bat (None, None, None, 3 128 expanded_conv_depthwise[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_depthwise_relu (R (None, None, None, 3 0 expanded_conv_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nexpanded_conv_project (Conv2D) (None, None, None, 1 512 expanded_conv_depthwise_relu[0][0\n__________________________________________________________________________________________________\nexpanded_conv_project_BN (Batch (None, None, None, 1 64 expanded_conv_project[0][0] \n__________________________________________________________________________________________________\nblock_1_expand (Conv2D) (None, None, None, 9 1536 expanded_conv_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_BN (BatchNormali (None, None, None, 9 384 block_1_expand[0][0] \n__________________________________________________________________________________________________\nblock_1_expand_relu (ReLU) (None, None, None, 9 0 block_1_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_pad (ZeroPadding2D) (None, None, None, 9 0 block_1_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise (DepthwiseCon (None, None, None, 9 864 block_1_pad[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_BN (BatchNorm (None, None, None, 9 384 block_1_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_1_depthwise_relu (ReLU) (None, None, None, 9 0 block_1_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_1_project (Conv2D) (None, None, None, 2 2304 block_1_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_1_project_BN (BatchNormal (None, None, None, 2 96 block_1_project[0][0] \n__________________________________________________________________________________________________\nblock_2_expand (Conv2D) (None, None, None, 1 3456 block_1_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_BN (BatchNormali (None, None, None, 1 576 block_2_expand[0][0] \n__________________________________________________________________________________________________\nblock_2_expand_relu (ReLU) (None, None, None, 1 0 block_2_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise (DepthwiseCon (None, None, None, 1 1296 block_2_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_BN (BatchNorm (None, None, None, 1 576 block_2_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_2_depthwise_relu (ReLU) (None, None, None, 1 0 block_2_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_2_project (Conv2D) (None, None, None, 2 3456 block_2_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_2_project_BN (BatchNormal (None, None, None, 2 96 block_2_project[0][0] \n__________________________________________________________________________________________________\nblock_2_add (Add) (None, None, None, 2 0 block_1_project_BN[0][0] \n block_2_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_expand (Conv2D) (None, None, None, 1 3456 block_2_add[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_BN (BatchNormali (None, None, None, 1 576 block_3_expand[0][0] \n__________________________________________________________________________________________________\nblock_3_expand_relu (ReLU) (None, None, None, 1 0 block_3_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_pad (ZeroPadding2D) (None, None, None, 1 0 block_3_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise (DepthwiseCon (None, None, None, 1 1296 block_3_pad[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_BN (BatchNorm (None, None, None, 1 576 block_3_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_3_depthwise_relu (ReLU) (None, None, None, 1 0 block_3_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_3_project (Conv2D) (None, None, None, 3 4608 block_3_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_3_project_BN (BatchNormal (None, None, None, 3 128 block_3_project[0][0] \n__________________________________________________________________________________________________\nblock_4_expand (Conv2D) (None, None, None, 1 6144 block_3_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_BN (BatchNormali (None, None, None, 1 768 block_4_expand[0][0] \n__________________________________________________________________________________________________\nblock_4_expand_relu (ReLU) (None, None, None, 1 0 block_4_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise (DepthwiseCon (None, None, None, 1 1728 block_4_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_BN (BatchNorm (None, None, None, 1 768 block_4_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_4_depthwise_relu (ReLU) (None, None, None, 1 0 block_4_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_4_project (Conv2D) (None, None, None, 3 6144 block_4_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_4_project_BN (BatchNormal (None, None, None, 3 128 block_4_project[0][0] \n__________________________________________________________________________________________________\nblock_4_add (Add) (None, None, None, 3 0 block_3_project_BN[0][0] \n block_4_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_expand (Conv2D) (None, None, None, 1 6144 block_4_add[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_BN (BatchNormali (None, None, None, 1 768 block_5_expand[0][0] \n__________________________________________________________________________________________________\nblock_5_expand_relu (ReLU) (None, None, None, 1 0 block_5_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise (DepthwiseCon (None, None, None, 1 1728 block_5_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_BN (BatchNorm (None, None, None, 1 768 block_5_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_5_depthwise_relu (ReLU) (None, None, None, 1 0 block_5_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_5_project (Conv2D) (None, None, None, 3 6144 block_5_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_5_project_BN (BatchNormal (None, None, None, 3 128 block_5_project[0][0] \n__________________________________________________________________________________________________\nblock_5_add (Add) (None, None, None, 3 0 block_4_add[0][0] \n block_5_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_expand (Conv2D) (None, None, None, 1 6144 block_5_add[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_BN (BatchNormali (None, None, None, 1 768 block_6_expand[0][0] \n__________________________________________________________________________________________________\nblock_6_expand_relu (ReLU) (None, None, None, 1 0 block_6_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_pad (ZeroPadding2D) (None, None, None, 1 0 block_6_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise (DepthwiseCon (None, None, None, 1 1728 block_6_pad[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_BN (BatchNorm (None, None, None, 1 768 block_6_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_6_depthwise_relu (ReLU) (None, None, None, 1 0 block_6_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_6_project (Conv2D) (None, None, None, 6 12288 block_6_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_6_project_BN (BatchNormal (None, None, None, 6 256 block_6_project[0][0] \n__________________________________________________________________________________________________\nblock_7_expand (Conv2D) (None, None, None, 3 24576 block_6_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_BN (BatchNormali (None, None, None, 3 1536 block_7_expand[0][0] \n__________________________________________________________________________________________________\nblock_7_expand_relu (ReLU) (None, None, None, 3 0 block_7_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise (DepthwiseCon (None, None, None, 3 3456 block_7_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_BN (BatchNorm (None, None, None, 3 1536 block_7_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_7_depthwise_relu (ReLU) (None, None, None, 3 0 block_7_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_7_project (Conv2D) (None, None, None, 6 24576 block_7_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_7_project_BN (BatchNormal (None, None, None, 6 256 block_7_project[0][0] \n__________________________________________________________________________________________________\nblock_7_add (Add) (None, None, None, 6 0 block_6_project_BN[0][0] \n block_7_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_expand (Conv2D) (None, None, None, 3 24576 block_7_add[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_BN (BatchNormali (None, None, None, 3 1536 block_8_expand[0][0] \n__________________________________________________________________________________________________\nblock_8_expand_relu (ReLU) (None, None, None, 3 0 block_8_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise (DepthwiseCon (None, None, None, 3 3456 block_8_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_BN (BatchNorm (None, None, None, 3 1536 block_8_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_8_depthwise_relu (ReLU) (None, None, None, 3 0 block_8_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_8_project (Conv2D) (None, None, None, 6 24576 block_8_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_8_project_BN (BatchNormal (None, None, None, 6 256 block_8_project[0][0] \n__________________________________________________________________________________________________\nblock_8_add (Add) (None, None, None, 6 0 block_7_add[0][0] \n block_8_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_expand (Conv2D) (None, None, None, 3 24576 block_8_add[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_BN (BatchNormali (None, None, None, 3 1536 block_9_expand[0][0] \n__________________________________________________________________________________________________\nblock_9_expand_relu (ReLU) (None, None, None, 3 0 block_9_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise (DepthwiseCon (None, None, None, 3 3456 block_9_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_BN (BatchNorm (None, None, None, 3 1536 block_9_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_9_depthwise_relu (ReLU) (None, None, None, 3 0 block_9_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_9_project (Conv2D) (None, None, None, 6 24576 block_9_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_9_project_BN (BatchNormal (None, None, None, 6 256 block_9_project[0][0] \n__________________________________________________________________________________________________\nblock_9_add (Add) (None, None, None, 6 0 block_8_add[0][0] \n block_9_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_expand (Conv2D) (None, None, None, 3 24576 block_9_add[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_BN (BatchNormal (None, None, None, 3 1536 block_10_expand[0][0] \n__________________________________________________________________________________________________\nblock_10_expand_relu (ReLU) (None, None, None, 3 0 block_10_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise (DepthwiseCo (None, None, None, 3 3456 block_10_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_BN (BatchNor (None, None, None, 3 1536 block_10_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_10_depthwise_relu (ReLU) (None, None, None, 3 0 block_10_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_10_project (Conv2D) (None, None, None, 9 36864 block_10_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_10_project_BN (BatchNorma (None, None, None, 9 384 block_10_project[0][0] \n__________________________________________________________________________________________________\nblock_11_expand (Conv2D) (None, None, None, 5 55296 block_10_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_BN (BatchNormal (None, None, None, 5 2304 block_11_expand[0][0] \n__________________________________________________________________________________________________\nblock_11_expand_relu (ReLU) (None, None, None, 5 0 block_11_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise (DepthwiseCo (None, None, None, 5 5184 block_11_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_BN (BatchNor (None, None, None, 5 2304 block_11_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_11_depthwise_relu (ReLU) (None, None, None, 5 0 block_11_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_11_project (Conv2D) (None, None, None, 9 55296 block_11_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_11_project_BN (BatchNorma (None, None, None, 9 384 block_11_project[0][0] \n__________________________________________________________________________________________________\nblock_11_add (Add) (None, None, None, 9 0 block_10_project_BN[0][0] \n block_11_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_expand (Conv2D) (None, None, None, 5 55296 block_11_add[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_BN (BatchNormal (None, None, None, 5 2304 block_12_expand[0][0] \n__________________________________________________________________________________________________\nblock_12_expand_relu (ReLU) (None, None, None, 5 0 block_12_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise (DepthwiseCo (None, None, None, 5 5184 block_12_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_BN (BatchNor (None, None, None, 5 2304 block_12_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_12_depthwise_relu (ReLU) (None, None, None, 5 0 block_12_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_12_project (Conv2D) (None, None, None, 9 55296 block_12_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_12_project_BN (BatchNorma (None, None, None, 9 384 block_12_project[0][0] \n__________________________________________________________________________________________________\nblock_12_add (Add) (None, None, None, 9 0 block_11_add[0][0] \n block_12_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_expand (Conv2D) (None, None, None, 5 55296 block_12_add[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_BN (BatchNormal (None, None, None, 5 2304 block_13_expand[0][0] \n__________________________________________________________________________________________________\nblock_13_expand_relu (ReLU) (None, None, None, 5 0 block_13_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_pad (ZeroPadding2D) (None, None, None, 5 0 block_13_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise (DepthwiseCo (None, None, None, 5 5184 block_13_pad[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_BN (BatchNor (None, None, None, 5 2304 block_13_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_13_depthwise_relu (ReLU) (None, None, None, 5 0 block_13_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_13_project (Conv2D) (None, None, None, 1 92160 block_13_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_13_project_BN (BatchNorma (None, None, None, 1 640 block_13_project[0][0] \n__________________________________________________________________________________________________\nblock_14_expand (Conv2D) (None, None, None, 9 153600 block_13_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_BN (BatchNormal (None, None, None, 9 3840 block_14_expand[0][0] \n__________________________________________________________________________________________________\nblock_14_expand_relu (ReLU) (None, None, None, 9 0 block_14_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise (DepthwiseCo (None, None, None, 9 8640 block_14_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_BN (BatchNor (None, None, None, 9 3840 block_14_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_14_depthwise_relu (ReLU) (None, None, None, 9 0 block_14_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_14_project (Conv2D) (None, None, None, 1 153600 block_14_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_14_project_BN (BatchNorma (None, None, None, 1 640 block_14_project[0][0] \n__________________________________________________________________________________________________\nblock_14_add (Add) (None, None, None, 1 0 block_13_project_BN[0][0] \n block_14_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_expand (Conv2D) (None, None, None, 9 153600 block_14_add[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_BN (BatchNormal (None, None, None, 9 3840 block_15_expand[0][0] \n__________________________________________________________________________________________________\nblock_15_expand_relu (ReLU) (None, None, None, 9 0 block_15_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise (DepthwiseCo (None, None, None, 9 8640 block_15_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_BN (BatchNor (None, None, None, 9 3840 block_15_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_15_depthwise_relu (ReLU) (None, None, None, 9 0 block_15_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_15_project (Conv2D) (None, None, None, 1 153600 block_15_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_15_project_BN (BatchNorma (None, None, None, 1 640 block_15_project[0][0] \n__________________________________________________________________________________________________\nblock_15_add (Add) (None, None, None, 1 0 block_14_add[0][0] \n block_15_project_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_expand (Conv2D) (None, None, None, 9 153600 block_15_add[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_BN (BatchNormal (None, None, None, 9 3840 block_16_expand[0][0] \n__________________________________________________________________________________________________\nblock_16_expand_relu (ReLU) (None, None, None, 9 0 block_16_expand_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise (DepthwiseCo (None, None, None, 9 8640 block_16_expand_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_BN (BatchNor (None, None, None, 9 3840 block_16_depthwise[0][0] \n__________________________________________________________________________________________________\nblock_16_depthwise_relu (ReLU) (None, None, None, 9 0 block_16_depthwise_BN[0][0] \n__________________________________________________________________________________________________\nblock_16_project (Conv2D) (None, None, None, 3 307200 block_16_depthwise_relu[0][0] \n__________________________________________________________________________________________________\nblock_16_project_BN (BatchNorma (None, None, None, 3 1280 block_16_project[0][0] \n__________________________________________________________________________________________________\nConv_1 (Conv2D) (None, None, None, 1 409600 block_16_project_BN[0][0] \n__________________________________________________________________________________________________\nConv_1_bn (BatchNormalizationV1 (None, None, None, 1 5120 Conv_1[0][0] \n__________________________________________________________________________________________________\nout_relu (ReLU) (None, None, None, 1 0 Conv_1_bn[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d (Globa (None, 1280) 0 out_relu[0][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 60) 76860 global_average_pooling2d[0][0] \n==================================================================================================\nTotal params: 2,334,844\nTrainable params: 2,300,732\nNon-trainable params: 34,112\n__________________________________________________________________________________________________\nNone\n"
]
],
[
[
"The below code freez the layers setup from base_model and keep the rest layers trainable. It provide us with chance of using the weight of the base model in or new model that is going to be modified to cover 60 classes of fruits.",
"_____no_output_____"
]
],
[
[
"for layer in base_model.layers:\n layer.trainable = False\n",
"_____no_output_____"
]
],
[
[
"### Compile the model . . .",
"_____no_output_____"
],
[
"Now we have the model and we defined its architecture. It is time to compile the model and determine the optimizer algorithm, the loss function which is used in optimization and the metrices that are intresting to monitor. ",
"_____no_output_____"
]
],
[
[
"model_mnv2.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"## to fit the model you can write an expression as:\nhistory = model.fit_generator(train_generator,\n epochs=20,validation_data=validation_generator,)",
"_____no_output_____"
],
[
"The way keras train a model and make prediction is diffrent. In diffrent modes some layers such as batch_normalization operate diffrent. For example in train mode the mean and variance of each mini_batch is used to rescale the tensors but in test mode the moving average of mean and variance is pluging in for rescaling. So what is the problem. If the mode is set test and we train the data. The model shows a significant fit on train data but very poor results on validation data which is not a real overfitting problem. To understand when the result steming from this problem it is better to use same data for both train and validation. when the results in train and validation are different means that the learning phase is wrong.",
"_____no_output_____"
]
],
[
[
"history = model_mnv2.fit_generator(validation_generator,\n epochs=5,validation_data=validation_generator)\nmodel_mnv2.save('testlp.h5')\n####WARNING!!!!!!The below code make a copy of the model file on your google drive. keep it comment if you dont want the copy \nmodel_file = drive.CreateFile({'title' : 'testlp.h5'})\nmodel_file.SetContentFile('testlp.h5')\nmodel_file.Upload()",
"_____no_output_____"
]
],
[
[
"It can be seen that with feeding the model the same data for both train and validation, the resuts of each epoch is sharply different. Let change the learning phase ",
"_____no_output_____"
]
],
[
[
"K.clear_session()\nK.set_learning_phase(1)\nmodel_mnv2 = load_model('testlp.h5')\nprint(model_mnv2.evaluate_generator(validation_generator))",
"[0.06165256894784857, 0.9829422]\n"
]
],
[
[
"Setting learning phase to train yields the same results. So keep the learning phase equal 1 to set it as train for the rest part of training the model.",
"_____no_output_____"
]
],
[
[
"for layer in model_mnv2.layers:\n layer.trainable = False\nmodel_mnv2.layers[-1].trainable = True\nmodel_mnv2.layers[-2].trainable = True\nmodel_mnv2.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nhistory = model_mnv2.fit_generator(train_generator,\n epochs=5,validation_data=validation_generator)\n\nmodel_mnv2.save('mnv2_01.h5')\n####WARNING!!!!!!The below code make a copy of the model file on your google drive. keep it comment if you dont want the copy \nmodel_file = drive.CreateFile({'title' : 'mnv2_01.h5'})\nmodel_file.SetContentFile('mnv2_01.h5')\nmodel_file.Upload()",
"_____no_output_____"
]
],
[
[
"### Fine tuning?",
"_____no_output_____"
],
[
"Although training the model only on last two layer make happy with 99.8% accuracy on validation data (there is still difference between train and validation accuracy train_acc < val_acc keeping in mind we manipulated the train data but not the test data). It might can be even better. Lets give a try to fine tuning and release the constrains of frozen layers.",
"_____no_output_____"
]
],
[
[
"K.clear_session()\nK.set_learning_phase(1)\nmodel_mnv2 = load_model('mnv2_01.h5')\nfor layer in model_mnv2.layers:\n layer.trainable = True\nmodel_mnv2.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nhistory = model_mnv2.fit_generator(train_generator,\n epochs=20,validation_data=validation_generator)\nmodel_mnv2.save('mnv2_final.h5')\n####WARNING!!!!!!The below code make a copy of the model file on your google drive. keep it comment if you dont want the copy \nmodel_file = drive.CreateFile({'title' : 'mnv2_final.h5'})\nmodel_file.SetContentFile('mnv2_final.h5')\nmodel_file.Upload()\n",
"Epoch 1/20\n152/152 [==============================] - 13s 84ms/step - loss: 2.2130 - acc: 0.8122\n449/449 [==============================] - 157s 349ms/step - loss: 0.0122 - acc: 0.9970 - val_loss: 2.2130 - val_acc: 0.8122\nEpoch 2/20\n152/152 [==============================] - 12s 81ms/step - loss: 4.2625 - acc: 0.6612\n449/449 [==============================] - 152s 338ms/step - loss: 0.0121 - acc: 0.9973 - val_loss: 4.2625 - val_acc: 0.6612\nEpoch 3/20\n152/152 [==============================] - 12s 82ms/step - loss: 7.9470 - acc: 0.4138\n449/449 [==============================] - 151s 336ms/step - loss: 0.0128 - acc: 0.9970 - val_loss: 7.9470 - val_acc: 0.4138\nEpoch 4/20\n152/152 [==============================] - 12s 81ms/step - loss: 2.7799 - acc: 0.7455\n449/449 [==============================] - 150s 335ms/step - loss: 0.0101 - acc: 0.9977 - val_loss: 2.7799 - val_acc: 0.7455\nEpoch 5/20\n152/152 [==============================] - 12s 81ms/step - loss: 1.8795 - acc: 0.8247\n449/449 [==============================] - 151s 335ms/step - loss: 0.0099 - acc: 0.9978 - val_loss: 1.8795 - val_acc: 0.8247\nEpoch 6/20\n152/152 [==============================] - 12s 82ms/step - loss: 2.0416 - acc: 0.8302\n449/449 [==============================] - 153s 340ms/step - loss: 0.0077 - acc: 0.9979 - val_loss: 2.0416 - val_acc: 0.8302\nEpoch 7/20\n152/152 [==============================] - 12s 82ms/step - loss: 2.3354 - acc: 0.8107\n449/449 [==============================] - 151s 337ms/step - loss: 0.0121 - acc: 0.9974 - val_loss: 2.3354 - val_acc: 0.8107\nEpoch 8/20\n152/152 [==============================] - 13s 83ms/step - loss: 1.7058 - acc: 0.8397\n449/449 [==============================] - 152s 338ms/step - loss: 0.0093 - acc: 0.9978 - val_loss: 1.7058 - val_acc: 0.8397\nEpoch 9/20\n152/152 [==============================] - 12s 81ms/step - loss: 2.7164 - acc: 0.7774\n449/449 [==============================] - 152s 338ms/step - loss: 0.0089 - acc: 0.9982 - val_loss: 2.7164 - val_acc: 0.7774\nEpoch 10/20\n152/152 [==============================] - 13s 83ms/step - loss: 0.9241 - acc: 0.8907\n449/449 [==============================] - 151s 336ms/step - loss: 0.0091 - acc: 0.9979 - val_loss: 0.9241 - val_acc: 0.8907\nEpoch 11/20\n152/152 [==============================] - 12s 82ms/step - loss: 1.3316 - acc: 0.8530\n449/449 [==============================] - 151s 337ms/step - loss: 0.0066 - acc: 0.9984 - val_loss: 1.3316 - val_acc: 0.8530\nEpoch 12/20\n152/152 [==============================] - 12s 82ms/step - loss: 4.8491 - acc: 0.6269\n449/449 [==============================] - 151s 336ms/step - loss: 0.0091 - acc: 0.9977 - val_loss: 4.8491 - val_acc: 0.6269\nEpoch 13/20\n152/152 [==============================] - 12s 82ms/step - loss: 0.8029 - acc: 0.8958\n449/449 [==============================] - 151s 337ms/step - loss: 0.0106 - acc: 0.9979 - val_loss: 0.8029 - val_acc: 0.8958\nEpoch 14/20\n152/152 [==============================] - 12s 81ms/step - loss: 0.7053 - acc: 0.9269\n449/449 [==============================] - 152s 338ms/step - loss: 0.0089 - acc: 0.9982 - val_loss: 0.7053 - val_acc: 0.9269\nEpoch 15/20\n152/152 [==============================] - 12s 82ms/step - loss: 2.1088 - acc: 0.7913\n449/449 [==============================] - 153s 340ms/step - loss: 0.0097 - acc: 0.9986 - val_loss: 2.1088 - val_acc: 0.7913\nEpoch 16/20\n152/152 [==============================] - 12s 82ms/step - loss: 0.9216 - acc: 0.8838\n449/449 [==============================] - 151s 336ms/step - loss: 0.0075 - acc: 0.9986 - val_loss: 0.9216 - val_acc: 0.8838\nEpoch 17/20\n152/152 [==============================] - 12s 82ms/step - loss: 3.6274 - acc: 0.6891\n449/449 [==============================] - 152s 337ms/step - loss: 0.0086 - acc: 0.9982 - val_loss: 3.6274 - val_acc: 0.6891\nEpoch 18/20\n152/152 [==============================] - 12s 82ms/step - loss: 2.4093 - acc: 0.7943\n449/449 [==============================] - 152s 338ms/step - loss: 0.0082 - acc: 0.9981 - val_loss: 2.4093 - val_acc: 0.7943\nEpoch 19/20\n152/152 [==============================] - 13s 83ms/step - loss: 0.3208 - acc: 0.9702\n449/449 [==============================] - 151s 337ms/step - loss: 0.0063 - acc: 0.9986 - val_loss: 0.3208 - val_acc: 0.9702\nEpoch 20/20\n 27/449 [>.............................] - ETA: 1:32 - loss: 0.0122 - acc: 0.9983"
]
],
[
[
"### once you have obtained the final estimate of the model you must evaluate it with more details . . .",
"_____no_output_____"
]
],
[
[
"plt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.legend(['Train', 'Test'])\nplt.suptitle('Accuracy')\nplt.xlabel('Iteration')\nplt.show()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['Train', 'Test'])\nplt.suptitle('Categorical Cross Entropy')\nplt.xlabel('Iteration')\nplt.show()\n\n\ny_true = validation_generator.classes\ny_pred = model_mnv2.predict_generator(validation_generator,verbose=1).argmax(axis=-1)\n\nprint(y_pred.shape)\nprint(y_true.shape)",
"_____no_output_____"
]
],
[
[
"### take an image of a papaya from internet and try to apply your model . . .",
"_____no_output_____"
]
],
[
[
"import requests\nf = open('papaya.jpg','wb')\nf.write(requests.get('https://www.xspo.it/media/image/16/0a/59/18_m-neal-pt_apple-green_600x600.jpg').content)\nf.close()\nimg = image.load_img('papaya.jpg', target_size=(128, 128))\nimg = image.img_to_array(img)\nimg = np.expand_dims(img, axis=0)\nprint(img.shape)\nimg_pred = int(model_mnv2.predict(img).argmax(axis=-1))\nx = list(validation_generator.class_indices.keys())\nprint(x[img_pred])",
"(1, 128, 128, 3)\nApple Red Yellow\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba4e24a5f182605db2618b6cb1fe69f49232d6c
| 46,731 |
ipynb
|
Jupyter Notebook
|
Support notebooks/Clustering & Sarima model.ipynb
|
MoshaLangerak/Data_Challenge_2_Group_18
|
34325993376edb967723611d0a86ccef748932d1
|
[
"MIT"
] | null | null | null |
Support notebooks/Clustering & Sarima model.ipynb
|
MoshaLangerak/Data_Challenge_2_Group_18
|
34325993376edb967723611d0a86ccef748932d1
|
[
"MIT"
] | null | null | null |
Support notebooks/Clustering & Sarima model.ipynb
|
MoshaLangerak/Data_Challenge_2_Group_18
|
34325993376edb967723611d0a86ccef748932d1
|
[
"MIT"
] | null | null | null | 65.44958 | 15,494 | 0.741585 |
[
[
[
"import pandas as pd\nimport seaborn as sns\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans",
"_____no_output_____"
]
],
[
[
"# Clustering",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv('2019_data.csv', encoding='utf-8', decimal=',')\ndata.shape\nprob = data",
"_____no_output_____"
],
[
"#to give insight in the crimes per LSOA in 2019\ncrimerate = prob.groupby('LSOA code')['Month'].count()\n#sum(crimerate.values)\ncrimerate",
"_____no_output_____"
],
[
"#to get the cluster data for each lsoa once\nprob = prob.drop_duplicates(subset=\"LSOA code\", keep='first')",
"_____no_output_____"
],
[
"#remove the nan values\na = prob[prob['Employment Domain Score'].notna()]",
"_____no_output_____"
],
[
"### Get all the features columns except the class\nfeatures_lst = ['LSOA code','Employment Domain Score','Income Domain Score','IDACI Score','IDAOPI Score','Police Strength',\n 'Police Funding','Population']\n\n\n### Get the features data\ndata = a[features_lst].reset_index()",
"_____no_output_____"
],
[
"fit_data = data[['Employment Domain Score', 'Income Domain Score',\n 'IDACI Score', 'IDAOPI Score', 'Police Strength', 'Police Funding',\n 'Population']]",
"_____no_output_____"
],
[
"#remove the 1.101.360 -> this is not computable to float\nfit_data['Population'] = fit_data['Population'].replace(['1.101.360'],'1101.360')",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n"
],
[
"#replace the nan values with the mode of the column\nfor column in fit_data.columns:\n fit_data[column].fillna(fit_data[column].mode()[0], inplace=True)",
"C:\\Users\\20202201\\AppData\\Roaming\\Python\\Python37\\site-packages\\pandas\\core\\generic.py:6392: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return self._update_inplace(result)\n"
],
[
"fit_data",
"_____no_output_____"
]
],
[
[
"# constrained clustering",
"_____no_output_____"
]
],
[
[
"from k_means_constrained import KMeansConstrained",
"_____no_output_____"
],
[
"clf = KMeansConstrained(n_clusters = 50, size_min=250, size_max=800,random_state=0)",
"_____no_output_____"
],
[
"clf.fit(fit_data)",
"_____no_output_____"
],
[
"#make a new dataframe\nlabel_data = pd.DataFrame({'LSOA code': data['LSOA code'], 'Cluster': clf.labels_})\n#label_data",
"_____no_output_____"
],
[
"label_data.sort_values(by=['LSOA code'], inplace = True)\nlabel_data['crime numb'] = crimerate.values\nlabel_data.groupby('Cluster')['crime numb'].sum().plot(kind ='bar', ylabel='Number of crimes', \n title=' Distribution of crimes over the clusters');",
"_____no_output_____"
]
],
[
[
"## code for merging dataclusters",
"_____no_output_____"
]
],
[
[
"label_data.groupby('Cluster')",
"_____no_output_____"
],
[
"#makes a dataframe for each cluster\ndf = [x for _, x in label_data.groupby('Cluster')]\nnumbcrimes = []\nfor i in df:\n numbcrimes.append(i['crime numb'].sum())",
"_____no_output_____"
],
[
"plt.hist(numbcrimes, bins=23)",
"_____no_output_____"
],
[
"cluster1 = df[2]['LSOA code'].values.tolist()\n#cluster1",
"_____no_output_____"
],
[
"df_street = pd.read_csv('city-of-london_street.csv')\ndf_street.index = pd.to_datetime(df_street['Month'])\ndf_notna = df_street[df_street['LSOA code'].notna()]",
"_____no_output_____"
],
[
"df_notna = df_notna[df_notna['LSOA code'].isin(cluster1)]",
"_____no_output_____"
],
[
"data = df_notna.groupby(by=[df_notna.index.date])['Month'].count()\ndata",
"_____no_output_____"
]
],
[
[
"# The sarima model",
"_____no_output_____"
]
],
[
[
"import datetime\nimport pmdarima as pm",
"_____no_output_____"
],
[
"# split the data into train and testdata and remove the covid data\nfor t in range(0,len(data.index)):\n if data.index[t] >= datetime.date(2019, 1, 1):\n break\nfor m in range(t+1, len(data.index)):\n if data.index[m] >= datetime.date(2020,1,1):\n break\n\ndata_train = data[:t]\ndata_test = data[t:m]",
"_____no_output_____"
],
[
"#plot the train test split\nsns.lineplot(data=data_train)\nsns.lineplot(data=data_test);",
"_____no_output_____"
],
[
"# Seasonal - fit stepwise auto-ARIMA\nSarima = pm.auto_arima(data_train, start_p=1, start_q=1,\n test='adf',\n max_p=3, max_q=3, m=12,\n start_P=0, seasonal=True,\n d=None, D=1, trace=True,\n error_action='ignore', \n suppress_warnings=True, \n stepwise=True)\n\nSarima.summary() ",
"_____no_output_____"
],
[
"n_periods = 12\nfitted, confint = Sarima.predict(n_periods=n_periods, return_conf_int=True)\nindex_of_fc = pd.date_range(data_train.index[-1], periods = n_periods, freq='MS')\n\n# make series for plotting purpose\nfitted_series = pd.Series(fitted, index=index_of_fc)\nlower_series = pd.Series(confint[:, 0], index=index_of_fc)\nupper_series = pd.Series(confint[:, 1], index=index_of_fc)\n\n# Plot\nplt.plot(data_train)\nplt.plot(fitted_series, color='darkgreen')\nplt.fill_between(lower_series.index, \n lower_series, \n upper_series, \n color='k', alpha=.15)\n\nplt.title(\"SARIMA model for LSOA E01000001\")\nplt.plot(data_test)\nplt.legend()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cba4e68a78f53233533f01c3849b26563508d30d
| 23,766 |
ipynb
|
Jupyter Notebook
|
tutorials/reinforcement learning/assignment1.ipynb
|
h-mayorquin/camp_india_2016
|
a8bf8db7778c39c7ca959a7f876c1aa85f2cae8b
|
[
"MIT"
] | 3 |
2019-04-10T07:38:55.000Z
|
2020-11-15T18:33:18.000Z
|
tutorials/reinforcement learning/assignment1.ipynb
|
h-mayorquin/camp_india_2016
|
a8bf8db7778c39c7ca959a7f876c1aa85f2cae8b
|
[
"MIT"
] | null | null | null |
tutorials/reinforcement learning/assignment1.ipynb
|
h-mayorquin/camp_india_2016
|
a8bf8db7778c39c7ca959a7f876c1aa85f2cae8b
|
[
"MIT"
] | null | null | null | 89.011236 | 10,454 | 0.803122 |
[
[
[
"from gridworld import *\n% matplotlib inline\n\n# create the gridworld as a specific MDP\ngridworld=GridMDP([[-0.04,-0.04,-0.04,1],[-0.04,None, -0.04, -1], [-0.04, -0.04, -0.04, -0.04]], terminals=[(3,2), (3,1)], gamma=1.)\n\nexample_pi = {(0,0): (0,1), (0,1): (0,1), (0,2): (1,0), (1,0): (1,0), (1,2): (1,0), (2,0): (0,1), (2,1): (0,1), (2,2): (1,0), (3,0):(-1,0), (3,1): None, (3,2):None}\n\nexample_V = {(0,0): 0.1, (0,1): 0.2, (0,2): 0.3, (1,0): 0.05, (1,2): 0.5, (2,0): 0., (2,1): -0.2, (2,2): 0.5, (3,0):-0.4, (3,1): -1, (3,2):+1}",
"_____no_output_____"
],
[
"\"\"\" \n1) \tComplete the function policy evaluation below and use it on example_pi!\n\tThe function takes as input a policy pi, and an MDP (including its transition model, \n\treward and discounting factor gamma), and gives as output the value function for this\n\tspecific policy in the MDP. Use equation (1) in the lecture slides!\n\"\"\"\n\n\ndef policy_evaluation(pi, V, mdp, k=20):\n \"\"\"Return an updated value function V for each state in the MDP \"\"\"\n R, T, gamma = mdp.R, mdp.T, mdp.gamma\t# retrieve reward, transition model and gamma from the MDP\n for i in range(k):\t\t\t\t# iterative update of V\n for s in mdp.states:\n V[s] = R(s) + gamma\n action = pi[s]\n probabilities = T(s, action)\n aux = 0\n for p, state in probabilities:\n aux += p * V[state] \n V[s] += aux\n # raise NotImplementedError # implement iterative policy evaluation here\n return V",
"_____no_output_____"
],
[
"def policy_evaluation(pi, V, mdp, k=20):\n \"\"\"Return an updated value function V for each state in the MDP \"\"\"\n R, T, gamma = mdp.R, mdp.T, mdp.gamma\t# retrieve reward, transition model and gamma from the MDP\n for i in range(k):\t\t\t\t# iterative update of V\n for s in mdp.states:\n V[s] = R(s) + gamma * sum([p * V[s1] for (p, s1) in T(s, pi[s])])\n return V",
"_____no_output_____"
],
[
"R = gridworld.R\nT = gridworld.T",
"_____no_output_____"
],
[
"V=policy_evaluation(example_pi, example_V, gridworld)\ngridworld.policy_plot(example_pi)",
"_____no_output_____"
],
[
"print(V)",
"{(1, 2): 0.8678082191892927, (3, 2): 1.0, (0, 0): 0.6910041685693834, (3, 0): 0.35695253067190863, (2, 1): 0.6602739726059087, (1, 0): 0.5265715933617807, (0, 1): 0.7615582342646277, (3, 1): -1.0, (2, 0): 0.5765715913091487, (2, 2): 0.9178082191786289, (0, 2): 0.8115582213945166}\n"
],
[
"gridworld.v_plot(V)",
"_____no_output_____"
],
[
"\"\"\"\n2)\tComplete the function value iteration below and use it to compute the optimal value function for the gridworld.\n\tThe function takes as input the MDP (including reward function and transition model) and is supposed to compute\n\tthe optimal value function using the value iteration algorithm presented in the lecture. Use the function best_policy\n\tto compute to compute the optimal policy under this value function!\n\n\"\"\"\n\ndef value_iteration(mdp, epsilon=0.0001):\n \"Solving an MDP by value iteration. epsilon determines the convergence criterion for stopping\"\n V1 = dict([(s, 0) for s in mdp.states]) # initialize value function\n R, T, gamma = mdp.R, mdp.T, mdp.gamma\n while True:\n V = V1.copy()\n delta = 0\n for s in mdp.states:\n raise NotImplementedError # implement the value iteration step here\n delta = max(delta, abs(V1[s] - V[s]))\n if delta < epsilon:\n return V\n\n\ndef argmax(seq, fn):\n best = seq[0]; best_score = fn(best)\n for x in seq:\n x_score = fn(x)\n if x_score > best_score:\n best, best_score = x, x_score\n return best\n\ndef expected_utility(a, s, V, mdp):\n \"The expected utility of doing a in state s, according to the MDP and U.\"\n return sum([p * V[s1] for (p, s1) in mdp.T(s, a)])\n\n\ndef best_policy(mdp, V):\n \"\"\"Given an MDP and a utility function V, best_policy determines the best policy,\n as a mapping from state to action. \"\"\"\n pi = {}\n for s in mdp.states:\n pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, V, mdp))\n return pi",
"_____no_output_____"
],
[
"Vopt=value_iteration(gridworld)\npiopt = best_policy(gridworld, Vopt)\ngridworld.policy_plot(piopt)\ngridworld.v_plot(Vopt)",
"_____no_output_____"
],
[
"\"\"\"\n3)\tComplete the function policy iteration below and use it to compute the optimal policy for the gridworld.\n\tThe function takes as input the MDP (including reward function and transition model) and is supposed to compute\n\tthe optimal policy using the policy iteration algorithm presented in the lecture. Compare the result with what\n\tyou got from running value_iteration and best_policy!\t\n\"\"\"\n\n\ndef policy_iteration(mdp):\n \"Solve an MDP by policy iteration\"\n V = dict([(s, 0) for s in mdp.states])\n pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states])\n while True:\n raise NotImplementedError # find value function for this policy \n unchanged = True\n for s in mdp.states:\n raise NotImplementedError # update policy\n if a != pi[s]:\n unchanged = False\n if unchanged: \n return pi",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba4e9034979b9b0e389080b18233313411b4e63
| 300,503 |
ipynb
|
Jupyter Notebook
|
xgboost/LinearAndQuadraticFunctionRegression/quadratic_xgboost_localmode.ipynb
|
udaysatapathy/aws_sagemaker
|
6aca5a52b8dee0161ed6c7a75bc7a7e33205af99
|
[
"Apache-2.0"
] | 2 |
2020-11-30T14:36:57.000Z
|
2020-12-31T19:48:45.000Z
|
xgboost/LinearAndQuadraticFunctionRegression/quadratic_xgboost_localmode.ipynb
|
Srvand/AmazonSageMakerCourse
|
77161445c68a5f0318ca469a9780aefcee713713
|
[
"Apache-2.0"
] | 5 |
2020-05-22T14:10:02.000Z
|
2022-03-25T19:13:05.000Z
|
xgboost/LinearAndQuadraticFunctionRegression/quadratic_xgboost_localmode.ipynb
|
Srvand/AmazonSageMakerCourse
|
77161445c68a5f0318ca469a9780aefcee713713
|
[
"Apache-2.0"
] | 3 |
2020-11-02T10:33:46.000Z
|
2020-11-03T05:50:51.000Z
| 174.103708 | 24,760 | 0.892091 |
[
[
[
"<h2>Quadratic Regression Dataset - Linear Regression vs XGBoost</h2>\n\nModel is trained with XGBoost installed in notebook instance\n\nIn the later examples, we will train using SageMaker's XGBoost algorithm.\n\nTraining on SageMaker takes several minutes (even for simple dataset). \n\nIf algorithm is supported on Python, we will try them locally on notebook instance\n\nThis allows us to quickly learn an algorithm, understand tuning options and then finally train on SageMaker Cloud\n\nIn this exercise, let's compare XGBoost and Linear Regression for Quadratic regression dataset",
"_____no_output_____"
]
],
[
[
"# Install xgboost in notebook instance.\n#### Command to install xgboost\n!conda install -y -c conda-forge xgboost",
"_____no_output_____"
],
[
"import sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\n\n# XGBoost \nimport xgboost as xgb\n# Linear Regression\nfrom sklearn.linear_model import LinearRegression",
"_____no_output_____"
],
[
"df = pd.read_csv('quadratic_all.csv')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"plt.plot(df.x,df.y,label='Target')\nplt.grid(True)\nplt.xlabel('Input Feature')\nplt.ylabel('Target')\nplt.legend()\nplt.title('Quadratic Regression Dataset')\nplt.show()",
"_____no_output_____"
],
[
"train_file = 'quadratic_train.csv'\nvalidation_file = 'quadratic_validation.csv'\n\n# Specify the column names as the file does not have column header\ndf_train = pd.read_csv(train_file,names=['y','x'])\ndf_validation = pd.read_csv(validation_file,names=['y','x'])",
"_____no_output_____"
],
[
"df_train.head()",
"_____no_output_____"
],
[
"df_validation.head()",
"_____no_output_____"
],
[
"plt.scatter(df_train.x,df_train.y,label='Training',marker='.')\nplt.scatter(df_validation.x,df_validation.y,label='Validation',marker='.')\nplt.grid(True)\nplt.xlabel('Input Feature')\nplt.ylabel('Target')\nplt.title('Quadratic Regression Dataset')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"X_train = df_train.iloc[:,1:] # Features: 1st column onwards \ny_train = df_train.iloc[:,0].ravel() # Target: 0th column\n\nX_validation = df_validation.iloc[:,1:]\ny_validation = df_validation.iloc[:,0].ravel()",
"_____no_output_____"
],
[
"# Create an instance of XGBoost Regressor\n# XGBoost Training Parameter Reference: \n# https://github.com/dmlc/xgboost/blob/master/doc/parameter.md\nregressor = xgb.XGBRegressor()",
"_____no_output_____"
],
[
"regressor",
"_____no_output_____"
],
[
"regressor.fit(X_train,y_train, eval_set = [(X_train, y_train), (X_validation, y_validation)])",
"[0]\tvalidation_0-rmse:852.082\tvalidation_1-rmse:931.882\n[1]\tvalidation_0-rmse:776.32\tvalidation_1-rmse:853.857\n[2]\tvalidation_0-rmse:707.455\tvalidation_1-rmse:779.725\n[3]\tvalidation_0-rmse:644.955\tvalidation_1-rmse:711.567\n[4]\tvalidation_0-rmse:587.747\tvalidation_1-rmse:652.779\n[5]\tvalidation_0-rmse:536.019\tvalidation_1-rmse:595.832\n[6]\tvalidation_0-rmse:490.469\tvalidation_1-rmse:545.727\n[7]\tvalidation_0-rmse:447.317\tvalidation_1-rmse:499.978\n[8]\tvalidation_0-rmse:410.19\tvalidation_1-rmse:460.088\n[9]\tvalidation_0-rmse:374.376\tvalidation_1-rmse:421.358\n[10]\tvalidation_0-rmse:342.484\tvalidation_1-rmse:387.917\n[11]\tvalidation_0-rmse:313.615\tvalidation_1-rmse:357.32\n[12]\tvalidation_0-rmse:286.623\tvalidation_1-rmse:328.889\n[13]\tvalidation_0-rmse:263.527\tvalidation_1-rmse:303.867\n[14]\tvalidation_0-rmse:241.564\tvalidation_1-rmse:280.437\n[15]\tvalidation_0-rmse:220.987\tvalidation_1-rmse:259.537\n[16]\tvalidation_0-rmse:202.775\tvalidation_1-rmse:239.52\n[17]\tvalidation_0-rmse:185.624\tvalidation_1-rmse:221.308\n[18]\tvalidation_0-rmse:169.985\tvalidation_1-rmse:204.528\n[19]\tvalidation_0-rmse:155.672\tvalidation_1-rmse:188.946\n[20]\tvalidation_0-rmse:143.911\tvalidation_1-rmse:176.024\n[21]\tvalidation_0-rmse:131.927\tvalidation_1-rmse:163.092\n[22]\tvalidation_0-rmse:122.288\tvalidation_1-rmse:152.472\n[23]\tvalidation_0-rmse:112.724\tvalidation_1-rmse:142.155\n[24]\tvalidation_0-rmse:103.577\tvalidation_1-rmse:132.591\n[25]\tvalidation_0-rmse:96.2028\tvalidation_1-rmse:125.041\n[26]\tvalidation_0-rmse:89.6539\tvalidation_1-rmse:118.124\n[27]\tvalidation_0-rmse:83.4567\tvalidation_1-rmse:111.683\n[28]\tvalidation_0-rmse:77.1489\tvalidation_1-rmse:104.977\n[29]\tvalidation_0-rmse:71.185\tvalidation_1-rmse:98.6005\n[30]\tvalidation_0-rmse:66.7935\tvalidation_1-rmse:93.733\n[31]\tvalidation_0-rmse:62.0247\tvalidation_1-rmse:88.7958\n[32]\tvalidation_0-rmse:57.5019\tvalidation_1-rmse:84.0843\n[33]\tvalidation_0-rmse:53.3899\tvalidation_1-rmse:79.9241\n[34]\tvalidation_0-rmse:50.374\tvalidation_1-rmse:76.5818\n[35]\tvalidation_0-rmse:47.1971\tvalidation_1-rmse:73.4824\n[36]\tvalidation_0-rmse:44.197\tvalidation_1-rmse:70.5546\n[37]\tvalidation_0-rmse:41.3579\tvalidation_1-rmse:67.7262\n[38]\tvalidation_0-rmse:39.3363\tvalidation_1-rmse:65.4868\n[39]\tvalidation_0-rmse:37.4231\tvalidation_1-rmse:63.4876\n[40]\tvalidation_0-rmse:35.4398\tvalidation_1-rmse:61.56\n[41]\tvalidation_0-rmse:33.4339\tvalidation_1-rmse:59.6057\n[42]\tvalidation_0-rmse:32.1077\tvalidation_1-rmse:58.001\n[43]\tvalidation_0-rmse:30.5971\tvalidation_1-rmse:56.4862\n[44]\tvalidation_0-rmse:29.2108\tvalidation_1-rmse:55.066\n[45]\tvalidation_0-rmse:27.911\tvalidation_1-rmse:53.6888\n[46]\tvalidation_0-rmse:26.7067\tvalidation_1-rmse:52.5642\n[47]\tvalidation_0-rmse:25.9105\tvalidation_1-rmse:51.5398\n[48]\tvalidation_0-rmse:25.1748\tvalidation_1-rmse:50.5098\n[49]\tvalidation_0-rmse:24.5456\tvalidation_1-rmse:49.5845\n[50]\tvalidation_0-rmse:23.7487\tvalidation_1-rmse:48.7455\n[51]\tvalidation_0-rmse:23.0308\tvalidation_1-rmse:47.9645\n[52]\tvalidation_0-rmse:22.3726\tvalidation_1-rmse:47.2763\n[53]\tvalidation_0-rmse:21.9597\tvalidation_1-rmse:46.6645\n[54]\tvalidation_0-rmse:21.6126\tvalidation_1-rmse:46.2015\n[55]\tvalidation_0-rmse:21.2343\tvalidation_1-rmse:45.6802\n[56]\tvalidation_0-rmse:20.7674\tvalidation_1-rmse:45.2139\n[57]\tvalidation_0-rmse:20.3399\tvalidation_1-rmse:44.7713\n[58]\tvalidation_0-rmse:19.95\tvalidation_1-rmse:44.3476\n[59]\tvalidation_0-rmse:19.7295\tvalidation_1-rmse:43.9905\n[60]\tvalidation_0-rmse:19.5036\tvalidation_1-rmse:43.6282\n[61]\tvalidation_0-rmse:19.2442\tvalidation_1-rmse:43.3416\n[62]\tvalidation_0-rmse:18.9807\tvalidation_1-rmse:43.1059\n[63]\tvalidation_0-rmse:18.7383\tvalidation_1-rmse:42.8711\n[64]\tvalidation_0-rmse:18.596\tvalidation_1-rmse:42.6286\n[65]\tvalidation_0-rmse:18.4014\tvalidation_1-rmse:42.4372\n[66]\tvalidation_0-rmse:18.0438\tvalidation_1-rmse:42.2478\n[67]\tvalidation_0-rmse:17.9386\tvalidation_1-rmse:42.0598\n[68]\tvalidation_0-rmse:17.8332\tvalidation_1-rmse:41.8871\n[69]\tvalidation_0-rmse:17.6853\tvalidation_1-rmse:41.7788\n[70]\tvalidation_0-rmse:17.3457\tvalidation_1-rmse:41.6835\n[71]\tvalidation_0-rmse:17.0409\tvalidation_1-rmse:41.5889\n[72]\tvalidation_0-rmse:16.9435\tvalidation_1-rmse:41.4817\n[73]\tvalidation_0-rmse:16.859\tvalidation_1-rmse:41.3854\n[74]\tvalidation_0-rmse:16.8006\tvalidation_1-rmse:41.2934\n[75]\tvalidation_0-rmse:16.706\tvalidation_1-rmse:41.1916\n[76]\tvalidation_0-rmse:16.6574\tvalidation_1-rmse:41.1213\n[77]\tvalidation_0-rmse:16.5384\tvalidation_1-rmse:41.1996\n[78]\tvalidation_0-rmse:16.4813\tvalidation_1-rmse:41.1091\n[79]\tvalidation_0-rmse:16.4372\tvalidation_1-rmse:41.0326\n[80]\tvalidation_0-rmse:16.357\tvalidation_1-rmse:40.998\n[81]\tvalidation_0-rmse:16.1302\tvalidation_1-rmse:41.0025\n[82]\tvalidation_0-rmse:16.0942\tvalidation_1-rmse:40.9609\n[83]\tvalidation_0-rmse:16.0651\tvalidation_1-rmse:40.941\n[84]\tvalidation_0-rmse:16.0229\tvalidation_1-rmse:40.8927\n[85]\tvalidation_0-rmse:15.9948\tvalidation_1-rmse:40.8606\n[86]\tvalidation_0-rmse:15.914\tvalidation_1-rmse:40.8323\n[87]\tvalidation_0-rmse:15.8566\tvalidation_1-rmse:40.8679\n[88]\tvalidation_0-rmse:15.8353\tvalidation_1-rmse:40.8268\n[89]\tvalidation_0-rmse:15.8092\tvalidation_1-rmse:40.7789\n[90]\tvalidation_0-rmse:15.6231\tvalidation_1-rmse:40.7666\n[91]\tvalidation_0-rmse:15.4342\tvalidation_1-rmse:40.9844\n[92]\tvalidation_0-rmse:15.3841\tvalidation_1-rmse:40.9501\n[93]\tvalidation_0-rmse:15.2451\tvalidation_1-rmse:40.9186\n[94]\tvalidation_0-rmse:15.1827\tvalidation_1-rmse:40.9995\n[95]\tvalidation_0-rmse:15.1632\tvalidation_1-rmse:40.9341\n[96]\tvalidation_0-rmse:15.1479\tvalidation_1-rmse:40.9171\n[97]\tvalidation_0-rmse:15.1357\tvalidation_1-rmse:40.8928\n[98]\tvalidation_0-rmse:14.9294\tvalidation_1-rmse:40.9756\n[99]\tvalidation_0-rmse:14.8071\tvalidation_1-rmse:40.9805\n"
],
[
"eval_result = regressor.evals_result()",
"_____no_output_____"
],
[
"training_rounds = range(len(eval_result['validation_0']['rmse']))",
"_____no_output_____"
],
[
"plt.scatter(x=training_rounds,y=eval_result['validation_0']['rmse'],label='Training Error')\nplt.scatter(x=training_rounds,y=eval_result['validation_1']['rmse'],label='Validation Error')\nplt.grid(True)\nplt.xlabel('Iteration')\nplt.ylabel('RMSE')\nplt.title('Training Vs Validation Error')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"xgb.plot_importance(regressor)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Validation Dataset Compare Actual and Predicted",
"_____no_output_____"
]
],
[
[
"result = regressor.predict(X_validation)",
"_____no_output_____"
],
[
"result[:5]",
"_____no_output_____"
],
[
"plt.title('XGBoost - Validation Dataset')\nplt.scatter(df_validation.x,df_validation.y,label='actual',marker='.')\nplt.scatter(df_validation.x,result,label='predicted',marker='.')\nplt.grid(True)\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# RMSE Metrics\nprint('XGBoost Algorithm Metrics')\nmse = mean_squared_error(df_validation.y,result)\nprint(\" Mean Squared Error: {0:.2f}\".format(mse))\nprint(\" Root Mean Square Error: {0:.2f}\".format(mse**.5))",
"XGBoost Algorithm Metrics\n Mean Squared Error: 1679.40\n Root Mean Square Error: 40.98\n"
],
[
"# Residual\n# Over prediction and Under Prediction needs to be balanced\n# Training Data Residuals\nresiduals = df_validation.y - result\nplt.hist(residuals)\nplt.grid(True)\nplt.xlabel('Actual - Predicted')\nplt.ylabel('Count')\nplt.title('XGBoost Residual')\nplt.axvline(color='r')\nplt.show()",
"_____no_output_____"
],
[
"# Count number of values greater than zero and less than zero\nvalue_counts = (residuals > 0).value_counts(sort=False)\n\nprint(' Under Estimation: {0}'.format(value_counts[True]))\nprint(' Over Estimation: {0}'.format(value_counts[False]))",
" Under Estimation: 29\n Over Estimation: 33\n"
],
[
"# Plot for entire dataset\nplt.plot(df.x,df.y,label='Target')\nplt.plot(df.x,regressor.predict(df[['x']]) ,label='Predicted')\nplt.grid(True)\nplt.xlabel('Input Feature')\nplt.ylabel('Target')\nplt.legend()\nplt.title('XGBoost')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Linear Regression Algorithm",
"_____no_output_____"
]
],
[
[
"lin_regressor = LinearRegression()",
"_____no_output_____"
],
[
"lin_regressor.fit(X_train,y_train)",
"_____no_output_____"
]
],
[
[
"Compare Weights assigned by Linear Regression.\n\nOriginal Function: 5*x**2 -23*x + 47 + some noise\n\nLinear Regression Function: -15.08 * x + 709.86 \n\nLinear Regression Coefficients and Intercepts are not close to actual",
"_____no_output_____"
]
],
[
[
"lin_regressor.coef_",
"_____no_output_____"
],
[
"lin_regressor.intercept_",
"_____no_output_____"
],
[
"result = lin_regressor.predict(df_validation[['x']])",
"_____no_output_____"
],
[
"plt.title('LinearRegression - Validation Dataset')\nplt.scatter(df_validation.x,df_validation.y,label='actual',marker='.')\nplt.scatter(df_validation.x,result,label='predicted',marker='.')\nplt.grid(True)\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# RMSE Metrics\nprint('Linear Regression Metrics')\nmse = mean_squared_error(df_validation.y,result)\nprint(\" Mean Squared Error: {0:.2f}\".format(mse))\nprint(\" Root Mean Square Error: {0:.2f}\".format(mse**.5))",
"Linear Regression Metrics\n Mean Squared Error: 488269.59\n Root Mean Square Error: 698.76\n"
],
[
"# Residual\n# Over prediction and Under Prediction needs to be balanced\n# Training Data Residuals\nresiduals = df_validation.y - result\nplt.hist(residuals)\nplt.grid(True)\nplt.xlabel('Actual - Predicted')\nplt.ylabel('Count')\nplt.title('Linear Regression Residual')\nplt.axvline(color='r')\nplt.show()",
"_____no_output_____"
],
[
"# Count number of values greater than zero and less than zero\nvalue_counts = (residuals > 0).value_counts(sort=False)\n\nprint(' Under Estimation: {0}'.format(value_counts[True]))\nprint(' Over Estimation: {0}'.format(value_counts[False]))",
" Under Estimation: 25\n Over Estimation: 37\n"
],
[
"# Plot for entire dataset\nplt.plot(df.x,df.y,label='Target')\nplt.plot(df.x,lin_regressor.predict(df[['x']]) ,label='Predicted')\nplt.grid(True)\nplt.xlabel('Input Feature')\nplt.ylabel('Target')\nplt.legend()\nplt.title('LinearRegression')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Linear Regression is showing clear symptoms of under-fitting\n\nInput Features are not sufficient to capture complex relationship",
"_____no_output_____"
],
[
"<h2>Your Turn</h2>\nYou can correct this under-fitting issue by adding relavant features.\n\n1. What feature will you add and why?\n2. Complete the code and Test\n3. What performance do you see now?",
"_____no_output_____"
]
],
[
[
"# Specify the column names as the file does not have column header\ndf_train = pd.read_csv(train_file,names=['y','x'])\ndf_validation = pd.read_csv(validation_file,names=['y','x'])\ndf = pd.read_csv('quadratic_all.csv')",
"_____no_output_____"
]
],
[
[
"# Add new features ",
"_____no_output_____"
]
],
[
[
"# Place holder to add new features to df_train, df_validation and df\n# if you need help, scroll down to see the answer\n# Add your code",
"_____no_output_____"
],
[
"X_train = df_train.iloc[:,1:] # Features: 1st column onwards \ny_train = df_train.iloc[:,0].ravel() # Target: 0th column\n\nX_validation = df_validation.iloc[:,1:]\ny_validation = df_validation.iloc[:,0].ravel()",
"_____no_output_____"
],
[
"lin_regressor.fit(X_train,y_train)",
"_____no_output_____"
]
],
[
[
"Original Function: -23*x + 5*x**2 + 47 + some noise (rewritten with x term first)",
"_____no_output_____"
]
],
[
[
"lin_regressor.coef_",
"_____no_output_____"
],
[
"lin_regressor.intercept_",
"_____no_output_____"
],
[
"result = lin_regressor.predict(X_validation)",
"_____no_output_____"
],
[
"plt.title('LinearRegression - Validation Dataset')\nplt.scatter(df_validation.x,df_validation.y,label='actual',marker='.')\nplt.scatter(df_validation.x,result,label='predicted',marker='.')\nplt.grid(True)\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# RMSE Metrics\nprint('Linear Regression Metrics')\nmse = mean_squared_error(df_validation.y,result)\nprint(\" Mean Squared Error: {0:.2f}\".format(mse))\nprint(\" Root Mean Square Error: {0:.2f}\".format(mse**.5))\n\nprint(\"***You should see an RMSE score of 30.45 or less\")",
"Linear Regression Metrics\n Mean Squared Error: 927.22\n Root Mean Square Error: 30.45\n***You should see an RMSE score of 30.45 or less\n"
],
[
"df.head()",
"_____no_output_____"
],
[
"# Plot for entire dataset\nplt.plot(df.x,df.y,label='Target')\nplt.plot(df.x,lin_regressor.predict(df[['x','x2']]) ,label='Predicted')\nplt.grid(True)\nplt.xlabel('Input Feature')\nplt.ylabel('Target')\nplt.legend()\nplt.title('LinearRegression')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Solution for under-fitting\n\nadd a new X**2 term to the dataframe\n\nsyntax:\n\ndf_train['x2'] = df_train['x']**2\n\ndf_validation['x2'] = df_validation['x']**2\n\ndf['x2'] = df['x']**2",
"_____no_output_____"
],
[
"### Tree Based Algorithms have a lower bound and upper bound for predicted values",
"_____no_output_____"
]
],
[
[
"# True Function\ndef quad_func (x):\n return 5*x**2 -23*x + 47",
"_____no_output_____"
],
[
"# X is outside range of training samples\n# New Feature: Adding X^2 term\n\nX = np.array([-100,-25,25,1000,5000])\ny = quad_func(X)\ndf_tmp = pd.DataFrame({'x':X,'y':y,'x2':X**2})\ndf_tmp['xgboost']=regressor.predict(df_tmp[['x']])\ndf_tmp['linear']=lin_regressor.predict(df_tmp[['x','x2']])",
"_____no_output_____"
],
[
"df_tmp",
"_____no_output_____"
],
[
"plt.scatter(df_tmp.x,df_tmp.y,label='Actual',color='r')\nplt.plot(df_tmp.x,df_tmp.linear,label='LinearRegression')\nplt.plot(df_tmp.x,df_tmp.xgboost,label='XGBoost')\nplt.legend()\nplt.xlabel('X')\nplt.ylabel('y')\nplt.title('Input Outside Range')\nplt.show()",
"_____no_output_____"
],
[
"# X is inside range of training samples\nX = np.array([-15,-12,-5,0,1,3,5,7,9,11,15,18])\ny = quad_func(X)\ndf_tmp = pd.DataFrame({'x':X,'y':y,'x2':X**2})\ndf_tmp['xgboost']=regressor.predict(df_tmp[['x']])\ndf_tmp['linear']=lin_regressor.predict(df_tmp[['x','x2']])",
"_____no_output_____"
],
[
"df_tmp",
"_____no_output_____"
],
[
"# XGBoost Predictions have an upper bound and lower bound\n# Linear Regression Extrapolates\nplt.scatter(df_tmp.x,df_tmp.y,label='Actual',color='r')\nplt.plot(df_tmp.x,df_tmp.linear,label='LinearRegression')\nplt.plot(df_tmp.x,df_tmp.xgboost,label='XGBoost')\nplt.legend()\nplt.xlabel('X')\nplt.ylabel('y')\nplt.title('Input within range')\nplt.show()",
"_____no_output_____"
]
],
[
[
"<h2>Summary</h2>",
"_____no_output_____"
],
[
"1. In this exercise, we compared performance of XGBoost model and Linear Regression on a quadratic dataset\n2. The relationship between input feature and target was non-linear.\n3. XGBoost handled it pretty well; whereas, linear regression was under-fitting\n4. To correct the issue, we had to add additional features for linear regression\n5. With this change, linear regression performed much better\n\nXGBoost can detect patterns involving non-linear relationship; whereas, algorithms like linear regression may need complex feature engineering",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cba4ee6f7692b41826015aa7df6e592260ec6b76
| 16,406 |
ipynb
|
Jupyter Notebook
|
Exercises-2.ipynb
|
wicky85/pycon-pandas-tutorial
|
ce7b217f3d85cbb415fdecae0322d2de5ff554f1
|
[
"MIT"
] | 1,007 |
2015-04-08T17:52:19.000Z
|
2022-03-28T12:15:16.000Z
|
Exercises-2.ipynb
|
wicky85/pycon-pandas-tutorial
|
ce7b217f3d85cbb415fdecae0322d2de5ff554f1
|
[
"MIT"
] | 55 |
2015-04-20T05:26:54.000Z
|
2022-03-31T18:13:59.000Z
|
Exercises-2.ipynb
|
wicky85/pycon-pandas-tutorial
|
ce7b217f3d85cbb415fdecae0322d2de5ff554f1
|
[
"MIT"
] | 752 |
2015-04-08T09:09:05.000Z
|
2022-03-28T08:11:11.000Z
| 20.740834 | 108 | 0.445325 |
[
[
[
"%matplotlib inline\nimport pandas as pd",
"_____no_output_____"
],
[
"from IPython.core.display import HTML\ncss = open('style-table.css').read() + open('style-notebook.css').read()\nHTML('<style>{}</style>'.format(css))",
"_____no_output_____"
],
[
"titles = pd.read_csv('data/titles.csv')\ntitles.head()",
"_____no_output_____"
],
[
"cast = pd.read_csv('data/cast.csv')\ncast.head()",
"_____no_output_____"
]
],
[
[
"### What are the ten most common movie names of all time?",
"_____no_output_____"
],
[
"### Which three years of the 1930s saw the most films released?",
"_____no_output_____"
],
[
"### Plot the number of films that have been released each decade over the history of cinema.",
"_____no_output_____"
],
[
"### Plot the number of \"Hamlet\" films made each decade.",
"_____no_output_____"
],
[
"### Plot the number of \"Rustler\" characters in each decade of the history of film.",
"_____no_output_____"
],
[
"### Plot the number of \"Hamlet\" characters each decade.",
"_____no_output_____"
],
[
"### What are the 11 most common character names in movie history?",
"_____no_output_____"
],
[
"### Who are the 10 people most often credited as \"Herself\" in film history?",
"_____no_output_____"
],
[
"### Who are the 10 people most often credited as \"Himself\" in film history?",
"_____no_output_____"
],
[
"### Which actors or actresses appeared in the most movies in the year 1945?",
"_____no_output_____"
],
[
"### Which actors or actresses appeared in the most movies in the year 1985?",
"_____no_output_____"
],
[
"### Plot how many roles Mammootty has played in each year of his career.",
"_____no_output_____"
],
[
"### What are the 10 most frequent roles that start with the phrase \"Patron in\"?",
"_____no_output_____"
],
[
"### What are the 10 most frequent roles that start with the word \"Science\"?",
"_____no_output_____"
],
[
"### Plot the n-values of the roles that Judi Dench has played over her career.",
"_____no_output_____"
],
[
"### Plot the n-values of Cary Grant's roles through his career.",
"_____no_output_____"
],
[
"### Plot the n-value of the roles that Sidney Poitier has acted over the years.",
"_____no_output_____"
],
[
"### How many leading (n=1) roles were available to actors, and how many to actresses, in the 1950s?",
"_____no_output_____"
],
[
"### How many supporting (n=2) roles were available to actors, and how many to actresses, in the 1950s?",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cba4efa00def010ade4378ee93985fb1eae76bd3
| 472,733 |
ipynb
|
Jupyter Notebook
|
annual-indices-of-spring.ipynb
|
usgs-bcb/phenology-baps
|
91a3938cdc6ebc8b91a9601489d2d197cd8bf4ce
|
[
"Unlicense"
] | 1 |
2019-11-22T19:53:41.000Z
|
2019-11-22T19:53:41.000Z
|
annual-indices-of-spring.ipynb
|
usgs-bcb/phenology-baps
|
91a3938cdc6ebc8b91a9601489d2d197cd8bf4ce
|
[
"Unlicense"
] | null | null | null |
annual-indices-of-spring.ipynb
|
usgs-bcb/phenology-baps
|
91a3938cdc6ebc8b91a9601489d2d197cd8bf4ce
|
[
"Unlicense"
] | 2 |
2018-05-06T17:39:51.000Z
|
2022-03-04T11:22:05.000Z
| 1,114.936321 | 245,108 | 0.941919 |
[
[
[
" # Table of Contents\n<div class=\"toc\" style=\"margin-top: 1em;\"><ul class=\"toc-item\" id=\"toc-level0\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Purpose\" data-toc-modified-id=\"Purpose-1\"><span class=\"toc-item-num\">1 </span>Purpose</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Requirements\" data-toc-modified-id=\"Requirements-2\"><span class=\"toc-item-num\">2 </span>Requirements</a></span><ul class=\"toc-item\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Abstract-Stakeholder\" data-toc-modified-id=\"Abstract-Stakeholder-2.1\"><span class=\"toc-item-num\">2.1 </span>Abstract Stakeholder</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Actual-Stakeholder\" data-toc-modified-id=\"Actual-Stakeholder-2.2\"><span class=\"toc-item-num\">2.2 </span>Actual Stakeholder</a></span></li></ul></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Dependencies\" data-toc-modified-id=\"Dependencies-3\"><span class=\"toc-item-num\">3 </span>Dependencies</a></span><ul class=\"toc-item\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#R-installation\" data-toc-modified-id=\"R-installation-3.1\"><span class=\"toc-item-num\">3.1 </span>R installation</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#An-R-kernel-for-Jupyter-notebooks\" data-toc-modified-id=\"An-R-kernel-for-Jupyter-notebooks-3.2\"><span class=\"toc-item-num\">3.2 </span>An R kernel for Jupyter notebooks</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Load-R-libraries-for-the-analyses\" data-toc-modified-id=\"Load-R-libraries-for-the-analyses-3.3\"><span class=\"toc-item-num\">3.3 </span>Load R libraries for the analyses</a></span></li></ul></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Analyses\" data-toc-modified-id=\"Analyses-4\"><span class=\"toc-item-num\">4 </span>Analyses</a></span><ul class=\"toc-item\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#First-Leaf\" data-toc-modified-id=\"First-Leaf-4.1\"><span class=\"toc-item-num\">4.1 </span>First Leaf</a></span><ul class=\"toc-item\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Inputs\" data-toc-modified-id=\"Inputs-4.1.1\"><span class=\"toc-item-num\">4.1.1 </span>Inputs</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Outputs\" data-toc-modified-id=\"Outputs-4.1.2\"><span class=\"toc-item-num\">4.1.2 </span>Outputs</a></span><ul class=\"toc-item\"><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Histogram\" data-toc-modified-id=\"Histogram-4.1.2.1\"><span class=\"toc-item-num\">4.1.2.1 </span>Histogram</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Boxplots\" data-toc-modified-id=\"Boxplots-4.1.2.2\"><span class=\"toc-item-num\">4.1.2.2 </span>Boxplots</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Ridgeline-Plots\" data-toc-modified-id=\"Ridgeline-Plots-4.1.2.3\"><span class=\"toc-item-num\">4.1.2.3 </span>Ridgeline Plots</a></span></li></ul></li></ul></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#First-Bloom\" data-toc-modified-id=\"First-Bloom-4.2\"><span class=\"toc-item-num\">4.2 </span>First Bloom</a></span></li></ul></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Code\" data-toc-modified-id=\"Code-5\"><span class=\"toc-item-num\">5 </span>Code</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Provenance\" data-toc-modified-id=\"Provenance-6\"><span class=\"toc-item-num\">6 </span>Provenance</a></span></li><li><span><a href=\"http://localhost:8888/notebooks/work/bisdev/phenology-baps/spring-indices/annual-indices-of-spring.ipynb#Citations\" data-toc-modified-id=\"Citations-7\"><span class=\"toc-item-num\">7 </span>Citations</a></span></li></ul></div>",
"_____no_output_____"
],
[
"# Purpose\n\nThis [biogeographical analysis package](https://github.com/usgs-bis/nbmdocs/blob/master/docs/baps.rst) (BAP) uses the [USA National Phenology Network](https://www.usanpn.org/usa-national-phenology-network) (USA-NPN)'s modeled information on phenological changes to inform and support management decisions on the timing and coordination of season-specific activities within the boundaries of a user-specified management unit. While various categories of phenological information are applicable to the seasonal allocation of resources, this package focuses on one of those, USA-NPN's modeled spring indices of first leaf and first bloom. The use case for design and development of the BAP was that of a resource manager using this analysis package and USA-NPN's Extended Spring Indices to guide the timing and location of treaments within their protected area. ",
"_____no_output_____"
],
[
"# Requirements",
"_____no_output_____"
],
[
"## Abstract Stakeholder\nStakeholders for the information produced by this analysis package are people making decisions based on the timing of seasonal events at a specific location. Examples include resource managers, health professionals, and recreationalists. \n\nNote: For more on the concept of \"Abstract Stakeholder\" please see this [reference](https://github.com/usgs-bis/nbmdocs/blob/master/docs/baps.rst#abstract-stakeholder).",
"_____no_output_____"
],
[
"## Actual Stakeholder\nTo be determined\n\nNote: For more on the concept of \"Actual Stakeholder\" see this [reference](https://github.com/usgs-bis/nbmdocs/blob/master/docs/baps.rst#actual-stakeholder).",
"_____no_output_____"
],
[
"\n# Dependencies\nThis notebook was developed using the R software environment. Several R software packages are required to run this scientific code in a Jupyter notebook. An R kernel for Jupyter notebooks is also required. \n\n## R installation\nGuidance on installing the R software environment is available at the [R Project](https://www.r-project.org). Several R libraries, listed below, are used for the analyses and visualizations in this notebook. General instructions for finding and installing libraries are also provided at the [R Project](https://www.r-project.org) website.\n \n## An R kernel for Jupyter notebooks\nThis notebook uses [IRkernel](https://irkernel.github.io). At the time of this writing (2018-05-06), Karlijn Willems provides excellent guidance on installing the IRkernel and running R in a Jupyter notebook in her article entitled [\"Jupyter And R Markdown: Notebooks With R\"](https://www.datacamp.com/community/blog/jupyter-notebook-r#markdown) ",
"_____no_output_____"
],
[
"## Load R libraries for the analyses",
"_____no_output_____"
]
],
[
[
"library(tidyverse)\nlibrary(ggplot2)\nlibrary(ggridges)\nlibrary(jsonlite)\nlibrary(viridis)",
"_____no_output_____"
]
],
[
[
"# Analyses\n\nAn understanding of the USA National Phenology Network's suite of [models and maps](https://www.usanpn.org/data/maps) is required to properly use this analysis package and to assess the results. \n\nThe Extended Spring Indices, the model used to estimate the timing of \"first leaf\" and \"first bloom\" events for early spring indicator species at a specific location, are detailed on this [page](https://www.usanpn.org/data/spring_indices) of the USA-NPN website. Note both indices are based on the 2013 version of the underlying predictive model (Schwartz et al. 2013). The current model and its antecedents are described on the USA-NPN site and in peer-reviewed literatire (Ault et al. 2015, Schwartz 1997, Schwartz et al. 2006, Schwartz et al. 2013). Crimmins et al. (2017) documents the USA National Phenology Network gridded data products used in this analysis package. USA-NPN also provides an assessment of Spring Index uncertainty and error with their [Spring Index and Plausibility Dashboard](https://www.usanpn.org/data/si-x_plausibility).\n",
"_____no_output_____"
],
[
"## First Leaf\n\nThis analysis looks at the timing of First Leaf or leaf out for a specific location as predicted by the USA-NPN Extended Spring Indices models (https://www.usanpn.org/data/spring_indices, accessed 2018-01-27). The variable *average_leaf_prism* which is based on [PRISM](http://www.prism.oregonstate.edu) temperature data was used for this analysis. ",
"_____no_output_____"
],
[
"### Inputs\nThe operational BAP prototype retrieves data in real-time from the [USA National Phenology Network](https://www.usanpn.org)'s Web Processing Service (WPS) using a developer key issued by USA-NPN. Their WPS allows a key holder to request and retrieve model output values for a specified model, area of interest and time period. Model output for the variable *average_leaf_prism* was retrieved 2018-01-27. The area of interest, Yellowstone National Park, was analyzed using information from the [Spatial Feature Registry](https://github.com/usgs-bis/nbmdocs/blob/master/docs/bis.rst). The specified time period was 1981 to 2016. This notebook provides a lightly processsed version of that retrieval, [YellowstoneNP-1981-2016-processed-numbers.json](./YellowstoneNP-1981-2016-processed-numbers.json), for those who do not have a personal developer key.",
"_____no_output_____"
]
],
[
[
"# transform the BIS emitted JSON into something ggplot2 can work with\nyell <- read_json(\"YellowstoneNP-1981-2016-processed-numbers.json\", simplifyDataFrame = TRUE, simplifyVector = TRUE, flatten = TRUE)\nyelldf <- as_tibble(yell)\nyellt <- gather(yelldf, Year, DOY)",
"_____no_output_____"
]
],
[
[
"\n### Outputs",
"_____no_output_____"
],
[
"#### Histogram\nProduce a histogram of modeled results for Yellowstone National Park for all years within the specified period of interest (1981 to 2016). The visualization allows the user to assess the range and distribution of all the modeled values for the user-selected area for the entire, user-specified time period. Here, the modeled Leaf Spring Index values for each of the grid that fall within the boundary of Yellowstone National Park are binned by Day of Year for the entire period of interest. The period of interest is 1981 to 2016 inclusive. Dotted vertical lines indicating the minimum (green), mean (red), and maximum (green) values of the dataset are also shown.",
"_____no_output_____"
]
],
[
[
"# produce a histogram for all years\nggplot(yellt, aes(DOY)) +\n geom_histogram(binwidth = 1, color = \"grey\", fill = \"lightblue\") +\n ggtitle(\"Histogram of First Leaf Spring Index, Yellowstone National Park (1981 - 2016)\") +\n geom_vline(aes(xintercept=mean(DOY, na.rm=T)), color = \"red\", linetype = \"dotted\", size = 0.5) +\n geom_vline(aes(xintercept = min(DOY, na.rm=T)), color = \"green\", linetype = \"dotted\", size = 0.5) +\n geom_vline(aes(xintercept = max(DOY, na.rm=T)), color = \"green\", linetype = \"dotted\", size = 0.5)",
"_____no_output_____"
]
],
[
[
"This notebook uses the [ggplot2](https://ggplot2.tidyverse.org/index.html) R library to produce the above histogram. Operationalized, online versions of this visualization should be based on the guidance provided by the ggplot2 developers. See their section entitled [*Histograms and frequency polygons*](https://ggplot2.tidyverse.org/reference/geom_histogram.html) for details and approaches. The webpage provides links to their source code. Also, note the modeled grid cell values are discrete and should be portrayed as such in an operationalized graphic.",
"_____no_output_____"
],
[
"#### Boxplots \nProduce a multiple boxplot display of the modeled results for Yellowstone National Park for each year within the specified time period. Each individual boxplot portrays that year's median, hinges, whiskers and \"outliers\". The multiple boxplot display allows the user to explore the distribution of modeled spring index values through time.",
"_____no_output_____"
]
],
[
[
"# Produce a mulitple boxplot display with a boxplot for each year\nggplot(yellt, aes(y = DOY, x = Year, group = Year)) +\n geom_boxplot() +\n geom_hline(aes(yintercept = median(DOY, na.rm=T)), color = \"blue\", linetype = \"dotted\", size = 0.5) +\n ggtitle(\"DRAFT: Boxplot of Spring Index, Yellowstone National Park (1981 to 2016)\")",
"_____no_output_____"
]
],
[
[
"This notebook uses the [ggplot2](https://ggplot2.tidyverse.org/index.html) R library to produce the multiple boxplot above. Base any operationalized, online versions of this visualization on the guidance provided by the ggplot2 developers. See their section entitled [*A box and whiskers plot (in the style of Tukey)*](https://ggplot2.tidyverse.org/reference/geom_boxplot.html) for details and approaches. Links to their source code are available at that web location. ",
"_____no_output_____"
],
[
"#### Ridgeline Plots\nProduce ridgeline plots for each year to better visualize changes in the distributions over time.",
"_____no_output_____"
]
],
[
[
"# ridgeline plot with gradient coloring based on day of year for each available year\nggplot(yellt, aes(x = DOY, y = Year, group = Year, fill = ..x..)) +\n geom_density_ridges_gradient(scale = 3, rel_min_height = 0.01, gradient_lwd = 1.0, from = 80, to = 180) +\n scale_x_continuous(expand = c(0.01, 0)) +\n scale_y_continuous(expand = c(0.01, 0)) +\n scale_fill_viridis(name = \"Day of\\nYear\", option = \"D\", direction = -1) +\n labs(title = 'DRAFT: Spring Index, Yellowstone National Park',\n subtitle = 'Annual Spring Index by Year for the Period 1981 to 2016\\nModel Results from the USA National Phenology Network',\n y = 'Year',\n x = 'Spring Index (Day of Year)',\n caption = \"(model results retrieved 2018-01-26)\") +\n theme_ridges(font_size = 12, grid = TRUE) +\n geom_vline(aes(xintercept = mean(DOY, na.rm=T)), color = \"red\", linetype = \"dotted\", size = 0.5) +\n geom_vline(aes(xintercept = min(DOY, na.rm=T)), color = \"green\", linetype = \"dotted\", size = 0.5) +\n geom_vline(aes(xintercept = max(DOY, na.rm=T)), color = \"green\", linetype = \"dotted\", size = 0.5) ",
"Picking joint bandwidth of 1.06\n"
]
],
[
[
"This notebook used the [ggridges](https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html) R package to produce the ridgeline above. Base any operationalized, online versions of this visualization on the guidance provided by the ggridges developer. See their R package vignette [Introduction to ggridges](https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html) for details and approaches. Source code is available at their [GitHub repo](https://github.com/clauswilke/ggridges). ",
"_____no_output_____"
],
[
"## First Bloom\n\nThis analysis looks at the timing of First Bloom for a specific location as predicted by the USA-NPN Extended Spring Indices models (https://www.usanpn.org/data/spring_indices, accessed 2018-01-27). The variable *average_bloom_prism* which is based on [PRISM](http://www.prism.oregonstate.edu) temperature data was used for this analysis. \n\nOutput visualizations and implementation notes follow the approach and patterns used for First Leaf: histograms, multiple boxplots and ridgeline plots.",
"_____no_output_____"
],
[
"# Code\nCode used for this notebook is available at the [usgs-bcb/phenology-baps](https://github.com/usgs-bcb/phenology-baps) GitHub repository. ",
"_____no_output_____"
],
[
"# Provenance\nThis prototype analysis package was a collaborative development effort between USGS [Core Science Analytics, Synthesis, and Libraries](https://www.usgs.gov/science/mission-areas/core-science-systems/csasl?qt-programs_l2_landing_page=0#qt-programs_l2_landing_page) and the [USA National Phenology Network](https://www.usanpn.org). Members of the scientific development team met and discussed use cases, analyses, and visualizations during the third quarter of 2016. Model output choices as well as accessing the information by means of the USA-NPN Web Processing Service were also discussed at that time.\n\nThis notebook was based upon those group discussions and Tristan Wellman's initial ideas for processing and visualizing the USA-NPN spring index data. That initial body of work and other suppporting code is available at his GitHub repository, [TWellman/USGS_BCB-NPN-Dev-Space](https://github.com/TWellman/USGS_BCB-NPN-Dev-Space). This notebook used the [ggplot2](https://ggplot2.tidyverse.org/index.html) R library to produce the histograms and boxplots and ridgeplots. The ggplot2 developers provide online guidance and links to their source code for these at [*Histograms and frequency polygons*](https://ggplot2.tidyverse.org/reference/geom_histogram.html) and [*A box and whiskers plot (in the style of Tukey)*](https://ggplot2.tidyverse.org/reference/geom_boxplot.html). The [ggridges](https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html) R package is used to produce the ridgeline plot. Usage is described in the R package vignette [Introduction to ggridges](https://cran.r-project.org/web/packages/ggridges/vignettes/introduction.html). The underlying source code is available at the author Claus O. Wilke's [GitHub repo](https://github.com/clauswilke/ggridges). Software developers at the Fort Collins Science Center worked with members of the team to operationalize the scientific code and make it publically available on the web. An initial prototype application is available at (https://my-beta.usgs.gov/biogeography/).\n\n",
"_____no_output_____"
],
[
"# Citations\n\nAult, T. R., M. D. Schwartz, R. Zurita-Milla, J. F. Weltzin, and J. L. Betancourt (2015): Trends and natural variability of North American spring onset as evaluated by a new gridded dataset of spring indices. Journal of Climate 28: 8363-8378.\n\nCrimmins, T.M., R.L. Marsh, J. Switzer, M.A. Crimmins, K.L. Gerst, A.H. Rosemartin, and J.F. Weltzin. 2017. USA National Phenology Network gridded products documentation. U.S. Geological Survey Open-File Report 2017–1003. DOI: 10.3133/ofr20171003.\n\nMonahan, W. B., A. Rosemartin, K. L. Gerst, N. A. Fisichelli, T. Ault, M. D. Schwartz, J. E. Gross, and J. F. Weltzin. 2016. Climate change is advancing spring onset across the U.S. national park system. Ecosphere 7(10):e01465. 10.1002/ecs2.1465\n\nSchwartz, M. D. 1997. Spring index models: an approach to connecting satellite and surface phenology. Phenology in seasonal climates I, 23-38.\n\nSchwartz, M.D., R. Ahas, and A. Aasa, 2006. Onset of spring starting earlier across the Northern Hemisphere. Global Change Biology, 12, 343-351.\n\nSchwartz, M. D., T. R. Ault, and J. L. Betancourt, 2013: Spring onset variations and trends in the continental United States: past and regional assessment using temperature-based indices. International Journal of Climatology, 33, 2917–2922, 10.1002/joc.3625.\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cba4f016a09fe506c3d329f79ebea5dde262a87b
| 231,481 |
ipynb
|
Jupyter Notebook
|
experiments/tl_1v2/cores-oracle.run1/trials/23/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null |
experiments/tl_1v2/cores-oracle.run1/trials/23/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null |
experiments/tl_1v2/cores-oracle.run1/trials/23/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null | 102.33466 | 75,056 | 0.77062 |
[
[
[
"# Transfer Learning Template",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n\n \nimport os, json, sys, time, random\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom easydict import EasyDict\nimport matplotlib.pyplot as plt\n\nfrom steves_models.steves_ptn import Steves_Prototypical_Network\n\nfrom steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper\nfrom steves_utils.iterable_aggregator import Iterable_Aggregator\nfrom steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig\nfrom steves_utils.torch_sequential_builder import build_sequential\nfrom steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader\nfrom steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path)\nfrom steves_utils.PTN.utils import independent_accuracy_assesment\n\nfrom torch.utils.data import DataLoader\n\nfrom steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory\n\nfrom steves_utils.ptn_do_report import (\n get_loss_curve,\n get_results_table,\n get_parameters_table,\n get_domain_accuracies,\n)\n\nfrom steves_utils.transforms import get_chained_transform",
"_____no_output_____"
]
],
[
[
"# Allowed Parameters\nThese are allowed parameters, not defaults\nEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)\n\nPapermill uses the cell tag \"parameters\" to inject the real parameters below this cell.\nEnable tags to see what I mean",
"_____no_output_____"
]
],
[
[
"required_parameters = {\n \"experiment_name\",\n \"lr\",\n \"device\",\n \"seed\",\n \"dataset_seed\",\n \"n_shot\",\n \"n_query\",\n \"n_way\",\n \"train_k_factor\",\n \"val_k_factor\",\n \"test_k_factor\",\n \"n_epoch\",\n \"patience\",\n \"criteria_for_best\",\n \"x_net\",\n \"datasets\",\n \"torch_default_dtype\",\n \"NUM_LOGS_PER_EPOCH\",\n \"BEST_MODEL_PATH\",\n \"x_shape\",\n}",
"_____no_output_____"
],
[
"from steves_utils.CORES.utils import (\n ALL_NODES,\n ALL_NODES_MINIMUM_1000_EXAMPLES,\n ALL_DAYS\n)\n\nfrom steves_utils.ORACLE.utils_v2 import (\n ALL_DISTANCES_FEET_NARROWED,\n ALL_RUNS,\n ALL_SERIAL_NUMBERS,\n)\n\nstandalone_parameters = {}\nstandalone_parameters[\"experiment_name\"] = \"STANDALONE PTN\"\nstandalone_parameters[\"lr\"] = 0.001\nstandalone_parameters[\"device\"] = \"cuda\"\n\nstandalone_parameters[\"seed\"] = 1337\nstandalone_parameters[\"dataset_seed\"] = 1337\n\nstandalone_parameters[\"n_way\"] = 8\nstandalone_parameters[\"n_shot\"] = 3\nstandalone_parameters[\"n_query\"] = 2\nstandalone_parameters[\"train_k_factor\"] = 1\nstandalone_parameters[\"val_k_factor\"] = 2\nstandalone_parameters[\"test_k_factor\"] = 2\n\n\nstandalone_parameters[\"n_epoch\"] = 50\n\nstandalone_parameters[\"patience\"] = 10\nstandalone_parameters[\"criteria_for_best\"] = \"source_loss\"\n\nstandalone_parameters[\"datasets\"] = [\n {\n \"labels\": ALL_SERIAL_NUMBERS,\n \"domains\": ALL_DISTANCES_FEET_NARROWED,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [\"unit_mag\", \"minus_two\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"ORACLE_\"\n },\n {\n \"labels\": ALL_NODES,\n \"domains\": ALL_DAYS,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [\"unit_power\", \"times_zero\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"CORES_\"\n } \n]\n\nstandalone_parameters[\"torch_default_dtype\"] = \"torch.float32\" \n\n\n\nstandalone_parameters[\"x_net\"] = [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\":[-1, 1, 2, 256]}},\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":1, \"out_channels\":256, \"kernel_size\":(1,7), \"bias\":False, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":256, \"out_channels\":80, \"kernel_size\":(2,7), \"bias\":True, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 80*256, \"out_features\": 256}}, # 80 units per IQ pair\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n]\n\n# Parameters relevant to results\n# These parameters will basically never need to change\nstandalone_parameters[\"NUM_LOGS_PER_EPOCH\"] = 10\nstandalone_parameters[\"BEST_MODEL_PATH\"] = \"./best_model.pth\"\n\n\n\n\n",
"_____no_output_____"
],
[
"# Parameters\nparameters = {\n \"experiment_name\": \"tl_1v2:cores-oracle.run1\",\n \"device\": \"cuda\",\n \"lr\": 0.0001,\n \"n_shot\": 3,\n \"n_query\": 2,\n \"train_k_factor\": 3,\n \"val_k_factor\": 2,\n \"test_k_factor\": 2,\n \"torch_default_dtype\": \"torch.float32\",\n \"n_epoch\": 50,\n \"patience\": 3,\n \"criteria_for_best\": \"target_accuracy\",\n \"x_net\": [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\": [-1, 1, 2, 256]}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 1,\n \"out_channels\": 256,\n \"kernel_size\": [1, 7],\n \"bias\": False,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 256}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 256,\n \"out_channels\": 80,\n \"kernel_size\": [2, 7],\n \"bias\": True,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 20480, \"out_features\": 256}},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\": 256}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n ],\n \"NUM_LOGS_PER_EPOCH\": 10,\n \"BEST_MODEL_PATH\": \"./best_model.pth\",\n \"n_way\": 16,\n \"datasets\": [\n {\n \"labels\": [\n \"1-10.\",\n \"1-11.\",\n \"1-15.\",\n \"1-16.\",\n \"1-17.\",\n \"1-18.\",\n \"1-19.\",\n \"10-4.\",\n \"10-7.\",\n \"11-1.\",\n \"11-14.\",\n \"11-17.\",\n \"11-20.\",\n \"11-7.\",\n \"13-20.\",\n \"13-8.\",\n \"14-10.\",\n \"14-11.\",\n \"14-14.\",\n \"14-7.\",\n \"15-1.\",\n \"15-20.\",\n \"16-1.\",\n \"16-16.\",\n \"17-10.\",\n \"17-11.\",\n \"17-2.\",\n \"19-1.\",\n \"19-16.\",\n \"19-19.\",\n \"19-20.\",\n \"19-3.\",\n \"2-10.\",\n \"2-11.\",\n \"2-17.\",\n \"2-18.\",\n \"2-20.\",\n \"2-3.\",\n \"2-4.\",\n \"2-5.\",\n \"2-6.\",\n \"2-7.\",\n \"2-8.\",\n \"3-13.\",\n \"3-18.\",\n \"3-3.\",\n \"4-1.\",\n \"4-10.\",\n \"4-11.\",\n \"4-19.\",\n \"5-5.\",\n \"6-15.\",\n \"7-10.\",\n \"7-14.\",\n \"8-18.\",\n \"8-20.\",\n \"8-3.\",\n \"8-8.\",\n ],\n \"domains\": [1, 2, 3, 4, 5],\n \"num_examples_per_domain_per_label\": -1,\n \"pickle_path\": \"/root/csc500-main/datasets/cores.stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"CORES_\",\n },\n {\n \"labels\": [\n \"3123D52\",\n \"3123D65\",\n \"3123D79\",\n \"3123D80\",\n \"3123D54\",\n \"3123D70\",\n \"3123D7B\",\n \"3123D89\",\n \"3123D58\",\n \"3123D76\",\n \"3123D7D\",\n \"3123EFE\",\n \"3123D64\",\n \"3123D78\",\n \"3123D7E\",\n \"3124E4A\",\n ],\n \"domains\": [32, 38, 8, 44, 14, 50, 20, 26],\n \"num_examples_per_domain_per_label\": 10000,\n \"pickle_path\": \"/root/csc500-main/datasets/oracle.Run1_10kExamples_stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"ORACLE.run1_\",\n },\n ],\n \"dataset_seed\": 7,\n \"seed\": 7,\n}\n",
"_____no_output_____"
],
[
"# Set this to True if you want to run this template directly\nSTANDALONE = False\nif STANDALONE:\n print(\"parameters not injected, running with standalone_parameters\")\n parameters = standalone_parameters\n\nif not 'parameters' in locals() and not 'parameters' in globals():\n raise Exception(\"Parameter injection failed\")\n\n#Use an easy dict for all the parameters\np = EasyDict(parameters)\n\nif \"x_shape\" not in p:\n p.x_shape = [2,256] # Default to this if we dont supply x_shape\n\n\nsupplied_keys = set(p.keys())\n\nif supplied_keys != required_parameters:\n print(\"Parameters are incorrect\")\n if len(supplied_keys - required_parameters)>0: print(\"Shouldn't have:\", str(supplied_keys - required_parameters))\n if len(required_parameters - supplied_keys)>0: print(\"Need to have:\", str(required_parameters - supplied_keys))\n raise RuntimeError(\"Parameters are incorrect\")",
"_____no_output_____"
],
[
"###################################\n# Set the RNGs and make it all deterministic\n###################################\nnp.random.seed(p.seed)\nrandom.seed(p.seed)\ntorch.manual_seed(p.seed)\n\ntorch.use_deterministic_algorithms(True) ",
"_____no_output_____"
],
[
"###########################################\n# The stratified datasets honor this\n###########################################\ntorch.set_default_dtype(eval(p.torch_default_dtype))",
"_____no_output_____"
],
[
"###################################\n# Build the network(s)\n# Note: It's critical to do this AFTER setting the RNG\n###################################\nx_net = build_sequential(p.x_net)",
"_____no_output_____"
],
[
"start_time_secs = time.time()",
"_____no_output_____"
],
[
"p.domains_source = []\np.domains_target = []\n\n\ntrain_original_source = []\nval_original_source = []\ntest_original_source = []\n\ntrain_original_target = []\nval_original_target = []\ntest_original_target = []",
"_____no_output_____"
],
[
"# global_x_transform_func = lambda x: normalize(x.to(torch.get_default_dtype()), \"unit_power\") # unit_power, unit_mag\n# global_x_transform_func = lambda x: normalize(x, \"unit_power\") # unit_power, unit_mag",
"_____no_output_____"
],
[
"def add_dataset(\n labels,\n domains,\n pickle_path,\n x_transforms,\n episode_transforms,\n domain_prefix,\n num_examples_per_domain_per_label,\n source_or_target_dataset:str,\n iterator_seed=p.seed,\n dataset_seed=p.dataset_seed,\n n_shot=p.n_shot,\n n_way=p.n_way,\n n_query=p.n_query,\n train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor),\n):\n \n if x_transforms == []: x_transform = None\n else: x_transform = get_chained_transform(x_transforms)\n \n if episode_transforms == []: episode_transform = None\n else: raise Exception(\"episode_transforms not implemented\")\n \n episode_transform = lambda tup, _prefix=domain_prefix: (_prefix + str(tup[0]), tup[1])\n\n\n eaf = Episodic_Accessor_Factory(\n labels=labels,\n domains=domains,\n num_examples_per_domain_per_label=num_examples_per_domain_per_label,\n iterator_seed=iterator_seed,\n dataset_seed=dataset_seed,\n n_shot=n_shot,\n n_way=n_way,\n n_query=n_query,\n train_val_test_k_factors=train_val_test_k_factors,\n pickle_path=pickle_path,\n x_transform_func=x_transform,\n )\n\n train, val, test = eaf.get_train(), eaf.get_val(), eaf.get_test()\n train = Lazy_Iterable_Wrapper(train, episode_transform)\n val = Lazy_Iterable_Wrapper(val, episode_transform)\n test = Lazy_Iterable_Wrapper(test, episode_transform)\n\n if source_or_target_dataset==\"source\":\n train_original_source.append(train)\n val_original_source.append(val)\n test_original_source.append(test)\n\n p.domains_source.extend(\n [domain_prefix + str(u) for u in domains]\n )\n elif source_or_target_dataset==\"target\":\n train_original_target.append(train)\n val_original_target.append(val)\n test_original_target.append(test)\n p.domains_target.extend(\n [domain_prefix + str(u) for u in domains]\n )\n else:\n raise Exception(f\"invalid source_or_target_dataset: {source_or_target_dataset}\")\n ",
"_____no_output_____"
],
[
"for ds in p.datasets:\n add_dataset(**ds)",
"_____no_output_____"
],
[
"# from steves_utils.CORES.utils import (\n# ALL_NODES,\n# ALL_NODES_MINIMUM_1000_EXAMPLES,\n# ALL_DAYS\n# )\n\n# add_dataset(\n# labels=ALL_NODES,\n# domains = ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"cores_{u}\"\n# )",
"_____no_output_____"
],
[
"# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle1_{u}\"\n# )\n",
"_____no_output_____"
],
[
"# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62,56}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle2_{u}\"\n# )",
"_____no_output_____"
],
[
"# add_dataset(\n# labels=list(range(19)),\n# domains = [0,1,2],\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"metehan.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"met_{u}\"\n# )",
"_____no_output_____"
],
[
"# # from steves_utils.wisig.utils import (\n# # ALL_NODES_MINIMUM_100_EXAMPLES,\n# # ALL_NODES_MINIMUM_500_EXAMPLES,\n# # ALL_NODES_MINIMUM_1000_EXAMPLES,\n# # ALL_DAYS\n# # )\n\n# import steves_utils.wisig.utils as wisig\n\n\n# add_dataset(\n# labels=wisig.ALL_NODES_MINIMUM_100_EXAMPLES,\n# domains = wisig.ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"wisig.node3-19.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"wisig_{u}\"\n# )",
"_____no_output_____"
],
[
"###################################\n# Build the dataset\n###################################\ntrain_original_source = Iterable_Aggregator(train_original_source, p.seed)\nval_original_source = Iterable_Aggregator(val_original_source, p.seed)\ntest_original_source = Iterable_Aggregator(test_original_source, p.seed)\n\n\ntrain_original_target = Iterable_Aggregator(train_original_target, p.seed)\nval_original_target = Iterable_Aggregator(val_original_target, p.seed)\ntest_original_target = Iterable_Aggregator(test_original_target, p.seed)\n\n# For CNN We only use X and Y. And we only train on the source.\n# Properly form the data using a transform lambda and Lazy_Iterable_Wrapper. Finally wrap them in a dataloader\n\ntransform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only\n\ntrain_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda)\nval_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda)\ntest_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda)\n\ntrain_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda)\nval_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda)\ntest_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda)\n\ndatasets = EasyDict({\n \"source\": {\n \"original\": {\"train\":train_original_source, \"val\":val_original_source, \"test\":test_original_source},\n \"processed\": {\"train\":train_processed_source, \"val\":val_processed_source, \"test\":test_processed_source}\n },\n \"target\": {\n \"original\": {\"train\":train_original_target, \"val\":val_original_target, \"test\":test_original_target},\n \"processed\": {\"train\":train_processed_target, \"val\":val_processed_target, \"test\":test_processed_target}\n },\n})",
"_____no_output_____"
],
[
"from steves_utils.transforms import get_average_magnitude, get_average_power\n\nprint(set([u for u,_ in val_original_source]))\nprint(set([u for u,_ in val_original_target]))\n\ns_x, s_y, q_x, q_y, _ = next(iter(train_processed_source))\nprint(s_x)\n\n# for ds in [\n# train_processed_source,\n# val_processed_source,\n# test_processed_source,\n# train_processed_target,\n# val_processed_target,\n# test_processed_target\n# ]:\n# for s_x, s_y, q_x, q_y, _ in ds:\n# for X in (s_x, q_x):\n# for x in X:\n# assert np.isclose(get_average_magnitude(x.numpy()), 1.0)\n# assert np.isclose(get_average_power(x.numpy()), 1.0)\n ",
"{'ORACLE.run1_20', 'ORACLE.run1_8', 'ORACLE.run1_14', 'ORACLE.run1_26', 'ORACLE.run1_32', 'ORACLE.run1_44', 'ORACLE.run1_38', 'ORACLE.run1_50'}\n"
],
[
"###################################\n# Build the model\n###################################\n# easfsl only wants a tuple for the shape\nmodel = Steves_Prototypical_Network(x_net, device=p.device, x_shape=tuple(p.x_shape))\noptimizer = Adam(params=model.parameters(), lr=p.lr)",
"(2, 256)\n"
],
[
"###################################\n# train\n###################################\njig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device)\n\njig.train(\n train_iterable=datasets.source.processed.train,\n source_val_iterable=datasets.source.processed.val,\n target_val_iterable=datasets.target.processed.val,\n num_epochs=p.n_epoch,\n num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH,\n patience=p.patience,\n optimizer=optimizer,\n criteria_for_best=p.criteria_for_best,\n)",
"epoch: 1, [batch: 1 / 33600], examples_per_second: 6.6148, train_label_loss: 2.7185, \n"
],
[
"total_experiment_time_secs = time.time() - start_time_secs",
"_____no_output_____"
],
[
"###################################\n# Evaluate the model\n###################################\nsource_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test)\ntarget_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test)\n\nsource_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val)\ntarget_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val)\n\nhistory = jig.get_history()\n\ntotal_epochs_trained = len(history[\"epoch_indices\"])\n\nval_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val))\n\nconfusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl)\nper_domain_accuracy = per_domain_accuracy_from_confusion(confusion)\n\n# Add a key to per_domain_accuracy for if it was a source domain\nfor domain, accuracy in per_domain_accuracy.items():\n per_domain_accuracy[domain] = {\n \"accuracy\": accuracy,\n \"source?\": domain in p.domains_source\n }\n\n# Do an independent accuracy assesment JUST TO BE SURE!\n# _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device)\n# _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device)\n# _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device)\n# _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device)\n\n# assert(_source_test_label_accuracy == source_test_label_accuracy)\n# assert(_target_test_label_accuracy == target_test_label_accuracy)\n# assert(_source_val_label_accuracy == source_val_label_accuracy)\n# assert(_target_val_label_accuracy == target_val_label_accuracy)\n\nexperiment = {\n \"experiment_name\": p.experiment_name,\n \"parameters\": dict(p),\n \"results\": {\n \"source_test_label_accuracy\": source_test_label_accuracy,\n \"source_test_label_loss\": source_test_label_loss,\n \"target_test_label_accuracy\": target_test_label_accuracy,\n \"target_test_label_loss\": target_test_label_loss,\n \"source_val_label_accuracy\": source_val_label_accuracy,\n \"source_val_label_loss\": source_val_label_loss,\n \"target_val_label_accuracy\": target_val_label_accuracy,\n \"target_val_label_loss\": target_val_label_loss,\n \"total_epochs_trained\": total_epochs_trained,\n \"total_experiment_time_secs\": total_experiment_time_secs,\n \"confusion\": confusion,\n \"per_domain_accuracy\": per_domain_accuracy,\n },\n \"history\": history,\n \"dataset_metrics\": get_dataset_metrics(datasets, \"ptn\"),\n}",
"_____no_output_____"
],
[
"ax = get_loss_curve(experiment)\nplt.show()",
"_____no_output_____"
],
[
"get_results_table(experiment)",
"_____no_output_____"
],
[
"get_domain_accuracies(experiment)",
"_____no_output_____"
],
[
"print(\"Source Test Label Accuracy:\", experiment[\"results\"][\"source_test_label_accuracy\"], \"Target Test Label Accuracy:\", experiment[\"results\"][\"target_test_label_accuracy\"])\nprint(\"Source Val Label Accuracy:\", experiment[\"results\"][\"source_val_label_accuracy\"], \"Target Val Label Accuracy:\", experiment[\"results\"][\"target_val_label_accuracy\"])",
"Source Test Label Accuracy: 0.8580143229166667 Target Test Label Accuracy: 0.9841101694915254\nSource Val Label Accuracy: 0.8584309895833333 Target Val Label Accuracy: 0.9838571428571429\n"
],
[
"json.dumps(experiment)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba4fa8a3bc14a96ac928e132b038b03084c6c97
| 102,752 |
ipynb
|
Jupyter Notebook
|
3 analyse data/3 Analyse data - Complete.ipynb
|
jornalistagustavoribeiro/pythonforjournalists
|
9bb475cf83aa26a3f31c8ca552ad5fe491533a1d
|
[
"MIT"
] | 45 |
2019-05-02T07:34:29.000Z
|
2022-03-24T12:28:37.000Z
|
3 analyse data/3 Analyse data - Complete.ipynb
|
jornalistagustavoribeiro/pythonforjournalists
|
9bb475cf83aa26a3f31c8ca552ad5fe491533a1d
|
[
"MIT"
] | null | null | null |
3 analyse data/3 Analyse data - Complete.ipynb
|
jornalistagustavoribeiro/pythonforjournalists
|
9bb475cf83aa26a3f31c8ca552ad5fe491533a1d
|
[
"MIT"
] | 75 |
2019-04-05T19:48:12.000Z
|
2022-03-12T19:46:13.000Z
| 37.985952 | 1,140 | 0.41824 |
[
[
[
"# Analyse data with Python Pandas",
"_____no_output_____"
],
[
"Welcome to this Jupyter Notebook! \n \nToday you'll learn how to import a CSV file into a Jupyter Notebook, and how to analyse already cleaned data. This notebook is part of the course Python for Journalists at [datajournalism.com](https://datajournalism.com/watch/python-for-journalists). The data used originally comes from [the Electoral Commission website](http://search.electoralcommission.org.uk/Search?currentPage=1&rows=10&sort=AcceptedDate&order=desc&tab=1&open=filter&et=pp&isIrishSourceYes=false&isIrishSourceNo=false&date=Reported&from=&to=&quarters=2018Q12&rptPd=3617&prePoll=false&postPoll=false&donorStatus=individual&donorStatus=tradeunion&donorStatus=company&donorStatus=unincorporatedassociation&donorStatus=publicfund&donorStatus=other&donorStatus=registeredpoliticalparty&donorStatus=friendlysociety&donorStatus=trust&donorStatus=limitedliabilitypartnership&donorStatus=impermissibledonor&donorStatus=na&donorStatus=unidentifiabledonor&donorStatus=buildingsociety®ister=ni®ister=gb&optCols=Register&optCols=IsIrishSource&optCols=ReportingPeriodName), but is edited for training purposes. The edited dataset is available on the course website. \n\n## About Jupyter Notebooks and Pandas\n\nRight now you're looking at a Jupyter Notebook: an interactive, browser based programming environment. You can use these notebooks to program in R, Julia or Python - as you'll be doing later on. Read more about Jupyter Notebook in the [Jupyter Notebook Quick Start Guide](https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html). \n \nTo analyse up our data, we'll be using Python and Pandas. Pandas is an open-source Python library - basically an extra toolkit to go with Python - that is designed for data analysis. Pandas is flexible, easy to use and has lots of useful functions built right in. Read more about Pandas and its features in [the Pandas documentation](https://pandas.pydata.org/pandas-docs/stable/). That Pandas functions in ways similar to both spreadsheets and SQL databases (though the latter won't be discussed in this course), makes it beginner friendly. :) \n\n**Notebook shortcuts** \n\nWithin Jupyter Notebooks, there are some shortcuts you can use. If you'll be using more notebooks for your data analysis in the future, you'll remember these shortcuts soon enough. :) \n\n* `esc` will take you into command mode\n* `a` will insert cell above\n* `b` will insert cell below\n* `shift then tab` will show you the documentation for your code\n* `shift and enter` will run your cell\n* ` d d` will delete a cell\n\n**Pandas dictionary**\n\n* **dataframe**: dataframe is Pandas speak for a table with a labeled y-axis, also known as an index. (The index usually starts at 0.)\n* **series**: a series is a list, a series can be made of a single column within a dataframe.\n\nBefore we dive in, a little more about Jupyter Notebooks. Every notebooks is made out of cells. A cell can either contain Markdown text - like this one - or code. In the latter you can execute your code. To see what that means, type the following command in the next cell `print(\"hello world\")`.",
"_____no_output_____"
]
],
[
[
"print(\"hello world\")",
"hello world\n"
]
],
[
[
"## Getting started",
"_____no_output_____"
],
[
"In the module 'Clean data' from this course, we cleaned up a dataset with donations to political parties in the UK. Now, we're going to analyse the data in that dataset. Let's start by importing the Pandas library, using `import pandas as pd`.",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"Now, import the cleaned dataset, use `df = pd.read_csv('/path/to/file_with_clean_data.csv')`.",
"_____no_output_____"
],
[
"## Importing data",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('results_clean.csv')",
"_____no_output_____"
]
],
[
[
"Let's see if the data is anything like you'd expect, use `df.head()`, `df.tail()` or `df.sample()`.",
"_____no_output_____"
]
],
[
[
"df.head(10)",
"_____no_output_____"
]
],
[
[
"Whoops! When we saved the data after cleaning it, the index was saved in an unnamed column. With importing, Pandas added a new index... Let's get rid of the 'Unnamed: 0' column. Drop it like it's hot... `df = df.drop('Unnamed: 0', 1)`.",
"_____no_output_____"
]
],
[
[
"df = df.drop('Unnamed: 0', 1)",
"_____no_output_____"
]
],
[
[
"Let's see if this worked, use `df.head()`, `df.tail()` or `df.sample()`.\n\n",
"_____no_output_____"
]
],
[
[
"df.tail(10)",
"_____no_output_____"
]
],
[
[
"Now, if this looks better, let's get started and analyse some data.\n\n# Analyse data\n\n## Statistical summary\n\nIn the module Clean data, you already saw the power of `df.describe()`. This function gives a basic statistical summary of every column in the dataset. It will give you even more information when you tell the function that you want everything included, like this: `df.describe(include='all')`",
"_____no_output_____"
]
],
[
[
"df.describe(include='all')",
"_____no_output_____"
]
],
[
[
"For columns with numeric values, `df.describe()` will give back the most information, here's a full list of the parameters and their meaning: \n\n**df.describe() parameters**\n* **count**: number of values in that column\n* **unique**: number of unique values in that column\n* **top**: first value in that column\n* **freq**: the most common value’s frequency\n* **mean**: average\n* **std**: standard deviation\n* **min**: minimum value, lowest value in the column\n* **25%**: first percentile\n* **50%**: second percentile, this is the same as the median\n* **75%**: thirth percentile\n* **max**: maximum value, highest value in the column\n\nIf a column does not contain numeric value, only those parameters that are applicable are returned. Python gives you NaN-values when that's the case - NaN is short for Not a Number. \n\nNotice that 'count' is 300 for every column. This means that every column has a value for every row in the dataset. How do I know? I looked at the total number of rows, using `df.shape`.",
"_____no_output_____"
]
],
[
[
"df.shape",
"_____no_output_____"
]
],
[
[
"## Filter\n\nLet's try to filter the dataframe based on the value in the Value column. You can do this using `df[df['Value'] > 10000 ]`. This will give you a dataframe with only donations from 10.000 pound or more.",
"_____no_output_____"
]
],
[
[
"df[df['Value'] > 10000 ]",
"_____no_output_____"
]
],
[
[
"## Sort\nLet's try to sort the data. Using the command `df.sort_values(by='column_name')` will sort the dataframe based on the column of your choosing. Sorting by default happens ascending, from small to big. \n\nIn case you want to see the sorting from big to small, descending, you'll have to type: `df.sort_values(by='column_name', ascending=False)`.\n\nNow, let's try to sort the dataframe based on the number in the Value column it's easy to find out who made the biggest donation. \n\nThe above commands will sort the dataframe by a column, but - since we never asked our notebook to - won't show the data. To sort the data and show us the new order of the top 10, we'll have to combine the command with `.head(10)` like this: `df.sort_values(by='column_name').head(10)`.\n\nNow, what would you type if you want to see the 10 smallest donations?",
"_____no_output_____"
]
],
[
[
"df.sort_values(by='Value').head(10)",
"_____no_output_____"
]
],
[
[
"If you want to see the biggest donations made, there are two ways to do that. You could use `df.tail(10)` to see the last 10 rows of the dataframe as it is now. Since the dataframe is ordered from small to big donation, the biggest donations will be in the last 10 rows.\n\nAnother way of doing this, is using `df.sort_values(by='Value', ascending=False).head(10)`. This would sort the dataframe based on the Value column from big to small. Personally I prefer the latter... ",
"_____no_output_____"
]
],
[
[
"df.sort_values(by='Value', ascending=False).head(10)",
"_____no_output_____"
]
],
[
[
"## Sum\n\nWow! There are some big donations in our dataset. If you want to know how much money was donated in total, you need to get the sum of the column Value. Use `df['Value'].sum()`.",
"_____no_output_____"
]
],
[
[
"df['Value'].sum()",
"_____no_output_____"
]
],
[
[
"## Count",
"_____no_output_____"
],
[
"Let's look at the receivers of all this donation money. Use `df['RegulatedEntityName'].count()` to count the number of times a regulated entity received a donation.\n\n",
"_____no_output_____"
]
],
[
[
"df['RegulatedEntityName'].count()",
"_____no_output_____"
]
],
[
[
"Not really what we were looking for, right? Using `.count()` gives you the number of values in a column. Not the number of appearances per unique value in the column. \n\nYou'll need to use `df['RegulatedEntityName'].value_counts()` if you want to know that... ",
"_____no_output_____"
]
],
[
[
"df['RegulatedEntityName'].value_counts()",
"_____no_output_____"
]
],
[
[
"Ok. Let's see if you really understand the difference between `.value_counts()` and `.count()` If you want to know how many donors have donated, you should count the values in the DonorName column. Do you use `df['DonorName'].value_counts()` or `df['DonorName'].count()`?\n\nWhen in doubt, try both. Remember: we're using a Jupyter Notebook here. It's a **Notebook**, so you can't go wrong here. :)",
"_____no_output_____"
]
],
[
[
"df['DonorName'].count()",
"_____no_output_____"
],
[
"df['DonorName'].value_counts()",
"_____no_output_____"
]
],
[
[
"Interesting: apparently Ms Jane Mactaggart, Mr Duncan Greenland, and Lord Charles Falconer of Thoroton have donated most often. Let's look into that...\n\n## Groupby\nIf you're familiar with Excel, you probably heard of 'pivot tables'. Python Pandas has a function very similar to those pivot tables. \n\nLet's start with a small refresher: pivot tables are summaries of a dataset inside a new table. Huh? That's might be a lot to take in. \n\nLook at our example: data on donations to political parties in the UK. If we want to know how much each unique donor donated, we are looking for a specific summary of our dataset. To get the anwer to this question: 'How much have Ms Jane Mactaggart, Mr Duncan Greenland, and Lord Charles Falconer of Thoroton donated in total?' We need Pandas to sum up all donation for every donor in the dataframe. In a way, this is a summary of the original dataframe by grouping values by in this case the column DonorName. \n\nUsing Python this can be done using the group by function. Let's create a new dataframe called donors, that has all donors and the total sum of their donations in there. Use `donors = df.groupby('DonorName')['Value'].sum()`. This is a combination of several functions: group data by 'DonorName', and sum the data in the 'Value' column...",
"_____no_output_____"
]
],
[
[
"donors = df.groupby('DonorName')['Value'].sum()\ndonors.head(10)",
"_____no_output_____"
]
],
[
[
"To see if it worked, you'll have to add `donors.head(10)`, otherwise your computer won't know that you actually want to see the result of your effort. :)\n\n## Pivot tables\n\nBut Python has it's own pivot table as well. You can get a similar result in a better looking table using de `df.pivot_table` function. \n\nHere's a perfectly fine `.pivot_table` example:\n`df.pivot_table(values=\"Value\", index=\"DonorName\", columns=\"Year\", aggfunc='sum').sort_values(2018).head(10)`\n\nLet's go over this code before running it. What will `df.pivot_table(values=\"Value\", index=\"DonorName\", columns=\"Year\", aggfunc='sum').sort_values(2018).head(10)` actually do? \n\nFor the dataframe called df, create a pivot table where: \n- the values in the pivot table should be based on the Value column\n- the index of the pivot table should be base don the DonorName column, in other words: create a row for every unique value in the DonorName column\n- create a new column for every unique value in the Year column\n- aggregate the data that fills up these columns (from the Value column, see?) by summing it for every row. \n\nAre you ready to try it yourself?",
"_____no_output_____"
]
],
[
[
"df.pivot_table(values=\"Value\", index=\"DonorName\", columns=\"Year\", aggfunc='sum').sort_values(2018).head(10)",
"_____no_output_____"
]
],
[
[
"## Save your data\n\nNow that we've put all this work into cleaning our dataset, let's save a copy. Off course Pandas has a nifty command for that too. Use `dataframe.to_csv('filename.csv', encoding='utf8')`. \n\nBe ware: use a different name than the filename of the original data file, or it will be overwritten. ",
"_____no_output_____"
]
],
[
[
"df.to_csv('results clean - pivot table.csv')",
"_____no_output_____"
]
],
[
[
"In case you want to check if a new file was created in your directory, you can use the `pwd` and `ls` commands. At the beginning of this module, we used these commands to print the working directory (`pwd`) and list the content of the working directory (`ls`). \n\nFirst, use `pwd` to see in which folder - also known as directory - you are:",
"_____no_output_____"
]
],
[
[
"pwd",
"_____no_output_____"
]
],
[
[
"Now use `ls` to get a list of all files in this directory. If everything worked your newly saved datafile should be among the files in the list. ",
"_____no_output_____"
]
],
[
[
"ls",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba50dab9c061c665f44452b834d00c791daef58
| 8,426 |
ipynb
|
Jupyter Notebook
|
examples/custom_hamiltonians.ipynb
|
avijitshee/cartan-quantum-synthesizer
|
d0430643c2eeb610eca8f46581bb70df9ec084b7
|
[
"BSD-2-Clause-Patent"
] | 5 |
2021-10-04T19:50:40.000Z
|
2022-02-17T21:41:44.000Z
|
examples/custom_hamiltonians.ipynb
|
avijitshee/cartan-quantum-synthesizer
|
d0430643c2eeb610eca8f46581bb70df9ec084b7
|
[
"BSD-2-Clause-Patent"
] | null | null | null |
examples/custom_hamiltonians.ipynb
|
avijitshee/cartan-quantum-synthesizer
|
d0430643c2eeb610eca8f46581bb70df9ec084b7
|
[
"BSD-2-Clause-Patent"
] | 1 |
2021-08-31T14:50:40.000Z
|
2021-08-31T14:50:40.000Z
| 33.839357 | 850 | 0.457987 |
[
[
[
"# Example File:\r\nIn this package, we show three examples: \r\n<ol>\r\n <li>4 site XY model</li>\r\n <li>4 site Transverse Field XY model with random coefficients</li>\r\n <li><b> Custom Hamiltonian from OpenFermion </b> </li>\r\n</ol>",
"_____no_output_____"
],
[
"## Clone and Install The Repo via command line:\r\n```\r\ngit clone https://github.com/kemperlab/cartan-quantum-synthesizer.git \r\n \r\ncd ./cartan-quantum-synthesizer/\r\n \r\npip install .\r\n```\r\n",
"_____no_output_____"
],
[
"# Building Custom Hamiltonians\r\nIn this example, we will use OpenFermion to generate a Hubbard Model Hamiltonian, then use the Jordan-Wigner methods of OpenFermion and some custom functions to feed the output into the Cartan-Quantum-Synthesizer package",
"_____no_output_____"
],
[
"## Step 1: Build the Hamiltonian in OpenFermion",
"_____no_output_____"
]
],
[
[
"from CQS.methods import *\r\nfrom CQS.util.IO import tuplesToMatrix\r\nimport openfermion\r\nfrom openfermion import FermionOperator\r\n\r\nt = 1\r\nU = 8\r\nmu = 1\r\nsystemSize = 4 #number of qubits neeed\r\n#2 site, 1D lattice, indexed as |↑_0↑_1↓_2↓_3>\r\n#Hopping terms\r\nH = -t*(FermionOperator('0^ 1') + FermionOperator('1^ 0') + FermionOperator('2^ 3') + FermionOperator('3^ 2'))\r\n#Coulomb Terms\r\nH += U*(FermionOperator('0^ 0 2^ 2') + FermionOperator('1^ 1 3^ 3'))\r\n#Chemical Potential\r\nH += -mu*(FermionOperator('0^ 0') + FermionOperator('1^ 1') + FermionOperator('2^ 2') + FermionOperator('3^ 3'))\r\nprint(H)",
"-1.0 [0^ 0] +\n8.0 [0^ 0 2^ 2] +\n-1.0 [0^ 1] +\n-1.0 [1^ 0] +\n-1.0 [1^ 1] +\n8.0 [1^ 1 3^ 3] +\n-1.0 [2^ 2] +\n-1.0 [2^ 3] +\n-1.0 [3^ 2] +\n-1.0 [3^ 3]\n"
],
[
"#Jordan Wigner Transform\r\nHPauli = openfermion.jordan_wigner(H)\r\nprint(HPauli)\r\n",
"(2+0j) [] +\n(-0.5+0j) [X0 X1] +\n(-0.5+0j) [Y0 Y1] +\n(-1.5+0j) [Z0] +\n(2+0j) [Z0 Z2] +\n(-1.5+0j) [Z1] +\n(2+0j) [Z1 Z3] +\n(-0.5+0j) [X2 X3] +\n(-0.5+0j) [Y2 Y3] +\n(-1.5+0j) [Z2] +\n(-1.5+0j) [Z3]\n"
],
[
"#Custom Function to convert OpenFermion operators to a format readable by CQS:\r\n#Feel free to use or modify this code, but it is not built into the CQS package\r\ndef OpenFermionToCQS(H, systemSize):\r\n \"\"\"\r\n Converts the Operators to a list of (PauliStrings)\r\n\r\n Args:\r\n H(obj): The OpenFermion Operator\r\n systemSize (int): The number of qubits in the system\r\n \"\"\"\r\n stringToTuple = { \r\n 'X': 1,\r\n 'Y': 2,\r\n 'Z': 3\r\n }\r\n opList = []\r\n coList = [] \r\n for op in H.terms.keys(): #Pulls the operator out of the QubitOperator format\r\n coList.append(H.terms[op])\r\n opIndexList = []\r\n opTypeDict = {}\r\n tempTuple = ()\r\n for (opIndex, opType) in op:\r\n opIndexList.append(opIndex)\r\n opTypeDict[opIndex] = opType\r\n for index in range(systemSize):\r\n if index in opIndexList:\r\n tempTuple += (stringToTuple[opTypeDict[index]],)\r\n else:\r\n tempTuple += (0,)\r\n opList.append(tempTuple)\r\n return (coList, opList)\r\n \r\n#The new format looks like:\r\nprint(OpenFermionToCQS(HPauli, systemSize))",
"([(-0.5+0j), (-0.5+0j), (-0.5+0j), (-0.5+0j), (2+0j), (-1.5+0j), (-1.5+0j), (2+0j), (-1.5+0j), (-1.5+0j), (2+0j)], [(2, 2, 0, 0), (1, 1, 0, 0), (0, 0, 2, 2), (0, 0, 1, 1), (0, 0, 0, 0), (0, 0, 3, 0), (3, 0, 0, 0), (3, 0, 3, 0), (0, 0, 0, 3), (0, 3, 0, 0), (0, 3, 0, 3)])\n"
],
[
"#Now, we can put all this together:\r\n\r\n#Step 1: Create an Empty Hamiltonian Object\r\nHubbardH = Hamiltonian(systemSize)\r\n\r\n#Use Hamiltonian.addTerms to build the Hubbard model Hamiltonian:\r\nHubbardH.addTerms(OpenFermionToCQS(HPauli, systemSize))\r\n#This gives:\r\nHubbardH.getHamiltonian(type='printText')\r\n#There's an IIII term we would rather not deal with, so we can remove it like this:\r\nHubbardH.removeTerm((0,0,0,0))\r\n#This gives:\r\nprint('Idenity/Global Phase removed:')\r\nHubbardH.getHamiltonian(type='printText')\r\n\r\n#Be careful choosing an involution, because it might now decompose such that the Hamiltonian is in M:\r\ntry:\r\n HubbardC = Cartan(HubbardH)\r\nexcept Exception as e:\r\n print('Default Even/Odd Involution does not work:')\r\n print(e)\r\nprint('countY does work though. g = ')\r\nHubbardC = Cartan(HubbardH, involution='countY')\r\nprint(HubbardC.g)\r\n\r\n",
"(-0.5+0j) * YYII\n(-0.5+0j) * XXII\n(-0.5+0j) * IIYY\n(-0.5+0j) * IIXX\n(2+0j) * IIII\n(-1.5+0j) * IIZI\n(-1.5+0j) * ZIII\n(2+0j) * ZIZI\n(-1.5+0j) * IIIZ\n(-1.5+0j) * IZII\n(2+0j) * IZIZ\nIdenity/Global Phase removed:\n(-0.5+0j) * YYII\n(-0.5+0j) * XXII\n(-0.5+0j) * IIYY\n(-0.5+0j) * IIXX\n(-1.5+0j) * IIZI\n(-1.5+0j) * ZIII\n(2+0j) * ZIZI\n(-1.5+0j) * IIIZ\n(-1.5+0j) * IZII\n(2+0j) * IZIZ\nDefault Even/Odd Involution does not work:\nInvalid Involution. Please Choose an involution such that H ⊂ m\ncountY does work though. g = \n[(1, 2, 0, 0), (1, 2, 3, 0), (2, 1, 0, 0), (2, 1, 0, 3), (2, 1, 3, 0), (1, 2, 0, 3), (0, 0, 1, 2), (3, 0, 1, 2), (0, 0, 2, 1), (0, 3, 2, 1), (3, 0, 2, 1), (0, 3, 1, 2), (2, 2, 1, 2), (1, 1, 2, 1), (2, 2, 2, 1), (1, 1, 1, 2), (1, 2, 2, 2), (1, 2, 1, 1), (2, 1, 1, 1), (2, 1, 2, 2), (3, 3, 2, 1), (3, 3, 1, 2), (2, 1, 3, 3), (1, 2, 3, 3), (2, 2, 0, 0), (1, 1, 0, 0), (0, 0, 2, 2), (0, 0, 1, 1), (1, 1, 3, 3), (2, 2, 3, 3), (3, 3, 1, 1), (3, 3, 2, 2), (2, 2, 2, 2), (1, 1, 1, 1), (2, 2, 1, 1), (1, 1, 2, 2), (0, 0, 3, 0), (3, 0, 0, 0), (3, 0, 3, 0), (0, 0, 0, 3), (0, 3, 0, 0), (0, 3, 0, 3), (0, 3, 3, 0), (3, 0, 0, 3), (1, 2, 1, 2), (2, 1, 2, 1), (1, 2, 2, 1), (2, 1, 1, 2), (3, 0, 2, 2), (0, 3, 1, 1), (3, 0, 1, 1), (0, 3, 2, 2), (2, 2, 3, 0), (1, 1, 0, 3), (1, 1, 3, 0), (2, 2, 0, 3), (0, 3, 3, 3), (3, 0, 3, 3), (3, 3, 0, 3), (3, 3, 3, 0)]\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cba515b582e3dfbcbab87b75afb40a3a057a83df
| 36,764 |
ipynb
|
Jupyter Notebook
|
Python/.ipynb_checkpoints/Austin Azimuth gold standard-checkpoint.ipynb
|
maddy3940/ASCTB-Azimuth-Comparison-22
|
dae5f6154ac1e837e081665a8db93edd2f2e0ed9
|
[
"MIT"
] | 2 |
2022-03-09T15:08:34.000Z
|
2022-03-09T16:44:14.000Z
|
Python/Austin Azimuth gold standard.ipynb
|
maddy3940/ASCTB-Azimuth-Comparison-22
|
dae5f6154ac1e837e081665a8db93edd2f2e0ed9
|
[
"MIT"
] | 1 |
2022-03-09T15:15:22.000Z
|
2022-03-10T21:29:41.000Z
|
Python/Austin Azimuth gold standard.ipynb
|
maddy3940/ASCTB-Azimuth-Comparison-22
|
dae5f6154ac1e837e081665a8db93edd2f2e0ed9
|
[
"MIT"
] | null | null | null | 41.077095 | 129 | 0.420384 |
[
[
[
"import requests\nimport simplejson as json\nimport pandas as pd\nimport numpy as np\nimport os\nimport json\nimport math\nfrom openpyxl import load_workbook",
"_____no_output_____"
],
[
"df={\"mapping\":{\n\t\"Afferent / Efferent Arteriole Endothelial\": \"Afferent Arteriole Endothelial Cell\",\n\t\"Ascending Thin Limb\": \"Ascending Thin Limb Cell\",\n\t\"Ascending Vasa Recta Endothelial\": \"Ascending Vasa Recta Endothelial Cell\",\n\t\"B\": \"B cell\",\n\t\"Classical Dendritic\": \"Dendritic Cell (classical)\",\n\t\"Connecting Tubule\": \"Connecting Tubule Cell\",\n\t\"Connecting Tubule Intercalated Type A\": \"Connecting Tubule Intercalated Cell Type A\",\n\t\"Connecting Tubule Principal\": \"Connecting Tubule Principal Cell\",\n\t\"Cortical Collecting Duct Intercalated Type A\": \"Collecting Duct Intercalated Cell Type A\",\n\t\"Cortical Collecting Duct Principal\": \"Cortical Collecting Duct Principal Cell\",\n\t\"Cortical Thick Ascending Limb\": \"Cortical Thick Ascending Limb Cell\",\n\t\"Cortical Vascular Smooth Muscle / Pericyte\": \"Vascular Smooth Muscle Cell/Pericyte (general)\",\n\t\"Cycling Mononuclear Phagocyte\": \"Monocyte\",\n\t\"Descending Thin Limb Type 1\": \"Descending Thin Limb Cell Type 1\",\n\t\"Descending Thin Limb Type 2\": \"Descending Thin Limb Cell Type 2\",\n\t\"Descending Thin Limb Type 3\": \"Descending Thin Limb Cell Type 3\",\n\t\"Descending Vasa Recta Endothelial\": \"Descending Vasa Recta Endothelial Cell\",\n\t\"Distal Convoluted Tubule Type 1\": \"Distal Convoluted Tubule Cell Type 1\",\n\t\"Distal Convoluted Tubule Type 2\": \"Distal Convoluted Tubule Cell Type 1\",\n\t\"Fibroblast\": \"Fibroblast\",\n\t\"Glomerular Capillary Endothelial\": \"Glomerular Capillary Endothelial Cell\",\n\t\"Inner Medullary Collecting Duct\": \"Inner Medullary Collecting Duct Cell\",\n\t\"Intercalated Type B\": \"Intercalated Cell Type B\",\n\t\"Lymphatic Endothelial\": \"Lymphatic Endothelial Cell\",\n\t\"M2 Macrophage\": \"M2-Macrophage\",\n\t\"Macula Densa\": \"Macula Densa cell\",\n\t\"Mast\": \"Mast cell\",\n\t\"Medullary Fibroblast\": \"Fibroblast\",\n\t\"Medullary Thick Ascending Limb\": \"Medullary Thick Ascending Limb Cell\",\n\t\"Mesangial\": \"Mesangial Cell\",\n\t\"Monocyte-derived\": \"Monocyte\",\n\t\"Natural Killer T\": \"Natural Killer T Cell\",\n\t\"Neutrophil\": \"Neutrophil\",\n\t\"Non-classical monocyte\": \"non Classical Monocyte\",\n\t\"Outer Medullary Collecting Duct Intercalated Type A\": \"Outer Medullary Collecting Duct Intercalated Cell Type A\",\n\t\"Outer Medullary Collecting Duct Principal\": \"Outer Medullary Collecting Duct Principal Cell\",\n\t\"Papillary Tip Epithelial\": \"Endothelial\",\n\t\"Parietal Epithelial\": \"Parietal Epithelial Cell\",\n\t\"Peritubular Capilary Endothelial\": \"Peritubular Capillary Endothelial Cell\",\n\t\"Plasma\": \"Plasma cell\",\n\t\"Plasmacytoid Dendritic\": \"Dendritic Cell (plasmatoid)\",\n\t\"Podocyte\": \"Podocyte\",\n\t\"Proximal Tubule Epithelial Segment 1\": \"Proximal Tubule Epithelial Cell Segment 1\",\n\t\"Proximal Tubule Epithelial Segment 2\": \"Proximal Tubule Epithelial Cell Segment 2\",\n\t\"Proximal Tubule Epithelial Segment 3\": \"Proximal Tubule Epithelial Cell Segment 3\",\n\t\"Renin-positive Juxtaglomerular Granular\": \"Juxtaglomerular granular cell (Renin positive)\",\n\t\"Schwann / Neural\": \"other\",\n\t\"T\": \"T Cell\",\n\t\"Vascular Smooth Muscle / Pericyte\": \"Vascular Smooth Muscle Cell/Pericyte (general)\"}\n}\ndf = pd.DataFrame(df)\ndf.reset_index(inplace=True)\ndf.rename(columns = {\"index\":\"AZ.CT/LABEL\",\"mapping\":\"ASCTB.CT/LABEL\"},inplace = True)\ndf.reset_index(inplace=True,drop=True)\ndf",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
],
[
"df_1=pd.read_excel('./Data/Final/kidney.xlsx',sheet_name='Final_Matches')",
"_____no_output_____"
],
[
"len(df_1)",
"_____no_output_____"
],
[
"df_1",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba521fe50af31d39b4e398eb60f6bc7fdcdee6a
| 71,855 |
ipynb
|
Jupyter Notebook
|
3_Creating_Reading and Writing/Viewing_Data.ipynb
|
sureshmecad/Pandas
|
128091e7021158f39eb0ff97e0e63d76e778a52c
|
[
"CNRI-Python"
] | null | null | null |
3_Creating_Reading and Writing/Viewing_Data.ipynb
|
sureshmecad/Pandas
|
128091e7021158f39eb0ff97e0e63d76e778a52c
|
[
"CNRI-Python"
] | null | null | null |
3_Creating_Reading and Writing/Viewing_Data.ipynb
|
sureshmecad/Pandas
|
128091e7021158f39eb0ff97e0e63d76e778a52c
|
[
"CNRI-Python"
] | null | null | null | 43.260084 | 148 | 0.386111 |
[
[
[
"## Viewing your data",
"_____no_output_____"
]
],
[
[
"The first thing to do when opening a new dataset is print out a few rows to keep as a visual reference.\nWe accomplish this with .head():",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"movies_df = pd.read_csv(\"C:/Users/deepusuresh/Documents/Data Science/01. Python/1. Practice/2. PANDAS/1. Data Frame/IMDB-Movie-Data.csv\")\nmovies_df",
"_____no_output_____"
]
],
[
[
"-------------------------------------------------------------------------------------------------------------------------------",
"_____no_output_____"
],
[
"### 1. head( ) outputs the first five rows of your DataFrame by default",
"_____no_output_____"
],
[
"### 2. We could also pass a number as well: movies_df.head(10) would output the top ten rows",
"_____no_output_____"
],
[
"-------------------------------------------------------------------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"movies_df.head()",
"_____no_output_____"
]
],
[
[
"-------------------------------------------------------------------------------------------------------------------------------",
"_____no_output_____"
],
[
"### 1. Last five rows use tail( )",
"_____no_output_____"
],
[
"### 2. tail( ) also accepts a number, and in this case we printing the bottom two rows movies_df.tail(2)",
"_____no_output_____"
],
[
"-------------------------------------------------------------------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"movies_df.tail(2)",
"_____no_output_____"
]
]
] |
[
"markdown",
"raw",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"raw"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
cba522c2baa438b67799236afb7e64dbb739fceb
| 27,214 |
ipynb
|
Jupyter Notebook
|
code/dws-reports.ipynb
|
data-workspaces/buoy-data-analysis
|
126bb4976264adbefb4e13a67ceba113f333c2c9
|
[
"Apache-2.0"
] | 1 |
2020-05-04T01:57:46.000Z
|
2020-05-04T01:57:46.000Z
|
code/dws-reports.ipynb
|
data-workspaces/buoy-data-analysis
|
126bb4976264adbefb4e13a67ceba113f333c2c9
|
[
"Apache-2.0"
] | null | null | null |
code/dws-reports.ipynb
|
data-workspaces/buoy-data-analysis
|
126bb4976264adbefb4e13a67ceba113f333c2c9
|
[
"Apache-2.0"
] | null | null | null | 60.207965 | 892 | 0.521937 |
[
[
[
"import dataworkspaces.kits.jupyter\n%load_ext dataworkspaces.kits.jupyter\n",
"_____no_output_____"
],
[
"%dws_history",
"_____no_output_____"
],
[
"%dws_history --heatmap --minimize-metrics air_slope,water_slope",
"_____no_output_____"
],
[
"%dws_history --baseline=buoy-42040-final --minimize-metrics air_slope,water_slope\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
cba5402c7606f7dbc171cfeacddc30c4cc93f5d9
| 1,667 |
ipynb
|
Jupyter Notebook
|
desihigh/sandbox/RipplesInTheCosmos.ipynb
|
XanderC9/desihigh
|
13ffabe1ed0ecb1811765bf6fe43709d8e92c3b3
|
[
"BSD-3-Clause"
] | 22 |
2021-01-29T05:34:05.000Z
|
2022-03-19T19:02:07.000Z
|
desihigh/sandbox/RipplesInTheCosmos.ipynb
|
XanderC9/desihigh
|
13ffabe1ed0ecb1811765bf6fe43709d8e92c3b3
|
[
"BSD-3-Clause"
] | 34 |
2021-01-18T02:22:52.000Z
|
2022-02-18T15:17:42.000Z
|
desihigh/sandbox/RipplesInTheCosmos.ipynb
|
XanderC9/desihigh
|
13ffabe1ed0ecb1811765bf6fe43709d8e92c3b3
|
[
"BSD-3-Clause"
] | 28 |
2021-02-01T02:02:25.000Z
|
2022-02-25T18:15:00.000Z
| 19.16092 | 60 | 0.54769 |
[
[
[
"import numpy as np\nimport astropy.io.fits as fits\n\nfrom IPython.display import YouTubeVideo",
"_____no_output_____"
]
],
[
[
"# Ripples in the Cosmos",
"_____no_output_____"
],
[
"The early Universe was extraordinarily hot, and dense.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown"
]
] |
cba543f0afa7195ffdbb9c4757eb666fd86747c2
| 402,253 |
ipynb
|
Jupyter Notebook
|
csc/cminl1_gry.ipynb
|
bwohlberg/sporco-notebooks
|
9248e7d5b3ec24d34c6d39a6b38295d5c062dc75
|
[
"BSD-3-Clause"
] | 16 |
2018-03-26T19:55:40.000Z
|
2022-03-29T10:17:33.000Z
|
csc/cminl1_gry.ipynb
|
bwohlberg/sporco-notebooks
|
9248e7d5b3ec24d34c6d39a6b38295d5c062dc75
|
[
"BSD-3-Clause"
] | 2 |
2018-05-01T03:28:58.000Z
|
2018-05-06T09:59:57.000Z
|
csc/cminl1_gry.ipynb
|
bwohlberg/sporco-notebooks
|
9248e7d5b3ec24d34c6d39a6b38295d5c062dc75
|
[
"BSD-3-Clause"
] | 3 |
2019-02-02T18:48:07.000Z
|
2020-10-29T09:29:30.000Z
| 724.78018 | 207,812 | 0.949015 |
[
[
[
"Single-channel CSC (Constrained Data Fidelity)\n==============================================\n\nThis example demonstrates solving a constrained convolutional sparse coding problem with a greyscale signal\n\n $$\\mathrm{argmin}_\\mathbf{x} \\sum_m \\| \\mathbf{x}_m \\|_1 \\; \\text{such that} \\; \\left\\| \\sum_m \\mathbf{d}_m * \\mathbf{x}_m - \\mathbf{s} \\right\\|_2 \\leq \\epsilon \\;,$$\n\nwhere $\\mathbf{d}_{m}$ is the $m^{\\text{th}}$ dictionary filter, $\\mathbf{x}_{m}$ is the coefficient map corresponding to the $m^{\\text{th}}$ dictionary filter, and $\\mathbf{s}$ is the input image.",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nfrom builtins import input\n\nimport pyfftw # See https://github.com/pyFFTW/pyFFTW/issues/40\nimport numpy as np\n\nfrom sporco import util\nfrom sporco import signal\nfrom sporco import plot\nplot.config_notebook_plotting()\nimport sporco.metric as sm\nfrom sporco.admm import cbpdn",
"_____no_output_____"
]
],
[
[
"Load example image.",
"_____no_output_____"
]
],
[
[
"img = util.ExampleImages().image('kodim23.png', scaled=True, gray=True,\n idxexp=np.s_[160:416,60:316])",
"_____no_output_____"
]
],
[
[
"Highpass filter example image.",
"_____no_output_____"
]
],
[
[
"npd = 16\nfltlmbd = 10\nsl, sh = signal.tikhonov_filter(img, fltlmbd, npd)",
"_____no_output_____"
]
],
[
[
"Load dictionary and display it.",
"_____no_output_____"
]
],
[
[
"D = util.convdicts()['G:12x12x36']\nplot.imview(util.tiledict(D), fgsz=(7, 7))",
"_____no_output_____"
]
],
[
[
"Set [admm.cbpdn.ConvMinL1InL2Ball](http://sporco.rtfd.org/en/latest/modules/sporco.admm.cbpdn.html#sporco.admm.cbpdn.ConvMinL1InL2Ball) solver options.",
"_____no_output_____"
]
],
[
[
"epsilon = 3.4e0\nopt = cbpdn.ConvMinL1InL2Ball.Options({'Verbose': True, 'MaxMainIter': 200,\n 'HighMemSolve': True, 'LinSolveCheck': True,\n 'RelStopTol': 5e-3, 'AuxVarObj': False, 'rho': 50.0,\n 'AutoRho': {'Enabled': False}})",
"_____no_output_____"
]
],
[
[
"Initialise and run CSC solver.",
"_____no_output_____"
]
],
[
[
"b = cbpdn.ConvMinL1InL2Ball(D, sh, epsilon, opt)\nX = b.solve()\nprint(\"ConvMinL1InL2Ball solve time: %.2fs\" % b.timer.elapsed('solve'))",
"Itn Fnc Cnstr r s \n--------------------------------------------\n"
]
],
[
[
"Reconstruct image from sparse representation.",
"_____no_output_____"
]
],
[
[
"shr = b.reconstruct().squeeze()\nimgr = sl + shr\nprint(\"Reconstruction PSNR: %.2fdB\\n\" % sm.psnr(img, imgr))",
"Reconstruction PSNR: 37.02dB\n\n"
]
],
[
[
"Display low pass component and sum of absolute values of coefficient maps of highpass component.",
"_____no_output_____"
]
],
[
[
"fig = plot.figure(figsize=(14, 7))\nplot.subplot(1, 2, 1)\nplot.imview(sl, title='Lowpass component', fig=fig)\nplot.subplot(1, 2, 2)\nplot.imview(np.sum(abs(X), axis=b.cri.axisM).squeeze(), cmap=plot.cm.Blues,\n title='Sparse representation', fig=fig)\nfig.show()",
"_____no_output_____"
]
],
[
[
"Display original and reconstructed images.",
"_____no_output_____"
]
],
[
[
"fig = plot.figure(figsize=(14, 7))\nplot.subplot(1, 2, 1)\nplot.imview(img, title='Original', fig=fig)\nplot.subplot(1, 2, 2)\nplot.imview(imgr, title='Reconstructed', fig=fig)\nfig.show()",
"_____no_output_____"
]
],
[
[
"Get iterations statistics from solver object and plot functional value, ADMM primary and dual residuals, and automatically adjusted ADMM penalty parameter against the iteration number.",
"_____no_output_____"
]
],
[
[
"its = b.getitstat()\nfig = plot.figure(figsize=(20, 5))\nplot.subplot(1, 3, 1)\nplot.plot(its.ObjFun, xlbl='Iterations', ylbl='Functional', fig=fig)\nplot.subplot(1, 3, 2)\nplot.plot(np.vstack((its.PrimalRsdl, its.DualRsdl)).T,\n ptyp='semilogy', xlbl='Iterations', ylbl='Residual',\n lgnd=['Primal', 'Dual'], fig=fig)\nplot.subplot(1, 3, 3)\nplot.plot(its.Rho, xlbl='Iterations', ylbl='Penalty Parameter', fig=fig)\nfig.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba545a3c00730f5dd06af3019054a68597b1c81
| 207,593 |
ipynb
|
Jupyter Notebook
|
Stewart/SymbolStewart.ipynb
|
sppool/works
|
2ab9c10d7326e0e836f3214f5067b6f070deb2e0
|
[
"MIT"
] | 1 |
2020-05-27T16:41:42.000Z
|
2020-05-27T16:41:42.000Z
|
Stewart/SymbolStewart.ipynb
|
sppool/works
|
2ab9c10d7326e0e836f3214f5067b6f070deb2e0
|
[
"MIT"
] | null | null | null |
Stewart/SymbolStewart.ipynb
|
sppool/works
|
2ab9c10d7326e0e836f3214f5067b6f070deb2e0
|
[
"MIT"
] | 3 |
2020-04-11T08:13:29.000Z
|
2020-05-11T14:15:53.000Z
| 216.01769 | 60,980 | 0.685953 |
[
[
[
"# 六軸史都華平台模擬",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nfrom sympy import *\ninit_printing(use_unicode=True)\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nimport seaborn as sns\nsns.set()\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Stewart Func",
"_____no_output_____"
]
],
[
[
"α, β, γ = symbols('α β γ')\nx, y, z = symbols('x y z')\nr, R, w, W, t = symbols('r R w W t')\n\n# x, y, z三軸固定軸旋轉矩陣\nrotx = lambda θ : Matrix([[1, 0, 0], \n [0, cos(θ), -sin(θ)], \n [0, sin(θ), cos(θ)]])\nroty = lambda θ : Matrix([[cos(θ), 0, sin(θ)], \n [0, 1, 0], \n [-sin(θ), 0, cos(θ)]])\nrotz = lambda θ : Matrix([[cos(θ), -sin(θ), 0], \n [sin(θ), cos(θ), 0], \n [0, 0, 1]])\n\n# 姿勢產生器 固定座標旋轉\ndef poses(α, β, γ):\n return rotz(γ)*roty(β)*rotx(α)\n\n# 質心位置產生器\ndef posit(x, y, z):\n return Matrix([x, y, z])\n\n# Basic 6 軸點設定\ndef basic(r, w):\n b1 = Matrix([w/2, r, 0])\n b2 = Matrix([-w/2, r, 0])\n b3 = rotz(pi*2/3)*b1\n b4 = rotz(pi*2/3)*b2\n b5 = rotz(pi*2/3)*b3\n b6 = rotz(pi*2/3)*b4\n return [b1, b2, b3, b4, b5, b6]\n\n# 平台 6 軸點設定\ndef plat(r, w, pos=poses(0, 0, 0), pit=posit(0, 0, 5)):\n p1 = Matrix([-w/2, r, 0])\n p1 = rotz(-pi/3)*p1\n p2 = Matrix([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])*p1\n p3 = rotz(pi*2/3)*p1\n p4 = rotz(pi*2/3)*p2\n p5 = rotz(pi*2/3)*p3\n p6 = rotz(pi*2/3)*p4\n lst = [p1, p2, p3, p4, p5, p6]\n for n in range(6):\n lst[n] = (pos*lst[n]) + pit\n return lst\n\n# 六軸長度\ndef leng(a, b):\n if a.ndim == 1:\n return (((a - b)**2).sum())**0.5\n else:\n return (((a - b)**2).sum(1))**0.5",
"_____no_output_____"
]
],
[
[
"### Basic & plane",
"_____no_output_____"
]
],
[
[
"basic(R, W)",
"_____no_output_____"
],
[
"plat(r, w, poses(α, β, γ), posit(x, y, z))",
"_____no_output_____"
]
],
[
[
"### 設定α, β, γ, x, y, z 可設定為時間t的函數",
"_____no_output_____"
]
],
[
[
"pos = poses(sin(2*t), cos(t), 0)\npit = posit(x, y, z)\n\nbaspt = basic(R, W)\nbaspt = np.array(baspt)\npltpt = plat(r, w, pos, pit)\npltpt = np.array(pltpt)",
"_____no_output_____"
]
],
[
[
"### 6軸的長度 (示範軸1)",
"_____no_output_____"
]
],
[
[
"length = leng(baspt ,pltpt)",
"_____no_output_____"
]
],
[
[
"### 設定參數 r = 10, R = 5, w = 2, W = 2, x = 0, y = 0, z = 10",
"_____no_output_____"
]
],
[
[
"x1 = length[0].subs([(r, 10), (R, 5), (w, 2), (W, 2), (x, 0), (y, 0), (z, 10)])",
"_____no_output_____"
],
[
"x1",
"_____no_output_____"
]
],
[
[
"### 微分一次獲得速度變化",
"_____no_output_____"
]
],
[
[
"dx1 = diff(x1, t)\ndx1",
"_____no_output_____"
]
],
[
[
"### 微分兩次獲得加速度變化",
"_____no_output_____"
]
],
[
[
"ddx1 = diff(dx1, t)\nddx1",
"_____no_output_____"
]
],
[
[
"### 畫圖",
"_____no_output_____"
]
],
[
[
"tline = np.linspace(0, 2*np.pi, 361)\n\nxlst = lambdify(t, x1, 'numpy') \ndxlst = lambdify(t, dx1, 'numpy') \nddxlst = lambdify(t, ddx1, 'numpy') \n\nplt.rcParams['figure.figsize'] = [16, 6]\nplt.plot(tline, xlst(tline), label = 'x')\nplt.plot(tline, dxlst(tline), label = 'v')\nplt.plot(tline, ddxlst(tline), label = 'a')\nplt.ylabel('Length')\nplt.xlabel('Time')\nplt.legend()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba54ed4f9eb7c7fcd5c98d73cff3a3f3dd7ecdd
| 825,472 |
ipynb
|
Jupyter Notebook
|
notebooks/classifiers_playground/box_method_classifier/classifier_1D__box_method__SAFE_COPY.ipynb
|
m-salewski/stay_classification
|
e3f9deadf51c97029a0f9a4bb669a5af68abf7c6
|
[
"MIT"
] | null | null | null |
notebooks/classifiers_playground/box_method_classifier/classifier_1D__box_method__SAFE_COPY.ipynb
|
m-salewski/stay_classification
|
e3f9deadf51c97029a0f9a4bb669a5af68abf7c6
|
[
"MIT"
] | null | null | null |
notebooks/classifiers_playground/box_method_classifier/classifier_1D__box_method__SAFE_COPY.ipynb
|
m-salewski/stay_classification
|
e3f9deadf51c97029a0f9a4bb669a5af68abf7c6
|
[
"MIT"
] | null | null | null | 330.850501 | 191,052 | 0.915006 |
[
[
[
"from IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))",
"_____no_output_____"
],
[
"import numpy as np\n\n%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import os, sys\nsys.path.append('/home/sandm/Notebooks/stay_classification/src/')",
"_____no_output_____"
]
],
[
[
"# TODOs (from 09.06.2020)\n\n1. Strip away the non-useful functions\n2. Document the remaining functions\n3. Move the remaining functions to modules\n4. Test the modules\n5. Clean up this NB",
"_____no_output_____"
],
[
"# Introduction: movement analysis\n\nFrom a sequence of signaling events, _eg_ GPS measurements, determine locations where the user remains for a significant duration of time, called \"stays\". For each of these, there should be a beginning and end, as well as a location. \n\nGenerally, this is meant for movement on the surface of the earth, but for present purposes, it is easiest to illustrate in one spatial dimension \"1D\"; all of the problems and strategies can be generalized to 2D as needed.",
"_____no_output_____"
],
[
"**Note** the signaling events for a given user, form a set $\\mathcal{E} := \\{e_i = (\\mathbf{x}_i, t_i), i=[0,N-1] \\; | \\; t_{i+1}>t_i\\}$",
"_____no_output_____"
]
],
[
[
"from synthetic_data.trajectory import get_stay\nfrom synthetic_data.trajectory import get_journey_path, get_segments\nfrom synthetic_data.masking import get_mask_with_duplicates\nfrom synthetic_data.trajectory import get_stay_segs, get_adjusted_stays\nfrom synthetic_data.noise import get_noisy_segs, get_noisy_path, get_noise_arr\n\ndsec = 1/3600.0\ntime = np.arange(0,24,dsec)\nstays = [\n get_stay( 0.00, 6.00,-1.00), #home\n get_stay( 7.50, 16.50, 1.00), #work, afternoon\n get_stay( 18.00, 24.00,-1.00) # overnight\n ]\n\nt_segs, x_segs = get_stay_segs(stays)\n\n\nraw_journey = get_journey_path(time, get_segments(time, stays, threshold=0.5))\n\n\ndup_mask = get_mask_with_duplicates(time, 0.05, 0.3)\n\ntime_sub = time[dup_mask]\nraw_journey_sub = raw_journey[dup_mask]\n\nsegments = get_segments(time, stays, threshold=0.5)\nnew_stays = get_adjusted_stays(segments, time_sub)\nnew_t_segs, new_x_segs = get_stay_segs(new_stays) \n\nnoises = get_noise_arr(0.02, 0.15, len(segments))\n\nnoise_segments = get_noisy_segs(segments, noises)\n\nnoise_journey_sub = get_noisy_path(time_sub, raw_journey_sub, noise_segments)",
"_____no_output_____"
]
],
[
[
"**Figure** in the above plot, time is on the \"x\"-axis. An interpretation of this motion, is that the user is initially making a \"stay\" at a location near $x=-1$, then makes another stay at $x=1$, ending with a return to the initial location. As with all of this data, there is an intrinsic noise that must be considered.",
"_____no_output_____"
],
[
"# Goal: Stay detection and positioning\n\nThe goal is to identify stays by their beginnings and ends, and associate them to a position. This effectively means to optimally match clusters of points with flat lines.\n\nFor a set of events within a cluster $\\mathcal{C}_l = \\{e_i \\; | \\; i = [m,n]_l \\subset [0,N-1]\\}$, a \"flat line\" has $|\\mathbf{x}_m-\\mathbf{x}_n| = 0$. Again, this is easiest to see in 1D but it also holds in 2D.\n",
"_____no_output_____"
],
[
"# Strategy\n\nTo find the stays, we consider some requirements.\n\nFirstly, there are two main requirements (previously noted):\n1. identify the start/stop of a stay\n2. estimate a dominant location, _ie_ the \"central location\" of the stay\n * this is where the agent spends the majority of the time, _e.g._ within a building, at a park, etc.\n\nThen, there are some minor rquirements:\n1. the clusters should contain a minimum number of points\n2. the duration between the first and last points should exceed $\\Delta t$\n3. the clusters should be as long (in time) as possible\n * if there is a sufficient temporal break between two consecutive events without a significant location change, then on must specify how this is to be dealt with.\n4. the clusters should contain as many events as possible\n\nOne additional requirement which affects all of the above: **cluster outliers should be identified and ignored** \n* outliers can change the central location and also the beginning/ending of the clusters\n* from the calculation of the central location\n * counting them could still help in identifying a cluster wihtout using their position\n \nAll of these must be considered together.",
"_____no_output_____"
],
[
"This clearly defines an optimization problem: \n* maximize the length of the fit line, while \n * mimimizing its error by adjusting its position ($\\mathrm{x}_{\\mathrm{opt.}}$) and end-regions ($t_{\\mathrm{start}}, t_{\\mathrm{stop}}$)\n * ignoring the outliers.\n\n**Notes** \n\n* When the error is the mean squared error: $\\epsilon := \\sqrt{ \\frac{1}{N}\\sum^N_i(\\mathrm{x}_i-\\mathrm{x}_{\\mathrm{opt.}})^2}$; \n * this simplifies the position since the mean (or \"centroid\") is the value of $\\mathrm{x}_{\\mathrm{opt.}}$ which minimizes this error, leaving only the adjustment of the end-regions and outliers for the optimization task.\n\nThis suggests that there is at least a solution to this problem: \nOne could consider all possible combinations of subsequences and all possible combinations of their outliers, and measure error, and then pick any from the set of lowest error subsequence-outlier combination fits. However, this is similar to the maximum subarray problem, and in the worst case it would be $\\mathcal{O}(n^3)$.\n\nIt's countably finite, but impractical approach; itcan be a benchmark to compare all other algorithms which aim to do the same within some acceptable error.",
"_____no_output_____"
],
[
"### The Box",
"_____no_output_____"
]
],
[
[
"eps = 0.25",
"_____no_output_____"
],
[
"from matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Rectangle",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1,1,figsize=(20,10))\n\nbegin = t_segs[3]+1\nbegin_buff = begin-2\nend = t_segs[4]-1\nend_buff = end+2\n\nloc = x_segs[3]\n\n\nrect_inner = Rectangle((begin, loc-eps), end-begin, 2*eps)\nrect_outer = Rectangle((begin_buff, loc-eps), end_buff-begin_buff, 2*eps)\nrect_outer2 = Rectangle((begin_buff/2, loc-eps), end+(begin-begin_buff), 2*eps)\n\n# The adjusted rwa-stays\n#plt.plot(t_segs, x_segs, '--', marker='o', color='k', linewidth=4.0, markerfacecolor='w', markersize=6.0, markeredgewidth=2.0, label='adjusted raw stays')\n\nax.plot([begin,end], [loc,loc], 'k--', dashes=[3,2], linewidth=3.0)\n\nax.plot([begin_buff,begin], [loc,loc], color='k', marker='|', markersize=40.0, dashes=[1,2], linewidth=3.0)\nax.plot([end,end_buff], [loc,loc], color='k', marker='|', markersize=40.0, dashes=[1,2], linewidth=3.0)\n\n#plt.plot(t_segs[3:5], x_segs[3:5], '--', marker='o', color='k', linewidth=4.0, markerfacecolor='w', markersize=6.0, markeredgewidth=2.0, label='adjusted raw stays')\n\nax.plot(time_sub, raw_journey_sub, ':', label='raw journey')\nax.plot(time_sub, noise_journey_sub, '.-', label='noisy journey', alpha=0.5)\n\n\n\n\nrect_inner = Rectangle((begin, loc-eps), end-begin, 2*eps)\nrect_outer = Rectangle((begin_buff, loc-eps), end_buff-begin_buff, 2*eps)\nrect_outer2 = Rectangle((begin_buff/2, loc-eps), end+(begin-begin_buff), 2*eps)\n\n# Create patch collection with specified colour/alpha\npc = PatchCollection([rect_outer2], \\\n facecolor='gray', alpha=0.2, edgecolor='k',linewidth=0)\n# Create patch collection with specified colour/alpha\npc1 = PatchCollection([rect_outer], \\\n facecolor='gray', alpha=0.2, edgecolor='k',linewidth=0)\n\npc2 = PatchCollection([rect_inner], \\\n facecolor='gray', alpha=0.5, edgecolor='k',linewidth=0)\n\n\n# Add collection to axes\nax.add_collection(pc)\nax.add_collection(pc1)\nax.add_collection(pc2)\n\n\n# interface tracking profiles\narrowprops=dict(arrowstyle=\"<->\", \n shrinkA=0.5,\n mutation_scale=30.0,\n connectionstyle=\"arc3\", linewidth=4.0)\n# the arrows\narrowcentery = 1.0\narrowcenterx = 12\narrowcenterh = 0.5\nax.annotate(\"\", xy=(arrowcenterx, arrowcentery-arrowcenterh), xytext=(arrowcenterx, arrowcentery+arrowcenterh),\n arrowprops=arrowprops)\n\ndt_arrowcentery = 0.25\nax.annotate(\"\", xy=(begin_buff, arrowcentery-dt_arrowcentery), xytext=(begin, arrowcentery-dt_arrowcentery),\n arrowprops=arrowprops)\n\nax.annotate(\"\", xy=(end, arrowcentery-dt_arrowcentery), xytext=(end_buff, arrowcentery-dt_arrowcentery),\n arrowprops=arrowprops)\n\n\nmid_point = lambda x1,x2: 0.5*(x1+x2)\n\ndelta_t_texty = 1.5\nax.annotate(r\"Adjust starting point by $\\Delta t$\", fontsize=24.0,\n xy=(mid_point(begin,begin_buff), 1.1), xycoords='data',\n xytext=(begin-8,delta_t_texty), textcoords='data',\n arrowprops=dict(arrowstyle=\"->\", color=\"0.5\",\n shrinkA=5, shrinkB=5,\n patchA=None, patchB=None,\n connectionstyle=\"arc3,rad=-0.3\", linewidth=2.0\n ),\n )\nax.annotate(r\"Adjust ending point by $\\Delta t$\", fontsize=24.0,\n xy=(mid_point(end,end_buff), 1.1), xycoords='data',\n xytext=(end, delta_t_texty), textcoords='data',\n arrowprops=dict(arrowstyle=\"->\", color=\"0.5\",\n shrinkA=5, shrinkB=5,\n patchA=None, patchB=None,\n connectionstyle=\"arc3,rad=0.3\", linewidth=2.0\n ),\n )\n\nax.annotate(r\"Adjust $x$-position of central location\",fontsize= 24,\n xy=(arrowcenterx+0.25, arrowcentery-0.1), xycoords='data',\n xytext=(arrowcenterx-5, arrowcentery-2.0), textcoords='data',\n arrowprops=dict(arrowstyle=\"->\", color=\"0.5\",\n shrinkA=5, shrinkB=5,\n patchA=None, patchB=None,\n connectionstyle=\"arc3,rad=0.3\", linewidth=2.0\n ),\n )\n\n'''plt.text(0, 0.1, r'$\\delta$',\n {'color': 'black', 'fontsize': 24, 'ha': 'center', 'va': 'center',\n 'bbox': dict(boxstyle=\"round\", fc=\"white\", ec=\"black\", pad=0.2)})\n'''\nplt.xlabel(r'time, $t$ [arb.]')\nplt.ylabel(r'position, $x$ [arb.]')\nplt.ylim(-1.5, 2)\nplt.grid(visible=False);",
"_____no_output_____"
]
],
[
[
"Once the box (width is provided by the spatial tolerance) is positioned in a good way (_ie_ the centroid), extending the box forwards or backwards in time makes no change to the _score_ of the box.\n\nHere, the score could be something like the number of points, the std/MSE; whatever it is, it should be saturated at some point and extending the box makes no difference, meaning that something converges which provides a stopping criterion. ",
"_____no_output_____"
],
[
"### Box method",
"_____no_output_____"
]
],
[
[
"import random\ncolors = [plt.cm.Spectral(each)\n for each in np.linspace(0, 1, 20)]\nrandom.shuffle(colors)",
"_____no_output_____"
]
],
[
[
"## From here",
"_____no_output_____"
]
],
[
[
"from stay_classification.box_method import asymm_box_method_modular\nfrom stay_classification.box_method import get_thresh_duration, get_slope",
"_____no_output_____"
],
[
"eps = 0.25\ntime_thresh = 5/12\n\nlong_time_thresh = 1.0\nslope_thresh = 1.0\ncount_thresh = 50\n\nmin_t, max_t = 0.5, 23.5\n\n\nfig, ax = plt.subplots(1,1,figsize=(20,10))\n\n# The adjusted rwa-stays\n#plt.plot(t_segs, x_segs, '--', marker='o', color='k', linewidth=4.0, markerfacecolor='w', markersize=6.0, markeredgewidth=2.0, label='adjusted raw stays')\n\nax.plot(time_sub, noise_journey_sub, '.-', color='gray', label='noisy journey', alpha=0.25)\nax.plot(time_sub, raw_journey_sub, ':', color='k', label='raw journey')\n#ax.plot(time_sub, noise_journey_sub, '.-', label='noisy journey', alpha=0.5)\n\nlast_ind = 0\n\nnnn = 0\nfor timepoint in np.arange(min_t,max_t,0.25):\n\n if timepoint < time_sub[last_ind]:\n continue \n \n mean, start_ind, last_ind = asymm_box_method_modular(time_sub,time_thresh,noise_journey_sub,eps,timepoint)\n \n if time_sub[last_ind]-time_sub[start_ind] < time_thresh:\n continue\n \n t0, t1 = get_thresh_duration(eps, mean)(noise_journey_sub[start_ind:last_ind],start_ind) \n if time_sub[t1]-time_sub[t0] < time_thresh:\n continue \n\n # If the stay is less than 1 hour, check the slope of the segement\n if time_sub[t1]-time_sub[t0] < long_time_thresh: \n xdata = time_sub[t0:t1]\n ydata = noise_journey_sub[t0:t1]\n slope = get_slope(xdata, ydata)\n print(timepoint, slope)\n if abs(slope) > slope_thresh: \n continue \n \n #print(timepoint,\":\", mean, start_ind, last_ind) \n ax.plot([time_sub[start_ind],time_sub[last_ind]], [mean,mean], '--', color=colors[nnn], label=f'ID #{timepoint}')\n \n t_diff = abs(time_sub[t1]-time_sub[t0])\n ax.plot([time_sub[t0],time_sub[t1]], [mean,mean], '--', \\\n dashes=[1,1], linewidth=5, color=colors[nnn], \\\n label=f'ID #{timepoint}: {round(t_diff,2)}, sub')\n \n # Add the box\n rect_color = \"gray\" #colors[nnn]\n rect = Rectangle((time_sub[t0], mean-eps), t_diff, 2*eps)\n pc = PatchCollection([rect], \\\n facecolor=rect_color, alpha=0.2, edgecolor=rect_color,linewidth=1)\n ax.add_collection(pc)\n\n print(timepoint, t_diff,t0,t1)\n nnn += 1\n \nplt.xlabel(r'time, $t$ [arb.]')\nplt.ylabel(r'position, $x$ [arb.]')\nplt.ylim(-1.5, 2)\n\n#plt.xlim(min_t, max_t)\nplt.xlim(-0.1, 24.1)\n#plt.xlim(15.1, 19.1)\n\nplt.title('Rough cut', fontsize=36)\nplt.grid(visible=False);\nplt.legend();",
"0.5 6.202222222222223 1 1161\n6.25 1.3438008611884393\n7.25 1.3438008611884393\n7.75 9.625277777777779 1363 2988\n17.0 -1.2073016525690423\n17.5 -1.3733710513734538\n18.0 6.302500000000002 3141 4317\n"
],
[
"rand_range = lambda size, max_, min_: (max_-min_)*np.random.random_sample(size=size) + min_",
"_____no_output_____"
],
[
"from synthetic_data.trajectory import get_stay\nfrom synthetic_data.trajectory import get_journey_path, get_segments\nfrom synthetic_data.masking import get_mask_with_duplicates\nfrom synthetic_data.trajectory import get_stay_segs, get_adjusted_stays\nfrom synthetic_data.noise import get_noisy_segs, get_noisy_path, get_noise_arr\nfrom synthetic_data.noise import get_noisy_segs, get_noisy_path, get_noise_arr",
"_____no_output_____"
],
[
"from synthetic_data.trajectory_class import get_trajectory",
"_____no_output_____"
],
[
"dsec = 1/3600.0\ntime = np.arange(0,24,dsec)",
"_____no_output_____"
],
[
"event_frac = rand_range(1,0.01,0.001)[0]\n\nduplicate_frac = rand_range(1,0.3,0.05)[0]\n\nprint(event_frac, duplicate_frac)\n\nconfigs = {\n 'threshold':0.5,\n 'event_frac':event_frac,\n 'duplicate_frac':duplicate_frac, \n 'noise_min':0.02,\n 'noise_max':0.15\n}\n\n\nnr_stays = np.random.randint(10)\nstay_time_bounds = np.concatenate((np.array([0]),rand_range(2*nr_stays, 24, 0),np.array([24])))\nstay_time_bounds = np.sort(stay_time_bounds)\nstay_xlocs = rand_range(nr_stays+1, 2, - 2.0)\n\nstays = []\nfor n in range(nr_stays+1):\n \n nn = 2*n\n stay = get_stay(stay_time_bounds[nn], stay_time_bounds[nn+1], stay_xlocs[n])\n #print(n,nn,nn+1,stay)\n stays.append(stay)\n \n\ntime_sub, raw_journey_sub, noise_journey_sub = get_trajectory(stays, time, configs)\n\nsegments = get_segments(time, stays, threshold=0.5)\nnew_stays = get_adjusted_stays(segments, time_sub)\nnew_t_segs, new_x_segs = get_stay_segs(new_stays) \n\nplt.figure(figsize=(20,10))\n#plt.plot(t_segs, x_segs, ':', marker='|', color='grey', linewidth=2.0, markerfacecolor='w', markersize=30.0, markeredgewidth=1.0, dashes=[0.5,0.5], label='raw stays')\n\n#plt.plot(new_t_segs, new_x_segs, 'ko--', linewidth=3.0, markerfacecolor='w', markersize=4.0, markeredgewidth=1.0, label='adjusted raw stays')\nplt.plot(time_sub, raw_journey_sub, ':', label='raw journey')\nplt.plot(time_sub, noise_journey_sub, '.-', label='noisy journey', alpha=0.5)\nplt.legend();\n#plt.xlim([6.2,6.6]);",
"0.002914221692034853 0.1473667181056486\n"
],
[
"# DONE\ndef get_thresh_duration2(eps, mean):\n \n # TODO: this fails when sub_arr.size = 0\n upper = mean+eps\n lower = mean-eps\n \n def meth(sub_arr, start):\n \n mask = np.where((sub_arr < upper) & (sub_arr > lower))[0] + start\n #print(mask)\n \n return mask.min(), mask.max(0)\n \n return meth",
"_____no_output_____"
],
[
"from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n AutoMinorLocator)",
"_____no_output_____"
],
[
"segs_plot_kwargs = {'linestyle':'--', 'marker':'o', 'color':'k', 'linewidth':4.0, 'markerfacecolor':'w', 'markersize':6.0, 'markeredgewidth':2.0}",
"_____no_output_____"
]
],
[
[
"### Debugging: when there is no thresh. mean",
"_____no_output_____"
]
],
[
[
"from stay_classification.box_method import extend_box, get_thresh_mean\nfrom stay_classification.checks import check_means",
"_____no_output_____"
],
[
"#DONE\ndef bug_get_converged(converged, means, indices, count_thresh, time_diff, time_thresh=0.5):\n \n # Originally, there were a few conditions for convergence -. moved to \"extend_box\"\n '''\n print(\"BGC:\",indices[0],indices[-1],len(indices))\n # If it converged early, get the converged results;\n if converged: & ((len(indices)>count_thresh) | ((time_diff>time_thresh) & (len(indices)>10))):\n index = min(len(indices), count_thresh) \n last_mean = means[-index]\n last_index = indices[-index]\n '''\n # If it converged early, get the converged results;\n if converged:\n last_mean = means[-1]\n last_index = indices[-1]\n else:\n # else, get the boundary value\n last_mean = means[-1]\n last_index = indices[-1] \n \n return last_mean, last_index",
"_____no_output_____"
],
[
"embedded = lambda t0,t1,pair: ((t0 >= pair[0]) & (t0 <= pair[1]) | (t1 >= pair[0]) & (t1 <= pair[1]))",
"_____no_output_____"
],
[
"# DONE\ndef get_time_ind(t_arr, timepoint, time_thresh, direction):\n \n index = np.where((time_sub < (timepoint)) & \\\n (time_sub > (timepoint-2*time_thresh)))\n n = 2\n while index[0].size == 0:\n index = np.where((time_sub < (timepoint)) & \\\n (time_sub > (timepoint + direction*n*time_thresh)))\n n+=1\n \n if direction == 1:\n return index[0].max() \n else: \n return index[0].min() ",
"_____no_output_____"
],
[
"# DONE\ndef bbug_extend_box(t_arr, x_loc, working_index, fixed_index, means, count_thresh = 50):\n\n \n keep_running = (working_index > 1) & (working_index < len(x_loc)-1)\n \n indices = []\n \n if working_index < fixed_index: \n # Go backwards in time\n direction = -1\n else: \n # Go forwards in time\n direction = 1\n \n mean = means[-1]\n converged_mean = mean\n converged_mean_ind0 = working_index\n while keep_running:\n #print(mean, direction)\n # Update and store the working index\n working_index += direction*1\n indices.append(working_index)\n \n # Update and store the mean\n if direction == -1:\n mean = get_thresh_mean(eps,mean)(x_loc[working_index:fixed_index])\n else:\n mean = get_thresh_mean(eps,mean)(x_loc[fixed_index:working_index])\n \n means.append(mean) \n \n if np.isnan(mean):\n #print(mean)\n break\n \n \n # Stopping criteria:\n # if the thresholded mean doesn't change upon getting new samples\n # * if the duration is too long and there are sufficient number of samples\n \n if mean != converged_mean:\n converged_mean = mean\n converged_mean_ind = working_index\n converged_mean_ind0 = working_index\n else:\n converged_mean_ind = working_index\n \n time_diff = abs(t_arr[fixed_index]-t_arr[working_index])\n ctime_diff = abs(t_arr[converged_mean_ind0]-t_arr[converged_mean_ind]) \n if ((ctime_diff>1.0) & (mean == converged_mean)): \n print('cdrop',ctime_diff)\n break \n \n \n # When the mean either converges or stops\n if ((len(indices)>count_thresh) | ((time_diff>0.5) & (len(indices)>5))): \n #print(time_diff,len(indices))\n nr_events = min(len(indices), count_thresh)\n # see also: bug_check_means(means,nr_events,0.25)\n if check_means(means,nr_events):\n print('drop',time_diff)\n break \n \n \n #print(f\"{t_arr[working_index]:.3f} {time_diff:.3f} {ctime_diff:.3f}\", \\\n # len(indices), fixed_index, working_index, converged_mean_ind0, converged_mean_ind, \\\n # f\"\\t{mean:.5f} {x_loc[working_index]:.3f} {mean+eps:.5f}\",)#,[m == m0 for m in means[-count_thresh:]]) \n \n keep_running = (working_index > 1) & (working_index < len(x_loc)-1)\n\n return means, indices, keep_running",
"_____no_output_____"
]
],
[
[
"~~`get_thresh_duration`~~ $\\to$ `get_bounded_indices` in `box_classifier.py` **TODO** check args!\n\n~~`extend_box`~~\n\n~~`get_counts`~~ $\\to$ `get_bounded_indices` in `box_classifier.py` \n**TODO** check args!\n\n~~`get_thresh_mean`~~\n\n~~`get_converged`~~\n\n`get_slope`$\\to$ `get_slope` in `box_classifier.py` \n\nNew:<br/>\n1. $\\checkmark$ ~~`bug_asymm_box_method_modular`~~ $\\to$ `make_box`\n * $\\checkmark$ ~~`get_time_ind`~~\n * $\\checkmark$ ~~`bbug_extend_box`~~\n * $\\checkmark$ ~~`bug_get_converged`~~\n \n2. $\\checkmark$ ~~`bbug_extend_box`~~ $\\to$ `extend_edge`\n * $\\checkmark$ ~~`get_thresh_mean`~~\n * $\\checkmark$ ~~`check_means`~~",
"_____no_output_____"
]
],
[
[
"# DONE\ndef bug_asymm_box_method_modular(t_arr, time_thresh, x_loc, eps, timepoint, count_thresh = 50, verbose=False):\n \n \n # 1. Initialization\n # 1.1. Init and store the start, end points from the timepoint\n if verbose: print(f\"\\t1. {timepoint-time_thresh:.3f} < {timepoint:.3f} < {timepoint+time_thresh:.3f}\") \n start = get_time_ind(t_arr, timepoint, time_thresh, -1)\n end = get_time_ind(t_arr, timepoint, time_thresh, 1) \n\n starts, ends = [], []\n starts.append(start)\n ends.append(end)\n \n # 1.2. Initialize and store the mean for the region\n mean = np.mean(x_loc[start:end])\n means = [mean]\n \n \n # 2. Extend the box in the backwards direction \n # 2.1. Extension phase\n if verbose: print(f\"\\t2. {mean:.4f} {start:4d} {end:4d}\") \n means, indices, keep_running = bbug_extend_box(t_arr, x_loc, start, end, means)\n \n # 2.2. Check if NAN --> TODO: check why this happens! \n if verbose: print(f\"\\t2.1. {mean:.4f} {start:4d} {end:4d}\", keep_running) \n if np.isnan(means[-1]):\n if verbose: print(f\"\\t2.1. \\t\\tDrop {means[-1]:.4f} {starts[-1]:4d}\", end)\n return means[-1], starts[-1], end \n starts += indices\n \n # 2.3. If it converged early, get the converged results; \n if verbose: print(f\"\\t2.2. {means[-1]:.4f} {starts[-1]:4d} {end:4d}\") \n tdiff = t_arr[end]-t_arr[starts[0]]\n mean, start = bug_get_converged(keep_running, means, starts, count_thresh, tdiff)\n \n # 2.4. Additional check if NAN\n if np.isnan(mean):\n if verbose: print(f\"\\t2.3. \\t\\tDrop {means[-1]:.4f} {starts[-1]:4d} {end:4d}\")\n return means[-1], starts[-1], end\n \n \n # 3. Extend the box in the forwards direction \n # 3.1. Extension phase\n if verbose: print(f\"\\t3. {mean:.4f} {start:4d} {end:4d}\", keep_running) \n means, indices, keep_running = bbug_extend_box(t_arr, x_loc, end, start, means)\n \n # 3.2. Check if NAN --> TODO: check why this happens! \n if verbose: print(f\"\\t3.1. {mean:.4f} {start:4d} {end:4d}\", keep_running) \n if np.isnan(means[-1]):\n if verbose: print(f\"\\t3.1. \\t\\tDrop {means[-1]:.4f} {start:4d} {ends[-1]:4d}\")\n return means[-1], start, ends[-1]\n ends += indices \n \n # 3.3. If it converged early, get the converged results\n if verbose: print(f\"\\t3.1. {means[-1]:.4f} {start:4d} {end:4d}\", keep_running) \n tdiff = t_arr[ends[-1]]-t_arr[start]\n mean, end = bug_get_converged(keep_running, means, ends, count_thresh, tdiff)\n\n # 2.4. Additional check if NAN\n if np.isnan(mean):\n if verbose: print(f\"\\n\\t3.3. \\t\\tDrop {means[-1]:.4f} {start:4d} {ends[-1]:4d}\")\n return means[-1], start, ends[-1]\n \n \n # 4\n if verbose: print(f\"\\t4. {mean:.4f} {start:4d} {end:4d}\") \n \n return mean, start, end",
"_____no_output_____"
],
[
"def time_overlap(t0,t1,tt0,tt1):\n \n if ((t0>=tt0)&(t0<tt1)):\n return True\n elif ((t1>=tt0)&(t1<tt1)):\n return True\n elif ((t0 <= tt0) & (tt1 <= t1)):\n return True\n else:\n return False",
"_____no_output_____"
],
[
"def bug_get_slope(eps, mean):\n \n upper = mean+eps\n lower = mean-eps\n \n def meth(t_subarr, x_subarr):\n \n mask = np.where((x_subarr < upper) & (x_subarr > lower))\n \n ub_xdata = t_subarr[mask] - t_subarr[mask].mean()\n ub_ydata = x_subarr[mask] - x_subarr[mask].mean()\n \n return (ub_xdata.T.dot(ub_ydata))/(ub_xdata.T.dot(ub_xdata))\n \n return meth",
"_____no_output_____"
],
[
"def check_true(t_s, t_l, tsegs):\n for t_1, t_2 in zip(tsegs.tolist()[::3],tsegs.tolist()[1::3]):\n if time_overlap(t_s, t_l, t_1, t_2 ): \n return t_1, t_2",
"_____no_output_____"
]
],
[
[
"### Run",
"_____no_output_____"
]
],
[
[
"configs = {\n 'eps':0.25,\n 'time_thresh':5/12,\n 'long_time_thresh':1.0,\n 'slope_thresh':0.50,\n 'count_thresh':50\n}",
"_____no_output_____"
],
[
"eps = configs['eps']\ntime_thresh = configs['time_thresh']\nlong_time_thresh = configs['long_time_thresh'] \nslope_thresh = configs['slope_thresh']\ncount_thresh = configs['count_thresh']\n\n\nmin_t, max_t = 0.1, 23.95\n\n\nfig, ax = plt.subplots(1,1,figsize=(22,10))\n\n# The adjusted raw-stays\nplt.plot(new_t_segs, new_x_segs, **segs_plot_kwargs, label='adjusted raw stays')\nax.plot(time_sub, noise_journey_sub, '.-', color='gray', label='noisy journey', alpha=0.25)\nax.plot(time_sub, raw_journey_sub, ':', color='k', label='raw journey')\n\nt0,t1 = 0,1\nstart_ind, last_ind = t0, t1\n\npairs = []\n\nnnn = 0\n\nfor timepoint in np.arange(min_t,23.95,0.25):\n \n # If the current timepoint is less than the last box-end, skip ahead\n # TODO: this is useful but possibly, without refinement, misses some stays \n # HOWEVER: without it, it doesn't work!\n if (time_sub[start_ind] <= timepoint) & (timepoint <= time_sub[last_ind]):\n #print(\"\\t\\t\\talready processed, skip\") \n continue \n else:\n print(f\"\\nStart at {timepoint:.3f}, dt = {t_diff:.3f}, {t0}, {t1}\") \n \n # Process the time point\n mean, start_ind, last_ind = bug_asymm_box_method_modular(\\\n time_sub,time_thresh,noise_journey_sub,eps,timepoint, 50, True)\n \n # Drop if a NAN was encountered --. failed to find a mean\n if np.isnan(mean):\n print(\"\\t\\t\\tmean = NaN, skip\")\n continue\n \n # If the duration of the stay is too small, skip ahead\n if time_sub[last_ind]-time_sub[start_ind] < time_thresh:\n print(\"\\t\\t\\ttoo short, skip\") \n continue\n \n # If the duration due to the thresholded box is too short, skip ahead\n #print(start_ind,last_ind,mean)\n t0, t1 = get_thresh_duration2(eps, mean)(noise_journey_sub[start_ind:last_ind],start_ind) \n #t0, t1 = get_thresh_duration(eps, mean)(noise_journey_sub[start_ind:last_ind],start_ind) \n print(start_ind,last_ind,t0, t1)\n if time_sub[t1]-time_sub[t0] < time_thresh:\n print(\"\\t\\t\\talso too short, skip\") \n continue \n\n # If the stay is less than 1 hour, check the slope of the segement --> This isn't watertight\n if time_sub[t1]-time_sub[t0] < long_time_thresh: \n xdata = time_sub[t0:t1]\n ydata = noise_journey_sub[t0:t1]\n slope = bug_get_slope(eps, mean)(xdata, ydata)\n print(f\"\\tAt {timepoint:.3f}, slope = {slope:.3f}\")\n if abs(slope) > slope_thresh: \n print(\"\\t\\t\\tslope is too big, skip\")\n continue \n # If the stay is less than 2 hour, check the slope of the segement\n if time_sub[t1]-time_sub[t0] < 2*long_time_thresh: \n xdata = time_sub[t0:t1]\n ydata = noise_journey_sub[t0:t1]\n slope = bug_get_slope(eps, mean)(xdata, ydata)\n print(f\"\\tAgain, at {timepoint:.3f}, slope = {slope:.3f}\")\n if abs(slope) > slope_thresh: \n print(\"\\t\\t\\tAgain, slope is too big, skip\")\n continue \n \n # If the stay is embedded with other stays --> This is tricky!\n if any([embedded(t0,t1, p) for p in pairs] + [embedded(p[0],p[1],[t0,t1]) for p in pairs]):\n print(\"\\t\\t\\tEmbedded, skip\") \n continue\n \n # PLOTTING\n dashing = \"-\"+23*\" -\"\n ddashing = \"=\"+30*\"==\"\n \n t_start = time_sub[t0]\n t_last = time_sub[t1]\n \n '''seg_ind = min(3*nnn+1,len(new_t_segs))\n t_seg_0 = new_t_segs[seg_ind-1]\n t_seg_1 = new_t_segs[seg_ind]'''\n #t_seg_0, t_seg_1 = check_true(t_start, t_last, new_t_segs)\n true_vals = \"\"\n '''if time_overlap(t_start, t_last, t_seg_0, t_seg_1 ):\n true_vals = f'{t_seg_0:2.3f}, {t_seg_1:2.3f}' \n else:\n true_vals = 'Unmatched'\n '''\n true_vals = f\"True: {true_vals};\"\n\n print(f'\\nPLOT: ID #{nnn:3d} {dashing}\\n\\t{timepoint:.3f}', \\\n f'{t0}, {t1}', \\\n true_vals,\\\n f'Pred: {t_start:.3f}, {t_last:.3f}',\\\n f'{mean:.3f}', \\\n f'\\n\\n{ddashing}')\n #print(timepoint,\":, mean, start_ind, last_ind) \n ax.plot([time_sub[start_ind],time_sub[last_ind]], [mean,mean],\\\n '--', color=colors[nnn], \\\n label=f'ID #{nnn},{timepoint:.3f}, {time_sub[start_ind]:.3f}, {time_sub[last_ind]:.3f}')\n \n t_diff = abs(time_sub[t1]-time_sub[t0])\n ax.plot([time_sub[t0],time_sub[t1]], [mean,mean], '--', \\\n dashes=[1,1], linewidth=5, color=colors[nnn], \\\n label=f'ID #{nnn}: {round(t_diff,2)}, sub')\n \n # Add the box\n rect_color = \"gray\" #colors[nnn]\n rect = Rectangle((time_sub[t0], mean-eps), t_diff, 2*eps)\n pc = PatchCollection([rect], \\\n facecolor=rect_color, alpha=0.2, edgecolor=rect_color,linewidth=1)\n ax.add_collection(pc)\n\n #print(f\"End At {timepoint:.3f}, dt = {t_diff:.3f}, {t0}, {t1}\") \n pairs.append([t0,t1])\n start_ind, last_ind = t0, t1\n nnn += 1\n \nplt.xlabel(r'time, $t$ [arb.]')\nplt.ylabel(r'position, $x$ [arb.]')\n\nymin = noise_journey_sub.min()-1*eps\nymax = noise_journey_sub.max()+1*eps\nplt.ylim(ymin, ymax)\n\n\nax.xaxis.set_major_locator(MultipleLocator(1))\n#ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\n\n# For the minor ticks, use no labels; default NullFormatter.\nax.xaxis.set_minor_locator(MultipleLocator(0.5))\n\nplt.xlim(min_t, max_t)\n#plt.xlim(-0.1, 19.1\n#plt.xlim(15.1, 19.1)\n\nplt.title('Rough cut', fontsize=36)\nplt.grid(visible=True);\nplt.legend(bbox_to_anchor=(1.2, 0.5), loc='right', ncol=1);",
"\nStart at 0.100, dt = 0.836, 0, 1\n\t1. -0.317 < 0.100 < 0.517\n\t2. -1.2085 0 3\n\t2.1. -1.2085 0 3 False\n\t2.2. -1.2085 0 3\n\t3. -1.2085 0 3 False\ncdrop 1.0075000000000003\n\t3.1. -1.2085 0 3 True\n\t3.1. -1.2341 0 3 True\n\t4. -1.2341 0 52\n0 52 0 37\n\nPLOT: ID # 0 - - - - - - - - - - - - - - - - - - - - - - - -\n\t0.100 0, 37 True: ; Pred: 0.043, 4.178 -1.234 \n\n=============================================================\n\nStart at 4.350, dt = 4.135, 0, 37\n\t1. 3.933 < 4.350 < 4.767\n\t2. -1.0452 32 40\n\t2.1. -1.0452 32 40 False\n\t2.2. -1.2376 1 40\n\t3. -1.2376 1 40 False\ndrop 5.022222222222222\n\t3.1. -1.2376 1 40 True\n\t3.1. -1.2376 1 40 True\n\t4. -1.2376 1 46\n1 46 1 37\n\t\t\tEmbedded, skip\n\nStart at 5.100, dt = 4.135, 1, 37\n\t1. 4.683 < 5.100 < 5.517\n\t2. 1.5417 40 49\ndrop 1.0872222222222225\n\t2.1. 1.5417 40 49 True\n\t2.2. 1.6229 34 49\n\t3. 1.6229 34 49 True\ncdrop 1.0147222222222219\n\t3.1. 1.6229 34 49 True\n\t3.1. 1.6209 34 49 True\n\t4. 1.6209 34 84\n34 84 41 74\n\nPLOT: ID # 1 - - - - - - - - - - - - - - - - - - - - - - - -\n\t5.100 41, 74 True: ; Pred: 4.400, 9.327 1.621 \n\n=============================================================\n\nStart at 9.350, dt = 4.927, 41, 74\n\t1. 8.933 < 9.350 < 9.767\n\t2. 1.5648 68 74\ncdrop 1.0266666666666668\n\t2.1. 1.5648 68 74 True\n\t2.2. 1.6209 30 74\n\t3. 1.6209 30 74 True\ndrop 6.8469444444444445\n\t3.1. 1.6209 30 74 True\n\t3.1. 1.6209 30 74 True\n\t4. 1.6209 30 80\n30 80 41 74\n\t\t\tEmbedded, skip\n\nStart at 10.350, dt = 4.927, 41, 74\n\t1. 9.933 < 10.350 < 10.767\n\t2. 0.7647 75 80\ndrop 1.4652777777777768\n\t2.1. 0.7647 75 80 True\n\t2.2. 0.7647 69 80\n\t3. 0.7647 69 80 True\ncdrop 1.0888888888888886\n\t3.1. 0.7647 69 80 True\n\t3.1. 0.6494 69 80 True\n\t4. 0.6494 69 107\n69 107 75 89\n\tAgain, at 10.350, slope = -0.236\n\nPLOT: ID # 2 - - - - - - - - - - - - - - - - - - - - - - - -\n\t10.350 75, 89 True: ; Pred: 9.751, 11.036 0.649 \n\n=============================================================\n\nStart at 11.100, dt = 1.286, 75, 89\n\t1. 10.683 < 11.100 < 11.517\n\t2. 0.5887 81 89\ncdrop 1.3486111111111114\n\t2.1. 0.5887 81 89 True\n\t2.2. 0.6624 67 89\n\t3. 0.6624 67 89 True\ndrop 3.1963888888888885\n\t3.1. 0.6624 67 89 True\n\t3.1. 0.6494 67 89 True\n\t4. 0.6494 67 95\n67 95 75 89\n\tAgain, at 11.100, slope = -0.236\n\t\t\tEmbedded, skip\n\nStart at 11.600, dt = 1.286, 75, 89\n\t1. 11.183 < 11.600 < 12.017\n\t2. 0.4127 85 95\ncdrop 1.237222222222222\n\t2.1. 0.4127 85 95 True\n\t2.2. 0.4414 74 95\n\t3. 0.4414 74 95 True\ncdrop 1.012777777777778\n\t3.1. 0.4414 74 95 True\n\t3.1. 0.3153 74 95 True\n\t4. 0.3153 74 117\n74 117 84 102\n\tAgain, at 11.600, slope = -0.424\n\t\t\tEmbedded, skip\n\nStart at 13.350, dt = 1.286, 84, 102\n\t1. 12.933 < 13.350 < 13.767\n\t2. -0.2422 113 119\ncdrop 1.006388888888889\n\t2.1. -0.2422 113 119 True\n\t2.2. 0.0885 80 119\n\t3. 0.0885 80 119 True\ndrop 3.4399999999999995\n\t3.1. 0.0885 80 119 True\n\t3.1. 0.0885 80 119 True\n\t4. 0.0885 80 125\n80 125 90 114\n\tAgain, at 13.350, slope = -0.320\n\nPLOT: ID # 3 - - - - - - - - - - - - - - - - - - - - - - - -\n\t13.350 90, 114 True: ; Pred: 11.227, 12.556 0.088 \n\n=============================================================\n\nStart at 13.600, dt = 1.329, 90, 114\n\t1. 13.183 < 13.600 < 14.017\n\t2. -0.4036 115 124\ncdrop 1.1166666666666671\n\t2.1. -0.4036 115 124 True\n\t2.2. -0.3788 93 124\n\t3. -0.3788 93 124 True\ncdrop 1.1269444444444439\n\t3.1. -0.3788 93 124 True\n\t3.1. -0.5621 93 124 True\n\t4. -0.5621 93 192\n93 192 117 173\n\nPLOT: ID # 4 - - - - - - - - - - - - - - - - - - - - - - - -\n\t13.600 117, 173 True: ; Pred: 13.178, 17.859 -0.562 \n\n=============================================================\n\nStart at 18.100, dt = 4.681, 117, 173\n\t1. 17.683 < 18.100 < 18.517\n\t2. -0.4966 167 175\ncdrop 1.012777777777778\n\t2.1. -0.4966 167 175 True\n\t2.2. -0.5621 104 175\n\t3. -0.5621 104 175 True\ndrop 6.517777777777777\n\t3.1. -0.5621 104 175 True\n\t3.1. -0.5621 104 175 True\n\t4. -0.5621 104 181\n104 181 117 173\n\t\t\tEmbedded, skip\n\nStart at 18.850, dt = 4.681, 117, 173\n\t1. 18.433 < 18.850 < 19.267\n\t2. 0.6435 175 188\ncdrop 1.1191666666666684\n\t2.1. 0.6435 175 188 True\n\t2.2. 0.7657 161 188\n\t3. 0.7657 161 188 True\ndrop 2.56527777777778\n\t3.1. 0.7657 161 188 True\n\t3.1. 0.7664 161 188 True\n\t4. 0.7664 161 194\n161 194 178 188\n\t\t\talso too short, skip\n\nStart at 19.350, dt = 4.681, 178, 188\n\t1. 18.933 < 19.350 < 19.767\n\t2. 0.8896 178 196\ndrop 1.4480555555555554\n\t2.1. 0.8896 178 196 True\n\t2.2. 0.8934 172 196\n\t3. 0.8934 172 196 True\ncdrop 1.0919444444444473\n\t3.1. 0.8934 172 196 True\n\t3.1. 0.9723 172 196 True\n\t4. 0.9723 172 218\n172 218 181 201\n\tAgain, at 19.350, slope = 0.291\n\nPLOT: ID # 5 - - - - - - - - - - - - - - - - - - - - - - - -\n\t19.350 181, 201 True: ; Pred: 18.683, 19.936 0.972 \n\n=============================================================\n\nStart at 20.100, dt = 1.253, 181, 201\n\t1. 19.683 < 20.100 < 20.517\n\t2. 1.1005 194 201\ncdrop 1.1600000000000001\n\t2.1. 1.1005 194 201 True\n\t2.2. 0.9807 169 201\n\t3. 0.9807 169 201 True\ndrop 3.2108333333333334\n\t3.1. 0.9807 169 201 True\n\t3.1. 0.9723 169 201 True\n\t4. 0.9723 169 207\n169 207 181 201\n\tAgain, at 20.100, slope = 0.291\n\t\t\tEmbedded, skip\n\nStart at 20.850, dt = 1.253, 181, 201\n\t1. 20.433 < 20.850 < 21.267\n\t2. -0.5412 202 208\n\t2.1. -0.5412 202 208 True\n\t2.1. \t\tDrop nan 202 208\n\t\t\tmean = NaN, skip\n\nStart at 21.100, dt = 1.253, 181, 201\n\t1. 20.683 < 21.100 < 21.517\n\t2. -1.5960 206 215\ndrop 1.2025000000000006\n\t2.1. -1.5960 206 215 True\n\t2.2. -1.6649 200 215\n\t3. -1.6649 200 215 True\ncdrop 1.0300000000000011\n\t3.1. -1.6649 200 215 True\n\t3.1. -1.6546 200 215 True\n\t4. -1.6546 200 242\n200 242 207 229\n\tAgain, at 21.100, slope = -0.037\n\nPLOT: ID # 6 - - - - - - - - - - - - - - - - - - - - - - - -\n\t21.100 207, 229 True: ; Pred: 20.672, 22.203 -1.655 \n\n=============================================================\n\nStart at 22.350, dt = 1.531, 207, 229\n\t1. 21.933 < 22.350 < 22.767\n\t2. -1.6164 221 231\ncdrop 1.1572222222222237\n\t2.1. -1.6164 221 231 True\n\t2.2. -1.6546 197 231\n\t3. -1.6546 197 231 True\ndrop 3.163888888888888\n\t3.1. -1.6546 197 231 True\n\t3.1. -1.6546 197 231 True\n\t4. -1.6546 197 237\n197 237 207 229\n\tAgain, at 22.350, slope = -0.037\n\t\t\tEmbedded, skip\n\nStart at 22.850, dt = 1.531, 207, 229\n\t1. 22.433 < 22.850 < 23.267\n\t2. -0.9842 225 238\ncdrop 1.0744444444444454\n\t2.1. -0.9842 225 238 True\n\t2.2. -1.2426 196 238\n\t3. -1.2426 196 238 True\ndrop 4.255555555555556\n\t3.1. -1.2426 196 238 True\n\t3.1. -1.2426 196 238 True\n\t4. -1.2426 196 244\n196 244 206 232\n\tAgain, at 22.850, slope = -0.035\n\t\t\tEmbedded, skip\n\nStart at 23.600, dt = 1.531, 206, 232\n\t1. 23.183 < 23.600 < 24.017\n\t2. 1.3048 239 244\ndrop 1.0227777777777796\n\t2.1. 1.3048 239 244 True\n\t2.2. 1.3048 233 244\n\t3. 1.3048 233 244 True\n\t3.1. 1.3048 233 244 False\n\t3.1. 1.2653 233 244 False\n\t4. 1.2653 233 250\n233 250 239 249\n\tAt 23.600, slope = -0.182\n\tAgain, at 23.600, slope = -0.182\n\nPLOT: ID # 7 - - - - - - - - - - - - - - - - - - - - - - - -\n\t23.600 239, 249 True: ; Pred: 23.000, 23.836 1.265 \n\n=============================================================\n\nStart at 23.850, dt = 0.836, 239, 249\n\t1. 23.433 < 23.850 < 24.267\n\t2. 1.2552 240 249\ndrop 1.2908333333333353\n\t2.1. 1.2552 240 249 True\n\t2.2. 1.2684 234 249\n\t3. 1.2684 234 249 True\n\t3.1. 1.2684 234 249 False\n\t3.1. 1.2653 234 249 False\n\t4. 1.2653 234 250\n234 250 239 249\n\tAt 23.850, slope = -0.182\n\tAgain, at 23.850, slope = -0.182\n\t\t\tEmbedded, skip\n"
]
],
[
[
"**Note** \n* a box will extend too _far_ when\n * if the duration of constant mean is too long, \n * if the number of events for a constant mean is too large\n * **!** need to consider numbers of samples because the samples can increase but time-delta not\n* a box will cut too _early_ when\n * if the number of events for a temporal constant mean is too large\n",
"_____no_output_____"
],
[
"### Run2",
"_____no_output_____"
]
],
[
[
"min_t, max_t = 0.1, 23.95\n\nfig, ax = plt.subplots(1,1,figsize=(22,10))\n\n\n# The adjusted raw-stays\nplt.plot(new_t_segs, new_x_segs, **segs_plot_kwargs, label='adjusted raw stays')\nax.plot(time_sub, noise_journey_sub, '.-', color='gray', label='noisy journey', alpha=0.25)\nax.plot(time_sub, raw_journey_sub, ':', color='k', label='raw journey')\n\nt0,t1 = 0,1\nstart_ind, last_ind = t0, t1\n\npairs = []\n\nnnn = 0\n\ntimepoint = min_t\n\nwhile timepoint < max_t:\n \n # If the current timepoint is less than the last box-end, skip ahead\n # TODO: this is useful but possibly, without refinement, misses some stays \n # HOWEVER: without it, it doesn't work!\n if (time_sub[start_ind] <= timepoint) & (timepoint <= time_sub[last_ind]):\n timepoint = timepoint+time_thresh\n \n print(f\"\\t\\t\\t {timepoint:.3f} already processed, skip\") \n continue \n else:\n print(f\"\\nStart at {timepoint:.3f}, dt = {t_diff:.3f}, {t0}, {t1}\") \n \n # Process the time point\n mean, start_ind, last_ind = bug_asymm_box_method_modular(\\\n time_sub,time_thresh,noise_journey_sub,eps,timepoint, 50, True)\n \n # Drop if a NAN was encountered --. failed to find a mean\n if np.isnan(mean):\n print(\"\\t\\t\\tmean = NaN, skip\")\n timepoint = time_sub[last_ind]+time_thresh\n continue\n \n # If the duration of the stay is too small, skip ahead\n if time_sub[last_ind]-time_sub[start_ind] < time_thresh:\n print(\"\\t\\t\\ttoo short, skip\") \n timepoint = time_sub[last_ind]+time_thresh\n continue\n \n # If the duration due to the thresholded box is too short, skip ahead\n #print(start_ind,last_ind,mean)\n t0, t1 = get_thresh_duration2(eps, mean)(noise_journey_sub[start_ind:last_ind],start_ind) \n #t0, t1 = get_thresh_duration(eps, mean)(noise_journey_sub[start_ind:last_ind],start_ind) \n print(start_ind,last_ind,t0, t1)\n if time_sub[t1]-time_sub[t0] < time_thresh:\n print(\"\\t\\t\\talso too short, skip\") \n timepoint = time_sub[t1]+time_thresh \n continue \n\n # If the stay is less than 1 hour, check the slope of the segement --> This isn't watertight\n if time_sub[t1]-time_sub[t0] < long_time_thresh: \n xdata = time_sub[t0:t1]\n ydata = noise_journey_sub[t0:t1]\n slope = bug_get_slope(eps, mean)(xdata, ydata)\n print(f\"\\tAt {timepoint:.3f}, slope = {slope:.3f}\")\n if abs(slope) > slope_thresh: \n print(\"\\t\\t\\tslope is too big, skip\")\n timepoint = time_sub[t1]+time_thresh \n continue \n # If the stay is less than 2 hour, check the slope of the segement\n if time_sub[t1]-time_sub[t0] < 2*long_time_thresh: \n xdata = time_sub[t0:t1]\n ydata = noise_journey_sub[t0:t1]\n slope = bug_get_slope(eps, mean)(xdata, ydata)\n print(f\"\\tAgain, at {timepoint:.3f}, slope = {slope:.3f}\")\n if abs(slope) > slope_thresh: \n print(\"\\t\\t\\tAgain, slope is too big, skip\")\n timepoint = time_sub[t1]+time_thresh \n continue \n \n # If the stay is embedded with other stays --> This is tricky!\n if any([embedded(t0,t1, p) for p in pairs] + [embedded(p[0],p[1],[t0,t1]) for p in pairs]):\n print(\"\\t\\t\\tEmbedded, skip\") \n timepoint = time_sub[t1]+time_thresh \n continue\n \n # PLOTTING\n dashing = \"-\"+23*\" -\"\n ddashing = \"=\"+30*\"==\"\n \n t_start = time_sub[t0]\n t_last = time_sub[t1]\n \n '''seg_ind = min(3*nnn+1,len(new_t_segs))\n t_seg_0 = new_t_segs[seg_ind-1]\n t_seg_1 = new_t_segs[seg_ind]'''\n t_seg_0, t_seg_1 = check_true(t_start, t_last, new_t_segs)\n true_vals = \"\"\n if time_overlap(t_start, t_last, t_seg_0, t_seg_1 ):\n true_vals = f'{t_seg_0:2.3f}, {t_seg_1:2.3f}' \n else:\n true_vals = 'Unmatched'\n true_vals = f\"True: {true_vals};\"\n\n print(f'\\nPLOT: ID #{nnn:3d} {dashing}\\n\\t{timepoint:.3f}', \\\n f'{t0}, {t1}', \\\n true_vals,\\\n f'Pred: {t_start:.3f}, {t_last:.3f}',\\\n f'{mean:.3f}', \\\n f'\\n\\n{ddashing}')\n #print(timepoint,\":, mean, start_ind, last_ind) \n ax.plot([time_sub[start_ind],time_sub[last_ind]], [mean,mean],\\\n '--', color=colors[nnn], \\\n label=f'ID #{nnn},{timepoint:.3f}, {time_sub[start_ind]:.3f}, {time_sub[last_ind]:.3f}')\n \n t_diff = abs(time_sub[t1]-time_sub[t0])\n ax.plot([time_sub[t0],time_sub[t1]], [mean,mean], '--', \\\n dashes=[1,1], linewidth=5, color=colors[nnn], \\\n label=f'ID #{nnn}: {round(t_diff,2)}, sub')\n \n # Add the box\n rect_color = \"gray\" #colors[nnn]\n rect = Rectangle((time_sub[t0], mean-eps), t_diff, 2*eps)\n pc = PatchCollection([rect], \\\n facecolor=rect_color, alpha=0.2, edgecolor=rect_color,linewidth=1)\n ax.add_collection(pc)\n\n #print(f\"End At {timepoint:.3f}, dt = {t_diff:.3f}, {t0}, {t1}\") \n pairs.append([t0,t1])\n start_ind, last_ind = t0, t1\n \n timepoint = time_sub[t1]+time_thresh\n nnn += 1\n \nplt.xlabel(r'time, $t$ [arb.]')\nplt.ylabel(r'position, $x$ [arb.]')\n\nymin = noise_journey_sub.min()-1*eps\nymax = noise_journey_sub.max()+1*eps\nplt.ylim(ymin, ymax)\n\n\nax.xaxis.set_major_locator(MultipleLocator(1))\n#ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\n\n# For the minor ticks, use no labels; default NullFormatter.\nax.xaxis.set_minor_locator(MultipleLocator(0.5))\n\nplt.xlim(min_t, max_t)\n#plt.xlim(-0.1, 19.1)\n#plt.xlim(15.1, 19.1)\n\nplt.title('Rough cut', fontsize=36)\nplt.grid(visible=True);\nplt.legend(bbox_to_anchor=(1.2, 0.5), loc='right', ncol=1);",
"\nStart at 0.100, dt = 4.927, 0, 1\n\t1. -0.317 < 0.100 < 0.517\n\t2. -1.2085 0 3\n\t2.1. -1.2085 0 3 False\n\t2.2. -1.2085 0 3\n\t3. -1.2085 0 3 False\ncdrop 1.0075000000000003\n\t3.1. -1.2085 0 3 True\n\t3.1. -1.2341 0 3 True\n\t4. -1.2341 0 52\n0 52 0 37\n\nPLOT: ID # 0 - - - - - - - - - - - - - - - - - - - - - - - -\n\t0.100 0, 37 True: 0.043, 4.178; Pred: 0.043, 4.178 -1.234 \n\n=============================================================\n\nStart at 4.594, dt = 4.135, 0, 37\n\t1. 4.178 < 4.594 < 5.011\n\t2. -0.5432 33 42\ndrop 1.4972222222222218\n\t2.1. -0.5432 33 42 True\n\t2.2. -0.3257 27 42\n\t3. -0.3257 27 42 True\ndrop 2.1422222222222222\n\t3.1. -0.3257 27 42 True\n\t3.1. -0.3257 27 42 True\n\t4. -0.3257 27 48\n27 48 38 39\n\t\t\talso too short, skip\n\t\t\t 5.097 already processed, skip\n\nStart at 5.097, dt = 4.135, 38, 39\n\t1. 4.680 < 5.097 < 5.513\n\t2. 1.5417 40 49\ndrop 1.0872222222222225\n\t2.1. 1.5417 40 49 True\n\t2.2. 1.6229 34 49\n\t3. 1.6229 34 49 True\ncdrop 1.0147222222222219\n\t3.1. 1.6229 34 49 True\n\t3.1. 1.6114 34 49 True\n\t4. 1.6114 34 84\n34 84 41 74\n\nPLOT: ID # 1 - - - - - - - - - - - - - - - - - - - - - - - -\n\t5.097 41, 74 True: 4.400, 9.327; Pred: 4.400, 9.327 1.611 \n\n=============================================================\n\nStart at 9.744, dt = 4.927, 41, 74\n\t1. 9.327 < 9.744 < 10.161\n\t2. 1.5395 70 74\ncdrop 1.0266666666666668\n\t2.1. 1.5395 70 74 True\n\t2.2. 1.6110 30 74\n\t3. 1.6110 30 74 True\ndrop 6.8469444444444445\n\t3.1. 1.6110 30 74 True\n\t3.1. 1.6114 30 74 True\n\t4. 1.6114 30 80\n30 80 41 74\n\t\t\tEmbedded, skip\n\t\t\t 10.161 already processed, skip\n\t\t\t 10.577 already processed, skip\n\nStart at 10.577, dt = 4.927, 41, 74\n\t1. 10.161 < 10.577 < 10.994\n\t2. 0.7495 75 83\ndrop 1.809444444444443\n\t2.1. 0.7495 75 83 True\n\t2.2. 0.7495 69 83\n\t3. 0.7495 69 83 True\ncdrop 1.1449999999999996\n\t3.1. 0.7495 69 83 True\n\t3.1. 0.2544 69 83 True\n\t4. 0.2544 69 130\n69 130 75 115\n\nPLOT: ID # 2 - - - - - - - - - - - - - - - - - - - - - - - -\n\t10.577 75, 115 True: 9.751, 10.136; Pred: 9.751, 12.940 0.254 \n\n=============================================================\n\nStart at 13.357, dt = 3.189, 75, 115\n\t1. 12.940 < 13.357 < 13.773\n\t2. -0.2422 113 119\ncdrop 1.0363888888888884\n\t2.1. -0.2422 113 119 True\n\t2.2. 0.1692 74 119\n\t3. 0.1692 74 119 True\ndrop 4.333055555555555\n\t3.1. 0.1692 74 119 True\n\t3.1. 0.1692 74 119 True\n\t4. 0.1692 74 125\n74 125 83 116\n\t\t\tEmbedded, skip\n\t\t\t 13.990 already processed, skip\n\nStart at 13.990, dt = 3.189, 83, 116\n\t1. 13.573 < 13.990 < 14.407\n\t2. -0.4470 116 127\ncdrop 1.006388888888889\n\t2.1. -0.4470 116 127 True\n\t2.2. -0.0562 80 127\n\t3. -0.0562 80 127 True\ncdrop 1.117222222222221\n\t3.1. -0.0562 80 127 True\n\t3.1. -0.4627 80 127 True\n\t4. -0.4627 80 197\n80 197 103 175\n\t\t\tEmbedded, skip\n\t\t\t 18.881 already processed, skip\n\t\t\t 19.298 already processed, skip\n\t\t\t 19.714 already processed, skip\n\nStart at 19.714, dt = 3.189, 103, 175\n\t1. 19.298 < 19.714 < 20.131\n\t2. 1.1069 192 198\ncdrop 1.006388888888889\n\t2.1. 1.1069 192 198 True\n\t2.2. 0.8870 169 198\n\t3. 0.8870 169 198 True\ncdrop 1.0919444444444473\n\t3.1. 0.8870 169 198 True\n\t3.1. 0.9106 169 198 True\n\t4. 0.9106 169 218\n169 218 177 201\n\tAgain, at 19.714, slope = 0.404\n\nPLOT: ID # 3 - - - - - - - - - - - - - - - - - - - - - - - -\n\t19.714 177, 201 True: 19.121, 19.720; Pred: 18.468, 19.936 0.911 \n\n=============================================================\n\nStart at 20.352, dt = 1.468, 177, 201\n\t1. 19.936 < 20.352 < 20.769\n\t2. 0.5529 198 205\ncdrop 1.006388888888889\n\t2.1. 0.5529 198 205 True\n\t2.2. 0.9106 169 205\n\t3. 0.9106 169 205 True\ndrop 3.545277777777777\n\t3.1. 0.9106 169 205 True\n\t3.1. 0.9106 169 205 True\n\t4. 0.9106 169 211\n169 211 177 201\n\tAgain, at 20.352, slope = 0.404\n\t\t\tEmbedded, skip\n\t\t\t 20.769 already processed, skip\n\t\t\t 21.186 already processed, skip\n\nStart at 21.186, dt = 1.468, 177, 201\n\t1. 20.769 < 21.186 < 21.602\n\t2. -1.6237 206 217\ndrop 1.2847222222222214\n\t2.1. -1.6237 206 217 True\n\t2.2. -1.6816 200 217\n\t3. -1.6816 200 217 True\ncdrop 1.0300000000000011\n\t3.1. -1.6816 200 217 True\n\t3.1. -1.6753 200 217 True\n\t4. -1.6753 200 242\n200 242 207 229\n\tAgain, at 21.186, slope = 0.009\n\nPLOT: ID # 4 - - - - - - - - - - - - - - - - - - - - - - - -\n\t21.186 207, 229 True: 20.672, 22.041; Pred: 20.672, 22.203 -1.675 \n\n=============================================================\n\nStart at 22.619, dt = 1.531, 207, 229\n\t1. 22.203 < 22.619 < 23.036\n\t2. -1.2767 224 235\ncdrop 1.1572222222222237\n\t2.1. -1.2767 224 235 True\n\t2.2. -1.6129 197 235\n\t3. -1.6129 197 235 True\ndrop 3.793333333333333\n\t3.1. -1.6129 197 235 True\n\t3.1. -1.6129 197 235 True\n\t4. -1.6129 197 241\n197 241 207 232\n\tAgain, at 22.619, slope = 0.172\n\t\t\tEmbedded, skip\n\t\t\t 23.195 already processed, skip\n\t\t\t 23.611 already processed, skip\n\nStart at 23.611, dt = 1.531, 207, 232\n\t1. 23.195 < 23.611 < 24.028\n\t2. 1.3048 239 244\ndrop 1.0227777777777796\n\t2.1. 1.3048 239 244 True\n\t2.2. 1.3048 233 244\n\t3. 1.3048 233 244 True\n\t3.1. 1.3048 233 244 False\n\t3.1. 1.2653 233 244 False\n\t4. 1.2653 233 250\n233 250 239 249\n\tAt 23.611, slope = -0.182\n\tAgain, at 23.611, slope = -0.182\n\nPLOT: ID # 5 - - - - - - - - - - - - - - - - - - - - - - - -\n\t23.611 239, 249 True: 23.184, 23.942; Pred: 23.000, 23.836 1.265 \n\n=============================================================\n"
],
[
"timepoint, timepoint-time_thresh",
"_____no_output_____"
],
[
"start = np.where((time_sub < (timepoint)) & \\\n (time_sub > (timepoint-1*time_thresh)))",
"_____no_output_____"
],
[
"start[0].size",
"_____no_output_____"
],
[
"get_time_ind(time_sub, timepoint, time_thresh, 1)",
"_____no_output_____"
],
[
"time_sub[70:80]",
"_____no_output_____"
],
[
"end = np.where((time_sub < (timepoint+time_thresh)) & \\\n (time_sub > (timepoint)))[0].max() \nprint(start,end)",
"_____no_output_____"
]
],
[
[
"### Slope testing",
"_____no_output_____"
]
],
[
[
"slope = bug_get_slope(0.25, 1.2652784536739390)(time_sub[239:249], noise_journey_sub[239:249])",
"_____no_output_____"
],
[
"get_slope(time_sub[239:249], noise_journey_sub[239:249])",
"_____no_output_____"
],
[
"aaa,bbb = 181,201\nmeano = 0.9723058514956978",
"_____no_output_____"
],
[
"slope = bug_get_slope(0.25, meano)(time_sub[aaa:bbb], noise_journey_sub[aaa:bbb])\n\nplt.plot(time_sub[aaa:bbb], noise_journey_sub[aaa:bbb], 'C0o-')\nplt.plot(time_sub[aaa:bbb], slope*(time_sub[aaa:bbb]-time_sub[aaa:bbb].mean())+noise_journey_sub[aaa:bbb].mean(), 'C1--')\nplt.plot([time_sub[aaa],time_sub[bbb]], [meano,meano], 'C2:')",
"_____no_output_____"
]
],
[
[
"### Test",
"_____no_output_____"
]
],
[
[
"# DONE\ndef bug_extend_box(t_arr, x_loc, working_index, fixed_index, means, count_thresh = 50):\n\n keep_running = (working_index > 1) & (working_index < len(x_loc)-1)\n \n indices = []\n \n if working_index < fixed_index: \n # Go backwards in time\n direction = -1\n else: \n # Go forwards in time\n direction = 1\n \n mean = means[-1]\n while keep_running:\n #print(mean, direction)\n # Update and store the working index\n working_index += direction*1\n indices.append(working_index)\n \n # Update and store the mean\n if direction == -1:\n mean = get_thresh_mean(eps,mean)(x_loc[working_index:fixed_index])\n else:\n mean = get_thresh_mean(eps,mean)(x_loc[fixed_index:working_index])\n \n means.append(mean) \n \n if np.isnan(mean):\n #print(mean)\n break\n \n time_diff = abs(t_arr[fixed_index]-t_arr[working_index])\n # When the mean either converges or stops\n if ((len(indices)>count_thresh) | ((time_diff>0.5) & (len(indices)>5))): \n #print(time_diff,len(indices))\n nr_events = min(len(indices), count_thresh)\n if check_means(means,nr_events):\n #print('drop',time_diff)\n break \n \n keep_running = (working_index > 1) & (working_index < len(x_loc)-1)\n \n return means, indices, keep_running",
"_____no_output_____"
],
[
"# DONE\ndef bug_check_means(means,nr_samples,eps):\n m0 = means[-nr_samples]\n #TODO: or means could be less than 10% of eps\n #return all([m == m0 for m in means[-count_thresh:]])\n return all([abs(m - m0)<=eps/10 for m in means[-nr_samples:]])",
"_____no_output_____"
],
[
"ms, inds, flag = bbug_extend_box(time_sub, noise_journey_sub, 193, 177, [0.8226433365921534], 20)",
"19.305 0.838 0.085 1 177 194 \t0.82264 1.113 1.07264\n19.305 0.838 0.085 2 177 195 \t0.82264 1.110 1.07264\n19.307 0.840 0.087 3 177 196 \t0.82264 1.085 1.07264\n19.515 1.047 0.294 4 177 197 \t0.82264 1.060 1.07264\n19.694 1.226 0.000 5 177 198 \t0.83846 1.113 1.08846\n19.720 1.253 0.000 6 177 199 \t0.87253 1.148 1.12253\n19.869 1.401 0.000 7 177 200 \t0.91241 1.075 1.16241\n19.936 1.468 0.000 8 177 201 \t0.98074 0.804 1.23074\n20.163 1.695 0.000 9 177 202 \t0.97231 -0.195 1.22231\n20.163 1.695 0.000 10 177 203 \t0.97231 0.010 1.22231\n20.163 1.695 0.000 11 177 204 \t0.97231 -0.083 1.22231\n\t\t\t\tvalid 2:11\n20.163 1.695 0.000 12 177 205 \t0.97231 -0.208 1.22231\n\t\t\t\tvalid 2:12\n20.382 1.914 0.219 13 177 206 \t0.97231 -1.045 1.22231\n\t\t\t\tvalid 2:13\n20.672 2.204 0.509 14 177 207 \t0.97231 -1.726 1.22231\n\t\t\t\tvalid 2:14\n20.677 2.209 0.514 15 177 208 \t0.97231 -1.838 1.22231\n\t\t\t\tvalid 2:15\n20.896 2.428 0.733 16 177 209 \t0.97231 -1.574 1.22231\n\t\t\t\tvalid 2:16\n20.984 2.516 0.821 17 177 210 \t0.97231 -1.725 1.22231\ncdrop 0.8208333333333329\n"
],
[
"no_arr = noise_journey_sub[177:205]\nti_arr = time_sub[177:205]\nbug_get_thresh_mean(eps,0.9807449844948974)(no_arr)",
"0.7307449844948974 1.2307449844948974\n(array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24]),)\n"
],
[
"get_thresh_mean(eps,0.9807449844948974)(no_arr)",
"_____no_output_____"
],
[
"indl = [ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n 21, 22, 23, 24]\nti_arr[np.array(indl)], \\\nno_arr[np.array(indl)]",
"_____no_output_____"
],
[
"# DONE\ndef bug_get_thresh_mean(eps, mean):\n \n upper = mean+eps\n lower = mean-eps\n print(lower,upper)\n def meth(sub_arr):\n \n mask = np.where((sub_arr < upper) & (sub_arr > lower))\n print(mask)\n return np.mean(sub_arr[mask])\n \n return meth",
"_____no_output_____"
],
[
"ms, inds",
"_____no_output_____"
],
[
"def func(in_):\n print(in_)\n return in_, out=False",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba56176e2e8a579eacf3466ea5740d36ea9e426
| 11,656 |
ipynb
|
Jupyter Notebook
|
text_cluster/text_cluster.ipynb
|
v-smwang/AI-NLP-Tutorial
|
3dbfdc7e19a025e00febab97f4948da8a3710f34
|
[
"Apache-2.0"
] | null | null | null |
text_cluster/text_cluster.ipynb
|
v-smwang/AI-NLP-Tutorial
|
3dbfdc7e19a025e00febab97f4948da8a3710f34
|
[
"Apache-2.0"
] | null | null | null |
text_cluster/text_cluster.ipynb
|
v-smwang/AI-NLP-Tutorial
|
3dbfdc7e19a025e00febab97f4948da8a3710f34
|
[
"Apache-2.0"
] | null | null | null | 33.302857 | 291 | 0.528312 |
[
[
[
"## 目录\n- [10. 文本聚类](#10-文本聚类)\n- [10.1 概述](#101-概述)\n- [10.2 文档的特征提取](#102-文档的特征提取)\n- [10.3 k均值算法](#103-k均值算法)\n- [10.4 重复二分聚类算法](#104-重复二分聚类算法)\n- [10.5 标准化评测](#105-标准化评测)\n\n## 10. 文本聚类\n\n正所谓物以类聚,人以群分。人们在获取数据时需要整理,将相似的数据归档到一起,自动发现大量样本之间的相似性,这种根据相似性归档的任务称为聚类。\n\n\n\n### 10.1 概述\n\n1. **聚类**\n\n **聚类**(cluster analysis )指的是将给定对象的集合划分为不同子集的过程,目标是使得每个子集内部的元素尽量相似,不同子集间的元素尽量不相似。这些子集又被称为**簇**(cluster),一般没有交集。\n\n \n\n 一般将聚类时簇的数量视作由使用者指定的超参数,虽然存在许多自动判断的算法,但它们往往需要人工指定其他超参数。\n\n 根据聚类结果的结构,聚类算法也可以分为**划分式**(partitional )和**层次化**(hierarchieal两种。划分聚类的结果是一系列不相交的子集,而层次聚类的结果是一棵树, 叶子节点是元素,父节点是簇。本章主要介绍划分聚类。\n\n \n\n2. **文本聚类**\n\n **文本聚类**指的是对文档进行聚类分析,被广泛用于文本挖掘和信息检索领域。\n\n 文本聚类的基本流程分为特征提取和向量聚类两步, 如果能将文档表示为向量,就可以对其应用聚类算法。这种表示过程称为**特征提取**,而一旦将文档表示为向量,剩下的算法就与文档无关了。这种抽象思维无论是从软件工程的角度,还是从数学应用的角度都十分简洁有效。\n\n\n\n### 10.2 文档的特征提取\n\n1. **词袋模型**\n\n **词袋**(bag-of-words )是信息检索与自然语言处理中最常用的文档表示模型,它将文档想象为一个装有词语的袋子, 通过袋子中每种词语的计数等统计量将文档表示为向量。比如下面的例子:\n\n ```\n 人 吃 鱼。\n 美味 好 吃!\n ```\n\n 统计词频后如下:\n\n ```\n 人=1\n 吃=2\n 鱼=1\n 美味=1\n 好=1\n ```\n\n 文档经过该词袋模型得到的向量表示为[1,2,1,1,1],这 5 个维度分别表示这 5 种词语的词频。\n\n 一般选取训练集文档的所有词语构成一个词表,词表之外的词语称为 oov,不予考虑。一旦词表固定下来,假设大小为 N。则任何一个文档都可以通过这种方法转换为一个N维向量。词袋模型不考虑词序,也正因为这个原因,词袋模型损失了词序中蕴含的语义,比如,对于词袋模型来讲,“人吃鱼”和“鱼吃人”是一样的,这就不对了。\n\n <font color=\"red\">不过目前工业界已经发展出很好的词向量表示方法了: word2vec/bert 模型等。</font>\n\n \n\n2. **词袋中的统计指标**\n\n 词袋模型并非只是选取词频作为统计指标,而是存在许多选项。常见的统计指标如下:\n\n - 布尔词频: 词频非零的话截取为1,否则为0,适合长度较短的数据集\n - TF-IDF: 适合主题较少的数据集\n - 词向量: 如果词语本身也是某种向量的话,则可以将所有词语的词向量求和作为文档向量。适合处理 OOV 问题严重的数据集。\n - 词频向量: 适合主题较多的数据集\n\n 定义由 n 个文档组成的集合为 S,定义其中第 i 个文档 di 的特征向量为 di,其公式如下:\n \n \n \n 其中 tj表示词表中第 j 种单词,m 为词表大小, TF(tj, di) 表示单词 tj 在文档 di 中的出现次数。为了处理长度不同的文档,通常将文档向量处理为单位向量,即缩放向量使得 ||d||=1。\n\n\n\n### 10.3 k均值算法\n\n一种简单实用的聚类算法是k均值算法(k-means),由Stuart Lloyd于1957年提出。该算法虽然无法保证一定能够得到最优聚类结果,但实践效果非常好。基于k均值算法衍生出许多改进算法,先介绍 k均值算法,然后推导它的一个变种。\n\n1. **基本原理**\n\n 形式化啊定义 k均值算法所解决的问题,给定 n 个向量 d1 到 dn,以及一个整数 k,要求找出 k 个簇 S1 到 Sk 以及各自的质心 C1 到 Ck,使得下式最小:\n\n \n\n 其中 ||di - Cr|| 是向量与质心的欧拉距离,I(Euclidean) 称作聚类的**准则函数**。也就是说,k均值以最小化每个向量到质心的欧拉距离的平方和为准则进行聚类,所以该准则函数有时也称作**平方误差和**函数。而质心的计算就是簇内数据点的几何平均:\n\n \n\n 其中,si 是簇 Si 内所有向量之和,称作**合成向量**。\n\n 生成 k 个簇的 k均值算法是一种迭代式算法,每次迭代都在上一步的基础上优化聚类结果,步骤如下:\n\n - 选取 k 个点作为 k 个簇的初始质心。\n - 将所有点分别分配给最近的质心所在的簇。\n - 重新计算每个簇的质心。\n - 重复步骤 2 和步骤 3 直到质心不再发生变化。\n\n k均值算法虽然无法保证收敛到全局最优,但能够有效地收敛到一个局部最优点。对于该算法,初级读者重点需要关注两个问题,即初始质心的选取和两点距离的度量。\n\n \n\n2. **初始质心的选取**\n\n 由于 k均值不保证收敏到全局最优,所以初始质心的选取对k均值的运行结果影响非常大,如果选取不当,则可能收敛到一个较差的局部最优点。\n\n 一种更高效的方法是, 将质心的选取也视作准则函数进行迭代式优化的过程。其具体做法是,先随机选择第一个数据点作为质心,视作只有一个簇计算准则函数。同时维护每个点到最近质心的距离的平方,作为一个映射数组 M。接着,随机取准则函数值的一部分记作。遍历剩下的所有数据点,若该点到最近质心的距离的平方小于0,则选取该点添加到质心列表,同时更新准则函数与 M。如此循环多次,直至凑足 k 个初始质心。这种方法可行的原理在于,每新增一个质心,都保证了准则函数的值下降一个随机比率。 而朴素实现相当于每次新增的质心都是完全随机的,准则函数的增减无法控制。孰优孰劣,一目了然。\n\n 考虑到 k均值是一种迭代式的算法, 需要反复计算质心与两点距离,这部分计算通常是效瓶颈。为了改进朴素 k均值算法的运行效率,HanLP利用种更快的准则函数实现了k均值的变种。\n\n \n\n3. **更快的准则函数**\n\n 除了欧拉准则函数,还存在一种基于余弦距离的准则函数:\n\n \n\n 该函数使用余弦函数衡量点与质心的相似度,目标是最大化同簇内点与质心的相似度。将向量夹角计算公式代人,该准则函数变换为: \n\n \n\n 代入后变换为:\n\n \n\n 也就是说,余弦准则函数等于 k 个簇各自合成向量的长度之和。比较之前的准则函数会发现在数据点从原簇移动到新簇时,I(Euclidean) 需要重新计算质心,以及两个簇内所有点到新质心的距离。而对于I(cos),由于发生改变的只有原簇和新簇两个合成向量,只需求两者的长度即可,计算量一下子减小不少。\n\n 基于新准则函数 I(cos),k均值变种算法流程如下:\n\n - 选取 k 个点作为 k 个簇的初始质心。\n - 将所有点分别分配给最近的质心所在的簇。\n - 对每个点,计算将其移入另一个簇时 I(cos) 的增大量,找出最大增大量,并完成移动。\n - 重复步骤 3 直到达到最大迭代次数,或簇的划分不再变化。\n\n \n\n4. **实现**\n\n 在 HanLP 中,聚类算法实现为 ClusterAnalyzer,用户可以将其想象为一个文档 id 到文档向量的映射容器。\n\n 此处以某音乐网站中的用户聚类为案例讲解聚类模块的用法。假设该音乐网站将 6 位用户点播的歌曲的流派记录下来,并且分别拼接为 6 段文本。给定用户名称与这 6 段播放历史,要求将这 6 位用户划分为 3 个簇。实现代码如下:\n\n ```python\n from pyhanlp import *\n \n ClusterAnalyzer = JClass('com.hankcs.hanlp.mining.cluster.ClusterAnalyzer')\n \n if __name__ == '__main__':\n analyzer = ClusterAnalyzer()\n analyzer.addDocument(\"赵一\", \"流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 蓝调, 蓝调, 蓝调, 蓝调, 蓝调, 蓝调, 摇滚, 摇滚, 摇滚, 摇滚\")\n analyzer.addDocument(\"钱二\", \"爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲\")\n analyzer.addDocument(\"张三\", \"古典, 古典, 古典, 古典, 民谣, 民谣, 民谣, 民谣\")\n analyzer.addDocument(\"李四\", \"爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 金属, 金属, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲\")\n analyzer.addDocument(\"王五\", \"流行, 流行, 流行, 流行, 摇滚, 摇滚, 摇滚, 嘻哈, 嘻哈, 嘻哈\")\n analyzer.addDocument(\"马六\", \"古典, 古典, 古典, 古典, 古典, 古典, 古典, 古典, 摇滚\")\n print(analyzer.kmeans(3))\n ```\n\n 结果如下:\n\n ```\n [[李四, 钱二], [王五, 赵一], [张三, 马六]]\n ```\n\n 通过 k均值聚类算法,我们成功的将用户按兴趣分组,获得了“人以群分”的效果。\n\n 聚类结果中簇的顺序是随机的,每个簇中的元素也是无序的,由于 k均值是个随机算法,有小概率得到不同的结果。\n\n 该聚类模块可以接受任意文本作为文档,而不需要用特殊分隔符隔开单词。\n\n\n\n### 10.4 重复二分聚类算法\n\n1. **基本原理**\n\n **重复二分聚类**(repeated bisection clustering) 是 k均值算法的效率加强版,其名称中的bisection是“二分”的意思,指的是反复对子集进行二分。该算法的步骤如下:\n\n - 挑选一个簇进行划分。\n - 利用 k均值算法将该簇划分为 2 个子集。\n - 重复步骤 1 和步骤 2,直到产生足够舒朗的簇。\n\n 每次产生的簇由上到下形成了一颗二叉树结构。\n\n \n\n \n\n 正是由于这个性质,重复二分聚类算得上一种基于划分的层次聚类算法。如果我们把算法运行的中间结果存储起来,就能输出一棵具有层级关系的树。树上每个节点都是一个簇,父子节点对应的簇满足包含关系。虽然每次划分都基于 k均值,由于每次二分都仅仅在一个子集上进行,输人数据少,算法自然更快。\n\n 在步骤1中,HanLP采用二分后准则函数的增幅最大为策略,每产生一个新簇,都试着将其二分并计算准则函数的增幅。然后对增幅最大的簇执行二分,重复多次直到满足算法停止条件。\n\n \n\n2. **自动判断聚类个数k**\n\n 读者可能觉得聚类个数 k 这个超参数很难准确估计。在重复二分聚类算法中,有一种变通的方法,那就是通过给准则函数的增幅设定阈值 β 来自动判断 k。此时算法的停止条件为,当一个簇的二分增幅小于 β 时不再对该簇进行划分,即认为这个簇已经达到最终状态,不可再分。当所有簇都不可再分时,算法终止,最终产生的聚类数量就不再需要人工指定了。\n\n \n\n3. **实现**\n\n ```python\n from pyhanlp import *\n \n ClusterAnalyzer = JClass('com.hankcs.hanlp.mining.cluster.ClusterAnalyzer')\n \n if __name__ == '__main__':\n analyzer = ClusterAnalyzer()\n analyzer.addDocument(\"赵一\", \"流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 流行, 蓝调, 蓝调, 蓝调, 蓝调, 蓝调, 蓝调, 摇滚, 摇滚, 摇滚, 摇滚\")\n analyzer.addDocument(\"钱二\", \"爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲\")\n analyzer.addDocument(\"张三\", \"古典, 古典, 古典, 古典, 民谣, 民谣, 民谣, 民谣\")\n analyzer.addDocument(\"李四\", \"爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 爵士, 金属, 金属, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲, 舞曲\")\n analyzer.addDocument(\"王五\", \"流行, 流行, 流行, 流行, 摇滚, 摇滚, 摇滚, 嘻哈, 嘻哈, 嘻哈\")\n analyzer.addDocument(\"马六\", \"古典, 古典, 古典, 古典, 古典, 古典, 古典, 古典, 摇滚\")\n \n print(analyzer.repeatedBisection(3)) # 重复二分聚类\n print(analyzer.repeatedBisection(1.0)) # 自动判断聚类数量k\n ```\n\n 运行结果如下:\n\n ```\n [[李四, 钱二], [王五, 赵一], [张三, 马六]]\n [[李四, 钱二], [王五, 赵一], [张三, 马六]]\n ```\n\n 与上面音乐案例得出的结果一致,但运行速度要快不少。\n\n\n\n### 10.5 标准化评测\n\n本次评测选择搜狗实验室提供的文本分类语料的一个子集,我称它为“搜狗文本分类语料库迷你版”。该迷你版语料库分为5个类目,每个类目下1000 篇文章,共计5000篇文章。运行代码如下:\n\n```python\nfrom pyhanlp import *\n\nimport zipfile\nimport os\nfrom pyhanlp.static import download, remove_file, HANLP_DATA_PATH\n\ndef test_data_path():\n \"\"\"\n 获取测试数据路径,位于$root/data/test,根目录由配置文件指定。\n :return:\n \"\"\"\n data_path = os.path.join(HANLP_DATA_PATH, 'test')\n if not os.path.isdir(data_path):\n os.mkdir(data_path)\n return data_path\n\n\n\n## 验证是否存在 MSR语料库,如果没有自动下载\ndef ensure_data(data_name, data_url):\n root_path = test_data_path()\n dest_path = os.path.join(root_path, data_name)\n if os.path.exists(dest_path):\n return dest_path\n \n if data_url.endswith('.zip'):\n dest_path += '.zip'\n download(data_url, dest_path)\n if data_url.endswith('.zip'):\n with zipfile.ZipFile(dest_path, \"r\") as archive:\n archive.extractall(root_path)\n remove_file(dest_path)\n dest_path = dest_path[:-len('.zip')]\n return dest_path\n\n\nsogou_corpus_path = ensure_data('搜狗文本分类语料库迷你版', 'http://file.hankcs.com/corpus/sogou-text-classification-corpus-mini.zip')\n\n\n## ===============================================\n## 以下开始聚类\n\nClusterAnalyzer = JClass('com.hankcs.hanlp.mining.cluster.ClusterAnalyzer')\n\nif __name__ == '__main__':\n for algorithm in \"kmeans\", \"repeated bisection\":\n print(\"%s F1=%.2f\\n\" % (algorithm, ClusterAnalyzer.evaluate(sogou_corpus_path, algorithm) * 100))\n```\n\n运行结果如下:\n\n```\nkmeans F1=83.74\n\nrepeated bisection F1=85.58\n```\n\n评测结果如下表:\n\n| 算法 | F1 | 耗时 |\n| ------------ | ----- | ---- |\n| k均值 | 83.74 | 67秒 |\n| 重复二分聚类 | 85.58 | 24秒 |\n\n对比两种算法,重复二分聚类不仅准确率比 k均值更高,而且速度是 k均值的 3 倍。然而重复二分聚类成绩波动较大,需要多运行几次才可能得出这样的结果。\n\n无监督聚类算法无法学习人类的偏好对文档进行划分,也无法学习每个簇在人类那里究竟叫什么。\n",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
cba56f59fabb92e3ab391f20481a721e4dd5c8a7
| 38,002 |
ipynb
|
Jupyter Notebook
|
src/notebooks/199-matplotlib-style-sheets.ipynb
|
nrslt/The-Python-Graph-Gallery
|
55898de66070ae716c95442466783ee986576e7d
|
[
"0BSD"
] | null | null | null |
src/notebooks/199-matplotlib-style-sheets.ipynb
|
nrslt/The-Python-Graph-Gallery
|
55898de66070ae716c95442466783ee986576e7d
|
[
"0BSD"
] | null | null | null |
src/notebooks/199-matplotlib-style-sheets.ipynb
|
nrslt/The-Python-Graph-Gallery
|
55898de66070ae716c95442466783ee986576e7d
|
[
"0BSD"
] | null | null | null | 348.642202 | 19,270 | 0.750066 |
[
[
[
"Welcome in the introductory template of the python graph gallery. Here is how to proceed to add a new `.ipynb` file that will be converted to a blogpost in the gallery!",
"_____no_output_____"
],
[
"## Notebook Metadata",
"_____no_output_____"
],
[
"It is very important to add the following fields to your notebook. It helps building the page later on:\n- **slug**: the URL of the blogPost. It should be exactly the same as the file title. Example: `70-basic-density-plot-with-seaborn`\n- **chartType**: the chart type like density or heatmap. For a complete list see [here](https://github.com/holtzy/The-Python-Graph-Gallery/blob/master/src/util/sectionDescriptions.js), it must be one of the `id` options.\n- **title**: what will be written in big on top of the blogpost! use html syntax there.\n- **description**: what will be written just below the title, centered text.\n- **keyword**: list of keywords related with the blogpost\n- **seoDescription**: a description for the bloppost meta. Should be a bit shorter than the description and must not contain any html syntax.",
"_____no_output_____"
],
[
"## Add a chart description",
"_____no_output_____"
],
[
"A chart example always come with some explanation. It must:\n\ncontain keywords\nlink to related pages like the parent page (graph section)\ngive explanations. In depth for complicated charts. High level for beginner level charts",
"_____no_output_____"
],
[
"## Add a chart",
"_____no_output_____"
]
],
[
[
"import seaborn as sns, numpy as np\nnp.random.seed(0)\nx = np.random.randn(100)\nax = sns.distplot(x)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
cba57f6cc874229db7e9e339c27365cc64537113
| 58,036 |
ipynb
|
Jupyter Notebook
|
04_ColloidViscosity_SOLUTION.ipynb
|
davidnoone/PHYS332_FluidExamples
|
28ff7aba8d79574faa3837925ac9aeedabfedbf4
|
[
"MIT"
] | 1 |
2021-07-13T08:02:11.000Z
|
2021-07-13T08:02:11.000Z
|
04_ColloidViscosity_SOLUTION.ipynb
|
davidnoone/PHYS332_FluidExamples
|
28ff7aba8d79574faa3837925ac9aeedabfedbf4
|
[
"MIT"
] | null | null | null |
04_ColloidViscosity_SOLUTION.ipynb
|
davidnoone/PHYS332_FluidExamples
|
28ff7aba8d79574faa3837925ac9aeedabfedbf4
|
[
"MIT"
] | null | null | null | 169.695906 | 21,330 | 0.876525 |
[
[
[
"<a href=\"https://colab.research.google.com/github/davidnoone/PHYS332_FluidExamples/blob/main/04_ColloidViscosity_SOLUTION.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Colloids and no-constant viscosity (1d case)\n\nColloids are a group of materials that include small particles emersen in a fluid (could be liquid or gas). Some examples include emulsions and gels, which emcompass substances like milk, whipped cream, styrofoam, jelly, and some glasses. \n\nWe imagine a \"pile\" of substance that undergoes a viscous dissipation following a simple law. \n\n$$\n \\frac{\\partial h}{\\partial t} = \\frac{\\partial}{\\partial x}\n \\left( \\nu \\frac{\\partial h}{\\partial x} \\right)\n$$\n\nwhere h is the depth of the colloidal material, and $\\nu$ is the kinematic viscosity, at constant density. \n\nThe viscosity follows a simple law:\n\n$$\n\\nu = \\nu_0 (1 + 2.5 \\phi)\n$$\n\n\nwhere $\\phi$ is the volume fraction. In the case that $\\phi = \\phi(h)$ some there are some non-linear consequences on the viscous flow. \n\n\n## Work tasks\n1. Create a numerical model of viscous flow using finite differences. \n(Hint: You have basically done this in previous excersizes). \n2. Compute the height at a futute time under the null case where $\\phi = 0$\n3. Repeate the experiment for the case that $\\phi$ has positive and negative values of a range of sizes. You may choose to assume $\\phi = \\pm h/h_{max}$, where $h_{max} $ is the maximum value of your initial \"pile\". \n4. Compare the results of your experiments. \n\n\n ",
"_____no_output_____"
]
],
[
[
"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n",
"_____no_output_____"
]
],
[
[
"The main component of this problem is developing an equation to calculate vicsous derivative using finite differences. Notice that unlike the previous case in which the viscosity is constant, here we must keep the viscosity within derivative estimates. We wish to evaluate the second grid on a discrete grid between 0 and 2$\\pi$, with steps $\\Delta x$ indicated by index $i = 0, N-1$. (Note python has arrays startning at index 0\n\nUsing a finite difference method, we can obtain scheme with second order accuracy as:\n\n$$\n\\frac{\\partial}{\\partial x}\n \\left( \\nu \\frac{\\partial h}{\\partial x} \\right)=\n \\frac{F_{i+1/2} - F_{i-1/2}}{(\\Delta x)}\n$$\n\nwhere we have used fluxes $F$ at the \"half\" locations defined by \n$$\nF_{i-1/2} = \\nu_{i-1/2} (\\frac{h_{i} - h_{i-1})}{\\Delta x}\n$$\n\nand\n$$\nF_{i+1/2} = \\nu_{i+1/2} (\\frac{h_{i+1} - h_{i})}{\\Delta x}\n$$\n\nNotice that $\\nu$ needs to be determined at the \"half\" locations, which means that $h$ needs to be estimated at those points. It is easiest to assume it is the average of the values on either side. \n\ni.e., $h_{i-1/2} = 0.5(h_i + h_{i-1})$, and similarly for $h_{i+1/2}$. \n\n\nWe are working with periodic boundary conditions so we may \"wrap arround\" such that $f_{-1} = f_{N-1}$ and $f_{N} = f_{1}$. You may choose to do this with python array indices, or take a look at the numpy finction [numpy.roll()](https://numpy.org/doc/stable/reference/generated/numpy.roll.html).\n",
"_____no_output_____"
]
],
[
[
"# Create a coordinate, which is periodix\nnpts = 50 \nxvals = np.linspace(-math.pi,math.pi,npts)\ndx = 2*math.pi/npts\n\nhmax = 1.0 # maximum height of pile [\"metres\"]\nvnu0 = 0.5 # reference viscosity [m2/sec]\n\n# Define the an initial \"pile\" of substance: a gaussian\nwidth = 3*dx\nh = hmax*np.exp(-(xvals/width)**2)\n",
"_____no_output_____"
]
],
[
[
"Make a plot showing your initial vorticity: vorticity as a function of X",
"_____no_output_____"
]
],
[
[
"# PLot!\nfig = plt.figure()\nplt.plot(xvals,h)",
"_____no_output_____"
]
],
[
[
"Let's define a function to perform some number of time steps",
"_____no_output_____"
]
],
[
[
"def viscosity(h):\n global hmax\n phi = 0.\n phi = h/hmax \n vnu = vnu0*(1 + 2.5*phi)\n return vnu\n\ndef forward_step(h_old, nsteps, dtime):\n for n in range(nsteps):\n\n dhdt = np.zeros_like(h_old)\n\n hmid = 0.5*(h_old + np.roll(h_old,+1)) # at indices i:nx1 = i-1/2 upward\n vmid = viscosity(hmid) \n hflx = vmid*(h_old - np.roll(h_old,+1))/dx \n dhdt = (np.roll(hflx,-1) - hflx)/dx # hflx(i+1/2) - hflx(i-1/2)\n\n h_new = h_old + dtime*dhdt\n return h_new\n",
"_____no_output_____"
]
],
[
[
"Use your integration function to march forward in time to check the analytic result. Note, the time step must be small enough for a robust solution. It must be:\n\n$$\n\\Delta t \\lt \\frac{(\\Delta x)^2} {4 \\eta}\n$$\n\n",
"_____no_output_____"
]
],
[
[
"dt_max = 0.25*dx*dx/vnu0\nprint(\"maximum allowed dtime is \",dt_max,\" seconds\")\n\ndtime = 0.005\nnsteps = 200\n\n\n# step forward more steps, and plot again\nnlines = 10\nfor iline in range(nlines):\n h = forward_step(h.copy(),nsteps,dtime)\n plt.plot(xvals,h)\n",
"maximum allowed dtime is 0.007895683520871487 seconds\n"
],
[
"#Rerun with a different phi (redefine the viscosity function - but clumsy)\ndef viscosity(h):\n global hmax\n phi = -h/hmax # Try this?\n vnu = vnu0*(1 + phi)\n return vnu\n\n\n# step forward more steps, and plot again\nh = hmax*np.exp(-(xvals/width)**2)\nfor iline in range(nlines):\n h = forward_step(h.copy(),nsteps,dtime)\n plt.plot(xvals,h)\n",
"_____no_output_____"
]
],
[
[
"#Results!\n\nHow did the shapes differ with thinning vs thickening?\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cba5928280bf6647a4024279206d19617aff39c4
| 128,010 |
ipynb
|
Jupyter Notebook
|
image-classification/dlnd_image_classification.ipynb
|
hc167/Udacity-Deep-Learning
|
56e857faafac99199cb3876d2f50681d624bab16
|
[
"MIT"
] | null | null | null |
image-classification/dlnd_image_classification.ipynb
|
hc167/Udacity-Deep-Learning
|
56e857faafac99199cb3876d2f50681d624bab16
|
[
"MIT"
] | null | null | null |
image-classification/dlnd_image_classification.ipynb
|
hc167/Udacity-Deep-Learning
|
56e857faafac99199cb3876d2f50681d624bab16
|
[
"MIT"
] | null | null | null | 96.538462 | 54,934 | 0.786298 |
[
[
[
"# Image Classification\nIn this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html). The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images.\n## Get the Data\nRun the following cell to download the [CIFAR-10 dataset for python](https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz).",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfrom urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\nimport problem_unittests as tests\nimport tarfile\n\ncifar10_dataset_folder_path = 'cifar-10-batches-py'\n\n# Use Floyd's cifar-10 dataset if present\nfloyd_cifar10_location = '/input/cifar-10/python.tar.gz'\nif isfile(floyd_cifar10_location):\n tar_gz_path = floyd_cifar10_location\nelse:\n tar_gz_path = 'cifar-10-python.tar.gz'\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(tar_gz_path):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:\n urlretrieve(\n 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',\n tar_gz_path,\n pbar.hook)\n\nif not isdir(cifar10_dataset_folder_path):\n with tarfile.open(tar_gz_path) as tar:\n tar.extractall()\n tar.close()\n\n\ntests.test_folder_path(cifar10_dataset_folder_path)",
"CIFAR-10 Dataset: 171MB [01:19, 2.14MB/s] \n"
]
],
[
[
"## Explore the Data\nThe dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named `data_batch_1`, `data_batch_2`, etc.. Each batch contains the labels and images that are one of the following:\n* airplane\n* automobile\n* bird\n* cat\n* deer\n* dog\n* frog\n* horse\n* ship\n* truck\n\nUnderstanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the `batch_id` and `sample_id`. The `batch_id` is the id for a batch (1-5). The `sample_id` is the id for a image and label pair in the batch.\n\nAsk yourself \"What are all possible labels?\", \"What is the range of values for the image data?\", \"Are the labels in order or random?\". Answers to questions like these will help you preprocess the data and end up with better predictions.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport helper\nimport numpy as np\n\n# Explore the dataset\nbatch_id = 2\nsample_id = 4\nhelper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)",
"\nStats of batch 2:\nSamples: 10000\nLabel Counts: {0: 984, 1: 1007, 2: 1010, 3: 995, 4: 1010, 5: 988, 6: 1008, 7: 1026, 8: 987, 9: 985}\nFirst 20 Labels: [1, 6, 6, 8, 8, 3, 4, 6, 0, 6, 0, 3, 6, 6, 5, 4, 8, 3, 2, 6]\n\nExample of Image 4:\nImage - Min Value: 0 Max Value: 255\nImage - Shape: (32, 32, 3)\nLabel - Label Id: 8 Name: ship\n"
]
],
[
[
"## Implement Preprocess Functions\n### Normalize\nIn the cell below, implement the `normalize` function to take in image data, `x`, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as `x`.",
"_____no_output_____"
]
],
[
[
"def normalize(x):\n \"\"\"\n Normalize a list of sample image data in the range of 0 to 1\n : x: List of image data. The image shape is (32, 32, 3)\n : return: Numpy array of normalize data\n \"\"\"\n _min = np.min(x)\n _max = np.max(x)\n \n return (x - _min) / (_max - _min)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_normalize(normalize)",
"Tests Passed\n"
]
],
[
[
"### One-hot encode\nJust like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the `one_hot_encode` function. The input, `x`, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to `one_hot_encode`. Make sure to save the map of encodings outside the function.\n\nHint: Don't reinvent the wheel.",
"_____no_output_____"
]
],
[
[
"def one_hot_encode(x):\n \"\"\"\n One hot encode a list of sample labels. Return a one-hot encoded vector for each label.\n : x: List of sample Labels\n : return: Numpy array of one-hot encoded labels\n \"\"\"\n return np.eye(10)[x]\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_one_hot_encode(one_hot_encode)",
"Tests Passed\n"
]
],
[
[
"### Randomize Data\nAs you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset.",
"_____no_output_____"
],
[
"## Preprocess all the data and save it\nRunning the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\nhelper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)",
"_____no_output_____"
]
],
[
[
"# Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport pickle\nimport problem_unittests as tests\nimport helper\n\n# Load the Preprocessed Validation data\nvalid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))",
"_____no_output_____"
]
],
[
[
"## Build the network\nFor the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.\n\n>**Note:** If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages to build each layer, except the layers you build in the \"Convolutional and Max Pooling Layer\" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.\n\n>However, if you would like to get the most out of this course, try to solve all the problems _without_ using anything from the TF Layers packages. You **can** still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the `conv2d` class, [tf.layers.conv2d](https://www.tensorflow.org/api_docs/python/tf/layers/conv2d), you would want to use the TF Neural Network version of `conv2d`, [tf.nn.conv2d](https://www.tensorflow.org/api_docs/python/tf/nn/conv2d). \n\nLet's begin!\n\n### Input\nThe neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions\n* Implement `neural_net_image_input`\n * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n * Set the shape using `image_shape` with batch size set to `None`.\n * Name the TensorFlow placeholder \"x\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n* Implement `neural_net_label_input`\n * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder)\n * Set the shape using `n_classes` with batch size set to `None`.\n * Name the TensorFlow placeholder \"y\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n* Implement `neural_net_keep_prob_input`\n * Return a [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) for dropout keep probability.\n * Name the TensorFlow placeholder \"keep_prob\" using the TensorFlow `name` parameter in the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder).\n\nThese names will be used at the end of the project to load your saved model.\n\nNote: `None` for shapes in TensorFlow allow for a dynamic size.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\ndef neural_net_image_input(image_shape):\n \"\"\"\n Return a Tensor for a batch of image input\n : image_shape: Shape of the images\n : return: Tensor for image input.\n \"\"\"\n return tf.placeholder(tf.float32, [None, *image_shape], name = 'x')\n\n\ndef neural_net_label_input(n_classes):\n \"\"\"\n Return a Tensor for a batch of label input\n : n_classes: Number of classes\n : return: Tensor for label input.\n \"\"\"\n return tf.placeholder(tf.float32, [None, n_classes], name = 'y')\n\n\ndef neural_net_keep_prob_input():\n \"\"\"\n Return a Tensor for keep probability\n : return: Tensor for keep probability.\n \"\"\"\n return tf.placeholder(tf.float32, name = 'keep_prob')\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntf.reset_default_graph()\ntests.test_nn_image_inputs(neural_net_image_input)\ntests.test_nn_label_inputs(neural_net_label_input)\ntests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)",
"Image Input Tests Passed.\nLabel Input Tests Passed.\nKeep Prob Tests Passed.\n"
]
],
[
[
"### Convolution and Max Pooling Layer\nConvolution layers have a lot of success with images. For this code cell, you should implement the function `conv2d_maxpool` to apply convolution then max pooling:\n* Create the weight and bias using `conv_ksize`, `conv_num_outputs` and the shape of `x_tensor`.\n* Apply a convolution to `x_tensor` using weight and `conv_strides`.\n * We recommend you use same padding, but you're welcome to use any padding.\n* Add bias\n* Add a nonlinear activation to the convolution.\n* Apply Max Pooling using `pool_ksize` and `pool_strides`.\n * We recommend you use same padding, but you're welcome to use any padding.\n\n**Note:** You **can't** use [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) for **this** layer, but you can still use TensorFlow's [Neural Network](https://www.tensorflow.org/api_docs/python/tf/nn) package. You may still use the shortcut option for all the **other** layers.",
"_____no_output_____"
]
],
[
[
"def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):\n \"\"\"\n Apply convolution then max pooling to x_tensor\n :param x_tensor: TensorFlow Tensor\n :param conv_num_outputs: Number of outputs for the convolutional layer\n :param conv_ksize: kernal size 2-D Tuple for the convolutional layer\n :param conv_strides: Stride 2-D Tuple for convolution\n :param pool_ksize: kernal size 2-D Tuple for pool\n :param pool_strides: Stride 2-D Tuple for pool\n : return: A tensor that represents convolution and max pooling of x_tensor\n \"\"\"\n depth_in = int(x_tensor.shape[3])\n depth_out = conv_num_outputs\n w_shape = [*conv_ksize, depth_in, depth_out]\n# weight = tf.Variable(tf.truncated_normal(w_shape))\n weight = tf.Variable(tf.random_normal(w_shape, stddev=0.1))\n \n bias = tf.Variable(tf.zeros(depth_out))\n \n conv_strides = [1, *conv_strides, 1]\n x = tf.nn.conv2d(x_tensor, weight, strides=conv_strides, padding='SAME')\n \n x = tf.nn.bias_add(x, bias)\n x = tf.nn.relu(x)\n \n pool_ksize = [1, *pool_ksize, 1]\n pool_strides = [1, *pool_strides, 1]\n return tf.nn.max_pool(x, pool_ksize, pool_strides, padding='SAME')\n \n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_con_pool(conv2d_maxpool)",
"Tests Passed\n"
]
],
[
[
"### Flatten Layer\nImplement the `flatten` function to change the dimension of `x_tensor` from a 4-D tensor to a 2-D tensor. The output should be the shape (*Batch Size*, *Flattened Image Size*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.",
"_____no_output_____"
]
],
[
[
"def flatten(x_tensor):\n \"\"\"\n Flatten x_tensor to (Batch Size, Flattened Image Size)\n : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.\n : return: A tensor of size (Batch Size, Flattened Image Size).\n \"\"\"\n return tf.contrib.layers.flatten(x_tensor)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_flatten(flatten)",
"Tests Passed\n"
]
],
[
[
"### Fully-Connected Layer\nImplement the `fully_conn` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.",
"_____no_output_____"
]
],
[
[
"def fully_conn(x_tensor, num_outputs):\n \"\"\"\n Apply a fully connected layer to x_tensor using weight and bias\n : x_tensor: A 2-D tensor where the first dimension is batch size.\n : num_outputs: The number of output that the new tensor should be.\n : return: A 2-D tensor where the second dimension is num_outputs.\n \"\"\"\n return tf.contrib.layers.fully_connected(x_tensor, num_outputs)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_fully_conn(fully_conn)",
"Tests Passed\n"
]
],
[
[
"### Output Layer\nImplement the `output` function to apply a fully connected layer to `x_tensor` with the shape (*Batch Size*, *num_outputs*). Shortcut option: you can use classes from the [TensorFlow Layers](https://www.tensorflow.org/api_docs/python/tf/layers) or [TensorFlow Layers (contrib)](https://www.tensorflow.org/api_guides/python/contrib.layers) packages for this layer. For more of a challenge, only use other TensorFlow packages.\n\n**Note:** Activation, softmax, or cross entropy should **not** be applied to this.",
"_____no_output_____"
]
],
[
[
"def output(x_tensor, num_outputs):\n \"\"\"\n Apply a output layer to x_tensor using weight and bias\n : x_tensor: A 2-D tensor where the first dimension is batch size.\n : num_outputs: The number of output that the new tensor should be.\n : return: A 2-D tensor where the second dimension is num_outputs.\n \"\"\"\n return tf.contrib.layers.fully_connected(x_tensor, num_outputs, activation_fn=None)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_output(output)",
"Tests Passed\n"
]
],
[
[
"### Create Convolutional Model\nImplement the function `conv_net` to create a convolutional neural network model. The function takes in a batch of images, `x`, and outputs logits. Use the layers you created above to create this model:\n\n* Apply 1, 2, or 3 Convolution and Max Pool layers\n* Apply a Flatten Layer\n* Apply 1, 2, or 3 Fully Connected Layers\n* Apply an Output Layer\n* Return the output\n* Apply [TensorFlow's Dropout](https://www.tensorflow.org/api_docs/python/tf/nn/dropout) to one or more layers in the model using `keep_prob`. ",
"_____no_output_____"
]
],
[
[
"def conv_net(x, keep_prob):\n \"\"\"\n Create a convolutional neural network model\n : x: Placeholder tensor that holds image data.\n : keep_prob: Placeholder tensor that hold dropout keep probability.\n : return: Tensor that represents logits\n \"\"\"\n # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers\n # Play around with different number of outputs, kernel size and stride\n # Function Definition from Above:\n # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides)\n \n x = conv2d_maxpool(x, 32, (3, 3), (1, 1), (2, 2), (2, 2))\n x = conv2d_maxpool(x, 32, (3, 3), (2, 2), (2, 2), (2, 2))\n x = conv2d_maxpool(x, 64, (3, 3), (1, 1), (2, 2), (2, 2))\n# x = tf.nn.dropout(x, keep_prob)\n\n # TODO: Apply a Flatten Layer\n # Function Definition from Above:\n # flatten(x_tensor)\n x = flatten(x) \n\n # TODO: Apply 1, 2, or 3 Fully Connected Layers\n # Play around with different number of outputs\n # Function Definition from Above:\n # fully_conn(x_tensor, num_outputs)\n x = fully_conn(x, 512)\n x = tf.nn.dropout(x, keep_prob)\n x = fully_conn(x, 128)\n x = tf.nn.dropout(x, keep_prob)\n \n \n # TODO: Apply an Output Layer\n # Set this to the number of classes\n # Function Definition from Above:\n # output(x_tensor, num_outputs)\n out = output(x, 10)\n \n \n # TODO: return output\n return out\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\n##############################\n## Build the Neural Network ##\n##############################\n\n# Remove previous weights, bias, inputs, etc..\ntf.reset_default_graph()\n\n# Inputs\nx = neural_net_image_input((32, 32, 3))\ny = neural_net_label_input(10)\nkeep_prob = neural_net_keep_prob_input()\n\n# Model\nlogits = conv_net(x, keep_prob)\n\n# Name logits Tensor, so that is can be loaded from disk after training\nlogits = tf.identity(logits, name='logits')\n\n# Loss and Optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\noptimizer = tf.train.AdamOptimizer().minimize(cost)\n\n# Accuracy\ncorrect_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\n\ntests.test_conv_net(conv_net)",
"Neural Network Built!\n"
]
],
[
[
"## Train the Neural Network\n### Single Optimization\nImplement the function `train_neural_network` to do a single optimization. The optimization should use `optimizer` to optimize in `session` with a `feed_dict` of the following:\n* `x` for image input\n* `y` for labels\n* `keep_prob` for keep probability for dropout\n\nThis function will be called for each batch, so `tf.global_variables_initializer()` has already been called.\n\nNote: Nothing needs to be returned. This function is only optimizing the neural network.",
"_____no_output_____"
]
],
[
[
"def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):\n \"\"\"\n Optimize the session on a batch of images and labels\n : session: Current TensorFlow session\n : optimizer: TensorFlow optimizer function\n : keep_probability: keep probability\n : feature_batch: Batch of Numpy image data\n : label_batch: Batch of Numpy label data\n \"\"\" \n session.run(optimizer, feed_dict={\n x: feature_batch,\n y: label_batch,\n keep_prob: keep_probability})\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_train_nn(train_neural_network)",
"Tests Passed\n"
]
],
[
[
"### Show Stats\nImplement the function `print_stats` to print loss and validation accuracy. Use the global variables `valid_features` and `valid_labels` to calculate validation accuracy. Use a keep probability of `1.0` to calculate the loss and validation accuracy.",
"_____no_output_____"
]
],
[
[
"def print_stats(session, feature_batch, label_batch, cost, accuracy):\n \"\"\"\n Print information about loss and validation accuracy\n : session: Current TensorFlow session\n : feature_batch: Batch of Numpy image data\n : label_batch: Batch of Numpy label data\n : cost: TensorFlow cost function\n : accuracy: TensorFlow accuracy function\n \"\"\"\n \n l = session.run(cost, feed_dict={\n x: feature_batch,\n y: label_batch,\n keep_prob: 1\n })\n \n a = session.run(accuracy, feed_dict={\n x: valid_features, \n y: valid_labels,\n keep_prob: 1\n })\n \n print('Loss: {:5.5f} Validation Accuracy: {:5.5f}'.format(l, a))",
"_____no_output_____"
]
],
[
[
"### Hyperparameters\nTune the following parameters:\n* Set `epochs` to the number of iterations until the network stops learning or start overfitting\n* Set `batch_size` to the highest number that your machine has memory for. Most people set them to common sizes of memory:\n * 64\n * 128\n * 256\n * ...\n* Set `keep_probability` to the probability of keeping a node using dropout",
"_____no_output_____"
]
],
[
[
"# TODO: Tune Parameters\nepochs = 50\nbatch_size = 256\nkeep_probability = .6",
"_____no_output_____"
]
],
[
[
"### Train on a Single CIFAR-10 Batch\nInstead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nprint('Checking the Training on a Single Batch...')\nwith tf.Session() as sess:\n # Initializing the variables\n sess.run(tf.global_variables_initializer())\n \n # Training cycle\n for epoch in range(epochs):\n batch_i = 1\n for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')\n print_stats(sess, batch_features, batch_labels, cost, accuracy)",
"Checking the Training on a Single Batch...\nEpoch 1, CIFAR-10 Batch 1: Loss: 2.15061 Validation Accuracy: 0.27200\nEpoch 2, CIFAR-10 Batch 1: Loss: 2.02397 Validation Accuracy: 0.34760\nEpoch 3, CIFAR-10 Batch 1: Loss: 1.82465 Validation Accuracy: 0.40080\nEpoch 4, CIFAR-10 Batch 1: Loss: 1.62279 Validation Accuracy: 0.42920\nEpoch 5, CIFAR-10 Batch 1: Loss: 1.48490 Validation Accuracy: 0.44040\nEpoch 6, CIFAR-10 Batch 1: Loss: 1.32405 Validation Accuracy: 0.45120\nEpoch 7, CIFAR-10 Batch 1: Loss: 1.14177 Validation Accuracy: 0.47560\nEpoch 8, CIFAR-10 Batch 1: Loss: 1.02922 Validation Accuracy: 0.48140\nEpoch 9, CIFAR-10 Batch 1: Loss: 0.91588 Validation Accuracy: 0.49980\nEpoch 10, CIFAR-10 Batch 1: Loss: 0.81385 Validation Accuracy: 0.50580\nEpoch 11, CIFAR-10 Batch 1: Loss: 0.73131 Validation Accuracy: 0.51640\nEpoch 12, CIFAR-10 Batch 1: Loss: 0.67057 Validation Accuracy: 0.51440\nEpoch 13, CIFAR-10 Batch 1: Loss: 0.61974 Validation Accuracy: 0.49980\nEpoch 14, CIFAR-10 Batch 1: Loss: 0.53529 Validation Accuracy: 0.53180\nEpoch 15, CIFAR-10 Batch 1: Loss: 0.51413 Validation Accuracy: 0.53520\nEpoch 16, CIFAR-10 Batch 1: Loss: 0.47905 Validation Accuracy: 0.53660\nEpoch 17, CIFAR-10 Batch 1: Loss: 0.46193 Validation Accuracy: 0.52380\nEpoch 18, CIFAR-10 Batch 1: Loss: 0.41395 Validation Accuracy: 0.54860\nEpoch 19, CIFAR-10 Batch 1: Loss: 0.38523 Validation Accuracy: 0.55040\nEpoch 20, CIFAR-10 Batch 1: Loss: 0.33333 Validation Accuracy: 0.54740\nEpoch 21, CIFAR-10 Batch 1: Loss: 0.30202 Validation Accuracy: 0.55760\nEpoch 22, CIFAR-10 Batch 1: Loss: 0.25566 Validation Accuracy: 0.55300\nEpoch 23, CIFAR-10 Batch 1: Loss: 0.24528 Validation Accuracy: 0.55580\nEpoch 24, CIFAR-10 Batch 1: Loss: 0.24035 Validation Accuracy: 0.54500\nEpoch 25, CIFAR-10 Batch 1: Loss: 0.19376 Validation Accuracy: 0.54880\nEpoch 26, CIFAR-10 Batch 1: Loss: 0.21146 Validation Accuracy: 0.54620\nEpoch 27, CIFAR-10 Batch 1: Loss: 0.17785 Validation Accuracy: 0.55780\nEpoch 28, CIFAR-10 Batch 1: Loss: 0.14539 Validation Accuracy: 0.55580\nEpoch 29, CIFAR-10 Batch 1: Loss: 0.13845 Validation Accuracy: 0.54720\nEpoch 30, CIFAR-10 Batch 1: Loss: 0.11860 Validation Accuracy: 0.52420\nEpoch 31, CIFAR-10 Batch 1: Loss: 0.11200 Validation Accuracy: 0.52820\nEpoch 32, CIFAR-10 Batch 1: Loss: 0.11594 Validation Accuracy: 0.51840\nEpoch 33, CIFAR-10 Batch 1: Loss: 0.09379 Validation Accuracy: 0.52340\nEpoch 34, CIFAR-10 Batch 1: Loss: 0.09426 Validation Accuracy: 0.52720\nEpoch 35, CIFAR-10 Batch 1: Loss: 0.08831 Validation Accuracy: 0.54760\nEpoch 36, CIFAR-10 Batch 1: Loss: 0.10127 Validation Accuracy: 0.54460\nEpoch 37, CIFAR-10 Batch 1: Loss: 0.07312 Validation Accuracy: 0.52620\nEpoch 38, CIFAR-10 Batch 1: Loss: 0.04516 Validation Accuracy: 0.55020\nEpoch 39, CIFAR-10 Batch 1: Loss: 0.05216 Validation Accuracy: 0.53560\nEpoch 40, CIFAR-10 Batch 1: Loss: 0.04994 Validation Accuracy: 0.54280\nEpoch 41, CIFAR-10 Batch 1: Loss: 0.06680 Validation Accuracy: 0.52980\nEpoch 42, CIFAR-10 Batch 1: Loss: 0.05252 Validation Accuracy: 0.52280\nEpoch 43, CIFAR-10 Batch 1: Loss: 0.04841 Validation Accuracy: 0.53280\nEpoch 44, CIFAR-10 Batch 1: Loss: 0.03477 Validation Accuracy: 0.51980\nEpoch 45, CIFAR-10 Batch 1: Loss: 0.03905 Validation Accuracy: 0.54200\nEpoch 46, CIFAR-10 Batch 1: Loss: 0.02633 Validation Accuracy: 0.55060\nEpoch 47, CIFAR-10 Batch 1: Loss: 0.04426 Validation Accuracy: 0.53040\nEpoch 48, CIFAR-10 Batch 1: Loss: 0.06521 Validation Accuracy: 0.50360\nEpoch 49, CIFAR-10 Batch 1: Loss: 0.03210 Validation Accuracy: 0.53660\nEpoch 50, CIFAR-10 Batch 1: Loss: 0.01759 Validation Accuracy: 0.54280\n"
]
],
[
[
"### Fully Train the Model\nNow that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nsave_model_path = './image_classification'\n\nprint('Training...')\nwith tf.Session() as sess:\n # Initializing the variables\n sess.run(tf.global_variables_initializer())\n \n # Training cycle\n for epoch in range(epochs):\n # Loop over all batches\n n_batches = 5\n for batch_i in range(1, n_batches + 1):\n for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')\n print_stats(sess, batch_features, batch_labels, cost, accuracy)\n \n # Save Model\n saver = tf.train.Saver()\n save_path = saver.save(sess, save_model_path)",
"Training...\nEpoch 1, CIFAR-10 Batch 1: Loss: 2.12201 Validation Accuracy: 0.32140\nEpoch 1, CIFAR-10 Batch 2: Loss: 1.83877 Validation Accuracy: 0.35760\nEpoch 1, CIFAR-10 Batch 3: Loss: 1.55159 Validation Accuracy: 0.35640\nEpoch 1, CIFAR-10 Batch 4: Loss: 1.59620 Validation Accuracy: 0.41860\nEpoch 1, CIFAR-10 Batch 5: Loss: 1.53219 Validation Accuracy: 0.44900\nEpoch 2, CIFAR-10 Batch 1: Loss: 1.65283 Validation Accuracy: 0.46120\nEpoch 2, CIFAR-10 Batch 2: Loss: 1.54079 Validation Accuracy: 0.47800\nEpoch 2, CIFAR-10 Batch 3: Loss: 1.17077 Validation Accuracy: 0.45800\nEpoch 2, CIFAR-10 Batch 4: Loss: 1.26037 Validation Accuracy: 0.49300\nEpoch 2, CIFAR-10 Batch 5: Loss: 1.22821 Validation Accuracy: 0.50420\nEpoch 3, CIFAR-10 Batch 1: Loss: 1.29969 Validation Accuracy: 0.51400\nEpoch 3, CIFAR-10 Batch 2: Loss: 1.25730 Validation Accuracy: 0.52200\nEpoch 3, CIFAR-10 Batch 3: Loss: 0.96511 Validation Accuracy: 0.51880\nEpoch 3, CIFAR-10 Batch 4: Loss: 1.01780 Validation Accuracy: 0.53700\nEpoch 3, CIFAR-10 Batch 5: Loss: 1.07288 Validation Accuracy: 0.54060\nEpoch 4, CIFAR-10 Batch 1: Loss: 1.07057 Validation Accuracy: 0.54560\nEpoch 4, CIFAR-10 Batch 2: Loss: 1.07218 Validation Accuracy: 0.55100\nEpoch 4, CIFAR-10 Batch 3: Loss: 0.79972 Validation Accuracy: 0.52480\nEpoch 4, CIFAR-10 Batch 4: Loss: 0.87446 Validation Accuracy: 0.56320\nEpoch 4, CIFAR-10 Batch 5: Loss: 0.95506 Validation Accuracy: 0.56440\nEpoch 5, CIFAR-10 Batch 1: Loss: 0.96654 Validation Accuracy: 0.57420\nEpoch 5, CIFAR-10 Batch 2: Loss: 0.90851 Validation Accuracy: 0.56160\nEpoch 5, CIFAR-10 Batch 3: Loss: 0.64565 Validation Accuracy: 0.57420\nEpoch 5, CIFAR-10 Batch 4: Loss: 0.77614 Validation Accuracy: 0.57640\nEpoch 5, CIFAR-10 Batch 5: Loss: 0.78678 Validation Accuracy: 0.59520\nEpoch 6, CIFAR-10 Batch 1: Loss: 0.84405 Validation Accuracy: 0.59160\nEpoch 6, CIFAR-10 Batch 2: Loss: 0.74251 Validation Accuracy: 0.58780\nEpoch 6, CIFAR-10 Batch 3: Loss: 0.58892 Validation Accuracy: 0.57020\nEpoch 6, CIFAR-10 Batch 4: Loss: 0.65396 Validation Accuracy: 0.60400\nEpoch 6, CIFAR-10 Batch 5: Loss: 0.69148 Validation Accuracy: 0.60660\nEpoch 7, CIFAR-10 Batch 1: Loss: 0.73410 Validation Accuracy: 0.60540\nEpoch 7, CIFAR-10 Batch 2: Loss: 0.61653 Validation Accuracy: 0.61080\nEpoch 7, CIFAR-10 Batch 3: Loss: 0.50703 Validation Accuracy: 0.60660\nEpoch 7, CIFAR-10 Batch 4: Loss: 0.59386 Validation Accuracy: 0.60860\nEpoch 7, CIFAR-10 Batch 5: Loss: 0.62965 Validation Accuracy: 0.61580\nEpoch 8, CIFAR-10 Batch 1: Loss: 0.63040 Validation Accuracy: 0.62000\nEpoch 8, CIFAR-10 Batch 2: Loss: 0.49412 Validation Accuracy: 0.62220\nEpoch 8, CIFAR-10 Batch 3: Loss: 0.43183 Validation Accuracy: 0.61020\nEpoch 8, CIFAR-10 Batch 4: Loss: 0.54021 Validation Accuracy: 0.60520\nEpoch 8, CIFAR-10 Batch 5: Loss: 0.50535 Validation Accuracy: 0.62700\nEpoch 9, CIFAR-10 Batch 1: Loss: 0.60686 Validation Accuracy: 0.63600\nEpoch 9, CIFAR-10 Batch 2: Loss: 0.43378 Validation Accuracy: 0.61800\nEpoch 9, CIFAR-10 Batch 3: Loss: 0.41160 Validation Accuracy: 0.62520\nEpoch 9, CIFAR-10 Batch 4: Loss: 0.53046 Validation Accuracy: 0.63600\nEpoch 9, CIFAR-10 Batch 5: Loss: 0.42199 Validation Accuracy: 0.65020\nEpoch 10, CIFAR-10 Batch 1: Loss: 0.56657 Validation Accuracy: 0.64280\nEpoch 10, CIFAR-10 Batch 2: Loss: 0.43190 Validation Accuracy: 0.61100\nEpoch 10, CIFAR-10 Batch 3: Loss: 0.36730 Validation Accuracy: 0.64380\nEpoch 10, CIFAR-10 Batch 4: Loss: 0.45725 Validation Accuracy: 0.63640\nEpoch 10, CIFAR-10 Batch 5: Loss: 0.37416 Validation Accuracy: 0.64340\nEpoch 11, CIFAR-10 Batch 1: Loss: 0.51493 Validation Accuracy: 0.64160\nEpoch 11, CIFAR-10 Batch 2: Loss: 0.34120 Validation Accuracy: 0.64160\nEpoch 11, CIFAR-10 Batch 3: Loss: 0.32584 Validation Accuracy: 0.64240\nEpoch 11, CIFAR-10 Batch 4: Loss: 0.39520 Validation Accuracy: 0.65620\nEpoch 11, CIFAR-10 Batch 5: Loss: 0.33550 Validation Accuracy: 0.66220\nEpoch 12, CIFAR-10 Batch 1: Loss: 0.46485 Validation Accuracy: 0.65160\nEpoch 12, CIFAR-10 Batch 2: Loss: 0.28812 Validation Accuracy: 0.65420\nEpoch 12, CIFAR-10 Batch 3: Loss: 0.27361 Validation Accuracy: 0.63680\nEpoch 12, CIFAR-10 Batch 4: Loss: 0.38162 Validation Accuracy: 0.65800\nEpoch 12, CIFAR-10 Batch 5: Loss: 0.30346 Validation Accuracy: 0.66260\nEpoch 13, CIFAR-10 Batch 1: Loss: 0.41133 Validation Accuracy: 0.63960\nEpoch 13, CIFAR-10 Batch 2: Loss: 0.31351 Validation Accuracy: 0.62620\nEpoch 13, CIFAR-10 Batch 3: Loss: 0.23571 Validation Accuracy: 0.66060\nEpoch 13, CIFAR-10 Batch 4: Loss: 0.33202 Validation Accuracy: 0.66100\nEpoch 13, CIFAR-10 Batch 5: Loss: 0.25950 Validation Accuracy: 0.67280\nEpoch 14, CIFAR-10 Batch 1: Loss: 0.39387 Validation Accuracy: 0.65060\nEpoch 14, CIFAR-10 Batch 2: Loss: 0.22593 Validation Accuracy: 0.64120\nEpoch 14, CIFAR-10 Batch 3: Loss: 0.22200 Validation Accuracy: 0.66140\nEpoch 14, CIFAR-10 Batch 4: Loss: 0.34284 Validation Accuracy: 0.67120\nEpoch 14, CIFAR-10 Batch 5: Loss: 0.24452 Validation Accuracy: 0.66200\nEpoch 15, CIFAR-10 Batch 1: Loss: 0.35341 Validation Accuracy: 0.66440\nEpoch 15, CIFAR-10 Batch 2: Loss: 0.23043 Validation Accuracy: 0.64660\nEpoch 15, CIFAR-10 Batch 3: Loss: 0.22805 Validation Accuracy: 0.65940\nEpoch 15, CIFAR-10 Batch 4: Loss: 0.29529 Validation Accuracy: 0.66940\nEpoch 15, CIFAR-10 Batch 5: Loss: 0.22622 Validation Accuracy: 0.65700\nEpoch 16, CIFAR-10 Batch 1: Loss: 0.32165 Validation Accuracy: 0.67280\nEpoch 16, CIFAR-10 Batch 2: Loss: 0.19322 Validation Accuracy: 0.65340\nEpoch 16, CIFAR-10 Batch 3: Loss: 0.22760 Validation Accuracy: 0.66260\nEpoch 16, CIFAR-10 Batch 4: Loss: 0.29061 Validation Accuracy: 0.66240\nEpoch 16, CIFAR-10 Batch 5: Loss: 0.21467 Validation Accuracy: 0.66820\nEpoch 17, CIFAR-10 Batch 1: Loss: 0.31269 Validation Accuracy: 0.66200\nEpoch 17, CIFAR-10 Batch 2: Loss: 0.15739 Validation Accuracy: 0.66920\nEpoch 17, CIFAR-10 Batch 3: Loss: 0.15988 Validation Accuracy: 0.67580\nEpoch 17, CIFAR-10 Batch 4: Loss: 0.24642 Validation Accuracy: 0.66480\nEpoch 17, CIFAR-10 Batch 5: Loss: 0.16050 Validation Accuracy: 0.67660\nEpoch 18, CIFAR-10 Batch 1: Loss: 0.27846 Validation Accuracy: 0.66960\nEpoch 18, CIFAR-10 Batch 2: Loss: 0.15513 Validation Accuracy: 0.67600\nEpoch 18, CIFAR-10 Batch 3: Loss: 0.14811 Validation Accuracy: 0.68220\nEpoch 18, CIFAR-10 Batch 4: Loss: 0.17928 Validation Accuracy: 0.67900\nEpoch 18, CIFAR-10 Batch 5: Loss: 0.17155 Validation Accuracy: 0.67360\nEpoch 19, CIFAR-10 Batch 1: Loss: 0.33342 Validation Accuracy: 0.66180\nEpoch 19, CIFAR-10 Batch 2: Loss: 0.12526 Validation Accuracy: 0.67280\nEpoch 19, CIFAR-10 Batch 3: Loss: 0.12739 Validation Accuracy: 0.67920\nEpoch 19, CIFAR-10 Batch 4: Loss: 0.17317 Validation Accuracy: 0.67440\nEpoch 19, CIFAR-10 Batch 5: Loss: 0.16353 Validation Accuracy: 0.67160\nEpoch 20, CIFAR-10 Batch 1: Loss: 0.22810 Validation Accuracy: 0.67860\nEpoch 20, CIFAR-10 Batch 2: Loss: 0.13148 Validation Accuracy: 0.67180\nEpoch 20, CIFAR-10 Batch 3: Loss: 0.12126 Validation Accuracy: 0.68280\nEpoch 20, CIFAR-10 Batch 4: Loss: 0.18157 Validation Accuracy: 0.67180\nEpoch 20, CIFAR-10 Batch 5: Loss: 0.13440 Validation Accuracy: 0.67820\nEpoch 21, CIFAR-10 Batch 1: Loss: 0.24084 Validation Accuracy: 0.67820\nEpoch 21, CIFAR-10 Batch 2: Loss: 0.12252 Validation Accuracy: 0.68840\nEpoch 21, CIFAR-10 Batch 3: Loss: 0.13012 Validation Accuracy: 0.67420\nEpoch 21, CIFAR-10 Batch 4: Loss: 0.18273 Validation Accuracy: 0.66240\nEpoch 21, CIFAR-10 Batch 5: Loss: 0.12326 Validation Accuracy: 0.66900\nEpoch 22, CIFAR-10 Batch 1: Loss: 0.22111 Validation Accuracy: 0.65980\nEpoch 22, CIFAR-10 Batch 2: Loss: 0.13979 Validation Accuracy: 0.67560\nEpoch 22, CIFAR-10 Batch 3: Loss: 0.11130 Validation Accuracy: 0.67920\nEpoch 22, CIFAR-10 Batch 4: Loss: 0.14572 Validation Accuracy: 0.66180\nEpoch 22, CIFAR-10 Batch 5: Loss: 0.11037 Validation Accuracy: 0.67720\nEpoch 23, CIFAR-10 Batch 1: Loss: 0.22459 Validation Accuracy: 0.66800\nEpoch 23, CIFAR-10 Batch 2: Loss: 0.13946 Validation Accuracy: 0.65680\n"
]
],
[
[
"# Checkpoint\nThe model has been saved to disk.\n## Test Model\nTest your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport tensorflow as tf\nimport pickle\nimport helper\nimport random\n\n# Set batch size if not already set\ntry:\n if batch_size:\n pass\nexcept NameError:\n batch_size = 64\n\nsave_model_path = './image_classification'\nn_samples = 4\ntop_n_predictions = 3\n\ndef test_model():\n \"\"\"\n Test the saved model against the test dataset\n \"\"\"\n\n test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb'))\n loaded_graph = tf.Graph()\n\n with tf.Session(graph=loaded_graph) as sess:\n # Load model\n loader = tf.train.import_meta_graph(save_model_path + '.meta')\n loader.restore(sess, save_model_path)\n\n # Get Tensors from loaded model\n loaded_x = loaded_graph.get_tensor_by_name('x:0')\n loaded_y = loaded_graph.get_tensor_by_name('y:0')\n loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n loaded_logits = loaded_graph.get_tensor_by_name('logits:0')\n loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')\n \n # Get accuracy in batches for memory limitations\n test_batch_acc_total = 0\n test_batch_count = 0\n \n for test_feature_batch, test_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):\n test_batch_acc_total += sess.run(\n loaded_acc,\n feed_dict={loaded_x: test_feature_batch, loaded_y: test_label_batch, loaded_keep_prob: 1.0})\n test_batch_count += 1\n\n print('Testing Accuracy: {}\\n'.format(test_batch_acc_total/test_batch_count))\n\n # Print Random Samples\n random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))\n random_test_predictions = sess.run(\n tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),\n feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})\n helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)\n\n\ntest_model()",
"INFO:tensorflow:Restoring parameters from ./image_classification\nTesting Accuracy: 0.66708984375\n\n"
]
],
[
[
"## Why 50-80% Accuracy?\nYou might be wondering why you can't get an accuracy any higher. First things first, 50% isn't bad for a simple CNN. Pure guessing would get you 10% accuracy. However, you might notice people are getting scores [well above 80%](http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html#43494641522d3130). That's because we haven't taught you all there is to know about neural networks. We still need to cover a few more techniques.\n## Submitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_image_classification.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba59c3126a7f67bff9c8ccb8c54f63cd6574105
| 2,443 |
ipynb
|
Jupyter Notebook
|
notebooks/notebook-1.ipynb
|
vauxgomes/ifce-ica
|
a37f20ea0850056e18a3d8426f333c2b7fc83b67
|
[
"MIT"
] | 1 |
2020-06-05T14:06:11.000Z
|
2020-06-05T14:06:11.000Z
|
notebooks/notebook-1.ipynb
|
vauxgomes/ica
|
a37f20ea0850056e18a3d8426f333c2b7fc83b67
|
[
"MIT"
] | null | null | null |
notebooks/notebook-1.ipynb
|
vauxgomes/ica
|
a37f20ea0850056e18a3d8426f333c2b7fc83b67
|
[
"MIT"
] | 1 |
2020-10-21T21:09:30.000Z
|
2020-10-21T21:09:30.000Z
| 33.013514 | 259 | 0.60745 |
[
[
[
"# Introdução ao Google Colab\n\n## Sumário\n\n - [Benefícios do Colab](#Benefícios-do-Colab)\n - [Criando um notebook](#Criando-um-notebook)\n - [Utilizando a GPU Gratis](#Utilizando-a-GPU-Gratis)\n\n## Benefícios do Colab\n\n- Suporte para Python 2.7 e Python 3.6;\n- Aceleração de **GPU grátis**;\n- Bibliotecas pré-instaladas: Todas as principais bibliotecas Python, como o TensorFlow, o Scikit-learn, o Matplotlib, entre muitas outras, estão pré-instaladas e prontas para serem importadas;\n- Construído com base no **Jupyter Notebook**;\n- Recurso de colaboração (funciona com uma equipe igual ao Google Docs): o Google Colab permite que os desenvolvedores usem e compartilhem o Jupyter notebook entre si sem precisar baixar, instalar ou executar qualquer coisa que não seja um navegador;\n- Suporta comandos bash;\n- Os notebooks do Google Colab são armazenados no drive.\n\n## Criando um notebook\n\n### Modo 1\n\n1. Abra o [Google Colab](https://colab.research.google.com/notebooks/welcome.ipynb#recent=true)\n2. Clique em “novo notebook” e selecione o notebook Python 3.\n\n### Modo 2\n\n1. Abra o [Google Drive](https://drive.google.com/drive/)\n2. Crie uma pastas para o projeto\n3. Clique em `Novo > Mais > Colaboratory`\n\n\n## Utilizando a GPU Gratis\n\n\nO hardware padrão do Google Colab é a CPU ou pode ser GPU.\n\n1. Clique em `Editar > Configurações do notebook > Acelerador de hardware > GPU`.\n\n\n## Links\n- [https://medium.com/machina-sapiens/google-colab-guia-do-iniciante-334d70aad531](https://medium.com/machina-sapiens/google-colab-guia-do-iniciante-334d70aad531)",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
cba5a8cdfa04367999a7cb2825679c7e515257c1
| 110,632 |
ipynb
|
Jupyter Notebook
|
static.ipynb
|
Shuhao99/2020-21-UNNC-CS-Final-Year-Project
|
33fa74d2fa43abf4927c7126fb7fc20348e76808
|
[
"MIT"
] | null | null | null |
static.ipynb
|
Shuhao99/2020-21-UNNC-CS-Final-Year-Project
|
33fa74d2fa43abf4927c7126fb7fc20348e76808
|
[
"MIT"
] | null | null | null |
static.ipynb
|
Shuhao99/2020-21-UNNC-CS-Final-Year-Project
|
33fa74d2fa43abf4927c7126fb7fc20348e76808
|
[
"MIT"
] | null | null | null | 183.165563 | 48,144 | 0.881906 |
[
[
[
"# 1. Load Data\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import QuantileTransformer\nfrom time import time\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n\nfrom sklearn.neural_network import MLPRegressor\n\nyears = ['2004', '2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015']\n\ncols = pd.read_csv('data_flag/2004_flag.csv').columns\ndata = pd.DataFrame(columns = cols[1:].append(pd.Index(['YEAR']))) \nfor year_ in years:\n #np.asarray(data['default_flag'].astype(int))\n# flag = np.asarray(.astype(int))\n# print(flag.values())\n data_path = 'data_flag/{year}_flag.csv'.format(year=year_) \n cols = pd.read_csv(data_path).columns\n data_this_year = pd.read_csv(data_path, usecols = cols[1:])\n print(data_this_year['default_flag'].value_counts())\n \n\n\n\n",
"False 1102435\nTrue 26296\nName: default_flag, dtype: int64\nFalse 1625202\nTrue 68249\nName: default_flag, dtype: int64\nFalse 1158824\nTrue 104672\nName: default_flag, dtype: int64\nFalse 1077732\nTrue 143814\nName: default_flag, dtype: int64\nFalse 1090119\nTrue 89993\nName: default_flag, dtype: int64\nFalse 1952676\nTrue 22117\nName: default_flag, dtype: int64\nFalse 1262648\nTrue 9016\nName: default_flag, dtype: int64\nFalse 950706\nTrue 5149\nName: default_flag, dtype: int64\nFalse 1327682\nTrue 4601\nName: default_flag, dtype: int64\nFalse 1296691\nTrue 6488\nName: default_flag, dtype: int64\nFalse 972312\nTrue 9228\nName: default_flag, dtype: int64\nFalse 1340008\nTrue 12646\nName: default_flag, dtype: int64\n"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import QuantileTransformer\nfrom time import time\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n\nfrom sklearn.neural_network import MLPRegressor\n\n#Load data\ndata_list = []\nfor fname in sorted(os.listdir(data_path)):\n subject_data_path = os.path.join(data_path, fname)\n print(subject_data_path)\n\n if not os.path.isfile(subject_data_path): continue\n data_list.append(\n pd.read_csv(\n subject_data_path,\n sep='|', \n header=None,\n names = [\n 'CREDIT_SCORE',\n 'FIRST_PAYMENT_DATE',\n 'FIRST_TIME_HOMEBUYER_FLAG',\n '4','5','6',\n 'NUMBER_OF_UNITS',\n 'OCCUPANCY_STATUS',\n '9',\n 'ORIGINAL_DTI_RATIO',\n 'ORIGINAL_UPB',\n 'ORIGINAL_LTV',\n 'ORIGINAL_INTEREST_RATE',\n 'CHANNEL',\n '15',\n 'PRODUCT_TYPE',\n 'PROPERTY_STATE',\n 'PROPERTY_TYPE',\n '19',\n 'LOAN_SQ_NUMBER',\n 'LOAN_PURPOSE',\n 'ORIGINAL_LOAN_TERM',\n 'NUMBER_OF_BORROWERS',\n '24','25','26'#,'27'#data from every year may have different column number\n #2004-2007: 27 2008: 26 2009: 27\n ],\n usecols=[\n 'CREDIT_SCORE',\n 'FIRST_TIME_HOMEBUYER_FLAG',\n 'NUMBER_OF_UNITS',\n 'OCCUPANCY_STATUS',\n 'ORIGINAL_DTI_RATIO',\n 'ORIGINAL_UPB',\n 'ORIGINAL_LTV',\n 'ORIGINAL_INTEREST_RATE',\n 'CHANNEL',\n 'PROPERTY_TYPE',\n 'LOAN_SQ_NUMBER',\n 'LOAN_PURPOSE',\n 'ORIGINAL_LOAN_TERM',\n 'NUMBER_OF_BORROWERS'\n ],\n dtype={'CREDIT_SCORE':np.float_, \n 'FIRST_TIME_HOMEBUYER_FLAG':np.str, \n 'NUMBER_OF_UNITS':np.int_, \n 'OCCUPANCY_STATUS':np.str,\n 'ORIGINAL_DTI_RATIO':np.float_,\n 'ORIGINAL_UPB':np.float_,\n 'ORIGINAL_LTV':np.float_,\n 'ORIGINAL_INTEREST_RATE':np.float_,\n 'CHANNEL':np.str,\n 'PROPERTY_TYPE':np.str,\n 'LOAN_SQ_NUMBER':np.str,\n 'LOAN_PURPOSE':np.str,\n 'ORIGINAL_LOAN_TERM':np.int_,\n 'NUMBER_OF_BORROWERS':np.int_},\n low_memory=False\n )\n )\ndata = pd.concat(data_list)",
"_____no_output_____"
]
],
[
[
"# Static and Visualise ",
"_____no_output_____"
]
],
[
[
"print(PRODUCT_TYPE.value_counts())",
"FRM 398439\nName: 15, dtype: int64\n"
]
],
[
[
"- **Credit Score**",
"_____no_output_____"
]
],
[
[
"CREDIT_clean = CREDIT_SCORE[CREDIT_SCORE != 9999]\nbin_size = CREDIT_clean.max()-CREDIT_clean.min()\nCREDIT_SCORE_UNKNOWN_RATIO = (CREDIT_SCORE.size-CREDIT_clean.size)/CREDIT_SCORE.size\nplt.figure()\nfigure = plt.hist(CREDIT_clean,bins = bin_size, weights=np.ones(CREDIT_clean.size) / CREDIT_clean.size)\nplt.show\nprint(CREDIT_SCORE_UNKNOWN_RATIO)\n\n",
"0.00025599903623892237\n"
]
],
[
[
"- **First Time Homebuyer Flag**",
"_____no_output_____"
]
],
[
[
"FIRST_TIME_HOMEBUYER_FLAG_Y = (FIRST_TIME_HOMEBUYER_FLAG[FIRST_TIME_HOMEBUYER_FLAG=='Y'].size)/FIRST_TIME_HOMEBUYER_FLAG.size\nFIRST_TIME_HOMEBUYER_FLAG_N = (FIRST_TIME_HOMEBUYER_FLAG[FIRST_TIME_HOMEBUYER_FLAG=='N'].size)/FIRST_TIME_HOMEBUYER_FLAG.size\nFIRST_TIME_HOMEBUYER_FLAG_NG = (FIRST_TIME_HOMEBUYER_FLAG[FIRST_TIME_HOMEBUYER_FLAG=='9'].size)/FIRST_TIME_HOMEBUYER_FLAG.size\n\nprint('FIRST_TIME_HOMEBUYER_FLAG_Y = {}'.format(FIRST_TIME_HOMEBUYER_FLAG_Y))\nprint('FIRST_TIME_HOMEBUYER_FLAG_N = {}'.format(FIRST_TIME_HOMEBUYER_FLAG_N))\nprint('FIRST_TIME_HOMEBUYER_FLAG_NG = {}'.format(FIRST_TIME_HOMEBUYER_FLAG_NG))",
"FIRST_TIME_HOMEBUYER_FLAG_Y = 0.06664508243419946\nFIRST_TIME_HOMEBUYER_FLAG_N = 0.7890266766054528\nFIRST_TIME_HOMEBUYER_FLAG_NG = 0.14432824096034777\n"
]
],
[
[
"- **Number of Units**",
"_____no_output_____"
]
],
[
[
"NUMBER_OF_UNITS_clean = NUMBER_OF_UNITS[NUMBER_OF_UNITS!=99]\nplt.bar(NUMBER_OF_UNITS_clean.value_counts().index,NUMBER_OF_UNITS_clean.value_counts().array)",
"_____no_output_____"
]
],
[
[
"- **State**",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(50,10))\n# dif = np.diff(np.unique(data[16])).min()\n# left_of_first_bin = data[16].min() - float(dif)/2\n# right_of_last_bin = data[16].max() + float(dif)/2\nplt.bar(data[16].value_counts().index,data[16].value_counts().array)\n#print(data[16].value_counts()) #value_counts() shows how many different value in a series use size to see the total number",
"_____no_output_____"
],
[
"#lable = np.asarray(pd.get_dummies(data[2]))",
"_____no_output_____"
]
],
[
[
"# 3. Imputation\n\nUse Mean substitution approach",
"_____no_output_____"
]
],
[
[
"data[0] = data[0].apply(lambda x : CREDIT_clean.mean() if x == 9999 else x)\ndata[9] = data[9].apply(lambda x : CREDIT_clean.mean() if x == 999 else x)\ndata[11] = data[11].apply(lambda x : CREDIT_clean.mean() if x == 999 else x)\n\n",
"_____no_output_____"
]
],
[
[
"- **Prepare input data for Linear Rgression**",
"_____no_output_____"
]
],
[
[
"data.shape\ndata_c = data[[0,9,10,11,21]]\n#data_d = data[[2,6,7,13,15,17,20,22]]\n\nlable_2 = np.asarray(pd.get_dummies(data[2]))\nlable_6 = np.asarray(pd.get_dummies(data[6]))\nlable_7 = np.asarray(pd.get_dummies(data[7]))\nlable_13 = np.asarray(pd.get_dummies(data[13]))\nlable_15 = np.asarray(pd.get_dummies(data[15]))\nlable_17 = np.asarray(pd.get_dummies(data[17]))\nlable_20 = np.asarray(pd.get_dummies(data[20]))\nlable_22 = np.asarray(pd.get_dummies(data[22]))\n\ninput_array = np.c_[data_c.to_numpy(),lable_2,lable_6,lable_7,lable_13,lable_15,lable_17,lable_20,lable_22] \noutput_array = data[12].to_numpy()\nprint(input_array.shape)",
"(398439, 32)\n"
],
[
"\n# Split the data into training/testing sets\nX_train = input_array[:-80000]\nX_test = input_array[-80000:]\n\n# Split the targets into training/testing sets\ny_train = output_array[:-80000]\ny_test = output_array[-80000:]\n\n# Create linear regression object\nregr = linear_model.LinearRegression()\n\n# Train the model using the training sets\nregr.fit(X_train, y_train)\n\n# Make predictions using the testing set\ny_pred = regr.predict(X_test)\n\n# The coefficients\nprint('Coefficients: \\n', regr.coef_)\n# The mean squared error\nprint('Mean squared error: %.2f'\n % mean_squared_error(y_test, y_pred))\n# The coefficient of determination: 1 is perfect prediction\nprint('Coefficient of determination: %.2f'\n % r2_score(y_test, y_pred))\n\n# Plot outputs\naxis = np.arange(80000)\nsize = np.linspace(0.5,0.5,80000)\nplt.scatter(axis, y_test,s=size, color='red',marker='x')\nplt.scatter(axis, y_pred, s = size, color='blue')\n\nplt.show()\n",
"Coefficients: \n [-2.21163886e-03 2.03804182e-05 -6.48855556e-07 3.45320839e-03\n 1.94234896e-03 1.63921030e-02 -1.56152885e-02 -7.76814512e-04\n 9.54392055e-03 4.98707097e-02 1.02623255e-02 -2.64981272e-02\n -4.31788286e-02 3.02724002e-01 -1.78134259e-01 -1.24589743e-01\n 8.18469564e-02 2.95272465e-02 -7.97538337e-02 -3.16203692e-02\n 8.32667268e-17 -7.29734151e-02 -7.55417418e-02 3.20379862e-01\n -1.07738055e-01 -6.41266499e-02 -5.49931937e-03 -4.65906997e-02\n 5.20900191e-02 -6.93070046e-03 -6.01321266e-02 6.70628270e-02]\nMean squared error: 0.18\nCoefficient of determination: 0.15\n"
],
[
"#try NN\nX_train, X_test, y_train, y_test = train_test_split(input_array, output_array, test_size=0.2,\n random_state=0)\n\nprint(\"Training MLPRegressor...\")\ntic = time()\nest = make_pipeline(QuantileTransformer(),\n MLPRegressor(hidden_layer_sizes=(50, 50),\n learning_rate_init=0.01,\n early_stopping=True))\nest.fit(X_train, y_train)\nprint(\"done in {:.3f}s\".format(time() - tic))\nprint(\"Test R2 score: {:.2f}\".format(est.score(X_test, y_test)))",
"Training MLPRegressor...\ndone in 115.203s\nTest R2 score: 0.44\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cba5b34aa9c393321c565f446869c2ec2dcb259a
| 8,329 |
ipynb
|
Jupyter Notebook
|
notebooks/ankitesh-devlog/05_climateInv_classification_data_generator.ipynb
|
ankitesh97/CBRAIN-CAM
|
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
|
[
"MIT"
] | null | null | null |
notebooks/ankitesh-devlog/05_climateInv_classification_data_generator.ipynb
|
ankitesh97/CBRAIN-CAM
|
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
|
[
"MIT"
] | null | null | null |
notebooks/ankitesh-devlog/05_climateInv_classification_data_generator.ipynb
|
ankitesh97/CBRAIN-CAM
|
cec46f1e5736aeedde480bdc0754c00bf0e06cf5
|
[
"MIT"
] | null | null | null | 34.995798 | 127 | 0.531036 |
[
[
[
"from cbrain.imports import *\nfrom cbrain.utils import *\nfrom cbrain.normalization import *\nimport h5py\nfrom sklearn.preprocessing import OneHotEncoder",
"_____no_output_____"
],
[
"class DataGeneratorClassification(tf.keras.utils.Sequence):\n def __init__(self, data_fn, input_vars, output_vars, percentile_path, data_name,\n norm_fn=None, input_transform=None, output_transform=None,\n batch_size=1024, shuffle=True, xarray=False, var_cut_off=None, normalize_flag=True, bin_size=100):\n # Just copy over the attributes\n self.data_fn, self.norm_fn = data_fn, norm_fn\n self.input_vars, self.output_vars = input_vars, output_vars\n self.batch_size, self.shuffle = batch_size, shuffle\n self.bin_size = bin_size\n self.percentile_bins = load_pickle(percentile_path)['Percentile'][data_name]\n self.enc = OneHotEncoder(sparse=False)\n classes = np.arange(self.bin_size+2)\n self.enc.fit(classes.reshape(-1,1))\n # Open datasets\n self.data_ds = xr.open_dataset(data_fn)\n if norm_fn is not None: self.norm_ds = xr.open_dataset(norm_fn)\n # Compute number of samples and batches\n self.n_samples = self.data_ds.vars.shape[0]\n self.n_batches = int(np.floor(self.n_samples) / self.batch_size)\n\n # Get input and output variable indices\n self.input_idxs = return_var_idxs(self.data_ds, input_vars, var_cut_off)\n self.output_idxs = return_var_idxs(self.data_ds, output_vars)\n self.n_inputs, self.n_outputs = len(self.input_idxs), len(self.output_idxs)\n \n # Initialize input and output normalizers/transformers\n if input_transform is None:\n self.input_transform = Normalizer()\n elif type(input_transform) is tuple:\n ## normalize flag added by Ankitesh\n self.input_transform = InputNormalizer(\n self.norm_ds,normalize_flag, input_vars, input_transform[0], input_transform[1], var_cut_off)\n else:\n self.input_transform = input_transform # Assume an initialized normalizer is passed\n \n \n if output_transform is None:\n self.output_transform = Normalizer()\n elif type(output_transform) is dict:\n self.output_transform = DictNormalizer(self.norm_ds, output_vars, output_transform)\n else:\n self.output_transform = output_transform # Assume an initialized normalizer is passed\n\n # Now close the xarray file and load it as an h5 file instead\n # This significantly speeds up the reading of the data...\n if not xarray:\n self.data_ds.close()\n self.data_ds = h5py.File(data_fn, 'r')\n \n def __len__(self):\n return self.n_batches\n \n # TODO: Find a better way to implement this, currently it is the hardcoded way.\n def _transform_to_one_hot(self,Y):\n '''\n return shape = batch_size X 64 X bin_size\n '''\n\n Y_trans = []\n out_vars = ['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS']\n var_dict = {}\n var_dict['PHQ'] = Y[:,:30]\n var_dict['TPHYSTND'] = Y[:,30:60]\n var_dict['FSNT'] = Y[:,60]\n var_dict['FSNS'] = Y[:,61]\n var_dict['FLNT'] = Y[:,62]\n var_dict['FLNS'] = Y[:,63]\n perc = self.percentile_bins\n for var in out_vars[:2]:\n all_levels_one_hot = []\n for ilev in range(30):\n bin_index = np.digitize(var_dict[var][:,ilev],perc[var][ilev])\n one_hot = self.enc.transform(bin_index.reshape(-1,1))\n all_levels_one_hot.append(one_hot)\n var_one_hot = np.stack(all_levels_one_hot,axis=1) \n Y_trans.append(var_one_hot)\n for var in out_vars[2:]:\n bin_index = np.digitize(var_dict[var][:], perc[var])\n one_hot = self.enc.transform(bin_index.reshape(-1,1))[:,np.newaxis,:]\n Y_trans.append(one_hot)\n return np.concatenate(Y_trans,axis=1)\n \n \n \n \n def __getitem__(self, index):\n # Compute start and end indices for batch\n start_idx = index * self.batch_size\n end_idx = start_idx + self.batch_size\n\n # Grab batch from data\n batch = self.data_ds['vars'][start_idx:end_idx]\n # Split into inputs and outputs\n X = batch[:, self.input_idxs]\n Y = batch[:, self.output_idxs]\n\n # Normalize\n X = self.input_transform.transform(X)\n Y = self.output_transform.transform(Y) #shape batch_size X 64 \n Y = self._transform_to_one_hot(Y)\n return X, Y\n\n def on_epoch_end(self):\n self.indices = np.arange(self.n_batches)\n if self.shuffle: np.random.shuffle(self.indices)",
"_____no_output_____"
],
[
"scale_dict = load_pickle('/export/nfs0home/ankitesg/CBrain_project/CBRAIN-CAM/nn_config/scale_dicts/009_Wm2_scaling.pkl')",
"_____no_output_____"
],
[
"TRAINFILE = 'CI_SP_M4K_train_shuffle.nc'\nNORMFILE = 'CI_SP_M4K_NORM_norm.nc'\ndata_path = '/scratch/ankitesh/data/'",
"_____no_output_____"
],
[
"data_gen = DataGeneratorClassification(\n data_fn=f'{data_path}{TRAINFILE}', \n input_vars= ['QBP','TBP','PS', 'SOLIN', 'SHFLX', 'LHFLX'], \n output_vars=['PHQ','TPHYSTND','FSNT', 'FSNS', 'FLNT', 'FLNS'], \n percentile_path='/export/nfs0home/ankitesg/data/percentile_data.pkl', \n data_name = 'M4K',\n input_transform = ('mean', 'maxrs'),\n output_transform = scale_dict,\n norm_fn = f'{data_path}{NORMFILE}',\n batch_size=1024\n)",
"_____no_output_____"
],
[
"data_gen[0][0].shape",
"_____no_output_____"
],
[
"data_gen[0][1].shape",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba5c5ba6a44c3233eb8eb5e9fa97cd71b5d2d14
| 69,317 |
ipynb
|
Jupyter Notebook
|
updating_map.ipynb
|
YoungestSalon/multiplex
|
dcc7c5260ac4620ca92c1eb12611841e19baf5c1
|
[
"MIT"
] | 1 |
2018-09-04T14:07:50.000Z
|
2018-09-04T14:07:50.000Z
|
updating_map.ipynb
|
YoungestSalon/multiplex
|
dcc7c5260ac4620ca92c1eb12611841e19baf5c1
|
[
"MIT"
] | 5 |
2018-08-09T05:30:03.000Z
|
2018-08-16T04:56:09.000Z
|
updating_map.ipynb
|
YoungestSalon/multiplex
|
dcc7c5260ac4620ca92c1eb12611841e19baf5c1
|
[
"MIT"
] | 7 |
2018-08-03T06:32:46.000Z
|
2018-08-16T02:40:51.000Z
| 59.448542 | 21,852 | 0.582556 |
[
[
[
"import warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"import pandas as pd\nfrom plotnine import *",
"_____no_output_____"
],
[
"%ls",
" C 드라이브의 볼륨에는 이름이 없습니다.\n 볼륨 일련 번호: 4820-D44C\n\n C:\\Users\\채송이\\data\\M3 디렉터리\n\n2018-08-16 오후 12:22 <DIR> .\n2018-08-16 오후 12:22 <DIR> ..\n2018-08-16 오후 12:22 <DIR> .ipynb_checkpoints\n2018-08-08 오후 12:52 517 MALL.csv\n2018-08-06 오후 06:25 55,924 multiprex.csv\n2018-08-08 오후 01:53 24,742 Shoppingmall_code.ipynb\n2018-08-16 오후 12:22 7,638 shoppingmall_info_template.csv\n2018-08-13 오후 04:54 10,377 shoppingmall_info_template.xlsx\n2018-08-14 오전 10:43 25,431 teampl_step1.ipynb\n2018-08-14 오후 02:09 464 test.csv\n2018-08-16 오후 12:19 64,748 updating_map.ipynb\n2018-08-13 오후 04:58 105,759 전국 멀티플렉스 위치보기.ipynb\n 9개 파일 295,600 바이트\n 3개 디렉터리 57,344,536,576 바이트 남음\n"
],
[
"test = pd.read_csv('shoppingmall_info_template.csv', encoding='cp949')\ntest.shape",
"_____no_output_____"
],
[
"test.head()",
"_____no_output_____"
],
[
"test.columns",
"_____no_output_____"
],
[
"test.head()",
"_____no_output_____"
],
[
"test['Category'] = test['Name'].str.extract(r'^(스타필드|롯데몰)\\s.*')\ntest",
"_____no_output_____"
],
[
"import folium\ngeo_df = test\n\nmap = folium.Map(location=[geo_df['Latitude'].mean(), geo_df['Longitude'].mean()], zoom_start=17, tiles='stamenwatercolor')\n\nfor i, row in geo_df.iterrows():\n mall_name = row['Name'] + '-' + row['Address']\n if row['Category'] == '롯데몰':\n icon = folium.Icon(color='red',icon='info-sign')\n elif row['Category'] == '스타필드':\n icon = folium.Icon(color='blue',icon='info-sign')\n else:\n icon = folium.Icon(color='green',icon='info-sign')\n\n folium.Marker(\n [row['Latitude'], row['Longitude']], \n popup=mall_name,\n icon=icon\n ).add_to(map)\n\n# for n in geo_df.index:\n# mall_name = geo_df['Name'][n] \\\n# + '-' + geo_df['Address'][n]\n \n# folium.Marker([geo_df['latitude'][n], \n# geo_df['longitude'][n]], \n# popup=mall_name,\n# icon=folium.Icon(color='pink',icon='info-sign'), \n# ).add_to(map)\n\n# folium.Marker(\n# location=[37.545614, 127.224064],\n# popup = mall_name,\n# icon=folium.Icon(icon='cloud')\n# ).add_to(map)\n# folium.Marker(\n# location=[37.511683, 127.059108],\n# popup = mall_name,\n# icon=folium.Icon(icon='cloud')\n# ).add_to(map)\nmap\n",
"_____no_output_____"
],
[
"import folium\ngeo_df = test\n\nmap = folium.Map(location=[geo_df['Latitude'].mean(), geo_df['Longitude'].mean()], zoom_start=6, tiles='stamenwatercolor')\n\nfor i, row in geo_df.iterrows():\n mall_name = row['Name'] + '-' + row['Address']\n if row['Category'] == '롯데몰':\n icon = folium.Icon(color='red',icon='info-sign')\n elif row['Category'] == '스타필드':\n icon = folium.Icon(color='blue',icon='info-sign')\n else:\n icon = folium.Icon(color='green',icon='info-sign')\n\n folium.Marker(\n [row['Latitude'], row['Longitude']], \n popup=mall_name,\n icon=icon\n ).add_to(map)\n\n \nmap.choropleth(\n geo_data = test,\n name='choropleth',\n data = test,\n columns=['Traffic_no'],\n key_on='feature.id',\n fill_color='Set1',\n fill_opacity=0.7,\n line_opacity=0.2,\n)\nfolium.LayerControl().add_to(map)\n\n\n",
"_____no_output_____"
],
[
"test['Traffic_no'] # 교통 가능 수",
"_____no_output_____"
],
[
"import plotly.plotly as py\n\nmap = folium.Map(\n location=[geo_df['Latitude'].mean(),\n geo_df['Longitude'].mean()],\n zoom_start=6,\n tiles='stamenwatercolor')\n\nmap.choropleth(\n geo_data = test,\n name='choropleth',\n data = test,\n columns=['Traffic_no'],\n key_on='feature.id',\n fill_color='Set1',\n fill_opacity=0.7,\n line_opacity=0.2,\n)\nfolium.LayerControl().add_to(map)\n\n\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba5d4fed803cf172ce0a3a42d1db4c2932c0cba
| 490,789 |
ipynb
|
Jupyter Notebook
|
FlowersClassifier.ipynb
|
gsuemith/Flower-Species-Classifier
|
b4230dbfd392f636d6acf874024943060d47f736
|
[
"MIT"
] | null | null | null |
FlowersClassifier.ipynb
|
gsuemith/Flower-Species-Classifier
|
b4230dbfd392f636d6acf874024943060d47f736
|
[
"MIT"
] | null | null | null |
FlowersClassifier.ipynb
|
gsuemith/Flower-Species-Classifier
|
b4230dbfd392f636d6acf874024943060d47f736
|
[
"MIT"
] | null | null | null | 723.877581 | 219,652 | 0.943377 |
[
[
[
"# Developing an AI application\n\nGoing forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. \n\nIn this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using [this dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html) of 102 flower categories, you can see a few examples below. \n\n<img src='assets/Flowers.png' width=500px>\n\nThe project is broken down into multiple steps:\n\n* Load and preprocess the image dataset\n* Train the image classifier on your dataset\n* Use the trained classifier to predict image content\n\nWe'll lead you through each part which you'll implement in Python.\n\nWhen you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.\n\nFirst up is importing the packages you'll need. It's good practice to keep all the imports at the beginning of your code. As you work through this notebook and find you need to import a package, make sure to add the import up here.",
"_____no_output_____"
]
],
[
[
"# Imports here\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models",
"_____no_output_____"
]
],
[
[
"## Load the data\n\nHere you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks.\n\nThe validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to resize then crop the images to the appropriate size.\n\nThe pre-trained networks you'll use were trained on the ImageNet dataset where each color channel was normalized separately. For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`, calculated from the ImageNet images. These values will shift each color channel to be centered at 0 and range from -1 to 1.\n ",
"_____no_output_____"
]
],
[
[
"data_dir = '../flowers'\ntrain_dir = data_dir + '/train'\nvalid_dir = data_dir + '/valid'\ntest_dir = data_dir + '/test'",
"_____no_output_____"
],
[
"means = [0.485, 0.456, 0.406]\nstdvs = [0.229, 0.224, 0.225]\n# TODO: Define your transforms for the training, validation, and testing sets\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(means,stdvs)])\n\nvalid_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(means,stdvs)])\n\ntest_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(means,stdvs)])\n\n# TODO: Load the datasets with ImageFolder\ntrain_data = datasets.ImageFolder(train_dir, transform=train_transforms)\n\nvalid_data = datasets.ImageFolder(valid_dir, transform=valid_transforms)\n\ntest_data = datasets.ImageFolder(test_dir, transform=test_transforms)\n# TODO: Using the image datasets and the trainforms, define the dataloaders\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\n\nvalidloader = torch.utils.data.DataLoader(valid_data, batch_size=64)\n\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)",
"_____no_output_____"
]
],
[
[
"### Label mapping\n\nYou'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categories to the actual names of the flowers.",
"_____no_output_____"
]
],
[
[
"import json\n\nwith open('cat_to_name.json', 'r') as f:\n cat_to_name = json.load(f)\n \ncategories = len(cat_to_name)",
"_____no_output_____"
]
],
[
[
"# Building and training the classifier\n\nNow that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features.\n\nWe're going to leave this part up to you. Refer to [the rubric](https://review.udacity.com/#!/rubrics/1663/view) for guidance on successfully completing this section. Things you'll need to do:\n\n* Load a [pre-trained network](http://pytorch.org/docs/master/torchvision/models.html) (If you need a starting point, the VGG networks work great and are straightforward to use)\n* Define a new, untrained feed-forward network as a classifier, using ReLU activations and dropout\n* Train the classifier layers using backpropagation using the pre-trained network to get the features\n* Track the loss and accuracy on the validation set to determine the best hyperparameters\n\nWe've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!\n\nWhen training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right. Make sure to try different hyperparameters (learning rate, units in the classifier, epochs, etc) to find the best model. Save those hyperparameters to use as default values in the next part of the project.\n\nOne last important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to\nGPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module.\n\n**Note for Workspace users:** If your network is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. Typically this happens with wide dense layers after the convolutional layers. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with `ls -lh`), you should reduce the size of your hidden layers and train again.",
"_____no_output_____"
]
],
[
[
"# TODO: Build and train your network\nmodel = models.densenet161(pretrained=True)\n\nfor param in model.parameters():\n param.requires_grad = False\n\nfrom collections import OrderedDict\nclassifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(2208, 512)),\n ('relu1', nn.ReLU()),\n ('drop1', nn.Dropout(0.2)),\n ('fc2', nn.Linear(512, 256)),\n ('relu2', nn.ReLU()),\n ('drop2', nn.Dropout(0.2)),\n ('fc3', nn.Linear(256, categories)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n \nmodel.classifier = classifier",
"_____no_output_____"
],
[
"criterion = nn.NLLLoss()\noptimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")",
"_____no_output_____"
],
[
"model.to(device)\n\nepochs = 5\nsteps = 0\nevery_step = 50\n\nrunning_loss, valid_loss = 0,0\n\nfor e in range(epochs):\n for images, labels in trainloader:\n images, labels = images.to(device), labels.to(device)\n \n optimizer.zero_grad()\n log_ps = model.forward(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n running_loss += loss.item()\n optimizer.step()\n \n steps += 1\n if steps % every_step == 0:\n \n valid_loss = 0\n accuracy = 0\n \n with torch.no_grad():\n \n model.eval()\n for images, labels in validloader:\n images, labels = images.to(device), labels.to(device)\n \n log_ps = model.forward(images)\n ps = torch.exp(log_ps)\n valid_loss += criterion(log_ps, labels).item()\n\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n print(f\"Epoch {e + 1}/{epochs}.. \"\n f\"Train loss: {running_loss/every_step:.3f}.. \"\n f\"Test loss: {valid_loss/len(validloader):.3f}.. \"\n f\"Test accuracy: {accuracy/len(validloader):.3f}\")\n running_loss = 0\n \n model.train()",
"Epoch 1/5.. Train loss: 4.296.. Test loss: 3.375.. Test accuracy: 0.238\nEpoch 1/5.. Train loss: 2.840.. Test loss: 1.730.. Test accuracy: 0.546\nEpoch 2/5.. Train loss: 1.997.. Test loss: 1.227.. Test accuracy: 0.671\nEpoch 2/5.. Train loss: 1.700.. Test loss: 0.923.. Test accuracy: 0.760\nEpoch 3/5.. Train loss: 1.442.. Test loss: 0.765.. Test accuracy: 0.790\nEpoch 3/5.. Train loss: 1.332.. Test loss: 0.713.. Test accuracy: 0.810\nEpoch 4/5.. Train loss: 1.200.. Test loss: 0.659.. Test accuracy: 0.815\nEpoch 4/5.. Train loss: 1.129.. Test loss: 0.622.. Test accuracy: 0.846\nEpoch 5/5.. Train loss: 1.141.. Test loss: 0.551.. Test accuracy: 0.857\nEpoch 5/5.. Train loss: 1.000.. Test loss: 0.533.. Test accuracy: 0.846\n"
]
],
[
[
"## Testing your network\n\nIt's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way you did validation. You should be able to reach around 70% accuracy on the test set if the model has been trained well.",
"_____no_output_____"
]
],
[
[
"# TODO: Do validation on the test set\nmodel.to(device)\nmodel.eval()\naccuracy = 0\n\nwith torch.no_grad():\n for images, labels in testloader:\n images, labels = images.to(device), labels.to(device)\n \n log_ps = model.forward(images)\n ps = torch.exp(log_ps)\n \n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n\nmodel.train()\nprint(f\"Test accuracy: {accuracy/len(testloader):.3f}\")",
"Test accuracy: 0.850\n"
]
],
[
[
"## Save the checkpoint\n\nNow that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as an attribute which makes inference easier later on.\n\n```model.class_to_idx = image_datasets['train'].class_to_idx```\n\nRemember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, `optimizer.state_dict`. You'll likely want to use this trained model in the next part of the project, so best to save it now.",
"_____no_output_____"
]
],
[
[
"# TODO: Save the checkpoint \nmodel.class_to_idx = train_data.class_to_idx\ncheckpoint = {'input_size': 2208,\n 'output_size': categories,\n 'state_dict': model.state_dict(),\n 'epochs': 5,\n 'optimizer_state': optimizer.state_dict(),\n 'class_to_idx': model.class_to_idx,\n 'hidden_layers':[512, 256]}\n\ntorch.save(checkpoint, 'checkpoint.pth')",
"_____no_output_____"
]
],
[
[
"## Loading the checkpoint\n\nAt this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network.",
"_____no_output_____"
]
],
[
[
"# TODO: Write a function that loads a checkpoint and rebuilds the model\ndef load_checkpoint(filepath):\n model = models.densenet161()\n \n checkpoint = torch.load(filepath)\n \n input = checkpoint['input_size']\n hidden_layers = checkpoint['hidden_layers']\n output = checkpoint['output_size']\n \n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(input, hidden_layers[0])),\n ('relu1', nn.ReLU()),\n ('drop1', nn.Dropout(0.2)),\n ('fc2', nn.Linear(hidden_layers[0], hidden_layers[1])),\n ('relu2', nn.ReLU()),\n ('drop2', nn.Dropout(0.2)),\n ('fc3', nn.Linear(hidden_layers[1], output)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n \n model.classifier = classifier\n model.load_state_dict(checkpoint['state_dict'])\n model.class_to_idx = checkpoint['class_to_idx']\n \n optimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\n optimizer.load_state_dict(checkpoint['optimizer_state'])\n \n return model",
"_____no_output_____"
],
[
"model = load_checkpoint('checkpoint.pth')",
"_____no_output_____"
]
],
[
[
"# Inference for classification\n\nNow you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like \n\n```python\nprobs, classes = predict(image_path, model)\nprint(probs)\nprint(classes)\n> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]\n> ['70', '3', '45', '62', '55']\n```\n\nFirst you'll need to handle processing the input image such that it can be used in your network. \n\n## Image Preprocessing\n\nYou'll want to use `PIL` to load the image ([documentation](https://pillow.readthedocs.io/en/latest/reference/Image.html)). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training. \n\nFirst, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the [`thumbnail`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) or [`resize`](http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.thumbnail) methods. Then you'll need to crop out the center 224x224 portion of the image.\n\nColor channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to convert the values. It's easiest with a Numpy array, which you can get from a PIL image like so `np_image = np.array(pil_image)`.\n\nAs before, the network expects the images to be normalized in a specific way. For the means, it's `[0.485, 0.456, 0.406]` and for the standard deviations `[0.229, 0.224, 0.225]`. You'll want to subtract the means from each color channel, then divide by the standard deviation. \n\nAnd finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using [`ndarray.transpose`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.transpose.html). The color channel needs to be first and retain the order of the other two dimensions.",
"_____no_output_____"
]
],
[
[
"from PIL import Image\nimport numpy as np\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n \n # TODO: Process a PIL image for use in a PyTorch model\n size = (256,256)\n image = image.resize(size)\n image = image.crop((16,16,16 + 224,16 + 224))\n \n np_image = np.array(image).astype('float64')/255\n np_image -= means\n np_image /= stdvs\n \n np_image = np_image.transpose((2,1,0))\n \n return np_image\n \nim = Image.open(test_dir + '/10/image_07090.jpg')\nimshow(process_image(im));",
"_____no_output_____"
]
],
[
[
"To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions).",
"_____no_output_____"
]
],
[
[
"def imshow(image, ax=None, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n \n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n \n ax.imshow(image)\n \n return ax",
"_____no_output_____"
]
],
[
[
"## Class Prediction\n\nOnce you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.\n\nTo get the top $K$ largest values in a tensor use [`x.topk(k)`](http://pytorch.org/docs/master/torch.html#torch.topk). This method returns both the highest `k` probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using `class_to_idx` which hopefully you added to the model or from an `ImageFolder` you used to load the data ([see here](#Save-the-checkpoint)). Make sure to invert the dictionary so you get a mapping from index to class as well.\n\nAgain, this method should take a path to an image and a model checkpoint, then return the probabilities and classes.\n\n```python\nprobs, classes = predict(image_path, model)\nprint(probs)\nprint(classes)\n> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]\n> ['70', '3', '45', '62', '55']\n```",
"_____no_output_____"
]
],
[
[
"def predict(image_path, model, topk=5):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n \n model.eval()\n model.to(device)\n class_id = model.class_to_idx\n \n # TODO: Implement the code to predict the class from an image file\n image = Image.open(image_path)\n image = process_image(image)\n image = torch.from_numpy(image)\n image = image.float().cuda()\n image.to(device)\n \n with torch.no_grad():\n probs, classes = torch.exp(model(image.unsqueeze_(0))).topk(topk, dim = 1)\n \n probs = probs.cpu().numpy()[0,:]\n classes = classes.cpu().numpy()[0,:]\n classes = [key for key in class_id.__iter__() if class_id[key] in classes]\n \n return probs, classes\n\nprobs, classes = predict(test_dir + '/10/image_07090.jpg', model)\nprint(probs)\nprint(classes)",
"[0.42871642 0.3713704 0.1332812 0.02214074 0.02210167]\n['10', '14', '25', '29', '35']\n"
]
],
[
[
"## Sanity Checking\n\nNow that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:\n\n<img src='assets/inference_example.png' width=300px>\n\nYou can convert from the class integer encoding to actual flower names with the `cat_to_name.json` file (should have been loaded earlier in the notebook). To show a PyTorch tensor as an image, use the `imshow` function defined above.",
"_____no_output_____"
]
],
[
[
"# TODO: Display an image along with the top 5 classes\n\nimshow(process_image(Image.open(test_dir + '/10/image_07090.jpg')), title = cat_to_name['10']);\nfig, ax1 = plt.subplots(figsize=(6,9))\n\nax1.barh(np.arange(5), probs)\nax1.set_aspect(0.1)\nax1.set_yticks(np.arange(5))\nax1.set_yticklabels([cat_to_name[i] for i in classes])",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba5e296625306185f64d548e50356fde0d2bcca
| 32,262 |
ipynb
|
Jupyter Notebook
|
Linked_List/Doubly_Linked_lists_Implelementaion.ipynb
|
pdx97/Python_Data_Structures_and_Algorithms_Implementations
|
898af6dce4fb5882145b1c2ce3f2d19e36a27bce
|
[
"MIT"
] | 2 |
2021-05-10T10:32:55.000Z
|
2021-05-11T10:18:11.000Z
|
Linked_List/Doubly_Linked_lists_Implelementaion.ipynb
|
pdx97/Python_Data_Structures_and_Algorithms_Implementations
|
898af6dce4fb5882145b1c2ce3f2d19e36a27bce
|
[
"MIT"
] | null | null | null |
Linked_List/Doubly_Linked_lists_Implelementaion.ipynb
|
pdx97/Python_Data_Structures_and_Algorithms_Implementations
|
898af6dce4fb5882145b1c2ce3f2d19e36a27bce
|
[
"MIT"
] | null | null | null | 96.304478 | 11,688 | 0.81393 |
[
[
[
"<h3>Implementation Of Doubly Linked List in Python</h3>\n<p> It is similar to Single Linked List but the only Difference lies that it where in Single Linked List we had a link to the next data element ,In Doubly Linked List we also have the link to previous data element with addition to next link</p>\n<ul> <b>It has three parts</b> \n <li> Data Part :This stores the data element of the Node and also consists the reference of the address of the next and previous element </li>\n <li>Next :This stores the address of the next pointer via links</li>\n <li>Previous :This stores the address of the previous element/ pointer via links </li>\n \n </ul>",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DoublyLinkedList.png',width=800, height=400)\n#save the images from github to your local machine and then give the absolute path of the image ",
"_____no_output_____"
],
[
"class Node: # All the operation are similar to Single Linked List with just an addition of Previous which points towards the Prev address via links\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\n\nclass Double_LL():\n def __init__(self):\n self.head = None\n\n def print_forward(self):\n if self.head is None:\n print(\"Linked List is empty\")\n return\n\n itr = self.head\n llstr = ''\n while itr:\n llstr += str(itr.data) + ' --> '\n itr = itr.next\n print(llstr)\n\n def print_backward(self):\n if self.head is None:\n print(\"Linked list is empty\")\n return\n\n last_node = self.get_last_node()\n itr = last_node\n llstr = ''\n while itr:\n llstr += itr.data + '-->'\n itr = itr.prev\n print(\"Link list in reverse: \", llstr)\n\n def get_last_node(self):\n itr = self.head\n while itr.next:\n itr = itr.next\n\n return itr\n\n def get_length(self):\n count = 0\n itr = self.head\n while itr:\n count += 1\n itr = itr.next\n\n return count\n\n def insert_at_begining(self, data):\n if self.head == None:\n node = Node(data, self.head, None)\n self.head = node\n else:\n node = Node(data, self.head, None)\n self.head.prev = node\n self.head = node\n\n def insert_at_end(self, data):\n if self.head is None:\n self.head = Node(data, None, None)\n return\n\n itr = self.head\n\n while itr.next:\n itr = itr.next\n\n itr.next = Node(data, None, itr)\n\n def insert_at(self, index, data):\n if index < 0 or index > self.get_length():\n raise Exception(\"Invalid Index\")\n\n if index == 0:\n self.insert_at_begining(data)\n return\n\n count = 0\n itr = self.head\n while itr:\n if count == index - 1:\n node = Node(data, itr.next, itr)\n if node.next:\n node.next.prev = node\n itr.next = node\n break\n\n itr = itr.next\n count += 1\n\n def remove_at(self, index):\n if index < 0 or index >= self.get_length():\n raise Exception(\"Invalid Index\")\n\n if index == 0:\n self.head = self.head.next\n self.head.prev = None\n return\n\n count = 0\n itr = self.head\n while itr:\n if count == index:\n itr.prev.next = itr.next\n if itr.next:\n itr.next.prev = itr.prev\n break\n\n itr = itr.next\n count += 1\n\n def insert_values(self, data_list):\n self.head = None\n for data in data_list:\n self.insert_at_end(data)",
"_____no_output_____"
],
[
"from IPython.display import Image \nImage(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DLL_insertion_at_beginning.png',width=800, height=400)\n#save the images from github to your local machine and then give the absolute path of the image ",
"_____no_output_____"
]
],
[
[
"<p> Insertion at Beginning</p>",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(filename='C:/Users/prakhar/Desktop/Python_Data_Structures_and_Algorithms_Implementations/Images/DLL_insertion.png',width=800, height=400)\n#save the images from github to your local machine and then give the absolute path of the image ",
"_____no_output_____"
]
],
[
[
"<p>Inserting Node at Index</p>",
"_____no_output_____"
]
],
[
[
"\nif __name__ == '__main__':\n ll = Double_LL()\n ll.insert_values([\"banana\", \"mango\", \"grapes\", \"orange\"])\n ll.print_forward()\n ll.print_backward()\n ll.insert_at_end(\"figs\")\n ll.print_forward()\n ll.insert_at(0, \"jackfruit\")\n ll.print_forward()\n ll.insert_at(6, \"dates\")\n ll.print_forward()\n ll.insert_at(2, \"kiwi\")\n ll.print_forward()",
"banana --> mango --> grapes --> orange --> \nLink list in reverse: orange-->grapes-->mango-->banana-->\nbanana --> mango --> grapes --> orange --> figs --> \njackfruit --> banana --> mango --> grapes --> orange --> figs --> \njackfruit --> banana --> mango --> grapes --> orange --> figs --> dates --> \njackfruit --> banana --> kiwi --> mango --> grapes --> orange --> figs --> dates --> \n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cba5efff92340deeaa2f1ec65bc15ffc7850290f
| 176,916 |
ipynb
|
Jupyter Notebook
|
Codes/02. Facebook Data Analysis/04. Platform/FB Analysis - Platform.ipynb
|
debarunpal/digital-marketing-campaign-analytics
|
75445247f835c57f045671d6ff9b15cd33df213f
|
[
"Apache-2.0"
] | 1 |
2021-02-07T02:57:49.000Z
|
2021-02-07T02:57:49.000Z
|
Codes/02. Facebook Data Analysis/04. Platform/FB Analysis - Platform.ipynb
|
debarunpal/digital-marketing-campaign-analytics
|
75445247f835c57f045671d6ff9b15cd33df213f
|
[
"Apache-2.0"
] | null | null | null |
Codes/02. Facebook Data Analysis/04. Platform/FB Analysis - Platform.ipynb
|
debarunpal/digital-marketing-campaign-analytics
|
75445247f835c57f045671d6ff9b15cd33df213f
|
[
"Apache-2.0"
] | null | null | null | 100.178935 | 61,248 | 0.772728 |
[
[
[
"#import libraries\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(font_scale = 1.2, style = 'darkgrid')\n\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
],
[
"#change display into using full screen\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))",
"_____no_output_____"
],
[
"#import .csv file\ndata = pd.read_csv('FB_data_platform.csv')",
"_____no_output_____"
]
],
[
[
"# 1. Data Exploration & Cleaning",
"_____no_output_____"
],
[
"### 1. Have a first look at data",
"_____no_output_____"
]
],
[
[
"data.head()",
"_____no_output_____"
],
[
"#Consider only those records where amount spent > 0\ndata = data[(data['Amount spent (INR)'] > 0)]",
"_____no_output_____"
],
[
"data.shape",
"_____no_output_____"
]
],
[
[
"### 2. Drop Columns that are extra",
"_____no_output_____"
]
],
[
[
"#We see that Reporting Starts and Reporting Ends are additional columns which we don't require. So we drop them\ndata.drop(['Reporting ends','Reporting starts'],axis = 1, inplace = True)",
"_____no_output_____"
],
[
"#look at the data again\ndata.head()",
"_____no_output_____"
],
[
"#check rows and columns in data\ndata.shape",
"_____no_output_____"
]
],
[
[
"#### So, there are 62 rows and 14 columns in the data",
"_____no_output_____"
],
[
"### 3. Deal with Null Values",
"_____no_output_____"
]
],
[
[
"#let's look if any column has null values\ndata.isnull().sum()",
"_____no_output_____"
]
],
[
[
"#### From this we can infer that some columns have Null values (basically blank). Let's look at them:\n**1. Results & Result Type:** This happened when there was no conversion (Result).\n\n**2. Result rate, Cost per result:** As both these metrics depend on Result, so these are also blank. \n\nThis was bound to happen because not every single day and every ad got a result (conversion). **So it is safe to replace all nulls in Results and Result rate column with 0.**",
"_____no_output_____"
]
],
[
[
"#Fill all blanks in Results with 0\ndata['Results'] = data['Results'].fillna(0)\ndata['Result rate'] = data['Result rate'].fillna(0)",
"_____no_output_____"
],
[
"#check how many nulls are still there \ndata.isnull().sum()",
"_____no_output_____"
]
],
[
[
"#### Voila! Results & Result rate column has no nulls now. Let's see what column Results Type is all about. ",
"_____no_output_____"
]
],
[
[
"data['Result Type'].value_counts()",
"_____no_output_____"
]
],
[
[
"So we infer that 'Result Type' is basically the type of conversion event taking place. It can be either Page Like, Post Like, On-Facebook Lead, Custom Conversion etc. **Since, we are analysing just one campaign here, we can drop this column as it has same meaning throughout data set.**\n\nIf we were analysing multiple campaigns, with different objectives, then keeping this column would have made sense.",
"_____no_output_____"
]
],
[
[
"#Drop Result Type column from data\ndata.drop(['Result Type'],axis = 1, inplace = True)",
"_____no_output_____"
],
[
"#check how many nulls are still there \ndata.isnull().sum()",
"_____no_output_____"
]
],
[
[
"Now we need to deal with **Cost per result**.\nThe cases where CPA is Null means that there was no conversion. So ideally, in these cases the CPA should be very high (in case a conversion actually happened).",
"_____no_output_____"
],
[
"#### So, let's leave this column as it is because we can't assign any value for records where no conversion happened.",
"_____no_output_____"
]
],
[
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 62 entries, 0 to 61\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Campaign name 62 non-null object \n 1 Ad set name 62 non-null object \n 2 Ad name 62 non-null object \n 3 Platform 62 non-null object \n 4 Results 62 non-null float64\n 5 CTR (all) 62 non-null float64\n 6 Result rate 62 non-null float64\n 7 Amount spent (INR) 62 non-null float64\n 8 Cost per result 46 non-null float64\n 9 Frequency 62 non-null float64\n 10 CPM (cost per 1,000 impressions) 62 non-null float64\n 11 Impressions 62 non-null int64 \n 12 Clicks (all) 62 non-null int64 \ndtypes: float64(7), int64(2), object(4)\nmemory usage: 6.8+ KB\n"
]
],
[
[
"# 2. Feature Engineering",
"_____no_output_____"
],
[
"### 1. We can divide Frequency in buckets",
"_____no_output_____"
]
],
[
[
"data['Frequency'] = data['Frequency'].apply(lambda x:'1 to 2' if x<2\n else '2 to 3' if x>=2 and x<3 \n else '3 to 4' if x>=3 and x<4\n else '4 to 5' if x>=4 and x<5\n else 'More than 5')",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
]
],
[
[
"### 2. Split Ad name into Ad Format and Ad Headline",
"_____no_output_____"
]
],
[
[
"data['Ad_name'] = data['Ad name']",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data[['Ad Format','Ad Headline']] = data.Ad_name.str.split(\"-\", expand = True)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data.drop(['Ad name','Ad_name'],axis = 1, inplace = True)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data.info(verbose = 1)",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 62 entries, 0 to 61\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Campaign name 62 non-null object \n 1 Ad set name 62 non-null object \n 2 Platform 62 non-null object \n 3 Results 62 non-null float64\n 4 CTR (all) 62 non-null float64\n 5 Result rate 62 non-null float64\n 6 Amount spent (INR) 62 non-null float64\n 7 Cost per result 46 non-null float64\n 8 Frequency 62 non-null object \n 9 CPM (cost per 1,000 impressions) 62 non-null float64\n 10 Impressions 62 non-null int64 \n 11 Clicks (all) 62 non-null int64 \n 12 Ad Format 62 non-null object \n 13 Ad Headline 62 non-null object \ndtypes: float64(6), int64(2), object(6)\nmemory usage: 7.3+ KB\n"
],
[
"data.to_csv('Clean_Data_Platform.csv')",
"_____no_output_____"
]
],
[
[
"## Now our data is clean. Here are our features that we will use for analysis\n\n- **1. Campaign Name** - Name of campaign\n- **2. Ad Set Name** - Targeting\n- **3. Platform** - Facebook / Instagram\n- **4. Results** - How many conversions were achieved\n- **5. Amount spent** - How much money was spent on ad campaign\n- **6. Frequency** - On an average how many times did one user see the ad\n- **7. Result Rate** - Conversion Rate\n- **8. CTR** - Click Through Rate\n- **9. CPM** - Cost per 1000 impressions\n- **10. Cost per result** - Average Cost required for 1 conversion\n- **11. Ad Format** - Whether the ad crative is **Image/Video/Carousel**\n- **12. Ad Headline** - The headline used in ad\nSo, our target variable here is **Results** and we will analyse the effect of other variable on our target variable.",
"_____no_output_____"
],
[
"# 3. Relationship Visualization",
"_____no_output_____"
],
[
"### 1. Effect of Platform + Ad Format",
"_____no_output_____"
]
],
[
[
"# increase figure size \nplt.figure(figsize = (20, 5))\n\n# subplot 1\nplt.subplot(1, 6, 1)\nsns.barplot(x = 'Platform', y = 'Amount spent (INR)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"Total Amount Spent\")\nplt.xticks(rotation = 90)\n\n\n# subplot 2\nplt.subplot(1, 6, 2)\nsns.barplot(x = 'Platform', y = 'Clicks (all)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"Total Clicks\")\nplt.xticks(rotation = 90)\n\n# subplot 3\nplt.subplot(1, 6, 3)\nsns.barplot(x = 'Platform', y = 'CTR (all)', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"CTR\")\nplt.xticks(rotation = 90)\n\n# subplot 4\nplt.subplot(1, 6, 4)\nsns.barplot(x = 'Platform', y = 'Results', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"Total Conversions\")\nplt.xticks(rotation = 90)\n\n# subplot 5\nplt.subplot(1, 6, 5)\nsns.barplot(x = 'Platform', y = 'Cost per result', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"Avg. Cost per Conversion\")\nplt.xticks(rotation = 90)\n\n# subplot 6\nplt.subplot(1,6, 6)\nsns.barplot(x = 'Platform', y = 'Result rate', data = data, hue = 'Ad Format', estimator = np.sum, ci = None)\nplt.title(\"CVR\")\nplt.xticks(rotation = 90)\n\n\nplt.tight_layout(pad = 0.7)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2. Effect of Platform + Frequency",
"_____no_output_____"
]
],
[
[
"data = data.sort_values(by = ['Frequency']) ",
"_____no_output_____"
],
[
"# increase figure size \nplt.figure(figsize = (25, 6))\n\n# subplot 1\nplt.subplot(1, 6, 1)\nsns.barplot(hue = 'Platform', y = 'Amount spent (INR)', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"Total Amount Spent\")\nplt.xticks(rotation = 90)\n\n\n# subplot 2\nplt.subplot(1, 6, 2)\nsns.barplot(hue = 'Platform', y = 'Clicks (all)', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"Total Clicks\")\nplt.xticks(rotation = 90)\n\n# subplot 3\nplt.subplot(1, 6, 3)\nsns.barplot(hue = 'Platform', y = 'CTR (all)', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"CTR\")\nplt.xticks(rotation = 90)\n\n# subplot 4\nplt.subplot(1, 6, 4)\nsns.barplot(hue = 'Platform', y = 'Results', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"Total Conversions\")\nplt.xticks(rotation = 90)\n\n# subplot 5\nplt.subplot(1, 6, 5)\nsns.barplot(hue = 'Platform', y = 'Cost per result', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"Avg. Cost per Conversion\")\nplt.xticks(rotation = 90)\n\n# subplot 6\nplt.subplot(1, 6, 6)\nsns.barplot(hue = 'Platform', y = 'Result rate', data = data, x = 'Frequency', estimator = np.sum, ci = None)\nplt.title(\"CVR\")\nplt.xticks(rotation = 90)\n\nplt.tight_layout(pad = 0.7)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cba6030f1cd2cbc78ee90f1dffb6c14a9c55e974
| 314,798 |
ipynb
|
Jupyter Notebook
|
notebooks/notebooks_variability_paper/along_isopycnal_spice_gradients_v2.ipynb
|
dhruvbalwada/sogos
|
4ccff0dc0bb7c3d9388bf1787167ce8d5dd78c59
|
[
"MIT"
] | 1 |
2021-03-15T14:05:18.000Z
|
2021-03-15T14:05:18.000Z
|
notebooks/notebooks_variability_paper/along_isopycnal_spice_gradients_v2.ipynb
|
dhruvbalwada/sogos
|
4ccff0dc0bb7c3d9388bf1787167ce8d5dd78c59
|
[
"MIT"
] | 22 |
2020-09-11T18:44:15.000Z
|
2021-11-05T19:11:30.000Z
|
notebooks/notebooks_variability_paper/along_isopycnal_spice_gradients_v2.ipynb
|
dhruvbalwada/sogos
|
4ccff0dc0bb7c3d9388bf1787167ce8d5dd78c59
|
[
"MIT"
] | 1 |
2021-07-07T20:12:04.000Z
|
2021-07-07T20:12:04.000Z
| 259.093004 | 156,880 | 0.908344 |
[
[
[
"# Along isopycnal spice gradients\n\nHere we consider the properties of spice gradients along isopycnals. We do this using the 2 point differences and their distributions. \n\nThis is similar (generalization) to the spice gradients that Klymak et al 2015 considered. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport xarray as xr\n\nimport glidertools as gt\nfrom cmocean import cm as cmo\n\nimport gsw\n\nimport matplotlib.pyplot as plt\n\nplt.style.use('seaborn-colorblind')\nplt.rcParams['font.size'] = 16",
"_____no_output_____"
],
[
"ds_659_rho = xr.open_dataset('data/sg_O2_659_isopycnal_grid_4m_27_sept_2021.nc')\nds_660_rho = xr.open_dataset('data/sg_O2_660_isopycnal_grid_4m_27_sept_2021.nc')\n\n# compute spice \n# Pick constant alpha and beta for convenience (can always update later)\nalpha_659 = gsw.alpha(ds_659_rho.SA, ds_659_rho.CT, ds_659_rho.ctd_pressure)\nalpha_660 = gsw.alpha(ds_660_rho.SA, ds_660_rho.CT, ds_660_rho.ctd_pressure)\n#alpha = 8.3012133e-05\n#beta = 0.00077351\n\n#\ndCT_659 = ds_659_rho.CT - ds_659_rho.CT.mean('dives')\ndSA_659 = ds_659_rho.SA - ds_659_rho.SA.mean('dives')\n\nds_659_rho['Spice'] = (2*alpha_659*dCT_659).rename('Spice')\n\n# remove a mean per isopycnal\ndCT_660 = ds_660_rho.CT - ds_660_rho.CT.mean('dives')\ndSA_660 = ds_660_rho.SA - ds_660_rho.SA.mean('dives')\n\nds_660_rho['Spice'] = (2*alpha_660*dCT_660).rename('Spice')",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,6))\n\nplt.subplot(211)\nds_660_rho.Spice.sel(rho_grid=27.2, method='nearest').plot(label='27.2')\nds_660_rho.Spice.sel(rho_grid=27.4, method='nearest').plot(label='27.4')\nds_660_rho.Spice.sel(rho_grid=27.6, method='nearest').plot(label='27.6')\nplt.legend()\nplt.title('660')\n\nplt.subplot(212)\nds_659_rho.Spice.sel(rho_grid=27.2, method='nearest').plot(label='27.2')\nds_659_rho.Spice.sel(rho_grid=27.4, method='nearest').plot(label='27.4')\nds_659_rho.Spice.sel(rho_grid=27.6, method='nearest').plot(label='27.6')\nplt.legend()\nplt.title('659')\n\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"### Analysis at a couple of single depths",
"_____no_output_____"
]
],
[
[
"#def great_circle_distance(lon1, lat1, lon2, lat2):\ndef great_circle_distance(X1, X2):\n \"\"\"Calculate the great circle distance between one or multiple pairs of\n points given in spherical coordinates. Spherical coordinates are expected\n in degrees. Angle definition follows standard longitude/latitude definition.\n This uses the arctan version of the great-circle distance function\n (en.wikipedia.org/wiki/Great-circle_distance) for increased\n numerical stability.\n Parameters\n ----------\n lon1: float scalar or numpy array\n Longitude coordinate(s) of the first element(s) of the point\n pair(s), given in degrees.\n lat1: float scalar or numpy array\n Latitude coordinate(s) of the first element(s) of the point\n pair(s), given in degrees.\n lon2: float scalar or numpy array\n Longitude coordinate(s) of the second element(s) of the point\n pair(s), given in degrees.\n lat2: float scalar or numpy array\n Latitude coordinate(s) of the second element(s) of the point\n pair(s), given in degrees.\n Calculation of distances follows numpy elementwise semantics, so if\n an array of length N is passed, all input parameters need to be\n arrays of length N or scalars.\n Returns\n -------\n distance: float scalar or numpy array\n The great circle distance(s) (in degrees) between the\n given pair(s) of points.\n \"\"\"\n \n # Change form of input to make compliant with pdist\n lon1 = X1[0]\n lat1 = X1[1]\n lon2 = X2[0]\n lat2 = X2[1]\n \n # Convert to radians:\n lat1 = np.array(lat1) * np.pi / 180.0\n lat2 = np.array(lat2) * np.pi / 180.0\n dlon = (lon1 - lon2) * np.pi / 180.0\n\n # Evaluate trigonometric functions that need to be evaluated more\n # than once:\n c1 = np.cos(lat1)\n s1 = np.sin(lat1)\n c2 = np.cos(lat2)\n s2 = np.sin(lat2)\n cd = np.cos(dlon)\n\n # This uses the arctan version of the great-circle distance function\n # from en.wikipedia.org/wiki/Great-circle_distance for increased\n # numerical stability.\n # Formula can be obtained from [2] combining eqns. (14)-(16)\n # for spherical geometry (f=0).\n\n return (\n 180.0\n / np.pi\n * np.arctan2(\n np.sqrt((c2 * np.sin(dlon)) ** 2 + (c1 * s2 - s1 * c2 * cd) ** 2),\n s1 * s2 + c1 * c2 * cd,\n )\n )",
"_____no_output_____"
],
[
"from scipy.spatial.distance import pdist",
"_____no_output_____"
]
],
[
[
"#### 27.4",
"_____no_output_____"
]
],
[
[
"spatial_bins=np.logspace(2,6,17)\n\ndef select_data(rho_sel):\n # function to find the dX and dSpice from the different data sets and merging them\n ds_sel = ds_660_rho.sel(rho_grid=rho_sel, method='nearest')\n\n lon_sel = ds_sel.longitude.values.reshape((-1,1))\n lat_sel = ds_sel.latitude.values.reshape((-1,1))\n time_sel = ds_sel.days.values.reshape((-1,1))\n\n Spice_sel = ds_sel.Spice.values.reshape((-1,1))\n\n Xvec = np.concatenate([lon_sel, lat_sel], axis=1) # mXn, where m is number of obs and n is dimension\n\n dX_660 = pdist(Xvec, great_circle_distance)*110e3 # convert to m\n dTime_660 = pdist(time_sel, 'cityblock')\n dSpice_660 = pdist(Spice_sel, 'cityblock') # we just want to know the abs diff\n\n ds_sel = ds_659_rho.sel(rho_grid=rho_sel, method='nearest')\n\n lon_sel = ds_sel.longitude.values.reshape((-1,1))\n lat_sel = ds_sel.latitude.values.reshape((-1,1))\n time_sel = ds_sel.days.values.reshape((-1,1))\n\n Spice_sel = ds_sel.Spice.values.reshape((-1,1))\n\n Xvec = np.concatenate([lon_sel, lat_sel], axis=1) # mXn, where m is number of obs and n is dimension\n\n dX_659 = pdist(Xvec, great_circle_distance)*110e3 # convert to m\n dTime_659 = pdist(time_sel, 'cityblock')\n dSpice_659 = pdist(Spice_sel, 'cityblock') # we just want to know the abs diff\n\n # combine data\n dX = np.concatenate([dX_659, dX_660])\n dTime = np.concatenate([dTime_659, dTime_660])\n dSpice = np.concatenate([dSpice_659, dSpice_660])\n\n # condition\n cond = (dTime <= 2e-3*dX**(2/3)) \n \n return dX[cond], dSpice[cond]",
"_____no_output_____"
],
[
"rho_sel = 27.25\n\ndX_sel, dSpice_sel = select_data(rho_sel)\n\n# estimate pdfs\nHspice, xedges, yedges = np.histogram2d(dX_sel, dSpice_sel/dX_sel,\n bins=(spatial_bins, np.logspace(-14, -6, 37)))\nxmid = 0.5*(xedges[0:-1] + xedges[1:])\nymid = 0.5*(yedges[0:-1] + yedges[1:])\n\n#dX_edges = xedges[1:] - xedges[0:-1]\n#dY_edges = yedges[1:] - yedges[0:-1]\n\nHspice_Xdnorm = Hspice/ Hspice.sum(axis=1).reshape((-1,1))\n\nmean_dist = np.zeros((len(xmid,)))\n\nfor i in range(len(xmid)):\n mean_dist[i] = np.sum(Hspice_Xdnorm[i, :]*ymid)",
"_____no_output_____"
],
[
"plt.figure(figsize=(7,5))\nplt.pcolor(xedges, yedges, Hspice_Xdnorm.T, norm=colors.LogNorm(vmin=1e-3, vmax=0.3),\n cmap=cmo.amp)\nplt.plot(xmid, mean_dist , linewidth=2., color='cyan', label='Mean')\nplt.plot(xmid, 1e-6*xmid**-.6, '--',linewidth=2, color='gray', label='L$^{-0.6}$')\nplt.colorbar(label='PDF')\n \nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel('L [m]')\nplt.ylabel(r'$|dSpice/dx|$ [kg m$^{-4}$]')\n\nplt.legend(loc='lower left')\nplt.ylim([1e-13, 1e-6])\nplt.xlim([1e2, 1e5])\n\nplt.grid()\nplt.title('$\\sigma$='+str(rho_sel)+'kg m$^{-3}$')\nplt.tight_layout()\n\nplt.savefig('./figures/figures_spice_gradients_panel1.pdf')",
"_____no_output_____"
]
],
[
[
"### Compute the structure functions at many depths \n\n### Structure functions \n\nHere we consider the structure functions; quantities like $<d\\tau ^n>$.\n\nPower law scalings go as, at $k^{-\\alpha}$ in power spectrum will appear at $r^{\\alpha-1}$ in spectra. \nSo a power law scaling of 2/3 corresponds to $-5/3$, while shallower than 2/3 would correspond to shallower. ",
"_____no_output_____"
]
],
[
[
"rho_sels = ds_660_rho.rho_grid[0:-1:10]\nrho_sels",
"_____no_output_____"
],
[
"# estimate the structure functions \n# We will do the distribution calculations at a few depths\n\nspatial_bins=np.logspace(2,6,17)\n\n\nS2 = np.zeros((len(rho_sels),len(spatial_bins)-1))\nS4 = np.zeros((len(rho_sels),len(spatial_bins)-1))\n\n\nfor count, rho_sel in enumerate(rho_sels):\n print(count)\n \n dX_cond, dSpice_cond = select_data(rho_sel)\n \n # compute the structure functions\n for i in range(len(spatial_bins)-1): \n S2[count, i] = np.nanmean(dSpice_cond[ (dX_cond> spatial_bins[i]) & (dX_cond <= spatial_bins[i+1])]**2)\n S4[count, i] = np.nanmean(dSpice_cond[ (dX_cond> spatial_bins[i]) & (dX_cond <= spatial_bins[i+1])]**4)\n ",
"0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n"
]
],
[
[
"Unlike the surface buoyancy gradients, there is less of a suggestion of saturation at the small scales. Suggesting that even if the is a natural limit to the smallest gradients (wave mixing or such), it is not reached at a few 100m. \n\nThis result seems to be similar, regardless of the isopycnal we are considering (tried this by changing the density level manually). \n\nThings to try: \n- Second order structure functions (do they look more like k^-1 or k^-2?) \n- 4th order structure functions could also help as a summary metric",
"_____no_output_____"
]
],
[
[
"import matplotlib.colors as colors\nfrom matplotlib import ticker",
"_____no_output_____"
],
[
"np.linspace(-4.5,0, 19)\nnp.linspace(-11,-8, 22)",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 7))\n\nlev_exp = np.linspace(-11,-8, 22)\nlevs = np.power(10, lev_exp)\n\ncnt = plt.contourf(xmid, rho_sels, S2, levels=levs,\n norm = colors.LogNorm(3e-11), extend='both',\n cmap=cmo.tempo_r)\n\nfor c in cnt.collections:\n c.set_edgecolor(\"face\")\n \nplt.xscale('log')\nplt.colorbar(ticks=[1e-11, 1e-10, 1e-9, 1e-8], label=r'$\\left< \\delta \\tau ^2\\right> $ [kg$^2$ m$^{-6}$]')\n\nplt.ylim([27.65, 27.15])\nplt.xlim([3e2, 1e5])\n\nplt.ylabel(r'$\\rho$ [kg m$^{-3}$]')\nplt.xlabel('L [m]')\n\nplt.tight_layout()\n\nplt.savefig('figures/figure_iso_spec_freq_panel4.pdf')\n",
"_____no_output_____"
],
[
"spatial_bins_mid = 0.5*(spatial_bins[0:-1] + spatial_bins[1:])",
"_____no_output_____"
],
[
"np.any(np.isnan(y))",
"_____no_output_____"
],
[
"# Fit slope\nnpres = len(rho_sels)\nm_mean = np.zeros((npres,))\n\nx = spatial_bins_mid[(spatial_bins_mid>=1e3) & (spatial_bins_mid<=40e3)]\n\nfor i in range(npres):\n \n y = S2[i, (spatial_bins_mid>=1e3) & (spatial_bins_mid<=40e3)]\n \n if ~np.any(np.isnan(y)):\n m_mean[i],b = np.polyfit(np.log(x), np.log(y),1)\n else:\n m_mean[i] = np.nan\n ",
"_____no_output_____"
],
[
"np.mean(m_mean[20:60])",
"_____no_output_____"
],
[
"plt.figure(figsize=(3,7))\nplt.plot(m_mean, rho_sels, color='k', linewidth=2)\n\nplt.vlines([0,2/3,1], 27.15, 27.65, linestyles='--')\n\nplt.gca().invert_yaxis()\nplt.ylim([27.65, 27.15])\n\nplt.xlim([-.1,1.1])\n\nplt.xlabel('Slope')\nplt.ylabel(r'$\\rho$ [kg m$^{-3}$]')\n\nplt.tight_layout()\nplt.savefig('figures/figure_iso_spec_freq_panel5.pdf')\n",
"_____no_output_____"
],
[
"np.linspace(2, 20, 19)",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 7))\n\n\ncnt = plt.contourf(xmid, rho_sels, S4/ S2**2, levels=np.linspace(2, 20, 19), extend='both', cmap=cmo.turbid_r)\nfor c in cnt.collections:\n c.set_edgecolor(\"face\")\n \nplt.xscale('log')\nplt.colorbar(ticks=[3, 6, 9, 12,15, 18], label=r'$\\left< \\delta \\tau ^4 \\right> / \\left< \\delta \\tau ^2\\right>^2 $ ')\n\n\nplt.ylim([27.65, 27.15])\nplt.xlim([3e2, 1e5])\n\nplt.ylabel(r'$\\rho$ [kg m$^{-3}$]')\nplt.xlabel('L [m]')\n\nplt.tight_layout()\nplt.savefig('figures/figure_iso_spec_freq_panel6.pdf')\n#plt.gca().invert_yaxis()",
"_____no_output_____"
]
],
[
[
"The second order structure of spice follow as power law of about 2/3, which corresponds to about -5/3 slope of tracers. This is slightly at odds with the $k^{-2}$. scaling seen in wavenumber. However, note that this is still very far from $r^0$ (constant) that one might expect is the $k^{-1}$ case (which is what theory would predict). ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cba60d256e59bc83d64d072af77d6ac4b38899b9
| 8,542 |
ipynb
|
Jupyter Notebook
|
Part_2__FeatureEngineering.ipynb
|
penningjoy/MachineLearningwithsklearn
|
1433668e118d780b65ff4c3081f0ef851e628d56
|
[
"MIT"
] | null | null | null |
Part_2__FeatureEngineering.ipynb
|
penningjoy/MachineLearningwithsklearn
|
1433668e118d780b65ff4c3081f0ef851e628d56
|
[
"MIT"
] | null | null | null |
Part_2__FeatureEngineering.ipynb
|
penningjoy/MachineLearningwithsklearn
|
1433668e118d780b65ff4c3081f0ef851e628d56
|
[
"MIT"
] | null | null | null | 30.077465 | 260 | 0.459963 |
[
[
[
"<a href=\"https://colab.research.google.com/github/penningjoy/MachineLearningwithsklearn/blob/main/Part_2__FeatureEngineering.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"### Feature Selection\n\nFeature Selection is a very important part of Feature Engineering process. You don't want features that are not relevant and unrelated to your target and thus do not have to participate in the Machine Learning process. \n\nReasons behind performing feature selection --\n\n* Reduction in Training time because you have less garbage\n* Reduced Dimension\n* More General and easier model \n* Better Interpretability",
"_____no_output_____"
],
[
"#### Removing features with low variance\n\nIt involves removing features which has only one value and other instances share the same value on this feature. There is no variance in its instances. Therefore it will not contribute anything to the prediction. And thus it's best to remove them.",
"_____no_output_____"
]
],
[
[
"import sklearn.feature_selection as fs\nimport numpy as np\n\nX = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]])\n\n'''\nVarianceThreshold function removes features with low variance based on a \nthreshold. Threshold is the variance threshold.\n'''\n\nvariance = fs.VarianceThreshold(threshold = 0.2)\nvariance.fit(X)\nX_transformed = variance.transform(X)\n\nprint(\" Original Data \")\nprint(\" ------------- \")\nprint(X)\n\nprint(\" \")\n\nprint(\" Label Encoded Data \")\nprint(\" -------------- \")\nprint(X_transformed)",
" Original Data \n ------------- \n[[0 0 1]\n [0 1 0]\n [1 0 0]\n [0 1 1]\n [0 1 0]\n [0 1 1]]\n \n Label Encoded Data \n -------------- \n[[0 1]\n [1 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]]\n"
]
],
[
[
"#### Select K-Best Features\n\n",
"_____no_output_____"
]
],
[
[
"import sklearn.datasets as datasets\n\nX, Y = datasets.make_classification(n_samples=300, n_features=10, n_informative=4)\n\n# Choosing the f_classif as the metric and K is 3\nkbest = fs.SelectKBest( fs.f_classif, 3)\nkbest.fit(X,Y)\n\nX_transformed = kbest.transform(X)\n\nprint(\" Original Data \")\nprint(\" ------------- \")\nprint(X)\n\nprint(\" \")\n\nprint(\" Label Encoded Data \")\nprint(\" -------------- \")\nprint(X_transformed)",
"_____no_output_____"
]
],
[
[
" #### Feature Selection by other model\n\n",
"_____no_output_____"
]
],
[
[
"import sklearn.feature_selection as fs\nimport sklearn.datasets as datasets\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.ensemble import GradientBoostingClassifier\nimport sklearn.metrics as metrics\n\nX, Y = datasets.make_classification(n_samples=500, n_features=20, n_informative=6,random_state=21)\n\ngbclassifier = GradientBoostingClassifier(n_estimators=20)\ngbclassifier.fit(X,Y)\n\nprint(\"Feature Selection using GBDT\")\nprint(gbclassifier.feature_importances_)\n\ngbdtmodel = fs.SelectFromModel(gbclassifier, prefit= True)\n\n# The features with very low importance will be removed\nX_transformed = gbdtmodel.transform(X) \n\nprint(\" Original Data Shape \")\nprint(\" ------------- \")\nprint(X.shape)\n\nprint(\" \")\n\nprint(\" Transformed Data Shape after Feature Selection \")\nprint(\" -------------- \")\nprint(X_transformed.shape)",
"Feature Selection using GBDT\n[0. 0.00493847 0. 0.00773537 0. 0.13557457\n 0.1600879 0. 0. 0.0490113 0.04407025 0.04873479\n 0.0078042 0. 0.005109 0. 0.53693415 0.\n 0. 0. ]\n Original Data Shape \n ------------- \n(500, 20)\n \n Transformed Data \n -------------- \n(500, 3)\n"
]
],
[
[
"### Feature Extraction\n\n",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_extraction.text import CountVectorizer\n\ncorpus = [\n \"I have an apple.\", \"The apple is red\", \"I like the apple\",\n \"I like the orange\", \"Apple and orange are fruit\", \"The orange is yellow\"\n]\n\ncounterVec = CountVectorizer()\n\ncounterVec.fit(corpus)\n\nprint(\"Get all the feature names of this corpus\")\n\nprint(counterVec.get_feature_names())\n\nprint(\"The number of feature is {}\".format(len(\n counterVec.get_feature_names())))\n\ncorpus_data = counterVec.transform(corpus)\n\nprint(\"The transform data's shape is {}\".format(corpus_data.toarray().shape))\n\nprint(corpus_data.toarray())",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cba61887da67b85f90e7f7ff2cf9a478616fadb3
| 58,169 |
ipynb
|
Jupyter Notebook
|
iss/.ipynb_checkpoints/parser-Copy1-checkpoint.ipynb
|
csaladenes/tsne
|
0af57d52f02a125df58bacb2bc026c93f4319f0a
|
[
"MIT"
] | 1 |
2019-01-12T19:21:13.000Z
|
2019-01-12T19:21:13.000Z
|
iss/.ipynb_checkpoints/parser-Copy1-checkpoint.ipynb
|
try-something-new-everyday/blog
|
0af57d52f02a125df58bacb2bc026c93f4319f0a
|
[
"MIT"
] | 1 |
2017-04-21T01:52:43.000Z
|
2017-04-21T01:56:45.000Z
|
iss/.ipynb_checkpoints/parser-Copy1-checkpoint.ipynb
|
try-something-new-everyday/blog
|
0af57d52f02a125df58bacb2bc026c93f4319f0a
|
[
"MIT"
] | null | null | null | 31.925906 | 138 | 0.520501 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"url='https://en.wikipedia.org/wiki/List_of_International_Space_Station_expeditions'",
"_____no_output_____"
],
[
"#!pip install beautifulsoup4",
"_____no_output_____"
],
[
"import bs4\nimport requests\nr=requests.get(url)\nsoup = bs4.BeautifulSoup(r.content)\ntables=soup.findAll(\"table\")",
"_____no_output_____"
],
[
"exps={}\nppls={}\nppcs={}\nmsns={}\ncnts={}\nfor trs in [tables[0].findAll(\"tr\"),tables[1].findAll(\"tr\")]:\n for i,tr in enumerate(trs):\n if i>0:\n aas=tr.findAll(\"a\")\n for a in aas:\n if a:\n txt=a.text\n if j==0:\n if exp not in exps: exps[exp]=a['href']\n elif j==1:\n print(txt)\n if not txt:\n img=a.find('img')\n cnt=img['alt']\n if 'ISS' not in cnt:\n if cnt not in cnts: cnts[cnt]=img['src']\n else:\n if '[' not in txt:\n if txt not in ppcs: \n ppcs[txt]=cnt\n if txt not in ppls: \n ppls[txt]=a['href']\n else:\n if txt:\n if '[' not in txt:\n if txt not in msns: msns[txt]=a['href']",
"Expedition 1\n\n\nWilliam M. Shepherd\n\nSergei Krikalev\n\nYuri Gidzenko\nSoyuz TM-31\nSTS-102\nExpedition 2\n\n\nYuri Usachev\n\nJames S. Voss\n\nSusan J. Helms\nSTS-102\nSTS-105\nExpedition 3\n\n\nFrank L. Culbertson\n\nMikhail Tyurin\n\nVladimir Dezhurov\nSTS-105\nSTS-108\nExpedition 4\n\n\nYury Onufrienko\n\nCarl E. Walz\n\nDaniel W. Bursch\nSTS-108\nSTS-111\nExpedition 5\n\n\nValery Korzun\n\nSergei Treshchev\n\nPeggy A. Whitson\nSTS-111\nSTS-113\nExpedition 6\n\n\nKenneth D. Bowersox\n\nDonald R. Pettit\n\nNikolai Budarin\nSTS-113\nSoyuz TMA-1\nExpedition 7\n\n\nYuri Malenchenko\n\nEdward T. Lu\nSoyuz TMA-2\nSoyuz TMA-2\nExpedition 8\n\n\nC. Michael Foale\n\nAlexander Kaleri\nSoyuz TMA-3\nSoyuz TMA-3\nExpedition 9\n\n\nGennady Padalka\n\nE. Michael Fincke\nSoyuz TMA-4\nSoyuz TMA-4\nExpedition 10\n\n\nLeroy Chiao\n\nSalizhan Sharipov\nSoyuz TMA-5\nSoyuz TMA-5\nExpedition 11\n\n\nSergei Krikalev\n\nJohn L. Phillips\nSoyuz TMA-6\nSoyuz TMA-6\nExpedition 12\n\n\nWilliam S. McArthur\n\nValeri Tokarev\nSoyuz TMA-7\nSoyuz TMA-7\nExpedition 13\n\n\nPavel Vinogradov\n\nJeffrey N. Williams\nSoyuz TMA-8\nSoyuz TMA-8\n\nThomas Reiter\nSTS-121\nExpedition 14\n\n\nMichael E. Lopez-Alegria\n\nMikhail Tyurin\nSoyuz TMA-9\nSoyuz TMA-9\n\nThomas Reiter\nSTS-116\n\nSunita L. Williams\nSTS-116\nExpedition 15\n\n\nFyodor Yurchikhin\n\nOleg Kotov\nSoyuz TMA-10\nSoyuz TMA-10\n\nSunita L. Williams\nSTS-117\n\nClayton C. Anderson\nSTS-117\nExpedition 16\n\n\nPeggy A. Whitson\n\nYuri Malenchenko\nSoyuz TMA-11\nSoyuz TMA-11\n\nClayton C. Anderson\nSTS-120\n\nDaniel M. Tani\nSTS-120\nSTS-122\n\nLéopold Eyharts\nSTS-122\nSTS-123\n\nGarrett E. Reisman\nSTS-123\nExpedition 17\n\n\nSergey Volkov\n\nOleg Kononenko\nSoyuz TMA-12\nSoyuz TMA-12\n\nGarrett E. Reisman\nSTS-124\n\nGregory E. Chamitoff\nSTS-124\nExpedition 18\n\n\nE. Michael Fincke\n\nYuri Lonchakov\nSoyuz TMA-13\nSoyuz TMA-13\n\nGregory E. Chamitoff\nSTS-126\n\nSandra H. Magnus\nSTS-126\nSTS-119\n\nKoichi Wakata\nSTS-119\nExpedition 19\n\n\nGennady Padalka\n\nMichael R. Barratt\nSoyuz TMA-14\n\nKoichi Wakata\nExpedition 20\n\n\nGennady Padalka\n\nMichael R. Barratt\nSoyuz TMA-14\n\nKoichi Wakata\nSTS-127\n\nTimothy L. Kopra\nSTS-127\nSTS-128\n\nFrank De Winne\n\nRoman Romanenko\n\nRobert B. Thirsk\nSoyuz TMA-15\n\nNicole P. Stott\nSTS-128\nExpedition 21\n\n\nFrank De Winne\n\nRoman Romanenko\n\nRobert B. Thirsk\nSoyuz TMA-15\n\nNicole P. Stott\nSTS-129\n\nJeffrey N. Williams\n\nMaksim Surayev\nSoyuz TMA-16\nExpedition 22\n\n\nJeffrey N. Williams\n\nMaksim Surayev\nSoyuz TMA-16\n\nOleg Kotov\n\nTimothy J. Creamer\n\nSoichi Noguchi\nSoyuz TMA-17\nExpedition 23\n\n\nOleg Kotov\n\nTimothy J. Creamer\n\nSoichi Noguchi\nSoyuz TMA-17\n\nAleksandr Skvortsov\n\nMikhail Korniyenko\n\nTracy E. Caldwell Dyson\nSoyuz TMA-18\nExpedition 24\n\n\nAleksandr Skvortsov\n\nMikhail Korniyenko\n\nTracy E. Caldwell Dyson\nSoyuz TMA-18\n\nDouglas H. Wheelock\n\nShannon Walker\n\nFyodor Yurchikhin\nSoyuz TMA-19\nExpedition 25\n\n\nDouglas H. Wheelock\n\nShannon Walker\n\nFyodor Yurchikhin\nSoyuz TMA-19\n\nScott J. Kelly\n\nAleksandr Kaleri\n\nOleg Skripochka\nSoyuz TMA-01M\nExpedition 26\n\n\nScott J. Kelly\n\nAleksandr Kaleri\n\nOleg Skripochka\nSoyuz TMA-01M\n\nDimitri Kondratyev\n\nCatherine G. Coleman\n\nPaolo Nespoli\nSoyuz TMA-20\nExpedition 27\n\n\nDimitri Kondratyev\n\nCatherine G. Coleman\n\nPaolo Nespoli\nSoyuz TMA-20\n\nAndrei Borisenko\n\nAleksandr Samokutyayev\n\nRonald J. Garan\nSoyuz TMA-21\nExpedition 28\n\n\nAndrei Borisenko\n\nAleksandr Samokutyayev\n\nRonald J. Garan\nSoyuz TMA-21\n\nMichael E. Fossum\n\nSergey Volkov\n\nSatoshi Furukawa\nSoyuz TMA-02M\nExpedition 29\n\n\nMichael E. Fossum\n\nSergey Volkov\n\nSatoshi Furukawa\nSoyuz TMA-02M\n\nDaniel C. Burbank\n\nAnton Shkaplerov\n\nAnatoli Ivanishin\nSoyuz TMA-22\nExpedition 30\n\n\nDaniel C. Burbank\n\nAnton Shkaplerov\n\nAnatoli Ivanishin\nSoyuz TMA-22\n\nOleg Kononenko\n\nDonald R. Pettit\n\nAndré Kuipers\nSoyuz TMA-03M\nExpedition 31\n\n\nOleg Kononenko\n\nDonald R. Pettit\n\nAndré Kuipers\nSoyuz TMA-03M\n\nGennady Padalka\n\nSergei Revin\n\nJoseph M. Acaba\nSoyuz TMA-04M\nExpedition 32\n\n\nGennady Padalka\n\nSergei Revin\n\nJoseph M. Acaba\nSoyuz TMA-04M\n\nSunita L. Williams\n\nYuri Malenchenko\n\nAkihiko Hoshide\nSoyuz TMA-05M\nExpedition 33\n\n\nSunita L. Williams\n\nYuri Malenchenko\n\nAkihiko Hoshide\nSoyuz TMA-05M\n\nKevin A. Ford\n\nOleg Novitskiy\n\nEvgeny Tarelkin\nSoyuz TMA-06M\nExpedition 34\n\n\nKevin A. Ford\n\nOleg Novitskiy\n\nEvgeny Tarelkin\nSoyuz TMA-06M\n\nChris Hadfield\n\nRoman Romanenko\n\nThomas H. Marshburn\nSoyuz TMA-07M\nExpedition 35\n\n\nChris Hadfield\n\nRoman Romanenko\n\nThomas H. Marshburn\nSoyuz TMA-07M\n\nPavel Vinogradov\n\nAleksandr Misurkin\n\nChristopher J. Cassidy\nSoyuz TMA-08M\nExpedition 36\n\n\nPavel Vinogradov\n\nAleksandr Misurkin\n\nChristopher J. Cassidy\nSoyuz TMA-08M\n\nFyodor Yurchikhin\n\nKaren L. Nyberg\n\nLuca Parmitano\nSoyuz TMA-09M\nExpedition 37\n\n\nFyodor Yurchikhin\n\nKaren L. Nyberg\n\nLuca Parmitano\nSoyuz TMA-09M\n\nOleg Kotov\n\nSergey Ryazansky\n\nMichael S. Hopkins\nSoyuz TMA-10M\nExpedition 38\n\n\nOleg Kotov\n\nSergey Ryazansky\n\nMichael S. Hopkins\nSoyuz TMA-10M\n\nKoichi Wakata\n\nMikhail Tyurin\n\nRichard A. Mastracchio\nSoyuz TMA-11M\nExpedition 39\n\n\nKoichi Wakata\n\nMikhail Tyurin\n\nRichard A. Mastracchio\nSoyuz TMA-11M\n\nAleksandr Skvortsov\n\nOleg Artemyev\n\nSteven R. Swanson\nSoyuz TMA-12M\nExpedition 40\n\n\nSteven R. Swanson\n\nAleksandr Skvortsov\n\nOleg Artemyev\nSoyuz TMA-12M\n\nGregory R. Wiseman\n\nMaksim Surayev\n\nAlexander Gerst\nSoyuz TMA-13M\nExpedition 41\n\n\nMaksim Surayev\n\nGregory R. Wiseman\n\nAlexander Gerst\nSoyuz TMA-13M\n\nAleksandr Samokutyayev\n\nYelena Serova\n\nBarry E. Wilmore\nSoyuz TMA-14M\nExpedition 42\n\n\nBarry E. Wilmore\n\nAleksandr Samokutyayev\n\nYelena Serova\nSoyuz TMA-14M\n\nAnton Shkaplerov\n\nSamantha Cristoforetti\n\nTerry W. Virts\nSoyuz TMA-15M\nExpedition 43\n\n\nTerry W. Virts\n\nAnton Shkaplerov\n\nSamantha Cristoforetti\n[1]\n[2]\nSoyuz TMA-15M\n\nGennady Padalka\nSoyuz TMA-16M\n\nMikhail Korniyenko\n\nScott J. Kelly\none year mission\n\nExpedition 44\n\n\nGennady Padalka\n[3]\nSoyuz TMA-16M\n\nMikhail Korniyenko\n\nScott J. Kelly\none year mission\n\n\nOleg Kononenko\n\nKimiya Yui\n\nKjell N. Lindgren\n[4]\nSoyuz TMA-17M\nExpedition 45\n\n\nScott J. Kelly\n\nMikhail Korniyenko\n\nOleg Kononenko\n\nKimiya Yui\n\nKjell N. Lindgren\nSoyuz TMA-17M\n\nSergey Volkov\nSoyuz TMA-18M\nExpedition 46\n\n\nScott J. Kelly\n\nMikhail Korniyenko\nSoyuz TMA-18M\n[n 1]\n[5]\n\nSergey Volkov\n[n 2]\n\nYuri Malenchenko\n\nTimothy Peake\n\nTimothy Kopra\nSoyuz TMA-19M\nExpedition 47\n\n\nTimothy Kopra\n\nTim Peake\n\nYuri Malenchenko\n[6]\nSoyuz TMA-19M\n\nAleksey Ovchinin\n\nOleg Skripochka\n\nJeffrey Williams\nSoyuz TMA-20M\nExpedition 48\n\n\nJeffrey Williams\n\nOleg Skripochka\n\nAleksey Ovchinin\n[7]\nSoyuz TMA-20M\n[8]\n\nAnatoli Ivanishin\n\nTakuya Onishi\n\nKathleen Rubins\n[9]\nSoyuz MS-01\nExpedition 49\n\n\nAnatoli Ivanishin\n\nTakuya Onishi\n\nKathleen Rubins\n[10]\nSoyuz MS-01\n\nShane Kimbrough\n\nAndrei Borisenko\n\nSergey Ryzhikov\n[11]\nSoyuz MS-02\nExpedition 50\n\n\nShane Kimbrough\n\nAndrei Borisenko\n\nSergey Ryzhikov\nSoyuz MS-02\n\nPeggy Whitson\n\nOleg Novitskiy\n\nThomas Pesquet\nSoyuz MS-03\nExpedition 51\n\n\nPeggy Whitson\n\nOleg Novitskiy\n\nThomas Pesquet\nSoyuz MS-03\n\nFyodor Yurchikhin\n\nJack D. Fischer\nSoyuz MS-04\nExpedition 52\n\n\nFyodor Yurchikhin\n\nJack D. Fischer\nSoyuz MS-04\n[12]\n\nPeggy Whitson\n[n 3]\n[13]\n\nRandolph Bresnik\n\nPaolo Nespoli\n\nSergey Ryazansky\nSoyuz MS-05\nExpedition 53\n\n\nRandolph Bresnik\n\nPaolo Nespoli\n\nSergey Ryazansky\n[14]\nSoyuz MS-05\n\nAlexander Misurkin\n\nMark Vande Hei\n\nJoseph Acaba\nSoyuz MS-06\nExpedition 54\n\n\nAlexander Misurkin\n\nMark Vande Hei\n\nJoseph Acaba\nSoyuz MS-06\n\nAnton Shkaplerov\n\nScott Tingle\n\nNorishige Kanai\nSoyuz MS-07\nExpedition 55\n\n\nAnton Shkaplerov\n\nScott Tingle\n\nNorishige Kanai\nSoyuz MS-07\n\nAndrew Feustel\n\nOleg Artemyev\n\nRichard Arnold\n[15]\nSoyuz MS-08\nExpedition 56\n\n\nAndrew Feustel\n\nOleg Artemyev\n\nRichard Arnold\n[16]\nSoyuz MS-08\n\nAlexander Gerst\n\nSergey Prokopyev\n\nSerena Auñón-Chancellor\nSoyuz MS-09\nExpedition 57\n\n\nAlexander Gerst\n\nSergey Prokopyev\n\nSerena Auñón-Chancellor\nSoyuz MS-09\n\nOleg Kononenko\n\nDavid Saint-Jacques\n\nAnne McClain\nSoyuz MS-11\nExpedition 58\n\n\nOleg Kononenko\n\nDavid Saint-Jacques\n\nAnne McClain\nExpedition 59\n\n\nOleg Kononenko\n\nDavid Saint-Jacques\n\nAnne McClain\nSoyuz MS-11\n\nAleksey Ovchinin\n\nChristina Koch\n\nNick Hague\nSoyuz MS-12\n"
],
[
"df=pd.read_html(url)\ndf=pd.concat(df[:2]).reset_index()",
"_____no_output_____"
],
[
"def find_names(s,ppls,z):\n nms=s.split(' ')\n l=2\n while l<4:\n ppl=' '.join(nms[:l])\n if ppl in ppls:\n print(ppl)\n z.append(ppl)\n rest=' '.join(nms[l:])\n find_names(rest,ppls,z)\n l=4\n l+=1\n return z",
"_____no_output_____"
],
[
"ppls",
"_____no_output_____"
],
[
"for i in df.index:\n crew=df.loc[i]['Crew'].replace('\\n','')\n crews=find_names(crew,ppls,[])\n if crew in ppls:\n crews.append(crew)\n print(crew,crews)",
"William M. Shepherd\nSergei Krikalev\nYuri Gidzenko\nWilliam M. Shepherd Sergei Krikalev Yuri Gidzenko ['William M. Shepherd', 'Sergei Krikalev', 'Yuri Gidzenko']\nYuri Usachev\nJames S. Voss\nSusan J. Helms\nYuri Usachev James S. Voss Susan J. Helms ['Yuri Usachev', 'James S. Voss', 'Susan J. Helms']\nFrank L. Culbertson\nMikhail Tyurin\nVladimir Dezhurov\nFrank L. Culbertson Mikhail Tyurin Vladimir Dezhurov ['Frank L. Culbertson', 'Mikhail Tyurin', 'Vladimir Dezhurov']\nYury Onufrienko\nCarl E. Walz\nDaniel W. Bursch\nYury Onufrienko Carl E. Walz Daniel W. Bursch ['Yury Onufrienko', 'Carl E. Walz', 'Daniel W. Bursch']\nValery Korzun\nSergei Treshchev\nPeggy A. Whitson\nValery Korzun Sergei Treshchev Peggy A. Whitson ['Valery Korzun', 'Sergei Treshchev', 'Peggy A. Whitson']\nKenneth D. Bowersox\nDonald R. Pettit\nNikolai Budarin\nKenneth D. Bowersox Donald R. Pettit Nikolai Budarin ['Kenneth D. Bowersox', 'Donald R. Pettit', 'Nikolai Budarin']\nYuri Malenchenko\nEdward T. Lu\nYuri Malenchenko Edward T. Lu ['Yuri Malenchenko', 'Edward T. Lu']\nC. Michael Foale\nAlexander Kaleri\nC. Michael Foale Alexander Kaleri ['C. Michael Foale', 'Alexander Kaleri']\nGennady Padalka\nE. Michael Fincke\nGennady Padalka E. Michael Fincke ['Gennady Padalka', 'E. Michael Fincke']\nLeroy Chiao\nSalizhan Sharipov\nLeroy Chiao Salizhan Sharipov ['Leroy Chiao', 'Salizhan Sharipov']\nSergei Krikalev\nJohn L. Phillips\nSergei Krikalev John L. Phillips ['Sergei Krikalev', 'John L. Phillips']\nWilliam S. McArthur\nValeri Tokarev\nWilliam S. McArthur Valeri Tokarev ['William S. McArthur', 'Valeri Tokarev']\nPavel Vinogradov\nJeffrey N. Williams\nPavel Vinogradov Jeffrey N. Williams ['Pavel Vinogradov', 'Jeffrey N. Williams']\nThomas Reiter []\nMichael E. Lopez-Alegria\nMikhail Tyurin\nMichael E. Lopez-Alegria Mikhail Tyurin ['Michael E. Lopez-Alegria', 'Mikhail Tyurin']\nThomas Reiter []\nSunita L. Williams\nSunita L. Williams ['Sunita L. Williams', 'Sunita L. Williams']\nFyodor Yurchikhin\nOleg Kotov\nFyodor Yurchikhin Oleg Kotov ['Fyodor Yurchikhin', 'Oleg Kotov']\nSunita L. Williams\nSunita L. Williams ['Sunita L. Williams', 'Sunita L. Williams']\nClayton C. Anderson []\nPeggy A. Whitson\nYuri Malenchenko\nPeggy A. Whitson Yuri Malenchenko ['Peggy A. Whitson', 'Yuri Malenchenko']\nClayton C. Anderson []\nDaniel M. Tani []\nLéopold Eyharts []\nGarrett E. Reisman []\nSergey Volkov\nOleg Kononenko\nSergey Volkov Oleg Kononenko ['Sergey Volkov', 'Oleg Kononenko']\nGarrett E. Reisman []\nGregory E. Chamitoff []\nE. Michael Fincke\nYuri Lonchakov\nE. Michael Fincke Yuri Lonchakov ['E. Michael Fincke', 'Yuri Lonchakov']\nGregory E. Chamitoff []\nSandra H. Magnus []\nKoichi Wakata\nKoichi Wakata ['Koichi Wakata', 'Koichi Wakata']\nGennady Padalka\nMichael R. Barratt\nGennady Padalka Michael R. Barratt ['Gennady Padalka', 'Michael R. Barratt']\nKoichi Wakata\nKoichi Wakata ['Koichi Wakata', 'Koichi Wakata']\nGennady Padalka\nMichael R. Barratt\nGennady Padalka Michael R. Barratt ['Gennady Padalka', 'Michael R. Barratt']\nKoichi Wakata\nKoichi Wakata ['Koichi Wakata', 'Koichi Wakata']\nTimothy L. Kopra []\nFrank De Winne\nRoman Romanenko\nRobert B. Thirsk\nFrank De Winne Roman Romanenko Robert B. Thirsk ['Frank De Winne', 'Roman Romanenko', 'Robert B. Thirsk']\nNicole P. Stott []\nFrank De Winne\nRoman Romanenko\nRobert B. Thirsk\nFrank De Winne Roman Romanenko Robert B. Thirsk ['Frank De Winne', 'Roman Romanenko', 'Robert B. Thirsk']\nNicole P. Stott []\nJeffrey N. Williams\nMaksim Surayev\nJeffrey N. Williams Maksim Surayev ['Jeffrey N. Williams', 'Maksim Surayev']\nJeffrey N. Williams\nMaksim Surayev\nJeffrey N. Williams Maksim Surayev ['Jeffrey N. Williams', 'Maksim Surayev']\nOleg Kotov\nTimothy J. Creamer\nSoichi Noguchi\nOleg Kotov Timothy J. Creamer Soichi Noguchi ['Oleg Kotov', 'Timothy J. Creamer', 'Soichi Noguchi']\nOleg Kotov\nTimothy J. Creamer\nSoichi Noguchi\nOleg Kotov Timothy J. Creamer Soichi Noguchi ['Oleg Kotov', 'Timothy J. Creamer', 'Soichi Noguchi']\nAleksandr Skvortsov\nMikhail Korniyenko\nAleksandr Skvortsov Mikhail Korniyenko Tracy E. Caldwell Dyson ['Aleksandr Skvortsov', 'Mikhail Korniyenko']\nAleksandr Skvortsov\nMikhail Korniyenko\nAleksandr Skvortsov Mikhail Korniyenko Tracy E. Caldwell Dyson ['Aleksandr Skvortsov', 'Mikhail Korniyenko']\nDouglas H. Wheelock\nShannon Walker\nFyodor Yurchikhin\nDouglas H. Wheelock Shannon Walker Fyodor Yurchikhin ['Douglas H. Wheelock', 'Shannon Walker', 'Fyodor Yurchikhin']\nDouglas H. Wheelock\nShannon Walker\nFyodor Yurchikhin\nDouglas H. Wheelock Shannon Walker Fyodor Yurchikhin ['Douglas H. Wheelock', 'Shannon Walker', 'Fyodor Yurchikhin']\nScott J. Kelly\nAleksandr Kaleri\nOleg Skripochka\nScott J. Kelly Aleksandr Kaleri Oleg Skripochka ['Scott J. Kelly', 'Aleksandr Kaleri', 'Oleg Skripochka']\nScott J. Kelly\nAleksandr Kaleri\nOleg Skripochka\nScott J. Kelly Aleksandr Kaleri Oleg Skripochka ['Scott J. Kelly', 'Aleksandr Kaleri', 'Oleg Skripochka']\nDimitri Kondratyev\nCatherine G. Coleman\nPaolo Nespoli\nDimitri Kondratyev Catherine G. Coleman Paolo Nespoli ['Dimitri Kondratyev', 'Catherine G. Coleman', 'Paolo Nespoli']\nDimitri Kondratyev\nCatherine G. Coleman\nPaolo Nespoli\nDimitri Kondratyev Catherine G. Coleman Paolo Nespoli ['Dimitri Kondratyev', 'Catherine G. Coleman', 'Paolo Nespoli']\nAndrei Borisenko\nAleksandr Samokutyayev\nRonald J. Garan\nAndrei Borisenko Aleksandr Samokutyayev Ronald J. Garan ['Andrei Borisenko', 'Aleksandr Samokutyayev', 'Ronald J. Garan']\nAndrei Borisenko\nAleksandr Samokutyayev\nRonald J. Garan\nAndrei Borisenko Aleksandr Samokutyayev Ronald J. Garan ['Andrei Borisenko', 'Aleksandr Samokutyayev', 'Ronald J. Garan']\nMichael E. Fossum\nSergey Volkov\nSatoshi Furukawa\nMichael E. Fossum Sergey Volkov Satoshi Furukawa ['Michael E. Fossum', 'Sergey Volkov', 'Satoshi Furukawa']\nMichael E. Fossum\nSergey Volkov\nSatoshi Furukawa\nMichael E. Fossum Sergey Volkov Satoshi Furukawa ['Michael E. Fossum', 'Sergey Volkov', 'Satoshi Furukawa']\nDaniel C. Burbank\nAnton Shkaplerov\nAnatoli Ivanishin\nDaniel C. Burbank Anton Shkaplerov Anatoli Ivanishin ['Daniel C. Burbank', 'Anton Shkaplerov', 'Anatoli Ivanishin']\nDaniel C. Burbank\nAnton Shkaplerov\nAnatoli Ivanishin\nDaniel C. Burbank Anton Shkaplerov Anatoli Ivanishin ['Daniel C. Burbank', 'Anton Shkaplerov', 'Anatoli Ivanishin']\nOleg Kononenko\nDonald R. Pettit\nAndré Kuipers\nOleg Kononenko Donald R. Pettit André Kuipers ['Oleg Kononenko', 'Donald R. Pettit', 'André Kuipers']\nOleg Kononenko\nDonald R. Pettit\nAndré Kuipers\nOleg Kononenko Donald R. Pettit André Kuipers ['Oleg Kononenko', 'Donald R. Pettit', 'André Kuipers']\nGennady Padalka\nSergei Revin\nJoseph M. Acaba\nGennady Padalka Sergei Revin Joseph M. Acaba ['Gennady Padalka', 'Sergei Revin', 'Joseph M. Acaba']\nGennady Padalka\nSergei Revin\nJoseph M. Acaba\nGennady Padalka Sergei Revin Joseph M. Acaba ['Gennady Padalka', 'Sergei Revin', 'Joseph M. Acaba']\nSunita L. Williams\nYuri Malenchenko\nAkihiko Hoshide\nSunita L. Williams Yuri Malenchenko Akihiko Hoshide ['Sunita L. Williams', 'Yuri Malenchenko', 'Akihiko Hoshide']\nSunita L. Williams\nYuri Malenchenko\nAkihiko Hoshide\nSunita L. Williams Yuri Malenchenko Akihiko Hoshide ['Sunita L. Williams', 'Yuri Malenchenko', 'Akihiko Hoshide']\nKevin A. Ford\nOleg Novitskiy\nEvgeny Tarelkin\nKevin A. Ford Oleg Novitskiy Evgeny Tarelkin ['Kevin A. Ford', 'Oleg Novitskiy', 'Evgeny Tarelkin']\nKevin A. Ford\nOleg Novitskiy\nEvgeny Tarelkin\nKevin A. Ford Oleg Novitskiy Evgeny Tarelkin ['Kevin A. Ford', 'Oleg Novitskiy', 'Evgeny Tarelkin']\nChris Hadfield\nRoman Romanenko\nThomas H. Marshburn\nChris Hadfield Roman Romanenko Thomas H. Marshburn ['Chris Hadfield', 'Roman Romanenko', 'Thomas H. Marshburn']\nChris Hadfield\nRoman Romanenko\nThomas H. Marshburn\nChris Hadfield Roman Romanenko Thomas H. Marshburn ['Chris Hadfield', 'Roman Romanenko', 'Thomas H. Marshburn']\nPavel Vinogradov\nAleksandr Misurkin\nChristopher J. Cassidy\nPavel Vinogradov Aleksandr Misurkin Christopher J. Cassidy ['Pavel Vinogradov', 'Aleksandr Misurkin', 'Christopher J. Cassidy']\nPavel Vinogradov\nAleksandr Misurkin\nChristopher J. Cassidy\nPavel Vinogradov Aleksandr Misurkin Christopher J. Cassidy ['Pavel Vinogradov', 'Aleksandr Misurkin', 'Christopher J. Cassidy']\nFyodor Yurchikhin\nKaren L. Nyberg\nLuca Parmitano\nFyodor Yurchikhin Karen L. Nyberg Luca Parmitano ['Fyodor Yurchikhin', 'Karen L. Nyberg', 'Luca Parmitano']\nFyodor Yurchikhin\nKaren L. Nyberg\nLuca Parmitano\nFyodor Yurchikhin Karen L. Nyberg Luca Parmitano ['Fyodor Yurchikhin', 'Karen L. Nyberg', 'Luca Parmitano']\nOleg Kotov\nSergey Ryazansky\nMichael S. Hopkins\nOleg Kotov Sergey Ryazansky Michael S. Hopkins ['Oleg Kotov', 'Sergey Ryazansky', 'Michael S. Hopkins']\nOleg Kotov\nSergey Ryazansky\nMichael S. Hopkins\nOleg Kotov Sergey Ryazansky Michael S. Hopkins ['Oleg Kotov', 'Sergey Ryazansky', 'Michael S. Hopkins']\nKoichi Wakata\nMikhail Tyurin\nRichard A. Mastracchio\nKoichi Wakata Mikhail Tyurin Richard A. Mastracchio ['Koichi Wakata', 'Mikhail Tyurin', 'Richard A. Mastracchio']\nKoichi Wakata\nMikhail Tyurin\nRichard A. Mastracchio\nKoichi Wakata Mikhail Tyurin Richard A. Mastracchio ['Koichi Wakata', 'Mikhail Tyurin', 'Richard A. Mastracchio']\nAleksandr Skvortsov\nOleg Artemyev\nSteven R. Swanson\nAleksandr Skvortsov Oleg Artemyev Steven R. Swanson ['Aleksandr Skvortsov', 'Oleg Artemyev', 'Steven R. Swanson']\nSteven R. Swanson\nAleksandr Skvortsov\nOleg Artemyev\nSteven R. Swanson Aleksandr Skvortsov Oleg Artemyev ['Steven R. Swanson', 'Aleksandr Skvortsov', 'Oleg Artemyev']\nGregory R. Wiseman\nMaksim Surayev\nAlexander Gerst\nGregory R. Wiseman Maksim Surayev Alexander Gerst ['Gregory R. Wiseman', 'Maksim Surayev', 'Alexander Gerst']\nMaksim Surayev\nGregory R. Wiseman\nAlexander Gerst\nMaksim Surayev Gregory R. Wiseman Alexander Gerst ['Maksim Surayev', 'Gregory R. Wiseman', 'Alexander Gerst']\nAleksandr Samokutyayev\nYelena Serova\nBarry E. Wilmore\nAleksandr Samokutyayev Yelena Serova Barry E. Wilmore ['Aleksandr Samokutyayev', 'Yelena Serova', 'Barry E. Wilmore']\nBarry E. Wilmore\nAleksandr Samokutyayev\nYelena Serova\nBarry E. Wilmore Aleksandr Samokutyayev Yelena Serova ['Barry E. Wilmore', 'Aleksandr Samokutyayev', 'Yelena Serova']\nAnton Shkaplerov\nSamantha Cristoforetti\nTerry W. Virts\nAnton Shkaplerov Samantha Cristoforetti Terry W. Virts ['Anton Shkaplerov', 'Samantha Cristoforetti', 'Terry W. Virts']\nTerry W. Virts\nAnton Shkaplerov\nSamantha Cristoforetti\nTerry W. Virts Anton Shkaplerov Samantha Cristoforetti ['Terry W. Virts', 'Anton Shkaplerov', 'Samantha Cristoforetti']\nGennady Padalka\nGennady Padalka ['Gennady Padalka', 'Gennady Padalka']\nMikhail Korniyenko\nScott J. Kelly\nMikhail Korniyenko Scott J. Kelly ['Mikhail Korniyenko', 'Scott J. Kelly']\nGennady Padalka\nGennady Padalka ['Gennady Padalka', 'Gennady Padalka']\nMikhail Korniyenko\nScott J. Kelly\nMikhail Korniyenko Scott J. Kelly ['Mikhail Korniyenko', 'Scott J. Kelly']\nOleg Kononenko\nOleg Kononenko Kimiya Yui Kjell N. Lindgren ['Oleg Kononenko']\nScott J. Kelly\nMikhail Korniyenko\nScott J. Kelly Mikhail Korniyenko ['Scott J. Kelly', 'Mikhail Korniyenko']\nOleg Kononenko\nOleg Kononenko Kimiya Yui Kjell N. Lindgren ['Oleg Kononenko']\nSergey Volkov\nSergey Volkov ['Sergey Volkov', 'Sergey Volkov']\nScott J. Kelly\nMikhail Korniyenko\nScott J. Kelly Mikhail Korniyenko ['Scott J. Kelly', 'Mikhail Korniyenko']\nSergey Volkov\nSergey Volkov ['Sergey Volkov', 'Sergey Volkov']\nYuri Malenchenko\nYuri Malenchenko Timothy Peake Timothy Kopra ['Yuri Malenchenko']\nTimothy Kopra\nTim Peake\nYuri Malenchenko\nTimothy Kopra Tim Peake Yuri Malenchenko ['Timothy Kopra', 'Tim Peake', 'Yuri Malenchenko']\nAleksey Ovchinin\nOleg Skripochka\nJeffrey Williams\nAleksey Ovchinin Oleg Skripochka Jeffrey Williams ['Aleksey Ovchinin', 'Oleg Skripochka', 'Jeffrey Williams']\nJeffrey Williams\nOleg Skripochka\nAleksey Ovchinin\nJeffrey Williams Oleg Skripochka Aleksey Ovchinin ['Jeffrey Williams', 'Oleg Skripochka', 'Aleksey Ovchinin']\nAnatoli Ivanishin\nTakuya Onishi\nKathleen Rubins\nAnatoli Ivanishin Takuya Onishi Kathleen Rubins ['Anatoli Ivanishin', 'Takuya Onishi', 'Kathleen Rubins']\nAnatoli Ivanishin\nTakuya Onishi\nKathleen Rubins\nAnatoli Ivanishin Takuya Onishi Kathleen Rubins ['Anatoli Ivanishin', 'Takuya Onishi', 'Kathleen Rubins']\nShane Kimbrough\nAndrei Borisenko\nSergey Ryzhikov\nShane Kimbrough Andrei Borisenko Sergey Ryzhikov ['Shane Kimbrough', 'Andrei Borisenko', 'Sergey Ryzhikov']\nShane Kimbrough\nAndrei Borisenko\nSergey Ryzhikov\nShane Kimbrough Andrei Borisenko Sergey Ryzhikov ['Shane Kimbrough', 'Andrei Borisenko', 'Sergey Ryzhikov']\nPeggy Whitson\nOleg Novitskiy\nPeggy Whitson Oleg Novitskiy Thomas Pesquet ['Peggy Whitson', 'Oleg Novitskiy']\nPeggy Whitson\nPeggy Whitson ['Peggy Whitson', 'Peggy Whitson']\nOleg Novitskiy\nOleg Novitskiy Thomas Pesquet ['Oleg Novitskiy']\nFyodor Yurchikhin\nJack D. Fischer\nFyodor Yurchikhin Jack D. Fischer ['Fyodor Yurchikhin', 'Jack D. Fischer']\nFyodor Yurchikhin\nJack D. Fischer\nFyodor Yurchikhin Jack D. Fischer ['Fyodor Yurchikhin', 'Jack D. Fischer']\nPeggy Whitson\nPeggy Whitson ['Peggy Whitson', 'Peggy Whitson']\nRandolph Bresnik\nPaolo Nespoli\nSergey Ryazansky\nRandolph Bresnik Paolo Nespoli Sergey Ryazansky ['Randolph Bresnik', 'Paolo Nespoli', 'Sergey Ryazansky']\nRandolph Bresnik\nPaolo Nespoli\nSergey Ryazansky\nRandolph Bresnik Paolo Nespoli Sergey Ryazansky ['Randolph Bresnik', 'Paolo Nespoli', 'Sergey Ryazansky']\nAlexander Misurkin\nMark Vande Hei\nJoseph Acaba\nAlexander Misurkin Mark Vande Hei Joseph Acaba ['Alexander Misurkin', 'Mark Vande Hei', 'Joseph Acaba']\nAlexander Misurkin\nMark Vande Hei\nJoseph Acaba\nAlexander Misurkin Mark Vande Hei Joseph Acaba ['Alexander Misurkin', 'Mark Vande Hei', 'Joseph Acaba']\nAnton Shkaplerov\nScott Tingle\nNorishige Kanai\nAnton Shkaplerov Scott Tingle Norishige Kanai ['Anton Shkaplerov', 'Scott Tingle', 'Norishige Kanai']\nAnton Shkaplerov\nScott Tingle\nNorishige Kanai\nAnton Shkaplerov Scott Tingle Norishige Kanai ['Anton Shkaplerov', 'Scott Tingle', 'Norishige Kanai']\nAndrew Feustel\nOleg Artemyev\nRichard Arnold\nAndrew Feustel Oleg Artemyev Richard Arnold ['Andrew Feustel', 'Oleg Artemyev', 'Richard Arnold']\nAndrew Feustel\nOleg Artemyev\nRichard Arnold\nAndrew Feustel Oleg Artemyev Richard Arnold ['Andrew Feustel', 'Oleg Artemyev', 'Richard Arnold']\nAlexander Gerst\nSergey Prokopyev\nSerena Auñón-Chancellor\nAlexander Gerst Sergey Prokopyev Serena Auñón-Chancellor ['Alexander Gerst', 'Sergey Prokopyev', 'Serena Auñón-Chancellor']\nAlexander Gerst\nSergey Prokopyev\nSerena Auñón-Chancellor\nAlexander Gerst Sergey Prokopyev Serena Auñón-Chancellor ['Alexander Gerst', 'Sergey Prokopyev', 'Serena Auñón-Chancellor']\nOleg Kononenko\nDavid Saint-Jacques\nAnne McClain\nOleg Kononenko David Saint-Jacques Anne McClain ['Oleg Kononenko', 'David Saint-Jacques', 'Anne McClain']\nOleg Kononenko\nDavid Saint-Jacques\nAnne McClain\nOleg Kononenko David Saint-Jacques Anne McClain ['Oleg Kononenko', 'David Saint-Jacques', 'Anne McClain']\nOleg Kononenko\nDavid Saint-Jacques\nAnne McClain\nOleg Kononenko David Saint-Jacques Anne McClain ['Oleg Kononenko', 'David Saint-Jacques', 'Anne McClain']\nAleksey Ovchinin\nAleksey Ovchinin Christina Koch Nick Hague ['Aleksey Ovchinin']\n"
],
[
"df.loc[[i]][['Expedition','Launch date','Duration(days)']]",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba6333d1f76ed32051fb45a3376faaa1c292174
| 32,242 |
ipynb
|
Jupyter Notebook
|
Prediction models/SIR_model.ipynb
|
anuradhakar49/Coro-Lib
|
49e42a48c433bd50267bc779f748fb6467d8b5fe
|
[
"MIT"
] | null | null | null |
Prediction models/SIR_model.ipynb
|
anuradhakar49/Coro-Lib
|
49e42a48c433bd50267bc779f748fb6467d8b5fe
|
[
"MIT"
] | null | null | null |
Prediction models/SIR_model.ipynb
|
anuradhakar49/Coro-Lib
|
49e42a48c433bd50267bc779f748fb6467d8b5fe
|
[
"MIT"
] | null | null | null | 266.46281 | 27,858 | 0.901526 |
[
[
[
"Source: https://scipython.com",
"_____no_output_____"
],
[
" The SIR epidemic model\n\nA simple mathematical description of the spread of a disease in a population is the so-called SIR model, which divides the (fixed) population of N\nindividuals into three \"compartments\" which may vary as a function of time, t\n\nS(t) are those susceptible but not yet infected with the disease;\nI(t) is the number of infectious individuals;\nR(t) are those individuals who have recovered from the disease and now have immunity to it.\n\nThe SIR model describes the change in the population of each of these compartments in terms of two parameters, β\nand γ. β describes the effective contact rate of the disease: an infected individual comes into contact with βN other individuals per unit time (of which the fraction that are susceptible to contracting the disease is S/N). γ is the mean recovery rate: that is, 1/γ is the mean period of time during which an infected individual can pass it on.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# Total population, N.\nN = 1000\n# Initial number of infected and recovered individuals, I0 and R0.\nI0, R0 = 1, 0\n# Everyone else, S0, is susceptible to infection initially.\nS0 = N - I0 - R0\n# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\nbeta, gamma = 0.2, 1./10 \n# A grid of time points (in days)\nt = np.linspace(0, 160, 160)\n\n# The SIR model differential equations.\ndef deriv(y, t, N, beta, gamma):\n S, I, R = y\n dSdt = -beta * S * I / N\n dIdt = beta * S * I / N - gamma * I\n dRdt = gamma * I\n return dSdt, dIdt, dRdt\n\n# Initial conditions vector\ny0 = S0, I0, R0\n# Integrate the SIR equations over the time grid, t.\nret = odeint(deriv, y0, t, args=(N, beta, gamma))\nS, I, R = ret.T\n\n# Plot the data on three separate curves for S(t), I(t) and R(t)\nfig = plt.figure(facecolor='w')\nax = fig.add_subplot(111, facecolor='#dddddd', axisbelow=True)\nax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible')\nax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected')\nax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity')\nax.set_xlabel('Time /days')\nax.set_ylabel('Number (1000s)')\nax.set_ylim(0,1.2)\nax.yaxis.set_tick_params(length=0)\nax.xaxis.set_tick_params(length=0)\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\nlegend = ax.legend()\nlegend.get_frame().set_alpha(0.5)\nfor spine in ('top', 'right', 'bottom', 'left'):\n ax.spines[spine].set_visible(False)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
]
] |
cba633d231be774e35cd40b584ad74c787bb9fe8
| 872,609 |
ipynb
|
Jupyter Notebook
|
CarND-Object-Detection-Lab.ipynb
|
sfefilatyev/CarND-Object-Detection-Lab
|
7da448411624469124083f9edda978d33083b0fa
|
[
"MIT"
] | null | null | null |
CarND-Object-Detection-Lab.ipynb
|
sfefilatyev/CarND-Object-Detection-Lab
|
7da448411624469124083f9edda978d33083b0fa
|
[
"MIT"
] | null | null | null |
CarND-Object-Detection-Lab.ipynb
|
sfefilatyev/CarND-Object-Detection-Lab
|
7da448411624469124083f9edda978d33083b0fa
|
[
"MIT"
] | null | null | null | 885.897462 | 819,200 | 0.951224 |
[
[
[
"# CarND Object Detection Lab\n\nLet's get started!",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageColor\nimport time\nfrom scipy.stats import norm\n\n%matplotlib inline\nplt.style.use('ggplot')",
"_____no_output_____"
]
],
[
[
"## MobileNets\n\n[*MobileNets*](https://arxiv.org/abs/1704.04861), as the name suggests, are neural networks constructed for the purpose of running very efficiently (high FPS, low memory footprint) on mobile and embedded devices. *MobileNets* achieve this with 3 techniques:\n\n1. Perform a depthwise convolution followed by a 1x1 convolution rather than a standard convolution. The 1x1 convolution is called a pointwise convolution if it's following a depthwise convolution. The combination of a depthwise convolution followed by a pointwise convolution is sometimes called a separable depthwise convolution.\n2. Use a \"width multiplier\" - reduces the size of the input/output channels, set to a value between 0 and 1.\n3. Use a \"resolution multiplier\" - reduces the size of the original input, set to a value between 0 and 1.\n\nThese 3 techniques reduce the size of cummulative parameters and therefore the computation required. Of course, generally models with more paramters achieve a higher accuracy. *MobileNets* are no silver bullet, while they perform very well larger models will outperform them. ** *MobileNets* are designed for mobile devices, NOT cloud GPUs**. The reason we're using them in this lab is automotive hardware is closer to mobile or embedded devices than beefy cloud GPUs.",
"_____no_output_____"
],
[
"### Convolutions\n\n#### Vanilla Convolution\n\nBefore we get into the *MobileNet* convolution block let's take a step back and recall the computational cost of a vanilla convolution. There are $N$ kernels of size $D_k * D_k$. Each of these kernels goes over the entire input which is a $D_f * D_f * M$ sized feature map or tensor (if that makes more sense). The computational cost is:\n\n$$\nD_g * D_g * M * N * D_k * D_k\n$$\n\nLet $D_g * D_g$ be the size of the output feature map. Then a standard convolution takes in a $D_f * D_f * M$ input feature map and returns a $D_g * D_g * N$ feature map as output.\n\n(*Note*: In the MobileNets paper, you may notice the above equation for computational cost uses $D_f$ instead of $D_g$. In the paper, they assume the output and input are the same spatial dimensions due to stride of 1 and padding, so doing so does not make a difference, but this would want $D_g$ for different dimensions of input and output.)\n\n\n\n\n\n#### Depthwise Convolution\n\nA depthwise convolution acts on each input channel separately with a different kernel. $M$ input channels implies there are $M$ $D_k * D_k$ kernels. Also notice this results in $N$ being set to 1. If this doesn't make sense, think about the shape a kernel would have to be to act upon an individual channel.\n\nComputation cost:\n\n$$\nD_g * D_g * M * D_k * D_k\n$$\n\n\n\n\n\n#### Pointwise Convolution\n\nA pointwise convolution performs a 1x1 convolution, it's the same as a vanilla convolution except the kernel size is $1 * 1$.\n\nComputation cost:\n\n$$\nD_k * D_k * D_g * D_g * M * N =\n1 * 1 * D_g * D_g * M * N =\nD_g * D_g * M * N\n$$\n\n\n\n\n\nThus the total computation cost is for separable depthwise convolution:\n\n$$\nD_g * D_g * M * D_k * D_k + D_g * D_g * M * N\n$$\n\nwhich results in $\\frac{1}{N} + \\frac{1}{D_k^2}$ reduction in computation:\n\n$$\n\\frac {D_g * D_g * M * D_k * D_k + D_g * D_g * M * N} {D_g * D_g * M * N * D_k * D_k} = \n\\frac {D_k^2 + N} {D_k^2*N} = \n\\frac {1}{N} + \\frac{1}{D_k^2}\n$$\n\n*MobileNets* use a 3x3 kernel, so assuming a large enough $N$, separable depthwise convnets are ~9x more computationally efficient than vanilla convolutions!",
"_____no_output_____"
],
[
"### Width Multiplier\n\nThe 2nd technique for reducing the computational cost is the \"width multiplier\" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\\alpha$. $\\alpha$ reduces the number of input and output channels proportionally:\n\n$$\nD_f * D_f * \\alpha M * D_k * D_k + D_f * D_f * \\alpha M * \\alpha N\n$$",
"_____no_output_____"
],
[
"### Resolution Multiplier\n\nThe 3rd technique for reducing the computational cost is the \"resolution multiplier\" which is a hyperparameter inhabiting the range [0, 1] denoted here as $\\rho$. $\\rho$ reduces the size of the input feature map:\n\n$$\n\\rho D_f * \\rho D_f * M * D_k * D_k + \\rho D_f * \\rho D_f * M * N\n$$",
"_____no_output_____"
],
[
"Combining the width and resolution multipliers results in a computational cost of:\n\n$$\n\\rho D_f * \\rho D_f * a M * D_k * D_k + \\rho D_f * \\rho D_f * a M * a N\n$$\n\nTraining *MobileNets* with different values of $\\alpha$ and $\\rho$ will result in different speed vs. accuracy tradeoffs. The folks at Google have run these experiments, the result are shown in the graphic below:\n\n",
"_____no_output_____"
],
[
"MACs (M) represents the number of multiplication-add operations in the millions.",
"_____no_output_____"
],
[
"### Exercise 1 - Implement Separable Depthwise Convolution\n\nIn this exercise you'll implement a separable depthwise convolution block and compare the number of parameters to a standard convolution block. For this exercise we'll assume the width and resolution multipliers are set to 1.\n\nDocs:\n\n* [depthwise convolution](https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)",
"_____no_output_____"
]
],
[
[
"def vanilla_conv_block(x, kernel_size, output_channels):\n \"\"\"\n Vanilla Conv -> Batch Norm -> ReLU\n \"\"\"\n x = tf.layers.conv2d(\n x, output_channels, kernel_size, (2, 2), padding='SAME')\n x = tf.layers.batch_normalization(x)\n return tf.nn.relu(x)\n\n# TODO: implement MobileNet conv block\ndef mobilenet_conv_block(x, kernel_size, output_channels):\n \"\"\"\n Depthwise Conv -> Batch Norm -> ReLU -> Pointwise Conv -> Batch Norm -> ReLU\n \"\"\"\n # assumes BHWC format\n input_channel_dim = x.get_shape().as_list()[-1] \n W = tf.Variable(tf.truncated_normal((kernel_size, kernel_size, input_channel_dim, 1)))\n\n # depthwise conv\n x = tf.nn.depthwise_conv2d(x, W, (1, 2, 2, 1), padding='SAME')\n x = tf.layers.batch_normalization(x)\n x = tf.nn.relu(x)\n\n # pointwise conv\n x = tf.layers.conv2d(x, output_channels, (1, 1), padding='SAME')\n x = tf.layers.batch_normalization(x)\n return tf.nn.relu(x)",
"_____no_output_____"
]
],
[
[
"**[Sample solution](./exercise-solutions/e1.py)**\n\nLet's compare the number of parameters in each block.",
"_____no_output_____"
]
],
[
[
"# constants but you can change them so I guess they're not so constant :)\nINPUT_CHANNELS = 32\nOUTPUT_CHANNELS = 512\nKERNEL_SIZE = 3\nIMG_HEIGHT = 256\nIMG_WIDTH = 256\n\nwith tf.Session(graph=tf.Graph()) as sess:\n # input\n x = tf.constant(np.random.randn(1, IMG_HEIGHT, IMG_WIDTH, INPUT_CHANNELS), dtype=tf.float32)\n\n with tf.variable_scope('vanilla'):\n vanilla_conv = vanilla_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS)\n with tf.variable_scope('mobile'):\n mobilenet_conv = mobilenet_conv_block(x, KERNEL_SIZE, OUTPUT_CHANNELS)\n\n vanilla_params = [\n (v.name, np.prod(v.get_shape().as_list()))\n for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'vanilla')\n ]\n mobile_params = [\n (v.name, np.prod(v.get_shape().as_list()))\n for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'mobile')\n ]\n\n print(\"VANILLA CONV BLOCK\")\n total_vanilla_params = sum([p[1] for p in vanilla_params])\n for p in vanilla_params:\n print(\"Variable {0}: number of params = {1}\".format(p[0], p[1]))\n print(\"Total number of params =\", total_vanilla_params)\n print()\n\n print(\"MOBILENET CONV BLOCK\")\n total_mobile_params = sum([p[1] for p in mobile_params])\n for p in mobile_params:\n print(\"Variable {0}: number of params = {1}\".format(p[0], p[1]))\n print(\"Total number of params =\", total_mobile_params)\n print()\n\n print(\"{0:.3f}x parameter reduction\".format(total_vanilla_params /\n total_mobile_params))",
"WARNING: Logging before flag parsing goes to stderr.\nW0907 19:00:04.141232 140019501975360 deprecation.py:323] From <ipython-input-2-8486de148bd7>:6: conv2d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.keras.layers.Conv2D` instead.\nW0907 19:00:04.145168 140019501975360 deprecation.py:506] From /usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling __init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\nInstructions for updating:\nCall initializer instance with the dtype argument instead of passing it to the constructor\nW0907 19:00:04.310260 140019501975360 deprecation.py:323] From <ipython-input-2-8486de148bd7>:7: batch_normalization (from tensorflow.python.layers.normalization) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.BatchNormalization instead. In particular, `tf.control_dependencies(tf.GraphKeys.UPDATE_OPS)` should not be used (consult the `tf.keras.layers.batch_normalization` documentation).\n"
]
],
[
[
"Your solution should show the majority of the parameters in *MobileNet* block stem from the pointwise convolution.",
"_____no_output_____"
],
[
"## *MobileNet* SSD\n\nIn this section you'll use a pretrained *MobileNet* [SSD](https://arxiv.org/abs/1512.02325) model to perform object detection. You can download the *MobileNet* SSD and other models from the [TensorFlow detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) (*note*: we'll provide links to specific models further below). [Paper](https://arxiv.org/abs/1611.10012) describing comparing several object detection models.\n\nAlright, let's get into SSD!",
"_____no_output_____"
],
[
"### Single Shot Detection (SSD)\n\nMany previous works in object detection involve more than one training phase. For example, the [Faster-RCNN](https://arxiv.org/abs/1506.01497) architecture first trains a Region Proposal Network (RPN) which decides which regions of the image are worth drawing a box around. RPN is then merged with a pretrained model for classification (classifies the regions). The image below is an RPN:\n\n",
"_____no_output_____"
],
[
"The SSD architecture is a single convolutional network which learns to predict bounding box locations and classify the locations in one pass. Put differently, SSD can be trained end to end while Faster-RCNN cannot. The SSD architecture consists of a base network followed by several convolutional layers: \n\n\n\n**NOTE:** In this lab the base network is a MobileNet (instead of VGG16.)\n\n#### Detecting Boxes\n\nSSD operates on feature maps to predict bounding box locations. Recall a feature map is of size $D_f * D_f * M$. For each feature map location $k$ bounding boxes are predicted. Each bounding box carries with it the following information:\n\n* 4 corner bounding box **offset** locations $(cx, cy, w, h)$\n* $C$ class probabilities $(c_1, c_2, ..., c_p)$\n\nSSD **does not** predict the shape of the box, rather just where the box is. The $k$ bounding boxes each have a predetermined shape. This is illustrated in the figure below:\n\n\n\nThe shapes are set prior to actual training. For example, In figure (c) in the above picture there are 4 boxes, meaning $k$ = 4.",
"_____no_output_____"
],
[
"### Exercise 2 - SSD Feature Maps\n\nIt would be a good exercise to read the SSD paper prior to a answering the following questions.\n\n***Q: Why does SSD use several differently sized feature maps to predict detections?***",
"_____no_output_____"
],
[
"A: Your answer here\n\n**[Sample answer](./exercise-solutions/e2.md)**",
"_____no_output_____"
],
[
"The current approach leaves us with thousands of bounding box candidates, clearly the vast majority of them are nonsensical.\n\n### Exercise 3 - Filtering Bounding Boxes\n\n***Q: What are some ways which we can filter nonsensical bounding boxes?***",
"_____no_output_____"
],
[
"A: Your answer here\n\n**[Sample answer](./exercise-solutions/e3.md)**",
"_____no_output_____"
],
[
"#### Loss\n\nWith the final set of matched boxes we can compute the loss:\n\n$$\nL = \\frac {1} {N} * ( L_{class} + L_{box})\n$$\n\nwhere $N$ is the total number of matched boxes, $L_{class}$ is a softmax loss for classification, and $L_{box}$ is a L1 smooth loss representing the error of the matched boxes with the ground truth boxes. L1 smooth loss is a modification of L1 loss which is more robust to outliers. In the event $N$ is 0 the loss is set 0.\n\n",
"_____no_output_____"
],
[
"### SSD Summary\n\n* Starts from a base model pretrained on ImageNet. \n* The base model is extended by several convolutional layers.\n* Each feature map is used to predict bounding boxes. Diversity in feature map size allows object detection at different resolutions.\n* Boxes are filtered by IoU metrics and hard negative mining.\n* Loss is a combination of classification (softmax) and dectection (smooth L1)\n* Model can be trained end to end.",
"_____no_output_____"
],
[
"## Object Detection Inference\n\nIn this part of the lab you'll detect objects using pretrained object detection models. You can download the latest pretrained models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md), although do note that you may need a newer version of TensorFlow (such as v1.8) in order to use the newest models.\n\nWe are providing the download links for the below noted files to ensure compatibility between the included environment file and the models.\n\n[SSD_Mobilenet 11.6.17 version](http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_11_06_2017.tar.gz)\n\n[RFCN_ResNet101 11.6.17 version](http://download.tensorflow.org/models/object_detection/rfcn_resnet101_coco_11_06_2017.tar.gz)\n\n[Faster_RCNN_Inception_ResNet 11.6.17 version](http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017.tar.gz)\n\nMake sure to extract these files prior to continuing!",
"_____no_output_____"
]
],
[
[
"# Frozen inference graph files. NOTE: change the path to where you saved the models.\nSSD_GRAPH_FILE = 'assets/ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb'\nRFCN_GRAPH_FILE = 'assets/rfcn_resnet101_coco_11_06_2017/frozen_inference_graph.pb'\nFASTER_RCNN_GRAPH_FILE = 'assets/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017/frozen_inference_graph.pb'",
"_____no_output_____"
]
],
[
[
"Below are utility functions. The main purpose of these is to draw the bounding boxes back onto the original image.",
"_____no_output_____"
]
],
[
[
"# Colors (one for each class)\ncmap = ImageColor.colormap\nprint(\"Number of colors =\", len(cmap))\nCOLOR_LIST = sorted([c for c in cmap.keys()])\n\n#\n# Utility funcs\n#\n\ndef filter_boxes(min_score, boxes, scores, classes):\n \"\"\"Return boxes with a confidence >= `min_score`\"\"\"\n n = len(classes)\n idxs = []\n for i in range(n):\n if scores[i] >= min_score:\n idxs.append(i)\n \n filtered_boxes = boxes[idxs, ...]\n filtered_scores = scores[idxs, ...]\n filtered_classes = classes[idxs, ...]\n return filtered_boxes, filtered_scores, filtered_classes\n\ndef to_image_coords(boxes, height, width):\n \"\"\"\n The original box coordinate output is normalized, i.e [0, 1].\n \n This converts it back to the original coordinate based on the image\n size.\n \"\"\"\n box_coords = np.zeros_like(boxes)\n box_coords[:, 0] = boxes[:, 0] * height\n box_coords[:, 1] = boxes[:, 1] * width\n box_coords[:, 2] = boxes[:, 2] * height\n box_coords[:, 3] = boxes[:, 3] * width\n \n return box_coords\n\ndef draw_boxes(image, boxes, classes, thickness=4):\n \"\"\"Draw bounding boxes on the image\"\"\"\n draw = ImageDraw.Draw(image)\n for i in range(len(boxes)):\n bot, left, top, right = boxes[i, ...]\n class_id = int(classes[i])\n color = COLOR_LIST[class_id]\n draw.line([(left, top), (left, bot), (right, bot), (right, top), (left, top)], width=thickness, fill=color)\n \ndef load_graph(graph_file):\n \"\"\"Loads a frozen inference graph\"\"\"\n graph = tf.Graph()\n with graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(graph_file, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n return graph",
"('Number of colors =', 147)\n"
]
],
[
[
"Below we load the graph and extract the relevant tensors using [`get_tensor_by_name`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). These tensors reflect the input and outputs of the graph, or least the ones we care about for detecting objects.",
"_____no_output_____"
]
],
[
[
"detection_graph = load_graph(SSD_GRAPH_FILE)\n#detection_graph = load_graph(RFCN_GRAPH_FILE)\n#detection_graph = load_graph(FASTER_RCNN_GRAPH_FILE)\n\n# The input placeholder for the image.\n# `get_tensor_by_name` returns the Tensor with the associated name in the Graph.\nimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n\n# Each box represents a part of the image where a particular object was detected.\ndetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n\n# Each score represent how level of confidence for each of the objects.\n# Score is shown on the result image, together with the class label.\ndetection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n\n# The classification of the object (integer id).\ndetection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n\nprint detection_graph",
"<tensorflow.python.framework.ops.Graph object at 0x7f5571f55490>\n"
]
],
[
[
"Run detection and classification on a sample image.",
"_____no_output_____"
]
],
[
[
"# Load a sample image.\nimage = Image.open('./assets/sample1.jpg')\nimage_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)\n\nwith tf.Session(graph=detection_graph) as sess: \n # Actual detection.\n (boxes, scores, classes) = sess.run([detection_boxes, detection_scores, detection_classes], \n feed_dict={image_tensor: image_np})\n\n # Remove unnecessary dimensions\n boxes = np.squeeze(boxes)\n scores = np.squeeze(scores)\n classes = np.squeeze(classes)\n\n confidence_cutoff = 0.8\n # Filter boxes with a confidence score less than `confidence_cutoff`\n boxes, scores, classes = filter_boxes(confidence_cutoff, boxes, scores, classes)\n\n # The current box coordinates are normalized to a range between 0 and 1.\n # This converts the coordinates actual location on the image.\n width, height = image.size\n box_coords = to_image_coords(boxes, height, width)\n\n # Each class with be represented by a differently colored box\n draw_boxes(image, box_coords, classes)\n\n plt.figure(figsize=(12, 8))\n plt.imshow(image) ",
"_____no_output_____"
]
],
[
[
"## Timing Detection\n\nThe model zoo comes with a variety of models, each its benefits and costs. Below you'll time some of these models. The general tradeoff being sacrificing model accuracy for seconds per frame (SPF).",
"_____no_output_____"
]
],
[
[
"def time_detection(sess, img_height, img_width, runs=10):\n image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')\n detection_classes = sess.graph.get_tensor_by_name('detection_classes:0')\n\n # warmup\n gen_image = np.uint8(np.random.randn(1, img_height, img_width, 3))\n sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: gen_image})\n \n times = np.zeros(runs)\n for i in range(runs):\n t0 = time.time()\n sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: image_np})\n t1 = time.time()\n times[i] = (t1 - t0) * 1000\n return times",
"_____no_output_____"
],
[
"with tf.Session(graph=detection_graph) as sess:\n times = time_detection(sess, 600, 1000, runs=10)",
"_____no_output_____"
],
[
"# Create a figure instance\nfig = plt.figure(1, figsize=(9, 6))\n\n# Create an axes instance\nax = fig.add_subplot(111)\nplt.title(\"Object Detection Timings\")\nplt.ylabel(\"Time (ms)\")\n\n# Create the boxplot\nplt.style.use('fivethirtyeight')\nbp = ax.boxplot(times)",
"_____no_output_____"
]
],
[
[
"### Exercise 4 - Model Tradeoffs\n\nDownload a few models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) and compare the timings.",
"_____no_output_____"
],
[
"## Detection on a Video\n\nFinally run your pipeline on [this short video](https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/advanced_deep_learning/driving.mp4).",
"_____no_output_____"
]
],
[
[
"# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML",
"Imageio: 'ffmpeg-linux64-v3.3.1' was not found on your computer; downloading it now.\nTry 1. Download from https://github.com/imageio/imageio-binaries/raw/master/ffmpeg/ffmpeg-linux64-v3.3.1 (43.8 MB)\nDownloading: 8192/45929032 bytes (0.0409600/45929032 bytes (0.91294336/45929032 bytes (2.8%2097152/45929032 bytes (4.6%2998272/45929032 bytes (6.5%3899392/45929032 bytes (8.5%4800512/45929032 bytes (10.55701632/45929032 bytes (12.46602752/45929032 bytes (14.47503872/45929032 bytes (16.38404992/45929032 bytes (18.39314304/45929032 bytes (20.310199040/45929032 bytes (22.2%11091968/45929032 bytes (24.2%11993088/45929032 bytes (26.1%12894208/45929032 bytes (28.1%13795328/45929032 bytes (30.0%14696448/45929032 bytes (32.0%15581184/45929032 bytes (33.9%16482304/45929032 bytes (35.9%17375232/45929032 bytes (37.8%18268160/45929032 bytes (39.8%19161088/45929032 bytes (41.7%20054016/45929032 bytes (43.7%20955136/45929032 bytes (45.6%21856256/45929032 bytes (47.6%22757376/45929032 bytes (49.5%23658496/45929032 bytes (51.5%24551424/45929032 bytes (53.5%25444352/45929032 bytes (55.4%26345472/45929032 bytes (57.4%27246592/45929032 bytes (59.3%28139520/45929032 bytes (61.3%29032448/45929032 bytes (63.2%29933568/45929032 bytes (65.2%30834688/45929032 bytes (67.1%31727616/45929032 bytes (69.1%32620544/45929032 bytes (71.0%33521664/45929032 bytes (73.0%34414592/45929032 bytes (74.9%35307520/45929032 bytes (76.9%36208640/45929032 bytes (78.8%37093376/45929032 bytes (80.8%37994496/45929032 bytes (82.7%38887424/45929032 bytes (84.7%39780352/45929032 bytes (86.6%40681472/45929032 bytes (88.6%41582592/45929032 bytes (90.5%42483712/45929032 bytes (92.5%43376640/45929032 bytes (94.4%44269568/45929032 bytes (96.4%45154304/45929032 bytes (98.3%45929032/45929032 bytes (100.0%)\n Done\nFile saved as /home/sfefilatyev/.imageio/ffmpeg/ffmpeg-linux64-v3.3.1.\n"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"600\" controls>\n <source src=\"{0}\" type=\"video/mp4\">\n</video>\n\"\"\".format('driving.mp4'))",
"_____no_output_____"
]
],
[
[
"### Exercise 5 - Object Detection on a Video\n\nRun an object detection pipeline on the above clip.",
"_____no_output_____"
]
],
[
[
"clip = VideoFileClip('driving.mp4')",
"_____no_output_____"
],
[
"# TODO: Complete this function.\n# The input is an NumPy array.\n# The output should also be a NumPy array.\ndef pipeline(img):\n draw_img = Image.fromarray(img)\n boxes, scores, classes = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: np.expand_dims(img, 0)})\n # Remove unnecessary dimensions\n boxes = np.squeeze(boxes)\n scores = np.squeeze(scores)\n classes = np.squeeze(classes)\n\n confidence_cutoff = 0.8\n # Filter boxes with a confidence score less than `confidence_cutoff`\n boxes, scores, classes = filter_boxes(confidence_cutoff, boxes, scores, classes)\n\n # The current box coordinates are normalized to a range between 0 and 1.\n # This converts the coordinates actual location on the image.\n width, height = draw_img.size\n box_coords = to_image_coords(boxes, height, width)\n\n # Each class with be represented by a differently colored box\n draw_boxes(draw_img, box_coords, classes)\n return np.array(draw_img)",
"_____no_output_____"
]
],
[
[
"**[Sample solution](./exercise-solutions/e5.py)**",
"_____no_output_____"
]
],
[
[
"with tf.Session(graph=detection_graph) as sess:\n image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')\n detection_classes = sess.graph.get_tensor_by_name('detection_classes:0')\n \n new_clip = clip.fl_image(pipeline)\n \n # write to file\n new_clip.write_videofile('result.mp4')",
"chunk: 23%|██▎ | 296/1311 [00:00<00:00, 2954.54it/s, now=None]"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"600\" controls>\n <source src=\"{0}\" type=\"video/mp4\">\n</video>\n\"\"\".format('result.mp4'))",
"_____no_output_____"
]
],
[
[
"## Further Exploration\n\nSome ideas to take things further:\n\n* Finetune the model on a new dataset more relevant to autonomous vehicles. Instead of loading the frozen inference graph you'll load the checkpoint.\n* Optimize the model and get the FPS as low as possible.\n* Build your own detector. There are several base model pretrained on ImageNet you can choose from. [Keras](https://keras.io/applications/) is probably the quickest way to get setup in this regard.\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cba639d430b6b33968aa38cb72be35f5b8a2d0ae
| 11,952 |
ipynb
|
Jupyter Notebook
|
SkosToYaml.ipynb
|
GROCCAD/importer-asn
|
d000a029ed07446eb4aa284811cec532b2abf21e
|
[
"MIT"
] | null | null | null |
SkosToYaml.ipynb
|
GROCCAD/importer-asn
|
d000a029ed07446eb4aa284811cec532b2abf21e
|
[
"MIT"
] | null | null | null |
SkosToYaml.ipynb
|
GROCCAD/importer-asn
|
d000a029ed07446eb4aa284811cec532b2abf21e
|
[
"MIT"
] | null | null | null | 31.787234 | 342 | 0.584839 |
[
[
[
"import requests\nimport rdflib\nfrom rdflib import Graph\nfrom itertools import groupby\n\nfrom rdfutils import get_vocab_props, get_terms_props\nfrom rdfutils import skos_to_terms\n",
"_____no_output_____"
],
[
"skos_sample = 'http://s3.amazonaws.com/jestaticd2l/purl/scheme/ASNPublicationStatus'\ng = Graph()\ng.parse(skos_sample, format='xml')\n\n",
"_____no_output_____"
],
[
"vocab_data = skos_to_terms(g)",
"found concept_scheme= http://purl.org/ASN/scheme/ASNPublicationStatus/\nfound 3 concepts\n"
],
[
"import yaml\nprint(yaml.dump(vocab_data, sort_keys=False))",
"type: ControlledVocabulary\nname: ASNPublicationStatus\nuri: http://purl.org/ASN/scheme/ASNPublicationStatus/\ndescription: A vocabulary describing the various publication statuses of ASN documents\n and statements.\ntitle: ASN Publication Status Vocabulary\nterms:\n- term: Deprecated\n label: Deprecated\n definition: Status assigned to a document/statement by the promulgating agency or\n by the ASN Directorate on request of the promulgating agency asserting that the\n document/statement has been superseded or its use otherwise disfavored. Documents/statements\n are never removed from the ASN and never become dereferencable.\n source_uri: http://purl.org/ASN/scheme/ASNPublicationStatus/Deprecated\n- term: Draft\n label: Draft\n definition: A status assigned to all documents/statements during development. Draft\n documents and statements should not be displayed to anyone other than their owners\n and ASN Directorate administrators.\n source_uri: http://purl.org/ASN/scheme/ASNPublicationStatus/Draft\n- term: Published\n label: Published\n definition: Status assigned to all documents that have been submitted by their owners\n to the ASN Directorate and, upon quality review, published.\n source_uri: http://purl.org/ASN/scheme/ASNPublicationStatus/Published\n\n"
],
[
"get_vocab_props(g)",
"found concept_scheme= http://purl.org/ASN/scheme/ASNPublicationStatus/\n"
],
[
"get_terms_props(g)",
"found concepts= [rdflib.term.URIRef('http://purl.org/ASN/scheme/ASNPublicationStatus/Published'), rdflib.term.URIRef('http://purl.org/ASN/scheme/ASNPublicationStatus/Deprecated'), rdflib.term.URIRef('http://purl.org/ASN/scheme/ASNPublicationStatus/Draft')]\n"
],
[
"from rdfutils import get_types, get_subjects_by_type, TYPE_PRED, build_class_props_map\n\n",
"_____no_output_____"
],
[
"get_types(g)",
"_____no_output_____"
],
[
"CONCEPT_PRED = get_types(g)[0]\nCONCEPT_SCHEME_PRED = get_types(g)[1]",
"_____no_output_____"
],
[
"scheme = list(get_subjects_by_type(g, CONCEPT_SCHEME_PRED))[0]\nscheme",
"_____no_output_____"
],
[
"list(get_subjects_by_type(g, CONCEPT_PRED))",
"_____no_output_____"
],
[
"list(g.predicate_objects(subject=scheme))",
"_____no_output_____"
],
[
"list(g.namespaces())",
"_____no_output_____"
],
[
"# dates as STR\nl = rdflib.term.Literal('2009-02-12', datatype=rdflib.term.URIRef('http://purl.org/dc/terms/W3CDTF'))\nstr(l)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba647d97b3485c52042a260ef094d3042e7466f
| 30,018 |
ipynb
|
Jupyter Notebook
|
test/influx/pandas_influx_csv_real.ipynb
|
csaladenes/csaladenes.github.io
|
b585ab399df169189a16164bc37d51ccd6cd5ef4
|
[
"MIT"
] | 2 |
2018-11-15T09:59:50.000Z
|
2020-01-01T09:35:20.000Z
|
test/influx/pandas_influx_csv_real.ipynb
|
csaladenes/csaladenes.github.io
|
b585ab399df169189a16164bc37d51ccd6cd5ef4
|
[
"MIT"
] | 1 |
2017-04-21T01:54:52.000Z
|
2017-04-21T01:56:55.000Z
|
test/influx/pandas_influx_csv_real.ipynb
|
csaladenes/csaladenes.github.io
|
b585ab399df169189a16164bc37d51ccd6cd5ef4
|
[
"MIT"
] | 2 |
2017-11-06T15:29:32.000Z
|
2021-03-30T15:49:38.000Z
| 54.380435 | 1,815 | 0.584283 |
[
[
[
"import pandas as pd\nfrom influxdb import DataFrameClient",
"_____no_output_____"
],
[
"user = 'root'\npassword = 'root'\ndbname = 'base47'\nhost='localhost'\nport=32768\n# Temporarily avoid line protocol time conversion issues #412, #426, #431.\nprotocol = 'json'\nclient = DataFrameClient(host, port, user, password, dbname)",
"_____no_output_____"
],
[
"print(\"Create pandas DataFrame\")\ndf = pd.DataFrame(data=list(range(30)),\n index=pd.date_range(start='2017-11-16',\n periods=30, freq='H'))",
"Create pandas DataFrame\n"
],
[
"gas=pd.read_csv('data/gas_ft.csv',parse_dates=True,index_col='ts').drop('measurement_unit',axis=1)",
"_____no_output_____"
],
[
"#client.create_database(dbname)\nclient.query(\"show databases\")",
"_____no_output_____"
],
[
"#for i in range(len(gas)/500):\nn=5000\nfor i in range(5):\n print(i),\n print(\"Writing batch \"+str(i)+\" of \"+str(n)+\" elements to Influx | progress: \"+str(round(i*100.0/(len(gas)/n),2)))+\"%\"\n client.write_points(gas[n*i:n*(i+1)], 'gas', protocol=protocol)",
"0 Writing batch 0 of 5000 elements to Influx | progress: 0.0%\n1 Writing batch 1 of 5000 elements to Influx | progress: 1.14%\n2 Writing batch 2 of 5000 elements to Influx | progress: 2.27%\n3 Writing batch 3 of 5000 elements to Influx | progress: 3.41%\n4 Writing batch 4 of 5000 elements to Influx | progress: 4.55%\n"
],
[
"#https://influxdb-python.readthedocs.io/en/latest/api-documentation.html#dataframeclient",
"_____no_output_____"
],
[
"client.write_points(gas, 'gas', protocol=protocol, batch_size=5000)",
"_____no_output_____"
],
[
"client.write_points(gas, 'gas2', protocol=protocol, tag_columns=['monitor_id'], field_columns=['measurement'], batch_size=5000)",
"_____no_output_____"
],
[
"\nprint(\"Write DataFrame with Tags\")\nclient.write_points(df, 'demo',\n {'k1': 'v1', 'k2': 'v2'}, protocol=protocol)",
"Write DataFrame with Tags\n"
],
[
"print(\"Read DataFrame\")\nclient.query(\"select * from demo\")",
"Read DataFrame\n"
],
[
"\nprint(\"Delete database: \" + dbname)\nclient.drop_database(dbname)",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport time\nimport requests\nurl = 'http://localhost:32768/write'\nparams = {\"db\": \"base\", \"u\": \"root\", \"p\": \"root\"}",
"_____no_output_____"
],
[
"def read_data():\n with open('data/gas_ft.csv') as f:\n return [x.split(',') for x in f.readlines()[1:]]\n\na = read_data()",
"_____no_output_____"
],
[
"a[0]",
"_____no_output_____"
],
[
"#payload = \"elec,id=500 value=24 2018-03-05T19:31:00.000Z\\n\"\npayload = \"elec,id=500 value=24 \"#+str(pd.to_datetime('2018-03-05T19:29:00.000Z\\n').value // 10 ** 9)\nr = requests.post(url, params=params, data=payload)",
"_____no_output_____"
],
[
"# -*- coding: utf-8 -*-\n\"\"\"Tutorial how to use the class helper `SeriesHelper`.\"\"\"\n\nfrom influxdb import InfluxDBClient\nfrom influxdb import SeriesHelper\n\n# InfluxDB connections settings\nhost = 'localhost'\nport = 8086\nuser = 'root'\npassword = 'root'\ndbname = 'mydb'\n\nmyclient = InfluxDBClient(host, port, user, password, dbname)\n\n# Uncomment the following code if the database is not yet created\n# myclient.create_database(dbname)\n# myclient.create_retention_policy('awesome_policy', '3d', 3, default=True)\n\n\nclass MySeriesHelper(SeriesHelper):\n \"\"\"Instantiate SeriesHelper to write points to the backend.\"\"\"\n\n class Meta:\n \"\"\"Meta class stores time series helper configuration.\"\"\"\n\n # The client should be an instance of InfluxDBClient.\n client = myclient\n\n # The series name must be a string. Add dependent fields/tags\n # in curly brackets.\n series_name = 'events.stats.{server_name}'\n\n # Defines all the fields in this time series.\n fields = ['some_stat', 'other_stat']\n\n # Defines all the tags for the series.\n tags = ['server_name']\n\n # Defines the number of data points to store prior to writing\n # on the wire.\n bulk_size = 5\n\n # autocommit must be set to True when using bulk_size\n autocommit = True\n\n\n# The following will create *five* (immutable) data points.\n# Since bulk_size is set to 5, upon the fifth construction call, *all* data\n# points will be written on the wire via MySeriesHelper.Meta.client.\nMySeriesHelper(server_name='us.east-1', some_stat=159, other_stat=10)\nMySeriesHelper(server_name='us.east-1', some_stat=158, other_stat=20)\nMySeriesHelper(server_name='us.east-1', some_stat=157, other_stat=30)\nMySeriesHelper(server_name='us.east-1', some_stat=156, other_stat=40)\nMySeriesHelper(server_name='us.east-1', some_stat=155, other_stat=50)\n\n# To manually submit data points which are not yet written, call commit:\nMySeriesHelper.commit()\n\n# To inspect the JSON which will be written, call _json_body_():\nMySeriesHelper._json_body_()",
"_____no_output_____"
],
[
"for metric in a[:]:\n payload = \"elec,id=\"+str(metric[0])+\" value=\"+str(metric[2])+\" \"+str(pd.to_datetime(metric[3]).value // 10 ** 9)+\"\\n\"\n #payload = \"water,id=\"+str(metric[0])+\" value=\"+str(metric[2])+\"\\n\"\n r = requests.post(url, params=params, data=payload)",
"_____no_output_____"
],
[
"def read_data():\n with open('data/water_ft.csv') as f:\n return [x.split(',') for x in f.readlines()[1:]]\n\na = read_data()",
"_____no_output_____"
],
[
"a[0]",
"_____no_output_____"
],
[
"for metric in a[1000:3000]:\n #payload = \"gas,id=\"+str(metric[0])+\" value=\"+str(metric[2])+\" \"+str(pd.to_datetime(metric[3]).value // 10 ** 9)+\"\\n\"\n payload = \"water,id=\"+str(metric[0])+\" value=\"+str(metric[2])+\"\\n\"\n r = requests.post(url, params=params, data=payload)\n time.sleep(1)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba661fdc1a67d34367b15ba8cec0ac5bbef5d43
| 13,989 |
ipynb
|
Jupyter Notebook
|
Neural Machine Translation/3.gru-seq2seq-manual.ipynb
|
dxvo/NLP-Models-Tensorflow
|
79e319966cc201f48db9f4d5753c5acf54e26c79
|
[
"MIT"
] | 1 |
2018-12-17T21:55:00.000Z
|
2018-12-17T21:55:00.000Z
|
Neural Machine Translation/3.gru-seq2seq-manual.ipynb
|
dxvo/NLP-Models-Tensorflow
|
79e319966cc201f48db9f4d5753c5acf54e26c79
|
[
"MIT"
] | null | null | null |
Neural Machine Translation/3.gru-seq2seq-manual.ipynb
|
dxvo/NLP-Models-Tensorflow
|
79e319966cc201f48db9f4d5753c5acf54e26c79
|
[
"MIT"
] | null | null | null | 37.808108 | 249 | 0.539281 |
[
[
[
"import numpy as np\nimport tensorflow as tf\nimport collections",
"/usr/local/lib/python3.5/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n"
],
[
"def build_dataset(words, n_words):\n count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', 3]]\n count.extend(collections.Counter(words).most_common(n_words - 1))\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in words:\n index = dictionary.get(word, 0)\n if index == 0:\n unk_count += 1\n data.append(index)\n count[0][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, count, dictionary, reversed_dictionary",
"_____no_output_____"
],
[
"with open('english-train', 'r') as fopen:\n text_from = fopen.read().lower().split('\\n')\nwith open('vietnam-train', 'r') as fopen:\n text_to = fopen.read().lower().split('\\n')\nprint('len from: %d, len to: %d'%(len(text_from), len(text_to)))",
"len from: 501, len to: 501\n"
],
[
"concat_from = ' '.join(text_from).split()\nvocabulary_size_from = len(list(set(concat_from)))\ndata_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from)\nprint('vocab from size: %d'%(vocabulary_size_from))\nprint('Most common words', count_from[4:10])\nprint('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]])",
"vocab from size: 1935\nMost common words [(',', 564), ('.', 477), ('the', 368), ('and', 286), ('to', 242), ('of', 220)]\nSample data [567, 558, 79, 6, 139, 668, 10, 226, 817, 14] ['rachel', 'pike', ':', 'the', 'science', 'behind', 'a', 'climate', 'headline', 'in']\n"
],
[
"concat_to = ' '.join(text_to).split()\nvocabulary_size_to = len(list(set(concat_to)))\ndata_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to)\nprint('vocab to size: %d'%(vocabulary_size_to))\nprint('Most common words', count_to[4:10])\nprint('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]])",
"vocab to size: 1461\nMost common words [(',', 472), ('.', 430), ('tôi', 283), ('và', 230), ('có', 199), ('chúng', 196)]\nSample data [86, 22, 803, 76, 10, 414, 112, 34, 81, 316] ['khoa', 'học', 'đằng', 'sau', 'một', 'tiêu', 'đề', 'về', 'khí', 'hậu']\n"
],
[
"GO = dictionary_from['GO']\nPAD = dictionary_from['PAD']\nEOS = dictionary_from['EOS']\nUNK = dictionary_from['UNK']",
"_____no_output_____"
],
[
"class Chatbot:\n def __init__(self, size_layer, num_layers, embedded_size,\n from_dict_size, to_dict_size, learning_rate, batch_size):\n \n def cells(reuse=False):\n return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n \n self.X = tf.placeholder(tf.int32, [None, None])\n self.Y = tf.placeholder(tf.int32, [None, None])\n self.X_seq_len = tf.placeholder(tf.int32, [None])\n self.Y_seq_len = tf.placeholder(tf.int32, [None])\n \n encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1))\n decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1))\n encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input)\n rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n dtype = tf.float32)\n with tf.variable_scope(\"decoder\"):\n rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n initial_state = last_state,\n dtype = tf.float32)\n self.logits = tf.layers.dense(outputs,to_dict_size)\n masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n targets = self.Y,\n weights = masks)\n self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)",
"_____no_output_____"
],
[
"size_layer = 128\nnum_layers = 2\nembedded_size = 128\nlearning_rate = 0.001\nbatch_size = 32\nepoch = 50",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = Chatbot(size_layer, num_layers, embedded_size, vocabulary_size_from + 4, \n vocabulary_size_to + 4, learning_rate, batch_size)\nsess.run(tf.global_variables_initializer())",
"_____no_output_____"
],
[
"def str_idx(corpus, dic):\n X = []\n for i in corpus:\n ints = []\n for k in i.split():\n try:\n ints.append(dic[k])\n except Exception as e:\n print(e)\n ints.append(2)\n X.append(ints)\n return X",
"_____no_output_____"
],
[
"X = str_idx(text_from, dictionary_from)\nY = str_idx(text_to, dictionary_to)",
"'store'\n'gạch'\n"
],
[
"def pad_sentence_batch(sentence_batch, pad_int):\n padded_seqs = []\n seq_lens = []\n max_sentence_len = 120\n for sentence in sentence_batch:\n padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n seq_lens.append(120)\n return padded_seqs, seq_lens\n\ndef check_accuracy(logits, Y):\n acc = 0\n for i in range(logits.shape[0]):\n internal_acc = 0\n for k in range(len(Y[i])):\n if Y[i][k] == logits[i][k]:\n internal_acc += 1\n acc += (internal_acc / len(Y[i]))\n return acc / logits.shape[0]",
"_____no_output_____"
],
[
"for i in range(epoch):\n total_loss, total_accuracy = 0, 0\n for k in range(0, (len(text_from) // batch_size) * batch_size, batch_size):\n batch_x, seq_x = pad_sentence_batch(X[k: k+batch_size], PAD)\n batch_y, seq_y = pad_sentence_batch(Y[k: k+batch_size], PAD)\n predicted, loss, _ = sess.run([tf.argmax(model.logits,2), model.cost, model.optimizer], \n feed_dict={model.X:batch_x,\n model.Y:batch_y,\n model.X_seq_len:seq_x,\n model.Y_seq_len:seq_y})\n total_loss += loss\n total_accuracy += check_accuracy(predicted,batch_y)\n total_loss /= (len(text_from) // batch_size)\n total_accuracy /= (len(text_from) // batch_size)\n print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy))",
"epoch: 1, avg loss: 4.843591, avg accuracy: 0.697587\nepoch: 2, avg loss: 1.935228, avg accuracy: 0.805955\nepoch: 3, avg loss: 1.497099, avg accuracy: 0.807483\nepoch: 4, avg loss: 1.390903, avg accuracy: 0.807413\nepoch: 5, avg loss: 1.307696, avg accuracy: 0.806597\nepoch: 6, avg loss: 1.289980, avg accuracy: 0.806997\nepoch: 7, avg loss: 1.278247, avg accuracy: 0.808455\nepoch: 8, avg loss: 1.270470, avg accuracy: 0.809149\nepoch: 9, avg loss: 1.264819, avg accuracy: 0.809653\nepoch: 10, avg loss: 1.258962, avg accuracy: 0.810035\nepoch: 11, avg loss: 1.253545, avg accuracy: 0.810642\nepoch: 12, avg loss: 1.247422, avg accuracy: 0.811059\nepoch: 13, avg loss: 1.241787, avg accuracy: 0.811806\nepoch: 14, avg loss: 1.233718, avg accuracy: 0.812569\nepoch: 15, avg loss: 1.224231, avg accuracy: 0.812760\nepoch: 16, avg loss: 1.220082, avg accuracy: 0.812569\nepoch: 17, avg loss: 1.225716, avg accuracy: 0.812847\nepoch: 18, avg loss: 1.224967, avg accuracy: 0.812274\nepoch: 19, avg loss: 1.210359, avg accuracy: 0.812483\nepoch: 20, avg loss: 1.196828, avg accuracy: 0.813351\nepoch: 21, avg loss: 1.188632, avg accuracy: 0.813351\nepoch: 22, avg loss: 1.178611, avg accuracy: 0.813628\nepoch: 23, avg loss: 1.171774, avg accuracy: 0.813750\nepoch: 24, avg loss: 1.164856, avg accuracy: 0.813785\nepoch: 25, avg loss: 1.160983, avg accuracy: 0.814045\nepoch: 26, avg loss: 1.168028, avg accuracy: 0.814253\nepoch: 27, avg loss: 1.175067, avg accuracy: 0.813854\nepoch: 28, avg loss: 1.198314, avg accuracy: 0.811528\nepoch: 29, avg loss: 1.167468, avg accuracy: 0.813628\nepoch: 30, avg loss: 1.146915, avg accuracy: 0.814583\nepoch: 31, avg loss: 1.137056, avg accuracy: 0.815000\nepoch: 32, avg loss: 1.130226, avg accuracy: 0.815312\nepoch: 33, avg loss: 1.122811, avg accuracy: 0.815573\nepoch: 34, avg loss: 1.114798, avg accuracy: 0.815660\nepoch: 35, avg loss: 1.109321, avg accuracy: 0.816094\nepoch: 36, avg loss: 1.111026, avg accuracy: 0.816319\nepoch: 37, avg loss: 1.121527, avg accuracy: 0.816580\nepoch: 38, avg loss: 1.123400, avg accuracy: 0.815781\nepoch: 39, avg loss: 1.133825, avg accuracy: 0.816337\nepoch: 40, avg loss: 1.115678, avg accuracy: 0.815885\nepoch: 41, avg loss: 1.092272, avg accuracy: 0.817170\nepoch: 42, avg loss: 1.083012, avg accuracy: 0.818142\nepoch: 43, avg loss: 1.073952, avg accuracy: 0.818472\nepoch: 44, avg loss: 1.067003, avg accuracy: 0.819219\nepoch: 45, avg loss: 1.060707, avg accuracy: 0.819878\nepoch: 46, avg loss: 1.056264, avg accuracy: 0.820208\nepoch: 47, avg loss: 1.054770, avg accuracy: 0.820104\nepoch: 48, avg loss: 1.064729, avg accuracy: 0.819566\nepoch: 49, avg loss: 1.104123, avg accuracy: 0.816910\nepoch: 50, avg loss: 1.127176, avg accuracy: 0.812517\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba670a58c22e4420ca96734a1f24290fc31ccec
| 5,310 |
ipynb
|
Jupyter Notebook
|
word2vec.ipynb
|
luozhouyang/machine-learning-notes
|
332bea905398891fed4a98aa139eac02c88cb5ae
|
[
"Apache-2.0"
] | 73 |
2018-09-07T06:47:18.000Z
|
2022-01-25T06:14:41.000Z
|
word2vec.ipynb
|
luozhouyang/machine-learning-notes
|
332bea905398891fed4a98aa139eac02c88cb5ae
|
[
"Apache-2.0"
] | 2 |
2018-10-18T06:40:19.000Z
|
2019-11-16T01:48:39.000Z
|
word2vec.ipynb
|
luozhouyang/machine-learning-notes
|
332bea905398891fed4a98aa139eac02c88cb5ae
|
[
"Apache-2.0"
] | 47 |
2018-09-27T10:50:21.000Z
|
2022-01-25T06:20:23.000Z
| 30.872093 | 113 | 0.605838 |
[
[
[
"# Word2Vec笔记\n\n学习word2vec的skip-gram实现,除了skip-gram模型还有CBOW模型。\nSkip-gram模式是根据中间词,预测前后词,CBOW模型刚好相反,根据前后的词,预测中间词。\n\n那么什么是**中间词**呢?什么样的词才叫做**前后词**呢?\n\n首先,我们需要定义一个窗口大小,在窗口里面的词,我们才有中间词和前后词的定义。一般这个窗口大小在5-10之间。\n举个例子,我们设置窗口大小(window size)为2:\n```bash\n|The|quick|brown|fox|jump|\n```\n那么,`brown`就是我们的中间词,`The`、`quick`、`fox`、`jump`就是前后词。\n\n我们知道,word2vec实际上就是一个神经网络(后面会解释),那么这样的数据,我们是以什么样的格式用来训练的呢?\n看一张图,你就明白了:\n\n\n\n可以看到,我们总是以**中间词**放在第一个位置,然后跟着我们的前后相邻词。可以看到,每一对词都是一个输入和一个输出组成的数据对(X,Y)。其中,X是feature,Y是label。\n\n所以,我们训练模型之前,需要根据语料,整理出所有的像上面这样的输入数据用来训练。\n\n## word2vec是一个神经网络\n\nword2vec是一个简单的神经网络,有以下几个层组成:\n\n* 1个输入层\n* 1个隐藏层\n* 1个输出层\n\n输入层输入的就是上面我们说的数据对的数字表示,输出到隐藏层。\n隐藏层的神经网络单元的数量,其实就是我们所说的**embedding size**,只有为什么,我们后面简单计算一下就知道。需要注意的是,我们的隐藏层后面不需要使用激活函数。\n输出层,我们使用softmax操作,得到每一个预测结果的概率。\n\n这里有一张图,能够表示这个网络:\n\n\n### 输入层\n现在问题来了,刚刚我们说,输入层的输入是我们之前准备的数据对的数字表示,那么我们该如何用数字表示文本数据呢?\n\n好像随便一种方式都可以用来表示我们的文本啊。\n\n看上图,我们发现,它的输入使用的是**one-hot**编码。什么是ont-hot编码呢?如图所示,假设有n个词,则每一个词可以用一个n维的向量来表示,这个n维向量只有一个位置是1,其余位置都是0。\n\n那么为什么要用这样的编码来表示呢?答案后面揭晓。\n\n\n### 隐藏层\n隐藏层的神经单元数量,代表着每一个词用向量表示的维度大小。假设我们的**hidden_size**取300,也就是我们的隐藏层有300个神经元,那么对于每一个词,我们的向量表示就是一个$1*N$的向量。\n有多少个词,就有多少个这样的向量!\n\n所以对于**输入层**和**隐藏层**之间的权值矩阵$W$,它的形状应该是`[vocab_size, hidden_size]`的矩阵,\n\n### 输出层\n那么我们的输出层,应该是什么样子的呢?从上面的图上可以看出来,输出层是一个`[vocab_size]`大小的向量,每一个值代表着输出一个词的概率。\n\n为什么要这样输出?因为我们想要知道,对于一个输入词,它接下来的词最有可能的若干个词是哪些,换句话说,我们需要知道它接下来的词的概率分布。\n\n你可以再看一看上面那张网络结构图。\n\n你会看到一个很常见的函数**softmax**,为什么是softmax而不是其他函数呢?不妨先看一下softmax函数长啥样:\n\n$$ softmax(x) = \\frac{e^x}{\\sum_{i}^{N}e^{x_i}}$$\n\n很显然,它的取值范围在(0,1),并别所有的值和为1。这不就是天然的概率表示吗?\n\n当然,softmax还有一个性质,因为它函数指数操作,如果**损失函数使用对数函数**,那么可以抵消掉指数计算。\n\n关于更多的softmax,请看斯坦福[Softmax Regression](http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/)\n\n\n### 整个过程的数学表示\n至此,我们已经知道了整个神经网络的结构,那么我们应该怎么用数学表示出来呢?\n\n回顾一下我们的结构图,很显然,三个层之间会有两个权值矩阵$W$,同时,两个偏置项$b$。所以我们的整个网络的构建,可以用下面的伪代码:\n\n```python\nimport tensorflow as tf\n\n# 假设vocab_size = 1000\nVOCAB_SIZE = 1000\n# 假设embedding_size = 300\nEMBEDDINGS_SIZE = 300\n\n# 输入单词x是一个[1,vocab_size]大小的矩阵。当然实际上我们一般会用一批单词作为输入,那么就是[N, vocab_size]的矩阵了\nx = tf.placeholder(tf.float32, shape=(1,VOCAB_SIZE))\n# W1是一个[vocab_size, embedding_size]大小的矩阵\nW1 = tf.Variable(tf.random_normal([VOCAB_SIZE, EMBEDDING_SIZE]))\n# b1是一个[1,embedding_size]大小的矩阵\nb1 = tf.Variable(tf.random_normal([EMBEDDING_SIZE]))\n# 简单的矩阵乘法和加法\nhidden = tf.add(tf.mutmul(x,W1),b1)\n\nW2 = tf.Variable(tf.random_normal([EMBEDDING_SIZE,VOCAB_SIZE]))\nb2 = tf.Variable(tf.random_normal([VOCAB_SIZE]))\n# 输出是一个vocab_size大小的矩阵,每个值都是一个词的概率值\nprediction = tf.nn.softmax(tf.add(tf.mutmul(hidden,w2),b2))\n```\n\n### 损失函数\n网络定义好了,我们需要选一个损失函数来使用梯度下降算法优化模型。\n\n我们的输出层,实际上就是一个softmax分类器。所以按照常规套路,损失函数就选择**交叉熵损失函数**。\n\n哈哈,还记得交叉熵是啥吗?\n\n$$ H(p,q)=-\\sum_{x}p(x)logq(x)$$\np,q是真是概率分布和估计概率分布。\n\n```python\n# 损失函数 \ncross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y_label * tf.log(prediction), reduction_indices=[1]))\n# 训练操作\ntrain_op = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy_loss)\n```\n接下来,就可以准备号数据,开始训练啦!\n\n\n### 为啥输入使用one-hot编码?\n\n我们知道word2vec训练后会得到一个权值矩阵W1(暂时忽略b1),这个矩阵就是我们的所有词的向量表示啦!这个矩阵的每一行,就是一个词的矢量表示。如果两个矩阵相乘...\n\n\n看到了吗?ont-hot编码的特点,**在矩阵相乘的时候,就是选取出矩阵中的某一行,而这一行就是我们输入这个词语的word2vec表示!**。\n\n怎么样?是不是很妙?\n\n由此,我们可以看出来,所谓的word2vec,实际上就是一个**查找表**,是一个**二维**的浮点数矩阵!\n\n以上是word2vec的skip-gram模型的完整分析,怎么样,是不是弄清楚了word2vec的原理和细节?\n\n完整代码请查看[word2vec](https://github.com/luozhouyang/machine-learning-notes/blob/master/word2vec/word2vec.py)",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
cba6761a20dc2c41b9b5e853203c2387d84a3679
| 175,505 |
ipynb
|
Jupyter Notebook
|
tools/revenues/.ipynb_checkpoints/Preparing Data 2013-14-checkpoint.ipynb
|
MyanmarEITI/meiti-data
|
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
|
[
"CC-BY-3.0"
] | null | null | null |
tools/revenues/.ipynb_checkpoints/Preparing Data 2013-14-checkpoint.ipynb
|
MyanmarEITI/meiti-data
|
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
|
[
"CC-BY-3.0"
] | null | null | null |
tools/revenues/.ipynb_checkpoints/Preparing Data 2013-14-checkpoint.ipynb
|
MyanmarEITI/meiti-data
|
d1b6c3932fd037f730f5f7e490eb0e7b3ac0c311
|
[
"CC-BY-3.0"
] | null | null | null | 45.538402 | 22,004 | 0.428694 |
[
[
[
"import pandas as pd\nimport json\nimport numpy as np",
"_____no_output_____"
],
[
"df = pd.read_csv('data/eiti-summary-company-payments.csv')",
"_____no_output_____"
],
[
"df = df[df['country'] == \"Myanmar\"]",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"## Clean data",
"_____no_output_____"
]
],
[
[
"df[\"company_name\"].unique()",
"_____no_output_____"
],
[
"companies_info_df = pd.read_csv('data/eiti_summary_companies_cleaned.csv')",
"_____no_output_____"
],
[
"companies_info_df.head()",
"_____no_output_____"
],
[
"df = pd.merge(df, companies_info_df, left_on='company_name', right_on='Legal name')",
"_____no_output_____"
],
[
"df[df['Commodities'] == 'Gems & Jade']['name_of_revenue_stream'].unique()",
"_____no_output_____"
],
[
"df[df['Commodities'] == 'Gems & Jade']['gfs_description'].unique()",
"_____no_output_____"
],
[
"df['revenue_stream_short'] = df['name_of_revenue_stream'].str.split(' - ').str[1]\n",
"_____no_output_____"
],
[
"df_gemsjade = df[df['Commodities'] == 'Gems & Jade']\ndf_gemsjade['type'] = 'entity'\ndf_gemsjade['target_type'] = ''",
"/Library/Python/2.7/site-packages/ipykernel/__main__.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n from ipykernel import kernelapp as app\n/Library/Python/2.7/site-packages/ipykernel/__main__.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n app.launch_new_instance()\n"
],
[
"df_gemsjade.head()",
"_____no_output_____"
],
[
"company_totals = df_gemsjade.pivot_table(index=['Company_name_cl'], aggfunc='sum')['value_reported']\ncompany_totals = company_totals.to_frame()\ncompany_totals.rename(columns={'value_reported': 'total_payments'}, inplace=True)\ncompany_totals.reset_index(level=0, inplace=True)\ncompany_totals",
"_____no_output_____"
],
[
"df_gemsjade = pd.merge(df_gemsjade, company_totals, on='Company_name_cl')\ndf_gemsjade = df_gemsjade.sort_values(by=['total_payments'], ascending=False)",
"_____no_output_____"
],
[
"append_dict_others = [{'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'revenue_stream_short': 'Royalties', 'value_reported': 111092756522 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'revenue_stream_short': 'Sale Split', 'value_reported': 51742994736 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'revenue_stream_short': 'Emporium Fees / Sale Fees', 'value_reported': 11401644588 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'revenue_stream_short': 'Supervision Fees', 'value_reported': 1246890624 },\n \n {'Company_name_cl': 'Companies not in EITI Reconciliation', 'type': 'entity', \n 'revenue_stream_short': 'Other significant payments', 'value_reported': 2186525820 }]\n\nothers_df = pd.DataFrame(append_dict_others)\nothers_df['total_payments'] = others_df['value_reported']\ndf_gemsjade = pd.concat([df_gemsjade, others_df])\ndf_gemsjade.tail(10)",
"_____no_output_____"
],
[
"df_gemsjade['revenue_stream_short'] = df_gemsjade['revenue_stream_short'].replace({'Other significant payments (> 50,000 USD)': 'Other significant payments'})",
"_____no_output_____"
]
],
[
[
"## Remove negative payments for Sankey",
"_____no_output_____"
]
],
[
[
"df_gemsjade = df_gemsjade[df_gemsjade[\"value_reported\"] >= 0]",
"_____no_output_____"
]
],
[
[
"## Prepare Source-Target-Value dataframe",
"_____no_output_____"
]
],
[
[
"links = pd.DataFrame(columns=['source','target','value','type'])\n",
"_____no_output_____"
],
[
"to_append = df_gemsjade.groupby(['revenue_stream_short'],as_index=False)['type','value_reported','value_reported_as_USD','total_payments'].sum()\nto_append[\"target\"] = \"Myanmar Gems Enterprise\"\nto_append.rename(columns = {'revenue_stream_short':'source', 'value_reported' : 'value'}, inplace = True)\nto_append = to_append.sort_values(by=['value'], ascending = False)\nlinks = pd.concat([links,to_append])\n\nprint(to_append['value'].sum())\nlinks",
"380196722113.0\n"
],
[
"append_dict_transfers = [{'source': 'Myanmar Gems Enterprise', 'type': 'entity',\n 'target': 'State Contribution', 'value': 48367022000 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'Transfers to Other Accounts', 'value': 195516457782 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'Commercial Tax', 'value': 21499000 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'Corporate Income Tax', 'value': 60458777000 },\n \n {'source': 'Myanmar Gems Enterprise', 'type': 'entity', \n 'target': 'Other material transfers', 'value': 119588538585 },\n \n {'source': 'State Contribution', 'target_type': 'entity',\n 'target': 'Ministry of Finance', 'value': 48367022000 },\n \n {'source': 'Corporate Income Tax', \n 'target': 'Internal Revenue Department', 'value': 60458777000 },\n \n {'source': 'Commercial Tax', \n 'target': 'Internal Revenue Department', 'value': 21499000 },\n \n {'source': 'Internal Revenue Department', 'type': 'entity','target_type': 'entity',\n 'target': 'Ministry of Finance', 'value': 60480276000 }]\n\nappend_dict_transfers_df = pd.DataFrame(append_dict_transfers)\nlinks = pd.concat([links, append_dict_transfers_df])\nlinks",
"_____no_output_____"
],
[
"to_append = df_gemsjade.groupby(['revenue_stream_short','Company_name_cl','type'],as_index=False)['value_reported','value_reported_as_USD','total_payments'].sum()\nto_append.rename(columns = {'Company_name_cl':'source','revenue_stream_short':'target', 'value_reported' : 'value'}, inplace = True)\nto_append = to_append.sort_values(by=['type','total_payments','value'], ascending = False)\nlinks = pd.concat([links,to_append])\n\nprint(to_append['value'].sum())\nlinks",
"380196722113.0\n"
],
[
"#to_append = df.groupby(['Payment Type','Reporting Company'],as_index=False)['Value (USD)'].sum()\n#to_append.rename(columns = {'Payment Type':'source','Reporting Company':'target', 'Value (USD)' : 'value'}, inplace = True)\n#to_append = to_append.sort_values(by=['value'], ascending = False)\n#links = pd.concat([links,to_append])\n\n#print(to_append['value'].sum())\n#links",
"_____no_output_____"
],
[
"unique_source = links['source'].unique()\nunique_targets = links['target'].unique()\n\nunique_source = pd.merge(pd.DataFrame(unique_source), links, left_on=0, right_on='source', how='left')\nunique_source = unique_source.filter([0,'type'])\nunique_targets = pd.merge(pd.DataFrame(unique_targets), links, left_on=0, right_on='target', how='left')\nunique_targets = unique_targets.filter([0,'target_type'])\nunique_targets.rename(columns = {'target_type':'type'}, inplace = True)\n\nunique_list = pd.concat([unique_source[0], unique_targets[0]]).unique()\n\nunique_list = pd.merge(pd.DataFrame(unique_list), \\\n pd.concat([unique_source, unique_targets]), left_on=0, right_on=0, how='left')\n\nunique_list.drop_duplicates(subset=0, keep='first', inplace=True)\n\nreplace_dict = {k: v for v, k in enumerate(unique_list[0])}\nunique_list\n#replace_dict",
"_____no_output_____"
],
[
"links_replaced = links.replace({\"source\": replace_dict,\"target\": replace_dict})",
"_____no_output_____"
],
[
"links_replaced",
"_____no_output_____"
],
[
"nodes = pd.DataFrame(unique_list)\nnodes.rename(columns = {0:'name'}, inplace = True)",
"_____no_output_____"
],
[
"nodes_json= pd.DataFrame(nodes).to_json(orient='records')\nnodes_json ",
"_____no_output_____"
],
[
"links_json= pd.DataFrame(links_replaced).to_json(orient='records')\nlinks_json ",
"_____no_output_____"
],
[
"data = { 'links' : json.loads(links_json), 'nodes' : json.loads(nodes_json) }\ndata_json = json.dumps(data)\ndata_json = data_json.replace(\"\\\\\",\"\")\n#print(data_json)\n#with open('sankey_data.json', 'w') as outfile:\n# json.dump(data_json, outfile)\n\ntext_file = open(\"sankey_data_2013-14.json\", \"w\")\ntext_file.write(data_json)\ntext_file.close()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba693b68ea2afea06871438cbdaef922e426b34
| 8,746 |
ipynb
|
Jupyter Notebook
|
opencv_with_python/bacterial_count.ipynb
|
Aliktk/Python_Chilla
|
bfc0bd0ae9ad4b3f4a4cbccf59874a93343d6913
|
[
"Apache-2.0"
] | 8 |
2022-02-16T19:17:15.000Z
|
2022-03-02T07:08:32.000Z
|
opencv_with_python/bacterial_count.ipynb
|
MansoorJan/Python_Chilla
|
63d6c86b6856ab858e2c6b9616941dfebeef45e1
|
[
"Apache-2.0"
] | null | null | null |
opencv_with_python/bacterial_count.ipynb
|
MansoorJan/Python_Chilla
|
63d6c86b6856ab858e2c6b9616941dfebeef45e1
|
[
"Apache-2.0"
] | 2 |
2022-02-26T15:27:07.000Z
|
2022-02-28T17:59:39.000Z
| 43.29703 | 131 | 0.546193 |
[
[
[
"import sys\nimport cv2 as cv\nimport os\nimport numpy as np\nfrom PyQt5.QtWidgets import QApplication, QDialog, QFileDialog\nfrom ui import *\n\n\nclass MainWindow(QDialog, Ui_Form):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n # Variables for initialization statistics\n self.path_list = []\n self.path_list_i = 0\n self.count = 0\n self.bias_sum = 0\n # Define control parameters\n self.CENTER_X = 900\n self.CENTER_Y = 900\n self.RADIUS = 680\n # Define image parameters\n self.THRESH = 170\n self.MAXVAL = 255\n # Initializing auxiliary lines\n self.left_line = 600\n self.right_line = 1200\n self.up_line = 600\n self.down_line = 1200\n # Initialization signal and slot connection\n ##Initialization open file operation button\n self.open_folder_button.clicked.connect(self.get_file_path)\n self.next_button.clicked.connect(self.press_next)\n self.pre_button.clicked.connect(self.press_pre)\n ## Initialize gray value adjustment connection\n self.min_spin.valueChanged.connect(self.change_min_grayscale_spin)\n self.max_spin.valueChanged.connect(self.change_max_grayscale_spin)\n self.min_slider.valueChanged.connect(self.change_min_grayscale_slider)\n self.max_slider.valueChanged.connect(self.change_max_grayscale_slider)\n ## Initialization guide line, mask connection\n self.left_spin.valueChanged.connect(self.change_left)\n self.right_spin.valueChanged.connect(self.change_right)\n self.up_spin.valueChanged.connect(self.change_up)\n self.down_spin.valueChanged.connect(self.change_down)\n self.center_x_spin.valueChanged.connect(self.change_center_x)\n self.center_y_spin.valueChanged.connect(self.change_center_y)\n self.r_spin.valueChanged.connect(self.change_r)\n ##Initialize nine offset connections\n self.bias_1.valueChanged.connect(self.bias_change)\n self.bias_2.valueChanged.connect(self.bias_change)\n self.bias_3.valueChanged.connect(self.bias_change)\n self.bias_4.valueChanged.connect(self.bias_change)\n self.bias_5.valueChanged.connect(self.bias_change)\n self.bias_6.valueChanged.connect(self.bias_change)\n self.bias_7.valueChanged.connect(self.bias_change)\n self.bias_8.valueChanged.connect(self.bias_change)\n self.bias_9.valueChanged.connect(self.bias_change)\n\n def get_file_path(self):\n dir_choose = QFileDialog.getExistingDirectory(self, \"Select Folder\", os.getcwd())\n temp_list = os.listdir(dir_choose)\n for i in temp_list:\n self.path_list.append(dir_choose + \"/\" + i)\n self.path_list_i = 0\n self.shulaibao()\n\n def press_next(self):\n if self.path_list_i == len(self.path_list) - 1:\n pass\n else:\n self.path_list_i += 1\n self.shulaibao()\n\n def press_pre(self):\n if self.path_list_i == 0:\n pass\n else:\n self.path_list_i -= 1\n self.shulaibao()\n\n def change_min_grayscale_slider(self):\n self.THRESH = self.min_slider.value()\n self.min_spin.setValue(self.THRESH)\n self.shulaibao()\n\n def change_min_grayscale_spin(self):\n self.THRESH = self.min_spin.value()\n self.min_slider.setValue(self.THRESH)\n self.shulaibao()\n\n def change_max_grayscale_slider(self):\n self.MAXVAL = self.max_slider.value()\n self.max_spin.setValue(self.MAXVAL)\n self.shulaibao()\n\n def change_max_grayscale_spin(self):\n self.MAXVAL = self.max_spin.value()\n self.max_slider.setValue(self.MAXVAL)\n self.shulaibao()\n\n def change_center_x(self):\n self.CENTER_X = self.center_x_spin.value()\n\n self.shulaibao()\n\n def change_center_y(self):\n self.CENTER_Y = self.center_y_spin.value()\n self.shulaibao()\n\n def change_r(self):\n self.RADIUS = self.r_spin.value()\n self.shulaibao()\n\n def change_left(self):\n self.left_line = self.left_spin.value()\n self.shulaibao()\n\n def change_right(self):\n self.right_line = self.right_spin.value()\n self.shulaibao()\n\n def change_down(self):\n self.right_line = self.right_spin.value()\n self.shulaibao()\n\n def change_up(self):\n self.right_line = self.right_spin.value()\n self.shulaibao()\n\n def bias_change(self):\n self.bias_sum = self.bias_1.value() + self.bias_2.value() + self.bias_3.value() + self.bias_4.value() + \\\n self.bias_5.value() + self.bias_6.value() + self.bias_7.value() + self.bias_8.value() + \\\n self.bias_9.value()\n self.count_label.setText(f\"The total is:{self.count + self.bias_sum}\")\n\n def shulaibao(self):\n cv.destroyAllWindows()\n img = cv.imread(self.path_list[self.path_list_i])\n img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n img_gray = cv.blur(img_gray, (3, 3))\n # The circular mask is drawn and the target image is synthesized with gray image\n mask = np.zeros_like(img_gray)\n mask = cv.circle(mask, (self.CENTER_X, self.CENTER_Y), self.RADIUS, (255, 255, 255), -1)\n mask = mask // 255\n img_with_mask = mask * img_gray\n # Binarization\n _, img_threshold = cv.threshold(img_with_mask, self.THRESH, self.MAXVAL, cv.THRESH_BINARY)\n # Connect the region to get the border\n contours, _ = cv.findContours(img_threshold, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\n img_1 = cv.drawContours(img, contours, -1, (0, 0, 255))\n img_1 = cv.circle(img_1, (self.CENTER_X, self.CENTER_Y), self.RADIUS, (0, 255, 0), 5)\n img_1 = cv.putText(img_1, \"{}\".format(len(contours)), (100, 100), cv.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),5)\n # Draw guides\n cv.line(img_1, (self.left_line, 0), (self.left_line, 1800), (0, 255, 0), 3, 8)\n cv.line(img_1, (self.right_line, 0), (self.right_line, 1800), (0, 255, 0), 3, 8)\n cv.line(img_1, (0, self.up_line), (1800, self.up_line), (0, 255, 0), 3, 8)\n cv.line(img_1, (0, self.down_line), (1800, self.down_line), (0, 255, 0), 3, 8)\n # Display picture, record number\n img_1 = cv.resize(img_1, (0, 0), fx=0.5, fy=0.5)\n self.count = len(contours)\n self.bias_change()\n cv.imshow(\"COUNT\", img_1)\n cv.waitKey(0)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n w = MainWindow()\n w.show()\n app.exec_()\n cv.destroyAllWindows()\n sys.exit()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cba6971ec3967fd4d735eb6dc8d64c80cb084e67
| 22,311 |
ipynb
|
Jupyter Notebook
|
Machine Learning & Data Science Masterclass - JP/08-Linear-Regression-Models/03-Regularization-Ridge-Lasso-ElasticNet.ipynb
|
ptyadana/probability-and-statistics-for-business-and-data-science
|
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
|
[
"MIT"
] | 10 |
2021-01-14T15:14:03.000Z
|
2022-02-19T14:06:25.000Z
|
Machine Learning & Data Science Masterclass - JP/08-Linear-Regression-Models/03-Regularization-Ridge-Lasso-ElasticNet.ipynb
|
ptyadana/probability-and-statistics-for-business-and-data-science
|
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
|
[
"MIT"
] | null | null | null |
Machine Learning & Data Science Masterclass - JP/08-Linear-Regression-Models/03-Regularization-Ridge-Lasso-ElasticNet.ipynb
|
ptyadana/probability-and-statistics-for-business-and-data-science
|
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
|
[
"MIT"
] | 8 |
2021-03-24T13:00:02.000Z
|
2022-03-27T16:32:20.000Z
| 21.788086 | 947 | 0.494509 |
[
[
[
"# Regularization with SciKit-Learn",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"df = pd.read_csv('Data/Advertising.csv')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"X = df.drop('sales', axis=1)\ny = df['sales']",
"_____no_output_____"
]
],
[
[
"### Polynomial Conversion",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import PolynomialFeatures",
"_____no_output_____"
],
[
"poly_converter = PolynomialFeatures(degree=3, include_bias=False)",
"_____no_output_____"
],
[
"poly_features = poly_converter.fit_transform(X)",
"_____no_output_____"
],
[
"poly_features.shape",
"_____no_output_____"
]
],
[
[
"### Train | Test Split",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(poly_features, y, test_size=0.3, random_state=101)",
"_____no_output_____"
]
],
[
[
"-----",
"_____no_output_____"
],
[
"# Scaling the Data",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler",
"_____no_output_____"
],
[
"scaler = StandardScaler()",
"_____no_output_____"
],
[
"# to avoid data leakage : meaning model got an idea of test data\n# only fit to train data set\nscaler.fit(X_train)",
"_____no_output_____"
],
[
"# overwrite scaled data\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)",
"_____no_output_____"
]
],
[
[
"We can see that after scaling, values has scaled down.",
"_____no_output_____"
]
],
[
[
"X_train[0]",
"_____no_output_____"
],
[
"poly_features[0]",
"_____no_output_____"
]
],
[
[
"--------\n\n-------",
"_____no_output_____"
],
[
"# Ridge Regression",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import Ridge",
"_____no_output_____"
],
[
"ridge_model = Ridge(alpha=10)",
"_____no_output_____"
],
[
"ridge_model.fit(X_train, y_train)",
"_____no_output_____"
],
[
"test_predictions = ridge_model.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_absolute_error, mean_squared_error",
"_____no_output_____"
],
[
"MAE = mean_absolute_error(y_test, test_predictions)",
"_____no_output_____"
],
[
"MAE",
"_____no_output_____"
],
[
"RMSE = np.sqrt(mean_squared_error(y_test, test_predictions))",
"_____no_output_____"
],
[
"RMSE",
"_____no_output_____"
],
[
"# Training Set Performance\ntrain_predictions = ridge_model.predict(X_train)\nMAE = mean_absolute_error(y_train, train_predictions)\nRMSE = np.sqrt(mean_squared_error(y_train, train_predictions))\n\nMAE, RMSE",
"_____no_output_____"
]
],
[
[
"---------",
"_____no_output_____"
],
[
"## Choosing an alpha value with Cross-Validation",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import RidgeCV",
"_____no_output_____"
],
[
"ridge_cv_model = RidgeCV(alphas=(0.1, 1.0, 10.0), scoring='neg_mean_absolute_error')",
"_____no_output_____"
],
[
"ridge_cv_model.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# get the best alpha value\nridge_cv_model.alpha_",
"_____no_output_____"
],
[
"ridge_cv_model.coef_",
"_____no_output_____"
]
],
[
[
"As we can see from the coefficient, ridge regression is considering every features.",
"_____no_output_____"
],
[
"------\n",
"_____no_output_____"
],
[
"If you don't remember which key to use for `scoring metrics`, we can search like that.",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import SCORERS",
"_____no_output_____"
],
[
"SCORERS.keys()\n# these are the scoring parameters that we can use. but depends on the model, use the appropriate key\n# for neg_mean_squared_error, etc the HIGHER the value is, the BETTER (because it is the negative value/opposite of mean squared error (the lower the bettter))",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
]
],
[
[
"# check performance\ntest_predictions = ridge_cv_model.predict(X_test)",
"_____no_output_____"
],
[
"MAE = mean_absolute_error(y_test, test_predictions)\nRMSE = np.sqrt(mean_squared_error(y_test, test_predictions))\n\nMAE, RMSE",
"_____no_output_____"
]
],
[
[
"Comparing the MAE and RMSE with alpha value of 10 result (0.5774404204714166, 0.8946386461319675), the results are much better now.",
"_____no_output_____"
],
[
"--------\n\n--------",
"_____no_output_____"
],
[
"# Lasso Regression\n- LASSO (Least Absolute Shinkage and Selection Operator)\n- **the smaller `eps` value is, the wider range we are checking**",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LassoCV",
"_____no_output_____"
],
[
"# lasso_cv_model = LassoCV(eps=0.001,n_alphas=100,cv=5, max_iter=1000000) #wider range because eps value is smaller\n\nlasso_cv_model = LassoCV(eps=0.1,n_alphas=100,cv=5) #narrower range",
"_____no_output_____"
],
[
"lasso_cv_model.fit(X_train,y_train)",
"_____no_output_____"
],
[
"# best alpha value\nlasso_cv_model.alpha_",
"_____no_output_____"
],
[
"test_predictions = lasso_cv_model.predict(X_test)",
"_____no_output_____"
],
[
"MAE = mean_absolute_error(y_test, test_predictions)\nRMSE = np.sqrt(mean_squared_error(y_test, test_predictions))",
"_____no_output_____"
],
[
"MAE, RMSE",
"_____no_output_____"
]
],
[
[
"By comparing the previous results of Ridge Regression, this model seems like not performing well.",
"_____no_output_____"
]
],
[
[
"lasso_cv_model.coef_",
"_____no_output_____"
]
],
[
[
"We can check the coefficient of lasso regression model. As we can see from the above, there are only 2 features that model is considering. Other features are 0 and not considered by model.\n\nBut based on the context and if we want to consider only two features, Lasso may be a better choice. However we need to take note that MAE, RMSE is not performing as well as Ridge. \n\nBut alphas value can be higher (expand the wider range of search) and make a more complext model.",
"_____no_output_____"
],
[
"--------\n-------",
"_____no_output_____"
],
[
"# Elastic Net (L1 + L2)",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import ElasticNetCV",
"_____no_output_____"
],
[
"elastic_cv_model = ElasticNetCV(l1_ratio=[.1, .5, .7,.9, .95, .99, 1], eps=0.001, n_alphas=100, max_iter=1000000)",
"_____no_output_____"
],
[
"elastic_cv_model.fit(X_train, y_train)",
"_____no_output_____"
],
[
"#best l1 ratio\nelastic_cv_model.l1_ratio_",
"_____no_output_____"
],
[
"elastic_cv_model.alpha_",
"_____no_output_____"
],
[
"test_predictions = elastic_cv_model.predict(X_test)",
"_____no_output_____"
],
[
"MAE = mean_absolute_error(y_test, test_predictions)\nRMSE = np.sqrt(mean_squared_error(y_test, test_predictions))",
"_____no_output_____"
],
[
"MAE, RMSE",
"_____no_output_____"
],
[
"elastic_cv_model.coef_",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cba69b47419734720f3c7098a795d9f6a5592557
| 246,774 |
ipynb
|
Jupyter Notebook
|
notebooks/figura0.ipynb
|
nahuelalmeira/chess
|
4bde6490483cfa04dfbdc43d5df3075c59c3e568
|
[
"MIT"
] | null | null | null |
notebooks/figura0.ipynb
|
nahuelalmeira/chess
|
4bde6490483cfa04dfbdc43d5df3075c59c3e568
|
[
"MIT"
] | null | null | null |
notebooks/figura0.ipynb
|
nahuelalmeira/chess
|
4bde6490483cfa04dfbdc43d5df3075c59c3e568
|
[
"MIT"
] | null | null | null | 656.31383 | 83,774 | 0.941947 |
[
[
[
"from chessnet.notebook_config import *",
"_____no_output_____"
],
[
"dfs = {\n \"OTB\": pd.read_csv(ARTIFACTS_DIR / f\"{Database.OTB}.csv\"),\n \"Portal\": pd.read_csv(ARTIFACTS_DIR / f\"{Database.Portal}.csv\"),\n}",
"_____no_output_____"
],
[
"games_per_player_dict = {}\nfor i, (name, df) in enumerate(dfs.items()):\n players = pd.concat([\n df[[\"White\"]].dropna().rename(columns={\"White\": \"Player\"}),\n df[[\"Black\"]].dropna().rename(columns={\"Black\": \"Player\"}),\n ])\n counts = players.value_counts()\n games_per_player = counts.values\n games_per_player_dict[name] = games_per_player",
"_____no_output_____"
],
[
"def plot_game_distribution(data, ax=None, **kwargs):\n if ax is None:\n _, ax = plt.subplots()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n ax.set_xlabel(\"Cantidad de partidas\")\n ax.set_ylabel(\"Frecuencia\")\n # Log scale\n bins = np.logspace(np.log10(min(data)), np.log10(max(data)+1), 20)\n freq, _ = np.histogram(data, bins=bins, density=True)\n X_log, Y_log = bins[:-1], freq\n\n Y_pred, slope, y_err = linear_regression(X_log[:-3], Y_log[:-3])\n c = Y_log[5] / X_log[5]**slope\n #label = r'$\\gamma = {{{:.2f}}}({{{:.0f}}})$'.format(slope, 100*y_err)\n label = r'${{{:.2f}}}({{{:.0f}}})$'.format(slope, 100*y_err)\n #ax.text(0.45, 0.73, label, fontsize=26, transform=ax.transAxes)\n ax.text(0.28, 0.5, r\"$\\gamma = -1.5$\", fontsize=26, transform=ax.transAxes)\n #ax.plot(\n # X_log, powerlaw(X_log, slope, c), \"--\", color=\"k\", zorder=10, #label=label,\n #)\n\n #X_powerlaw = X_log\n X_powerlaw = np.array([1, 10000])\n ax.plot(\n X_powerlaw, powerlaw(X_powerlaw, -1.5, c), \"--\", color=\"k\", zorder=10, #label=label,\n )\n\n # Lin scale\n bins = range(1, max(data)+1)\n freq, _ = np.histogram(data, bins=bins, density=True)\n X_lin, Y_lin = bins[:-1], freq\n\n ax.plot(\n X_lin,\n Y_lin,\n \".\",\n color=\"gray\",\n alpha=0.5,\n fillstyle=\"none\",\n label=\"Bineado lineal\"\n )\n color = kwargs.get(\"color\")\n ax.plot(\n X_log,\n Y_log,\n \"o\",\n markersize=10,\n color=color,\n label=\"Bineado logarítmico\"\n )\n return ax",
"_____no_output_____"
],
[
"ncols = 2\nnrows = 1\nfig, axes = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows)\nfor ax in axes.flatten():\n ax.set_xlim(0.5, 30000)\naxes[0].set_title(database_latex[\"OTB\"], fontsize=30)\naxes[1].set_title(database_latex[\"Portal\"], fontsize=30)\naxes[0].plot([0.3, 0.45], [0.6, 0.6], \"-\", color=\"k\", transform=axes[0].transAxes)\naxes[0].plot([0.3, 0.3], [0.6, 0.7], \"-\", color=\"k\", transform=axes[0].transAxes)\naxes[1].plot([0.3, 0.45], [0.6, 0.6], \"-\", color=\"k\", transform=axes[1].transAxes)\naxes[1].plot([0.3, 0.3], [0.6, 0.7], \"-\", color=\"k\", transform=axes[1].transAxes)\nfor i, (name, df) in enumerate(dfs.items()):\n ax = axes[0]\n ax.text(0.9, 0.9, panels[i], fontsize=30, transform=ax.transAxes)\n games_per_player = games_per_player_dict[name]\n plot_game_distribution(games_per_player, ax=ax, color=f\"C{i}\")\n ax.set_xticks([1, 10, 100, 1000, 10000])\n ax.set_ylim(5e-10, 1)\n\naxes[0].legend(frameon=False)\naxes[1].legend(frameon=False)\n\nsns.despine()\nplt.tight_layout()\nplt.savefig(FIGS_DIR / \"game_distribution.pdf\")\nplt.show()",
"No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.\n"
],
[
"def plot_game_distribution(data, ax=None, **kwargs):\n if ax is None:\n _, ax = plt.subplots()\n ax.set_xscale(\"log\")\n ax.set_yscale(\"log\")\n ax.set_xlabel(\"Cantidad de partidas\")\n ax.set_ylabel(\"Frecuencia\")\n # Log scale\n bins = np.logspace(np.log10(min(data)), np.log10(max(data)+1), 35)\n freq, _ = np.histogram(data, bins=bins, density=True)\n X_log, Y_log = bins[:-1], freq\n mask = ~np.isnan(Y_log)\n mask = Y_log>1e-10\n X_log, Y_log = X_log[mask], Y_log[mask]\n ax.plot(\n X_log,\n Y_log,\n markersize=8,\n color=kwargs.get(\"color\"),\n label=kwargs.get(\"label\"),\n marker=kwargs.get(\"marker\"),\n fillstyle=\"none\",\n )\n return ax",
"_____no_output_____"
],
[
"ncols = 1\nnrows = 1\nfig, ax = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows)\nax.set_xlim(0.5, 200000)\nax.text(0.9, 0.9, panels[0], fontsize=30, transform=ax.transAxes)\nax.plot([0.3, 0.42], [0.6, 0.6], \"-\", color=\"k\", transform=ax.transAxes)\nax.plot([0.3, 0.3], [0.6, 0.7], \"-\", color=\"k\", transform=ax.transAxes)\nfor i, (name, df) in enumerate(dfs.items()):\n games_per_player = games_per_player_dict[name]\n marker = \"o\" if name == \"OTB\" else \"s\"\n plot_game_distribution(games_per_player, ax=ax, color=f\"C{i}\", label=name, marker=marker)\n\nX_powerlaw = np.array([1, 50000])\nax.plot(\n X_powerlaw, powerlaw(X_powerlaw, -1.5, 0.15), \"--\", color=\"k\", zorder=10\n)\n#ax.text(0.28, 0.5, r\"$\\gamma = -1.5$\", fontsize=26, transform=ax.transAxes)\nax.text(0.3, 0.5, r\"$-1.5$\", fontsize=26, transform=ax.transAxes)\nax.set_xticks([1, 10, 100, 1000, 10000, 100000])\nax.set_ylim(1e-11, 2)\nax.set_yticks([1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10])\n\n\n\nax.legend(frameon=False, loc=\"lower left\")\nsns.despine()\nplt.tight_layout()\n#plt.savefig(FIGS_DIR / \"game_distribution.pdf\")\nplt.show()",
"_____no_output_____"
],
[
"ncols = 1\nnrows = 1\nfig, ax = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows)\nax.set_ylabel(\"Cantidad de partidas\")\nax.set_xlabel(\"Índice del jugador\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nfor i, (name, df) in enumerate(dfs.items()):\n games_per_player = games_per_player_dict[name]\n Y = games_per_player\n X = np.arange(1, len(Y)+1)\n ax.plot(X, Y, label=name)\nax.set_xlim(0.5, 1e6)\nax.set_xticks([1, 10, 100, 1000, 10000, 100000, 1e6])\nax.set_yticks([1, 10, 100, 1000, 10000, 100000])\nax.legend(frameon=False)\nsns.despine()\nplt.show()",
"_____no_output_____"
],
[
"ncols = 2\nnrows = 1\nfig, axes = plt.subplots(figsize=(8*ncols, 6*nrows), ncols=ncols, nrows=nrows)\nax = axes[0]\nax.set_xlim(0.5, 200000)\nax.text(0.9, 0.9, panels[0], fontsize=30, transform=ax.transAxes)\nax.plot([0.3, 0.42], [0.6, 0.6], \"-\", color=\"k\", transform=ax.transAxes)\nax.plot([0.3, 0.3], [0.6, 0.7], \"-\", color=\"k\", transform=ax.transAxes)\nfor i, (name, df) in enumerate(dfs.items()):\n games_per_player = games_per_player_dict[name]\n marker = \"o\" if name == \"OTB\" else \"s\"\n plot_game_distribution(games_per_player, ax=ax, color=f\"C{i}\", label=name, marker=marker)\n\nX_powerlaw = np.array([1, 50000])\nax.plot(\n X_powerlaw, powerlaw(X_powerlaw, -1.5, 0.15), \"--\", color=\"k\", zorder=10\n)\n#ax.text(0.28, 0.5, r\"$\\gamma = -1.5$\", fontsize=26, transform=ax.transAxes)\nax.text(0.3, 0.5, r\"$-1.5$\", fontsize=26, transform=ax.transAxes)\nax.set_xticks([1, 10, 100, 1000, 10000, 100000])\nax.set_ylim(1e-11, 2)\nax.set_yticks([1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10])\nax.legend(frameon=False, loc=\"lower left\")\n\n\nax = axes[1]\nax.text(0.9, 0.9, panels[1], fontsize=30, transform=ax.transAxes)\nax.set_ylabel(\"Cantidad de partidas\")\nax.set_xlabel(\"Índice del jugador\")\nax.set_xscale(\"log\")\nax.set_yscale(\"log\")\nfor i, (name, df) in enumerate(dfs.items()):\n games_per_player = games_per_player_dict[name]\n Y = games_per_player\n X = np.arange(1, len(Y)+1)\n ax.plot(X, Y, label=name)\nax.set_xlim(0.5, 1e6)\nax.set_xticks([1, 10, 100, 1000, 10000, 100000, 1e6])\nax.set_yticks([1, 10, 100, 1000, 10000, 100000])\nax.legend(frameon=False, loc=\"lower left\")\n\nsns.despine()\nplt.tight_layout()\nplt.savefig(FIGS_DIR / \"game_distribution.pdf\")\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.