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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb46b0fe642a68762cad05756f64d209a891adae | 329,538 | ipynb | Jupyter Notebook | notebooks/experimental/clip retrain objectnet.ipynb | Manny810/seesaw | 83ef0435cdc7187f677430373437a8f294dfe092 | [
"MIT"
] | 4 | 2022-02-08T19:07:32.000Z | 2022-02-12T22:30:09.000Z | notebooks/experimental/clip retrain objectnet.ipynb | orm011/vsl | 8281a249ce41f8049f01e59e552e7dd756a2ddeb | [
"MIT"
] | 2 | 2022-01-26T23:52:16.000Z | 2022-01-27T19:17:55.000Z | notebooks/experimental/clip retrain objectnet.ipynb | orm011/vsl | 8281a249ce41f8049f01e59e552e7dd756a2ddeb | [
"MIT"
] | null | null | null | 85.284161 | 1,972 | 0.481574 | [
[
[
"%load_ext autoreload",
"_____no_output_____"
],
[
"%autoreload 2",
"_____no_output_____"
],
[
"import importlib",
"_____no_output_____"
],
[
"import vsms\nimport torch\nimport torch.nn as nn",
"_____no_output_____"
],
[
"import clip",
"_____no_output_____"
],
[
"from vsms import *",
"_____no_output_____"
],
[
"from vsms import BoxFeedbackQuery",
"_____no_output_____"
],
[
"class StringEncoder(object):\n def __init__(self):\n variant =\"ViT-B/32\"\n device='cpu'\n jit = False\n self.device = device\n model, preproc = clip.load(variant, device=device, jit=jit)\n self.model = model\n self.preproc = preproc\n self.celoss = nn.CrossEntropyLoss(reduction='none')\n \n def encode_string(self, string):\n model = self.model.eval()\n with torch.no_grad():\n ttext = clip.tokenize([string])\n text_features = model.encode_text(ttext.to(self.device))\n text_features = text_features / text_features.norm(dim=-1, keepdim=True)\n return text_features.detach().cpu().numpy()\n\ndef get_text_features(self, actual_strings, target_string): \n s2id = {}\n sids = []\n s2id[target_string] = 0\n for s in actual_strings:\n if s not in s2id:\n s2id[s] = len(s2id)\n\n sids.append(s2id[s])\n\n strings = [target_string] + actual_strings\n ustrings = list(s2id)\n stringids = torch.tensor([s2id[s] for s in actual_strings], dtype=torch.long).to(self.device)\n tstrings = clip.tokenize(ustrings)\n text_features = self.model.encode_text(tstrings.to(self.device))\n text_features = text_features / text_features.norm(dim=-1, keepdim=True)\n return text_features, stringids, ustrings\n \ndef forward(self, imagevecs, actual_strings, target_string):\n ## uniquify strings \n text_features, stringids, ustrings = get_text_features(self, actual_strings, target_string)\n\n image_features = torch.from_numpy(imagevecs).type(text_features.dtype)\n image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n image_features = image_features.to(self.device)\n scores = image_features @ text_features.t()\n \n assert scores.shape[0] == stringids.shape[0]\n return scores, stringids.to(self.device), ustrings\n\ndef forward2(self, imagevecs, actual_strings, target_string):\n text_features, stringids, ustrings = get_text_features(self, actual_strings, target_string)\n actual_vecs = text_features[stringids]\n sought_vec = text_features[0].reshape(1,-1)\n \n image_features = torch.from_numpy(imagevecs).type(text_features.dtype)\n image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n image_features = image_features.to(self.device)\n\n search_score = image_features @ sought_vec.reshape(-1)\n confounder_score = (image_features * actual_vecs).sum(dim=1)\n return search_score, confounder_score\n \nimport torch.optim\n",
"_____no_output_____"
],
[
"import torch.nn.functional as F",
"_____no_output_____"
],
[
"nn.HingeEmbeddingLoss()",
"_____no_output_____"
],
[
"import ray\nray.init('auto')\nxclip = ModelService(ray.get_actor('clip'))",
"2021-06-28 20:33:25,629\tINFO worker.py:640 -- Connecting to existing Ray cluster at address: 192.168.1.18:6379\n"
],
[
"from vsms import *\nbenchparams = dict(\n objectnet=dict(loader=objectnet_cropped, idxs=np.load('./data/object_random_idx.npy')[:10000])\n)\n\ndef load_ds(evs, dsnames):\n for k,v in tqdm(benchparams.items(), total=len(benchparams)):\n if k in dsnames:\n def closure():\n ev0 = v['loader'](xclip)\n idxs = v['idxs']\n idxs = np.sort(idxs) if idxs is not None else None\n ev = extract_subset(ev0, idxsample=idxs)\n evs[k] = ev\n closure()",
"_____no_output_____"
],
[
"evs = {}\nload_ds(evs, 'objectnet')",
"_____no_output_____"
],
[
"ev = evs['objectnet']",
"_____no_output_____"
],
[
"vecs = ev.embedded_dataset\nhdb = AugmentedDB(raw_dataset=ev.image_dataset, embedding=ev.embedding,\n embedded_dataset=vecs, vector_meta=ev.fine_grained_meta)",
"_____no_output_____"
],
[
"def show_scores(se, vecs, actual_strings, target_string):\n with torch.no_grad():\n se.model.eval()\n scs,stids,rawstrs = forward(se, vecs, actual_strings, target_string=target_string)\n scdf = pd.DataFrame({st:col for st,col in zip(rawstrs,scs.cpu().numpy().transpose())})\n display(scdf.style.highlight_max(axis=1))\n\ndef get_feedback(idxbatch):\n strids = np.where(ev.query_ground_truth.iloc[idxbatch])[1]\n strs = ev.query_ground_truth.columns[strids]\n strs = [search_terms['objectnet'][fbstr] for fbstr in strs.values]\n return strs",
"_____no_output_____"
],
[
"curr_firsts = pd.read_parquet('./data/cats_objectnet_ordered.parquet')",
"_____no_output_____"
],
[
"class Updater(object):\n def __init__(self, se, lr, rounds=1, losstype='hinge'):\n self.se = se\n self.losstype=losstype\n self.opt = torch.optim.AdamW([{'params': se.model.ln_final.parameters()},\n {'params':se.model.text_projection},\n# {'params':se.model.transformer.parameters(), 'lr':lr*.01}\n ], lr=lr, weight_decay=0.)\n# self.opt = torch.optim.Adam@([{'params': se.model.parameters()}], lr=lr)\n self.rounds = rounds\n \n def update(self, imagevecs, actual_strings, target_string):\n se = self.se\n se.model.train()\n losstype = self.losstype\n opt = self.opt\n margin = .3\n\n def opt_closure():\n opt.zero_grad() \n if losstype=='ce':\n scores, stringids, rawstrs = forward(se, imagevecs, actual_strings, target_string)\n # breakpoint()\n iidx = torch.arange(scores.shape[0]).long()\n actuals = scores[iidx, stringids]\n midx = scores.argmax(dim=1)\n maxes = scores[iidx, midx] \n elif losstype=='hinge':\n #a,b = forward2(se, imagevecs, actual_strings, target_string)\n scores, stringids, rawstrs = forward(se, imagevecs, actual_strings, target_string)\n # breakpoint()\n iidx = torch.arange(scores.shape[0]).long()\n maxidx = scores.argmax(dim=1)\n \n actual_score = scores[iidx, stringids].reshape(-1,1)\n #max_score = scores[iidx, maxidx]\n \n \n #target_score = scores[:,0]\n losses1 = F.relu(- (actual_score - scores - margin))\n #losses2 = F.relu(- (actual_score - target_score - margin))\n #losses = torch.cat([losses1, losses2])\n losses = losses1\n else:\n assert False\n loss = losses.mean()\n #print(loss.detach().cpu())\n loss.backward()\n\n for _ in range(self.rounds):\n opt.step(opt_closure)\n\n\n\ndef closure(search_query, max_n, firsts, show_display=False, batch_size=10):\n sq = search_terms['objectnet'][search_query]\n se = StringEncoder()\n up = Updater(se, lr=.0001, rounds=1)\n bs = batch_size\n bfq = BoxFeedbackQuery(hdb, batch_size=bs, auto_fill_df=None)\n tvecs = []\n dbidxs = []\n accstrs = []\n gts = []\n while True:\n tvec = se.encode_string(sq)\n tvecs.append(tvec)\n idxbatch, _ = bfq.query_stateful(mode='dot', vector=tvec, batch_size=bs)\n dbidxs.append(idxbatch)\n gtvals = ev.query_ground_truth[search_query][idxbatch].values\n gts.append(gtvals)\n if show_display:\n display(hdb.raw.show_images(idxbatch))\n display(gtvals)\n #vecs = ev.embedded_dataset[idxbatch]\n actual_strings = get_feedback(idxbatch)\n accstrs.extend(actual_strings)\n\n if show_display:\n display(actual_strings)\n if gtvals.sum() > 0 or len(accstrs) > max_n:\n break\n\n # vcs = ev.embedded_dataset[idxbatch]\n # astrs = actual_strings \n vcs = ev.embedded_dataset[np.concatenate(dbidxs)]\n astrs = accstrs\n\n if show_display:\n show_scores(se, vcs, astrs, target_string=sq)\n \n up.update(vcs, actual_strings=astrs, target_string=sq)\n\n if show_display:\n show_scores(se, vcs, astrs, target_string=sq)\n\n\n frsts = np.where(np.concatenate(gts).reshape(-1))[0]\n if frsts.shape[0] == 0:\n firsts[search_query] = np.inf\n else:\n firsts[search_query] = frsts[0] + 1",
"_____no_output_____"
],
[
"cf = curr_firsts[curr_firsts.nfirst_x > batch_size]",
"_____no_output_____"
],
[
"x.category",
"_____no_output_____"
],
[
"firsts = {}\nbatch_size = 10\nfor x in tqdm(curr_firsts.itertuples()):\n closure(x.category, max_n=30, firsts=firsts, show_display=True, batch_size=batch_size)\n print(firsts[x.category], x.nfirst_x)\n if x.nfirst_x <= batch_size:\n break",
"_____no_output_____"
],
[
"firsts = {}\nbatch_size = 10\nfor x in tqdm(curr_firsts.itertuples()):\n closure(x.category, max_n=3*x.nfirst_x, firsts=firsts, show_display=True, batch_size=batch_size)\n print(firsts[x.category], x.nfirst_x)\n if x.nfirst_x <= batch_size:\n break",
"_____no_output_____"
],
[
"rdf = pd.concat([pd.Series(firsts).rename('feedback'), cf[['category', 'nfirst_x']].set_index('category')['nfirst_x'].rename('no_feedback')], axis=1)",
"_____no_output_____"
],
[
"((rdf.feedback < rdf.no_feedback).mean(), \n(rdf.feedback == rdf.no_feedback).mean(), \n (rdf.feedback > rdf.no_feedback).mean())",
"_____no_output_____"
],
[
"rdf",
"_____no_output_____"
],
[
"rdf.to_parquet('./data/objectnet_nfirst_verbal.parquet')",
"_____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"
]
] |
cb46c23360fceb99a19b15eeef7b57b7c98401a9 | 12,272 | ipynb | Jupyter Notebook | Examples of Tables.ipynb | tommydkinnovation/numpy-random | 9e1a17b4f9c9b2135cc635cc2d24bf5294103bd3 | [
"MIT"
] | null | null | null | Examples of Tables.ipynb | tommydkinnovation/numpy-random | 9e1a17b4f9c9b2135cc635cc2d24bf5294103bd3 | [
"MIT"
] | null | null | null | Examples of Tables.ipynb | tommydkinnovation/numpy-random | 9e1a17b4f9c9b2135cc635cc2d24bf5294103bd3 | [
"MIT"
] | null | null | null | 35.571014 | 176 | 0.551744 | [
[
[
"<a name=\"top\"></a>\n# Examples of Tables",
"_____no_output_____"
],
[
"## Table of Content\n\n1. [Tabel 1 - No Alignment](#table1) <br>\n2. [Tabel 2 - Center Alignment](#table2) <br>\n3. [Tabel 3 - Left Alignment](#table3) <br>\n4. [Tabel 4 - Right Alignment](#table4) <br>\n5. [Table 5 - HTML](#table5) <br>\n 5a. [Html Table](#table5)<br>\n 5b. [Adding borders](#table5b) <br>\n 5c. [Align Text](#table5c) <br>\n 5d. [Adding colour](#table5d) <br>",
"_____no_output_____"
],
[
"<a id='table1'></a>\n### Tabel 1 - No Alignment\n\n|Sections |No of Functions |Brief Descriptions |\n|-|-|-|\nRandom Sample Data | 10 functions |Random data computations on specified arrays\nPermutations | 2 functions | Alters the sequence of generated outputs within arrays\nDistributions |35 functions |Determines the occurance of variables accross defined parameters within arrays\nRandom Generator | 4 functions | Determining the probability of occurance within arrays",
"_____no_output_____"
],
[
"<a id='table2'></a>\n### Tabel 2 - Center Alignment\n\n|Sections |No of Functions |Brief Descriptions |\n|:-:|:-:|:-:|\n|Random Sample Data | 10 functions |Random data computations on specified arrays\n|Permutations | 2 functions | Alters the sequence of generated outputs within arrays\n|Distributions |35 functions |Determines the occurance of variables accross defined parameters within arrays\n|Random Generator | 4 functions | Determining the probability of occurance within arrays",
"_____no_output_____"
],
[
"<a id='table3'></a>\n### Tabel 3 - Left Alignment\n\n|Sections |No of Functions |Brief Descriptions |\n|:-|:-|:-\n|Random Sample Data | 10 functions |Random data computations on specified arrays\n|Permutations | 2 functions | Alters the sequence of generated outputs within arrays\n|Distributions |35 functions |Determines the occurance of variables accross defined parameters within arrays\n|Random Generator | 4 functions | Determining the probability of occurance within arrays",
"_____no_output_____"
],
[
"<a id='table4'></a>\n### Tabel 4 - Right Alignment\n\n|Sections |No of Functions |Brief Descriptions |\n|-:|-:|-:\n|Random Sample Data | 10 functions |Random data computations on specified arrays\n|Permutations | 2 functions | Alters the sequence of generated outputs within arrays\n|Distributions |35 functions |Determines the occurance of variables accross defined parameters within arrays\n|Random Generator | 4 functions | Determining the probability of occurance within arrays",
"_____no_output_____"
],
[
"<a id='table5'></a>\n### Table 5 - HTML\n#### HTML Table",
"_____no_output_____"
]
],
[
[
"%%html\n\n<table>\n <tr>\n <th>Sections </th>\n <th>No of Functions </th>\n <th>Brief Descriptions </th>\n </tr>\n <tr>\n <td >Random Sample Data </td>\n <td>10 functions</td>\n <td>Random data computations on specified arrays</td>\n </tr>\n <tr>\n <td>Permutations</td>\n <td>2 functions</td>\n <td>Alters the sequence of generated outputs within arrays</td>\n </tr>\n <tr>\n <td>Distributions</td>\n <td>35 functions</td>\n <td>Determines the occurance of variables accross defined parameters within arrays</td>\n </tr>\n <tr>\n <td>Random Generator</td>\n <td>4 functions </td>\n <td>Determining the probability of occurance within arrays</td>\n </tr>\n</table>",
"_____no_output_____"
]
],
[
[
"<a id='table5b'></a>\n#### Adding borders",
"_____no_output_____"
]
],
[
[
"%%html\n<table>\n <tr>\n <th style=\"border:1px solid; text-align:center\">Sections </th>\n <th style=\"border:1px solid; text-align:center\">No of Functions </th>\n <th style=\"border:1px solid ; text-align:center\">Brief Descriptions </th>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Random Sample Data </td>\n <td style=\"border:1px solid; text-align:center\">10 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Random data computations on specified arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Permutations</td>\n <td style=\"border:1px solid; text-align:center\">2 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Alters the sequence of generated outputs within arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Distributions</td>\n <td style=\"border:1px solid; text-align:center\">35 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Determines the occurance of variables accross defined parameters within arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Random Generator</td>\n <td style=\"border:1px solid; text-align:center\">4 functions </td>\n <td style=\"border:1px solid; text-align:center\">Determining the probability of occurance within arrays</td>\n </tr>\n</table>",
"_____no_output_____"
]
],
[
[
"<a id='table5c'></a>\n#### Align Text - Center\n\n<table>\n <tr>\n <th style=\"border:1px solid; text-align:center\">Sections </th>\n <th style=\"border:1px solid; text-align:center\">No of Functions </th>\n <th style=\"border:1px solid ; text-align:center\">Brief Descriptions </th>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Random Sample Data </td>\n <td style=\"border:1px solid; text-align:center\">10 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Random data computations on specified arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Permutations</td>\n <td style=\"border:1px solid; text-align:center\">2 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Alters the sequence of generated outputs within arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Distributions</td>\n <td style=\"border:1px solid; text-align:center\">35 functions</td>\n <td style=\"border:1px solid ; text-align:center\">Determines the occurance of variables accross defined parameters within arrays</td>\n </tr>\n <tr>\n <td style=\"border:1px solid; text-align:center\">Random Generator</td>\n <td style=\"border:1px solid; text-align:center\">4 functions </td>\n <td style=\"border:1px solid; text-align:center\">Determining the probability of occurance within arrays</td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"<a id='table5d'></a>\n#### Adding colour",
"_____no_output_____"
],
[
"<a href=\"#top\"><img style=\"float: right; width:50px;height:50px;\" src=\"https://cdn.pixabay.com/photo/2016/09/05/10/50/app-1646212_1280.png\" alt=\"Back To Top\"></a>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cb46c29c00f4ac922cec523c5a6af0441d79114d | 5,042 | ipynb | Jupyter Notebook | RootFinding.ipynb | Farr-PHY-604/RootFinding.jl | 29e76be4756a7e3e861953138b56f1268fab40c3 | [
"MIT"
] | null | null | null | RootFinding.ipynb | Farr-PHY-604/RootFinding.jl | 29e76be4756a7e3e861953138b56f1268fab40c3 | [
"MIT"
] | null | null | null | RootFinding.ipynb | Farr-PHY-604/RootFinding.jl | 29e76be4756a7e3e861953138b56f1268fab40c3 | [
"MIT"
] | null | null | null | 19.318008 | 71 | 0.3929 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb46c3242df509c85aaa49987ec5d7576c27f27b | 347,145 | ipynb | Jupyter Notebook | PIAIC Assignments/Deep Learning Assignments Set/Car Price Prediction assignment (1).ipynb | fazeel15/PIAIC125459_PIAIC_Assignments | 91aa64a055c24d7056c98614bba228251b41d378 | [
"MIT"
] | null | null | null | PIAIC Assignments/Deep Learning Assignments Set/Car Price Prediction assignment (1).ipynb | fazeel15/PIAIC125459_PIAIC_Assignments | 91aa64a055c24d7056c98614bba228251b41d378 | [
"MIT"
] | null | null | null | PIAIC Assignments/Deep Learning Assignments Set/Car Price Prediction assignment (1).ipynb | fazeel15/PIAIC125459_PIAIC_Assignments | 91aa64a055c24d7056c98614bba228251b41d378 | [
"MIT"
] | null | null | null | 45.707044 | 17,680 | 0.508243 | [
[
[
"# Car Price Prediction::",
"_____no_output_____"
],
[
"Download dataset from this link:\n\nhttps://www.kaggle.com/hellbuoy/car-price-prediction",
"_____no_output_____"
],
[
"# Problem Statement::",
"_____no_output_____"
]
],
[
[
"# mount google drive in to your Colab enviornment\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"
],
[
"cd /content/drive/MyDrive/AI_assignment/\n",
"/content/drive/MyDrive/AI_assignment\n"
]
],
[
[
"A Chinese automobile company Geely Auto aspires to enter the US market by setting up their manufacturing unit there and producing cars locally to give competition to their US and European counterparts.\n\nThey have contracted an automobile consulting company to understand the factors on which the pricing of cars depends. Specifically, they want to understand the factors affecting the pricing of cars in the American market, since those may be very different from the Chinese market. The company wants to know:\n\nWhich variables are significant in predicting the price of a car\nHow well those variables describe the price of a car\nBased on various market surveys, the consulting firm has gathered a large data set of different types of cars across the America market.\n\n# task::\nWe are required to model the price of cars with the available independent variables. It will be used by the management to understand how exactly the prices vary with the independent variables. They can accordingly manipulate the design of the cars, the business strategy etc. to meet certain price levels. Further, the model will be a good way for management to understand the pricing dynamics of a new market.",
"_____no_output_____"
],
[
"# WORKFLOW ::",
"_____no_output_____"
],
[
"1.Load Data\n\n2.Check Missing Values ( If Exist ; Fill each record with mean of its feature )\n\n3.Split into 50% Training(Samples,Labels) , 30% Test(Samples,Labels) and 20% Validation Data(Samples,Labels).\n\n4.Model : input Layer (No. of features ), 3 hidden layers including 10,8,6 unit & Output Layer with activation function relu/tanh (check by experiment).\n\n5.Compilation Step (Note : Its a Regression problem , select loss , metrics according to it)\n6.Train the Model with Epochs (100) and validate it\n\n7.If the model gets overfit tune your model by changing the units , No. of layers , activation function , epochs , add dropout layer or add Regularizer according to the need .\n\n8.Evaluation Step\n\n9.Prediction",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\ncar_data = pd.read_csv('/content/drive/MyDrive/AI_assignment/CarPrice_Assignment.csv')",
"_____no_output_____"
],
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"car_data.head()",
"_____no_output_____"
],
[
"car_data['CarName'].unique()",
"_____no_output_____"
],
[
"#check if there are empty cells, if there are then row and column indexes will be returned where values are empty or missing\nnp.where(car_data.applymap(lambda x: x ==''))",
"_____no_output_____"
],
[
"car_data.isnull().any()",
"_____no_output_____"
],
[
"# correct the name error in audi 100 ls\ncar_data.iloc[3,2] = 'audi 100ls'",
"_____no_output_____"
],
[
"car_data.dtypes",
"_____no_output_____"
],
[
"car_data.drop(columns=['car_ID'], inplace = True)",
"_____no_output_____"
],
[
"# get columns so that we can use the column names for onehot encoding of catagorical featrues in next cell\ncar_data.columns",
"_____no_output_____"
],
[
"# onehot encode all catagorical columns\nfinal_car = pd.get_dummies(car_data, columns=['CarName','symboling','fueltype',\t'aspiration',\t'doornumber',\t'carbody',\t'drivewheel',\t'enginelocation',\t'enginetype',\t'cylindernumber',\t'fuelsystem'], drop_first = True)\n",
"_____no_output_____"
],
[
"final_car.head()",
"_____no_output_____"
],
[
"#check statistical data to see abnormal values and outliers\nfinal_car.describe()",
"_____no_output_____"
],
[
"#initialize a seed value so that each time we can get the same random number sequence, it will help us as a team\n# working on a common project to work on the same random data. Each new seed will generate a particular sequnce\n#of random number. You can choose any seed value here of your choice\n# 0.72 means we have taken 72% values for training set as we will make 72/4 = 18 rows of k fold validation data, where\n# value of k will be 4 when we compile and fit our model for validation\nnp.random.seed(11111)\nmsk = np.random.rand(len(final_car)) < 0.72\ntrain_total = final_car[msk]\ntest_total = final_car[~msk]\n",
"_____no_output_____"
],
[
"#check the length of our test and train datasets\nprint(len(train_total))\nprint(len(test_total))\n",
"141\n64\n"
],
[
"train_total.head(10)",
"_____no_output_____"
],
[
"# check statistical overview if there are some outliers and abnormal values\ntrain_total.describe()",
"_____no_output_____"
],
[
"print(train_total.dtypes)",
"wheelbase float64\ncarlength float64\ncarwidth float64\ncarheight float64\ncurbweight int64\n ... \nfuelsystem_idi uint8\nfuelsystem_mfi uint8\nfuelsystem_mpfi uint8\nfuelsystem_spdi uint8\nfuelsystem_spfi uint8\nLength: 193, dtype: object\n"
],
[
"# get our price labels and store in another dataframe\ntrain_label = train_total.loc[:,'price']\ntest_label = test_total.loc[:,'price']",
"_____no_output_____"
],
[
"train_label",
"_____no_output_____"
],
[
"# drop price from oroginal training and test dataset , as price is not needed there\ntest_data= test_total.drop(columns = ['price'])\ntrain_data= train_total.drop(columns = ['price'])",
"_____no_output_____"
],
[
"train_data.shape",
"_____no_output_____"
],
[
"train_data",
"_____no_output_____"
],
[
"#get indices of the columns so that we can know how many columns we have to normalize, as catagorical columns which we\n# have added with onehot encoding, do not need to be normalized.. normalizing will be done in next cell\n{train_data.columns.get_loc(c): c for idx, c in enumerate(train_data.columns)}",
"_____no_output_____"
],
[
"## we normalize data because data has big vlaues in decimal and it will worsen performance of our model, may overfit \n## or we may face hardware resource high usage\n# we will apply the formula normalized_train_data = (train_data - mean)/ stadrad_deviation\n## firt take mean of training, then subtract mean from each value of the array slice train_data.iloc[:,0:13]\nmean = train_data.iloc[:,0:13].mean(axis=0) # taking the mean of \ntrain_data.iloc[:,0:13] -= mean\nstd = train_data.iloc[:,0:13].std(axis=0)\ntrain_data.iloc[:,0:13] /= std\ntest_data.iloc[:,0:13] -= mean\ntest_data.iloc[:,0:13] /= std\n\n",
"_____no_output_____"
],
[
"mean",
"_____no_output_____"
],
[
"std",
"_____no_output_____"
],
[
"mean_label = train_label.mean()\ntrain_label -= mean_label\nstd_label = train_label.std()\ntrain_label /= std_label\ntest_label -= mean_label\ntest_label /= std_label\n",
"_____no_output_____"
],
[
"mean_label",
"_____no_output_____"
],
[
"std_label",
"_____no_output_____"
],
[
"print(mean_label)",
"13379.132390070921\n"
],
[
"test_label",
"_____no_output_____"
],
[
"train_data.shape",
"_____no_output_____"
],
[
"#store in numpy array",
"_____no_output_____"
],
[
"test = np.array(test_data.iloc[:]).astype('float32')",
"_____no_output_____"
],
[
"train = np.array(train_data.iloc[:]).astype('float32')",
"_____no_output_____"
],
[
"test_l= np.array(test_label.astype('float32'))",
"_____no_output_____"
],
[
"train_l= np.array(train_label.astype('float32'))",
"_____no_output_____"
],
[
"train.shape[1]\n",
"_____no_output_____"
],
[
"(141,192)[1]",
"_____no_output_____"
],
[
"train.dtype",
"_____no_output_____"
]
],
[
[
"\n# Models section\n```\n#WE will configure different models here according to relu, tanh , regularization, dropout etc..\n```\n\n",
"_____no_output_____"
]
],
[
[
"# we are passing activation function as a parameter here so that we can call this function with tanh or relu while\n# fitting and training the model\nfrom keras import models\nfrom keras import layers\ndef build_model(act):\n model = models.Sequential()\n model.add(layers.Dense(128, activation= act,input_shape=(train.shape[1],)))\n model.add(layers.Dense(64, activation= act))\n model.add(layers.Dense(32, activation= act))\n model.add(layers.Dense(1))\n model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])\n return model",
"_____no_output_____"
],
[
"build_model('relu').summary()",
"Model: \"sequential_48\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_192 (Dense) (None, 128) 24704 \n_________________________________________________________________\ndense_193 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndense_194 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_195 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 35,073\nTrainable params: 35,073\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"build_model('tanh').summary()",
"Model: \"sequential_49\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_196 (Dense) (None, 128) 24704 \n_________________________________________________________________\ndense_197 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndense_198 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_199 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 35,073\nTrainable params: 35,073\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Regularized model\nfrom keras import regularizers\ndef build_model_regular(act):\n model = models.Sequential()\n model.add(layers.Dense(10, activation= act,kernel_regularizer= regularizers.l1_l2(l1=0.001, l2=0.001),input_shape=(train.shape[1],)))\n model.add(layers.Dense(8, activation= act,kernel_regularizer= regularizers.l1_l2(l1=0.001, l2=0.001)))\n model.add(layers.Dense(6, activation= act,kernel_regularizer= regularizers.l1_l2(l1=0.001, l2=0.001)))\n model.add(layers.Dense(1))\n model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])\n return model",
"_____no_output_____"
],
[
"build_model_regular('tanh').summary()",
"Model: \"sequential_50\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_200 (Dense) (None, 10) 1930 \n_________________________________________________________________\ndense_201 (Dense) (None, 8) 88 \n_________________________________________________________________\ndense_202 (Dense) (None, 6) 54 \n_________________________________________________________________\ndense_203 (Dense) (None, 1) 7 \n=================================================================\nTotal params: 2,079\nTrainable params: 2,079\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# dropout model\nfrom keras import regularizers\ndef build_model_drop(act):\n model = models.Sequential()\n model.add(layers.Dense(10, activation= act,input_shape=(train.shape[1],)))\n model.add(layers.Dropout(0.2))\n model.add(layers.Dense(8, activation= act))\n model.add(layers.Dropout(0.2))\n model.add(layers.Dense(6, activation= act))\n model.add(layers.Dropout(0.2))\n model.add(layers.Dense(1))\n model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])\n return model",
"_____no_output_____"
],
[
"build_model_drop('relu').summary()",
"Model: \"sequential_51\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_204 (Dense) (None, 10) 1930 \n_________________________________________________________________\ndropout_36 (Dropout) (None, 10) 0 \n_________________________________________________________________\ndense_205 (Dense) (None, 8) 88 \n_________________________________________________________________\ndropout_37 (Dropout) (None, 8) 0 \n_________________________________________________________________\ndense_206 (Dense) (None, 6) 54 \n_________________________________________________________________\ndropout_38 (Dropout) (None, 6) 0 \n_________________________________________________________________\ndense_207 (Dense) (None, 1) 7 \n=================================================================\nTotal params: 2,079\nTrainable params: 2,079\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"# K Fold validation section\n## here we will use len(train)//k to make 141//4 = 36 rows for validation in each validation test and collect the validation scores for relu , tanh , regularization , and dropout",
"_____no_output_____"
]
],
[
[
"#k fold validation with relu\n# 141/4\nimport numpy as np\nk = 4\nnum_val_samples = len(train) // k\nnum_epochs = 100\nall_scores_relu = []\nfor i in range(k):\n print('processing fold #', i)\n val_data = train[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_l[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate([train[:i * num_val_samples],train[(i + 1) * num_val_samples:]], axis=0)\n # print(partial_train_data)\n partial_train_targets = np.concatenate([train_l[:i * num_val_samples],train_l[(i + 1) * num_val_samples:]],axis=0)\n model = build_model('relu')\n model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=1, verbose=0)\n val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)\n all_scores_relu.append(val_mae)\n",
"processing fold # 0\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b6a51830> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 1\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6ad8c9e60> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 2\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b5c0d7a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 3\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6bc68b950> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"# 141/4\n#k fold validation with tanh\nimport numpy as np\nk = 4\nnum_val_samples = len(train) // k\nnum_epochs = 100\nall_scores_tanh = []\nfor i in range(k):\n print('processing fold #', i)\n val_data = train[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_l[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate([train[:i * num_val_samples],train[(i + 1) * num_val_samples:]], axis=0)\n # print(partial_train_data)\n partial_train_targets = np.concatenate([train_l[:i * num_val_samples],train_l[(i + 1) * num_val_samples:]],axis=0)\n model = build_model('tanh')\n model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=1, verbose=0)\n val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)\n all_scores_tanh.append(val_mae)",
"processing fold # 0\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6ad967200> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 1\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6ad95e290> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 2\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b0da15f0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 3\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b5e677a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"#k-fold validtion with regularization\nimport numpy as np\nk = 4\nnum_val_samples = len(train) // k\nnum_epochs = 100\nall_scores_regular = []\nfor i in range(k):\n print('processing fold #', i)\n val_data = train[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_l[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate([train[:i * num_val_samples],train[(i + 1) * num_val_samples:]], axis=0)\n # print(partial_train_data)\n partial_train_targets = np.concatenate([train_l[:i * num_val_samples],train_l[(i + 1) * num_val_samples:]],axis=0)\n model = build_model_regular('relu')\n model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=1, verbose=0)\n val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)\n all_scores_regular.append(val_mae)",
"processing fold # 0\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6bceec9e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 1\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b9ed39e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 2\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b9ed3e60> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nprocessing fold # 3\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b694a170> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"#k-fold validtion with dropout\nimport numpy as np\nk = 4\nnum_val_samples = len(train) // k\nnum_epochs = 100\nall_scores_drop = []\nfor i in range(k):\n print('processing fold #', i)\n val_data = train[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_l[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate([train[:i * num_val_samples],train[(i + 1) * num_val_samples:]], axis=0)\n # print(partial_train_data)\n partial_train_targets = np.concatenate([train_l[:i * num_val_samples],train_l[(i + 1) * num_val_samples:]],axis=0)\n model = build_model_drop('relu')\n model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=1, verbose=1)\n val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=1)\n all_scores_drop.append(val_mae)",
"processing fold # 0\nEpoch 1/100\n106/106 [==============================] - 1s 947us/step - loss: 0.7836 - mae: 0.6582\nEpoch 2/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6849 - mae: 0.5250\nEpoch 3/100\n106/106 [==============================] - 0s 921us/step - loss: 0.6058 - mae: 0.5574\nEpoch 4/100\n106/106 [==============================] - 0s 982us/step - loss: 0.5037 - mae: 0.4585\nEpoch 5/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4986 - mae: 0.4664\nEpoch 6/100\n106/106 [==============================] - 0s 949us/step - loss: 0.5802 - mae: 0.4604\nEpoch 7/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6526 - mae: 0.4818\nEpoch 8/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6838 - mae: 0.5564\nEpoch 9/100\n106/106 [==============================] - 0s 943us/step - loss: 0.5513 - mae: 0.4783\nEpoch 10/100\n106/106 [==============================] - 0s 980us/step - loss: 0.4993 - mae: 0.4620\nEpoch 11/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6288 - mae: 0.4943\nEpoch 12/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5745 - mae: 0.4684\nEpoch 13/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6083 - mae: 0.5045\nEpoch 14/100\n106/106 [==============================] - 0s 932us/step - loss: 0.5550 - mae: 0.4650\nEpoch 15/100\n106/106 [==============================] - 0s 952us/step - loss: 0.4322 - mae: 0.4399\nEpoch 16/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6446 - mae: 0.4739\nEpoch 17/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5703 - mae: 0.4729\nEpoch 18/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6759 - mae: 0.5032\nEpoch 19/100\n106/106 [==============================] - 0s 986us/step - loss: 0.7300 - mae: 0.5691\nEpoch 20/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8043 - mae: 0.5372\nEpoch 21/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7026 - mae: 0.4759\nEpoch 22/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8208 - mae: 0.5759\nEpoch 23/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4222 - mae: 0.3816\nEpoch 24/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.1579 - mae: 0.6315\nEpoch 25/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4417 - mae: 0.4089\nEpoch 26/100\n106/106 [==============================] - 0s 978us/step - loss: 0.4890 - mae: 0.4332\nEpoch 27/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7226 - mae: 0.5326\nEpoch 28/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6143 - mae: 0.4987\nEpoch 29/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4138 - mae: 0.4102\nEpoch 30/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4967 - mae: 0.4612\nEpoch 31/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7271 - mae: 0.5731\nEpoch 32/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6570 - mae: 0.5116\nEpoch 33/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4299 - mae: 0.4191\nEpoch 34/100\n106/106 [==============================] - 0s 954us/step - loss: 0.2726 - mae: 0.3146\nEpoch 35/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4069 - mae: 0.4186\nEpoch 36/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4201 - mae: 0.4341\nEpoch 37/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6433 - mae: 0.5459\nEpoch 38/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7927 - mae: 0.5560\nEpoch 39/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3818 - mae: 0.4084\nEpoch 40/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3813 - mae: 0.4453\nEpoch 41/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7214 - mae: 0.5017\nEpoch 42/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5816 - mae: 0.4539\nEpoch 43/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4720 - mae: 0.4660\nEpoch 44/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8166 - mae: 0.5538\nEpoch 45/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5622 - mae: 0.4971\nEpoch 46/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5483 - mae: 0.4592\nEpoch 47/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4533 - mae: 0.4296\nEpoch 48/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8482 - mae: 0.5362\nEpoch 49/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5704 - mae: 0.4759\nEpoch 50/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4364 - mae: 0.4100\nEpoch 51/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3213 - mae: 0.3866\nEpoch 52/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8501 - mae: 0.6023\nEpoch 53/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3460 - mae: 0.3882\nEpoch 54/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4423 - mae: 0.4329\nEpoch 55/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6833 - mae: 0.5442\nEpoch 56/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5850 - mae: 0.4994\nEpoch 57/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5518 - mae: 0.4368\nEpoch 58/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3823 - mae: 0.3822\nEpoch 59/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5088 - mae: 0.4555\nEpoch 60/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5841 - mae: 0.4894\nEpoch 61/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4261 - mae: 0.4626\nEpoch 62/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2992 - mae: 0.3754\nEpoch 63/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3994 - mae: 0.4166\nEpoch 64/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.9888 - mae: 0.6181\nEpoch 65/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5080 - mae: 0.5402\nEpoch 66/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7800 - mae: 0.5571\nEpoch 67/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4285 - mae: 0.4197\nEpoch 68/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3553 - mae: 0.4081\nEpoch 69/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3108 - mae: 0.3673\nEpoch 70/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6916 - mae: 0.5162\nEpoch 71/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6785 - mae: 0.5436\nEpoch 72/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8392 - mae: 0.5913\nEpoch 73/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4354 - mae: 0.3701\nEpoch 74/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3992 - mae: 0.4087\nEpoch 75/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4589 - mae: 0.4695\nEpoch 76/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7036 - mae: 0.5384\nEpoch 77/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3091 - mae: 0.3595\nEpoch 78/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6585 - mae: 0.4815\nEpoch 79/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4584 - mae: 0.4205\nEpoch 80/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6009 - mae: 0.5008\nEpoch 81/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6869 - mae: 0.5404\nEpoch 82/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4147 - mae: 0.4151\nEpoch 83/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2889 - mae: 0.3819\nEpoch 84/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3252 - mae: 0.3645\nEpoch 85/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3831 - mae: 0.3914\nEpoch 86/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4420 - mae: 0.4326\nEpoch 87/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4524 - mae: 0.4243\nEpoch 88/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2966 - mae: 0.3695\nEpoch 89/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6347 - mae: 0.5159\nEpoch 90/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4784 - mae: 0.4622\nEpoch 91/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4603 - mae: 0.4700\nEpoch 92/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5507 - mae: 0.4505\nEpoch 93/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5105 - mae: 0.4381\nEpoch 94/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4366 - mae: 0.3788\nEpoch 95/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5224 - mae: 0.4497\nEpoch 96/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6998 - mae: 0.4765\nEpoch 97/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2603 - mae: 0.3723\nEpoch 98/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4073 - mae: 0.4223\nEpoch 99/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4181 - mae: 0.4403\nEpoch 100/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4341 - mae: 0.4109\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b5b94f80> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 5ms/step - loss: 0.5670 - mae: 0.5407\nprocessing fold # 1\nEpoch 1/100\n106/106 [==============================] - 1s 939us/step - loss: 0.6963 - mae: 0.6958\nEpoch 2/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6472 - mae: 0.6106\nEpoch 3/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7655 - mae: 0.6030\nEpoch 4/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3168 - mae: 0.3985\nEpoch 5/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5973 - mae: 0.4642\nEpoch 6/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4877 - mae: 0.4668\nEpoch 7/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3978 - mae: 0.4601\nEpoch 8/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4482 - mae: 0.4828\nEpoch 9/100\n106/106 [==============================] - 0s 947us/step - loss: 0.5066 - mae: 0.4305\nEpoch 10/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5122 - mae: 0.4565\nEpoch 11/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2272 - mae: 0.3540\nEpoch 12/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3009 - mae: 0.3903\nEpoch 13/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2408 - mae: 0.3489\nEpoch 14/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2597 - mae: 0.4077\nEpoch 15/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4109 - mae: 0.4200\nEpoch 16/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2205 - mae: 0.3216\nEpoch 17/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2145 - mae: 0.3084\nEpoch 18/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2265 - mae: 0.3690\nEpoch 19/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2154 - mae: 0.3549\nEpoch 20/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3479 - mae: 0.3806\nEpoch 21/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1651 - mae: 0.2705\nEpoch 22/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2699 - mae: 0.3502\nEpoch 23/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3751 - mae: 0.3508\nEpoch 24/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2220 - mae: 0.3051\nEpoch 25/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3299 - mae: 0.3594\nEpoch 26/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2492 - mae: 0.3187\nEpoch 27/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4365 - mae: 0.3623\nEpoch 28/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2388 - mae: 0.3255\nEpoch 29/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3041 - mae: 0.3750\nEpoch 30/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2259 - mae: 0.2713\nEpoch 31/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2377 - mae: 0.3241\nEpoch 32/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4768 - mae: 0.3679\nEpoch 33/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2897 - mae: 0.3391\nEpoch 34/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2937 - mae: 0.3122\nEpoch 35/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2910 - mae: 0.3334\nEpoch 36/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1220 - mae: 0.2531\nEpoch 37/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2557 - mae: 0.3366\nEpoch 38/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1994 - mae: 0.3327\nEpoch 39/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2427 - mae: 0.2670\nEpoch 40/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1152 - mae: 0.2580\nEpoch 41/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1841 - mae: 0.2980\nEpoch 42/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2665 - mae: 0.3537\nEpoch 43/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4163 - mae: 0.4014\nEpoch 44/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2351 - mae: 0.3391\nEpoch 45/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1441 - mae: 0.3016\nEpoch 46/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2870 - mae: 0.3495\nEpoch 47/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2668 - mae: 0.3206\nEpoch 48/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1463 - mae: 0.2725\nEpoch 49/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1358 - mae: 0.2607\nEpoch 50/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1954 - mae: 0.2863\nEpoch 51/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2326 - mae: 0.3258\nEpoch 52/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1082 - mae: 0.2462\nEpoch 53/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1724 - mae: 0.2974\nEpoch 54/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2682 - mae: 0.3303\nEpoch 55/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1232 - mae: 0.2633\nEpoch 56/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3354 - mae: 0.3700\nEpoch 57/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2118 - mae: 0.2788\nEpoch 58/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1165 - mae: 0.2606\nEpoch 59/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1916 - mae: 0.3047\nEpoch 60/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1341 - mae: 0.2314\nEpoch 61/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1687 - mae: 0.2758\nEpoch 62/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1965 - mae: 0.3120\nEpoch 63/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1497 - mae: 0.2576\nEpoch 64/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1432 - mae: 0.2803\nEpoch 65/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2288 - mae: 0.3206\nEpoch 66/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1585 - mae: 0.2637\nEpoch 67/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1893 - mae: 0.2557\nEpoch 68/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2387 - mae: 0.3299\nEpoch 69/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2283 - mae: 0.2550\nEpoch 70/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.0932 - mae: 0.2318\nEpoch 71/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1384 - mae: 0.2345\nEpoch 72/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3347 - mae: 0.3513\nEpoch 73/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3278 - mae: 0.3653\nEpoch 74/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5472 - mae: 0.3610\nEpoch 75/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1792 - mae: 0.2584\nEpoch 76/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1089 - mae: 0.2267\nEpoch 77/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1518 - mae: 0.2778\nEpoch 78/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2906 - mae: 0.3068\nEpoch 79/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1466 - mae: 0.2941\nEpoch 80/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1305 - mae: 0.2619\nEpoch 81/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2306 - mae: 0.2688\nEpoch 82/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2762 - mae: 0.3163\nEpoch 83/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3421 - mae: 0.3590\nEpoch 84/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2097 - mae: 0.3267\nEpoch 85/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2286 - mae: 0.3050\nEpoch 86/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.0886 - mae: 0.2225\nEpoch 87/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2160 - mae: 0.2937\nEpoch 88/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1050 - mae: 0.2301\nEpoch 89/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2398 - mae: 0.3202\nEpoch 90/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1159 - mae: 0.2325\nEpoch 91/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1077 - mae: 0.2052\nEpoch 92/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1256 - mae: 0.2453\nEpoch 93/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3999 - mae: 0.3738\nEpoch 94/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1119 - mae: 0.1871\nEpoch 95/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1213 - mae: 0.2241\nEpoch 96/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1552 - mae: 0.2500\nEpoch 97/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1118 - mae: 0.2203\nEpoch 98/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1024 - mae: 0.2354\nEpoch 99/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.0948 - mae: 0.2242\nEpoch 100/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1631 - mae: 0.2744\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6bc5fe4d0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 7ms/step - loss: 0.4772 - mae: 0.4202\nprocessing fold # 2\nEpoch 1/100\n106/106 [==============================] - 1s 1ms/step - loss: 1.0295 - mae: 0.7556\nEpoch 2/100\n106/106 [==============================] - 0s 949us/step - loss: 0.7407 - mae: 0.5959\nEpoch 3/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4980 - mae: 0.4636\nEpoch 4/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.0514 - mae: 0.6216\nEpoch 5/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8827 - mae: 0.5496\nEpoch 6/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4272 - mae: 0.4347\nEpoch 7/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4891 - mae: 0.4636\nEpoch 8/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4305 - mae: 0.4593\nEpoch 9/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5227 - mae: 0.4828\nEpoch 10/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5784 - mae: 0.4648\nEpoch 11/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4708 - mae: 0.4657\nEpoch 12/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3848 - mae: 0.4355\nEpoch 13/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2897 - mae: 0.3963\nEpoch 14/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3589 - mae: 0.3947\nEpoch 15/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7231 - mae: 0.5122\nEpoch 16/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6635 - mae: 0.5232\nEpoch 17/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2633 - mae: 0.3182\nEpoch 18/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4941 - mae: 0.4577\nEpoch 19/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8865 - mae: 0.5924\nEpoch 20/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2646 - mae: 0.3712\nEpoch 21/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2756 - mae: 0.4071\nEpoch 22/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4156 - mae: 0.3603\nEpoch 23/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3127 - mae: 0.3607\nEpoch 24/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4678 - mae: 0.4372\nEpoch 25/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3799 - mae: 0.3881\nEpoch 26/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3122 - mae: 0.3743\nEpoch 27/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4596 - mae: 0.4375\nEpoch 28/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2424 - mae: 0.3193\nEpoch 29/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7215 - mae: 0.4467\nEpoch 30/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2602 - mae: 0.3171\nEpoch 31/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1560 - mae: 0.2874\nEpoch 32/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7326 - mae: 0.4746\nEpoch 33/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3597 - mae: 0.3904\nEpoch 34/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3391 - mae: 0.3632\nEpoch 35/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4067 - mae: 0.3315\nEpoch 36/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4118 - mae: 0.3761\nEpoch 37/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2880 - mae: 0.3502\nEpoch 38/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1886 - mae: 0.3011\nEpoch 39/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3301 - mae: 0.3608\nEpoch 40/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5451 - mae: 0.4176\nEpoch 41/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3544 - mae: 0.4040\nEpoch 42/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1974 - mae: 0.2850\nEpoch 43/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2163 - mae: 0.3122\nEpoch 44/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2028 - mae: 0.3320\nEpoch 45/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1997 - mae: 0.2884\nEpoch 46/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1986 - mae: 0.2923\nEpoch 47/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2511 - mae: 0.3033\nEpoch 48/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2502 - mae: 0.3272\nEpoch 49/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4437 - mae: 0.3946\nEpoch 50/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3096 - mae: 0.3511\nEpoch 51/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2325 - mae: 0.3416\nEpoch 52/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3370 - mae: 0.3594\nEpoch 53/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4298 - mae: 0.3142\nEpoch 54/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6553 - mae: 0.4779\nEpoch 55/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3015 - mae: 0.3358\nEpoch 56/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2292 - mae: 0.3224\nEpoch 57/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1221 - mae: 0.2592\nEpoch 58/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5715 - mae: 0.4204\nEpoch 59/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4014 - mae: 0.3791\nEpoch 60/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1202 - mae: 0.2537\nEpoch 61/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3960 - mae: 0.4005\nEpoch 62/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4465 - mae: 0.3931\nEpoch 63/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2266 - mae: 0.3041\nEpoch 64/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4336 - mae: 0.3873\nEpoch 65/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3199 - mae: 0.3412\nEpoch 66/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3334 - mae: 0.3844\nEpoch 67/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2516 - mae: 0.3117\nEpoch 68/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1913 - mae: 0.2791\nEpoch 69/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3408 - mae: 0.3641\nEpoch 70/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4673 - mae: 0.4206\nEpoch 71/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3511 - mae: 0.3582\nEpoch 72/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2478 - mae: 0.2800\nEpoch 73/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2495 - mae: 0.3398\nEpoch 74/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1528 - mae: 0.2758\nEpoch 75/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1451 - mae: 0.2717\nEpoch 76/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2552 - mae: 0.2977\nEpoch 77/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1548 - mae: 0.2888\nEpoch 78/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2912 - mae: 0.3193\nEpoch 79/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1644 - mae: 0.3026\nEpoch 80/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1873 - mae: 0.2576\nEpoch 81/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1482 - mae: 0.2499\nEpoch 82/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1956 - mae: 0.2709\nEpoch 83/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.9151 - mae: 0.4600\nEpoch 84/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3341 - mae: 0.2988\nEpoch 85/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1329 - mae: 0.2511\nEpoch 86/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3164 - mae: 0.3013\nEpoch 87/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1950 - mae: 0.2831\nEpoch 88/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4189 - mae: 0.3931\nEpoch 89/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4194 - mae: 0.3281\nEpoch 90/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2013 - mae: 0.2734\nEpoch 91/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2522 - mae: 0.2914\nEpoch 92/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5704 - mae: 0.3916\nEpoch 93/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5827 - mae: 0.3976\nEpoch 94/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2654 - mae: 0.3267\nEpoch 95/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2077 - mae: 0.3181\nEpoch 96/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1772 - mae: 0.2981\nEpoch 97/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2189 - mae: 0.2886\nEpoch 98/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2851 - mae: 0.2967\nEpoch 99/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2318 - mae: 0.2939\nEpoch 100/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2170 - mae: 0.2853\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b9ed3320> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 8ms/step - loss: 0.4369 - mae: 0.4527\nprocessing fold # 3\nEpoch 1/100\n106/106 [==============================] - 1s 1ms/step - loss: 1.2738 - mae: 0.7879\nEpoch 2/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.4708 - mae: 0.7930\nEpoch 3/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8197 - mae: 0.6511\nEpoch 4/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.8413 - mae: 0.6085\nEpoch 5/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3908 - mae: 0.4277\nEpoch 6/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6737 - mae: 0.5652\nEpoch 7/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.0471 - mae: 0.6484\nEpoch 8/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7135 - mae: 0.5635\nEpoch 9/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.9645 - mae: 0.5971\nEpoch 10/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6237 - mae: 0.5109\nEpoch 11/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.0228 - mae: 0.6051\nEpoch 12/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6109 - mae: 0.4947\nEpoch 13/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5464 - mae: 0.4952\nEpoch 14/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3723 - mae: 0.4081\nEpoch 15/100\n106/106 [==============================] - 0s 1ms/step - loss: 1.2001 - mae: 0.6198\nEpoch 16/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2621 - mae: 0.3819\nEpoch 17/100\n106/106 [==============================] - 0s 2ms/step - loss: 0.7415 - mae: 0.5550\nEpoch 18/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3444 - mae: 0.3756\nEpoch 19/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4014 - mae: 0.3859\nEpoch 20/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4462 - mae: 0.3966\nEpoch 21/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3778 - mae: 0.3980\nEpoch 22/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4404 - mae: 0.4069\nEpoch 23/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4304 - mae: 0.4451\nEpoch 24/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3809 - mae: 0.4001\nEpoch 25/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6367 - mae: 0.4345\nEpoch 26/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3524 - mae: 0.3811\nEpoch 27/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3725 - mae: 0.3697\nEpoch 28/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3830 - mae: 0.4531\nEpoch 29/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4814 - mae: 0.4136\nEpoch 30/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4242 - mae: 0.3850\nEpoch 31/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3749 - mae: 0.3604\nEpoch 32/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6708 - mae: 0.4687\nEpoch 33/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5101 - mae: 0.4825\nEpoch 34/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7490 - mae: 0.4728\nEpoch 35/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4205 - mae: 0.3928\nEpoch 36/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3162 - mae: 0.3743\nEpoch 37/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3644 - mae: 0.4082\nEpoch 38/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5174 - mae: 0.4035\nEpoch 39/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6632 - mae: 0.4742\nEpoch 40/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6064 - mae: 0.4383\nEpoch 41/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5227 - mae: 0.4705\nEpoch 42/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3187 - mae: 0.3809\nEpoch 43/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5321 - mae: 0.4589\nEpoch 44/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4187 - mae: 0.4238\nEpoch 45/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5840 - mae: 0.4346\nEpoch 46/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3558 - mae: 0.3847\nEpoch 47/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2972 - mae: 0.3954\nEpoch 48/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4099 - mae: 0.3785\nEpoch 49/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2659 - mae: 0.3649\nEpoch 50/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3808 - mae: 0.4002\nEpoch 51/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2525 - mae: 0.3628\nEpoch 52/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2522 - mae: 0.2982\nEpoch 53/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1744 - mae: 0.2604\nEpoch 54/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3299 - mae: 0.3653\nEpoch 55/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3841 - mae: 0.4209\nEpoch 56/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4349 - mae: 0.3823\nEpoch 57/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2978 - mae: 0.3365\nEpoch 58/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4084 - mae: 0.3593\nEpoch 59/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4199 - mae: 0.4086\nEpoch 60/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2602 - mae: 0.3423\nEpoch 61/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3859 - mae: 0.4061\nEpoch 62/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4082 - mae: 0.4204\nEpoch 63/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5823 - mae: 0.4032\nEpoch 64/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3836 - mae: 0.4198\nEpoch 65/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2884 - mae: 0.3198\nEpoch 66/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2387 - mae: 0.3245\nEpoch 67/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3679 - mae: 0.3520\nEpoch 68/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2793 - mae: 0.3134\nEpoch 69/100\n106/106 [==============================] - 0s 2ms/step - loss: 0.5334 - mae: 0.3912\nEpoch 70/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4258 - mae: 0.3685\nEpoch 71/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4323 - mae: 0.3967\nEpoch 72/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.5791 - mae: 0.4921\nEpoch 73/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2708 - mae: 0.3502\nEpoch 74/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6172 - mae: 0.4650\nEpoch 75/100\n106/106 [==============================] - 0s 2ms/step - loss: 0.1741 - mae: 0.2952\nEpoch 76/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3470 - mae: 0.3751\nEpoch 77/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2875 - mae: 0.3222\nEpoch 78/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2035 - mae: 0.3210\nEpoch 79/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1978 - mae: 0.2914\nEpoch 80/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2769 - mae: 0.2958\nEpoch 81/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.6036 - mae: 0.4225\nEpoch 82/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2576 - mae: 0.2875\nEpoch 83/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2945 - mae: 0.3251\nEpoch 84/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3358 - mae: 0.3099\nEpoch 85/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2873 - mae: 0.3360\nEpoch 86/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1660 - mae: 0.2733\nEpoch 87/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2646 - mae: 0.3257\nEpoch 88/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2454 - mae: 0.2816\nEpoch 89/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3382 - mae: 0.3445\nEpoch 90/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.4151 - mae: 0.3938\nEpoch 91/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2420 - mae: 0.3118\nEpoch 92/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2925 - mae: 0.2941\nEpoch 93/100\n106/106 [==============================] - 0s 2ms/step - loss: 0.2355 - mae: 0.2809\nEpoch 94/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2309 - mae: 0.3247\nEpoch 95/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1874 - mae: 0.2751\nEpoch 96/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.1866 - mae: 0.2697\nEpoch 97/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.7509 - mae: 0.5415\nEpoch 98/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2808 - mae: 0.3660\nEpoch 99/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.3841 - mae: 0.3699\nEpoch 100/100\n106/106 [==============================] - 0s 1ms/step - loss: 0.2435 - mae: 0.2798\nWARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6bceec440> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 4ms/step - loss: 0.1671 - mae: 0.2976\n"
]
],
[
[
"# Scores\n## here we will see MAE mean absolute Error scores of all model which we have saved in the list during each training in above section",
"_____no_output_____"
]
],
[
[
"all_scores_relu",
"_____no_output_____"
],
[
"all_scores_tanh",
"_____no_output_____"
],
[
"all_scores_regular",
"_____no_output_____"
],
[
"all_scores_drop",
"_____no_output_____"
]
],
[
[
"# training on the training data\n## here we will call each model separately from Models section and train on the training data and evaluate on the test data",
"_____no_output_____"
]
],
[
[
"\nmodel_tanh = build_model('tanh')\nmodel_tanh.fit(train, train_l,epochs= 100, batch_size=1, verbose=0)\ntest_mse_score, test_mae_score = model_tanh.evaluate(test, test_l)",
"WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6ad955c20> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 5ms/step - loss: 0.1038 - mae: 0.2437\n"
],
[
"model_relu = build_model('relu')\nmodel_relu.fit(train, train_l,epochs= 100, batch_size=1, verbose=0)\ntest_mse_score, test_mae_score = model_relu.evaluate(test, test_l)",
"WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b5921d40> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 9ms/step - loss: 0.0852 - mae: 0.2275\n"
],
[
"model_regular = build_model_regular('relu')\nmodel_regular.fit(train, train_l,epochs= 100, batch_size=1, verbose=0)\ntest_mse_score, test_mae_score = model_regular.evaluate(test, test_l)",
"WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6b0d9e9e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 9ms/step - loss: 0.1397 - mae: 0.2406\n"
],
[
"model_drop = build_model_drop('relu')\nmodel_drop.fit(train, train_l,epochs= 100, batch_size=1, verbose=0)\ntest_mse_score, test_mae_score = model_drop.evaluate(test, test_l)",
"WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fa6ad967710> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n2/2 [==============================] - 0s 9ms/step - loss: 0.1683 - mae: 0.3534\n"
]
],
[
[
"# Prediction Section\n## here we will predict our prices of our test dataset with each model which we have trained in training section\n## Note that here we will use the reverse process of Normalization to retrieve our values of price in thousand of dollars i.e. x = (y - mean)/ std ==>> we will calculate( y = x * std + mean) and then we will compare it with our target values",
"_____no_output_____"
]
],
[
[
"test_l",
"_____no_output_____"
],
[
"def predict(model, m):\n print(f\" the Actual value Price was : {test_l[m]* std_label + mean_label} \" )\n return(f\" the predicted Price was : {(model.predict(test[m:m+1].reshape(1,test.shape[1]))) * std_label + mean_label} \")\n",
"_____no_output_____"
],
[
"x_tanh = predict(model_tanh,2)\nx_tanh",
" the Actual value Price was : 24565.000309357743 \nWARNING:tensorflow:7 out of the last 11 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fa6b9eed560> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"x_relu = predict(model_relu,2)\nx_relu",
" the Actual value Price was : 24565.000309357743 \nWARNING:tensorflow:7 out of the last 11 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fa6bcfc2560> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"x_regular = predict(model_regular,2)\nx_regular",
" the Actual value Price was : 24565.000309357743 \nWARNING:tensorflow:8 out of the last 12 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fa6aa28f200> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"x_drop = predict(model_drop,2)\nx_drop",
" the Actual value Price was : 24565.000309357743 \nWARNING:tensorflow:8 out of the last 11 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fa6aa2a0ef0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n"
],
[
"def plot_fn(mod):\n y_true = test_l* std_label + mean_label\n y_pred = mod.predict(test) * std_label + mean_label\n return y_true , y_pred.flatten()",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\ndef plotting(mod, label):\n y_true, y_pred = plot_fn(mod)\n coef = np.polyfit(y_true,y_pred,1)\n poly1d_fn = np.poly1d(coef) \n # poly1d_fn is now a function which takes in x and returns an estimate for y\n plt.figure()\n plt.plot(y_true,y_pred, 'yo', y_true, poly1d_fn(y_true), '--k')\n plt.title(label)\n plt.xlabel('Thousand Dollar True' )\n plt.ylabel('Thousand Dollar Predictions' )\n plt.xlim(0, 50000)\n plt.ylim(0, 50000)",
"_____no_output_____"
],
[
"plot_list = []\nfor i,j in enumerate([model_relu, model_tanh, model_regular, model_drop]):\n list_name = ['model_relu', 'model_tanh', 'model_regular', 'model_drop']\n plot_list.append(plotting(j,list_name[i]))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"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",
"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",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb46cbd04063eb53fcabb0e417d26c04a3cf848b | 45,041 | ipynb | Jupyter Notebook | User_CF.ipynb | wjie0309/-AI- | 44d6c4b97e85cb16b976e559f4236641e074720c | [
"Apache-2.0"
] | null | null | null | User_CF.ipynb | wjie0309/-AI- | 44d6c4b97e85cb16b976e559f4236641e074720c | [
"Apache-2.0"
] | null | null | null | User_CF.ipynb | wjie0309/-AI- | 44d6c4b97e85cb16b976e559f4236641e074720c | [
"Apache-2.0"
] | null | null | null | 32.264327 | 219 | 0.387935 | [
[
[
"# [AI达人创造营第二期] 从电影推荐系统出发了解基于用户的协同过滤算法",
"_____no_output_____"
],
[
"## 1. 项目背景介绍\n### 1.1 协同过滤算法\n协同过滤算法是推荐算法领域中基础但非常重要的部分, 它从1992年开始投入推荐算法的研究过程中, 并在AMAZON等大型电子商务的推荐系统中起到了非常出色的效果.\n\n协同过滤算法可以被分为基于用户的协同过滤算法以及基于项目的协同过滤算法. 本项目将从电影推荐系统的简单构建出发来介绍基于用户的协同过滤算法\n\n### 1.2 以用户为基础(User-based)的协同过滤\n用相似统计的方法得到具有相似爱好或者兴趣的相邻用户, 所以称之为以用户为基础(User-based)的协同过滤或基于邻居的协同过滤(Neighbor-based Collaborative Filtering). \n\n\n\n基本方法步骤:\n1. 收集用户信息\n\n收集可以代表用户兴趣的信息, 一般的网站系统使用评分的方式或是给予评价, 这种方式被称为“主动评分”, 另外一种是“被动评分”, 是根据用户的行为模式由系统代替用户完成评价. 不需要用户直接打分或输入评价数据. 电子商务网站在被动评分的数据获取上有其优势, 用户购买的商品记录是相当有用的数据.\n\n2. 最近邻搜索(Nearest neighbor search, NNS)\n\n以用户为基础(User-based)的协同过滤的出发点是与用户兴趣爱好相同的另一组用户, 就是计算两个用户的相似度. 例如:查找n个和A有相似兴趣用户, 把他们对M的评分作为A对M的评分预测. 一般会根据数据的不同选择不同的算法, 较多使用的相似度算法有Pearson Correlation Coefficient、Cosine-based Similarity、Adjusted Cosine Similarity.\n \n3. 产生推荐结果\n\n有了最近邻集合, 就可以对目标用户的兴趣进行预测,产生推荐结果。依据推荐目的的不同进行不同形式的推荐, 较常见的推荐结果有Top-N 推荐和关系推荐。Top-N 推荐是针对个体用户产生, 对每个人产生不一样的结果, 例如:通过对A用户的最近邻用户进行统计, 选择出现频率高且在A用户的评分项目中不存在的,作为推荐结果。关系推荐是对最近邻用户的记录进行关系规则(association rules)挖掘.",
"_____no_output_____"
],
[
"## 2. 数据介绍\n模型决定复现经典的协同过滤算法(CF), 在本项目中, 拟使用Movielens的ml-latest数据集来完成一个简单的电影推荐系统.\n\nMovieLens数据集包含多个用户对多部电影的评级数据, 也包括电影元数据信息和用户属性信息.\n\n这个数据集经常用来做推荐系统, 机器学习算法的测试数据集. 尤其在推荐系统领域, 很多著名论文都是基于这个数据集的.\n\n本文采用的是MovieLens中的ml-latest数据集.",
"_____no_output_____"
],
[
"### 2.1 解压数据集及导入依赖包\n项目中导入了m1-latest数据集",
"_____no_output_____"
]
],
[
[
"!unzip -oq data/data101354/ml-latest.zip -d data/\r\nprint('解压成功!')",
"解压成功!\n"
],
[
"import pandas as pd\r\nimport paddle\r\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"### 2.2 数据集的读取\n在读取数据集时, 由于评价时间在统计过程中没有用到, 所以不读取. 为了快速看到训练效果, 只取前10w个数据作为小量数据集",
"_____no_output_____"
]
],
[
[
"dtype = {'userId': np.int64, 'movieId': np.int64, 'rating': np.float32}\r\n# 由于评价时间在统计过程中没有用到, 所以不读取. 为了缩短训练时间, 只取前10w个数据作为小量数据集\r\nratings_data = pd.read_csv(r'data/ml-latest/ratings.csv', dtype=dtype, usecols=[0,1,2], nrows=100000)\r\nprint('success!')",
"success!\n"
]
],
[
[
"### 2.3 数据的可视化与处理\n在完成数据的读取后, 对数据集的基本信息进行简单的了解, 以及转变数据集的储存格式",
"_____no_output_____"
]
],
[
[
"# 数据的基本结构\r\nprint(ratings_data.head())\r\n# 数据集的信息\r\nprint(ratings_data.describe())",
" userId movieId rating\n0 1 307 3.5\n1 1 481 3.5\n2 1 1091 1.5\n3 1 1257 4.5\n4 1 1449 4.5\n userId movieId rating\ncount 100000.000000 100000.000000 100000.000000\nmean 507.615380 18282.999630 3.507395\nstd 303.510237 35015.296487 1.103155\nmin 1.000000 1.000000 0.500000\n25% 239.000000 1079.000000 3.000000\n50% 491.000000 2580.000000 4.000000\n75% 780.000000 6934.000000 4.000000\nmax 1041.000000 192579.000000 5.000000\n"
]
],
[
[
"在看完基本的数据集信息后, 为了能够更直观地看到用户和电影之间的关系, 以及更好地调用同一个用户的电影评分以及同一部电影不同用户给出的评分, 现将数据集转化为透视表的形式, 将评价信息转化为用户对电影的评分矩阵",
"_____no_output_____"
]
],
[
[
"# 构建透视表\r\nratings_matrix = ratings_data.pivot_table(index='userId', columns='movieId', values='rating')\r\n# 透视表概览\r\nratings_matrix",
"_____no_output_____"
]
],
[
[
"## 3. 模型构建",
"_____no_output_____"
],
[
"### 3.1 相似度的计算\n在协同过滤算法中, 经常使用的相似度有三种, 分别为余弦相似度, 皮尔逊(Pearson)相似度, 以及杰卡德(Jacaard)相似度.\n\n\n- 余弦相似度, Pearson相似度\n\t- 余弦相似度: \n $$sim(a,b) = \\frac{\\vec{a} \\cdot \\vec{b}}{|\\vec{a}| \\times |\\vec{b}|}$$\n \n - Pearson相似度:\n $$corr(a,b) = \\frac{\\sum _{i} (r_{ai}-\\overline{r_a})(r_{b\ti}-\\overline{r_b})}{\\sqrt{\\sum _{i}(r_{ai}-\\overline{r_a})^2 \\sum _{i}(r_{b\ti}-\\overline{r_b})^2}}$$\n\t- 都为向量的余弦角值\n - Pearson相似度会对向量的每一个分量做中心化处理\n - 相对于余弦相似度, Pearson相似度还考虑每一个向量的长度, 因此Pearson更加常用\n - 在评价数据是连续分布的情况下, 常使用余弦相似度以及Pearson相似度\n- Jaccard相似度\n\t- 计算方法: $sim(a,b) = \\frac{交集}{并集}$\n - 在计算评分数据为布尔值的情况下, 使用Jaccard相似度\n\n\n\n对电影评分的预测我们使用Pearson相似度来作为用户之间的相似度.\n",
"_____no_output_____"
]
],
[
[
"# 计算pearson_similarity\r\nsimilarity = ratings_matrix.T.corr()\r\nsimilarity",
"_____no_output_____"
]
],
[
[
"### 3.2 构建预测模型\n在得到了用户之间的相似度矩阵后, 我们就可以开始构建对于某个指定的用户对电影的喜好程度的预测了. 以下是实现思路:\n1. 对相似度矩阵先进行处理, 去除无关用户和与目标用户负相关的用户, 得到初步的相似用户similar_users\n2. 在相似用户中进行筛选, 只留下那些只看过我们目标电影的用户作为最终参与预测的用户群体final_similar_users\n3. 根据评分预测的公式\n$$pred(user, movie) = \\frac{\\sum_{v \\in U} sim(user, movie) * r_{vi}}{\\sum_{v \\in U} |sim(user, movie)|}$$\n我们可以计算出预测分数",
"_____no_output_____"
]
],
[
[
"# 构建指定用户对指定电影的评分预测\r\ndef predict(user, movie, ratings_matrix, similarity):\r\n # 找到和目标user相关的用户\r\n similar_users = similarity[user].drop([user]).dropna()\r\n # 去除掉负相关的干扰项\r\n similar_users = similar_users.where(similar_users>0).dropna()\r\n # 找到其中评价过目标电影的用户\r\n idx = ratings_matrix[movie].dropna().index & similar_users.index\r\n # 得到最终这些相似用户的相似度\r\n final_similar_users = similar_users.loc[list(idx)]\r\n # 初始化评分预测公式的分子分母\r\n sum_up = 0\r\n sum_down = 0\r\n for sim_user, similarity in final_similar_users.iteritems():\r\n # 相似用户的评分数据\r\n sim_user_rated_movies = ratings_matrix.loc[sim_user].dropna()\r\n # 相似用户对目标电影的评分\r\n sim_user_rating_for_movie = sim_user_rated_movies[movie]\r\n sum_up += similarity*sim_user_rating_for_movie\r\n sum_down += similarity\r\n \r\n # 计算预测评分\r\n predict_rating = sum_up/sum_down\r\n return predict_rating\r\n",
"_____no_output_____"
]
],
[
[
"### 3.3 构建排序模型\n通过之前计算得到的评分预测模型, 我们可以通过计算指定用户对电影的评分预测来得到电影评分预测的排序, 从而给出针对特定用户的电影推荐.\n\n\n在这个过程中, 首先我们将构建一个对所有电影进行评分预测的函数, 这其中会包含对极端数据的处理:\n- 不会再次预测目标用户已经观看过的电影.\n- 不会给用户推荐评分数量过少的\"冷门\"电影.\n通过筛选掉这些电影之后, 我们就会得到对一个特定用户来说的电影评分预测清单.\n\n\n利用这个预测清单既可以轻松得到推荐电影的movieId",
"_____no_output_____"
]
],
[
[
"# 对一个指定用户的所有电影进行评分预测\r\ndef predict_all(user, ratings_matrix, similarity, filter_rule=None):\r\n # 添加过滤条件简化数据集中的冗余数据\r\n if not filter_rule:\r\n # 获取电影Id索引\r\n movie_idx = ratings_matrix.columns\r\n elif filter_rule == ['unhot','rated']:\r\n # 去除用户已经看过的电影\r\n user_ratings = ratings_matrix.iloc[user]\r\n # 判断已经有过评分的电影\r\n _ = user_ratings<=5\r\n idx1 = _.where(_ == False).dropna().index\r\n\r\n # 去除冷门电影, 热门电影的判断标准暂定为被观看(评分)超过十次\r\n count = ratings_matrix.count()\r\n idx2 = count.where(count>10).dropna().index\r\n\r\n movie_idx = set(idx1) & set(idx2)\r\n else:\r\n raise Exception('无效过滤参数')\r\n \r\n # 进入循环\r\n for movie in movie_idx:\r\n try:\r\n rating = predict(user, movie, ratings_matrix, similarity)\r\n except Exception as e:\r\n pass\r\n else:\r\n yield user, movie, rating\r\n",
"_____no_output_____"
],
[
"# 给出前n项推荐的电影ID\r\ndef rank(user, n):\r\n results = predict_all(user, ratings_matrix, similarity, filter_rule=['unhot','rated'])\r\n # 根据分数进行降序排序, 然后输出前n项\r\n return sorted(results, key=lambda x: x[2], reverse = True)[:n]",
"_____no_output_____"
]
],
[
[
"### 3.4 结合movies.csv数据集输出电影名称\n在得到了推荐的电影的movieId后, 可以通过movies,csv来读取电影名称最后输出推荐的电影.",
"_____no_output_____"
]
],
[
[
"# 读取movies数据集\r\nmovie_names = pd.read_csv(r'data/ml-latest/movies.csv')\r\nprint('success!')",
"success!\n"
],
[
"# 电影id与名称对应概览\r\n# print(movie_names.head())\r\nmovie_id = 1\r\nprint(movie_names.where(movie_names['movieId']==movie_id).dropna().values[0][1])",
"Toy Story (1995)\n"
],
[
"# 输出推荐的电影的电影名称\r\ndef get_movie_name(rank, movie_names):\r\n count = 0\r\n print(f'推荐的电影按推荐力度排列如下:')\r\n # rank函数返回的是一个二维数组, 其中每一项的第二个数据为推荐的movieId\r\n for item in rank:\r\n movie_id = item[1]\r\n count += 1\r\n print(f'{count}.', movie_names.where(movie_names['movieId']==movie_id).dropna().values[0][1])",
"_____no_output_____"
],
[
"# 电影推荐实例测试\r\nuser_id = 100\r\n# 输出top10推荐电影\r\nget_movie_name(rank(user_id,10), movie_names)",
"推荐的电影按推荐力度排列如下:\n1. Thin Man, The (1934)\n2. Inherit the Wind (1960)\n3. Strangers on a Train (1951)\n4. 12 Angry Men (1957)\n5. Doctor Zhivago (1965)\n6. Roger & Me (1989)\n7. Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb (1964)\n8. Shawshank Redemption, The (1994)\n9. Treasure of the Sierra Madre, The (1948)\n10. Seven Samurai (Shichinin no samurai) (1954)\n"
]
],
[
[
"## 4. 总结与升华\n协同过滤算法是推荐算法领域的重要部分, 它有许多优点, 比如能够过滤机器难以自动内容分析的信息, 避免了内容分析的不完全或不精确; 并且能够基于一些复杂的, 难以表述的概念(如信息质量, 个人品味)进行过滤等等.\n\n但是协同过滤算法同样有着许多不足:\n1. 对于新用户的推荐效果就较差, 由于新用户的评价数据较少, 就很难确定用户的准确的相似用户群体, 因此也难以给出准确的判断\n2. 由于推荐系统的应用场景大部分都是在具有非常庞大的项目数量的基础上的, 因此用户评价数据的稀疏性也会成为一个值得关注的问题\n\n对于协同过滤算法中的每一个细节, 我们也都可以思考优化的方向, 比如相似度的计算, 数据的读取使用的方法, 相似度矩阵的储存和读取等等. 当下本项目使用的仅仅是节选的10万的数据集, 在面对实际应用时大体量的数据场景下, 这些问题的优化就会起到举足轻重的作用.",
"_____no_output_____"
]
],
[
[
"# 查看当前挂载的数据集目录, 该目录下的变更重启环境后会自动还原\n# View dataset directory. \n# This directory will be recovered automatically after resetting environment. \n!ls /home/aistudio/data",
"data101354 ml-latest\r\n"
],
[
"# 查看工作区文件, 该目录下的变更将会持久保存. 请及时清理不必要的文件, 避免加载过慢.\n# View personal work directory. \n# All changes under this directory will be kept even after reset. \n# Please clean unnecessary files in time to speed up environment loading. \n!ls /home/aistudio/work",
"_____no_output_____"
],
[
"# 如果需要进行持久化安装, 需要使用持久化路径, 如下方代码示例:\n# If a persistence installation is required, \n# you need to use the persistence path as the following: \n!mkdir /home/aistudio/external-libraries\n!pip install beautifulsoup4 -t /home/aistudio/external-libraries",
"mkdir: cannot create directory ‘/home/aistudio/external-libraries’: File exists\nLooking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\nCollecting beautifulsoup4\n Using cached https://pypi.tuna.tsinghua.edu.cn/packages/69/bf/f0f194d3379d3f3347478bd267f754fc68c11cbf2fe302a6ab69447b1417/beautifulsoup4-4.10.0-py3-none-any.whl (97 kB)\nCollecting soupsieve>1.2\n Using cached https://pypi.tuna.tsinghua.edu.cn/packages/72/a6/fd01694427f1c3fcadfdc5f1de901b813b9ac756f0806ef470cfed1de281/soupsieve-2.3.1-py3-none-any.whl (37 kB)\nInstalling collected packages: soupsieve, beautifulsoup4\nSuccessfully installed beautifulsoup4-4.10.0 soupsieve-2.3.1\n\u001b[33mWARNING: Target directory /home/aistudio/external-libraries/bs4 already exists. Specify --upgrade to force replacement.\u001b[0m\n\u001b[33mWARNING: Target directory /home/aistudio/external-libraries/soupsieve already exists. Specify --upgrade to force replacement.\u001b[0m\n\u001b[33mWARNING: Target directory /home/aistudio/external-libraries/soupsieve-2.3.1.dist-info already exists. Specify --upgrade to force replacement.\u001b[0m\n\u001b[33mWARNING: Target directory /home/aistudio/external-libraries/beautifulsoup4-4.10.0.dist-info already exists. Specify --upgrade to force replacement.\u001b[0m\n\u001b[33mWARNING: You are using pip version 21.3.1; however, version 22.0.3 is available.\nYou should consider upgrading via the '/opt/conda/envs/python35-paddle120-env/bin/python -m pip install --upgrade pip' command.\u001b[0m\n"
],
[
"# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可: \n# Also add the following code, \n# so that every time the environment (kernel) starts, \n# just run the following code: \nimport sys \nsys.path.append('/home/aistudio/external-libraries')",
"_____no_output_____"
]
],
[
[
"请点击[此处](https://ai.baidu.com/docs#/AIStudio_Project_Notebook/a38e5576)查看本环境基本用法. <br>\nPlease click [here ](https://ai.baidu.com/docs#/AIStudio_Project_Notebook/a38e5576) for more detailed instructions. ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb46cff2a767a5e3c9dd8dcdd64a874af774a4f9 | 749,653 | ipynb | Jupyter Notebook | analysis/SebiUnipan/milestone3.ipynb | data301-2020-winter1/course-project-solo_122 | 0cc6e4a2cb404ed6bc12e68ef4341f1cccc58bb6 | [
"MIT"
] | 1 | 2021-06-10T03:32:23.000Z | 2021-06-10T03:32:23.000Z | analysis/SebiUnipan/milestone3.ipynb | sunipan/Data-Analysis-Project | d44010805459a26da9e86f71616bbe3caf10478c | [
"MIT"
] | 1 | 2020-11-24T01:22:59.000Z | 2020-11-24T01:22:59.000Z | analysis/SebiUnipan/milestone3.ipynb | sunipan/Data-Analysis-Project | d44010805459a26da9e86f71616bbe3caf10478c | [
"MIT"
] | 1 | 2020-10-27T08:56:06.000Z | 2020-10-27T08:56:06.000Z | 454.886529 | 87,584 | 0.927084 | [
[
[
"import sys, os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas_profiling as pp\n\nsys.path.insert(0, os.path.abspath('..'))\nfrom script.functions import *",
"_____no_output_____"
]
],
[
[
"#### First, we import the data and display it after passing it through the function.",
"_____no_output_____"
]
],
[
[
"df = load_and_process('../../data/raw/adult.data')\ndf\n#MANAGED THE IMPORT THANK GOD",
"_____no_output_____"
]
],
[
[
"#### Next, we describe the data to show the mean surveyed age (38) and the mean work hours of 40/week",
"_____no_output_____"
]
],
[
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"#### Create a profile report for the dataset.",
"_____no_output_____"
]
],
[
[
"df.to_csv('../../data/processed/processed1.csv')\nreport = pp.ProfileReport(df).to_file('../../data/processed/report.html')",
"_____no_output_____"
]
],
[
[
"#### Let's check the relationship between Age and Education",
"_____no_output_____"
]
],
[
[
"ageEdu = df.loc[:,['Age', 'Education']]\nageEdu",
"_____no_output_____"
]
],
[
[
"### Create countplot for different education levels:\nThis is to see what education the majority of the people surveyed in this dataset had.\nWe can clearly see that most of the people only joined the workforce with a HS degree\nwhile others mainly did some college courses or compeleted a full Bachelors",
"_____no_output_____"
]
],
[
[
"ageEdu.replace({'Some-college': 'Some\\ncollege','Prof-school':'Prof-\\nschool',\n 'Assoc-voc':'Assoc\\n-voc','Assoc-acdm':'Assoc\\n-acdm',\n 'Preschool':'Pre-\\nschool'}, inplace = True)\n#names didn't fit on graph so I had to change them.\nsns.despine()\nplt.figure(figsize = (20,10))\nsns.set(style = 'white', font_scale = 1.5)\neduCountGraph = sns.countplot(x = 'Education', data = ageEdu, palette = 'viridis', order = ageEdu['Education'].value_counts().index)\neduCountGraph.get_figure().savefig('../../images/eduCount.jpg',dpi = 500)",
"_____no_output_____"
],
[
"#Replace all row values in Education with new format.\ndf.replace({'Some-college': 'Some\\ncollege','Prof-school':'Prof-\\nschool',\n 'Assoc-voc':'Assoc\\n-voc','Assoc-acdm':'Assoc\\n-acdm',\n 'Preschool':'Pre-\\nschool'}, inplace = True)\ndf",
"_____no_output_____"
]
],
[
[
"## Let's check the relationship of Age vs Earnings:\n#### First, we check the count of ages that have >50K earning/year\nThis shows that the most amount of people with above 50K yearly income are aged 37 - 47\nwhich just shows that this is the age when adults become most settled with a good job",
"_____no_output_____"
]
],
[
[
"ageEarn = df.loc[:,['Age', 'Yearly Income']]\nageEarnAbove50k = ageEarn.loc[lambda x: x['Yearly Income'] == '>50K']\n\n#We'll check both Ages that have above and below 50K income\nsns.set(style = 'white', font_scale = 1.5,rc={'figure.figsize':(30,10)})\nageEarnGraph = sns.histplot(x = 'Age',data = ageEarnAbove50k,shrink = 0.9, bins = 6, kde = True)\nageEarnGraph.set(ylabel = 'Yearly Income\\nAbove 50K Count')\nageEarnGraph.get_figure().savefig('../../images/ageEarnAbove50k.jpg', dpi = 500)",
"_____no_output_____"
]
],
[
[
"#### Next, we check the count of ages with <=50K earning/year\nThis shows that the most amount of people with below 50K yearly income are aged 19 - 36\nwhich is understandable for young people",
"_____no_output_____"
]
],
[
[
"ageEarnBelow50k = ageEarn.loc[lambda x: x['Yearly Income'] == '<=50K']\nageEarnGraph = sns.histplot(x = 'Age', data = ageEarnBelow50k,bins = 6, shrink = 0.9, kde = True)\nageEarnGraph.set(ylabel = 'Yearly Income\\nBelow 50K Count')\nageEarnGraph.get_figure().savefig('../../images/ageEarnBelow50k.jpg', dpi = 500)",
"_____no_output_____"
]
],
[
[
"## Let's make a density plot to see the trends in each graph and where they overlap\n#### TL;DR Mo money mo money mo money - as we age..to the peak of 47.\nThis just shows the immense density of those aged around 40 in the above 50K\ngroup. It also shows that at around age 25 most is where most people make under 50K\nthen they start to climb the above 50K ladder at the peak age of 40. From\nthis data it is evident that we make more money as we get older.",
"_____no_output_____"
]
],
[
[
"ageEarnDenisty = sns.kdeplot(x = 'Age',hue = 'Yearly Income', data = ageEarn,\n alpha = 0.3, fill = True, common_norm = False)",
"_____no_output_____"
]
],
[
[
"# Time to look at research questions.\n## RESEARCH QUESTION 1:\n### How much of a role does education play into someone's yearly income?\nI will conduct this analysis through a count plot of each education category to see which of them has the highest count of >50k/year earners and which have the lowest and the same with <=50k/year earners.\n#### TL;DR Bachelor is all you need for a good paying job\n**Start with >50K wages**\n\nThis data shows that most of the people in the Above50k dataset only have their\nBachelors degree with HS-grad and some college education trailing behind. Of course the data becomes skewed\nas we can't directly compare against other educational paths since they are not\nin equal numbers.",
"_____no_output_____"
]
],
[
[
"eduWageAbove50k = df.loc[lambda x: x['Yearly Income'] == '>50K']\n#Let's make a countplot for that.\neduWageGraph = sns.countplot(x = 'Education', data = eduWageAbove50k,\n palette = 'Spectral', order = eduWageAbove50k['Education'].value_counts().index)\neduWageGraph.set(title = 'Education VS Salary (Over 50K) Count', ylabel = 'Count')",
"_____no_output_____"
]
],
[
[
"**Now with Below50k dataset**\n#### TL;DR HS grads who don't go to post secondary and finish a degree have lower paying jobs\nThis data shows that most of the people with jobs paying below 50k/year are the ones\nwith only a HS-grad education with people that have only done some college courses\nas second place. Unless you complete a program at post-secondary or go into trades\nafter finishing school, you may make less than 50k/year ",
"_____no_output_____"
]
],
[
[
"eduWageBelow50k = df.loc[lambda x: x['Yearly Income'] == '<=50K']\n#Let's make a countplot for that.\nsns.countplot(x = 'Education', data = eduWageBelow50k, order = eduWageBelow50k['Education'].value_counts().index, palette = 'Spectral')",
"_____no_output_____"
]
],
[
[
"**Since my data is all categorical and a violin, distplot, plot doesn't count occurences of categorical data I am limited to a certain amount of graphs.**\n## RESEARCH QUESTION 2:\n### Which industries of work pay the most amount of money on average?\nTo analyze this I will create a count plot of every job category to observe the amount of people earning above or below 50k/year\n#### TL;DR Own a suit, managerial and executive have most top earners while trades/clerical industries have most low earners\nWe can see from this data that no one in armed forces makes above 50K/year\nwith the Exec/Managerial and Prof-specialty occupations making the majority of\nthe people with wages above 50K/year",
"_____no_output_____"
]
],
[
[
"#change row values to fit graph\ndf.replace({'Adm-clerical':'Adm-\\nclerical','Exec-managerial':'Exec-\\nmanagerial',\n 'Handlers-cleaners':'Handlers\\n-cleaners','Tech-support':'Tech-\\nsupport',\n 'Craft-repair':'Craft-\\nrepair','Other-service':'Other-\\nservice',\n 'Prof-specialty':'Prof-\\nspecialty','Machine-op-inspct':'Machine\\n-op-\\ninspct','Farming-fishing':'Farming\\n-fishing'}, inplace = True)\nwageOc = df.loc[:,['Occupation', 'Yearly Income']]\nwageOcAbove50k = wageOc.loc[lambda x:x['Yearly Income'] == '>50K']\nwageOcGraph = sns.countplot(data = wageOcAbove50k, x = 'Occupation', palette = 'Spectral', order = wageOcAbove50k['Occupation'].value_counts().index)\nwageOcGraph.set(title = 'Occupation VS Yearly Income', ylabel = 'Count of People with >50K\\nEarnings per Occupation')",
"_____no_output_____"
]
],
[
[
"**Check jobs with below 50k/year earnings**\n\nNow seeing the second half of the data we can observe that no one surveyed worked\nin the armed forces. It also shows that the majority of people making below 50K a year\nstrike a 3 way tie between Adm-clerical, Other-services, and Craft-repair jobs.\nAlthough Exec/managerial jobs make up most of the people who make >50K/year,\nthey also make up a decent chunk of the people who make less than 50K/year.",
"_____no_output_____"
]
],
[
[
"wageOcBelow50k = wageOc.loc[lambda x:x['Yearly Income'] == '<=50K']\nwageOcGraph = sns.countplot(data = wageOcBelow50k, x = 'Occupation',palette = 'Spectral', order = wageOcBelow50k['Occupation'].value_counts().index)\nwageOcGraph.set(title = 'Occupation VS Yearly Income', ylabel = 'Count of People with <=50K\\nEarnings per Occupation')",
"_____no_output_____"
]
],
[
[
"## RESEARCH QUESTION 3:\n### What is the most common occupation surveyed in this dataset?\nI will conduct this analysis through a count plot of each occupation.\n### Results:\nIn an interesting 3 way tie, we have prof-specialty, craft-repair, and exec-managerial occupations with the highest counts although not far behind are adm-clerical, sales, and other-services. It is super interesting to see that execute/managerial roles are so prevelant in this dataset as it can be thought by some as a difficult role to obtain. The occupations in this category are also the first place holder for most number of wages above 50k/year.",
"_____no_output_____"
]
],
[
[
"occ = df.loc[:,['Occupation']]\nsns.countplot(x='Occupation', data = occ, order = occ['Occupation'].value_counts().index)",
"_____no_output_____"
]
],
[
[
"## RESEARCH QUESTION 4:\n### What is the ratio of people earning >50k/year and <=50k/year by sex?\nI will conduct this in two seperate graphs by first focusing on people who manke above 50k/year and in the second graph I will focus on those earning <=50k/year.\n### Results:\nThe graphs show that this dataset shows a majority of men that were surveyed. In the first half of the data, men just about sextuple the women in earning above 50k/year. The ratio of high earners/low earners of each sex is about\n6100/14000 = 44% of men are high earners where 1000/8000 = 12.5% of women are high earners.",
"_____no_output_____"
]
],
[
[
"earnSex = df.loc[:,['Sex', 'Yearly Income']]\nearnSexAbove50k = earnSex.loc[lambda x: x['Yearly Income'] == '>50K']\nplt.figure(figsize=(5,5))\ngraph = sns.countplot(data = earnSexAbove50k, x = 'Sex')\ngraph.set(ylabel = 'Number of People who Make\\n >50K/year')",
"_____no_output_____"
],
[
"earnSexBelow50k = earnSex.loc[lambda x: x['Yearly Income'] == '<=50K']\nplt.figure(figsize=(5,5))\ngraph = sns.countplot(data = earnSexBelow50k, x = 'Sex')\ngraph.set(ylabel = 'Number of People who Make\\n <=50K/year')",
"_____no_output_____"
],
[
"#replace some values so they fit on graph\ndf.replace({'Married-civ-spouse':'Married\\n-civ-\\nspouse', 'Never-married':'Never-\\nMarried',\n 'Married-spouse-absent':'Married\\n-spouse\\n-absent','Married-AF-spouse':'Married\\n-AF-\\nspouse'}, inplace = True)\ndf",
"_____no_output_____"
]
],
[
[
"## RESEARCH QUESTION 5:\n### What is the relationship of yearly earnings and marital status?\nI will conduct this through splitting the data into the top earners and low earners (>50K/year,<=50K/year) and comparing them to their marital status.\n### Results\nPeople who are married are most likely to make over 50k/year while people who have never married top the charts for below 50k/year.",
"_____no_output_____"
]
],
[
[
"earnMar = df.loc[:,['Yearly Income', 'Marital Status']]\nearnMarAbove50k = earnMar.loc[lambda x: x['Yearly Income'] == '>50K']\nplt.figure(figsize= (10,5))\ngraph = sns.countplot(data = earnMarAbove50k, x = 'Marital Status')\ngraph.set_ylabel('Number of Top Earners\\nby Marital Status')",
"_____no_output_____"
],
[
"earnMarBelow50k = earnMar.loc[lambda x: x['Yearly Income'] == '<=50K']\nplt.figure(figsize= (10,5))\ngraph = sns.countplot(data = earnMarBelow50k, x = 'Marital Status')\ngraph.set_ylabel('Number of Low Earners\\nby Marital Status')",
"_____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"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb46ec45091c003465319b38bfc67f7eddbaee08 | 293,221 | ipynb | Jupyter Notebook | .ipynb_checkpoints/probabilistic_robotics_task-checkpoint.ipynb | Ikeda-Togo/probabilistic_robotics_task | 428c11d0b989c59a9c8d950a79d27f3268a800e3 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/probabilistic_robotics_task-checkpoint.ipynb | Ikeda-Togo/probabilistic_robotics_task | 428c11d0b989c59a9c8d950a79d27f3268a800e3 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/probabilistic_robotics_task-checkpoint.ipynb | Ikeda-Togo/probabilistic_robotics_task | 428c11d0b989c59a9c8d950a79d27f3268a800e3 | [
"MIT"
] | null | null | null | 75.339414 | 43,365 | 0.681885 | [
[
[
"# 確率ロボティクス課題\n\n## 参考\n+ [詳解 確率ロボティクス](https://www.amazon.co.jp/%E8%A9%B3%E8%A7%A3-%E7%A2%BA%E7%8E%87%E3%83%AD%E3%83%9C%E3%83%86%E3%82%A3%E3%82%AF%E3%82%B9-Python%E3%81%AB%E3%82%88%E3%82%8B%E5%9F%BA%E7%A4%8E%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0%E3%81%AE%E5%AE%9F%E8%A3%85-KS%E7%90%86%E5%B7%A5%E5%AD%A6%E5%B0%82%E9%96%80%E6%9B%B8-%E4%B8%8A%E7%94%B0/dp/4065170060/ref=sr_1_1?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=%E8%A9%B3%E8%A7%A3+%E7%A2%BA%E7%8E%87%E3%83%AD%E3%83%9C%E3%83%86%E3%82%A3%E3%82%AF%E3%82%B9&qid=1610537879&sr=8-1)\n+ [確率ロボティクス](https://www.amazon.co.jp/%E7%A2%BA%E7%8E%87%E3%83%AD%E3%83%9C%E3%83%86%E3%82%A3%E3%82%AF%E3%82%B9-%E3%83%97%E3%83%AC%E3%83%9F%E3%82%A2%E3%83%A0%E3%83%96%E3%83%83%E3%82%AF%E3%82%B9%E7%89%88-Sebastian-Thrun/dp/4839952981/ref=sr_1_2?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=%E8%A9%B3%E8%A7%A3+%E7%A2%BA%E7%8E%87%E3%83%AD%E3%83%9C%E3%83%86%E3%82%A3%E3%82%AF%E3%82%B9&qid=1610537879&sr=8-2)\n+ [詳解 確率ロボティクスのサンプルコード](https://github.com/ryuichiueda/LNPR_BOOK_CODES)\n+ [自己位置推定](https://github.com/KobayashiRui/ProbabilisticRobotics_Task)\n\n## 問題設定\n+ 授業で扱ったマルコフ決定過程の全方向移動バージョンを実装\n+ ロボットはx,y方向に移動可能\n+ 回転はしない\n+ 自己位置推定は去年の先輩のコードを引用しています\n\nコードの変数名やクラス名は基本的に参考の「詳解 確率ロボティクス」に準拠しています",
"_____no_output_____"
]
],
[
[
"%matplotlib nbagg\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.animation as anm\n\nimport math\nimport numpy as np\nfrom scipy.stats import expon, norm, multivariate_normal\nfrom matplotlib.patches import Ellipse\n\nimport itertools \nimport collections \nfrom copy import copy",
"_____no_output_____"
]
],
[
[
"## Worldの作成\ngoal puddle Landmark",
"_____no_output_____"
]
],
[
[
"class Goal:\n def __init__(self, x, y, radius=0.3, value=0.0):\n self.pos = np.array([x, y]).T\n self.radius = radius\n self.value = value \n \n def inside(self, pose): #ゴールの範囲設定\n return self.radius > math.sqrt( (self.pos[0]-pose[0])**2 + (self.pos[1]-pose[1])**2 )\n \n def draw(self, ax, elems):\n x, y = self.pos\n c = ax.scatter(x + 0.16, y + 0.5, s=50, marker=\">\", label=\"landmarks\", color=\"red\")\n elems.append(c)\n elems += ax.plot([x, x], [y, y + 0.6], color=\"black\")",
"_____no_output_____"
],
[
"class Puddle: #水たまり\n def __init__(self, lowerleft, upperright, depth):\n self.lowerleft = lowerleft\n self.upperright = upperright\n self.depth = depth\n \n def draw(self, ax, elems):\n w = self.upperright[0] - self.lowerleft[0]\n h = self.upperright[1] - self.lowerleft[1]\n r = patches.Rectangle(self.lowerleft, w, h, color=\"blue\", alpha=self.depth)\n elems.append(ax.add_patch(r))\n \n def inside(self, pose): \n return all([ self.lowerleft[i] < pose[i] < self.upperright[i] for i in [0, 1] ])",
"_____no_output_____"
],
[
"class PuddleWorld():\n def __init__(self, time_span, time_interval, debug=False):\n self.objects = []\n self.debug = debug\n self.time_span = time_span\n self.time_interval = time_interval\n \n self.puddles = []\n self.robots = []\n self.goals = []\n \n def draw(self): \n fig = plt.figure(figsize=(4,4))\n ax = fig.add_subplot(111)\n ax.set_aspect('equal') \n ax.set_xlim(-5,5) \n ax.set_ylim(-5,5) \n ax.set_xlabel(\"X\",fontsize=10) \n ax.set_ylabel(\"Y\",fontsize=10) \n \n elems = []\n \n if self.debug: \n for i in range(int(self.time_span/self.time_interval)): self.one_step(i, elems, ax)\n else:\n self.ani = anm.FuncAnimation(fig, self.one_step, fargs=(elems, ax),\n frames=int(self.time_span/self.time_interval)+1, interval=int(self.time_interval*1000), repeat=False)\n plt.show()\n \n def append(self,obj):\n self.objects.append(obj)\n if isinstance(obj, Puddle): self.puddles.append(obj)\n if isinstance(obj, Robot): self.robots.append(obj)\n if isinstance(obj, Goal): self.goals.append(obj)\n \n def puddle_depth(self, pose):\n return sum([p.depth * p.inside(pose) for p in self.puddles])\n \n def one_step(self, i, elems, ax):\n while elems:\n elems.pop().remove()\n time_str = \"t=%.2f[s]\" % (self.time_interval*i)\n elems.append(ax.text(-4.4, 4.5, time_str, fontsize=10))\n for obj in self.objects:\n obj.draw(ax, elems)\n if hasattr(obj, \"one_step\"):\n obj.one_step(self.time_interval)\n for r in self.robots:\n r.agent.puddle_depth = self.puddle_depth(r.pose)\n for g in self.goals: ##goal判定\n if g.inside(r.pose):\n r.agent.in_goal = True\n r.agent.final_value = g.value",
"_____no_output_____"
],
[
"class Landmark:\n def __init__(self, x, y):\n self.pos = np.array([x, y]).T\n self.id = None\n \n def draw(self, ax, elems):\n c = ax.scatter(self.pos[0], self.pos[1], s=100, marker=\"*\", label=\"landmarks\", color=\"orange\")\n elems.append(c)\n elems.append(ax.text(self.pos[0], self.pos[1], \"id:\" + str(self.id), fontsize=10))\n\nclass Map:\n def __init__(self): # 空のランドマークのリストを準備\n self.landmarks = []\n \n def append_landmark(self, landmark): # ランドマークを追加\n landmark.id = len(self.landmarks) # 追加するランドマークにIDを与える\n self.landmarks.append(landmark)\n\n def draw(self, ax, elems): # 描画(Landmarkのdrawを順に呼び出し)\n for lm in self.landmarks: lm.draw(ax, elems)",
"_____no_output_____"
]
],
[
[
"## Robotの作成\nノイズのみ(スタック、誘拐は考えない)",
"_____no_output_____"
]
],
[
[
"class Robot:\n '''\n ロボット1台の処理関係\n agentとsensorを含む\n '''\n def __init__(self, pose, agent=None, sensor=None, color=\"blue\", noise_per_meter=5, noise_std=0.05):\n self.pose = pose\n self.r = 0.2\n self.color = color\n self.agent = agent\n self.poses = [pose] #移動の軌跡を保存\n self.sensor = sensor\n \n self.noise_pdf = expon(scale=1.0/(1e-100 + noise_per_meter))\n self.distance_until_noise = self.noise_pdf.rvs()\n self.pose_noise = norm(scale=noise_std)\n \n def noise(self, pose, v_x, v_y, time_interval):\n distance = np.hypot(v_x*time_interval, v_y*time_interval)\n self.distance_until_noise -= distance\n if self.distance_until_noise <= 0.0:\n self.distance_until_noise += self.noise_pdf.rvs()\n noise_value = self.pose_noise.rvs()\n pose[0] += self.pose_noise.rvs() #noise_value\n pose[1] += self.pose_noise.rvs() #noise_value\n \n return pose\n \n def draw(self, ax, elems):\n \n #初期値or状態遷移後のposeを取得\n x,y = self.pose\n robot = patches.Circle(xy=(x,y), radius=self.r, color=self.color)\n elems.append(ax.add_patch(robot))\n \n self.poses.append(np.array([x,y]).T)\n poses_x = [e[0] for e in self.poses]\n poses_y = [e[1] for e in self.poses]\n elems += ax.plot(poses_x, poses_y, linewidth=0.5, color=\"black\")\n \n if self.sensor and len(self.poses) > 1:\n #状態遷移前の姿勢で観測しているのでposes[-2] (一つ前の姿勢値から線分の計算)\n self.sensor.draw(ax, elems, self.poses[-2])\n \n if self.agent and hasattr(self.agent, \"draw\"):\n self.agent.draw(ax, elems)\n \n @classmethod\n def state_transition(cls, v_x, v_y, time, pose): #x軸の速度, y軸の速度, 移動時間\n return pose + np.array([v_x*time, v_y*time])\n \n \n def one_step(self, time_interval):\n if self.agent:\n obs = self.sensor.data(self.pose) if self.sensor else None\n v_x, v_y = self.agent.decision(obs)\n self.pose = self.state_transition(v_x, v_y, time_interval, self.pose)\n self.pose = self.noise(self.pose, v_x, v_y, time_interval)\n\n ",
"_____no_output_____"
]
],
[
[
"## カメラの作成\nセンサノイズのみ考慮(オクルージョン、ファントムなどは考えない)",
"_____no_output_____"
]
],
[
[
"class Camera:\n '''\n 観測を管理する, sensorとしてRobotに登録する\n '''\n def __init__(self, env_map, distance_range = (0.5, 4),pos_noise=0.1):\n self.map = env_map\n self.lastdata = []\n self.distance_range = distance_range\n self.pos_noise = pos_noise\n \n def noise(self, relpos):\n noise_x = norm.rvs(loc=relpos[0], scale=self.pos_noise)\n noise_y = norm.rvs(loc=relpos[1], scale=self.pos_noise)\n return np.array([noise_x, noise_y]).T\n \n def visible(self, pos):\n if pos is None:\n return False\n \n distance = np.hypot(*pos)\n return self.distance_range[0] <= distance <= self.distance_range[1]\n \n def data(self, cam_pose):\n observed = []\n for lm in self.map.landmarks:\n z = self.observation_function(cam_pose, lm.pos)\n if self.visible(z):\n z = self.noise(z)\n observed.append((z, lm.id))\n \n self.lastdata = observed\n return observed\n \n @classmethod\n def observation_function(cls, cam_pose, obj_pos):\n diff = obj_pos - cam_pose\n return np.array(diff).T\n \n def draw(self, ax, elems, cam_pose):\n for lm in self.lastdata:\n x, y = cam_pose\n lx = lm[0][0] + x\n ly = lm[0][1] + y\n elems += ax.plot([x,lx],[y,ly], color=\"pink\")\n \n \n",
"_____no_output_____"
]
],
[
[
"## エージェント\n+ 授業でのPuddleIgnorePolicyではゴールの方向に向きを合わせて進行\n+ 全方向移動ではゴールと現在位置との距離をx軸y軸方向の比で行動を決定する\n+ 行動選択が増えすぎないように近似",
"_____no_output_____"
]
],
[
[
"class Agent:\n '''\n ロボットの動作を決定する, agent(操縦者)としてRobotに登録する\n '''\n def __init__(self, v_x, v_y):\n self.v_x = v_x\n self.v_y = v_y\n self.counter =0\n \n def decision(self, observation=None):\n self.counter += 1\n return self.v_x, self.v_y\n ",
"_____no_output_____"
],
[
"class EstimationAgent(Agent):\n def __init__(self, time_interval, v_x, v_y, estimator):\n super().__init__(v_x, v_y)\n self.estimator = estimator\n self.time_interval = time_interval\n self.prev_v_x = 0.0\n self.prev_v_y = 0.0\n \n def draw(self, ax, elems):\n self.estimator.draw(ax, elems)",
"_____no_output_____"
],
[
"class PuddleIgnoreAgent(EstimationAgent):\n def __init__(self, time_interval, estimator, goal, puddle_coef=100): \n super().__init__(time_interval, 0.0, 0.0, estimator)\n \n self.puddle_coef = puddle_coef\n self.puddle_depth = 0.0\n self.total_reward = 0.0\n self.in_goal = False \n self.final_value = 0.0\n self.goal = goal\n \n def reward_per_sec(self):\n return -1.0 - self.puddle_depth*self.puddle_coef\n \n @classmethod ###puddleignoreagent(以下全部)\n def policy(cls, pose, goal):\n x, y = pose\n dx, dy = goal.pos[0] - x, goal.pos[1] - y\n if dx==0: ##エラー回避\n dx=0.01\n if dy==0:\n dy=0.01\n \n v_x, v_y = dx/(abs(dx)+abs(dy)), dy/(abs(dx)+abs(dy)) ##xとyのゴールの距離の比で制御値を決定\n v_x, v_y = round(v_x,1), round(v_y,1) \n return v_x, v_y\n\n def decision(self, observation=None): #行動決定\n if self.in_goal:\n return 0.0, 0.0\n \n self.estimator.motion_update(self.prev_v_x, self.prev_v_y, self.time_interval)##推定更新\n v_x, v_y= self.policy(self.estimator.pose, self.goal)##推定値から行動決定\n self.prev_v_x, self.prev_v_y = v_x, v_y\n self.estimator.observation_update(observation)##観測更新\n self.total_reward += self.time_interval*self.reward_per_sec()##報酬の計算\n return v_x, v_y\n \n def draw(self, ax, elems): \n super().draw(ax, elems)\n x, y= self.estimator.pose\n elems.append(ax.text(x+1.0, y-0.5, \"reward/sec:\" + str(self.reward_per_sec()), fontsize=8))\n elems.append(ax.text(x+1.0, y-1.0, \"eval: {:.1f}\".format(self.total_reward+self.final_value), fontsize=8))",
"_____no_output_____"
]
],
[
[
"## 価値反復後の方策用エージェント",
"_____no_output_____"
]
],
[
[
"class DpPolicyAgent(PuddleIgnoreAgent): ###dppolicyagent\n def __init__(self, time_interval, estimator, goal, puddle_coef=100, widths=np.array([0.2, 0.2]).T, \\\n lowerleft=np.array([-4, -4]).T, upperright=np.array([4, 4]).T): #widths以降はDynamicProgrammingから持ってくる\n super().__init__(time_interval, estimator, goal, puddle_coef) \n \n ###座標関連の変数をDynamicProgrammingから持ってくる###\n self.pose_min = np.r_[lowerleft] \n self.pose_max = np.r_[upperright]\n self.widths = widths\n self.index_nums = ((self.pose_max - self.pose_min)/self.widths).astype(int)\n \n self.policy_data = self.init_policy(self.index_nums)\n \n def init_policy(self, index_nums):\n tmp = np.zeros(np.r_[index_nums,2])\n for line in open(\"policy.txt\", \"r\"):\n d = line.split()\n tmp[int(d[0]), int(d[1])] = [float(d[2]), float(d[3])]\n \n return tmp\n \n def to_index(self, pose, pose_min, index_nums , widths): #姿勢をインデックスに変えて正規化\n index = np.floor((pose - pose_min)/widths).astype(int) #姿勢からインデックスに\n \n for i in [0,1]: #端の処理(内側の座標の方策を使う)\n if index[i] < 0: index[i] = 0\n elif index[i] >= index_nums[i]: index[i] = index_nums[i] - 1\n \n return tuple(index) #ベクトルのままだとインデックスに使えないのでタプルに\n \n def policy(self, pose, goal=None): #姿勢から離散状態のインデックスを作って方策を参照して返すだけ \n return self.policy_data[self.to_index(pose, self.pose_min, self.index_nums, self.widths)]",
"_____no_output_____"
]
],
[
[
"## カルマンフィルタ",
"_____no_output_____"
]
],
[
[
"def sigma_ellipse(p, cov, n):\n eig_vals, eig_vec = np.linalg.eig(cov)\n ang = math.atan2(eig_vec[:,0][1], eig_vec[:,0][0])/math.pi*180\n return Ellipse(p, width=2*n*math.sqrt(eig_vals[0]), height=2*n*math.sqrt(eig_vals[1]), angle=ang, fill=False, color=\"blue\", alpha=0.5)",
"_____no_output_____"
],
[
"class KalmanFilter:\n def __init__(self, envmap, init_pose, motion_noise_stds= {\"nn\":0.05, \"oo\":0.05}, pos_noise=0.1):\n self.belief = multivariate_normal(mean=np.array([0.0, 0.0]), cov=np.diag([1e-10, 1e-10]))\n self.pose = self.belief.mean\n self.motion_noise_stds = motion_noise_stds\n self.pose = self.belief.mean\n self.map = envmap\n self.pos_noise = pos_noise\n \n def matR(self, v_x, v_y,time):\n return np.diag([self.motion_noise_stds[\"nn\"]**2*abs(v_x)/time, self.motion_noise_stds[\"oo\"]**2*abs(v_y)/time])\n \n def observation_update(self, observation):\n for d in observation:\n z = d[0]\n obs_id = d[1]\n estimated_z = Camera.observation_function(self.belief.mean, self.map.landmarks[obs_id].pos)\n H = np.array([[-1,0],[0,-1]])\n K = self.belief.cov.dot(H.T).dot(np.linalg.inv(H.dot(self.belief.cov).dot(H.T) + np.diag([self.pos_noise, self.pos_noise]))) \n self.belief.mean += K.dot(z - estimated_z)\n self.belief.cov = (np.eye(2) - K.dot(H)).dot(self.belief.cov)\n self.pose = self.belief.mean\n \n def motion_update(self, v_x, v_y, time):\n self.belief.cov = self.belief.cov + self.matR(v_x,v_y,time)\n self.belief.mean = Robot.state_transition(v_x, v_y, time, self.belief.mean)\n self.pose = self.belief.mean\n \n def draw(self, ax, elems):\n e = sigma_ellipse(self.belief.mean[0:2], self.belief.cov[0:2, 0:2], 3)\n elems.append(ax.add_patch(e))",
"_____no_output_____"
]
],
[
[
"## dynamic_programming",
"_____no_output_____"
]
],
[
[
"class DynamicProgramming: \n def __init__(self, widths, goal, puddles, time_interval, sampling_num, \\\n puddle_coef=100.0, lowerleft=np.array([-4, -4]).T, upperright=np.array([4, 4]).T): \n self.pose_min = np.r_[lowerleft]\n self.pose_max = np.r_[upperright]\n self.widths = widths\n self.goal = goal\n \n self.index_nums = ((self.pose_max - self.pose_min)/self.widths).astype(int)\n nx, ny = self.index_nums\n self.indexes = list(itertools.product(range(nx), range(ny)))\n \n self.value_function, self.final_state_flags = self.init_value_function() \n self.policy = self.init_policy()\n self.actions = list(set([tuple(self.policy[i]) for i in self.indexes]))\n \n self.state_transition_probs = self.init_state_transition_probs(time_interval, sampling_num)\n self.depths = self.depth_means(puddles, sampling_num)\n \n self.time_interval = time_interval\n self.puddle_coef = puddle_coef\n \n def value_iteration_sweep(self):\n max_delta = 0.0\n for index in self.indexes:\n if not self.final_state_flags[index]:\n max_q = -1e100\n max_a = None\n qs = [self.action_value(a, index) for a in self.actions] #全行動の行動価値を計算\n max_q = max(qs) #最大の行動価値\n max_a = self.actions[np.argmax(qs)] #最大の行動価値を与える行動\n \n delta = abs(self.value_function[index] - max_q) #変化量\n max_delta = delta if delta > max_delta else max_delta #スイープ中で最大の変化量の更新\n \n self.value_function[index] = max_q #価値の更新\n self.policy[index] = np.array(max_a).T #方策の更新\n \n return max_delta \n \n def policy_evaluation_sweep(self): \n max_delta = 0.0\n for index in self.indexes:\n if not self.final_state_flags[index]:\n q = self.action_value(tuple(self.policy[index]), index)\n \n delta = abs(self.value_function[index] - q)\n max_delta = delta if delta > max_delta else max_delta\n \n self.value_function[index] = q\n \n return max_delta\n \n def action_value(self, action, index, out_penalty=True): \n value = 0.0\n for delta, prob in self.state_transition_probs[(action)]: \n after, out_reward = self.out_correction(np.array(index).T + delta)\n after = tuple(after)\n reward = - self.time_interval * self.depths[(after[0], after[1])] * self.puddle_coef - self.time_interval + out_reward*out_penalty\n value += (self.value_function[after] + reward) * prob\n\n return value\n \n def out_correction(self, index): \n out_reward = 0.0\n \n for i in range(2):\n if index[i] < 0:\n index[i] = 0\n out_reward = -1e100\n elif index[i] >= self.index_nums[i]:\n index[i] = self.index_nums[i]-1\n out_reward = -1e100\n \n return index, out_reward\n \n def depth_means(self, puddles, sampling_num):\n ###セルの中の座標を均等にsampling_num**2点サンプリング###\n dx = np.linspace(0, self.widths[0], sampling_num) \n dy = np.linspace(0, self.widths[1], sampling_num)\n samples = list(itertools.product(dx, dy))\n \n tmp = np.zeros(self.index_nums[0:2]) #深さの合計が計算されて入る\n for xy in itertools.product(range(self.index_nums[0]), range(self.index_nums[1])):\n for s in samples:\n pose = self.pose_min + self.widths*np.array([xy[0], xy[1]]).T + np.array([s[0], s[1]]).T #セルの中心の座標\n for p in puddles:\n tmp[xy] += p.depth*p.inside(pose) #深さに水たまりの中か否か(1 or 0)をかけて足す\n \n tmp[xy] /= sampling_num**2 #深さの合計から平均値に変換\n \n return tmp\n \n def init_state_transition_probs(self, time_interval, sampling_num):\n ###セルの中の座標を均等にsampling_num**2点サンプリング###\n dx = np.linspace(0.001, self.widths[0]*0.999, sampling_num) #隣のセルにはみ出さないように端を避ける\n dy = np.linspace(0.001, self.widths[1]*0.999, sampling_num)\n samples = list(itertools.product(dx, dy))\n \n ###各行動、各方角でサンプリングした点を移動してインデックスの増分を記録###\n tmp = {}\n for a in self.actions:\n transitions = []\n for s in samples:\n before = np.array([s[0], s[1]]).T + self.pose_min #遷移前の姿勢\n before_index = np.array([0, 0]).T #遷移前のインデックス\n \n after =Robot.state_transition(a[0], a[1], time_interval, before) #遷移後の姿勢\n after_index = np.floor((after - self.pose_min)/self.widths).astype(int) #遷移後のインデックス\n \n transitions.append(after_index - before_index) #インデックスの差分を追加\n \n unique, count = np.unique(transitions, axis=0, return_counts=True) #集計(どのセルへの遷移が何回か)\n probs = [c/sampling_num**2 for c in count] #サンプル数で割って確率にする\n tmp[a] = list(zip(unique, probs))\n \n return tmp\n \n def init_policy(self):\n tmp = np.zeros(np.r_[self.index_nums,2]) #制御出力が2次元なので、配列の次元を4次元に\n for index in self.indexes:\n center = self.pose_min + self.widths*(np.array(index).T + 0.5) #セルの中心の座標\n tmp[index] = PuddleIgnoreAgent.policy(center, self.goal)\n \n return tmp\n \n def init_value_function(self): \n v = np.empty(self.index_nums) #全離散状態を要素に持つ配列を作成\n f = np.zeros(self.index_nums) \n \n for index in self.indexes:\n f[index] = self.final_state(np.array(index).T)\n v[index] = self.goal.value if f[index] else -100.0\n \n return v, f\n \n def final_state(self, index):\n x_min, y_min= self.pose_min + self.widths*index #xy平面で左下の座標\n x_max, y_max= self.pose_min + self.widths*(index + 1) #右上の座標(斜め上の離散状態の左下の座標)\n \n corners = [[x_min, y_min], [x_min, y_max], [x_max, y_min], [x_max, y_max] ] #4隅の座標\n return all([self.goal.inside(np.array(c).T) for c in corners ])",
"_____no_output_____"
],
[
"import seaborn as sns ###dp2exec\n\npuddles = [Puddle((-2, 0), (0, 2), 0.1), Puddle((-0.5, -2), (2.5, 1), 0.1)] \ndp = DynamicProgramming(np.array([0.2, 0.2]).T, Goal(-3,-3), puddles, 0.1, 10) \ncounter = 0 #スイープの回数",
"_____no_output_____"
]
],
[
[
"## 価値反復の実行",
"_____no_output_____"
]
],
[
[
"delta = 1e100\n\nwhile delta > 0.01: \n delta = dp.value_iteration_sweep()\n counter += 1\n print(counter, delta)",
"1 52.394999999999996\n2 27.27398749999999\n3 25.95870368749999\n4 20.234357140390628\n5 19.347495811569132\n6 16.77398063773242\n7 16.05140830506072\n8 14.621568246271416\n9 13.28684710132584\n10 12.64374301593653\n11 11.99667628797323\n12 11.209581445485462\n13 10.980780376667937\n14 10.133387522676422\n15 8.763358695684413\n16 8.286981416616577\n17 7.965068703037375\n18 7.66848729596358\n19 7.395374831491814\n20 7.143867087779036\n21 6.919403615750184\n22 6.72226811738917\n23 6.5377567223970985\n24 6.365118782847887\n25 6.203572063323541\n26 6.052332063158389\n27 5.91063214804668\n28 5.7777366624775155\n29 5.652949186106071\n30 5.535617249165291\n31 5.425134412893371\n32 5.320940543523932\n33 5.22252085647407\n34 5.129404116010839\n35 5.041160292540994\n36 4.957397920765942\n37 4.877761312480608\n38 4.744934035153555\n39 4.565840593258535\n40 4.508787116473954\n41 4.450113300643281\n42 4.391548115927094\n43 4.339983706464622\n44 4.287453804914968\n45 4.235331342980032\n46 4.186340146810856\n47 4.13894788907767\n48 4.093773239194064\n49 4.049640784753677\n50 4.004287387283007\n51 3.9643228721222172\n52 3.92439747049324\n53 3.883341207288936\n54 3.841341270850151\n55 3.765549769420403\n56 3.6555277075376864\n57 3.515493945128995\n58 3.3501631047745377\n59 3.1645305453772252\n60 2.9636681058122107\n61 2.7525398434751907\n62 2.53584459350828\n63 2.317889672322515\n64 2.1024976364199155\n65 1.8929458414456555\n66 1.6919367412641506\n67 1.5015954912264036\n68 1.3234904974353157\n69 1.158672068700529\n70 1.0077242324136044\n71 0.8708250006507363\n72 0.7478108381678901\n73 0.6382417075727993\n74 0.541463772728406\n75 0.45666756433475086\n76 0.3829401005576898\n77 0.3209156185143449\n78 0.28690442917391223\n79 0.24719552191033856\n80 0.20844167577375217\n81 0.1733082361466849\n82 0.14263932945255675\n83 0.11852350913802212\n84 0.10065111495639556\n85 0.08339481018130712\n86 0.06803619206138123\n87 0.05491301747449029\n88 0.043960022603798166\n89 0.034955222668710206\n90 0.027631115362318326\n91 0.021723585059490347\n92 0.016991961711180892\n93 0.013225732993241479\n94 0.01024515866609832\n95 0.007899211764183178\n"
],
[
"with open(\"policy.txt\", \"w\") as f: \n for index in dp.indexes:\n p = dp.policy[index]\n f.write(\"{} {} {} {}\\n\".format(index[0], index[1], p[0], p[1]))\n \nwith open(\"value.txt\", \"w\") as f:\n for index in dp.indexes:\n p = dp.value_function[index]\n f.write(\"{} {} {} {}\\n\".format(index[0], index[1], 0, p))",
"_____no_output_____"
]
],
[
[
"## 状態価値と方策のグラフ化",
"_____no_output_____"
]
],
[
[
"v = dp.value_function[:, :]\nfig = plt.figure(figsize=(4,4))\nax = fig.add_subplot(111)\nax.set_aspect('equal')\nsns.heatmap(np.rot90(v), square=False)\nplt.show()",
"_____no_output_____"
],
[
"p = np.zeros(dp.index_nums) \nfor i in dp.indexes:\n p[i] = sum(dp.policy[i]) \nfig = plt.figure(figsize=(4,4))\nax = fig.add_subplot(111)\nax.set_aspect('equal')\nsns.heatmap(np.rot90(p[:, :]), square=False)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Demo",
"_____no_output_____"
]
],
[
[
"def trial(): ###puddle_world4_trial\n time_interval = 0.1\n world = PuddleWorld(30, time_interval, debug=False) \n\n ## 地図を生成して3つランドマークを追加 ##\n m = Map()\n for ln in [(-4,2), (2,-3), (4,4), (-4,-4)]: m.append_landmark(Landmark(*ln))\n world.append(m) \n\n ##ゴールの追加##\n goal = Goal(-3,-3) #goalを変数に\n world.append(goal)\n \n ##水たまりの追加##\n world.append(Puddle((-2, 0), (0, 2), 0.1)) \n world.append(Puddle((-0.5, -2), (2.5, 1), 0.1)) \n\n# ##ロボットを作る##\n\n init_poses = []\n for p in [[-3, 3], [0.5, 1.5], [3, 3], [2, -1]]:\n init_pose = np.array(p).T\n kf = KalmanFilter(m, init_pose)\n a = DpPolicyAgent(time_interval, kf, goal)\n r = Robot(init_pose, sensor=Camera(m), agent=a, color=\"red\")\n world.append(r)\n world.draw()\n \ntrial()",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb46ecb53963d0b6ac1c93ebcbac02aabeebec4d | 304,559 | ipynb | Jupyter Notebook | C4 Machine Learning II/SOLUTIONS/SOLUTION_Tech_Fun_C4_S2_Computer_Vision_Part_2_(Defect_Detection_Case_Study).ipynb | ronva-h/technology_fundamentals | 31432b512cfe9879a9ea97fca814d67142bd6057 | [
"MIT"
] | 5 | 2021-07-24T19:50:41.000Z | 2021-09-27T22:28:37.000Z | C4 Machine Learning II/SOLUTIONS/SOLUTION_Tech_Fun_C4_S2_Computer_Vision_Part_2_(Defect_Detection_Case_Study).ipynb | ronva-h/technology_fundamentals | 31432b512cfe9879a9ea97fca814d67142bd6057 | [
"MIT"
] | 2 | 2021-07-23T00:53:50.000Z | 2021-08-04T14:52:22.000Z | C4 Machine Learning II/SOLUTIONS/SOLUTION_Tech_Fun_C4_S2_Computer_Vision_Part_2_(Defect_Detection_Case_Study).ipynb | ronva-h/technology_fundamentals | 31432b512cfe9879a9ea97fca814d67142bd6057 | [
"MIT"
] | 4 | 2021-07-22T22:37:27.000Z | 2021-08-05T00:18:51.000Z | 159.957458 | 100,954 | 0.847475 | [
[
[
"<a href=\"https://colab.research.google.com/github/wesleybeckner/technology_fundamentals/blob/main/C4%20Machine%20Learning%20II/SOLUTIONS/SOLUTION_Tech_Fun_C4_S2_Computer_Vision_Part_2_(Defect_Detection_Case_Study).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Technology Fundamentals Course 4, Session 2: Computer Vision Part 2 (Defect Detection Case Study)\n\n**Instructor**: Wesley Beckner\n\n**Contact**: [email protected]\n\n**Teaching Assitants**: Varsha Bang, Harsha Vardhan\n\n**Contact**: [email protected], [email protected]\n<br>\n\n---\n\n<br>\n\nIn this session we will continue with our exploration of CNNs. In the previous session we discussed three flagship layers for the CNN: convolution ReLU and maximum pooling. Here we'll discuss the sliding window, how to build your custom CNN, and data augmentation for images.\n\n<br>\n\n_images in this notebook borrowed from [Ryan Holbrook](https://mathformachines.com/)_\n\n---\n\n<br>\n\n<a name='top'></a>\n\n# Contents\n\n* 4.0 [Preparing Environment and Importing Data](#x.0)\n * 4.0.1 [Enabling and Testing the GPU](#x.0.1)\n * 4.0.2 [Observe TensorFlow on GPU vs CPU](#x.0.2)\n * 4.0.3 [Import Packages](#x.0.3)\n * 4.0.4 [Load Dataset](#x.0.4)\n * 4.0.4.1 [Loading Data with ImageDataGenerator](#x.0.4.1)\n * 4.0.4.2 [Loading Data with image_dataset_from_directory](#x.0.4.2)\n* 4.1 [Sliding Window](#x.1)\n * 4.1.1 [Stride](#x.1.1)\n * 4.1.2 [Padding](#x.1.2)\n * 4.1.3 [Exercise: Exploring Sliding Windows](#x.1.3)\n* 4.2 [Custom CNN](#x.2)\n * 4.2.1 [Evaluate Model](#x.2.1)\n* 4.3 [Data Augmentation](#x.3)\n * 4.3.1 [Evaluate Model](#x.3.1)\n * 4.3.2 [Exercise: Image Preprocessing Layers](#x.3.2)\n* 4.4 [Transfer Learning](#x.4)\n \n\n<br>\n\n---",
"_____no_output_____"
],
[
"<a name='x.0'></a>\n\n## 4.0 Preparing Environment and Importing Data\n\n[back to top](#top)",
"_____no_output_____"
],
[
"<a name='x.0.1'></a>\n\n### 4.0.1 Enabling and testing the GPU\n\n[back to top](#top)\n\nFirst, you'll need to enable GPUs for the notebook:\n\n- Navigate to Edit→Notebook Settings\n- select GPU from the Hardware Accelerator drop-down\n\nNext, we'll confirm that we can connect to the GPU with tensorflow:",
"_____no_output_____"
]
],
[
[
"%tensorflow_version 2.x\nimport tensorflow as tf\ndevice_name = tf.test.gpu_device_name()\nif device_name != '/device:GPU:0':\n raise SystemError('GPU device not found')\nprint('Found GPU at: {}'.format(device_name))",
"Found GPU at: /device:GPU:0\n"
]
],
[
[
"<a name='x.0.2'></a>\n\n### 4.0.2 Observe TensorFlow speedup on GPU relative to CPU\n\n[back to top](#top)\n\nThis example constructs a typical convolutional neural network layer over a\nrandom image and manually places the resulting ops on either the CPU or the GPU\nto compare execution speed.",
"_____no_output_____"
]
],
[
[
"%tensorflow_version 2.x\nimport tensorflow as tf\nimport timeit\n\ndevice_name = tf.test.gpu_device_name()\nif device_name != '/device:GPU:0':\n print(\n '\\n\\nThis error most likely means that this notebook is not '\n 'configured to use a GPU. Change this in Notebook Settings via the '\n 'command palette (cmd/ctrl-shift-P) or the Edit menu.\\n\\n')\n raise SystemError('GPU device not found')\n\ndef cpu():\n with tf.device('/cpu:0'):\n random_image_cpu = tf.random.normal((100, 100, 100, 3))\n net_cpu = tf.keras.layers.Conv2D(32, 7)(random_image_cpu)\n return tf.math.reduce_sum(net_cpu)\n\ndef gpu():\n with tf.device('/device:GPU:0'):\n random_image_gpu = tf.random.normal((100, 100, 100, 3))\n net_gpu = tf.keras.layers.Conv2D(32, 7)(random_image_gpu)\n return tf.math.reduce_sum(net_gpu)\n \n# We run each op once to warm up; see: https://stackoverflow.com/a/45067900\ncpu()\ngpu()\n\n# Run the op several times.\nprint('Time (s) to convolve 32x7x7x3 filter over random 100x100x100x3 images '\n '(batch x height x width x channel). Sum of ten runs.')\nprint('CPU (s):')\ncpu_time = timeit.timeit('cpu()', number=10, setup=\"from __main__ import cpu\")\nprint(cpu_time)\nprint('GPU (s):')\ngpu_time = timeit.timeit('gpu()', number=10, setup=\"from __main__ import gpu\")\nprint(gpu_time)\nprint('GPU speedup over CPU: {}x'.format(int(cpu_time/gpu_time)))",
"Time (s) to convolve 32x7x7x3 filter over random 100x100x100x3 images (batch x height x width x channel). Sum of ten runs.\nCPU (s):\n2.6837491450000357\nGPU (s):\n0.036380309999969995\nGPU speedup over CPU: 73x\n"
]
],
[
[
"<a name='x.0.3'></a>\n\n### 4.0.3 Import Packages\n\n[back to top](#top)",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image_dataset_from_directory",
"_____no_output_____"
],
[
"#importing required libraries\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, MaxPooling2D, InputLayer\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.metrics import classification_report,confusion_matrix",
"_____no_output_____"
]
],
[
[
"<a name='x.0.4'></a>\n\n### 4.0.4 Load Dataset\n\n[back to top](#top)\n\nWe will actually take a beat here today. When we started building our ML frameworks, we simply wanted our data in a numpy array to feed it into our pipeline. At some point, especially when working with images, the data becomes too large to fit into memory. For this reason we need an alternative way to import our data. With the merger of keras/tf two popular frameworks became available, `ImageDataGenerator` and `image_dataset_from_directory` both under `tf.keras.preprocessing.image`. `image_dataset_from_directory` can sometimes be faster (tf origin) but `ImageDataGenerator` is a lot simpler to use and has on-the-fly data augmentation capability (keras).\n\nFor a full comparison of methods visit [this link](https://towardsdatascience.com/what-is-the-best-input-pipeline-to-train-image-classification-models-with-tf-keras-eb3fe26d3cc5)",
"_____no_output_____"
]
],
[
[
"# Sync your google drive folder\nfrom google.colab import drive\ndrive.mount(\"/content/drive\")",
"Mounted at /content/drive\n"
]
],
[
[
"<a name='x.0.4.1'></a>\n\n#### 4.0.4.1 Loading Data with `ImageDataGenerator`\n\n[back to top](#top)",
"_____no_output_____"
]
],
[
[
"# full dataset can be attained from kaggle if you are interested\n# https://www.kaggle.com/ravirajsinh45/real-life-industrial-dataset-of-casting-product?select=casting_data\n\npath_to_casting_data = '/content/drive/MyDrive/courses/tech_fundamentals/TECH_FUNDAMENTALS/data/casting_data_class_practice'\n\nimage_shape = (300,300,1)\nbatch_size = 32\n\ntechnocast_train_path = path_to_casting_data + '/train/'\ntechnocast_test_path = path_to_casting_data + '/test/'\n\nimage_gen = ImageDataGenerator(rescale=1/255) # normalize pixels to 0-1\n\n#we're using keras inbuilt function to ImageDataGenerator so we \n# dont need to label all images into 0 and 1 \nprint(\"loading training set...\")\n\ntrain_set = image_gen.flow_from_directory(technocast_train_path,\n target_size=image_shape[:2],\n color_mode=\"grayscale\",\n batch_size=batch_size,\n class_mode='binary',\n shuffle=True)\n\nprint(\"loading testing set...\")\ntest_set = image_gen.flow_from_directory(technocast_test_path,\n target_size=image_shape[:2],\n color_mode=\"grayscale\",\n batch_size=batch_size,\n class_mode='binary',\n shuffle=False)",
"loading training set...\nFound 840 images belonging to 2 classes.\nloading testing set...\nFound 715 images belonging to 2 classes.\n"
]
],
[
[
"<a name='x.0.4.2'></a>\n\n#### 4.0.4.2 loading data with `image_dataset_from_directory`\n\n[back to top](#top)\n\nThis method should be approx 2x faster than `ImageDataGenerator`",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.preprocessing import image_dataset_from_directory\nfrom tensorflow.data.experimental import AUTOTUNE\n\npath_to_casting_data = '/content/drive/MyDrive/courses/tech_fundamentals/TECH_FUNDAMENTALS/data/casting_data_class_practice'\n\ntechnocast_train_path = path_to_casting_data + '/train/'\ntechnocast_test_path = path_to_casting_data + '/test/'\n\n# Load training and validation sets\n\nimage_shape = (300,300,1)\nbatch_size = 32\n\nds_train_ = image_dataset_from_directory(\n technocast_train_path,\n labels='inferred',\n label_mode='binary',\n color_mode=\"grayscale\",\n image_size=image_shape[:2],\n batch_size=batch_size,\n shuffle=True,\n)\nds_valid_ = image_dataset_from_directory(\n technocast_test_path,\n labels='inferred',\n label_mode='binary',\n color_mode=\"grayscale\",\n image_size=image_shape[:2],\n batch_size=batch_size,\n shuffle=False,\n)\n\ntrain_set = ds_train_.prefetch(buffer_size=AUTOTUNE)\ntest_set = ds_valid_.prefetch(buffer_size=AUTOTUNE)",
"Found 840 files belonging to 2 classes.\nFound 715 files belonging to 2 classes.\n"
],
[
"# view some images\ndef_path = '/def_front/cast_def_0_1001.jpeg'\nok_path = '/ok_front/cast_ok_0_1.jpeg'\nimage_path = technocast_train_path + ok_path\nimage = tf.io.read_file(image_path)\nimage = tf.io.decode_jpeg(image)\n\nplt.figure(figsize=(6, 6))\nplt.imshow(tf.squeeze(image), cmap='gray')\nplt.axis('off')\nplt.show();",
"_____no_output_____"
]
],
[
[
"<a name='x.1'></a>\n\n## 4.1 Sliding Window\n\n[back to top](#top)\n\nThe kernels we just reviewed, need to be swept or _slid_ along the preceding layer. We call this a **_sliding window_**, the window being the kernel. \n\n<p align=center>\n<img src=\"https://i.imgur.com/LueNK6b.gif\" width=400></img>\n\nWhat do you notice about the gif? One perhaps obvious observation is that you can't scoot all the way up to the border of the input layer, this is because the kernel defines operations _around_ the centered pixel and so you bang up against the margin of the input array. We can change the behavior at the boundary with a **_padding_** hyperparameter. A second observation, is that the distance we move the kernel along in each step could be variable, we call this the **_stride_**. We will explore the affects of each of these.\n\n",
"_____no_output_____"
]
],
[
[
"from tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.Sequential([\n layers.Conv2D(filters=64,\n kernel_size=3,\n strides=1,\n padding='same',\n activation='relu'),\n layers.MaxPool2D(pool_size=2,\n strides=1,\n padding='same')\n # More layers follow\n])",
"_____no_output_____"
]
],
[
[
"<a name='x.1.1'></a>\n\n### 4.1.1 Stride\n\n[back to top](#top)\n\nStride defines the the step size we take with each kernel as it passes along the input array. The stride needs to be defined in both the horizontal and vertical dimensions. This animation shows a 2x2 stride\n\n\n<p align=center>\n<img src=\"https://i.imgur.com/Tlptsvt.gif\" width=400></img>\n\nThe stride will often be 1 for CNNs, where we don't want to lose any important information. Maximum pooling layers will often have strides greater than 1, to better summarize/accentuate the relevant features/activations.\n\nIf the stride is the same in both the horizontal and vertical directions, it can be set with a single number like `strides=2` within keras.\n\n",
"_____no_output_____"
],
[
"### 4.1.2 Padding\n\n[back to top](#top)\n\nPadding attempts to resolve our issue at the border: our kernel requires information surrounding the centered pixel, and at the border of the input array we don't have that information. What to do?\n\nWe have a couple popular options within the keras framework. We can set `padding='valid'` and only slide the kernel to the edge of the input array. This has the drawback of feature maps shrinking in size as we pass through the NN. Another option is to set `padding='same'` what this will do is pad the input array with 0's, just enough of them to allow the feature map to be the same size as the input array. This is shown in the gif below:\n\n\n<p align=center>\n<img src=\"https://i.imgur.com/RvGM2xb.gif\" width=400></img>\n\nThe downside of setting the padding to same will be that features at the edges of the image will be diluted. ",
"_____no_output_____"
],
[
"<a name='x.1.3'></a>\n\n### 4.1.3 Exercise: Exploring Sliding Windows\n\n[back to top](#top)",
"_____no_output_____"
]
],
[
[
"from skimage import draw, transform\nfrom itertools import product\n# helper functions borrowed from Ryan Holbrook\n# https://mathformachines.com/\n\ndef circle(size, val=None, r_shrink=0):\n circle = np.zeros([size[0]+1, size[1]+1])\n rr, cc = draw.circle_perimeter(\n size[0]//2, size[1]//2,\n radius=size[0]//2 - r_shrink,\n shape=[size[0]+1, size[1]+1],\n )\n if val is None:\n circle[rr, cc] = np.random.uniform(size=circle.shape)[rr, cc]\n else:\n circle[rr, cc] = val\n circle = transform.resize(circle, size, order=0)\n return circle\n\ndef show_kernel(kernel, label=True, digits=None, text_size=28):\n # Format kernel\n kernel = np.array(kernel)\n if digits is not None:\n kernel = kernel.round(digits)\n\n # Plot kernel\n cmap = plt.get_cmap('Blues_r')\n plt.imshow(kernel, cmap=cmap)\n rows, cols = kernel.shape\n thresh = (kernel.max()+kernel.min())/2\n # Optionally, add value labels\n if label:\n for i, j in product(range(rows), range(cols)):\n val = kernel[i, j]\n color = cmap(0) if val > thresh else cmap(255)\n plt.text(j, i, val, \n color=color, size=text_size,\n horizontalalignment='center', verticalalignment='center')\n plt.xticks([])\n plt.yticks([])\n\ndef show_extraction(image,\n kernel,\n conv_stride=1,\n conv_padding='valid',\n activation='relu',\n pool_size=2,\n pool_stride=2,\n pool_padding='same',\n figsize=(10, 10),\n subplot_shape=(2, 2),\n ops=['Input', 'Filter', 'Detect', 'Condense'],\n gamma=1.0):\n # Create Layers\n model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(\n filters=1,\n kernel_size=kernel.shape,\n strides=conv_stride,\n padding=conv_padding,\n use_bias=False,\n input_shape=image.shape,\n ),\n tf.keras.layers.Activation(activation),\n tf.keras.layers.MaxPool2D(\n pool_size=pool_size,\n strides=pool_stride,\n padding=pool_padding,\n ),\n ])\n\n layer_filter, layer_detect, layer_condense = model.layers\n kernel = tf.reshape(kernel, [*kernel.shape, 1, 1])\n layer_filter.set_weights([kernel])\n\n # Format for TF\n image = tf.expand_dims(image, axis=0)\n image = tf.image.convert_image_dtype(image, dtype=tf.float32) \n \n # Extract Feature\n image_filter = layer_filter(image)\n image_detect = layer_detect(image_filter)\n image_condense = layer_condense(image_detect)\n \n images = {}\n if 'Input' in ops:\n images.update({'Input': (image, 1.0)})\n if 'Filter' in ops:\n images.update({'Filter': (image_filter, 1.0)})\n if 'Detect' in ops:\n images.update({'Detect': (image_detect, gamma)})\n if 'Condense' in ops:\n images.update({'Condense': (image_condense, gamma)})\n \n # Plot\n plt.figure(figsize=figsize)\n for i, title in enumerate(ops):\n image, gamma = images[title]\n plt.subplot(*subplot_shape, i+1)\n plt.imshow(tf.image.adjust_gamma(tf.squeeze(image), gamma))\n plt.axis('off')\n plt.title(title)",
"_____no_output_____"
]
],
[
[
"Create an image and kernel:",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport matplotlib.pyplot as plt\n\nplt.rc('figure', autolayout=True)\nplt.rc('axes', labelweight='bold', labelsize='large',\n titleweight='bold', titlesize=18, titlepad=10)\nplt.rc('image', cmap='magma')\n\nimage = circle([64, 64], val=1.0, r_shrink=3)\nimage = tf.reshape(image, [*image.shape, 1])\n# Bottom sobel\nkernel = tf.constant(\n [[-1, -2, -1],\n [0, 0, 0],\n [1, 2, 1]],\n)\n\nshow_kernel(kernel)",
"_____no_output_____"
]
],
[
[
"What do we think this kernel is meant to detect for?\n\nWe will apply our kernel with a 1x1 stride and our max pooling with a 2x2 stride and pool size of 2.",
"_____no_output_____"
]
],
[
[
"show_extraction(\n image, kernel,\n\n # Window parameters\n conv_stride=1,\n pool_size=2,\n pool_stride=2,\n\n subplot_shape=(1, 4),\n figsize=(14, 6),\n)",
"_____no_output_____"
]
],
[
[
"Works ok! what about a higher conv stride?",
"_____no_output_____"
]
],
[
[
"show_extraction(\n image, kernel,\n\n # Window parameters\n conv_stride=2,\n pool_size=3,\n pool_stride=4,\n\n subplot_shape=(1, 4),\n figsize=(14, 6),\n)",
"_____no_output_____"
]
],
[
[
"Looks like we lost a bit of information!\n\nSometimes published models will use a larger kernel and stride in the initial layer to produce large-scale features early on in the network without losing too much information (ResNet50 uses 7x7 kernels with a stride of 2). For now, without having much experience it's safe to set conv strides to 1.\n\nTake a moment here with the given kernel and explore different settings for applying both the kernel and the max_pool\n\n```\nconv_stride=YOUR_VALUE, # condenses pixels\npool_size=YOUR_VALUE,\npool_stride=YOUR_VALUE, # condenses pixels\n```\n\nGiven a total condensation of 8 (I'm taking condensation to mean `conv_stride` x `pool_stride`). what do you think is the best combination of values for `conv_stride, pool_size, and pool_stride`?",
"_____no_output_____"
],
[
"<a name='x.2'></a>\n\n## 4.2 Custom CNN\n\n[back to top](#top)\n\nAs we move through the network, small-scale features (lines, edges, etc.) turn to large-scale features (shapes, eyes, ears, etc). We call these blocks of convolution, ReLU, and max pool **_convolutional blocks_** and they are the low level modular framework we work with. By this means, the CNN is able to design it's own features, ones suited for the classification or regression task at hand. \n\nWe will design a custom CNN for the Casting Defect Detection Dataset.",
"_____no_output_____"
],
[
"In the following I'm going to double the filter size after the first block. This is a common pattern as the max pooling layers forces us in the opposite direction.",
"_____no_output_____"
]
],
[
[
"#Creating model\n\nmodel = Sequential()\n\nmodel.add(InputLayer(input_shape=(image_shape)))\n\nmodel.add(Conv2D(filters=8, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(224))\nmodel.add(Activation('relu'))\n\n# Last layer\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['binary_accuracy'])\n\nearly_stop = EarlyStopping(monitor='val_loss',\n patience=5,\n restore_best_weights=True,)",
"_____no_output_____"
],
[
"# with CPU + ImageDataGenerator runs for about 40 minutes (5 epochs)\n# with GPU + image_dataset_from_directory runs for about 4 minutes (16 epochs)\nwith tf.device('/device:GPU:0'):\n results = model.fit(train_set,\n epochs=20,\n validation_data=test_set,\n callbacks=[early_stop])",
"Epoch 1/20\n27/27 [==============================] - 216s 7s/step - loss: 106.8427 - binary_accuracy: 0.5214 - val_loss: 0.9809 - val_binary_accuracy: 0.4587\nEpoch 2/20\n27/27 [==============================] - 3s 95ms/step - loss: 0.5812 - binary_accuracy: 0.6810 - val_loss: 0.5878 - val_binary_accuracy: 0.6685\nEpoch 3/20\n27/27 [==============================] - 3s 91ms/step - loss: 0.3734 - binary_accuracy: 0.8250 - val_loss: 0.4595 - val_binary_accuracy: 0.7664\nEpoch 4/20\n27/27 [==============================] - 3s 93ms/step - loss: 0.2949 - binary_accuracy: 0.8750 - val_loss: 0.5249 - val_binary_accuracy: 0.7399\nEpoch 5/20\n27/27 [==============================] - 3s 94ms/step - loss: 0.2743 - binary_accuracy: 0.8869 - val_loss: 0.4261 - val_binary_accuracy: 0.8042\nEpoch 6/20\n27/27 [==============================] - 3s 93ms/step - loss: 0.4171 - binary_accuracy: 0.8250 - val_loss: 0.4889 - val_binary_accuracy: 0.7748\nEpoch 7/20\n27/27 [==============================] - 3s 91ms/step - loss: 0.2597 - binary_accuracy: 0.8940 - val_loss: 0.7065 - val_binary_accuracy: 0.7343\nEpoch 8/20\n27/27 [==============================] - 3s 93ms/step - loss: 0.1480 - binary_accuracy: 0.9464 - val_loss: 0.3443 - val_binary_accuracy: 0.8769\nEpoch 9/20\n27/27 [==============================] - 3s 90ms/step - loss: 0.0761 - binary_accuracy: 0.9786 - val_loss: 0.3585 - val_binary_accuracy: 0.8643\nEpoch 10/20\n27/27 [==============================] - 3s 89ms/step - loss: 0.0536 - binary_accuracy: 0.9845 - val_loss: 0.4970 - val_binary_accuracy: 0.8336\nEpoch 11/20\n27/27 [==============================] - 3s 87ms/step - loss: 0.0279 - binary_accuracy: 0.9964 - val_loss: 0.4734 - val_binary_accuracy: 0.8434\nEpoch 12/20\n27/27 [==============================] - 3s 87ms/step - loss: 0.0193 - binary_accuracy: 0.9976 - val_loss: 0.3529 - val_binary_accuracy: 0.9007\nEpoch 13/20\n27/27 [==============================] - 3s 85ms/step - loss: 0.0188 - binary_accuracy: 0.9952 - val_loss: 0.6841 - val_binary_accuracy: 0.8112\n"
],
[
"# model.save('inspection_of_casting_products.h5')",
"_____no_output_____"
]
],
[
[
"<a name='x.2.1'></a>\n\n### 4.2.1 Evaluate Model\n\n[back to top](#top)",
"_____no_output_____"
]
],
[
[
"# model.load_weights('inspection_of_casting_products.h5')",
"_____no_output_____"
],
[
"losses = pd.DataFrame(results.history)\n# losses.to_csv('history_simple_model.csv', index=False)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 2, figsize=(10,5))\nlosses[['loss','val_loss']].plot(ax=ax[0])\nlosses[['binary_accuracy','val_binary_accuracy']].plot(ax=ax[1])",
"_____no_output_____"
],
[
"# predict test set\npred_probability = model.predict(test_set)\n\n# convert to bool\npredictions = pred_probability > 0.5\n\n# precision / recall / f1-score \n\n# test_set.classes to get images from ImageDataGenerator\n\n# for image_dataset_from_directory we have to do a little gymnastics \n# to get the labels\nlabels = np.array([])\nfor x, y in ds_valid_:\n labels = np.concatenate([labels, tf.squeeze(y.numpy()).numpy()])\n\nprint(classification_report(labels,predictions))",
" precision recall f1-score support\n\n 0.0 0.89 0.92 0.90 453\n 1.0 0.85 0.81 0.83 262\n\n accuracy 0.88 715\n macro avg 0.87 0.86 0.87 715\nweighted avg 0.88 0.88 0.88 715\n\n"
],
[
"plt.figure(figsize=(10,6))\nsns.heatmap(confusion_matrix(labels,predictions),annot=True)",
"_____no_output_____"
]
],
[
[
"<a name='x.3'></a>\n\n## 4.3 Data Augmentation\n\n[back to top](#top)\n\nAlright, alright, alright. We've done pretty good making our CNN model. But let's see if we can make it even better. There's a last trick we'll cover here in regard to image classifiers. We're going to perturb the input images in such a way as to create a pseudo-larger dataset.\n\nWith any machine learning model, the more relevant training data we give the model, the better. The key here is _relevant_ training data. We can easily do this with images so long as we do not change the class of the image. For example, in the small plot below, we are changing contrast, hue, rotation, and doing other things to the image of a car; and this is okay because it does not change the classification from a car to, say, a truck.\n\n<p align=center>\n<img src=\"https://i.imgur.com/UaOm0ms.png\" width=400></img>\n\nTypically when we do data augmentation for images, we do them _online_, i.e. during training. Recall that we train in batches (or minibatches) with CNNs. An example of a minibatch then, might be the small multiples plot below.\n\n<p align=center>\n<img src=\"https://i.imgur.com/MFviYoE.png\" width=400></img>\n\nby varying the images in this way, the model always sees slightly new data, and becomes a more robust model. Remember that the caveat is that we can't muddle the relevant classification of the image. Sometimes the best way to see if data augmentation will be helpful is to just try it and see!",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.layers.experimental import preprocessing\n\n#Creating model\n\nmodel = Sequential()\n\nmodel.add(preprocessing.RandomFlip('horizontal')), # flip left-to-right\nmodel.add(preprocessing.RandomFlip('vertical')), # flip upside-down\nmodel.add(preprocessing.RandomContrast(0.5)), # contrast change by up to 50%\n\nmodel.add(Conv2D(filters=8, kernel_size=(3,3),input_shape=image_shape, activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(224))\nmodel.add(Activation('relu'))\n\n# Last layer\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['binary_accuracy'])\n\nearly_stop = EarlyStopping(monitor='val_loss',\n patience=5,\n restore_best_weights=True,)",
"_____no_output_____"
],
[
"results = model.fit(train_set,\n epochs=30,\n validation_data=test_set,\n callbacks=[early_stop])",
"Epoch 1/30\n27/27 [==============================] - 4s 91ms/step - loss: 76.2214 - binary_accuracy: 0.5071 - val_loss: 0.8650 - val_binary_accuracy: 0.6294\nEpoch 2/30\n27/27 [==============================] - 3s 89ms/step - loss: 0.8103 - binary_accuracy: 0.6274 - val_loss: 0.6360 - val_binary_accuracy: 0.6420\nEpoch 3/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.6127 - binary_accuracy: 0.6881 - val_loss: 0.6022 - val_binary_accuracy: 0.6587\nEpoch 4/30\n27/27 [==============================] - 3s 86ms/step - loss: 0.5352 - binary_accuracy: 0.7571 - val_loss: 0.7390 - val_binary_accuracy: 0.6252\nEpoch 5/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.6084 - binary_accuracy: 0.7131 - val_loss: 0.4597 - val_binary_accuracy: 0.7762\nEpoch 6/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.4360 - binary_accuracy: 0.8083 - val_loss: 0.4494 - val_binary_accuracy: 0.7734\nEpoch 7/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.4178 - binary_accuracy: 0.8131 - val_loss: 0.3622 - val_binary_accuracy: 0.8224\nEpoch 8/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.3240 - binary_accuracy: 0.8560 - val_loss: 0.3029 - val_binary_accuracy: 0.8755\nEpoch 9/30\n27/27 [==============================] - 3s 87ms/step - loss: 0.2831 - binary_accuracy: 0.8833 - val_loss: 0.2903 - val_binary_accuracy: 0.8699\nEpoch 10/30\n27/27 [==============================] - 3s 96ms/step - loss: 0.2518 - binary_accuracy: 0.9048 - val_loss: 0.3015 - val_binary_accuracy: 0.8811\nEpoch 11/30\n27/27 [==============================] - 3s 96ms/step - loss: 0.2901 - binary_accuracy: 0.8952 - val_loss: 0.3804 - val_binary_accuracy: 0.8238\nEpoch 12/30\n27/27 [==============================] - 3s 95ms/step - loss: 0.2564 - binary_accuracy: 0.8940 - val_loss: 0.2921 - val_binary_accuracy: 0.8825\nEpoch 13/30\n27/27 [==============================] - 3s 94ms/step - loss: 0.2307 - binary_accuracy: 0.9012 - val_loss: 0.2420 - val_binary_accuracy: 0.8979\nEpoch 14/30\n27/27 [==============================] - 3s 92ms/step - loss: 0.2575 - binary_accuracy: 0.8952 - val_loss: 0.2712 - val_binary_accuracy: 0.8937\nEpoch 15/30\n27/27 [==============================] - 3s 92ms/step - loss: 0.1533 - binary_accuracy: 0.9333 - val_loss: 0.4368 - val_binary_accuracy: 0.8699\nEpoch 16/30\n27/27 [==============================] - 3s 89ms/step - loss: 0.2305 - binary_accuracy: 0.9167 - val_loss: 0.2654 - val_binary_accuracy: 0.8965\nEpoch 17/30\n27/27 [==============================] - 3s 88ms/step - loss: 0.2781 - binary_accuracy: 0.8929 - val_loss: 0.4747 - val_binary_accuracy: 0.8126\nEpoch 18/30\n27/27 [==============================] - 3s 88ms/step - loss: 0.2832 - binary_accuracy: 0.8893 - val_loss: 0.3223 - val_binary_accuracy: 0.8853\n"
]
],
[
[
"<a name='x.3.1'></a>\n\n### 4.3.1 Evaluate Model\n\n[back to top](#top)",
"_____no_output_____"
]
],
[
[
"losses = pd.DataFrame(results.history)\n# losses.to_csv('history_augment_model.csv', index=False)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 2, figsize=(10,5))\nlosses[['loss','val_loss']].plot(ax=ax[0])\nlosses[['binary_accuracy','val_binary_accuracy']].plot(ax=ax[1])",
"_____no_output_____"
],
[
"# predict test set\npred_probability = model.predict(test_set)\n\n# convert to bool\npredictions = pred_probability > 0.5\n\n# precision / recall / f1-score \n\n# test_set.classes to get images from ImageDataGenerator\n\n# for image_dataset_from_directory we have to do a little gymnastics \n# to get the labels\nlabels = np.array([])\nfor x, y in ds_valid_:\n labels = np.concatenate([labels, tf.squeeze(y.numpy()).numpy()])\n\nprint(classification_report(labels,predictions))",
" precision recall f1-score support\n\n 0.0 0.97 0.87 0.91 453\n 1.0 0.80 0.95 0.87 262\n\n accuracy 0.90 715\n macro avg 0.89 0.91 0.89 715\nweighted avg 0.91 0.90 0.90 715\n\n"
],
[
"plt.figure(figsize=(10,6))\nsns.heatmap(confusion_matrix(labels,predictions),annot=True)",
"_____no_output_____"
]
],
[
[
"<a name='x.3.2'></a>\n\n### 4.3.2 Exercise: Image Preprocessing Layers\n\n[back to top](#top)\n\nThese layers apply random augmentation transforms to a batch of images. They are only active during training. You can visit the documentation [here](https://keras.io/api/layers/preprocessing_layers/image_preprocessing/)\n\n* `RandomCrop` layer\n* `RandomFlip` layer\n* `RandomTranslation` layer\n* `RandomRotation` layer\n* `RandomZoom` layer\n* `RandomHeight` layer\n* `RandomWidth` layer\n\nUse any combination of random augmentation transforms and retrain your model. Can you get a higher val performance? you may need to increase your epochs.",
"_____no_output_____"
]
],
[
[
"# code cell for exercise 4.3.2\nfrom tensorflow.keras.layers.experimental import preprocessing\n\n#Creating model\n\nmodel = Sequential()\n\nmodel.add(preprocessing.RandomFlip('horizontal')), # flip left-to-right\nmodel.add(preprocessing.RandomFlip('vertical')), # flip upside-down\nmodel.add(preprocessing.RandomContrast(0.5)), # contrast change by up to 50%\nmodel.add(preprocessing.RandomRotation((-1,1))), # contrast change by up to 50%\n\nmodel.add(Conv2D(filters=8, kernel_size=(3,3),input_shape=image_shape, activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu',))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(224))\nmodel.add(Activation('relu'))\n\n# Last layer\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['binary_accuracy'])\n\nearly_stop = EarlyStopping(monitor='val_loss',\n patience=5,\n restore_best_weights=True,)",
"_____no_output_____"
],
[
"results = model.fit(train_set,\n epochs=200,\n validation_data=test_set,\n callbacks=[early_stop])",
"Epoch 1/200\n27/27 [==============================] - 3s 91ms/step - loss: 0.1499 - binary_accuracy: 0.9369 - val_loss: 0.1408 - val_binary_accuracy: 0.9343\nEpoch 2/200\n27/27 [==============================] - 3s 88ms/step - loss: 0.1315 - binary_accuracy: 0.9560 - val_loss: 0.0707 - val_binary_accuracy: 0.9748\nEpoch 3/200\n27/27 [==============================] - 3s 95ms/step - loss: 0.1301 - binary_accuracy: 0.9524 - val_loss: 0.1000 - val_binary_accuracy: 0.9594\nEpoch 4/200\n27/27 [==============================] - 3s 98ms/step - loss: 0.1378 - binary_accuracy: 0.9512 - val_loss: 0.0977 - val_binary_accuracy: 0.9692\nEpoch 5/200\n27/27 [==============================] - 3s 94ms/step - loss: 0.1036 - binary_accuracy: 0.9631 - val_loss: 0.0894 - val_binary_accuracy: 0.9580\nEpoch 6/200\n27/27 [==============================] - 3s 96ms/step - loss: 0.1226 - binary_accuracy: 0.9631 - val_loss: 0.1019 - val_binary_accuracy: 0.9678\nEpoch 7/200\n27/27 [==============================] - 3s 97ms/step - loss: 0.1102 - binary_accuracy: 0.9631 - val_loss: 0.0662 - val_binary_accuracy: 0.9734\nEpoch 8/200\n27/27 [==============================] - 3s 96ms/step - loss: 0.1815 - binary_accuracy: 0.9298 - val_loss: 0.1919 - val_binary_accuracy: 0.9161\nEpoch 9/200\n27/27 [==============================] - 3s 91ms/step - loss: 0.2733 - binary_accuracy: 0.8917 - val_loss: 0.0973 - val_binary_accuracy: 0.9664\nEpoch 10/200\n27/27 [==============================] - 3s 89ms/step - loss: 0.1829 - binary_accuracy: 0.9250 - val_loss: 0.0684 - val_binary_accuracy: 0.9706\nEpoch 11/200\n27/27 [==============================] - 3s 90ms/step - loss: 0.1058 - binary_accuracy: 0.9655 - val_loss: 0.0898 - val_binary_accuracy: 0.9622\nEpoch 12/200\n27/27 [==============================] - 3s 89ms/step - loss: 0.0841 - binary_accuracy: 0.9726 - val_loss: 0.0629 - val_binary_accuracy: 0.9790\nEpoch 13/200\n27/27 [==============================] - 3s 87ms/step - loss: 0.1014 - binary_accuracy: 0.9655 - val_loss: 0.0490 - val_binary_accuracy: 0.9832\nEpoch 14/200\n27/27 [==============================] - 3s 88ms/step - loss: 0.1066 - binary_accuracy: 0.9619 - val_loss: 1.0592 - val_binary_accuracy: 0.7678\nEpoch 15/200\n27/27 [==============================] - 3s 91ms/step - loss: 0.2655 - binary_accuracy: 0.9083 - val_loss: 0.0748 - val_binary_accuracy: 0.9762\nEpoch 16/200\n27/27 [==============================] - 3s 87ms/step - loss: 0.1535 - binary_accuracy: 0.9345 - val_loss: 0.0996 - val_binary_accuracy: 0.9664\nEpoch 17/200\n27/27 [==============================] - 3s 87ms/step - loss: 0.1483 - binary_accuracy: 0.9440 - val_loss: 0.0917 - val_binary_accuracy: 0.9636\nEpoch 18/200\n27/27 [==============================] - 3s 86ms/step - loss: 0.1443 - binary_accuracy: 0.9488 - val_loss: 0.0879 - val_binary_accuracy: 0.9566\n"
],
[
"# predict test set\npred_probability = model.predict(test_set)\n\n# convert to bool\npredictions = pred_probability > 0.5\n\n# precision / recall / f1-score \n\n# test_set.classes to get images from ImageDataGenerator\n\n# for image_dataset_from_directory we have to do a little gymnastics \n# to get the labels\nlabels = np.array([])\nfor x, y in ds_valid_:\n labels = np.concatenate([labels, tf.squeeze(y.numpy()).numpy()])\n\nprint(classification_report(labels,predictions))",
" precision recall f1-score support\n\n 0.0 0.99 0.98 0.99 453\n 1.0 0.97 0.98 0.98 262\n\n accuracy 0.98 715\n macro avg 0.98 0.98 0.98 715\nweighted avg 0.98 0.98 0.98 715\n\n"
],
[
"plt.figure(figsize=(10,6))\nsns.heatmap(confusion_matrix(labels,predictions),annot=True)",
"_____no_output_____"
]
],
[
[
"<a name='x.4'></a>\n\n## 4.4 Transfer Learning\n\n[back to top](#top)\n\nTransfer learning with [EfficientNet](https://keras.io/examples/vision/image_classification_efficientnet_fine_tuning/)",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.preprocessing import image_dataset_from_directory\nfrom tensorflow.data.experimental import AUTOTUNE\n\npath_to_casting_data = '/content/drive/MyDrive/courses/TECH_FUNDAMENTALS/data/casting_data_class_practice'\n\ntechnocast_train_path = path_to_casting_data + '/train/'\ntechnocast_test_path = path_to_casting_data + '/test/'\n\n# Load training and validation sets\n\nimage_shape = (300,300,3)\nbatch_size = 32\n\nds_train_ = image_dataset_from_directory(\n technocast_train_path,\n labels='inferred',\n label_mode='binary',\n color_mode=\"grayscale\",\n image_size=image_shape[:2],\n batch_size=batch_size,\n shuffle=True,\n)\n\nds_valid_ = image_dataset_from_directory(\n technocast_test_path,\n labels='inferred',\n label_mode='binary',\n color_mode=\"grayscale\",\n image_size=image_shape[:2],\n batch_size=batch_size,\n shuffle=False,\n)\n\ntrain_set = ds_train_.prefetch(buffer_size=AUTOTUNE)\ntest_set = ds_valid_.prefetch(buffer_size=AUTOTUNE)",
"Found 840 files belonging to 2 classes.\nFound 715 files belonging to 2 classes.\n"
],
[
"def build_model(image_shape):\n input = tf.keras.layers.Input(shape=(image_shape))\n\n # include_top = False will take of the last dense layer used for classification\n model = tf.keras.applications.EfficientNetB3(include_top=False, \n input_tensor=input, \n weights=\"imagenet\")\n\n # Freeze the pretrained weights\n model.trainable = False\n\n # now we have to rebuild the top\n x = tf.keras.layers.GlobalAveragePooling2D(name=\"avg_pool\")(model.output)\n x = tf.keras.layers.BatchNormalization()(x)\n\n top_dropout_rate = 0.2\n x = tf.keras.layers.Dropout(top_dropout_rate, name=\"top_dropout\")(x)\n\n # use num-nodes = 1 for binary, class # for multiclass\n output = tf.keras.layers.Dense(1, activation=\"softmax\", name=\"pred\")(x)\n\n # Compile\n model = tf.keras.Model(input, output, name=\"EfficientNet\")\n model.compile(optimizer='adam', \n loss=\"binary_crossentropy\", \n metrics=[\"binary_accuracy\"])\n return model",
"_____no_output_____"
],
[
"model = build_model(image_shape)",
"_____no_output_____"
],
[
"with tf.device('/device:GPU:0'):\n results = model.fit(train_set,\n epochs=20,\n validation_data=test_set,\n callbacks=[early_stop])",
"Epoch 1/20\nWARNING:tensorflow:Model was constructed with shape (None, 300, 300, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 300, 300, 3), dtype=tf.float32, name='input_12'), name='input_12', description=\"created by layer 'input_12'\"), but it was called on an input with incompatible shape (None, 300, 300, 1).\nWARNING:tensorflow:Model was constructed with shape (None, 300, 300, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 300, 300, 3), dtype=tf.float32, name='input_12'), name='input_12', description=\"created by layer 'input_12'\"), but it was called on an input with incompatible shape (None, 300, 300, 1).\n27/27 [==============================] - ETA: 0s - loss: 0.4457 - binary_accuracy: 0.4905WARNING:tensorflow:Model was constructed with shape (None, 300, 300, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 300, 300, 3), dtype=tf.float32, name='input_12'), name='input_12', description=\"created by layer 'input_12'\"), but it was called on an input with incompatible shape (None, 300, 300, 1).\n27/27 [==============================] - 20s 442ms/step - loss: 0.4457 - binary_accuracy: 0.4905 - val_loss: 0.4851 - val_binary_accuracy: 0.3664\nEpoch 2/20\n27/27 [==============================] - 11s 381ms/step - loss: 0.1878 - binary_accuracy: 0.4905 - val_loss: 0.3930 - val_binary_accuracy: 0.3664\nEpoch 3/20\n27/27 [==============================] - 11s 384ms/step - loss: 0.1816 - binary_accuracy: 0.4905 - val_loss: 0.3407 - val_binary_accuracy: 0.3664\nEpoch 4/20\n27/27 [==============================] - 11s 378ms/step - loss: 0.1394 - binary_accuracy: 0.4905 - val_loss: 0.2971 - val_binary_accuracy: 0.3664\nEpoch 5/20\n27/27 [==============================] - 11s 380ms/step - loss: 0.0982 - binary_accuracy: 0.4905 - val_loss: 0.2490 - val_binary_accuracy: 0.3664\nEpoch 6/20\n27/27 [==============================] - 11s 376ms/step - loss: 0.1032 - binary_accuracy: 0.4905 - val_loss: 0.2130 - val_binary_accuracy: 0.3664\nEpoch 7/20\n27/27 [==============================] - 11s 380ms/step - loss: 0.0801 - binary_accuracy: 0.4905 - val_loss: 0.1846 - val_binary_accuracy: 0.3664\nEpoch 8/20\n27/27 [==============================] - 11s 383ms/step - loss: 0.0806 - binary_accuracy: 0.4905 - val_loss: 0.1509 - val_binary_accuracy: 0.3664\nEpoch 9/20\n27/27 [==============================] - 11s 379ms/step - loss: 0.0736 - binary_accuracy: 0.4905 - val_loss: 0.1263 - val_binary_accuracy: 0.3664\nEpoch 10/20\n27/27 [==============================] - 11s 379ms/step - loss: 0.0916 - binary_accuracy: 0.4905 - val_loss: 0.1008 - val_binary_accuracy: 0.3664\nEpoch 11/20\n27/27 [==============================] - 11s 381ms/step - loss: 0.0618 - binary_accuracy: 0.4905 - val_loss: 0.0886 - val_binary_accuracy: 0.3664\nEpoch 12/20\n27/27 [==============================] - 11s 380ms/step - loss: 0.0843 - binary_accuracy: 0.4905 - val_loss: 0.0728 - val_binary_accuracy: 0.3664\nEpoch 13/20\n27/27 [==============================] - 11s 383ms/step - loss: 0.0741 - binary_accuracy: 0.4905 - val_loss: 0.0593 - val_binary_accuracy: 0.3664\nEpoch 14/20\n27/27 [==============================] - 11s 381ms/step - loss: 0.0637 - binary_accuracy: 0.4905 - val_loss: 0.0535 - val_binary_accuracy: 0.3664\nEpoch 15/20\n27/27 [==============================] - 11s 380ms/step - loss: 0.0657 - binary_accuracy: 0.4905 - val_loss: 0.0491 - val_binary_accuracy: 0.3664\nEpoch 16/20\n27/27 [==============================] - 11s 375ms/step - loss: 0.0653 - binary_accuracy: 0.4905 - val_loss: 0.0424 - val_binary_accuracy: 0.3664\nEpoch 17/20\n27/27 [==============================] - 11s 378ms/step - loss: 0.0451 - binary_accuracy: 0.4905 - val_loss: 0.0394 - val_binary_accuracy: 0.3664\nEpoch 18/20\n27/27 [==============================] - 11s 382ms/step - loss: 0.0667 - binary_accuracy: 0.4905 - val_loss: 0.0345 - val_binary_accuracy: 0.3664\nEpoch 19/20\n27/27 [==============================] - 11s 382ms/step - loss: 0.0541 - binary_accuracy: 0.4905 - val_loss: 0.0351 - val_binary_accuracy: 0.3664\nEpoch 20/20\n27/27 [==============================] - 11s 381ms/step - loss: 0.0353 - binary_accuracy: 0.4905 - val_loss: 0.0365 - val_binary_accuracy: 0.3664\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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb46fb8d90505e31860ccb04ada1aaf6b2b61752 | 462,343 | ipynb | Jupyter Notebook | Modelagem/.ipynb_checkpoints/[DRAFT] isolation_forest-checkpoint.ipynb | lsawakuchi/x1 | 564a135b4fdaa687a4ef6d470ddaa4730932d429 | [
"MIT"
] | null | null | null | Modelagem/.ipynb_checkpoints/[DRAFT] isolation_forest-checkpoint.ipynb | lsawakuchi/x1 | 564a135b4fdaa687a4ef6d470ddaa4730932d429 | [
"MIT"
] | null | null | null | Modelagem/.ipynb_checkpoints/[DRAFT] isolation_forest-checkpoint.ipynb | lsawakuchi/x1 | 564a135b4fdaa687a4ef6d470ddaa4730932d429 | [
"MIT"
] | null | null | null | 42.281024 | 43,536 | 0.539848 | [
[
[
"- Usar o algorithmo Isolation Forest ( IF ) para identificar comportamentos outliers no dataset de dívidas\n- Hipótese : um comportamento outlier pode indicar um usuário de alto risco/fraudulento",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"df = pd.read_excel(\"../tabelas/dataset_modelo_201904.xlsx\")",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df.index = df.cnpj",
"_____no_output_____"
],
[
"df.drop(columns=['cnpj'], axis=1, inplace=True)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"#### Distributions of the variables",
"_____no_output_____"
]
],
[
[
"from plotly.offline import init_notebook_mode, iplot\nimport plotly.graph_objs as go\ninit_notebook_mode(connected=True)",
"_____no_output_____"
]
],
[
[
"- prop_divida",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['prop_divida'],\n marker = dict(color='rgb(88,190,148)')\n)\nlayout = go.Layout(title = \"prop_divida\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- quantidade_cheques",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['quantidade_cheques'],\n marker = dict(color='rgb(88,190,148)')\n)\nlayout = go.Layout(title = \"quantidade_cheques\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- tempo_medio",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['tempo_medio'],\n marker = dict(color='rgb(88,190,148)')\n)\nlayout = go.Layout(title = \"tempo_medio\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- idade_maxima",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['idade_maxima'],\n marker = dict(color='rgb(88,190,148)'),\n xbins=dict(\n start=df['idade_maxima'].min(),\n end=df['idade_maxima'].max(),\n size=10\n )\n)\nlayout = go.Layout(title = \"idade_maxima\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- credito",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['credito'],\n marker = dict(color='rgb(88,190,148)'),\n xbins = dict(\n start = df['credito'].min(),\n end = df['credito'].max(),\n size = 0.05\n )\n)\n\nlayout = go.Layout(title = \"credito\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- infra",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['infra'],\n marker = dict(color='rgb(88,190,148)')\n)\nlayout = go.Layout(title = \"infra\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- outros",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['outros'],\n marker = dict(color='rgb(88,190,148)'),\n xbins = dict(\n start = df['outros'].min(),\n end = df['outros'].max(),\n size=0.02\n )\n)\nlayout = go.Layout(title = \"outros\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- processos",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['processos'],\n marker = dict(color='rgb(88,190,148)'),\n xbins = dict(\n start = df['processos'].min(),\n end = df['processos'].max(),\n size = 0.05\n )\n)\nlayout = go.Layout(title = \"processos\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"- dispersao",
"_____no_output_____"
]
],
[
[
"trace = go.Histogram(\n x = df['dispersao'],\n marker = dict(color='rgb(88,190,148)'),\n)\nlayout = go.Layout(title = \"dispersao\")\nfig = go.Figure(data = [trace], layout=layout)\niplot(fig)",
"_____no_output_____"
]
],
[
[
"#### Outlier detection with the entire set of variables",
"_____no_output_____"
]
],
[
[
"X = df.copy()",
"_____no_output_____"
],
[
"outlier_detect = IsolationForest(n_estimators=100,\n max_samples=1000, contamination=.05, max_features=X.shape[1], random_state=1)\n\noutlier_detect.fit(X)\n\noutliers_predicted = outlier_detect.predict(X)",
"_____no_output_____"
],
[
"df[\"outlier\"] = outliers_predicted",
"_____no_output_____"
],
[
"df[df['outlier']==-1]",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
]
],
[
[
"- var idade_maxima has a nearly uniform distribution, it will not define an outlier",
"_____no_output_____"
]
],
[
[
"pca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(X)\n\ndf_pca = pd.DataFrame(data = principalComponents\n , columns = ['pc1', 'pc2'])\n\ndf_pca[\"outlier\"] = outliers_predicted\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = [\"outlier\", \"inlier\"]\ncolors = ['r', 'b']\nfor target, color in zip(targets,colors):\n indicesToKeep = df_pca['outlier'] == -1 if target == \"outlier\" else df_pca['outlier'] == 1\n ax.scatter(df_pca.loc[indicesToKeep, 'pc1']\n , df_pca.loc[indicesToKeep, 'pc2']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()\n",
"_____no_output_____"
]
],
[
[
"- dropping the var idae_maxima",
"_____no_output_____"
]
],
[
[
"X = df.drop(columns=[\"idade_maxima\", \"outlier\"])",
"_____no_output_____"
],
[
"# X.drop(columns=[\"outlier\"], axis=1, inplace=True)",
"_____no_output_____"
],
[
"# X.drop(columns=['outros'], axis=1, inplace=True)",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"X.shape",
"_____no_output_____"
],
[
"X = X[X['prop_divida']<1.5]",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"# X.drop(columns=['outlier'], axis=1, inplace=True)",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"outlier_detect = IsolationForest(n_estimators=100,\n max_samples=1000, contamination=.04, max_features=X.shape[1], random_state=1)\n\noutlier_detect.fit(X)\n\noutliers_predicted = outlier_detect.predict(X)",
"_____no_output_____"
],
[
"X[\"outlier\"] = outliers_predicted",
"_____no_output_____"
],
[
"X[X['outlier']==-1]",
"_____no_output_____"
],
[
"pca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(X)\n\ndf_pca = pd.DataFrame(data = principalComponents\n , columns = ['pc1', 'pc2'])\n\ndf_pca[\"outlier\"] = outliers_predicted\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = [\"outlier\", \"inlier\"]\ncolors = ['r', 'b']\nfor target, color in zip(targets,colors):\n indicesToKeep = df_pca['outlier'] == -1 if target == \"outlier\" else df_pca['outlier'] == 1\n ax.scatter(df_pca.loc[indicesToKeep, 'pc1']\n , df_pca.loc[indicesToKeep, 'pc2']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()\n",
"_____no_output_____"
],
[
"X = df[(df['prop_divida']<1.5) & (df['quantidade_cheques']==0)]",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"X.drop(columns=[\"idade_maxima\", \"outlier\"], axis=1, inplace=True)",
"_____no_output_____"
],
[
"# X = X.drop(columns=['prop_divida', 'quantidade_cheques', 'tempo_medio', 'idade_maxima', 'outros', 'outlier'])",
"_____no_output_____"
],
[
"outlier_detect = IsolationForest(n_estimators=100,\n max_samples=1000, contamination=.1, max_features=X.shape[1], random_state=1)\n\noutlier_detect.fit(X)\n\noutliers_predicted = outlier_detect.predict(X)",
"_____no_output_____"
],
[
"X['outlier'] = outliers_predicted",
"_____no_output_____"
],
[
"pca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(X)\n\ndf_pca = pd.DataFrame(data = principalComponents\n , columns = ['pc1', 'pc2'])\n\ndf_pca[\"outlier\"] = outliers_predicted\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = [\"outlier\", \"inlier\"]\ncolors = ['r', 'b']\nfor target, color in zip(targets,colors):\n indicesToKeep = df_pca['outlier'] == -1 if target == \"outlier\" else df_pca['outlier'] == 1\n ax.scatter(df_pca.loc[indicesToKeep, 'pc1']\n , df_pca.loc[indicesToKeep, 'pc2']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()\n",
"_____no_output_____"
],
[
"X.shape",
"_____no_output_____"
],
[
"df2 = df.drop(columns=['outros'])",
"_____no_output_____"
],
[
"# df2.head()",
"_____no_output_____"
],
[
"df3 = df2[df2['prop_divida']<1.5]",
"_____no_output_____"
],
[
"df3.head()",
"_____no_output_____"
],
[
"# applying Isolation Forest",
"_____no_output_____"
],
[
"X = df3.iloc[:, 1:]",
"_____no_output_____"
],
[
"X.head()",
"_____no_output_____"
],
[
"outlier_detect = IsolationForest(n_estimators=1000,\n max_samples=1000, contamination=.04, max_features=X.shape[1], random_state=1)\n\noutlier_detect.fit(X)\n\noutliers_predicted = outlier_detect.predict(X)",
"_____no_output_____"
],
[
"df3['outlier'] = outliers_predicted",
"_____no_output_____"
],
[
"df3.groupby('outlier').count()",
"_____no_output_____"
],
[
"df3[df3['outlier']==-1]",
"_____no_output_____"
],
[
"## trying PCA to visualize outliers",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler",
"_____no_output_____"
],
[
"features = list(X.columns)",
"_____no_output_____"
],
[
"features",
"_____no_output_____"
],
[
"x = X.loc[:, features].values",
"_____no_output_____"
],
[
"x = StandardScaler().fit_transform(x)",
"_____no_output_____"
],
[
"X = pd.DataFrame(x)\n\nX.columns = features",
"_____no_output_____"
],
[
"# features dataframe mean normalized\nX.head()",
"_____no_output_____"
],
[
"# reducing dimensionality to plot the data and, hoppefully, detect outliers by visualization",
"_____no_output_____"
],
[
"from sklearn.decomposition import PCA\n\npca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(X)\n\ndf_pca = pd.DataFrame(data = principalComponents\n , columns = ['pc1', 'pc2'])\n\ndf_pca.head()\n\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']\ncolors = ['r', 'g', 'b']\n\n\nax.scatter(df_pca.iloc[:, 0]\n , df_pca.iloc[:, 1]\n , s = 50)\n\nax.grid()\n",
"_____no_output_____"
],
[
"df_pca",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"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",
"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"
]
] |
cb4711ad65a5fd1ff77ae203c27c57c7b0877e97 | 58,136 | ipynb | Jupyter Notebook | notebooks/Geometry Optimisation.ipynb | YangshuaiWang/TightBinding.jl | 12656829645666fd943bc3be4183494870c299d0 | [
"MIT"
] | 1 | 2018-12-27T05:32:25.000Z | 2018-12-27T05:32:25.000Z | notebooks/Geometry Optimisation.ipynb | YangshuaiWang/TightBinding.jl | 12656829645666fd943bc3be4183494870c299d0 | [
"MIT"
] | null | null | null | notebooks/Geometry Optimisation.ipynb | YangshuaiWang/TightBinding.jl | 12656829645666fd943bc3be4183494870c299d0 | [
"MIT"
] | null | null | null | 78.668471 | 7,029 | 0.543312 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb47130f8559635f8d08228d7f217c1beef05c2f | 23,440 | ipynb | Jupyter Notebook | Time_Series/Part3_Time_Series_Data_Pivot_Tables_Interaction.ipynb | mrpal39/Python_Tutorials | b245f0d219684eaf09c26a13442ad25c7a986dd2 | [
"MIT"
] | 1,040 | 2016-08-07T02:27:28.000Z | 2022-03-30T02:31:40.000Z | Time_Series/Part3_Time_Series_Data_Pivot_Tables_Interaction.ipynb | mrpal39/Python_Tutorials | b245f0d219684eaf09c26a13442ad25c7a986dd2 | [
"MIT"
] | 16 | 2017-09-18T05:39:52.000Z | 2022-01-28T20:40:43.000Z | Time_Series/Part3_Time_Series_Data_Pivot_Tables_Interaction.ipynb | mrpal39/Python_Tutorials | b245f0d219684eaf09c26a13442ad25c7a986dd2 | [
"MIT"
] | 1,102 | 2016-08-07T02:27:24.000Z | 2022-03-31T16:18:48.000Z | 31.211718 | 165 | 0.400171 | [
[
[
"<h1 align=\"center\"> Time Series Data Basics with Pandas Part 3: Price Variation from Pandas groupby </h1>",
"_____no_output_____"
],
[
"This code demonstrates how to \n\n**if this tutorial doesn't cover what you are looking for, please leave a comment below the youtube video and I will try to cover what you are interested in.**",
"_____no_output_____"
],
[
"<b> Part 1 </b>: Sampling, Rolling Mean (Smoothing), Linear Regression, Filtering, Join, plotting of a Time Series Pandas DataFrame <br>\nhttps://www.youtube.com/watch?v=OwnaUVt6VVE",
"_____no_output_____"
],
[
"<b> Part 2 </b>: Price Variation from Pandas GroupBy <br>\nhttps://www.youtube.com/watch?v=1S5UKLqe-gg",
"_____no_output_____"
],
[
"<h3 align='Left'> Importing Libraries</h3>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport pandas_datareader.data as web\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"<h3 align='Left'> Getting Data and Viewing with Pandas </h3>",
"_____no_output_____"
]
],
[
[
"# https://pandas-datareader.readthedocs.io/en/latest/remote_data.html\ngoogle = web.DataReader('GOOG', data_source = 'google', start = '3/14/2009', end = '4/14/2016')\ngoogle.head()",
"_____no_output_____"
]
],
[
[
"<h3 align='Left'> Getting Data and Viewing with Pandas </h3>",
"_____no_output_____"
]
],
[
[
"google_date = google.groupby(pd.TimeGrouper(freq='M')).mean()\ngoogle_date.head()",
"_____no_output_____"
],
[
"google_date = google_date.reset_index()\ngoogle_date.head()",
"_____no_output_____"
],
[
"pd.DataFrame(data = google_date.dropna())",
"_____no_output_____"
],
[
"from IPython.html import widgets\nfrom IPython.display import display\n\ngeo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}\n\ndef print_city(city):\n print city\n\ndef select_city(country):\n cityW.options = geo[country]\n\n\nscW = widgets.Select(options=geo.keys())\ninit = scW.value\ncityW = widgets.Select(options=geo[init])\nj = widgets.interactive(print_city, city=cityW)\ni = widgets.interactive(select_city, country=scW)\ndisplay(i)\ndisplay(j)",
"MOW\n"
],
[
"from __future__ import print_function\nfrom ipywidgets import interact, interactive, fixed\nimport ipywidgets as widgets\ndef f(x):\n return x\n\ninteract(f, x=('apples','oranges'));",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb471c0cc3713ecc01744227bbb87c7cb159e536 | 473,227 | ipynb | Jupyter Notebook | Data Preprocecing.ipynb | preyash2047/Hindi_chat_bot | 1e2ff4f3f15abcee5219951031f22bd86e753549 | [
"MIT"
] | null | null | null | Data Preprocecing.ipynb | preyash2047/Hindi_chat_bot | 1e2ff4f3f15abcee5219951031f22bd86e753549 | [
"MIT"
] | null | null | null | Data Preprocecing.ipynb | preyash2047/Hindi_chat_bot | 1e2ff4f3f15abcee5219951031f22bd86e753549 | [
"MIT"
] | null | null | null | 37.435883 | 1,382 | 0.53207 | [
[
[
"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport time\nimport csv\nimport os\nimport shutil\nimport codecs\nimport pandas as pd\nimport numpy as np\nimport random",
"_____no_output_____"
],
[
"data = r'C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)'\nfile_paths = []\n#loop to get append file_paths \nfor root, directories, files in os.walk(data):\n for filename in files:\n if \".html\" in filename:\n # Join the two strings in order to form the full filepath.\n filepath = os.path.join(root, filename)\n #to append\n file_paths.append(filepath)",
"_____no_output_____"
],
[
"messages = []\nfor file in file_paths: \n soup = BeautifulSoup(codecs.open(file, 'r', \"utf-8\").read())\n messages.extend(soup.findAll('div', attrs={'class':'message default clearfix'}))\n messages.extend(soup.findAll('div', attrs={'class':'message default clearfix joined'}))\n \nprint(len(contents))",
"4500\n"
],
[
"current_ids, previous_ids, message_texts,message_statuses = [],[],[],[]\n\nfor meg in messages:\n current_id = meg.get(\"id\")[7:]\n current_id = int(current_id)\n \n try:\n previous_id = meg.find(\"div\", {\"class\":\"reply_to details\"}).a.get(\"href\")[14:]\n previous_id = int(previous_id)\n except:\n previous_id = 0\n \n try:\n message_text = meg.find(\"div\", {\"class\":\"description\"})\n message_text = message_text.text.strip()\n except:\n try:\n message_text = meg.find(\"div\", {\"class\":\"text\"})\n message_text = message_text.text.strip()\n except:\n continue\n \n try:\n message_status = meg.find(\"div\", {\"class\":\"status details\"})\n message_status = message_status.text.strip().split(\",\")[0]\n except:\n message_status = None\n \n if \"Not included, change data exporting settings to download.\" not in message_text and \"/\" not in message_text and \"Try command /\" not in message_text:\n current_ids.append(current_id)\n previous_ids.append(previous_id)\n message_texts.append(message_text)\n message_statuses.append(message_status)",
"_____no_output_____"
],
[
"dataset = pd.DataFrame({\n \"current_id\":current_ids,\n \"previous_id\":previous_ids,\n \"message_text\":message_texts,\n \"message_status\":message_statuses\n })",
"_____no_output_____"
],
[
"np.sum(dataset.isnull())",
"_____no_output_____"
],
[
"def readPreviousMain(currentID):\n pm = dataset[dataset[\"previous_id\"] == currentID].iloc[:,2].values\n pm = str(pm)\n\n cm = dataset[dataset[\"current_id\"] == currentID].iloc[:,2].values\n cm = str(cm)\n\n print(\"Previous Message: \", pm)\n print(\"Current Message: \", cm)",
"_____no_output_____"
],
[
"readPreviousMain(5500021)",
"Previous Message: []\nCurrent Message: ['I m also free You got free from ?']\n"
],
[
"readPreviousMain(5500036)",
"Previous Message: []\nCurrent Message: ['Hi']\n"
],
[
"readPreviousMain(5500023)",
"Previous Message: ['Chhii Omg']\nCurrent Message: ['Vo to funny hai sirf 😂🙈👀']\n"
],
[
"dataset.to_csv(r'C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)\\dataset.csv')",
"_____no_output_____"
],
[
"dataset.to_csv(r'C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)\\dataset.csv')",
"_____no_output_____"
],
[
"dataset = pd.read_csv(r\"C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)\\dataset.csv\")\ndataset = dataset.iloc[:,1:]",
"_____no_output_____"
],
[
"messages_set = list(set(dataset.message_text))\nexclude_text = [\"bet\", \"Level\", \"YOUR PROFILE Messages sent here\",\"LEADERBOARD\",\"Local\",\"City | Informations\",\"Статистика пользователя\" , \"Report\", \"coinsOh no!\",\"Status | Informations of\" ,\"coins\", \"\\\\u\"]\n\nfinal_messages_set = []\nfor i in messages_set:\n valid = True\n for j in exclude_text:\n if j in i:\n valid = False\n if valid:\n final_messages_set.append(i)\n \n#removing only usernames\nfinal_messages_set = [i for i in final_messages_set if i[0] != \"@\" and len(i.split(\" \")) != 1] \nlen(final_messages_set)",
"_____no_output_____"
],
[
"def readPreviousMain(currentID):\n question = dataset[dataset[\"previous_id\"] == currentID]\n question_str = str(question.message_text.values[0])\n if question.message_status.isna().bool() == False:\n question_str += \" \" + str(question.message_status.values[0])\n\n ans = dataset[dataset[\"current_id\"] == currentID]\n ans_str = str(ans.message_text.values[0])\n if ans.message_status.isna().bool() == False:\n ans_str += \" \" + str(ans.message_status.values[0])\n \n #print(\"Previous Message: \", question_str)\n #print(\"Current Message: \", ans_str)\n return question_str, ans_str",
"_____no_output_____"
],
[
"question_message_text = []\nans_message_text = []\nfor message in final_messages_set:\n temp_dataset = dataset[dataset[\"message_text\"] == message]\n try:\n q, a = readPreviousMain(int(temp_dataset.current_id.values[0]))\n question_message_text.append(q)\n ans_message_text.append(a)\n except:\n pass",
"_____no_output_____"
],
[
"output = pd.DataFrame({\n \"question_message_text\": question_message_text,\n \"ans_message_text\":ans_message_text\n})\noutput.to_csv(r\"C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)\\question_and_answer.csv\")",
"_____no_output_____"
],
[
"len(question_message_text)",
"_____no_output_____"
]
],
[
[
"DilogFlow",
"_____no_output_____"
]
],
[
[
"def create_intent(project_id, display_name, training_phrases_parts, message_texts):\n \"\"\"Create an intent of the given intent type.\"\"\"\n from google.cloud import dialogflow\n\n intents_client = dialogflow.IntentsClient()\n\n parent = dialogflow.AgentsClient.agent_path(project_id)\n training_phrases = []\n for training_phrases_part in training_phrases_parts:\n part = dialogflow.Intent.TrainingPhrase.Part(text=training_phrases_part)\n # Here we create a new training phrase for each provided part.\n training_phrase = dialogflow.Intent.TrainingPhrase(parts=[part])\n training_phrases.append(training_phrase)\n\n text = dialogflow.Intent.Message.Text(text=message_texts)\n message = dialogflow.Intent.Message(text=text)\n\n intent = dialogflow.Intent(\n display_name=display_name, training_phrases=training_phrases, messages=[message]\n )\n\n response = intents_client.create_intent(\n request={\"parent\": parent, \"intent\": intent}\n )\n\n print(\"Intent created: {}\".format(response))\n \n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"hindienglishchatbot-3d57939ede44.json\"",
"_____no_output_____"
],
[
"question_ans = pd.read_csv(r\"C:\\Users\\preya\\Downloads\\Telegram Desktop\\ChatExport_2021-06-27 (1)\\question_and_answer.csv\")\nquestion_ans = question_ans.iloc[:,1:]\nquestion_ans",
"_____no_output_____"
],
[
"training_phrases_parts = [\"who is developer of this?\", \"who has developed it\", \"who is admin name\", \"who is admin of this\"]\nmessage_texts = [\"Preyash Patel is our developer, here you can talk with him https://www.linkedin.com/in/preyash2047/\"]\ncreate_intent(\n project_id=\"hindienglishchatbot\",\n display_name=\"about\",\n training_phrases_parts = training_phrases_parts,\n message_texts = message_texts\n)",
"Intent created: name: \"projects/hindienglishchatbot/agent/intents/187689ea-729c-4422-aa02-d28c6a8ddd62\"\ndisplay_name: \"about\"\npriority: 500000\nmessages {\n text {\n text: \"Preyash Patel is our developer, here you can talk with him https://www.linkedin.com/in/preyash2047/\"\n }\n}\n\n"
],
[
"for i in range(len(question_ans)): \n training_phrases_parts = [question_ans.iloc[i,0]]\n message_texts = [question_ans.iloc[i,1]]\n create_intent(\n project_id=\"hindienglishchatbot\",\n display_name=\"intent_\" + str(i),\n training_phrases_parts = training_phrases_parts,\n message_texts = message_texts\n )\n time.sleep(random.randint(5,10))",
"Intent created: name: \"projects/hindienglishchatbot/agent/intents/189540eb-8aaa-4120-8961-ddccf186e091\"\ndisplay_name: \"intent_0\"\npriority: 500000\nmessages {\n text {\n text: \"Kaha rhte hai not rhta hoo\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/e7b3653a-31d9-4101-a57a-cf7b56761a77\"\ndisplay_name: \"intent_1\"\npriority: 500000\nmessages {\n text {\n text: \"report kar diye h don\\'t worry\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/5a51c1a7-0095-4119-ad1f-7a542fa19025\"\ndisplay_name: \"intent_2\"\npriority: 500000\nmessages {\n text {\n text: \"It will take years \\360\\237\\230\\202\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/0672ed11-fe44-40cf-91c0-b193bb8bbce4\"\ndisplay_name: \"intent_3\"\npriority: 500000\nmessages {\n text {\n text: \"\\360\\235\\230\\211\\360\\235\\230\\260\\360\\235\\230\\255\\360\\235\\230\\242 \\360\\235\\230\\257\\360\\235\\230\\242, \\360\\235\\230\\256\\360\\235\\230\\266\\360\\235\\230\\253\\360\\235\\230\\251\\360\\235\\230\\246 \\360\\235\\230\\254\\360\\235\\230\\252\\360\\235\\230\\264\\360\\235\\230\\252 \\360\\235\\230\\264\\360\\235\\230\\246 \\360\\235\\230\\243\\360\\235\\230\\251\\360\\235\\230\\252 \\360\\235\\230\\261\\360\\235\\230\\263\\360\\235\\230\\264\\360\\235\\230\\257\\360\\235\\230\\255 \\360\\235\\230\\261\\360\\235\\230\\246\\360\\235\\230\\263 \\360\\235\\230\\243\\360\\235\\230\\242\\360\\235\\230\\242\\360\\235\\230\\265 \\360\\235\\230\\257\\360\\235\\230\\251\\360\\235\\230\\252 \\360\\235\\230\\254\\360\\235\\230\\263\\360\\235\\230\\257\\360\\235\\230\\252 \\360\\237\\230\\220\\360\\237\\230\\220\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/4796c721-d0ca-4b10-8074-5d023f1b8ceb\"\ndisplay_name: \"intent_4\"\npriority: 500000\nmessages {\n text {\n text: \"\\340\\244\\254\\340\\244\\271\\340\\244\\250 \\340\\244\\225\\340\\244\\276 ....\\340\\244\\255\\340\\244\\276\\340\\244\\210 \\340\\244\\271\\340\\245\\210\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/6688f20e-c959-415d-b95a-a9cc3e4da572\"\ndisplay_name: \"intent_5\"\npriority: 500000\nmessages {\n text {\n text: \"No.... But this is awesome\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/1312e3c3-e0f5-4a58-bb05-4651bf0979a1\"\ndisplay_name: \"intent_6\"\npriority: 500000\nmessages {\n text {\n text: \"Ghr pe hogi\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/7fa6aa4d-b24f-484f-bbe1-ebc9c70c6b8a\"\ndisplay_name: \"intent_7\"\npriority: 500000\nmessages {\n text {\n text: \"Khana kha liya?\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/24936157-c031-498a-a125-830367b64c89\"\ndisplay_name: \"intent_8\"\npriority: 500000\nmessages {\n text {\n text: \"Sb ni hote\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/9632f656-0cd5-483f-b283-d909b5dbfe26\"\ndisplay_name: \"intent_9\"\npriority: 500000\nmessages {\n text {\n text: \"Okk good I am from India\\360\\237\\230\\212\\360\\237\\230\\212\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/f6466a66-dbd2-4b19-9e77-fff36ca8387c\"\ndisplay_name: \"intent_10\"\npriority: 500000\nmessages {\n text {\n text: \"The issue with some people\\'s brain, trying to figure out my life and trying to figure out why you are stubborn?\\360\\237\\231\\202\\360\\237\\230\\202\\360\\237\\230\\202\\360\\237\\230\\202\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/9ffc01e2-c046-4d01-8c53-c5faeaa9fd88\"\ndisplay_name: \"intent_11\"\npriority: 500000\nmessages {\n text {\n text: \"People know about it!\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/b9391b4a-6591-421b-9b67-d7a7bc084153\"\ndisplay_name: \"intent_12\"\npriority: 500000\nmessages {\n text {\n text: \"Teacher dhund rahe ho kya apne liye?\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/ba0de4ef-ce78-4e1b-a970-1bee09fefda8\"\ndisplay_name: \"intent_13\"\npriority: 500000\nmessages {\n text {\n text: \"\\360\\237\\230\\212i don\\'t know whether u remember or not...My old name was Sud\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/b91f6cd6-9cbf-4a73-b6d8-b555361af6c6\"\ndisplay_name: \"intent_14\"\npriority: 500000\nmessages {\n text {\n text: \"U ignore me :(\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/3e930e63-1d36-4f67-b6a5-07ef793cdea6\"\ndisplay_name: \"intent_15\"\npriority: 500000\nmessages {\n text {\n text: \"You are no\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/61b841f6-1108-4532-ac3e-dc694478991d\"\ndisplay_name: \"intent_16\"\npriority: 500000\nmessages {\n text {\n text: \"Or else i will bite ur nose\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/bb6de6ae-1bab-4e09-ab7d-8eaa27edef30\"\ndisplay_name: \"intent_17\"\npriority: 500000\nmessages {\n text {\n text: \"Ha pta hai \\360\\237\\230\\220\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/0035d078-0c37-418e-82d2-41729f360620\"\ndisplay_name: \"intent_18\"\npriority: 500000\nmessages {\n text {\n text: \"Ha vahi to na thodi der pahle discussion chal raha tha anu aur vedika ke bich me to anu bhai says jisko ban kare aur mute kare usko batao mat\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/62605047-5c05-479b-af47-5edb47b150f7\"\ndisplay_name: \"intent_19\"\npriority: 500000\nmessages {\n text {\n text: \"bro aise bolte sab yaha so kisi se expect mt karo kuch\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/3889a44b-e088-42fd-971c-ec026318b51b\"\ndisplay_name: \"intent_20\"\npriority: 500000\nmessages {\n text {\n text: \"Study u\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/e919db94-ab8c-40fd-ba09-3b3b9ea18fdd\"\ndisplay_name: \"intent_21\"\npriority: 500000\nmessages {\n text {\n text: \"Yet to do...N u?\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/ef0eefb2-d357-4b71-8161-d1d796a51632\"\ndisplay_name: \"intent_22\"\npriority: 500000\nmessages {\n text {\n text: \"Saste nashe\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/7a4428ce-3f38-4959-a831-93e6b2b8a883\"\ndisplay_name: \"intent_23\"\npriority: 500000\nmessages {\n text {\n text: \"Aise hi sticker irritation types h\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/3d64013f-9272-44f9-9ec8-3fa9af74997a\"\ndisplay_name: \"intent_24\"\npriority: 500000\nmessages {\n text {\n text: \"I am uzbek\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/d5711712-36a6-4ccc-93ec-f7dcf6292424\"\ndisplay_name: \"intent_25\"\npriority: 500000\nmessages {\n text {\n text: \"Koj yog neeg txawj ntse.\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/f8cef451-1294-43c2-9d5b-0800457f3997\"\ndisplay_name: \"intent_26\"\npriority: 500000\nmessages {\n text {\n text: \"Ek warn to banta h\\360\\237\\230\\202\\360\\237\\230\\202\\360\\237\\230\\202\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/de27aefe-3048-4851-a255-bf3d839ea6a7\"\ndisplay_name: \"intent_27\"\npriority: 500000\nmessages {\n text {\n text: \"Music player m gana konsa bj rha h ? \\360\\237\\245\\272\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/89d28e42-4cb1-4e64-a9de-c056ec97b81c\"\ndisplay_name: \"intent_28\"\npriority: 500000\nmessages {\n text {\n text: \"the pain \\360\\237\\230\\225\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/ee33185f-b99f-4ec2-bbd6-6294e366e178\"\ndisplay_name: \"intent_29\"\npriority: 500000\nmessages {\n text {\n text: \"Thank u\\360\\237\\230\\255\\360\\237\\230\\255\\360\\237\\230\\255\\360\\237\\230\\255\\360\\237\\230\\255\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/df5f8485-7861-4526-987c-4cd49481399b\"\ndisplay_name: \"intent_30\"\npriority: 500000\nmessages {\n text {\n text: \"Hlo Nita \\360\\237\\230\\212\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/03a3edc3-aba0-4a9c-b59a-49ec36140c4b\"\ndisplay_name: \"intent_31\"\npriority: 500000\nmessages {\n text {\n text: \"Mujhe samjh nhi aaya\\360\\237\\230\\205\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/0ee71e6c-09de-459b-a063-2b4d1c0896cb\"\ndisplay_name: \"intent_32\"\npriority: 500000\nmessages {\n text {\n text: \"Ni yaar , gym se aaya hu abhii,\"\n }\n}\n\nIntent created: name: \"projects/hindienglishchatbot/agent/intents/d7d14f24-0504-4516-9a01-356d066dc26f\"\ndisplay_name: \"intent_33\"\npriority: 500000\nmessages {\n text {\n text: \"Uske piche kuyu padha hai tu? She is getting irritated\"\n }\n}\n\n"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb4720ac932f2f3a94cc6e123e717fbb316189e0 | 170,692 | ipynb | Jupyter Notebook | Question_11_20/solutions_py/solution_016.ipynb | tsutaj/Gasyori100knock | 3b78839cf2218259d9a943b26c28312cf19b4648 | [
"MIT"
] | 1 | 2020-09-11T10:08:04.000Z | 2020-09-11T10:08:04.000Z | Question_11_20/solutions_py/solution_016.ipynb | tsutaj/Gasyori100knock | 3b78839cf2218259d9a943b26c28312cf19b4648 | [
"MIT"
] | null | null | null | Question_11_20/solutions_py/solution_016.ipynb | tsutaj/Gasyori100knock | 3b78839cf2218259d9a943b26c28312cf19b4648 | [
"MIT"
] | null | null | null | 1,471.482759 | 99,020 | 0.95936 | [
[
[
"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"img = cv2.cvtColor(cv2.imread(\"../imori.jpg\"), cv2.COLOR_BGR2GRAY)\nH, W = img.shape\nplt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\nplt.show()",
"_____no_output_____"
],
[
"pad = 1\nK = 3\nK_v = [ [1, 2, 1], [0, 0, 0], [-1, -2, -1] ]\nK_h = [ [1, 0, -1], [2, 0, -2], [1, 0, -1] ]\n\ntmp_img = np.zeros((H+2*pad, W+2*pad))\ntmp_img[pad:pad+H, pad:pad+W] = img.copy()\noutput_img_h = tmp_img.copy()\noutput_img_v = tmp_img.copy()\n\nfor i in range(H):\n for j in range(W):\n output_img_h[i+pad, j+pad] = np.sum(K_h * tmp_img[i:i+K, j:j+K])\n output_img_v[i+pad, j+pad] = np.sum(K_v * tmp_img[i:i+K, j:j+K])\n \noutput_img_h = np.clip(output_img_h, 0, 255).astype(\"uint8\")\noutput_img_v = np.clip(output_img_v, 0, 255).astype(\"uint8\")",
"_____no_output_____"
],
[
"plt.subplot(1, 2, 1)\nplt.imshow(output_img_h, cmap=\"gray\")\nplt.title(\"horizontal\")\nplt.subplot(1, 2, 2)\nplt.imshow(output_img_v, cmap=\"gray\")\nplt.title(\"vertical\")\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
cb4723b71dee26d93c0672f80a017928e0c3c31e | 3,441 | ipynb | Jupyter Notebook | notebooks/03-00 Introduction to Numpy.ipynb | Mohitsharma44/ucsl17 | 389206c8bbd5f4f0dd6d27d954aff0bdc3395c7f | [
"MIT"
] | 17 | 2017-06-12T04:08:07.000Z | 2020-12-08T06:34:21.000Z | notebooks/03-00 Introduction to Numpy.ipynb | Mohitsharma44/ucsl17 | 389206c8bbd5f4f0dd6d27d954aff0bdc3395c7f | [
"MIT"
] | null | null | null | notebooks/03-00 Introduction to Numpy.ipynb | Mohitsharma44/ucsl17 | 389206c8bbd5f4f0dd6d27d954aff0bdc3395c7f | [
"MIT"
] | 18 | 2017-06-12T14:19:28.000Z | 2020-10-11T06:52:23.000Z | 42.481481 | 593 | 0.661436 | [
[
[
"## 03 - 00 Introduction to Numpy\n`Numpy` (Numerical Python) is an opensource library for performing scientific computation in python. Numpy lets you work with arrays and matrices in a natural way unlike lists where you have to loop through individual elements to perform any numerical operation. \n> This would probably be a good time to refresh your memory on what are arrays and matrices.. here is something that you need to know to get started\n> - Arrays are simply a collection of values of *same type* indexed by integers.\n> - Matrices are defined to be multi-dimensional array indexed by rows, columns and dimensions.\n\nThe methods in numpy are designed with high performance in mind. Numpy arrays are stored more efficiently than an equivalent data structure in python such as lists and arrays. This especially pays off when you are using really large arrays (i.e large data sets). The major portion of numpy is written in C and thus the computations are faster than the pure python code. Numpy is one of the part of the scientific stack in Python. It actually used to be a part of major scientific package called SciPy but was later separated and now scipy uses numpy for almost all of its major tasks.\n\nNumpy is a very huge topic and we will barely scratch the surface in this bootcamp but it will be enough to get you all up to speed for starting with your Master's courseworks. \n\nIn this module (and sub-modules) we will be looking at ways for effectively loading, storing, and manipulating in-memory. We will be dealing with some of the datasets comprising of wide range of sources such as images, sound clips, text data etc. but to reach that stage, lets first get a working understanding of `Numpy Arrays`.\n\nNumpy is a third party module that has been installed for you here on UCSLHUB. Before we can begin using Numpy, we have to first `import` it in python. You must remember from the File IO module where we imported built-in csv module. Similarly, to import numpy module, you can type",
"_____no_output_____"
]
],
[
[
"import numpy as np\nprint(np.__version__)",
"1.19.2\n"
]
],
[
[
"We use `import numpy as np` so that we wont have to type `numpy` everytime we want to use the module, instead we can use `np`.\n\nA gentle reminder to use tab-completion(`<TAB>`) and `?` to explore and access the documentation for anything that you are looking for.\n\nExample:\n```ipython\nIn [1]: np.<TAB>\n```\nor \n```ipython\nIn [2]: np.__version__?\n```",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb47316478a02a089c38a23051aa36043ff79664 | 150,439 | ipynb | Jupyter Notebook | Phase_1/ds-pandas_dataframes-main/data_manipulation_plotting_pandas.ipynb | ismizu/ds-east-042621-lectures | 3d962df4d3cb19a4d0c92c8246ec251a5969f644 | [
"MIT"
] | 1 | 2021-08-12T21:48:21.000Z | 2021-08-12T21:48:21.000Z | Phase_1/ds-pandas_dataframes-main/data_manipulation_plotting_pandas.ipynb | ismizu/ds-east-042621-lectures | 3d962df4d3cb19a4d0c92c8246ec251a5969f644 | [
"MIT"
] | null | null | null | Phase_1/ds-pandas_dataframes-main/data_manipulation_plotting_pandas.ipynb | ismizu/ds-east-042621-lectures | 3d962df4d3cb19a4d0c92c8246ec251a5969f644 | [
"MIT"
] | null | null | null | 44.12995 | 21,328 | 0.548541 | [
[
[
"# Data Manipulation and Plotting with `pandas`",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"## Learning Goals\n\n- Load .csv files into `pandas` DataFrames\n- Describe and manipulate data in Series and DataFrames\n- Visualize data using DataFrame methods and `matplotlib`",
"_____no_output_____"
],
[
"## What is Pandas?\n\nPandas, as [the Anaconda docs](https://docs.anaconda.com/anaconda/packages/py3.7_osx-64/) tell us, offers us \"High-performance, easy-to-use data structures and data analysis tools.\" It's something like \"Excel for Python\", but it's quite a bit more powerful.",
"_____no_output_____"
],
[
"Let's read in the heart dataset.\n\nPandas has many methods for reading different types of files. Note that here we have a .csv file.\n\nRead about this dataset [here](https://www.kaggle.com/ronitf/heart-disease-uci).",
"_____no_output_____"
]
],
[
[
"heart_df = pd.read_csv('heart.csv')",
"_____no_output_____"
]
],
[
[
"The output of the `.read_csv()` function is a pandas *DataFrame*, which has a familiar tabaular structure of rows and columns.",
"_____no_output_____"
]
],
[
[
"type(heart_df)",
"_____no_output_____"
],
[
"heart_df",
"_____no_output_____"
]
],
[
[
"## DataFrames and Series\n\nTwo main types of pandas objects are the DataFrame and the Series, the latter being in effect a single column of the former:",
"_____no_output_____"
]
],
[
[
"age_series = heart_df['age']\ntype(age_series)",
"_____no_output_____"
]
],
[
[
"Notice how we can isolate a column of our DataFrame simply by using square brackets together with the name of the column.",
"_____no_output_____"
],
[
"Both Series and DataFrames have an *index* as well:",
"_____no_output_____"
]
],
[
[
"heart_df.index",
"_____no_output_____"
],
[
"age_series.index",
"_____no_output_____"
]
],
[
[
"Pandas is built on top of NumPy, and we can always access the NumPy array underlying a DataFrame using `.values`.",
"_____no_output_____"
]
],
[
[
"heart_df.values",
"_____no_output_____"
]
],
[
[
"## Basic DataFrame Attributes and Methods",
"_____no_output_____"
],
[
"### `.head()`",
"_____no_output_____"
]
],
[
[
"heart_df.head()",
"_____no_output_____"
]
],
[
[
"### `.tail()`",
"_____no_output_____"
]
],
[
[
"heart_df.tail()",
"_____no_output_____"
]
],
[
[
"### `.info()`",
"_____no_output_____"
]
],
[
[
"heart_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 303 entries, 0 to 302\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 age 303 non-null int64 \n 1 sex 303 non-null int64 \n 2 cp 303 non-null int64 \n 3 trestbps 303 non-null int64 \n 4 chol 303 non-null int64 \n 5 fbs 303 non-null int64 \n 6 restecg 303 non-null int64 \n 7 thalach 303 non-null int64 \n 8 exang 303 non-null int64 \n 9 oldpeak 303 non-null float64\n 10 slope 303 non-null int64 \n 11 ca 303 non-null int64 \n 12 thal 303 non-null int64 \n 13 target 303 non-null int64 \ndtypes: float64(1), int64(13)\nmemory usage: 33.3 KB\n"
]
],
[
[
"### `.describe()`",
"_____no_output_____"
]
],
[
[
"heart_df.describe()\n#Provides statistical data on the file data",
"_____no_output_____"
]
],
[
[
"### `.dtypes`",
"_____no_output_____"
]
],
[
[
"heart_df.dtypes",
"_____no_output_____"
]
],
[
[
"### `.shape`",
"_____no_output_____"
]
],
[
[
"heart_df.shape",
"_____no_output_____"
]
],
[
[
"### Exploratory Plots",
"_____no_output_____"
],
[
"Let's make ourselves a histogram of ages:",
"_____no_output_____"
]
],
[
[
"sns.set_style('darkgrid')\nsns.distplot(a=heart_df['age']);",
"C:\\Users\\IM\\anaconda3\\lib\\site-packages\\seaborn\\distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n"
]
],
[
[
"And while we're at it let's do a scatter plot of maximum heart rate vs. age:",
"_____no_output_____"
]
],
[
[
"sns.scatterplot(x=heart_df['age'], y=heart_df['thalach']);",
"_____no_output_____"
]
],
[
[
"## Adding to a DataFrame\n\n\n### Adding Rows\n\nHere are two rows that our engineer accidentally left out of the .csv file, expressed as a Python dictionary:",
"_____no_output_____"
]
],
[
[
"extra_rows = {'age': [40, 30], 'sex': [1, 0], 'cp': [0, 0], 'trestbps': [120, 130],\n 'chol': [240, 200],\n 'fbs': [0, 0], 'restecg': [1, 0], 'thalach': [120, 122], 'exang': [0, 1],\n 'oldpeak': [0.1, 1.0], 'slope': [1, 1], 'ca': [0, 1], 'thal': [2, 3],\n 'target': [0, 0]}\nextra_rows",
"_____no_output_____"
]
],
[
[
"How can we add this to the bottom of our dataset?",
"_____no_output_____"
]
],
[
[
"# Let's first turn this into a DataFrame.\n# We can use the .from_dict() method.\n\nmissing = pd.DataFrame(extra_rows)\nmissing",
"_____no_output_____"
],
[
"# Now we just need to concatenate the two DataFrames together.\n# Note the `ignore_index` parameter! We'll set that to True.\n\nheart_augmented = pd.concat([heart_df, missing],\n ignore_index=True)",
"_____no_output_____"
],
[
"# Let's check the end to make sure we were successful!\n\nheart_augmented.tail()",
"_____no_output_____"
]
],
[
[
"### Adding Columns\n\nAdding a column is very easy in `pandas`. Let's add a new column to our dataset called \"test\", and set all of its values to 0.",
"_____no_output_____"
]
],
[
[
"heart_augmented['test'] = 0",
"_____no_output_____"
],
[
"heart_augmented.head()",
"_____no_output_____"
]
],
[
[
"I can also add columns whose values are functions of existing columns.\n\nSuppose I want to add the cholesterol column (\"chol\") to the resting systolic blood pressure column (\"trestbps\"):",
"_____no_output_____"
]
],
[
[
"heart_augmented['chol+trestbps'] = heart_augmented['chol'] + heart_augmented['trestbps']",
"_____no_output_____"
],
[
"heart_augmented.head()",
"_____no_output_____"
]
],
[
[
"## Filtering",
"_____no_output_____"
],
[
"We can use filtering techniques to see only certain rows of our data. If we wanted to see only the rows for patients 70 years of age or older, we can simply type:",
"_____no_output_____"
]
],
[
[
"heart_augmented[heart_augmented['age'] >= 70]",
"_____no_output_____"
]
],
[
[
"Use '&' for \"and\" and '|' for \"or\".",
"_____no_output_____"
],
[
"### Exercise\n\nDisplay the patients who are 70 or over as well as the patients whose trestbps score is greater than 170.",
"_____no_output_____"
]
],
[
[
"heart_augmented[(heart_augmented['age'] >= 70) | (heart_augmented['trestbps'] > 170)]",
"_____no_output_____"
]
],
[
[
"<details>\n <summary>Answer</summary>\n <code>heart_augmented[(heart_augmented['age'] >= 70) | (heart_augmented['trestbps'] > 170)]</code>\n </details>",
"_____no_output_____"
],
[
"### Exploratory Plot\n\nUsing the subframe we just made, let's make a scatter plot of their cholesterol levels vs. age and color by sex:",
"_____no_output_____"
]
],
[
[
"at_risk = heart_augmented[(heart_augmented['age'] >= 70) \\\n | (heart_augmented['trestbps'] > 170)]\n#the backslash figure allows you to break the line, but still continue it on the next\nsns.scatterplot(data=at_risk, x='age', y='chol', hue='sex');",
"_____no_output_____"
]
],
[
[
"### `.loc` and `.iloc`",
"_____no_output_____"
],
[
"We can use `.loc` to get, say, the first ten values of the age and resting blood pressure (\"trestbps\") columns:",
"_____no_output_____"
]
],
[
[
"heart_augmented.loc",
"_____no_output_____"
],
[
"heart_augmented.loc[:9, ['age', 'trestbps']]\n#Note that .loc is grabbing the endpoint as well. Instead of ending at that point. Potentially\n#because it is grabbing things by name and the index has a name of '9'",
"_____no_output_____"
]
],
[
[
"`.iloc` is used for selecting locations in the DataFrame **by number**:",
"_____no_output_____"
]
],
[
[
"heart_augmented.iloc",
"_____no_output_____"
],
[
"heart_augmented.iloc[3, 0]",
"_____no_output_____"
]
],
[
[
"### Exercise\n\nHow would we get the same slice as just above by using .iloc() instead of .loc()?",
"_____no_output_____"
]
],
[
[
"heart_augmented.iloc[:10, [0,3]]",
"_____no_output_____"
]
],
[
[
"<details>\n <summary>Answer</summary>\n <code>heart_augmented.iloc[:10, [0, 3]]</code>\n </details>",
"_____no_output_____"
],
[
"## Statistics\n\n### `.mean()`",
"_____no_output_____"
]
],
[
[
"heart_augmented.mean()",
"_____no_output_____"
]
],
[
[
"Be careful! Some of these will are not straightforwardly interpretable. What does an average \"sex\" of 0.682 mean?",
"_____no_output_____"
],
[
"### `.min()`",
"_____no_output_____"
]
],
[
[
"heart_augmented.min()",
"_____no_output_____"
]
],
[
[
"### `.max()`",
"_____no_output_____"
]
],
[
[
"heart_augmented.max()",
"_____no_output_____"
]
],
[
[
"## Series Methods\n\n### `.value_counts()`\n\nHow many different values does have slope have? What about sex? And target?",
"_____no_output_____"
]
],
[
[
"heart_augmented['slope'].value_counts()",
"_____no_output_____"
]
],
[
[
"### `.sort_values()`",
"_____no_output_____"
]
],
[
[
"heart_augmented['age'].sort_values()",
"_____no_output_____"
]
],
[
[
"## `pandas`-Native Plotting\n\nThe `.plot()` and `.hist()` methods available for DataFrames use a wrapper around `matplotlib`:",
"_____no_output_____"
]
],
[
[
"heart_augmented.plot(x='age', y='trestbps', kind='scatter');",
"_____no_output_____"
],
[
"heart_augmented.hist(column='chol');",
"_____no_output_____"
]
],
[
[
"## Exercises",
"_____no_output_____"
],
[
"1. Make a bar plot of \"age\" vs. \"slope\" for the `heart_augmented` DataFrame.",
"_____no_output_____"
],
[
"<details>\n <summary>Answer</summary>\n <code>sns.barplot(data=heart_augmented, x='slope', y='age');</code>\n </details>",
"_____no_output_____"
],
[
"2. Make a histogram of ages for **just the men** in `heart_augmented` (heart_augmented['sex']=1).",
"_____no_output_____"
],
[
"<details>\n <summary>Answer</summary>\n<code>men = heart_augmented[heart_augmented['sex'] == 1]\nsns.distplot(a=men['age']);</code>\n </details>",
"_____no_output_____"
],
[
"3. Make separate scatter plots of cholesterol vs. resting systolic blood pressure for the target=0 and the target=1 groups. Put both plots on the same figure and give each an appropriate title.",
"_____no_output_____"
],
[
"<details>\n <summary>Answer</summary>\n<code>target0 = heart_augmented[heart_augmented['target'] == 0]\ntarget1 = heart_augmented[heart_augmented['target'] == 1]\nfig, ax = plt.subplots(1, 2, figsize=(10, 5))\nsns.scatterplot(data=target0, x='trestbps', y='chol', ax=ax[0])\nsns.scatterplot(data=target1, x='trestbps', y='chol', ax=ax[1])\nax[0].set_title('Cholesterol Vs. Resting Blood Pressure in Women')\n ax[1].set_title('Cholesterol Vs. Resting Blood Pressure in Men');</code>\n </details>",
"_____no_output_____"
],
[
"## Let's find a .csv file online and experiment with it.\n\nI'm going to head to [dataportals.org](https://dataportals.org) to find a .csv file.",
"_____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"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"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",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb473f95aeaa655fe4029f88bf60bfd9863080e5 | 456,112 | ipynb | Jupyter Notebook | KCWI/KCWI_calcs.ipynb | devincunningham/Black-Holes-and-Revelations | c0e8323d520681986b50eab3cf7a6dce45544670 | [
"MIT"
] | 1 | 2018-02-20T00:02:56.000Z | 2018-02-20T00:02:56.000Z | KCWI/KCWI_calcs.ipynb | devincunningham/Black-Holes-and-Revelations | c0e8323d520681986b50eab3cf7a6dce45544670 | [
"MIT"
] | null | null | null | KCWI/KCWI_calcs.ipynb | devincunningham/Black-Holes-and-Revelations | c0e8323d520681986b50eab3cf7a6dce45544670 | [
"MIT"
] | null | null | null | 637.918881 | 149,956 | 0.929647 | [
[
[
"# KCWI_calcs.ipynb",
"_____no_output_____"
],
[
"functions from Busola Alabi, Apr 2018",
"_____no_output_____"
]
],
[
[
"from __future__ import division\nimport glob\nimport re\nimport os, sys\nfrom astropy.io.fits import getheader, getdata\nfrom astropy.wcs import WCS\nimport astropy.units as u\nimport numpy as np\nfrom scipy import interpolate\nimport logging\nfrom time import time\nimport matplotlib.pyplot as plt\nfrom pylab import *\nimport matplotlib as mpl\nimport matplotlib.ticker as mtick\nfrom scipy.special import gamma",
"_____no_output_____"
],
[
"def make_obj(flux, grat_wave, f_lam_index):\n '''\n '''\n w = np.arange(3000)+3000.\n p_A = flux/(2.e-8/w)*(w/grat_wave)**f_lam_index\n\n return w, p_A\n\ndef inst_throughput(wave, grat):\n '''\n '''\n eff_bl = np.asarray([0.1825,0.38,0.40,0.46,0.47,0.44])\n eff_bm = np.asarray([0.1575, 0.33, 0.36, 0.42, 0.48, 0.45])\n eff_bh1 = np.asarray([0., 0.0, 0.0, 0.0, 0.0, 0.])\n eff_bh2 = np.asarray([0., 0.18, 0.3, 0.4, 0.28, 0.])\n eff_bh3 = np.asarray([0., 0., 0., 0.2, 0.29, 0.31])\n wave_0 = np.asarray([355.,380.,405.,450.,486.,530.])*10.\n wave_bl = np.asarray([355., 530.])*10.\n wave_bm = np.asarray([355., 530.])*10.\n wave_bh1 = np.asarray([350., 450.])*10.\n wave_bh2 = np.asarray([405., 486.])*10.\n wave_bh3 = np.asarray([405., 530.])*10.\n trans_atmtel = np.asarray([0.54, 0.55, 0.56, 0.56, 0.56, 0.55])\n\n if grat=='BL':\n eff = eff_bl*trans_atmtel\n wave_range = wave_bl\n\n if grat=='BM':\n eff = eff_bm*trans_atmtel\n wave_range = wave_bm\n\n if grat=='BH1':\n eff = eff_bh1*trans_atmtel\n wave_range = wave_bh1\n\n if grat=='BH2':\n eff = eff_bh2*trans_atmtel\n wave_range = wave_bh2\n\n if grat=='BH3':\n eff = eff_bh3*trans_atmtel\n wave_range = wave_bh3\n\n\n wave1 = wave\n interpfunc = interpolate.interp1d(wave_0, eff, fill_value=\"extrapolate\") #this is the only way I've gotten this interpolation to work\n eff_int = interpfunc(wave1)\n idx = np.where((wave1 <= wave_range[0]) | (wave1 > wave_range[1]))\n eff_int[idx] = 0.\n return eff_int\n\n\n\ndef obj_cts(w, f0, grat, exposure_time):\n '''\n '''\n A_geo = np.pi/4.*(10.e2)**2\n eff = inst_throughput(w, grat)\n cts = eff*A_geo*exposure_time*f0\n return cts\n\ndef sky(wave):\n '''\n '''\n with open('mk_sky.dat') as f:\n lines = (line for line in f if not line.startswith('#'))\n skydata = np.loadtxt(lines, skiprows=2)\n\n ws = skydata[:,0]\n fs = skydata[:,1]\n f_nu_data = getdata('lris_esi_skyspec_fnu_uJy.fits')\n f_nu_hdr = getheader('lris_esi_skyspec_fnu_uJy.fits')\n dw = f_nu_hdr[\"CDELT1\"]\n w0 = f_nu_hdr[\"CRVAL1\"]\n ns = len(fs)\n ws = np.arange(ns)*dw + w0\n f_lam = f_nu_data[:len(ws)]*1e-29*3.*1e18/ws/ws\n\n interpfunc = interpolate.interp1d(ws,f_lam, fill_value=\"extrapolate\")\n fs_int = interpfunc(wave)\n return fs_int\n\ndef sky_mk(wave):\n '''\n '''\n with open('mk_sky.dat') as f:\n lines = (line for line in f if not line.startswith('#'))\n skydata = np.loadtxt(lines, skiprows=2)\n\n ws = skydata[:,0]\n fs = skydata[:,1]\n f_nu_data = getdata('lris_esi_skyspec_fnu_uJy.fits')\n f_nu_hdr = getheader('lris_esi_skyspec_fnu_uJy.fits')\n dw = f_nu_hdr[\"CDELT1\"]\n w0 = f_nu_hdr[\"CRVAL1\"]\n ns = len(fs)\n ws = np.arange(ns)*dw + w0\n f_lam = f_nu_data[:len(ws)]*1e-29*3.*1e18/ws/ws\n p_lam = f_lam/(2.e-8/ws)\n\n interpfunc = interpolate.interp1d(ws,p_lam, fill_value=\"extrapolate\") #using linear since argument not set in idl\n ps_int = interpfunc(wave)\n return ps_int\n\ndef sky_cts(w, grat, exposure_time, airmass=1.2, area=1.0):\n '''\n '''\n A_geo = np.pi/4.*(10.e2)**2\n eff = inst_throughput(w, grat)\n cts = eff*A_geo*exposure_time*sky_mk(w)*airmass*area\n return cts",
"_____no_output_____"
],
[
"def ETC(slicer, grating, grat_wave, f_lam_index, seeing, exposure_time, ccd_bin, spatial_bin=[],\n spectral_bin=None, nas=True, sb=True, mag_AB=None, flux=None, Nframes=1, emline_width=None):\n\n\n \"\"\"\n Parameters\n ==========\n slicer: str\n L/M/S (Large, Medium or Small)\n grating: str\n BH1, BH2, BH3, BM, BL\n grating wavelength: float or int\n 3400. < ref_wave < 6000.\n f_lam_index: float\n source f_lam ~ lam^f_lam_index, default = 0\n seeing: float\n arcsec\n exposure_time: float\n seconds for source image (total) for all frames\n ccd_bin: str\n '1x1','2x2'\"\n spatial_bin: list\n [dx,dy] bin in arcsec x arcsec for binning extended emission flux. if sb=True then default is 1 x 1 arcsec^2'\n spectral_bin: float or int\n Ang to bin for S/N calculation, default=None\n nas: boolean\n nod and shuffle\n sb: boolean\n surface brightness m_AB in mag arcsec^2; flux = cgs arcsec^-2'\n mag_AB: float or int\n continuum AB magnitude at wavelength (ref_wave)'\n flux: float\n erg cm^-2 s^-1 Ang^1 (continuum source [total]); erg cm^-2 s^1 (point line source [total]) [emline = width in Ang]\n EXTENDED: erg cm^-2 s^-1 Ang^1 arcsec^-2 (continuum source [total]); erg cm^-2 s^1 arcsec^-2 (point line source [total]) [emline = width in Ang]\n Nframes: int\n number of frames (default is 1)\n emline_width: float\n flux is for an emission line, not continuum flux (only works for flux), and emission line width is emline_width Ang\n\n \"\"\"\n# logger = logging.getLogger(__name__)\n logger.info('Running KECK/ETC')\n t0 = time()\n slicer_OPTIONS = ('L', 'M','S')\n grating_OPTIONS = ('BH1', 'BH2', 'BH3', 'BM', 'BL')\n\n if slicer not in slicer_OPTIONS:\n raise ValueError(\"slicer must be L, M, or S, wrongly entered {}\".format(slicer))\n logger.info('Using SLICER=%s', slicer)\n\n if grating not in grating_OPTIONS:\n raise ValueError(\"grating must be L, M, or S, wrongly entered {}\".format(grating))\n logger.info('Using GRATING=%s', grating)\n\n if grat_wave < 3400. or grat_wave > 6000:\n raise ValueError('wrong value for grating wavelength')\n logger.info('Using reference wavelength=%.2f', grat_wave)\n\n if len(spatial_bin) != 2 and len(spatial_bin) !=0:\n raise ValueError('wrong spatial binning!!')\n logger.info('Using spatial binning, spatial_bin=%s', str(spatial_bin[0])+'x'+str(spatial_bin[1]))\n\n\n bin_factor = 1.\n if ccd_bin == '2x2':\n bin_factor = 0.25\n if ccd_bin == '2x2' and slicer == 'S':\n print'******** WARNING: DO NOT USE 2x2 BINNING WITH SMALL SLICER'\n read_noise = 2.7 # electrons\n Nf = Nframes\n\n chsz = 3 #what is this????\n nas_overhead = 10. #seconds per half cycle\n seeing1 = seeing\n seeing2 = seeing\n pixels_per_arcsec = 1./0.147\n if slicer == 'L':\n seeing2 = 1.38\n snr_spatial_bin = seeing1*seeing2\n pixels_spectral = 8\n arcsec_per_slice = 1.35\n\n if slicer == 'M':\n seeing2 = max(0.69,seeing)\n snr_spatial_bin = seeing1*seeing2\n pixels_spectral = 4\n arcsec_per_slice = 0.69\n if slicer == 'S':\n seeing2 = seeing\n snr_spatial_bin = seeing1*seeing2\n pixels_spectral = 2\n arcsec_per_slice = 0.35\n\n N_slices = seeing/arcsec_per_slice\n\n if len(spatial_bin) == 2:\n N_slices = spatial_bin[1]/arcsec_per_slice\n snr_spatial_bin = spatial_bin[0]*spatial_bin[1]\n\n pixels_spatial_bin = pixels_per_arcsec * N_slices\n print \"GRATING :\", grating\n\n if grating == 'BL':\n A_per_pixel = 0.625\n\n if grating == 'BM':\n A_per_pixel = 0.28\n\n if grating == 'BH2' or grating == 'BH3':\n A_per_pixel = 0.125\n\n print 'A_per_pixel', A_per_pixel\n\n logger.info('f_lam ~ lam = %.2f',f_lam_index)\n logger.info('SEEING: %.2f, %s', seeing, ' arcsec')\n logger.info('Ang/pixel: %.2f', A_per_pixel)\n logger.info('spectral pixels in 1 spectral resolution element: %.2f',pixels_spectral)\n\n A_per_spectral_bin = pixels_spectral*A_per_pixel\n\n logger.info('Ang/resolution element: =%.2f',A_per_spectral_bin)\n\n if spectral_bin is not None:\n snr_spectral_bin = spectral_bin\n else:\n snr_spectral_bin = A_per_spectral_bin\n\n logger.info('Ang/SNR bin: %.2f', snr_spectral_bin)\n pixels_per_snr_spec_bin = snr_spectral_bin/A_per_pixel\n logger.info('Pixels/Spectral SNR bin: %.2f', pixels_per_snr_spec_bin)\n logger.info('SNR Spatial Bin [arcsec^2]: %.2f', snr_spatial_bin)\n logger.info('SNR Spatial Bin [pixels^2]: %.2f', pixels_spatial_bin)\n\n flux1 = 0\n if flux is not None:\n flux1 = flux\n if flux is not None and emline_width is not None:\n flux1 = flux/emline_width\n if flux1 == 0 and emline_width is not None:\n raise ValueError('Dont use mag_AB for emission line')\n\n if mag_AB is not None:\n flux1 = (10**(-0.4*(mag_AB+48.6)))*(3.e18/grat_wave)/grat_wave\n\n w, p_A = make_obj(flux1,grat_wave, f_lam_index)\n\n if sb==False and mag_AB is not None:\n flux_input = ' mag_AB'\n logger.info('OBJECT mag: %.2f, %s', mag_AB,flux_input)\n\n if sb==True and mag_AB is not None:\n flux_input = ' mag_AB / arcsec^2'\n logger.info('OBJECT mag: %.2f, %s',mag_AB,flux_input)\n\n\n if flux is not None and sb==False and emline_width is None:\n flux_input = 'erg cm^-2 s^-1 Ang^-1'\n if flux is not None and sb==False and emline_width is not None:\n flux_input = 'erg cm^-2 s^-1 in '+ str(emline_width) +' Ang'\n if flux is not None and sb and emline_width is None:\n flux_input = 'erg cm^-2 s^-1 Ang^-1 arcsec^-2'\n if flux is not None and sb and emline_width is not None:\n flux_input = 'erg cm^-2 s^-1 arcsec^-2 in '+ str(emline_width) +' Ang'\n if flux is not None:\n logger.info('OBJECT Flux %.2f, %s',flux,flux_input)\n if emline_width is not None:\n logger.info('EMISSION LINE OBJECT --> flux is not per unit Ang')\n\n\n t_exp = exposure_time\n if nas==False:\n c_o = obj_cts(w,p_A,grating,t_exp)*snr_spatial_bin*snr_spectral_bin\n c_s = sky_cts(w,grating,exposure_time,airmass=1.2,area=1.0)*snr_spatial_bin*snr_spectral_bin\n c_r = Nf*read_noise**2*pixels_per_snr_spec_bin*pixels_spatial_bin*bin_factor\n snr = c_o/np.sqrt(c_s+c_o+c_r)\n\n\n if nas==True:\n n_cyc = np.floor((exposure_time-nas_overhead)/2./(nas+nas_overhead)+0.5)\n total_exposure = (2*n_cyc*(nas+nas_overhead))+nas_overhead\n logger.info('NAS: Rounding up to ',n_cyc, ' Cycles of NAS for total exposure of',total_exposure,' s')\n t_exp = n_cyc*nas\n c_o = obj_cts(w,p_A,grating,t_exp)*snr_spatial_bin*snr_spectral_bin\n c_s = sky_cts(w,grating,t_exp,airmass=1.2,area=1.0)*snr_spatial_bin*snr_spectral_bin\n c_r = 2.*Nf*read_noise**2*pixels_per_snr_spec_bin*pixels_spatial_bin*bin_factor\n snr = c_o/np.sqrt(2.*c_s+c_o+c_r)\n\n\n fig=figure(num=1, figsize=(12, 16), dpi=80, facecolor='w', edgecolor='k')\n subplots_adjust(hspace=0.001)\n\n ax0 = fig.add_subplot(611)\n ax0.plot(w, snr, 'k-')\n ax0.minorticks_on()\n ax0.tick_params(axis='both',which='minor',direction='in', length=5,width=2)\n ax0.tick_params(axis='both',which='major',direction='in', length=8,width=2,labelsize=8)\n ylabel('SNR / %.1f'%snr_spectral_bin+r'$\\rm \\ \\AA$', fontsize=12)\n\n ax1 = fig.add_subplot(612)\n ax1.plot(w,c_o, 'k--')\n ax1.minorticks_on()\n ax1.tick_params(axis='both',which='minor',direction='in',length=5,width=2)\n ax1.tick_params(axis='both',which='major',direction='in',length=8,width=2,labelsize=12)\n ylabel('Obj cts / %.1f'%snr_spectral_bin+r'$\\rm \\ \\AA$', fontsize=12)\n\n ax2 = fig.add_subplot(613)\n ax2.plot(w,c_s, 'k--')\n ax2.minorticks_on()\n ax2.tick_params(axis='both',which='minor',direction='in', length=5,width=2)\n ax2.tick_params(axis='both',which='major',direction='in', length=8,width=2,labelsize=12)\n ylabel('Sky cts / %.1f'%snr_spectral_bin+r'$\\rm \\ \\AA$', fontsize=12)\n\n ax3 = fig.add_subplot(614)\n ax3.plot(w,c_r*np.ones(len(w)), 'k--')\n ax3.minorticks_on()\n ax3.tick_params(axis='both',which='minor', direction='in', length=5,width=2)\n ax3.tick_params(axis='both',which='major', direction='in', length=8,width=2,labelsize=12)\n ylabel('Rd. Noise cts / %.1f'%snr_spectral_bin+r'$\\rm \\ \\AA$', fontsize=12)\n\n ax4 = fig.add_subplot(615)\n yval = w[c_s > 0]\n num = c_o[c_s > 0]\n den = c_s[c_s > 0]\n ax4.plot(yval, num/den, 'k--') #some c_s are zeros\n ax4.minorticks_on()\n xlim(min(w), max(w)) #only show show valid data!\n ax4.tick_params(axis='both',which='minor', direction='in', length=5,width=2)\n ax4.tick_params(axis='both',which='major', direction='in', length=8,width=2,labelsize=12)\n ylabel('Obj/Sky cts /%.1f'%snr_spectral_bin+r'$\\rm \\ \\AA$', fontsize=12)\n\n\n ax5 = fig.add_subplot(616)\n ax5.plot(w,p_A, 'k--')\n ax5.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))\n ax5.minorticks_on()\n ax5.tick_params(axis='both',which='minor',direction='in', length=5,width=2)\n ax5.tick_params(axis='both',which='major',direction='in', length=8,width=2,labelsize=12)\n\n ylabel('Flux ['r'$\\rm ph\\ cm^{-2}\\ s^{-1}\\ \\AA^{-1}$]', fontsize=12)\n xlabel('Wavelength ['r'$\\rm \\AA$]', fontsize=12)\n\n show()\n fig.savefig('{}.pdf'.format('KCWI_ETC_calc'), format='pdf', transparent=True, bbox_inches='tight')\n logger.info('KCWI/ETC run successful!')",
"_____no_output_____"
],
[
"logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s', stream=sys.stdout)\nlogger = logging.getLogger(__name__)",
"_____no_output_____"
],
[
"if __name__ == '__main__':\n\n print(\"KCWI/ETC...python version\")",
"KCWI/ETC...python version\n"
]
],
[
[
"Simulate DF44 observation, begin by figuring out Sérsic model conversions. \nSee toy_jeans4.ipynb for more detailed Sérsic calculations.",
"_____no_output_____"
]
],
[
[
"# n, R_e, M_g = 0.85, 7.1, 19.05 # van Dokkum+16 (van Dokkum+17 is slightly different)\nn, mu_0, a_e, R_e = 0.94, 24.2, 9.7, 7.9 # van Dokkum+17; some guesses\nb_n = 1.9992*n - 0.3271\nmu_m_e = mu_0 - 2.5*log10(n*exp(b_n)/b_n**(2.0*n)*gamma(2.0*n)) + 2.5*b_n / log(10.0) # mean SB, using Graham & Driver eqns 6 and ?\nprint '<mu>_e =', mu_m_e",
"<mu>_e = 25.2144770968\n"
],
[
"ETC('M','BM', 5110., 0., 0.75, 3600., '2x2', spatial_bin=[14.0,14.0], spectral_bin=None, nas=False, sb=True, mag_AB=25.2, flux=None, Nframes=1, emline_width=None)\n# S/N ~ 20/Ang, binned over ~1 R_e aperture",
"[INFO] Running KECK/ETC\n[INFO] Using SLICER=M\n[INFO] Using GRATING=BM\n[INFO] Using reference wavelength=5110.00\n[INFO] Using spatial binning, spatial_bin=14.0x14.0\nGRATING : BM\nA_per_pixel 0.28\n[INFO] f_lam ~ lam = 0.00\n[INFO] SEEING: 0.75, arcsec\n[INFO] Ang/pixel: 0.28\n[INFO] spectral pixels in 1 spectral resolution element: 4.00\n[INFO] Ang/resolution element: =1.12\n[INFO] Ang/SNR bin: 1.12\n[INFO] Pixels/Spectral SNR bin: 4.00\n[INFO] SNR Spatial Bin [arcsec^2]: 196.00\n[INFO] SNR Spatial Bin [pixels^2]: 138.03\n[INFO] OBJECT mag: 25.20, mag_AB / arcsec^2\n"
]
],
[
[
"Simulate VCC 1287 observation:",
"_____no_output_____"
]
],
[
[
"n, a_e, q, m_i = 0.6231, 46.34, 0.809, 15.1081 # Viraj Pandya sci_gf_i.fits header GALFIT results, sent 19 Mar 2018\nR_e = a_e * sqrt(q)\ng_i = 0.72 # note this is a CFHT g-i not SDSSS g-i\nmu_m_e = m_i + 2.5*log10(2.0) + 2.5*log10(pi*R_e**2)\nprint '<mu>_e (i-band) =', mu_m_e\nmu_m_e += g_i\nprint '<mu>_e (g-band) =', mu_m_e\nb_n = 1.9992*n - 0.3271\nmu_0 = mu_m_e + 2.5*log10(n*exp(b_n)/b_n**(2.0*n)*gamma(2.0*n)) - 2.5*b_n / log(10.0) # mean SB, using Graham & Driver eqns 6 and ?\nprint 'mu_0 (g-band) =', mu_0",
"<mu>_e (i-band) = 25.2032011222\n<mu>_e (g-band) = 25.9232011222\nmu_0 (g-band) = 25.4187233699\n"
],
[
"ETC('M','BM', 5092., 0., 0.75, 3600., '2x2', spatial_bin=[16.5,20.4], spectral_bin=None, nas=False, sb=True, mag_AB=25.5, flux=None, Nframes=1, emline_width=None)\n# S/N ~ 20/Ang, binned over full FOV",
"[INFO] Running KECK/ETC\n[INFO] Using SLICER=M\n[INFO] Using GRATING=BM\n[INFO] Using reference wavelength=5092.00\n[INFO] Using spatial binning, spatial_bin=16.5x20.4\nGRATING : BM\nA_per_pixel 0.28\n[INFO] f_lam ~ lam = 0.00\n[INFO] SEEING: 0.75, arcsec\n[INFO] Ang/pixel: 0.28\n[INFO] spectral pixels in 1 spectral resolution element: 4.00\n[INFO] Ang/resolution element: =1.12\n[INFO] Ang/SNR bin: 1.12\n[INFO] Pixels/Spectral SNR bin: 4.00\n[INFO] SNR Spatial Bin [arcsec^2]: 336.60\n[INFO] SNR Spatial Bin [pixels^2]: 201.12\n[INFO] OBJECT mag: 25.50, mag_AB / arcsec^2\n"
]
],
[
[
"Simulate Hubble VII observation:",
"_____no_output_____"
]
],
[
[
"R_e = 0.9\nm_V = 15.8\nmue = 15.8 + 2.5*log10(2) + 2.5*log10(pi*R_e**2)\nprint '<mu_V>_e = ', mue\nside = sqrt(pi * R_e**2)\nprint 'box size = %f arcsec' % (side)\nETC('S','BM', 4500., 0., 0.75, 900., '1x1', spatial_bin=[side,side], spectral_bin=None, nas=False, sb=True, mag_AB=mue, flux=None, Nframes=3, emline_width=None)",
"<mu_V>_e = 17.5666622181\nbox size = 1.595208 arcsec\n[INFO] Running KECK/ETC\n[INFO] Using SLICER=S\n[INFO] Using GRATING=BM\n[INFO] Using reference wavelength=4500.00\n[INFO] Using spatial binning, spatial_bin=1.59520846581x1.59520846581\nGRATING : BM\nA_per_pixel 0.28\n[INFO] f_lam ~ lam = 0.00\n[INFO] SEEING: 0.75, arcsec\n[INFO] Ang/pixel: 0.28\n[INFO] spectral pixels in 1 spectral resolution element: 2.00\n[INFO] Ang/resolution element: =0.56\n[INFO] Ang/SNR bin: 0.56\n[INFO] Pixels/Spectral SNR bin: 2.00\n[INFO] SNR Spatial Bin [arcsec^2]: 2.54\n[INFO] SNR Spatial Bin [pixels^2]: 31.01\n[INFO] OBJECT mag: 17.57, mag_AB / arcsec^2\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb4765d54586bfa04c03e428428e0f7dcab11ce6 | 22,296 | ipynb | Jupyter Notebook | demo/MIC Demo 1 - Basic steps for measurement.ipynb | Sylvain-Barde/mic-toolbox | 10d9d930a1a359aaa831f2f917eff357a3d5282e | [
"BSD-3-Clause"
] | 4 | 2019-06-28T20:36:33.000Z | 2022-01-04T21:49:52.000Z | demo/MIC Demo 1 - Basic steps for measurement.ipynb | Sylvain-Barde/mic-toolbox | 10d9d930a1a359aaa831f2f917eff357a3d5282e | [
"BSD-3-Clause"
] | 1 | 2019-06-27T14:52:52.000Z | 2019-07-04T14:14:14.000Z | demo/MIC Demo 1 - Basic steps for measurement.ipynb | Sylvain-Barde/mic-toolbox | 10d9d930a1a359aaa831f2f917eff357a3d5282e | [
"BSD-3-Clause"
] | 1 | 2019-06-27T13:33:42.000Z | 2019-06-27T13:33:42.000Z | 44.861167 | 693 | 0.553463 | [
[
[
"## MIC Demo 1 - Basic steps for measurement\n\nThis simple demonstration of the MIC toolbox uses two simulated bivariate VAR(2) models from the [\"Macroeconomic simulation comparison with a multivariate extension of the Markov Information Criterion\"](https://www.kent.ac.uk/economics/documents/research/papers/2019/1908.pdf) paper. These are the first two settings from the VAR validation exercises. The two simulated datasets are located in `data/model_1.txt` and `data/model_2.txt`. In addition this, one of these two models has been used to generated an 'empirical' dataset `data/emp_dat.txt`. The purpose of the demonstration is to show how to run the MIC and see if we can figure out which of models 1 or 2 is the true model.\n\nThe purpose of this first part is to outline the individual steps required to obtain a MIC measurement on a single variable in a multivariate system. As a full multivariate measurment requires several runs of the algorithms, this is best done in parallel, which will be covered in the second demonstration notebook.\n\nWe start with the setup, including the toolbox import:",
"_____no_output_____"
]
],
[
[
"import time\nimport numpy as np\nfrom scipy.stats import pearsonr\nimport mic.toolbox as mt",
"_____no_output_____"
]
],
[
[
"### Stage 0 - Discretising the data\n\nThe first task that needs to be done is to discretise the two variables in the system (denoted $x^1$ and $x^2$). In order to do so, we need to provide the following information:\n- `lb` and `ub` : Bounds to the range of variation. \n- `r_vec` : Binary discretisation resolution of the variables\n- `hp_bit_vec` : High priority bits - Number of bits to prioritise in the permutation\n\nWe can then call the binary quantisation function in the toolbox, `mt.bin_quant()`, and look at the result of the discretisation diagnostics to ensure that settings above are chosen so that the discretisation error is i.i.d uniformly distributed.",
"_____no_output_____"
]
],
[
[
"lb = [-10,-10]\nub = [ 10, 10]\nr_vec = [7,7]\nhp_bit_vec = [3,3]\n\n# Load 'empirical' data \npath = 'data/emp_data.txt'\nemp_data = np.loadtxt(path, delimiter=\"\\t\") \n\n# Pick first replication (columns 1 and 2) - just as an example\ndat = emp_data[:,0:2]\n\n# Run the discretisation tests (displays are active by passing any string other than 'notests' or 'nodisplay')\ndata_struct_emp = mt.bin_quant(dat,lb,ub,r_vec,'')\n\n# Check the correlation of the high-priority bits (example of 'notests' here)\ndata_struct_hp = mt.bin_quant(dat,lb,ub,hp_bit_vec,'notests')\ndat_bin = data_struct_hp['binary_data']\nhp_dat = dat - np.asarray(dat_bin.errors)\n\nprint('\\n Correlation of high priority bits with raw data:')\nfor n in range(2):\n corr = pearsonr(dat[:,n],hp_dat[:,n])\n print(' Variable {:1d}: {:7.4f}'.format(n+1,corr[0]))",
"+-------------------------------------------------+\n| Quantization diagnostics |\n+-------------------------------------------------+\n N° of observations: 1000\n\n Var N°: 1 2\n Lower bound: -10.000 -10.000\n Upper bound: 10.000 10.000\n Min obs.: -5.259 -4.709\n Max obs.: 6.160 4.381\n Out of bounds: 0 0\n Resolution: 7 7\n Standard dev.: 1.737 1.580\n Discr. unit: 0.156 0.156\n\n Signal-to-Noise ratio for quantisation (in dB):\n Var N°: 1 2\n Theoretical: 31.710 30.886\n Effective: 25.748 24.540\n\n+-------------------------------------------------+\n Kolmogorov-Smirnov test for uniformity\n H0: Distribution of errors is uniform\n\n Var N°: 1 2\n KS statistic: 0.016 0.059\n P-value: 0.999 0.059\n\n+-------------------------------------------------+\n Ljung-Box tests for autocorrelation of errors\n H0: The errors are independently distributed\n\n Critical value (Chi-sq, 7 df): 14.067\n\n Var N°: 1 2\n LB statistic: 2.243 5.252\n P-value: 0.945 0.629\n\n+-------------------------------------------------+\n Spearman correlation of error with digitised data\n H0: Quantisation errors not correlated with data\n\n Var N°: 1 2\n Correlation: -0.025 -0.007\n P-value: 0.435 0.818\n\n+-------------------------------------------------+\n\n Correlation of high priority bits with raw data:\n Variable 1: 0.9865\n Variable 2: 0.9832\n"
]
],
[
[
"We can see here that under the settings picked above, the quantisation errors for both series are indeed uniformly distributed (KS test not rejected), independent (LB test is not rejected) and the errors are not correlated with the discretisation levels. Furthermore, a discretisation using only the first three bits of each variable (the 'high priority bits') already has a 98% correlation with the raw data. This suggests that the settings are appropriate for the analysis.\n\n### Stage 1 - learning model probabilities from the data\n\nThe important parameters to choose at this stage relate to the size of the tree that we want to build with the simulated data. The parameters of interest are:\n- `mem` : the maximum amount of nodes we can initialise. As trees tend to be sparse, this does not have to match the theoretical number of the trees $2^D$.\n- `d`: maximum depth of the context trees (in bits). Combined with `mem`, these implement a cap on the amount of the amount of memory that can be used.\n- `lags`: The number of lags in the Markov process being used to learn the probabilities.\n",
"_____no_output_____"
]
],
[
[
"mem = 200000\nd = 24\nlags = 2",
"_____no_output_____"
]
],
[
[
"Choosing 2 Markov lags and 14 bits per observations means that the full context will be 28 bits long (not counting contemporaneous correlations). Given a maximum tree depth $D=24$, it is clear that some of the context will be truncated. We therefore need to permute the bits in the context to prioritise the most important ones and ensure only the least informative ones get truncated. In order to do so, the next step is to generate a permutation the context bits. \n\nAs stated above, we are only demonstrating a single run of the MIC algorithm, and we choose to predict the first variable conditional on the context and the current value of the second variable. This is declared via the `var_vec` list below. To clarify the syntax, the first entry in the `var_vec` list identifies the variable to predict (1 in this case), and any subsequent entries in the list indentify contemporaneous conditioning variables (2 in our case)\n\nThis will allow us to determine the value of $\\lambda^1 (x_t^1 \\mid x_t^2, \\Omega_t)$. It is important to note that to get the full MIC measurement, will need to run the algorithm again. The steps are essentially the same, and this will be covered in the second part of the demonstration.",
"_____no_output_____"
]
],
[
[
"num_runs = 2\nvar_vec = [1,2] # This is the critical input, it governs the conditioning order.\n\nperm = mt.corr_perm(dat, r_vec, hp_bit_vec, var_vec, lags, d)",
"\n+------------------------------------------------------+\n Predicting variable: 1\n Contemporaneous conditioning vars: \n\t[2]\n Number of conditioning lags: 2\n\n\n --------- Iteration 1 ---------\n Select lag 1 of var 1\n Correlation: 0.7443\n --------- Iteration 2 ---------\n Select lag 2 of var 2\n Correlation: 0.4978\n --------- Iteration 3 ---------\n Select lag 2 of var 1\n Correlation: 0.4974\n --------- Iteration 4 ---------\n Select lag 1 of var 2\n Correlation: 0.3625\n --------- Iteration 5 ---------\n Select contemporaneous var 2\n Correlation: 0.0899\n+------------------------------------------------------+\n\n"
]
],
[
[
"We now have all the elements required to train the tree. For the purpose of the demonstration the two simulated data files contain two training sets of 125,000 observations for each variable $x^1$ and $x^2$. The first set is located in the first two columns of the traing data, while the second set is located in columns 3 and 4. This division into two training sets is done in order to illustrate:\n- How to initialise a new tree on the first series\n- How to update an existing tree with further data\n\nAs stated above, we are only carrying out a single run here, so we choose to learn the probabilities for the 1st model only. Once again, to get a measurement for the second model will require further runs which we do in the second part of the demonstration.",
"_____no_output_____"
]
],
[
[
"# Load model data\npath = 'data/model_1.txt'\nsim_data = np.loadtxt(path, delimiter=\"\\t\") \n\n# Pick a tag for the tree (useful for indentifying the tree later on)\ntag = 'Model 1'\n\n# Discretise the training data. \nsim_dat1 = sim_data[:,0:2]\ndata_struct = mt.bin_quant(sim_dat1,lb,ub,r_vec,'notests') # Note the 'notests' option\ndata_bin = data_struct['binary_data']\n\n# Initialise a tree and train it, trying to predict the 1st variable\nvar = var_vec[0]\noutput = mt.train(None, data_bin, mem, lags, d, var, tag, perm)",
"\n+------------------------------------------------------+\n| Context Tree Weighting on training series |\n+------------------------------------------------------+\n Empty tree structure initialised\n+------------------------------------------------------+\n\t 10% complete\t 10.1220 seconds\n\t 20% complete\t 18.8578 seconds\n\t 30% complete\t 27.1562 seconds\n\t 40% complete\t 35.4127 seconds\n\t 50% complete\t 43.4386 seconds\n\t 60% complete\t 51.9838 seconds\n\t 70% complete\t 59.8614 seconds\n\t 80% complete\t 68.0705 seconds\n\t 90% complete\t 75.2379 seconds\n\t100% complete\t 82.3344 seconds\n+------------------------------------------------------+\n Total hashing time required : 59.1277\n Average per context : 4.7303e-04\n Total CTW updating time required : 19.7348\n Average per context : 1.5788e-04\n+------------------------------------------------------+\n"
]
],
[
[
"Let's now update the tree with the second run of training data to see the difference in syntax and output",
"_____no_output_____"
]
],
[
[
"# Discretise the second run of training data\nsim_dat1 = sim_data[:,2:4]\ndata_struct = mt.bin_quant(sim_dat1,lb,ub,r_vec,'notests') # Note, we are not running discretisation tests\ndata_bin = data_struct['binary_data']\n\n# Extract the tree from the previous output and train it again. Only the 1st argument changes\nT = output['T']\noutput = mt.train(T, data_bin, mem, lags, d, var, tag, perm)",
"\n+------------------------------------------------------+\n| Context Tree Weighting on training series |\n+------------------------------------------------------+\n Using \"Model 1\" structure\n+------------------------------------------------------+\n\t 10% complete\t 7.5647 seconds\n\t 20% complete\t 15.5909 seconds\n\t 30% complete\t 23.4861 seconds\n\t 40% complete\t 31.5217 seconds\n\t 50% complete\t 39.5597 seconds\n\t 60% complete\t 47.5197 seconds\n\t 70% complete\t 55.6947 seconds\n\t 80% complete\t 63.7563 seconds\n\t 90% complete\t 71.4348 seconds\n\t100% complete\t 78.3093 seconds\n+------------------------------------------------------+\n Total hashing time required : 54.0317\n Average per context : 4.3226e-04\n Total CTW updating time required : 20.4773\n Average per context : 1.6382e-04\n+------------------------------------------------------+\n"
]
],
[
[
"Notice how the header of the output has changed, using the tag to flag that we are updating an existing tree. We are done training the tree, let's get some descriptive statistics.",
"_____no_output_____"
]
],
[
[
"# Use the built-in descriptive statistic method to get some diagnostics\nT = output['T']\nT.desc()",
" \n+------------------------------------------------------+\n Tree diagnostics: Model 1\n+------------------------------------------------------+\n Variable 1 of 2\n Training observations: 249996\n+------------------------------------------------------+\n Memory locations allocated: 200000 nodes\n Memory usage per node: 2040 Bytes\n Memory space required: 408000000 Bytes\n Effective memory useage: 147628680 Bytes\n+------------------------------------------------------+\n Resolution: 7 bits\n Tree depth: 24 bits\n Leaf nodes: 16724 nodes\n Branch nodes: 55643 nodes\n Free nodes: 127633 nodes\n+------------------------------------------------------+\n N° of failed allocations: 0\n Maximum N° of leaf tries: 7\n Average N° of leaf tries: 1.3716\n Maximum N° of branch tries: 10\n Average N° of branch tries: 1.3506\n+------------------------------------------------------+\n Number of leaf counter rescalings: 0\n+------------------------------------------------------+\n"
]
],
[
[
"We can see that the tree has used about 1/3 of the initial node allocation, so we have plenty of margin on memory. This will typically change if more variables are included. There is an element of trial and error to figuring out how much memory to allocated, which is why this diagnostic is useful. \n\nIt is important to note that the algorithm can cope with failed node allocations (situations where the algorithm attempts to allocate a node to memory but fails), as it has a heuristic that allows it to 'skip' failed nodes, at the cost of introducing an error in the probabilities. Furthermore, because the tree implements a pruning and rollout mechanism, nodes are only allocated when they are not on a single branch path. This means that node allocation failures due to lack of memory will typically occur for very rare events\n\nBoth of these mechanisms mean that memory allocation failure is graceful and the odd failure will not impair the measurement. It is nevertheless a good idea to check `T.desc()` to ensure that failed allocations are not too numerous.\n\n### Stage 2 - Scoring the empirical data with the model probabilities\n\nWe have already loaded the empirical data when running the discretisation tests. For the purposes of this demonstration, we have 10 replications of 1000 observations each, in order to show the consistency of the measurement. We will therefore loop the steps required to score these series over the 10 replications. In a normal application with only one emprical dataset, this loop is of course not needed!\n\n- Discretise the empirical data into `data_stuct_emp`\n- Extract the binary data from the dictionary \n- Pass the binary data alongside the tree `T` to the score function. The function knows which variable to score as this is given in the tree.\n- Correct the score by removing the estimate of the bias (measured using the Rissanen bound correction).\n",
"_____no_output_____"
]
],
[
[
"scores = np.zeros([998,10])\n\nfor j in range(10):\n loop_t = time.time()\n\n # Discretise the data\n k = 2*j\n dat = emp_data[:,k:k+2]\n data_struct_emp = mt.bin_quant(dat,lb,ub,T.r_vec,'notests')\n data_bin_emp = data_struct_emp['binary_data']\n\n # Score the data using the tree\n score_struct = mt.score(T, data_bin_emp)\n\n # Correct the measurement\n scores[:,j] = score_struct['score'] - score_struct['bound_corr']\n\n print('Replication {:2d}: {:10.4f} secs.'.format(j,time.time() - loop_t))\n\nflt_str = ' {:7.2f}'*10 \nprint('\\n Scores obtained ')\nprint(flt_str.format(*np.sum(scores,0)))",
"Replication 0: 0.7932 secs.\nReplication 1: 0.8078 secs.\nReplication 2: 0.8371 secs.\nReplication 3: 0.8248 secs.\nReplication 4: 0.8004 secs.\nReplication 5: 0.8059 secs.\nReplication 6: 0.8500 secs.\nReplication 7: 0.8098 secs.\nReplication 8: 0.8036 secs.\nReplication 9: 0.7955 secs.\n\n Scores obtained \n 4793.87 4827.00 4794.54 4795.12 4784.41 4851.00 4788.13 4843.35 4805.88 4753.12\n"
]
],
[
[
"This provides the measurement for $\\lambda^1 (x_t^1 \\mid x_t^2, \\Omega_t)$. To complete the measurement, one also requires $\\lambda^1 (x_t^2 \\mid \\Omega_t)$. This will enable us to calculate:\n\n$$ \\lambda^1 (X) = \\sum _{t=L}^T \\left[ \\lambda^1 (x_t^1 \\mid x_t^2, \\Omega_t) + \\lambda^1 (x_t^2 \\mid \\Omega_t) \\right]$$\n\nTo do this, the analysis can be re-run from `In [4]` onwards, setting `var_vec = [2]` and choosing . The resulting score for variable 2 can be added to the score above, which measures the score for variable 1, conditional on 2, thus providing the MIC for the entire system.\n\nFinally, the accuracy of the measurement can be improved by re-doing the analysis using a different conditioning order in the cross-entropy measurement. In this case this can be done by carrying out the same analysis with `var_vec = [2,1]` and `var_vec = [1]` and adding the result. This provides the following measurement:\n\n$$ \\lambda^1 (X) = \\sum _{t=L}^T \\left[ \\lambda^1 (x_t^2 \\mid x_t^1, \\Omega_t) + \\lambda^1 (x_t^1 \\mid \\Omega_t) \\right]$$\n\nIn theory, the two $\\lambda^1 (X)$ measurements should be indentical, in practice they will differ by a measurement error. Averaging the will therefore improve precision.\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb4768f31663406bf8237e13fe8da3180761a833 | 820,005 | ipynb | Jupyter Notebook | Modeling_fake_news.ipynb | Boogey9/Fake-News-Detection-EDA | 2d67e5c1cf9053289746e161821546d983922410 | [
"MIT"
] | null | null | null | Modeling_fake_news.ipynb | Boogey9/Fake-News-Detection-EDA | 2d67e5c1cf9053289746e161821546d983922410 | [
"MIT"
] | null | null | null | Modeling_fake_news.ipynb | Boogey9/Fake-News-Detection-EDA | 2d67e5c1cf9053289746e161821546d983922410 | [
"MIT"
] | null | null | null | 717.414698 | 227,052 | 0.942099 | [
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.utils import shuffle\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize\nfrom collections import Counter\nimport nltk, string\nimport matplotlib\nfrom wordcloud import WordCloud\nfrom sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import *\nfrom sklearn import metrics\nfrom sklearn import model_selection\nfrom sklearn import feature_extraction\nfrom sklearn.metrics import classification_report\nmatplotlib.style.use('ggplot')\npd.set_option('display.max_colwidth', -1)\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 20, 10",
"/Users/mac/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:20: 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"
],
[
"true = pd.read_csv(\"./data/true.csv\")\nfake = pd.read_csv(\"./data/fake.csv\")",
"_____no_output_____"
],
[
"true.head()",
"_____no_output_____"
],
[
"fake.head()",
"_____no_output_____"
],
[
"true['category'] = 1\nfake['category'] = 0",
"_____no_output_____"
],
[
"df = pd.concat([true,fake]) \ndata = shuffle(df)\ndata = data.reset_index(drop=True)\n",
"_____no_output_____"
],
[
"data.drop([\"date\"])",
"_____no_output_____"
],
[
"sns.set_style(\"darkgrid\")\nsns.countplot(data.category)\n",
"_____no_output_____"
],
[
"data.isna().sum()\n",
"_____no_output_____"
],
[
"data.subject.value_counts()\n",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,5))\nsns.countplot(\"subject\", data=fake)\nplt.show()",
"_____no_output_____"
],
[
"data[\"full_text\"] = data[\"title\"]+\" \"+data[\"text\"]",
"_____no_output_____"
],
[
"stop_words = set(stopwords.words('english'))\npunct = re.compile(r'(\\w+)')\n\ndef normalize_sentence(txt): \n #string to lowercase\n txt = txt.lower()\n #punctuation removal and map it to space\n tokenized = [m.group() for m in punct.finditer(txt)]\n s = ' '.join(tokenized)\n\n #remove digits \n no_digits = ''.join([i for i in s if not i.isdigit()])\n cleaner = \" \".join(no_digits.split())\n \n #tokenize words and removing stop words \n word_tokens = word_tokenize(cleaner)\n filtered_sentence = [w for w in word_tokens if not w in stop_words]\n filtered_sentence = \" \".join(filtered_sentence)\n return filtered_sentence\n\n#creating column with cleaned and normalized text \ndata['ntext'] = data.full_text.apply(normalize_sentence)\n#data['normalized_text'] = data.text.apply(stemming_words)\ndata.head()",
"_____no_output_____"
],
[
"data.ntext.values[4]",
"_____no_output_____"
],
[
"freq = pd.Series(' '.join(data['ntext']).split()).value_counts()[:3]\ndata['ntext'] = data['ntext'].apply(lambda x: \" \".join(x for x in x.split() if x not in freq))",
"_____no_output_____"
],
[
"all_docs = list(data.ntext.values)\nword_frequencies = pd.DataFrame(data.ntext.str.split(expand=True).stack().value_counts(),columns = [\"frequency\"])\nword_frequencies.reset_index(inplace=True)\nword_frequencies.rename(columns={'index':'word'},inplace=True)\nword_frequencies.head(5)",
"_____no_output_____"
],
[
"count_true = Counter(\" \".join(data[data['category']==1][\"ntext\"]).split()).most_common(30)\ndf1 = pd.DataFrame.from_dict(count_true)\ndf1 = df1.rename(columns={0: \"True news\", 1 : \"count\"})\n\ncount_fake = Counter(\" \".join(data[data['category']==0][\"ntext\"]).split()).most_common(30)\ndf2 = pd.DataFrame.from_dict(count_fake)\ndf2 = df2.rename(columns={0: \"Fake news\", 1 : \"count\"})",
"_____no_output_____"
],
[
"df1.plot.bar(legend = False,color = 'Green')\ny_pos = np.arange(len(df1[\"True news\"]))\nplt.xticks(y_pos, df1[\"True news\"])\nplt.title('More frequent positive words')\nplt.xlabel('Words')\nplt.ylabel('Number of occurences')\nplt.show()",
"_____no_output_____"
],
[
"df2.plot.bar(legend = False)\ny_pos = np.arange(len(df2[\"Fake news\"]))\nplt.xticks(y_pos, df2[\"Fake news\"])\nplt.title('More frequent negative words')\nplt.xlabel('Words')\nplt.ylabel('Number of occurences')\nplt.show()",
"_____no_output_____"
],
[
"def wordcloud_function(doc):\n corpus =(\" \").join(doc)\n wordcloud = WordCloud(width = 1000, height = 500, max_words=100, background_color=\"white\").generate(corpus)\n plt.figure(figsize=(15,8))\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.savefig(\"wordcloud\"+\".png\", bbox_inches='tight')\n plt.show()\n plt.close()",
"_____no_output_____"
],
[
"wordcloud_function(all_docs)",
"_____no_output_____"
],
[
"real_docs = list(data['ntext'][data['category']==1])\n#wordcloud of real news\nwordcloud_function(real_docs)",
"_____no_output_____"
],
[
"fake_docs = list(data['ntext'][data['category']==0])\n#wordcloud of real news\nwordcloud_function(fake_docs)",
"_____no_output_____"
],
[
"def featureExtraction(data):\n vect = TfidfVectorizer()\n tfidf_data = vect.fit_transform(data)\n return tfidf_data",
"_____no_output_____"
],
[
"def learning(clf, X, Y):\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=60) #60\n classifier = clf()#4800-br #5900 #6200 #6700 #6800 #7800-ba #7800 #8800\n classifier.fit(X_train, Y_train)\n predict = classifier.predict(X_test) \n return predict, X_train, X_test, classifier, Y_test, Y_train",
"_____no_output_____"
],
[
"def model_evaluation(classifier, predict, X_train, Y_train, X_test, Y_test):\n print(\"Train Accuracy : {}%\".format(round(classifier.score(X_train, Y_train)*100,1))) #training accuracy\n print(\"Test Accuracy : {}%\".format(round(classifier.score(X_test, Y_test)*100,1))) #Test accuracy\n print(\"Test precision : {}%\".format(round( metrics.precision_score(Y_test, predict)*100,1))) #Test precision\n print(\"Recall : {}%\".format(round(metrics.recall_score(Y_test,predict)*100,1))) #Recall\n print(classification_report(predict, Y_test)) #Classification report\n m_confusion_test = metrics.confusion_matrix(Y_test, predict) \n \n #Confusion Matrix\n pd.DataFrame(data = m_confusion_test, columns = ['Predicted 0', 'Predicted 1'], index = ['Actual 0', 'Actual 1'])\n fig, ax = plt.subplots(figsize=(4, 4))\n ax.matshow(m_confusion_test, cmap=plt.cm.RdPu_r, alpha=0.1)\n for i in range(m_confusion_test.shape[0]):\n for j in range(m_confusion_test.shape[1]):\n ax.text(x=j, y=i, s=m_confusion_test[i, j], va='center', ha='center')\n plt.title('SVC Linear Kernel \\nRecall: {0:.1f}%'.format(metrics.recall_score(Y_test,predict)*100))\n plt.xlabel('PREDICTED LABELS')\n plt.ylabel('ACTUAL LABELS')\n plt.tight_layout()",
"_____no_output_____"
],
[
"def main(clf):\n data_train, polarity = data.ntext, data.category\n tfidf_data = featureExtraction(data_train)\n pred, X_train, X_test, classifier, Y_test, Y_train = learning(clf, tfidf_data, polarity)\n model_evaluation(classifier, pred, X_train, Y_train, X_test, Y_test)\n return classifier",
"_____no_output_____"
],
[
"classifier = main(SVC)",
"Train Accuracy : 100.0%\nTest Accuracy : 99.5%\nTest precision : 99.5%\nRecall : 99.5%\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 4668\n 1 1.00 0.99 1.00 4312\n\n accuracy 1.00 8980\n macro avg 1.00 1.00 1.00 8980\nweighted avg 1.00 1.00 1.00 8980\n\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb476e535727ab6bf0f1cdfa3e66d870a6a82a30 | 69,377 | ipynb | Jupyter Notebook | Advanced Featuretools RUL.ipynb | Featuretools/predict-remaining-useful-life | c6a78c7b1922b8144c54dc2359e0e66fc5425b7d | [
"BSD-3-Clause"
] | 200 | 2018-03-27T21:21:33.000Z | 2022-01-08T02:05:31.000Z | Advanced Featuretools RUL.ipynb | Featuretools/remaining-useful-life-demo | c6a78c7b1922b8144c54dc2359e0e66fc5425b7d | [
"BSD-3-Clause"
] | 11 | 2018-07-05T13:47:13.000Z | 2020-08-13T21:23:27.000Z | Advanced Featuretools RUL.ipynb | Featuretools/remaining-useful-life-demo | c6a78c7b1922b8144c54dc2359e0e66fc5425b7d | [
"BSD-3-Clause"
] | 101 | 2018-04-10T17:09:19.000Z | 2022-02-01T13:54:14.000Z | 41.100118 | 501 | 0.402987 | [
[
[
"# Predicting Remaining Useful Life (advanced)\n<p style=\"margin:30px\">\n <img style=\"display:inline; margin-right:50px\" width=50% src=\"https://www.featuretools.com/wp-content/uploads/2017/12/FeatureLabs-Logo-Tangerine-800.png\" alt=\"Featuretools\" />\n <img style=\"display:inline\" width=15% src=\"https://upload.wikimedia.org/wikipedia/commons/e/e5/NASA_logo.svg\" alt=\"NASA\" />\n</p>\n\nThis notebook has a more advanced workflow than [the other notebook](Simple%20Featuretools%20RUL%20Demo.ipynb) for predicting Remaining Useful Life (RUL). If you are a new to either this dataset or Featuretools, I would recommend reading the other notebook first.\n\n## Highlights\n* Demonstrate how novel entityset structures improve predictive accuracy\n* Use TSFresh Primitives from a featuretools [addon](https://docs.featuretools.com/getting_started/install.html#add-ons)\n* Improve Mean Absolute Error by tuning hyper parameters with [BTB](https://github.com/HDI-Project/BTB)\n\nHere is a collection of mean absolute errors from both notebooks. Though we've used averages where possible (denoted by \\*), the randomness in the Random Forest Regressor and how we choose labels from the train data changes the score.\n\n| | Train/Validation MAE| Test MAE|\n|---------------------------------|---------------------|----------|\n| Median Baseline | 72.06* | 50.66* |\n| Simple Featuretools | 40.92* | 39.56 |\n| Advanced: Custom Primitives | 35.90* | 28.84 |\n| Advanced: Hyperparameter Tuning | 34.80* | 27.85 |\n\n\n# Step 1: Load Data\nWe load in the train data using the same function we used in the previous notebook:",
"_____no_output_____"
]
],
[
[
"import composeml as cp\nimport numpy as np\nimport pandas as pd\nimport featuretools as ft\nimport utils\nimport os\n\nfrom tqdm import tqdm\nfrom sklearn.cluster import KMeans",
"_____no_output_____"
],
[
"data_path = 'data/train_FD004.txt'\ndata = utils.load_data(data_path)\ndata.head()",
"Loaded data with:\n61249 Recordings\n249 Engines\n21 Sensor Measurements\n3 Operational Settings\n"
]
],
[
[
"We also make cutoff times by using [Compose](https://compose.featurelabs.com) for generating labels on engines that reach at least 100 cycles. For each engine, we generate 10 labels that are spaced 10 cycles apart.",
"_____no_output_____"
]
],
[
[
"def remaining_useful_life(df):\n return len(df) - 1\n\nlm = cp.LabelMaker(\n target_entity='engine_no',\n time_index='time',\n labeling_function=remaining_useful_life,\n)\n\nlabel_times = lm.search(\n data.sort_values('time'),\n num_examples_per_instance=10,\n minimum_data=100,\n gap=10,\n verbose=True,\n)\n\nlabel_times.head()",
"Elapsed: 00:01 | Remaining: 00:00 | Progress: 100%|██████████| engine_no: 2490/2490 \n"
]
],
[
[
"We're going to make 5 sets of cutoff times to use for cross validation by random sampling the labels times we created previously.",
"_____no_output_____"
]
],
[
[
"splits = 5\ncutoff_time_list = []\n\nfor i in range(splits):\n sample = label_times.sample(n=249, random_state=i)\n sample.sort_index(inplace=True)\n cutoff_time_list.append(sample)\n\ncutoff_time_list[0].head()",
"_____no_output_____"
]
],
[
[
"We're going to do something fancy for our entityset. The values for `operational_setting` 1-3 are continuous but create an implicit relation between different engines. If two engines have a similar `operational_setting`, it could indicate that we should expect the sensor measurements to mean similar things. We make clusters of those settings using [KMeans](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html) from scikit-learn and make a new entity from the clusters.",
"_____no_output_____"
]
],
[
[
"nclusters = 50\n\ndef make_entityset(data, nclusters, kmeans=None):\n X = data[[\n 'operational_setting_1',\n 'operational_setting_2',\n 'operational_setting_3',\n ]]\n\n if kmeans is None:\n kmeans = KMeans(n_clusters=nclusters).fit(X)\n\n data['settings_clusters'] = kmeans.predict(X)\n\n es = ft.EntitySet('Dataset')\n\n es.entity_from_dataframe(\n dataframe=data,\n entity_id='recordings',\n index='index',\n time_index='time',\n )\n\n es.normalize_entity(\n base_entity_id='recordings',\n new_entity_id='engines',\n index='engine_no',\n )\n\n es.normalize_entity(\n base_entity_id='recordings',\n new_entity_id='settings_clusters',\n index='settings_clusters',\n )\n\n return es, kmeans\n\n\nes, kmeans = make_entityset(data, nclusters)\nes",
"_____no_output_____"
]
],
[
[
"## Visualize EntitySet",
"_____no_output_____"
]
],
[
[
"es.plot()",
"_____no_output_____"
]
],
[
[
"# Step 2: DFS and Creating a Model\nIn addition to changing our `EntitySet` structure, we're also going to use the [Complexity](http://tsfresh.readthedocs.io/en/latest/api/tsfresh.feature_extraction.html#tsfresh.feature_extraction.feature_calculators.cid_ce) time series primitive from the featuretools [addon](https://docs.featuretools.com/getting_started/install.html#add-ons) of ready-to-use TSFresh Primitives.",
"_____no_output_____"
]
],
[
[
"from featuretools.tsfresh import CidCe\n\nfm, features = ft.dfs(\n entityset=es,\n target_entity='engines',\n agg_primitives=['last', 'max', CidCe(normalize=False)],\n trans_primitives=[],\n chunk_size=.26,\n cutoff_time=cutoff_time_list[0],\n max_depth=3,\n verbose=True,\n)\n\nfm.to_csv('advanced_fm.csv')\nfm.head()",
"Built 304 features\nElapsed: 02:31 | Progress: 100%|██████████\n"
]
],
[
[
"We build 4 more feature matrices with the same feature set but different cutoff times. That lets us test the pipeline multiple times before using it on test data.",
"_____no_output_____"
]
],
[
[
"fm_list = [fm]\n\nfor i in tqdm(range(1, splits)):\n es = make_entityset(data, nclusters, kmeans=kmeans)[0]\n fm = ft.calculate_feature_matrix(\n entityset=es,\n features=features,\n chunk_size=.26,\n cutoff_time=cutoff_time_list[i],\n )\n fm_list.append(fm)",
"100%|██████████| 4/4 [08:39<00:00, 129.77s/it]\n"
],
[
"from sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.feature_selection import RFE",
"_____no_output_____"
],
[
"def pipeline_for_test(fm_list, hyperparams=None, do_selection=False):\n scores = []\n regs = []\n selectors = []\n\n hyperparams = hyperparams or {\n 'n_estimators': 100,\n 'max_feats': 50,\n 'nfeats': 50,\n }\n\n for fm in fm_list:\n X = fm.copy().fillna(0)\n y = X.pop('remaining_useful_life')\n\n n_estimators = int(hyperparams['n_estimators'])\n max_features = int(hyperparams['max_feats'])\n max_features = min(max_features, int(hyperparams['nfeats']))\n reg = RandomForestRegressor(n_estimators=n_estimators, max_features=max_features)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n\n if do_selection:\n reg2 = RandomForestRegressor(n_estimators=10, n_jobs=3)\n selector = RFE(reg2, int(hyperparams['nfeats']), step=25)\n selector.fit(X_train, y_train)\n X_train = selector.transform(X_train)\n X_test = selector.transform(X_test)\n selectors.append(selector)\n\n reg.fit(X_train, y_train)\n regs.append(reg)\n\n preds = reg.predict(X_test)\n mae = mean_absolute_error(preds, y_test)\n scores.append(mae)\n\n return scores, regs, selectors\n\n\nscores, regs, selectors = pipeline_for_test(fm_list)\nprint([float('{:.1f}'.format(score)) for score in scores])\n\nmean, std = np.mean(scores), np.std(scores)\ninfo = 'Average MAE: {:.1f}, Std: {:.2f}\\n'\nprint(info.format(mean, std))\n\nmost_imp_feats = utils.feature_importances(fm_list[0], regs[0])",
"[46.2, 34.8, 36.8, 34.6, 37.2]\nAverage MAE: 37.9, Std: 4.25\n\n1: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_13)) [0.090]\n2: MAX(recordings.sensor_measurement_13) [0.078]\n3: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_4)) [0.054]\n4: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_11)) [0.050]\n5: MAX(recordings.sensor_measurement_17) [0.048]\n-----\n\n"
],
[
"data_test = utils.load_data('data/test_FD004.txt')\n\nes_test, _ = make_entityset(\n data_test,\n nclusters,\n kmeans=kmeans,\n)\n\nfm_test = ft.calculate_feature_matrix(\n entityset=es_test,\n features=features,\n verbose=True,\n chunk_size=.26,\n)\n\nX = fm_test.copy().fillna(0)\n\ny = pd.read_csv(\n 'data/RUL_FD004.txt',\n sep=' ',\n header=None,\n names=['remaining_useful_life'],\n index_col=False,\n)\n\npreds = regs[0].predict(X)\nmae = mean_absolute_error(preds, y)\nprint('Mean Abs Error: {:.2f}'.format(mae))",
"Loaded data with:\n41214 Recordings\n248 Engines\n21 Sensor Measurements\n3 Operational Settings\nElapsed: 00:03 | Progress: 100%|██████████\nMean Abs Error: 28.87\n"
]
],
[
[
"# Step 3: Feature Selection and Scoring\nHere, we'll use [Recursive Feature Elimination](http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html). In order to set ourselves up for later optimization, we're going to write a generic `pipeline` function which takes in a set of hyperparameters and returns a score. Our pipeline will first run `RFE` and then split the remaining data for scoring by a `RandomForestRegressor`. We're going to pass in a list of hyperparameters, which we will tune later.",
"_____no_output_____"
],
[
"Lastly, we can use that selector and regressor to score the test values.",
"_____no_output_____"
],
[
"# Step 4: Hyperparameter Tuning\nBecause of the way we set up our pipeline, we can use a Gaussian Process to tune the hyperparameters. We will use [BTB](https://github.com/HDI-Project/BTB) from the [HDI Project](https://github.com/HDI-Project). This will search through the hyperparameters `n_estimators` and `max_feats` for RandomForest, and the number of features for RFE to find the hyperparameter set that has the best average score.",
"_____no_output_____"
]
],
[
[
"from btb import HyperParameter, ParamTypes\nfrom btb.tuning import GP\n\n\ndef run_btb(fm_list, n=30, best=45):\n hyperparam_ranges = [\n ('n_estimators', HyperParameter(ParamTypes.INT, [10, 200])),\n ('max_feats', HyperParameter(ParamTypes.INT, [5, 50])),\n ('nfeats', HyperParameter(ParamTypes.INT, [10, 70])),\n ]\n\n tuner = GP(hyperparam_ranges)\n shape = (n, len(hyperparam_ranges))\n tested_parameters = np.zeros(shape, dtype=object)\n scores = []\n\n print('[n_est, max_feats, nfeats]')\n\n best_hyperparams = None\n best_sel = None\n best_reg = None\n\n for i in tqdm(range(n)):\n hyperparams = tuner.propose()\n\n cvscores, regs, selectors = pipeline_for_test(\n fm_list,\n hyperparams=hyperparams,\n do_selection=True,\n )\n\n bound = np.mean(cvscores)\n tested_parameters[i, :] = hyperparams\n tuner.add(hyperparams, -np.mean(cvscores))\n\n if np.mean(cvscores) + np.std(cvscores) < best:\n best = np.mean(cvscores)\n best_hyperparams = hyperparams\n best_reg = regs[0]\n best_sel = selectors[0]\n\n info = '{}. {} -- Average MAE: {:.1f}, Std: {:.2f}'\n mean, std = np.mean(cvscores), np.std(cvscores)\n print(info.format(i, best_hyperparams, mean, std))\n print('Raw: {}'.format([float('{:.1f}'.format(s)) for s in cvscores]))\n\n return best_hyperparams, (best_sel, best_reg)\n\n\nbest_hyperparams, best_pipeline = run_btb(fm_list, n=30)",
"\r 0%| | 0/30 [00:00<?, ?it/s]"
],
[
"X = fm_test.copy().fillna(0)\n\ny = pd.read_csv(\n 'data/RUL_FD004.txt',\n sep=' ',\n header=None,\n names=['remaining_useful_life'],\n index_col=False,\n)\n\npreds = best_pipeline[1].predict(best_pipeline[0].transform(X))\nscore = mean_absolute_error(preds, y)\nprint('Mean Abs Error on Test: {:.2f}'.format(score))\n\nmost_imp_feats = utils.feature_importances(\n X.iloc[:, best_pipeline[0].support_],\n best_pipeline[1],\n)",
"Mean Abs Error on Test: 47.75\n1: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_13)) [0.196]\n2: MAX(recordings.sensor_measurement_15) [0.155]\n3: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_4)) [0.139]\n4: MAX(recordings.settings_clusters.LAST(recordings.sensor_measurement_11)) [0.130]\n5: MAX(recordings.sensor_measurement_11) [0.085]\n-----\n\n"
]
],
[
[
"# Appendix: Averaging old scores\nTo make a fair comparison between the previous notebook and this one, we should average scores where possible. The work in this section is exactly the work in the previous notebook plus some code for taking the average in the validation step.",
"_____no_output_____"
]
],
[
[
"from featuretools.primitives import Min\n\nold_fm, features = ft.dfs(\n entityset=es,\n target_entity='engines',\n agg_primitives=['last', 'max', 'min'],\n trans_primitives=[],\n cutoff_time=cutoff_time_list[0],\n max_depth=3,\n verbose=True,\n)\n\nold_fm_list = [old_fm]\n\nfor i in tqdm(range(1, splits)):\n es = make_entityset(data, nclusters, kmeans=kmeans)[0]\n old_fm = ft.calculate_feature_matrix(\n entityset=es,\n features=features,\n cutoff_time=cutoff_time_list[i],\n )\n old_fm_list.append(fm)\n\nold_scores = []\nmedian_scores = []\n\nfor fm in old_fm_list:\n X = fm.copy().fillna(0)\n y = X.pop('remaining_useful_life')\n\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n\n reg = RandomForestRegressor(n_estimators=10)\n reg.fit(X_train, y_train)\n preds = reg.predict(X_test)\n\n mae = mean_absolute_error(preds, y_test)\n old_scores.append(mae)\n\n medianpredict = [np.median(y_train) for _ in y_test]\n mae = mean_absolute_error(medianpredict, y_test)\n median_scores.append(mae)\n\nprint([float('{:.1f}'.format(score)) for score in old_scores])\nmean, std = np.mean(old_scores), np.std(old_scores)\ninfo = 'Average MAE: {:.2f}, Std: {:.2f}\\n'\nprint(info.format(mean, std))\n\nprint([float('{:.1f}'.format(score)) for score in median_scores])\nmean, std = np.mean(median_scores), np.std(median_scores)\ninfo = 'Baseline by Median MAE: {:.2f}, Std: {:.2f}\\n'\nprint(info.format(mean, std))",
"Built 304 features\nElapsed: 01:54 | Progress: 100%|██████████"
],
[
"y = pd.read_csv(\n 'data/RUL_FD004.txt',\n sep=' ',\n header=None,\n names=['remaining_useful_life'],\n index_col=False,\n)\n\nmedian_scores_2 = []\n\nfor ct in cutoff_time_list:\n medianpredict2 = [np.median(ct['remaining_useful_life'].values) for _ in y.values]\n mae = mean_absolute_error(medianpredict2, y)\n median_scores_2.append(mae)\n\nprint([float('{:.1f}'.format(score)) for score in median_scores_2])\nmean, std = np.mean(median_scores_2), np.std(median_scores_2)\ninfo = 'Baseline by Median MAE: {:.2f}, Std: {:.2f}\\n'\nprint(info.format(mean, std))",
"[47.4, 48.1, 47.4, 46.7, 46.5]\nBaseline by Median MAE: 47.18, Std: 0.58\n\n"
],
[
"# Save output files\nos.makedirs(\"output\", exist_ok=True)\nfm.to_csv('output/advanced_train_feature_matrix.csv')\ncutoff_time_list[0].to_csv('output/advanced_train_label_times.csv')\nfm_test.to_csv('output/advanced_test_feature_matrix.csv')",
"_____no_output_____"
]
],
[
[
"<p>\n <img src=\"https://www.featurelabs.com/wp-content/uploads/2017/12/logo.png\" alt=\"Featuretools\" />\n</p>\n\nFeaturetools was created by the developers at [Feature Labs](https://www.featurelabs.com/). If building impactful data science pipelines is important to you or your business, please [get in touch](https://www.featurelabs.com/contact).",
"_____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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb477a85ce2499775ec64d3d4a2cac7a992af4ff | 23,326 | ipynb | Jupyter Notebook | financial_modeling/DCF_model/Bilibili_re.ipynb | linusqzdeng/pyfinance | f8a1c137acbbe4a43d915b2bff15760764a6b97d | [
"MIT"
] | 1 | 2022-01-05T09:28:03.000Z | 2022-01-05T09:28:03.000Z | financial_modeling/DCF_model/Bilibili_re.ipynb | linusqzdeng/pyfinance | f8a1c137acbbe4a43d915b2bff15760764a6b97d | [
"MIT"
] | null | null | null | financial_modeling/DCF_model/Bilibili_re.ipynb | linusqzdeng/pyfinance | f8a1c137acbbe4a43d915b2bff15760764a6b97d | [
"MIT"
] | 1 | 2022-01-05T01:20:58.000Z | 2022-01-05T01:20:58.000Z | 30.491503 | 140 | 0.366458 | [
[
[
"# Bilibili's Cost of Equity",
"_____no_output_____"
],
[
"### Import essential libraries",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport datetime as dt \nimport statsmodels.api as sm\nfrom pandas_datareader import DataReader as web",
"_____no_output_____"
]
],
[
[
"### Fetch daily stock prices from yahoo",
"_____no_output_____"
]
],
[
[
"start_date = dt.date(2018, 3, 28)\nend_date = dt.date.today()\n\ntickers = ['BILI', '^GSPC', '^TNX'] # Tickers for Bilibili, S&P500 and US 10-year treasury bond",
"_____no_output_____"
],
[
"df = pd.DataFrame()\n\nfor ticker in tickers:\n df[ticker] = web(ticker, 'yahoo', start_date, end_date)['Adj Close']",
"_____no_output_____"
],
[
"df.rename(columns={'^GSPC': 'S&P 500', '^TNX': '10-year T-bills'}, inplace=True)\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Convert stock prices into daily returns",
"_____no_output_____"
]
],
[
[
"stock_returns = df.copy()\nstock_returns.dropna(inplace=True)\n\nfor column in df.columns[:2]:\n# stock_returns[column] = np.log(stock_returns[column]) - np.log(stock_returns[column].shift(1))\n stock_returns[column] = stock_returns[column].pct_change()\n\nstock_returns.head()",
"_____no_output_____"
]
],
[
[
"### Presenting OLS estimation of beta",
"_____no_output_____"
]
],
[
[
"risk_free = stock_returns['10-year T-bills'].mean() / 100 # Average bond yield\n\nstock_returns.dropna(inplace=True)\nstock_returns['MRP'] = stock_returns['S&P 500'] - risk_free\nstock_returns.head()",
"_____no_output_____"
],
[
"X = sm.add_constant(stock_returns['MRP'])\ny = stock_returns['BILI']\n\nreg_model = sm.OLS(y, X)\nresults = reg_model.fit()\nresults.summary()",
"_____no_output_____"
],
[
"beta = results.params['MRP']\nbeta",
"_____no_output_____"
]
],
[
[
"### Using CAPM to calculate the cost of equity",
"_____no_output_____"
]
],
[
[
"market_return = stock_returns['S&P 500'].mean() # obtain expected return for market portfolio\n\nre = risk_free + beta * (market_return - risk_free)\nre",
"_____no_output_____"
],
[
"market_return",
"_____no_output_____"
],
[
"risk_free",
"_____no_output_____"
],
[
"stock_returns[stock_returns['S&P 500'] < 0.0005]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb479e69f8d083bd55c69461bfc87d1b94263cfa | 51,083 | ipynb | Jupyter Notebook | Ex 1_Iris Flower B.ipynb | SalustianoGSS/Salusttiano | 4a7bf8f2f9559c276f2a49f2e62693715868c4cc | [
"Apache-2.0"
] | null | null | null | Ex 1_Iris Flower B.ipynb | SalustianoGSS/Salusttiano | 4a7bf8f2f9559c276f2a49f2e62693715868c4cc | [
"Apache-2.0"
] | null | null | null | Ex 1_Iris Flower B.ipynb | SalustianoGSS/Salusttiano | 4a7bf8f2f9559c276f2a49f2e62693715868c4cc | [
"Apache-2.0"
] | null | null | null | 97.486641 | 19,920 | 0.861872 | [
[
[
"# Tutorial Machine Learning\nEXERCÍCIO 1_Iris Flower B",
"_____no_output_____"
],
[
"### 1. Livrarias a utilizar",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"### 2. Importação dos dados",
"_____no_output_____"
],
[
"#### Importamos o dataset para iniciar a análise",
"_____no_output_____"
]
],
[
[
"iris=pd.read_csv('IRIS.csv')",
"_____no_output_____"
]
],
[
[
"#### Visualizamos os 5 primeiros dados do dataset",
"_____no_output_____"
]
],
[
[
"print(iris.head())",
" sepal_length sepal_width petal_length petal_width species\n0 5.1 3.5 1.4 0.2 Iris-setosa\n1 4.9 3.0 1.4 0.2 Iris-setosa\n2 4.7 3.2 1.3 0.2 Iris-setosa\n3 4.6 3.1 1.5 0.2 Iris-setosa\n4 5.0 3.6 1.4 0.2 Iris-setosa\n"
]
],
[
[
"### 3. Analisando os dados",
"_____no_output_____"
],
[
"#### Analisamos os dados que temos disponíveis",
"_____no_output_____"
]
],
[
[
"print('Informação do datasete:')",
"Informação do datasete:\n"
],
[
"print(iris.info())",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 150 entries, 0 to 149\nData columns (total 5 columns):\nsepal_length 150 non-null float64\nsepal_width 150 non-null float64\npetal_length 150 non-null float64\npetal_width 150 non-null float64\nspecies 150 non-null object\ndtypes: float64(4), object(1)\nmemory usage: 5.9+ KB\nNone\n"
],
[
"print('Descrição das species de Iris')",
"Descrição das species de Iris\n"
],
[
"print('Distribuição das species de Iris')",
"Distribuição das species de Iris\n"
],
[
"print(iris.groupby('species').size())",
"species\nIris-setosa 50\nIris-versicolor 50\nIris-virginica 50\ndtype: int64\n"
]
],
[
[
"### 4. Visualização dos dados",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"#### Gráfico da Sépala - Comprimento Vs Largura",
"_____no_output_____"
]
],
[
[
"fig=iris[iris.species=='Iris-setosa'].plot(kind='scatter', x='sepal_length', y='sepal_width', color='blue', label='Iris-setosa')\nfig=iris[iris.species=='Iris-versicolor'].plot(kind='scatter', x='sepal_length', y='sepal_width', color='green', label='Iris-versicolor', ax=fig)\nfig=iris[iris.species=='Iris-virginica'].plot(kind='scatter', x='sepal_length', y='sepal_width', color='red', label='Iris-virginica', ax=fig)\nfig.set_xlabel('Sépala - Comprimento')\nfig.set_ylabel('Sépala - Largura')\nfig.set_title('Sépala - Comprimento Vs Largura')\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Gráfico da Pétala - Comprimento Vs Largura",
"_____no_output_____"
]
],
[
[
"fig=iris[iris.species=='Iris-setosa'].plot(kind='scatter', x='petal_length', y='petal_width', color='blue', label='Iris-setosa')\nfig=iris[iris.species=='Iris-versicolor'].plot(kind='scatter', x='petal_length', y='petal_width', color='green', label='Iris-versicolor', ax=fig)\nfig=iris[iris.species=='Iris-virginica'].plot(kind='scatter', x='petal_length', y='petal_width', color='red', label='Iris-virginica', ax=fig)\nfig.set_xlabel('Pétala - Comprimento')\nfig.set_ylabel('Pétala - Largura')\nfig.set_title('Pétala - Comprimento Vs Largura')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 5. Aplicação de algoritmos de Machine Learning",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier",
"_____no_output_____"
]
],
[
[
"### 6. Modelo com todos os dados",
"_____no_output_____"
],
[
"#### Separar todos os dados com as características e os rótulos ou resultados",
"_____no_output_____"
]
],
[
[
"x=np.array(iris.drop(['species'], 1))",
"_____no_output_____"
],
[
"y=np.array(iris['species'])",
"_____no_output_____"
]
],
[
[
"#### Separar os dados de treinamento e teste para utilização dos algoritmos",
"_____no_output_____"
]
],
[
[
"x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2)",
"_____no_output_____"
],
[
"print('São {} dados para treinamento e {} dados para teste'.format(x_train.shape[0], x_test.shape[0]))",
"São 120 dados para treinamento e 30 dados para teste\n"
]
],
[
[
"#### Modelo de Regressão logística",
"_____no_output_____"
]
],
[
[
"algoritmo=LogisticRegression()\nalgoritmo.fit(x_train, y_train)\ny_pred=algoritmo.predict(x_test)\nprint ('Precisão Regressão Logística:{}'.format(algoritmo.score(x_train, y_train)))",
"Precisão Regressão Logística:0.9583333333333334\n"
]
],
[
[
"#### Modelo de Máquinas de Vetores de Suporte",
"_____no_output_____"
]
],
[
[
"algoritmo=SVC()\nalgoritmo.fit(x_train, y_train)\ny_pred=algoritmo.predict(x_test)\nprint ('Precisão Máquinas de Vetores de Suport:{}'.format(algoritmo.score(x_train, y_train)))",
"Precisão Máquinas de Vetores de Suport:0.9833333333333333\n"
]
],
[
[
"#### Modelo de vizinhos mais próximos",
"_____no_output_____"
]
],
[
[
"algoritmo=KNeighborsClassifier(n_neighbors=5)\nalgoritmo.fit(x_train, y_train)\ny_pred=algoritmo.predict(x_test)\nprint ('Precisão Vizinhos mais próximos:{}'.format(algoritmo.score(x_train, y_train)))",
"Precisão Vizinhos mais próximos:0.9583333333333334\n"
]
],
[
[
"#### Modelo de Árvore de Decisão Classificação",
"_____no_output_____"
]
],
[
[
"algoritmo=DecisionTreeClassifier()\nalgoritmo.fit(x_train, y_train)\ny_pred=algoritmo.predict(x_test)\nprint ('Precisão Árvore de Decisão Classificação:{}'.format(algoritmo.score(x_train, y_train)))",
"Precisão Árvore de Decisão Classificação:1.0\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",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb47b1e955256ee78a873e1707e1c439da56a12d | 1,210 | ipynb | Jupyter Notebook | kaggle/titanic/Untitled.ipynb | JayMiao/MLAction | fec1c08fa33ed1f5d9b0befecc6dac551cc02302 | [
"MIT"
] | 1 | 2017-02-13T10:25:11.000Z | 2017-02-13T10:25:11.000Z | kaggle/titanic/Untitled.ipynb | JayMiao/MLAction | fec1c08fa33ed1f5d9b0befecc6dac551cc02302 | [
"MIT"
] | null | null | null | kaggle/titanic/Untitled.ipynb | JayMiao/MLAction | fec1c08fa33ed1f5d9b0befecc6dac551cc02302 | [
"MIT"
] | null | null | null | 18.90625 | 43 | 0.449587 | [
[
[
"import numpy as np\nfrom sklearn import preprocessing\nX = [[ 1., -1., 2.],\n [ 2., 0., 0.],\n [ 0., 1., -1.]]\npreprocessing.normalize(X, norm='l1')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
cb47c63fb6dc1c18ee36a908033975093f3a0e4b | 21,462 | ipynb | Jupyter Notebook | TwitterSentimentAnalysis.ipynb | RahulSingh1594/TwitterSentimentAnalysis | b8acd7322a7cdb216b5abb7e8d25705ea6824127 | [
"MIT"
] | null | null | null | TwitterSentimentAnalysis.ipynb | RahulSingh1594/TwitterSentimentAnalysis | b8acd7322a7cdb216b5abb7e8d25705ea6824127 | [
"MIT"
] | null | null | null | TwitterSentimentAnalysis.ipynb | RahulSingh1594/TwitterSentimentAnalysis | b8acd7322a7cdb216b5abb7e8d25705ea6824127 | [
"MIT"
] | null | null | null | 47.482301 | 7,888 | 0.638477 | [
[
[
"import pandas as pd\nimport re\nimport string\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.naive_bayes import MultinomialNB\npd.set_option(\"display.max_colwidth\",100)\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression",
"_____no_output_____"
],
[
"train_data=pd.read_csv(\"train_tweets.csv\")\ntest_data=pd.read_csv(\"test_tweets.csv\")",
"_____no_output_____"
],
[
"train_data.head()",
"_____no_output_____"
],
[
"train_data[\"text_length\"]=train_data[\"tweet\"].apply(lambda x: len(x)-x.count(\" \"))\ntest_data[\"text_length\"]=test_data[\"tweet\"].apply(lambda x: len(x)-x.count(\" \"))",
"_____no_output_____"
],
[
"def count_punct(text):\n count=sum([1 for char in text if char in string.punctuation])\n return round(count/(len(text)-text.count(\" \")),2)*100\ntrain_data[\"punct%\"]=train_data[\"tweet\"].apply(lambda x:count_punct(x))\ntest_data[\"punct%\"]=test_data[\"tweet\"].apply(lambda x:count_punct(x))\ntrain_data.head()",
"_____no_output_____"
],
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nbins=np.linspace(0,200,40)\nplt.hist(train_data[train_data[\"label\"]==0][\"text_length\"],bins,normed=True,alpha=0.5,label=\"Love\")\nplt.hist(train_data[train_data[\"label\"]==1][\"text_length\"],bins,normed=True,alpha=0.5,label=\"Hate\")\nplt.legend(loc=\"upper left\")\n",
"C:\\Users\\Rahul Singh\\Anaconda3\\lib\\site-packages\\matplotlib\\axes\\_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.\n warnings.warn(\"The 'normed' kwarg is deprecated, and has been \"\n"
],
[
"sw=stopwords.words(\"english\")",
"_____no_output_____"
],
[
"ps=nltk.PorterStemmer()\ndef clean_tweets(text):\n l=\"\".join([char for char in text if char not in string.punctuation])\n w=re.split(\"\\W+\", l)\n te=\" \".join([word.lower() for word in w if word.lower() not in sw])\n #text=\" \".join([ps.stem(word) for word in te])\n return text",
"_____no_output_____"
],
[
"train_data[\"tweet\"]=train_data[\"tweet\"].apply(lambda x:clean_tweets(x))\ntest_data[\"tweet\"]=test_data[\"tweet\"].apply(lambda x:clean_tweets(x))",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\ntrain_x,test_x,train_y, test_y=train_test_split(train_data[\"tweet\"],train_data[\"label\"], test_size=0.3, random_state=0)",
"_____no_output_____"
],
[
"vec=CountVectorizer()\ntrain_x=vec.fit_transform(train_x)\ntest_x=vec.transform(test_x)",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score\nmod=RandomForestClassifier()\nmod.fit(train_x,train_y)\naccuracy_score(test_y,mod.predict(test_x))",
"_____no_output_____"
],
[
"model=SGDClassifier()\nmodel.fit(train_x,train_y)\naccuracy_score(test_y,model.predict(test_x))",
"C:\\Users\\Rahul Singh\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\stochastic_gradient.py:128: FutureWarning: max_iter and tol parameters have been added in <class 'sklearn.linear_model.stochastic_gradient.SGDClassifier'> in 0.19. If both are left unset, they default to max_iter=5 and tol=None. If tol is not None, max_iter defaults to max_iter=1000. From 0.21, default max_iter will be 1000, and default tol will be 1e-3.\n \"and default tol will be 1e-3.\" % type(self), FutureWarning)\n"
],
[
"model=MultinomialNB()\nmodel.fit(train_x,train_y)\naccuracy_score(test_y,model.predict(test_x))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb47db72f9c2dadd0495f6086b5c8e649d82ff24 | 188,666 | ipynb | Jupyter Notebook | source_synphot.ipynb | CheerfulUser/source_synphot | a66b2172e229922fcd09020ff94243dd56ac7378 | [
"MIT"
] | null | null | null | source_synphot.ipynb | CheerfulUser/source_synphot | a66b2172e229922fcd09020ff94243dd56ac7378 | [
"MIT"
] | null | null | null | source_synphot.ipynb | CheerfulUser/source_synphot | a66b2172e229922fcd09020ff94243dd56ac7378 | [
"MIT"
] | 1 | 2020-05-05T04:38:41.000Z | 2020-05-05T04:38:41.000Z | 70.345265 | 30,259 | 0.671812 | [
[
[
"import source_synphot.passband\nimport source_synphot.io\nimport source_synphot.source\nimport astropy.table as at\nfrom collections import OrderedDict\nimport pysynphot as S\n%matplotlib notebook\n%pylab",
"Using matplotlib backend: nbAgg\nPopulating the interactive namespace from numpy and matplotlib\n"
],
[
"def myround(x, prec=2, base=.5):\n return round(base * round(float(x)/base),prec)",
"_____no_output_____"
],
[
"models = at.Table.read('ckmodels.txt',format='ascii')\nlogZ = 0.\nmodel_sed_names = []\ntemp = []\nfor s in models:\n teff = max(3500.,s['teff'])\n logg = myround(s['logg'])\n # the models with logg < 1 are just padded with 0s\n if logg >= 1:\n temp.append(teff)\n modstring = 'ckmod{:.0f}_{:.1f}_{:.2f}'.format(teff,logZ, logg)\n model_sed_names.append(modstring)\nmodel_sed = source_synphot.source.load_source(model_sed_names)",
"_____no_output_____"
],
[
"passbands = at.Table.read('source_synphot/passbands/pbzptmag.txt',format='ascii')\npbnames = [x['obsmode'] for x in passbands if x['passband'].startswith(\"WFIRST\")]\nmodel_mags = 0.\nmodel = 'AB'\npbnames += ['sdss,g', 'sdss,r', 'sdss,i', 'sdss,z']\npbs = source_synphot.passband.load_pbs(pbnames, model_mags, model)\npbnames = pbs.keys()",
"Passband passbands/WFIRST/W149_Aeff_norm_new.dat could not be loaded from any source.\n"
],
[
"print(pbnames)",
"odict_keys(['R606', 'Z087', 'Y106', 'J129', 'H158', 'F184', 'sdss,g', 'sdss,r', 'sdss,i', 'sdss,z'])\n"
],
[
"color1 = 'sdss,g_sdss,r'\ncolor2 = 'sdss,r_sdss,i'\ncol1 = []\ncol2 = []\n# construct color-color vectors\nfor modelname in model_sed:\n model= model_sed[modelname]\n model = S.ArraySpectrum(model.wave, model.flux, name=modelname)\n c1, c2 = color1.split('_')\n pb1, zp1 = pbs[c1]\n pb2, zp2 = pbs[c2]\n c3, c4 = color2.split('_')\n pb3, zp3 = pbs[c3]\n pb4, zp4 = pbs[c4]\n thiscol1 = source_synphot.passband.syncolor(model, pb1, pb2, zp1, zp2)\n thiscol2 = source_synphot.passband.syncolor(model, pb3, pb4, zp3, zp4)\n col1.append(thiscol1)\n col2.append(thiscol2)\ncol1 = array(col1)\ncol2 = array(col2)\n# select only useful objects\ngood = ~isnan(col1)* ~isnan(col2)\ngood = array(good)",
"/Users/gnarayan/work/source_synphot/source_synphot/passband.py:117: RuntimeWarning: divide by zero encountered in log10\n m1 = -2.5*np.log10(flux1) + zp1\n/Users/gnarayan/work/source_synphot/source_synphot/passband.py:119: RuntimeWarning: divide by zero encountered in log10\n m2 = -2.5*np.log10(flux2) + zp2\n/Users/gnarayan/work/source_synphot/source_synphot/passband.py:120: RuntimeWarning: invalid value encountered in double_scalars\n return m1-m2\n"
],
[
"\nfrom astroML.plotting import scatter_contour\nfrom astroML.datasets import fetch_sdss_S82standards\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=True)\n\ndata = fetch_sdss_S82standards()\n\ng = data['mmu_g']\nr = data['mmu_r']\ni = data['mmu_i']\n\nfig, ax = plt.subplots(figsize=(6, 6))\nscatter_contour(g - r, r - i, threshold=200, log_counts=True, ax=ax,\n histogram2d_args=dict(bins=40),\n plot_args=dict(marker=',', linestyle='none', color='black'),\n contour_args=dict(cmap=plt.cm.bone))\n\nax.set_xlabel(r'${\\rm g - r}$')\nax.set_ylabel(r'${\\rm r - i}$')\n\nax.set_xlim(-0.6, 2.5)\nax.set_ylim(-0.6, 2.5)\nplot(col1[good], col2[good], marker='o', linestyle='None')",
"_____no_output_____"
],
[
"z = linspace(1e-8, 0.2, 1000, endpoint=True)",
"_____no_output_____"
],
[
"outspec = source_synphot.source.pre_process_source('./sn2000fa-20001215.flm',15.3,pbs['sdss,r'][0],0.021)",
"/Users/gnarayan/work/source_synphot/source_synphot/source.py:107: RuntimeWarning: Spectrum ./sn2000fa-20001215.flm not listed in lookup table\n warnings.warn(message, RuntimeWarning)\n"
],
[
"figure()\nplot(outspec.wave, outspec.flux)\nsource_synphot.passband.synphot(outspec, pbs['sdss,r'][0], zp=pbs['sdss,r'][1])\n# if you believe the observations, this should be kinda like the absolute magnitude of an SNIa at peak.",
"_____no_output_____"
],
[
"mag = source_synphot.passband.synphot_over_redshifts(outspec, z, pbs['sdss,r'][0], pbs['sdss,r'][1])",
"_____no_output_____"
],
[
"figure()\nplot(z, mag)\nxscale('log')",
"_____no_output_____"
],
[
"ind = np.abs(z-0.021).argmin()\nprint(mag[ind])\n# We should get back what we normalized to for input at the same redshift. Not bad!",
"15.2848569524\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb47dd9c5605d9014315bf045a0f39cf795d6269 | 20,385 | ipynb | Jupyter Notebook | content/lessons/11/Class-Coding-Lab/CCL-Web-Services-And-APIs.ipynb | mikiec84/learn-python | 130685d4ceb2892fecad69f9ea2f25959e562242 | [
"MIT"
] | null | null | null | content/lessons/11/Class-Coding-Lab/CCL-Web-Services-And-APIs.ipynb | mikiec84/learn-python | 130685d4ceb2892fecad69f9ea2f25959e562242 | [
"MIT"
] | null | null | null | content/lessons/11/Class-Coding-Lab/CCL-Web-Services-And-APIs.ipynb | mikiec84/learn-python | 130685d4ceb2892fecad69f9ea2f25959e562242 | [
"MIT"
] | null | null | null | 35.207254 | 383 | 0.597351 | [
[
[
"# In-Class Coding Lab: Web Services and APIs\n\n### Overview\n\nThe web has long evolved from user-consumption to device consumption. In the early days of the web when you wanted to check the weather, you opened up your browser and visited a website. Nowadays your smart watch / smart phone retrieves the weather for you and displays it on the device. Your device can't predict the weather. It's simply consuming a weather based service. \n\nThe key to making device consumption work are API's (Application Program Interfaces). Products we use everyday like smartphones, Amazon's Alexa, and gaming consoles all rely on API's. They seem \"smart\" and \"powerful\" but in actuality they're only interfacing with smart and powerful services in the cloud.\n\nAPI consumption is the new reality of programming; it is why we cover it in this course. Once you undersand how to conusme API's you can write a program to do almost anything and harness the power of the internet to make your own programs look \"smart\" and \"powerful.\" \n\nThis lab covers how to properly use consume web service API's with Python. Here's what we will cover.\n\n1. Understading requests and responses\n1. Proper error handling\n1. Parameter handling\n1. Refactoring as a function\n",
"_____no_output_____"
]
],
[
[
"# Run this to make sure you have the pre-requisites!\n!pip install -q requests",
"_____no_output_____"
]
],
[
[
"## Part 1: Understanding Requests and responses\n\nIn this part we learn about the Python requests module. http://docs.python-requests.org/en/master/user/quickstart/ \n\nThis module makes it easy to write code to send HTTP requests over the internet and handle the responses. It will be the cornerstone of our API consumption in this course. While there are other modules which accomplish the same thing, `requests` is the most straightforward and easiest to use.\n\nWe'll begin by importing the modules we will need. We do this here so we won't need to include these lines in the other code we write in this lab.",
"_____no_output_____"
]
],
[
[
"# start by importing the modules we will need\nimport requests\nimport json ",
"_____no_output_____"
]
],
[
[
"### The request \n\nAs you learned in class and your assigned readings, the HTTP protocol has **verbs** which consititue the type of request you will send to the remote resource, or **url**. Based on the url and request type, you will get a **response**.\n\nThe following line of code makes a **get** request (that's the HTTP verb) to Google's Geocoding API service. This service attempts to convert the address (in this case `Syracuse University`) into a set of coordinates global coordinates (Latitude and Longitude), so that location can be plotted on a map.\n",
"_____no_output_____"
]
],
[
[
"url = 'https://nominatim.openstreetmap.org/search?q=Hinds+Hall+Syracuse+University&format=json'\nresponse = requests.get(url)",
"_____no_output_____"
]
],
[
[
"### The response \n\nThe `get()` method returns a `Response` object variable. I called it `response` in this example but it could be called anything. \n\nThe HTTP response consists of a *status code* and *body*. The status code lets you know if the request worked, while the body of the response contains the actual data. \n",
"_____no_output_____"
]
],
[
[
"response.ok # did the request work?",
"_____no_output_____"
],
[
"response.text # what's in the body of the response, as a raw string",
"_____no_output_____"
]
],
[
[
"### Converting responses into Python object variables \n\nIn the case of **web site url's** the response body is **HTML**. This should be rendered in a web browser. But we're dealing with Web Service API's so...\n\nIn the case of **web API url's** the response body could be in a variety of formats from **plain text**, to **XML** or **JSON**. In this course we will only focus on JSON format because as we've seen these translate easily into Python object variables.\n\nLet's convert the response to a Python object variable. I this case it will be a Python dictionary",
"_____no_output_____"
]
],
[
[
"geodata = response.json() # try to decode the response from JSON format\ngeodata # this is now a Python object variable",
"_____no_output_____"
]
],
[
[
"With our Python object, we can now walk the list of dictionary to retrieve the latitude and longitude\n",
"_____no_output_____"
]
],
[
[
"lat = geodata[0]['lat']\nlon =geodata[0]['lon']\nprint(lat, lon)",
"_____no_output_____"
]
],
[
[
"In the code above we \"walked\" the Python list of dictionary to get to the location\n\n- `geodata` is a list\n- `geodata[0]` is the first item in that list, a dictionary\n- `geodata[0]['lat']` is a dictionary key which represents the latitude \n- `geodata[0]['lon']` is a dictionary key which represents the longitude\n\nIt should be noted that this process will vary for each API you call, so its important to get accustomed to performing this task. You'll be doing it quite often. \n\nOne final thing to address. What is the type of `lat` and `lon`?",
"_____no_output_____"
]
],
[
[
"type(lat), type(lon)",
"_____no_output_____"
]
],
[
[
"Bummer they are strings. we want them to be floats so we will need to parse the strings with the `float()` function:",
"_____no_output_____"
]
],
[
[
"lat = float(geodata[0]['lat'])\nlon = float(geodata[0]['lon'])\nprint(\"Latitude: %f, Longitude: %f\" % (lat, lon))",
"_____no_output_____"
]
],
[
[
"### Now You Try It!\n\nWalk the `geodata` object variable and reteieve the value under the key `display_name` and the key `bounding_box`",
"_____no_output_____"
]
],
[
[
"# todo:\n# retrieve the place_id put in a variable\n# retrieve the formatted_address put it in a variable\n# print both of them out\n\n\n",
"_____no_output_____"
]
],
[
[
"## Part 2: Parameter Handling\n\nIn the example above we hard-coded \"Hinds Hall Syracuse University\" into the request:\n```\nurl = 'https://nominatim.openstreetmap.org/search?q=Hinds+Hall+Syracuse+University&format=json'\n``` \nA better way to write this code is to allow for the input of any location and supply that to the service. To make this work we need to send parameters into the request as a dictionary. This way we can geolocate any address!\n\nYou'll notice that on the url, we are passing **key-value pairs** the key is `q` and the value is `Hinds+Hall+Syracuse+University`. The other key is `format` and the value is `json`. Hey, Python dictionaries are also key-value pairs so:",
"_____no_output_____"
]
],
[
[
"url = 'https://nominatim.openstreetmap.org/search' # base URL without paramters after the \"?\"\nsearch = 'Hinds Hall Syracuse University'\noptions = { 'q' : search, 'format' : 'json'}\nresponse = requests.get(url, params = options) \ngeodata = response.json()\ncoords = { 'lat' : float(geodata[0]['lat']), 'lng' : float(geodata[0]['lon']) }\nprint(\"Search for:\", search)\nprint(\"Coordinates:\", coords)\nprint(\"%s is located at (%f,%f)\" %(search, coords['lat'], coords['lng']))",
"_____no_output_____"
]
],
[
[
"### Looking up any address\n\nRECALL: For `requests.get(url, params = options)` the part that says `params = options` is called a **named argument**, which is Python's way of specifying an optional function argument.\n\nWith our parameter now outside the url, we can easily re-write this code to work for any location! Go ahead and execute the code and input `Queens, NY`. This will retrieve the coordinates `(40.728224,-73.794852)`",
"_____no_output_____"
]
],
[
[
"url = 'https://nominatim.openstreetmap.org/search' # base URL without paramters after the \"?\"\nsearch = input(\"Enter a loacation to Geocode: \")\noptions = { 'q' : search, 'format' : 'json'}\nresponse = requests.get(url, params = options) \ngeodata = response.json()\ncoords = { 'lat' : float(geodata[0]['lat']), 'lng' : float(geodata[0]['lon']) }\nprint(\"Search for:\", search)\nprint(\"Coordinates:\", coords)\nprint(\"%s is located at (%f,%f)\" %(search, coords['lat'], coords['lng']))",
"_____no_output_____"
]
],
[
[
"### So useful, it should be a function!\n\nOne thing you'll come to realize quickly is that your API calls should be wrapped in functions. This promotes **readability** and **code re-use**. For example:",
"_____no_output_____"
]
],
[
[
"def get_coordinates(search):\n url = 'https://nominatim.openstreetmap.org/search' # base URL without paramters after the \"?\"\n options = { 'q' : search, 'format' : 'json'}\n response = requests.get(url, params = options) \n geodata = response.json()\n coords = { 'lat' : float(geodata[0]['lat']), 'lng' : float(geodata[0]['lon']) }\n return coords\n\n# main program here:\nlocation = input(\"Enter a location: \")\ncoords = get_coordinates(location)\nprint(\"%s is located at (%f,%f)\" %(location, coords['lat'], coords['lng']))\n",
"_____no_output_____"
]
],
[
[
"### Other request methods\n\nNot every API we call uses the `get()` method. Some use `post()` because the amount of data you provide it too large to place on the url. \n\nAn example of this is the **Text-Processing.com** sentiment analysis service. http://text-processing.com/docs/sentiment.html This service will detect the sentiment or mood of text. You give the service some text, and it tells you whether that text is positive, negative or neutral. ",
"_____no_output_____"
]
],
[
[
"# 'you suck' == 'negative'\nurl = 'http://text-processing.com/api/sentiment/'\noptions = { 'text' : 'you suck'}\nresponse = requests.post(url, data = options)\nsentiment = response.json()\nsentiment",
"_____no_output_____"
],
[
"# 'I love cheese' == 'positive'\nurl = 'http://text-processing.com/api/sentiment/'\noptions = { 'text' : 'I love cheese'}\nresponse = requests.post(url, data = options)\nsentiment = response.json()\nsentiment",
"_____no_output_____"
]
],
[
[
"In the examples provided we used the `post()` method instead of the `get()` method. the `post()` method has a named argument `data` which takes a dictionary of data. The key required by **text-processing.com** is `text` which hold the text you would like to process for sentiment.\n\nWe use a post in the event the text we wish to process is very long. Case in point:",
"_____no_output_____"
]
],
[
[
"tweet = \"Arnold Schwarzenegger isn't voluntarily leaving the Apprentice, he was fired by his bad (pathetic) ratings, not by me. Sad end to a great show\"\nurl = 'http://text-processing.com/api/sentiment/'\noptions = { 'text' : tweet }\nresponse = requests.post(url, data = options)\nsentiment = response.json()\nsentiment",
"_____no_output_____"
]
],
[
[
"### Now You Try It!\n\nUse the above example to write a program which will input any text and print the sentiment using this API!",
"_____no_output_____"
]
],
[
[
"# todo write code here\n\n",
"_____no_output_____"
]
],
[
[
"\n## Part 3: Proper Error Handling (In 3 Simple Rules)\n\nWhen you write code that depends on other people's code from around the Internet, there's a lot that can go wrong. Therefore we perscribe the following advice:\n\n```\nAssume anything that CAN go wrong WILL go wrong\n```\n",
"_____no_output_____"
],
[
"### Rule 1: Don't assume the internet 'always works'\n\nThe first rule of programming over a network is to NEVER assume the network is available. You need to assume the worst. No WiFi, user types in a bad url, the remote website is down, etc. \n\nWe handle this in the `requests` module by catching the `requests.exceptions.RequestException` Here's an example:",
"_____no_output_____"
]
],
[
[
"url = \"http://this is not a website\"\ntry:\n\n response = requests.get(url) # throws an exception when it cannot connect\n\n# internet is broken\nexcept requests.exceptions.RequestException as e:\n print(\"ERROR: Cannot connect to \", url)\n print(\"DETAILS:\", e)",
"_____no_output_____"
]
],
[
[
"### Rule 2: Don't assume the response you get back is valid\n\nAssuming the internet is not broken (Rule 1) You should now check for HTTP response 200 which means the url responded successfully. Other responses like 404 or 501 indicate an error occured and that means you should not keep processing the response.\n\nHere's one way to do it:",
"_____no_output_____"
]
],
[
[
"url = 'http://www.syr.edu/mikeisawesum' # this should 404\ntry:\n \n response = requests.get(url)\n \n if response.ok: # same as response.status_code == 200\n data = response.text\n else: # Some other non 200 response code\n print(\"There was an Error requesting:\", url, \" HTTP Response Code: \", response.status_code)\n\n# internet is broken\nexcept requests.exceptions.RequestException as e: \n print(\"ERROR: Cannot connect to \", url)\n print(\"DETAILS:\", e)\n",
"_____no_output_____"
]
],
[
[
"### Rule 2a: Use exceptions instead of if else in this case\n\nPersonally I don't like to use `if ... else` to handle an error. Instead, I prefer to instruct `requests` to throw an exception of `requests.exceptions.HTTPError` whenever the response is not ok. This makes the code you write a little cleaner.\n\nErrors are rare occurences, and so I don't like error handling cluttering up my code. \n",
"_____no_output_____"
]
],
[
[
"url = 'http://www.syr.edu/mikeisawesum' # this should 404\ntry:\n \n response = requests.get(url) # throws an exception when it cannot connect\n response.raise_for_status() # throws an exception when not 'ok'\n data = response.text\n\n# response not ok\nexcept requests.exceptions.HTTPError as e:\n print(\"ERROR: Response from \", url, 'was not ok.')\n print(\"DETAILS:\", e)\n \n# internet is broken\nexcept requests.exceptions.RequestException as e: \n print(\"ERROR: Cannot connect to \", url)\n print(\"DETAILS:\", e)\n",
"_____no_output_____"
]
],
[
[
"### Rule 3: Don't assume the data you get back is the data you expect.\n\nAnd finally, do not assume the data arriving the the `response` is the data you expected. Specifically when you try and decode the `JSON` don't assume that will go smoothly. Catch the `json.decoder.JSONDecodeError`.",
"_____no_output_____"
]
],
[
[
"url = 'http://www.syr.edu' # this is HTML, not JSON\ntry:\n\n response = requests.get(url) # throws an exception when it cannot connect\n response.raise_for_status() # throws an exception when not 'ok'\n data = response.json() # throws an exception when cannot decode json\n \n# cannot decode json\nexcept json.decoder.JSONDecodeError as e: \n print(\"ERROR: Cannot decode the response into json\")\n print(\"DETAILS\", e)\n\n# response not ok\nexcept requests.exceptions.HTTPError as e:\n print(\"ERROR: Response from \", url, 'was not ok.')\n print(\"DETAILS:\", e)\n \n# internet is broken\nexcept requests.exceptions.RequestException as e: \n print(\"ERROR: Cannot connect to \", url)\n print(\"DETAILS:\", e)",
"_____no_output_____"
]
],
[
[
"### Now You try it!\n\nUsing the last example above, write a program to input a location, call the `get_coordinates()` function, then print the coordindates. Make sure to handle all three types of exceptions!!!\n",
"_____no_output_____"
]
],
[
[
"# todo write code here to input a location, look up coordinates, and print\n# it should handle errors!!!\n\n\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb47e376a48edbdd30d15c9849144db881de740f | 14,540 | ipynb | Jupyter Notebook | test/Models/energybalance_pkg/test/cs/Soilevaporation.ipynb | cyrillemidingoyi/PyCropML | b866cc17374424379142d9162af985c1f87c74b6 | [
"MIT"
] | 5 | 2020-06-21T18:58:04.000Z | 2022-01-29T21:32:28.000Z | test/Models/energybalance_pkg/test/cs/Soilevaporation.ipynb | cyrillemidingoyi/PyCropML | b866cc17374424379142d9162af985c1f87c74b6 | [
"MIT"
] | 27 | 2018-12-04T15:35:44.000Z | 2022-03-11T08:25:03.000Z | test/Models/energybalance_pkg/test/cs/Soilevaporation.ipynb | cyrillemidingoyi/PyCropML | b866cc17374424379142d9162af985c1f87c74b6 | [
"MIT"
] | 7 | 2019-04-20T02:25:22.000Z | 2021-11-04T07:52:35.000Z | 37.282051 | 143 | 0.515337 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb47e4f2b997fb989e94568530583655d5d522ec | 844,304 | ipynb | Jupyter Notebook | hangul_analysis/notebooks/umap.ipynb | BouchardLab/HangulFontsDatasetGenerator | 307fe0d3533a62e286b53aa71885a0af79456bab | [
"BSD-3-Clause-LBNL"
] | null | null | null | hangul_analysis/notebooks/umap.ipynb | BouchardLab/HangulFontsDatasetGenerator | 307fe0d3533a62e286b53aa71885a0af79456bab | [
"BSD-3-Clause-LBNL"
] | null | null | null | hangul_analysis/notebooks/umap.ipynb | BouchardLab/HangulFontsDatasetGenerator | 307fe0d3533a62e286b53aa71885a0af79456bab | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-07-14T20:17:41.000Z | 2021-07-14T20:17:41.000Z | 3,138.67658 | 382,560 | 0.956398 | [
[
[
"%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nfrom hangul.read_data import load_data, load_all_labels, load_images\nimport umap\nimport pandas as pd\nfrom sklearn.decomposition import PCA, FastICA\nfrom scipy.stats import gaussian_kde\nfrom bokeh.palettes import Greys256, Inferno256, Plasma256, inferno, viridis, grey\nimport matplotlib.font_manager as mfm\nfrom hangul import style",
"_____no_output_____"
],
[
"fonts = ['GothicA1-Regular', 'NanumMyeongjo', 'NanumBrush', 'Stylish-Regular']",
"_____no_output_____"
],
[
"fontsfolder = '/data/hangul/h5s'\nfontnames = os.listdir(fontsfolder)",
"_____no_output_____"
],
[
"for font in [fonts[0]]:\n filename = os.path.join(fontsfolder, '{}/{}_24.h5'.format(font, font))\n image, label, initial, medial, final = load_data(filename, median_shape=True)\n imf, style = load_all_labels(filename)",
"_____no_output_____"
],
[
"font_path = \"/home/ahyeon96/GothicA1-Regular.ttf\"\nprop = mfm.FontProperties(fname=font_path)",
"_____no_output_____"
],
[
"image = image.reshape(11172,-1)",
"_____no_output_____"
],
[
"emb = umap.UMAP(random_state=0, learning_rate=0.01, n_neighbors = 100).fit_transform(image)\nnp.savez('/home/ahyeon96/hangul_misc/umap_emb.npz', data=emb)",
"_____no_output_____"
],
[
"emb = np.load('/home/ahyeon96/hangul_misc/umap_emb.npz')\nemb = emb['data']\nx = emb[:,0]\ny = emb[:,1]\nxmin = np.min(x)\nxmax = np.max(x)\nymin = np.min(y)\nymax = np.max(y)\nX, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\npositions = np.vstack([X.ravel(), Y.ravel()])\nvalues = np.vstack([x, y])\nkernel = gaussian_kde(values)\nZ = np.reshape(kernel(positions).T, X.shape)",
"_____no_output_____"
],
[
"# appendix figure 9\n\nfig, axes = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(18,6))\ntitle = ['Initial', 'Medial', 'Final']\nabc = ['A', 'B', 'C']\nranges = [19,21,28]\n\ninit_chars = ['ᆨ', 'ᆩ', 'ᆫ', 'ᆮ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']\nmed_chars = ['ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ',\n 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ']\nfin_chars = ['', 'ㄱ', 'ㄲ', 'ᆪ', 'ㄴ', 'ᆬ', 'ᆭ', 'ㄷ', 'ㄹ', 'ᆰ', 'ᆱ', 'ᆲ', 'ᆳ', 'ᆴ', 'ᆵ', 'ᆶ',\n 'ㅁ', 'ㅂ', 'ᆹ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']\nsmall = ['ᆪ', 'ㄴ', 'ᆬ', 'ᆭ','ᆰ', 'ᆱ', 'ᆲ', 'ᆳ', 'ᆴ', 'ᆵ', 'ᆶ','ᆹ']\nlabel_name = [init_chars, med_chars, fin_chars]\nsizes = [10,10,8]\nints = [21*28,19*28,19*21]\neps = 0.3\n\nfor i in range(3):\n lab = label[:,i]\n axes[i].imshow(np.rot90(Z), cmap=plt.cm.Reds, extent=[xmin, xmax, ymin, ymax], vmin=np.min(Z), vmax=1.5*np.max(Z), aspect='auto',\n rasterized=True)\n for k in range(ranges[i]):\n idxs = np.nonzero(lab == k)[0]\n for j in np.random.permutation(ints[i])[:sizes[i]]:\n xj = x[idxs[j]]\n yj = y[idxs[j]]\n if (abs(xj-xmax) > eps) and (abs(xj-xmin) > eps) and (abs(yj-ymax) > eps) and (abs(yj-ymin) > eps):\n if label_name[i][k] in small:\n axes[i].text(xj, yj, label_name[i][k], fontproperties=prop, fontsize=28,\n horizontalalignment='center', verticalalignment='center')\n else:\n axes[i].text(xj, yj, label_name[i][k], fontproperties=prop, fontsize=20,\n horizontalalignment='center', verticalalignment='center')\n axes[i].set_xlim([xmin, xmax])\n axes[i].set_ylim([ymin, ymax])\n axes[i].set_title('GothicA1-Regular {}'.format(title[i]), fontsize=22)\n axes[i].text(-5.5,10, '{}'.format(abc[i]), fontsize=22, fontweight='bold')\nplt.tight_layout()\nplt.savefig('/home/ahyeon96/hangul_misc/umap_chars.png', dpi=300)\nplt.show()",
"_____no_output_____"
],
[
"# umap single font\nlabel_type = ['Initial', 'Medial', 'Final']\nlabel_num = [19,21,28]\n\nfig, ax = plt.subplots(1,3, sharey=True, figsize=(25,5))\nfor i in range(3):\n labels = label[:,i]\n transformed_umap = umap.UMAP(random_state=0, learning_rate=0.01, n_neighbors = 100).fit_transform(image)\n g = ax[i].scatter(transformed_umap[:,0], transformed_umap[:,1], c=labels, cmap=plt.get_cmap(\"jet\", label_num[i]), marker='.', alpha=0.5)\n ax[i].set_title('UMAP AppleGothic {}'.format(label_type[i]), fontsize=20)\n plt.colorbar(g, ticks=range(label_num[i]), ax=ax[i])\nplt.savefig('/Users/ahyeon/Desktop/umap_single.pdf')\nplt.show()",
"_____no_output_____"
],
[
"# appendix figure 10 \n\nlabel_type = ['Initial', 'Medial', 'Final']\nlabel_num = [2,5,3]\nplot_labs = ['A', 'B', 'C']\ncolorbar_labs = [['single','double'],['below','right-single','right-double','below-right-single','below-right-double'],\n ['none','single','double']]\nticks = [[0.25, 0.75],[0.4,1.2,2,2.8,3.6],[0.35,1,1.65]]\n\n\nf, ax = plt.subplots(1,3, sharey=True, figsize=(24,6))\nimage = image.reshape(11172,-1)\nfor i in range(3):\n labels = style[:,i]\n g = ax[i].scatter(emb[:,0], emb[:,1], c=labels, cmap=plt.get_cmap(\"viridis\", label_num[i]), marker='.')\n ax[i].set_title('GothicA1-Regular\\n {} Geometry'.format(label_type[i]), fontsize=20)\n ax[i].text(-7,10, plot_labs[i], fontweight='bold', fontsize=26)\n cbar = plt.colorbar(g, ticks=ticks[i], ax=ax[i])\n cbar.ax.set_yticklabels(colorbar_labs[i], fontsize=12)\nplt.tight_layout()\nplt.savefig('/home/ahyeon96/hangul_misc/umap_geometry.pdf', dpi=300, bbox_inches='tight')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb47e543c7354e8c6cd0b2890e7d924fc8953f87 | 20,756 | ipynb | Jupyter Notebook | 2) Rotten Tomatoes Movie Score/Rotten Tomatoes Movies - Roger Ebert Reviews.ipynb | marcellovictorino/DAND_4_Data_Wrangling | 99c51dce11cf09c97811effed28a96d7fd537fa4 | [
"MIT"
] | null | null | null | 2) Rotten Tomatoes Movie Score/Rotten Tomatoes Movies - Roger Ebert Reviews.ipynb | marcellovictorino/DAND_4_Data_Wrangling | 99c51dce11cf09c97811effed28a96d7fd537fa4 | [
"MIT"
] | null | null | null | 2) Rotten Tomatoes Movie Score/Rotten Tomatoes Movies - Roger Ebert Reviews.ipynb | marcellovictorino/DAND_4_Data_Wrangling | 99c51dce11cf09c97811effed28a96d7fd537fa4 | [
"MIT"
] | null | null | null | 57.655556 | 199 | 0.591443 | [
[
[
"%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom bs4 import BeautifulSoup\nimport os\nimport unicodedata",
"_____no_output_____"
]
],
[
[
"## Reviews from Roger Ebert",
"_____no_output_____"
]
],
[
[
"# Reading Roger Ebert review from text files online\nimport requests\nimport glob\n\nfolder = 'ebert_reviews'\n# Create folder if it doesn't already exists\nif not os.path.exists(folder):\n os.makedirs(folder)",
"_____no_output_____"
],
[
"ebert_review_urls = ['https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9900_1-the-wizard-of-oz-1939-film/1-the-wizard-of-oz-1939-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9901_2-citizen-kane/2-citizen-kane.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9901_3-the-third-man/3-the-third-man.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9902_4-get-out-film/4-get-out-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9902_5-mad-max-fury-road/5-mad-max-fury-road.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9902_6-the-cabinet-of-dr.-caligari/6-the-cabinet-of-dr.-caligari.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9903_7-all-about-eve/7-all-about-eve.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9903_8-inside-out-2015-film/8-inside-out-2015-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9903_9-the-godfather/9-the-godfather.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9904_10-metropolis-1927-film/10-metropolis-1927-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9904_11-e.t.-the-extra-terrestrial/11-e.t.-the-extra-terrestrial.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9904_12-modern-times-film/12-modern-times-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9904_14-singin-in-the-rain/14-singin-in-the-rain.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9905_15-boyhood-film/15-boyhood-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9905_16-casablanca-film/16-casablanca-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9905_17-moonlight-2016-film/17-moonlight-2016-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9906_18-psycho-1960-film/18-psycho-1960-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9906_19-laura-1944-film/19-laura-1944-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9906_20-nosferatu/20-nosferatu.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9907_21-snow-white-and-the-seven-dwarfs-1937-film/21-snow-white-and-the-seven-dwarfs-1937-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9907_22-a-hard-day27s-night-film/22-a-hard-day27s-night-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9907_23-la-grande-illusion/23-la-grande-illusion.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9908_25-the-battle-of-algiers/25-the-battle-of-algiers.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9908_26-dunkirk-2017-film/26-dunkirk-2017-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9908_27-the-maltese-falcon-1941-film/27-the-maltese-falcon-1941-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9909_29-12-years-a-slave-film/29-12-years-a-slave-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9909_30-gravity-2013-film/30-gravity-2013-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9909_31-sunset-boulevard-film/31-sunset-boulevard-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990a_32-king-kong-1933-film/32-king-kong-1933-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990a_33-spotlight-film/33-spotlight-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990a_34-the-adventures-of-robin-hood/34-the-adventures-of-robin-hood.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990b_35-rashomon/35-rashomon.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990b_36-rear-window/36-rear-window.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990b_37-selma-film/37-selma-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990c_38-taxi-driver/38-taxi-driver.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990c_39-toy-story-3/39-toy-story-3.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990c_40-argo-2012-film/40-argo-2012-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990d_41-toy-story-2/41-toy-story-2.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990d_42-the-big-sick/42-the-big-sick.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990d_43-bride-of-frankenstein/43-bride-of-frankenstein.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990d_44-zootopia/44-zootopia.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990e_45-m-1931-film/45-m-1931-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990e_46-wonder-woman-2017-film/46-wonder-woman-2017-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990e_48-alien-film/48-alien-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990f_49-bicycle-thieves/49-bicycle-thieves.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990f_50-seven-samurai/50-seven-samurai.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad990f_51-the-treasure-of-the-sierra-madre-film/51-the-treasure-of-the-sierra-madre-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9910_52-up-2009-film/52-up-2009-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9910_53-12-angry-men-1957-film/53-12-angry-men-1957-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9910_54-the-400-blows/54-the-400-blows.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9911_55-logan-film/55-logan-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9911_57-army-of-shadows/57-army-of-shadows.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9912_58-arrival-film/58-arrival-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9912_59-baby-driver/59-baby-driver.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9913_60-a-streetcar-named-desire-1951-film/60-a-streetcar-named-desire-1951-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9913_61-the-night-of-the-hunter-film/61-the-night-of-the-hunter-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9913_62-star-wars-the-force-awakens/62-star-wars-the-force-awakens.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9913_63-manchester-by-the-sea-film/63-manchester-by-the-sea-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9914_64-dr.-strangelove/64-dr.-strangelove.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9914_66-vertigo-film/66-vertigo-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9914_67-the-dark-knight-film/67-the-dark-knight-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9915_68-touch-of-evil/68-touch-of-evil.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9915_69-the-babadook/69-the-babadook.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9915_72-rosemary27s-baby-film/72-rosemary27s-baby-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9916_73-finding-nemo/73-finding-nemo.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9916_74-brooklyn-film/74-brooklyn-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9917_75-the-wrestler-2008-film/75-the-wrestler-2008-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9917_77-l.a.-confidential-film/77-l.a.-confidential-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9918_78-gone-with-the-wind-film/78-gone-with-the-wind-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9918_79-the-good-the-bad-and-the-ugly/79-the-good-the-bad-and-the-ugly.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9918_80-skyfall/80-skyfall.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9919_82-tokyo-story/82-tokyo-story.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9919_83-hell-or-high-water-film/83-hell-or-high-water-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9919_84-pinocchio-1940-film/84-pinocchio-1940-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad9919_85-the-jungle-book-2016-film/85-the-jungle-book-2016-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991a_86-la-la-land-film/86-la-la-land-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991b_87-star-trek-film/87-star-trek-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991b_89-apocalypse-now/89-apocalypse-now.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991c_90-on-the-waterfront/90-on-the-waterfront.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991c_91-the-wages-of-fear/91-the-wages-of-fear.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991c_92-the-last-picture-show/92-the-last-picture-show.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991d_93-harry-potter-and-the-deathly-hallows-part-2/93-harry-potter-and-the-deathly-hallows-part-2.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991d_94-the-grapes-of-wrath-film/94-the-grapes-of-wrath-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991d_96-man-on-wire/96-man-on-wire.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991e_97-jaws-film/97-jaws-film.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991e_98-toy-story/98-toy-story.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991e_99-the-godfather-part-ii/99-the-godfather-part-ii.txt',\n 'https://d17h27t6h515a5.cloudfront.net/topher/2017/September/59ad991e_100-battleship-potemkin/100-battleship-potemkin.txt']",
"_____no_output_____"
],
[
"# access url, read content and write to local file\nfor url in ebert_review_urls:\n r = requests.get(url)\n with open(os.path.join(folder, url.split('/')[-1]),encoding='utf-8', 'wb') as file:\n file.write(r.content)",
"_____no_output_____"
],
[
"len(os.listdir(folder))",
"_____no_output_____"
]
],
[
[
"Note not all 100 movies have been reviewed by Roger Ebert. As a matter of fact, we only have 88 out of the 100 best movies list.",
"_____no_output_____"
]
],
[
[
"# Parsing each Review\nreview_list = []\n\n# read all txt files in folder\nfor review in glob.glob(folder+'/*.txt'):\n with open(review, encoding='utf-8') as file:\n title = file.readline().strip()\n review_url = file.readline().strip()\n review_text = file.read().strip()\n \n review_dict = {'title': title, 'review_url': review_url, 'review': review_text}\n review_list.append(review_dict)",
"_____no_output_____"
],
[
"df_reviews = pd.DataFrame(review_list, columns=review_dict.keys())\ndf_reviews = df_reviews.sort_values('title').reset_index(drop=True)\ndf_reviews.head()",
"_____no_output_____"
],
[
"# Saving it locally\ndf_reviews.to_csv('movies_review_text.csv', index=False)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb47e783205612961b935a0e7f46ed535f4777e7 | 37,310 | ipynb | Jupyter Notebook | dev/15_callback_hook.ipynb | tianjianjiang/fastai_dev | cc8e2d64c330c1a93dd84c854b12e700c7d68a8b | [
"Apache-2.0"
] | 1 | 2021-01-24T23:17:50.000Z | 2021-01-24T23:17:50.000Z | dev/15_callback_hook.ipynb | tianjianjiang/fastai_dev | cc8e2d64c330c1a93dd84c854b12e700c7d68a8b | [
"Apache-2.0"
] | null | null | null | dev/15_callback_hook.ipynb | tianjianjiang/fastai_dev | cc8e2d64c330c1a93dd84c854b12e700c7d68a8b | [
"Apache-2.0"
] | 1 | 2019-08-30T14:34:07.000Z | 2019-08-30T14:34:07.000Z | 30.91135 | 400 | 0.542294 | [
[
[
"#export\nfrom local.torch_basics import *\nfrom local.test import *\nfrom local.layers import *\nfrom local.data.all import *\nfrom local.notebook.showdoc import show_doc\nfrom local.optimizer import *\nfrom local.learner import *",
"_____no_output_____"
],
[
"#default_exp callback.hook",
"_____no_output_____"
]
],
[
[
"# Model hooks\n\n> Callback and helper function to add hooks in models",
"_____no_output_____"
]
],
[
[
"from local.utils.test import *",
"_____no_output_____"
]
],
[
[
"## What are hooks?",
"_____no_output_____"
],
[
"Hooks are function you can attach to a particular layer in your model and that will be executed in the foward pass (for forward hooks) or backward pass (for backward hooks). Here we begin with an introduction around hooks, but you should jump to `HookCallback` if you quickly want to implemet one (and read the following example `ActivationStats`).\n\nForward hooks are functions that take three arguments, the layer it's applied to, the input of that layer and the output of that layer.",
"_____no_output_____"
]
],
[
[
"tst_model = nn.Linear(5,3)\ndef example_forward_hook(m,i,o): print(m,i,o)\n \nx = torch.randn(4,5)\nhook = tst_model.register_forward_hook(example_forward_hook)\ny = tst_model(x)\nhook.remove()",
"Linear(in_features=5, out_features=3, bias=True) (tensor([[ 0.8686, 0.7311, 2.4489, 0.8700, -0.1670],\n [ 0.6731, 1.0484, 1.9074, 0.6036, 0.2924],\n [ 1.8885, -0.7867, -0.1672, 0.6644, 0.0809],\n [ 0.2057, -0.7538, 0.7381, -1.3444, -0.7304]]),) tensor([[-1.6029, 0.3864, -0.6523],\n [-1.5455, 0.2899, -0.3769],\n [-0.2761, -0.7362, -1.2814],\n [ 0.3392, -0.5898, -0.3673]], grad_fn=<AddmmBackward>)\n"
]
],
[
[
"Backward hooks are functions that take three arguments: the layer it's applied to, the gradients of the loss with respect to the input, and the gradients with respect to the output.",
"_____no_output_____"
]
],
[
[
"def example_backward_hook(m,gi,go): print(m,gi,go)\nhook = tst_model.register_backward_hook(example_backward_hook)\n\nx = torch.randn(4,5)\ny = tst_model(x)\nloss = y.pow(2).mean()\nloss.backward()\nhook.remove()",
"Linear(in_features=5, out_features=3, bias=True) (tensor([ 0.0678, -0.3397, -0.0614]), None, tensor([[ 0.1027, -0.1562, -0.1236],\n [-0.4457, 0.3023, 0.1885],\n [ 0.0831, 0.1418, 0.1246],\n [-0.6508, 0.6550, -0.0966],\n [-0.2673, -0.0194, -0.0025]])) (tensor([[ 0.0574, -0.1234, -0.1313],\n [-0.1468, 0.0679, 0.0180],\n [ 0.1980, -0.1640, 0.0177],\n [-0.0408, -0.1202, 0.0341]]),)\n"
]
],
[
[
"Hooks can change the input/output of a layer, or the gradients, print values or shapes. If you want to store something related to theses inputs/outputs, it's best to have you hook associated to a class so that it can put it in the state of an instance of that class.",
"_____no_output_____"
],
[
"## Hook -",
"_____no_output_____"
]
],
[
[
"#export\n@docs\nclass Hook():\n \"Create a hook on `m` with `hook_func`.\"\n def __init__(self, m, hook_func, is_forward=True, detach=True, cpu=False):\n self.hook_func,self.detach,self.cpu,self.stored = hook_func,detach,cpu,None\n f = m.register_forward_hook if is_forward else m.register_backward_hook\n self.hook = f(self.hook_fn)\n self.removed = False\n\n def hook_fn(self, module, input, output):\n \"Applies `hook_func` to `module`, `input`, `output`.\"\n if self.detach: input,output = to_detach(input, cpu=self.cpu),to_detach(output, cpu=self.cpu)\n self.stored = self.hook_func(module, input, output)\n\n def remove(self):\n \"Remove the hook from the model.\"\n if not self.removed:\n self.hook.remove()\n self.removed=True\n\n def __enter__(self, *args): return self\n def __exit__(self, *args): self.remove()\n\n _docs = dict(__enter__=\"Register the hook\",\n __exit__=\"Remove the hook\")",
"_____no_output_____"
]
],
[
[
"This will be called during the forward pass if `is_forward=True`, the backward pass otherwise, and will optionally `detach` and put on the `cpu` the (gradient of the) input/output of the model before passing them to `hook_func`. The result of `hook_func` will be stored in the `stored` attribute of the `Hook`.",
"_____no_output_____"
]
],
[
[
"tst_model = nn.Linear(5,3)\nhook = Hook(tst_model, lambda m,i,o: o)\ny = tst_model(x)\ntest_eq(hook.stored, y)",
"_____no_output_____"
],
[
"show_doc(Hook.hook_fn)",
"_____no_output_____"
],
[
"show_doc(Hook.remove)",
"_____no_output_____"
]
],
[
[
"> Note: It's important to properly remove your hooks for your model when you're done to avoid them being called again next time your model is applied to some inputs, and to free the memory that go with their state.",
"_____no_output_____"
]
],
[
[
"tst_model = nn.Linear(5,10)\nx = torch.randn(4,5)\ny = tst_model(x)\nhook = Hook(tst_model, example_forward_hook)\ntest_stdout(lambda: tst_model(x), f\"{tst_model} ({x},) {y.detach()}\")\nhook.remove()\ntest_stdout(lambda: tst_model(x), \"\")",
"_____no_output_____"
]
],
[
[
"### Context Manager",
"_____no_output_____"
],
[
"Since it's very important to remove your `Hook` even if your code is interrupted by some bug, `Hook` can be used as context managers.",
"_____no_output_____"
]
],
[
[
"show_doc(Hook.__enter__)",
"_____no_output_____"
],
[
"show_doc(Hook.__exit__)",
"_____no_output_____"
],
[
"tst_model = nn.Linear(5,10)\nx = torch.randn(4,5)\ny = tst_model(x)\nwith Hook(tst_model, example_forward_hook) as h:\n test_stdout(lambda: tst_model(x), f\"{tst_model} ({x},) {y.detach()}\")\ntest_stdout(lambda: tst_model(x), \"\")",
"_____no_output_____"
],
[
"#export\ndef _hook_inner(m,i,o): return o if isinstance(o,Tensor) or is_listy(o) else list(o)\n\ndef hook_output(module, detach=True, cpu=False, grad=False):\n \"Return a `Hook` that stores activations of `module` in `self.stored`\"\n return Hook(module, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad)",
"_____no_output_____"
]
],
[
[
"The activations stored are the gradients if `grad=True`, otherwise the output of `module`. If `detach=True` they are detached from their history, and if `cpu=True`, they're put on the CPU.",
"_____no_output_____"
]
],
[
[
"tst_model = nn.Linear(5,10)\nx = torch.randn(4,5)\nwith hook_output(tst_model) as h:\n y = tst_model(x)\n test_eq(y, h.stored)\n assert not h.stored.requires_grad\n \nwith hook_output(tst_model, grad=True) as h:\n y = tst_model(x)\n loss = y.pow(2).mean()\n loss.backward()\n test_close(2*y / y.numel(), h.stored[0])",
"_____no_output_____"
],
[
"#cuda\nwith hook_output(tst_model, cpu=True) as h:\n y = tst_model.cuda()(x.cuda())\n test_eq(h.stored.device, torch.device('cpu'))",
"_____no_output_____"
]
],
[
[
"## Hooks -",
"_____no_output_____"
]
],
[
[
"#export\n@docs\nclass Hooks():\n \"Create several hooks on the modules in `ms` with `hook_func`.\"\n def __init__(self, ms, hook_func, is_forward=True, detach=True, cpu=False):\n self.hooks = [Hook(m, hook_func, is_forward, detach, cpu) for m in ms]\n\n def __getitem__(self,i): return self.hooks[i]\n def __len__(self): return len(self.hooks)\n def __iter__(self): return iter(self.hooks)\n @property\n def stored(self): return [o.stored for o in self]\n\n def remove(self):\n \"Remove the hooks from the model.\"\n for h in self.hooks: h.remove()\n\n def __enter__(self, *args): return self\n def __exit__ (self, *args): self.remove()\n\n _docs = dict(stored = \"The states saved in each hook.\",\n __enter__=\"Register the hooks\",\n __exit__=\"Remove the hooks\")",
"_____no_output_____"
],
[
"layers = [nn.Linear(5,10), nn.ReLU(), nn.Linear(10,3)]\ntst_model = nn.Sequential(*layers)\nhooks = Hooks(tst_model, lambda m,i,o: o)\ny = tst_model(x)\ntest_eq(hooks.stored[0], layers[0](x))\ntest_eq(hooks.stored[1], F.relu(layers[0](x)))\ntest_eq(hooks.stored[2], y)\nhooks.remove()",
"_____no_output_____"
],
[
"show_doc(Hooks.stored, name='Hooks.stored')",
"_____no_output_____"
],
[
"show_doc(Hooks.remove)",
"_____no_output_____"
]
],
[
[
"### Context Manager",
"_____no_output_____"
],
[
"Like `Hook` , you can use `Hooks` as context managers.",
"_____no_output_____"
]
],
[
[
"show_doc(Hooks.__enter__)",
"_____no_output_____"
],
[
"show_doc(Hooks.__exit__)",
"_____no_output_____"
],
[
"layers = [nn.Linear(5,10), nn.ReLU(), nn.Linear(10,3)]\ntst_model = nn.Sequential(*layers)\nwith Hooks(layers, lambda m,i,o: o) as h:\n y = tst_model(x)\n test_eq(h.stored[0], layers[0](x))\n test_eq(h.stored[1], F.relu(layers[0](x)))\n test_eq(h.stored[2], y)",
"_____no_output_____"
],
[
"#export\ndef hook_outputs(modules, detach=True, cpu=False, grad=False):\n \"Return `Hooks` that store activations of all `modules` in `self.stored`\"\n return Hooks(modules, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad)",
"_____no_output_____"
]
],
[
[
"The activations stored are the gradients if `grad=True`, otherwise the output of `modules`. If `detach=True` they are detached from their history, and if `cpu=True`, they're put on the CPU.",
"_____no_output_____"
]
],
[
[
"layers = [nn.Linear(5,10), nn.ReLU(), nn.Linear(10,3)]\ntst_model = nn.Sequential(*layers)\nx = torch.randn(4,5)\nwith hook_outputs(layers) as h:\n y = tst_model(x)\n test_eq(h.stored[0], layers[0](x))\n test_eq(h.stored[1], F.relu(layers[0](x)))\n test_eq(h.stored[2], y)\n for s in h.stored: assert not s.requires_grad\n \nwith hook_outputs(layers, grad=True) as h:\n y = tst_model(x)\n loss = y.pow(2).mean()\n loss.backward()\n g = 2*y / y.numel()\n test_close(g, h.stored[2][0])\n g = g @ layers[2].weight.data\n test_close(g, h.stored[1][0])\n g = g * (layers[0](x) > 0).float()\n test_close(g, h.stored[0][0])",
"_____no_output_____"
],
[
"#cuda\nwith hook_outputs(tst_model, cpu=True) as h:\n y = tst_model.cuda()(x.cuda())\n for s in h.stored: test_eq(s.device, torch.device('cpu'))",
"_____no_output_____"
]
],
[
[
"## HookCallback -",
"_____no_output_____"
],
[
"To make hooks easy to use, we wrapped a version in a Callback where you just have to implement a `hook` function (plus any element you might need).",
"_____no_output_____"
]
],
[
[
"#export\ndef has_params(m):\n \"Check if `m` has at least one parameter\"\n return len(list(m.parameters())) > 0",
"_____no_output_____"
],
[
"assert has_params(nn.Linear(3,4))\nassert has_params(nn.LSTM(4,5,2))\nassert not has_params(nn.ReLU())",
"_____no_output_____"
],
[
"#export\nclass HookCallback(Callback):\n \"`Callback` that can be used to register hooks on `modules`\"\n def __init__(self, hook=None, modules=None, do_remove=True, is_forward=True, detach=True, cpu=False):\n self.modules,self.do_remove = modules,do_remove\n self.is_forward,self.detach,self.cpu = is_forward,detach,cpu\n if hook is not None: setattr(self, 'hook', hook)\n\n def begin_fit(self):\n \"Register the `Hooks` on `self.modules`.\"\n if not self.modules:\n self.modules = [m for m in flatten_model(self.model) if has_params(m)]\n self.hooks = Hooks(self.modules, self.hook, self.is_forward, self.detach, self.cpu)\n\n def after_fit(self):\n \"Remove the `Hooks`.\"\n if self.do_remove: self._remove()\n\n def _remove(self):\n if getattr(self, 'hooks', None): self.hooks.remove()\n\n def __del__(self): self._remove()",
"_____no_output_____"
]
],
[
[
"You can either subclass and implement a `hook` function (along with any event you want) or pass that a `hook` function when initializing. Such a function needs to take three argument: a layer, input and output (for a backward hook, input means gradient with respect to the inputs, output, gradient with respect to the output) and can either modify them or update the state according to them.\n\nIf not provided, `modules` will default to the layers of `self.model` that have a `weight` attribute. Depending on `do_remove`, the hooks will be properly removed at the end of training (or in case of error). `is_forward` , `detach` and `cpu` are passed to `Hooks`.\n\nThe function called at each forward (or backward) pass is `self.hook` and must be implemented when subclassing this callback.",
"_____no_output_____"
]
],
[
[
"class TstCallback(HookCallback):\n def hook(self, m, i, o): return o\n def after_batch(self): test_eq(self.hooks.stored[0], self.pred)\n \nlearn = synth_learner(n_trn=5, cbs = TstCallback())\nlearn.fit(1)",
"[0, 9.737648010253906, 6.20616340637207, '00:00']\n"
],
[
"class TstCallback(HookCallback):\n def __init__(self, modules=None, do_remove=True, detach=True, cpu=False):\n super().__init__(None, modules, do_remove, False, detach, cpu)\n def hook(self, m, i, o): return o\n def after_batch(self):\n if self.training:\n test_eq(self.hooks.stored[0][0], 2*(self.pred-self.yb)/self.pred.shape[0])\n \nlearn = synth_learner(n_trn=5, cbs = TstCallback())\nlearn.fit(1)",
"[0, 10.041898727416992, 6.416956901550293, '00:00']\n"
],
[
"show_doc(HookCallback.begin_fit)",
"_____no_output_____"
],
[
"show_doc(HookCallback.after_fit)",
"_____no_output_____"
]
],
[
[
"An example of such a `HookCallback` is the following, that stores the mean and stds of activations that go through the network.",
"_____no_output_____"
]
],
[
[
"#exports\n@docs\nclass ActivationStats(HookCallback):\n \"Callback that record the mean and std of activations.\"\n\n def begin_fit(self):\n \"Initialize stats.\"\n super().begin_fit()\n self.stats = []\n\n def hook(self, m, i, o): return o.mean().item(),o.std().item()\n\n def after_batch(self):\n \"Take the stored results and puts it in `self.stats`\"\n if self.training: self.stats.append(self.hooks.stored)\n\n def after_fit(self):\n \"Polish the final result.\"\n self.stats = tensor(self.stats).permute(2,1,0)\n super().after_fit()\n\n _docs = dict(hook=\"Take the mean and std of the output\")",
"_____no_output_____"
],
[
"learn = synth_learner(n_trn=5, cbs = ActivationStats())\nlearn.fit(1)",
"[0, 16.44314956665039, 9.00023078918457, '00:00']\n"
],
[
"learn.activation_stats.stats",
"_____no_output_____"
]
],
[
[
"The first line contains the means of the outputs of the model for each batch in the training set, the second line their standard deviations.",
"_____no_output_____"
]
],
[
[
"#hide\nclass TstCallback(HookCallback):\n def hook(self, m, i, o): return o\n def begin_fit(self):\n super().begin_fit()\n self.means,self.stds = [],[]\n \n def after_batch(self):\n if self.training:\n self.means.append(self.hooks.stored[0].mean().item())\n self.stds.append (self.hooks.stored[0].std() .item())\n\nlearn = synth_learner(n_trn=5, cbs = [TstCallback(), ActivationStats()])\nlearn.fit(1)\ntest_eq(learn.activation_stats.stats[0].squeeze(), tensor(learn.tst.means))\ntest_eq(learn.activation_stats.stats[1].squeeze(), tensor(learn.tst.stds))",
"[0, 20.896137237548828, 12.390987396240234, '00:00']\n"
]
],
[
[
"## Model summary",
"_____no_output_____"
]
],
[
[
"#export\ndef total_params(m):\n \"Give the number of parameters of a module and if it's trainable or not\"\n params = sum([p.numel() for p in m.parameters()])\n trains = [p.requires_grad for p in m.parameters()]\n return params, (False if len(trains)==0 else trains[0])",
"_____no_output_____"
],
[
"test_eq(total_params(nn.Linear(10,32)), (32*10+32,True))\ntest_eq(total_params(nn.Linear(10,32, bias=False)), (32*10,True))\ntest_eq(total_params(nn.BatchNorm2d(20)), (20*2, True))\ntest_eq(total_params(nn.BatchNorm2d(20, affine=False)), (0,False))\ntest_eq(total_params(nn.Conv2d(16, 32, 3)), (16*32*3*3 + 32, True))\ntest_eq(total_params(nn.Conv2d(16, 32, 3, bias=False)), (16*32*3*3, True))\n#First ih layer 20--10, all else 10--10. *4 for the four gates\ntest_eq(total_params(nn.LSTM(20, 10, 2)), (4 * (20*10 + 10) + 3 * 4 * (10*10 + 10), True))",
"_____no_output_____"
],
[
"#export\ndef layer_info(learn):\n def _track(m, i, o):\n return (m.__class__.__name__,)+total_params(m)+(apply(lambda x:x.shape, o),)\n layers = [m for m in flatten_model(learn.model)]\n xb,_ = learn.data.train_dl.one_batch()\n with Hooks(layers, _track) as h:\n _ = learn.model.eval()(apply(lambda o:o[:1], xb))\n return h.stored",
"_____no_output_____"
],
[
"m = nn.Sequential(nn.Linear(1,50), nn.ReLU(), nn.BatchNorm1d(50), nn.Linear(50, 1))\nlearn = synth_learner()\nlearn.model=m",
"_____no_output_____"
],
[
"test_eq(layer_info(learn), [\n ('Linear', 100, True, [1, 50]),\n ('ReLU', 0, False, [1, 50]),\n ('BatchNorm1d', 100, True, [1, 50]),\n ('Linear', 51, True, [1, 1])\n])",
"_____no_output_____"
],
[
"#export core\nclass PrettyString(str):\n \"Little hack to get strings to show properly in Jupyter.\"\n def __repr__(self): return self",
"_____no_output_____"
],
[
"#export\ndef _print_shapes(o, bs):\n if isinstance(o, torch.Size): return ' x '.join([str(bs)] + [str(t) for t in o[1:]])\n else: return [_print_shapes(x, bs) for x in o]",
"_____no_output_____"
],
[
"#export\n@patch\ndef summary(self:Learner):\n \"Print a summary of the model, optimizer and loss function.\"\n infos = layer_info(self)\n xb,_ = self.data.train_dl.one_batch()\n n,bs = 64,find_bs(xb)\n inp_sz = _print_shapes(apply(lambda x:x.shape, xb), bs)\n res = f\"{self.model.__class__.__name__} (Input shape: {inp_sz})\\n\"\n res += \"=\" * n + \"\\n\"\n res += f\"{'Layer (type)':<20} {'Output Shape':<20} {'Param #':<10} {'Trainable':<10}\\n\"\n res += \"=\" * n + \"\\n\"\n ps,trn_ps = 0,0\n for typ,np,trn,sz in infos:\n if sz is None: continue\n ps += np\n if trn: trn_ps += np\n res += f\"{typ:<20} {_print_shapes(sz, bs):<20} {np:<10,} {str(trn):<10}\\n\"\n res += \"_\" * n + \"\\n\"\n res += f\"\\nTotal params: {ps:,}\\n\"\n res += f\"Total trainable params: {trn_ps:,}\\n\"\n res += f\"Total non-trainable params: {ps - trn_ps:,}\\n\\n\"\n res += f\"Optimizer used: {self.opt_func}\\nLoss function: {self.loss_func}\\n\\nCallbacks:\\n\"\n res += '\\n'.join(f\" - {cb}\" for cb in sort_by_run(self.cbs))\n return PrettyString(res)",
"_____no_output_____"
],
[
"m = nn.Sequential(nn.Linear(1,50), nn.ReLU(), nn.BatchNorm1d(50), nn.Linear(50, 1))\nfor p in m[0].parameters(): p.requires_grad_(False)\nlearn = synth_learner()\nlearn.model=m\nlearn.summary()",
"_____no_output_____"
]
],
[
[
"## Export -",
"_____no_output_____"
]
],
[
[
"#hide\nfrom local.notebook.export import notebook2script\nnotebook2script(all_fs=True)",
"Converted 00_test.ipynb.\nConverted 01_core.ipynb.\nConverted 01a_dataloader.ipynb.\nConverted 01a_script.ipynb.\nConverted 02_transforms.ipynb.\nConverted 03_pipeline.ipynb.\nConverted 04_data_external.ipynb.\nConverted 05_data_core.ipynb.\nConverted 06_data_source.ipynb.\nConverted 07_vision_core.ipynb.\nConverted 08_pets_tutorial.ipynb.\nConverted 09_vision_augment.ipynb.\nConverted 11_layers.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_learner.ipynb.\nConverted 14_callback_schedule.ipynb.\nConverted 15_callback_hook.ipynb.\nConverted 16_callback_progress.ipynb.\nConverted 17_callback_tracker.ipynb.\nConverted 18_callback_fp16.ipynb.\nConverted 19_callback_mixup.ipynb.\nConverted 20_metrics.ipynb.\nConverted 21_tutorial_imagenette.ipynb.\nConverted 30_text_core.ipynb.\nConverted 31_text_data.ipynb.\nConverted 32_text_models_awdlstm.ipynb.\nConverted 33_test_models_core.ipynb.\nConverted 34_callback_rnn.ipynb.\nConverted 35_tutorial_wikitext.ipynb.\nConverted 36_text_models_qrnn.ipynb.\nConverted 40_tabular_core.ipynb.\nConverted 41_tabular_model.ipynb.\nConverted 50_data_block.ipynb.\nConverted 60_vision_models_xresnet.ipynb.\nConverted 90_notebook_core.ipynb.\nConverted 91_notebook_export.ipynb.\nConverted 92_notebook_showdoc.ipynb.\nConverted 93_notebook_export2html.ipynb.\nConverted 94_index.ipynb.\nConverted 95_synth_learner.ipynb.\nConverted notebook2jekyll.ipynb.\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb47e912b53227ce8f5ec27d896643f4f9240286 | 6,009 | ipynb | Jupyter Notebook | .ipynb_checkpoints/ANPRNN_1D_regression-checkpoint.ipynb | VersElectronics/Neural-Processes | 6eb7552a0d1c489189d6dd0f83704dcdbeaed24b | [
"MIT"
] | 5 | 2020-06-22T20:36:51.000Z | 2021-11-29T08:18:08.000Z | .ipynb_checkpoints/ANPRNN_1D_regression-checkpoint.ipynb | VersElectronics/Neural-Processes | 6eb7552a0d1c489189d6dd0f83704dcdbeaed24b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/ANPRNN_1D_regression-checkpoint.ipynb | VersElectronics/Neural-Processes | 6eb7552a0d1c489189d6dd0f83704dcdbeaed24b | [
"MIT"
] | 3 | 2021-08-08T11:38:21.000Z | 2022-01-19T11:39:47.000Z | 33.949153 | 280 | 0.537194 | [
[
[
"## Demo of 1D regression with an Attentive Neural Process with Recurrent Neural Network (ANP-RNN) model",
"_____no_output_____"
],
[
"This notebook will provide a simple and straightforward demonstration on how to utilize an Attentive Neural Process with a Recurrent Neural Network (ANP-RNN) to regress context and target points to a sine curve.\n\nFirst, we need to import all necessary packages and modules for our task:",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport torch\n# from matplotlib import pyplot as plt\n\n# Provide access to modules in repo.\nsys.path.insert(0, os.path.abspath('neural_process_models'))\nsys.path.insert(0, os.path.abspath('misc'))\n\nfrom neural_process_models.anp_rnn import ANP_RNN_Model\nfrom misc.test_sin_regression.Sin_Wave_Data import sin_wave_data, plot_functions",
"_____no_output_____"
]
],
[
[
"The `sin_wave_data` class, defined in `misc/test_sin_regression/Sin_Data_Wave.py`, represents the curve that we will try to regress to. From instances of this class, we are able to sample context and target points from the curve to serve as inputs for our neural process.\n\nThe default parameters of this class will produce a \"ground truth\" curve defined as the sum of the following:\n1. A sine curve with amplitude 1, frequency 1, and phase 1.\n2. A sine curve with amplitude 2, frequency 2, and phase 1.\n3. A measured amount of noise (0.1).\n\nLet us create an instance of this class:",
"_____no_output_____"
]
],
[
[
"data = sin_wave_data()",
"_____no_output_____"
]
],
[
[
"Next, we need to instantiate our model. The ANP model is implemented under the `NeuralProcessModel` class under the file `neural_process_models/attentive_neural_process.py`.\n\nWe will use the following parameters for our example model:\n* 1 for x-dimension and y-dimension (since this is 1D regression)\n* 4 hidden layers of dimension 256 for encoders and decoder\n* 256 as the latent dimension for encoders and decoder\n* We will utilize a self-attention process.\n* We will utilize a deterministic path for the encoder.\n\nLet us create an instance of this class, as well as set some hyperparameters for our training:",
"_____no_output_____"
]
],
[
[
"np_model = ANP_RNN_Model(x_dim=1,\n y_dim=1,\n mlp_hidden_size_list=[256, 256, 256, 256],\n latent_dim=256,\n use_rnn=True,\n use_self_attention=True,\n le_self_attention_type=\"laplace\",\n de_self_attention_type=\"laplace\",\n de_cross_attention_type=\"laplace\",\n use_deter_path=True)\n\noptim = torch.optim.Adam(np_model.parameters(), lr=1e-4)\n\nnum_epochs = 1000\nbatch_size = 16",
"_____no_output_____"
]
],
[
[
"Now, let us train our model. For each epoch, we will print the loss at that epoch.\n\nAdditionally, every 50 epochs, an image will be generated and displayed, using `pyplot`. This will give you an opportunity to more closely analyze and/or save the images, if you would like.",
"_____no_output_____"
]
],
[
[
"for epoch in range(1, num_epochs + 1):\n print(\"step = \" + str(epoch))\n\n np_model.train()\n\n plt.clf()\n optim.zero_grad()\n\n ctt_x, ctt_y, tgt_x, tgt_y = data.query(batch_size=batch_size,\n context_x_start=-6,\n context_x_end=6,\n context_x_num=200,\n target_x_start=-6,\n target_x_end=6,\n target_x_num=200)\n\n mu, sigma, log_p, kl, loss = np_model(ctt_x, ctt_y, tgt_x, tgt_y)\n\n print('loss = ', loss)\n loss.backward()\n optim.step()\n np_model.eval()\n \n if epoch % 50 == 0:\n plt.ion()\n plot_functions(tgt_x.numpy(),\n tgt_y.numpy(),\n ctt_x.numpy(),\n ctt_y.numpy(),\n mu.detach().numpy(),\n sigma.detach().numpy())\n title_str = 'Training at epoch ' + str(epoch)\n plt.title(title_str)\n plt.pause(0.1)\n\nplt.ioff()\nplt.show() ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb47f14189857acaa004926b08077a72b45cc4f7 | 28,258 | ipynb | Jupyter Notebook | labs/01_python/laboratorio_08.ipynb | andresmontecinos12/mat281_portfolio | 38036b441349f68f3d1224cf592864d84d26490b | [
"MIT"
] | 1 | 2020-10-01T16:06:54.000Z | 2020-10-01T16:06:54.000Z | labs/01_python/laboratorio_08.ipynb | andresmontecinos12/mat281_portfolio | 38036b441349f68f3d1224cf592864d84d26490b | [
"MIT"
] | null | null | null | labs/01_python/laboratorio_08.ipynb | andresmontecinos12/mat281_portfolio | 38036b441349f68f3d1224cf592864d84d26490b | [
"MIT"
] | null | null | null | 33.56057 | 711 | 0.522896 | [
[
[
"<img src=\"images/usm.jpg\" width=\"480\" height=\"240\" align=\"left\"/>",
"_____no_output_____"
],
[
"# MAT281 - Laboratorio N°02\n\n## Objetivos del laboratorio\n\n* Reforzar conceptos básicos de clasificación.",
"_____no_output_____"
],
[
"## Contenidos\n\n* [Problema 01](#p1)\n",
"_____no_output_____"
],
[
"<a id='p1'></a>\n## I.- Problema 01\n\n\n<img src=\"https://www.xenonstack.com/wp-content/uploads/xenonstack-credit-card-fraud-detection.png\" width=\"360\" height=\"360\" align=\"center\"/>\n\n\nEl conjunto de datos se denomina `creditcard.csv` y consta de varias columnas con información acerca del fraude de tarjetas de crédito, en donde la columna **Class** corresponde a: 0 si no es un fraude y 1 si es un fraude.\n\nEn este ejercicio se trabajará el problemas de clases desbalancedas. Veamos las primeras cinco filas dle conjunto de datos:",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score,recall_score,precision_score,f1_score\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\n\n%matplotlib inline\nsns.set_palette(\"deep\", desat=.6)\nsns.set(rc={'figure.figsize':(11.7,8.27)})",
"_____no_output_____"
],
[
"# cargar datos\ndf = pd.read_csv(os.path.join(\"data\",\"creditcard.csv\"), sep=\";\")\ndf.head()",
"_____no_output_____"
]
],
[
[
"Analicemos el total de fraudes respecto a los casos que nos son fraudes:\n",
"_____no_output_____"
]
],
[
[
"# calcular proporciones\ndf_count = pd.DataFrame()\ndf_count[\"fraude\"] =[\"no\",\"si\"]\ndf_count[\"total\"] = df[\"Class\"].value_counts() \ndf_count[\"porcentaje\"] = 100*df_count[\"total\"] /df_count[\"total\"] .sum()\n\ndf_count",
"_____no_output_____"
]
],
[
[
"Se observa que menos del 1% corresponde a registros frudulentos. La pregunta que surgen son:\n\n* ¿ Cómo deben ser el conjunto de entrenamiento y de testeo?\n* ¿ Qué modelos ocupar?\n* ¿ Qué métricas ocupar?\n\nPor ejemplo, analicemos el modelos de regresión logística y apliquemos el procedimiento estándar:",
"_____no_output_____"
]
],
[
[
"# datos \ny = df.Class\nX = df.drop('Class', axis=1)\n\n# split dataset\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=27)\n\n\n# Creando el modelo\nlr = LogisticRegression(solver='liblinear').fit(X_train, y_train)\n \n# predecir\nlr_pred = lr.predict(X_test)\n\n# calcular accuracy\naccuracy_score(y_test, lr_pred)",
"_____no_output_____"
]
],
[
[
"En general el modelo tiene un **accuracy** del 99,9%, es decir, un podría suponer que el modelo predice casi perfectamente, pero eso esta lejos de ser así. Para ver por qué es necesario seguir los siguientes pasos:",
"_____no_output_____"
],
[
"### 1. Cambiar la métrica de rendimiento\n\nEl primer paso es comparar con distintas métricas, para eso ocupemos las 4 métricas clásicas abordadas en el curso:\n* accuracy\n* precision\n* recall\n* f-score\n\nEn este punto deberá poner las métricas correspondientes y comentar sus resultados.",
"_____no_output_____"
]
],
[
[
"# metrics\ny_true = list(y_test)\ny_pred = list(lr.predict(X_test))\n\nprint('\\nMatriz de confusion:\\n ')\nprint(confusion_matrix(y_true,y_pred))\n\nprint('\\nMetricas:\\n ')\nprint('accuracy: ',accuracy_score(y_test, lr_pred))\nprint('recall: ',recall_score(y_test, lr_pred))\nprint('precision: ',precision_score(y_test, lr_pred))\nprint('f-score: ',f1_score(y_test, lr_pred))\nprint(\"\")",
"\nMatriz de confusion:\n \n[[12471 16]\n [ 33 103]]\n\nMetricas:\n \naccuracy: 0.9961181969420898\nrecall: 0.7573529411764706\nprecision: 0.865546218487395\nf-score: 0.807843137254902\n\n"
]
],
[
[
"##### accuracy : posee gran certeza en la predicción de tarjetas con fraude y no fraude respecto al total de la muestra.\n\n##### recall:respecto a las predicciones hechas para tarjetas con fraude se observa un decaimiento en la certeza de las predicciones, probablemente dado que el modelo este entrenado preferentemente para predecir casos sin fraude, dada la cantidad de ejemplos con esta categoria.Por otro lado, estoy dando enfasis por medio de esta métrica a los casos que dije que no eran fraudes cuando si lo eran.\n\n##### precisión: Esta métrica indica la importancia relativa de las predicciones correctas como no fraude respecto a las señaladas como no fraude aún cuando fueron hechas incorrectamente. Respecto, a recall está es más elevada implicando. El error en equivocarse en predecir fraude cuando no lo es, es menos grave. En tal caso, la metrica de recall que implica equivocarse en decir que una tarjeta no posee fraude cuando lo tiene es más importante, este análisis pensando en los factores del denominador de ambas métricas.\n\n\n##### f-score: seria el equilibrio entre las otras métricas, ponderando precisión y recall. En este caso, se encuentra intermedia entre el reclla y precisión. \n\n##### Comentarios finales, usar el accuracy por si solo para analizar los resultados del problema sería incompleto. Análizando las otras métricas propondría mejorar el problema equilibrando los datos de ejemplos.\n",
"_____no_output_____"
],
[
"### 2. Cambiar algoritmo\n\nEl segundo paso es comparar con distintos modelos. Debe tener en cuenta que el modelo ocupado resuelva el problema supervisado de clasificación.\n\nEn este punto deberá ajustar un modelo de **random forest**, aplicar las métricas y comparar con el modelo de regresión logística.",
"_____no_output_____"
]
],
[
[
"# train model\n\nrfc = RandomForestClassifier(n_estimators=5).fit(X_train, y_train) # algoritmo random forest\n",
"_____no_output_____"
],
[
"# metrics\n\ny_true = list(y_test)\ny_pred = list(rfc.predict(X_test)) # predicciones con random forest\n\n\nprint('\\nMatriz de confusion:\\n ')\nprint(confusion_matrix(y_true,y_pred))\n\nprint('\\nMetricas:\\n ')\nprint('accuracy: ',accuracy_score(y_true,y_pred))\nprint('recall: ',recall_score(y_true,y_pred))\nprint('precision: ',precision_score(y_true,y_pred))\nprint('f-score: ',f1_score(y_true,y_pred))\nprint(\"\")",
"\nMatriz de confusion:\n \n[[12484 3]\n [ 25 111]]\n\nMetricas:\n \naccuracy: 0.9977818268240514\nrecall: 0.8161764705882353\nprecision: 0.9736842105263158\nf-score: 0.888\n\n"
]
],
[
[
"###### En este caso se puede observar que las métricas de Recall, precisión y f-score mejoran, en comparación al modelo de regresión logisticas. Sin embargo, el orden de certeza se mantiene accuracy, precisión, f-score y recal (Respectivamente).\n\n##### cambiar de modelo de predicción probablemente puede ayudar a mejorar en cierto nivel las métricas, sin embargo, no soluciona el problema de desbalanceo de clases y puede seguir existiendo cierto nivel de sesgo en clasificar clases.\n\n\n###### nota:En este caso los estimadores se seleccionaron arbitrariamente como 5 para el algoritmo de random forest.\n",
"_____no_output_____"
],
[
"### 3. Técnicas de remuestreo: sobremuestreo de clase minoritaria\n\nEl tercer paso es ocupar ténicas de remuestreo, pero sobre la clase minoritaria. Esto significa que mediantes ténicas de remuestreo trataremos de equiparar el número de elementos de la clase minoritaria a la clase mayoritaria.",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import resample\n\n# concatenar el conjunto de entrenamiento\nX = pd.concat([X_train, y_train], axis=1)\n\n# separar las clases\nnot_fraud = X[X.Class==0]\nfraud = X[X.Class==1]\n\n# remuestrear clase minoritaria\nfraud_upsampled = resample(fraud,\n replace=True, # sample with replacement\n n_samples=len(not_fraud), # match number in majority class\n random_state=27) # reproducible results\n\n# recombinar resultados\nupsampled = pd.concat([not_fraud, fraud_upsampled])\n\n# chequear el número de elementos por clases\nupsampled.Class.value_counts()",
"_____no_output_____"
],
[
"# datos de entrenamiento sobre-balanceados\ny_train = upsampled.Class\nX_train = upsampled.drop('Class', axis=1)",
"_____no_output_____"
]
],
[
[
"Ocupando estos nuevos conjunto de entrenamientos, vuelva a aplicar el modelos de regresión logística y calcule las correspondientes métricas. Además, justifique las ventajas y desventjas de este procedimiento.",
"_____no_output_____"
]
],
[
[
"upsampled = LogisticRegression(solver='liblinear').fit(X_train, y_train) # algoritmo de regresion logistica\n\n# metrics\n\ny_true = list(y_test)\ny_pred = list(upsampled.predict(X_test))\n\n\nprint('\\nMatriz de confusion:\\n ')\nprint(confusion_matrix(y_true,y_pred))\n\nprint('\\nMetricas:\\n ')\nprint('accuracy: ',accuracy_score(y_true,y_pred))\nprint('recall: ',recall_score(y_true,y_pred))\nprint('precision: ',precision_score(y_true,y_pred))\nprint('f-score: ',f1_score(y_true,y_pred))\nprint(\"\")",
"\nMatriz de confusion:\n \n[[12200 287]\n [ 12 124]]\n\nMetricas:\n \naccuracy: 0.976313079299691\nrecall: 0.9117647058823529\nprecision: 0.30170316301703165\nf-score: 0.45338208409506403\n\n"
]
],
[
[
"##### En este caso, las metricas en general disminuyeron su valor en comparación a la clase desbalanceada. Cabe señalar que la metrica de acurracy se dispara respecto a las otras metricas. Probablemente incurra en una especie de sobreajuste del clasificador, no siendo util para extrapolar a otras realidades. Redoblar la clase minoritaria quizás sea más efectiva cuando haya un desbalanceo no tan extremo como el problema de ejemplo, y sobre esta misma clase minoritaria haya algo más de variabilidad de los datos de la clase para realizar mejores extrapolaciones.\n",
"_____no_output_____"
],
[
"### 4. Técnicas de remuestreo - Ejemplo de clase mayoritaria\n\nEl cuarto paso es ocupar ténicas de remuestreo, pero sobre la clase mayoritaria. Esto significa que mediantes ténicas de remuestreo trataremos de equiparar el número de elementos de la clase mayoritaria a la clase minoritaria.",
"_____no_output_____"
]
],
[
[
"# remuestreo clase mayoritaria\nnot_fraud_downsampled = resample(not_fraud,\n replace = False, # sample without replacement\n n_samples = len(fraud), # match minority n\n random_state = 27) # reproducible results\n\n# recombinar resultados\ndownsampled = pd.concat([not_fraud_downsampled, fraud])\n\n# chequear el número de elementos por clases\ndownsampled.Class.value_counts()",
"_____no_output_____"
],
[
"# datos de entrenamiento sub-balanceados\n\ny_train = downsampled.Class\nX_train = downsampled.drop('Class', axis=1)",
"_____no_output_____"
]
],
[
[
"Ocupando estos nuevos conjunto de entrenamientos, vuelva a aplicar el modelos de regresión logística y calcule las correspondientes métricas. Además, justifique las ventajas y desventjas de este procedimiento.",
"_____no_output_____"
]
],
[
[
"undersampled = LogisticRegression(solver='liblinear').fit(X_train, y_train) # modelo de regresi+on logística\n\n# metrics\n\ny_true = list(y_test)\ny_pred = list(undersampled.predict(X_test))\n\n\nprint('\\nMatriz de confusion:\\n ')\nprint(confusion_matrix(y_true,y_pred))\n\nprint('\\nMetricas:\\n ')\nprint('accuracy: ',accuracy_score(y_true,y_pred))\nprint('recall: ',recall_score(y_true,y_pred))\nprint('precision: ',precision_score(y_true,y_pred))\nprint('f-score: ',f1_score(y_true,y_pred))\nprint(\"\")",
"\nMatriz de confusion:\n \n[[12216 271]\n [ 16 120]]\n\nMetricas:\n \naccuracy: 0.9772637249465261\nrecall: 0.8823529411764706\nprecision: 0.3069053708439898\nf-score: 0.45540796963946867\n\n"
]
],
[
[
"##### La métrica bajan en comparación al análisis de clases desbalancedas presenta métricas con valores más bajos. Respecto a la metodologia anterior las métricas dan resultados levemente mejores para precision, f-score y accuracy. Sin embargo, no son suficientes para decir que está metodologia es mejor que la anterior.\n##### La desventaja que mencionaria de esta metodologia es que al intentar equilibrar la clase mayoritaria a la minoritaria, se puede perder información importante para clasificar una de las clases.",
"_____no_output_____"
],
[
"### 5. Conclusiones\n\nPara finalizar el laboratorio, debe realizar un análisis comparativo con los disintos resultados obtenidos en los pasos 1-4. Saque sus propias conclusiones del caso.",
"_____no_output_____"
],
[
"##### Cuando los ejemplos dentro de un problema de clasificación se encuentran desproporcionados, el algoritmo de clasificador puede favorecer la clase mayoritaria. Para identificar esto es necesario analizar la proporción de las clases, y no solo basarse en la métrica de accuracy, revisando otras como precision, recall y f-score. Esto es altamente recomendable cuando el error que se comente al acertar es más importante que solo clasificar, lo que consideran alguna de estas otras métricas mencionadas.\n##### Para analizar la certeza de lo modelos analizados, más alla de variar el algoritmo que puede aportar en mejorar cierto nivel de confianza en las predicciones, es importante agregar alguna metodologia de balanceo de clases para analizar estos problemas. Cuando se intenta doblar la clase minoritaria a una clase mayoritaria, se puede caer en un sobre ajuste del clasificador, dado que los ejemplos de la clase minoritaria pueden no aportar información nueva y se mantiene la tendencia sesgada en las predicciones. Por otro lado, al disminuir la clase mayoritaria a la minoritaria se puede perder información importante de la clase mayoritaria para clasificar. Se recomienda analizar el caso a caso.\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cb47ff7351be3931ca62a0fe826d4a651fb855b4 | 124,355 | ipynb | Jupyter Notebook | venture_funding_with_deep_learning.ipynb | briggslalor/Challenge_13 | 1185f523d83d47438726865ea84648cc71dcf39a | [
"MIT"
] | null | null | null | venture_funding_with_deep_learning.ipynb | briggslalor/Challenge_13 | 1185f523d83d47438726865ea84648cc71dcf39a | [
"MIT"
] | null | null | null | venture_funding_with_deep_learning.ipynb | briggslalor/Challenge_13 | 1185f523d83d47438726865ea84648cc71dcf39a | [
"MIT"
] | null | null | null | 37.83237 | 530 | 0.356198 | [
[
[
"# Venture Funding with Deep Learning\n\nYou work as a risk management associate at Alphabet Soup, a venture capital firm. Alphabet Soup’s business team receives many funding applications from startups every day. This team has asked you to help them create a model that predicts whether applicants will be successful if funded by Alphabet Soup.\n\nThe business team has given you a CSV containing more than 34,000 organizations that have received funding from Alphabet Soup over the years. With your knowledge of machine learning and neural networks, you decide to use the features in the provided dataset to create a binary classifier model that will predict whether an applicant will become a successful business. The CSV file contains a variety of information about these businesses, including whether or not they ultimately became successful.\n\n## Instructions:\n\nThe steps for this challenge are broken out into the following sections:\n\n* Prepare the data for use on a neural network model.\n\n* Compile and evaluate a binary classification model using a neural network.\n\n* Optimize the neural network model.\n\n### Prepare the Data for Use on a Neural Network Model \n\nUsing your knowledge of Pandas and scikit-learn’s `StandardScaler()`, preprocess the dataset so that you can use it to compile and evaluate the neural network model later.\n\nOpen the starter code file, and complete the following data preparation steps:\n\n1. Read the `applicants_data.csv` file into a Pandas DataFrame. Review the DataFrame, looking for categorical variables that will need to be encoded, as well as columns that could eventually define your features and target variables. \n\n2. Drop the “EIN” (Employer Identification Number) and “NAME” columns from the DataFrame, because they are not relevant to the binary classification model.\n \n3. Encode the dataset’s categorical variables using `OneHotEncoder`, and then place the encoded variables into a new DataFrame.\n\n4. Add the original DataFrame’s numerical variables to the DataFrame containing the encoded variables.\n\n> **Note** To complete this step, you will employ the Pandas `concat()` function that was introduced earlier in this course. \n\n5. Using the preprocessed data, create the features (`X`) and target (`y`) datasets. The target dataset should be defined by the preprocessed DataFrame column “IS_SUCCESSFUL”. The remaining columns should define the features dataset. \n\n6. Split the features and target sets into training and testing datasets.\n\n7. Use scikit-learn's `StandardScaler` to scale the features data.\n\n### Compile and Evaluate a Binary Classification Model Using a Neural Network\n\nUse your knowledge of TensorFlow to design a binary classification deep neural network model. This model should use the dataset’s features to predict whether an Alphabet Soup–funded startup will be successful based on the features in the dataset. Consider the number of inputs before determining the number of layers that your model will contain or the number of neurons on each layer. Then, compile and fit your model. Finally, evaluate your binary classification model to calculate the model’s loss and accuracy. \n \nTo do so, complete the following steps:\n\n1. Create a deep neural network by assigning the number of input features, the number of layers, and the number of neurons on each layer using Tensorflow’s Keras.\n\n> **Hint** You can start with a two-layer deep neural network model that uses the `relu` activation function for both layers.\n\n2. Compile and fit the model using the `binary_crossentropy` loss function, the `adam` optimizer, and the `accuracy` evaluation metric.\n\n> **Hint** When fitting the model, start with a small number of epochs, such as 20, 50, or 100.\n\n3. Evaluate the model using the test data to determine the model’s loss and accuracy.\n\n4. Save and export your model to an HDF5 file, and name the file `AlphabetSoup.h5`. \n\n### Optimize the Neural Network Model\n\nUsing your knowledge of TensorFlow and Keras, optimize your model to improve the model's accuracy. Even if you do not successfully achieve a better accuracy, you'll need to demonstrate at least two attempts to optimize the model. You can include these attempts in your existing notebook. Or, you can make copies of the starter notebook in the same folder, rename them, and code each model optimization in a new notebook. \n\n> **Note** You will not lose points if your model does not achieve a high accuracy, as long as you make at least two attempts to optimize the model.\n\nTo do so, complete the following steps:\n\n1. Define at least three new deep neural network models (the original plus 2 optimization attempts). With each, try to improve on your first model’s predictive accuracy.\n\n> **Rewind** Recall that perfect accuracy has a value of 1, so accuracy improves as its value moves closer to 1. To optimize your model for a predictive accuracy as close to 1 as possible, you can use any or all of the following techniques:\n>\n> * Adjust the input data by dropping different features columns to ensure that no variables or outliers confuse the model.\n>\n> * Add more neurons (nodes) to a hidden layer.\n>\n> * Add more hidden layers.\n>\n> * Use different activation functions for the hidden layers.\n>\n> * Add to or reduce the number of epochs in the training regimen.\n\n2. After finishing your models, display the accuracy scores achieved by each model, and compare the results.\n\n3. Save each of your models as an HDF5 file.\n",
"_____no_output_____"
]
],
[
[
"# Imports\nimport pandas as pd\nfrom pathlib import Path\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler,OneHotEncoder",
"_____no_output_____"
]
],
[
[
"---\n\n## Prepare the data to be used on a neural network model",
"_____no_output_____"
],
[
"### Step 1: Read the `applicants_data.csv` file into a Pandas DataFrame. Review the DataFrame, looking for categorical variables that will need to be encoded, as well as columns that could eventually define your features and target variables. \n",
"_____no_output_____"
]
],
[
[
"# Read the applicants_data.csv file from the Resources folder into a Pandas DataFrame\napplicant_data_df = pd.read_csv('Resources/applicants_data.csv')\n\n# Review the DataFrame\napplicant_data_df\n",
"_____no_output_____"
],
[
"# Review the data types associated with the columns\napplicant_data_df.dtypes\n",
"_____no_output_____"
]
],
[
[
"### Step 2: Drop the “EIN” (Employer Identification Number) and “NAME” columns from the DataFrame, because they are not relevant to the binary classification model.",
"_____no_output_____"
]
],
[
[
"# Drop the 'EIN' and 'NAME' columns from the DataFrame\napplicant_data_df = applicant_data_df.drop(columns=['EIN', 'NAME'])\n\n# Review the DataFrame\napplicant_data_df\n",
"_____no_output_____"
]
],
[
[
"### Step 3: Encode the dataset’s categorical variables using `OneHotEncoder`, and then place the encoded variables into a new DataFrame.",
"_____no_output_____"
]
],
[
[
"# Create a list of categorical variables \ncategorical_variables = list(applicant_data_df.dtypes[applicant_data_df.dtypes == \"object\"].index)\n\n# Display the categorical variables list\ndisplay(categorical_variables)\n",
"_____no_output_____"
],
[
"# Create a OneHotEncoder instance\nenc = OneHotEncoder(sparse=False)\n",
"_____no_output_____"
],
[
"# Encode the categorcal variables using OneHotEncoder\nencoded_data = enc.fit_transform(applicant_data_df[categorical_variables])\n",
"_____no_output_____"
],
[
"# Create a DataFrame with the encoded variables\nencoded_df = pd.DataFrame(encoded_data, columns=enc.get_feature_names(categorical_variables))\n\n# Review the DataFrame\nencoded_df\n",
"_____no_output_____"
]
],
[
[
"### Step 4: Add the original DataFrame’s numerical variables to the DataFrame containing the encoded variables.\n\n> **Note** To complete this step, you will employ the Pandas `concat()` function that was introduced earlier in this course. ",
"_____no_output_____"
]
],
[
[
"# Add the numerical variables from the original DataFrame to the one-hot encoding DataFrame\nencoded_df = pd.concat([encoded_df, applicant_data_df[['STATUS', 'ASK_AMT', 'IS_SUCCESSFUL']]], axis = 1)\n\n# Review the Dataframe\nencoded_df\n",
"_____no_output_____"
]
],
[
[
"### Step 5: Using the preprocessed data, create the features (`X`) and target (`y`) datasets. The target dataset should be defined by the preprocessed DataFrame column “IS_SUCCESSFUL”. The remaining columns should define the features dataset. \n\n",
"_____no_output_____"
]
],
[
[
"# Define the target set y using the IS_SUCCESSFUL column\ny = encoded_df['IS_SUCCESSFUL']\n\n# Display a sample of y\ny\n",
"_____no_output_____"
],
[
"# Define features set X by selecting all columns but IS_SUCCESSFUL\nX = encoded_df.drop(columns=['IS_SUCCESSFUL'])\n\n# Review the features DataFrame\nX\n",
"_____no_output_____"
]
],
[
[
"### Step 6: Split the features and target sets into training and testing datasets.\n",
"_____no_output_____"
]
],
[
[
"# Split the preprocessed data into a training and testing dataset\n# Assign the function a random_state equal to 1\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n",
"_____no_output_____"
]
],
[
[
"### Step 7: Use scikit-learn's `StandardScaler` to scale the features data.",
"_____no_output_____"
]
],
[
[
"# Create a StandardScaler instance\nscaler = StandardScaler()\n\n# Fit the scaler to the features training dataset\nX_scaler = scaler.fit(X_train)\n\n# Fit the scaler to the features training dataset\nX_train_scaled = X_scaler.transform(X_train)\nX_test_scaled = X_scaler.transform(X_test)\n",
"_____no_output_____"
]
],
[
[
"---\n\n## Compile and Evaluate a Binary Classification Model Using a Neural Network",
"_____no_output_____"
],
[
"### Step 1: Create a deep neural network by assigning the number of input features, the number of layers, and the number of neurons on each layer using Tensorflow’s Keras.\n\n> **Hint** You can start with a two-layer deep neural network model that uses the `relu` activation function for both layers.\n",
"_____no_output_____"
]
],
[
[
"# Define the the number of inputs (features) to the model\nnumber_input_features = 116\n\n# Review the number of features\nnumber_input_features\n",
"_____no_output_____"
],
[
"# Define the number of neurons in the output layer\nnumber_output_neurons = 1",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the first hidden layer\nhidden_nodes_layer1 = 58\n\n# Review the number hidden nodes in the first layer\nhidden_nodes_layer1\n",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the second hidden layer\nhidden_nodes_layer2 = 28\n\n# Review the number hidden nodes in the second layer\nhidden_nodes_layer2\n",
"_____no_output_____"
],
[
"# Create the Sequential model instance\nnn = Sequential()\n",
"_____no_output_____"
],
[
"# Add the first hidden layer\nnn.add(Dense(units=hidden_nodes_layer1, input_dim=number_input_features, activation=\"relu\"))\n",
"_____no_output_____"
],
[
"# Add the second hidden layer\nnn.add(Dense(units=hidden_nodes_layer2, activation='relu'))\n",
"_____no_output_____"
],
[
"# Add the output layer to the model specifying the number of output neurons and activation function\nnn.add(Dense(units=number_output_neurons, activation='sigmoid'))\n",
"_____no_output_____"
],
[
"# Display the Sequential model summary\nnn.summary()\n",
"Model: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense (Dense) (None, 58) 6786 \n \n dense_1 (Dense) (None, 28) 1652 \n \n dense_2 (Dense) (None, 1) 29 \n \n=================================================================\nTotal params: 8,467\nTrainable params: 8,467\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"### Step 2: Compile and fit the model using the `binary_crossentropy` loss function, the `adam` optimizer, and the `accuracy` evaluation metric.\n",
"_____no_output_____"
]
],
[
[
"# Compile the Sequential model\nnn.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])",
"_____no_output_____"
],
[
"# Fit the model using 50 epochs and the training data\nnn.fit(X_train_scaled, y_train, epochs = 50)\n",
"Epoch 1/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5728 - accuracy: 0.7183\nEpoch 2/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5508 - accuracy: 0.7299\nEpoch 3/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5487 - accuracy: 0.7305\nEpoch 4/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5466 - accuracy: 0.7317\nEpoch 5/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5454 - accuracy: 0.7320\nEpoch 6/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5447 - accuracy: 0.7337\nEpoch 7/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5441 - accuracy: 0.7333\nEpoch 8/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5428 - accuracy: 0.7349\nEpoch 9/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5418 - accuracy: 0.7342\nEpoch 10/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5420 - accuracy: 0.7349\nEpoch 11/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5411 - accuracy: 0.7352\nEpoch 12/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5411 - accuracy: 0.7357\nEpoch 13/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5402 - accuracy: 0.7371\nEpoch 14/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5400 - accuracy: 0.7361\nEpoch 15/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5397 - accuracy: 0.7370\nEpoch 16/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5391 - accuracy: 0.7366\nEpoch 17/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5391 - accuracy: 0.7382\nEpoch 18/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5384 - accuracy: 0.7355\nEpoch 19/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5382 - accuracy: 0.7365\nEpoch 20/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5375 - accuracy: 0.7392\nEpoch 21/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5374 - accuracy: 0.7379\nEpoch 22/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5379 - accuracy: 0.7376\nEpoch 23/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5367 - accuracy: 0.7381\nEpoch 24/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5370 - accuracy: 0.7385\nEpoch 25/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5365 - accuracy: 0.7393\nEpoch 26/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5360 - accuracy: 0.7383\nEpoch 27/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5355 - accuracy: 0.7397\nEpoch 28/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5354 - accuracy: 0.7395\nEpoch 29/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5353 - accuracy: 0.7390\nEpoch 30/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5353 - accuracy: 0.7390\nEpoch 31/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5349 - accuracy: 0.7392\nEpoch 32/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5350 - accuracy: 0.7392\nEpoch 33/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5346 - accuracy: 0.7401\nEpoch 34/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5345 - accuracy: 0.7397\nEpoch 35/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5342 - accuracy: 0.7392\nEpoch 36/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5342 - accuracy: 0.7400\nEpoch 37/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5335 - accuracy: 0.7404\nEpoch 38/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5344 - accuracy: 0.7402\nEpoch 39/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5330 - accuracy: 0.7397\nEpoch 40/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5334 - accuracy: 0.7411\nEpoch 41/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5331 - accuracy: 0.7404\nEpoch 42/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5327 - accuracy: 0.7405\nEpoch 43/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5332 - accuracy: 0.7402\nEpoch 44/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5322 - accuracy: 0.7407\nEpoch 45/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5326 - accuracy: 0.7399\nEpoch 46/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5327 - accuracy: 0.7410\nEpoch 47/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5326 - accuracy: 0.7404\nEpoch 48/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5326 - accuracy: 0.7407\nEpoch 49/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5321 - accuracy: 0.7403\nEpoch 50/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5322 - accuracy: 0.7415\n"
]
],
[
[
"### Step 3: Evaluate the model using the test data to determine the model’s loss and accuracy.\n",
"_____no_output_____"
]
],
[
[
"# Evaluate the model loss and accuracy metrics using the evaluate method and the test data\nmodel_loss, model_accuracy = nn.evaluate(X_test_scaled, y_test, verbose = 2)\n\n# Display the model loss and accuracy results\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"268/268 - 0s - loss: 0.5526 - accuracy: 0.7300 - 279ms/epoch - 1ms/step\nLoss: 0.552593469619751, Accuracy: 0.7300291657447815\n"
]
],
[
[
"### Step 4: Save and export your model to an HDF5 file, and name the file `AlphabetSoup.h5`. \n",
"_____no_output_____"
]
],
[
[
"# Set the model's file path\nfile_path = Path('Resources/AlphabetSoup.h5')\n\n# Export your model to a HDF5 file\nnn.save(file_path)\n",
"_____no_output_____"
]
],
[
[
"---\n\n## Optimize the neural network model\n",
"_____no_output_____"
],
[
"### Step 1: Define at least three new deep neural network models (resulting in the original plus 3 optimization attempts). With each, try to improve on your first model’s predictive accuracy.\n\n> **Rewind** Recall that perfect accuracy has a value of 1, so accuracy improves as its value moves closer to 1. To optimize your model for a predictive accuracy as close to 1 as possible, you can use any or all of the following techniques:\n>\n> * Adjust the input data by dropping different features columns to ensure that no variables or outliers confuse the model.\n>\n> * Add more neurons (nodes) to a hidden layer.\n>\n> * Add more hidden layers.\n>\n> * Use different activation functions for the hidden layers.\n>\n> * Add to or reduce the number of epochs in the training regimen.\n",
"_____no_output_____"
],
[
"### Alternative Model 1",
"_____no_output_____"
]
],
[
[
"# Define the the number of inputs (features) to the model\nnumber_input_features = len(X_train.iloc[0])\n\n# Review the number of features\nnumber_input_features",
"_____no_output_____"
],
[
"# Define the number of neurons in the output layer\nnumber_output_neurons_A1 = 1",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the first hidden layer\nhidden_nodes_layer1_A1 = 200\n\n# Review the number of hidden nodes in the first layer\nhidden_nodes_layer1_A1",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the second hidden layer\nhidden_nodes_layer2_A1 = 100\n\n# Review the number of hidden nodes in the second layer\nhidden_nodes_layer2_A1",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the third hidden layer\nhidden_nodes_layer3_A1 = 50\n\n# Review the number of hidden nodes in the third layer\nhidden_nodes_layer3_A1",
"_____no_output_____"
],
[
"# Create the Sequential model instance\nnn_A1 = Sequential()",
"_____no_output_____"
],
[
"# First hidden layer\nnn_A1.add(Dense(units = hidden_nodes_layer1_A1, input_dim = number_input_features, activation = 'relu'))\n\n# Second hidden layer \nnn_A1.add(Dense(units = hidden_nodes_layer2_A1, activation = 'relu'))\n\n# Third hidden layer\nnn_A1.add(Dense(units = hidden_nodes_layer3_A1, activation = 'relu'))\n\n\n# Output layer\nnn_A1.add(Dense(1, activation = 'sigmoid'))\n\n\n# Check the structure of the model\nnn_A1.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense_3 (Dense) (None, 200) 23400 \n \n dense_4 (Dense) (None, 100) 20100 \n \n dense_5 (Dense) (None, 50) 5050 \n \n dense_6 (Dense) (None, 1) 51 \n \n=================================================================\nTotal params: 48,601\nTrainable params: 48,601\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compile the Sequential model\nnn_A1.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
"_____no_output_____"
],
[
"# Fit the model using 50 epochs and the training data\nfit_model_A1 = nn_A1.fit(X_train_scaled, y_train, epochs=50)\n",
"Epoch 1/50\n804/804 [==============================] - 2s 1ms/step - loss: 0.5672 - accuracy: 0.7227\nEpoch 2/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5528 - accuracy: 0.7289\nEpoch 3/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5487 - accuracy: 0.7321\nEpoch 4/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5468 - accuracy: 0.7332\nEpoch 5/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5453 - accuracy: 0.7354\nEpoch 6/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5448 - accuracy: 0.7343\nEpoch 7/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5437 - accuracy: 0.7361\nEpoch 8/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5430 - accuracy: 0.7361\nEpoch 9/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5425 - accuracy: 0.7357\nEpoch 10/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5421 - accuracy: 0.7372\nEpoch 11/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5407 - accuracy: 0.7372\nEpoch 12/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5400 - accuracy: 0.7373\nEpoch 13/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5401 - accuracy: 0.7370\nEpoch 14/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5401 - accuracy: 0.7370\nEpoch 15/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5391 - accuracy: 0.7377\nEpoch 16/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5377 - accuracy: 0.7388\nEpoch 17/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5379 - accuracy: 0.7377\nEpoch 18/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5377 - accuracy: 0.7381\nEpoch 19/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5371 - accuracy: 0.7378\nEpoch 20/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5371 - accuracy: 0.7383\nEpoch 21/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5364 - accuracy: 0.7391\nEpoch 22/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5354 - accuracy: 0.7393\nEpoch 23/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5361 - accuracy: 0.7394\nEpoch 24/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5353 - accuracy: 0.7392\nEpoch 25/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5355 - accuracy: 0.7395\nEpoch 26/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5351 - accuracy: 0.7394\nEpoch 27/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5343 - accuracy: 0.7388\nEpoch 28/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5343 - accuracy: 0.7403\nEpoch 29/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5339 - accuracy: 0.7404\nEpoch 30/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5335 - accuracy: 0.7409\nEpoch 31/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5332 - accuracy: 0.7414\nEpoch 32/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5333 - accuracy: 0.7411\nEpoch 33/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5327 - accuracy: 0.7407\nEpoch 34/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5334 - accuracy: 0.7411\nEpoch 35/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5329 - accuracy: 0.7412\nEpoch 36/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5319 - accuracy: 0.7416\nEpoch 37/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5324 - accuracy: 0.7409\nEpoch 38/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5322 - accuracy: 0.7407\nEpoch 39/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5313 - accuracy: 0.7413\nEpoch 40/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5313 - accuracy: 0.7411\nEpoch 41/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5312 - accuracy: 0.7414\nEpoch 42/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5328 - accuracy: 0.7419\nEpoch 43/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5303 - accuracy: 0.7411\nEpoch 44/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5305 - accuracy: 0.7416\nEpoch 45/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5308 - accuracy: 0.7415\nEpoch 46/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5302 - accuracy: 0.7414\nEpoch 47/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5305 - accuracy: 0.7418\nEpoch 48/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5299 - accuracy: 0.7420\nEpoch 49/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5297 - accuracy: 0.7417\nEpoch 50/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5305 - accuracy: 0.7416\n"
]
],
[
[
"#### Alternative Model 2",
"_____no_output_____"
]
],
[
[
"# Define the the number of inputs (features) to the model\nnumber_input_features = len(X_train.iloc[0])\n\n# Review the number of features\nnumber_input_features",
"_____no_output_____"
],
[
"# Define the number of neurons in the output layer\nnumber_output_neurons_A2 = 1",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the first hidden layer\nhidden_nodes_layer1_A2 = 150\n\n# Review the number of hidden nodes in the first layer\nhidden_nodes_layer1_A2",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the second hidden layer\nhidden_nodes_layer2_A2 = 75\n\n# Review the number of hidden nodes in the second layer\nhidden_nodes_layer2_A2",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the third hidden layer\nhidden_nodes_layer3_A2 = 35\n\n# Review the number of hidden nodes in the third layer\nhidden_nodes_layer3_A2",
"_____no_output_____"
],
[
"# Define the number of hidden nodes for the fourth hidden layer\nhidden_nodes_layer4_A2 = 15\n\n# Review the number of hidden nodes in the fourth layer\nhidden_nodes_layer4_A2",
"_____no_output_____"
],
[
"# Create the Sequential model instance\nnn_A2 = Sequential()",
"_____no_output_____"
],
[
"# First hidden layer\nnn_A2.add(Dense(units = hidden_nodes_layer1_A2, input_dim = number_input_features, activation = 'relu'))\n\n# Second hidden layer\nnn_A2.add(Dense(units = hidden_nodes_layer2_A2, activation = 'relu'))\n\n# Third hidden layer\nnn_A2.add(Dense(units = hidden_nodes_layer3_A2, activation = 'relu'))\n\n# Fourth hidden layer\nnn_A2.add(Dense(units = hidden_nodes_layer4_A2, activation = 'relu'))\n\n# Output layer\nnn_A2.add(Dense(1, activation = 'sigmoid'))\n\n# Check the structure of the model\nnn_A2.summary()\n",
"Model: \"sequential_2\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense_7 (Dense) (None, 150) 17550 \n \n dense_8 (Dense) (None, 75) 11325 \n \n dense_9 (Dense) (None, 35) 2660 \n \n dense_10 (Dense) (None, 15) 540 \n \n dense_11 (Dense) (None, 1) 16 \n \n=================================================================\nTotal params: 32,091\nTrainable params: 32,091\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compile the model\nnn_A2.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
"_____no_output_____"
],
[
"# Fit the model\nnn_A2.fit(X_train_scaled, y_train, epochs=50)\n",
"Epoch 1/50\n804/804 [==============================] - 2s 1ms/step - loss: 0.5684 - accuracy: 0.7228\nEpoch 2/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5515 - accuracy: 0.7306\nEpoch 3/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5479 - accuracy: 0.7323: 0s - loss: 0.5473 - accuracy: 0.73\nEpoch 4/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5472 - accuracy: 0.7327\nEpoch 5/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5456 - accuracy: 0.7325\nEpoch 6/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5447 - accuracy: 0.7343\nEpoch 7/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5430 - accuracy: 0.7348\nEpoch 8/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5423 - accuracy: 0.7360\nEpoch 9/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5411 - accuracy: 0.7372\nEpoch 10/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5412 - accuracy: 0.7362\nEpoch 11/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5413 - accuracy: 0.7378\nEpoch 12/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5399 - accuracy: 0.7369\nEpoch 13/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5397 - accuracy: 0.7378\nEpoch 14/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5388 - accuracy: 0.7371\nEpoch 15/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5382 - accuracy: 0.7376\nEpoch 16/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5386 - accuracy: 0.7388\nEpoch 17/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5379 - accuracy: 0.7392\nEpoch 18/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5374 - accuracy: 0.7392\nEpoch 19/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5370 - accuracy: 0.7392\nEpoch 20/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5365 - accuracy: 0.7392\nEpoch 21/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5363 - accuracy: 0.7387\nEpoch 22/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5358 - accuracy: 0.7390\nEpoch 23/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5359 - accuracy: 0.7390\nEpoch 24/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5354 - accuracy: 0.7395\nEpoch 25/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5349 - accuracy: 0.7406\nEpoch 26/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5348 - accuracy: 0.7400\nEpoch 27/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5355 - accuracy: 0.7392\nEpoch 28/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5346 - accuracy: 0.7402\nEpoch 29/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5342 - accuracy: 0.7398\nEpoch 30/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5337 - accuracy: 0.7400\nEpoch 31/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5336 - accuracy: 0.7407\nEpoch 32/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5334 - accuracy: 0.7400\nEpoch 33/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5335 - accuracy: 0.7405\nEpoch 34/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5330 - accuracy: 0.7407\nEpoch 35/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5331 - accuracy: 0.7402\nEpoch 36/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5324 - accuracy: 0.7407\nEpoch 37/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5323 - accuracy: 0.7407\nEpoch 38/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5322 - accuracy: 0.7411\nEpoch 39/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5321 - accuracy: 0.7402\nEpoch 40/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5318 - accuracy: 0.7406\nEpoch 41/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5321 - accuracy: 0.7409\nEpoch 42/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5314 - accuracy: 0.7414\nEpoch 43/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5314 - accuracy: 0.7416\nEpoch 44/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5318 - accuracy: 0.7418\nEpoch 45/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5314 - accuracy: 0.7411\nEpoch 46/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5310 - accuracy: 0.7414\nEpoch 47/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5309 - accuracy: 0.7417\nEpoch 48/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5311 - accuracy: 0.7413\nEpoch 49/50\n804/804 [==============================] - 1s 2ms/step - loss: 0.5307 - accuracy: 0.7413\nEpoch 50/50\n804/804 [==============================] - 1s 1ms/step - loss: 0.5305 - accuracy: 0.7414\n"
]
],
[
[
"### Step 2: After finishing your models, display the accuracy scores achieved by each model, and compare the results.",
"_____no_output_____"
]
],
[
[
"print(\"Original Model Results\")\n\n# Evaluate the model loss and accuracy metrics using the evaluate method and the test data\nmodel_loss, model_accuracy = nn.evaluate(X_test_scaled, y_test, verbose = 2)\n\n# Display the model loss and accuracy results\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"Original Model Results\n268/268 - 0s - loss: 0.5526 - accuracy: 0.7300 - 198ms/epoch - 739us/step\nLoss: 0.552593469619751, Accuracy: 0.7300291657447815\n"
],
[
"print(\"Alternative Model 1 Results\")\n\n# Evaluate the model loss and accuracy metrics using the evaluate method and the test data\nmodel_loss, model_accuracy = nn_A1.evaluate(X_test_scaled, y_test, verbose = 2)\n\n# Display the model loss and accuracy results\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"Alternative Model 1 Results\n268/268 - 0s - loss: 0.5581 - accuracy: 0.7300 - 295ms/epoch - 1ms/step\nLoss: 0.5580672025680542, Accuracy: 0.7300291657447815\n"
],
[
"print(\"Alternative Model 2 Results\")\n\n# Evaluate the model loss and accuracy metrics using the evaluate method and the test data\nmodel_loss, model_accuracy = nn_A2.evaluate(X_test_scaled, y_test, verbose = 2)\n\n# Display the model loss and accuracy results\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"Alternative Model 2 Results\n268/268 - 0s - loss: 0.5634 - accuracy: 0.7318 - 305ms/epoch - 1ms/step\nLoss: 0.5633556246757507, Accuracy: 0.7317784428596497\n"
]
],
[
[
"### Step 3: Save each of your alternative models as an HDF5 file.\n",
"_____no_output_____"
]
],
[
[
"# Set the file path for the first alternative model\nfile_path = Path('Resources/AlphabetSoup_A1.h5')\n\n# Export your model to a HDF5 file\nnn_A1.save(file_path)",
"_____no_output_____"
],
[
"# Set the file path for the second alternative model\nfile_path = Path('Resources/AlphabetSoup_A2.h5')\n\n# Export your model to a HDF5 file\nnn_A2.save(file_path)\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb480517200ae4773fbe261188f7d73066a1b32a | 1,615 | ipynb | Jupyter Notebook | array_strings/ipynb/reverse_rows_in_matrix.ipynb | PRkudupu/Algo-python | a0b9c3e19e4ece48f5dc47e34860510565ab2f38 | [
"MIT"
] | 1 | 2019-05-04T00:43:52.000Z | 2019-05-04T00:43:52.000Z | array_strings/ipynb/reverse_rows_in_matrix.ipynb | PRkudupu/Algo-python | a0b9c3e19e4ece48f5dc47e34860510565ab2f38 | [
"MIT"
] | null | null | null | array_strings/ipynb/reverse_rows_in_matrix.ipynb | PRkudupu/Algo-python | a0b9c3e19e4ece48f5dc47e34860510565ab2f38 | [
"MIT"
] | null | null | null | 19.938272 | 66 | 0.462539 | [
[
[
"#Reverse rows using string comprehesion\ndef flip_image(image):\n return [row[::-1]for row in image]\n\nmatrix=[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nprint(flip_image(matrix))",
"[[0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 1, 0], [0, 1, 0, 1]]\n"
],
[
"#Print reverse rows\ndef reverse_rows_in_matrix(image):\n for row in image:\n print(row[::-1])\nmatrix=[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nprint(reverse_rows_in_matrix(matrix))",
"[0, 0, 1, 1]\n[1, 0, 0, 1]\n[1, 1, 1, 0]\n[0, 1, 0, 1]\nNone\n"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
cb481471c50a090f6960303711139cea3826c5ba | 296,530 | ipynb | Jupyter Notebook | DSPT6_LS_DS_224.ipynb | rawalk/DS-Unit-2-Linear-Models | 88f401296656bd878f3c65020c1a927277d86897 | [
"MIT"
] | null | null | null | DSPT6_LS_DS_224.ipynb | rawalk/DS-Unit-2-Linear-Models | 88f401296656bd878f3c65020c1a927277d86897 | [
"MIT"
] | null | null | null | DSPT6_LS_DS_224.ipynb | rawalk/DS-Unit-2-Linear-Models | 88f401296656bd878f3c65020c1a927277d86897 | [
"MIT"
] | null | null | null | 90.405488 | 21,886 | 0.782349 | [
[
[
"<a href=\"https://colab.research.google.com/github/rawalk/DS-Unit-2-Linear-Models/blob/master/DSPT6_LS_DS_224.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"Lambda School Data Science\n\n*Unit 2, Sprint 2, Module 4*\n\n---",
"_____no_output_____"
],
[
"# Classification Metrics\n\n- get and interpret the **confusion matrix** for classification models\n- use classification metrics: **precision, recall**\n- understand the relationships between precision, recall, **thresholds, and predicted probabilities**, to help **make decisions and allocate budgets**\n- Get **ROC AUC** (Receiver Operating Characteristic, Area Under the Curve)",
"_____no_output_____"
],
[
"### Setup\n\nRun the code cell below. You can work locally (follow the [local setup instructions](https://lambdaschool.github.io/ds/unit2/local/)) or on Colab.\n\nLibraries\n\n- category_encoders\n- ipywidgets\n- matplotlib\n- numpy\n- pandas\n- scikit-learn\n- seaborn",
"_____no_output_____"
]
],
[
[
"%%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-Kaggle-Challenge/master/data/'\n !pip install category_encoders==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'",
"_____no_output_____"
]
],
[
[
"# Get and interpret the confusion matrix for classification models",
"_____no_output_____"
],
[
"## Overview",
"_____no_output_____"
],
[
"First, load the Tanzania Waterpumps data and fit a model. (This code isn't new, we've seen it all before.)",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport category_encoders as ce\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef wrangle(X):\n \"\"\"Wrangles train, validate, and test sets in the same way\"\"\"\n X = X.copy()\n\n # Convert date_recorded to datetime\n X['date_recorded'] = pd.to_datetime(X['date_recorded'], infer_datetime_format=True)\n \n # Extract components from date_recorded, then drop the original column\n X['year_recorded'] = X['date_recorded'].dt.year\n X['month_recorded'] = X['date_recorded'].dt.month\n X['day_recorded'] = X['date_recorded'].dt.day\n X = X.drop(columns='date_recorded')\n \n # Engineer feature: how many years from construction_year to date_recorded\n X['years'] = X['year_recorded'] - X['construction_year'] \n \n # Drop recorded_by (never varies) and id (always varies, random)\n unusable_variance = ['recorded_by', 'id']\n X = X.drop(columns=unusable_variance)\n \n # Drop duplicate columns\n duplicate_columns = ['quantity_group']\n X = X.drop(columns=duplicate_columns)\n \n # About 3% of the time, latitude has small values near zero,\n # outside Tanzania, so we'll treat these like null values\n X['latitude'] = X['latitude'].replace(-2e-08, np.nan)\n \n # When columns have zeros and shouldn't, they are like null values\n cols_with_zeros = ['construction_year', 'longitude', 'latitude', 'gps_height', 'population']\n for col in cols_with_zeros:\n X[col] = X[col].replace(0, np.nan)\n \n return X\n\n\n# Merge train_features.csv & train_labels.csv\ntrain = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'), \n pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))\n\n# Read test_features.csv & sample_submission.csv\ntest = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv')\nsample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')\n\n# Split train into train & val. Make val the same size as test.\ntarget = 'status_group'\ntrain, val = train_test_split(train, test_size=len(test), \n stratify=train[target], random_state=42)\n\n# Wrangle train, validate, and test sets in the same way\ntrain = wrangle(train)\nval = wrangle(val)\ntest = wrangle(test)\n\n# Arrange data into X features matrix and y target vector\nX_train = train.drop(columns=target)\ny_train = train[target]\nX_val = val.drop(columns=target)\ny_val = val[target]\nX_test = test\n\n# Make pipeline!\npipeline = make_pipeline(\n ce.OrdinalEncoder(), \n SimpleImputer(strategy='mean'), \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)\ny_pred = pipeline.predict(X_val)\nprint('Validation Accuracy', accuracy_score(y_val, y_pred))",
"/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
]
],
[
[
"## Follow Along\n\nScikit-learn added a [**`plot_confusion_matrix`**](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html) function in version 0.22!",
"_____no_output_____"
]
],
[
[
"import sklearn\nsklearn.__version__",
"_____no_output_____"
],
[
"from sklearn.metrics import plot_confusion_matrix\n\nplot_confusion_matrix(pipeline, X_val, y_val,\n values_format='.0f', xticks_rotation='vertical', cmap='Blues')",
"_____no_output_____"
],
[
"plot_confusion_matrix(pipeline, X_val, y_val,\n normalize='true',\n values_format='.2f', \n xticks_rotation='vertical', cmap='Blues')",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_val, y_pred)\ncm",
"_____no_output_____"
],
[
"cm.sum(axis=1)",
"_____no_output_____"
],
[
"cm.sum(axis=1)[:, np.newaxis]",
"_____no_output_____"
],
[
"normalized_cm = cm/cm.sum(axis=1)[:, np.newaxis]\nnormalized_cm",
"_____no_output_____"
],
[
"import seaborn as sns\nfrom sklearn.utils.multiclass import unique_labels\n\ndef plot_cm(y_val, y_pred, normalize=False):\n cols = unique_labels(y_val)\n cm = confusion_matrix(y_val, y_pred)\n if normalize:\n cm = cm/cm.sum(axis=1)[:, np.newaxis]\n fmt = '.2f'\n else:\n fmt = '.0f'\n df_cm = pd.DataFrame(cm, columns = ['Predicted ' + str(col) for col in cols], \n index = ['Actual ' + str(col) for col in cols])\n plt.figure(figsize=(10,8))\n sns.heatmap(df_cm, annot=True, cmap='Blues', fmt=fmt)\n\nplot_cm(y_val, y_pred, normalize=True)",
"_____no_output_____"
],
[
"unique_labels(y_val)",
"_____no_output_____"
]
],
[
[
"#### How many correct predictions were made?",
"_____no_output_____"
]
],
[
[
"7005 + 332 + 4351",
"_____no_output_____"
],
[
"np.diag(cm).sum()",
"_____no_output_____"
]
],
[
[
"#### How many total predictions were made?",
"_____no_output_____"
]
],
[
[
"len(y_val)",
"_____no_output_____"
],
[
"cm.sum()",
"_____no_output_____"
]
],
[
[
"#### What was the classification accuracy?",
"_____no_output_____"
]
],
[
[
"(7005 + 332 + 4351)/len(y_pred)",
"_____no_output_____"
],
[
"np.diag(cm).sum()/cm.sum()",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score\naccuracy_score(y_val, y_pred)",
"_____no_output_____"
]
],
[
[
"# Use classification metrics: precision, recall",
"_____no_output_____"
],
[
"## Overview\n\n[Scikit-Learn User Guide — Classification Report](https://scikit-learn.org/stable/modules/model_evaluation.html#classification-report)",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report\n\nprint(classification_report(y_val, y_pred))",
" precision recall f1-score support\n\n functional 0.81 0.90 0.85 7798\nfunctional needs repair 0.58 0.32 0.41 1043\n non functional 0.85 0.79 0.82 5517\n\n accuracy 0.81 14358\n macro avg 0.75 0.67 0.69 14358\n weighted avg 0.81 0.81 0.81 14358\n\n"
]
],
[
[
"#### Wikipedia, [Precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall)\n\n> Both precision and recall are based on an understanding and measure of relevance.\n\n> Suppose a computer program for recognizing dogs in photographs identifies 8 dogs in a picture containing 12 dogs and some cats. Of the 8 identified as dogs, 5 actually are dogs (true positives), while the rest are cats (false positives). The program's precision is 5/8 while its recall is 5/12.\n\n> High precision means that an algorithm returned substantially more relevant results than irrelevant ones, while high recall means that an algorithm returned most of the relevant results.\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Precisionrecall.svg/700px-Precisionrecall.svg.png\" width=\"400\">",
"_____no_output_____"
],
[
"## Follow Along",
"_____no_output_____"
],
[
"#### [We can get precision & recall from the confusion matrix](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context))",
"_____no_output_____"
]
],
[
[
"plot_cm(y_val, y_pred)",
"_____no_output_____"
]
],
[
[
"#### How many correct predictions of \"non functional\"?",
"_____no_output_____"
]
],
[
[
"correct_pred_non_func = 4351",
"_____no_output_____"
]
],
[
[
"#### How many total predictions of \"non functional\"?",
"_____no_output_____"
]
],
[
[
"total_pred_non_func = 4351 + 156 + 622\ntotal_pred_non_func",
"_____no_output_____"
]
],
[
[
"#### What's the precision for \"non functional\"?",
"_____no_output_____"
]
],
[
[
"precision_non_func = correct_pred_non_func/total_pred_non_func\nprecision_non_func",
"_____no_output_____"
]
],
[
[
"#### How many actual \"non functional\" waterpumps?",
"_____no_output_____"
]
],
[
[
"actual_non_func = 1098 + 68 + 4351\nactual_non_func",
"_____no_output_____"
]
],
[
[
"#### What's the recall for \"non functional\"?",
"_____no_output_____"
]
],
[
[
"recall_non_func = correct_pred_non_func/actual_non_func\nrecall_non_func",
"_____no_output_____"
],
[
"print(classification_report(y_val, y_pred))",
" precision recall f1-score support\n\n functional 0.81 0.90 0.85 7798\nfunctional needs repair 0.58 0.32 0.41 1043\n non functional 0.85 0.79 0.82 5517\n\n accuracy 0.81 14358\n macro avg 0.75 0.67 0.69 14358\n weighted avg 0.81 0.81 0.81 14358\n\n"
],
[
"f1_score_non_func = 2*(precision_non_func*recall_non_func)/(precision_non_func + recall_non_func)\nf1_score_non_func",
"_____no_output_____"
]
],
[
[
"# Understand the relationships between precision, recall, thresholds, and predicted probabilities, to help make decisions and allocate budgets",
"_____no_output_____"
],
[
"## Overview",
"_____no_output_____"
],
[
"### Imagine this scenario...\n\nSuppose there are over 14,000 waterpumps that you _do_ have some information about, but you _don't_ know whether they are currently functional, or functional but need repair, or non-functional.",
"_____no_output_____"
]
],
[
[
"len(test)",
"_____no_output_____"
]
],
[
[
"**You have the time and resources to go to just 2,000 waterpumps for proactive maintenance.** You want to predict, which 2,000 are most likely non-functional or in need of repair, to help you triage and prioritize your waterpump inspections.\n\nYou have historical inspection data for over 59,000 other waterpumps, which you'll use to fit your predictive model.",
"_____no_output_____"
]
],
[
[
"len(train) + len(val)",
"_____no_output_____"
]
],
[
[
"You have historical inspection data for over 59,000 other waterpumps, which you'll use to fit your predictive model.\n\nBased on this historical data, if you randomly chose waterpumps to inspect, then about 46% of the waterpumps would need repairs, and 54% would not need repairs.",
"_____no_output_____"
]
],
[
[
"y_train.value_counts(normalize=True)",
"_____no_output_____"
],
[
"2000 * 0.46",
"_____no_output_____"
]
],
[
[
"**Can you do better than random at prioritizing inspections?**",
"_____no_output_____"
],
[
"In this scenario, we should define our target differently. We want to identify which waterpumps are non-functional _or_ are functional but needs repair:",
"_____no_output_____"
]
],
[
[
"y_train = y_train != 'functional'\ny_val = y_val != 'functional'\ny_train.value_counts(normalize=True)",
"_____no_output_____"
]
],
[
[
"We already made our validation set the same size as our test set.",
"_____no_output_____"
]
],
[
[
"len(val) == len(test)",
"_____no_output_____"
]
],
[
[
"We can refit our model, using the redefined target.\n\nThen make predictions for the validation set.",
"_____no_output_____"
]
],
[
[
"pipeline.fit(X_train, y_train)\ny_pred = pipeline.predict(X_val)",
"_____no_output_____"
]
],
[
[
"## Follow Along",
"_____no_output_____"
],
[
"#### Look at the confusion matrix:",
"_____no_output_____"
]
],
[
[
"plot_cm(y_val, y_pred)",
"_____no_output_____"
]
],
[
[
"#### How many total predictions of \"True\" (\"non functional\" or \"functional needs repair\") ?",
"_____no_output_____"
]
],
[
[
"y_pred",
"_____no_output_____"
],
[
"5032+977",
"_____no_output_____"
],
[
"y_pred.sum()",
"_____no_output_____"
]
],
[
[
"### We don't have \"budget\" to take action on all these predictions\n\n- But we can get predicted probabilities, to rank the predictions. \n- Then change the threshold, to change the number of positive predictions, based on our budget.",
"_____no_output_____"
],
[
"### Get predicted probabilities and plot the distribution",
"_____no_output_____"
]
],
[
[
"pipeline.predict_proba(X_val)",
"_____no_output_____"
],
[
"pipeline.predict(X_val)",
"_____no_output_____"
],
[
"pipeline.predict_proba(X_val)[:, 1] > 0.5",
"_____no_output_____"
],
[
"y_pred_proba = pipeline.predict_proba(X_val)[:, 1]\nsns.distplot(y_pred_proba)",
"_____no_output_____"
]
],
[
[
"### Change the threshold",
"_____no_output_____"
]
],
[
[
"thres = 0.5\ny_pred = y_pred_proba > thres\nax = sns.distplot(y_pred_proba)\nax.axvline(thres, color='red')\npd.Series(y_pred).value_counts()",
"_____no_output_____"
]
],
[
[
"### Or, get exactly 2,000 positive predictions",
"_____no_output_____"
],
[
"Identify the 2,000 waterpumps in the validation set with highest predicted probabilities.",
"_____no_output_____"
]
],
[
[
"def set_thres(y_true, y_pred_proba, thres=0.5):\n y_pred = y_pred_proba > thres\n ax = sns.distplot(y_pred_proba)\n ax.axvline(thres, color='red')\n plt.show()\n print(classification_report(y_true, y_pred))\n plot_cm(y_true, y_pred)\n\nset_thres(y_val, y_pred_proba, thres=0.6)",
"_____no_output_____"
],
[
"from ipywidgets import interact, fixed\n\ninteract(set_thres, \n y_true=fixed(y_val), \n y_pred_proba=fixed(y_pred_proba), \n thres=(0, 1, 0.05))",
"_____no_output_____"
]
],
[
[
"Most of these top 2,000 waterpumps will be relevant recommendations, meaning `y_val==True`, meaning the waterpump is non-functional or needs repairs.\n\nSome of these top 2,000 waterpumps will be irrelevant recommendations, meaning `y_val==False`, meaning the waterpump is functional and does not need repairs.\n\nLet's look at a random sample of 50 out of these top 2,000:",
"_____no_output_____"
]
],
[
[
"results = pd.DataFrame({'y_val': y_val, 'y_pred_proba': y_pred_proba})\ntop2000 = results.sort_values(by='y_pred_proba', ascending=False)[:2000]\ntop2000",
"_____no_output_____"
],
[
"top2000.sample(n=50)",
"_____no_output_____"
]
],
[
[
"So how many of our recommendations were relevant? ...",
"_____no_output_____"
]
],
[
[
"n_trips = 2000\nprint(f'Baseline: {n_trips*0.46} waterpump repairs in {n_trips} trips')\nprint(f\"With model: {top2000['y_val'].sum()} waterpump repairs in {n_trips} trips\")",
"Baseline: 920.0 waterpump repairs in 2000 trips\nWith model: 1972 waterpump repairs in 2000 trips\n"
]
],
[
[
"What's the precision for this subset of 2,000 predictions?",
"_____no_output_____"
]
],
[
[
"precision_at_K = top2000['y_val'].sum()/n_trips\nprint(f'Precision @ K=2000: {precision_at_K}')",
"Precision @ K=2000: 0.986\n"
]
],
[
[
"### In this scenario ... \n\nAccuracy _isn't_ the best metric!\n\nInstead, change the threshold, to change the number of positive predictions, based on the budget. (You have the time and resources to go to just 2,000 waterpumps for proactive maintenance.)\n\nThen, evaluate with the precision for \"non functional\"/\"functional needs repair\".\n\nThis is conceptually like **Precision@K**, where k=2,000.\n\nRead more here: [Recall and Precision at k for Recommender Systems: Detailed Explanation with examples](https://medium.com/@m_n_malaeb/recall-and-precision-at-k-for-recommender-systems-618483226c54)\n\n> Precision at k is the proportion of recommended items in the top-k set that are relevant\n\n> Mathematically precision@k is defined as: `Precision@k = (# of recommended items @k that are relevant) / (# of recommended items @k)`\n\n> In the context of recommendation systems we are most likely interested in recommending top-N items to the user. So it makes more sense to compute precision and recall metrics in the first N items instead of all the items. Thus the notion of precision and recall at k where k is a user definable integer that is set by the user to match the top-N recommendations objective.\n\nWe asked, can you do better than random at prioritizing inspections?\n\nIf we had randomly chosen waterpumps to inspect, we estimate that only 920 waterpumps would be repaired after 2,000 maintenance visits. (46%)\n\nBut using our predictive model, in the validation set, we succesfully identified over 1,900 waterpumps in need of repair!\n\nSo we will use this predictive model with the dataset of over 14,000 waterpumps that we _do_ have some information about, but we _don't_ know whether they are currently functional, or functional but need repair, or non-functional.\n\nWe will predict which 2,000 are most likely non-functional or in need of repair.\n\nWe estimate that approximately 1,900 waterpumps will be repaired after these 2,000 maintenance visits.\n\nSo we're confident that our predictive model will help triage and prioritize waterpump inspections.",
"_____no_output_____"
],
[
"### But ...\n\nThis metric (~1,900 waterpumps repaired after 2,000 maintenance visits) is specific for _one_ classification problem and _one_ possible trade-off.\n\nCan we get an evaluation metric that is generic for _all_ classification problems and _all_ possible trade-offs?\n\nYes — the most common such metric is **ROC AUC.**",
"_____no_output_____"
],
[
"## Get ROC AUC (Receiver Operating Characteristic, Area Under the Curve)\n\n[Wikipedia explains,](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) \"A receiver operating characteristic curve, or ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. **The ROC curve is created by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings.**\"\n\nROC AUC is the area under the ROC curve. [It can be interpreted](https://stats.stackexchange.com/questions/132777/what-does-auc-stand-for-and-what-is-it) as \"the expectation that a uniformly drawn random positive is ranked before a uniformly drawn random negative.\" \n\nROC AUC measures **how well a classifier ranks predicted probabilities.** So, when you get your classifier’s ROC AUC score, you need to **use predicted probabilities, not discrete predictions.**\n\nROC AUC ranges **from 0 to 1.** Higher is better. A naive majority class **baseline** will have an ROC AUC score of **0.5.** \n\n#### Scikit-Learn docs\n- [User Guide: Receiver operating characteristic (ROC)](https://scikit-learn.org/stable/modules/model_evaluation.html#receiver-operating-characteristic-roc)\n- [sklearn.metrics.roc_curve](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html)\n- [sklearn.metrics.roc_auc_score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)\n\n#### More links\n- [ROC curves and Area Under the Curve explained](https://www.dataschool.io/roc-curves-and-auc-explained/)\n- [The philosophical argument for using ROC curves](https://lukeoakdenrayner.wordpress.com/2018/01/07/the-philosophical-argument-for-using-roc-curves/)",
"_____no_output_____"
]
],
[
[
"# \"The ROC curve is created by plotting the true positive rate (TPR) \n# against the false positive rate (FPR) \n# at various threshold settings.\"\n\n# Use scikit-learn to calculate TPR & FPR at various thresholds\nfrom sklearn.metrics import roc_curve\nfpr, tpr, thresholds = roc_curve(y_val, y_pred_proba)",
"_____no_output_____"
],
[
"# See the results in a table\npd.DataFrame({\n 'False Positive Rate': fpr, \n 'True Positive Rate': tpr, \n 'Threshold': thresholds\n})",
"_____no_output_____"
],
[
"# See the results on a plot. \n# This is the \"Receiver Operating Characteristic\" curve\nplt.scatter(fpr, tpr)\nplt.title('ROC curve')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate');",
"_____no_output_____"
],
[
"# Use scikit-learn to calculate the area under the curve.\nfrom sklearn.metrics import roc_auc_score\nroc_auc_score(y_val, y_pred_proba)",
"_____no_output_____"
],
[
"y_pred",
"_____no_output_____"
],
[
"roc_auc_score(y_val, y_pred)",
"_____no_output_____"
]
],
[
[
"**Recap:** ROC AUC measures how well a classifier ranks predicted probabilities. So, when you get your classifier’s ROC AUC score, you need to use predicted probabilities, not discrete predictions. \n\nYour code may look something like this:\n\n```python\nfrom sklearn.metrics import roc_auc_score\ny_pred_proba = model.predict_proba(X_test_transformed)[:, -1] # Probability for last class\nprint('Test ROC AUC:', roc_auc_score(y_test, y_pred_proba))\n```\n\nROC AUC ranges from 0 to 1. Higher is better. A naive majority class baseline will have an ROC AUC score of 0.5.",
"_____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"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb4828e73cc956c5703acf4023e0551fd47259de | 176,585 | ipynb | Jupyter Notebook | nbs/01_data.env.ipynb | qAp/earthshotsoil | 29386e80f4e0188cd69334d7ddb526d923732f14 | [
"Apache-2.0"
] | null | null | null | nbs/01_data.env.ipynb | qAp/earthshotsoil | 29386e80f4e0188cd69334d7ddb526d923732f14 | [
"Apache-2.0"
] | null | null | null | nbs/01_data.env.ipynb | qAp/earthshotsoil | 29386e80f4e0188cd69334d7ddb526d923732f14 | [
"Apache-2.0"
] | null | null | null | 54.150567 | 4,015 | 0.458884 | [
[
[
"# Environmental Covariates",
"_____no_output_____"
],
[
"Datasets listed in [Supplementary_Data_File_1._environmental_covariates - Google Sheet](https://docs.google.com/spreadsheets/d/1hPw9G1A34SnlbDJ8sk3LYfwgoLN0Gbail2xdNb7viGc/edit#gid=106509025).",
"_____no_output_____"
]
],
[
[
"#default_exp data.env",
"_____no_output_____"
],
[
"#export\n\nimport os, sys\nimport shutil, io, subprocess\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport requests, wget\nfrom urlpath import URL\nimport math\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport rioxarray\n\nfrom earthshotsoil.core import *",
"_____no_output_____"
]
],
[
[
"# Helper functions",
"_____no_output_____"
]
],
[
[
"def check_id(data_id):\n if data_id in DATA_SRC:\n print(f'Data_id \"{data_id}\" already exists. '\n 'Check that it is not re-used.')\n raise \n\n \ndef add_download(id, download):\n ENCOV = ENCOV.append(\n {'id':id, 'download':URL(download)}, ignore_index=True)\n\n \ndef add_filename(id, filename):\n ENCOV = ENCOV.append(\n {'id':id, 'filename':filename}, ignore_index=True)\n",
"_____no_output_____"
],
[
"def download_file(url):\n local_filename = url.split('/')[-1]\n # NOTE the stream=True parameter below\n with requests.get(url, stream=True) as r:\n r.raise_for_status()\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=8192): \n # If you have chunk encoded response uncomment if\n # and set chunk_size parameter to None.\n #if chunk: \n f.write(chunk)\n return local_filename\n\n\n\ndef execute_wgt(url, dst='./'):\n url = URL(url)\n \n cmd = ['wget', url, '-O', Path(dst)/url.name]\n \n proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)\n return proc\n\n\n# def monitor_wgt_proc(proc):\n# while True:\n# line = proc.stderr.readline()\n\n# if line=='' and proc.poll() is not None:\n# break\n# else:\n# print(f'\\r{line}', end='')\n \n# proc.stderr.close()\n \n# return_code = proc.wait()\n# return return_code",
"_____no_output_____"
],
[
"def unzip(src, dst='./'):\n '''\n Unpack zip file at `src` to directory `dst`.\n '''\n dst.mkdir(exist_ok=True)\n proc = subprocess.Popen(\n ['unzip', str(src), '-d', str(dst)], \n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return proc",
"_____no_output_____"
]
],
[
[
"# Load data index",
"_____no_output_____"
],
[
"Load Google Sheet for data sources and info",
"_____no_output_____"
]
],
[
[
"#export\nDIR_DATA = Path('../data')\npth_csv = DIR_DATA / 'environmental_covariate.csv'\nENCOV = pd.read_csv(pth_csv)",
"_____no_output_____"
]
],
[
[
"## Earthenv Cloud\nGlobal 1-km Cloud Cover: https://www.earthenv.org/cloud",
"_____no_output_____"
]
],
[
[
"var_downloads = [\n ('EarthEnvCloudCover_MODCF_interannualSD', \n 'https://data.earthenv.org/cloud/MODCF_interannualSD.tif'),\n\n ('EarthEnvCloudCover_MODCF_intraannualSD',\n 'https://data.earthenv.org/cloud/MODCF_intraannualSD.tif'),\n\n ('EarthEnvCloudCover_MODCF_meanannual',\n 'https://data.earthenv.org/cloud/MODCF_meanannual.tif'),\n\n ('EarthEnvCloudCover_MODCF_seasonality_concentration',\n 'https://data.earthenv.org/cloud/'\n 'MODCF_seasonality_concentration.tif'),\n\n ('EarthEnvCloudCover_MODCF_seasonality_theta',\n 'https://data.earthenv.org/cloud/MODCF_seasonality_theta.tif'),\n]",
"_____no_output_____"
],
[
"for variable, download in var_downloads:\n ENCOV.loc[ENCOV.Variable==variable, 'Source / Link'] = download",
"_____no_output_____"
]
],
[
[
"Upload to GEE, then record the ID.",
"_____no_output_____"
]
],
[
[
"for variable, _ in var_downloads:\n gee_id = f'users/bingosaucer/{variable}'\n \n ENCOV.loc[\n ENCOV.Variable==variable, 'GEE ID'] = gee_id",
"_____no_output_____"
]
],
[
[
"## Earthenv Topography\n\nGlobal 1,5,10,100-km Topography: https://www.earthenv.org/topography.",
"_____no_output_____"
],
[
"Couldn't obtain the direct download URLs for these using the browser's developer tools.",
"_____no_output_____"
]
],
[
[
"var_fns = [\n ('EarthEnvTopoMed_1stOrderPartialDerivEW',\n 'dx_1KMmd_GMTEDmd.tif'),\n \n ('EarthEnvTopoMed_1stOrderPartialDerivNS', \n 'dy_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_2ndOrderPartialDerivEW',\n 'dxx_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_2ndOrderPartialDerivNS',\n 'dyy_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_AspectCosine',\n 'aspectcosine_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_AspectSine',\n 'aspectsine_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_Eastness',\n 'eastness_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_Elevation', \n 'elevation_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_Northness',\n 'northness_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_ProfileCurvature',\n 'pcurv_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_Roughness',\n 'roughness_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_Slope',\n 'slope_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_TangentialCurvature',\n 'tcurv_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_TerrainRuggednessIndex',\n 'tri_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_TopoPositionIndex',\n 'tpi_1KMmd_GMTEDmd.tif'),\n\n ('EarthEnvTopoMed_VectorRuggednessMeasure', \n 'vrm_1KMmd_GMTEDmd.tif')\n]",
"_____no_output_____"
],
[
"for variable, filename in var_fns:\n ENCOV.loc[ENCOV.Variable==variable, 'filename'] = filename\n",
"_____no_output_____"
]
],
[
[
"After uploading to GEE by user `bingosaucer`, say, set `gee_id`:",
"_____no_output_____"
]
],
[
[
"gee_user = 'bingosaucer'",
"_____no_output_____"
],
[
"is_topo = ENCOV.Variable.apply(lambda o: str(o).startswith('EarthEnvTopoMed'))",
"_____no_output_____"
],
[
"ENCOV.loc[is_topo, 'GEE ID'] = (\n ENCOV.loc[is_topo, 'Variable'].apply(\n lambda var: f'users/{gee_user}/{var}')\n)",
"_____no_output_____"
]
],
[
[
"## FanEtAl_Depth_to_Water_Table_AnnualMean ",
"_____no_output_____"
],
[
"http://thredds-gfnl.usc.es/thredds/catalog/GLOBALWTDFTP/catalog.html",
"_____no_output_____"
]
],
[
[
"var_wtb = 'FanEtAl_Depth_to_Water_Table_AnnualMean'",
"_____no_output_____"
],
[
"var_downloads = [\n ('NAMERICA_WTD_annualmean', \n 'http://thredds-gfnl.usc.es/thredds/fileServer/'\n 'GLOBALWTDFTP/annualmeans/NAMERICA_WTD_annualmean.nc'),\n \n ('SAMERICA_WTD_annualmean', \n 'http://thredds-gfnl.usc.es/thredds/fileServer/'\n 'GLOBALWTDFTP/annualmeans/SAMERICA_WTD_annualmean.nc'),\n \n ('OCEANA_WTD_annualmean', \n 'http://thredds-gfnl.usc.es/thredds/fileServer/'\n 'GLOBALWTDFTP/annualmeans/OCEANA_WTD_annualmean.nc'),\n \n ('EURASIA_WTD_annualmean', \n 'http://thredds-gfnl.usc.es/thredds/fileServer/'\n 'GLOBALWTDFTP/annualmeans/EURASIA_WTD_annualmean.nc'),\n \n ('AFRICA_WTD_annualmean', \n 'http://thredds-gfnl.usc.es/thredds/fileServer/'\n 'GLOBALWTDFTP/annualmeans/AFRICA_WTD_annualmean.nc'),\n]",
"_____no_output_____"
],
[
"procs_watertb = []\n\nfor variable, download in var_downloads:\n print('Downloading', download)\n \n proc = execute_wgt(download, dst=DIR_DATA)\n procs_watertb.append(proc)",
"Downloading http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/NAMERICA_WTD_annualmean.nc\nDownloading http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/SAMERICA_WTD_annualmean.nc\nDownloading http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/OCEANA_WTD_annualmean.nc\nDownloading http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/EURASIA_WTD_annualmean.nc\nDownloading http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/AFRICA_WTD_annualmean.nc\n"
],
[
"for proc in procs_watertb:\n print(proc.poll())",
"None\n0\n8\nNone\nNone\n"
],
[
"dict_wtb = ENCOV[ENCOV.Variable==var_wtb].squeeze().to_dict()",
"_____no_output_____"
],
[
"for variable, download in var_downloads:\n d = dict_wtb.copy()\n d.update(\n {'Variable': variable, \n 'Source / Link': download})\n print(d, end='\\n\\n')",
"{'#': 26.0, 'Variable': 'NAMERICA_WTD_annualmean', 'Description': 'Mean annual depth of the water table on the terrestrial land surface (in m below land surface)', 'Source / Link': 'http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/NAMERICA_WTD_annualmean.nc', 'doi': '10.1126/science.1229881', 'File Size (GB)': 0.09, 'GEE ID': 'users/bingosaucer/FanEtAl_Depth_to_Water_Table_AnnualMean', 'Unnamed: 7': nan, 'filename': nan}\n\n{'#': 26.0, 'Variable': 'SAMERICA_WTD_annualmean', 'Description': 'Mean annual depth of the water table on the terrestrial land surface (in m below land surface)', 'Source / Link': 'http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/SAMERICA_WTD_annualmean.nc', 'doi': '10.1126/science.1229881', 'File Size (GB)': 0.09, 'GEE ID': 'users/bingosaucer/FanEtAl_Depth_to_Water_Table_AnnualMean', 'Unnamed: 7': nan, 'filename': nan}\n\n{'#': 26.0, 'Variable': 'OCEANA_WTD_annualmean', 'Description': 'Mean annual depth of the water table on the terrestrial land surface (in m below land surface)', 'Source / Link': 'http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/OCEANA_WTD_annualmean.nc', 'doi': '10.1126/science.1229881', 'File Size (GB)': 0.09, 'GEE ID': 'users/bingosaucer/FanEtAl_Depth_to_Water_Table_AnnualMean', 'Unnamed: 7': nan, 'filename': nan}\n\n{'#': 26.0, 'Variable': 'EURASIA_WTD_annualmean', 'Description': 'Mean annual depth of the water table on the terrestrial land surface (in m below land surface)', 'Source / Link': 'http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/EURASIA_WTD_annualmean.nc', 'doi': '10.1126/science.1229881', 'File Size (GB)': 0.09, 'GEE ID': 'users/bingosaucer/FanEtAl_Depth_to_Water_Table_AnnualMean', 'Unnamed: 7': nan, 'filename': nan}\n\n{'#': 26.0, 'Variable': 'AFRICA_WTD_annualmean', 'Description': 'Mean annual depth of the water table on the terrestrial land surface (in m below land surface)', 'Source / Link': 'http://thredds-gfnl.usc.es/thredds/fileServer/GLOBALWTDFTP/annualmeans/AFRICA_WTD_annualmean.nc', 'doi': '10.1126/science.1229881', 'File Size (GB)': 0.09, 'GEE ID': 'users/bingosaucer/FanEtAl_Depth_to_Water_Table_AnnualMean', 'Unnamed: 7': nan, 'filename': nan}\n\n"
],
[
"%%time\n\nds = rioxarray.open_rasterio(f'../data/{url.name}')\nds.rio.write_crs('epsg:4326', inplace=True)\nds = ds.squeeze()",
"CPU times: user 131 ms, sys: 43.4 ms, total: 174 ms\nWall time: 280 ms\n"
],
[
"ds.rio.crs",
"_____no_output_____"
],
[
"%%time\n\n# ds.WTD.rio.to_raster(f'../data/{url.stem}.tiff')\nds.WTD.rio.to_raster(f'../data/NAMERICA_WTD_annualmean.tiff')",
"CPU times: user 21min 11s, sys: 3min 35s, total: 24min 47s\nWall time: 25min 59s\n"
],
[
"xr.open_rasterio('../data/FanEtAl_Depth_to_Water_Table_AnnualMean.tiff')",
"_____no_output_____"
]
],
[
[
"## MODIS_LAI",
"_____no_output_____"
],
[
"https://explorer.earthengine.google.com/#detail/MODIS%2F006%2FMCD15A3H",
"_____no_output_____"
],
[
"## ISRIC Data\nISRIC World Soil Information. \nData Hub: https://data.isric.org/geonetwork/srv/eng/catalog.search#/home",
"_____no_output_____"
],
[
"## WCS_Human_Footprint_2009\n> Human Footprint 2009",
"_____no_output_____"
],
[
"http://wcshumanfootprint.org/",
"_____no_output_____"
],
[
"### Full dataset",
"_____no_output_____"
],
[
"How to unpack full dataset download:\n```\n$ unzip doi_10.5061_dryad.052q5__v2.zip\n$ brew install p7zip\n$ 7za x HumanFootprintv2.7z\n```",
"_____no_output_____"
]
],
[
[
"path = '../data/Dryadv3/Maps'\nns = [f'{path}/{n}' for n in os.listdir(path) if n.endswith('.tif')]\nsum([os.path.getsize(n) for n in ns]) / 1e9",
"_____no_output_____"
],
[
"%%time\n\nda_fullset = xr.open_rasterio(\n '../data/Dryadv3/Maps/HFP2009.tif', chunks={'x':10, 'y':10})",
"CPU times: user 15.5 s, sys: 37.4 s, total: 53 s\nWall time: 1min 8s\n"
],
[
"%%time\n\n(da_fullset - da).sum()",
"CPU times: user 34.3 s, sys: 47.6 s, total: 1min 21s\nWall time: 1min 36s\n"
]
],
[
[
"### Summary 2009",
"_____no_output_____"
],
[
"## WorldClim2\n\nhttps://www.worldclim.org/data/index.html ",
"_____no_output_____"
]
],
[
[
"def worldclim2_histdata_src():\n '''\n WorldClim v2.1 historical climate data found at:\n https://www.worldclim.org/data/worldclim21.html\n '''\n d = {}\n \n d['minimum temperature'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_tmin.zip'),\n 'units': 'C'}\n \n d['maximum temperature'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_tmax.zip'),\n 'units': 'C'}\n\n d['average temperature'] = {\n 'download': \n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_tavg.zip'),\n 'units': 'C'}\n \n d['precipitation'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_prec.zip'),\n 'units': 'mm'}\n \n d['solar radiation'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_srad.zip'),\n 'units': 'kJ m^-2 day^-1'}\n \n d['wind speed'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_wind.zip'),\n 'units': 'm s^-1'}\n \n d['water vapor pressure'] = {\n 'download':\n URL('http://biogeo.ucdavis.edu/data/worldclim/v2.1/base/'\n 'wc2.1_30s_vapr.zip'), \n 'units': 'kPa'}\n \n return d\n\nWORLDCLIM2 = worldclim2_histdata_src()",
"_____no_output_____"
]
],
[
[
"Download a couple of variables.",
"_____no_output_____"
]
],
[
[
"vns = ['wind speed', 'water vapor pressure']\n\nurls = [WORLDCLIM2[vn]['download'] for vn in vns]\n\nprocs = [execute_wgt(url, dst=DIR_DATA) for url in urls]",
"_____no_output_____"
]
],
[
[
"Unpack a variable and set it up for GEE.",
"_____no_output_____"
]
],
[
[
"vn = 'water vapor pressure'\n\ncollection_id = 'WorldClim2_' + '_'.join(vn.split())\ncollection_download = WORLD_CLIM2_SRC[vn]['download']\n\npth_zip = DIR_DATA / collection_download.name\ndir_unzip = DIR_DATA / collection_id\n\n# proc = unzip(pth_zip, dir_unzip)",
"_____no_output_____"
],
[
"fns = [n.name for n in dir_unzip.ls() if n.name.endswith('.tif')]\nmonths = [n.split('.')[1].split('_')[-1] for n in fns]\nasset_ids = [f'{collection_id}_{m}' for m in months]",
"_____no_output_____"
]
],
[
[
"Register the Image Collection.",
"_____no_output_____"
]
],
[
[
"ENCOV = ENCOV.append(\n {'id': collection_id, 'download': collection_download}, \n ignore_index=True)",
"_____no_output_____"
]
],
[
[
"Register Images.",
"_____no_output_____"
]
],
[
[
"ENCOV = ENCOV.append(\n pd.DataFrame({'id': asset_ids, 'filename': fns}))\n\nENCOV.loc[ENCOV.id.isin(asset_ids), \n 'download'] = collection_download",
"_____no_output_____"
]
],
[
[
"Create the Image Collection in GEE (in the browser).",
"_____no_output_____"
],
[
"Set `gee_user` for the collection and individual assets.",
"_____no_output_____"
]
],
[
[
"ENCOV.loc[ENCOV.id.isin(asset_ids), 'gee_user'] = 'bingosaucer'",
"_____no_output_____"
]
],
[
[
"## ConsensusLandCover_Human_Development_Percentage",
"_____no_output_____"
]
],
[
[
"humandev_source = [\n ('Evergreen/Deciduous Needleleaf Trees', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_1.tif'),\n ('Evergreen Broadleaf Trees', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_2.tif'),\n ('Deciduous Broadleaf Trees', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_3.tif'),\n ('Mixed/Other Trees', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_4.tif'),\n ('Shrubs', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_5.tif'),\n ('Herbaceous Vegetation', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_6.tif'),\n ('Cultivated and Managed Vegetation', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_7.tif'),\n ('Regularly Flooded Vegetation', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_8.tif'),\n ('Urban/Built-up', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_9.tif'),\n ('Snow/Ice', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_10.tif'),\n ('Barren', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_11.tif'),\n ('Open Water', 'https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_12.tif')\n ]",
"_____no_output_____"
]
],
[
[
"Download the files.",
"_____no_output_____"
]
],
[
[
"for i in range(5, len(humandev_source)):\n url = humandev_source[i][1]\n ! wget {url} -O {DIR_DATA / Path(url).name}",
"--2021-02-20 05:56:02-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_6.tif\nResolving data.earthenv.org (data.earthenv.org)... 172.67.196.246, 104.21.34.38\nConnecting to data.earthenv.org (data.earthenv.org)|172.67.196.246|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 65617214 (63M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_6.tif’\n\n../data/consensus_f 100%[===================>] 62.58M 10.2MB/s in 9.3s \n\n2021-02-20 05:56:13 (6.69 MB/s) - ‘../data/consensus_full_class_6.tif’ saved [65617214/65617214]\n\n--2021-02-20 05:56:13-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_7.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 76079198 (73M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_7.tif’\n\n../data/consensus_f 100%[===================>] 72.55M 11.2MB/s in 9.9s \n\n2021-02-20 05:56:24 (7.35 MB/s) - ‘../data/consensus_full_class_7.tif’ saved [76079198/76079198]\n\n--2021-02-20 05:56:24-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_8.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 22102767 (21M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_8.tif’\n\n../data/consensus_f 100%[===================>] 21.08M 5.22MB/s in 4.0s \n\n2021-02-20 05:56:29 (5.22 MB/s) - ‘../data/consensus_full_class_8.tif’ saved [22102767/22102767]\n\n--2021-02-20 05:56:29-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_9.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 12969598 (12M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_9.tif’\n\n../data/consensus_f 100%[===================>] 12.37M 7.28MB/s in 1.7s \n\n2021-02-20 05:56:32 (7.28 MB/s) - ‘../data/consensus_full_class_9.tif’ saved [12969598/12969598]\n\n--2021-02-20 05:56:32-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_10.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 15509218 (15M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_10.tif’\n\n../data/consensus_f 100%[===================>] 14.79M 6.97MB/s in 2.1s \n\n2021-02-20 05:56:35 (6.97 MB/s) - ‘../data/consensus_full_class_10.tif’ saved [15509218/15509218]\n\n--2021-02-20 05:56:36-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_11.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 62330988 (59M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_11.tif’\n\n../data/consensus_f 100%[===================>] 59.44M 11.1MB/s in 7.7s \n\n2021-02-20 05:56:44 (7.69 MB/s) - ‘../data/consensus_full_class_11.tif’ saved [62330988/62330988]\n\n--2021-02-20 05:56:44-- https://data.earthenv.org/consensus_landcover/with_DISCover/consensus_full_class_12.tif\nResolving data.earthenv.org (data.earthenv.org)... 104.21.34.38, 172.67.196.246\nConnecting to data.earthenv.org (data.earthenv.org)|104.21.34.38|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 28060356 (27M) [image/tiff]\nSaving to: ‘../data/consensus_full_class_12.tif’\n\n../data/consensus_f 100%[===================>] 26.76M 7.35MB/s in 3.8s \n\n2021-02-20 05:56:49 (7.09 MB/s) - ‘../data/consensus_full_class_12.tif’ saved [28060356/28060356]\n\n"
]
],
[
[
"Check projection is available.",
"_____no_output_____"
]
],
[
[
"rda = rioxarray.open_rasterio(DIR_DATA / 'consensus_full_class_4.tif')",
"_____no_output_____"
],
[
"rda.rio.crs",
"_____no_output_____"
],
[
"geeids = [f'users/bingosaucer/{Path(url).stem}' \n for _, url in humandev_source]\n\nvariables = [f'humandev_{Path(url).stem}'\n for _, url in humandev_source]",
"_____no_output_____"
]
],
[
[
"Update data index.",
"_____no_output_____"
]
],
[
[
"doi = ENCOV[\n ENCOV.Variable==('ConsensusLandCover_Human'\n '_Development_Percentage')].doi.values[0]\n\nfor i in range(len(humandev_source)):\n desc, download = humandev_source[i]\n desc = f'Consensus Land Cover. {desc}'\n\n ENCOV = ENCOV.append(\n {'Variable': variables[i],\n 'Description': desc,\n 'Source / Link': download,\n 'doi': doi,\n 'GEE ID': geeids[i]}, ignore_index=True)",
"_____no_output_____"
]
],
[
[
"Create an Image Collection for these Images, and then update the index.",
"_____no_output_____"
]
],
[
[
"# ENCOV.append(\n# {'Variable': 'ConsensusLandCover',\n# 'Description': 'Global 1-km Consensus Land Cover',\n# 'Source / Link': 'http://www.earthenv.org//landcover',\n# 'doi': ,\n# 'GEE ID': }, ignore_index=True)",
"_____no_output_____"
]
],
[
[
"# Google Earth Engine Access",
"_____no_output_____"
],
[
"Sets all assets under my account to be public.",
"_____no_output_____"
]
],
[
[
"on_mygee = ENCOV['GEE ID'].apply(lambda o: 'bingosaucer' in str(o))\n\nfor _, r in tqdm(ENCOV[on_mygee].iterrows()):\n try:\n subprocess.check_call(\n ['earthengine', 'acl', 'set', 'public', r['GEE ID']])\n except subprocess.CalledProcessError:\n continue ",
"35it [03:29, 5.99s/it]\n"
],
[
"ENCOV.dropna(axis=0, how='all', inplace=True)\n\nENCOV.to_csv(DIR_DATA / 'environmental_covariate.csv', index=False)",
"_____no_output_____"
]
],
[
[
"Available",
"_____no_output_____"
]
],
[
[
"pd.set_option('display.max_rows', None)\npd.set_option('display.max_colwidth', None)\nENCOV[ENCOV['GEE ID'].notnull()][['Variable', 'GEE ID', 'Description']]",
"_____no_output_____"
]
],
[
[
"Not yet available",
"_____no_output_____"
]
],
[
[
"ENCOV[ENCOV['GEE ID'].isnull()]",
"_____no_output_____"
]
],
[
[
"# Reference",
"_____no_output_____"
],
[
"Reading GeoTIFF:\n- http://xarray.pydata.org/en/stable/io.html#rasterio\n- http://xarray.pydata.org/en/stable/generated/xarray.open_rasterio.html#xarray-open-rasterio",
"_____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"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb482964a0f512bf70d88dd9be9454015f5c1c30 | 4,437 | ipynb | Jupyter Notebook | playbook/tactics/privilege-escalation/T1548.001.ipynb | haresudhan/The-AtomicPlaybook | 447b1d6bca7c3750c5a58112634f6bac31aff436 | [
"MIT"
] | 8 | 2021-05-25T15:25:31.000Z | 2021-11-08T07:14:45.000Z | playbook/tactics/privilege-escalation/T1548.001.ipynb | haresudhan/The-AtomicPlaybook | 447b1d6bca7c3750c5a58112634f6bac31aff436 | [
"MIT"
] | 1 | 2021-08-23T17:38:02.000Z | 2021-10-12T06:58:19.000Z | playbook/tactics/privilege-escalation/T1548.001.ipynb | haresudhan/The-AtomicPlaybook | 447b1d6bca7c3750c5a58112634f6bac31aff436 | [
"MIT"
] | 2 | 2021-05-29T20:24:24.000Z | 2021-08-05T23:44:12.000Z | 43.5 | 1,276 | 0.669822 | [
[
[
"# T1548.001 - Abuse Elevation Control Mechanism: Setuid and Setgid\nAn adversary may perform shell escapes or exploit vulnerabilities in an application with the setsuid or setgid bits to get code running in a different user’s context. On Linux or macOS, when the setuid or setgid bits are set for an application, the application will run with the privileges of the owning user or group respectively. (Citation: setuid man page). Normally an application is run in the current user’s context, regardless of which user or group owns the application. However, there are instances where programs need to be executed in an elevated context to function properly, but the user running them doesn’t need the elevated privileges.\n\nInstead of creating an entry in the sudoers file, which must be done by root, any user can specify the setuid or setgid flag to be set for their own applications. These bits are indicated with an \"s\" instead of an \"x\" when viewing a file's attributes via <code>ls -l</code>. The <code>chmod</code> program can set these bits with via bitmasking, <code>chmod 4777 [file]</code> or via shorthand naming, <code>chmod u+s [file]</code>.\n\nAdversaries can use this mechanism on their own malware to make sure they're able to execute in elevated contexts in the future.(Citation: OSX Keydnap malware).",
"_____no_output_____"
],
[
"## Atomic Tests",
"_____no_output_____"
]
],
[
[
"#Import the Module before running the tests.\n# Checkout Jupyter Notebook at https://github.com/cyb3rbuff/TheAtomicPlaybook to run PS scripts.\nImport-Module /Users/0x6c/AtomicRedTeam/atomics/invoke-atomicredteam/Invoke-AtomicRedTeam.psd1 - Force",
"_____no_output_____"
]
],
[
[
"### Atomic Test #1 - Make and modify binary from C source\nMake, change owner, and change file attributes on a C source code file\n\n**Supported Platforms:** macos, linux\nElevation Required (e.g. root or admin)\n#### Attack Commands: Run with `sh`\n```sh\ncp PathToAtomicsFolder/T1548.001/src/hello.c /tmp/hello.c\nsudo chown root /tmp/hello.c\nsudo make /tmp/hello\nsudo chown root /tmp/hello\nsudo chmod u+s /tmp/hello\n/tmp/hello\n```",
"_____no_output_____"
]
],
[
[
"Invoke-AtomicTest T1548.001 -TestNumbers 1",
"_____no_output_____"
]
],
[
[
"### Atomic Test #2 - Set a SetUID flag on file\nThis test sets the SetUID flag on a file in Linux and macOS.\n\n**Supported Platforms:** macos, linux\nElevation Required (e.g. root or admin)\n#### Attack Commands: Run with `sh`\n```sh\nsudo touch /tmp/evilBinary\nsudo chown root /tmp/evilBinary\nsudo chmod u+s /tmp/evilBinary\n```",
"_____no_output_____"
]
],
[
[
"Invoke-AtomicTest T1548.001 -TestNumbers 2",
"_____no_output_____"
]
],
[
[
"### Atomic Test #3 - Set a SetGID flag on file\nThis test sets the SetGID flag on a file in Linux and macOS.\n\n**Supported Platforms:** macos, linux\nElevation Required (e.g. root or admin)\n#### Attack Commands: Run with `sh`\n```sh\nsudo touch /tmp/evilBinary\nsudo chown root /tmp/evilBinary\nsudo chmod g+s /tmp/evilBinary\n```",
"_____no_output_____"
]
],
[
[
"Invoke-AtomicTest T1548.001 -TestNumbers 3",
"_____no_output_____"
]
],
[
[
"## Detection\nMonitor the file system for files that have the setuid or setgid bits set. Monitor for execution of utilities, like chmod, and their command-line arguments to look for setuid or setguid bits being set.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb484ac3059bc2f6006b5bd47e010cdfb1cb9386 | 310,446 | ipynb | Jupyter Notebook | Neural Networks and Deep Learning/Deep+Neural+Network+-+Application+v8.ipynb | amoghj8/Deep-Learning | 651ebac837a6eb9021b49d2bccc6c8c1294f9248 | [
"MIT"
] | null | null | null | Neural Networks and Deep Learning/Deep+Neural+Network+-+Application+v8.ipynb | amoghj8/Deep-Learning | 651ebac837a6eb9021b49d2bccc6c8c1294f9248 | [
"MIT"
] | null | null | null | Neural Networks and Deep Learning/Deep+Neural+Network+-+Application+v8.ipynb | amoghj8/Deep-Learning | 651ebac837a6eb9021b49d2bccc6c8c1294f9248 | [
"MIT"
] | null | null | null | 314.853955 | 202,038 | 0.906193 | [
[
[
"# Deep Neural Network for Image Classification: Application\n\nWhen you finish this, you will have finished the last programming assignment of Week 4, and also the last programming assignment of this course! \n\nYou will use use the functions you'd implemented in the previous assignment to build a deep network, and apply it to cat vs non-cat classification. Hopefully, you will see an improvement in accuracy relative to your previous logistic regression implementation. \n\n**After this assignment you will be able to:**\n- Build and apply a deep neural network to supervised learning. \n\nLet's get started!",
"_____no_output_____"
],
[
"## 1 - Packages",
"_____no_output_____"
],
[
"Let's first import all the packages that you will need during this assignment. \n- [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.\n- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n- [h5py](http://www.h5py.org) is a common package to interact with a dataset that is stored on an H5 file.\n- [PIL](http://www.pythonware.com/products/pil/) and [scipy](https://www.scipy.org/) are used here to test your model with your own picture at the end.\n- dnn_app_utils provides the functions implemented in the \"Building your Deep Neural Network: Step by Step\" assignment to this notebook.\n- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work.",
"_____no_output_____"
]
],
[
[
"import time\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nfrom dnn_app_utils_v3 import *\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n%load_ext autoreload\n%autoreload 2\n\nnp.random.seed(1)",
"_____no_output_____"
]
],
[
[
"## 2 - Dataset\n\nYou will use the same \"Cat vs non-Cat\" dataset as in \"Logistic Regression as a Neural Network\" (Assignment 2). The model you had built had 70% test accuracy on classifying cats vs non-cats images. Hopefully, your new model will perform a better!\n\n**Problem Statement**: You are given a dataset (\"data.h5\") containing:\n - a training set of m_train images labelled as cat (1) or non-cat (0)\n - a test set of m_test images labelled as cat and non-cat\n - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB).\n\nLet's get more familiar with the dataset. Load the data by running the cell below.",
"_____no_output_____"
]
],
[
[
"train_x_orig, train_y, test_x_orig, test_y, classes = load_data()",
"_____no_output_____"
]
],
[
[
"The following code will show you an image in the dataset. Feel free to change the index and re-run the cell multiple times to see other images. ",
"_____no_output_____"
]
],
[
[
"# Example of a picture\nindex = 10\nplt.imshow(train_x_orig[index])\nprint (\"y = \" + str(train_y[0,index]) + \". It's a \" + classes[train_y[0,index]].decode(\"utf-8\") + \" picture.\")",
"y = 0. It's a non-cat picture.\n"
],
[
"# Explore your dataset \nm_train = train_x_orig.shape[0]\nnum_px = train_x_orig.shape[1]\nm_test = test_x_orig.shape[0]\n\nprint (\"Number of training examples: \" + str(m_train))\nprint (\"Number of testing examples: \" + str(m_test))\nprint (\"Each image is of size: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\nprint (\"train_x_orig shape: \" + str(train_x_orig.shape))\nprint (\"train_y shape: \" + str(train_y.shape))\nprint (\"test_x_orig shape: \" + str(test_x_orig.shape))\nprint (\"test_y shape: \" + str(test_y.shape))",
"Number of training examples: 209\nNumber of testing examples: 50\nEach image is of size: (64, 64, 3)\ntrain_x_orig shape: (209, 64, 64, 3)\ntrain_y shape: (1, 209)\ntest_x_orig shape: (50, 64, 64, 3)\ntest_y shape: (1, 50)\n"
]
],
[
[
"As usual, you reshape and standardize the images before feeding them to the network. The code is given in the cell below.\n\n<img src=\"images/imvectorkiank.png\" style=\"width:450px;height:300px;\">\n\n<caption><center> <u>Figure 1</u>: Image to vector conversion. <br> </center></caption>",
"_____no_output_____"
]
],
[
[
"# Reshape the training and test examples \ntrain_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The \"-1\" makes reshape flatten the remaining dimensions\ntest_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T\n\n# Standardize data to have feature values between 0 and 1.\ntrain_x = train_x_flatten/255.\ntest_x = test_x_flatten/255.\n\nprint (\"train_x's shape: \" + str(train_x.shape))\nprint (\"test_x's shape: \" + str(test_x.shape))\n",
"train_x's shape: (12288, 209)\ntest_x's shape: (12288, 50)\n"
]
],
[
[
"$12,288$ equals $64 \\times 64 \\times 3$ which is the size of one reshaped image vector.",
"_____no_output_____"
],
[
"## 3 - Architecture of your model",
"_____no_output_____"
],
[
"Now that you are familiar with the dataset, it is time to build a deep neural network to distinguish cat images from non-cat images.\n\nYou will build two different models:\n- A 2-layer neural network\n- An L-layer deep neural network\n\nYou will then compare the performance of these models, and also try out different values for $L$. \n\nLet's look at the two architectures.\n\n### 3.1 - 2-layer neural network\n\n<img src=\"images/2layerNN_kiank.png\" style=\"width:650px;height:400px;\">\n<caption><center> <u>Figure 2</u>: 2-layer neural network. <br> The model can be summarized as: ***INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT***. </center></caption>\n\n<u>Detailed Architecture of figure 2</u>:\n- The input is a (64,64,3) image which is flattened to a vector of size $(12288,1)$. \n- The corresponding vector: $[x_0,x_1,...,x_{12287}]^T$ is then multiplied by the weight matrix $W^{[1]}$ of size $(n^{[1]}, 12288)$.\n- You then add a bias term and take its relu to get the following vector: $[a_0^{[1]}, a_1^{[1]},..., a_{n^{[1]}-1}^{[1]}]^T$.\n- You then repeat the same process.\n- You multiply the resulting vector by $W^{[2]}$ and add your intercept (bias). \n- Finally, you take the sigmoid of the result. If it is greater than 0.5, you classify it to be a cat.\n\n### 3.2 - L-layer deep neural network\n\nIt is hard to represent an L-layer deep neural network with the above representation. However, here is a simplified network representation:\n\n<img src=\"images/LlayerNN_kiank.png\" style=\"width:650px;height:400px;\">\n<caption><center> <u>Figure 3</u>: L-layer neural network. <br> The model can be summarized as: ***[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID***</center></caption>\n\n<u>Detailed Architecture of figure 3</u>:\n- The input is a (64,64,3) image which is flattened to a vector of size (12288,1).\n- The corresponding vector: $[x_0,x_1,...,x_{12287}]^T$ is then multiplied by the weight matrix $W^{[1]}$ and then you add the intercept $b^{[1]}$. The result is called the linear unit.\n- Next, you take the relu of the linear unit. This process could be repeated several times for each $(W^{[l]}, b^{[l]})$ depending on the model architecture.\n- Finally, you take the sigmoid of the final linear unit. If it is greater than 0.5, you classify it to be a cat.\n\n### 3.3 - General methodology\n\nAs usual you will follow the Deep Learning methodology to build the model:\n 1. Initialize parameters / Define hyperparameters\n 2. Loop for num_iterations:\n a. Forward propagation\n b. Compute cost function\n c. Backward propagation\n d. Update parameters (using parameters, and grads from backprop) \n 4. Use trained parameters to predict labels\n\nLet's now implement those two models!",
"_____no_output_____"
],
[
"## 4 - Two-layer neural network\n\n**Question**: Use the helper functions you have implemented in the previous assignment to build a 2-layer neural network with the following structure: *LINEAR -> RELU -> LINEAR -> SIGMOID*. The functions you may need and their inputs are:\n```python\ndef initialize_parameters(n_x, n_h, n_y):\n ...\n return parameters \ndef linear_activation_forward(A_prev, W, b, activation):\n ...\n return A, cache\ndef compute_cost(AL, Y):\n ...\n return cost\ndef linear_activation_backward(dA, cache, activation):\n ...\n return dA_prev, dW, db\ndef update_parameters(parameters, grads, learning_rate):\n ...\n return parameters\n```",
"_____no_output_____"
]
],
[
[
"### CONSTANTS DEFINING THE MODEL ####\nn_x = 12288 # num_px * num_px * 3\nn_h = 7\nn_y = 1\nlayers_dims = (n_x, n_h, n_y)",
"_____no_output_____"
],
[
"# GRADED FUNCTION: two_layer_model\n\ndef two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):\n \"\"\"\n Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID.\n \n Arguments:\n X -- input data, of shape (n_x, number of examples)\n Y -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)\n layers_dims -- dimensions of the layers (n_x, n_h, n_y)\n num_iterations -- number of iterations of the optimization loop\n learning_rate -- learning rate of the gradient descent update rule\n print_cost -- If set to True, this will print the cost every 100 iterations \n \n Returns:\n parameters -- a dictionary containing W1, W2, b1, and b2\n \"\"\"\n \n np.random.seed(1)\n grads = {}\n costs = [] # to keep track of the cost\n m = X.shape[1] # number of examples\n (n_x, n_h, n_y) = layers_dims\n \n # Initialize parameters dictionary, by calling one of the functions you'd previously implemented\n ### START CODE HERE ### (≈ 1 line of code)\n parameters = initialize_parameters(n_x, n_h, n_y)\n ### END CODE HERE ###\n \n # Get W1, b1, W2 and b2 from the dictionary parameters.\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n \n # Loop (gradient descent)\n\n for i in range(0, num_iterations):\n\n # Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: \"X, W1, b1, W2, b2\". Output: \"A1, cache1, A2, cache2\".\n ### START CODE HERE ### (≈ 2 lines of code)\n A1, cache1 = linear_activation_forward(X, W1, b1, activation='relu')\n A2, cache2 = linear_activation_forward(A1, W2, b2, activation='sigmoid')\n ### END CODE HERE ###\n \n # Compute cost\n ### START CODE HERE ### (≈ 1 line of code)\n cost = compute_cost(A2, Y)\n ### END CODE HERE ###\n \n # Initializing backward propagation\n dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))\n \n # Backward propagation. Inputs: \"dA2, cache2, cache1\". Outputs: \"dA1, dW2, db2; also dA0 (not used), dW1, db1\".\n ### START CODE HERE ### (≈ 2 lines of code)\n dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation='sigmoid')\n dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation='relu')\n ### END CODE HERE ###\n \n # Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2\n grads['dW1'] = dW1\n grads['db1'] = db1\n grads['dW2'] = dW2\n grads['db2'] = db2\n \n # Update parameters.\n ### START CODE HERE ### (approx. 1 line of code)\n parameters = update_parameters(parameters, grads, learning_rate)\n ### END CODE HERE ###\n\n # Retrieve W1, b1, W2, b2 from parameters\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n \n # Print the cost every 100 training example\n if print_cost and i % 100 == 0:\n print(\"Cost after iteration {}: {}\".format(i, np.squeeze(cost)))\n if print_cost and i % 100 == 0:\n costs.append(cost)\n \n # plot the cost\n\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n \n return parameters",
"_____no_output_____"
]
],
[
[
"Run the cell below to train your parameters. See if your model runs. The cost should be decreasing. It may take up to 5 minutes to run 2500 iterations. Check if the \"Cost after iteration 0\" matches the expected output below, if not click on the square (⬛) on the upper bar of the notebook to stop the cell and try to find your error.",
"_____no_output_____"
]
],
[
[
"parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)",
"Cost after iteration 0: 0.693049735659989\nCost after iteration 100: 0.6464320953428849\nCost after iteration 200: 0.6325140647912678\nCost after iteration 300: 0.6015024920354665\nCost after iteration 400: 0.5601966311605748\nCost after iteration 500: 0.515830477276473\nCost after iteration 600: 0.4754901313943325\nCost after iteration 700: 0.43391631512257495\nCost after iteration 800: 0.4007977536203886\nCost after iteration 900: 0.35807050113237987\nCost after iteration 1000: 0.3394281538366413\nCost after iteration 1100: 0.30527536361962654\nCost after iteration 1200: 0.2749137728213015\nCost after iteration 1300: 0.24681768210614827\nCost after iteration 1400: 0.1985073503746611\nCost after iteration 1500: 0.17448318112556593\nCost after iteration 1600: 0.1708076297809661\nCost after iteration 1700: 0.11306524562164737\nCost after iteration 1800: 0.09629426845937163\nCost after iteration 1900: 0.08342617959726878\nCost after iteration 2000: 0.0743907870431909\nCost after iteration 2100: 0.06630748132267938\nCost after iteration 2200: 0.05919329501038176\nCost after iteration 2300: 0.05336140348560564\nCost after iteration 2400: 0.048554785628770226\n"
]
],
[
[
"**Expected Output**:\n<table> \n <tr>\n <td> **Cost after iteration 0**</td>\n <td> 0.6930497356599888 </td>\n </tr>\n <tr>\n <td> **Cost after iteration 100**</td>\n <td> 0.6464320953428849 </td>\n </tr>\n <tr>\n <td> **...**</td>\n <td> ... </td>\n </tr>\n <tr>\n <td> **Cost after iteration 2400**</td>\n <td> 0.048554785628770206 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"Good thing you built a vectorized implementation! Otherwise it might have taken 10 times longer to train this.\n\nNow, you can use the trained parameters to classify images from the dataset. To see your predictions on the training and test sets, run the cell below.",
"_____no_output_____"
]
],
[
[
"predictions_train = predict(train_x, train_y, parameters)",
"Accuracy: 1.0\n"
]
],
[
[
"**Expected Output**:\n<table> \n <tr>\n <td> **Accuracy**</td>\n <td> 1.0 </td>\n </tr>\n</table>",
"_____no_output_____"
]
],
[
[
"predictions_test = predict(test_x, test_y, parameters)",
"Accuracy: 0.72\n"
]
],
[
[
"**Expected Output**:\n\n<table> \n <tr>\n <td> **Accuracy**</td>\n <td> 0.72 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"**Note**: You may notice that running the model on fewer iterations (say 1500) gives better accuracy on the test set. This is called \"early stopping\" and we will talk about it in the next course. Early stopping is a way to prevent overfitting. \n\nCongratulations! It seems that your 2-layer neural network has better performance (72%) than the logistic regression implementation (70%, assignment week 2). Let's see if you can do even better with an $L$-layer model.",
"_____no_output_____"
],
[
"## 5 - L-layer Neural Network\n\n**Question**: Use the helper functions you have implemented previously to build an $L$-layer neural network with the following structure: *[LINEAR -> RELU]$\\times$(L-1) -> LINEAR -> SIGMOID*. The functions you may need and their inputs are:\n```python\ndef initialize_parameters_deep(layers_dims):\n ...\n return parameters \ndef L_model_forward(X, parameters):\n ...\n return AL, caches\ndef compute_cost(AL, Y):\n ...\n return cost\ndef L_model_backward(AL, Y, caches):\n ...\n return grads\ndef update_parameters(parameters, grads, learning_rate):\n ...\n return parameters\n```",
"_____no_output_____"
]
],
[
[
"### CONSTANTS ###\nlayers_dims = [12288, 20, 7, 5, 1] # 4-layer model",
"_____no_output_____"
],
[
"# GRADED FUNCTION: L_layer_model\n\ndef L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009\n \"\"\"\n Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.\n \n Arguments:\n X -- data, numpy array of shape (number of examples, num_px * num_px * 3)\n Y -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)\n layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).\n learning_rate -- learning rate of the gradient descent update rule\n num_iterations -- number of iterations of the optimization loop\n print_cost -- if True, it prints the cost every 100 steps\n \n Returns:\n parameters -- parameters learnt by the model. They can then be used to predict.\n \"\"\"\n\n np.random.seed(1)\n costs = [] # keep track of cost\n \n # Parameters initialization. (≈ 1 line of code)\n ### START CODE HERE ###\n parameters = initialize_parameters_deep(layers_dims)\n ### END CODE HERE ###\n \n # Loop (gradient descent)\n for i in range(0, num_iterations):\n\n # Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.\n ### START CODE HERE ### (≈ 1 line of code)\n AL, caches = L_model_forward(X, parameters)\n ### END CODE HERE ###\n \n # Compute cost.\n ### START CODE HERE ### (≈ 1 line of code)\n cost = compute_cost(AL, Y)\n ### END CODE HERE ###\n \n # Backward propagation.\n ### START CODE HERE ### (≈ 1 line of code)\n grads = L_model_backward(AL, Y, caches)\n ### END CODE HERE ###\n \n # Update parameters.\n ### START CODE HERE ### (≈ 1 line of code)\n parameters = update_parameters(parameters, grads, learning_rate)\n ### END CODE HERE ###\n \n # Print the cost every 100 training example\n if print_cost and i % 100 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n if print_cost and i % 100 == 0:\n costs.append(cost)\n \n # plot the cost\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n \n return parameters",
"_____no_output_____"
]
],
[
[
"You will now train the model as a 4-layer neural network. \n\nRun the cell below to train your model. The cost should decrease on every iteration. It may take up to 5 minutes to run 2500 iterations. Check if the \"Cost after iteration 0\" matches the expected output below, if not click on the square (⬛) on the upper bar of the notebook to stop the cell and try to find your error.",
"_____no_output_____"
]
],
[
[
"parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)",
"Cost after iteration 0: 0.771749\nCost after iteration 100: 0.672053\nCost after iteration 200: 0.648263\nCost after iteration 300: 0.611507\nCost after iteration 400: 0.567047\nCost after iteration 500: 0.540138\nCost after iteration 600: 0.527930\nCost after iteration 700: 0.465477\nCost after iteration 800: 0.369126\nCost after iteration 900: 0.391747\nCost after iteration 1000: 0.315187\nCost after iteration 1100: 0.272700\nCost after iteration 1200: 0.237419\nCost after iteration 1300: 0.199601\nCost after iteration 1400: 0.189263\nCost after iteration 1500: 0.161189\nCost after iteration 1600: 0.148214\nCost after iteration 1700: 0.137775\nCost after iteration 1800: 0.129740\nCost after iteration 1900: 0.121225\nCost after iteration 2000: 0.113821\nCost after iteration 2100: 0.107839\nCost after iteration 2200: 0.102855\nCost after iteration 2300: 0.100897\nCost after iteration 2400: 0.092878\n"
]
],
[
[
"**Expected Output**:\n<table> \n <tr>\n <td> **Cost after iteration 0**</td>\n <td> 0.771749 </td>\n </tr>\n <tr>\n <td> **Cost after iteration 100**</td>\n <td> 0.672053 </td>\n </tr>\n <tr>\n <td> **...**</td>\n <td> ... </td>\n </tr>\n <tr>\n <td> **Cost after iteration 2400**</td>\n <td> 0.092878 </td>\n </tr>\n</table>",
"_____no_output_____"
]
],
[
[
"pred_train = predict(train_x, train_y, parameters)",
"Accuracy: 0.985645933014\n"
]
],
[
[
"<table>\n <tr>\n <td>\n **Train Accuracy**\n </td>\n <td>\n 0.985645933014\n </td>\n </tr>\n</table>",
"_____no_output_____"
]
],
[
[
"pred_test = predict(test_x, test_y, parameters)",
"Accuracy: 0.8\n"
]
],
[
[
"**Expected Output**:\n\n<table> \n <tr>\n <td> **Test Accuracy**</td>\n <td> 0.8 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"Congrats! It seems that your 4-layer neural network has better performance (80%) than your 2-layer neural network (72%) on the same test set. \n\nThis is good performance for this task. Nice job! \n\nThough in the next course on \"Improving deep neural networks\" you will learn how to obtain even higher accuracy by systematically searching for better hyperparameters (learning_rate, layers_dims, num_iterations, and others you'll also learn in the next course). ",
"_____no_output_____"
],
[
"## 6) Results Analysis\n\nFirst, let's take a look at some images the L-layer model labeled incorrectly. This will show a few mislabeled images. ",
"_____no_output_____"
]
],
[
[
"print_mislabeled_images(classes, test_x, test_y, pred_test)",
"_____no_output_____"
]
],
[
[
"**A few types of images the model tends to do poorly on include:** \n- Cat body in an unusual position\n- Cat appears against a background of a similar color\n- Unusual cat color and species\n- Camera Angle\n- Brightness of the picture\n- Scale variation (cat is very large or small in image) ",
"_____no_output_____"
],
[
"## 7) Test with your own image (optional/ungraded exercise) ##\n\nCongratulations on finishing this assignment. You can use your own image and see the output of your model. To do that:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Change your image's name in the following code\n 4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!",
"_____no_output_____"
]
],
[
[
"## START CODE HERE ##\nmy_image = \"my_image.jpg\" # change this to the name of your image file \nmy_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)\n## END CODE HERE ##\n\nfname = \"images/\" + my_image\nimage = np.array(ndimage.imread(fname, flatten=False))\nmy_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))\nmy_image = my_image/255.\nmy_predicted_image = predict(my_image, my_label_y, parameters)\n\nplt.imshow(image)\nprint (\"y = \" + str(np.squeeze(my_predicted_image)) + \", your L-layer model predicts a \\\"\" + classes[int(np.squeeze(my_predicted_image)),].decode(\"utf-8\") + \"\\\" picture.\")",
"_____no_output_____"
]
],
[
[
"**References**:\n\n- for auto-reloading external module: http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb4855a0305db56d0a69a8370097ac741653d15e | 13,156 | ipynb | Jupyter Notebook | homeworks_basic/assignment0_04_tree/assignment0_04_decision_tree.ipynb | iapetus2/ml-mipt | c461ed06c4f50b064ac72fb6b2816c1158587d09 | [
"MIT"
] | null | null | null | homeworks_basic/assignment0_04_tree/assignment0_04_decision_tree.ipynb | iapetus2/ml-mipt | c461ed06c4f50b064ac72fb6b2816c1158587d09 | [
"MIT"
] | null | null | null | homeworks_basic/assignment0_04_tree/assignment0_04_decision_tree.ipynb | iapetus2/ml-mipt | c461ed06c4f50b064ac72fb6b2816c1158587d09 | [
"MIT"
] | null | null | null | 30.313364 | 409 | 0.588173 | [
[
[
"## assignment 04: Decision Tree construction",
"_____no_output_____"
]
],
[
[
"# If working in colab, uncomment the following line\n# ! wget https://raw.githubusercontent.com/girafe-ai/ml-mipt/21f_basic/homeworks_basic/assignment0_04_tree/tree.py -nc",
"_____no_output_____"
],
[
"import numpy as np\nfrom matplotlib import pyplot as plt\n%matplotlib inline\nfrom sklearn.base import BaseEstimator\nfrom sklearn.datasets import make_classification, make_regression, load_digits, load_boston\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import accuracy_score, mean_squared_error\nimport pandas as pd\n\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
]
],
[
[
"Let's fix the `random_state` (a.k.a. random seed).",
"_____no_output_____"
]
],
[
[
"RANDOM_STATE = 42",
"_____no_output_____"
]
],
[
[
"__Your ultimate task for today is to impement the `DecisionTree` class and use it to solve classification and regression problems.__\n\n__Specifications:__\n- The class inherits from `sklearn.BaseEstimator`;\n- Constructor is implemented for you. It has the following parameters:\n * `max_depth` - maximum depth of the tree; `np.inf` by default\n * `min_samples_split` - minimal number of samples in the leaf to make a split; `2` by default;\n * `criterion` - criterion to select the best split; in classification one of `['gini', 'entropy']`, default `gini`; in regression `variance`;\n\n- `fit` method takes `X` (`numpy.array` of type `float` shaped `(n_objects, n_features)`) and `y` (`numpy.array` of type float shaped `(n_objects, 1)` in regression; `numpy.array` of type int shaped `(n_objects, 1)` with class labels in classification). It works inplace and fits the `DecisionTree` class instance to the provided data from scratch.\n\n- `predict` method takes `X` (`numpy.array` of type `float` shaped `(n_objects, n_features)`) and returns the predicted $\\hat{y}$ values. In classification it is a class label for every object (the most frequent in the leaf; if several classes meet this requirement select the one with the smallest class index). In regression it is the desired constant (e.g. mean value for `variance` criterion)\n\n- `predict_proba` method (works only for classification (`gini` or `entropy` criterion). It takes `X` (`numpy.array` of type `float` shaped `(n_objects, n_features)`) and returns the `numpy.array` of type `float` shaped `(n_objects, n_features)` with class probabilities for every object from `X`. Class $i$ probability equals the ratio of $i$ class objects that got in this node in the training set.\n\n \n__Small recap:__\n\nTo find the optimal split the following functional is evaluated:\n \n$$G(j, t) = H(Q) - \\dfrac{|L|}{|Q|} H(L) - \\dfrac{|R|}{|Q|} H(R),$$\n where $Q$ is the dataset from the current node, $L$ and $R$ are left and right subsets defined by the split $x^{(j)} < t$.\n\n\n\n1. Classification. Let $p_i$ be the probability of $i$ class in subset $X$ (ratio of the $i$ class objects in the dataset). The criterions are defined as:\n \n * `gini`: Gini impurity $$H(R) = 1 -\\sum_{i = 1}^K p_i^2$$\n \n * `entropy`: Entropy $$H(R) = -\\sum_{i = 1}^K p_i \\log(p_i)$$ (One might use the natural logarithm).\n \n2. Regression. Let $y_l$ be the target value for the $R$, $\\mathbf{y} = (y_1, \\dots, y_N)$ – all targets for the selected dataset $X$.\n \n * `variance`: $$H(R) = \\dfrac{1}{|R|} \\sum_{y_j \\in R}(y_j - \\text{mean}(\\mathbf{y}))^2$$\n \n * `mad_median`: $$H(R) = \\dfrac{1}{|R|} \\sum_{y_j \\in R}|y_j - \\text{median}(\\mathbf{y})|$$\n \n",
"_____no_output_____"
],
[
"**Hints and comments**:\n\n* No need to deal with categorical features, they will not be present.\n* Siple greedy recursive procedure is enough. However, you can speed it up somehow (e.g. using percentiles).\n* Please, do not copy implementations available online. You are supposed to build very simple example of the Decision Tree.",
"_____no_output_____"
],
[
"File `tree.py` is waiting for you. Implement all the needed methods in that file.",
"_____no_output_____"
],
[
"### Check yourself",
"_____no_output_____"
]
],
[
[
"from tree import entropy, gini, variance, mad_median, DecisionTree",
"_____no_output_____"
]
],
[
[
"#### Simple check",
"_____no_output_____"
]
],
[
[
"X = np.ones((4, 5), dtype=float) * np.arange(4)[:, None]\ny = np.arange(4)[:, None] + np.asarray([0.2, -0.3, 0.1, 0.4])[:, None]\nclass_estimator = DecisionTree(max_depth=10, criterion_name='gini')\n\n(X_l, y_l), (X_r, y_r) = class_estimator.make_split(1, 1., X, y)\n\nassert np.array_equal(X[:1], X_l)\nassert np.array_equal(X[1:], X_r)\nassert np.array_equal(y[:1], y_l)\nassert np.array_equal(y[1:], y_r)",
"_____no_output_____"
]
],
[
[
"#### Classification problem",
"_____no_output_____"
]
],
[
[
"digits_data = load_digits().data\ndigits_target = load_digits().target[:, None] # to make the targets consistent with our model interfaces\nX_train, X_test, y_train, y_test = train_test_split(digits_data, digits_target, test_size=0.2, random_state=RANDOM_STATE)",
"_____no_output_____"
],
[
"assert len(y_train.shape) == 2 and y_train.shape[0] == len(X_train)",
"_____no_output_____"
],
[
"class_estimator = DecisionTree(max_depth=10, criterion_name='gini')\nclass_estimator.fit(X_train, y_train)\nans = class_estimator.predict(X_test)\naccuracy_gini = accuracy_score(y_test, ans)\nprint(accuracy_gini)",
"_____no_output_____"
],
[
"reference = np.array([0.09027778, 0.09236111, 0.08333333, 0.09583333, 0.11944444,\n 0.13888889, 0.09930556, 0.09444444, 0.08055556, 0.10555556])",
"_____no_output_____"
],
[
"class_estimator = DecisionTree(max_depth=10, criterion_name='entropy')\nclass_estimator.fit(X_train, y_train)\nans = class_estimator.predict(X_test)\naccuracy_entropy = accuracy_score(y_test, ans)\nprint(accuracy_entropy)",
"_____no_output_____"
],
[
"assert 0.84 < accuracy_gini < 0.9\nassert 0.86 < accuracy_entropy < 0.9\nassert np.sum(np.abs(class_estimator.predict_proba(X_test).mean(axis=0) - reference)) < 1e-4",
"_____no_output_____"
]
],
[
[
"Let's use 5-fold cross validation (`GridSearchCV`) to find optimal values for `max_depth` and `criterion` hyperparameters.",
"_____no_output_____"
]
],
[
[
"param_grid = {'max_depth': range(3,11), 'criterion_name': ['gini', 'entropy']}\ngs = GridSearchCV(DecisionTree(), param_grid=param_grid, cv=5, scoring='accuracy', n_jobs=-2)",
"_____no_output_____"
],
[
"%%time\ngs.fit(X_train, y_train)",
"_____no_output_____"
],
[
"gs.best_params_",
"_____no_output_____"
],
[
"assert gs.best_params_['criterion_name'] == 'entropy'\nassert 6 < gs.best_params_['max_depth'] < 9",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 8))\nplt.title(\"The dependence of quality on the depth of the tree\")\nplt.plot(np.arange(3,11), gs.cv_results_['mean_test_score'][:8], label='Gini')\nplt.plot(np.arange(3,11), gs.cv_results_['mean_test_score'][8:], label='Entropy')\nplt.legend(fontsize=11, loc=1)\nplt.xlabel(\"max_depth\")\nplt.ylabel('accuracy')\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Regression problem",
"_____no_output_____"
]
],
[
[
"regr_data = load_boston().data\nregr_target = load_boston().target[:, None] # to make the targets consistent with our model interfaces\nRX_train, RX_test, Ry_train, Ry_test = train_test_split(regr_data, regr_target, test_size=0.2, random_state=RANDOM_STATE)",
"_____no_output_____"
],
[
"regressor = DecisionTree(max_depth=10, criterion_name='mad_median')\nregressor.fit(RX_train, Ry_train)\npredictions_mad = regressor.predict(RX_test)\nmse_mad = mean_squared_error(Ry_test, predictions_mad)\nprint(mse_mad)",
"_____no_output_____"
],
[
"regressor = DecisionTree(max_depth=10, criterion_name='variance')\nregressor.fit(RX_train, Ry_train)\npredictions_mad = regressor.predict(RX_test)\nmse_var = mean_squared_error(Ry_test, predictions_mad)\nprint(mse_var)",
"_____no_output_____"
],
[
"assert 9 < mse_mad < 20\nassert 8 < mse_var < 12",
"_____no_output_____"
],
[
"param_grid_R = {'max_depth': range(2,9), 'criterion_name': ['variance', 'mad_median']}",
"_____no_output_____"
],
[
"gs_R = GridSearchCV(DecisionTree(), param_grid=param_grid_R, cv=5, scoring='neg_mean_squared_error', n_jobs=-2)\ngs_R.fit(RX_train, Ry_train)",
"_____no_output_____"
],
[
"gs_R.best_params_",
"_____no_output_____"
],
[
"assert gs_R.best_params_['criterion_name'] == 'mad_median'\nassert 3 < gs_R.best_params_['max_depth'] < 7",
"_____no_output_____"
],
[
"var_scores = gs_R.cv_results_['mean_test_score'][:7]\nmad_scores = gs_R.cv_results_['mean_test_score'][7:]",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 8))\nplt.title(\"The dependence of neg_mse on the depth of the tree\")\nplt.plot(np.arange(2,9), var_scores, label='variance')\nplt.plot(np.arange(2,9), mad_scores, label='mad_median')\nplt.legend(fontsize=11, loc=1)\nplt.xlabel(\"max_depth\")\nplt.ylabel('neg_mse')\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb48561770b14935df00398387c0935f7eac71f9 | 4,460 | ipynb | Jupyter Notebook | _teaching/2018Spring/APMA_E2000/Homework2.ipynb | drewyoungren/drewyoungren.github.io | 38ed4e7e053f4a79320bdf5423f1d42eb0ce618b | [
"MIT"
] | null | null | null | _teaching/2018Spring/APMA_E2000/Homework2.ipynb | drewyoungren/drewyoungren.github.io | 38ed4e7e053f4a79320bdf5423f1d42eb0ce618b | [
"MIT"
] | 2 | 2020-02-26T18:01:37.000Z | 2021-09-27T21:28:24.000Z | _teaching/2018Spring/APMA_E2000/Homework2.ipynb | drewyoungren/drewyoungren.github.io | 38ed4e7e053f4a79320bdf5423f1d42eb0ce618b | [
"MIT"
] | 1 | 2018-04-17T03:25:55.000Z | 2018-04-17T03:25:55.000Z | 34.045802 | 210 | 0.527354 | [
[
[
"# Homework 2\n## Due: January 30, 2018, 8 a.m.\n\nPlease give a complete, justified solution to each question below. A single-term answer without explanation will receive no credit. \n\nPlease complete each question on its own sheet of paper (or more if necessary), and upload to [Gradsescope](https://gradescope.com/).",
"_____no_output_____"
],
[
"$$\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\dydx}{\\frac{dy}{dx}}\n\\newcommand{\\proj}{\\textrm{proj}}\n% For boldface vectors:\n\\renewcommand{\\vec}[1]{\\mathbf{#1}}\n$$",
"_____no_output_____"
],
[
"1\\. Suppose $\\vec a \\ne \\vec 0$.\n - Suppose $\\vec a \\cdot \\vec b = \\vec a \\cdot \\vec c$. Does it follow that $\\vec b = \\vec c$?\n - Suppose $\\vec a \\times \\vec b = \\vec a \\times \\vec c$. Does it follow that $\\vec b = \\vec c$?\n - Suppose $\\vec a \\cdot \\vec b = \\vec a \\cdot \\vec c$ and $\\vec a \\times \\vec b = \\vec a \\times \\vec c$. Does it follow that $\\vec b = \\vec c$?",
"_____no_output_____"
],
[
"2\\. Find parametric equations for the following lines:\n - the line that goes through the points $(0, -3, 1)$ and $(5, 2, 2)$\n - the line that goes through the point $(3, 2, 1)$ and is perpendicular to the plane described by the equation\n$$4x + 3y - 5z = 3.$$\n\n Find equations for the following planes:\n - the plane that passes through the point $(1, -1, 1)$ and contains the line with symmetric equations\n$$x = 2y = 3z.$$ \n - the plane that contains all points that are equidistant from the points $(3, 2, -1)$ and $(-7, 4, -3)$.\n",
"_____no_output_____"
],
[
"3\\. Show that if $\\langle a, b, c \\rangle$ is a unit vector, then the distance between the parallel planes given by \n$$\n\tax+by+cz = d_1 ~~~\\text{ and }~~~ ax+by+cz = d_2\n$$ is $\\left|d_1-d_2\\right|$. _Do not just quote a formula in the text. Use projection._",
"_____no_output_____"
],
[
"4\\. Show that the planes $$ 2x + y -3 z = 4 ~~~\\text{ and } ~~~ 4x + 2y -6 z = -2 $$\n\tare parallel and find the distance between the two parallel planes above.\n",
"_____no_output_____"
],
[
"5\\. (1) Sketch the trace at $z=0$ for each relation below and (2) match the equation with the surface it defines.\n\t\n<table text-align=\"left\">\n <tr><td width=\"25%\">(i) $x = y^2 - z^2$</td>\n <td width=\"25%\">(iii) $x^2 = y^2 + z^2$</td></tr>\n <tr><td> (ii) $9y^2 + z^2 = 16$ </td>\n <td> (iv) $z^2 + x^2 - y^2 = 1$</td></tr>\n</table>\n\n<table>\n <tr><td width=\"25%\">(A) <img src=\"hw-10-6-fig2.png\" width=\"45%\"></td>\n <td width=\"25%\">(B) <img src=\"hw-10-6-fig1.png\" width=\"45%\"></td></tr>\n <tr><td>(C) <img src=\"hw-10-6-fig4.png\" width=\"45%\"></td>\n <td>(D) <img src=\"hw-10-6-fig3.png\" width=\"45%\"></td></tr>\n</table>",
"_____no_output_____"
],
[
"6\\. Find an equation for the surface consisting of all points $P$ for which the distance from $P$ to the $y$-axis is half the distance from $P$ to the $xz$-plane. Sketch or briefly describe the surface.",
"_____no_output_____"
],
[
"7\\. Find paramtric equations for a straight line through the point $(1,1,0)$ that lies entirely on the surface of the hyperboloid $$\n\tx^2+y^2 = z^2 +2.\n$$\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb4865639dedf3c97ae2b885d85b41eed5dcce16 | 89,506 | ipynb | Jupyter Notebook | S5/s5pass2.ipynb | VijayPrakashReddy-k/EVA | fd78ff8bda4227aebd0f5db14865d3c5a47b19b0 | [
"MIT"
] | null | null | null | S5/s5pass2.ipynb | VijayPrakashReddy-k/EVA | fd78ff8bda4227aebd0f5db14865d3c5a47b19b0 | [
"MIT"
] | null | null | null | S5/s5pass2.ipynb | VijayPrakashReddy-k/EVA | fd78ff8bda4227aebd0f5db14865d3c5a47b19b0 | [
"MIT"
] | null | null | null | 101.943052 | 59,140 | 0.768697 | [
[
[
"# Import Libraries",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms",
"_____no_output_____"
],
[
"# Train Phase transformations\ntrain_transforms = transforms.Compose([\n # transforms.Resize((28, 28)),\n # transforms.ColorJitter(brightness=0.10, contrast=0.1, saturation=0.10, hue=0.1),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)) # The mean and std have to be sequences (e.g., tuples), therefore you should add a comma after the values. \n # Note the difference between (0.1307) and (0.1307,)\n ])\n\n\n# Test Phase transformations\ntest_transforms = transforms.Compose([\n # transforms.Resize((28, 28)),\n # transforms.ColorJitter(brightness=0.10, contrast=0.1, saturation=0.10, hue=0.1),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n",
"_____no_output_____"
]
],
[
[
"Transforms.compose-Composes several transforms together.\nToTensor()-Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor\nConverts a PIL Image or numpy.ndarray (H x W x C) in the range\n [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]\n if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)\n or if the numpy.ndarray has dtype = np.uint8\nNormalize- Normalize a tensor image with mean and standard deviation.\n Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform\n will normalize each channel of the input ``torch.*Tensor`` i.e.\n ``input[channel] = (input[channel] - mean[channel]) / std[channel]\n \nResize-Resize the input PIL Image to the given size.\nCenterCrop-Crops the given PIL Image at the center.\nPad-Pad the given PIL Image on all sides with the given \"pad\" value\nRandomTransforms-Base class for a list of transformations with randomness\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"# Dataset and Creating Train/Test Split",
"_____no_output_____"
]
],
[
[
"train = datasets.MNIST('./data', train=True, download=True, transform=train_transforms)\ntest = datasets.MNIST('./data', train=False, download=True, transform=test_transforms)",
"_____no_output_____"
]
],
[
[
"# Dataloader Arguments & Test/Train Dataloaders\n",
"_____no_output_____"
]
],
[
[
"SEED = 1\n\n# CUDA?\ncuda = torch.cuda.is_available()\nprint(\"CUDA Available?\", cuda)\n\n# For reproducibility\ntorch.manual_seed(SEED)\n\nif cuda:\n torch.cuda.manual_seed(SEED)\n\n# dataloader arguments - something you'll fetch these from cmdprmt\ndataloader_args = dict(shuffle=True, batch_size=128, num_workers=4, pin_memory=True) if cuda else dict(shuffle=True, batch_size=64)\n\n# train dataloader\ntrain_loader = torch.utils.data.DataLoader(train, **dataloader_args)\n\n# test dataloader\ntest_loader = torch.utils.data.DataLoader(test, **dataloader_args)",
"CUDA Available? True\n"
]
],
[
[
"# The model\nLet's start with the model we first saw",
"_____no_output_____"
]
],
[
[
"#defining the network structure\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=10, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15), # output_size = 26\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15), # output_size = 24\n nn.Conv2d(in_channels=10, out_channels=20, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(20),\n nn.ReLU(),\n nn.Dropout(0.15),# output_size = 22\n nn.MaxPool2d(2, 2)# output_size = 11\n \n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(in_channels=20, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15)# output_size = 11\n\n ) \n \n self.conv3 = nn.Sequential(\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15),# output_size = 9\n nn.Conv2d(in_channels=10, out_channels=16, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.Dropout(0.15)# output_size = 7\n )\n \n self.conv4 = nn.Sequential(\n nn.Conv2d(in_channels=16, out_channels=10, kernel_size=(3, 3), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15),#output_size = 5\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n nn.BatchNorm2d(10),\n nn.ReLU(),\n nn.Dropout(0.15),# output_size = 5\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(5, 5), padding=0, bias=False)\n \n )\n\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n \n x = x.view(-1, 10)\n return F.log_softmax(x)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"# Model Params\nCan't emphasize on how important viewing Model Summary is. \nUnfortunately, there is no in-built model visualizer, so we have to take external help",
"_____no_output_____"
]
],
[
[
"!pip install torchsummary\nfrom torchsummary import summary\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nprint(device)\nmodel = Net().to(device)\nsummary(model, input_size=(1, 28, 28))",
"Requirement already satisfied: torchsummary in /usr/local/lib/python3.6/dist-packages (1.5.1)\ncuda\n----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 10, 26, 26] 90\n BatchNorm2d-2 [-1, 10, 26, 26] 20\n ReLU-3 [-1, 10, 26, 26] 0\n Dropout-4 [-1, 10, 26, 26] 0\n Conv2d-5 [-1, 10, 24, 24] 900\n BatchNorm2d-6 [-1, 10, 24, 24] 20\n ReLU-7 [-1, 10, 24, 24] 0\n Dropout-8 [-1, 10, 24, 24] 0\n Conv2d-9 [-1, 20, 22, 22] 1,800\n BatchNorm2d-10 [-1, 20, 22, 22] 40\n ReLU-11 [-1, 20, 22, 22] 0\n Dropout-12 [-1, 20, 22, 22] 0\n MaxPool2d-13 [-1, 20, 11, 11] 0\n Conv2d-14 [-1, 10, 11, 11] 200\n BatchNorm2d-15 [-1, 10, 11, 11] 20\n ReLU-16 [-1, 10, 11, 11] 0\n Dropout-17 [-1, 10, 11, 11] 0\n Conv2d-18 [-1, 10, 9, 9] 900\n BatchNorm2d-19 [-1, 10, 9, 9] 20\n ReLU-20 [-1, 10, 9, 9] 0\n Dropout-21 [-1, 10, 9, 9] 0\n Conv2d-22 [-1, 16, 7, 7] 1,440\n BatchNorm2d-23 [-1, 16, 7, 7] 32\n ReLU-24 [-1, 16, 7, 7] 0\n Dropout-25 [-1, 16, 7, 7] 0\n Conv2d-26 [-1, 10, 5, 5] 1,440\n BatchNorm2d-27 [-1, 10, 5, 5] 20\n ReLU-28 [-1, 10, 5, 5] 0\n Dropout-29 [-1, 10, 5, 5] 0\n Conv2d-30 [-1, 10, 5, 5] 100\n BatchNorm2d-31 [-1, 10, 5, 5] 20\n ReLU-32 [-1, 10, 5, 5] 0\n Dropout-33 [-1, 10, 5, 5] 0\n Conv2d-34 [-1, 10, 1, 1] 2,500\n================================================================\nTotal params: 9,562\nTrainable params: 9,562\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 0.80\nParams size (MB): 0.04\nEstimated Total Size (MB): 0.84\n----------------------------------------------------------------\n"
]
],
[
[
"# Training and Testing\n\nLooking at logs can be boring, so we'll introduce **tqdm** progressbar to get cooler logs. \n\nLet's write train and test functions",
"_____no_output_____"
]
],
[
[
"from tqdm import tqdm\n\ntrain_losses = []\ntest_losses = []\ntrain_acc = []\ntest_acc = []\n\ndef train(model, device, train_loader, optimizer, epoch):\n model.train()\n pbar = tqdm(train_loader)\n correct = 0\n processed = 0\n for batch_idx, (data, target) in enumerate(pbar):\n # get samples\n data, target = data.to(device), target.to(device)\n\n # Init\n optimizer.zero_grad()\n # In PyTorch, we need to set the gradients to zero before starting to do backpropragation because PyTorch accumulates the gradients on subsequent backward passes. \n # Because of this, when you start your training loop, ideally you should zero out the gradients so that you do the parameter update correctly.\n\n # Predict\n y_pred = model(data)\n\n # Calculate loss\n loss = F.nll_loss(y_pred, target)\n train_losses.append(loss)\n\n # Backpropagation\n loss.backward()\n optimizer.step()\n\n # Update pbar-tqdm\n \n pred = y_pred.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n processed += len(data)\n\n pbar.set_description(desc= f'Loss={loss.item()} Batch_id={batch_idx} Accuracy={100*correct/processed:0.2f}')\n train_acc.append(100*correct/processed)\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n test_losses.append(test_loss)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n \n test_acc.append(100. * correct / len(test_loader.dataset))",
"_____no_output_____"
]
],
[
[
"# Let's Train and test our model",
"_____no_output_____"
]
],
[
[
"model = Net().to(device)\noptimizer = optim.SGD(model.parameters(), lr=0.0335, momentum=0.9)\nEPOCHS = 15\nfor epoch in range(EPOCHS):\n print(\"EPOCH:\", epoch)\n train(model, device, train_loader, optimizer, epoch)\n test(model, device, test_loader)",
"\r 0%| | 0/469 [00:00<?, ?it/s]"
],
[
"import matplotlib.pyplot as plt\n \nfig, axs = plt.subplots(2,2,figsize=(15,10))\naxs[0, 0].plot(train_losses)\naxs[0, 0].set_title(\"Training Loss\")\naxs[1, 0].plot(train_acc)\naxs[1, 0].set_title(\"Training Accuracy\")\naxs[0, 1].plot(test_losses)\naxs[0, 1].set_title(\"Test Loss\")\naxs[1, 1].plot(test_acc)\naxs[1, 1].set_title(\"Test Accuracy\")",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb4871f2470d9c038507f348f929380ce134ee8b | 153,805 | ipynb | Jupyter Notebook | Matplotlib/examples.ipynb | SaintXoXo/python-cheat-sheet | 949f9a0587882bcb95ad48234b75cf2dafb55d9b | [
"MIT"
] | 15 | 2019-03-21T14:49:23.000Z | 2022-03-27T09:10:39.000Z | Matplotlib/examples.ipynb | SaintXoXo/python-cheat-sheet | 949f9a0587882bcb95ad48234b75cf2dafb55d9b | [
"MIT"
] | null | null | null | Matplotlib/examples.ipynb | SaintXoXo/python-cheat-sheet | 949f9a0587882bcb95ad48234b75cf2dafb55d9b | [
"MIT"
] | 10 | 2019-03-21T14:07:54.000Z | 2021-08-04T08:18:18.000Z | 456.394659 | 42,492 | 0.929404 | [
[
[
"import matplotlib.pyplot as plt\n\nx = [1, 2.1, 0.4, 8.9, 7.1, 0.1, 3, 5.1, 6.1, 3.4, 2.9, 9]\ny = [1, 3.4, 0.7, 1.3, 9, 0.4, 4, 1.9, 9, 0.3, 4.0, 2.9]\nplt.scatter(x,y, color='red')\n\nw = [0.1, 0.2, 0.4, 0.8, 1.6, 2.1, 2.5, 4, 6.5, 8, 10]\nz = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nplt.plot(z, w, color='lightblue', linewidth=2)\n\nc = [0,1,2,3,4, 5, 6, 7, 8, 9, 10]\nplt.plot(c)\n\nplt.ylabel('some numbers')\nplt.xlabel('some more numbers')\n\nplt.savefig('plot.png')\nplt.show()\n",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.random.rand(10)\ny = np.random.rand(10)\n\nplt.plot(x,y,'--', x**2, y**2,'-.')\nplt.savefig('lines.png')\nplt.axis('equal')\nplt.show()",
"_____no_output_____"
],
[
"\"\"\"\nDemo of custom tick-labels with user-defined rotation.\n\"\"\"\nimport matplotlib.pyplot as plt\n\n\nx = [1, 2, 3, 4]\ny = [1, 4, 9, 6]\nlabels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']\n\nplt.plot(x, y, 'ro')\n# You can specify a rotation for the tick labels in degrees or with keywords.\nplt.xticks(x, labels, rotation='vertical')\n# Pad margins so that markers don't get clipped by the axes\nplt.margins(0.2)\nplt.savefig('ticks.png')\nplt.show()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nx = [0.5, 0.6, 0.8, 1.2, 2.0, 3.0]\ny = [10, 15, 20, 25, 30, 35]\nz = [1, 2, 3, 4]\nw = [10, 20, 30, 40]\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, y, color='lightblue', linewidth=3)\nax.scatter([2,3.4,4, 5.5],\n [5,10,12, 15],\n color='black',\n marker='^')\nax.set_xlim(0, 6.5)\n\nax2 = fig.add_subplot(222)\nax2.plot(z, w, color='lightgreen', linewidth=3)\nax2.scatter([3,5,7],\n [5,15,25],\n color='red',\n marker='*')\nax2.set_xlim(1, 7.5)\n\nplt.savefig('mediumplot.png')\nplt.show()",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# First way: the top plot, all in one #\n\nx = np.random.rand(10)\ny = np.random.rand(10)\n\nfigure1 = plt.plot(x,y)\n\n# Second way: the lower 4 plots#\n\nx1 = np.random.rand(10)\nx2 = np.random.rand(10)\nx3 = np.random.rand(10)\nx4 = np.random.rand(10)\ny1 = np.random.rand(10)\ny2 = np.random.rand(10)\ny3 = np.random.rand(10)\ny4 = np.random.rand(10)\n\nfigure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)\nax1.plot(x1,y1)\nax2.plot(x2,y2)\nax3.plot(x3,y3)\nax4.plot(x4,y4)\n\nplt.savefig('axes.png')\nplt.show()",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(0, 1, 500)\ny = np.sin(4 * np.pi * x) * np.exp(-5 * x)\n\nfig, ax = plt.subplots()\n\nax.fill(x, y, color='lightblue')\n#ax.grid(True, zorder=5)\nplt.savefig('fill.png')\nplt.show()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nnp.random.seed(0)\n\nx, y = np.random.randn(2, 100)\nfig = plt.figure()\nax1 = fig.add_subplot(211)\nax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)\n#ax1.grid(True)\nax1.axhline(0, color='black', lw=2)\n\nax2 = fig.add_subplot(212, sharex=ax1)\nax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)\n#ax2.grid(True)\nax2.axhline(0, color='black', lw=2)\n\nplt.savefig('advanced.png')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb48757f3f3d6be7dc220b4ce74b3bbedd94a8f6 | 7,690 | ipynb | Jupyter Notebook | PythonAPI/pycocoEvalDemo.ipynb | zgebler/cocoapi | f894b6c18ffb18740707bd65222ee2900ae31904 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | PythonAPI/pycocoEvalDemo.ipynb | zgebler/cocoapi | f894b6c18ffb18740707bd65222ee2900ae31904 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | PythonAPI/pycocoEvalDemo.ipynb | zgebler/cocoapi | f894b6c18ffb18740707bd65222ee2900ae31904 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | 48.36478 | 1,337 | 0.614824 | [
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nimport numpy as np\nimport skimage.io as io\nimport pylab\npylab.rcParams['figure.figsize'] = (10.0, 8.0)",
"_____no_output_____"
],
[
"annType = ['segm','bbox','keypoints']\nannType = annType[1] #specify type here\nprefix = 'person_keypoints' if annType=='keypoints' else 'instances'\nprint 'Running demo for *%s* results.'%(annType)",
"Running demo for *bbox* results.\n"
],
[
"#initialize COCO ground truth api\ndataDir='../'\ndataType='val2014'\nannFile = '%s/annotations/%s_%s.json'%(dataDir,prefix,dataType)\ncocoGt=COCO(annFile)",
"loading annotations into memory...\nDone (t=8.01s)\ncreating index...\nindex created!\n"
],
[
"#initialize COCO detections api\nresFile='%s/results/%s_%s_fake%s100_results.json'\nresFile = resFile%(dataDir, prefix, dataType, annType)\ncocoDt=cocoGt.loadRes(resFile)",
"Loading and preparing results... \nDONE (t=0.05s)\ncreating index...\nindex created!\n"
],
[
"imgIds=sorted(cocoGt.getImgIds())\nimgIds=imgIds[0:100]\nimgId = imgIds[np.random.randint(100)]",
"_____no_output_____"
],
[
"# running evaluation\ncocoEval = COCOeval(cocoGt,cocoDt,annType)\ncocoEval.params.imgIds = imgIds\ncocoEval.evaluate()\ncocoEval.accumulate()\ncocoEval.summarize()",
"Running per image evaluation... \nDONE (t=0.46s).\nAccumulating evaluation results... \nDONE (t=0.38s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.505\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.697\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.573\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.586\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.519\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.501\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.387\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.594\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.595\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.640\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.566\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.564\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb488399bf85e8319f869a0e4e16765a255e577d | 27,082 | ipynb | Jupyter Notebook | code/evo_tune_201023/LSTM5_evotune_mini.ipynb | steveyu323/motor_embedding | 65b05e024ca5a0aa339330eff6b63927af5ce4aa | [
"MIT"
] | null | null | null | code/evo_tune_201023/LSTM5_evotune_mini.ipynb | steveyu323/motor_embedding | 65b05e024ca5a0aa339330eff6b63927af5ce4aa | [
"MIT"
] | null | null | null | code/evo_tune_201023/LSTM5_evotune_mini.ipynb | steveyu323/motor_embedding | 65b05e024ca5a0aa339330eff6b63927af5ce4aa | [
"MIT"
] | null | null | null | 30.810011 | 112 | 0.490806 | [
[
[
"import torch\nimport torch.nn as nn \nimport torch.optim as optim \n\nimport torchvision \nimport torchvision.transforms as transforms \nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import Dataset, IterableDataset, DataLoader\n# import tqdm\nimport numpy as np\nimport pandas as pd\n\nimport math\n\nseed = 7\ntorch.manual_seed(seed)\nnp.random.seed(seed)\n",
"_____no_output_____"
],
[
"pfamA_motors = pd.read_csv(\"../../data/pfamA_motors.csv\")\ndf_dev = pd.read_csv(\"../../data/df_dev.csv\")\nmotor_toolkit = pd.read_csv(\"../../data/motor_tookits.csv\")",
"_____no_output_____"
],
[
"pfamA_motors_balanced = pfamA_motors.groupby('clan').apply(lambda _df: _df.sample(4500,random_state=1))\npfamA_motors_balanced = pfamA_motors_balanced.apply(lambda x: x.reset_index(drop = True))",
"_____no_output_____"
],
[
"pfamA_motors_balanced.to_csv(\"../../data/pfamA_motors_balanced.csv\",index = False)",
"_____no_output_____"
],
[
"pfamA_target_name = [\"PF00349\",\"PF00022\",\"PF03727\",\"PF06723\",\\\n \"PF14450\",\"PF03953\",\"PF12327\",\"PF00091\",\"PF10644\",\\\n \"PF13809\",\"PF14881\",\"PF00063\",\"PF00225\",\"PF03028\"]\n\npfamA_target = pfamA_motors.loc[pfamA_motors[\"pfamA_acc\"].isin(pfamA_target_name),:]",
"_____no_output_____"
],
[
"# shuffle pfamA_target and pfamA_motors_balanced\npfamA_target = pfamA_target.sample(frac = 1)\npfamA_target_ind = pfamA_target.iloc[:,0]\nprint(pfamA_target_ind[0:5])\nprint(pfamA_motors_balanced.shape)\n\npfamA_motors_balanced = pfamA_motors_balanced.sample(frac = 1) \npfamA_motors_balanced_ind = pfamA_motors_balanced.iloc[:,0]\nprint(pfamA_motors_balanced_ind[0:5])\nprint(pfamA_target.shape)",
"179519 179519\n1414859 1414859\n12920 12920\n1415258 1415258\n13385 13385\nName: Unnamed: 0, dtype: int64\n(18000, 6)\n13493 180756\n1539 166414\n2688 131988\n1691 37094\n188 130155\nName: Unnamed: 0, dtype: int64\n(59149, 6)\n"
],
[
"pfamA_motors_balanced.head()",
"_____no_output_____"
],
[
"pfamA_target.head()",
"_____no_output_____"
],
[
"aminoacid_list = [\n 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L',\n 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'\n]\nclan_list = [\"actin_like\",\"tubulin_c\",\"tubulin_binding\",\"p_loop_gtpase\"]\n \naa_to_ix = dict(zip(aminoacid_list, np.arange(1, 21)))\nclan_to_ix = dict(zip(clan_list, np.arange(0, 4)))\n\ndef word_to_index(seq,to_ix):\n \"Returns a list of indices (integers) from a list of words.\"\n return [to_ix.get(word, 0) for word in seq]\n\nix_to_aa = dict(zip(np.arange(1, 21), aminoacid_list))\nix_to_clan = dict(zip(np.arange(0, 4), clan_list))\n\ndef index_to_word(ixs,ix_to): \n \"Returns a list of words, given a list of their corresponding indices.\"\n return [ix_to.get(ix, 'X') for ix in ixs]\n\ndef prepare_sequence(seq):\n idxs = word_to_index(seq[0:-1],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\ndef prepare_labels(seq):\n idxs = word_to_index(seq[1:],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\ndef prepare_eval(seq):\n idxs = word_to_index(seq[:],aa_to_ix)\n return torch.tensor(idxs, dtype=torch.long)\n\nprepare_labels('YCHXXXXX')",
"_____no_output_____"
],
[
"# set device\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndevice",
"_____no_output_____"
],
[
"# Hyperparameters\ninput_size = len(aminoacid_list) + 1\nnum_layers = 1\nhidden_size = 128\noutput_size = len(aminoacid_list) + 1\nembedding_size= 10\nlearning_rate = 0.001\n\n# Create Bidirectional LSTM\nclass BRNN(nn.Module):\n def __init__(self,input_size, embedding_size, hidden_size, num_layers, output_size):\n super(BRNN,self).__init__()\n self.embedding_size = embedding_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.num_layers = num_layers\n self.log_softmax = nn.LogSoftmax(dim= 1)\n self.aa_embedding = nn.Embedding(input_size, embedding_size)\n self.lstm = nn.LSTM(input_size = embedding_size, \n hidden_size = hidden_size,\n num_layers = num_layers, \n bidirectional = True)\n #hidden_state: a forward and a backward state for each layer of LSTM\n self.fc = nn.Linear(hidden_size*2, output_size)\n \n def aa_encoder(self, input): \n \"Helper function to map single aminoacids to the embedding space.\"\n projected = self.embedding(input)\n return projected \n \n\n def forward(self,seq):\n # embed each aa to the embedded space\n embedding_tensor = self.aa_embedding(seq)\n\n # initialization could be neglected as the default is 0 for h0 and c0\n # initialize hidden state\n # h0 = torch.zeros(self.num_layers*2,x.size(0),self.hidden_size).to(device)\n # initialize cell_state\n # c0 = torch.zeros(self.num_layers*2,x.size(0),self.hidden_size).to(device)\n\n # shape(seq_len = len(sequence), batch_size = 1, input_size = -1)\n # (5aa,1 sequence per batch, 10-dimension embedded vector)\n\n #output of shape (seq_len, batch, num_directions * hidden_size):\n out, (hn, cn) = self.lstm(embedding_tensor.view(len(seq), 1, -1))\n # decoded_space = self.fc(out.view(len(seq), -1))\n decoded_space = self.fc(out.view(len(seq), -1))\n decoded_scores = F.log_softmax(decoded_space, dim=1)\n return decoded_scores, hn\n",
"_____no_output_____"
],
[
"# initialize network\nmodel = BRNN(input_size, embedding_size, hidden_size, num_layers, output_size).to(device)",
"_____no_output_____"
],
[
"# model.load_state_dict(torch.load(\"../../data/bidirectional_lstm_5_201008.pt\"))",
"_____no_output_____"
],
[
"loss_function = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr = learning_rate)",
"_____no_output_____"
],
[
"model.train()",
"_____no_output_____"
]
],
[
[
"## Proceed weight updates using motor_balanced",
"_____no_output_____"
]
],
[
[
"#Train Network\n\n# loss_vector = []\nrunning_loss = 0\nprint_every = 1000\n\nfor epoch in np.arange(0, pfamA_motors_balanced.shape[0]): \n seq = pfamA_motors_balanced.iloc[epoch, 3]\n # Step 1. Remember that Pytorch accumulates gradients.\n # We need to clear them out before each instance\n \n # Step 2. Get our inputs ready for the network, that is, turn them into\n # Tensors of word indices.\n sentence_in = prepare_sequence(seq)\n targets = prepare_labels(seq)\n \n sentence_in = sentence_in.to(device = device)\n targets = targets.to(device = device)\n \n # Step 3. Run our forward pass.\n model.zero_grad()\n aa_scores, hn = model(sentence_in)\n\n # Step 4. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n\n loss = loss_function(aa_scores, targets)\n loss.backward()\n optimizer.step()\n\n if epoch % print_every == 0:\n print(f\"At Epoch: %.2f\"% epoch)\n print(f\"Loss %.2f\"% loss)\n # Print current loss \n# loss_vector.append(loss) ",
"At Epoch: 0.00\nLoss 0.02\nAt Epoch: 1000.00\nLoss 0.00\nAt Epoch: 2000.00\nLoss 0.01\nAt Epoch: 3000.00\nLoss 0.03\nAt Epoch: 4000.00\nLoss 0.00\nAt Epoch: 5000.00\nLoss 0.01\nAt Epoch: 6000.00\nLoss 0.01\nAt Epoch: 7000.00\nLoss 0.01\nAt Epoch: 8000.00\nLoss 0.02\nAt Epoch: 9000.00\nLoss 0.00\nAt Epoch: 10000.00\nLoss 0.04\nAt Epoch: 11000.00\nLoss 0.00\nAt Epoch: 12000.00\nLoss 0.00\nAt Epoch: 13000.00\nLoss 0.00\nAt Epoch: 14000.00\nLoss 0.01\nAt Epoch: 15000.00\nLoss 0.03\nAt Epoch: 16000.00\nLoss 0.02\nAt Epoch: 17000.00\nLoss 0.00\n"
],
[
"torch.save(model.state_dict(), \"../../data/mini_lstm_5_balanced.pt\")",
"_____no_output_____"
]
],
[
[
"## Proceed weight updates using the entire pfam_motor set",
"_____no_output_____"
]
],
[
[
"#Train Network\n\n# loss_vector = []\nrunning_loss = 0\nprint_every = 1000\n\nfor epoch in np.arange(0, pfamA_target.shape[0]): \n seq = pfamA_target.iloc[epoch, 3]\n # Step 1. Remember that Pytorch accumulates gradients.\n # We need to clear them out before each instance\n \n # Step 2. Get our inputs ready for the network, that is, turn them into\n # Tensors of word indices.\n sentence_in = prepare_sequence(seq)\n targets = prepare_labels(seq)\n \n sentence_in = sentence_in.to(device = device)\n targets = targets.to(device = device)\n \n # Step 3. Run our forward pass.\n model.zero_grad()\n aa_scores, hn = model(sentence_in)\n\n # Step 4. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n\n loss = loss_function(aa_scores, targets)\n loss.backward()\n optimizer.step()\n\n if epoch % print_every == 0:\n print(f\"At Epoch: %.2f\"% epoch)\n print(f\"Loss %.2f\"% loss)\n # Print current loss \n# loss_vector.append(loss) ",
"At Epoch: 0.00\nLoss 0.00\nAt Epoch: 1000.00\nLoss 0.00\nAt Epoch: 2000.00\nLoss 0.02\nAt Epoch: 3000.00\nLoss 0.01\nAt Epoch: 4000.00\nLoss 0.00\nAt Epoch: 5000.00\nLoss 0.01\nAt Epoch: 6000.00\nLoss 0.00\nAt Epoch: 7000.00\nLoss 0.01\nAt Epoch: 8000.00\nLoss 0.01\nAt Epoch: 9000.00\nLoss 0.00\nAt Epoch: 10000.00\nLoss 0.01\nAt Epoch: 11000.00\nLoss 0.00\nAt Epoch: 12000.00\nLoss 0.02\nAt Epoch: 13000.00\nLoss 0.00\nAt Epoch: 14000.00\nLoss 0.04\nAt Epoch: 15000.00\nLoss 0.03\nAt Epoch: 16000.00\nLoss 0.10\nAt Epoch: 17000.00\nLoss 0.03\nAt Epoch: 18000.00\nLoss 0.00\nAt Epoch: 19000.00\nLoss 0.00\nAt Epoch: 20000.00\nLoss 0.00\nAt Epoch: 21000.00\nLoss 0.02\nAt Epoch: 22000.00\nLoss 0.02\nAt Epoch: 23000.00\nLoss 0.00\nAt Epoch: 24000.00\nLoss 0.01\nAt Epoch: 25000.00\nLoss 0.00\nAt Epoch: 26000.00\nLoss 0.01\nAt Epoch: 27000.00\nLoss 0.01\nAt Epoch: 28000.00\nLoss 0.00\nAt Epoch: 29000.00\nLoss 0.00\nAt Epoch: 30000.00\nLoss 0.01\nAt Epoch: 31000.00\nLoss 0.00\nAt Epoch: 32000.00\nLoss 0.00\nAt Epoch: 33000.00\nLoss 0.02\nAt Epoch: 34000.00\nLoss 0.01\nAt Epoch: 35000.00\nLoss 0.02\nAt Epoch: 36000.00\nLoss 0.00\nAt Epoch: 37000.00\nLoss 0.02\nAt Epoch: 38000.00\nLoss 0.00\nAt Epoch: 39000.00\nLoss 0.00\nAt Epoch: 40000.00\nLoss 0.02\nAt Epoch: 41000.00\nLoss 0.00\nAt Epoch: 42000.00\nLoss 0.00\nAt Epoch: 43000.00\nLoss 0.00\nAt Epoch: 44000.00\nLoss 0.01\nAt Epoch: 45000.00\nLoss 0.00\nAt Epoch: 46000.00\nLoss 0.01\nAt Epoch: 47000.00\nLoss 0.01\nAt Epoch: 48000.00\nLoss 0.01\nAt Epoch: 49000.00\nLoss 0.01\nAt Epoch: 50000.00\nLoss 0.01\nAt Epoch: 51000.00\nLoss 0.00\nAt Epoch: 52000.00\nLoss 0.00\nAt Epoch: 53000.00\nLoss 0.00\nAt Epoch: 54000.00\nLoss 0.00\nAt Epoch: 55000.00\nLoss 0.00\nAt Epoch: 56000.00\nLoss 0.03\nAt Epoch: 57000.00\nLoss 0.01\nAt Epoch: 58000.00\nLoss 0.00\nAt Epoch: 59000.00\nLoss 0.00\n"
],
[
"torch.save(model.state_dict(), \"../../data/mini_lstm_5_balanced_target.pt\")",
"_____no_output_____"
],
[
"print(\"done\")",
"done\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb48840a98a357d0123f79013371587da90eb83a | 775,102 | ipynb | Jupyter Notebook | factory/.ipynb_checkpoints/gmvrfit_2d_example-checkpoint.ipynb | llondon6/koalas | bc778ba492027b3d40f9c92ef44da5949d0e43c7 | [
"MIT"
] | 1 | 2019-03-29T03:59:12.000Z | 2019-03-29T03:59:12.000Z | factory/.ipynb_checkpoints/gmvrfit_2d_example-checkpoint.ipynb | llondon6/koalas | bc778ba492027b3d40f9c92ef44da5949d0e43c7 | [
"MIT"
] | 13 | 2018-08-23T11:37:20.000Z | 2021-12-13T15:24:32.000Z | factory/.ipynb_checkpoints/gmvrfit_2d_example-checkpoint.ipynb | llondon6/koalas | bc778ba492027b3d40f9c92ef44da5949d0e43c7 | [
"MIT"
] | 3 | 2018-08-29T06:36:58.000Z | 2021-11-21T16:06:22.000Z | 2,123.567123 | 358,416 | 0.948203 | [
[
[
"# GMVRFIT 2D Example\n<center>Development for a fitting function (greedy+linear based on mvpolyfit and gmvpfit) that handles rational fucntions</center>",
"_____no_output_____"
]
],
[
[
"# Low-level import \nfrom numpy import *\nfrom numpy.linalg import pinv,lstsq\n# Setup ipython environment\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n# Setup plotting backend\nimport matplotlib as mpl\nmpl.rcParams['lines.linewidth'] = 0.8\nmpl.rcParams['font.family'] = 'serif'\nmpl.rcParams['font.size'] = 12\nmpl.rcParams['axes.labelsize'] = 20\nmpl.rcParams['axes.titlesize'] = 20\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.pyplot import *\n#\nfrom positive import *",
"_____no_output_____"
]
],
[
[
"## Package Development (positive/learning.py)",
"_____no_output_____"
],
[
"### Setup test data",
"_____no_output_____"
]
],
[
[
"################################################################################\nh = 3\nQ = 25\nx = h*linspace(-1,1,Q) \ny = h*linspace(-1,1,Q) \nX,Y = meshgrid(x,y)\n# X += np.random.random( X.shape )-0.5\n# Y += np.random.random( X.shape )-0.5\n\nzfun = lambda xx,yy: 50 + (1.0 + xx*yy ) / ( 0.8 + xx**2 + yy**2 )\nnumerator_symbols, denominator_symbols = ['01'], ['00','11'] \n\nnp.random.seed(42)\nns = 0.1*(np.random.random( X.shape )-0.5)\nZ = zfun(X,Y) + ns\ndomain,scalar_range = ndflatten( [X,Y], Z )\n################################################################################",
"_____no_output_____"
]
],
[
[
"### Initiate class object for fitting",
"_____no_output_____"
]
],
[
[
"foo = mvrfit( domain, scalar_range, numerator_symbols, denominator_symbols, verbose=True )",
"_____no_output_____"
]
],
[
[
"### Plot using class method",
"_____no_output_____"
]
],
[
[
"foo.plot()",
"/Library/Python/2.7/site-packages/matplotlib/lines.py:1106: UnicodeWarning: Unicode unequal comparison failed to convert both arguments to Unicode - interpreting them as being unequal\n if self._markerfacecolor != fc:\n"
]
],
[
[
"### Generate python string for fit model",
"_____no_output_____"
]
],
[
[
"print foo.__str_python__(precision=8)",
"f = lambda x0,x1: 5.02241109e+01 + 3.85252449e-01 * ( -6.88184091e-01*(x0*x0) + 3.08902945e+00*(x0*x1) + -7.15211199e-01*(x1*x1) + 2.59342646e+00 ) / ( 1.0 + 1.17625631e+00*(x0*x0) + 1.17841567e+00*(x1*x1) )\n"
]
],
[
[
"### Use greedy algorithm",
"_____no_output_____"
]
],
[
[
"star = gmvrfit( domain, scalar_range, verbose=True )",
"(\u001b[0;36mgmvrfit\u001b[0m)>> Now working deg = 1\n&& The estimator has changed by -inf\n&& Degree tempering will continue.\nFalse\n&& The current boundary is [('1', True)]\n&& The current estimator value is 0.999998\n\n(\u001b[0;36mgmvrfit\u001b[0m)>> Now working deg = 2\n&& The estimator has changed by -0.922429\n&& Degree tempering will continue.\nFalse\n&& The current boundary is [('01', True), ('11', True), ('00', False), ('11', False), ('00', True)]\n&& The current estimator value is 0.077569\n\n(\u001b[0;36mgmvrfit\u001b[0m)>> Now working deg = 3\n&& The estimator has changed by 0.000000\n&& Degree tempering will continue.\nFalse\n&& The current boundary is [('01', True), ('11', True), ('00', False), ('11', False), ('00', True)]\n&& The current estimator value is 0.077569\n\n(\u001b[0;36mgmvrfit\u001b[0m)>> Now working deg = 4\n&& The estimator has changed by 0.000000\n&& Degree tempering has completed becuase the estimator hasnt changes since the last degree value. The results of the last iteration wil be kept.\nTrue\n&& The Final boundary is [('01', True), ('11', True), ('00', False), ('11', False), ('00', True)]\n&& The Final estimator value is 0.077569\n\n\n========================================\n# Degree Tempered Positive Greedy Solution:\n========================================\nf = lambda x0,x1: 5.02241109e+01 + 3.85252449e-01 * ( -6.88184091e-01*(x0*x0) + 3.08902945e+00*(x0*x1) + -7.15211199e-01*(x1*x1) + 2.59342646e+00 ) / ( 1.0 + 1.17625631e+00*(x0*x0) + 1.17841567e+00*(x1*x1) )\n\n############################################\n# Applying a Negative Greedy Algorithm\n############################################\n\n\nIteration #1 (Negative Greedy)\n------------------------------------\n>> min_estimator = 2.6900e-01\n>> The current boundary = [('01', True), ('11', True), ('00', False), ('11', False), ('00', True)]\n>> Exiting because |min_est-initial_estimator_value| = |0.269004-0.077569| = |0.191434| > 0.189520.\n>> NOTE that the result of the previous iteration will be kept.\n\n========================================\n# Negative Greedy Solution:\n========================================\nf = lambda x0,x1: 5.02241109e+01 + 3.85252449e-01 * ( -6.88184091e-01*(x0*x0) + 3.08902945e+00*(x0*x1) + -7.15211199e-01*(x1*x1) + 2.59342646e+00 ) / ( 1.0 + 1.17625631e+00*(x0*x0) + 1.17841567e+00*(x1*x1) )\n\nFit Information:\n----------------------------------------\nf = lambda x0,x1: 5.02241109e+01 + 3.85252449e-01 * ( -6.88184091e-01*(x0*x0) + 3.08902945e+00*(x0*x1) + -7.15211199e-01*(x1*x1) + 2.59342646e+00 ) / ( 1.0 + 1.17625631e+00*(x0*x0) + 1.17841567e+00*(x1*x1) )\n"
],
[
"star.plot()\nstar.bin['pgreedy_result'].plot()\nstar.bin['ngreedy_result'].plot()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48a0d34b0c828bd462afc4d30ba34d5c1dfb54 | 23,357 | ipynb | Jupyter Notebook | Sorting_Algorithm_Visualizer.ipynb | shadab4150/Sorting-Algorithm-Visualizer | b3ba3875ea203e3aac9dd0e6a6b02d55db3b1301 | [
"MIT"
] | null | null | null | Sorting_Algorithm_Visualizer.ipynb | shadab4150/Sorting-Algorithm-Visualizer | b3ba3875ea203e3aac9dd0e6a6b02d55db3b1301 | [
"MIT"
] | null | null | null | Sorting_Algorithm_Visualizer.ipynb | shadab4150/Sorting-Algorithm-Visualizer | b3ba3875ea203e3aac9dd0e6a6b02d55db3b1301 | [
"MIT"
] | null | null | null | 51.789357 | 12,200 | 0.716573 | [
[
[
"<center><h1> Sorting Algorithms Visualizer.</h1></center>\n<center><h3>Made Using Matplotlib Animation.</h3></center>\n<ceter><img src='https://miro.medium.com/max/1400/0*qwkWXc-wzW2D8ggV.jpg'></center>",
"_____no_output_____"
],
[
"### Sorting Algorithms \n* Quick Sort\n* Merge Sort\n* Insertion Sort\n* Selection Sort\n* Bubble Sort",
"_____no_output_____"
],
[
"# Importing Libraries to be used.",
"_____no_output_____"
]
],
[
[
"import random\nimport time\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.animation as animation",
"_____no_output_____"
],
[
"sns.set_style('darkgrid')",
"_____no_output_____"
]
],
[
[
"### Helper function to swap elements i and j of list.",
"_____no_output_____"
]
],
[
[
"def swap(A, i, j):\n \"\"\"Helper function to swap elements i and j of list.\"\"\"\n\n if i != j:\n A[i], A[j] = A[j], A[i]",
"_____no_output_____"
]
],
[
[
"# Bubble Sort Algorithm",
"_____no_output_____"
]
],
[
[
"def bubblesort(A):\n \"\"\"In-place bubble sort.\"\"\"\n\n if len(A) == 1:\n return\n\n swapped = True\n for i in range(len(A) - 1):\n if not swapped:\n break\n swapped = False\n for j in range(len(A) - 1 - i):\n if A[j] > A[j + 1]:\n swap(A, j, j + 1)\n swapped = True\n yield A",
"_____no_output_____"
]
],
[
[
"# Insertion sort Algorithm",
"_____no_output_____"
]
],
[
[
"def insertionsort(A):\n \"\"\"In-place insertion sort.\"\"\"\n\n for i in range(1, len(A)):\n j = i\n while j > 0 and A[j] < A[j - 1]:\n swap(A, j, j - 1)\n j -= 1\n yield A",
"_____no_output_____"
]
],
[
[
"# Merge sort Algorithm",
"_____no_output_____"
]
],
[
[
"\ndef mergesort(A, start, end):\n \"\"\"Merge sort.\"\"\"\n\n if end <= start:\n return\n\n mid = start + ((end - start + 1) // 2) - 1\n yield from mergesort(A, start, mid)\n yield from mergesort(A, mid + 1, end)\n yield from merge(A, start, mid, end)\n yield A",
"_____no_output_____"
]
],
[
[
"# Algorithm to merge sublists",
"_____no_output_____"
]
],
[
[
"def merge(A, start, mid, end):\n \"\"\"Helper function for merge sort.\"\"\"\n \n merged = []\n leftIdx = start\n rightIdx = mid + 1\n\n while leftIdx <= mid and rightIdx <= end:\n if A[leftIdx] < A[rightIdx]:\n merged.append(A[leftIdx])\n leftIdx += 1\n else:\n merged.append(A[rightIdx])\n rightIdx += 1\n\n while leftIdx <= mid:\n merged.append(A[leftIdx])\n leftIdx += 1\n\n while rightIdx <= end:\n merged.append(A[rightIdx])\n rightIdx += 1\n\n for i, sorted_val in enumerate(merged):\n A[start + i] = sorted_val\n yield A",
"_____no_output_____"
]
],
[
[
"# Quick Sort Algorithm",
"_____no_output_____"
]
],
[
[
"\ndef quicksort(A, start, end):\n \"\"\"In-place quicksort.\"\"\"\n\n if start >= end:\n return\n\n pivot = A[end]\n pivotIdx = start\n\n for i in range(start, end):\n if A[i] < pivot:\n swap(A, i, pivotIdx)\n pivotIdx += 1\n yield A\n swap(A, end, pivotIdx)\n yield A\n\n yield from quicksort(A, start, pivotIdx - 1)\n yield from quicksort(A, pivotIdx + 1, end)",
"_____no_output_____"
]
],
[
[
"# Selection Sort Algorithm",
"_____no_output_____"
]
],
[
[
"def selectionsort(A):\n \"\"\"In-place selection sort.\"\"\"\n if len(A) == 1:\n return\n\n for i in range(len(A)):\n # Find minimum unsorted value.\n minVal = A[i]\n minIdx = i\n for j in range(i, len(A)):\n if A[j] < minVal:\n minVal = A[j]\n minIdx = j\n yield A\n swap(A, i, minIdx)\n yield A",
"_____no_output_____"
]
],
[
[
"# Function to give a new color each time",
"_____no_output_____"
]
],
[
[
"def colors(N):\n if N%5==0:\n colors='skyblue'\n elif N%5==1:\n colors='green'\n elif N%5==2:\n colors='orange'\n elif N%5==3:\n colors='red'\n elif N%5==4:\n colors='pink'\n return colors",
"_____no_output_____"
]
],
[
[
"# Main function for Image Animation and plotting",
"_____no_output_____"
]
],
[
[
"\nif __name__ == \"__main__\":\n \n # Get user input to determine range of integers (1 to N) and desired\n \n # sorting method (algorithm).\n \n N = int(input(\"Enter number of integers: \"))\n #A=list(map(int,input(\"Enter the Integers :\").split()))\n method_msg = \"Enter sorting method:\\n(b)ubble\\n(i)nsertion\\n(m)erge \\\n \\n(q)uick\\n(s)election\\n\"\n method = input(method_msg)\n\n # Build and randomly shuffle list of integers.\n \n A = [x + 1 for x in range(20,N+20)]\n random.seed(time.time())\n random.shuffle(A)\n yl1=min(A)\n yl2=max(A)\n\n # Get appropriate generator to supply to matplotlib FuncAnimation method.\n \n if method == \"b\":\n title = \"Bubble sort\"\n generator = bubblesort(A)\n elif method == \"i\":\n title = \"Insertion sort\"\n generator = insertionsort(A)\n elif method == \"m\":\n title = \"Merge sort\"\n generator = mergesort(A, 0, N - 1)\n elif method == \"q\":\n title = \"Quick sort\"\n generator = quicksort(A, 0, N - 1)\n else:\n title = \"Selection sort\"\n generator = selectionsort(A)\n \n fig, ax = plt.subplots()\n ax.set_title(title)\n\n # Initializing a bar plot.\n \n bar_rects = ax.bar(range(len(A)), A, align=\"edge\",color=colors(N))\n\n # Set axis limits. Set y axis upper limit high enough that the tops of\n # the bars won't overlap with the text label.\n \n ax.set_xlim(0,N)\n ax.set_ylim(max(yl1-2,0),yl2+2)\n\n # Place a text label in the upper-left corner of the plot to display\n # number of operations performed. \n \n text = ax.text(0.02, 0.95, \"\", transform=ax.transAxes)\n\n # Define function update_fig() for use with matplotlib.pyplot.FuncAnimation().\n # To track the number of operations, i.e., iterations\n \n iteration = [0]\n def update_fig(A, rects, iteration):\n for rect, val in zip(rects, A):\n rect.set_height(val)\n iteration[0] += 1\n text.set_text(\"# Number of operations: {}\".format(iteration[0]))\n\n anim = animation.FuncAnimation(fig, func=update_fig,\n fargs=(bar_rects, iteration), frames=generator, interval=2,\n repeat=False)\n plt.show()\n",
"Enter number of integers: 12\nEnter sorting method:\n(b)ubble\n(i)nsertion\n(m)erge \n(q)uick\n(s)election\n b\n"
]
],
[
[
"<center><h1> Below is a Example.</h1></center>",
"_____no_output_____"
],
[
"<center><img src='https://i.ibb.co/LQbCvgN/ezgif-com-crop.gif' width=\"700\"></center>",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb48b5159fbe3943a21d11f8138c7f12b7e396f6 | 84,046 | ipynb | Jupyter Notebook | scrapbook/extract.ipynb | alan-turing-institute/dsg-CityMaaS | 85ef01d1d86daa2c15831e1a88127c2a3f4273b1 | [
"MIT"
] | 2 | 2021-04-21T15:07:53.000Z | 2021-04-22T08:15:43.000Z | scrapbook/extract.ipynb | alan-turing-institute/dsg-CityMaaS | 85ef01d1d86daa2c15831e1a88127c2a3f4273b1 | [
"MIT"
] | null | null | null | scrapbook/extract.ipynb | alan-turing-institute/dsg-CityMaaS | 85ef01d1d86daa2c15831e1a88127c2a3f4273b1 | [
"MIT"
] | 2 | 2021-04-22T12:42:22.000Z | 2021-05-05T22:41:54.000Z | 51.848242 | 15,120 | 0.507686 | [
[
[
"import pandas as pd\nimport sklearn as sk\nimport json\nimport ast\nimport pickle\nimport math\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"df = pd.read_json('/data/accessible_POIs/great-britain-latest.json')",
"_____no_output_____"
],
[
"df.loc[:,'id'] = df['Node'].apply(lambda x: dict(x)['id'])\ndf.loc[:,'access'] = df['Node'].apply(lambda x: dict(x)['tags'].get('access') if 'access' in dict(x)['tags'] else 'NONE')\ndf.loc[:,'barrier'] = df['Node'].apply(lambda x: dict(x)['tags'].get('barrier'))\ndf.loc[:,'bicycle'] = df['Node'].apply(lambda x: dict(x)['tags'].get('bicycle'))\ndf.loc[:,'motor_vehicle'] = df['Node'].apply(lambda x: dict(x)['tags'].get('motor_vehicle'))\ndf.loc[:,'opening_hours'] = df['Node'].apply(lambda x: dict(x)['tags'].get('opening_hours'))\ndf.loc[:,'wheelchair'] = df['Node'].apply(lambda x: dict(x)['tags'].get('wheelchair'))\ndf.loc[:,'amenity'] = df['Node'].apply(lambda x: dict(x)['tags'].get('amenity'))\ndf.loc[:,'lon'] = df['Node'].apply(lambda x: dict(x)['lonlat'][0])\ndf.loc[:,'lat'] = df['Node'].apply(lambda x: dict(x)['lonlat'][1])\n\ndf.drop(['Node','Way','Relation'], axis=1, inplace=True)\ndf",
"_____no_output_____"
],
[
"df.to_pickle('/shared/accessible_pois.pkl')",
"_____no_output_____"
],
[
"from zipfile import ZipFile",
"_____no_output_____"
],
[
"with ZipFile('/data/All_POIs_by_country/pois_by_countries.zip', 'r') as z:\n z.extract('geojson/great-britain-latest.json', '/shared/great-britain-latest.json')\n #z.extract('geojson/great-britain-latest.geojson', '/shared/great-britain-latest.geojson')",
"_____no_output_____"
],
[
"with open('/shared/great-britain-latest.json','r') as j:\n data = json.load(j)\n\ndf = pd.json_normalize(data)\ndf",
"_____no_output_____"
],
[
"with open('/shared/great-britain-latest.json','r') as j:\n data = json.load(j)\n\ndf = pd.json_normalize(data['features'], max_level=3)\ndf",
"_____no_output_____"
],
[
"def extract_key(x,key):\n if type(x) == float:\n return None\n x_ = x.split(',')\n x_ = [y.replace('\\'','').replace('\"','') for y in x_]\n\n for k in x_:\n if key in k:\n return k[k.find('>')+1:]\n return None\n\ndf.loc[:,'shop'] = df['properties.other_tags'].apply(extract_key, args=('shop',))\ndf.loc[:,'amenity'] = df['properties.other_tags'].apply(extract_key, args=('amenity',))\ndf.loc[:,'wheelchair'] = df['properties.other_tags'].apply(extract_key, args=('wheelchair',))\ndf.loc[:,'barrier'] = df['properties.other_tags'].apply(extract_key, args=('barrier',))\ndf.loc[:,'access'] = df['properties.other_tags'].apply(extract_key, args=('access',))",
"_____no_output_____"
],
[
"df.loc[:,'lon'] = df['geometry.coordinates'].apply(lambda x: list(x)[0])\ndf.loc[:,'lat'] = df['geometry.coordinates'].apply(lambda x: list(x)[1])",
"_____no_output_____"
],
[
"df.to_csv('all_pois_wordcloud.csv')",
"_____no_output_____"
],
[
"len(df)\ndf = df[df['wheelchair'].isin(['yes','no','limited','designated'])]\n#df.drop(['geometry.coordinates','type','geometry.type'], axis=1, inplace=True)\ndf.to_csv('accessible_pois_wordcloud.csv')",
"_____no_output_____"
],
[
"set(df['wheelchair'])\nplt.figure(figsize=(30,10))\ndf['wheelchair'].value_counts().plot(kind='bar')\nlen(df)",
"_____no_output_____"
],
[
"_ = df\n_['wheelchair'].value_counts().plot(kind='bar')\n_",
"_____no_output_____"
],
[
"df['properties.other_tags'].to_csv('wordcloud.csv')",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb48b96c10c6abcb3bebc81eff0dbc95bc5a7e33 | 693,486 | ipynb | Jupyter Notebook | source/examples/basics/geocoding/geocoding_geometries_rectangle_japan.ipynb | JetBrains/lets-plot-docs | 73583bce5308d34b341d9f8a7249ccb34a95f504 | [
"MIT"
] | 2 | 2021-06-02T10:24:24.000Z | 2021-11-08T09:50:22.000Z | source/examples/basics/geocoding/geocoding_geometries_rectangle_japan.ipynb | JetBrains/lets-plot-docs | 73583bce5308d34b341d9f8a7249ccb34a95f504 | [
"MIT"
] | 13 | 2021-05-25T19:49:50.000Z | 2022-03-22T12:30:29.000Z | source/examples/basics/geocoding/geocoding_geometries_rectangle_japan.ipynb | JetBrains/lets-plot-docs | 73583bce5308d34b341d9f8a7249ccb34a95f504 | [
"MIT"
] | 4 | 2021-01-19T12:26:21.000Z | 2022-03-19T07:47:52.000Z | 3,611.90625 | 659,442 | 0.768871 | [
[
[
"from lets_plot.geo_data import *\nfrom lets_plot import *\nLetsPlot.setup_html()",
"The geodata is provided by © OpenStreetMap contributors and is made available here under the Open Database License (ODbL).\n"
],
[
"country = 'Japan'\nbbox = geocode_countries(names=country)\ngdf = geocode_states().scope(bbox).inc_res(4).get_boundaries()\n\nggplot() + \\\n geom_rect(data=bbox.get_boundaries(), fill='#95a5a6', size=0) + \\\n geom_map(data=gdf, color='#95a5a6', fill='white') + \\\n theme(axis_title='blank', axis_text='blank', axis_ticks='blank', axis_line='blank') + \\\n ggsize(800, 600) + ggtitle(country) + \\\n theme(panel_grid='blank')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
cb48bfaf433e4281ada03ce34f0483e72ccc7a97 | 101,002 | ipynb | Jupyter Notebook | geo_coord.ipynb | mmmarchetti/Coursera_Capstone | 5aa51972225e6bb5fc7594e71950c5008c345844 | [
"MIT"
] | null | null | null | geo_coord.ipynb | mmmarchetti/Coursera_Capstone | 5aa51972225e6bb5fc7594e71950c5008c345844 | [
"MIT"
] | null | null | null | geo_coord.ipynb | mmmarchetti/Coursera_Capstone | 5aa51972225e6bb5fc7594e71950c5008c345844 | [
"MIT"
] | null | null | null | 88.598246 | 459 | 0.549276 | [
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"### 1- Check the path",
"_____no_output_____"
]
],
[
[
"!ls",
"coursera_capstone.ipynb geo_coord.ipynb neighborhoods_toronto.ipynb\ndatasets\t\t LICENSE\t README.md\n"
]
],
[
[
"### 2- Load and Create a DataFrame",
"_____no_output_____"
],
[
"#### Load the Geospatial Coordinates",
"_____no_output_____"
]
],
[
[
"geo_coordinates = pd.read_csv('datasets/Geospatial_Coordinates.csv')\ngeo_coordinates.rename(columns={'Postal Code':'Postcode'}, inplace=True)\ngeo_coordinates.head()",
"_____no_output_____"
]
],
[
[
"#### Load the Neighbohood",
"_____no_output_____"
]
],
[
[
"neigh = pd.read_csv('datasets/neighbor.csv')\nneigh.head()",
"_____no_output_____"
]
],
[
[
"### 3- Merge the two Dataframes",
"_____no_output_____"
]
],
[
[
"result = pd.merge(neigh, geo_coordinates, on='Postcode')",
"_____no_output_____"
]
],
[
[
"#### Display the final result",
"_____no_output_____"
]
],
[
[
"result.style",
"_____no_output_____"
],
[
"result.to_csv('datasets/final_neighborhoods.csv', index=False)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48bff858804672b53553eb05359cbc024b8b0e | 669,267 | ipynb | Jupyter Notebook | L7126/MSCOCO_Captioning.ipynb | tomkraljevic/gtc-2017-labs | 3892025d940822bc6b1c2ecd2f86e7f2ecaf9352 | [
"Apache-2.0"
] | 5 | 2017-05-12T18:47:08.000Z | 2021-08-20T16:32:14.000Z | L7126/MSCOCO_Captioning.ipynb | tomkraljevic/gtc2017-labs | 3892025d940822bc6b1c2ecd2f86e7f2ecaf9352 | [
"Apache-2.0"
] | null | null | null | L7126/MSCOCO_Captioning.ipynb | tomkraljevic/gtc2017-labs | 3892025d940822bc6b1c2ecd2f86e7f2ecaf9352 | [
"Apache-2.0"
] | null | null | null | 743.63 | 143,634 | 0.934811 | [
[
[
"### Image Captioning\n\nTo perform image captioning we are going to apply an approach similar to the work described in references [1],[2], and [3]. The approach applied here uses a recurrent neural network (RNN) to train a network to generate image captions. The input to the RNN is comprised of a high-level representation of an image and a caption describing it. The Microsoft Common Object in Context (MSCOCO) data set is used for this because it has many images and five captions for each one in most cases. In the previous section, we learned how to create and train a simple RNN. For this part, we will learn how to concatenate a feature vector that represents the images with its corresponding sentence and feed this into an RNN.",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport inspect\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import dtypes\n#import reader\nimport collections\nimport os\nimport re\nimport json\n\nimport matplotlib.pyplot as plt\n\nfrom scipy import ndimage\nfrom scipy import misc\nimport sys\nsys.path.insert(0, '/data/models/slim')\n\nslim=tf.contrib.slim\nfrom nets import vgg\n\nfrom preprocessing import vgg_preprocessing\n\n%matplotlib inline \n!nvidia-smi",
"Wed May 10 21:05:00 2017 \r\n+-----------------------------------------------------------------------------+\r\n| NVIDIA-SMI 367.57 Driver Version: 367.57 |\r\n|-------------------------------+----------------------+----------------------+\r\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\r\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\r\n|===============================+======================+======================|\r\n| 0 Tesla K80 On | 0000:00:1E.0 Off | 0 |\r\n| N/A 43C P8 26W / 149W | 0MiB / 11439MiB | 0% Default |\r\n+-------------------------------+----------------------+----------------------+\r\n \r\n+-----------------------------------------------------------------------------+\r\n| Processes: GPU Memory |\r\n| GPU PID Type Process name Usage |\r\n|=============================================================================|\r\n| No running processes found |\r\n+-----------------------------------------------------------------------------+\r\n"
]
],
[
[
"### MSCOCO Captions \nWe are going to build on our RNN example. First, we will look at the data and evaluate a single image, its captions, and feature vector.",
"_____no_output_____"
]
],
[
[
"TRAIN_IMAGE_PATH='/data/mscoco/train2014/'\n## Read Training files\nwith open(\"/data/mscoco/captions_train2014.json\") as data_file:\n data=json.load(data_file)\n\nimage_feature_vectors={} \ntf.reset_default_graph()\n \none_image=ndimage.imread(TRAIN_IMAGE_PATH+data[\"images\"][0]['file_name'])\n #resize for vgg network\nresize_img=misc.imresize(one_image,[224,224])\nif len(one_image.shape)!= 3: #Check to see if the image is grayscale if True mirror colorband\n resize_img=np.asarray(np.dstack((resize_img, resize_img, resize_img)), dtype=np.uint8)\n\nprocessed_image = vgg_preprocessing.preprocess_image(resize_img, 224, 224, is_training=False)\nprocessed_images = tf.expand_dims(processed_image, 0) \nnetwork,endpts= vgg.vgg_16(processed_images, is_training=False)\n\n \ninit_fn = slim.assign_from_checkpoint_fn(os.path.join('/data/mscoco/vgg_16.ckpt'),slim.get_model_variables('vgg_16'))\nsess = tf.Session()\ninit_fn(sess)\nNETWORK,ENDPTS=sess.run([network,endpts])\nsess.close()\nprint('fc7 array for a single image')\nprint(ENDPTS['vgg_16/fc7'][0][0][0]) ",
"INFO:tensorflow:Restoring parameters from /data/mscoco/vgg_16.ckpt\nfc7 array for a single image\n[ 0.81308055 2.55591011 0.9547044 ..., 1.50954461 0. 0. ]\n"
],
[
"plt.plot(ENDPTS['vgg_16/fc7'][0][0][0])\nplt.xlabel('feature vector index')\nplt.ylabel('amplitude')\nplt.title('fc7 feature vector')\ndata[\"images\"][0]['file_name']",
"_____no_output_____"
]
],
[
[
"How can you look at feature maps from the first convolutional layer? Look here if you need a [hint](#answer1 \"The output from the convolutional layer is in the form of height, width, and number of feature maps. FEATUREMAPID can be any value between 0 and the number of feature maps minus 1.\").",
"_____no_output_____"
]
],
[
[
"print(ENDPTS['vgg_16/conv1/conv1_1'][0].shape)\nFEATUREMAPID=0\nprint('input image and feature map from conv1')\nplt.subplot(1,2,1)\nplt.imshow(resize_img)\nplt.subplot(1,2,2)\nplt.imshow(ENDPTS['vgg_16/conv1/conv1_1'][0][:,:,FEATUREMAPID])",
"(224, 224, 64)\ninput image and feature map from conv1\n"
]
],
[
[
"How can you look at the response of different layers in your network? ",
"_____no_output_____"
],
[
"Next, we are going to combine the feature maps with their respective captions. Many of the images have five captions. Run the code below to view the captions for one image.",
"_____no_output_____"
]
],
[
[
"CaptionsForOneImage=[]\nfor k in range(len(data['annotations'])):\n if data['annotations'][k]['image_id']==data[\"images\"][0]['id']:\n CaptionsForOneImage.append([data['annotations'][k]['caption'].lower()])",
"_____no_output_____"
],
[
"plt.imshow(resize_img)\nprint('MSCOCO captions for a single image')\nCaptionsForOneImage",
"MSCOCO captions for a single image\n"
]
],
[
[
"A file with feature vectors from 2000 of the MSCOCO images has been created. Next, you will load these and train. Please note this step can take more than 5 minutes to run.",
"_____no_output_____"
]
],
[
[
"example_load=np.load('/data/mscoco/train_vgg_16_fc7_2000.npy').tolist()\nimage_ids=example_load.keys()",
"_____no_output_____"
],
[
"#Create 3 lists image_id, feature maps, and captions.\nimage_id_key=[]\nfeature_maps_to_id=[]\ncaption_to_id=[]\nfor observed_image in image_ids: \n for k in range(len(data['annotations'])):\n if data['annotations'][k]['image_id']==observed_image:\n image_id_key.append([observed_image])\n feature_maps_to_id.append(example_load[observed_image])\n caption_to_id.append(re.sub('[^A-Za-z0-9]+',' ',data['annotations'][k]['caption']).lower()) #remove punctuation \n \nprint('number of images ',len(image_ids))\nprint('number of captions ',len(caption_to_id))",
"number of images 2000\nnumber of captions 10006\n"
]
],
[
[
"In the cell above we created three lists, one for the image_id, feature map. and caption. To verify that the indices of each list are aligned, display the image id and caption for one image. ",
"_____no_output_____"
]
],
[
[
"STRING='%012d' % image_id_key[0][0]\nexp_image=ndimage.imread(TRAIN_IMAGE_PATH+'COCO_train2014_'+STRING+'.jpg')\nplt.imshow(exp_image)\nprint('image_id ',image_id_key[:5])\nprint('the captions for this image ')\nprint(caption_to_id[:5])",
"image_id [[196611], [196611], [196611], [196611], [196611]]\nthe captions for this image \n[u'a light turned on at a desk with a chair and computer ', u'a living room with the light on next to a computer desk ', u'a living room with a white chair and desk ', u'a computer on a desk next to an empty chair ', u'empty chair in front of a desk with a laptop computer and lamp ']\n"
],
[
"num_steps=20\n######################################################################\n##Create a list of all of the sentences.\nDatasetWordList=[]\nfor dataset_caption in caption_to_id:\n DatasetWordList+=str(dataset_caption).split()\n#Determine number of distint words \ndistintwords=collections.Counter(DatasetWordList)\n#Order words \ncount_pairs = sorted(distintwords.items(), key=lambda x: (-x[1], x[0])) #ascending order\nwords, occurence = list(zip(*count_pairs))\n#DictionaryLength=occurence.index(4) #index for words that occur 4 times or less\nwords=['PAD','UNK','EOS']+list(words)#[:DictionaryLength])\nword_to_id=dict(zip(words, range(len(words))))\n##################### Tokenize Sentence #######################\nTokenized=[]\nfor full_words in caption_to_id:\n EmbeddedSentence=[word_to_id[word] for word in full_words.split() if word in word_to_id]+[word_to_id['EOS']]\n #Pad sentences that are shorter than the number of steps \n if len(EmbeddedSentence)<num_steps:\n b=[word_to_id['PAD']]*num_steps\n b[:len(EmbeddedSentence)]=EmbeddedSentence\n if len(EmbeddedSentence)>num_steps:\n b=EmbeddedSentence[:num_steps]\n if len(b)==EmbeddedSentence:\n b=EmeddedSentence\n #b=[word_to_id['UNK'] if x>=DictionaryLength else x for x in b] #turn all words used 4 times or less to 'UNK'\n #print(b)\n Tokenized+=[b]\n \nprint(\"Number of words in this dictionary \", len(words))",
"Number of words in this dictionary 4644\n"
],
[
"#Tokenized Sentences\nTokenized[::2000]",
"_____no_output_____"
]
],
[
[
"The next cell contains functions for queuing our data and the RNN model. What should the output for each function be? If you need a hint look [here](#answer2 \"The data_queue function batches the data for us, this needs to return tokenized_caption, input_feature_map. The RNN model should return prediction before the softmax is applied and is defined as pred.\").",
"_____no_output_____"
]
],
[
[
"def data_queue(caption_input,feature_vector,batch_size,):\n\n\n train_input_queue = tf.train.slice_input_producer(\n [caption_input, np.asarray(feature_vector)],num_epochs=10000,\n shuffle=True) #False before\n\n ##Set our train data and label input shape for the queue\n\n TrainingInputs=train_input_queue[0]\n FeatureVectors=train_input_queue[1]\n TrainingInputs.set_shape([num_steps])\n FeatureVectors.set_shape([len(feature_vector[0])]) #fc7 is 4096\n min_after_dequeue=1000000\n capacity = min_after_dequeue + 3 * batch_size \n #input_x, target_y\n tokenized_caption, input_feature_map = tf.train.batch([TrainingInputs, FeatureVectors],\n batch_size=batch_size,\n capacity=capacity,\n num_threads=6)\n return tokenized_caption,input_feature_map\n \n \n\ndef rnn_model(Xconcat,input_keep_prob,output_keep_prob,num_layers,num_hidden):\n#Create a multilayer RNN\n#reuse=False for training but reuse=True for sharing\n layer_cell=[]\n for _ in range(num_layers):\n lstm_cell = tf.contrib.rnn.LSTMCell(num_units=num_hidden, state_is_tuple=True)\n lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell,\n input_keep_prob=input_keep_prob,\n output_keep_prob=output_keep_prob)\n layer_cell.append(lstm_cell)\n\n cell = tf.contrib.rnn.MultiRNNCell(layer_cell, state_is_tuple=True)\n outputs, last_states = tf.contrib.rnn.static_rnn(\n cell=cell,\n dtype=tf.float32,\n inputs=tf.unstack(Xconcat))\n\n output_reshape=tf.reshape(outputs, [batch_size*(num_steps),num_hidden]) #[12==batch_size*num_steps,num_hidden==12]\n pred=tf.matmul(output_reshape, variables_dict[\"weights_mscoco\"]) +variables_dict[\"biases_mscoco\"]\n return pred",
"_____no_output_____"
],
[
"tf.reset_default_graph()\n#######################################################################################################\n# Parameters\nnum_hidden=2048\nnum_steps=num_steps\ndict_length=len(words)\nbatch_size=4\nnum_layers=2\ntrain_lr=0.00001\n#######################################################################################################\nTrainingInputs=Tokenized\nFeatureVectors=feature_maps_to_id\n\n## Variables ## \n# Learning rate placeholder\nlr = tf.placeholder(tf.float32, shape=[])\n#tf.get_variable_scope().reuse_variables()\n\nvariables_dict = {\n \"weights_mscoco\":tf.Variable(tf.truncated_normal([num_hidden,dict_length],\n stddev=1.0,dtype=tf.float32),name=\"weights_mscoco\"),\n \"biases_mscoco\": tf.Variable(tf.truncated_normal([dict_length],\n stddev=1.0,dtype=tf.float32), name=\"biases_mscoco\")}\n\n\ntokenized_caption, input_feature_map=data_queue(TrainingInputs,FeatureVectors,batch_size)\nmscoco_dict=words\n\nTrainInput=tf.constant(word_to_id['PAD'],shape=[batch_size,1],dtype=tf.int32)\n#Pad the beginning of our caption. The first step now only has the image feature vector. Drop the last time step \n#to timesteps to 20\nTrainInput=tf.concat([tf.constant(word_to_id['PAD'],shape=[batch_size,1],dtype=tf.int32),\n tokenized_caption],1)[:,:-1]\nX_one_hot=tf.nn.embedding_lookup(np.identity(dict_length), TrainInput) #[batch,num_steps,dictionary_length][2,6,7]\n#ImageFeatureTensor=input_feature_map\nXconcat=tf.concat([input_feature_map+tf.zeros([num_steps,batch_size,4096]), \n tf.unstack(tf.to_float(X_one_hot),num_steps,1)],2)#[:num_steps,:,:]\n\npred=rnn_model(Xconcat,1.0,1.0,num_layers,num_hidden)\n\n\n#the full caption is the target sentence\ny_one_hot=tf.unstack(tf.nn.embedding_lookup(np.identity(dict_length), tokenized_caption),num_steps,1) #[batch,num_steps,dictionary_length][2,6,7]\n\ny_target_reshape=tf.reshape(y_one_hot,[batch_size*num_steps,dict_length])\n\n\n# Define loss and optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y_target_reshape))\n\noptimizer = tf.train.MomentumOptimizer(lr,0.9)\n\ngvs = optimizer.compute_gradients(cost,aggregation_method = tf.AggregationMethod.EXPERIMENTAL_TREE)\ncapped_gvs = [(tf.clip_by_value(grad, -10., 10.), var) for grad, var in gvs]\ntrain_op=optimizer.apply_gradients(capped_gvs)\n\nsaver = tf.train.Saver()\n\ninit_op = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer()) \n\nwith tf.Session() as sess:\n \n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n #Load a pretrained network\n saver.restore(sess, '/data/mscoco/rnn_layermodel_iter40000')\n print('Model restored from file')\n \n for i in range(100):\n \n loss,y_pred,target_caption,_=sess.run([cost,pred,tokenized_caption,train_op],feed_dict={lr:train_lr})\n\n if i% 10==0:\n print(\"iteration: \",i, \"loss: \",loss)\n \n MODEL_NAME='rnn_model_iter'+str(i)\n saver.save(sess, MODEL_NAME) \n print('saved trained network ',MODEL_NAME)\n print(\"Done Training\")\n coord.request_stop()\n coord.join(threads)\n sess.close() \n",
"INFO:tensorflow:Restoring parameters from /data/mscoco/rnn_layermodel_iter40000\nModel restored from file\niteration: 0 loss: 0.614859\niteration: 10 loss: 0.852881\niteration: 20 loss: 0.91307\niteration: 30 loss: 0.761541\niteration: 40 loss: 0.765284\niteration: 50 loss: 0.742418\niteration: 60 loss: 0.722067\niteration: 70 loss: 0.69909\niteration: 80 loss: 0.836048\niteration: 90 loss: 0.6169\nsaved trained network rnn_model_iter99\nDone Training\n"
]
],
[
[
"We can use the function below to estimate how well the network is able to predict the next word in the caption. You can evaluate a single image and its caption from the last batch using the index of the batch. If you need a hint look [here](#answer3 \"if the batch_size is 4, batch_id may be any value between 0 and 3.\").\n\n##### Please note that depending on the status of the neural network at the time it was saved, incomplete, incoherent, and sometimes inappropriate captions could be generated.",
"_____no_output_____"
]
],
[
[
"def show_next_predicted_word(batch_id,batch_size,id_of_image,target_caption,predicted_caption,words,PATH):\n Target=[words[ind] for ind in target_caption[batch_id]]\n Prediction_Tokenized=np.argmax(predicted_caption[batch_id::batch_size],1)\n Prediction=[words[ind] for ind in Prediction_Tokenized]\n STRING2='%012d' % id_of_image\n img=ndimage.imread(PATH+STRING2+'.jpg')\n return Target,Prediction,img,STRING2\n\n#You can change the batch id to a number between [0 , batch_size-1]\nbatch_id=0\nimage_id_for_predicted_caption=[x for x in range(len(Tokenized)) if target_caption[batch_id].tolist()== Tokenized[x]][0]\n\n\nt,p,input_img,string_out=show_next_predicted_word(batch_id,batch_size,image_id_key[image_id_for_predicted_caption][0]\n ,target_caption,y_pred,words,TRAIN_IMAGE_PATH+'COCO_train2014_')\nprint('Caption')\nprint(t)\nprint('Predicted Words')\nprint(p)\nplt.imshow(input_img)\n",
"Caption\n['a', 'man', 'jumping', 'in', 'the', 'air', 'to', 'catch', 'a', 'frisbee', 'in', 'motion', 'EOS', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD']\nPredicted Words\n['a', 'man', 'that', 'through', 'the', 'air', 'to', 'a', 'a', 'frisbee', 'EOS', 'his', 'EOS', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD']\n"
]
],
[
[
"##### Questions\n[1] Can the show_next_predicted_word function be used for deployment?\n\nProbably not. Can you think of any reason why? Each predicted word is based on the previous ground truth word. In a deployment scenario, we will only have the feature map from our input image. \n\n[2] Can you load your saved network and use it to generate a caption from a validation image?\n\nThe validation images are stored in /data/mscoco/val2014. A npy file of the feature vectors is stored /data/mscoco/val_vgg_16_fc7_100.npy. For a hint on how to add this look [here](#answer4 \"You can change this parameter to val_load=np.load(/data/mscoco/val_vgg_16_fc7_100.npy).tolist()\").\n\n[3] Do you need to calculate the loss or cost when only performing inference?\n\n[4] Do you use dropout when performing inference?\n",
"_____no_output_____"
]
],
[
[
"##Load and test our test set\nval_load=np.load('/data/mscoco/val_vgg_16_fc7_100.npy').tolist()\nval_ids=val_load.keys()",
"_____no_output_____"
],
[
"#Create 3 lists image_id, feature maps, and captions.\nval_id_key=[]\nval_map_to_id=[]\nval_caption_to_id=[]\nfor observed_image in val_ids: \n val_id_key.append([observed_image])\n val_map_to_id.append(val_load[observed_image])\n \nprint('number of images ',len(val_ids))\nprint('number of captions ',len(val_map_to_id))",
"number of images 100\nnumber of captions 100\n"
]
],
[
[
"The cell below will load a feature vector from one of the images in the validation data set and use it with our pretrained network to generate a caption. Use the VALDATA variable to propagate and image through our RNN and generate a caption. You also need to load the network you just created during training. Look here if you need a [hint](#answer5 \"Any of the of the data points in our validation set can be used here. There are 501 captions. Any number between 0 and 501-1 can be used for the VALDATA parameter, such as VALDATA=430. The pretrained network file that you just saved is rnn_model_iter99, insert this string into saver.restore(sess,FILENAME)\").\n\n##### Please note that depending on the status of the neural network at the time it was saved, incomplete, incoherent, and sometimes inappropriate captions could be generated.",
"_____no_output_____"
]
],
[
[
"tf.reset_default_graph()\nbatch_size=1\nnum_steps=20\nprint_topn=0 #0for do not display \nprintnum0f=3\n#Choose a image to caption\nVALDATA=54 #ValImage fc7 feature vector\n\nvariables_dict = {\n \"weights_mscoco\":tf.Variable(tf.truncated_normal([num_hidden,dict_length],\n stddev=1.0,dtype=tf.float32),name=\"weights_mscoco\"),\n \"biases_mscoco\": tf.Variable(tf.truncated_normal([dict_length],\n stddev=1.0,dtype=tf.float32), name=\"biases_mscoco\")}\n\n\nStartCaption=np.zeros([batch_size,num_steps],dtype=np.int32).tolist()\n\nCaptionPlaceHolder = tf.placeholder(dtype=tf.int32, shape=(batch_size , num_steps))\n\nValFeatureMap=val_map_to_id[VALDATA]\nX_one_hot=tf.nn.embedding_lookup(np.identity(dict_length), CaptionPlaceHolder) #[batch,num_steps,dictionary_length][2,6,7]\n #ImageFeatureTensor=input_feature_map\nXconcat=tf.concat([ValFeatureMap+tf.zeros([num_steps,batch_size,4096]), \n tf.unstack(tf.to_float(X_one_hot),num_steps,1)],2)#[:num_steps,:,:]\n\npred=rnn_model(Xconcat,1.0,1.0,num_layers,num_hidden)\npred=tf.nn.softmax(pred)\nsaver = tf.train.Saver()\n\ninit_op = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer()) \n\nwith tf.Session() as sess:\n \n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n #Load a pretrained network\n saver.restore(sess, 'rnn_model_iter99')\n print('Model restored from file')\n for i in range(num_steps-1):\n predict_next_word=sess.run([pred],feed_dict={CaptionPlaceHolder:StartCaption})\n INDEX=np.argmax(predict_next_word[0][i])\n StartCaption[0][i+1]=INDEX\n ##Post N most probable next words at each step\n if print_topn !=0:\n print(\"Top \",str(printnum0f), \"predictions for the\", str(i+1), \"word in the predicted caption\" )\n result_args = np.argsort(predict_next_word[0][i])[-printnum0f:][::-1]\n NextWord=[words[x] for x in result_args]\n print(NextWord)\n \n coord.request_stop()\n coord.join(threads)\n sess.close() \n\nSTRING2='%012d' % val_id_key[VALDATA][0]\nimg=ndimage.imread('/data/mscoco/val2014/COCO_val2014_'+STRING2+'.jpg')\nplt.imshow(img)\nplt.title('COCO_val2014_'+STRING2+'.jpg')\nPredictedCaption=[words[x] for x in StartCaption[0]]\nprint(\"predicted sentence: \",PredictedCaption[1:])",
"INFO:tensorflow:Restoring parameters from rnn_model_iter99\nModel restored from file\npredicted sentence: ['a', 'bathroom', 'with', 'a', 'mirror', 'and', 'a', 'mirror', 'and', 'a', 'mirror', 'EOS', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD', 'PAD']\n"
],
[
"#Free our GPU memory before proceeding to the next part of the lab\nimport os\nos._exit(00)",
"_____no_output_____"
]
],
[
[
"## References \n\n[1] Donahue, J, et al. \"Long-term recurrent convolutional networks for visual recognition and description.\" Proceedings of the IEEE conference on computer vision and pattern recognition. 2015.\n\n[2]Vinyals, Oriol, et al. \"Show and tell: Lessons learned from the 2015 mscoco image captioning challenge.\" IEEE transactions on pattern analysis and machine intelligence 39.4 (2017): 652-663.\n\n[3] TensorFlow Show and Tell:A Neural Image Caption Generator [example] (https://github.com/tensorflow/models/tree/master/im2txt)\n\n[4] Karapthy, A. [NeuralTalk2](https://github.com/karpathy/neuraltalk2)\n\n[5]Lin, Tsung-Yi, et al. \"Microsoft coco: Common objects in context.\" European Conference on Computer Vision. Springer International Publishing, 2014.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb48c4ec5a0f1d71a0829f139dc010e491f99bb1 | 24,069 | ipynb | Jupyter Notebook | Program's_Contributed_By_Contributors/AI-Summer-Course/Numpy/.ipynb_checkpoints/Numpy Tutorial-checkpoint.ipynb | siddharthdeo99/Hacktoberfest2k21 | 95666a2e704b0ce43c2ce3f3d521ff5bd843b17e | [
"MIT"
] | null | null | null | Program's_Contributed_By_Contributors/AI-Summer-Course/Numpy/.ipynb_checkpoints/Numpy Tutorial-checkpoint.ipynb | siddharthdeo99/Hacktoberfest2k21 | 95666a2e704b0ce43c2ce3f3d521ff5bd843b17e | [
"MIT"
] | null | null | null | Program's_Contributed_By_Contributors/AI-Summer-Course/Numpy/.ipynb_checkpoints/Numpy Tutorial-checkpoint.ipynb | siddharthdeo99/Hacktoberfest2k21 | 95666a2e704b0ce43c2ce3f3d521ff5bd843b17e | [
"MIT"
] | null | null | null | 17.684791 | 85 | 0.410237 | [
[
[
"import numpy as np\nimport sys",
"_____no_output_____"
]
],
[
[
"# The Basics",
"_____no_output_____"
]
],
[
[
"a = np.array([1,2,3], dtype='int32')\nprint(a)",
"[1 2 3]\n"
],
[
"b = np.array([[1.0,2.0,3.0],[4.0,5.0,6.0]])\nprint(b)",
"[[1. 2. 3.]\n [4. 5. 6.]]\n"
],
[
"#Get Dimension\na.ndim",
"_____no_output_____"
],
[
"#Get Shape\na.shape",
"_____no_output_____"
],
[
"b.shape",
"_____no_output_____"
],
[
"#Get Type \na.dtype",
"_____no_output_____"
],
[
"#Get size\na.itemsize",
"_____no_output_____"
],
[
"#Get Total Size\na.nbytes",
"_____no_output_____"
],
[
"b.itemsize",
"_____no_output_____"
]
],
[
[
"## Accessing / Changing specific elements, row, columns",
"_____no_output_____"
]
],
[
[
"a = np.array([[1,2,3,4,5,6,7],[8,9,10,11,12,13,14]])\nprint(a)",
"[[ 1 2 3 4 5 6 7]\n [ 8 9 10 11 12 13 14]]\n"
],
[
"#Get element\na[1, 5]",
"_____no_output_____"
],
[
"#Get specific row\na[0, :]",
"_____no_output_____"
],
[
"#Get specific column\na[:, 2]",
"_____no_output_____"
],
[
"#Getting fancier[startindex:endindex:stepsize]\na[0, 1:6:2]",
"_____no_output_____"
],
[
"a[1,5] = 20\nprint(a)\n\na[:,2] = [1,2]\nprint(a)",
"[[ 1 2 3 4 5 6 7]\n [ 8 9 10 11 12 20 14]]\n[[ 1 2 1 4 5 6 7]\n [ 8 9 2 11 12 20 14]]\n"
],
[
"#3d example\nb = np.array([[[1,2], [3,4]], [[5,6],[7,8]]])\nprint(b)",
"[[[1 2]\n [3 4]]\n\n [[5 6]\n [7 8]]]\n"
],
[
"#Get specific element(work outside in)\nb[0, 1, 1]",
"_____no_output_____"
],
[
"b[:,1,:]",
"_____no_output_____"
]
],
[
[
"## Initializing Different types of arrays",
"_____no_output_____"
]
],
[
[
"#All 0s matrix\nnp.zeros((2,3,3))",
"_____no_output_____"
],
[
"#All ones matrix\nnp.ones((4,2,2), dtype='int32')",
"_____no_output_____"
],
[
"#Any number\nnp.full((2,2), 99, dtype=\"float32\")",
"_____no_output_____"
],
[
"# Any other number (full-like)\nnp.full_like(a.shape, 4)",
"_____no_output_____"
],
[
"# Random decimal numbers\nnp.random.rand(4,2,3)",
"_____no_output_____"
],
[
"#Random integers\nnp.random.randint(-4,7, size=(3,3))",
"_____no_output_____"
],
[
"#The identity matrix\nnp.identity(3)",
"_____no_output_____"
],
[
"#Repeat an array\narr = np.array([[1,2,3]])\nr1 = np.repeat(arr, 3, axis=0)\nprint(r1)",
"[[1 2 3]\n [1 2 3]\n [1 2 3]]\n"
],
[
"output = np.ones((5,5))\nprint(output)\n\nz = np.zeros((3,3))\nz[1,1] = 9\nprint(z)\n\noutput[1:-1, 1:-1] = z\nprint(output)",
"[[1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]\n [1. 1. 1. 1. 1.]]\n[[0. 0. 0.]\n [0. 9. 0.]\n [0. 0. 0.]]\n[[1. 1. 1. 1. 1.]\n [1. 0. 0. 0. 1.]\n [1. 0. 9. 0. 1.]\n [1. 0. 0. 0. 1.]\n [1. 1. 1. 1. 1.]]\n"
]
],
[
[
"### Be careful when copying arrays",
"_____no_output_____"
]
],
[
[
"a = np.array([1,2,3])\nb = a.copy()\nb[0] = 100\nprint(b)\nprint(a)",
"[100 2 3]\n[1 2 3]\n"
]
],
[
[
"# Mathematics",
"_____no_output_____"
]
],
[
[
"a = np.array([1,2,3,4])\na",
"_____no_output_____"
],
[
"a+2",
"_____no_output_____"
],
[
"a*2",
"_____no_output_____"
],
[
"a/2",
"_____no_output_____"
],
[
"a+=2\na",
"_____no_output_____"
],
[
"b = np.array([1,0,1,0])\na + b",
"_____no_output_____"
],
[
"a * b",
"_____no_output_____"
],
[
"a ** 2",
"_____no_output_____"
],
[
"#Take a sin\nnp.sin(a)",
"_____no_output_____"
],
[
"#Look up scipy routines for more mathematics",
"_____no_output_____"
]
],
[
[
"# Linear Algebra",
"_____no_output_____"
]
],
[
[
"a = np.ones((2,3))\nprint(a)",
"[[1. 1. 1.]\n [1. 1. 1.]]\n"
],
[
"b = np.full((3,2),2)\nprint(b)",
"[[2 2]\n [2 2]\n [2 2]]\n"
],
[
"np.matmul(a,b)",
"_____no_output_____"
],
[
"c = np.identity(3)\nnp.linalg.det(c)",
"_____no_output_____"
],
[
"# https://numpy.org/doc/stable/reference/routines.linalg.html",
"_____no_output_____"
]
],
[
[
"## Statistics",
"_____no_output_____"
]
],
[
[
"stats = np.array([[1,2,3],[4,5,6]])\nstats",
"_____no_output_____"
],
[
"np.min(stats)",
"_____no_output_____"
],
[
"np.max(stats, axis=0)",
"_____no_output_____"
],
[
"np.sum(stats)",
"_____no_output_____"
]
],
[
[
"# Reorganizing Arrays",
"_____no_output_____"
]
],
[
[
"before = np.array([[1,2,3,4],[5,6,7,8]])\nprint(before)\n\nafter = before.reshape((2,2,2))\nprint(after)",
"[[1 2 3 4]\n [5 6 7 8]]\n[[[1 2]\n [3 4]]\n\n [[5 6]\n [7 8]]]\n"
],
[
"#Vertically stacking vectors\nv1 = np.array([1,2,3,4])\nv2 = np.array([5,6,7,8])\n\nnp.vstack([v1,v2,v2,v2])",
"_____no_output_____"
],
[
"#Horizontal stack\nnp.hstack((v1,v2))",
"_____no_output_____"
]
],
[
[
"## Load Data from file",
"_____no_output_____"
]
],
[
[
"filedata = np.genfromtxt('data.txt', delimiter=',')\nfiledata = filedata.astype('int32')\nprint(filedata)",
"[[ 1 13 21 11 196 75 4 3 34 6 7 8 0 1 2 3 4 5]\n [ 3 42 12 33 766 75 4 55 6 4 3 4 5 6 7 0 11 12]\n [ 1 22 33 11 999 11 2 1 78 0 1 2 9 8 7 1 76 88]]\n"
]
],
[
[
"#### Boolean Masking and Advanced Indexing",
"_____no_output_____"
]
],
[
[
"filedata[filedata > 50]",
"_____no_output_____"
],
[
"#You can index with list in numpy\na = np.array([1,2,3,4,5,6,7,8,9])\n\na[[1,2,8]]",
"_____no_output_____"
],
[
"np.any(filedata>50, axis=0)",
"_____no_output_____"
],
[
"(filedata > 50) & (filedata < 100)",
"_____no_output_____"
]
],
[
[
"## Save and Load Arrays",
"_____no_output_____"
]
],
[
[
"x = np.arange(0,10,1)\ny = x**2\nprint(x)\nprint(y)",
"[0 1 2 3 4 5 6 7 8 9]\n[ 0 1 4 9 16 25 36 49 64 81]\n"
],
[
"np.savez(\"x_y-squared.npz\", x-axis= x, )",
"_____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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48cb5a2bb315aee7906190658c5292d7e69ea8 | 42,184 | ipynb | Jupyter Notebook | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | charithsiu/pytorch | 60dbcc545c334e1b5c5bd4827904ef4a16d500fd | [
"MIT"
] | null | null | null | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | charithsiu/pytorch | 60dbcc545c334e1b5c5bd4827904ef4a16d500fd | [
"MIT"
] | 5 | 2019-12-16T21:51:20.000Z | 2021-08-25T15:36:10.000Z | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | charithsiu/pytorch | 60dbcc545c334e1b5c5bd4827904ef4a16d500fd | [
"MIT"
] | null | null | null | 119.501416 | 24,092 | 0.80265 | [
[
[
"# Classifying Fashion-MNIST\n\nNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% accuracy. Fashion-MNIST is a set of 28x28 greyscale images of clothes. It's more complex than MNIST, so it's a better representation of the actual performance of your network, and a better representation of datasets you'll use in the real world.\n\n<img src='assets/fashion-mnist-sprite.png' width=500px>\n\nIn this notebook, you'll build your own neural network. For the most part, you could just copy and paste the code from Part 3, but you wouldn't be learning. It's important for you to write the code yourself and get it to work. Feel free to consult the previous notebooks though as you work through this.\n\nFirst off, let's load the dataset through torchvision.",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torchvision import datasets, transforms\nimport helper\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)",
"Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to C:\\Users\\cata015747/.pytorch/F_MNIST_data/FashionMNIST\\raw\\train-images-idx3-ubyte.gz\n"
]
],
[
[
"Here we can see one of the images.",
"_____no_output_____"
]
],
[
[
"image, label = next(iter(trainloader))\nhelper.imshow(image[0,:]);",
"_____no_output_____"
]
],
[
[
"## Building the network\n\nHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up to you how many layers you add and the size of those layers.",
"_____no_output_____"
]
],
[
[
"# TODO: Define your network architecture here\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch import optim\n\nmodel = nn.Sequential(nn.Linear(784, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 10),\n nn.LogSoftmax(dim=1))",
"_____no_output_____"
]
],
[
[
"# Train the network\n\nNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.html#loss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).\n\nThen write the training code. Remember the training pass is a fairly straightforward process:\n\n* Make a forward pass through the network to get the logits \n* Use the logits to calculate the loss\n* Perform a backward pass through the network with `loss.backward()` to calculate the gradients\n* Take a step with the optimizer to update the weights\n\nBy adjusting the hyperparameters (hidden units, learning rate, etc), you should be able to get the training loss below 0.4.",
"_____no_output_____"
]
],
[
[
"# TODO: Create the network, define the criterion and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.003)",
"_____no_output_____"
],
[
"# TODO: Train the network here\nepochs = 5\nfor e in range(epochs):\n running_loss = 0\n for image, label in trainloader:\n \n images = image.view(image.shape[0], -1)\n \n # TODO: Training pass\n optimizer.zero_grad()\n \n output = model(images)\n loss = criterion(output, label)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n else:\n print(f\"Training loss: {running_loss/len(trainloader)}\")",
"Training loss: 0.5033602697222725\nTraining loss: 0.3848633481495416\nTraining loss: 0.35284329154121596\nTraining loss: 0.3290072170211308\nTraining loss: 0.31423430216274284\n"
],
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport helper\n\n# Test out your network!\n\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\nimg = images[0]\n# Convert 2D image to 1D vector\nimg = img.resize_(1, 784)\n\nwith torch.no_grad():\n logps = model(img)\n# TODO: Calculate the class probabilities (softmax) for img\nps = torch.exp(logps)\n\n# Plot the image and probabilities\nhelper.view_classify(img.resize_(1, 28, 28), ps, version='Fashion')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb48dffcc4c6bc86e578699a7186576001028c95 | 73,959 | ipynb | Jupyter Notebook | _posts/python-v3/javascript-controls/ipython-widgets/slider_example.ipynb | arauzo/graphing-library-docs | c99f3ed921727e1dcb321e6a52c5c7f7fe74356d | [
"CC-BY-3.0"
] | 43 | 2020-02-06T00:54:56.000Z | 2022-03-24T22:29:33.000Z | _posts/python-v3/javascript-controls/ipython-widgets/slider_example.ipynb | arauzo/graphing-library-docs | c99f3ed921727e1dcb321e6a52c5c7f7fe74356d | [
"CC-BY-3.0"
] | 92 | 2020-01-31T16:23:50.000Z | 2022-03-21T05:31:39.000Z | _posts/python-v3/javascript-controls/ipython-widgets/slider_example.ipynb | arauzo/graphing-library-docs | c99f3ed921727e1dcb321e6a52c5c7f7fe74356d | [
"CC-BY-3.0"
] | 63 | 2020-02-08T15:16:06.000Z | 2022-03-29T17:24:38.000Z | 44.101968 | 325 | 0.448519 | [
[
[
"#### New to Plotly?\nPlotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).\n<br>You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).\n<br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!",
"_____no_output_____"
],
[
"#### Using a Single Slider to Set the Range",
"_____no_output_____"
]
],
[
[
"import plotly.plotly as py\nimport ipywidgets as widgets\n\nfrom ipywidgets import interact, interactive, fixed\nfrom IPython.core.display import HTML\nfrom IPython.display import display, clear_output\nfrom plotly.widgets import GraphWidget\n\n\nstyles = '''<style>.widget-hslider { width: 100%; }\n .widget-hbox { width: 100% !important; }\n .widget-slider { width: 100% !important; }</style>'''\n\nHTML(styles)\n\n#this widget will display our plotly chart\ngraph = GraphWidget(\"https://plotly.com/~jordanpeterson/889\")\nfig = py.get_figure(\"https://plotly.com/~jordanpeterson/889\")\n\n#find the range of the slider.\nxmin, xmax = fig['layout']['xaxis']['range']\n\n# use the interact decorator to tie a widget to the listener function\n@interact(y=widgets.FloatRangeSlider(min=xmin, max=xmax, step=(xmax-xmin)/1000.0, continuous_update=False))\ndef update_plot(y):\n graph.relayout({'xaxis.range[0]': y[0], 'xaxis.range[1]': y[1]})\n \n#display the app \ngraph",
"_____no_output_____"
],
[
"%%html\n<img src='https://cloud.githubusercontent.com/assets/12302455/16469485/42791e90-3e1f-11e6-8db4-2364bd610ce4.gif'>",
"_____no_output_____"
]
],
[
[
"#### Using Two Sliders to Set Range",
"_____no_output_____"
]
],
[
[
"import plotly.plotly as py\nimport ipywidgets as widgets\n\nfrom ipywidgets import interact, interactive, fixed\nfrom IPython.core.display import HTML\nfrom IPython.display import display, clear_output\nfrom plotly.widgets import GraphWidget\nfrom traitlets import link\n\n\nstyles = '''<style>.widget-hslider { width: 100%; }\n .widget-hbox { width: 100% !important; }\n .widget-slider { width: 100% !important; }</style>'''\n\nHTML(styles)\n\n#this widget will display our plotly chart\ngraph = GraphWidget(\"https://plotly.com/~jordanpeterson/889\")\nfig = py.get_figure(\"https://plotly.com/~jordanpeterson/889\")\n\n#find the range of the slider.\nxmin, xmax = fig['layout']['xaxis']['range']\n\n# let's define our listener functions that will respond to changes in the sliders\ndef on_value_change_left(change):\n graph.relayout({'xaxis.range[0]': change['new']})\n \ndef on_value_change_right(change):\n graph.relayout({'xaxis.range[1]': change['new']})\n \n# define the sliders\nleft_slider = widgets.FloatSlider(min=xmin, max=xmax, value=xmin, description=\"Left Slider\")\nright_slider = widgets.FloatSlider(min=xmin, max=xmax, value=xmax, description=\"Right Slider\")\n\n# put listeners on slider activity\nleft_slider.observe(on_value_change_left, names='value')\nright_slider.observe(on_value_change_right, names='value')\n\n# set a relationship between the left and right slider\nlink((left_slider, 'max'), (right_slider, 'value'))\nlink((left_slider, 'value'), (right_slider, 'min'))\n\n# display our app\ndisplay(left_slider)\ndisplay(right_slider)\ndisplay(graph)\n",
"_____no_output_____"
],
[
"%%html\n<img src='https://cloud.githubusercontent.com/assets/12302455/16469486/42891d0e-3e1f-11e6-9576-02c5f6c3d3c9.gif'>",
"_____no_output_____"
]
],
[
[
"#### Sliders with 3d Plots",
"_____no_output_____"
]
],
[
[
"import plotly.plotly as py\nimport ipywidgets as widgets\nimport numpy as np\n\nfrom ipywidgets import interact, interactive, fixed\nfrom IPython.core.display import HTML\nfrom IPython.display import display, clear_output\nfrom plotly.widgets import GraphWidget\n\ng = GraphWidget('https://plotly.com/~DemoAccount/10147/')\nx = y = np.arange(-5,5,0.1)\nyt = x[:,np.newaxis]\n\n# define our listener class\nclass z_data:\n \n def __init__(self):\n self.z = np.cos(x*yt)+np.sin(x*yt)*2\n \n def on_z_change(self, name):\n new_value = name['new']\n \n self.z = np.cos(x*yt*(new_value+1)/100)+np.sin(x*yt*(new_value+1/100))\n self.replot()\n \n def replot(self):\n g.restyle({ 'z': [self.z], 'colorscale': 'Viridis'})\n\n# create sliders\nz_slider = widgets.FloatSlider(min=0,max=30,value=1,step=0.05, continuous_update=False)\nz_slider.description = 'Frequency'\nz_slider.value = 1\n\n# initialize listener class\nz_state = z_data()\n\n# activate listener on our slider\nz_slider.observe(z_state.on_z_change, 'value')\n\n# display our app\ndisplay(z_slider)\ndisplay(g)",
"_____no_output_____"
],
[
"%%html\n<img src=\"https://cloud.githubusercontent.com/assets/12302455/16569550/bd02e030-4205-11e6-8087-d41c9b5d3681.gif\">",
"_____no_output_____"
]
],
[
[
"#### Reference",
"_____no_output_____"
]
],
[
[
"help(GraphWidget)",
"Help on class GraphWidget in module plotly.widgets.graph_widget:\n\nclass GraphWidget(ipywidgets.widgets.domwidget.DOMWidget)\n | An interactive Plotly graph widget for use in IPython\n | Notebooks.\n | \n | Method resolution order:\n | GraphWidget\n | ipywidgets.widgets.domwidget.DOMWidget\n | ipywidgets.widgets.widget.Widget\n | traitlets.config.configurable.LoggingConfigurable\n | traitlets.config.configurable.Configurable\n | traitlets.traitlets.HasTraits\n | traitlets.traitlets.HasDescriptors\n | __builtin__.object\n | \n | Methods defined here:\n | \n | __init__(self, graph_url='https://plotly.com/~playground/7', **kwargs)\n | Initialize a plotly graph widget\n | \n | Args:\n | graph_url: The url of a Plotly graph\n | \n | Example:\n | ```\n | GraphWidget('https://plotly.com/~chris/3375')\n | ```\n | \n | add_traces(self, traces, new_indices=None)\n | Add new data traces to a graph.\n | \n | If `new_indices` isn't specified, they are simply appended.\n | \n | Args:\n | traces (dict or list of dicts, or class of plotly.graph_objs):trace\n | new_indices (list[int]|None), optional: The final indices the\n | added traces should occupy in the graph.\n | \n | Examples:\n | Initialization - Start each example below with this setup:\n | ```\n | from plotly.widgets import GraphWidget\n | from plotly.graph_objs import Scatter\n | from IPython.display import display\n | \n | graph = GraphWidget('https://plotly.com/~chris/3979')\n | display(graph)\n | ```\n | \n | Example 1 - Add a scatter/line trace to the graph\n | ```\n | graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 4, 5]))\n | ```\n | \n | Example 2 - Add a scatter trace and set it to to be the\n | second trace. This will appear as the second\n | item in the legend.\n | ```\n | graph.add_traces(Scatter(x = [1, 2, 3], y = [5, 6, 5]),\n | new_indices=[1])\n | ```\n | \n | Example 3 - Add multiple traces to the graph\n | ```\n | graph.add_traces([\n | Scatter(x = [1, 2, 3], y = [5, 6, 5]),\n | Scatter(x = [1, 2.5, 3], y = [5, 8, 5])\n | ])\n | ```\n | \n | delete_traces(self, indices)\n | Delete data traces from a graph.\n | \n | Args:\n | indices (list[int]): The indices of the traces to be removed\n | \n | Example - Delete the 2nd trace:\n | ```\n | from plotly.widgets import GraphWidget\n | from IPython.display import display\n | \n | graph = GraphWidget('https://plotly.com/~chris/3979')\n | display(graph)\n | \n | \n | graph.delete_traces([1])\n | ```\n | \n | extend_traces(self, update, indices=(0,), max_points=None)\n | Append data points to existing traces in the Plotly graph.\n | \n | Args:\n | update (dict):\n | dict where keys are the graph attribute strings\n | and values are arrays of arrays with values to extend.\n | \n | Each array in the array will extend a trace.\n | \n | Valid keys include:\n | 'x', 'y', 'text,\n | 'marker.color', 'marker.size', 'marker.symbol',\n | 'marker.line.color', 'marker.line.width'\n | \n | indices (list, int):\n | Specify which traces to apply the `update` dict to.\n | If indices are not given, the update will apply to\n | the traces in order.\n | \n | max_points (int or dict, optional):\n | If specified, then only show the `max_points` most\n | recent points in the graph.\n | This is useful to prevent traces from becoming too\n | large (and slow) or for creating \"windowed\" graphs\n | in monitoring applications.\n | \n | To set max_points to different values for each trace\n | or attribute, set max_points to a dict mapping keys\n | to max_points values. See the examples below.\n | \n | Examples:\n | Initialization - Start each example below with this setup:\n | ```\n | from plotly.widgets import GraphWidget\n | from IPython.display import display\n | \n | graph = GraphWidget()\n | graph.plot([\n | {'x': [], 'y': []},\n | {'x': [], 'y': []}\n | ])\n | \n | display(graph)\n | ```\n | \n | Example 1 - Extend the first trace with x and y data\n | ```\n | graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},\n | indices=[0])\n | ```\n | \n | Example 2 - Extend the second trace with x and y data\n | ```\n | graph.extend_traces({'x': [[1, 2, 3]], 'y': [[10, 20, 30]]},\n | indices=[1])\n | ```\n | \n | Example 3 - Extend the first two traces with x and y data\n | ```\n | graph.extend_traces({\n | 'x': [[1, 2, 3], [2, 3, 4]],\n | 'y': [[10, 20, 30], [3, 4, 3]]\n | }, indices=[0, 1])\n | ```\n | \n | Example 4 - Extend the first trace with x and y data and\n | limit the length of data in that trace to 50\n | points.\n | ```\n | \n | graph.extend_traces({\n | 'x': [range(100)],\n | 'y': [range(100)]\n | }, indices=[0, 1], max_points=50)\n | ```\n | \n | Example 5 - Extend the first and second trace with x and y data\n | and limit the length of data in the first trace to\n | 25 points and the second trace to 50 points.\n | ```\n | new_points = range(100)\n | graph.extend_traces({\n | 'x': [new_points, new_points],\n | 'y': [new_points, new_points]\n | },\n | indices=[0, 1],\n | max_points={\n | 'x': [25, 50],\n | 'y': [25, 50]\n | }\n | )\n | ```\n | \n | Example 6 - Update other attributes, like marker colors and\n | sizes and text\n | ```\n | # Initialize a plot with some empty attributes\n | graph.plot([{\n | 'x': [],\n | 'y': [],\n | 'text': [],\n | 'marker': {\n | 'size': [],\n | 'color': []\n | }\n | }])\n | # Append some data into those attributes\n | graph.extend_traces({\n | 'x': [[1, 2, 3]],\n | 'y': [[10, 20, 30]],\n | 'text': [['A', 'B', 'C']],\n | 'marker.size': [[10, 15, 20]],\n | 'marker.color': [['blue', 'red', 'orange']]\n | }, indices=[0])\n | ```\n | \n | Example 7 - Live-update a graph over a few seconds\n | ```\n | import time\n | \n | graph.plot([{'x': [], 'y': []}])\n | for i in range(10):\n | graph.extend_traces({\n | 'x': [[i]],\n | 'y': [[i]]\n | }, indices=[0])\n | \n | time.sleep(0.5)\n | ```\n | \n | hover(self, *hover_objs)\n | Show hover labels over the points specified in hover_obj.\n | \n | Hover labels are the labels that normally appear when the\n | mouse hovers over points in the plotly graph.\n | \n | Args:\n | hover_objs (tuple of dicts):\n | Specifies which points to place hover labels over.\n | \n | The location of the hover labels is described by a dict with\n | keys and'xval' and/or 'yval' or 'curveNumber' and 'pointNumber'\n | and optional keys 'hovermode' and 'subplot'\n | \n | 'xval' and 'yval' specify the (x, y) coordinates to\n | place the label.\n | 'xval' and 'yval need to be close to a point drawn in a graph.\n | \n | 'curveNumber' and 'pointNumber' specify the trace number and\n | the index theof the point in that trace respectively.\n | \n | 'subplot' describes which axes to the coordinates refer to.\n | By default, it is equal to 'xy'. For example, to specify the\n | second x-axis and the third y-axis, set 'subplot' to 'x2y3'\n | \n | 'hovermode' is either 'closest', 'x', or 'y'.\n | When set to 'x', all data sharing the same 'x' coordinate will\n | be shown on screen with corresponding trace labels.\n | When set to 'y' all data sharing the same 'y' coordinates will\n | be shown on the screen with corresponding trace labels.\n | When set to 'closest', information about the data point closest\n | to where the viewer is hovering will appear.\n | \n | Note: If 'hovermode' is 'x', only 'xval' needs to be set.\n | If 'hovermode' is 'y', only 'yval' needs to be set.\n | If 'hovermode' is 'closest', 'xval' and 'yval' both\n | need to be set.\n | \n | Note: 'hovermode' can be toggled by the user in the graph\n | toolbar.\n | \n | Note: It is not currently possible to apply multiple hover\n | labels to points on different axes.\n | \n | Note: `hover` can only be called with multiple dicts if\n | 'curveNumber' and 'pointNumber' are the keys of the dicts\n | \n | Examples:\n | Initialization - Start each example below with this setup:\n | ```\n | from plotly.widgets import GraphWidget\n | from IPython.display import display\n | \n | graph = GraphWidget('https://plotly.com/~chris/3979')\n | display(graph)\n | ```\n | \n | Example 1 - Apply a label to the (x, y) point (3, 2)\n | ```\n | graph.hover({'xval': 3, 'yval': 2, 'hovermode': 'closest'})\n | ```\n | \n | Example 2 -Apply a labels to all the points with the x coordinate 3\n | ```\n | graph.hover({'xval': 3, 'hovermode': 'x'})\n | ```\n | \n | Example 3 - Apply a label to the first point of the first trace\n | and the second point of the second trace.\n | ```\n | graph.hover({'curveNumber': 0, 'pointNumber': 0},\n | {'curveNumber': 1, 'pointNumber': 1})\n | ```\n | \n | on_click(self, callback, remove=False)\n | Assign a callback to click events propagated\n | by clicking on point(s) in the Plotly graph.\n | \n | Args:\n | callback (function): Callback function this is called\n | on click events with the signature:\n | callback(widget, hover_obj) -> None\n | \n | Args:\n | widget (GraphWidget): The current instance\n | of the graph widget that this callback is assigned to.\n | \n | click_obj (dict): a nested dict that describes\n | which point(s) were clicked on.\n | \n | click_obj example:\n | [\n | {\n | 'curveNumber': 1,\n | 'pointNumber': 2,\n | 'x': 4,\n | 'y': 14\n | }\n | ]\n | \n | remove (bool, optional): If False, attach the callback.\n | If True, remove the callback. Defaults to False.\n | \n | \n | Returns:\n | None\n | \n | Example:\n | ```\n | from IPython.display import display\n | def message_handler(widget, msg):\n | display(widget._graph_url)\n | display(msg)\n | \n | g = GraphWidget('https://plotly.com/~chris/3375')\n | display(g)\n | \n | g.on_click(message_handler)\n | ```\n | \n | on_hover(self, callback, remove=False)\n | Assign a callback to hover events propagated\n | by hovering over points in the Plotly graph.\n | \n | Args:\n | callback (function): Callback function this is called\n | on hover events with the signature:\n | callback(widget, hover_obj) -> None\n | \n | Args:\n | widget (GraphWidget): The current instance\n | of the graph widget that this callback is assigned to.\n | \n | hover_obj (dict): a nested dict that describes\n | which point(s) was hovered over.\n | \n | hover_obj example:\n | [\n | {\n | 'curveNumber': 1,\n | 'pointNumber': 2,\n | 'x': 4,\n | 'y': 14\n | }\n | ]\n | \n | remove (bool, optional): If False, attach the callback.\n | If True, remove the callback. Defaults to False.\n | \n | \n | Returns:\n | None\n | \n | Example:\n | ```\n | from IPython.display import display\n | def message_handler(widget, hover_msg):\n | display(widget._graph_url)\n | display(hover_msg)\n | \n | g = GraphWidget('https://plotly.com/~chris/3375')\n | display(g)\n | \n | g.on_hover(message_handler)\n | ```\n | \n | on_zoom(self, callback, remove=False)\n | Assign a callback to zoom events propagated\n | by zooming in regions in the Plotly graph.\n | \n | Args:\n | callback (function): Callback function this is called\n | on zoom events with the signature:\n | callback(widget, ranges) -> None\n | \n | Args:\n | widget (GraphWidget): The current instance\n | of the graph widget that this callback is assigned to.\n | \n | ranges (dict): A description of the\n | region that was zoomed into.\n | \n | ranges example:\n | {\n | 'x': [1.8399058038561549, 2.16443359662],\n | 'y': [4.640902872777017, 7.855677154582]\n | }\n | \n | remove (bool, optional): If False, attach the callback.\n | If True, remove the callback. Defaults to False.\n | \n | Returns:\n | None\n | \n | Example:\n | ```\n | from IPython.display import display\n | def message_handler(widget, ranges):\n | display(widget._graph_url)\n | display(ranges)\n | \n | g = GraphWidget('https://plotly.com/~chris/3375')\n | display(g)\n | \n | g.on_zoom(message_handler)\n | ```\n | \n | plot(self, figure_or_data, validate=True)\n | Plot figure_or_data in the Plotly graph widget.\n | \n | Args:\n | figure_or_data (dict, list, or plotly.graph_obj object):\n | The standard Plotly graph object that describes Plotly\n | graphs as used in `plotly.plotly.plot`. See examples\n | of the figure_or_data in https://plotly.com/python/\n | \n | Returns: None\n | \n | Example 1 - Graph a scatter plot:\n | ```\n | from plotly.graph_objs import Scatter\n | g = GraphWidget()\n | g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])\n | ```\n | \n | Example 2 - Graph a scatter plot with a title:\n | ```\n | from plotly.graph_objs import Scatter, Figure, Data\n | fig = Figure(\n | data = Data([\n | Scatter(x=[1, 2, 3], y=[20, 15, 13])\n | ]),\n | layout = Layout(title='Experimental Data')\n | )\n | \n | g = GraphWidget()\n | g.plot(fig)\n | ```\n | \n | Example 3 - Clear a graph widget\n | ```\n | from plotly.graph_objs import Scatter, Figure\n | g = GraphWidget()\n | g.plot([Scatter(x=[1, 2, 3], y=[10, 15, 13])])\n | \n | # Now clear it\n | g.plot({}) # alternatively, g.plot(Figure())\n | ```\n | \n | relayout(self, layout)\n | Update the layout of the Plotly graph.\n | \n | Args:\n | layout (dict):\n | dict where keys are the graph attribute strings\n | and values are the value of the graph attribute.\n | \n | To update graph objects that are nested, like\n | the title of an axis, combine the keys with a period\n | e.g. `xaxis.title`. To set a value of an element in an array,\n | like an axis's range, use brackets, e.g. 'xaxis.range[0]'.\n | To replace an entire nested object, just specify the value to\n | the sub-object. See example 4 below.\n | \n | See all of the layout attributes in our reference documentation\n | https://plotly.com/python/reference/#Layout\n | Or by calling `help` on `plotly.graph_objs.Layout`\n | \n | Examples - Start each example below with this setup:\n | Initialization:\n | ```\n | from plotly.widgets import GraphWidget\n | from IPython.display import display\n | \n | graph = GraphWidget('https://plotly.com/~chris/3979')\n | display(graph)\n | ```\n | \n | Example 1 - Update the title\n | ```\n | graph.relayout({'title': 'Experimental results'})\n | ```\n | \n | Example 2 - Update the xaxis range\n | ```\n | graph.relayout({'xaxis.range': [-1, 6]})\n | ```\n | \n | Example 3 - Update the first element of the xaxis range\n | ```\n | graph.relayout({'xaxis.range[0]': -3})\n | ```\n | \n | Example 4 - Replace the entire xaxis object\n | ```\n | graph.relayout({'xaxis': {'title': 'Experimental results'}})\n | ```\n | \n | reorder_traces(self, current_indices, new_indices=None)\n | Reorder the traces in a graph.\n | \n | The order of the traces determines the order of the legend entries\n | and the layering of the objects drawn in the graph, i.e. the first\n | trace is drawn first and the second trace is drawn on top of the\n | first trace.\n | \n | Args:\n | current_indices (list[int]): The index of the traces to reorder.\n | \n | new_indices (list[int], optional): The index of the traces\n | specified by `current_indices` after ordering.\n | If None, then move the traces to the end.\n | \n | Examples:\n | Example 1 - Move the first trace to the second to last\n | position, the second trace to the last position\n | ```\n | graph.move_traces([0, 1])\n | ```\n | \n | Example 2 - Move the first trace to the second position,\n | the second trace to the first position.\n | ```\n | graph.move_traces([0], [1])\n | ```\n | \n | restyle(self, update, indices=None)\n | Update the style of existing traces in the Plotly graph.\n | \n | Args:\n | update (dict):\n | dict where keys are the graph attribute strings\n | and values are the value of the graph attribute.\n | \n | To update graph objects that are nested, like\n | a marker's color, combine the keys with a period,\n | e.g. `marker.color`. To replace an entire nested object,\n | like `marker`, set the value to the object.\n | See Example 2 below.\n | \n | To update an attribute of multiple traces, set the\n | value to an list of values. If the list is shorter\n | than the number of traces, the values will wrap around.\n | Note: this means that for values that are naturally an array,\n | like `x` or `colorscale`, you need to wrap the value\n | in an extra array,\n | i.e. {'colorscale': [[[0, 'red'], [1, 'green']]]}\n | \n | You can also supply values to different traces with the\n | indices argument.\n | \n | See all of the graph attributes in our reference documentation\n | here: https://plotly.com/python/reference or by calling `help` on\n | graph objects in `plotly.graph_objs`.\n | \n | indices (list, optional):\n | Specify which traces to apply the update dict to.\n | Negative indices are supported.\n | If indices are not given, the update will apply to\n | *all* traces.\n | \n | Examples:\n | Initialization - Start each example below with this setup:\n | ```\n | from plotly.widgets import GraphWidget\n | from IPython.display import display\n | \n | graph = GraphWidget()\n | display(graph)\n | ```\n | \n | Example 1 - Set `marker.color` to red in every trace in the graph\n | ```\n | graph.restyle({'marker.color': 'red'})\n | ```\n | \n | Example 2 - Replace `marker` with {'color': 'red'}\n | ```\n | graph.restyle({'marker': {'color': red'}})\n | ```\n | \n | Example 3 - Set `marker.color` to red\n | in the first trace of the graph\n | ```\n | graph.restyle({'marker.color': 'red'}, indices=[0])\n | ```\n | \n | Example 4 - Set `marker.color` of all of the traces to\n | alternating sequences of red and green\n | ```\n | graph.restyle({'marker.color': ['red', 'green']})\n | ```\n | \n | Example 5 - Set just `marker.color` of the first two traces\n | to red and green\n | ```\n | graph.restyle({'marker.color': ['red', 'green']}, indices=[0, 1])\n | ```\n | \n | Example 6 - Set multiple attributes of all of the traces\n | ```\n | graph.restyle({\n | 'marker.color': 'red',\n | 'line.color': 'green'\n | })\n | ```\n | \n | Example 7 - Update the data of the first trace\n | ```\n | graph.restyle({\n | 'x': [[1, 2, 3]],\n | 'y': [[10, 20, 30]],\n | }, indices=[0])\n | ```\n | \n | Example 8 - Update the data of the first two traces\n | ```\n | graph.restyle({\n | 'x': [[1, 2, 3],\n | [1, 2, 4]],\n | 'y': [[10, 20, 30],\n | [5, 8, 14]],\n | }, indices=[0, 1])\n | ```\n | \n | save(self, ignore_defaults=False, filename='')\n | Save a copy of the current state of the widget in plotly.\n | \n | :param (bool) ignore_defaults: Auto-fill in unspecified figure keys?\n | :param (str) filename: Name of the file on plotly.\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | url\n | \n | ----------------------------------------------------------------------\n | Methods inherited from ipywidgets.widgets.domwidget.DOMWidget:\n | \n | add_class(self, className)\n | Adds a class to the top level element of the widget.\n | \n | Doesn't add the class if it already exists.\n | \n | remove_class(self, className)\n | Removes a class from the top level element of the widget.\n | \n | Doesn't remove the class if it doesn't exist.\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from ipywidgets.widgets.domwidget.DOMWidget:\n | \n | layout\n | \n | ----------------------------------------------------------------------\n | Methods inherited from ipywidgets.widgets.widget.Widget:\n | \n | __del__(self)\n | Object disposal\n | \n | add_traits(self, **traits)\n | Dynamically add trait attributes to the Widget.\n | \n | close(self)\n | Close method.\n | \n | Closes the underlying comm.\n | When the comm is closed, all of the widget views are automatically\n | removed from the front-end.\n | \n | get_state(self, key=None, drop_defaults=False)\n | Gets the widget state, or a piece of it.\n | \n | Parameters\n | ----------\n | key : unicode or iterable (optional)\n | A single property's name or iterable of property names to get.\n | \n | Returns\n | -------\n | state : dict of states\n | metadata : dict\n | metadata for each field: {key: metadata}\n | \n | get_view_spec(self)\n | \n | hold_sync(*args, **kwds)\n | Hold syncing any state until the outermost context manager exits\n | \n | notify_change(self, change)\n | Called when a property has changed.\n | \n | on_displayed(self, callback, remove=False)\n | (Un)Register a widget displayed callback.\n | \n | Parameters\n | ----------\n | callback: method handler\n | Must have a signature of::\n | \n | callback(widget, **kwargs)\n | \n | kwargs from display are passed through without modification.\n | remove: bool\n | True if the callback should be unregistered.\n | \n | on_msg(self, callback, remove=False)\n | (Un)Register a custom msg receive callback.\n | \n | Parameters\n | ----------\n | callback: callable\n | callback will be passed three arguments when a message arrives::\n | \n | callback(widget, content, buffers)\n | \n | remove: bool\n | True if the callback should be unregistered.\n | \n | open(self)\n | Open a comm to the frontend if one isn't already open.\n | \n | send(self, content, buffers=None)\n | Sends a custom msg to the widget model in the front-end.\n | \n | Parameters\n | ----------\n | content : dict\n | Content of the message to send.\n | buffers : list of binary buffers\n | Binary buffers to send with message\n | \n | send_state(self, key=None)\n | Sends the widget state, or a piece of it, to the front-end.\n | \n | Parameters\n | ----------\n | key : unicode, or iterable (optional)\n | A single property's name or iterable of property names to sync with the front-end.\n | \n | set_state(self, sync_data)\n | Called when a state is received from the front-end.\n | \n | ----------------------------------------------------------------------\n | Static methods inherited from ipywidgets.widgets.widget.Widget:\n | \n | get_manager_state(drop_defaults=False)\n | \n | handle_comm_opened(comm, msg)\n | Static method, called when a widget is constructed.\n | \n | on_widget_constructed(callback)\n | Registers a callback to be called when a widget is constructed.\n | \n | The callback must have the following signature:\n | callback(widget)\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from ipywidgets.widgets.widget.Widget:\n | \n | comm\n | A trait whose value must be an instance of a specified class.\n | \n | The value can also be an instance of a subclass of the specified class.\n | \n | Subclasses can declare default classes by overriding the klass attribute\n | \n | keys\n | An instance of a Python list.\n | \n | model_id\n | Gets the model id of this widget.\n | \n | If a Comm doesn't exist yet, a Comm will be created automagically.\n | \n | msg_throttle\n | An int trait.\n | \n | ----------------------------------------------------------------------\n | Data and other attributes inherited from ipywidgets.widgets.widget.Widget:\n | \n | widget_types = {'Jupyter.Accordion': <class 'ipywidgets.widgets.widget...\n | \n | widgets = {u'10921463ae5d42e6b544809cc744c6ae': <ipywidgets.widgets.wi...\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from traitlets.config.configurable.LoggingConfigurable:\n | \n | log\n | A trait whose value must be an instance of a specified class.\n | \n | The value can also be an instance of a subclass of the specified class.\n | \n | Subclasses can declare default classes by overriding the klass attribute\n | \n | ----------------------------------------------------------------------\n | Methods inherited from traitlets.config.configurable.Configurable:\n | \n | update_config(self, config)\n | Update config and load the new values\n | \n | ----------------------------------------------------------------------\n | Class methods inherited from traitlets.config.configurable.Configurable:\n | \n | class_config_rst_doc(cls) from traitlets.traitlets.MetaHasTraits\n | Generate rST documentation for this class' config options.\n | \n | Excludes traits defined on parent classes.\n | \n | class_config_section(cls) from traitlets.traitlets.MetaHasTraits\n | Get the config class config section\n | \n | class_get_help(cls, inst=None) from traitlets.traitlets.MetaHasTraits\n | Get the help string for this class in ReST format.\n | \n | If `inst` is given, it's current trait values will be used in place of\n | class defaults.\n | \n | class_get_trait_help(cls, trait, inst=None) from traitlets.traitlets.MetaHasTraits\n | Get the help string for a single trait.\n | \n | If `inst` is given, it's current trait values will be used in place of\n | the class default.\n | \n | class_print_help(cls, inst=None) from traitlets.traitlets.MetaHasTraits\n | Get the help string for a single trait and print it.\n | \n | section_names(cls) from traitlets.traitlets.MetaHasTraits\n | return section names as a list\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from traitlets.config.configurable.Configurable:\n | \n | config\n | A trait whose value must be an instance of a specified class.\n | \n | The value can also be an instance of a subclass of the specified class.\n | \n | Subclasses can declare default classes by overriding the klass attribute\n | \n | parent\n | A trait whose value must be an instance of a specified class.\n | \n | The value can also be an instance of a subclass of the specified class.\n | \n | Subclasses can declare default classes by overriding the klass attribute\n | \n | ----------------------------------------------------------------------\n | Methods inherited from traitlets.traitlets.HasTraits:\n | \n | __getstate__(self)\n | \n | __setstate__(self, state)\n | \n | has_trait(self, name)\n | Returns True if the object has a trait with the specified name.\n | \n | hold_trait_notifications(*args, **kwds)\n | Context manager for bundling trait change notifications and cross\n | validation.\n | \n | Use this when doing multiple trait assignments (init, config), to avoid\n | race conditions in trait notifiers requesting other trait values.\n | All trait notifications will fire after all values have been assigned.\n | \n | observe(self, handler, names=traitlets.All, type='change')\n | Setup a handler to be called when a trait changes.\n | \n | This is used to setup dynamic notifications of trait changes.\n | \n | Parameters\n | ----------\n | handler : callable\n | A callable that is called when a trait changes. Its\n | signature should be ``handler(change)``, where ``change`` is a\n | dictionary. The change dictionary at least holds a 'type' key.\n | * ``type``: the type of notification.\n | Other keys may be passed depending on the value of 'type'. In the\n | case where type is 'change', we also have the following keys:\n | * ``owner`` : the HasTraits instance\n | * ``old`` : the old value of the modified trait attribute\n | * ``new`` : the new value of the modified trait attribute\n | * ``name`` : the name of the modified trait attribute.\n | names : list, str, All\n | If names is All, the handler will apply to all traits. If a list\n | of str, handler will apply to all names in the list. If a\n | str, the handler will apply just to that name.\n | type : str, All (default: 'change')\n | The type of notification to filter by. If equal to All, then all\n | notifications are passed to the observe handler.\n | \n | on_trait_change(self, handler=None, name=None, remove=False)\n | DEPRECATED: Setup a handler to be called when a trait changes.\n | \n | This is used to setup dynamic notifications of trait changes.\n | \n | Static handlers can be created by creating methods on a HasTraits\n | subclass with the naming convention '_[traitname]_changed'. Thus,\n | to create static handler for the trait 'a', create the method\n | _a_changed(self, name, old, new) (fewer arguments can be used, see\n | below).\n | \n | If `remove` is True and `handler` is not specified, all change\n | handlers for the specified name are uninstalled.\n | \n | Parameters\n | ----------\n | handler : callable, None\n | A callable that is called when a trait changes. Its\n | signature can be handler(), handler(name), handler(name, new),\n | handler(name, old, new), or handler(name, old, new, self).\n | name : list, str, None\n | If None, the handler will apply to all traits. If a list\n | of str, handler will apply to all names in the list. If a\n | str, the handler will apply just to that name.\n | remove : bool\n | If False (the default), then install the handler. If True\n | then unintall it.\n | \n | set_trait(self, name, value)\n | Forcibly sets trait attribute, including read-only attributes.\n | \n | setup_instance(self, *args, **kwargs)\n | \n | trait_metadata(self, traitname, key, default=None)\n | Get metadata values for trait by key.\n | \n | trait_names(self, **metadata)\n | Get a list of all the names of this class' traits.\n | \n | traits(self, **metadata)\n | Get a ``dict`` of all the traits of this class. The dictionary\n | is keyed on the name and the values are the TraitType objects.\n | \n | The TraitTypes returned don't know anything about the values\n | that the various HasTrait's instances are holding.\n | \n | The metadata kwargs allow functions to be passed in which\n | filter traits based on metadata values. The functions should\n | take a single value as an argument and return a boolean. If\n | any function returns False, then the trait is not included in\n | the output. If a metadata key doesn't exist, None will be passed\n | to the function.\n | \n | unobserve(self, handler, names=traitlets.All, type='change')\n | Remove a trait change handler.\n | \n | This is used to unregister handlers to trait change notifications.\n | \n | Parameters\n | ----------\n | handler : callable\n | The callable called when a trait attribute changes.\n | names : list, str, All (default: All)\n | The names of the traits for which the specified handler should be\n | uninstalled. If names is All, the specified handler is uninstalled\n | from the list of notifiers corresponding to all changes.\n | type : str or All (default: 'change')\n | The type of notification to filter by. If All, the specified handler\n | is uninstalled from the list of notifiers corresponding to all types.\n | \n | unobserve_all(self, name=traitlets.All)\n | Remove trait change handlers of any type for the specified name.\n | If name is not specified, removes all trait notifiers.\n | \n | ----------------------------------------------------------------------\n | Class methods inherited from traitlets.traitlets.HasTraits:\n | \n | class_own_trait_events(cls, name) from traitlets.traitlets.MetaHasTraits\n | Get a dict of all event handlers defined on this class, not a parent.\n | \n | Works like ``event_handlers``, except for excluding traits from parents.\n | \n | class_own_traits(cls, **metadata) from traitlets.traitlets.MetaHasTraits\n | Get a dict of all the traitlets defined on this class, not a parent.\n | \n | Works like `class_traits`, except for excluding traits from parents.\n | \n | class_trait_names(cls, **metadata) from traitlets.traitlets.MetaHasTraits\n | Get a list of all the names of this class' traits.\n | \n | This method is just like the :meth:`trait_names` method,\n | but is unbound.\n | \n | class_traits(cls, **metadata) from traitlets.traitlets.MetaHasTraits\n | Get a ``dict`` of all the traits of this class. The dictionary\n | is keyed on the name and the values are the TraitType objects.\n | \n | This method is just like the :meth:`traits` method, but is unbound.\n | \n | The TraitTypes returned don't know anything about the values\n | that the various HasTrait's instances are holding.\n | \n | The metadata kwargs allow functions to be passed in which\n | filter traits based on metadata values. The functions should\n | take a single value as an argument and return a boolean. If\n | any function returns False, then the trait is not included in\n | the output. If a metadata key doesn't exist, None will be passed\n | to the function.\n | \n | trait_events(cls, name=None) from traitlets.traitlets.MetaHasTraits\n | Get a ``dict`` of all the event handlers of this class.\n | \n | Parameters\n | ----------\n | name: str (default: None)\n | The name of a trait of this class. If name is ``None`` then all\n | the event handlers of this class will be returned instead.\n | \n | Returns\n | -------\n | The event handlers associated with a trait name, or all event handlers.\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from traitlets.traitlets.HasTraits:\n | \n | cross_validation_lock\n | A contextmanager for running a block with our cross validation lock set\n | to True.\n | \n | At the end of the block, the lock's value is restored to its value\n | prior to entering the block.\n | \n | ----------------------------------------------------------------------\n | Static methods inherited from traitlets.traitlets.HasDescriptors:\n | \n | __new__(cls, *args, **kwargs)\n | \n | ----------------------------------------------------------------------\n | Data descriptors inherited from traitlets.traitlets.HasDescriptors:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n\n"
],
[
"from IPython.display import display, HTML\n\ndisplay(HTML('<link href=\"//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700\" rel=\"stylesheet\" type=\"text/css\" />'))\ndisplay(HTML('<link rel=\"stylesheet\" type=\"text/css\" href=\"http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css\">'))\n\n! pip install git+https://github.com/plotly/publisher.git --upgrade\n \nimport publisher\npublisher.publish(\n 'slider_example.ipynb', 'python/slider-widget/', 'IPython Widgets | plotly',\n 'Interacting with Plotly charts using Sliders',\n title = 'Slider Widget with Plotly',\n name = 'Slider Widget with Plotly',\n has_thumbnail='true', thumbnail='thumbnail/ipython_widgets.jpg', \n language='python', page_type='example_index', \n display_as='chart_events', order=20,\n ipynb= '~notebook_demo/91')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48e10e9bd10734f8be903f8230a19266d030fe | 8,938 | ipynb | Jupyter Notebook | insar.ipynb | snowex-hackweek/hyp3SAR | cb5586a70935443ab0733ebd9df3a9a2816fc6b5 | [
"MIT"
] | 3 | 2021-05-10T10:58:14.000Z | 2022-02-03T16:38:44.000Z | insar.ipynb | snowex-hackweek/hyp3SAR | cb5586a70935443ab0733ebd9df3a9a2816fc6b5 | [
"MIT"
] | null | null | null | insar.ipynb | snowex-hackweek/hyp3SAR | cb5586a70935443ab0733ebd9df3a9a2816fc6b5 | [
"MIT"
] | 2 | 2021-07-16T04:27:34.000Z | 2021-07-19T06:38:31.000Z | 25.683908 | 133 | 0.552696 | [
[
[
"# Process an interferogram with ASF HyP3\n\nhttps://hyp3-docs.asf.alaska.edu/using/sdk/ ",
"_____no_output_____"
],
[
"## Search for scenes\n\nscenes over grand mesa, colorado using https://asf.alaska.edu/api/",
"_____no_output_____"
]
],
[
[
"import requests\nimport shapely.geometry\n\nroi = shapely.geometry.box(-108.3,39.2,-107.8,38.8)\npolygonWKT = roi.wkt\n\nbaseurl = \"https://api.daac.asf.alaska.edu/services/search/param\"\n\ndata = dict(\n intersectsWith=polygonWKT,\n platform='Sentinel-1',\n processingLevel=\"SLC\",\n beamMode='IW',\n output='json',\n start='2020-10-30T11:59:59Z',\n end='2020-11-30T11:59:59Z',\n #relativeOrbit=None,\n #flightDirection=None,\n)\n\nr = requests.get(baseurl, params=data, timeout=100)\nprint(r.url)",
"_____no_output_____"
],
[
"# load results into pandas dataframe\nimport pandas as pd\ndf = pd.DataFrame(r.json()[0])\ndf.head()",
"_____no_output_____"
],
[
"# Easier to explore the inventory in plots\nimport hvplot.pandas\nfrom bokeh.models.formatters import DatetimeTickFormatter\n\nformatter = DatetimeTickFormatter(years='%m-%d')\ntimeseries = df.hvplot.scatter(x='startTime', y='relativeOrbit', c='relativeOrbit',\n xformatter=formatter,\n title='Acquisition times (UTC)')",
"_____no_output_____"
],
[
"import geopandas as gpd\nimport geoviews as gv\nimport panel as pn\n\ngf_aoi = gpd.GeoDataFrame(geometry=[roi])\npolygons = df.stringFootprint.apply(shapely.wkt.loads)\ngf_footprints = gpd.GeoDataFrame(df, crs=\"EPSG:4326\", geometry=polygons)\n\ntiles = gv.tile_sources.StamenTerrainRetina.options(width=600, height=400)\naoi = gf_aoi.hvplot(geo=True, fill_color=None, line_color='m', hover=False)\nfootprints = gf_footprints.hvplot.polygons(geo=True, legend=False, alpha=0.2, c='relativeOrbit', title='Sentinel-1 Tracks') \n\nmapview = tiles * footprints * aoi\n\npn.Column(mapview,timeseries)",
"_____no_output_____"
]
],
[
[
"From the plots above we can choose a pair that has:\n1. good spatial coverage of our area of interest\n2. a timespan of interest \n\nSo let's use relativeOrbit=129 2020-11-11 and 2020-10-30",
"_____no_output_____"
]
],
[
[
"df.relativeOrbit.unique()",
"_____no_output_____"
],
[
"orbit = '129'\nreference = '2020-11-11'\nsecondary = '2020-10-30'\n\ndfS = df[df.relativeOrbit == orbit]\ngranule1 = dfS.loc[dfS.sceneDate.str.startswith(reference), 'granuleName'].values[0]\ngranule2 = dfS.loc[dfS.sceneDate.str.startswith(secondary), 'granuleName'].values[0]\nprint(f'granule1: {granule1}')\nprint(f'granule2: {granule2}')",
"_____no_output_____"
],
[
"for ref in [reference, secondary]:\n print(dfS.loc[dfS.sceneDate.str.startswith(ref), 'downloadUrl'].values[0])",
"_____no_output_____"
]
],
[
[
"## Process an InSAR pair (interferogram)\n\nexamples:\n- https://nbviewer.jupyter.org/github/ASFHyP3/hyp3-sdk/blob/main/docs/sdk_example.ipynb\n- https://hyp3-docs.asf.alaska.edu/using/sdk/",
"_____no_output_____"
]
],
[
[
"import hyp3_sdk",
"_____no_output_____"
],
[
"# ~/.netrc file used for credentials\nhyp3 = hyp3_sdk.HyP3()",
"_____no_output_____"
],
[
"# Processing quota\nhyp3.check_quota() #199 (200 scenes per month?)",
"_____no_output_____"
],
[
"job = hyp3.submit_insar_job(granule1,\n granule2,\n name='gm_20201111_20201030', \n include_los_displacement=True, \n include_inc_map=True)",
"_____no_output_____"
],
[
"# All jobs you've submitted\n# NOTE: processing w/ defaults uses INSAR_GAMMA \n# NOTE: re-run this cell to update results of batch job\nbatch = hyp3.find_jobs()\njob = batch.jobs[0] # most recent job\njob",
"_____no_output_____"
],
[
"# If you have lists of dictionaries, visualizing with a pandas dataframe is convenient\ndf = pd.DataFrame([job.to_dict() for job in batch])\ndf.head()",
"_____no_output_____"
],
[
"# Actually no, expiration time is not available for download...\n#pd.to_datetime(df.expiration_time[0]) - pd.to_datetime(df.request_time[0])",
"_____no_output_____"
],
[
"# ImportError: IProgress not found. Please update jupyter and ipywidgets.\n# but I think this still succeeeds\njob.download_files()",
"_____no_output_____"
],
[
"!ls -ltrh",
"_____no_output_____"
],
[
"# requires ipywidgets\n#hyp3.watch(job)",
"_____no_output_____"
]
],
[
[
"## Process multiple pairs in batch mode",
"_____no_output_____"
]
],
[
[
"# with progress bar\n#from tqdm.auto import tqdm \n\n#insar_jobs = sdk.Batch()\n#for reference in tqdm(granules):\n# neighbors_metadata = asf_search.get_nearest_neighbors(reference, max_neighbors=2)\n# for secondary_metadata in neighbors_metadata:\n# insar_jobs += hyp3.submit_insar_job(reference, secondary_metadata['granuleName'], name='insar-example')\n#print(insar_jobs)",
"_____no_output_____"
],
[
"# Can also submit jobs via web interface # Can also visit https://hyp3.asf.alaska.edu/pending_products \n# Which then shows logs that can be sorted into 'submitted, failed, etc...'",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"raw",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"raw"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48e23f96f6bc35f8ab3e3a2c0c65ca2d02f868 | 146,285 | ipynb | Jupyter Notebook | _site/week09/prep_notebook_week09.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2019-08-11T04:03:24.000Z | 2019-08-11T04:03:24.000Z | _site/week09/prep_notebook_week09.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2020-03-02T00:11:33.000Z | 2020-03-02T00:11:33.000Z | _site/week09/prep_notebook_week09.ipynb | UIUC-iSchool-DataViz/spring2019online | e586cfafd90d6de38c308bf8ad072c9a4ed8485b | [
"BSD-3-Clause"
] | 1 | 2020-03-09T16:13:34.000Z | 2020-03-09T16:13:34.000Z | 40.600888 | 871 | 0.393834 | [
[
[
"# Activity #1: MarketMap\n* another way to visualize mappable data",
"_____no_output_____"
],
[
"## 1.a : explore the dataset",
"_____no_output_____"
]
],
[
[
"# our usual stuff\n%matplotlib inline\nimport pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"#!pip install xlrd # JPN, might have to run this\n\n# note: this is quering from the web! How neat is that??\ndf = pd.read_excel('https://query.data.world/s/ivl45pdpubos6jpsii3djsjwm2pcjv', skiprows=5)\n# the above might take a while to load all the data",
"_____no_output_____"
],
[
"# what is in this dataframe? lets take a look at the top\ndf.head()\n# this dataset is called: \"Surgery Charges Across the U.S.\"\n# and its just showing us how much different procedures \n# cost from different hospitals",
"_____no_output_____"
],
[
"# what kinds of data are we working with?\ndf.dtypes",
"_____no_output_____"
],
[
"# lets look at some summary data\n# recall: this is like R's \"summary\" function\ndf.describe()\n# so, things like the mean zipcode aren't\n# meaningful, same thing with provider ID\n# But certainly looking at the average\n# total payments, discharges, might \n# be useful",
"_____no_output_____"
],
[
"# lets look at how many seperate types of surgery are \n# represented in this dataset:\ndf[\"DRG Definition\"].unique().size",
"_____no_output_____"
],
[
"# what about how many provider (hospital) names?\ndf[\"Provider Name\"].unique().size",
"_____no_output_____"
],
[
"# how many states are represented\ndf[\"Provider State\"].unique().size",
"_____no_output_____"
],
[
"# what are the state codes?\ndf[\"Provider State\"].unique()",
"_____no_output_____"
],
[
"# lets figure out what the most common surgeries are via how \n# many many folks are discharged after each type of surgery\n# (1)\nmost_common = df.groupby(\"DRG Definition\")[\"Total Discharges\"].sum()\nmost_common\n\n# (2) but lets sort by the largest on top\nmost_common = df.groupby(\"DRG Definition\")[\"Total Discharges\"].sum().sort_values(ascending=False)\nmost_common\n\n# (3) lets look at only the top 5, for fun\nmost_common[:5]\n\n# (4) or we can only look at the names of the top 5:\nmost_common[:5].index.values",
"_____no_output_____"
]
],
[
[
"## 1.b: formatting data for MarketMap\n* here we are going to practice doing some fancy things to clean this data\n* this will be good practice for when you run into other datasets \"in the wild\"",
"_____no_output_____"
]
],
[
[
"# (1) lets create a little table of total discharges for\n# each type of surgery & state\ntotal_discharges = df.groupby([\"DRG Definition\", \"Provider State\"])[\"Total Discharges\"].sum()\ntotal_discharges\n\n# (2) the above is not intuative, lets prettify it\ntotal_discharges = df.groupby([\"DRG Definition\", \"Provider State\"])[\"Total Discharges\"].sum().unstack()\ntotal_discharges",
"_____no_output_____"
]
],
[
[
"### Aside: lets quick check out what are the most frequent surgeries",
"_____no_output_____"
]
],
[
[
"# for our map, we are going to want to \n# normalize the discharges or each surgery \n# for each \n# state by the total discharges across all \n# states for a particular type of surger\n# lets add this to our total_discharges DF\ntotal_discharges[\"Total\"] = total_discharges.sum(axis = 1)\ntotal_discharges[\"Total\"].head() # just look at the first few",
"_____no_output_____"
],
[
"# finally, lets check out the most often\n# performed surgery across all states\n\n# we can do this by sorting our DF by this total we just\n# calculated:\ntotal_discharges.sort_values(by = \"Total\", \n ascending=False, \n inplace = True)\n\n# now lets just look at the first few of our \n# sorted array\ntotal_discharges.head()\n\n# so, from this we see that joint replacement\n# or reattachment of a lower extremeity is \n# the most likely surgery (in number of discharges)\n# followed by surgeries for sepsis and then heart failure",
"_____no_output_____"
],
[
"# neat. We won't need these for plotting, so we can remove our\n# total column we just calculated\ndel total_discharges[\"Total\"]\ntotal_discharges.head()\n# now we see that we are back to just states & surgeries\n# *but* our sorting is still by the total that we \n# previously calculated.\n# spiffy!",
"_____no_output_____"
]
],
[
[
"## 1.c: plot data with bqplot",
"_____no_output_____"
]
],
[
[
"import bqplot\n# by default bqplot does not import \n# all packages, we have to \n# explicitely import market_map\nimport bqplot.market_map # for access to market_map",
"_____no_output_____"
],
[
"# lets do our usual thing, but with a market map\n# instead of a heat map\n\n# scales:\nx_sc, y_sc = bqplot.OrdinalScale(), bqplot.OrdinalScale() # note, just a different way to call things\nc_sc = bqplot.ColorScale(scheme=\"Blues\")\n\n# just a color axes for now:\nc_ax = bqplot.ColorAxis(scale = c_sc, orientation = 'vertical')\n\n# lets make the market map:\n\n# (1) what should we plot for our color? lets take a look:\ntotal_discharges.iloc[0].values, total_discharges.columns.values\n# this is the total discharges for the most \n# popular surgical procedure\n# the columns will be states\n\n# (2) lets put this into a map\nmmap = bqplot.market_map.MarketMap(color = total_discharges.iloc[0].values, \n names = total_discharges.columns.values,\n scales={'color':c_sc}, \n axes=[c_ax])\n\n# (3) ok, but just clicking on things doesn't tell us too much\n# lets add a little label to print out the total of the selected\nimport ipywidgets\nlabel = ipywidgets.Label()\n# link to market map\ndef get_data(change):\n # (3.1)\n #print(change['owner'].selected)\n # (3.2) loop\n v = 0.0 # to store total value\n for s in change['owner'].selected:\n v += total_discharges.iloc[0][total_discharges.iloc[0].index == s].values\n if v > 0: # in case nothing is selected\n # what are we printing?\n l = 'Total discharges of ' + \\\n total_discharges.iloc[0].name + \\\n ' = ' + str(v[0]) # note: v is by default an array\n label.value = l \n \nmmap.observe(get_data,'selected')\n \n#mmap\n\n# (3)\nipywidgets.VBox([label,mmap])",
"_____no_output_____"
]
],
[
[
"## Discussion:\n* think back to the map we had last week: we can certainly plot this information with a more geo-realistic map\n* what are the pros & cons of each style of map? What do each highlight? How are each biased?",
"_____no_output_____"
],
[
"## IF we have time: Re-do with other mapping system:",
"_____no_output_____"
]
],
[
[
"from us_state_abbrev import us_state_abbrev\n\nsc_geo = bqplot.AlbersUSA()\nstate_data = bqplot.topo_load('map_data/USStatesMap.json')\n\n#(1)\n#states_map = bqplot.Map(map_data=state_data, scales={'projection':sc_geo})\n\n#(2)\n# library from last time\nfrom states_utils import get_ids_and_names\nids, state_names = get_ids_and_names(states_map)\n\n# color maps\nimport matplotlib.cm as cm\ncmap = cm.Blues\n\n# most popular surgery\npopSurg = total_discharges.iloc[0]\n\n# here, we will go through the process of getting colors to plot\n# each state with its similar color to the marketmap above:\n\n#!pip install webcolors\nfrom webcolors import rgb_to_hex\nd = {} # empty dict to store colors\nfor s in states_map.map_data['objects']['subunits']['geometries']:\n if s['properties'] is not None:\n #print(s['properties']['name'], s['id'])\n # match states to abbreviations\n state_abbrev = us_state_abbrev[s['properties']['name']]\n #print(state_abbrev)\n v = popSurg[popSurg.index == state_abbrev].values[0]\n # renorm v to colors and then number of states\n v = (v - popSurg.values.min())/(popSurg.values.max()-popSurg.values.min())\n #print(v, int(cmap(v)[0]), int(cmap(v)[1]), int(cmap(v)[2]))\n # convert to from 0-1 to 0-255 rgbs\n c = [int(cmap(v)[i]*255) for i in range(3)]\n #d[s['id']] = rgb_to_hex([int(cmap(v)[0]*255), int(cmap(v)[1]*255), int(cmap(v)[2]*255)])\n d[s['id']] = rgb_to_hex(c)\n \n \ndef_tt = bqplot.Tooltip(fields=['name'])\n \nstates_map = bqplot.Map(map_data=state_data, scales={'projection':sc_geo}, colors = d, tooltip=def_tt)\n# add interactions\nstates_map.interactions = {'click': 'select', 'hover': 'tooltip'}\n\n# (3)\nlabel = ipywidgets.Label()\n# link to heat map\ndef get_data(change):\n v = 0.0 # to store total value\n if change['owner'].selected is not None:\n for s in change['owner'].selected:\n #print(s)\n sn = state_names[s == ids][0]\n state_abbrev = us_state_abbrev[sn]\n v += popSurg[popSurg.index == state_abbrev].values[0]\n if v > 0: # in case nothing is selected\n # what are we printing?\n l = 'Total discharges of ' + \\\n popSurg.name + \\\n ' = ' + str(v) # note: v is by default an array\n label.value = l \n \nstates_map.observe(get_data,'selected')\n\nfig=bqplot.Figure(marks=[states_map], \n title='US States Map Example',\n fig_margin={'top': 0, 'bottom': 0, 'left': 0, 'right': 0}) # try w/o first and see\n#fig\n# (3)\nipywidgets.VBox([label,fig])",
"_____no_output_____"
]
],
[
[
"# Activity #2: Real quick ipyleaflets\n* since cartopy wasn't working for folks, we'll quickly look at another option: ipyleaflets",
"_____no_output_____"
]
],
[
[
"#!pip install ipyleaflet\nfrom ipyleaflet import *\n# note: you might have to close and reopen you notebook\n# to see the map\n\nm = Map(center=(52, 10), zoom=8, basemap=basemaps.Hydda.Full)\n\n#(2) street maps\nstrata_all = basemap_to_tiles(basemaps.Strava.All)\nm.add_layer(strata_all)\nm",
"_____no_output_____"
]
],
[
[
"### Note: more examples available here - https://github.com/jupyter-widgets/ipyleaflet/tree/master/examples",
"_____no_output_____"
],
[
"# Activity #3: Networked data - Simple example\n",
"_____no_output_____"
]
],
[
[
"# lets start with some very basic node data\n# **copy paste into chat **\nnode_data = [\n {\"label\": \"Luke Skywalker\", \"media\": \"Star Wars\", \"shape\": \"rect\"},\n {\"label\": \"Jean-Luc Picard\", \"media\": \"Star Trek\", \"shape\": \"rect\"},\n {\"label\": \"Doctor Who\", \"media\": \"Doctor Who\", \"shape\": \"rect\"},\n {\"label\": \"Pikachu\", \"media\": \"Detective Pikachu\", \"shape\": \"circle\"},\n]\n\n# we'll use bqplot.Graph to plot these\ngraph = bqplot.Graph(node_data=node_data,\n colors = [\"red\", \"red\", \"red\", \"red\"])\n\nfig = bqplot.Figure(marks = [graph])\nfig\n\n# you note I can pick them up and move them around, but they aren't connected in any way\n# lets make some connections",
"_____no_output_____"
],
[
"node_data = [\n {\"label\": \"Luke Skywalker\", \"media\": \"Star Wars\", \"shape\": \"rect\"},\n {\"label\": \"Jean-Luc Picard\", \"media\": \"Star Trek\", \"shape\": \"rect\"},\n {\"label\": \"Doctor Who\", \"media\": \"Doctor Who\", \"shape\": \"rect\"},\n {\"label\": \"Pikachu\", \"media\": \"Detective Pikachu\", \"shape\": \"circle\"},\n]\n\n# lets link the 0th entry (luke skywalker) to both\n# jean-luc picard (1th entry) and pikachu (3rd entry)\nlink_data = [{'source': 0, 'target': 1}, {'source': 0, 'target': 3}]\n\ngraph = bqplot.Graph(node_data=node_data, link_data=link_data, \n colors = [\"red\", \"red\", \"red\", \"red\"])\n\n#(2) we can also play with the springiness of our links:\ngraph.charge = -300 # setting it to positive makes them want to overlap and is, ingeneral, a lot of fun\n# -300 is default\n\n# (3) we can also change the link type:\ngraph.link_type = 'line' # arc = default, line, slant_line\n\n# (4) highlight link direction, or not\ngraph.directed = False\n\nfig = bqplot.Figure(marks = [graph])\nfig",
"_____no_output_____"
],
[
"# we can do all the same things we've done with\n# our previous map plots:\n# for example, we can add a tooltip:\n#(1)\ntooltip = bqplot.Tooltip(fields=[\"media\"])\ngraph = bqplot.Graph(node_data=node_data, link_data=link_data, \n colors = [\"red\", \"red\", \"red\", \"red\"],\n tooltip=tooltip)\n\n# we can also do interactive things with labels\nlabel = ipywidgets.Label()\n\n# note here that the calling sequence \n# is a little different - instead \n# of \"change\" we have \"obj\" and \n# \"element\"\ndef printstuff(obj, element):\n # (1.1)\n #print(obj)\n #print(element)\n label.value = 'Media = ' + element['data']['media']\n \ngraph.on_element_click(printstuff)\n\n\nfig = bqplot.Figure(marks = [graph])\nipywidgets.VBox([label,fig])",
"_____no_output_____"
]
],
[
[
"# Activity #4: Network data - subset of facebook friends dataset\n* from: https://snap.stanford.edu/data/egonets-Facebook.html\n* dataset of friends lists\n\n#### Info about this dataset:\n* the original file you can read in has about 80,000 different connections\n* it is ordered by the most connected person (person 0) at the top\n* because this network would be computationally slow and just a hairball - we're going to be working with downsampled data\n* for example, a file tagged \"000090_000010\" starts with the 10th most connected person, and only included connections up to the 90th most connected person\n* Its worth noting that this dataset (linked here and on the webpage) also includes feature data like gender, last name, school, etc - however it is too sparse to be of visualization use to us\n\nCheck out the other social network links at the SNAP data webpage!",
"_____no_output_____"
]
],
[
[
"# from 10 to 150 connections, a few large nodes\n#filename = 'facebook_combined_sm000150_000010.txt'\n\n# this might be too large: one large node, up to 100 connections\n#filename='facebook_combined_sm000100.txt'\n\n# start here\nfilename = 'facebook_combined_sm000090_000010.txt'\n\n# then this one\n#filename = 'facebook_combined_sm000030_000000.txt'\n# note how different the topologies are\n\nnetwork = pd.read_csv('/Users/jillnaiman1/Downloads/'+filename,\n sep=' ', names=['ind1', 'ind2'])\nnetwork",
"_____no_output_____"
],
[
"# build the network\nnode_data = []\nlink_data = []\ncolor_data = [] # all same color\n\n# add nodes\nmaxNet = max([network['ind1'].max(),network['ind2'].max()])\nfor i in range(maxNet+1):\n node_data.append({\"label\": str(i), 'shape_attrs': {'r': 8} }) # small circles\n \n# now, make links\nfor i in range(len(network)):\n # we are linking the ith object to another jth object, but we \n # gotta figure out with jth object it is\n source_id = network.iloc[i]['ind1']\n target_id = network.iloc[i]['ind2']\n link_data.append({'source': source_id, 'target': target_id})\n color_data.append('blue')\n \n#link_data,node_data\n#color_data",
"_____no_output_____"
],
[
"# plot\n\ngraph = bqplot.Graph(node_data=node_data, \n link_data = link_data,\n colors=color_data)\n\n# play with these for different graphs\ngraph.charge = -100 \ngraph.link_type = 'line'\ngraph.link_distance=50\n# there is no direction to links\ngraph.directed = False\n\nfig = bqplot.Figure(marks = [graph])\nfig.layout.min_width='1000px'\nfig.layout.min_height='900px'\n# note: I think this has to be the layout for this to look right\nfig\n\n# in theory, we could color this network by what school folks are in, or some such\n# but while the dataset does contain some of these features, the \n# answer rate is too sparse for our subset here",
"_____no_output_____"
]
],
[
[
"# Note: the below is just prep if you want to make your own subset datasets",
"_____no_output_____"
]
],
[
[
"# prep fb data by downsampling\nminCon = 0\nmaxCon = 30\nG = pd.read_csv('/Users/jillnaiman1/Downloads/facebook_combined.txt',sep=' ', names=['ind1', 'ind2'])\nGnew = np.zeros([2],dtype='int')\n# loop and append\nGnew = G.loc[G['ind1']==minCon].values[0]\nfor i in xrange(G.loc[G['ind1']==minCon].index[0],len(G)):\n gl = G.loc[i].values\n if (gl[0] <= maxCon) and (gl[1] <= maxCon) and (gl[0] >= minCon) and (gl[1] >= minCon):\n Gnew = np.vstack((Gnew,gl))\n\nnp.savetxt('/Users/jillnaiman1/spring2019online/week09/data/facebook_combined_sm' + \\\n str(maxCon).zfill(6) + '_' + str(minCon).zfill(6) + '.txt', Gnew,fmt='%i')",
"_____no_output_____"
],
[
"graph.link_distance",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb48eca36e71e8bd3e9981f21f1468cb98accac2 | 10,176 | ipynb | Jupyter Notebook | labs/lab-5/notebooks/basic_rdd.ipynb | tomdewildt/data-engineering | bdfb6ab0676846f1f027db5bd825b5b7d16ae2c7 | [
"MIT"
] | null | null | null | labs/lab-5/notebooks/basic_rdd.ipynb | tomdewildt/data-engineering | bdfb6ab0676846f1f027db5bd825b5b7d16ae2c7 | [
"MIT"
] | 7 | 2021-11-05T12:39:48.000Z | 2021-12-24T11:48:13.000Z | labs/lab-5/notebooks/basic_rdd.ipynb | tomdewildt/data-engineering | bdfb6ab0676846f1f027db5bd825b5b7d16ae2c7 | [
"MIT"
] | null | null | null | 23.501155 | 903 | 0.443396 | [
[
[
"from pyspark.sql import SparkSession",
"_____no_output_____"
],
[
"spark = SparkSession.builder.appName(\"RDD_Lab\").master(\"spark://master:7077\").getOrCreate() ",
"_____no_output_____"
],
[
"# A SparkContext represents the connection to a Spark cluster, and can be used to create RDDs, accumulators and broadcast variables on that cluster.\nsc = spark.sparkContext\nsc.setLogLevel(\"FATAL\")",
"_____no_output_____"
],
[
"data = [1, 2, 3, 4, 5]\ndata_rdd = spark.sparkContext.parallelize(data) # Create a RDD from an array \ndata_rdd = data_rdd.map(lambda x: x*x) # Apply a transformation\n\nprint(data_rdd.collect()) # Collection data",
"[1, 4, 9, 16, 25]\n"
],
[
"lines_rdd = spark.sparkContext.textFile(\"../data/wordcount.txt\") # Create a RDD from a text file\n\n# Differences between Flatmap and Map\nprint(lines_rdd.map(lambda x: x.split(' ')).take(5))\nprint(\"\\n\")\nprint(lines_rdd.flatMap(lambda x: x.split(' ')).take(5))",
"[[\"We've\", 'all', 'heard', 'the', 'scare', 'stories', 'about', 'North', 'Korea:', 'the', 'homemade', 'nuclear', 'arsenal', 'built', 'while', 'their', 'people', 'starve', 'and', 'then', 'aimed', 'imprecisely', 'at', 'the', 'rest', 'of', 'the', 'world,', 'a', ''], ['leader', 'so', 'deluded', 'he', 'makes', 'L', 'Ron', 'Hubbard', 'look', 'like', 'a', 'man', 'excessively', 'overburdened', 'with', 'self-doubt', 'and', 'their', 'deep-seated', 'belief', 'that', 'foreign', 'capitalists', 'will', 'invade', 'at', 'any', ''], ['moment', 'and', 'steal', 'all', 'their', 'bauxite.'], ['The', 'popular', 'portrayal', 'of', 'this', 'Marxist', 'nation', 'is', 'something', 'like', 'one', 'of', 'the', 'more', 'harrowing', 'episodes', 'of', 'M*A*S*H,', 'only', 'with', 'the', 'cast', 'of', 'wacky', 'characters', 'replaced', 'by', 'twitchy,', ''], ['heavily', 'armed', 'Stalinist', 'meth', 'addicts']]\n\n\n[\"We've\", 'all', 'heard', 'the', 'scare']\n"
],
[
"from operator import add",
"_____no_output_____"
],
[
"# https://spark.apache.org/docs/latest/rdd-programming-guide.html#passing-functions-to-spark\ndef myMapFun(x):\n return (x, 1)",
"_____no_output_____"
],
[
"# Word Couting MapReduce\ncounts = lines_rdd.flatMap(lambda x: x.split(' ')).map(myMapFun).reduceByKey(add)\n\noutput = counts.collect()",
"_____no_output_____"
],
[
"for (word, count) in output:\n print(\"%s: %i\" % (word, count))",
"heard: 1\nNorth: 5\nhomemade: 1\nnuclear: 1\nstarve: 1\nimprecisely: 1\nat: 4\nrest: 1\nof: 11\nworld,: 1\n: 11\nleader: 2\nhe: 2\nL: 1\nRon: 1\nlook: 1\nlike: 4\nself-doubt: 1\ndeep-seated: 1\nbelief: 1\nforeign: 1\ninvade: 1\nsteal: 1\nbauxite.: 1\nThe: 1\nportrayal: 1\nthis: 2\nMarxist: 1\nnation: 1\nis: 2\nsomething: 1\nmore: 2\nM*A*S*H,: 1\nonly: 1\ncast: 1\ncharacters: 1\nreplaced: 1\ntwitchy,: 1\nheavily: 1\narmed: 1\nStalinist: 1\nmeth: 1\nCracked: 1\nwould: 2\ntake: 1\ngood: 1\nthings: 2\nKorea: 2\nthough,: 1\ncountry's: 1\nsuppress: 1\nas: 1\nmotivated: 1\njealousy.: 1\nno: 1\ndifferent: 1\nthere's: 1\nKorean: 1\nlikes: 1\nafter: 1\nan: 1\nplant: 1\nthan: 1\nnice: 1\ngo: 1\nhis: 2\ndried: 1\nfish: 1\nattentive: 1\npeople's: 1\nneeds: 1\nin: 2\ntwinkling: 1\nKorea's: 1\nleadership: 1\nbought,: 1\ntransported: 1\nrebuilt: 1\ndiscover: 1\nreproduce: 1\nsecrets: 1\nsweet: 1\npeople,: 1\nbottles: 1\nAnd: 3\nWhen: 1\nwas: 1\nlast: 1\nYOUR: 1\ngot: 1\nYOU,: 1\ndo: 1\nquestion: 1\nare: 1\nOr: 1\nrestaurant: 1\nsleeping: 1\noptional: 1\neven: 2\nhave: 1\nremove: 1\nout: 1\nAmericans: 1\nmust: 1\nvery: 1\nseasoning: 1\nused: 1\nintentionally: 1\nkept: 1\nthem.: 1\ncall: 1\nnations: 1\nbourgeois: 1\nBill: 1\nClinton: 1\nlet: 1\nanywhere: 1\nnear: 1\nwomenfolk?: 1\npast: 1\nBill's: 1\nmany,: 1\nimperfections: 1\ntreat: 1\npity: 1\naccepting: 1\npleas: 1\npardon: 1\nAmerican: 1\nspies: 1\nrightly: 1\nconvicted: 1\nsensitive: 1\nfields.: 1\nWe've: 1\nall: 2\nthe: 22\nscare: 1\nstories: 1\nabout: 3\nKorea:: 1\narsenal: 1\nbuilt: 1\nwhile: 1\ntheir: 6\npeople: 1\nand: 11\nthen: 3\naimed: 1\na: 10\nso: 2\ndeluded: 1\nmakes: 1\nHubbard: 1\nman: 1\nexcessively: 1\noverburdened: 1\nwith: 6\nthat: 4\ncapitalists: 1\nwill: 1\nany: 1\nmoment: 2\npopular: 1\none: 1\nharrowing: 1\nepisodes: 1\nwacky: 1\nby: 2\naddicts: 1\nto: 11\ncelebrate: 1\nenemies: 1\nprefer: 1\npart: 1\npolitically: 1\nLike: 1\nhow: 3\nyou: 3\nme,: 1\nnothing: 1\nevery: 1\n18: 2\nhour: 1\nshift: 1\nphosphorus: 1\nbeer: 4\nration.: 1\nEver: 1\nits: 2\ndecade,: 1\ndisassembled,: 1\nBritish: 1\nbrewery: 1\norder: 1\nbrew: 1\nnectar: 1\nfor: 2\nhardworking: 1\nup: 1\ntime.: 1\nminimal: 1\nfatalities.: 1\ntime: 1\nAmerican?: 1\n(NB: 1\nnot: 1\nanswer: 1\nif: 2\nHenry: 1\nLouis: 1\nGates).: 1\nfried: 3\nchicken: 2\ndowntown: 1\nPyongyang: 1\nboasts?: 1\nYes: 1\nreal: 1\nchicken,: 1\ndelivered: 1\nyour: 1\ncube,: 1\nlike!: 1\nYou: 1\ndon't: 1\nfeathers: 1\nor: 1\npull: 1\ngizzard: 1\nyourself.: 1\nMostly.: 1\neat: 1\nfrom: 2\nbucket,: 1\nswine,: 1\nsold: 1\ncompany: 1\nsecretive: 1\nblend: 1\nthey: 1\nparanoid?: 1\nmany: 2\nentertain: 1\nsyphilitic,: 1\nramblings: 1\nalone: 1\npermit: 1\nhim: 2\nproud: 1\nOnly: 1\nwise: 1\nKim: 1\nJong: 1\nIl: 1\ncould: 1\nsee: 1\nkindness: 1\ndeserves,: 1\nfeeble: 1\nphotographing: 1\nnation's: 1\nbeetroot: 1\n"
],
[
"# Stop the spark context\nspark.stop()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb48fc04ad1339af7eb69ca7b08eeaf43f53a3d0 | 228,620 | ipynb | Jupyter Notebook | prefilter_for_EMG_signal.ipynb | vasilevIT/emg-interface | e282aa07051a81c8abec800e244a91d1f8e7fdd7 | [
"MIT"
] | 1 | 2021-09-20T05:25:16.000Z | 2021-09-20T05:25:16.000Z | prefilter_for_EMG_signal.ipynb | vasilevIT/emg-interface | e282aa07051a81c8abec800e244a91d1f8e7fdd7 | [
"MIT"
] | null | null | null | prefilter_for_EMG_signal.ipynb | vasilevIT/emg-interface | e282aa07051a81c8abec800e244a91d1f8e7fdd7 | [
"MIT"
] | null | null | null | 205.040359 | 36,512 | 0.863127 | [
[
[
"import sys\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\" #for training on gpu\n\nfrom scipy import signal\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport time\nfrom random import shuffle\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense, Conv1D, MaxPooling1D, Dropout, GlobalAveragePooling1D, Reshape\n\n#path to data files\npath = \"./nine_movs_six_sub_split/\"\n\n#path where you want to save trained model and some other files\nsec_path = \"./\"\n\ndef create_dataset(file_path, persons):\n path = file_path + \"{}_{}.txt\"\n sgn = []\n lbl = []\n for i in persons:\n for j in range(9):\n with open(path.format(i, j + 1), \"rb\") as fp: # Unpickling\n data = pickle.load(fp)\n\n for k in range(np.shape(data)[0]):\n sgn.append(data[k])\n lbl.append(j)\n\n sgn = np.asarray(sgn, dtype=np.float32)\n lbl = np.asarray(lbl, dtype=np.int32)\n\n c = list(zip(sgn, lbl))\n shuffle(c)\n sgn, lbl = zip(*c)\n\n sgn = np.asarray(sgn, dtype=np.float64)\n lbl = np.asarray(lbl, dtype=np.int64)\n\n print(sgn.shape)\n\n train_signals = sgn[0:int(0.8 * len(sgn))]\n train_labels = lbl[0:int(0.8 * len(lbl))]\n val_signals = sgn[int(0.8*len(sgn)):]\n val_labels = lbl[int(0.8*len(lbl)):]\n #test_signals = sgn[int(0.8*len(sgn)):]\n #test_labels = lbl[int(0.8*len(lbl)):]\n\n train_labels = to_categorical(train_labels)\n val_labels = to_categorical(val_labels)\n #test_labels = to_categorical(test_labels)\n\n return train_signals, train_labels, val_signals, val_labels\n\ndef create_dataset2(file_path, persons):\n path = file_path + \"{}_{}.txt\"\n sgn = []\n lbl = []\n i = persons\n for j in range(9):\n with open(path.format(i, j + 1), \"rb\") as fp: # Unpickling\n data = pickle.load(fp)\n\n for k in range(np.shape(data)[0]):\n sgn.append(data[k])\n lbl.append(j)\n\n sgn = np.asarray(sgn, dtype=np.float32)\n lbl = np.asarray(lbl, dtype=np.int32)\n\n c = list(zip(sgn, lbl))\n shuffle(c)\n sgn, lbl = zip(*c)\n\n sgn = np.asarray(sgn, dtype=np.float64)\n lbl = np.asarray(lbl, dtype=np.int64)\n\n print(sgn.shape)\n\n train_signals = sgn[0:int(0.6 * len(sgn))]\n train_labels = lbl[0:int(0.6 * len(lbl))]\n val_signals = sgn[int(0.6*len(sgn)):int(0.8*len(sgn))]\n val_labels = lbl[int(0.6*len(lbl)):int(0.8*len(lbl))]\n test_signals = sgn[int(0.8*len(sgn)):]\n test_labels = lbl[int(0.8*len(lbl)):]\n\n train_labels = to_categorical(train_labels)\n val_labels = to_categorical(val_labels)\n test_labels = to_categorical(test_labels)\n\n return train_signals, train_labels, val_signals, val_labels, test_signals, test_labels\n\n\ndef evaluate_model(model, expected_person_index = 2):\n print(\"evaluate_model, expected_person_index:\", expected_person_index)\n persons = [1, 2, 3, 4, 5, 6]\n persons.remove(expected_person_index)\n train_signals, train_labels, val_signals, val_labels = create_dataset(path, persons)\n model.evaluate(train_signals, train_labels)\n\n train_signals, train_labels, val_signals, val_labels, test_signals, test_labels = create_dataset2(path, expected_person_index)\n model.evaluate(train_signals, train_labels)\n\n \ndef plot_history(history):\n plt.figure(figsize=(10,6))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n plt.xlabel('Эпоха')\n plt.ylabel('Вероятность корректного распознавания')\n #plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n plt.grid(True)\n print(history.history['val_accuracy'])\n\n# training model on 5 form 6 persons\na = [1, 3, 4, 5, 6]\ntrain_signals, train_labels, val_signals, val_labels = create_dataset(path, a)",
"(2329, 400)\n"
],
[
"num_classes = 9\nnum_sensors = 1\ninput_size = train_signals.shape[1]\n\nmodel = Sequential()\nmodel.add(Reshape((input_size, num_sensors), input_shape=(input_size, )))\nmodel.add(Conv1D(50, 10, activation='relu', input_shape=(input_size, num_sensors)))\nmodel.add(Conv1D(25, 10, activation='relu'))\nmodel.add(MaxPooling1D(4))\nmodel.add(Conv1D(100, 10, activation='relu'))\nmodel.add(Conv1D(50, 10, activation='relu'))\nmodel.add(MaxPooling1D(4))\nmodel.add(Dropout(0.5))\n#next layers will be retrained\nmodel.add(Conv1D(100, 10, activation='relu'))\nmodel.add(GlobalAveragePooling1D())\nmodel.add(Dense(num_classes, activation='softmax'))\n\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n\n#elapsed_time = time.time() - start_time # training time\n\n#loss, accuracy = model.evaluate(val_signals, val_labels) # evaluating model on test data\n\n#loss = float(\"{0:.3f}\".format(loss))\n#accuracy = float(\"{0:.3f}\".format(accuracy))\n#elapsed_time = float(\"{0:.3f}\".format(elapsed_time))\n\n#saving some data\n#f = open(sec_path + \"info.txt\", 'w')\n#f.writelines([\"loss: \", str(loss), '\\n', \"accuracy: \", str(accuracy), '\\n', \"elapsed_time: \", str(elapsed_time), '\\n'])\n\n#saving model\n#model.save(sec_path + \"pretrained_model.h5\")\n\n#saving test data just in case\n#cc = list(zip(test_signals, test_labels))\n#with open(sec_path + \"pretrained_model_test_data.txt\", \"wb\") as fp:\n# pickle.dump(cc, fp)\n\n#saving history\n#with open(sec_path + \"pretrained_model_history.h5\", \"wb\") as fp:\n# pickle.dump(history.history, fp)\n",
"2022-01-06 20:10:56.148494: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA\nTo enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
],
[
"start_time = time.time()\n\nhistory = model.fit(train_signals, train_labels,\n steps_per_epoch=25,\n epochs=100,\n batch_size=None,\n validation_data=(val_signals, val_labels),\n #validation_steps=25\n)",
"Epoch 1/100\n25/25 [==============================] - 3s 86ms/step - loss: 2.1581 - accuracy: 0.1487 - val_loss: 1.9669 - val_accuracy: 0.2146\nEpoch 2/100\n25/25 [==============================] - 2s 78ms/step - loss: 1.8916 - accuracy: 0.2281 - val_loss: 1.7577 - val_accuracy: 0.2682\nEpoch 3/100\n25/25 [==============================] - 2s 78ms/step - loss: 1.7073 - accuracy: 0.3344 - val_loss: 1.6691 - val_accuracy: 0.3562\nEpoch 4/100\n25/25 [==============================] - 2s 80ms/step - loss: 1.5775 - accuracy: 0.4031 - val_loss: 1.3731 - val_accuracy: 0.4979\nEpoch 5/100\n25/25 [==============================] - 2s 77ms/step - loss: 1.3252 - accuracy: 0.5105 - val_loss: 1.3125 - val_accuracy: 0.5021\nEpoch 6/100\n25/25 [==============================] - 2s 80ms/step - loss: 1.1806 - accuracy: 0.5813 - val_loss: 1.0562 - val_accuracy: 0.6094\nEpoch 7/100\n25/25 [==============================] - 2s 82ms/step - loss: 1.0781 - accuracy: 0.6216 - val_loss: 0.9638 - val_accuracy: 0.6502\nEpoch 8/100\n25/25 [==============================] - 2s 81ms/step - loss: 0.9329 - accuracy: 0.6656 - val_loss: 0.9824 - val_accuracy: 0.6481\nEpoch 9/100\n25/25 [==============================] - 2s 76ms/step - loss: 0.8830 - accuracy: 0.6812 - val_loss: 0.8052 - val_accuracy: 0.7124\nEpoch 10/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.7360 - accuracy: 0.7327 - val_loss: 0.6677 - val_accuracy: 0.7918\nEpoch 11/100\n25/25 [==============================] - 2s 72ms/step - loss: 0.7102 - accuracy: 0.7424 - val_loss: 0.7296 - val_accuracy: 0.7403\nEpoch 12/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.6523 - accuracy: 0.7751 - val_loss: 0.6542 - val_accuracy: 0.7725\nEpoch 13/100\n25/25 [==============================] - 2s 72ms/step - loss: 0.6029 - accuracy: 0.7939 - val_loss: 0.6229 - val_accuracy: 0.7811\nEpoch 14/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.5577 - accuracy: 0.8025 - val_loss: 0.6198 - val_accuracy: 0.8197\nEpoch 15/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.5285 - accuracy: 0.8175 - val_loss: 0.6411 - val_accuracy: 0.7833\nEpoch 16/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.5024 - accuracy: 0.8256 - val_loss: 0.6207 - val_accuracy: 0.7854\nEpoch 17/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.4438 - accuracy: 0.8513 - val_loss: 0.5914 - val_accuracy: 0.7790\nEpoch 18/100\n25/25 [==============================] - 2s 71ms/step - loss: 0.4029 - accuracy: 0.8567 - val_loss: 0.5089 - val_accuracy: 0.8262\nEpoch 19/100\n25/25 [==============================] - 2s 89ms/step - loss: 0.3791 - accuracy: 0.8771 - val_loss: 0.5671 - val_accuracy: 0.8133\nEpoch 20/100\n25/25 [==============================] - 2s 81ms/step - loss: 0.4209 - accuracy: 0.8486 - val_loss: 0.5097 - val_accuracy: 0.8433\nEpoch 21/100\n25/25 [==============================] - 2s 78ms/step - loss: 0.4582 - accuracy: 0.8406 - val_loss: 0.5248 - val_accuracy: 0.8069\nEpoch 22/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.3530 - accuracy: 0.8744 - val_loss: 0.4660 - val_accuracy: 0.8605\nEpoch 23/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.2935 - accuracy: 0.8980 - val_loss: 0.4096 - val_accuracy: 0.8627\nEpoch 24/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.3099 - accuracy: 0.8959 - val_loss: 0.4626 - val_accuracy: 0.8455\nEpoch 25/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2659 - accuracy: 0.9087 - val_loss: 0.4814 - val_accuracy: 0.8476\nEpoch 26/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.2437 - accuracy: 0.9173 - val_loss: 0.4667 - val_accuracy: 0.8605\nEpoch 27/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2550 - accuracy: 0.9195 - val_loss: 0.4258 - val_accuracy: 0.8605\nEpoch 28/100\n25/25 [==============================] - 2s 76ms/step - loss: 0.2426 - accuracy: 0.9211 - val_loss: 0.4704 - val_accuracy: 0.8605\nEpoch 29/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1938 - accuracy: 0.9361 - val_loss: 0.4604 - val_accuracy: 0.8670\nEpoch 30/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2125 - accuracy: 0.9286 - val_loss: 0.3835 - val_accuracy: 0.8755\nEpoch 31/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2064 - accuracy: 0.9238 - val_loss: 0.4639 - val_accuracy: 0.8584\nEpoch 32/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2487 - accuracy: 0.9152 - val_loss: 0.4458 - val_accuracy: 0.8712\nEpoch 33/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2203 - accuracy: 0.9265 - val_loss: 0.5077 - val_accuracy: 0.8519\nEpoch 34/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.2029 - accuracy: 0.9334 - val_loss: 0.4566 - val_accuracy: 0.8755\nEpoch 35/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1999 - accuracy: 0.9238 - val_loss: 0.5131 - val_accuracy: 0.8584\nEpoch 36/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1856 - accuracy: 0.9388 - val_loss: 0.3870 - val_accuracy: 0.8798\nEpoch 37/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1719 - accuracy: 0.9383 - val_loss: 0.4120 - val_accuracy: 0.8884\nEpoch 38/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1630 - accuracy: 0.9452 - val_loss: 0.3664 - val_accuracy: 0.8755\nEpoch 39/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1479 - accuracy: 0.9544 - val_loss: 0.4599 - val_accuracy: 0.8691\nEpoch 40/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.1550 - accuracy: 0.9447 - val_loss: 0.3507 - val_accuracy: 0.8970\nEpoch 41/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1503 - accuracy: 0.9501 - val_loss: 0.3599 - val_accuracy: 0.8991\nEpoch 42/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1543 - accuracy: 0.9490 - val_loss: 0.4487 - val_accuracy: 0.8691\nEpoch 43/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.1355 - accuracy: 0.9587 - val_loss: 0.4015 - val_accuracy: 0.8798\nEpoch 44/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1265 - accuracy: 0.9544 - val_loss: 0.3865 - val_accuracy: 0.8906\nEpoch 45/100\n25/25 [==============================] - 2s 77ms/step - loss: 0.1094 - accuracy: 0.9635 - val_loss: 0.4110 - val_accuracy: 0.8991\nEpoch 46/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1381 - accuracy: 0.9533 - val_loss: 0.4097 - val_accuracy: 0.8927\nEpoch 47/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1381 - accuracy: 0.9506 - val_loss: 0.4029 - val_accuracy: 0.8777\nEpoch 48/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1180 - accuracy: 0.9581 - val_loss: 0.3851 - val_accuracy: 0.8991\nEpoch 49/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.0851 - accuracy: 0.9667 - val_loss: 0.3914 - val_accuracy: 0.8906\nEpoch 50/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.0913 - accuracy: 0.9705 - val_loss: 0.4808 - val_accuracy: 0.8777\nEpoch 51/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.1063 - accuracy: 0.9640 - val_loss: 0.4790 - val_accuracy: 0.8777\nEpoch 52/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.0999 - accuracy: 0.9640 - val_loss: 0.5113 - val_accuracy: 0.8734\nEpoch 53/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1264 - accuracy: 0.9549 - val_loss: 0.3698 - val_accuracy: 0.8948\nEpoch 54/100\n25/25 [==============================] - 2s 73ms/step - loss: 0.1122 - accuracy: 0.9651 - val_loss: 0.4277 - val_accuracy: 0.8820\nEpoch 55/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1064 - accuracy: 0.9662 - val_loss: 0.3838 - val_accuracy: 0.9034\nEpoch 56/100\n25/25 [==============================] - 2s 74ms/step - loss: 0.1120 - accuracy: 0.9678 - val_loss: 0.3699 - val_accuracy: 0.9077\nEpoch 57/100\n25/25 [==============================] - 2s 75ms/step - loss: 0.0874 - accuracy: 0.9726 - val_loss: 0.3793 - val_accuracy: 0.8927\nEpoch 58/100\n"
],
[
"train_signals, train_labels, val_signals, val_labels, test_signals, test_labels = create_dataset2(path, 2)",
"(491, 400)\n"
],
[
"plot_history(history)",
"[0.21459227800369263, 0.2682403326034546, 0.3562231659889221, 0.497854083776474, 0.5021459460258484, 0.6094420552253723, 0.6502146124839783, 0.6480686664581299, 0.7124463319778442, 0.7918455004692078, 0.7403433322906494, 0.7725321650505066, 0.7811158895492554, 0.8197425007820129, 0.783261775970459, 0.7854077219963074, 0.778969943523407, 0.8261802792549133, 0.8133047223091125, 0.8433476686477661, 0.8068669438362122, 0.8605149984359741, 0.8626609444618225, 0.8454935550689697, 0.8476395010948181, 0.8605149984359741, 0.8605149984359741, 0.8605149984359741, 0.8669527769088745, 0.8755365014076233, 0.8583691120147705, 0.8712446093559265, 0.8519313335418701, 0.8755365014076233, 0.8583691120147705, 0.8798283338546753, 0.8884119987487793, 0.8755365014076233, 0.8690987229347229, 0.8969957232475281, 0.8991416096687317, 0.8690987229347229, 0.8798283338546753, 0.8905579447746277, 0.8991416096687317, 0.8927038908004761, 0.8776823878288269, 0.8991416096687317, 0.8905579447746277, 0.8776823878288269, 0.8776823878288269, 0.8733905553817749, 0.8948497772216797, 0.8819742202758789, 0.9034335017204285, 0.9077253341674805, 0.8927038908004761, 0.9034335017204285, 0.9012875556945801, 0.8841201663017273, 0.9034335017204285, 0.8991416096687317, 0.8841201663017273, 0.8927038908004761, 0.9012875556945801, 0.8969957232475281, 0.9012875556945801, 0.8991416096687317, 0.9012875556945801, 0.8605149984359741, 0.8841201663017273, 0.9034335017204285, 0.8969957232475281, 0.9034335017204285, 0.9034335017204285, 0.9163089990615845, 0.9163089990615845, 0.8905579447746277, 0.8819742202758789, 0.9034335017204285, 0.8862661123275757, 0.8776823878288269, 0.9120171666145325, 0.9248927235603333, 0.8862661123275757, 0.9163089990615845, 0.8927038908004761, 0.9034335017204285, 0.8884119987487793, 0.9270386099815369, 0.8927038908004761, 0.9270386099815369, 0.9012875556945801, 0.9184549450874329, 0.9120171666145325, 0.9098712205886841, 0.8862661123275757, 0.9098712205886841, 0.9120171666145325, 0.9120171666145325]\n"
],
[
"evaluate_model(model, 2)",
"evaluate_model, expected_person_index: 2\n(2329, 400)\n59/59 [==============================] - 0s 7ms/step - loss: 0.0902 - accuracy: 0.9796\n(491, 400)\n10/10 [==============================] - 0s 7ms/step - loss: 5.1609 - accuracy: 0.3163\n"
],
[
"checkpoin_weights = []\n\nfor l in model.layers:\n checkpoin_weights.append(l.get_weights())\n\n\nmodel2 = Sequential()\nmodel2.add(Reshape((input_size, num_sensors), input_shape=(input_size, )))\n# Новый слой (КИХ фильтра)\n# 1 свертка из 11 чисел\nlength_of_conv_filter = 11\nmodel2.add(Conv1D(1, length_of_conv_filter, activation='linear', input_shape=(input_size, num_sensors), padding='same', name=\"Filter\"))\nmodel2.add(Dropout(0.5))\nmodel2.add(Conv1D(50, 10, activation='relu', input_shape=(input_size, num_sensors), trainable='False'))\nmodel2.add(Conv1D(25, 10, activation='relu', trainable='False'))\nmodel2.add(MaxPooling1D(4))\nmodel2.add(Conv1D(100, 10, activation='relu', trainable='False'))\nmodel2.add(Conv1D(50, 10, activation='relu', trainable='False'))\nmodel2.add(MaxPooling1D(4))\nmodel2.add(Dropout(0.5))\n#next layers will be retrained\nmodel2.add(Conv1D(100, 10, activation='relu', trainable='False'))\nmodel2.add(GlobalAveragePooling1D())\nmodel2.add(Dense(num_classes, activation='softmax', trainable='False'))\n\n#for i in range(1, 11):\n# model2.layers[i+1].set_weights(checkpoin_weights[i])\n\nw = model2.layers[1].get_weights()\nprint(w[0].shape)\n\n# Подбираем параметры для первого слоя КИХ фильтра\nw[0] = w[0] * 0\nw[0][int(length_of_conv_filter/2),0,0] = 1\nw[1] = w[1]*0\nplt.plot(w[0].flatten())\n\nw = model2.layers[1].set_weights(w)\n\n# Устанавливаем веса для уже обученных слоев\nn_layers = 11\nfor i in range(1, n_layers):\n model2.layers[i+2].set_weights(checkpoin_weights[i])\n# model2.layers[i+1].trainable = False\n\nmodel2.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\nmodel2.evaluate(train_signals, train_labels)\n\n# !tensorboard dev upload --logdir ./ \\\n# --name \"Simple experiment\" \\\n# --description \"Training results from https://colab.sandbox.google.com/github/tensorflow/tensorboard/blob/master/docs/tbdev_getting_started.ipynb\" \\\n# --one_shot\n# !tensorboard dev list\n#keras.utils.plot_model(model2, 'dense_image_classifier.png', show_shapes=True)\n",
"(11, 1, 1)\n10/10 [==============================] - 0s 9ms/step - loss: 4.6372 - accuracy: 0.3367\n"
],
[
"\nkeras.utils.plot_model(model2, 'dense_image_classifier2.png', show_shapes=True)",
"_____no_output_____"
],
[
"#keras.utils.plot_model(model2, 'dense_image_classifier.png', show_shapes=True)",
"_____no_output_____"
],
[
"history2 = model2.fit(train_signals, train_labels, epochs=25, \n validation_data=(test_signals, test_labels))",
"Epoch 1/25\n10/10 [==============================] - 1s 55ms/step - loss: 6.4059 - accuracy: 0.2959 - val_loss: 2.6690 - val_accuracy: 0.4040\nEpoch 2/25\n10/10 [==============================] - 0s 44ms/step - loss: 2.1682 - accuracy: 0.3265 - val_loss: 1.5535 - val_accuracy: 0.4545\nEpoch 3/25\n10/10 [==============================] - 0s 40ms/step - loss: 1.8071 - accuracy: 0.3299 - val_loss: 1.3684 - val_accuracy: 0.4646\nEpoch 4/25\n10/10 [==============================] - 0s 41ms/step - loss: 1.6328 - accuracy: 0.3707 - val_loss: 1.3792 - val_accuracy: 0.5051\nEpoch 5/25\n10/10 [==============================] - 0s 41ms/step - loss: 1.5806 - accuracy: 0.4048 - val_loss: 1.2545 - val_accuracy: 0.5051\nEpoch 6/25\n10/10 [==============================] - 0s 40ms/step - loss: 1.4130 - accuracy: 0.4762 - val_loss: 1.3489 - val_accuracy: 0.5051\nEpoch 7/25\n10/10 [==============================] - 0s 41ms/step - loss: 1.4027 - accuracy: 0.5170 - val_loss: 1.2096 - val_accuracy: 0.5556\nEpoch 8/25\n10/10 [==============================] - 0s 42ms/step - loss: 1.3424 - accuracy: 0.5476 - val_loss: 1.0948 - val_accuracy: 0.5960\nEpoch 9/25\n10/10 [==============================] - 0s 42ms/step - loss: 1.2712 - accuracy: 0.5476 - val_loss: 1.1389 - val_accuracy: 0.5657\nEpoch 10/25\n10/10 [==============================] - 0s 47ms/step - loss: 1.2281 - accuracy: 0.5442 - val_loss: 0.9210 - val_accuracy: 0.7071\nEpoch 11/25\n10/10 [==============================] - 0s 40ms/step - loss: 1.1994 - accuracy: 0.5476 - val_loss: 0.9951 - val_accuracy: 0.6465\nEpoch 12/25\n10/10 [==============================] - 0s 41ms/step - loss: 1.1457 - accuracy: 0.5748 - val_loss: 0.7964 - val_accuracy: 0.6970\nEpoch 13/25\n10/10 [==============================] - 0s 43ms/step - loss: 1.0246 - accuracy: 0.5986 - val_loss: 0.9275 - val_accuracy: 0.6869\nEpoch 14/25\n10/10 [==============================] - 0s 41ms/step - loss: 1.1250 - accuracy: 0.6224 - val_loss: 0.6436 - val_accuracy: 0.8384\nEpoch 15/25\n10/10 [==============================] - 0s 41ms/step - loss: 0.9856 - accuracy: 0.6531 - val_loss: 0.8177 - val_accuracy: 0.7374\nEpoch 16/25\n10/10 [==============================] - 0s 43ms/step - loss: 0.9765 - accuracy: 0.6769 - val_loss: 0.6509 - val_accuracy: 0.7778\nEpoch 17/25\n10/10 [==============================] - 0s 43ms/step - loss: 0.9529 - accuracy: 0.6531 - val_loss: 0.6614 - val_accuracy: 0.7879\nEpoch 18/25\n10/10 [==============================] - 0s 44ms/step - loss: 0.8350 - accuracy: 0.7041 - val_loss: 0.6574 - val_accuracy: 0.7980\nEpoch 19/25\n10/10 [==============================] - 0s 40ms/step - loss: 0.8706 - accuracy: 0.7143 - val_loss: 0.7605 - val_accuracy: 0.7677\nEpoch 20/25\n10/10 [==============================] - 0s 40ms/step - loss: 0.7401 - accuracy: 0.7381 - val_loss: 0.5595 - val_accuracy: 0.8586\nEpoch 21/25\n10/10 [==============================] - 0s 40ms/step - loss: 0.7816 - accuracy: 0.7177 - val_loss: 0.5945 - val_accuracy: 0.8485\nEpoch 22/25\n10/10 [==============================] - 0s 40ms/step - loss: 0.7517 - accuracy: 0.7551 - val_loss: 0.6449 - val_accuracy: 0.7778\nEpoch 23/25\n10/10 [==============================] - 0s 38ms/step - loss: 0.7091 - accuracy: 0.7279 - val_loss: 0.5424 - val_accuracy: 0.8384\nEpoch 24/25\n10/10 [==============================] - 0s 40ms/step - loss: 0.6636 - accuracy: 0.7551 - val_loss: 0.6183 - val_accuracy: 0.8283\nEpoch 25/25\n10/10 [==============================] - 0s 38ms/step - loss: 0.6108 - accuracy: 0.7755 - val_loss: 0.6463 - val_accuracy: 0.7778\n"
],
[
"\n\nplot_history(history2)\n\n#функция вывода коэффициентов свёрточного слоя\ndef check_coef_conv_layer(model_name, num_layer, num_filter):\n \n #сохраняем в переменную коэффициенты наблюдаемого слоя\n layer = model_name.layers[num_layer].get_weights()\n\n #коэффициенты 'а' наблюдаемого слоя первой сети \n weights = layer[0]\n #коэффициенты 'b' наблюдаемого слоя первой сети \n biases = layer[1]\n #вывод данных на экран\n for i in range(10):\n print(\"k{} = {:7.4f}\".format(i, weights[i][0][num_filter]))\n print(\"\\nb = {:7.4f}\".format(biases[num_filter]))\n \n#функция вывода коеффициентов полносвязного слоя\ndef check_coef_dense_layer(model_name, num_layer, num_filter):\n\n #сохраняем в переменную веса наблюдаемого слоя сети\n layer = model_name.layers[num_layer].get_weights()\n\n #коэффициенты 'а' наблюдаемого слоя сети \n weights = layer[0]\n #коэффициенты 'b' наблюдаемого слоя сети \n biases = layer[1]\n #вывод данных на экран\n for i in range(10):\n print(\"k{} = {:7.4f}\".format(i, weights[i][num_filter]))\n print(\"\\nb = {:7.4f}\".format(biases[num_filter]))\n\nl = model.layers[10].get_weights()\n",
"[0.4040403962135315, 0.4545454680919647, 0.46464645862579346, 0.5050504803657532, 0.5050504803657532, 0.5050504803657532, 0.5555555820465088, 0.5959596037864685, 0.5656565427780151, 0.7070707082748413, 0.6464646458625793, 0.6969696879386902, 0.6868686676025391, 0.8383838534355164, 0.7373737096786499, 0.7777777910232544, 0.7878788113594055, 0.7979797720909119, 0.7676767706871033, 0.8585858345031738, 0.8484848737716675, 0.7777777910232544, 0.8383838534355164, 0.8282828330993652, 0.7777777910232544]\n"
],
[
"plot_history(history2)",
"[0.4040403962135315, 0.4545454680919647, 0.46464645862579346, 0.5050504803657532, 0.5050504803657532, 0.5050504803657532, 0.5555555820465088, 0.5959596037864685, 0.5656565427780151, 0.7070707082748413, 0.6464646458625793, 0.6969696879386902, 0.6868686676025391, 0.8383838534355164, 0.7373737096786499, 0.7777777910232544, 0.7878788113594055, 0.7979797720909119, 0.7676767706871033, 0.8585858345031738, 0.8484848737716675, 0.7777777910232544, 0.8383838534355164, 0.8282828330993652, 0.7777777910232544]\n"
],
[
"\nevaluate_model(model2, 2)\n# keras.utils.plot_model(model, 'dense_image_classifier.png', show_shapes=True)",
"evaluate_model, expected_person_index: 2\n(2329, 400)\n59/59 [==============================] - 0s 7ms/step - loss: 3.2421 - accuracy: 0.3945\n(491, 400)\n10/10 [==============================] - 0s 7ms/step - loss: 0.6131 - accuracy: 0.7721\n"
],
[
"b = model2.layers[1].get_weights()\n# b[0] - neurons weights\nw, h = signal.freqz(b[0].flatten())\n\nplt.figure(figsize=(7, 5))\nplt.plot(w, 20 * np.log10(abs(h)), 'b', label='амплитудно-частотная характеристика 1 человек')\nplt.grid(True)\nplt.xlabel('Нормированная частота')\nplt.ylabel('Амплитуда, dB')\nplt.legend(loc='lower right')\n#print(b[0])\n \n#plt.set_xlabel('Frequency [rad/sample]')\n#plt.set_ylabel('Amplitude [dB]', color='b')",
"_____no_output_____"
],
[
"plt.figure(figsize=(8,5))\nprint(b[0].flatten())\nprint(abs(b[0].flatten().min()))\n# plt.plot(np.log10(b[0].flatten()+0.1), label='импульсная характеристика')\nplt.plot(b[0].flatten(), label='импульсная характеристика')\nplt.grid(True)\nplt.xlabel('коэффициент')\nplt.ylabel('значение')\nplt.legend(loc='upper right')\nplt.title('импульсная характеристика')",
"[-9.4782264e-04 -7.2347978e-03 -1.6765982e-02 -2.9175609e-02\n -3.5905249e-02 9.6807557e-01 -3.3159658e-02 -2.7200067e-02\n -9.9515198e-03 -9.0171711e-04 1.2501380e-02]\n0.03590525\n"
],
[
"plt.plot(b[0].flatten())\nprint(b[0].flatten())",
"[-9.4782264e-04 -7.2347978e-03 -1.6765982e-02 -2.9175609e-02\n -3.5905249e-02 9.6807557e-01 -3.3159658e-02 -2.7200067e-02\n -9.9515198e-03 -9.0171711e-04 1.2501380e-02]\n"
],
[
"# Обучаем теперь на третьем субъекте\n\ntrain_signals, train_labels, val_signals, val_labels, test_signals, test_labels = create_dataset2(path, 3)\nmodel.evaluate(train_signals, train_labels)\nhistory2 = model2.fit(train_signals, train_labels, epochs=25, \n validation_data=(test_signals, test_labels))",
"(347, 400)\n7/7 [==============================] - 0s 7ms/step - loss: 0.1924 - accuracy: 0.9519\nEpoch 1/25\n7/7 [==============================] - 0s 48ms/step - loss: 2.5803 - accuracy: 0.2885 - val_loss: 1.2139 - val_accuracy: 0.5571\nEpoch 2/25\n7/7 [==============================] - 0s 42ms/step - loss: 1.4849 - accuracy: 0.4663 - val_loss: 1.3076 - val_accuracy: 0.5143\nEpoch 3/25\n7/7 [==============================] - 0s 45ms/step - loss: 1.3664 - accuracy: 0.4952 - val_loss: 1.0334 - val_accuracy: 0.6571\nEpoch 4/25\n7/7 [==============================] - 0s 48ms/step - loss: 1.2128 - accuracy: 0.5673 - val_loss: 0.9827 - val_accuracy: 0.6857\nEpoch 5/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.9531 - accuracy: 0.6346 - val_loss: 0.6445 - val_accuracy: 0.7857\nEpoch 6/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.7847 - accuracy: 0.6923 - val_loss: 0.6393 - val_accuracy: 0.8000\nEpoch 7/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.8314 - accuracy: 0.6923 - val_loss: 0.5340 - val_accuracy: 0.8143\nEpoch 8/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.7563 - accuracy: 0.7308 - val_loss: 0.6221 - val_accuracy: 0.7714\nEpoch 9/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.7211 - accuracy: 0.7788 - val_loss: 0.5615 - val_accuracy: 0.8000\nEpoch 10/25\n7/7 [==============================] - 0s 44ms/step - loss: 0.7038 - accuracy: 0.7356 - val_loss: 0.7131 - val_accuracy: 0.7000\nEpoch 11/25\n7/7 [==============================] - 0s 44ms/step - loss: 0.6259 - accuracy: 0.7740 - val_loss: 0.9251 - val_accuracy: 0.6714\nEpoch 12/25\n7/7 [==============================] - 0s 41ms/step - loss: 0.5282 - accuracy: 0.7981 - val_loss: 0.5743 - val_accuracy: 0.8143\nEpoch 13/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.5923 - accuracy: 0.8077 - val_loss: 1.0063 - val_accuracy: 0.6857\nEpoch 14/25\n7/7 [==============================] - 0s 46ms/step - loss: 0.5459 - accuracy: 0.7933 - val_loss: 0.5061 - val_accuracy: 0.8143\nEpoch 15/25\n7/7 [==============================] - 0s 46ms/step - loss: 0.4783 - accuracy: 0.8221 - val_loss: 0.7588 - val_accuracy: 0.7286\nEpoch 16/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.5112 - accuracy: 0.7981 - val_loss: 0.4608 - val_accuracy: 0.8857\nEpoch 17/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.3338 - accuracy: 0.9038 - val_loss: 0.5951 - val_accuracy: 0.7571\nEpoch 18/25\n7/7 [==============================] - 0s 44ms/step - loss: 0.4507 - accuracy: 0.8558 - val_loss: 0.4915 - val_accuracy: 0.8714\nEpoch 19/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.4023 - accuracy: 0.8606 - val_loss: 0.6471 - val_accuracy: 0.7714\nEpoch 20/25\n7/7 [==============================] - 0s 41ms/step - loss: 0.3635 - accuracy: 0.8654 - val_loss: 0.6138 - val_accuracy: 0.8429\nEpoch 21/25\n7/7 [==============================] - 0s 42ms/step - loss: 0.3683 - accuracy: 0.8558 - val_loss: 0.6050 - val_accuracy: 0.8143\nEpoch 22/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.3637 - accuracy: 0.8702 - val_loss: 0.7856 - val_accuracy: 0.8286\nEpoch 23/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.3769 - accuracy: 0.8606 - val_loss: 0.5282 - val_accuracy: 0.8286\nEpoch 24/25\n7/7 [==============================] - 0s 43ms/step - loss: 0.2482 - accuracy: 0.9135 - val_loss: 0.5227 - val_accuracy: 0.8429\nEpoch 25/25\n7/7 [==============================] - 0s 45ms/step - loss: 0.2611 - accuracy: 0.8846 - val_loss: 0.7758 - val_accuracy: 0.7714\n"
],
[
"\nevaluate_model(model2, 3)",
"evaluate_model, expected_person_index: 3\n(2473, 400)\n62/62 [==============================] - 0s 7ms/step - loss: 5.1025 - accuracy: 0.3064\n(347, 400)\n7/7 [==============================] - 0s 7ms/step - loss: 0.3206 - accuracy: 0.8846\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb490dce50dce89e9c8de26a00426b7ac956a4d0 | 156,421 | ipynb | Jupyter Notebook | Prim.ipynb | Draco666888/Stock_Recommendation_System | f95f31139bd4c0de7c342c87f64b8ac337a56d1b | [
"Apache-2.0"
] | null | null | null | Prim.ipynb | Draco666888/Stock_Recommendation_System | f95f31139bd4c0de7c342c87f64b8ac337a56d1b | [
"Apache-2.0"
] | null | null | null | Prim.ipynb | Draco666888/Stock_Recommendation_System | f95f31139bd4c0de7c342c87f64b8ac337a56d1b | [
"Apache-2.0"
] | null | null | null | 166.582535 | 68,032 | 0.84169 | [
[
[
"import csv\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n%matplotlib inline",
"_____no_output_____"
],
[
"priceData = pd.read_csv('SP_500_close_2015.csv',index_col = 0)\npriceData.head()",
"_____no_output_____"
],
[
"firms = pd.read_csv(\"SP_500_firms.csv\")\nfirms.head()",
"_____no_output_____"
],
[
"percent_change = priceData.pct_change()\npercent_change = percent_change.drop(percent_change.index[0])\npercent_change.head()\n\n#Or equivalently without using Pandas' built-in \n#percent change function.\npercent_changeD = {}\nfor i in percent_change:\n percent_changeD[i] = []\n for j in range(1,(len(priceData))):\n ret = (priceData[i][j]-priceData[i][j-1])/priceData[i][j-1]\n percent_changeD[i].append(ret)\n \npercent_change2 = pd.DataFrame(data = percent_changeD,index=priceData.index[1:])",
"_____no_output_____"
],
[
"def fullname(ts):\n return firms[firms.Symbol == ts].Name.values[0]\n\ncurrMax = 0\nfor i in percent_change2:\n for j in percent_change2.index:\n if percent_change2[i][j] > currMax:\n currMax = percent_change2[i][j]\n bestCo = i\n bestDate = j\n \nprint (fullname(bestCo), bestDate, currMax)",
"Freeport-McMoran Cp & Gld 2015-08-27 0.286616201466348\n"
],
[
"currMin = 1\nfor i in percent_change2:\n for j in percent_change2.index:\n if percent_change2[i][j] < currMin:\n currMin = percent_change2[i][j]\n worstCo = i\n worstDate = j\n\nprint (fullname(worstCo), worstDate, currMin)",
"Quanta Services Inc. 2015-10-16 -0.2850056957270392\n"
],
[
"AnnualReturn = {}\nyearMax = -math.inf\nfor i in percent_change2:\n AnnualReturn[i] = (priceData[i][-1]-priceData[i][0])/priceData[i][0]\n if AnnualReturn[i] > yearMax:\n yearMax = AnnualReturn[i]\n maxCo = i\n\nprint (yearMax, maxCo, fullname(maxCo))",
"1.2945491196819041 NFLX Netflix Inc.\n"
],
[
"AnnualReturn = {}\nyearMin = math.inf\nfor i in percent_change2:\n AnnualReturn[i] = (priceData[i][-1]-priceData[i][0])/priceData[i][0]\n if AnnualReturn[i] < yearMin:\n yearMin = AnnualReturn[i]\n minCo = i\n\nprint (yearMin, minCo, fullname(minCo))\n",
"-0.7697847497642084 CHK Chesapeake Energy\n"
],
[
"def mean(x):\n return float(sum(x)) / len(x)\n\ndef std(x):\n stdev = 0.0\n for value in x:\n difference = value - mean(x)\n stdev = stdev + (difference ** 2)\n stdev = (stdev / len(x))**(1/2)\n return stdev",
"_____no_output_____"
],
[
"Volatility = {}\nvolMax = -math.inf\n\nfor i in percent_change2:\n Volatility[i] = std(percent_change2[i])\n if Volatility[i] > volMax:\n volMax = Volatility[i]\n volMaxC = i\n \nprint (volMax, volMaxC, fullname(volMaxC))",
"0.04398338070543049 FCX Freeport-McMoran Cp & Gld\n"
],
[
"Volatility = {}\nvolMin = math.inf\n\nfor i in percent_change2:\n Volatility[i] = std(percent_change2[i])\n if Volatility[i] < volMin:\n volMin = Volatility[i]\n volMinC = i\n\nprint (volMin, volMinC, fullname(volMinC))",
"0.009044853669708705 KO The Coca Cola Company\n"
],
[
"def corr(x,y):\n xy = sum([a*b for a,b in zip(x,y)])\n x2 = sum([i**2 for i in x])\n y2 = sum([i**2 for i in y])\n n = len(x)\n numer = (n*xy - sum(x)*sum(y))\n denom = ((n*x2 - sum(x)**2)**(1/2) * (n*y2 - sum(y)**2)**(1/2))\n correlation = numer/denom\n return correlation\n\ncorrelations = {}\n\nfor i in percent_change:\n correlations[i] = {}\n\nfor i in correlations: \n for j in percent_change:\n correlations[i][j]=[]\n \nfor company1 in percent_change:\n for company2 in percent_change:\n if not correlations[company1][company2]:\n x=percent_change[company1] \n y=percent_change[company2]\n if company1 == company2:\n correlations[company1][company2] = 1\n correlations[company2][company1] = 1\n else:\n correlations[company1][company2] = corr(x,y)\n correlations[company2][company1] = corr(x,y)\n \ndef corr_print(company1, company2):\n print (\"The correlation coefficient between {} and {} is {}.\"\n .format(fullname(company1), fullname(company2), correlations[company1][company2]))\n\ncorr_print(\"AAPL\", \"MMM\")",
"The correlation coefficient between Apple Inc. and 3M Company is 0.5157280000348696.\n"
],
[
"ticker_symbols = list(priceData.columns.values)\n\ndef top_bottomcorr(ts):\n corr_tb = []\n for ss in ticker_symbols:\n if ss == ts:\n continue\n corr_co = correlations[ts][ss]\n corr_tb.append((corr_co, ss))\n corr_tb.sort() \n print (\"Most Correlated:\", fullname(corr_tb[-1][1]), \"(\", corr_tb[-1][0],\")\")\n print (\"Least Correlated:\", fullname(corr_tb[0][1]), \"(\", corr_tb[0][0],\")\")",
"_____no_output_____"
],
[
"top_bottomcorr(\"GOOG\")",
"Most Correlated: Alphabet Inc Class A ( 0.9893650403946361 )\nLeast Correlated: Stericycle Inc ( 0.01714894347853482 )\n"
],
[
"correlations = percent_change.corr()\n\ncorrelations = correlations.where(np.triu(np.ones(correlations.shape)).astype(np.bool))\ncorrelations = correlations.stack().reset_index()\ncorrelations.columns = ['Company1', 'Company2', 'Correlation']\n\ncorrelation_tuples = [tuple(x) for x in correlations.values]",
"_____no_output_____"
],
[
"def mergeSort(array):\n if len(array) > 1:\n mid = len(array) //2\n left = array[:mid]\n right = array [mid:]\n mergeSort(left)\n mergeSort(right)\n\n i = 0\n j = 0\n k = 0\n while i < len(left) and j < len(right):\n if left[i][2] > right[j][2]:\n array[k] = left[i]\n i = i + 1\n else:\n array[k] = right[j]\n j = j + 1\n k = k+1\n while i < len(left):\n array[k] = left[i]\n i += 1\n k += 1\n while j < len(right):\n array[k] = right[j]\n j += 1\n k += 1\n return(array)\n\nsortedWeights = mergeSort(correlation_tuples)",
"_____no_output_____"
],
[
"class Digraph():\n def __init__(self,filename = None):\n self.edges = {}\n self.numEdges = 0\n \n def addNode(self,node): \n self.edges[node] = set()\n\n def add_Edge(self,src,dest,weight):\n if not self.hasNode(src): \n self.addNode(src)\n self.edges[src] = {}\n if not self.hasNode(dest): \n self.addNode(dest)\n self.edges[dest] = {}\n if not self.hasEdge(src, dest):\n self.numEdges += 1\n self.edges[src][dest] = weight\n \n def childrenOf(self, v):\n # Returns a node's children\n return self.edges[v].items()\n \n def hasNode(self, v):\n return v in self.edges\n \n def hasEdge(self, v, w):\n return w in self.edges[v]\n\n def listEdges(self):\n ll = []\n for src,values in self.edges.items():\n for dest,weight in values.items():\n ll.append([src,dest,weight])\n return ll\n \n def __str__(self):\n result = ''\n for src in self.edges:\n for dest,weight in self.edges[src].items():\n result = result + src + '->'\\\n + dest + ', length ' + str(weight) + '\\n'\n return result[:-1]\n\nclass Graph(Digraph):\n def addEdge(self, src, dest, weight):\n Digraph.addEdge(self, src, dest, weight)\n Digraph.addEdge(self, dest, src, weight)",
"_____no_output_____"
],
[
"def init_graph(sortedWeights):\n graph = Graph()\n for x in sortedWeights:\n graph.add_Edge(x[0],x[1],weight = x[2])\n return graph\n\ndef init_nodePointers(graph):\n nodePointers = {src:src for src in graph.edges}\n return nodePointers\n\ndef init_nodeStarting(graph):\n nodeStarting = {src:True for src in graph.edges}\n return nodeStarting\n\ndef init_nodeBottom(graph):\n nodeBottom = {src:True for src in graph.edges}\n return nodeBottom\n\ndef findbottom(node, nodePointers):\n source = node\n destination = nodePointers[source]\n while destination != source:\n source = destination\n destination = nodePointers[source]\n return destination\n\ndef mergeSets(sortedWeights, k):\n sortedWeights = [value for value in sortedWeights\n if value[0] != value[1]]\n graph = init_graph(sortedWeights)\n nodePointers = init_nodePointers(graph)\n nodeStarting = init_nodeStarting(graph)\n nodeBottom = init_nodeBottom(graph)\n counter = 0\n for key in sortedWeights:\n if counter < k:\n bottom1 = findbottom(key[0], nodePointers)\n bottom2 = findbottom(key[1], nodePointers)\n if bottom1 != bottom2:\n nodePointers[bottom2] = bottom1\n nodeBottom[bottom2] = False\n nodeStarting[bottom1] = False\n \n counter += 1\n return (nodePointers, nodeStarting, nodeBottom)\n\ndef recoverSets(nodePointers, nodeStarting, nodeBottom):\n dict = {}\n for b_key, b_value in nodeBottom.items():\n if b_value:\n dict.setdefault(b_key, set())\n for s_key, s_value in nodeStarting.items():\n if s_value and findbottom(s_key, nodePointers)== b_key:\n bottom = findbottom(s_key, nodePointers)\n current_node = s_key\n while current_node != bottom:\n dict[b_key].add(current_node)\n current_node = nodePointers[current_node]\n dict[b_key].add(b_key)\n return list(dict.values())",
"_____no_output_____"
],
[
"nodePointers, nodeStarting, nodeBottom = mergeSets(sortedWeights, 100000)\nprint(recoverSets(nodePointers, nodeStarting, nodeBottom))\n# print(\"For k = 100000, \" + str(len(cluster_100000)) + \" clusters are generated.\" + '\\n')",
"[{'ALL', 'CXO', 'GS', 'RIG', 'URI', 'PX', 'FOX', 'SEE', 'DGX', 'WFC', 'MA', 'FLS', 'HOLX', 'YUM', 'LEG', 'PXD', 'XEL', 'VRSK', 'ADM', 'CNP', 'SNA', 'HBAN', 'YHOO', 'PBCT', 'CVS', 'AVB', 'EIX', 'RTN', 'NLSN', 'ADP', 'NAVI', 'HRS', 'NBL', 'IFF', 'PRGO', 'EA', 'EMR', 'UNM', 'ADSK', 'MSI', 'SRCL', 'PKI', 'UNP', 'ORLY', 'FSLR', 'LVLT', 'CAT', 'GILD', 'BAX', 'SYF', 'ANTM', 'DVN', 'XEC', 'UDR', 'CTSH', 'AMT', 'WHR', 'TAP', 'CLX', 'CA', 'PEG', 'DAL', 'SPLS', 'F', 'ESS', 'DTE', 'AVY', 'ALLE', 'MCK', 'PM', 'PNR', 'LYB', 'CB', 'R', 'ZTS', 'ATVI', 'TSN', 'PFE', 'COP', 'CAH', 'MOS', 'NKE', 'HRB', 'HRL', 'CRM', 'NEM', 'APH', 'MO', 'EMC', 'DD', 'CMI', 'PGR', 'ACN', 'FBHS', 'TMO', 'NRG', 'VNO', 'BBT', 'HAS', 'JCI', 'HOT', 'FTI', 'SWK', 'BIIB', 'GPN', 'EXC', 'SYK', 'AET', 'HSY', 'VIAB', 'REGN', 'HCP', 'BDX', 'PFG', 'C', 'IPG', 'STT', 'SJM', 'LNC', 'PRU', 'AMGN', 'MJN', 'KMI', 'LOW', 'ZION', 'ENDP', 'UTX', 'NTRS', 'V', 'VRSN', 'NI', 'KSU', 'VZ', 'MAR', 'HP', 'JNPR', 'KLAC', 'LUK', 'FRT', 'ES', 'HUM', 'TWX', 'BSX', 'PEP', 'EXR', 'WDC', 'CBS', 'PSA', 'RAI', 'AN', 'HCN', 'BK', 'ICE', 'CERN', 'ABC', 'MAT', 'ALB', 'ABT', 'DPS', 'XYL', 'ETR', 'AEP', 'GWW', 'AGN', 'GOOG', 'GM', 'CTXS', 'EW', 'RL', 'RF', 'GPC', 'WYNN', 'PNW', 'AXP', 'JEC', 'BLK', 'ROK', 'ORCL', 'BWA', 'AMZN', 'GE', 'MET', 'MDT', 'MHK', 'DNB', 'FIS', 'FTR', 'NWS', 'COL', 'EBAY', 'AIV', 'WBA', 'JBHT', 'AMP', 'ADI', 'BHI', 'SE', 'WAT', 'LKQ', 'WMT', 'CCL', 'DOV', 'ESRX', 'CBG', 'XLNX', 'HAR', 'KMX', 'SPGI', 'MDLZ', 'PCG', 'HSIC', 'UAL', 'EQR', 'WM', 'XL', 'DIS', 'GT', 'RCL', 'FMC', 'CI', 'ETN', 'KEY', 'BRK-B', 'EL', 'IP', 'D', 'HIG', 'ABBV', 'CSX', 'NOV', 'DISCA', 'FCX', 'AAL', 'AYI', 'ROP', 'MTB', 'EMN', 'CSCO', 'COF', 'VMC', 'CHRW', 'EQT', 'TSS', 'BMY', 'KSS', 'LRCX', 'HCA', 'EXPD', 'TSCO', 'DHI', 'BA', 'AJG', 'MSFT', 'DVA', 'APC', 'IR', 'CTL', 'CFG', 'TYC', 'SWN', 'AMG', 'CMG', 'KO', 'SCG', 'SBUX', 'AKAM', 'MAC', 'JNJ', 'BCR', 'BXP', 'SHW', 'T', 'VLO', 'TSO', 'HST', 'PDCO', 'CHK', 'MLM', 'TIF', 'LLL', 'BLL', 'EXPE', 'APA', 'CNC', 'RRC', 'SNI', 'AZO', 'PCLN', 'QRVO', 'SRE', 'TRIP', 'HOG', 'MCD', 'XRAY', 'FOXA', 'NUE', 'VTR', 'MRO', 'LUV', 'AAPL', 'UPS', 'ED', 'FB', 'CINF', 'DE', 'CL', 'PSX', 'AFL', 'CVX', 'VRTX', 'LLY', 'JPM', 'DO', 'APD', 'ETFC', 'UNH', 'IRM', 'CTAS', 'AEE', 'PLD', 'UHS', 'INTC', 'SLG', 'WY', 'CMS', 'SPG', 'MMC', 'EFX', 'DUK', 'COH', 'RHI', 'TGNA', 'DLPH', 'VAR', 'TXT', 'AWK', 'CELG', 'MYL', 'GOOGL', 'ALXN', 'MS', 'FFIV', 'GRMN', 'WU', 'FE', 'MON', 'LB', 'IVZ', 'FL', 'SWKS', 'TDG', 'OMC', 'NWL', 'RHT', 'HPQ', 'O', 'HES', 'KORS', 'NFX', 'LMT', 'HD', 'GLW', 'CMA', 'NDAQ', 'AIG', 'CCI', 'RSG', 'NFLX', 'PH', 'ULTA', 'AES', 'MRK', 'SLB', 'FLR', 'STZ', 'FISV', 'DLR', 'BBBY', 'ISRG', 'HAL', 'PHM', 'AMAT', 'FITB', 'LM', 'BAC', 'DHR', 'CPB', 'HON', 'MKC', 'AON', 'WFM', 'DFS', 'BF-B', 'KR', 'OKE', 'SYY', 'DLTR', 'WMB', 'PVH', 'NOC', 'MUR', 'CAG', 'BBY', 'AIZ', 'TMK', 'UA', 'GIS', 'PWR', 'ROST', 'NVDA', 'URBN', 'ADBE', 'PG', 'XOM', 'L', 'MNST', 'DRI', 'MU', 'TJX', 'JWN', 'SYMC', 'MPC', 'ALK', 'ZBH', 'DOW', 'STJ', 'ILMN', 'LH', 'AAP', 'BEN', 'TEL', 'AVGO', 'CMCSA', 'LEN', 'OI', 'PNC', 'K', 'INTU', 'M', 'COST', 'SCHW', 'NSC', 'PBI', 'SO', 'MAS', 'AA', 'TRV', 'LLTC', 'TGT', 'STX', 'MCO', 'STI', 'PCAR', 'TDC', 'VFC', 'FLIR', 'FAST', 'IBM', 'OXY', 'CF', 'SIG', 'MMM', 'PPG', 'EQIX', 'FDX', 'KMB', 'ITW', 'DISCK', 'CHD', 'LNT', 'USB', 'HBI', 'COG', 'PPL', 'GD', 'ADS', 'WYN', 'A', 'XRX', 'TROW', 'CME', 'WEC', 'GGP', 'MNK', 'QCOM', 'TXN', 'EOG', 'ECL', 'AME', 'GPS', 'NWSA', 'PAYX', 'MCHP', 'KIM', 'DG', 'NTAP'}]\n"
],
[
"nodePointers, nodeStarting, nodeBottom = mergeSets(sortedWeights, 2000)\ncluster_2000 = recoverSets(nodePointers, nodeStarting, nodeBottom)\nprint(cluster_2000)\nprint(\"For k = 2000, \" + str(len(cluster_2000)) + \" clusters are generated.\" + '\\n')",
"[{'GOOG', 'GOOGL'}, {'NWSA', 'NWS'}, {'DISCA', 'DISCK', 'SNI'}, {'PHM', 'DHI', 'LEN'}, {'CCL', 'RCL'}, {'ANTM', 'AET', 'UNH', 'CI', 'CNC'}, {'HCA', 'UHS'}, {'ROST', 'TJX'}, {'VLO', 'TSO', 'MPC', 'PSX'}, {'MO', 'PM', 'RAI'}, {'VMC', 'MLM'}, {'RSG', 'WM'}, {'DGX', 'LH'}, {'DAL', 'ALK', 'LUV', 'AAL', 'UAL'}, {'WYN', 'MAR', 'HOT'}, {'EXPD', 'CHRW'}, {'AMAT', 'LRCX'}, {'AVGO', 'SWKS'}, {'GWW', 'FAST'}, {'AZO', 'ORLY'}, {'FOXA', 'CMCSA', 'DIS', 'FOX', 'TWX'}, {'GM', 'F'}, {'NSC', 'CSX', 'UNP', 'KSU'}, {'WDC', 'STX'}, {'HCN', 'DUK', 'ED', 'AIV', 'ESS', 'AWK', 'LNT', 'D', 'DTE', 'PPL', 'ETR', 'VNO', 'DLR', 'AEP', 'FE', 'NI', 'AEE', 'PLD', 'XEL', 'PNW', 'SRE', 'WEC', 'SCG', 'CNP', 'GGP', 'SLG', 'UDR', 'AMT', 'FRT', 'PCG', 'ES', 'BXP', 'CMS', 'SO', 'O', 'EXC', 'EQR', 'AVB', 'EXR', 'EIX', 'SPG', 'VTR', 'PSA', 'HCP', 'KIM', 'CCI', 'PEG'}, {'LNC', 'CXO', 'PH', 'GS', 'PRU', 'APC', 'AMGN', 'RIG', 'MRK', 'PX', 'SLB', 'FLR', 'KMI', 'LOW', 'ZION', 'FISV', 'UTX', 'CFG', 'TYC', 'NTRS', 'WFC', 'V', 'MA', 'FLS', 'HAL', 'FITB', 'PXD', 'LM', 'SWN', 'BAC', 'DHR', 'CPB', 'AMG', 'HON', 'HP', 'VZ', 'MKC', 'AON', 'KO', 'SNA', 'SBUX', 'DFS', 'HBAN', 'PBCT', 'JNJ', 'BCR', 'SHW', 'OKE', 'PEP', 'T', 'RTN', 'ADP', 'NBL', 'IFF', 'EMR', 'UNM', 'BK', 'NOC', 'MUR', 'ICE', 'LLL', 'ABT', 'TMK', 'APA', 'GIS', 'DPS', 'PKI', 'RRC', 'XYL', 'PG', 'AJG', 'XOM', 'L', 'CAT', 'GPC', 'RF', 'DVN', 'JEC', 'XEC', 'BLK', 'ROK', 'BWA', 'CTSH', 'MET', 'MDT', 'DNB', 'MRO', 'UPS', 'CLX', 'DOW', 'CA', 'COL', 'CINF', 'CL', 'AFL', 'CVX', 'BEN', 'TEL', 'AMP', 'AVY', 'JPM', 'ADI', 'BHI', 'SE', 'DO', 'PNC', 'WAT', 'ETFC', 'K', 'INTU', 'CTAS', 'PNR', 'LYB', 'CB', 'SCHW', 'DOV', 'XLNX', 'INTC', 'SPGI', 'HSIC', 'TRV', 'LLTC', 'COP', 'XL', 'MCO', 'STI', 'PCAR', 'CAH', 'IBM', 'OXY', 'ETN', 'KEY', 'MMC', 'BRK-B', 'APH', 'MMM', 'PPG', 'DLPH', 'CMI', 'PGR', 'VAR', 'ACN', 'KMB', 'FDX', 'ITW', 'TXT', 'CHD', 'CELG', 'USB', 'HIG', 'TMO', 'COG', 'GD', 'MS', 'IPG', 'NOV', 'A', 'TROW', 'CME', 'ROP', 'BBT', 'MTB', 'EMN', 'JCI', 'COF', 'IVZ', 'FTI', 'SWK', 'EQT', 'OMC', 'TSS', 'TXN', 'SYK', 'HES', 'EOG', 'NFX', 'ECL', 'LMT', 'HD', 'AME', 'TSCO', 'CMA', 'PAYX', 'MCHP', 'BA', 'PFG', 'C', 'AIG', 'STT', 'NDAQ', 'REGN', 'BDX'}, {'AIZ'}, {'CSCO'}, {'EFX'}, {'XRAY'}, {'IR'}, {'DD'}, {'MCD'}, {'MDLZ'}, {'ADS'}, {'CBG'}, {'ORCL'}, {'SRCL'}, {'VFC'}, {'CVS'}, {'WBA'}, {'ALL'}, {'FBHS'}, {'MAS'}, {'DG'}, {'DLTR'}, {'WMB'}, {'NLSN'}, {'PFE'}, {'FIS'}, {'URI'}, {'NWL'}, {'AN'}, {'APD'}, {'AXP'}, {'ALXN'}, {'MCK'}, {'RHT'}, {'HST'}, {'WY'}, {'BF-B'}, {'HAR'}, {'ABC'}, {'GILD'}, {'RHI'}, {'CBS'}, {'ALLE'}, {'PVH'}, {'VRTX'}, {'QRVO'}, {'R'}, {'NKE'}, {'PDCO'}, {'XRX'}, {'ZBH'}, {'LUK'}, {'STZ'}, {'ESRX'}, {'ULTA'}, {'VIAB'}, {'IP'}, {'JBHT'}, {'CHK'}, {'EW'}, {'LVLT'}, {'FCX'}, {'NVDA'}, {'HRL'}, {'JWN'}, {'EL'}, {'DE'}, {'TGT'}, {'COST'}, {'VRSN'}, {'FMC'}, {'BLL'}, {'TGNA'}, {'MHK'}, {'GT'}, {'OI'}, {'SEE'}, {'WU'}, {'LEG'}, {'NUE'}, {'KLAC'}, {'BAX'}, {'FL'}, {'ADBE'}, {'FB'}, {'BMY'}, {'KR'}, {'IRM'}, {'AGN'}, {'AKAM'}, {'GE'}, {'UA'}, {'HSY'}, {'DVA'}, {'FLIR'}, {'PBI'}, {'MAC'}, {'STJ'}, {'ENDP'}, {'MNK'}, {'EBAY'}, {'KMX'}, {'GLW'}, {'M'}, {'MSFT'}, {'BBBY'}, {'LB'}, {'ADM'}, {'HRS'}, {'AAPL'}, {'GPN'}, {'CTXS'}, {'EMC'}, {'CTL'}, {'MOS'}, {'EQIX'}, {'GPS'}, {'LKQ'}, {'RL'}, {'AMZN'}, {'PWR'}, {'HUM'}, {'BSX'}, {'SYMC'}, {'EA'}, {'TIF'}, {'ALB'}, {'MON'}, {'ABBV'}, {'CAG'}, {'JNPR'}, {'LLY'}, {'CERN'}, {'MJN'}, {'ISRG'}, {'BIIB'}, {'KSS'}, {'WHR'}, {'SJM'}, {'HRB'}, {'WMT'}, {'VRSK'}, {'AA'}, {'AYI'}, {'ATVI'}, {'HOLX'}, {'PCLN'}, {'TDG'}, {'COH'}, {'SIG'}, {'MU'}, {'EXPE'}, {'TSN'}, {'MSI'}, {'CRM'}, {'FFIV'}, {'NRG'}, {'ZTS'}, {'CF'}, {'HOG'}, {'FTR'}, {'FSLR'}, {'SYY'}, {'ADSK'}, {'ILMN'}, {'AES'}, {'HBI'}, {'GRMN'}, {'QCOM'}, {'HPQ'}, {'DRI'}, {'AAP'}, {'YHOO'}, {'NTAP'}, {'SPLS'}, {'YUM'}, {'NAVI'}, {'BBY'}, {'MNST'}, {'MYL'}, {'NEM'}, {'WYNN'}, {'URBN'}, {'TDC'}, {'MAT'}, {'TRIP'}, {'NFLX'}, {'HAS'}, {'KORS'}, {'SYF'}, {'PRGO'}, {'TAP'}, {'CMG'}, {'WFM'}]\nFor k = 2000, 218 clusters are generated.\n\n"
],
[
"percent_change[['DAL', 'AAL', 'LUV', 'UAL', 'ALK']].plot()",
"_____no_output_____"
],
[
"pricesScaled = priceData.divide(priceData.iloc[0])\npricesScaled[['MAR', 'HOT', 'WYN']].plot()",
"_____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"
]
] |
cb491679d6a901c4d9ae79910b957523989d84de | 11,276 | ipynb | Jupyter Notebook | submodules/resource/d2l-zh/pytorch/chapter_computer-vision/transposed-conv.ipynb | alphajayGithub/ai.online | 3e440d88111627827456aa8672516eb389a68e98 | [
"MIT"
] | 2 | 2021-12-11T07:19:34.000Z | 2022-03-11T09:29:49.000Z | submodules/resource/d2l-zh/pytorch/chapter_computer-vision/transposed-conv.ipynb | alphajayGithub/ai.online | 3e440d88111627827456aa8672516eb389a68e98 | [
"MIT"
] | null | null | null | submodules/resource/d2l-zh/pytorch/chapter_computer-vision/transposed-conv.ipynb | alphajayGithub/ai.online | 3e440d88111627827456aa8672516eb389a68e98 | [
"MIT"
] | null | null | null | 22.872211 | 152 | 0.495388 | [
[
[
"# 转置卷积\n:label:`sec_transposed_conv`\n\n到目前为止,我们所见到的卷积神经网络层,例如卷积层( :numref:`sec_conv_layer`)和汇聚层( :numref:`sec_pooling`),通常会减少下采样输入图像的空间维度(高和宽)。\n然而如果输入和输出图像的空间维度相同,在以像素级分类的语义分割中将会很方便。\n例如,输出像素所处的通道维可以保有输入像素在同一位置上的分类结果。\n\n为了实现这一点,尤其是在空间维度被卷积神经网络层缩小后,我们可以使用另一种类型的卷积神经网络层,它可以增加上采样中间层特征图的空间维度。\n在本节中,我们将介绍\n*转置卷积*(transposed convolution) :cite:`Dumoulin.Visin.2016`,\n用于逆转下采样导致的空间尺寸减小。\n",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torch import nn\nfrom d2l import torch as d2l",
"_____no_output_____"
]
],
[
[
"## 基本操作\n\n让我们暂时忽略通道,从基本的转置卷积开始,设步幅为1且没有填充。\n假设我们有一个$n_h \\times n_w$的输入张量和一个$k_h \\times k_w$的卷积核。\n以步幅为1滑动卷积核窗口,每行$n_w$次,每列$n_h$次,共产生$n_h n_w$个中间结果。\n每个中间结果都是一个$(n_h + k_h - 1) \\times (n_w + k_w - 1)$的张量,初始化为0。\n为了计算每个中间张量,输入张量中的每个元素都要乘以卷积核,从而使所得的$k_h \\times k_w$张量替换中间张量的一部分。\n请注意,每个中间张量被替换部分的位置与输入张量中元素的位置相对应。\n最后,所有中间结果相加以获得最终结果。\n\n例如, :numref:`fig_trans_conv`解释了如何为$2\\times 2$的输入张量计算卷积核为$2\\times 2$的转置卷积。\n\n\n:label:`fig_trans_conv`\n\n我们可以对输入矩阵`X`和卷积核矩阵`K`(**实现基本的转置卷积运算**)`trans_conv`。\n",
"_____no_output_____"
]
],
[
[
"def trans_conv(X, K):\n h, w = K.shape\n Y = torch.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))\n for i in range(X.shape[0]):\n for j in range(X.shape[1]):\n Y[i: i + h, j: j + w] += X[i, j] * K\n return Y",
"_____no_output_____"
]
],
[
[
"与通过卷积核“减少”输入元素的常规卷积(在 :numref:`sec_conv_layer`中)相比,转置卷积通过卷积核“广播”输入元素,从而产生大于输入的输出。\n我们可以通过 :numref:`fig_trans_conv`来构建输入张量`X`和卷积核张量`K`从而[**验证上述实现输出**]。\n此实现是基本的二维转置卷积运算。\n",
"_____no_output_____"
]
],
[
[
"X = torch.tensor([[0.0, 1.0], [2.0, 3.0]])\nK = torch.tensor([[0.0, 1.0], [2.0, 3.0]])\ntrans_conv(X, K)",
"_____no_output_____"
]
],
[
[
"或者,当输入`X`和卷积核`K`都是四维张量时,我们可以[**使用高级API获得相同的结果**]。\n",
"_____no_output_____"
]
],
[
[
"X, K = X.reshape(1, 1, 2, 2), K.reshape(1, 1, 2, 2)\ntconv = nn.ConvTranspose2d(1, 1, kernel_size=2, bias=False)\ntconv.weight.data = K\ntconv(X)",
"_____no_output_____"
]
],
[
[
"## [**填充、步幅和多通道**]\n\n与常规卷积不同,在转置卷积中,填充被应用于的输出(常规卷积将填充应用于输入)。\n例如,当将高和宽两侧的填充数指定为1时,转置卷积的输出中将删除第一和最后的行与列。\n",
"_____no_output_____"
]
],
[
[
"tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, padding=1, bias=False)\ntconv.weight.data = K\ntconv(X)",
"_____no_output_____"
]
],
[
[
"在转置卷积中,步幅被指定为中间结果(输出),而不是输入。\n使用 :numref:`fig_trans_conv`中相同输入和卷积核张量,将步幅从1更改为2会增加中间张量的高和权重,因此输出张量在 :numref:`fig_trans_conv_stride2`中。\n\n\n:label:`fig_trans_conv_stride2`\n\n以下代码可以验证 :numref:`fig_trans_conv_stride2`中步幅为2的转置卷积的输出。\n",
"_____no_output_____"
]
],
[
[
"tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, stride=2, bias=False)\ntconv.weight.data = K\ntconv(X)",
"_____no_output_____"
]
],
[
[
"对于多个输入和输出通道,转置卷积与常规卷积以相同方式运作。\n假设输入有$c_i$个通道,且转置卷积为每个输入通道分配了一个$k_h\\times k_w$的卷积核张量。\n当指定多个输出通道时,每个输出通道将有一个$c_i\\times k_h\\times k_w$的卷积核。\n\n同样,如果我们将$\\mathsf{X}$代入卷积层$f$来输出$\\mathsf{Y}=f(\\mathsf{X})$,并创建一个与$f$具有相同的超参数、但输出通道数量是$\\mathsf{X}$中通道数的转置卷积层$g$,那么$g(Y)$的形状将与$\\mathsf{X}$相同。\n下面的示例可以解释这一点。\n",
"_____no_output_____"
]
],
[
[
"X = torch.rand(size=(1, 10, 16, 16))\nconv = nn.Conv2d(10, 20, kernel_size=5, padding=2, stride=3)\ntconv = nn.ConvTranspose2d(20, 10, kernel_size=5, padding=2, stride=3)\ntconv(conv(X)).shape == X.shape",
"_____no_output_____"
]
],
[
[
"## [**与矩阵变换的联系**]\n:label:`subsec-connection-to-mat-transposition`\n\n转置卷积为何以矩阵变换命名呢?\n让我们首先看看如何使用矩阵乘法来实现卷积。\n在下面的示例中,我们定义了一个$3\\times 3$的输入`X`和$2\\times 2$卷积核`K`,然后使用`corr2d`函数计算卷积输出`Y`。\n",
"_____no_output_____"
]
],
[
[
"X = torch.arange(9.0).reshape(3, 3)\nK = torch.tensor([[1.0, 2.0], [3.0, 4.0]])\nY = d2l.corr2d(X, K)\nY",
"_____no_output_____"
]
],
[
[
"接下来,我们将卷积核`K`重写为包含大量0的稀疏权重矩阵`W`。\n权重矩阵的形状是($4$,$9$),其中非0元素来自卷积核`K`。\n",
"_____no_output_____"
]
],
[
[
"def kernel2matrix(K):\n k, W = torch.zeros(5), torch.zeros((4, 9))\n k[:2], k[3:5] = K[0, :], K[1, :]\n W[0, :5], W[1, 1:6], W[2, 3:8], W[3, 4:] = k, k, k, k\n return W\n\nW = kernel2matrix(K)\nW",
"_____no_output_____"
]
],
[
[
"逐行连结输入`X`,获得了一个长度为9的矢量。\n然后,`W`的矩阵乘法和向量化的`X`给出了一个长度为4的向量。\n重塑它之后,可以获得与上面的原始卷积操作所得相同的结果`Y`:我们刚刚使用矩阵乘法实现了卷积。\n",
"_____no_output_____"
]
],
[
[
"Y == torch.matmul(W, X.reshape(-1)).reshape(2, 2)",
"_____no_output_____"
]
],
[
[
"同样,我们可以使用矩阵乘法来实现转置卷积。\n在下面的示例中,我们将上面的常规卷积$2 \\times 2$的输出`Y`作为转置卷积的输入。\n想要通过矩阵相乘来实现它,我们只需要将权重矩阵`W`的形状转置为$(9, 4)$。\n",
"_____no_output_____"
]
],
[
[
"Z = trans_conv(Y, K)\nZ == torch.matmul(W.T, Y.reshape(-1)).reshape(3, 3)",
"_____no_output_____"
]
],
[
[
"抽象来看,给定输入向量$\\mathbf{x}$和权重矩阵$\\mathbf{W}$,卷积的前向传播函数可以通过将其输入与权重矩阵相乘并输出向量$\\mathbf{y}=\\mathbf{W}\\mathbf{x}$来实现。\n由于反向传播遵循链式法则和$\\nabla_{\\mathbf{x}}\\mathbf{y}=\\mathbf{W}^\\top$,卷积的反向传播函数可以通过将其输入与转置的权重矩阵$\\mathbf{W}^\\top$相乘来实现。\n因此,转置卷积层能够交换卷积层的正向传播函数和反向传播函数:它的正向传播和反向传播函数将输入向量分别与$\\mathbf{W}^\\top$和$\\mathbf{W}$相乘。\n\n## 小结\n\n* 与通过卷积核减少输入元素的常规卷积相反,转置卷积通过卷积核广播输入元素,从而产生形状大于输入的输出。\n* 如果我们将$\\mathsf{X}$输入卷积层$f$来获得输出$\\mathsf{Y}=f(\\mathsf{X})$并创造一个与$f$有相同的超参数、但输出通道数是$\\mathsf{X}$中通道数的转置卷积层$g$,那么$g(Y)$的形状将与$\\mathsf{X}$相同。\n* 我们可以使用矩阵乘法来实现卷积。转置卷积层能够交换卷积层的正向传播函数和反向传播函数。\n\n## 练习\n\n1. 在 :numref:`subsec-connection-to-mat-transposition`中,卷积输入`X`和转置的卷积输出`Z`具有相同的形状。他们的数值也相同吗?为什么?\n1. 使用矩阵乘法来实现卷积是否有效率?为什么?\n",
"_____no_output_____"
],
[
"[Discussions](https://discuss.d2l.ai/t/3302)\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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb49252d2a2b685dc631c26967c067e672834037 | 70,006 | ipynb | Jupyter Notebook | tfp_notebook/03_q_learning_ml.ipynb | katsugeneration/behavior-data-computation-modeling-for-python | a97ec30471f684849d4799d8b0ad46da53dea14f | [
"MIT"
] | 1 | 2021-08-14T13:09:11.000Z | 2021-08-14T13:09:11.000Z | tfp_notebook/03_q_learning_ml.ipynb | katsugeneration/behavior-data-computation-modeling-for-python | a97ec30471f684849d4799d8b0ad46da53dea14f | [
"MIT"
] | null | null | null | tfp_notebook/03_q_learning_ml.ipynb | katsugeneration/behavior-data-computation-modeling-for-python | a97ec30471f684849d4799d8b0ad46da53dea14f | [
"MIT"
] | null | null | null | 291.691667 | 34,303 | 0.757821 | [
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nT = 80\nalpha = 0.3\nbeta = 2.0\npra = 0.7\nprb = 0.3\n\nra = tfp.distributions.Bernoulli(probs=pra, dtype=tf.float32)\nrb = tfp.distributions.Bernoulli(probs=prb, dtype=tf.float32)\nQ = np.zeros((2, T+1), dtype=np.float32)\nchoices = np.zeros((T, ), dtype=np.int32)\nrewards = np.zeros((T, ), dtype=np.float32)\npahist = np.zeros((T+1, ), dtype=np.float32)\n\nfor t in range(1, T):\n pa = 1. / (1 + tf.exp(-beta * (Q[0, t] - Q[1, t])))\n pahist[t+1] = pa\n a = tfp.distributions.Bernoulli(probs=pa, dtype=tf.bool).sample(1)[0]\n choices[t] = a\n if a == True:\n r = ra.sample(1)[0]\n Q[0, t+1] = Q[0, t] + alpha * (r - Q[0, t]) \n Q[1, t+1] = Q[1, t]\n else:\n r = rb.sample(1)[0]\n Q[1, t+1] = Q[1, t] + alpha * (r - Q[1, t]) \n Q[0, t+1] = Q[0, t]\n rewards[t] = r",
"2021-08-13 09:41:52.313920: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory\n2021-08-13 09:41:52.313975: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.\n2021-08-13 09:41:57.229871: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory\n2021-08-13 09:41:57.229913: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303)\n2021-08-13 09:41:57.230003: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (ip-172-26-3-85): /proc/driver/nvidia/version does not exist\n2021-08-13 09:41:57.232251: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA\nTo enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
],
[
"plt.plot(range(T+1), Q[0, :], label='A')\nplt.plot(range(T+1), Q[1, :], label='B')\nplt.plot(range(T+1), pahist, label='pa')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"import functools\n\nT = 80\n\ndef make_val_and_grad_fn(value_fn):\n @functools.wraps(value_fn)\n def val_and_grad(x):\n return tfp.math.value_and_gradient(value_fn, x)\n return val_and_grad\n\n@make_val_and_grad_fn\ndef simulate(params):\n tf.print(params)\n alpha_est, beta_est = tf.exp(params[0]), tf.exp(params[1])\n Qa = np.array(0.0, dtype=np.float32)\n Qb = np.array(0.0, dtype=np.float32)\n ll = tf.Variable(0.0, dtype=np.float32)\n\n for t in range(T):\n pa = 1. / (1 + tf.exp(-beta_est * (Qa- Qb)))\n pa = tf.clip_by_value(pa, 0.00001, 0.99999)\n ll = ll + choices[t] * tf.math.log(pa) + (1 - choices[t]) * tf.math.log(1 - pa)\n\n if choices[t] == 1:\n Qa = Qa + alpha_est * (rewards[t] - Qa)\n else:\n Qb = Qb + alpha_est * (rewards[t] - Qb)\n tf.print(ll)\n return -ll\n\nalpha_est = 0.\nbeta_est = 0.\n\noptim_results = tfp.optimizer.lbfgs_minimize(\n simulate, initial_position=np.array([alpha_est, beta_est], dtype=np.float32))",
"[0.409444332 4.90714931]\n-258.812561\n(<tf.Tensor: shape=(), dtype=float32, numpy=258.81256>, <tf.Tensor: shape=(2,), dtype=float32, numpy=array([nan, nan], dtype=float32)>)\n[0 0]\n-48.3178596\n[-5.12117195 1.25389421]\n-51.6998062\n[-3.70568657 0.907319486]\n-48.6543427\n[-1.85284328 0.453659743]\n-47.0860291\n[-1.63843024 0.40116173]\n-46.9055672\n[-1.82482958 1.17726243]\n-44.9415474\n[-1.77975023 0.989567876]\n-44.9327736\n[-1.5905745 1.13561916]\n-44.7602654\n[-1.64187765 1.09601104]\n-44.7427406\n[-1.13100243 0.993355632]\n-44.4460144\n[-1.25670803 1.01861489]\n-44.4513474\n[-0.863636494 0.820047796]\n-44.5396347\n[-1.1201129 0.949611425]\n-44.3816147\n[-1.12899911 0.862236142]\n-44.345993\n[-1.12685108 0.883357823]\n-44.3414\n[-1.10480154 0.875246167]\n-44.3404579\n[-1.10684264 0.875997]\n-44.3404465\n[-1.10680723 0.876125395]\n-44.340435\n[-1.10666561 0.876639]\n-44.3404579\n[-1.10680497 0.876133442]\n-44.3404579\n[-1.10681212 0.876136899]\n-44.3404579\n[-1.10684061 0.876150608]\n-44.3404388\n[-1.10681224 0.876136899]\n-44.3404617\n[-1.10681212 0.876136839]\n-44.3404579\n[-1.10681224 0.876136899]\n-44.3404617\n"
],
[
"np.exp(optim_results.position.numpy())",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
cb49453168123579114451cf18b1a87c87f1d95d | 59,238 | ipynb | Jupyter Notebook | site/en/guide/function.ipynb | kewlcoder/docs | b0971871742a84c283c7aaa764ab13f127bd4439 | [
"Apache-2.0"
] | 1 | 2020-02-14T04:02:03.000Z | 2020-02-14T04:02:03.000Z | site/en/guide/function.ipynb | kewlcoder/docs | b0971871742a84c283c7aaa764ab13f127bd4439 | [
"Apache-2.0"
] | 32 | 2020-07-23T21:36:02.000Z | 2020-09-11T05:46:09.000Z | site/en/guide/function.ipynb | kewlcoder/docs | b0971871742a84c283c7aaa764ab13f127bd4439 | [
"Apache-2.0"
] | 2 | 2020-05-14T12:53:13.000Z | 2020-07-30T20:12:17.000Z | 36.164835 | 538 | 0.552787 | [
[
[
"##### Copyright 2020 The TensorFlow Authors.\n",
"_____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_____"
]
],
[
[
"# Better performance with tf.function\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/function\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/function.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/function.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/function.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"In TensorFlow 2, [eager execution](eager.ipynb) is turned on by default. The user interface is intuitive and flexible (running one-off operations is much easier and faster), but this can come at the expense of performance and deployability.\n\nYou can use `tf.function` to make graphs out of your programs. It is a transformation tool that creates Python-independent dataflow graphs out of your Python code. This will help you create performant and portable models, and it is required to use `SavedModel`.\n\nThis guide will help you conceptualize how `tf.function` works under the hood, so you can use it effectively.\n\nThe main takeaways and recommendations are:\n\n- Debug in eager mode, then decorate with `@tf.function`.\n- Don't rely on Python side effects like object mutation or list appends.\n- `tf.function` works best with TensorFlow ops; NumPy and Python calls are converted to constants.\n",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf",
"_____no_output_____"
]
],
[
[
"Define a helper function to demonstrate the kinds of errors you might encounter:",
"_____no_output_____"
]
],
[
[
"import traceback\nimport contextlib\n\n# Some helper code to demonstrate the kinds of errors you might encounter.\[email protected]\ndef assert_raises(error_class):\n try:\n yield\n except error_class as e:\n print('Caught expected exception \\n {}:'.format(error_class))\n traceback.print_exc(limit=2)\n except Exception as e:\n raise e\n else:\n raise Exception('Expected {} to be raised but no error was raised!'.format(\n error_class))",
"_____no_output_____"
]
],
[
[
"## Basics",
"_____no_output_____"
],
[
"### Usage\n\nA `Function` you define (for example by applying the `@tf.function` decorator) is just like a core TensorFlow operation: You can execute it eagerly; you can compute gradients; and so on.",
"_____no_output_____"
]
],
[
[
"@tf.function # The decorator converts `add` into a `Function`.\ndef add(a, b):\n return a + b\n\nadd(tf.ones([2, 2]), tf.ones([2, 2])) # [[2., 2.], [2., 2.]]",
"_____no_output_____"
],
[
"v = tf.Variable(1.0)\nwith tf.GradientTape() as tape:\n result = add(v, 1.0)\ntape.gradient(result, v)",
"_____no_output_____"
]
],
[
[
"You can use `Function`s inside other `Function`s.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef dense_layer(x, w, b):\n return add(tf.matmul(x, w), b)\n\ndense_layer(tf.ones([3, 2]), tf.ones([2, 2]), tf.ones([2]))",
"_____no_output_____"
]
],
[
[
"`Function`s can be faster than eager code, especially for graphs with many small ops. But for graphs with a few expensive ops (like convolutions), you may not see much speedup.\n",
"_____no_output_____"
]
],
[
[
"import timeit\nconv_layer = tf.keras.layers.Conv2D(100, 3)\n\[email protected]\ndef conv_fn(image):\n return conv_layer(image)\n\nimage = tf.zeros([1, 200, 200, 100])\n# Warm up\nconv_layer(image); conv_fn(image)\nprint(\"Eager conv:\", timeit.timeit(lambda: conv_layer(image), number=10))\nprint(\"Function conv:\", timeit.timeit(lambda: conv_fn(image), number=10))\nprint(\"Note how there's not much difference in performance for convolutions\")\n",
"_____no_output_____"
]
],
[
[
"### Tracing\n\nThis section exposes how `Function` works under the hood, including implementation details *which may change in the future*. However, once you understand why and when tracing happens, it's much easier to use `tf.function` effectively!",
"_____no_output_____"
],
[
"#### What is \"tracing\"?\n\nA `Function` runs your program in a [TensorFlow Graph](https://www.tensorflow.org/guide/intro_to_graphs#what_are_graphs). However, a `tf.Graph` cannot represent all the things that you'd write in an eager TensorFlow program. For instance, Python supports polymorphism, but `tf.Graph` requires its inputs to have a specified data type and dimension. Or you may perform side tasks like reading command-line arguments, raising an error, or working with a more complex Python object; none of these things can run in a `tf.Graph`.\n\n`Function` bridges this gap by separating your code in two stages:\n\n 1) In the first stage, referred to as \"**tracing**\", `Function` creates a new `tf.Graph`. Python code runs normally, but all TensorFlow operations (like adding two Tensors) are *deferred*: they are captured by the `tf.Graph` and not run.\n\n 2) In the second stage, a `tf.Graph` which contains everything that was deferred in the first stage is run. This stage is much faster than the tracing stage.\n\nDepending on its inputs, `Function` will not always run the first stage when it is called. See [\"Rules of tracing\"](#rules_of_tracing) below to get a better sense of how it makes that determination. Skipping the first stage and only executing the second stage is what gives you TensorFlow's high performance.\n\nWhen `Function` does decide to trace, the tracing stage is immediately followed by the second stage, so calling the `Function` both creates and runs the `tf.Graph`. Later you will see how you can run only the tracing stage with [`get_concrete_function`](#obtaining_concrete_functions).",
"_____no_output_____"
],
[
"When we pass arguments of different types into a `Function`, both stages are run:\n",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef double(a):\n print(\"Tracing with\", a)\n return a + a\n\nprint(double(tf.constant(1)))\nprint()\nprint(double(tf.constant(1.1)))\nprint()\nprint(double(tf.constant(\"a\")))\nprint()\n",
"_____no_output_____"
]
],
[
[
"Note that if you repeatedly call a `Function` with the same argument type, TensorFlow will skip the tracing stage and reuse a previously traced graph, as the generated graph would be identical.",
"_____no_output_____"
]
],
[
[
"# This doesn't print 'Tracing with ...'\nprint(double(tf.constant(\"b\")))",
"_____no_output_____"
]
],
[
[
"You can use `pretty_printed_concrete_signatures()` to see all of the available traces:",
"_____no_output_____"
]
],
[
[
"print(double.pretty_printed_concrete_signatures())",
"_____no_output_____"
]
],
[
[
"So far, you've seen that `tf.function` creates a cached, dynamic dispatch layer over TensorFlow's graph tracing logic. To be more specific about the terminology:\n\n- A `tf.Graph` is the raw, language-agnostic, portable representation of a TensorFlow computation.\n- A `ConcreteFunction` wraps a `tf.Graph`.\n- A `Function` manages a cache of `ConcreteFunction`s and picks the right one for your inputs.\n- `tf.function` wraps a Python function, returning a `Function` object.\n- **Tracing** creates a `tf.Graph` and wraps it in a `ConcreteFunction`, also known as a **trace.**\n",
"_____no_output_____"
],
[
"#### Rules of tracing\n\nA `Function` determines whether to reuse a traced `ConcreteFunction` by computing a **cache key** from an input's args and kwargs. A **cache key** is a key that identifies a `ConcreteFunction` based on the input args and kwargs of the `Function` call, according to the following rules (which may change):\n",
"_____no_output_____"
],
[
"- The key generated for a `tf.Tensor` is its shape and dtype.\n- The key generated for a `tf.Variable` is a unique variable id.\n- The key generated for a Python primitive (like `int`, `float`, `str`) is its value. \n- The key generated for nested `dict`s, `list`s, `tuple`s, `namedtuple`s, and [`attr`](https://www.attrs.org/en/stable/)s is the flattened tuple of leaf-keys (see `nest.flatten`). (As a result of this flattening, calling a concrete function with a different nesting structure than the one used during tracing will result in a TypeError).\n- For all other Python types the key is unique to the object. This way a function or method is traced independently for each instance it is called with.\n",
"_____no_output_____"
],
[
"Note: Cache keys are based on the `Function` input parameters so changes to global and [free variables](https://docs.python.org/3/reference/executionmodel.html#binding-of-names) alone will not create a new trace. See [this section](#depending_on_python_global_and_free_variables) for recommended practices when dealing with Python global and free variables.",
"_____no_output_____"
],
[
"#### Controlling retracing\n\nRetracing, which is when your `Function` creates more than one trace, helps ensures that TensorFlow generates correct graphs for each set of inputs. However, tracing is an expensive operation! If your `Function` retraces a new graph for every call, you'll find that your code executes more slowly than if you didn't use `tf.function`.\n\nTo control the tracing behavior, you can use the following techniques:",
"_____no_output_____"
],
[
"- Specify `input_signature` in `tf.function` to limit tracing.",
"_____no_output_____"
]
],
[
[
"@tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.int32),))\ndef next_collatz(x):\n print(\"Tracing with\", x)\n return tf.where(x % 2 == 0, x // 2, 3 * x + 1)\n\nprint(next_collatz(tf.constant([1, 2])))\n# You specified a 1-D tensor in the input signature, so this should fail.\nwith assert_raises(ValueError):\n next_collatz(tf.constant([[1, 2], [3, 4]]))\n\n# You specified an int32 dtype in the input signature, so this should fail.\nwith assert_raises(ValueError):\n next_collatz(tf.constant([1.0, 2.0]))\n",
"_____no_output_____"
]
],
[
[
"- Specify a \\[None\\] dimension in `tf.TensorSpec` to allow for flexibility in trace reuse.\n\n Since TensorFlow matches tensors based on their shape, using a `None` dimension as a wildcard will allow `Function`s to reuse traces for variably-sized input. Variably-sized input can occur if you have sequences of different length, or images of different sizes for each batch (See the [Transformer](../tutorials/text/transformer.ipynb) and [Deep Dream](../tutorials/generative/deepdream.ipynb) tutorials for example).",
"_____no_output_____"
]
],
[
[
"@tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.int32),))\ndef g(x):\n print('Tracing with', x)\n return x\n\n# No retrace!\nprint(g(tf.constant([1, 2, 3])))\nprint(g(tf.constant([1, 2, 3, 4, 5])))\n",
"_____no_output_____"
]
],
[
[
"- Cast Python arguments to Tensors to reduce retracing.\n\n Often, Python arguments are used to control hyperparameters and graph constructions - for example, `num_layers=10` or `training=True` or `nonlinearity='relu'`. So, if the Python argument changes, it makes sense that you'd have to retrace the graph.\n\n However, it's possible that a Python argument is not being used to control graph construction. In these cases, a change in the Python value can trigger needless retracing. Take, for example, this training loop, which AutoGraph will dynamically unroll. Despite the multiple traces, the generated graph is actually identical, so retracing is unnecessary.",
"_____no_output_____"
]
],
[
[
"def train_one_step():\n pass\n\[email protected]\ndef train(num_steps):\n print(\"Tracing with num_steps = \", num_steps)\n tf.print(\"Executing with num_steps = \", num_steps)\n for _ in tf.range(num_steps):\n train_one_step()\n\nprint(\"Retracing occurs for different Python arguments.\")\ntrain(num_steps=10)\ntrain(num_steps=20)\n\nprint()\nprint(\"Traces are reused for Tensor arguments.\")\ntrain(num_steps=tf.constant(10))\ntrain(num_steps=tf.constant(20))",
"_____no_output_____"
]
],
[
[
"If you need to force retracing, create a new `Function`. Separate `Function` objects are guaranteed not to share traces.",
"_____no_output_____"
]
],
[
[
"def f():\n print('Tracing!')\n tf.print('Executing')\n\ntf.function(f)()\ntf.function(f)()",
"_____no_output_____"
]
],
[
[
"### Obtaining concrete functions\n\nEvery time a function is traced, a new concrete function is created. You can directly obtain a concrete function, by using `get_concrete_function`.\n",
"_____no_output_____"
]
],
[
[
"print(\"Obtaining concrete trace\")\ndouble_strings = double.get_concrete_function(tf.constant(\"a\"))\nprint(\"Executing traced function\")\nprint(double_strings(tf.constant(\"a\")))\nprint(double_strings(a=tf.constant(\"b\")))\n",
"_____no_output_____"
],
[
"# You can also call get_concrete_function on an InputSpec\ndouble_strings_from_inputspec = double.get_concrete_function(tf.TensorSpec(shape=[], dtype=tf.string))\nprint(double_strings_from_inputspec(tf.constant(\"c\")))",
"_____no_output_____"
]
],
[
[
"Printing a `ConcreteFunction` displays a summary of its input arguments (with types) and its output type.",
"_____no_output_____"
]
],
[
[
"print(double_strings)",
"_____no_output_____"
]
],
[
[
"You can also directly retrieve a concrete function's signature.",
"_____no_output_____"
]
],
[
[
"print(double_strings.structured_input_signature)\nprint(double_strings.structured_outputs)",
"_____no_output_____"
]
],
[
[
"Using a concrete trace with incompatible types will throw an error",
"_____no_output_____"
]
],
[
[
"with assert_raises(tf.errors.InvalidArgumentError):\n double_strings(tf.constant(1))",
"_____no_output_____"
]
],
[
[
"You may notice that Python arguments are given special treatment in a concrete function's input signature. Prior to TensorFlow 2.3, Python arguments were simply removed from the concrete function's signature. Starting with TensorFlow 2.3, Python arguments remain in the signature, but are constrained to take the value set during tracing.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef pow(a, b):\n return a ** b\n\nsquare = pow.get_concrete_function(a=tf.TensorSpec(None, tf.float32), b=2)\nprint(square)",
"_____no_output_____"
],
[
"assert square(tf.constant(10.0)) == 100\n\nwith assert_raises(TypeError):\n square(tf.constant(10.0), b=3)",
"_____no_output_____"
]
],
[
[
"### Obtaining graphs\n\nEach concrete function is a callable wrapper around a `tf.Graph`. Although retrieving the actual `tf.Graph` object is not something you'll normally need to do, you can obtain it easily from any concrete function.",
"_____no_output_____"
]
],
[
[
"graph = double_strings.graph\nfor node in graph.as_graph_def().node:\n print(f'{node.input} -> {node.name}')\n",
"_____no_output_____"
]
],
[
[
"### Debugging\n\nIn general, debugging code is easier in eager mode than inside `tf.function`. You should ensure that your code executes error-free in eager mode before decorating with `tf.function`. To assist in the debugging process, you can call `tf.config.run_functions_eagerly(True)` to globally disable and reenable `tf.function`.\n\nWhen tracking down issues that only appear within `tf.function`, here are some tips:\n- Plain old Python `print` calls only execute during tracing, helping you track down when your function gets (re)traced.\n- `tf.print` calls will execute every time, and can help you track down intermediate values during execution.\n- `tf.debugging.enable_check_numerics` is an easy way to track down where NaNs and Inf are created.\n- `pdb` (the [Python debugger](https://docs.python.org/3/library/pdb.html)) can help you understand what's going on during tracing. (Caveat: `pdb` will drop you into AutoGraph-transformed source code.)",
"_____no_output_____"
],
[
"## AutoGraph transformations\n\nAutoGraph is a library that is on by default in `tf.function`, and transforms a subset of Python eager code into graph-compatible TensorFlow ops. This includes control flow like `if`, `for`, `while`.\n\nTensorFlow ops like `tf.cond` and `tf.while_loop` continue to work, but control flow is often easier to write and understand when written in Python.",
"_____no_output_____"
]
],
[
[
"# A simple loop\n\[email protected]\ndef f(x):\n while tf.reduce_sum(x) > 1:\n tf.print(x)\n x = tf.tanh(x)\n return x\n\nf(tf.random.uniform([5]))",
"_____no_output_____"
]
],
[
[
"If you're curious you can inspect the code autograph generates.",
"_____no_output_____"
]
],
[
[
"print(tf.autograph.to_code(f.python_function))",
"_____no_output_____"
]
],
[
[
"### Conditionals\n\nAutoGraph will convert some `if <condition>` statements into the equivalent `tf.cond` calls. This substitution is made if `<condition>` is a Tensor. Otherwise, the `if` statement is executed as a Python conditional.\n\nA Python conditional executes during tracing, so exactly one branch of the conditional will be added to the graph. Without AutoGraph, this traced graph would be unable to take the alternate branch if there is data-dependent control flow.\n\n`tf.cond` traces and adds both branches of the conditional to the graph, dynamically selecting a branch at execution time. Tracing can have unintended side effects; check out [AutoGraph tracing effects](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/control_flow.md#effects-of-the-tracing-process) for more information.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef fizzbuzz(n):\n for i in tf.range(1, n + 1):\n print('Tracing for loop')\n if i % 15 == 0:\n print('Tracing fizzbuzz branch')\n tf.print('fizzbuzz')\n elif i % 3 == 0:\n print('Tracing fizz branch')\n tf.print('fizz')\n elif i % 5 == 0:\n print('Tracing buzz branch')\n tf.print('buzz')\n else:\n print('Tracing default branch')\n tf.print(i)\n\nfizzbuzz(tf.constant(5))\nfizzbuzz(tf.constant(20))",
"_____no_output_____"
]
],
[
[
"See the [reference documentation](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/control_flow.md#if-statements) for additional restrictions on AutoGraph-converted if statements.",
"_____no_output_____"
],
[
"### Loops\n\nAutoGraph will convert some `for` and `while` statements into the equivalent TensorFlow looping ops, like `tf.while_loop`. If not converted, the `for` or `while` loop is executed as a Python loop.\n\nThis substitution is made in the following situations:\n\n- `for x in y`: if `y` is a Tensor, convert to `tf.while_loop`. In the special case where `y` is a `tf.data.Dataset`, a combination of `tf.data.Dataset` ops are generated.\n- `while <condition>`: if `<condition>` is a Tensor, convert to `tf.while_loop`.\n\nA Python loop executes during tracing, adding additional ops to the `tf.Graph` for every iteration of the loop.\n\nA TensorFlow loop traces the body of the loop, and dynamically selects how many iterations to run at execution time. The loop body only appears once in the generated `tf.Graph`.\n\nSee the [reference documentation](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/control_flow.md#while-statements) for additional restrictions on AutoGraph-converted `for` and `while` statements.",
"_____no_output_____"
],
[
"#### Looping over Python data\n\nA common pitfall is to loop over Python/NumPy data within a `tf.function`. This loop will execute during the tracing process, adding a copy of your model to the `tf.Graph` for each iteration of the loop.\n\nIf you want to wrap the entire training loop in `tf.function`, the safest way to do this is to wrap your data as a `tf.data.Dataset` so that AutoGraph will dynamically unroll the training loop.",
"_____no_output_____"
]
],
[
[
"def measure_graph_size(f, *args):\n g = f.get_concrete_function(*args).graph\n print(\"{}({}) contains {} nodes in its graph\".format(\n f.__name__, ', '.join(map(str, args)), len(g.as_graph_def().node)))\n\[email protected]\ndef train(dataset):\n loss = tf.constant(0)\n for x, y in dataset:\n loss += tf.abs(y - x) # Some dummy computation.\n return loss\n\nsmall_data = [(1, 1)] * 3\nbig_data = [(1, 1)] * 10\nmeasure_graph_size(train, small_data)\nmeasure_graph_size(train, big_data)\n\nmeasure_graph_size(train, tf.data.Dataset.from_generator(\n lambda: small_data, (tf.int32, tf.int32)))\nmeasure_graph_size(train, tf.data.Dataset.from_generator(\n lambda: big_data, (tf.int32, tf.int32)))",
"_____no_output_____"
]
],
[
[
"When wrapping Python/NumPy data in a Dataset, be mindful of `tf.data.Dataset.from_generator` versus ` tf.data.Dataset.from_tensors`. The former will keep the data in Python and fetch it via `tf.py_function` which can have performance implications, whereas the latter will bundle a copy of the data as one large `tf.constant()` node in the graph, which can have memory implications.\n\nReading data from files via `TFRecordDataset`, `CsvDataset`, etc. is the most effective way to consume data, as then TensorFlow itself can manage the asynchronous loading and prefetching of data, without having to involve Python. To learn more, see the [`tf.data`: Build TensorFlow input pipelines](../../guide/data) guide.",
"_____no_output_____"
],
[
"#### Accumulating values in a loop\n\nA common pattern is to accumulate intermediate values from a loop. Normally, this is accomplished by appending to a Python list or adding entries to a Python dictionary. However, as these are Python side effects, they will not work as expected in a dynamically unrolled loop. Use `tf.TensorArray` to accumulate results from a dynamically unrolled loop.",
"_____no_output_____"
]
],
[
[
"batch_size = 2\nseq_len = 3\nfeature_size = 4\n\ndef rnn_step(inp, state):\n return inp + state\n\[email protected]\ndef dynamic_rnn(rnn_step, input_data, initial_state):\n # [batch, time, features] -> [time, batch, features]\n input_data = tf.transpose(input_data, [1, 0, 2])\n max_seq_len = input_data.shape[0]\n\n states = tf.TensorArray(tf.float32, size=max_seq_len)\n state = initial_state\n for i in tf.range(max_seq_len):\n state = rnn_step(input_data[i], state)\n states = states.write(i, state)\n return tf.transpose(states.stack(), [1, 0, 2])\n \ndynamic_rnn(rnn_step,\n tf.random.uniform([batch_size, seq_len, feature_size]),\n tf.zeros([batch_size, feature_size]))",
"_____no_output_____"
]
],
[
[
"## Limitations\n\nTensorFlow `Function` has a few limitations by design that you should be aware of when converting a Python function to a `Function`.",
"_____no_output_____"
],
[
"### Executing Python side effects\n\nSide effects, like printing, appending to lists, and mutating globals, can behave unexpectedly inside a `Function`, sometimes executing twice or not all. They only happen the first time you call a `Function` with a set of inputs. Afterwards, the traced `tf.Graph` is reexecuted, without executing the Python code.\n\nThe general rule of thumb is to avoid relying on Python side effects in your logic and only use them to debug your traces. Otherwise, TensorFlow APIs like `tf.data`, `tf.print`, `tf.summary`, `tf.Variable.assign`, and `tf.TensorArray` are the best way to ensure your code will be executed by the TensorFlow runtime with each call.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef f(x):\n print(\"Traced with\", x)\n tf.print(\"Executed with\", x)\n\nf(1)\nf(1)\nf(2)\n",
"_____no_output_____"
]
],
[
[
"If you would like to execute Python code during each invocation of a `Function`, `tf.py_function` is an exit hatch. The drawback of `tf.py_function` is that it's not portable or particularly performant, cannot be saved with SavedModel, and does not work well in distributed (multi-GPU, TPU) setups. Also, since `tf.py_function` has to be wired into the graph, it casts all inputs/outputs to tensors.",
"_____no_output_____"
],
[
"#### Changing Python global and free variables\n\nChanging Python global and [free variables](https://docs.python.org/3/reference/executionmodel.html#binding-of-names) counts as a Python side effect, so it only happens during tracing.\n",
"_____no_output_____"
]
],
[
[
"external_list = []\n\[email protected]\ndef side_effect(x):\n print('Python side effect')\n external_list.append(x)\n\nside_effect(1)\nside_effect(1)\nside_effect(1)\n# The list append only happened once!\nassert len(external_list) == 1",
"_____no_output_____"
]
],
[
[
"You should avoid mutating containers like lists, dicts, other objects that live outside the `Function`. Instead, use arguments and TF objects. For example, the section [\"Accumulating values in a loop\"](#accumulating_values_in_a_loop) has one example of how list-like operations can be implemented.\n\nYou can, in some cases, capture and manipulate state if it is a [`tf.Variable`](https://www.tensorflow.org/guide/variable). This is how the weights of Keras models are updated with repeated calls to the same `ConcreteFunction`.",
"_____no_output_____"
],
[
"#### Using Python iterators and generators",
"_____no_output_____"
],
[
"Many Python features, such as generators and iterators, rely on the Python runtime to keep track of state. In general, while these constructs work as expected in eager mode, they are examples of Python side effects and therefore only happen during tracing.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef buggy_consume_next(iterator):\n tf.print(\"Value:\", next(iterator))\n\niterator = iter([1, 2, 3])\nbuggy_consume_next(iterator)\n# This reuses the first value from the iterator, rather than consuming the next value.\nbuggy_consume_next(iterator)\nbuggy_consume_next(iterator)\n",
"_____no_output_____"
]
],
[
[
"Just like how TensorFlow has a specialized `tf.TensorArray` for list constructs, it has a specialized `tf.data.Iterator` for iteration constructs. See the section on [AutoGraph transformations](#autograph_transformations) for an overview. Also, the [`tf.data`](https://www.tensorflow.org/guide/data) API can help implement generator patterns:\n",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef good_consume_next(iterator):\n # This is ok, iterator is a tf.data.Iterator\n tf.print(\"Value:\", next(iterator))\n\nds = tf.data.Dataset.from_tensor_slices([1, 2, 3])\niterator = iter(ds)\ngood_consume_next(iterator)\ngood_consume_next(iterator)\ngood_consume_next(iterator)",
"_____no_output_____"
]
],
[
[
"### Deleting tf.Variables between `Function` calls\n\nAnother error you may encounter is a garbage-collected variable. `ConcreteFunction`s only retain [WeakRefs](https://docs.python.org/3/library/weakref.html) to the variables they close over, so you must retain a reference to any variables.",
"_____no_output_____"
]
],
[
[
"external_var = tf.Variable(3)\[email protected]\ndef f(x):\n return x * external_var\n\ntraced_f = f.get_concrete_function(4)\nprint(\"Calling concrete function...\")\nprint(traced_f(4))\n\n# The original variable object gets garbage collected, since there are no more\n# references to it.\nexternal_var = tf.Variable(4)\nprint()\nprint(\"Calling concrete function after garbage collecting its closed Variable...\")\nwith assert_raises(tf.errors.FailedPreconditionError):\n traced_f(4)",
"_____no_output_____"
]
],
[
[
"### All outputs of a tf.function must be return values\n\nWith the exception of `tf.Variable`s, a tf.function must return all its\noutputs. Attempting to directly access any tensors from a function without\ngoing through return values causes \"leaks\".\n\nFor example, the function below \"leaks\" the tensor `a` through the Python\nglobal `x`:",
"_____no_output_____"
]
],
[
[
"x = None\n\[email protected]\ndef leaky_function(a):\n global x\n x = a + 1 # Bad - leaks local tensor\n return a + 2\n\ncorrect_a = leaky_function(tf.constant(1))\n\nprint(correct_a.numpy()) # Good - value obtained from function's returns\nwith assert_raises(AttributeError):\n x.numpy() # Bad - tensor leaked from inside the function, cannot be used here\nprint(x)",
"_____no_output_____"
]
],
[
[
"This is true even if the leaked value is also returned:",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef leaky_function(a):\n global x\n x = a + 1 # Bad - leaks local tensor\n return x # Good - uses local tensor\n\ncorrect_a = leaky_function(tf.constant(1))\n\nprint(correct_a.numpy()) # Good - value obtained from function's returns\nwith assert_raises(AttributeError):\n x.numpy() # Bad - tensor leaked from inside the function, cannot be used here\nprint(x)\n\[email protected]\ndef captures_leaked_tensor(b):\n b += x # Bad - `x` is leaked from `leaky_function`\n return b\n\nwith assert_raises(TypeError):\n captures_leaked_tensor(tf.constant(2))",
"_____no_output_____"
]
],
[
[
"Usually, leaks such as these occur when you use Python statements or data structures.\nIn addition to leaking inaccessible tensors, such statements are also likely wrong because they count as Python side effects, and are not guaranteed to execute at every function call.\n\nCommon ways to leak local tensors also include mutating an external Python collection, or an object:",
"_____no_output_____"
]
],
[
[
"class MyClass:\n\n def __init__(self):\n self.field = None\n\nexternal_list = []\nexternal_object = MyClass()\n\ndef leaky_function():\n a = tf.constant(1)\n external_list.append(a) # Bad - leaks tensor\n external_object.field = a # Bad - leaks tensor",
"_____no_output_____"
]
],
[
[
"## Known Issues\n\nIf your `Function` is not evaluating correctly, the error may be explained by these known issues which are planned to be fixed in the future.",
"_____no_output_____"
],
[
"### Depending on Python global and free variables\n\n`Function` creates a new `ConcreteFunction` when called with a new value of a Python argument. However, it does not do that for the Python closure, globals, or nonlocals of that `Function`. If their value changes in between calls to the `Function`, the `Function` will still use the values they had when it was traced. This is different from how regular Python functions work.\n\nFor that reason, we recommend a functional programming style that uses arguments instead of closing over outer names.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef buggy_add():\n return 1 + foo\n\[email protected]\ndef recommended_add(foo):\n return 1 + foo\n\nfoo = 1\nprint(\"Buggy:\", buggy_add())\nprint(\"Correct:\", recommended_add(foo))",
"_____no_output_____"
],
[
"print(\"Updating the value of `foo` to 100!\")\nfoo = 100\nprint(\"Buggy:\", buggy_add()) # Did not change!\nprint(\"Correct:\", recommended_add(foo))",
"_____no_output_____"
]
],
[
[
"You can close over outer names, as long as you don't update their values.\n",
"_____no_output_____"
],
[
"#### Depending on Python objects",
"_____no_output_____"
],
[
"The recommendation to pass Python objects as arguments into `tf.function` has a number of known issues, that are expected to be fixed in the future. In general, you can rely on consistent tracing if you use a Python primitive or `tf.nest`-compatible structure as an argument or pass in a *different* instance of an object into a `Function`. However, `Function` will *not* create a new trace when you pass **the same object and only change its attributes**.",
"_____no_output_____"
]
],
[
[
"class SimpleModel(tf.Module):\n def __init__(self):\n # These values are *not* tf.Variables.\n self.bias = 0.\n self.weight = 2.\n\[email protected]\ndef evaluate(model, x):\n return model.weight * x + model.bias\n\nsimple_model = SimpleModel()\nx = tf.constant(10.)\nprint(evaluate(simple_model, x))",
"_____no_output_____"
],
[
"print(\"Adding bias!\")\nsimple_model.bias += 5.0\nprint(evaluate(simple_model, x)) # Didn't change :(",
"_____no_output_____"
]
],
[
[
"Using the same `Function` to evaluate the updated instance of the model will be buggy since the updated model has the [same cache key](#rules_of_tracing) as the original model.\n\nFor that reason, we recommend that you write your `Function` to avoid depending on mutable object attributes or create new objects.\n\nIf that is not possible, one workaround is to make new `Function`s each time you modify your object to force retracing:",
"_____no_output_____"
]
],
[
[
"def evaluate(model, x):\n return model.weight * x + model.bias\n\nnew_model = SimpleModel()\nevaluate_no_bias = tf.function(evaluate).get_concrete_function(new_model, x)\n# Don't pass in `new_model`, `Function` already captured its state during tracing.\nprint(evaluate_no_bias(x)) ",
"_____no_output_____"
],
[
"print(\"Adding bias!\")\nnew_model.bias += 5.0\n# Create new Function and ConcreteFunction since you modified new_model.\nevaluate_with_bias = tf.function(evaluate).get_concrete_function(new_model, x)\nprint(evaluate_with_bias(x)) # Don't pass in `new_model`.",
"_____no_output_____"
]
],
[
[
"As [retracing can be expensive](https://www.tensorflow.org/guide/intro_to_graphs#tracing_and_performance), you can use `tf.Variable`s as object attributes, which can be mutated (but not changed, careful!) for a similar effect without needing a retrace.\n",
"_____no_output_____"
]
],
[
[
"class BetterModel:\n\n def __init__(self):\n self.bias = tf.Variable(0.)\n self.weight = tf.Variable(2.)\n\[email protected]\ndef evaluate(model, x):\n return model.weight * x + model.bias\n\nbetter_model = BetterModel()\nprint(evaluate(better_model, x))\n",
"_____no_output_____"
],
[
"print(\"Adding bias!\")\nbetter_model.bias.assign_add(5.0) # Note: instead of better_model.bias += 5\nprint(evaluate(better_model, x)) # This works!",
"_____no_output_____"
]
],
[
[
"### Creating tf.Variables\n\n`Function` only supports singleton `tf.Variable`s created once on the first call, and reused across subsequent function calls. The code snippet below would create a new `tf.Variable` in every function call, which results in a `ValueError` exception.\n\nExample:",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef f(x):\n v = tf.Variable(1.0)\n return v\n\nwith assert_raises(ValueError):\n f(1.0)",
"_____no_output_____"
]
],
[
[
"A common pattern used to work around this limitation is to start with a Python None value, then conditionally create the `tf.Variable` if the value is None:",
"_____no_output_____"
]
],
[
[
"class Count(tf.Module):\n def __init__(self):\n self.count = None\n\n @tf.function\n def __call__(self):\n if self.count is None:\n self.count = tf.Variable(0)\n return self.count.assign_add(1)\n\nc = Count()\nprint(c())\nprint(c())",
"_____no_output_____"
]
],
[
[
"#### Using with multiple Keras optimizers\nYou may encounter `ValueError: tf.function only supports singleton tf.Variables created on the first call.` when using more than one Keras optimizer with a `tf.function`. This error occurs because optimizers internally create `tf.Variables` when they apply gradients for the first time.",
"_____no_output_____"
]
],
[
[
"opt1 = tf.keras.optimizers.Adam(learning_rate = 1e-2)\nopt2 = tf.keras.optimizers.Adam(learning_rate = 1e-3)\n \[email protected]\ndef train_step(w, x, y, optimizer):\n with tf.GradientTape() as tape:\n L = tf.reduce_sum(tf.square(w*x - y))\n gradients = tape.gradient(L, [w])\n optimizer.apply_gradients(zip(gradients, [w]))\n\nw = tf.Variable(2.)\nx = tf.constant([-1.])\ny = tf.constant([2.])\n\ntrain_step(w, x, y, opt1)\nprint(\"Calling `train_step` with different optimizer...\")\nwith assert_raises(ValueError):\n train_step(w, x, y, opt2)",
"_____no_output_____"
]
],
[
[
"If you need to change the optimizer during training, a workaround is to create a new `Function` for each optimizer, calling the [`ConcreteFunction`](#obtaining_concrete_functions) directly.",
"_____no_output_____"
]
],
[
[
"opt1 = tf.keras.optimizers.Adam(learning_rate = 1e-2)\nopt2 = tf.keras.optimizers.Adam(learning_rate = 1e-3)\n\n# Not a tf.function.\ndef train_step(w, x, y, optimizer):\n with tf.GradientTape() as tape:\n L = tf.reduce_sum(tf.square(w*x - y))\n gradients = tape.gradient(L, [w])\n optimizer.apply_gradients(zip(gradients, [w]))\n\nw = tf.Variable(2.)\nx = tf.constant([-1.])\ny = tf.constant([2.])\n\n# Make a new Function and ConcreteFunction for each optimizer.\ntrain_step_1 = tf.function(train_step).get_concrete_function(w, x, y, opt1)\ntrain_step_2 = tf.function(train_step).get_concrete_function(w, x, y, opt2)\nfor i in range(10):\n if i % 2 == 0:\n train_step_1(w, x, y) # `opt1` is not used as a parameter. \n else:\n train_step_2(w, x, y) # `opt2` is not used as a parameter.",
"_____no_output_____"
]
],
[
[
"#### Using with multiple Keras models\n\nYou may also encounter `ValueError: tf.function only supports singleton tf.Variables created on the first call.` when passing different model instances to the same `Function`.\n\nThis error occurs because Keras models (which [do not have their input shape defined](https://www.tensorflow.org/guide/keras/custom_layers_and_models#best_practice_deferring_weight_creation_until_the_shape_of_the_inputs_is_known)) and Keras layers create `tf.Variables`s when they are first called. You may be attempting to initialize those variables inside a `Function`, which has already been called. To avoid this error, try calling `model.build(input_shape)` to initialize all the weights before training the model.\n",
"_____no_output_____"
],
[
"## Further reading\n\nTo learn about how to export and load a `Function`, see the [SavedModel guide](../../guide/saved_model). To learn more about graph optimizations that are performed after tracing, see the [Grappler guide](../../guide/graph_optimization). To learn how to optimize your data pipeline and profile your model, see the [Profiler guide](../../guide/profiler.md).",
"_____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"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb494d5f6fc1077186ae9c2f2e616b4ef477ea54 | 218,258 | ipynb | Jupyter Notebook | chapter08_ml/08_clustering.ipynb | tkondoh1022/cookbook-2nd-code | 52d8c6c0a199a9009dfaccbac3cc2e8dfd21a859 | [
"MIT"
] | null | null | null | chapter08_ml/08_clustering.ipynb | tkondoh1022/cookbook-2nd-code | 52d8c6c0a199a9009dfaccbac3cc2e8dfd21a859 | [
"MIT"
] | null | null | null | chapter08_ml/08_clustering.ipynb | tkondoh1022/cookbook-2nd-code | 52d8c6c0a199a9009dfaccbac3cc2e8dfd21a859 | [
"MIT"
] | null | null | null | 987.59276 | 129,228 | 0.953889 | [
[
[
"# 8.8. Detecting hidden structures in a dataset with clustering",
"_____no_output_____"
]
],
[
[
"from itertools import permutations\nimport numpy as np\nimport sklearn\nimport sklearn.decomposition as dec\nimport sklearn.cluster as clu\nimport sklearn.datasets as ds\nimport sklearn.model_selection as ms\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"X, y = ds.make_blobs(n_samples=200,\n n_features=2,\n centers=3,\n cluster_std=1.5,\n )",
"_____no_output_____"
],
[
"def relabel(cl):\n \"\"\"Relabel a clustering with three clusters\n to match the original classes.\"\"\"\n if np.max(cl) != 2:\n return cl\n perms = np.array(list(permutations((0, 1, 2))))\n i = np.argmin([np.sum(np.abs(perm[cl] - y))\n for perm in perms])\n p = perms[i]\n return p[cl]",
"_____no_output_____"
],
[
"def display_clustering(labels, title):\n \"\"\"Plot the data points with the cluster\n colors.\"\"\"\n\n # We relabel the classes when there are 3 clusters\n labels = relabel(labels)\n fig, axes = plt.subplots(1, 2, figsize=(8, 3),\n sharey=True)\n # Display the points with the true labels on the\n # left, and with the clustering labels on the\n # right.\n for ax, c, title in zip(\n axes,\n [y, labels],\n [\"True labels\", title]):\n ax.scatter(X[:, 0], X[:, 1], c=c, s=30,\n linewidths=0, cmap=plt.cm.rainbow)\n ax.set_title(title)",
"_____no_output_____"
],
[
"km = clu.KMeans()\nkm.fit(X)\ndisplay_clustering(km.labels_, \"KMeans\")",
"_____no_output_____"
],
[
"km = clu.KMeans(n_clusters=3)\nkm.fit(X)\ndisplay_clustering(km.labels_, \"KMeans(3)\")",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(2, 3,\n figsize=(10, 7),\n sharex=True,\n sharey=True)\n\naxes[0, 0].scatter(X[:, 0], X[:, 1],\n c=y, s=30,\n linewidths=0,\n cmap=plt.cm.rainbow)\naxes[0, 0].set_title(\"True labels\")\n\nfor ax, est in zip(axes.flat[1:], [\n clu.SpectralClustering(3),\n clu.AgglomerativeClustering(3),\n clu.MeanShift(),\n clu.AffinityPropagation(),\n clu.DBSCAN(),\n]):\n est.fit(X)\n c = relabel(est.labels_)\n ax.scatter(X[:, 0], X[:, 1], c=c, s=30,\n linewidths=0, cmap=plt.cm.rainbow)\n ax.set_title(est.__class__.__name__)\n\n# Fix the spacing between subplots.\nfig.tight_layout()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb494e1f7f26f91511bae90c429ebb14e21d5df4 | 26,134 | ipynb | Jupyter Notebook | python_lecture_two.ipynb | GalvanizeOpenSource/bdr-platte-intro-to-ds-oct-2018 | 0354fa9fe925fc7b10e2ab344b56bb32c3b574f8 | [
"BSD-3-Clause"
] | 2 | 2018-12-07T02:40:11.000Z | 2019-01-01T18:52:06.000Z | python_lecture_two.ipynb | GalvanizeOpenSource/bdr-platte-intro-to-ds-oct-2018 | 0354fa9fe925fc7b10e2ab344b56bb32c3b574f8 | [
"BSD-3-Clause"
] | null | null | null | python_lecture_two.ipynb | GalvanizeOpenSource/bdr-platte-intro-to-ds-oct-2018 | 0354fa9fe925fc7b10e2ab344b56bb32c3b574f8 | [
"BSD-3-Clause"
] | 2 | 2018-12-07T02:40:08.000Z | 2018-12-07T02:40:17.000Z | 20.991165 | 332 | 0.489936 | [
[
[
"### Strings - Quotation Marks",
"_____no_output_____"
]
],
[
[
"# Quotation marks must be matching. Both of the following work.\ngood_string = \"Hello, how are you?\"\nanother_good_string = 'Hello, how are you?'",
"_____no_output_____"
],
[
"# These strings will not work\nbad_string = 'Don't do that'",
"_____no_output_____"
],
[
"another_bad_string = \"Don't do that' ",
"_____no_output_____"
],
[
"# Notice you enclose the whole sentence in doubles if there is\n# a single within the sentence. \nsolution_to_bad_string = \"Don't do that.\"",
"_____no_output_____"
],
[
"# If for some reason you need both, escape with backslash\n# 'She said, \"Don't do that!\"'\nmy_escape_string = 'She said, \"Don\\'t do that!\"'\nprint(my_escape_string)",
"She said, \"Don't do that!\"\n"
],
[
"# Multiple line breaks\nmy_super_long_string = '''This is a\nstring that spans\nmultiple lines.'''\nprint(my_super_long_string)",
"This is a\nstring that spans\nmultiple lines.\n"
],
[
"# Another way for multiple line breaks\nmy_long_string = ('This is a\\n'\n'string that spans\\n'\n'multiple lines.')\nprint(my_long_string)",
"This is a\nstring that spans\nmultiple lines.\n"
]
],
[
[
"### String Type",
"_____no_output_____"
]
],
[
[
"# As with numeric, can assign strings to variables\n# and can check the type\nmy_string = 'Hello World'\ntype(my_string)",
"_____no_output_____"
]
],
[
[
"### String Operators + and *",
"_____no_output_____"
]
],
[
[
"# Use + to add two strings together\none = 'Hello, my name is '\ntwo = 'Erin'\nmy_name = one + two\nprint(my_name)",
"Hello, my name is Erin\n"
],
[
"# Use * to repeat a string a number of times\n# Notice that I told Python to add space between the strings\nrepeat_this = 'I will use descriptive variable names. ' \nrepeat_this * 3",
"_____no_output_____"
]
],
[
[
"### String Methods",
"_____no_output_____"
]
],
[
[
"# Notice the space at the end when the string prints\n'Repeating string ' * 3",
"_____no_output_____"
],
[
"# Let's use a method to get rid of that space\n# Use dot notation to call a method\n'Repeating string Repeating string Repeating string '.strip()",
"_____no_output_____"
],
[
"# Another example\n# Notice it removed white space from both start and end\n' Repeating string Repeating string Repeating string '.strip()",
"_____no_output_____"
],
[
"my_str_variable = 'this IS my STRING to PLAY around WITH.'\n# .capitalize()\ncap_str = my_str_variable.capitalize()\n# .upper()\nupp_str = my_str_variable.upper()\n# .lower()\nlow_str = my_str_variable.lower()\n# .replace()\nnew_str = my_str_variable.replace('STR', 'fl')\n# .split()\nsplit_str = my_str_variable.split()\n\nprint(cap_str)\nprint(upp_str)\nprint(low_str)\nprint(new_str)\nprint(split_str)",
"This is my string to play around with.\nTHIS IS MY STRING TO PLAY AROUND WITH.\nthis is my string to play around with.\nthis IS my flING to PLAY around WITH.\n['this', 'IS', 'my', 'STRING', 'to', 'PLAY', 'around', 'WITH.']\n"
],
[
"# Want to know all the methods available for strings?\n# type your string then dot-tab\nmy_str_variable",
"_____no_output_____"
]
],
[
[
"### String Indexing",
"_____no_output_____"
]
],
[
[
"# Grab a specific character\nmy_str_variable = 'Test String'\n\nsecond_char = my_str_variable[1]\nsixth_char = my_str_variable[5]\nlast_char = my_str_variable[-1]\nthird_from_last_char = my_str_variable[-3]\n\n# Notice the zero indexing\nprint(second_char)\nprint(sixth_char)\nprint(last_char)\nprint(third_from_last_char)",
"e\nS\ng\ni\n"
],
[
"# Grab characters in some subset (range)\nmy_str_variable = 'Test String'\n\n# This is called 'slicing'\nsubset1 = my_str_variable[1:3]\nsubset2 = my_str_variable[5:9]\nsubset3 = my_str_variable[-6:-1]\nsubset4 = my_str_variable[1:]\nsubset5 = my_str_variable[:-1]\n\n# Start at index, print everything up to end index\n# Inclusive on left, exclusive on right\nprint(subset1)\nprint(subset2)\nprint(subset3)\nprint(subset4)\nprint(subset5)",
"es\nStri\nStrin\nest String\nTest Strin\n"
],
[
"# Grab characters in steps\nmy_str_variable = 'Test String'\n\nevery_second = my_str_variable[::2]\nevery_third_between210 = my_str_variable[2:10:3]\n\nprint(every_second)\nprint(every_third_between210)",
"Ts tig\nsSi\n"
]
],
[
[
"### String Looping",
"_____no_output_____"
]
],
[
[
"string_to_loop = 'Denver is better than Colorado Springs'\n\n# find out the length of your string (the number of characters)\nlength_of_str = len(string_to_loop)\nprint(length_of_str)",
"38\n"
],
[
"# Loop through string with while loop\n\n# define your variables\nstring_to_loop = \"What's Up?\"\nlength_of_str = len(string_to_loop)\nidx = 0\n\n# loop until condition is met\nwhile idx < length_of_str:\n print(string_to_loop[idx])\n idx += 1",
"W\nh\na\nt\n'\ns\n \nU\np\n?\n"
],
[
"# Loop through string with for loop\n\n# define variables\nstring_to_loop = \"What's Up?\"\nlength_of_str = len(string_to_loop)\n\n# loop until end of string\nfor index in range(length_of_str):\n print(string_to_loop[index])\n \n# Notice the range() constructor: this tells the for\n# loop how long to continue. Thus our for loop will\n# continue for the length of the string",
"W\nh\na\nt\n'\ns\n \nU\np\n?\n"
],
[
"# The following for loop will do the same as above,\n# but it's considered cleaner code\n\nstring_to_loop = \"What's Up?\"\n\nfor char in string_to_loop:\n print(char)",
"W\nh\na\nt\n'\ns\n \nU\np\n?\n"
]
],
[
[
"### Zen of Python",
"_____no_output_____"
]
],
[
[
"# The Zen of Python\nimport 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"
]
],
[
[
"### String Formatting",
"_____no_output_____"
]
],
[
[
"my_name = 'Sean'\n\nprint('Hello, my name is {}.'.format(my_name))",
"Hello, my name is Sean.\n"
],
[
"# Now you can just update one variable without\n# having to retype the entire sentence \nmy_name = 'Erin'\n\nprint('Hello, my name is {}.'.format(my_name))\n\n# .format() told Python to format the string\n# the {} are the location to format.",
"Hello, my name is Erin.\n"
],
[
"# Multiple values to insert?\nname_one = 'Sean'\nname_two = 'Erin'\n\nprint('{1} is cooler than {0}.'.format(name_two, name_one))",
"Sean is cooler than Erin.\n"
],
[
"# If you don't tell .format() the order, it will\n# assume the order.\nprint('{} is cooler than {}.'.format(name_two, name_one))",
"Erin is cooler than Sean.\n"
],
[
"# .format() can also accept numbers\n# numbers can be formatted\n\n\nprint(\"To be precise, that's {:.1f} times.\".format(2))\n\n\n# Here, the {:.1f} told Python that you would pass\n# it a number which you wanted to be a float\n# with only one decimal place.",
"To be precise, that's 2.0 times.\n"
],
[
"'hello this is a test'.split()",
"_____no_output_____"
]
],
[
[
"### Lists",
"_____no_output_____"
]
],
[
[
"# Create a list by hard coding things into it\n# Notice: lists are enclosed with [] \nmy_first_lst = [1, 'hello', 3, 'goodbye']\n\n# Create a list by wrapping list() around\n# something you want to split apart\nmy_second_lst = list('hello')\n\nprint(my_first_lst)\nprint(my_second_lst)",
"[1, 'hello', 3, 'goodbye']\n['h', 'e', 'l', 'l', 'o']\n"
],
[
"# You can also create lists of lists\nlist_of_lists = [[1,2,3], ['erin', 'bob']]\nprint(list_of_lists)\n# look what happens when you index into a list of lists\nprint(list_of_lists[0])\n# what about getting into an inside list?\nprint(list_of_lists[1][0])",
"[[1, 2, 3], ['erin', 'bob']]\n[1, 2, 3]\nerin\n"
]
],
[
[
"### List Methods",
"_____no_output_____"
]
],
[
[
"my_list = [1,2,3,'erin']\n\n# .tab-complete to see methods for lists\nmy_list",
"_____no_output_____"
],
[
"my_lst = [1, 2, 3, 4]",
"_____no_output_____"
],
[
"# add an element to list\nmy_lst.append(5)\nprint(my_lst)",
"[1, 2, 3, 4, 5]\n"
],
[
"# remove last element and print it\nprint(my_lst.pop())\nprint(my_lst)",
"5\n[1, 2, 3, 4]\n"
],
[
"# remove element from list\nmy_lst.remove(4)\nprint(my_lst)",
"[1, 2, 3]\n"
],
[
"# reverse order of list\nmy_lst.reverse()\nprint(my_lst)",
"[3, 2, 1]\n"
],
[
"# sort the list\nmy_lst.sort()\nprint(my_lst)",
"[1, 2, 3]\n"
]
],
[
[
"### List Iteration",
"_____no_output_____"
]
],
[
[
"# define a list\nlist_of_nums = [1,2,3,4,5,6]\n\n# loop through list and print\nfor num in list_of_nums:\n print(num)",
"1\n2\n3\n4\n5\n6\n"
],
[
"# What if you need the index in a list?\n# There's a special method for that called\n# enumerate()\n\nlist_of_letters = ['a','b','c','d','e']\n\nfor index, letter in enumerate(list_of_letters):\n print(index, letter)",
"0 a\n1 b\n2 c\n3 d\n4 e\n"
],
[
"# Class challenge answer\n\nlist_of_nums = [1,2,3,456,32,75]\n\nfor idx, num in enumerate(list_of_nums):\n \n if (num % 3 == 0) and (num % 5 == 0):\n print(idx, num, 'FizzBuzz')\n elif num % 3 == 0:\n print(idx, num, 'Fizz')\n elif num % 5 == 0:\n print(idx, num, 'Buzz')\n else:\n print(idx, num)\n \n",
"0 1\n1 2\n2 3 Fizz\n3 456 Fizz\n4 32\n5 75 FizzBuzz\n"
]
],
[
[
"### List Comprehensions",
"_____no_output_____"
]
],
[
[
"# Let's transform this for loop into a comprehension loop\nmy_list = [1,2,3,4,5,6]\n\n# create an empty list that you will populate\nmy_squares = []\n\n# loop through your number list and append\n# the square of each number to the new list\nfor num in my_list:\n my_squares.append(num**2)\n \nprint(my_squares)",
"[1, 4, 9, 16, 25, 36]\n"
],
[
"# Now let's do the same thing with a list comprehension\nmy_squares_comp = [num**2 for num in my_list]",
"_____no_output_____"
],
[
"# Walk through this on white board\n\nprint(my_squares)\nprint(my_squares_comp)",
"[1, 4, 9, 16, 25, 36]\n[1, 4, 9, 16, 25, 36]\n"
],
[
"# What about building a list with a conditional?\nmy_num_list = [1,2,3,4,89,1234]\n\neven_numbers = []\nfor num in my_num_list:\n if num % 2 == 0:\n even_numbers.append(num)",
"[2, 4, 1234]\n"
],
[
"# Now with list comprehension\neven_numbers_comp = [num for num in my_num_list if num % 2 == 0]",
"_____no_output_____"
],
[
"print(even_numbers)\nprint(even_numbers_comp)",
"[2, 4, 1234]\n[2, 4, 1234]\n"
],
[
"# Class challenge question and answer\nclass_names = ['bob', 'sally', 'fred']\nshort_names = [ ]\nfor name in class_names:\n if len(name) <= 3:\n short_names.append(name)",
"_____no_output_____"
],
[
"short_names_comp = [name for name in class_names if len(name) <= 3]",
"_____no_output_____"
],
[
"print(short_names)\nprint(short_names_comp)",
"['bob']\n['bob']\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",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb494fd394d602bbfbbaf323d88c84ae32a87483 | 608,661 | ipynb | Jupyter Notebook | examples/Notebooks/flopy3_gridgen.ipynb | briochh/flopy | 51d4442cb0ff96024be0bc81c554a4e1d2d9ed78 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | examples/Notebooks/flopy3_gridgen.ipynb | briochh/flopy | 51d4442cb0ff96024be0bc81c554a4e1d2d9ed78 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | examples/Notebooks/flopy3_gridgen.ipynb | briochh/flopy | 51d4442cb0ff96024be0bc81c554a4e1d2d9ed78 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | 1,320.305857 | 532,264 | 0.953626 | [
[
[
"# FloPy Creating Layered Quadtree Grids with GRIDGEN\n\nFloPy has a module that can be used to drive the GRIDGEN program. This notebook shows how it works.\n\nThe Flopy GRIDGEN module requires that the gridgen executable can be called using subprocess **(i.e., gridgen is in your path)**.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# run installed version of flopy or add local path\ntry:\n import flopy\nexcept:\n fpth = os.path.abspath(os.path.join('..', '..'))\n sys.path.append(fpth)\n import flopy\n\nfrom flopy.utils.gridgen import Gridgen \n\nprint(sys.version)\nprint('numpy version: {}'.format(np.__version__))\nprint('matplotlib version: {}'.format(mpl.__version__))\nprint('flopy version: {}'.format(flopy.__version__))",
"flopy is installed in /Users/jdhughes/Documents/Development/flopy_git/flopy_us/flopy\n3.7.3 (default, Mar 27 2019, 16:54:48) \n[Clang 4.0.1 (tags/RELEASE_401/final)]\nnumpy version: 1.16.2\nmatplotlib version: 3.0.3\nflopy version: 3.2.12\n"
]
],
[
[
"## Setup Base MODFLOW Grid",
"_____no_output_____"
],
[
"GRIDGEN works off of a base MODFLOW grid. The following information defines the basegrid.",
"_____no_output_____"
]
],
[
[
"Lx = 100.\nLy = 100.\nnlay = 2\nnrow = 51\nncol = 51\ndelr = Lx / ncol\ndelc = Ly / nrow\nh0 = 10\nh1 = 5\ntop = h0\nbotm = np.zeros((nlay, nrow, ncol), dtype=np.float32)\nbotm[1, :, :] = -10.",
"_____no_output_____"
],
[
"ms = flopy.modflow.Modflow(rotation=-20.)\ndis = flopy.modflow.ModflowDis(ms, nlay=nlay, nrow=nrow, ncol=ncol, delr=delr,\n delc=delc, top=top, botm=botm)",
"_____no_output_____"
]
],
[
[
"## Create the Gridgen Object",
"_____no_output_____"
]
],
[
[
"model_ws = os.path.join('.', 'data')\ng = Gridgen(dis, model_ws=model_ws)",
"_____no_output_____"
]
],
[
[
"## Add an Optional Active Domain\nCells outside of the active domain will be clipped and not numbered as part of the final grid. If this step is not performed, then all cells will be included in the final grid.",
"_____no_output_____"
]
],
[
[
"# setup the active domain\nadshp = os.path.join(model_ws, 'ad0')\nadpoly = [[[(0, 0), (0, 60), (40, 80), (60, 0), (0, 0)]]]\n# g.add_active_domain(adpoly, range(nlay))",
"_____no_output_____"
]
],
[
[
"## Refine the Grid",
"_____no_output_____"
]
],
[
[
"x = Lx * np.random.random(10)\ny = Ly * np.random.random(10)\nwells = list(zip(x, y))\ng.add_refinement_features(wells, 'point', 3, range(nlay))\nrf0shp = os.path.join(model_ws, 'rf0')",
"_____no_output_____"
],
[
"river = [[[(-20, 10), (60, 60)]]]\ng.add_refinement_features(river, 'line', 3, range(nlay))\nrf1shp = os.path.join(model_ws, 'rf1')",
"_____no_output_____"
],
[
"g.add_refinement_features(adpoly, 'polygon', 1, range(nlay))\nrf2shp = os.path.join(model_ws, 'rf2')",
"_____no_output_____"
]
],
[
[
"## Plot the Gridgen Input",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(15, 15))\nax = fig.add_subplot(1, 1, 1, aspect='equal')\nmm = flopy.plot.ModelMap(model=ms)\nmm.plot_grid()\nflopy.plot.plot_shapefile(rf2shp, ax=ax, facecolor='yellow', edgecolor='none')\nflopy.plot.plot_shapefile(rf1shp, ax=ax, linewidth=10)\nflopy.plot.plot_shapefile(rf0shp, ax=ax, facecolor='red', radius=1)",
"/Users/jdhughes/Documents/Development/flopy_git/flopy_us/flopy/plot/map.py:1356: PendingDeprecationWarning: ModelMap will be replaced by PlotMapView(); Calling PlotMapView()\n warnings.warn(err_msg, PendingDeprecationWarning)\n"
]
],
[
[
"## Build the Grid",
"_____no_output_____"
]
],
[
[
"g.build(verbose=False)",
"_____no_output_____"
]
],
[
[
"## Plot the Grid",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(15, 15))\nax = fig.add_subplot(1, 1, 1, aspect='equal')\ng.plot(ax, linewidth=0.5)\nflopy.plot.plot_shapefile(rf2shp, ax=ax, facecolor='yellow', edgecolor='none', alpha=0.2)\nflopy.plot.plot_shapefile(rf1shp, ax=ax, linewidth=10, alpha=0.2)\nflopy.plot.plot_shapefile(rf0shp, ax=ax, facecolor='red', radius=1, alpha=0.2)",
"_____no_output_____"
]
],
[
[
"## Create a Flopy ModflowDisu Object",
"_____no_output_____"
]
],
[
[
"mu = flopy.modflow.Modflow(model_ws=model_ws, modelname='mfusg')\ndisu = g.get_disu(mu)\ndisu.write_file()\n# print(disu)",
"_____no_output_____"
]
],
[
[
"## Intersect Features with the Grid",
"_____no_output_____"
]
],
[
[
"adpoly_intersect = g.intersect(adpoly, 'polygon', 0)\nprint(adpoly_intersect.dtype.names)\nprint(adpoly_intersect)\nprint(adpoly_intersect.nodenumber)",
"('nodenumber', 'polyid', 'totalarea', 'SHAPEID')\n[( 614, 0, 0.961169 , 0) ( 613, 0, 0.961169 , 0) ( 617, 0, 0.961169 , 0)\n ... (6822, 0, 0.792964 , 0) (6825, 0, 0.0768934, 0)\n (6824, 0, 0.956363 , 0)]\n[ 614 613 617 ... 6822 6825 6824]\n"
],
[
"well_intersect = g.intersect(wells, 'point', 0)\nprint(well_intersect.dtype.names)\nprint(well_intersect)\nprint(well_intersect.nodenumber)",
"('nodenumber', 'pointid', 'SHAPEID')\n[(1172, 0, 0) (2943, 1, 1) (4798, 2, 2) (2432, 3, 3) (5016, 4, 4)\n (6177, 5, 5) ( 580, 6, 6) (2250, 7, 7) (1711, 8, 8) (6105, 9, 9)]\n[1172 2943 4798 2432 5016 6177 580 2250 1711 6105]\n"
],
[
"river_intersect = g.intersect(river, 'line', 0)\nprint(river_intersect.dtype.names)\n# print(river_intersect)\n# print(river_intersect.nodenumber)",
"('nodenumber', 'arcid', 'length', 'starting_distance', 'ending_distance', 'SHAPEID')\n"
]
],
[
[
"## Plot Intersected Features",
"_____no_output_____"
]
],
[
[
"a = np.zeros((g.nodes), dtype=np.int)\na[adpoly_intersect.nodenumber] = 1\na[well_intersect.nodenumber] = 2\na[river_intersect.nodenumber] = 3\nfig = plt.figure(figsize=(15, 15))\nax = fig.add_subplot(1, 1, 1, aspect='equal')\ng.plot(ax, a=a, masked_values=[0], edgecolor='none', cmap='jet')\nflopy.plot.plot_shapefile(rf2shp, ax=ax, facecolor='yellow', alpha=0.25)",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb494ff7d142a773ba08cdc05e6356718c24a18d | 921,204 | ipynb | Jupyter Notebook | ieee-preprocess-v1-0.ipynb | tarekoraby/IEEE-CIS-Fraud-Detection | 2f1ec955b318c5d98f7af0d5f8df4f969531e728 | [
"MIT"
] | null | null | null | ieee-preprocess-v1-0.ipynb | tarekoraby/IEEE-CIS-Fraud-Detection | 2f1ec955b318c5d98f7af0d5f8df4f969531e728 | [
"MIT"
] | null | null | null | ieee-preprocess-v1-0.ipynb | tarekoraby/IEEE-CIS-Fraud-Detection | 2f1ec955b318c5d98f7af0d5f8df4f969531e728 | [
"MIT"
] | null | null | null | 102.939323 | 139,572 | 0.726659 | [
[
[
"run_checks = False\nrun_sample = False",
"_____no_output_____"
]
],
[
[
"### Overview\nThis notebook works on the IEEE-CIS Fraud Detection competition. Here I build a simple XGBoost model based on a balanced dataset.",
"_____no_output_____"
],
[
"### Lessons:\n\n. keep the categorical variables as single items\n\n. Use a high max_depth for xgboost (maybe 40)\n\n\n### Ideas to try:\n\n. train divergence of expected value (eg. for TransactionAmt and distance based on the non-fraud subset (not all subset as in the case now)\n\n. try using a temporal approach to CV",
"_____no_output_____"
]
],
[
[
"# all imports necessary for this notebook\n%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport gc\nimport copy\nimport missingno as msno \nimport xgboost\nfrom xgboost import XGBClassifier, XGBRegressor\nfrom sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split \nfrom sklearn.metrics import roc_auc_score, r2_score\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))",
"/kaggle/input/ieee-fraud-detection/test_identity.csv\n/kaggle/input/ieee-fraud-detection/sample_submission.csv\n/kaggle/input/ieee-fraud-detection/train_identity.csv\n/kaggle/input/ieee-fraud-detection/train_transaction.csv\n/kaggle/input/ieee-fraud-detection/test_transaction.csv\n"
],
[
"# Helpers\n \ndef seed_everything(seed=0):\n '''Seed to make all processes deterministic '''\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n \ndef drop_correlated_cols(df, threshold, sample_frac = 1):\n '''Drops one of two dataframe's columns whose pairwise pearson's correlation is above the provided threshold'''\n if sample_frac != 1:\n dataset = df.sample(frac = sample_frac).copy()\n else:\n dataset = df\n \n col_corr = set() # Set of all the names of deleted columns\n corr_matrix = dataset.corr()\n for i in range(len(corr_matrix.columns)):\n if corr_matrix.columns[i] in col_corr:\n continue\n for j in range(i):\n if (corr_matrix.iloc[i, j] >= threshold) and (corr_matrix.columns[j] not in col_corr):\n colname = corr_matrix.columns[i] # getting the name of column\n col_corr.add(colname)\n del dataset\n gc.collect()\n df.drop(columns = col_corr, inplace = True)\n\ndef calc_feature_difference(df, feature_name, indep_features, min_r2 = 0.1, min_r2_improv = 0, frac1 = 0.1,\n max_depth_start = 2, max_depth_step = 4):\n \n from copy import deepcopy\n \n print(\"Feature name %s\" %feature_name)\n #print(\"Indep_features %s\" %indep_features)\n \n is_imrpoving = True\n curr_max_depth = max_depth_start\n best_r2 = float(\"-inf\")\n clf_best = np.nan\n \n while is_imrpoving:\n clf = XGBRegressor(max_depth = curr_max_depth)\n\n rand_sample_indeces = df[df[feature_name].notnull()].sample(frac = frac1).index\n clf.fit(df.loc[rand_sample_indeces, indep_features], df.loc[rand_sample_indeces, feature_name]) \n\n rand_sample_indeces = df[df[feature_name].notnull()].sample(frac = frac1).index\n \n pred_y = clf.predict(df.loc[rand_sample_indeces, indep_features])\n r2Score = r2_score(df.loc[rand_sample_indeces, feature_name], pred_y)\n print(\"%d, R2 score %.4f\" % (curr_max_depth, r2Score))\n \n curr_max_depth = curr_max_depth + max_depth_step\n \n if r2Score > best_r2:\n best_r2 = r2Score\n clf_best = deepcopy(clf)\n if r2Score < best_r2 + (best_r2 * min_r2_improv) or (curr_max_depth > max_depth_start * max_depth_step and best_r2 < min_r2 / 2):\n is_imrpoving = False\n\n print(\"The best R2 score of %.4f\" % ( best_r2))\n \n if best_r2 > min_r2:\n pred_feature = clf_best.predict(df.loc[:, indep_features])\n return (df[feature_name] - pred_feature)\n else:\n return df[feature_name]",
"_____no_output_____"
],
[
"seed_everything()\npd.set_option('display.max_columns', 500)",
"_____no_output_____"
],
[
"#read data\nfolder_path = '/kaggle/input/ieee-fraud-detection/'\ntrain_identity = pd.read_csv(f'{folder_path}train_identity.csv')\ntrain_transaction = pd.read_csv(f'{folder_path}train_transaction.csv')\ntest_identity = pd.read_csv(f'{folder_path}test_identity.csv')\ntest_transaction = pd.read_csv(f'{folder_path}test_transaction.csv')\nsample_submission = pd.read_csv(f'{folder_path}sample_submission.csv')\n# Merge identity and transaction data \ntrain_df = pd.merge(train_transaction, train_identity, on='TransactionID', how='left')\ntest_df = pd.merge(test_transaction, test_identity, on='TransactionID', how='left')\n\ndel train_identity, train_transaction, test_identity, test_transaction\ngc.collect()",
"_____no_output_____"
],
[
"print(train_df.shape)\nprint(test_df.shape)\ngc.collect()",
"(590540, 434)\n(506691, 433)\n"
],
[
"df_missing = pd.DataFrame((train_df.isnull().mean() * 100), columns=['missing_perc_train'])\ntest_missing = (test_df.isnull().mean() * 100)\ndf_missing = df_missing.join(test_missing.rename('missing_perc_test')).reset_index()\ndf_missing.rename(columns = {'index' :'Feature'}, inplace=True)\ndf_missing['missing_percent_avg'] = (df_missing['missing_perc_train'] + df_missing['missing_perc_test']) / 2\ndf_missing.sort_values(by=['missing_percent_avg', 'missing_perc_train', 'missing_perc_test'], inplace=True)\n#df_missing['abs_missing_percent_diff'] = np.abs(df_missing['missing_perc_train'] - df_missing['missing_perc_test'])\n#df_missing.sort_values(by=['abs_missing_percent_diff'], ascending=False)\nprint(df_missing.shape)\ndf_missing.head()",
"(434, 4)\n"
],
[
"df_missing[~df_missing.Feature.str.contains('isFraud')].set_index('Feature').plot(figsize=(15,7.5), grid=True)",
"_____no_output_____"
],
[
"df_missing[~df_missing.Feature.str.contains('isFraud')].loc[df_missing.missing_perc_train<50].set_index('Feature').plot(figsize=(15,7.5), grid=True)\n#df_missing.loc[df_missing.missing_perc_train<50].shape",
"_____no_output_____"
],
[
"gc.collect()",
"_____no_output_____"
],
[
"train_df['is_train_df'] = 1\ntest_df['is_train_df'] = 0\nprint(train_df.shape)\nprint(test_df.shape)",
"(590540, 435)\n(506691, 434)\n"
],
[
"cols_orig_train = train_df.columns\nmaster_df = pd.concat([train_df, test_df], ignore_index=True, sort =True).reindex(columns=cols_orig_train)\nprint(master_df.shape)\n#master_df.head()",
"(1097231, 435)\n"
],
[
"if run_sample:\n master_df = master_df.sample(frac = 0.25)",
"_____no_output_____"
],
[
"drop_correlated = False\nif drop_correlated:\n %%time\n print(master_df.shape)\n temp_df_must_keep = master_df[['TransactionID', 'TransactionDT', 'isFraud', 'is_train_df']].copy()\n drop_correlated_cols(master_df, 0.95, sample_frac = 0.5)\n cols_to_use = master_df.columns.difference(temp_df_must_keep.columns)\n master_df = pd.merge(temp_df_must_keep, master_df[cols_to_use], left_index=True, right_index=True, how='left', validate = 'one_to_one')\n master_df.sort_values(by=['TransactionID', 'TransactionDT'], inplace=True)\n gc.collect()\n print(master_df.shape)\n master_df.head()",
"_____no_output_____"
],
[
"if drop_correlated:\n del temp_df_must_keep\n gc.collect()",
"_____no_output_____"
],
[
"master_df.sort_values(by=['TransactionID', 'TransactionDT'], inplace=True)\ngc.collect()",
"_____no_output_____"
],
[
"del test_df, train_df\ngc.collect()",
"_____no_output_____"
],
[
"cols_all = set(master_df.columns)\n\ncols_target = 'isFraud'\n\ncols_cat = {'id_12', 'id_13', 'id_14', 'id_15', 'id_16', 'id_17', 'id_18', 'id_19', 'id_20', 'id_21', 'id_22', \n 'id_23', 'id_24', 'id_25', 'id_26', 'id_27', 'id_28', 'id_29', 'id_30', 'id_31', 'id_32', 'id_33', \n 'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType', 'DeviceInfo', 'ProductCD', 'card4', \n 'card6', 'M4','P_emaildomain', 'R_emaildomain', 'card1', 'card2', 'card3', 'card5', 'addr1', \n 'addr2', 'M1', 'M2', 'M3', 'M5', 'M6', 'M7', 'M8', 'M9'}\n\ncols_cont = set([col for col in cols_all if col not in cols_cat and col != cols_target] )\n# cols_cont.remove(cols_target)\nprint(len(cols_cat))\nprint(len(cols_cont))\nprint(len(cols_cat) + len(cols_cont))",
"49\n385\n434\n"
],
[
"msno.matrix(master_df[cols_cat].sample(10000))",
"_____no_output_____"
],
[
"msno.matrix(master_df[cols_cont].sample(10000))",
"_____no_output_____"
],
[
"master_df.loc[:, cols_cat] = master_df.loc[:, cols_cat].astype('category')",
"_____no_output_____"
],
[
"# Some FE\nmaster_df[['P_emaildomain_1', 'P_emaildomain_2', 'P_emaildomain_3']] = master_df['P_emaildomain'].str.split('.', expand=True)\nmaster_df[['R_emaildomain_1', 'R_emaildomain_2', 'R_emaildomain_3']] = master_df['R_emaildomain'].str.split('.', expand=True)\nmaster_df['P_emaildomain_4'] = master_df['P_emaildomain'].str.replace('^[^.]+.', '', regex=True)\nmaster_df['R_emaildomain_4'] = master_df['R_emaildomain'].str.replace('^[^.]+.', '', regex=True)\ncols_cat.update(['P_emaildomain_1', 'P_emaildomain_2', 'P_emaildomain_3', 'P_emaildomain_4', 'R_emaildomain_1', 'R_emaildomain_2', 'R_emaildomain_3', 'R_emaildomain_4'])",
"_____no_output_____"
],
[
"print('P_emaildomain_1', master_df['P_emaildomain_1'].unique())\nprint(80 * '-')\nprint('P_emaildomain_2', master_df['P_emaildomain_2'].unique())\nprint(80 * '-')\nprint('P_emaildomain_3', master_df['P_emaildomain_3'].unique())\nprint(80 * '-')\nprint('P_emaildomain_4', master_df['P_emaildomain_4'].unique())",
"P_emaildomain_1 [nan 'gmail' 'outlook' 'yahoo' 'mail' 'anonymous' 'hotmail' 'verizon'\n 'aol' 'me' 'comcast' 'optonline' 'cox' 'charter' 'rocketmail' 'prodigy'\n 'embarqmail' 'icloud' 'live' 'att' 'juno' 'ymail' 'sbcglobal' 'bellsouth'\n 'msn' 'q' 'centurylink' 'servicios-ta' 'earthlink' 'cfl' 'roadrunner'\n 'netzero' 'gmx' 'suddenlink' 'frontiernet' 'windstream' 'frontier' 'mac'\n 'aim' 'web' 'twc' 'cableone' 'sc' 'ptd' 'protonmail' 'scranton']\n--------------------------------------------------------------------------------\nP_emaildomain_2 [nan 'com' 'net' None 'es' 'rr' 'de' 'fr' 'co' 'edu']\n--------------------------------------------------------------------------------\nP_emaildomain_3 [nan None 'mx' 'com' 'uk' 'jp']\n--------------------------------------------------------------------------------\nP_emaildomain_4 [nan 'com' 'net' 'net.mx' 'com.mx' '' 'es' 'rr.com' 'de' 'fr' 'co.uk'\n 'co.jp' 'edu']\n"
],
[
"print(master_df.loc[:, master_df.dtypes == object].shape)\nprint(len(cols_cat))\n\ntemp_missing_cat = master_df.loc[:, cols_cat].isnull().sum()\ntemp_missing_cat.sort_values(inplace=True)\n\ntemp_missing_cat_train = master_df.loc[master_df['is_train_df'] ==1 , cols_cat].isnull().sum()\ntemp_missing_cat_test = master_df.loc[master_df['is_train_df'] ==0 , cols_cat].isnull().sum()\n\ntemp_len = len(master_df)\ntemp_len_train = len(master_df.loc[master_df['is_train_df'] ==1])\ntemp_len_test = len(master_df.loc[master_df['is_train_df'] ==0])\n\nfor col in temp_missing_cat.index:\n \n temp_missing_percent = temp_missing_cat[col] * 100 / temp_len\n temp_missing_percent_train = temp_missing_cat_train[col] * 100 / temp_len_train\n temp_missing_percent_test = temp_missing_cat_test[col] * 100 / temp_len_test\n print(\"\\n%s, missing is: %.1f%% (train: %.1f%%, test: %.1f%%), n_unique is: %s\\n\" \n %(col, temp_missing_percent, temp_missing_percent_train, temp_missing_percent_test, len(master_df.loc[:, col].unique()) ))\n temp_unique_list = master_df.loc[master_df[col].notnull(), col].astype(str).unique()\n temp_unique_list.sort()\n print(master_df.loc[:, col].value_counts().iloc[0:10])\n print(80* '-')\n print(80* '-')",
"(1097231, 8)\n57\n\ncard1, missing is: 0.0% (train: 0.0%, test: 0.0%), n_unique is: 17091\n\n7919 28015\n9500 26243\n15885 22691\n17188 19606\n15066 14606\n6019 13268\n12695 12732\n12544 12694\n2803 11043\n7585 10097\nName: card1, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nProductCD, missing is: 0.0% (train: 0.0%, test: 0.0%), n_unique is: 5\n\nW 800657\nC 137785\nR 73346\nH 62397\nS 23046\nName: ProductCD, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\ncard3, missing is: 0.4% (train: 0.3%, test: 0.6%), n_unique is: 134\n\n150.0 956845\n185.0 109960\n106.0 3543\n117.0 2841\n144.0 2633\n146.0 2470\n143.0 1670\n102.0 1198\n119.0 1091\n162.0 1039\nName: card3, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\ncard6, missing is: 0.4% (train: 0.3%, test: 0.6%), n_unique is: 5\n\ndebit 824959\ncredit 267648\ndebit or credit 30\ncharge card 16\nName: card6, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\ncard4, missing is: 0.4% (train: 0.3%, test: 0.6%), n_unique is: 5\n\nvisa 719649\nmastercard 347386\namerican express 16009\ndiscover 9524\nName: card4, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\ncard5, missing is: 0.8% (train: 0.7%, test: 0.9%), n_unique is: 139\n\n226.0 553537\n224.0 153109\n166.0 102930\n102.0 49491\n117.0 47061\n138.0 41839\n195.0 31896\n126.0 21737\n137.0 19450\n219.0 18326\nName: card5, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\ncard2, missing is: 1.6% (train: 1.5%, test: 1.7%), n_unique is: 502\n\n321.0 91731\n111.0 82537\n555.0 80404\n490.0 70496\n583.0 41503\n170.0 33411\n545.0 31894\n194.0 31511\n514.0 27225\n360.0 26532\nName: card2, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\naddr2, missing is: 12.0% (train: 11.1%, test: 12.9%), n_unique is: 94\n\n87.0 956415\n60.0 7125\n96.0 1246\n32.0 152\n65.0 131\n31.0 83\n16.0 77\n19.0 56\n69.0 44\n27.0 34\nName: addr2, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\naddr1, missing is: 12.0% (train: 11.1%, test: 12.9%), n_unique is: 442\n\n299.0 85045\n204.0 77069\n325.0 76902\n264.0 72580\n330.0 48387\n315.0 43035\n441.0 38890\n272.0 35929\n123.0 28700\n126.0 28198\nName: addr1, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nP_emaildomain_1, missing is: 14.9% (train: 16.0%, test: 13.7%), n_unique is: 46\n\ngmail 436796\nyahoo 186568\nhotmail 87414\nanonymous 71062\naol 52337\ncomcast 14474\nicloud 12316\noutlook 10797\natt 7647\nmsn 7480\nName: P_emaildomain_1, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nP_emaildomain, missing is: 14.9% (train: 16.0%, test: 13.7%), n_unique is: 61\n\ngmail.com 435803\nyahoo.com 182784\nhotmail.com 85649\nanonymous.com 71062\naol.com 52337\ncomcast.net 14474\nicloud.com 12316\noutlook.com 9934\natt.net 7647\nmsn.com 7480\nName: P_emaildomain, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nP_emaildomain_4, missing is: 14.9% (train: 16.0%, test: 13.7%), n_unique is: 13\n\ncom 877106\nnet 45780\ncom.mx 4297\nes 1762\nfr 1124\nde 1083\n 993\nrr.com 595\nco.uk 437\nnet.mx 303\nName: P_emaildomain_4, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nP_emaildomain_2, missing is: 15.0% (train: 16.1%, test: 13.8%), n_unique is: 10\n\ncom 881403\nnet 46083\nes 1762\nfr 1124\nde 1083\nrr 595\nco 538\nedu 2\nName: P_emaildomain_2, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM6, missing is: 29.9% (train: 28.7%, test: 31.4%), n_unique is: 3\n\nF 419433\nT 349499\nName: M6, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM3, missing is: 40.8% (train: 45.9%, test: 34.9%), n_unique is: 3\n\nT 518244\nF 131248\nName: M3, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM2, missing is: 40.8% (train: 45.9%, test: 34.9%), n_unique is: 3\n\nT 588323\nF 61169\nName: M2, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM1, missing is: 40.8% (train: 45.9%, test: 34.9%), n_unique is: 3\n\nT 649436\nF 56\nName: M1, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM4, missing is: 47.3% (train: 47.7%, test: 46.9%), n_unique is: 4\n\nM0 357789\nM2 122947\nM1 97306\nName: M4, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM8, missing is: 53.0% (train: 58.6%, test: 46.4%), n_unique is: 3\n\nF 323650\nT 192325\nName: M8, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM9, missing is: 53.0% (train: 58.6%, test: 46.4%), n_unique is: 3\n\nT 441935\nF 74040\nName: M9, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM7, missing is: 53.0% (train: 58.6%, test: 46.4%), n_unique is: 3\n\nF 444604\nT 71344\nName: M7, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nM5, missing is: 60.2% (train: 59.3%, test: 61.1%), n_unique is: 3\n\nF 240155\nT 196962\nName: M5, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_12, missing is: 73.9% (train: 75.6%, test: 72.0%), n_unique is: 3\n\nNotFound 243920\nFound 42220\nName: id_12, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_15, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 4\n\nFound 135690\nNew 119397\nUnknown 22875\nName: id_15, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_36, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nF 267353\nT 10609\nName: id_36, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_35, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nT 149464\nF 128498\nName: id_35, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_37, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nT 215149\nF 62813\nName: id_37, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_38, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nF 168980\nT 108982\nName: id_38, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_29, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nFound 149264\nNotFound 128492\nName: id_29, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_28, missing is: 74.7% (train: 76.1%, test: 73.0%), n_unique is: 3\n\nFound 151813\nNew 125943\nName: id_28, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nDeviceType, missing is: 74.7% (train: 76.2%, test: 73.0%), n_unique is: 3\n\ndesktop 159568\nmobile 118173\nName: DeviceType, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_31, missing is: 74.8% (train: 76.2%, test: 73.0%), n_unique is: 173\n\nmobile safari 11.0 23655\nchrome 63.0 22168\nchrome 70.0 16054\nie 11.0 for desktop 14203\nmobile safari 12.0 13098\nmobile safari generic 11474\nchrome 71.0 9489\nchrome 69.0 8294\nsafari generic 8195\nchrome 70.0 for android 7624\nName: id_31, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_17, missing is: 74.9% (train: 76.4%, test: 73.2%), n_unique is: 128\n\n166.0 150938\n225.0 116313\n102.0 1443\n159.0 690\n121.0 646\n100.0 539\n148.0 482\n191.0 378\n150.0 305\n142.0 285\nName: id_17, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_19, missing is: 74.9% (train: 76.4%, test: 73.2%), n_unique is: 569\n\n266.0 39541\n410.0 22414\n427.0 16646\n529.0 15893\n100.0 9998\n542.0 9784\n153.0 9518\n215.0 9133\n417.0 9010\n176.0 7786\nName: id_19, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_20, missing is: 74.9% (train: 76.4%, test: 73.2%), n_unique is: 548\n\n507.0 34192\n222.0 20843\n325.0 15427\n533.0 12483\n563.0 12280\n595.0 11814\n549.0 10970\n214.0 10945\n600.0 10345\n333.0 6979\nName: id_20, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nR_emaildomain_4, missing is: 75.1% (train: 76.8%, test: 73.2%), n_unique is: 13\n\ncom 254533\nnet 9540\ncom.mx 4207\nes 1572\nfr 1087\nde 1080\nco.uk 399\nnet.mx 303\n 196\nco.jp 104\nName: R_emaildomain_4, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nR_emaildomain_1, missing is: 75.1% (train: 76.8%, test: 73.2%), n_unique is: 46\n\ngmail 119081\nhotmail 54875\nanonymous 39644\nyahoo 24912\naol 7239\noutlook 5864\ncomcast 3513\nlive 3013\nicloud 2820\nmsn 1698\nName: R_emaildomain_1, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nR_emaildomain, missing is: 75.1% (train: 76.8%, test: 73.2%), n_unique is: 61\n\ngmail.com 118885\nhotmail.com 53166\nanonymous.com 39644\nyahoo.com 21405\naol.com 7239\noutlook.com 5011\ncomcast.net 3513\nicloud.com 2820\nyahoo.com.mx 2743\nmsn.com 1698\nName: R_emaildomain, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nR_emaildomain_2, missing is: 75.1% (train: 76.8%, test: 73.2%), n_unique is: 10\n\ncom 258740\nnet 9843\nes 1572\nfr 1087\nde 1080\nco 503\nrr 71\nedu 69\nName: R_emaildomain_2, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_13, missing is: 76.5% (train: 78.4%, test: 74.3%), n_unique is: 56\n\n52.0 109760\n27.0 73282\n49.0 26365\n64.0 14429\n33.0 10048\n14.0 6427\n20.0 3804\n63.0 2050\n62.0 1752\n25.0 1302\nName: id_13, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_16, missing is: 76.8% (train: 78.1%, test: 75.2%), n_unique is: 3\n\nFound 132805\nNotFound 122282\nName: id_16, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nDeviceInfo, missing is: 78.7% (train: 79.9%, test: 77.3%), n_unique is: 2800\n\nWindows 92710\niOS Device 38502\nMacOS 23722\nTrident/7.0 12330\nrv:11.0 2650\nSM-G532M Build/MMB29T 980\nrv:57.0 968\nSM-J700M Build/MMB29K 829\nSM-G610M Build/MMB29K 804\nSM-G531H Build/LMY48B 682\nName: DeviceInfo, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_14, missing is: 86.2% (train: 86.4%, test: 85.9%), n_unique is: 29\n\n-300.0 83733\n-360.0 31196\n-480.0 24245\n-420.0 8751\n-600.0 1010\n 60.0 687\n 0.0 364\n-240.0 297\n-180.0 204\n-540.0 195\nName: id_14, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_34, missing is: 86.3% (train: 86.8%, test: 85.8%), n_unique is: 5\n\nmatch_status:2 132185\nmatch_status:1 17377\nmatch_status:0 415\nmatch_status:-1 3\nName: id_34, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_32, missing is: 86.5% (train: 86.9%, test: 86.1%), n_unique is: 7\n\n24.0 104040\n32.0 44077\n16.0 121\n8.0 11\n0.0 6\n48.0 2\nName: id_32, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_30, missing is: 86.5% (train: 86.9%, test: 86.1%), n_unique is: 88\n\nWindows 10 42170\nWindows 7 23478\niOS 12.1.0 6349\nMac OS X 10_12_6 3884\niOS 11.2.1 3824\nMac OS X 10_11_6 3802\niOS 11.1.2 3776\nAndroid 7.0 3573\niOS 11.4.1 3539\nWindows 8.1 3308\nName: id_30, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_33, missing is: 86.9% (train: 87.6%, test: 86.1%), n_unique is: 462\n\n1920x1080 33742\n1366x768 15046\n1334x750 11550\n2208x1242 9113\n1440x900 8127\n1600x900 6603\n2048x1536 6556\n2436x1125 4230\n2560x1600 3871\n1280x800 3704\nName: id_33, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_18, missing is: 91.3% (train: 92.4%, test: 90.0%), n_unique is: 20\n\n15.0 53476\n13.0 25223\n12.0 8765\n17.0 4489\n18.0 1113\n20.0 960\n26.0 903\n11.0 368\n27.0 275\n21.0 207\nName: id_18, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_23, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 4\n\nIP_PROXY:TRANSPARENT 7203\nIP_PROXY:ANONYMOUS 2010\nIP_PROXY:HIDDEN 1018\nName: id_23, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_22, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 36\n\n14.0 9487\n41.0 487\n33.0 64\n43.0 23\n24.0 21\n27.0 18\n21.0 15\n36.0 14\n39.0 13\n22.0 9\nName: id_22, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_27, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 3\n\nFound 10214\nNotFound 17\nName: id_27, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_21, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 735\n\n252.0 3552\n711.0 1796\n228.0 469\n576.0 167\n255.0 162\n849.0 154\n277.0 139\n755.0 115\n596.0 114\n770.0 110\nName: id_21, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_26, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 116\n\n161.0 1576\n184.0 1196\n142.0 1126\n100.0 891\n119.0 669\n102.0 583\n147.0 547\n137.0 441\n169.0 410\n216.0 352\nName: id_26, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_25, missing is: 99.1% (train: 99.1%, test: 99.0%), n_unique is: 441\n\n321.0 5233\n205.0 569\n426.0 469\n442.0 188\n501.0 151\n371.0 132\n509.0 115\n524.0 114\n123.0 97\n126.0 64\nName: id_25, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nid_24, missing is: 99.1% (train: 99.2%, test: 99.1%), n_unique is: 18\n\n11.0 5666\n15.0 2948\n16.0 315\n21.0 222\n24.0 141\n18.0 104\n12.0 26\n19.0 24\n26.0 14\n17.0 9\nName: id_24, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nP_emaildomain_3, missing is: 99.5% (train: 99.5%, test: 99.5%), n_unique is: 6\n\nmx 4600\ncom 595\nuk 437\njp 101\nName: P_emaildomain_3, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\nR_emaildomain_3, missing is: 99.5% (train: 99.5%, test: 99.5%), n_unique is: 6\n\nmx 4510\nuk 399\njp 104\ncom 71\nName: R_emaildomain_3, dtype: int64\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n"
]
],
[
[
"Further FE",
"_____no_output_____"
]
],
[
[
"#focus on id_31\nmaster_df.id_31.astype(str).value_counts()[0:20]",
"_____no_output_____"
],
[
"#lowercase the whole column\nmaster_df['id_31'] = master_df['id_31'].loc[master_df['id_31'].notnull()].str.lower()",
"_____no_output_____"
],
[
"temp = list(master_df['id_31'].unique())\n\ntemp.remove(np.nan)\n#print(temp)\nnew_temp = []\nimport re\n#DATA = \"Hey, you - what are you doing here!?\"\n#print re.findall(r\"[\\w']+\", DATA)\nfor item in temp:\n #new_temp.extend(item.split())\n new_temp.extend(re.findall(r\"[\\w']+\", item))\nnew_temp\nfrom collections import Counter\nmost_common_words= [word for word, word_count in Counter(new_temp).most_common(1000)]\n\n#remove digits\nmost_common_words= [word for word in most_common_words if not word.isdigit()]\n\n#remove single letter words\nmost_common_words= [word for word in most_common_words if len(word) > 1]\n\nprint(most_common_words)",
"['chrome', 'for', 'android', 'firefox', 'samsung', 'google', 'browser', 'safari', 'search', 'application', 'mobile', 'ios', 'generic', 'opera', 'edge', 'ie', 'sm', 'uiwebview', 'desktop', 'tablet', 'other', 'webview', 'g532m', 'aol', 'sch', 'silk', 'g531h', 'waterfox', 'nokia', 'lumia', 'puffin', 'microsoft', 'windows', 'cyberfox', 'zte', 'blade', 'palemoon', 'maxthon', 'line', 'lg', 'iron', 'blu', 'dash', 'seamonkey', 'm4tel', 'm4', 'comodo', 'lanix', 'ilium', 'chromium', 'inco', 'minion', 'mozilla', 'cherry', 'icedragon', 'facebook', 'rim', 'uc', 'blackberry']\n"
],
[
"temp_min_n_in_cat_to_keep = 1000\n\ntemp_added_cols = set()\n\nfor word in most_common_words:\n temp_len = len(master_df['id_31'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains(word)])\n if temp_len >= temp_min_n_in_cat_to_keep:\n print(\"%s: %d \\n\" %(word, temp_len))\n temp_new_col_name = 'id_31' + '_' + word \n master_df[temp_new_col_name] = master_df['id_31'].str.contains(word)\n temp_added_cols.add(temp_new_col_name)\n print(master_df[temp_new_col_name].describe())\n print(80* '-')",
"chrome: 155502 \n\ncount 276907\nunique 2\ntop True\nfreq 155502\nName: id_31_chrome, dtype: object\n--------------------------------------------------------------------------------\nfor: 67953 \n\ncount 276907\nunique 2\ntop False\nfreq 208954\nName: id_31_for, dtype: object\n--------------------------------------------------------------------------------\nandroid: 50994 \n\ncount 276907\nunique 2\ntop False\nfreq 225913\nName: id_31_android, dtype: object\n--------------------------------------------------------------------------------\nfirefox: 14393 \n\ncount 276907\nunique 2\ntop False\nfreq 262514\nName: id_31_firefox, dtype: object\n--------------------------------------------------------------------------------\nsamsung: 4787 \n\ncount 276907\nunique 2\ntop False\nfreq 272120\nName: id_31_samsung, dtype: object\n--------------------------------------------------------------------------------\ngoogle: 2146 \n\ncount 276907\nunique 2\ntop False\nfreq 274761\nName: id_31_google, dtype: object\n--------------------------------------------------------------------------------\nbrowser: 4785 \n\ncount 276907\nunique 2\ntop False\nfreq 272122\nName: id_31_browser, dtype: object\n--------------------------------------------------------------------------------\nsafari: 69866 \n\ncount 276907\nunique 2\ntop False\nfreq 207041\nName: id_31_safari, dtype: object\n--------------------------------------------------------------------------------\nsearch: 1847 \n\ncount 276907\nunique 2\ntop False\nfreq 275060\nName: id_31_search, dtype: object\n--------------------------------------------------------------------------------\napplication: 1847 \n\ncount 276907\nunique 2\ntop False\nfreq 275060\nName: id_31_application, dtype: object\n--------------------------------------------------------------------------------\nmobile: 53482 \n\ncount 276907\nunique 2\ntop False\nfreq 223425\nName: id_31_mobile, dtype: object\n--------------------------------------------------------------------------------\nios: 2615 \n\ncount 276907\nunique 2\ntop False\nfreq 274292\nName: id_31_ios, dtype: object\n--------------------------------------------------------------------------------\ngeneric: 26141 \n\ncount 276907\nunique 2\ntop False\nfreq 250766\nName: id_31_generic, dtype: object\n--------------------------------------------------------------------------------\nedge: 11985 \n\ncount 276907\nunique 2\ntop False\nfreq 264922\nName: id_31_edge, dtype: object\n--------------------------------------------------------------------------------\nie: 16469 \n\ncount 276907\nunique 2\ntop False\nfreq 260438\nName: id_31_ie, dtype: object\n--------------------------------------------------------------------------------\ndesktop: 14203 \n\ncount 276907\nunique 2\ntop False\nfreq 262704\nName: id_31_desktop, dtype: object\n--------------------------------------------------------------------------------\ntablet: 1330 \n\ncount 276907\nunique 2\ntop False\nfreq 275577\nName: id_31_tablet, dtype: object\n--------------------------------------------------------------------------------\n"
],
[
"cols_cat = cols_cat.union(temp_added_cols)\n#cols_cat",
"_____no_output_____"
],
[
"corr = master_df[temp_added_cols].astype('float16').corr()\ncorr.style.background_gradient(cmap='coolwarm')",
"_____no_output_____"
],
[
"gc.collect()",
"_____no_output_____"
],
[
"master_df['id_31'].loc[master_df['id_31_chrome']== True].loc[master_df['id_31_android']== True].value_counts()",
"_____no_output_____"
],
[
"master_df['id_31_chrome_version'] = master_df['id_31'].loc[master_df['id_31_chrome'] & \n (master_df['id_31_generic']==False)].str.slice(start=7, stop=9)\nmaster_df['id_31_chrome_version'].loc[master_df['id_31_chrome_version'] ==''] = np.nan\n#master_df[['id_31', 'id_31_chrome_version']].loc[master_df['id_31_chrome_version'].notnull()].head(20)\nmaster_df['id_31_chrome_version'].value_counts()",
"_____no_output_____"
],
[
"rolling_window = 1000\nmin_rolling_window = 10\ntemp_df = master_df[['id_31_chrome_version']].loc[master_df['id_31_chrome_version'].notnull()].astype('float16')\ntemp_df['id_31_chrome_version_newness'] = temp_df['id_31_chrome_version'] / temp_df['id_31_chrome_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean()\n#train_df[new_col_name] = train_df[col] / train_df[col].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean().interpolate()",
"_____no_output_____"
],
[
"plt.plot(temp_df['id_31_chrome_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())\nplt.show()\nplt.plot(temp_df['id_31_chrome_version_newness'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())",
"_____no_output_____"
],
[
"master_df['id_31_chrome_version_newness'] = temp_df['id_31_chrome_version_newness']\nmaster_df.drop(columns=['id_31_chrome_version'], inplace=True)\ndel temp_df\ngc.collect()\ncols_cont.add('id_31_chrome_version_newness')",
"_____no_output_____"
],
[
"master_df['id_31'].loc[master_df['id_31_safari']== True].value_counts()",
"_____no_output_____"
],
[
"master_df['id_31_safari_version'] = np.nan\nmaster_df['id_31_safari_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('safari 8.0')] = 8\nmaster_df['id_31_safari_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('safari 9.0')] = 9\nmaster_df['id_31_safari_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('safari 10.0')] = 10\nmaster_df['id_31_safari_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('safari 11.0')] = 11\nmaster_df['id_31_safari_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('safari 12.0')] = 12",
"_____no_output_____"
],
[
"master_df['id_31_safari_version'].plot()",
"_____no_output_____"
],
[
"rolling_window = 20\nmin_rolling_window = 10\ntemp_df = master_df[['id_31_safari_version']].loc[master_df['id_31_safari_version'].notnull()].astype('float16')\ntemp_df['id_31_safari_version_newness'] = temp_df['id_31_safari_version'] / temp_df['id_31_safari_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean()\n#train_df[new_col_name] = train_df[col] / train_df[col].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean().interpolate()\n\nplt.plot(temp_df['id_31_safari_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())\nplt.show()\nplt.plot(temp_df['id_31_safari_version_newness'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())",
"_____no_output_____"
],
[
"temp_df['id_31_safari_version_newness'].hist()",
"_____no_output_____"
],
[
"master_df['id_31_safari_version_newness'] = temp_df['id_31_safari_version_newness']\nmaster_df.drop(columns=['id_31_safari_version'], inplace=True)\ndel temp_df\ngc.collect()\ncols_cont.add('id_31_safari_version_newness')",
"_____no_output_____"
],
[
"# id_31 values excluding chrome and safari\nmaster_df['id_31'].loc[(master_df['id_31_chrome']==False) & \n (master_df['id_31_safari']== False)].astype(str).value_counts()[0:16]",
"_____no_output_____"
],
[
"master_df.id_31.loc[master_df['id_31_edge']==True].value_counts()",
"_____no_output_____"
],
[
"master_df['id_31_edge_version'] = np.nan\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 13.0')] = 13\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 14.0')] = 14\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 15.0')] = 15\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 16.0')] = 16\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 17.0')] = 17\nmaster_df['id_31_edge_version'].loc[master_df['id_31'].notnull() & master_df['id_31'].str.contains('edge 18.0')] = 18",
"_____no_output_____"
],
[
"master_df['id_31_edge_version'].plot()",
"_____no_output_____"
],
[
"rolling_window = 100\nmin_rolling_window = 10\ntemp_df = master_df[['id_31_edge_version']].loc[master_df['id_31_edge_version'].notnull()].astype('float16')\ntemp_df['id_31_edge_version_newness'] = temp_df['id_31_edge_version'] / temp_df['id_31_edge_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean()\n#train_df[new_col_name] = train_df[col] / train_df[col].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean().interpolate()\n\nplt.plot(temp_df['id_31_edge_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())\nplt.show()\nplt.plot(temp_df['id_31_edge_version_newness'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())",
"_____no_output_____"
],
[
"master_df['id_31_edge_version_newness'] = temp_df['id_31_edge_version_newness']\nmaster_df.drop(columns=['id_31_edge_version'], inplace=True)\ndel temp_df\ngc.collect()\ncols_cont.add('id_31_edge_version_newness')",
"_____no_output_____"
],
[
"master_df.id_31.loc[master_df['id_31_firefox']==True].value_counts()",
"_____no_output_____"
],
[
"master_df['id_31_firefox_version'] = master_df['id_31'].loc[master_df['id_31_firefox']==True].str.slice(start=-4, stop=-2)\nmaster_df['id_31_firefox_version'].loc[master_df['id_31_firefox_version'] =='ef'] = np.nan\nmaster_df['id_31_firefox_version'].loc[master_df['id_31_firefox_version'] =='er'] = np.nan\n#master_df[['id_31', 'id_31_firefox_version']].loc[master_df['id_31_firefox_version'].notnull()].head(20)\nmaster_df['id_31_firefox_version'].value_counts()",
"_____no_output_____"
],
[
"master_df['id_31_firefox_version'].astype('float16').plot()",
"_____no_output_____"
],
[
"rolling_window = 1000\nmin_rolling_window = 100\ntemp_df = master_df[['id_31_firefox_version']].loc[master_df['id_31_firefox_version'].notnull()].astype('float16')\ntemp_df['id_31_firefox_version_newness'] = temp_df['id_31_firefox_version'] / temp_df['id_31_firefox_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean()\n#train_df[new_col_name] = train_df[col] / train_df[col].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean().interpolate()\n\nplt.plot(temp_df['id_31_firefox_version'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())\nplt.show()\nplt.plot(temp_df['id_31_firefox_version_newness'].rolling(rolling_window, center= True, min_periods=min_rolling_window).mean())",
"_____no_output_____"
],
[
"master_df['id_31_firefox_version_newness'] = temp_df['id_31_firefox_version_newness']\nmaster_df.drop(columns=['id_31_firefox_version'], inplace=True)\ndel temp_df\ngc.collect()\ncols_cont.add('id_31_firefox_version_newness')",
"_____no_output_____"
]
],
[
[
"That's enough with the id_31 variable (but can do the same for the samsung kind)",
"_____no_output_____"
]
],
[
[
"# check 'DeviceInfo' variable\nmaster_df['DeviceInfo'].astype(str).value_counts()[0:20]",
"_____no_output_____"
]
],
[
[
"No clear FE to do here .... move on",
"_____no_output_____"
]
],
[
[
"# check 'id_30'\nmaster_df['id_30'].astype(str).value_counts()[0:30]",
"_____no_output_____"
],
[
"#lowercase the whole column\nmaster_df['id_30'] = master_df['id_30'].loc[master_df['id_30'].notnull()].str.lower()",
"_____no_output_____"
],
[
"temp = list(master_df['id_30'].unique())\n\ntemp.remove(np.nan)\n#print(temp)\nnew_temp = []\nimport re\n#DATA = \"Hey, you - what are you doing here!?\"\n#print re.findall(r\"[\\w']+\", DATA)\nfor item in temp:\n #new_temp.extend(item.split())\n new_temp.extend(re.findall(r\"[\\w']+\", item))\nnew_temp\nfrom collections import Counter\nmost_common_words= [word for word, word_count in Counter(new_temp).most_common(1000)]\n\n#remove digits\nmost_common_words= [word for word in most_common_words if not word.isdigit()]\n\n#remove single letter words\nmost_common_words= [word for word in most_common_words if len(word) > 1]\n\nprint(most_common_words)",
"['mac', 'os', 'ios', 'android', 'windows', '10_11_6', 'linux', '10_7_5', '10_12_6', '10_13_1', '10_9_5', '10_10_5', '10_11_5', 'vista', '10_12_3', '10_12', '10_12_5', '10_8_5', 'xp', '10_6_8', '10_11_4', '10_12_1', '10_11_3', '10_12_4', '10_13_2', '10_12_2', 'func', 'other', '10_13_3', '10_13_4', '10_13_5', '10_13_6', '10_14_0', '10_14', '10_14_1', '10_14_2']\n"
],
[
"# Hard code most common words\nmost_common_words = ['mac', 'ios', 'android', 'windows', 'linux']\nmost_common_words",
"_____no_output_____"
],
[
"temp_min_n_in_cat_to_keep = 1000\n\ntemp_added_cols = set()\n\nfor word in most_common_words:\n temp_len = len(master_df['id_30'].loc[master_df['id_30'].notnull() & master_df['id_30'].str.contains(word)])\n if temp_len >= temp_min_n_in_cat_to_keep:\n print(\"%s: %d \\n\" %(word, temp_len))\n temp_new_col_name = 'id_30' + '_' + word \n master_df[temp_new_col_name] = master_df['id_30'].str.contains(word)\n temp_added_cols.add(temp_new_col_name)\n print(master_df[temp_new_col_name].describe())\n print(80* '-')",
"mac: 25634 \n\ncount 148224\nunique 2\ntop False\nfreq 122590\nName: id_30_mac, dtype: object\n--------------------------------------------------------------------------------\nios: 38502 \n\ncount 148224\nunique 2\ntop False\nfreq 109722\nName: id_30_ios, dtype: object\n--------------------------------------------------------------------------------\nandroid: 11783 \n\ncount 148224\nunique 2\ntop False\nfreq 136441\nName: id_30_android, dtype: object\n--------------------------------------------------------------------------------\nwindows: 69777 \n\ncount 148224\nunique 2\ntop False\nfreq 78447\nName: id_30_windows, dtype: object\n--------------------------------------------------------------------------------\nlinux: 2488 \n\ncount 148224\nunique 2\ntop False\nfreq 145736\nName: id_30_linux, dtype: object\n--------------------------------------------------------------------------------\n"
],
[
"cols_cat = cols_cat.union(temp_added_cols)\n#cols_cat",
"_____no_output_____"
],
[
"corr = master_df[temp_added_cols].astype('float16').corr()\ncorr.style.background_gradient(cmap='coolwarm')",
"_____no_output_____"
]
],
[
[
"enough FE with id_30 (though could code newness like done with 'id_31'",
"_____no_output_____"
]
],
[
[
"# FE of id_33\nmaster_df['id_33'].loc[master_df['id_33'].notnull()].astype(str).value_counts()[0:30]",
"_____no_output_____"
],
[
"gc.collect()",
"_____no_output_____"
],
[
"temp_df = pd.DataFrame()\ntemp_df[['id_33_1', 'id_33_2']] = master_df['id_33'].loc[master_df['id_33'].notnull()].str.split('x', expand=True)\ntemp_df = temp_df.astype('float64')\ntemp_df['id_33_1'].loc[temp_df['id_33_1']==0] = np.nan\ntemp_df['id_33_2'].loc[temp_df['id_33_2']==0] = np.nan",
"_____no_output_____"
],
[
"temp_df['id_33_resolution'] = temp_df['id_33_1'] * temp_df['id_33_2']\ntemp_df['id_33_resolution'] = np.log(temp_df['id_33_resolution'])\ntemp_df.describe()",
"_____no_output_____"
],
[
"master_df['id_33_resolution'] = temp_df['id_33_resolution']\ncols_cont.add('id_33_resolution')\ndel temp_df\ngc.collect()",
"_____no_output_____"
],
[
"master_df['id_33_resolution'].hist()",
"_____no_output_____"
]
],
[
[
"Moving now to some FE of continuous variables",
"_____no_output_____"
]
],
[
[
"# Decimal part of the 'TransactionAmt' feature\nmaster_df['TransactionAmt_decimal'] = ((master_df['TransactionAmt'] - master_df['TransactionAmt'].astype(int)) * 1000).astype(int)\n# Length of the 'TransactionAmt' feature\nmaster_df['TransactionAmt_decimal_length'] = master_df['TransactionAmt'].astype(str).str.split('.', expand=True)[1].str.len()\n\ncols_cont.update(['TransactionAmt_decimal', 'TransactionAmt_decimal_length'])",
"_____no_output_____"
],
[
"master_df['TransactionAmt_decimal_length'].hist()",
"_____no_output_____"
],
[
"gc.collect()",
"_____no_output_____"
],
[
"## Thanks to FChmiel (https://www.kaggle.com/fchmiel) for these two functions\ndef make_day_feature(df, offset=0, tname='TransactionDT'):\n \"\"\"\n Creates a day of the week feature, encoded as 0-6. \n \n Parameters:\n -----------\n df : pd.DataFrame\n df to manipulate.\n offset : float (default=0)\n offset (in days) to shift the start/end of a day.\n tname : str\n Name of the time column in df.\n \"\"\"\n # found a good offset is 0.58\n days = df[tname] / (3600*24) \n encoded_days = np.floor(days-1+offset) % 7\n return encoded_days\n\ndef make_hour_feature(df, tname='TransactionDT'):\n \"\"\"\n Creates an hour of the day feature, encoded as 0-23. \n \n Parameters:\n -----------\n df : pd.DataFrame\n df to manipulate.\n tname : str\n Name of the time column in df.\n \"\"\"\n hours = df[tname] / (3600) \n encoded_hours = np.floor(hours) % 24\n return encoded_hours",
"_____no_output_____"
],
[
"master_df['weekday'] = make_day_feature(master_df, offset=0.58)\nmaster_df['hours'] = make_hour_feature(master_df)\n \ncols_cat.update(['weekday', 'hours'])",
"_____no_output_____"
],
[
"# check all cols in either cols_cat or cols_cont\nprint(set(master_df.columns).difference(cols_cat.union(cols_cont)))\nprint(cols_cat.intersection(cols_cont))",
"{'isFraud'}\nset()\n"
],
[
"master_df.memory_usage().sum()",
"_____no_output_____"
],
[
"temp_cols_cat_list = list(cols_cat)\nmaster_df[temp_cols_cat_list] = master_df[temp_cols_cat_list].astype('category')\ngc.collect()\nmaster_df[cols_cat].describe()",
"_____no_output_____"
],
[
"master_df.memory_usage().sum()",
"_____no_output_____"
],
[
"master_df.drop(columns = ['id_30', 'id_31', 'id_33'], inplace = True)\ncols_cat.remove('id_30')\ncols_cat.remove('id_31')\ncols_cat.remove('id_33')",
"_____no_output_____"
],
[
"cols_cat_dummified = set()\nn_categories_to_keep = 24\n\nfor col in cols_cat:\n print(\"%s, \" %col, end=\"\")\n \n len_categories = len(master_df[col].loc[master_df[col].notnull()].unique())\n temp_col = master_df.loc[:, [col]]\n \n if n_categories_to_keep < len_categories:\n top_cats = list(temp_col[col].value_counts(ascending = False, normalize=False).iloc[:n_categories_to_keep].index) \n temp_col[col].cat.add_categories(['infrequent_category'], inplace = True)\n top_cats.append('infrequent_category')\n #print(list(top_cats))\n temp_col.loc[temp_col[col].notnull() & ~temp_col[col].isin(top_cats), [col]] = 'infrequent_category'\n temp_col[col].cat.remove_categories([cat for cat in temp_col[col].cat.categories if not cat in top_cats], inplace = True)\n \n temp_col = pd.get_dummies(temp_col, dummy_na=True)\n \n cols_cat_dummified.update(list(temp_col.columns))\n master_df[temp_col.columns] = temp_col\n \n del temp_col\n gc.collect()",
"id_18, card3, R_emaildomain_2, M1, id_37, id_14, P_emaildomain_3, id_15, id_31_browser, M4, card6, M8, hours, card4, id_13, id_31_google, R_emaildomain, P_emaildomain_4, id_31_tablet, id_30_mac, id_12, addr2, id_19, M6, M3, M5, card1, id_30_windows, id_31_android, id_16, id_31_firefox, id_34, M2, id_22, P_emaildomain, id_31_edge, DeviceType, id_26, P_emaildomain_2, addr1, id_31_application, id_30_android, id_35, ProductCD, M9, id_31_ios, id_36, id_20, id_38, id_21, id_24, card2, id_25, id_31_search, M7, id_31_ie, id_23, id_31_mobile, id_29, id_30_linux, weekday, id_31_safari, id_31_chrome, id_30_ios, card5, id_31_generic, P_emaildomain_1, R_emaildomain_3, id_27, id_31_desktop, id_31_for, R_emaildomain_4, id_28, R_emaildomain_1, id_31_samsung, id_17, id_32, DeviceInfo, "
],
[
"master_df[cols_cat_dummified].astype('category').describe()",
"_____no_output_____"
],
[
"master_df.shape",
"_____no_output_____"
],
[
"'''\nfor col in cols_cat:\n master_df[col] = master_df[col].astype('category').cat.codes\n'''",
"_____no_output_____"
],
[
"'''\nplt.plot(master_df['V91'].rolling(1000, center= True, min_periods=100).mean())\ntemp = calc_feature_difference(master_df, 'V91', indep_features, min_r2=0, max_depths_list=[2, 4, 8, 16])\nplt.plot(temp.rolling(1000, center= True, min_periods=100).mean())\n'''",
"_____no_output_____"
],
[
"'''\n%%time\nlength_ones = len(master_df[master_df['isFraud']==1])\ntrain_balanced = pd.concat([master_df[master_df['isFraud']==1], (master_df[master_df['isFraud']==0]).sample(length_ones)], axis=0)\n\nX_train, X_test, y_train, y_test = train_test_split(\n train_balanced.drop(columns=['isFraud', 'TransactionID', 'TransactionDT']), train_balanced['isFraud'], \n test_size=1/6, stratify =train_balanced['isFraud'], random_state=0)\n\n\n\nprint(X_train.shape)\nprint(X_test.shape)\n\nclf = XGBClassifier(max_depth=40)\nclf.fit(X_train, y_train)\npred_prob = clf.predict_proba(X_test)\npred_prob[:, 1]\nroc_score = roc_auc_score(y_test, pred_prob[:, 1])\nprint(\"roc_auc score %.4f\" % roc_score)\nxgboost.plot_importance(clf, max_num_features=20, importance_type='gain')\nxgboost.plot_importance(clf, max_num_features=20, importance_type='weight')\n'''",
"_____no_output_____"
],
[
"'''\ntemp = clf.get_booster().get_score(importance_type='gain')\ndf_gain = pd.DataFrame(temp.keys(), columns=['Feature'])\ndf_gain['Feature_importance'] = temp.values()\ndf_gain = df_gain.sort_values(by=['Feature_importance'], ascending = False)\ntemp = clf.get_booster().get_score(importance_type='weight')\ndf_weight = pd.DataFrame(temp.keys(), columns=['Feature'])\ndf_weight['Feature_importance'] = temp.values()\ndf_weight = df_weight.sort_values(by=['Feature_importance'], ascending = False)\n\ntemp_must_keep = ['isFraud', 'TransactionID', 'TransactionDT', 'is_train_df', 'weekday', 'hours', 'TransactionDT', 'ProductCD', 'card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'addr1', 'addr2']\n\ntemp_list_to_keep_100 = temp_must_keep.copy()\ntemp_list_to_keep_100.extend(df_gain['Feature'][0:100])\ntemp_list_to_keep_100.extend(df_weight['Feature'][0:100])\ntemp_list_to_keep_100 = list(set(temp_list_to_keep_100))\nprint(\"Len top 100 features according to gain and weight is %d\" % len(temp_list_to_keep_100))\n\ntemp_list_to_keep_200 = temp_must_keep.copy()\ntemp_list_to_keep_200.extend(df_gain['Feature'][0:200])\ntemp_list_to_keep_200.extend(df_weight['Feature'][0:200])\ntemp_list_to_keep_200 = list(set(temp_list_to_keep_200))\nprint(\"Len top 200 features according to gain and weight is %d\" % len(temp_list_to_keep_200))\n\n\ntemp_list_to_keep_300 = temp_must_keep.copy()\ntemp_list_to_keep_300.extend(df_gain['Feature'][0:300])\ntemp_list_to_keep_300.extend(df_weight['Feature'][0:300])\ntemp_list_to_keep_300 = list(set(temp_list_to_keep_300))\nprint(\"Len top 200 features according to gain and weight is %d\" % len(temp_list_to_keep_300))\n\ntemp_list_to_keep_all = temp_must_keep.copy()\ntemp_list_to_keep_all.extend(df_gain['Feature'][:])\nprint(\"Len top (all) features according to gain and weight is %d\" % len(temp_list_to_keep_all))\n'''",
"_____no_output_____"
],
[
"'''\nprint(temp_list_to_keep_100)\nprint(\"\\n\\n\" + (80 * '-') + \"\\n\\n\")\n\nprint(temp_list_to_keep_200)\nprint(\"\\n\\n\" + (80 * '-') + \"\\n\\n\")\n\nprint(temp_list_to_keep_300)\nprint(\"\\n\\n\" + (80 * '-') + \"\\n\\n\")\n\nprint(temp_list_to_keep_all)\nprint(\"\\n\\n\" + (80 * '-') + \"\\n\\n\")\n'''",
"_____no_output_____"
],
[
"temp_list_to_keep_100 = ['V112', 'M4_M1', 'P_emaildomain', 'R_emaildomain', 'card2_555.0', 'V320', 'V91', 'V314', 'V206', 'card2_225.0', 'id_31_chrome_version_newness', 'card4_american express', 'card1_9500', 'card1_9633', 'weekday_3.0', 'card1', 'D5', 'V145', 'P_emaildomain_1_infrequent_category', 'M7', 'M5_F', 'addr2_87.0', 'V20', 'hours', 'D2', 'addr2', 'P_emaildomain_verizon.net', 'id_01', 'V258', 'card3', 'V329', 'V223', 'card2_553.0', 'card1_17188', 'card2_infrequent_category', 'id_17_166.0', 'TransactionAmt_decimal', 'V162', 'C9', 'id_13', 'V177', 'id_14_-420.0', 'V304', 'dist2', 'V75', 'id_06', 'V254', 'V149', 'V269', 'V188', 'M4', 'V70', 'hours_5.0', 'weekday_2.0', 'id_20_612.0', 'D11', 'ProductCD_H', 'card6', 'addr1_299.0', 'C14', 'card1_infrequent_category', 'V131', 'dist1', 'D10', 'id_31_safari_version_newness', 'V152', 'D15', 'V283', 'V133', 'D14', 'V126', 'addr1_204.0', 'V324', 'V257', 'TransactionAmt', 'M6', 'V36', 'card2', 'V230', 'V209', 'id_02', 'V94', 'card4', 'hours_11.0', 'V173', 'P_emaildomain_comcast.net', 'card6_credit', 'ProductCD', 'V103', 'V310', 'V130', 'addr1_infrequent_category', 'card5_224.0', 'M8_F', 'V306', 'card2_490.0', 'P_emaildomain_hotmail.com', 'P_emaildomain_me.com', 'C10', 'M4_M0', 'card5', 'V244', 'V308', 'P_emaildomain_msn.com', 'id_17', 'P_emaildomain_infrequent_category', 'P_emaildomain_optonline.net', 'TransactionID', 'M9', 'id_20', 'card3_185.0', 'weekday_1.0', 'D3', 'V127', 'weekday_5.0', 'addr1_337.0', 'V285', 'V245', 'addr1_325.0', 'V35', 'addr1_485.0', 'V294', 'D1', 'D4', 'id_30_android', 'R_emaildomain_anonymous.com', 'card2_567.0', 'P_emaildomain_gmail.com', 'id_20_549.0', 'id_32_24.0', 'V12', 'V76', 'V102', 'C13', 'V87', 'V141', 'D9', 'ProductCD_R', 'card5_166.0', 'C1', 'id_05', 'isFraud', 'V201', 'M5', 'P_emaildomain_3', 'card2_321.0', 'V313', 'id_33_resolution', 'V99', 'V307', 'M3_F', 'V189', 'V191', 'addr1', 'V312', 'C8', 'C2', 'id_19', 'id_26', 'card3_150.0', 'M8', 'V53', 'weekday', 'R_emaildomain_2_com', 'card2_268.0', 'V56', 'C5', 'card2_481.0', 'addr1_472.0', 'id_20_333.0', 'V4', 'weekday_4.0', 'card3_144.0', 'C11', 'C6', 'is_train_df', 'M3', 'V176', 'TransactionDT', 'V208', 'id_14_60.0', 'P_emaildomain_2', 'M7_F', 'V315', 'V62', 'M6_F', 'V317', 'id_31_edge', 'DeviceInfo', 'V271', 'D8', 'V82', 'V128']\ntemp_list_to_keep_200 = ['M4_M1', 'addr1_315.0', 'card2_225.0', 'card1_9500', 'V288', 'V293', 'weekday_3.0', 'card1', 'D5', 'id_13_49.0', 'M7', 'V298', 'P_emaildomain_1_outlook', 'V77', 'card2_111.0', 'D2', 'addr2', 'V137', 'card1_17188', 'V75', 'V61', 'V79', 'V254', 'V269', 'M4', 'id_20_612.0', 'card3_143.0', 'D15', 'D14', 'V309', 'V230', 'V166', 'card4', 'id_17_100.0', 'hours_1.0', 'card5_229.0', 'DeviceInfo_Windows', 'card5', 'V117', 'id_31_ie', 'addr1_337.0', 'V35', 'addr1_485.0', 'card2_567.0', 'V291', 'V263', 'V12', 'V110', 'ProductCD_R', 'V49', 'id_05', 'isFraud', 'V201', 'P_emaildomain_3', 'V150', 'M3_F', 'V312', 'C8', 'card3_150.0', 'D13', 'addr1_264.0', 'D6', 'V225', 'V4', 'weekday_4.0', 'V302', 'M7_F', 'V97', 'card2_170.0', 'V82', 'V128', 'P_emaildomain', 'V74', 'card1_9633', 'V64', 'V100', 'V86', 'V243', 'V145', 'hours_22.0', 'M5_F', 'addr2_87.0', 'hours', 'R_emaildomain_gmail.com', 'id_19_infrequent_category', 'P_emaildomain_verizon.net', 'id_01', 'V258', 'id_19_193.0', 'V280', 'V10', 'TransactionAmt_decimal', 'V177', 'V311', 'V149', 'V188', 'V202', 'weekday_2.0', 'V78', 'card6', 'D10', 'V152', 'V126', 'id_19_312.0', 'addr1_204.0', 'V324', 'V257', 'M6', 'V209', 'id_02', 'V247', 'V105', 'hours_11.0', 'V173', 'P_emaildomain_comcast.net', 'V323', 'ProductCD', 'V103', 'M8_F', 'id_19_271.0', 'M4_M0', 'V244', 'id_17', 'TransactionID', 'weekday_1.0', 'card3_185.0', 'V301', 'D3', 'hours_15.0', 'V245', 'D4', 'P_emaildomain_anonymous.com', 'id_32_24.0', 'V102', 'D9', 'C1', 'id_20_507.0', 'id_25', 'id_20_401.0', 'V313', 'V99', 'V189', 'V191', 'addr1', 'card2_174.0', 'V48', 'id_26', 'V316', 'C5', 'C6', 'M3', 'V208', 'id_14_60.0', 'P_emaildomain_2', 'DeviceInfo', 'V271', 'V112', 'card2_555.0', 'V320', 'V91', 'V314', 'V206', 'card4_american express', 'V20', 'D7', 'id_18_15.0', 'V333', 'V223', 'card2_553.0', 'card2_infrequent_category', 'M2_F', 'P_emaildomain_yahoo.com', 'card5_195.0', 'card4_mastercard', 'V19', 'card2_361.0', 'dist2', 'id_06', 'P_emaildomain_4', 'R_emaildomain_hotmail.com', 'V70', 'hours_5.0', 'V115', 'ProductCD_H', 'V303', 'V40', 'C14', 'V54', 'V131', 'dist1', 'id_31_safari_version_newness', 'V283', 'V133', 'card5_236.0', 'addr1_184.0', 'V134', 'V37', 'TransactionAmt', 'V203', 'card2', 'DeviceInfo_Trident/7.0', 'card2_490.0', 'id_13_19.0', 'P_emaildomain_hotmail.com', 'P_emaildomain_infrequent_category', 'P_emaildomain_optonline.net', 'id_20_500.0', 'V285', 'addr1_325.0', 'R_emaildomain_anonymous.com', 'card1_12695', 'id_20_549.0', 'V76', 'card1_15885', 'addr1_231.0', 'V55', 'C13', 'V87', 'TransactionAmt_decimal_length', 'M5', 'card2_321.0', 'V129', 'V136', 'V165', 'P_emaildomain_outlook.com', 'addr1_441.0', 'M8', 'V144', 'id_19_321.0', 'card2_268.0', 'V56', 'addr1_472.0', 'id_20_333.0', 'V5', 'V296', 'V67', 'V176', 'TransactionDT', 'V3', 'V211', 'V315', 'card1_16132', 'V322', 'id_31_edge', 'D8', 'V171', 'R_emaildomain', 'P_emaildomain_bellsouth.net', 'id_31_chrome_version_newness', 'card1_12839', 'V13', 'hours_21.0', 'DeviceType', 'V21', 'P_emaildomain_1_infrequent_category', 'card1_10616', 'id_18', 'card3', 'V7', 'V329', 'id_14', 'card2_514.0', 'hours_17.0', 'id_17_166.0', 'V162', 'V45', 'C9', 'V38', 'id_13', 'V96', 'id_14_-420.0', 'M9_F', 'V304', 'V132', 'M2', 'id_16', 'V282', 'V221', 'D11', 'addr1_299.0', 'card1_infrequent_category', 'card2_360.0', 'hours_19.0', 'DeviceInfo_SM-J700M Build/MMB29K', 'V194', 'V36', 'V94', 'V224', 'addr1_infrequent_category', 'V130', 'card6_credit', 'V249', 'P_emaildomain_live.com', 'V310', 'card5_224.0', 'V306', 'P_emaildomain_me.com', 'C10', 'card4_discover', 'C12', 'V308', 'P_emaildomain_msn.com', 'M9', 'id_20', 'V264', 'V127', 'V122', 'weekday_5.0', 'V294', 'D1', 'V47', 'id_30_android', 'P_emaildomain_gmail.com', 'hours_18.0', 'id_38', 'V141', 'id_36', 'card5_166.0', 'V83', 'V2', 'id_33_resolution', 'V307', 'hours_3.0', 'addr1_330.0', 'hours_16.0', 'hours_20.0', 'C2', 'id_19', 'V281', 'V53', 'P_emaildomain_4_com', 'weekday', 'id_31_tablet_False', 'R_emaildomain_2_com', 'V44', 'card2_481.0', 'V318', 'card1_6019', 'card3_144.0', 'C11', 'card5_226.0', 'is_train_df', 'addr1_181.0', 'id_20_533.0', 'V62', 'addr1_433.0', 'M6_F', 'V317']\ntemp_list_to_keep_300 = ['M4_M1', 'addr1_315.0', 'card2_225.0', 'card1_9500', 'V288', 'V293', 'P_emaildomain_icloud.com', 'DeviceInfo_infrequent_category', 'weekday_3.0', 'card1', 'D5', 'id_13_49.0', 'M7', 'V298', 'P_emaildomain_1_outlook', 'V77', 'card2_111.0', 'D2', 'addr2', 'V137', 'card1_17188', 'hours_14.0', 'V75', 'V61', 'id_09', 'V79', 'V254', 'hours_12.0', 'V66', 'V269', 'M4', 'V265', 'id_19_427.0', 'id_20_612.0', 'id_20_325.0', 'V292', 'card3_143.0', 'D15', 'D14', 'V109', 'V69', 'id_19_266.0', 'V309', 'V230', 'V166', 'card4', 'id_17_100.0', 'hours_1.0', 'card5_229.0', 'V34', 'DeviceInfo_Windows', 'card5', 'V117', 'id_31_ie', 'addr1_387.0', 'addr1_337.0', 'V273', 'V35', 'addr1_485.0', 'card2_567.0', 'V291', 'id_19_410.0', 'V263', 'V12', 'id_31_android', 'id_13_52.0', 'id_03', 'V110', 'ProductCD_R', 'V6', 'P_emaildomain_aol.com', 'V49', 'id_05', 'isFraud', 'V201', 'P_emaildomain_3', 'V150', 'M3_F', 'V312', 'id_20_597.0', 'V270', 'C8', 'card3_150.0', 'D13', 'addr1_264.0', 'D6', 'V225', 'addr2_60.0', 'V4', 'weekday_4.0', 'V154', 'V214', 'id_20_infrequent_category', 'V302', 'M7_F', 'V97', 'card2_170.0', 'card1_7508', 'V82', 'V128', 'card2_583.0', 'P_emaildomain', 'V234', 'V74', 'card1_9633', 'P_emaildomain_live.com.mx', 'V64', 'V100', 'V146', 'V86', 'V243', 'V145', 'hours_22.0', 'M5_F', 'addr2_87.0', 'hours', 'R_emaildomain_gmail.com', 'id_19_infrequent_category', 'P_emaildomain_verizon.net', 'id_01', 'V258', 'id_19_193.0', 'V280', 'card1_2884', 'V248', 'card5_102.0', 'V10', 'TransactionAmt_decimal', 'V177', 'V311', 'V149', 'V188', 'V202', 'weekday_2.0', 'V78', 'card6', 'D10', 'V152', 'V218', 'V51', 'V126', 'id_19_312.0', 'V222', 'addr1_204.0', 'V324', 'V257', 'V267', 'V332', 'M6', 'V209', 'id_02', 'V247', 'V105', 'hours_11.0', 'V173', 'P_emaildomain_comcast.net', 'V323', 'ProductCD', 'V103', 'M8_F', 'id_19_271.0', 'M4_M0', 'V244', 'id_17', 'TransactionID', 'weekday_1.0', 'card3_185.0', 'V301', 'D3', 'hours_15.0', 'V245', 'D4', 'id_14_-360.0', 'P_emaildomain_anonymous.com', 'id_32_24.0', 'V102', 'D9', 'C1', 'id_20_507.0', 'id_25', 'id_20_401.0', 'V287', 'V313', 'V99', 'V189', 'V191', 'addr1', 'card2_174.0', 'V48', 'id_26', 'V316', 'C5', 'V279', 'C6', 'card5_117.0', 'M3', 'V208', 'id_14_60.0', 'P_emaildomain_2', 'V160', 'DeviceInfo', 'V271', 'V319', 'V112', 'id_20_595.0', 'card2_555.0', 'V320', 'V91', 'V314', 'card1_15066', 'V206', 'V25', 'card4_american express', 'V295', 'addr1_126.0', 'V20', 'D7', 'id_18_15.0', 'V333', 'V95', 'V223', 'card2_553.0', 'card2_infrequent_category', 'M2_F', 'P_emaildomain_yahoo.com', 'card5_195.0', 'card4_mastercard', 'V19', 'V272', 'card2_361.0', 'dist2', 'V23', 'id_06', 'P_emaildomain_4', 'V24', 'R_emaildomain_hotmail.com', 'V139', 'V337', 'V70', 'hours_5.0', 'id_20_222.0', 'V115', 'ProductCD_H', 'V135', 'V303', 'V40', 'C14', 'V54', 'V131', 'V161', 'dist1', 'id_31_safari_version_newness', 'V283', 'V133', 'card5_236.0', 'addr1_184.0', 'card5_198.0', 'V253', 'V134', 'V170', 'card3_infrequent_category', 'V37', 'TransactionAmt', 'hours_2.0', 'V203', 'card2', 'DeviceInfo_Trident/7.0', 'P_emaildomain_hotmail.com', 'id_13_19.0', 'card2_490.0', 'id_30_windows', 'P_emaildomain_infrequent_category', 'P_emaildomain_optonline.net', 'id_20_500.0', 'V285', 'addr1_325.0', 'R_emaildomain_anonymous.com', 'card1_12695', 'V192', 'id_20_549.0', 'P_emaildomain_1_hotmail', 'V76', 'card1_15885', 'addr1_231.0', 'V151', 'V55', 'C13', 'V87', 'TransactionAmt_decimal_length', 'V104', 'M5', 'card2_321.0', 'V290', 'V129', 'V136', 'V164', 'V165', 'P_emaildomain_outlook.com', 'addr1_441.0', 'M8', 'V144', 'id_19_321.0', 'card2_268.0', 'V56', 'addr1_472.0', 'id_20_333.0', 'V5', 'V296', 'V67', 'id_31_for', 'V60', 'id_34', 'V176', 'TransactionDT', 'V3', 'card2_215.0', 'V211', 'V315', 'card1_16132', 'V322', 'id_31_edge', 'D8', 'V171', 'V52', 'R_emaildomain', 'V226', 'P_emaildomain_bellsouth.net', 'id_31_chrome_version_newness', 'card5_219.0', 'card1_12839', 'V13', 'hours_21.0', 'V39', 'DeviceType', 'addr1_310.0', 'V21', 'P_emaildomain_1_infrequent_category', 'card1_10616', 'V116', 'id_31_chrome', 'card1_7919', 'id_18', 'card3', 'V7', 'V329', 'id_14', 'card2_514.0', 'hours_17.0', 'V124', 'id_17_166.0', 'V162', 'V45', 'C9', 'V38', 'id_13', 'V96', 'id_14_-420.0', 'M9_F', 'V304', 'card1_7585', 'V132', 'M2', 'id_16', 'P_emaildomain_cox.net', 'V282', 'V221', 'id_19_100.0', 'D11', 'V90', 'DeviceInfo_MacOS', 'addr1_299.0', 'hours_6.0', 'card1_infrequent_category', 'card2_360.0', 'hours_19.0', 'DeviceInfo_SM-J700M Build/MMB29K', 'V194', 'V143', 'V36', 'V94', 'V224', 'addr1_infrequent_category', 'V130', 'card6_credit', 'V249', 'P_emaildomain_live.com', 'V310', 'V187', 'card5_224.0', 'V306', 'P_emaildomain_me.com', 'C10', 'card4_discover', 'C12', 'V308', 'P_emaildomain_msn.com', 'M9', 'id_20', 'V264', 'V127', 'V122', 'weekday_5.0', 'V81', 'addr1_191.0', 'V294', 'D1', 'V47', 'id_30_android', 'V286', 'P_emaildomain_gmail.com', 'hours_18.0', 'id_38', 'D12', 'C4', 'hours_4.0', 'V141', 'id_36', 'hours_13.0', 'V331', 'card5_166.0', 'V83', 'V2', 'card5_137.0', 'V29', 'id_07', 'card1_12544', 'id_31_safari', 'id_33_resolution', 'V307', 'id_38_F', 'hours_3.0', 'addr1_272.0', 'addr1_330.0', 'hours_16.0', 'hours_20.0', 'C2', 'id_19', 'V281', 'V53', 'P_emaildomain_4_com', 'weekday', 'id_31_tablet_False', 'R_emaildomain_2_com', 'V44', 'card2_481.0', 'V318', 'card1_6019', 'card3_144.0', 'C11', 'V229', 'id_31_generic', 'card5_226.0', 'V236', 'card2_512.0', 'is_train_df', 'id_31_firefox_False', 'addr1_181.0', 'id_20_533.0', 'V62', 'addr1_433.0', 'V266', 'M6_F', 'V317']\ntemp_list_to_keep_all = ['isFraud', 'TransactionID', 'TransactionDT', 'is_train_df', 'weekday', 'hours', 'TransactionDT', 'ProductCD', 'card1', 'card2', 'card3', 'card4', 'card5', 'card6', 'addr1', 'addr2', 'V258', 'V91', 'V70', 'V294', 'V201', 'R_emaildomain_2_com', 'id_17', 'C8', 'C14', 'P_emaildomain_optonline.net', 'V162', 'card4_american express', 'addr2_87.0', 'V173', 'V324', 'V141', 'V223', 'P_emaildomain_me.com', 'V189', 'P_emaildomain_verizon.net', 'P_emaildomain_msn.com', 'id_17_166.0', 'V131', 'V320', 'C10', 'V102', 'card6', 'C5', 'C1', 'V94', 'V271', 'card3_150.0', 'D2', 'V112', 'V329', 'card6_credit', 'V312', 'addr1_337.0', 'V191', 'V283', 'ProductCD', 'V177', 'V285', 'ProductCD_R', 'V103', 'card2_567.0', 'V317', 'V208', 'card2_481.0', 'V269', 'ProductCD_H', 'card1_9633', 'id_14_-420.0', 'id_14_60.0', 'V145', 'P_emaildomain_3', 'id_26', 'id_30_android', 'V230', 'V87', 'id_20_612.0', 'card1_9500', 'V56', 'V254', 'V149', 'id_20_549.0', 'card2_268.0', 'id_32_24.0', 'card5_166.0', 'V257', 'card2_553.0', 'card2_225.0', 'P_emaildomain_comcast.net', 'card3_185.0', 'V206', 'addr1_485.0', 'R_emaildomain_anonymous.com', 'V315', 'id_20_333.0', 'V244', 'V99', 'V209', 'P_emaildomain_2', 'V152', 'V245', 'V176', 'card3', 'V133', 'card1_17188', 'card3_144.0', 'id_31_edge', 'hours_11.0', 'P_emaildomain_infrequent_category', 'V188', 'P_emaildomain_1_infrequent_category', 'V304', 'card2_555.0', 'addr1_472.0', 'hours_5.0', 'V20', 'R_emaildomain_gmail.com', 'C2', 'V171', 'V62', 'card1_15885', 'id_36', 'V333', 'V100', 'V263', 'V55', 'id_25', 'id_17_100.0', 'id_20_533.0', 'P_emaildomain_1_outlook', 'R_emaildomain_hotmail.com', 'id_19_312.0', 'V79', 'addr1_231.0', 'C11', 'V40', 'card2_360.0', 'card3_143.0', 'card1_10616', 'id_19_321.0', 'DeviceInfo_Trident/7.0', 'C13', 'V243', 'DeviceInfo_SM-J700M Build/MMB29K', 'V144', 'V309', 'V74', 'id_31_tablet_False', 'V225', 'V247', 'id_19_271.0', 'V298', 'card4_discover', 'P_emaildomain_bellsouth.net', 'card2_361.0', 'id_19_193.0', 'V249', 'V166', 'V293', 'V288', 'V130', 'card5_236.0', 'V137', 'id_20_401.0', 'V45', 'card1_6019', 'P_emaildomain_live.com', 'DeviceInfo_Windows', 'V21', 'addr1_433.0', 'V224', 'V280', 'V302', 'V281', 'id_13_19.0', 'V194', 'card1_12839', 'id_18_15.0', 'addr1_181.0', 'V117', 'V122', 'P_emaildomain_outlook.com', 'id_31_ie', 'C9', 'V44', 'V310', 'V47', 'V76', 'V323', 'V211', 'P_emaildomain_4', 'V86', 'V150', 'C6', 'V49', 'V54', 'V110', 'V115', 'V67', 'V311', 'card1_12695', 'V97', 'V303', 'V134', 'card1_16132', 'V105', 'V64', 'V301', 'addr1_184.0', 'M5', 'V322', 'card2_514.0', 'card5_229.0', 'card5_195.0', 'id_20_500.0', 'V136', 'C12', 'hours_12.0', 'V226', 'card1_7585', 'V248', 'card2_174.0', 'hours_6.0', 'V290', 'V229', 'id_31_android', 'P_emaildomain_cox.net', 'V160', 'card5_117.0', 'DeviceInfo_MacOS', 'M2_F', 'V154', 'V214', 'V187', 'V308', 'V165', 'M6_F', 'V331', 'V313', 'V61', 'addr1_387.0', 'P_emaildomain_1_hotmail', 'V116', 'D1', 'V104', 'V192', 'V129', 'V161', 'M4', 'id_20_597.0', 'V24', 'P_emaildomain_anonymous.com', 'V109', 'V37', 'D8', 'D14', 'V34', 'id_31_firefox_False', 'card5_226.0', 'V279', 'V286', 'V151', 'V90', 'id_19_100.0', 'P_emaildomain_live.com.mx', 'addr2_60.0', 'V13', 'id_20_595.0', 'V332', 'id_19_infrequent_category', 'card5_198.0', 'card1_2884', 'card1_7919', 'addr1_126.0', 'V266', 'card2_215.0', 'V95', 'D15', 'V52', 'V60', 'V83', 'V272', 'P_emaildomain_icloud.com', 'card2_170.0', 'id_19_410.0', 'V296', 'V273', 'V295', 'D3', 'V337', 'V66', 'id_03', 'V82', 'V146', 'V236', 'V170', 'V318', 'M3_F', 'card1_7508', 'V5', 'addr1_272.0', 'addr1_310.0', 'P_emaildomain_hotmail.com', 'R_emaildomain', 'id_20_222.0', 'card1_12544', 'V287', 'card2_490.0', 'card3_infrequent_category', 'card2_583.0', 'V270', 'V7', 'V253', 'id_13_52.0', 'V12', 'addr1_441.0', 'card5_138.0', 'V155', 'card2_512.0', 'M4_M1', 'V233', 'V38', 'card1_15066', 'V46', 'V202', 'V123', 'hours_13.0', 'TransactionAmt', 'addr1_330.0', 'card1_10112', 'card2_321.0', 'V127', 'V53', 'D10', 'V307', 'V314', 'V159', 'V250', 'P_emaildomain_aol.com', 'V231', 'V63', 'id_30_mac_False', 'D4', 'V75', 'V277', 'R_emaildomain_2', 'V321', 'V132', 'D7', 'V58', 'P_emaildomain_att.net', 'id_13_49.0', 'addr1_476.0', 'M6', 'id_14_-360.0', 'card2_375.0', 'id_20_325.0', 'V57', 'V114', 'addr1_325.0', 'hours_8.0', 'id_20_391.0', 'R_emaildomain_outlook.es', 'V175', 'id_35_F', 'V306', 'V126', 'V172', 'V2', 'addr1_299.0', 'V181', 'M1', 'V77', 'V221', 'V59', 'V316', 'id_20_563.0', 'DeviceType', 'DeviceInfo_infrequent_category', 'R_emaildomain_2_es', 'card2_111.0', 'dist2', 'id_09', 'V234', 'V71', 'id_31_safari', 'id_01', 'V124', 'V168', 'addr1_315.0', 'V81', 'card4_mastercard', 'V289', 'M3', 'V275', 'card2_476.0', 'V204', 'V85', 'R_emaildomain_cox.net', 'card2_infrequent_category', 'V260', 'V3', 'V128', 'id_20_infrequent_category', 'V125', 'V237', 'card4', 'V207', 'id_20_507.0', 'D13', 'id_14_-480.0', 'V96', 'addr1_512.0', 'id_19_417.0', 'M9_F', 'V205', 'R_emaildomain_aol.com', 'R_emaildomain_4', 'id_13_62.0', 'V267', 'V256', 'V183', 'V19', 'V156', 'DeviceInfo', 'id_33_resolution', 'V217', 'V291', 'card2', 'card5_102.0', 'V274', 'addr1_204.0', 'id_13_27.0', 'D6', 'V232', 'card5', 'V139', 'hours_1.0', 'card1_16075', 'id_02', 'V167', 'V35', 'V164', 'V300', 'V199', 'id_30_windows_False', 'card5_202.0', 'id_31_chrome_version_newness', 'card5_224.0', 'V6', 'M4_M0', 'card1_3154', 'V33', 'dist1', 'V335', 'id_08', 'V292', 'id_06', 'id_14', 'V23', 'hours_7.0', 'hours_17.0', 'id_07', 'card2_194.0', 'V278', 'card1', 'card2_399.0', 'card1_2803', 'card5_126.0', 'hours_20.0', 'V78', 'id_31_edge_False', 'D11', 'V25', 'V242', 'id_31_chrome_False', 'id_20_256.0', 'id_30_windows', 'addr1_143.0', 'id_31_samsung_False', 'id_05', 'V36', 'V180', 'D5', 'addr1_infrequent_category', 'card1_5812', 'D9', 'M5_F', 'V210', 'id_19_548.0', 'V29', 'V101', 'P_emaildomain', 'id_19_153.0', 'V143', 'id_19_176.0', 'hours_21.0', 'weekday_4.0', 'V228', 'P_emaildomain_gmail.com', 'addr1', 'addr1_123.0', 'id_16', 'id_20', 'V284', 'id_31_firefox', 'V218', 'P_emaildomain_4_net', 'hours_15.0', 'id_31_safari_version_newness', 'V238', 'hours_2.0', 'V174', 'id_38', 'V203', 'id_31_edge_version_newness', 'TransactionAmt_decimal_length', 'card5_146.0', 'id_34_match_status:1', 'id_34', 'card1_15497', 'TransactionAmt_decimal', 'V4', 'C7', 'V39', 'card5_219.0', 'hours_18.0', 'card2_545.0', 'V282', 'addr1_264.0', 'id_31_for', 'id_13_33.0', 'id_31_desktop', 'card1_infrequent_category', 'hours_16.0', 'V73', 'id_31_android_False', 'id_19_542.0', 'V135', 'hours_22.0', 'id_19_290.0', 'V178', 'V297', 'V51', 'id_18', 'C4', 'V319', 'M8', 'P_emaildomain_charter.net', 'V276', 'weekday_3.0', 'M2', 'V15', 'weekday_2.0', 'R_emaildomain_1_outlook', 'D12', 'V336', 'id_19_427.0', 'id_37', 'id_13', 'id_31_chrome', 'weekday_1.0', 'V213', 'V261', 'id_11', 'id_19', 'id_13_20.0', 'V17', 'V43', 'P_emaildomain_mail.com', 'V264', 'R_emaildomain_1_hotmail', 'hours_3.0', 'addr1_327.0', 'V216', 'id_18_13.0', 'hours_10.0', 'P_emaildomain_1_gmail', 'addr1_191.0', 'id_19_266.0', 'id_31_generic', 'hours_19.0', 'card2_408.0', 'R_emaildomain_icloud.com', 'V268', 'R_emaildomain_infrequent_category', 'V222', 'id_30_android_False', 'id_31_browser_False', 'hours', 'M7', 'V9', 'id_32', 'M9', 'V190', 'id_37_F', 'V26', 'card1_2616', 'card2_100.0', 'weekday_5.0', 'id_38_F', 'V84', 'P_emaildomain_yahoo.com', 'V169', 'card5_infrequent_category', 'id_31_firefox_version_newness', 'id_15', 'card5_162.0', 'V80', 'V251', 'weekday', 'id_18_12.0', 'hours_4.0', 'id_30_mac', 'V92', 'id_17_infrequent_category', 'id_19_215.0', 'id_31_safari_False', 'V42', 'V158', 'V8', 'V299', 'id_13_63.0', 'id_20_161.0', 'V98', 'P_emaildomain_4_com', 'hours_9.0', 'M8_F', 'V265', 'card5_137.0', 'R_emaildomain_yahoo.com', 'V184', 'id_20_214.0', 'id_24', 'id_19_352.0', 'V48', 'C3', 'id_20_305.0', 'V220', 'id_31_generic_False', 'id_13_14.0', 'M7_F', 'id_28', 'id_04', 'ProductCD_S', 'P_emaildomain_4_com.mx', 'V179', 'id_28_Found', 'V69', 'id_15_New', 'P_emaildomain_1_yahoo', 'P_emaildomain_2_com', 'id_31_mobile', 'V106', 'hours_14.0', 'DeviceType_desktop', 'id_19_529.0', 'R_emaildomain_4_com', 'id_31_browser', 'V11', 'id_31_desktop_False', 'id_30_ios', 'V10', 'V262', 'V235', 'V219', 'V215', 'V200', 'V30', 'card1_4461', 'V108', 'id_30_ios_False', 'id_14_-300.0', 'V212', 'V334', 'id_15_Found', 'V138', 'id_31_ie_False', 'id_31_mobile_False', 'id_29', 'id_20_600.0', 'id_20_489.0', 'V50', 'V246', 'id_20_127.0', 'V157', 'R_emaildomain_outlook.com', 'id_23', 'card3_119.0', 'id_31_samsung', 'V120', 'V186', 'V239', 'DeviceInfo_ALE-L23 Build/HuaweiALE-L23', 'addr2', 'id_31_for_False', 'V140', 'P_emaildomain_1_live', 'V259', 'id_19_567.0', 'V227', 'V18', 'V148', 'V111', 'R_emaildomain_1_infrequent_category', 'id_20_535.0', 'V147', 'id_12', 'V252', 'id_13_25.0', 'V326', 'V338', 'card5_118.0', 'id_13_24.0', 'V182', 'P_emaildomain_yahoo.com.mx', 'card5_223.0', 'V121', 'card1_18132', 'V328', 'V339', 'id_19_390.0', 'id_10', 'card5_150.0', 'id_36_F', 'id_30_linux_False', 'V185', 'R_emaildomain_comcast.net', 'id_31_ios_False', 'P_emaildomain_rocketmail.com', 'id_19_633.0', 'id_13_infrequent_category', 'V27', 'DeviceInfo_SM-G532M Build/MMB29T', 'V22']",
"_____no_output_____"
],
[
"temp_list_to_drop = [x for x in list(master_df.columns) if x not in temp_list_to_keep_all]\nmaster_df.drop(columns = temp_list_to_drop, inplace = True)\nmaster_df.to_csv('master_df_top_all.csv', index=False)\n\ntemp_list_to_drop = [x for x in list(master_df.columns) if x not in temp_list_to_keep_300]\nmaster_df.drop(columns = temp_list_to_drop, inplace = True)\nmaster_df.to_csv('master_df_top_300.csv', index=False)\n\ntemp_list_to_drop = [x for x in list(master_df.columns) if x not in temp_list_to_keep_200]\nmaster_df.drop(columns = temp_list_to_drop, inplace = True)\nmaster_df.to_csv('master_df_top_200.csv', index=False)\n\ntemp_list_to_drop = [x for x in list(master_df.columns) if x not in temp_list_to_keep_100]\nmaster_df.drop(columns = temp_list_to_drop, inplace = True)\nmaster_df.to_csv('master_df_top_100.csv', index=False)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb495d0d17ac365d44a5482033790dadf8d4f7a8 | 55,873 | ipynb | Jupyter Notebook | tools/tools-sol.ipynb | simoneb1x/softpython-en | 4321fb033a10b57058e10c07f763d170b41a3082 | [
"CC-BY-4.0"
] | null | null | null | tools/tools-sol.ipynb | simoneb1x/softpython-en | 4321fb033a10b57058e10c07f763d170b41a3082 | [
"CC-BY-4.0"
] | 16 | 2020-10-24T15:16:59.000Z | 2022-03-19T04:05:48.000Z | tools/tools-sol.ipynb | simoneb1x/softpython-en | 4321fb033a10b57058e10c07f763d170b41a3082 | [
"CC-BY-4.0"
] | 1 | 2021-10-30T18:09:14.000Z | 2021-10-30T18:09:14.000Z | 34.96433 | 846 | 0.531473 | [
[
[
"# Remember to execute this cell with Shift+Enter\n\nimport sys\nsys.path.append('../')\nimport jupman",
"_____no_output_____"
]
],
[
[
"# Tools and scripts\n\n## [Download exercises zip](../_static/generated/tools.zip)\n\n[Browse files online](https://github.com/DavidLeoni/softpython-en/tree/master/tools)\n\n<div class=\"alert alert-warning\">\n\n**REQUISITES:**\n \n* **Having Python 3 and Jupyter installed:** if you haven't already, see [Installation](https://en.softpython.org/installation.html)\n</div>",
"_____no_output_____"
],
[
"## Python interpreter\n\nIn these tutorials we will use extensively the notebook editor Jupyter, because it allows to comfortably execute Python code, display charts and take notes. But if we want only make calculations it is not mandatory at all!\n\nThe most immediate way (even if not very practical) to execute Python things is by using the _command line_ interpreter in the so-called _interactive mode,_ that is, having Python to wait commands which will be manually inserted one by one. This usage _does not_ require Jupyter, you only need to have installed Python. Note that in Mac OS X and many linux systems like Ubuntu, Python is already installed by default, although sometimes it might not be version 3. Let's try to understand which version we have on our system.",
"_____no_output_____"
],
[
"\n### Let's open system console\n\nOpen a console (in Windows: system menu -> Anaconda Prompt, in Mac OS X: run the Terminal)\n\nIn the console you find the so-called _prompt_ of commands. In this _prompt_ you can directly insert commands for the operating system.\n\n<div class=\"alert alert-warning\">\n\n**WARNING**: the commands you give in the prompt are commands in the language of the operating system you are using, **NOT** Python language !!!!!\n \n</div>\n\nIn Windows you should see something like this:\n\n```\nC:\\Users\\David> \n```\n\nIn Mac / Linux it could be something like this:\n\n```bash\ndavid@my-computer:~$\n```",
"_____no_output_____"
],
[
"### Listing files and folders\n\nIn system console, try:\n\n**Windows**: type the command `dir` and press Enter\n\n**Mac or Linux**: type the command `ls` and press Enter.\n\nA listing with all the files in the current folder should appear. In my case appears a list like this:\n\n<div class=\"alert alert-warning\">\n\n**LET ME REPEAT**: in this context `dir` and `ls` are commands of _the operating system,_ **NOT** of Python !!\n\n</div>\n\nWindows: \n\n```\nC:\\Users\\David> dir\nArduino gotysc program.wav\na.txt index.html Public\nMYFOLDER java0.log RegDocente.pdf\nbackupsys java1.log \nBaseXData java_error_in_IDEA_14362.log \n```\n\nMac / Linux: \n\n\n```\ndavid@david-computer:~$ ls\nArduino gotysc program.wav\na.txt index.html Public\nMYFOLDER java0.log RegistroDocenteStandard(1).pdf\nbackupsys java1.log RegistroDocenteStandard.pdf\nBaseXData java_error_in_IDEA_14362.log \n```\n",
"_____no_output_____"
],
[
"### Let's launch the Python interpreter\n\nIn the opened system console, simply type the command `python`:\n\n<div class=\"alert alert-warning\">\n\n**WARNING**: If Python does not run, try typing `python3` with the `3` at the end of `python` \n\n</div>\n\n\n```\nC:\\Users\\David> python\n```",
"_____no_output_____"
],
[
"You should see appearing something like this (most probably won't be exactly the same). Note that Python version is contained in the first row. If it begins with `2.`, then you are not using the right one for this book - in that case try exiting the interpreter ([see how to exit](#Exiting-the-interpreter)) and then type `python3`\n \n```\nPython 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on windows\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> \n```",
"_____no_output_____"
],
[
"<div class=\"alert alert-warning\">\n\n**CAREFUL** about the triple greater-than `>>>` at the beginning!\n\nThe triple greater-than `>>>` at the start tells us that differently from before now the console is expecting commands _in Python language._ So, the system commands we used before (`cd`, `dir`, ...) will NOT work anymore, or will give different results! \n\n</div>",
"_____no_output_____"
],
[
"Now the console is expecting Python commands, so try inserting `3 + 5` and press Enter:\n\n<div class=\"alert alert-warning\">\n\n**WARNING** DO NOT type `>>>`, only type the command which appears afterwards!\n\n</div>\n\n\n```\n>>> 3 + 5\n```\n\nThe writing `8` should appear:\n\n```\n8\n```\n\nBeyond calculations, we might tell PYthon to print something with the function `print(\"ciao\")`\n\n```\n>>> print(\"ciao\")\nciao\n```",
"_____no_output_____"
],
[
"### Exiting the interpreter\n\nTo get out from the Python interpreter and go back to system prompt (that is, the one which accepts `cd` and `dir`/`ls` commands), type the Python comand `exit()`\n\nAfter you actually exited the Python interpreter, the triple `>>>` should be gone (you should see it at the start of the line)\n\nIn Windows, you should see something similar:\n\n```\n>>> exit()\nC:\\Users\\David>\n```\n\nin Mac / Linux it could be like this:\n\n\n```\n>>> exit()\ndavid@my-computer:~$\n```",
"_____no_output_____"
],
[
"Now you might go back to execute commands for the operating system like `dir` and `cd`:\n\n\n**Windows**:\n```\nC:\\Users\\David> dir\nArduino gotysc program.wav\na.txt index.html Public\nMYFOLDER java0.log RegDocente.pdf\nbackupsys java1.log \nBaseXData java_error_in_IDEA_14362.log \n```\n\n**Mac / Linux**:\n```\ndavid@david-computer:~$ ls\nArduino gotysc program.wav\na.txt index.html Public\nMYFOLDER java0.log RegistroDocenteStandard(1).pdf\nbackupsys java1.log RegistroDocenteStandard.pdf\nBaseXData java_error_in_IDEA_14362.log \n```\n",
"_____no_output_____"
],
[
"## Modules\n\nPython Modules are simply text files which have the extension **.py** (for example `my_script.py`). When you write code in an editor, as a matter of fact you are implementing the corresponding module.\n\nIn Jupyter we use notebook files with the extension `.ipynb`, but to edit them you necessarily need Jupyter.\n\nWith `.py` files (alse said _script_ ) we can instead use any text editor, and we can then tell the interpreter to execute that file. Let's see how to do it.\n\n\n### Simple text editor\n\n1. With a text editor (_Notepad_ in Windows, or _TextEdit_ in Mac Os X) creates a text file, and put inside this code\n\n\n```python\nx = 3\ny = 5\nprint(x + y)\n```\n\n2. Let's try to save it - it seems easy, but it is often definitely not, so read carefully!\n\n\n<div class=\"alert alert-warning\">\n\n**WARNING**: when you are saving the file, **make sure the file have the extension** `.py` **!!** \n</div>\n\nLet's suppose to create the file `my_script.py` inside a folder called `MYFOLDER`:\n\n* **WINDOWS**: if you use _Notepad_, in the save window you have to to set _Save as_ to _All files_ (otherwise the file will be wrongly saved like `my_script.py.txt` !)\n* **MAC**: if you use _TextEdit,_ before saving click _Format_ and then _Convert to format Only text:_ **if you forget this passage, TextEdit in the save window will not allow you to save in the right format and you will probably end up with a** `.rtf` **file which we're not interested in**",
"_____no_output_____"
],
[
"3. Open a console (in Windows: system menu -> Anaconda Prompt, in Mac OS X: run the Terminal)\n\nthe console opens the so-called _commands prompt_. In this _prompt_ you can directly enter commands for the operating system (see [previous paragraph](#Python-interpreter)\n\n<div class=\"alert alert-warning\">\n\n**WARNING**: the commands you give in the prompt are commands in the language of the operating system you are using, **NOT** Python language !!!!!\n \n</div>\n\nIn Windows you should see something like this:\n\n```\nC:\\Users\\David> \n```\n\nIn Mac / Linux it could be something like this:\n\n```bash\ndavid@my-computer:~$\n```",
"_____no_output_____"
],
[
"Try for example to type the command `dir` (or `ls` for Mac / Linux) which shows all the files in the current folder. In my case a list like this appears:\n\n<div class=\"alert alert-warning\">\n\n**LET ME REPEAT**: in this context `dir` / `ls` are commands of the _operating system,_ **NOT** Python. \n\n</div>\n\n```\nC:\\Users\\David> dir\nArduino gotysc program.wav\na.txt index.html Public\nMYFOLDER java0.log RegDocente.pdf\nbackupsys java1.log \nBaseXData java_error_in_IDEA_14362.log \n```\n\nIf you notice, in the list there is the name MYFOLDER, where I put `my_script.py`. To _enter_ the folder in the _prompt,_ you must first use the operating system command `cd` like this:",
"_____no_output_____"
],
[
"4. To enter a folder called MYFOLDER, type `cd MYFOLDER`:\n\n```\nC:\\Users\\David> cd MYFOLDER\nC:\\Users\\David\\MYFOLDER>\n```\n\n**What if I get into the wrong folder?**\n\nIf by chance you enter the wrong folder, like `DUMBTHINGS`, to go back of one folder, type `cd ..` (NOTE: `cd` is followed by one space and TWO dots `..` _one after the other_ )\n\n\n```\nC:\\Users\\David\\DUMBTHINGS> cd ..\nC:\\Users\\David\\>\n```",
"_____no_output_____"
],
[
"5. Make sure to be in the folder which contains `my_script.py`. If you aren't there, use commands `cd` and `cd ..` like above to navigate the folders.\n\nLet's see what present in MYFOLDER with the system command `dir` (or `ls` if in Mac/Linux):\n\n<div class=\"alert alert-warning\">\n\n**LET ME REPEAT**: inthis context `dir` (or `ls` is a command of the _operating system,_ **NOT** Python.\n</div>\n\n\n```\nC:\\Users\\David\\MYFOLDER> dir\n\nmy_script.py\n```\n\n`dir` is telling us that inside `MYFOLDER` there is our file `my_script.py`",
"_____no_output_____"
],
[
"\n\n6. From within `MYFOLDER`, type `python my_script.py`\n\n```\nC:\\Users\\David\\MYFOLDER>python my_script.py\n```\n\n<div class=\"alert alert-warning\">\n\n**WARNING**: if Python does not run, try typing `python3 my_script.py` with `3` at the end of `python` \n\n</div>\n\n\nIf everything went fine, you should see\n\n```\n8\nC:\\Users\\David\\MYFOLDER>\n```\n<div class=\"alert alert-warning\">\n\n**WARNING**: After executing a script this way, the console is awaiting new _system_ commands, **NOT** Python commands (so, there shouldn't be any triple greater-than `>>>`) \n</div>",
"_____no_output_____"
],
[
"### IDE\n\nIn these tutorials we work on Jupyter notebooks with extension `.ipynb`, but to edit long `.py` files it's more convenient to use more traditional editors, also called IDE _(Integrated Development Environment)._ For Python we can use [Spyder](https://www.spyder-ide.org/), [Visual Studio Code](https://code.visualstudio.com/Download) or [PyCharme Community Edition](https://www.jetbrains.com/pycharm/download/).\n\nDifferently from Jupyter, these editors allow more easily code _debugging_ and _testing._ ",
"_____no_output_____"
],
[
"Let's try Spyder, which is the easiest - if you have Anaconda, you find it available inside Anaconda Navigator.\n\n<div class=\"alert alert-info\">\n\n**INFO**: Whenever you run Spyder, it might ask you to perform an upgrade, in these cases you can just click No. \n</div>\n\nIn the upper-left corner of the editor there is the code of the file `.py` you are editing. Such files are also said _script._ In the lower-right corner there is the console with the IPython interpreter (which is the same at the heart of Jupyter, here in textual form). When you execute the script, it's like inserting commands in that interpreter.\n\n- To execute the whole script: press `F5`\n- To execute only the current line or the selection: press `F9`\n- To clear memory: after many executions the variables in the memory of the interpreter might get values you don't expect. To clear the memory, click on the gear to the right of the console, and select _Restart kernel_",
"_____no_output_____"
],
[
"**EXERCISE**: do some test, taking the file `my_script.py` we created before:\n\n```python\nx = 3\ny = 5\nprint(x + y)\n```\n\n- once the code is in the script, hit `F5`\n- select only `print(x+y)` and hit F9\n- select only `x=3` and hit F9\n- click on th gear the right of the console panel, and select _Restart kernel,_ then select only `print(x+y)` and hit F9. What happens?\n\nRemember that if the memory of the interpreter has been cleared with _Restart kernel,_ and then you try executing a code row with variables defined in lines which were not exectued before, Python will not know which variables you are referring to and will show a `NameError`. ",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"## Jupyter\n\nJupyter is an editor that allows to work on so called _notebooks,_ which are files ending with the extension `.ipynb`. They are documents divided in cells where in each cell you can insert commands and immediately see the respective output. Let's try opening this.",
"_____no_output_____"
],
[
"1. Unzip [exercises zip](../_static/generated/tools.zip) in a folder, you should obtain something like this:\n\n```\n\ntools\n tools-sol.ipynb\n tools.ipynb\n jupman.py\n```\n\n<div class=\"alert alert-warning\">\n\n**WARNING: To correctly visualize the notebook, it MUST be in the unzipped folder.**\n</div>\n",
"_____no_output_____"
],
[
"\n2. open Jupyter Notebook. Two things should appear, first a console and then a browser. In the browser navigate the files to reach the unzipped folder, and open the notebook `tools.ipynb`\n\n<div class=\"alert alert-warning\">\n\n**WARNING: DO NOT click Upload button in Jupyer**\n \nJust navigate until you reach the file.\n</div>\n\n\n<div class=\"alert alert-warning\">\n\n**WARNING: open the notebook WITHOUT the** `-sol` **at the end!**\n \nSeeing now the solutions is too easy ;-) \n \n</div>",
"_____no_output_____"
],
[
"3. Go on reading the exercises file, sometimes you will find paragraphs marked **Exercises** which will ask to write Python commands in the following cells.Exercises are graded by difficulty, from one star ✪ to four ✪✪✪✪\n\n<div class=\"alert alert-warning\">\n\n**WARNING: In this book we use ONLY PYTHON 3** <br/>\n\nIf by chance you obtain weird behaviours, check you are using Python 3 and not 2. If by chance by typing `python` your operating system runs python 2, try executing the third by typing the command `python3`\n \n</div>\n\n<div class=\"alert alert-info\">\n\n**If you don't find Jupyter / something doesn't work:** have a look at [installation](https://en.softpython.org/installation.html#Jupyter-Notebook) \n</div>\n\n",
"_____no_output_____"
],
[
"Useful shortcuts:\n\n* to execute Python code inside a Jupyter cell, press `Control + Enter`\n* to execute Python code inside a Jupyter cell AND select next cell, press `Shift + Enter`\n* to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press `Alt + Enter`\n* when something seem wrong in computations, try to clean memory by running `Kernel->Restart and Run all`",
"_____no_output_____"
],
[
"**EXERCISE**: Let's try inserting a Python command: type in the cell below here `3 + 5`, then while in that cell press special keys `Control+Enter`. As a result, the number `8` should appear",
"_____no_output_____"
],
[
"**EXERCISE**: with Python we can write comments by starting a row with a sharp `#`. Like before, type in the next cell `3 + 5` but this time type it in the row under the writing `# write here`:",
"_____no_output_____"
]
],
[
[
"# write here\n",
"_____no_output_____"
]
],
[
[
"**EXERCISE**: In every cell Jupyter only shows the result of last executed row. Try inserting this code in the cell below and execute by pressing `Control+Enter`. Which result do you see?\n\n```python\n3 + 5\n1 + 1\n```",
"_____no_output_____"
]
],
[
[
"# write here\n\n",
"_____no_output_____"
]
],
[
[
"**EXERCISE**: Let's try now to create a new cell.\n\n* While you are with curson the cell, press `Alt+Enter`. A new cell should be created after the current one.\n\n* In the cell just created, insert `2 + 3` and press `Shift+Enter`. What happens to the cursor? Try the difference swith `Control+Enter`. If you don't understand the difference, try pressing many times `Shift+Enter` and see what happens.",
"_____no_output_____"
],
[
"### Printing an expression",
"_____no_output_____"
],
[
"Let's try to assign an expression to a variable:",
"_____no_output_____"
]
],
[
[
"coins = 3 + 2",
"_____no_output_____"
]
],
[
[
"Note the assignment by itself does not produce any output in the Jupyter cell. We can ask Jupyter the value of the variable by simply typing again the name in a cell:",
"_____no_output_____"
]
],
[
[
"coins",
"_____no_output_____"
]
],
[
[
"The effect is (almost always) the same we would obtain by explictly calling the function `print`:",
"_____no_output_____"
]
],
[
[
"print(coins)",
"5\n"
]
],
[
[
"What's the difference? For our convenience Jupyter will directly show the result of the last executed expression in the cell, but only the last one:",
"_____no_output_____"
]
],
[
[
"coins = 4\n2 + 5\ncoins",
"_____no_output_____"
]
],
[
[
"If we want to be sure to print both, we need to use the function `print`:",
"_____no_output_____"
]
],
[
[
"coins = 4\nprint(2 + 5)\nprint(coins)",
"7\n4\n"
]
],
[
[
"Furthermore, the result of last expression is shown only in Jupyter notebooks, if you are writig a normal `.py` script and you want to see results you must in any case use `print`.",
"_____no_output_____"
],
[
"If we want to print more expressions in one row, we can pass them as different parameters to `print` by separating them with a comma:",
"_____no_output_____"
]
],
[
[
"coins = 4\nprint(2+5, coins)",
"7 4\n"
]
],
[
[
"To `print` we can pass as many expressions as we want:",
"_____no_output_____"
]
],
[
[
"coins = 4\nprint(2 + 5, coins, coins*3)",
"7 4 12\n"
]
],
[
[
"If we also want to show some text, we can write it by creating so-called _strings_ between double quotes (we will see strings much more in detail in next chapters):",
"_____no_output_____"
]
],
[
[
"coins = 4\nprint(\"We have\", coins, \"golden coins, but we would like to have double:\", coins * 2) ",
"We have 4 golden coins, but we would like to have double: 8\n"
]
],
[
[
"**QUESTION**: Have a look at following expressions, and for each one of them try to guess the result it produces. Try verifying your guesses both in Jupyter and another editor of files `.py` like Spyder:\n \n1. ```python\n x = 1\n x\n x \n ``` \n1. ```python\n x = 1\n x = 2\n print(x)\n ``` \n1. ```python\n x = 1\n x = 2\n x\n ``` \n1. ```python\n x = 1\n print(x)\n x = 2\n print(x)\n ``` \n1. ```python\n print(zam)\n print(zam)\n zam = 1 \n zam = 2 \n ``` \n1. ```python \n x = 5\n print(x,x)\n ``` \n1. ```python \n x = 5\n print(x)\n print(x)\n ```\n1. ```python\n carpets = 8\n length = 5\n print(\"If I have\", carpets, \"carpets in sequence I walk for\",\n carpets * length, \"meters.\")\n ```\n1. ```python\n carpets = 8\n length = 5\n print(\"If\", \"I\",\"have\", carpets, \"carpets\",\"in\", \"sequence\",\n \"I\", \"walk\", \"for\", carpets * length, \"meters.\")\n ``` ",
"_____no_output_____"
],
[
"### Exercise - Castles in the air\n\nGiven two variables\n\n```python\ncastles = 7\ndirigibles = 4\n```\nwrite some code to print:\n\n```\nI've built 7 castles in the air\nI have 4 steam dirigibles\nI want a dirigible parked at each castle\nSo I will buy other 3 at the Steam Market\n```\n\n- **DO NOT** put numerical constants in your code like `7`, `4` or `3`! Write generic code which only uses the provided variables.",
"_____no_output_____"
]
],
[
[
"#jupman-purge-output\ncastles = 7\ndirigibles = 4\n# write here\nprint(\"I've built\",castles, \"castles in the air\")\nprint(\"I have\", dirigibles, \"steam dirigibles\")\nprint(\"I want a dirigible parked at each castle\")\nprint(\"So I will buy other\", castles - dirigibles, \"at the Steam Market\")",
"I've built 7 castles in the air\nI have 4 steam dirigibles\nI want a dirigible parked at each castle\nSo I will buy other 3 at the Steam Market\n"
]
],
[
[
"## Visualizing the execution with Python Tutor\n\nWe have seen some of the main data types. Before going further, let's see the right tools to understand what happens when we execute the code.\n\n[Python tutor](http://pythontutor.com/) is a very good website to visualize online Python code execution, allowing to step forth and _back_ in code flow. Exploit it as much as you can, it should work with many of the examples we shall see in the book. Let's now try an example.\n\n**Python tutor 1/4**\n\nGo to [pythontutor.com](http://pythontutor.com/) and select _Python 3_",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"**Python tutor 2/4**\n\nMake sure at least Python 3.6 is selected:\n\n",
"_____no_output_____"
],
[
"**Python tutor 3/4**\n\n**Try inserting:**\n\n```python\nx = 5\ny = 7\nz = x + y\n```\n\n",
"_____no_output_____"
],
[
"**Python tutor 4/4**\n\n**By clicking on Next, you will see the changes in Python memory**\n\n",
"_____no_output_____"
],
[
"### Debugging code in Jupyter\n\nPython Tutor is fantastic, but when you execute code in Jupyter and it doesn't work, what can you do? To inspect the execution, the editor usually makes available a tool called _debugger,_ which allows to execute instructions one by one. At present (August 2018), the Jupyter debugger is called [pdb](https://davidhamann.de/2017/04/22/debugging-jupyter-notebooks/) and it is extremely limited. To overcome its limitations, in this book we invented a custom solution which exploits Python Tutor.\n\nIf you insert Python code in a cell, and then **at the cell end** you write the instruction `jupman.pytut()`, the preceding code will be visualized inside Jupyter notebook with Python Tutor, as if by magic.",
"_____no_output_____"
],
[
"<div class=\"alert alert-warning\">\n\n**WARNING**: `jupman` is a collection of support functions we created just for this book.\n \nWhenever you see commands which start with `jupman`, to make them work you need first to execute the cell at the beginning of the document. For convenience we report here that cell. If you already didn't, execute it now.\n\n</div>\n",
"_____no_output_____"
]
],
[
[
"# Remember to execute this cell with Control+Enter\n# These commands tell Python where to find the file jupman.py\nimport sys;\nsys.path.append('../'); \nimport jupman;",
"_____no_output_____"
]
],
[
[
"Now we are ready yo try Python Tutor with the magic function `jupman.pytut()`: ",
"_____no_output_____"
]
],
[
[
"x = 5\ny = 7\nz = x + y\n\njupman.pytut()",
"_____no_output_____"
]
],
[
[
"#### Python Tutor : Limitation 1\n\nPython Tutor is handy, but there are important limitations:\n\n",
"_____no_output_____"
],
[
"<div class=\"alert alert-warning\">\n\n**ATTENTION**: Python Tutor only looks inside one cell!\n\nWhenever you use Python Tutor inside Jupyter, the only code Python tutors considers is the one inside the cell containing the command `jupman.pytut()` \n \n</div>\n\nSo for example in the two following cells, only `print(w)` will appear inside Python tutor without the `w = 3`. If you try clicking _Forward_ in Python tutor, you will we warned that `w` was not defined.",
"_____no_output_____"
]
],
[
[
"w = 3",
"_____no_output_____"
],
[
"print(w)\n\njupman.pytut()",
"3\n"
]
],
[
[
"To have it work in Python Tutor you must put ALL the code in the SAME cell:",
"_____no_output_____"
]
],
[
[
"w = 3\nprint(w)\n\njupman.pytut()",
"3\n"
]
],
[
[
"#### Python Tutor : Limitation 2\n\n<div class=\"alert alert-warning\">\n\n**WARNING: Python Tutor only uses functions from standard PYthon distribution**\n\nPYthon Tutor is good to inspect simple algorithms with basic Python functions, if you use libraries from third parties it will not work. \n</div>\n\nIf you use some library like `numpy`, you can try **only online** to select `Python 3.6 with Anaconda` :\n\n\n",
"_____no_output_____"
],
[
"### Exercise - tavern\n\nGiven the variables\n\n```python\npirates = 10\neach_wants = 5 # mugs of grog \nkegs = 4\nkeg_capacity = 20 # mugs of grog\n```\n\nTry writing some code which prints:\n\n```\nIn the tavern there are 10 pirates, each wants 5 mugs of grog\nWe have 4 kegs full of grog\nFrom each keg we can take 20 mugs\nTonight the pirates will drink 50 mugs, and 30 will remain for tomorrow\n```\n\n- **DO NOT** use numerical constants in your code, instead try using the proposed variables\n- To keep track of remaining kegs, make a variable `remaining_mugs`\n- if you are using Jupyter, try using `jupman.pytut()` at the cell end to visualize execution",
"_____no_output_____"
]
],
[
[
"pirates = 10\neach_wants = 5 # mugs of grog \nkegs = 4\nkeg_capacity = 20 # mugs of grog\n\n\n# write here\nprint(\"In the tavern there are\", pirates, \"pirates, each wants\", each_wants, \"mugs of grog\")\nprint(\"We have\", kegs, \"kegs full of grog\")\nprint(\"From each keg we can take\", keg_capacity,\"mugs\")\nremaining_mugs = kegs*keg_capacity - pirates*each_wants\nprint(\"Tonight the pirates will drink\", pirates * each_wants, \"mugs, and\", remaining_mugs, \"will remain for tomorrow\")\n\n#jupman.pytut()",
"In the tavern there are 10 pirates, each wants 5 mugs of grog\nWe have 4 kegs full of grog\nFrom each keg we can take 20 mugs\nTonight the pirates will drink 50 mugs, and 30 will remain for tomorrow\n"
]
],
[
[
"## Python Architecture\n\nWhile not strictly fundamental to understand the book, the following part is useful to understand what happens under the hood when you execute commands.\n\nLet's go back to Jupyter: the notebook editor Jupyter is a very powerful tool and flexible, allows to execute Python code, not only that, also code written in other programming languages (R, Bash, etc) and formatting languages (HTML, Markdown, Latex, etc).\n\nSe must keep in mind that the Python code we insert in cells of Jupyter notebooks (the files with extension `.ipynb`) is not certainly magically understood by your computer. Under the hood, a lot of transformations are performed so to allow you computer processor to understaned the instructions to be executed. We report here the main transformations which happen, from Jupyter to the processor (CPU):",
"_____no_output_____"
],
[
"### Python is a high level language\n\nLet's try to understand well what happens when you execute a cell:\n\n1. **source code**: First Jupyter checks if you wrote some Python _source code_ in the cell (it could also be other programming languages like R, Bash, or formatting like Markdown ...). By default Jupyter assumes your code is Python. Let's suppose there is the following code:\n\n```python\nx = 3\ny = 5\nprint(x + y)\n```\n\n**EXERCISE**: Without going into code details, try copy/pasting it into the cell below. Making sure to have the cursor in the cell, execute it with `Control + Enter`. When you execute it an `8` should appear as calculation result. The `# write down here` as all rows beginning with a sharp `#` is only a comment which will be ignored by Python",
"_____no_output_____"
]
],
[
[
"# write down here\n\n",
"_____no_output_____"
]
],
[
[
"If you managed to execute the code, you can congratulate Python! It allowed you to execute a program written in a quite comprehensible language _independently_ from your operating system (Windows, Mac Os X, Linux ...) and from the processor of your computer (x86, ARM, ...)! Not only that, the notebook editor Jupyter also placed the result in your browser.",
"_____no_output_____"
],
[
"\nIn detail, what happened? Let's see:\n\n2. **bytecode**: When requesting the execution, Jupyter took the text written in the cell, and sent it to the so-called _Python compiler_ which transformed it into _bytecode_. The _bytecode_ is a longer sequence of instructions which is less intelligeble for us humans (**this is only an example, there is no need to understand it !!**):\n\n``` \n 2 0 LOAD_CONST 1 (3)\n 3 STORE_FAST 0 (x)\n\n 3 6 LOAD_CONST 2 (5)\n 9 STORE_FAST 1 (y)\n\n 4 12 LOAD_GLOBAL 0 (print)\n 15 LOAD_FAST 0 (x)\n 18 LOAD_FAST 1 (y)\n 21 BINARY_ADD\n 22 CALL_FUNCTION 1 (1 positional, 0 keyword pair)\n 25 POP_TOP\n 26 LOAD_CONST 0 (None)\n 29 RETURN_VALUE\n```",
"_____no_output_____"
],
[
"3. **machine code**: The _Python interpreter_ took the _bytecode_ above one instruction per time, and converted it into _machine code_ which can actually be understood by the processor (CPU) of your computer. To us the _machine code_ may look even longer and uglier of _bytecode_ but the processor is happy and by reading it produces the program results. Example of _machine code_ (**it is just an example, you do not need to understand it !!**):\n\n``` \nmult:\n\tpush rbp\n\tmov rbp, rsp\n\tmov eax, 0\nmult_loop:\n\tcmp edi, 0\n\tje mult_end\n\tadd eax, esi\n\tsub edi, 1\n\tjmp mult_loop\nmult_end:\n\tpop rbp\n\tret\n```",
"_____no_output_____"
],
[
"We report in a table what we said above. In the table we explicitly write the file extension ni which we can write the various code formats\n\n- The ones interesting for us are Jupyter notebooks `.ipynb` and Python source code files `.py`\n- `.pyc` file smay be generated by the compiler when reading `.py` files, but they are not interesting to us, we will never need to edit the,\n- `.asm` machine code also doesn't matter for us\n\n| Tool | Language| File extension | Example|\n|-----|-----------|---------|---|\n| Jupyter Notebook| Python| .ipynb||\n| Python Compiler | Python source code | .py |`x = 3`<br> `y = 5`<br> `print(x + y)`|\n| Python Interpreter | Python bytecode | .pyc| `0 LOAD_CONST 1 (3)`<br>`3 STORE_FAST 0 (x)`|\n| Processor (CPU) | Machine code| .asm |`cmp edi, 0`<br>`je mult_end`|\n\n\n\nNo that we now have an idea of what happens, we can maybe understand better the statement _Python is a high level language,_ that is, it's positioned high in the above table: when we write Python code, we are not interested in the generated _bytecode_ or _machine code,_ we can **just focus on the program logic**. \nBesides, the Python code we write is **independent from the pc architecture**: if we have a Python interpreter installed on a computer, it will take care of converting the high-level code into the machine code of that particular architecture, which includes the operating system (Windows / Mac Os X / Linux) and processor (x86, ARM, PowerPC, etc).",
"_____no_output_____"
],
[
"### Performance\n\nEverything has a price. If we want to write programs focusing only on the _high level logic_ without entering into the details of how it gets interpreted by the processor, we tyipcally need to give up on _performance._ Since Python is an _interpreted_ language has the downside of being slow. What if we really need efficiency? Luckily, Python can be extended with code written in _C language_ which typically is much more performant. Actually, even if you won't notice it, many functions of Python under the hood are directly written in the fast C language. If you really need performance (not in this book!) it might be worth writing first a prototype in Python and, once established it works, compile it into _C language_ by using [Cython compiler](http://cython.org/) and manually optimize the generated code.",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code"
],
[
"markdown",
"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"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb495e89f8a39ae37e72d78ee9b71a778ccc4632 | 4,729 | ipynb | Jupyter Notebook | data/population_data_revenue/discover_population_data.ipynb | taylor-curran/vrb-know | 6dd189629d56e3c2b32fcc4fa23dff89570db1b5 | [
"MIT"
] | null | null | null | data/population_data_revenue/discover_population_data.ipynb | taylor-curran/vrb-know | 6dd189629d56e3c2b32fcc4fa23dff89570db1b5 | [
"MIT"
] | null | null | null | data/population_data_revenue/discover_population_data.ipynb | taylor-curran/vrb-know | 6dd189629d56e3c2b32fcc4fa23dff89570db1b5 | [
"MIT"
] | null | null | null | 25.84153 | 89 | 0.365193 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"# Data Source\n# https://data.world/gmoney/us-city-populations",
"_____no_output_____"
],
[
"data_path = 'us_city_population.csv'\n\npops = pd.read_csv(data_path)\n\nprint(pops.shape)\npops.head()",
"(6889, 7)\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
cb496adf4b7cc1f5f7756c3c01d8e9d78c5d3bef | 8,384 | ipynb | Jupyter Notebook | 1. Beginner/Pytorch3_2_LinearRegression.ipynb | gjustin40/Pytorch | b099fe7975490790f5179f2733a3fc546b5b3d46 | [
"MIT"
] | null | null | null | 1. Beginner/Pytorch3_2_LinearRegression.ipynb | gjustin40/Pytorch | b099fe7975490790f5179f2733a3fc546b5b3d46 | [
"MIT"
] | 1 | 2022-03-12T01:01:53.000Z | 2022-03-12T01:01:53.000Z | 1. Beginner/Pytorch3_2_LinearRegression.ipynb | gjustin40/Pytorch | b099fe7975490790f5179f2733a3fc546b5b3d46 | [
"MIT"
] | 1 | 2020-06-06T09:09:39.000Z | 2020-06-06T09:09:39.000Z | 26.871795 | 1,376 | 0.512285 | [
[
[
"import torch\nprint(torch.__version__)",
"1.4.0\n"
]
],
[
[
"$y = \\theta_1x + \\theta_0$\n<br>\n$\\theta_1 = 0.6, \\theta_0 = -44$",
"_____no_output_____"
],
[
"대충 내가 가진 데이터로 계산을 해보니",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\n\nsimple_regression = nn.Linear(1, 1, bias=True)\nprint(simple_regression)",
"Linear(in_features=1, out_features=1, bias=True)\n"
],
[
"init_weight = simple_regression.weight\ninit_bias = simple_regression.bias\n\nprint(init_weight)\nprint(init_bias)\n\nprint(init_weight.size())\nprint(init_bias.size())",
"Parameter containing:\ntensor([[-0.5959]], requires_grad=True)\nParameter containing:\ntensor([-0.7601], requires_grad=True)\ntorch.Size([1, 1])\ntorch.Size([1])\n"
],
[
"my_weight = torch.tensor([0.6666], dtype=torch.float).reshape_as(init_weight)\nmy_bias = torch.tensor([-44], dtype=torch.float).reshape_as(init_bias)\n\nnew_weight = nn.Parameter(my_weight)\nnew_bias = nn.Parameter(my_bias)\n\nsimple_regression.weight = new_weight\nsimple_regression.bias = new_bias\n\nprint(simple_regression.weight)\nprint(simple_regression.bias)",
"Parameter containing:\ntensor([[0.6666]], requires_grad=True)\nParameter containing:\ntensor([-44.], requires_grad=True)\n"
],
[
"cm = [174, 180, 169, 171]\nkg = [ 72, 76, 65, 68]\n\ndata_x = torch.tensor(cm, dtype=torch.float, requires_grad=False).reshape(len(cm), 1)\ndata_y = torch.tensor(kg, dtype=torch.float, requires_grad=False).reshape(len(cm), 1)\n\nwith torch.no_grad():\n kg_prediction = simple_regression(data_x)\n\nprint(kg_prediction.reshape(1,-1))\nprint(data_y.reshape(1,-1))",
"tensor([[71.9884, 75.9880, 68.6554, 69.9886]])\ntensor([[72., 76., 65., 68.]])\n"
],
[
"import seaborn as sns\nsns.set_theme(color_codes=True)\n\nplot1 = sns.regplot(x=cm, y=kg)\nplot1.set(xlabel='cm', ylabel='kg')",
"_____no_output_____"
]
],
[
[
"$$\n\\hat{\\theta} = (\\text{X}^T\\cdot X)^{-1} \\cdot \\text{X}^T\\cdot y\n$$\n\n\\begin{aligned}\n& (1)\\qquad (\\text{X}^T\\cdot \\text{X})^{-1} \\\\\n& (2)\\qquad (1)\\cdot \\text{X}^T \\\\ \n& (3)\\qquad (2)\\cdot y\\\\\n\\end{aligned}",
"_____no_output_____"
]
],
[
[
"cm = [174, 180, 169, 171] # x\nkg = [ 72, 76, 65, 68] # y\n\n# cm = [174, 180] # x\n# kg = [ 72, 76]\n\ndata_x = torch.tensor(cm, dtype=torch.float, requires_grad=False).reshape(len(cm), 1)\ndata_y = torch.tensor(kg, dtype=torch.float, requires_grad=False).reshape(len(cm), 1)\n\nprint(data_x, data_x.size())\nprint(data_y, data_y.size())\n\ndef dot(a,b):\n return torch.matmul(a,b)\n\nX = torch.cat((torch.ones_like(data_x), data_x,), 1)\ny = data_y\n\n\ndot1 = torch.inverse(dot(X.T, X))\ndot2 = dot(dot1, X.T)\ndot3 = dot(dot2, y)\ndot3",
"tensor([[174.],\n [180.],\n [169.],\n [171.]]) torch.Size([4, 1])\ntensor([[72.],\n [76.],\n [65.],\n [68.]]) torch.Size([4, 1])\n"
],
[
"X",
"_____no_output_____"
],
[
"torch.ones_like(data_x)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb496efa62cbff2900712fb0977a1e04ef0773a3 | 27,188 | ipynb | Jupyter Notebook | horrid archive/TrainingRegimes.ipynb | tsteternlieb/DrugDesignThesis | 2ab00826dbfd2567db5a9054731bd7d49ff12126 | [
"MIT"
] | 2 | 2021-12-29T13:14:29.000Z | 2022-02-07T20:03:09.000Z | horrid archive/TrainingRegimes.ipynb | tsteternlieb/DrugDesignThesis | 2ab00826dbfd2567db5a9054731bd7d49ff12126 | [
"MIT"
] | 4 | 2022-02-04T00:39:19.000Z | 2022-02-16T18:37:09.000Z | horrid archive/TrainingRegimes.ipynb | tsteternlieb/DrugDesignThesis | 2ab00826dbfd2567db5a9054731bd7d49ff12126 | [
"MIT"
] | null | null | null | 26.945491 | 131 | 0.504745 | [
[
[
"import copy\n",
"_____no_output_____"
],
[
"if __name__ == '__main__': \n %run Tests.ipynb\n %run MoleculeGenerator2.ipynb\n %run Discrim.ipynb\n %run Rewards.ipynb\n %run PPO_WITH_TRICKS.ipynb\n %run ChemEnv.ipynb\n %run SupervisedPreTraining.ipynb",
"_____no_output_____"
],
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"_____no_output_____"
],
[
"# wants: a single class for pretraining and rl training\n# also want a singler logger for everything\n# also should put in cross validation for the supervised portion\n# means a logger instance in the init method\n\nclass SupervisedToReinforcement():\n def __init__(self,run_title, rewards_list, chem_env_kwargs, PPO_kwargs, svw_kwargs):\n \n self.run_title = run_title\n self.writer = SummaryWriter(f'./tb_logs/{run_title}/{run_title}_logs')\n \n self.reward_module = FinalRewardModule(self.writer,rewards_list)\n \n chem_env_kwargs['num_chunks'] = train_kwargs['num_chunks']\n chem_env_kwargs['RewardModule'] = self.reward_module\n chem_env_kwargs['writer'] = self.writer\n \n self.ChemEnv = ChemEnv(**chem_env_kwargs)\n \n \n input_dim = chem_env_kwargs['num_node_feats']\n \n #self.policy = Spin2(input_dim,300,chem_env_kwargs['num_atom_types']).cuda()\n self.policy = BaseLine(input_dim,800,chem_env_kwargs['num_atom_types']+1).cuda()\n self.policy.apply(init_weights_recursive)\n \n \n \n svw_kwargs['writer'] = self.writer\n svw_kwargs['input_dim'] = input_dim\n svw_kwargs['num_atom_types'] = chem_env_kwargs['num_atom_types']\n \n print(svw_kwargs)\n self.svw = Supervised_Trainer(self.policy, **svw_kwargs)\n \n PPO_kwargs['env'] = self.ChemEnv\n PPO_kwargs['actor'] = self.policy\n PPO_kwargs['writer'] = self.writer\n self.PPO = PPO_MAIN(**PPO_kwargs)\n self.PPO.to_device(device)\n \n \n def Train(self,total_epochs, batch_size, epochs_per_chunk, num_chunks, PPO_steps, cv_path):\n \n self.svw.TrainModel(total_epochs)\n \n# torch.save({\n# 'model_state_dict': self.policy.state_dict(),\n# 'optimizer_state_dict': self.svw.optim.state_dict()\n# }, f'./{self.run_title}/SavedModel')\n \n print(\"fra\")\n# self.PPO.learn(PPO_steps)\n ",
"_____no_output_____"
],
[
"%run SupervisedPreTraining.ipynb",
"_____no_output_____"
],
[
"# rewards_list = [SizeSynth_norm()]\n# rewards_list = [Synthesizability(), SizeReward()]\nrewards_list = [ Synthesizability()]\n\nchem_env_kwargs = {'max_nodes' : 12, \n 'num_atom_types' : 17, \n 'num_node_feats' : 54,\n 'num_edge_types' : 3, \n 'bond_padding' : 12, \n 'mol_featurizer': mol_to_graph_full, \n 'RewardModule' : None, \n 'writer' : None}\n\n\nPPO_kwargs = {'env' : None,\n 'batch_size' : 32,\n 'timesteps_per_batch' : 1200,\n 'clip' : 0.08,\n 'a_lr' : 1e-4,\n 'c_lr' : 3e-4,\n 'n_updates_per_iteration' : 6,\n 'max_timesteps_per_episode' : 40,\n 'gamma' : .95,\n 'actor' : None}\nsvw_kwargs = {'batch_size' : 128, 'data_set_size' : 507528}\ntrain_kwargs = {'total_epochs' : 15,\n 'batch_size' : 256,\n 'epochs_per_chunk' : 1,\n 'num_chunks' : 0,\n 'cv_path' : './CrossVal/chunk_11',\n 'PPO_steps' : 150000}\n\n\n%run ChemEnv.ipynb\nsvtr = SupervisedToReinforcement('test_18',rewards_list,chem_env_kwargs,PPO_kwargs,svw_kwargs)\nsvtr.Train(**train_kwargs)\n\n",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CCCN(CC)C(=O)S')",
"_____no_output_____"
],
[
"svtr.PPO.inference()",
"_____no_output_____"
],
[
"env = svtr.ChemEnv",
"_____no_output_____"
],
[
"env.assignMol(Chem.MolFromSmiles('CCC(C)C(=O)O'))\nprint(env.last_action_node)\nenv.StateSpace",
"_____no_output_____"
],
[
"env.step(0,verbose=True)\nenv.StateSpace",
"_____no_output_____"
],
[
"PPO_kwargs = {'env' : env,\n 'batch_size' : 32,\n 'timesteps_per_batch' : 1200,\n 'clip' : 0.08,\n 'a_lr' : 1e-4,\n 'c_lr' : 3e-4,\n 'n_updates_per_iteration' : 6,\n 'max_timesteps_per_episode' : 40,\n 'gamma' : .95,\n 'actor' : svtr.svw.policy,\n 'writer': SummaryWriter(f'./tb_logs/3/3_logs')}\nppo_test = PPO_MAIN(**PPO_kwargs)\nppo_test.inference()\n",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CCC(C(N)=O)N1CC(C)CC1=O')",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CCCNC(=O)n1ccnc1C')",
"_____no_output_____"
],
[
"env.assignMol(Chem.MolFromSmiles('C.C'))\nenv.step(19,verbose=True)\nenv.StateSpace",
"_____no_output_____"
],
[
"chem_env_kwargs = {'max_nodes' : 12, \n 'num_atom_types' : 17, \n 'num_node_feats' : 54,\n 'num_edge_types' : 3, \n 'bond_padding' : 12, \n 'mol_featurizer': mol_to_graph_full, \n 'RewardModule' : rewards_list, \n 'writer' : SummaryWriter(f'./tb_logs/3/3_logs'),\n 'num_chunks': 1}",
"_____no_output_____"
],
[
"%run ChemEnv.ipynb",
"_____no_output_____"
],
[
"env = ChemEnv(**chem_env_kwargs)",
"_____no_output_____"
],
[
"env.assignMol(Chem.MolFromSmiles('CCC.N'))",
"_____no_output_____"
],
[
"env.step(2, verbose=True)\nenv.StateSpace",
"_____no_output_____"
],
[
"ppo_test = PPO_MAIN(**PPO_kwargs)",
"_____no_output_____"
],
[
"svtr.PPO.actor = svtr.policy",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CCC.N')",
"_____no_output_____"
],
[
"ppo_test.inference(True)",
"_____no_output_____"
],
[
"torch.save({\n 'model_state_dict': svtr.policy.state_dict(),\n 'optimizer_state_dict': svtr.svw.optim.state_dict()\n }, './test_1/ah')",
"_____no_output_____"
],
[
"svtr.policy.state_dict()\nmodel = Spin2(54,300,17)\nmodel.load_state_dict(svtr.policy.state_dict())",
"_____no_output_____"
],
[
"%run ChemEnv.ipynb\nsvtr = SupervisedToReinforcement('test',rewards_list,chem_env_kwargs,PPO_kwargs)\nenv = svtr.ChemEnv",
"_____no_output_____"
],
[
"svtr.PPO.inference()",
"_____no_output_____"
],
[
"torch.save(svtr.PPO.actor.state_dict(), './model')",
"_____no_output_____"
],
[
"env = svtr.ChemEnv\nenv.reset()\nenv.step(14)\nenv.step(17)\nenv.step(14)\nenv.StateSpace",
"_____no_output_____"
],
[
"(Chem.MolFromSmiles('NCc1cccc([SH]=O)c1', sanitize = True))\n",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('Nc1cc2ccc1SSC(S)C2O.c1ccnc1', sanitize = False)",
"_____no_output_____"
],
[
"\n\nenv.reset()\n#env.StateSpace = Chem.RWMol(Chem.MolFromSmiles('Nc1cc2ccc1SSC(S)C2O.c1ccnc1', sanitize = False))\n#env.step(16)\n\n#env.addEdge(1,0)\n\nenv.addBenzine()\nenv.addEdge(1,0)\nenv.StateSpace\nenv.addPyrrole()\nenv.addEdge(1,11) \n# env.StateSpace.RemoveAtom(17)\n# env.StateSpace.RemoveAtom(16)\n# env.StateSpace.RemoveAtom(15)\n# env.StateSpace.RemoveAtom(14)\n# env.StateSpace.RemoveAtom(13)\n#Chem.SanitizeMol(env.StateSpace)\nenv.StateSpace",
"_____no_output_____"
],
[
"for atom in env.StateSpace.GetAtoms():\n print(atom.GetDegree(),atom.GetSymbol(),atom.GetIsAromatic())",
"_____no_output_____"
],
[
"t_mol = Chem.RWMol(Chem.MolFromSmiles('FC(CBr)c1ccccc1',sanitize = True))\nt_mol",
"_____no_output_____"
],
[
"env.reset()\nenv.addBenzine()\nenv.addEdge(2,0)\nenv.StateSpace",
"_____no_output_____"
],
[
"t_mol = Chem.RWMol(Chem.MolFromSmiles('FC(CBr)c1ccccc1',sanitize = True))\nenv = svtr.ChemEnv\nenv.reset()\nenv.StateSpace = t_mol\n# env.StateSpace\nenv.addEdge(2,7)\nenv.StateSpace",
"_____no_output_____"
],
[
"env = svtr.ChemEnv\nenv.reset()\n# env.addPyrrole()\nenv.addBenzine()\nenv.addEdge(1,2)\n# env.addNode('C')\n# env.addEdge(2,4)\n#env.addNode('C')\n#env.addEdge(1,3)\nenv.StateSpace",
"_____no_output_____"
],
[
"mol2 = SanitizeNoKEKU(mol2)",
"_____no_output_____"
],
[
"mol2",
"_____no_output_____"
],
[
"\nmol2 = Chem.RWMol(Chem.MolFromSmiles('O=CC(=Bc1ccccc1P)P(Br)c1ccccc1.[NaH]', sanitize = True))\nmol1 = Chem.RWMol(Chem.MolFromSmiles('CC.c1ccnc1', sanitize = False))\nmol2.UpdatePropertyCache()\n#mol2.AddAtom(Chem.Atom('C'))\n#mol2.AddBond(0,5,Chem.BondType.SINGLE)\n# print(mol2.NeedsUpdatePropertyCache())\n# mol2.UpdatePropertyCache()\nChem.SanitizeMol(mol2)\nmol1.AddBond(0,5,Chem.BondType.SINGLE)\nChem.SanitizeMol(mol1)\nmol2",
"_____no_output_____"
],
[
"for atom in mol2.GetAtoms():\n print(atom.GetSymbol(),atom.GetImplicitValence())",
"_____no_output_____"
],
[
"SanitizeNoKEKU(mol2)\ncycles = list(mol2.GetRingInfo().AtomRings())\nfor cycle in cycles:\n for atom_idx in cycle:\n bonds = mol2.GetAtomWithIdx(atom_idx).GetBonds()\n for bond_x in bonds:\n if bond_x.GetBondType() == Chem.BondType.DOUBLE:\n print(\"fraraf\")",
"_____no_output_____"
],
[
"for atom in mol2.GetAtoms():\n atom.UpdatePropertyCache()\n print(atom.GetExplicitValence())",
"_____no_output_____"
],
[
"for bond in atom.GetBonds():\n print(bond.GetBondType())",
"_____no_output_____"
],
[
"#env.reset()\nenv.addPyrrole()",
"_____no_output_____"
],
[
"env.StateSpace",
"_____no_output_____"
],
[
"env.step(17)",
"_____no_output_____"
],
[
"mol = Chem.MolFromSmiles('n1cccc1', sanitize = False)\nmol.UpdatePropertyCache()\nfor bond in mol.GetBonds():\n print(bond.GetBondType())",
"_____no_output_____"
],
[
"mol",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('[nH]1cccc1')",
"_____no_output_____"
],
[
"def SanitizeNoKEKU(mol):\n s_dict = {'SANITIZE_ADJUSTHS': Chem.rdmolops.SanitizeFlags.SANITIZE_ADJUSTHS,\n 'SANITIZE_ALL': Chem.rdmolops.SanitizeFlags.SANITIZE_ALL, \n 'SANITIZE_CLEANUP': Chem.rdmolops.SanitizeFlags.SANITIZE_CLEANUP, \n 'SANITIZE_CLEANUPCHIRALITY': Chem.rdmolops.SanitizeFlags.SANITIZE_CLEANUPCHIRALITY, \n 'SANITIZE_FINDRADICALS': Chem.rdmolops.SanitizeFlags.SANITIZE_FINDRADICALS, \n 'SANITIZE_KEKULIZE': Chem.rdmolops.SanitizeFlags.SANITIZE_KEKULIZE, \n 'SANITIZE_NONE': Chem.rdmolops.SanitizeFlags.SANITIZE_NONE, \n 'SANITIZE_PROPERTIES': Chem.rdmolops.SanitizeFlags.SANITIZE_PROPERTIES, \n 'SANITIZE_SETAROMATICITY': Chem.rdmolops.SanitizeFlags.SANITIZE_SETAROMATICITY, \n 'SANITIZE_SETCONJUGATION': Chem.rdmolops.SanitizeFlags.SANITIZE_SETCONJUGATION, \n 'SANITIZE_SETHYBRIDIZATION': Chem.rdmolops.SanitizeFlags.SANITIZE_SETHYBRIDIZATION, \n 'SANITIZE_SYMMRINGS': Chem.rdmolops.SanitizeFlags.SANITIZE_SYMMRINGS}\n \n #mol = Chem.SanitizeMol(mol,s_dict['SANITIZE_KEKULIZE'])\n mol = Chem.SanitizeMol(mol, s_dict['SANITIZE_ADJUSTHS'] | s_dict['SANITIZE_SETAROMATICITY'] | \n s_dict['SANITIZE_CLEANUP'] | s_dict['SANITIZE_CLEANUPCHIRALITY'] | \n s_dict['SANITIZE_FINDRADICALS'] | s_dict['SANITIZE_NONE'] | \n s_dict['SANITIZE_PROPERTIES'] | s_dict['SANITIZE_SETCONJUGATION'] | \n s_dict['SANITIZE_SETHYBRIDIZATION'] | s_dict['SANITIZE_SYMMRINGS'] \n )\n return mol",
"_____no_output_____"
],
[
"True | False",
"_____no_output_____"
],
[
"mol = Chem.RWMol(Chem.MolFromSmiles('CC.c1ccnc1', sanitize = False))\n#mol.AddBond(8,mol.GetNumAtoms()-1,Chem.BondType.SINGLE)\nprint(SanitizeNoKEKU(mol))\nprint(mol.GetAromaticAtoms().__len__())\nmol",
"_____no_output_____"
],
[
"from rdkit import Chem\nm = Chem.MolFromSmiles('CN(C)(C)C', sanitize=False)\nproblems = Chem.DetectChemistryProblems(m)\nprint(len(problems))\nm",
"_____no_output_____"
],
[
"SanitizeNoKEKU(m)",
"_____no_output_____"
],
[
"Chem.SanitizeFlags.SANITIZE_ADJUSTHS",
"_____no_output_____"
],
[
"print(problems[0].GetType())\n#print(problems[0].GetAtomIdx())\nprint(problems[0].Message())",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CN1C=CC=CC1=O')",
"_____no_output_____"
],
[
"Chem.MolFromSmiles('CN(C)(C)C', sanitize=False)",
"_____no_output_____"
],
[
"# wants: a single class for pretraining and rl training\n# also want a singler logger for everything\n# also should put in cross validation for the supervised portion\n# means a logger instance in the init method\n\nclass SupervisedToReinforcement():\n def __init__(self, PPO_env, PPO_Train_Steps, policy_model,rewards, run_title):\n \n \n self.writer = SummaryWriter('./run_title')\n self.reward_module = FinalRewardModule(sef.writer,rewards)\n \n \n self.PPO_env = PPO_env\n self.PPO_Train_Steps = PPO_Train_Steps \n self.SV_trainer = Supervised_trainer(policy_model)\n \n \n self.SV_trainer.writer = self.writer\n self.PPO_env.env.RewardModule = self.reward_module\n self.PPO_env.actor = self.policy_model\n \n def Train():\n sv_trainer.Train(20,16, 1,24)\n self.PPO_env.learn(self.PPO_Train_Steps)\n ",
"_____no_output_____"
],
[
"class AdversarialTraining():\n def __init__(self, PPO_agent,Disc, epochs, G_steps,\n D_steps, K, G_pretrain_steps, D_train_size,\n D_batch_size,pre_train_env, smiles_values):\n \n self.PPO_agent = PPO_agent\n self.Disc = Disc\n \n self.epochs = epochs\n self.G_steps = G_steps\n self.D_steps = D_steps\n self.K = K \n \n self.pre_train_env = pre_train_env\n \n self.D_batch_size = D_batch_size \n self.D_train_size = D_train_size\n self.smiles_values = smiles_values\n \n def mini_batch_reward_train(self, batch_size, num_batch):\n for j in range(num_batch):\n graphs = self.PPO_agent.generate_graphs(batch_size)\n for model in self.reward_models:\n model.TrainOnBatch(graphs)\n \n def _preTrain(self):\n \n \n env,batch_size,timesteps_per_batch,clip,a_lr,c_lr,\n n_updates_per_iteration,max_timesteps_per_episode,gamma\n\n \n t_dict = vars(self.PPO_agent)\n PPO_agent_pre = PPO_MAIN(t_dict['env'],t_dict['batch_size'],t_dict['timesteps_per_batch'],\n t_dict['clip'],t_dict['a_lr'], t_dict['c_lr'],\n t_dict['n_updates_per_iteration'],t_dict['max_timesteps_per_episode'],\n t_dict['gamma'])\n \n \n \n PPO_agent_pre.learn(G_pretrain_steps)\n self.PPO_agent.assignActor(PPO_agent_pre.actor)\n \n \n \n def pull_real_samples(self, g_number):\n graphs = smiles_to_graph([self.smiles_values[random.randint(0,len(self.smiles_values))] for _ in range(g_number)])\n print(len(graphs), \"graph len\")\n \n return graphs\n def i_hate_python(self):\n a = self.PPO_agent.generate_graphs(10)\n def train(self, epochs):\n self._preTrain()\n for epoch in range(epochs):\n print('G_train')\n self.PPO_agent.learn(G_steps) \n \n print('D_train')\n for d_step in range(self.D_steps):\n \n x_fake = self.PPO_agent.generate_graphs(self.D_steps)\n x_real = self.pull_real_samples(self.D_train_size)\n for k_step in range(self.K):\n slices = list(range(0,self.D_train_size,self.D_batch_size)) + [self.D_train_size]\n for idx in range(1,len(slices)):\n slice_= slice(slices[idx-1],slices[idx])\n print(slice_)\n \n \n x_fake_batch = x_fake[slice_]\n if x_fake_batch != []:\n Y_fake_batch = torch.zeros(len(x_fake_batch),1)\n\n\n x_real_batch = x_real[slice_]\n Y_real_batch = torch.ones(len(x_real_batch),1)\n\n\n self.Disc.train(x_fake_batch, Y_fake_batch)\n self.Disc.train(x_real_batch,Y_real_batch)\n \n \n \n \n \n ",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb497f6c15b8ace5842de86afe62e5282b0418e2 | 24,267 | ipynb | Jupyter Notebook | module3/lesson_applied_modeling_3.ipynb | alxanderpierre/DS-Unit-2-Applied-Modeling | a8248f61131932bb77235bfb25db2a20e6d312db | [
"MIT"
] | 1 | 2019-09-17T03:33:16.000Z | 2019-09-17T03:33:16.000Z | module3/lesson_applied_modeling_3.ipynb | alxanderpierre/DS-Unit-2-Applied-Modeling | a8248f61131932bb77235bfb25db2a20e6d312db | [
"MIT"
] | null | null | null | module3/lesson_applied_modeling_3.ipynb | alxanderpierre/DS-Unit-2-Applied-Modeling | a8248f61131932bb77235bfb25db2a20e6d312db | [
"MIT"
] | null | null | null | 29.959259 | 631 | 0.495941 | [
[
[
"Lambda School Data Science, Unit 2: Predictive Modeling\n\n# Applied Modeling, Module 3\n\n### Objective\n- Visualize and interpret partial dependence plots",
"_____no_output_____"
],
[
"### Links\n- [Kaggle / Dan Becker: Machine Learning Explainability — Partial Dependence Plots](https://www.kaggle.com/dansbecker/partial-plots)\n- [Christoph Molnar: Interpretable Machine Learning — Partial Dependence Plots](https://christophm.github.io/interpretable-ml-book/pdp.html) + [animated explanation](https://twitter.com/ChristophMolnar/status/1066398522608635904)",
"_____no_output_____"
],
[
"\n\n### Three types of model explanations this unit:\n\n#### 1. Global model explanation: all features in relation to each other _(Last Week)_\n- Feature Importances: _Default, fastest, good for first estimates_\n- Drop-Column Importances: _The best in theory, but much too slow in practice_\n- Permutaton Importances: _A good compromise!_\n\n#### 2. Global model explanation: individual feature(s) in relation to target _(Today)_\n- Partial Dependence plots\n\n#### 3. Individual prediction explanation _(Tomorrow)_\n- Shapley Values\n\n_Note that the coefficients from a linear model give you all three types of explanations!_",
"_____no_output_____"
],
[
"### Setup\n\n#### If you're using [Anaconda](https://www.anaconda.com/distribution/) locally\n\nInstall required Python packages, if you haven't already:\n\n- [category_encoders](https://github.com/scikit-learn-contrib/categorical-encoding), version >= 2.0: `conda install -c conda-forge category_encoders` / `pip install category_encoders`\n- [PDPbox](https://github.com/SauceCat/PDPbox): `pip install pdpbox`\n- [Plotly](https://medium.com/plotly/plotly-py-4-0-is-here-offline-only-express-first-displayable-anywhere-fc444e5659ee), version >= 4.0\n",
"_____no_output_____"
]
],
[
[
"# If you're in Colab...\nimport os, sys\nin_colab = 'google.colab' in sys.modules\n\nif in_colab:\n # Install required python package:\n # category_encoders, version >= 2.0\n !pip install --upgrade category_encoders pdpbox plotly\n \n # Pull files from Github repo\n os.chdir('/content')\n !git init .\n !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Applied-Modeling.git\n !git pull origin master\n \n # Change into directory for module\n os.chdir('module3')",
"_____no_output_____"
]
],
[
[
"## Lending Club: Predict interest rate",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\n# Stratified sample, 10% of expired Lending Club loans, grades A-D\n# Source: https://www.lendingclub.com/info/download-data.action\nhistory_location = '../data/lending-club/lending-club-subset.csv'\nhistory = pd.read_csv(history_location)\nhistory['issue_d'] = pd.to_datetime(history['issue_d'], infer_datetime_format=True)\n\n# Just use 36 month loans\nhistory = history[history.term==' 36 months']\n\n# Index & sort by issue date\nhistory = history.set_index('issue_d').sort_index()\n\n# Clean data, engineer feature, & select subset of features\nhistory = history.rename(columns= \n {'annual_inc': 'Annual Income', \n 'fico_range_high': 'Credit Score', \n 'funded_amnt': 'Loan Amount', \n 'title': 'Loan Purpose'})\n\nhistory['Interest Rate'] = history['int_rate'].str.strip('%').astype(float)\nhistory['Monthly Debts'] = history['Annual Income'] / 12 * history['dti'] / 100\n\ncolumns = ['Annual Income', \n 'Credit Score', \n 'Loan Amount', \n 'Loan Purpose', \n 'Monthly Debts', \n 'Interest Rate']\n\nhistory = history[columns]\nhistory = history.dropna()\n\n# Test on the last 10,000 loans,\n# Validate on the 10,000 before that,\n# Train on the rest\ntest = history[-10000:]\nval = history[-20000:-10000]\ntrain = history[:-20000]",
"_____no_output_____"
],
[
"# Assign to X, y\ntarget = 'Interest Rate'\nfeatures = history.columns.drop('Interest Rate')\n\nX_train = train[features]\ny_train = train[target]\n\nX_val = val[features]\ny_val = val[target]\n\nX_test = test[features]\ny_test = test[target]",
"_____no_output_____"
],
[
"# The target has some right skew.\n# It's not bad, but we'll log transform anyways\n%matplotlib inline\nimport seaborn as sns\nsns.distplot(y_train);",
"_____no_output_____"
],
[
"# Log transform the target\nimport numpy as np\ny_train_log = np.log1p(y_train)\ny_val_log = np.log1p(y_val)\ny_test_log = np.log1p(y_test)\n\n# Plot the transformed target's distribution\nsns.distplot(y_train_log);",
"_____no_output_____"
]
],
[
[
"### Fit Linear Regression model, with original target",
"_____no_output_____"
]
],
[
[
"import category_encoders as ce\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nlr = make_pipeline(\n ce.OrdinalEncoder(), # Not ideal for Linear Regression \n StandardScaler(), \n LinearRegression()\n)\n\nlr.fit(X_train, y_train)\nprint('Linear Regression R^2', lr.score(X_val, y_val))",
"_____no_output_____"
]
],
[
[
"### Fit Gradient Boosting model, with log transformed target",
"_____no_output_____"
]
],
[
[
"from xgboost import XGBRegressor\n\ngb = make_pipeline(\n ce.OrdinalEncoder(), \n XGBRegressor(n_estimators=200, objective='reg:squarederror', n_jobs=-1)\n)\n\ngb.fit(X_train, y_train_log)\n# print('Gradient Boosting R^2', gb.score(X_val, y_val_log))\n# Convert back away from log space",
"_____no_output_____"
]
],
[
[
"### Explaining Linear Regression",
"_____no_output_____"
]
],
[
[
"example = X_val.iloc[[0]]\nexample",
"_____no_output_____"
],
[
"pred = lr.predict(example)[0]\nprint(f'Predicted Interest Rate: {pred:.2f}%')",
"_____no_output_____"
],
[
"def predict(model, example, log=False):\n print('Vary income, hold other features constant', '\\n')\n example = example.copy()\n preds = []\n for income in range(20000, 200000, 20000):\n example['Annual Income'] = income\n pred = model.predict(example)[0]\n if log:\n pred = np.expm1(pred)\n print(f'Predicted Interest Rate: {pred:.3f}%')\n print(example.to_string(), '\\n')\n preds.append(pred)\n print('Difference between predictions')\n print(np.diff(preds))\n \npredict(lr, example)",
"_____no_output_____"
],
[
"example2 = X_val.iloc[[2]]\npredict(lr, example2);",
"_____no_output_____"
]
],
[
[
"### Explaining Gradient Boosting???",
"_____no_output_____"
]
],
[
[
"predict(gb, example, log=True)",
"_____no_output_____"
],
[
"predict(gb, example2, log=True)",
"_____no_output_____"
]
],
[
[
"## Partial Dependence Plots",
"_____no_output_____"
],
[
"From [PDPbox documentation](https://pdpbox.readthedocs.io/en/latest/):\n\n\n>**The common headache**: When using black box machine learning algorithms like random forest and boosting, it is hard to understand the relations between predictors and model outcome. For example, in terms of random forest, all we get is the feature importance. Although we can know which feature is significantly influencing the outcome based on the importance calculation, it really sucks that we don’t know in which direction it is influencing. And in most of the real cases, the effect is non-monotonic. We need some powerful tools to help understanding the complex relations between predictors and model prediction.",
"_____no_output_____"
],
[
"[Animation by Christoph Molnar](https://twitter.com/ChristophMolnar/status/1066398522608635904), author of [_Interpretable Machine Learning_](https://christophm.github.io/interpretable-ml-book/pdp.html#examples)\n\n> Partial dependence plots show how a feature affects predictions of a Machine Learning model on average.\n> 1. Define grid along feature\n> 2. Model predictions at grid points\n> 3. Line per data instance -> ICE (Individual Conditional Expectation) curve\n> 4. Average curves to get a PDP (Partial Dependence Plot)",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nexamples = pd.concat([example, example2])\nfor income in range(20000, 200000, 20000):\n examples['Annual Income'] = income\n preds_log = gb.predict(examples)\n preds = np.expm1(preds_log)\n for pred in preds:\n plt.scatter(income, pred, color='grey')\n plt.scatter(income, np.mean(preds), color='red')",
"_____no_output_____"
]
],
[
[
"## Partial Dependence Plots with 1 feature\n\n#### PDPbox\n- [Gallery](https://github.com/SauceCat/PDPbox#gallery)\n- [API Reference: pdp_isolate](https://pdpbox.readthedocs.io/en/latest/pdp_isolate.html)\n- [API Reference: pdp_plot](https://pdpbox.readthedocs.io/en/latest/pdp_plot.html)",
"_____no_output_____"
]
],
[
[
"# Later, when you save matplotlib images to include in blog posts or web apps,\n# increase the dots per inch (double it), so the text isn't so fuzzy\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 72",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"#### You can customize it\n\nPDPbox\n- [API Reference: PDPIsolate](https://pdpbox.readthedocs.io/en/latest/PDPIsolate.html)",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"## Partial Dependence Plots with 2 features\n\nSee interactions!\n\nPDPbox\n- [Gallery](https://github.com/SauceCat/PDPbox#gallery)\n- [API Reference: pdp_interact](https://pdpbox.readthedocs.io/en/latest/pdp_interact.html)\n- [API Reference: pdp_interact_plot](https://pdpbox.readthedocs.io/en/latest/pdp_interact_plot.html)\n\nBe aware of a bug in PDPBox version <= 0.20:\n- With the `pdp_interact_plot` function, `plot_type='contour'` gets an error, but `plot_type='grid'` works\n- This will be fixed in the next release of PDPbox: https://github.com/SauceCat/PDPbox/issues/40",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"### 3D with Plotly!",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# Partial Dependence Plots with categorical features\n\n1. I recommend you use Ordinal Encoder, outside of a pipeline, to encode your data first. Then use the encoded data with pdpbox.\n2. There's some extra work to get readable category names on your plot, instead of integer category codes.",
"_____no_output_____"
]
],
[
[
"# Fit a model on Titanic data\nimport category_encoders as ce\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestClassifier\n\ndf = sns.load_dataset('titanic')\ndf.age = df.age.fillna(df.age.median())\ndf = df.drop(columns='deck')\ndf = df.dropna()\n\ntarget = 'survived'\nfeatures = df.columns.drop(['survived', 'alive'])\n\nX = df[features]\ny = df[target]\n\n# Use Ordinal \nencoder = ce.OrdinalEncoder()\nX_encoded = encoder.fit_transform(X)\n\nmodel = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)\nmodel.fit(X_encoded, y)",
"_____no_output_____"
],
[
"# Use Pdpbox\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pdpbox import pdp\nfeature = 'sex'\npdp_dist = pdp.pdp_isolate(model=model, dataset=X_encoded, model_features=features, feature=feature)\npdp.pdp_plot(pdp_dist, feature);",
"_____no_output_____"
],
[
"# Look at the encoder's mappings\nencoder.mapping",
"_____no_output_____"
],
[
"pdp.pdp_plot(pdp_dist, feature)\n\n# Manually change the xticks labels\nplt.xticks([1, 2], ['male', 'female']);",
"_____no_output_____"
],
[
"# Let's automate it\n\nfeature = 'sex'\nfor item in encoder.mapping:\n if item['col'] == feature:\n feature_mapping = item['mapping']\n\nfeature_mapping = feature_mapping[feature_mapping.index.dropna()]\ncategory_names = feature_mapping.index.tolist()\ncategory_codes = feature_mapping.values.tolist()",
"_____no_output_____"
],
[
"# Use Pdpbox\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pdpbox import pdp\nfeature = 'sex'\npdp_dist = pdp.pdp_isolate(model=model, dataset=X_encoded, model_features=features, feature=feature)\npdp.pdp_plot(pdp_dist, feature)\n\n# Automatically change the xticks labels\nplt.xticks(category_codes, category_names);",
"_____no_output_____"
],
[
"features = ['sex', 'age']\n\ninteraction = pdp_interact(\n model=model, \n dataset=X_encoded, \n model_features=X_encoded.columns, \n features=features\n)\n\npdp_interact_plot(interaction, plot_type='grid', feature_names=features);",
"_____no_output_____"
],
[
"pdp = interaction.pdp.pivot_table(\n values='preds', \n columns=features[0], # First feature on x axis\n index=features[1] # Next feature on y axis\n)[::-1] # Reverse the index order so y axis is ascending\n\npdp = pdp.rename(columns=dict(zip(category_codes, category_names)))\n\nplt.figure(figsize=(10,8))\nsns.heatmap(pdp, annot=True, fmt='.2f', cmap='viridis')\nplt.title('Partial Dependence of Titanic survival, on sex & age');",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb49b0eafc363e1dff8c83da3661db929b7a1081 | 18,030 | ipynb | Jupyter Notebook | scratch_work/API_testing.ipynb | pawlodkowski/Movie_Recommender | 2294081ec439b43feb2596835aa3508c7a3e4d28 | [
"MIT"
] | 2 | 2018-10-12T07:59:35.000Z | 2018-10-12T08:04:18.000Z | scratch_work/API_testing.ipynb | pawlodkowski/Movie_Recommender | 2294081ec439b43feb2596835aa3508c7a3e4d28 | [
"MIT"
] | null | null | null | scratch_work/API_testing.ipynb | pawlodkowski/Movie_Recommender | 2294081ec439b43feb2596835aa3508c7a3e4d28 | [
"MIT"
] | null | null | null | 24.266487 | 143 | 0.389795 | [
[
[
"# Obtaining movie data, API-testing",
"_____no_output_____"
]
],
[
[
"# open questions:\n\n# API only allows 1k requests per day..\n# initial load (static database) or load on request, maybe another API required then?\n# regular updates?",
"_____no_output_____"
],
[
"import requests\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"# get imdb ids",
"_____no_output_____"
]
],
[
[
"# uses links.csv, a list of random imdbIds from https://grouplens.org/datasets/movielens/ , to obtain imdb ids, \n# then loops through some of them and puts them into a list",
"_____no_output_____"
],
[
"def get_ids(n):\n dtype_dic= {'movieId': str,'imdbId' : str, \"tmdbId\": str}\n IDdf = pd.read_csv(\"data/temp_links.csv\", dtype = dtype_dic)\n #IMDB IDs to eventually be used as index\n idlist = list(IDdf[\"imdbId\"].head(n))\n return idlist",
"_____no_output_____"
],
[
"imdbIDs = get_ids(500)\nimdbIDs",
"_____no_output_____"
]
],
[
[
"# get data from omdb",
"_____no_output_____"
]
],
[
[
"# http://www.omdbapi.com/\n# API-key d3de5220\n# max # of requests per day ~ 1k",
"_____no_output_____"
],
[
"# Receiving data from API and putting it into df\ndef get_data_from_omdb(imdbIDs):\n df0 = pd.DataFrame()\n for id in imdbIDs:\n url = f\"http://www.omdbapi.com/?i=tt{id}&apikey=d3de5220\"\n result = requests.get(url)\n j = result.json()\n df_single_movie = pd.DataFrame(j)\n df0 = pd.concat([df0, df_single_movie])\n return df0\n\n\ndef perform_cleaning(df):\n \n # turns date of release into date format \n df[\"Released\"] = pd.to_datetime(df[\"Released\"])\n \n #converting \"xx mins\" into \"xx\"\n def get_mins(x):\n y = x.replace(\" min\", \"\")\n return y\n df[\"Runtime\"] = df[\"Runtime\"].apply(get_mins) \n df[\"Runtime\"] = pd.to_numeric(df[\"Runtime\"])\n \n # drops duplicates, for some reason same movie appears always three times in df when converting json file...\n df0 = df.drop_duplicates(\"imdbID\", keep = \"first\", inplace = False)\n return df0",
"_____no_output_____"
],
[
"df_raw = get_data_from_omdb(imdbIDs)",
"_____no_output_____"
],
[
"df = df_raw.copy()\ndf = perform_cleaning(df_raw)",
"_____no_output_____"
],
[
"df.to_csv(\"data/OMDB.csv\", index = False)",
"_____no_output_____"
]
],
[
[
"# \"parked\" code for now",
"_____no_output_____"
]
],
[
[
"#df0 = pd.read_csv(\"data/OMDB.csv\")\n#df0.info()",
"_____no_output_____"
],
[
"#df = pd.read_csv(\"data/OMDB.csv\", dtype = df_dtypes)\n#df.head(3)",
"_____no_output_____"
],
[
"# provide a list of datatypes that the columns shall have --> leading zeros?\n'''\ndf_columns = [\"Title\", 'Year', 'Rated', 'Released', 'Runtime', 'Genre', 'Director','Writer','Actors','Plot','Language', \\\n 'Country','Awards', 'Poster', 'Ratings','Metascore','imdbRating','imdbVotes','imdbID','Type','DVD',\\\n 'BoxOffice','Production','Website','Response']\n\ndf_dtypes = {'Title': str,'Year' : int, \"Rated\": str, \"Released\" : str, \"Runtime\": int, \"Genre\": str, \"Director\": str, \\\n \"Writer\": str, \"Actors\": str, \"Plot\": str, \"Language\": str, \"Country\": str, \"Awards\": str, \"Poster\": str, \\\n \"Ratings\": str, \"Metascore\": int, \"imdbRating\": str, \"imdbVotes\": str, \"imdbID\": str, \"Type\": str, \\\n \"DVD\": str, \"BoxOffice\": str, \"Production\": str, \"Website\": str, \"Response\": str}\n'''",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb49b709029f9d575d59dc1f7c840d61159a39ea | 37,476 | ipynb | Jupyter Notebook | 08-deep-learning/labs/01_labs_DeepLearning/04a_overfitting-and-underfitting.ipynb | RaquelMartinDiaz/NEOLAND-DS2020-datalabs | 9e327b8aadd5e7200d66b8f9e78dc8e556e6893e | [
"MIT"
] | null | null | null | 08-deep-learning/labs/01_labs_DeepLearning/04a_overfitting-and-underfitting.ipynb | RaquelMartinDiaz/NEOLAND-DS2020-datalabs | 9e327b8aadd5e7200d66b8f9e78dc8e556e6893e | [
"MIT"
] | null | null | null | 08-deep-learning/labs/01_labs_DeepLearning/04a_overfitting-and-underfitting.ipynb | RaquelMartinDiaz/NEOLAND-DS2020-datalabs | 9e327b8aadd5e7200d66b8f9e78dc8e556e6893e | [
"MIT"
] | null | null | null | 73.771654 | 16,868 | 0.745864 | [
[
[
"# Introduction #\n\nRecall from the example in the previous lesson that Keras will keep a history of the training and validation loss over the epochs that it is training the model. In this lesson, we're going to learn how to interpret these learning curves and how we can use them to guide model development. In particular, we'll examine at the learning curves for evidence of *underfitting* and *overfitting* and look at a couple of strategies for correcting it.\n\n# Interpreting the Learning Curves #\n\nYou might think about the information in the training data as being of two kinds: *signal* and *noise*. The signal is the part that generalizes, the part that can help our model make predictions from new data. The noise is that part that is *only* true of the training data; the noise is all of the random fluctuation that comes from data in the real-world or all of the incidental, non-informative patterns that can't actually help the model make predictions. The noise is the part might look useful but really isn't.\n\nWe train a model by choosing weights or parameters that minimize the loss on a training set. You might know, however, that to accurately assess a model's performance, we need to evaluate it on a new set of data, the *validation* data. (You could see our lesson on [model validation](https://www.kaggle.com/dansbecker/model-validation) in *Introduction to Machine Learning* for a review.)\n\nWhen we train a model we've been plotting the loss on the training set epoch by epoch. To this we'll add a plot the validation data too. These plots we call the **learning curves**. To train deep learning models effectively, we need to be able to interpret them.\n\n<figure style=\"padding: 1em;\">\n<img src=\"https://i.imgur.com/tHiVFnM.png\" width=\"500\" alt=\"A graph of training and validation loss.\">\n<figcaption style=\"textalign: center; font-style: italic\"><center>The validation loss gives an estimate of the expected error on unseen data.\n</center></figcaption>\n</figure>\n\nNow, the training loss will go down either when the model learns signal or when it learns noise. But the validation loss will go down only when the model learns signal. (Whatever noise the model learned from the training set won't generalize to new data.) So, when a model learns signal both curves go down, but when it learns noise a *gap* is created in the curves. The size of the gap tells you how much noise the model has learned.\n\nIdeally, we would create models that learn all of the signal and none of the noise. This will practically never happen. Instead we make a trade. We can get the model to learn more signal at the cost of learning more noise. So long as the trade is in our favor, the validation loss will continue to decrease. After a certain point, however, the trade can turn against us, the cost exceeds the benefit, and the validation loss begins to rise.\n\n<figure style=\"padding: 1em;\">\n<img src=\"https://i.imgur.com/eUF6mfo.png\" width=\"600\" alt=\"Two graphs. On the left, a line through a few data points with the true fit a parabola. On the right, a curve running through each datapoint with the true fit a parabola.\">\n<figcaption style=\"textalign: center; font-style: italic\"><center>Underfitting and overfitting.\n</center></figcaption>\n</figure>\n\nThis trade-off indicates that there can be two problems that occur when training a model: not enough signal or too much noise. **Underfitting** the training set is when the loss is not as low as it could be because the model hasn't learned enough *signal*. **Overfitting** the training set is when the loss is not as low as it could be because the model learned too much *noise*. The trick to training deep learning models is finding the best balance between the two.\n\nWe'll look at a couple ways of getting more signal out of the training data while reducing the amount of noise.\n\n# Capacity #\n\nA model's **capacity** refers to the size and complexity of the patterns it is able to learn. For neural networks, this will largely be determined by how many neurons it has and how they are connected together. If it appears that your network is underfitting the data, you should try increasing its capacity.\n\nYou can increase the capacity of a network either by making it *wider* (more units to existing layers) or by making it *deeper* (adding more layers). Wider networks have an easier time learning more linear relationships, while deeper networks prefer more nonlinear ones. Which is better just depends on the dataset.\n\n```\nmodel = keras.Sequential([\n layers.Dense(16, activation='relu'),\n layers.Dense(1),\n])\n\nwider = keras.Sequential([\n layers.Dense(32, activation='relu'),\n layers.Dense(1),\n])\n\ndeeper = keras.Sequential([\n layers.Dense(16, activation='relu'),\n layers.Dense(16, activation='relu'),\n layers.Dense(1),\n])\n```\n\nYou'll explore how the capacity of a network can affect its performance in the exercise.\n\n# Early Stopping #\n\nWe mentioned that when a model is too eagerly learning noise, the validation loss may start to increase during training. To prevent this, we can simply stop the training whenever it seems the validation loss isn't decreasing anymore. Interrupting the training this way is called **early stopping**.\n\n<figure style=\"padding: 1em;\">\n<img src=\"https://i.imgur.com/eP0gppr.png\" width=500 alt=\"A graph of the learning curves with early stopping at the minimum validation loss, underfitting to the left of it and overfitting to the right.\">\n<figcaption style=\"textalign: center; font-style: italic\"><center>We keep the model where the validation loss is at a minimum.\n</center></figcaption>\n</figure>\n\nOnce we detect that the validation loss is starting to rise again, we can reset the weights back to where the minimum occured. This ensures that the model won't continue to learn noise and overfit the data.\n\nTraining with early stopping also means we're in less danger of stopping the training too early, before the network has finished learning signal. So besides preventing overfitting from training too long, early stopping can also prevent *underfitting* from not training long enough. Just set your training epochs to some large number (more than you'll need), and early stopping will take care of the rest.\n\n## Adding Early Stopping ##\n\nIn Keras, we include early stopping in our training through a callback. A **callback** is just a function you want run every so often while the network trains. The early stopping callback will run after every epoch. (Keras has [a variety of useful callbacks](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks) pre-defined, but you can [define your own](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/LambdaCallback), too.)",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.callbacks import EarlyStopping\n\nearly_stopping = EarlyStopping(\n min_delta=0.001, # minimium amount of change to count as an improvement\n patience=20, # how many epochs to wait before stopping\n restore_best_weights=True,\n)",
"_____no_output_____"
]
],
[
[
"These parameters say: \"If there hasn't been at least an improvement of 0.001 in the validation loss over the previous 20 epochs, then stop the training and keep the best model you found.\" It can sometimes be hard to tell if the validation loss is rising due to overfitting or just due to random batch variation. The parameters allow us to set some allowances around when to stop.\n\nAs we'll see in our example, we'll pass this callback to the `fit` method along with the loss and optimizer.\n\n# Example - Train a Model with Early Stopping #\n\nLet's continue developing the model from the example in the last tutorial. We'll increase the capacity of that network but also add an early-stopping callback to prevent overfitting.\n\nHere's the data prep again.",
"_____no_output_____"
]
],
[
[
"\nimport pandas as pd\nfrom IPython.display import display\n\nred_wine = pd.read_csv('../input/dl-course-data/red-wine.csv')\n\n# Create training and validation splits\ndf_train = red_wine.sample(frac=0.7, random_state=0)\ndf_valid = red_wine.drop(df_train.index)\ndisplay(df_train.head(4))\n\n# Scale to [0, 1]\nmax_ = df_train.max(axis=0)\nmin_ = df_train.min(axis=0)\ndf_train = (df_train - min_) / (max_ - min_)\ndf_valid = (df_valid - min_) / (max_ - min_)\n\n# Split features and target\nX_train = df_train.drop('quality', axis=1)\nX_valid = df_valid.drop('quality', axis=1)\ny_train = df_train['quality']\ny_valid = df_valid['quality']",
"_____no_output_____"
]
],
[
[
"Now let's increase the capacity of the network. We'll go for a fairly large network, but rely on the callback to halt the training once the validation loss shows signs of increasing.",
"_____no_output_____"
]
],
[
[
"from tensorflow import keras\nfrom tensorflow.keras import layers, callbacks\n\nearly_stopping = callbacks.EarlyStopping(\n min_delta=0.001, # minimium amount of change to count as an improvement\n patience=20, # how many epochs to wait before stopping\n restore_best_weights=True,\n)\n\nmodel = keras.Sequential([\n layers.Dense(512, activation='relu', input_shape=[11]),\n layers.Dense(512, activation='relu'),\n layers.Dense(512, activation='relu'),\n layers.Dense(1),\n])\nmodel.compile(\n optimizer='adam',\n loss='mae',\n)",
"_____no_output_____"
]
],
[
[
"After defining the callback, add it as an argument in `fit` (you can have several, so put it in a list). Choose a large number of epochs when using early stopping, more than you'll need.",
"_____no_output_____"
]
],
[
[
"history = model.fit(\n X_train, y_train,\n validation_data=(X_valid, y_valid),\n batch_size=256,\n epochs=500,\n callbacks=[early_stopping], # put your callbacks in a list\n verbose=0, # turn off training log\n)\n\nhistory_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot();\nprint(\"Minimum validation loss: {}\".format(history_df['val_loss'].min()))",
"Minimum validation loss: 0.09185197949409485\n"
]
],
[
[
"And sure enough, Keras stopped the training well before the full 500 epochs!\n\n# Your Turn #\n\nNow [**predict how popular a song is**] with the *Spotify* dataset.\n\n**PRACTICES** > 04b_overfitting_underfitting",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb49c15446db50660dd99419da158400ba9df51a | 168,070 | ipynb | Jupyter Notebook | Python_Stock/Technical_Indicators/Moving_Summation.ipynb | eu90h/Stock_Analysis_For_Quant | 5e5e9f9c2a8f4af72e26564bc9d66bd2c90880df | [
"MIT"
] | null | null | null | Python_Stock/Technical_Indicators/Moving_Summation.ipynb | eu90h/Stock_Analysis_For_Quant | 5e5e9f9c2a8f4af72e26564bc9d66bd2c90880df | [
"MIT"
] | null | null | null | Python_Stock/Technical_Indicators/Moving_Summation.ipynb | eu90h/Stock_Analysis_For_Quant | 5e5e9f9c2a8f4af72e26564bc9d66bd2c90880df | [
"MIT"
] | null | null | null | 214.648787 | 71,054 | 0.858041 | [
[
[
"# Moving Summation",
"_____no_output_____"
],
[
"https://www.fmlabs.com/reference/default.htm",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# yfinance is used to fetch data \nimport yfinance as yf\nyf.pdr_override()",
"_____no_output_____"
],
[
"# input\nsymbol = 'AAPL'\nstart = '2017-01-01'\nend = '2018-12-31'\n\n# Read data \ndf = yf.download(symbol,start,end)\n\n# View Columns\ndf.head()",
"[*********************100%***********************] 1 of 1 downloaded\n"
],
[
"n = 14 # number of periods\ndf['sum'] = df['Adj Close'].rolling(n).sum()",
"_____no_output_____"
],
[
"df.head(20)",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(14,10))\nax1 = plt.subplot(2, 1, 1)\nax1.plot(df['Adj Close'])\nax1.set_title('Stock '+ symbol +' Closing Price')\nax1.set_ylabel('Price')\n\nax2 = plt.subplot(2, 1, 2)\nax2.plot(df['sum'], label='Moving Summation')\nax2.grid()\nax2.legend(loc='best')\nax2.set_ylabel('Moving Summation')\nax2.set_xlabel('Date')",
"_____no_output_____"
]
],
[
[
"## Candlestick with Moving Summation",
"_____no_output_____"
]
],
[
[
"from matplotlib import dates as mdates\nimport datetime as dt\n\ndfc = df.copy()\ndfc['VolumePositive'] = dfc['Open'] < dfc['Adj Close']\n#dfc = dfc.dropna()\ndfc = dfc.reset_index()\ndfc['Date'] = mdates.date2num(dfc['Date'].astype(dt.date))\ndfc.head()",
"_____no_output_____"
],
[
"from mpl_finance import candlestick_ohlc\n\nfig = plt.figure(figsize=(14,10))\nax1 = plt.subplot(2, 1, 1)\ncandlestick_ohlc(ax1,dfc.values, width=0.5, colorup='g', colordown='r', alpha=1.0)\nax1.xaxis_date()\nax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))\nax1.grid(True, which='both')\nax1.minorticks_on()\nax1v = ax1.twinx()\ncolors = dfc.VolumePositive.map({True: 'g', False: 'r'})\nax1v.bar(dfc.Date, dfc['Volume'], color=colors, alpha=0.4)\nax1v.axes.yaxis.set_ticklabels([])\nax1v.set_ylim(0, 3*df.Volume.max())\nax1.set_title('Stock '+ symbol +' Closing Price')\nax1.set_ylabel('Price')\n\nax2 = plt.subplot(2, 1, 2)\nax2.plot(df['sum'], label='Moving Summation')\nax2.grid()\nax2.legend(loc='best')\nax2.set_ylabel('Moving Summation')\nax2.set_xlabel('Date')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb49c8f36029b3dc5f0c1aacb6dde5b6ceac01aa | 7,497 | ipynb | Jupyter Notebook | ohop/Episode5.ipynb | gitter-badger/ohop | e7a88b4aaefb3ee250cf3c44893c801d201e0378 | [
"MIT"
] | null | null | null | ohop/Episode5.ipynb | gitter-badger/ohop | e7a88b4aaefb3ee250cf3c44893c801d201e0378 | [
"MIT"
] | null | null | null | ohop/Episode5.ipynb | gitter-badger/ohop | e7a88b4aaefb3ee250cf3c44893c801d201e0378 | [
"MIT"
] | 1 | 2021-10-04T19:37:54.000Z | 2021-10-04T19:37:54.000Z | 21.058989 | 87 | 0.478458 | [
[
[
"import nbimport\nimport MetaMagicsPlay",
"ERROR:root:Exception in cell.\nTraceback (most recent call last):\n File \"/home/jon/git/ohop/ohop/nbimport.py\", line 73, in load_module\n exec(code, manager.namespace)\n File \"<string>\", line 1, in <module>\n File \"<string>\", line 1\n the_possibly_worst_answer = 0\n ^\nSyntaxError: invalid syntax\nERROR:root:Exception in cell.\nTraceback (most recent call last):\n File \"/home/jon/git/ohop/ohop/nbimport.py\", line 73, in load_module\n exec(code, manager.namespace)\n File \"<string>\", line 2, in <module>\n File \"<string>\", line 1\n not_a_good_answer = -1\n ^\nSyntaxError: invalid syntax\n"
],
[
"list(MetaMagicsPlay.__dict__.keys())",
"_____no_output_____"
],
[
"MetaMagicsPlay.the_possibly_worst_answer",
"_____no_output_____"
],
[
"%load_ext metamagics",
"The metamagics extension is already loaded. To reload it, use:\n %reload_ext metamagics\n"
],
[
"%myline MetaMagicsPlay.the_possibly_worst_answer",
"_____no_output_____"
],
[
"def a_foot(cell):\n print(f'The cell is {\"\" if cell.startswith(\"12\") else \"NOT \"}afoot!')\n",
"_____no_output_____"
],
[
"%%mycell a_foot\n12 inches?",
"The cell is afoot!\n"
],
[
"import ast\neval_ast = ast.parse('1 + 2', mode='eval')\nexec_ast = ast.parse('1 + 2', mode='exec')\neval_ast, exec_ast",
"_____no_output_____"
],
[
"class MyVisitor(ast.NodeVisitor):\n def __init__(self):\n self.names = {}\n\n def visit_Name(self, node):\n print(ast.dump(node, indent=2))\n self.names[node.id] = node\n self.generic_visit(node)\n \n def visit_Store(self, node):\n print(f'I have a store node: {ast.dump(node)}')\n\ndef ouroboros(cell):\n cell_ast = ast.parse(cell, mode='exec')\n visitor = MyVisitor()\n visitor.visit(cell_ast)\n cell_co = compile(cell_ast, '<ouroboros-cell>', 'exec')\n exec(cell_co)\n return visitor\n",
"_____no_output_____"
],
[
"%%mycell ouroboros\nprint('Silly snake, Python is for the curious!')\ncurious = True\nif curious:\n print('Go to grad school!')\n curious = False\n",
"Name(id='print', ctx=Load())\nName(id='curious', ctx=Store())\nI have a store node: Store()\nName(id='curious', ctx=Load())\nName(id='print', ctx=Load())\nName(id='curious', ctx=Store())\nI have a store node: Store()\nSilly snake, Python is for the curious!\nGo to grad school!\n"
],
[
"visitor = _13\nvisitor.names",
"_____no_output_____"
],
[
"visitor.names['curious'].lineno",
"_____no_output_____"
],
[
"visitor.names['curious'].col_offset",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb49ccd1f368939981395303d6ce454efee8c1fe | 41,452 | ipynb | Jupyter Notebook | Notebooks/Jas_307_GenCode_MLP.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | 1 | 2021-08-16T14:49:04.000Z | 2021-08-16T14:49:04.000Z | Notebooks/Jas_307_GenCode_MLP.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | null | null | null | Notebooks/Jas_307_GenCode_MLP.ipynb | ShepherdCode/Soars2021 | ab4f304eaa09e52d260152397a6c53d7a05457da | [
"MIT"
] | null | null | null | 68.289951 | 19,872 | 0.776561 | [
[
[
"# MLP ORF to GenCode \n\nUse GenCode 38 and length-restricted data. \nUse model pre-trained on Simulated ORF. ",
"_____no_output_____"
]
],
[
[
"import time\ndef show_time():\n t = time.time()\n print(time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t)))\nshow_time()",
"2021-08-18 09:58:48 EDT\n"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Embedding,Dropout\nfrom keras.layers import Flatten,TimeDistributed\nfrom keras.losses import BinaryCrossentropy\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model",
"2021-08-18 09:58:49.316801: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0\n"
],
[
"import sys\nIN_COLAB = False\ntry:\n from google.colab import drive\n IN_COLAB = True\nexcept:\n pass\nif IN_COLAB:\n print(\"On Google CoLab, mount cloud-local file, get our code from GitHub.\")\n PATH='/content/drive/'\n #drive.mount(PATH,force_remount=True) # hardly ever need this\n drive.mount(PATH) # Google will require login credentials\n DATAPATH=PATH+'My Drive/data/' # must end in \"/\"\n import requests\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_describe.py')\n with open('RNA_describe.py', 'w') as f:\n f.write(r.text) \n from RNA_describe import ORF_counter\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/GenCodeTools.py')\n with open('GenCodeTools.py', 'w') as f:\n f.write(r.text) \n from GenCodeTools import GenCodeLoader\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/KmerTools.py')\n with open('KmerTools.py', 'w') as f:\n f.write(r.text) \n from KmerTools import KmerTools\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/DataPrep.py')\n with open('DataPrep.py', 'w') as f:\n f.write(r.text) \n from DataPrep import DataPrep\nelse:\n print(\"CoLab not working. On my PC, use relative paths.\")\n DATAPATH='data/' # must end in \"/\"\n sys.path.append(\"..\") # append parent dir in order to use sibling dirs\n from SimTools.RNA_describe import ORF_counter\n from SimTools.GenCodeTools import GenCodeLoader\n from SimTools.KmerTools import KmerTools\n from SimTools.DataPrep import DataPrep\nBESTMODELPATH=DATAPATH+\"BestModel-304\" \nLASTMODELPATH=DATAPATH+\"LastModel\" ",
"CoLab not working. On my PC, use relative paths.\n"
]
],
[
[
"## Data Load",
"_____no_output_____"
]
],
[
[
"PC_TRAINS=1000\nNC_TRAINS=1000\nPC_TESTS=40000\nNC_TESTS=40000 \nPC_LENS=(200,4000)\nNC_LENS=(200,4000) # Wen used 3500 for hyperparameter, 3000 for train\nPC_FILENAME='gencode.v38.pc_transcripts.fa.gz'\nNC_FILENAME='gencode.v38.lncRNA_transcripts.fa.gz'\nPC_FULLPATH=DATAPATH+PC_FILENAME\nNC_FULLPATH=DATAPATH+NC_FILENAME\nMAX_K = 3 \nINPUT_SHAPE=(None,84) # 4^3 + 4^2 + 4^1\nNEURONS=32\nDROP_RATE=0.30\nEPOCHS=200\nSPLITS=3\nFOLDS=3 \nshow_time()",
"2021-08-18 09:58:49 EDT\n"
],
[
"loader=GenCodeLoader()\nloader.set_label(1)\nloader.set_check_utr(False) # not ORF-restricted\nloader.set_check_size(*PC_LENS) # length-restricted\npcdf=loader.load_file(PC_FULLPATH)\nprint(\"PC seqs loaded:\",len(pcdf))\nloader.set_label(0)\nloader.set_check_utr(False) \nloader.set_check_size(*NC_LENS) # length-restricted\nncdf=loader.load_file(NC_FULLPATH)\nprint(\"NC seqs loaded:\",len(ncdf))\nshow_time()",
"PC seqs loaded: 88964\nNC seqs loaded: 46919\n2021-08-18 09:58:51 EDT\n"
],
[
"def dataframe_extract_sequence(df):\n return df['sequence'].tolist()\n\npc_all = dataframe_extract_sequence(pcdf)\nnc_all = dataframe_extract_sequence(ncdf)\npcdf=None\nncdf=None\n\nshow_time()\nprint(\"PC seqs pass filter:\",len(pc_all),type(pc_all))\nprint(\"NC seqs pass filter:\",len(nc_all),type(nc_all))\n\n#PC seqs pass filter: 55381\n#NC seqs pass filter: 46919",
"2021-08-18 09:58:51 EDT\nPC seqs pass filter: 88964 <class 'list'>\nNC seqs pass filter: 46919 <class 'list'>\n"
],
[
"print(\"Simulated sequence characteristics:\")\noc = ORF_counter()\nprint(\"PC seqs\")\noc.describe_sequences(pc_all)\nprint(\"NC seqs\")\noc.describe_sequences(nc_all)\noc=None\nshow_time()",
"Simulated sequence characteristics:\nPC seqs\nAverage RNA length: 1546.957241131244\nAverage ORF length: 785.6919203273234\nNC seqs\nAverage RNA length: 1179.5947483961722\nAverage ORF length: 203.12651591039878\n2021-08-18 09:59:09 EDT\n"
]
],
[
[
"## Data Prep",
"_____no_output_____"
]
],
[
[
"dp = DataPrep()\nXseq,y=dp.combine_pos_and_neg(pc_all,nc_all)\nnc_all=None\npc_all=None\nnc_all=None\nprint(\"The first few shuffled labels:\")\nprint(y[:30])\nshow_time()",
"The first few shuffled labels:\n[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]\n2021-08-18 09:59:09 EDT\n"
],
[
"Xfrq=KmerTools.seqs_to_kmer_freqs(Xseq,MAX_K)\nXseq = None\ny=np.asarray(y)\nshow_time()",
"2021-08-18 09:59:45 EDT\n"
],
[
"# Assume X and y were shuffled.\ntrain_size=PC_TRAINS+NC_TRAINS\nX_train=Xfrq[:train_size] \nX_test=Xfrq[train_size:]\ny_train=y[:train_size] \ny_test=y[train_size:]\nprint(\"Training set size=\",len(X_train),\"=\",len(y_train))\nprint(\"Reserved test set size=\",len(X_test),\"=\",len(y_test))\nXfrq=None\ny=None\nshow_time()",
"Training set size= 2000 = 2000\nReserved test set size= 133883 = 133883\n2021-08-18 09:59:45 EDT\n"
]
],
[
[
"## Load a trained neural network",
"_____no_output_____"
]
],
[
[
"show_time()\nmodel = load_model(BESTMODELPATH)\nprint(model.summary())",
"2021-08-18 09:59:45 EDT\nModel: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_4 (Dense) (None, 32) 2720 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 32) 0 \n_________________________________________________________________\ndense_5 (Dense) (None, 32) 1056 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 32) 0 \n_________________________________________________________________\ndense_6 (Dense) (None, 32) 1056 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 32) 0 \n_________________________________________________________________\ndense_7 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 4,865\nTrainable params: 4,865\nNon-trainable params: 0\n_________________________________________________________________\nNone\n"
]
],
[
[
"## Test the neural network",
"_____no_output_____"
]
],
[
[
"def show_test_AUC(model,X,y):\n ns_probs = [0 for _ in range(len(y))]\n bm_probs = model.predict(X)\n ns_auc = roc_auc_score(y, ns_probs)\n bm_auc = roc_auc_score(y, bm_probs)\n ns_fpr, ns_tpr, _ = roc_curve(y, ns_probs)\n bm_fpr, bm_tpr, _ = roc_curve(y, bm_probs)\n plt.plot(ns_fpr, ns_tpr, linestyle='--', label='Guess, auc=%.4f'%ns_auc)\n plt.plot(bm_fpr, bm_tpr, marker='.', label='Model, auc=%.4f'%bm_auc)\n plt.title('ROC')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.legend()\n plt.show()\n print(\"%s: %.2f%%\" %('AUC',bm_auc*100.0))\ndef show_test_accuracy(model,X,y):\n scores = model.evaluate(X, y, verbose=0)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n",
"_____no_output_____"
],
[
"print(\"Accuracy on test data.\")\nshow_time()\nshow_test_AUC(model,X_test,y_test)\nshow_test_accuracy(model,X_test,y_test)\nshow_time()",
"Accuracy on test data.\n2021-08-18 09:59:46 EDT\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb49d5cea83cc9880f6e9e571ee6118f8affdb9b | 6,516 | ipynb | Jupyter Notebook | notebooks/1-data-gathering.ipynb | mikhailsirenko/spacetimegeo | 9bb04cc516fb495ed853f8a91a330187b58890ef | [
"BSD-3-Clause"
] | 1 | 2019-12-19T15:49:22.000Z | 2019-12-19T15:49:22.000Z | notebooks/1-data-gathering.ipynb | mikhailsirenko/spacetimegeo | 9bb04cc516fb495ed853f8a91a330187b58890ef | [
"BSD-3-Clause"
] | null | null | null | notebooks/1-data-gathering.ipynb | mikhailsirenko/spacetimegeo | 9bb04cc516fb495ed853f8a91a330187b58890ef | [
"BSD-3-Clause"
] | 1 | 2020-02-11T16:52:44.000Z | 2020-02-11T16:52:44.000Z | 28.578947 | 305 | 0.587477 | [
[
[
"# Step 1: Data gathering ",
"_____no_output_____"
],
[
"__Step goal__: Download and store the datasets used in this study.\n\n__Step overview__:\n1. London demographic data;\n2. London shape files;\n3. Counts data;\n4. Metro stations and lines.",
"_____no_output_____"
],
[
"#### Introduction\n\nAll data is __open access__ and can be found on the official websites. Note, that the data sets can be updated by corresponding agencies; therefore, some discrepancies are possible: new variables will become available, or some data set will have fewer attributes.",
"_____no_output_____"
]
],
[
[
"import requests, zipfile, io\nfrom datetime import datetime\nimport os\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs",
"_____no_output_____"
]
],
[
[
"## 1. London demographic data",
"_____no_output_____"
]
],
[
[
"url = 'https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthelondonregionofengland%2fmid2017/sape20dt10amid2017coaunformattedsyoaestimateslondon.zip'\nr = requests.get(url)\nz = zipfile.ZipFile(io.BytesIO(r.content))\n\ndirectory = \"../data/raw/population/\"\nif not os.path.exists(directory):\n print(f'Succefully created new directory {directory}')\n os.makedirs(directory)\n \nz.extractall(path=directory)\nprint(f'Downloading date: {datetime.today().strftime(\"%d-%m-%Y %H:%M:%S\")}')",
"Downloading date: 09-04-2020 18:54:38\n"
]
],
[
[
"## 2. London shape files",
"_____no_output_____"
]
],
[
[
"url = 'https://data.london.gov.uk/download/statistical-gis-boundary-files-london/9ba8c833-6370-4b11-abdc-314aa020d5e0/statistical-gis-boundaries-london.zip'\nr = requests.get(url)\nz = zipfile.ZipFile(io.BytesIO(r.content))\n\ndirectory = \"../data/raw/geometry/london/\"\nif not os.path.exists(directory):\n print(f'Succefully created new directory {directory}')\n os.makedirs(directory)\n\nz.extractall(path=directory)\nprint(f'Downloading date: {datetime.today().strftime(\"%d-%m-%Y %H:%M:%S\")}')",
"Downloading date: 09-04-2020 18:54:43\n"
]
],
[
[
"## 3. Counts data",
"_____no_output_____"
]
],
[
[
"url = 'http://tfl.gov.uk/tfl/syndication/feeds/counts.zip?app_id=&app_key='\nr = requests.get(url)\nz = zipfile.ZipFile(io.BytesIO(r.content))\n\ndirectory = \"../data/raw/counts/\"\nif not os.path.exists(directory):\n print(f'Succefully created new directory {directory}')\n os.makedirs(directory)\n\nz.extractall(path=directory)\nprint(f'Downloading date: {datetime.today().strftime(\"%d-%m-%Y %H:%M:%S\")}')",
"Downloading date: 09-04-2020 18:54:43\n"
]
],
[
[
"## 4. Station locations ans lines",
"_____no_output_____"
]
],
[
[
"url = 'https://commons.wikimedia.org/wiki/London_Underground_geographic_maps/CSV'\nr = requests.get(url)\nsoup = bs(r.content, 'lxml')\npre = soup.select('pre')\n\nfile_names = ['stations.csv', 'routes.csv', 'lines.csv']\n\ndirectory = \"../data/raw/geometry/metro_stations/\"\nif not os.path.exists(directory):\n print(f'Succefully created new directory {directory}')\n os.makedirs(directory)\n\nfor i, p in enumerate(pre):\n df = pd.DataFrame([x.split(',') for x in p.text.split('\\n')])\n df.to_csv(directory + file_names[i])\nprint(f'Downloading date: {datetime.today().strftime(\"%d-%m-%Y %H:%M:%S\")}')",
"Downloading date: 09-04-2020 19:34:10\n"
]
],
[
[
"## References\n1. Office for National Statistics (2019). Census Output Area population estimates – London, England (supporting information). Retrieved from https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/censusoutputareaestimatesinthelondonregionofengland\n2. London Datastore (2019). Statistical GIS Boundary Files for London. Retrieved from https://data.london.gov.uk/dataset/statistical-gis-boundary-files-london\n3. Transport for London (2020). Transport for London API. Retrieved from https://api-portal.tfl.gov.uk/docs\n4. Wikimedia Commons (2020). London Underground geographic maps/CSV. Retrieved from https://commons.wikimedia.org/wiki/London_Underground_geographic_maps/CSV",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb49dc2d07015186ec013256c3404fea853a1550 | 4,314 | ipynb | Jupyter Notebook | sveske/sources/05_NumpyMatplotlib/trapezoid_rule.v3.ipynb | sandraASMD/unibl_radionica | 3b36e07fd3835ea9bfc63ed3a0fd25ef620a99d3 | [
"BSD-3-Clause"
] | 2 | 2019-09-18T19:21:44.000Z | 2019-09-19T00:00:25.000Z | sveske/sources/05_NumpyMatplotlib/trapezoid_rule.v3.ipynb | sandraASMD/unibl_radionica | 3b36e07fd3835ea9bfc63ed3a0fd25ef620a99d3 | [
"BSD-3-Clause"
] | null | null | null | sveske/sources/05_NumpyMatplotlib/trapezoid_rule.v3.ipynb | sandraASMD/unibl_radionica | 3b36e07fd3835ea9bfc63ed3a0fd25ef620a99d3 | [
"BSD-3-Clause"
] | 34 | 2019-09-18T14:39:38.000Z | 2019-09-20T06:45:07.000Z | 30.595745 | 160 | 0.516226 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
cb49e637e6646483c72e6fbaa299ff5dc3835d42 | 99,035 | ipynb | Jupyter Notebook | Chapter01/.ipynb_checkpoints/game_of_thrones_eda_plotly-checkpoint.ipynb | e93fem/Hands-On-Transfer-Learning-with-Python | 57e38231380aa95d753f1c7f7a711b5107436038 | [
"MIT"
] | 64 | 2018-09-06T05:26:30.000Z | 2022-01-06T10:47:21.000Z | Chapter01/.ipynb_checkpoints/game_of_thrones_eda_plotly-checkpoint.ipynb | e93fem/Hands-On-Transfer-Learning-with-Python | 57e38231380aa95d753f1c7f7a711b5107436038 | [
"MIT"
] | 2 | 2019-10-23T07:19:25.000Z | 2020-05-19T07:00:31.000Z | Chapter01/.ipynb_checkpoints/game_of_thrones_eda_plotly-checkpoint.ipynb | e93fem/Hands-On-Transfer-Learning-with-Python | 57e38231380aa95d753f1c7f7a711b5107436038 | [
"MIT"
] | 59 | 2018-09-19T22:49:25.000Z | 2021-11-25T09:02:16.000Z | 45.139015 | 2,899 | 0.465442 | [
[
[
"<h1 align=\"center\">Exploratory Analysis : Game of Thrones</h1> \n\n\nOne of the most popular television series of all time, Game of Thrones is a fantasy drama set in fictional continents of Westeros and Essos filled with multiple plots and a huge number of characters all battling for the Iron Throne! It is an adaptation of _Song of Ice and Fire_ novel series by **George R. R. Martin**.\n\nBeing a popular series, it has caught the attention of many, and Data Scientists aren't to be excluded. This notebook presents **Exploratory Data Analysis (EDA)** on the _Kaggle_ dataset enhanced by _Myles O'Neill_ (more details: [click here](https://www.kaggle.com/mylesoneill/game-of-thrones)). This dataset is based on a combination of multiple datasets collected and contributed by multiple people. We utilize the ```battles.csv``` in this notebook. The original battles data was presented by _Chris Albon_, more details are on [github](https://github.com/chrisalbon/war_of_the_five_kings_dataset)\n\n---\nThe image was taken from Game of Thrones, or from websites created and owned by HBO, the copyright of which is held by HBO. All trademarks and registered trademarks present in the image are proprietary to HBO, the inclusion of which implies no affiliation with the Game of Thrones. The use of such images is believed to fall under the fair dealing clause of copyright law.",
"_____no_output_____"
],
[
"## Import required packages",
"_____no_output_____"
]
],
[
[
"import cufflinks as cf\n\nimport pandas as pd\nfrom collections import Counter\n\n# pandas display data frames as tables\nfrom IPython.display import display, HTML",
"IOPub data rate exceeded.\nThe notebook server will temporarily stop sending output\nto the client in order to avoid crashing it.\nTo change this limit, set the config variable\n`--NotebookApp.iopub_data_rate_limit`.\n"
]
],
[
[
"### Set Configurations",
"_____no_output_____"
]
],
[
[
"cf.set_config_file(theme='white')",
"_____no_output_____"
],
[
"from plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)",
"_____no_output_____"
]
],
[
[
"## Load Dataset\n\nIn this step we load the ```battles.csv``` for analysis",
"_____no_output_____"
]
],
[
[
"# load dataset using cufflinks wrapper for later usage with plot.ly plots\nbattles_df = cf.pd.read_csv('battles.csv')",
"_____no_output_____"
],
[
"# Display sample rows\ndisplay(battles_df.head())",
"_____no_output_____"
]
],
[
[
"## Explore raw properties",
"_____no_output_____"
]
],
[
[
"print(\"Number of attributes available in the dataset = {}\".format(battles_df.shape[1]))",
"Number of attributes available in the dataset = 25\n"
],
[
"# View available columns and their data types\nbattles_df.dtypes",
"_____no_output_____"
]
],
[
[
"<h3 align=\"center\">Battles for the Iron Throne</h3> \n",
"_____no_output_____"
]
],
[
[
"# Analyze properties of numerical columns\nbattles_df.describe()",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Number of Battles Fought\nThis data is till **season 5** only",
"_____no_output_____"
]
],
[
[
"print(\"Number of battles fought={}\".format(battles_df.shape[0]))",
"Number of battles fought=38\n"
]
],
[
[
"## Battle Distribution Across Years\nThe plot below shows that maximum bloodshed happened in the year 299 with a total of 20 battles fought!",
"_____no_output_____"
]
],
[
[
"battles_df.year.value_counts().iplot(kind='barh',\n xTitle='Number of Battles',\n yTitle='Year',\n title='Battle Distribution over Years',\n showline=True)",
"_____no_output_____"
]
],
[
[
"## Which Regions saw most Battles?\n<img src=\"https://racefortheironthrone.files.wordpress.com/2016/11/riverlands-political-map.jpg?w=580&h=781\" alt=\"RiverLands\" style=\"width: 200px;\" align=\"left\"/> **Riverland**s seem to be the favorite battle ground followed by the famous **The North**. Interestingly, till season 5, there was only 1 battle beyond the wall. Spoiler Alert: Winter is Coming!",
"_____no_output_____"
]
],
[
[
"battles_df.region.value_counts().iplot(kind='bar',\n xTitle='Regions',\n yTitle='Number of Battles',\n title='Battles by Regions',\n showline=True)",
"_____no_output_____"
]
],
[
[
"### Death or Capture of Main Characters by Region",
"_____no_output_____"
],
[
"No prizes for guessing that Riverlands have seen some of the main characters being killed or captured. Though _The Reach_ has seen 2 battles, none of the major characters seemed to have fallen there.",
"_____no_output_____"
]
],
[
[
"battles_df.groupby('region').agg({'major_death':'sum',\n 'major_capture':'sum'}).iplot(kind='bar')",
"_____no_output_____"
]
],
[
[
"## Who Attacked the most?\nThe Baratheon boys love attacking as they lead the pack with 38% while Rob Stark has been the attacker in close second with 27.8% of the battles.\n\n<img src=\"http://vignette3.wikia.nocookie.net/gameofthrones/images/4/4c/JoffreyBaratheon-Profile.PNG/revision/latest?cb=20160626094917\" alt=\"joffrey\" style=\"width: 200px;\" align=\"left\"/> <img src=\"https://meninblazers.com/.image/t_share/MTMwMDE5NTU4NTI5NDk1MDEw/tumblr_mkzsdafejy1r2xls3o1_400.png\" alt=\"robb\" style=\"width: 200px; height: 200px\" align=\"right\"/>",
"_____no_output_____"
]
],
[
[
"king_attacked = battles_df.attacker_king.value_counts().reset_index()\nking_attacked.rename(columns={'index':'king','attacker_king':'battle_count'},inplace=True)\nking_attacked.iplot(kind='pie',labels='king',values='battle_count')",
"_____no_output_____"
]
],
[
[
"## Who Defended the most?\nRob Stark and Baratheon boys are again on the top of the pack. Looks like they have been on either sides of the war lot many times.",
"_____no_output_____"
]
],
[
[
"king_defended = battles_df.defender_king.value_counts().reset_index()\nking_defended.rename(columns={'index':'king','defender_king':'battle_count'},inplace=True)\nking_defended.iplot(kind='pie',labels='king',values='battle_count')",
"_____no_output_____"
]
],
[
[
"## Battle Style Distribution\nPlenty of battles all across, yet the men of Westeros and Essos are men of honor. \nThis is visible in the distribution which shows **pitched battle** as the most common style of battle.",
"_____no_output_____"
]
],
[
[
"battles_df.battle_type.value_counts().iplot(kind='barh')",
"_____no_output_____"
]
],
[
[
"## Attack or Defend?\nDefending your place in Westeros isn't easy, this is clearly visible from the fact that 32 out of 37 battles were won by attackers",
"_____no_output_____"
]
],
[
[
"battles_df.attacker_outcome.value_counts().iplot(kind='barh')",
"_____no_output_____"
]
],
[
[
"## Winners\nWho remembers losers? (except if you love the Starks)\nThe following plot helps us understand who won how many battles and how, by attacking or defending.",
"_____no_output_____"
]
],
[
[
"attack_winners = battles_df[battles_df.attacker_outcome=='win']['attacker_king'].value_counts().reset_index()\nattack_winners.rename(columns={'index':'king','attacker_king':'attack_wins'},inplace=True)\n\ndefend_winners = battles_df[battles_df.attacker_outcome=='loss']['defender_king'].value_counts().reset_index()\ndefend_winners.rename(columns={'index':'king','defender_king':'defend_wins'},inplace=True)\n\nwinner_df = pd.merge(attack_winners,defend_winners,how='outer',on='king')\nwinner_df.fillna(0,inplace=True)\nwinner_df['total_wins'] = winner_df.apply(lambda row: row['attack_wins']+row['defend_wins'],axis=1)\nwinner_df[['king','attack_wins','defend_wins']].set_index('king').iplot(kind='bar',barmode='stack',\n xTitle='King',\n yTitle='Number of Wins',\n title='Wins per King',\n showline=True)",
"_____no_output_____"
]
],
[
[
"## Battle Commanders\nA battle requires as much brains as muscle power. \nThe following is a distribution of the number of commanders involved on attacking and defending sides.",
"_____no_output_____"
]
],
[
[
"battles_df['attack_commander_count'] = battles_df.dropna(subset=['attacker_commander']).apply(lambda row: len(row['attacker_commander'].split()),axis=1)\nbattles_df['defend_commander_count'] = battles_df.dropna(subset=['defender_commander']).apply(lambda row: len(row['defender_commander'].split()),axis=1)",
"_____no_output_____"
],
[
"battles_df[['attack_commander_count',\n 'defend_commander_count']].iplot(kind='box',boxpoints='suspectedoutliers')",
"_____no_output_____"
]
],
[
[
"## How many houses fought in a battle?\nWere the battles evenly balanced? The plots tell the whole story.\n\n<img src=\"https://c1.staticflickr.com/4/3893/14834104277_54d309b4ca_b.jpg\" style=\"height: 200px;\"/>",
"_____no_output_____"
]
],
[
[
"battles_df['attacker_house_count'] = (4 - battles_df[['attacker_1', \n 'attacker_2', \n 'attacker_3', \n 'attacker_4']].isnull().sum(axis = 1))\n\nbattles_df['defender_house_count'] = (4 - battles_df[['defender_1',\n 'defender_2', \n 'defender_3', \n 'defender_4']].isnull().sum(axis = 1))\n\nbattles_df['total_involved_count'] = battles_df.apply(lambda row: row['attacker_house_count']+row['defender_house_count'],\n axis=1)\nbattles_df['bubble_text'] = battles_df.apply(lambda row: '{} had {} house(s) attacking {} house(s) '.format(row['name'],\n row['attacker_house_count'],\n row['defender_house_count']),\n axis=1)",
"_____no_output_____"
]
],
[
[
"## Unbalanced Battles\nMost battles so far have seen more houses forming alliances while attacking. \nThere are only a few friends when you are under attack!",
"_____no_output_____"
]
],
[
[
"house_balance = battles_df[battles_df.attacker_house_count != battles_df.defender_house_count][['name',\n 'attacker_house_count',\n 'defender_house_count']].set_index('name')\nhouse_balance.iplot(kind='bar',tickangle=-25)",
"_____no_output_____"
]
],
[
[
"## Battles and The size of Armies\nAttackers don't take any chances, they come in huge numbers, keep your eyes open",
"_____no_output_____"
]
],
[
[
"battles_df.dropna(subset=['total_involved_count',\n 'attacker_size',\n 'defender_size',\n 'bubble_text']).iplot(kind='bubble', \n x='defender_size',\n y='attacker_size',\n size='total_involved_count',\n text='bubble_text',\n #color='red',\n xTitle='Defender Size', \n yTitle='Attacker Size')",
"_____no_output_____"
]
],
[
[
"## Archenemies?\nThe Stark-Baratheon friendship has taken a complete U-turn with a total of 19 battles and counting. Indeed there is no one to be trusted in this land.",
"_____no_output_____"
]
],
[
[
"temp_df = battles_df.dropna(subset = [\"attacker_king\", \n \"defender_king\"])[[\n \"attacker_king\", \n \"defender_king\"\n ]]\n\narchenemy_df = pd.DataFrame(list(Counter([tuple(set(king_pair)) \n for king_pair in temp_df.values \n if len(set(king_pair))>1]).items()),\n columns=['king_pair','battle_count'])\n\narchenemy_df['versus_text'] = archenemy_df.apply(lambda row:\n '{} Vs {}'.format(\n row['king_pair'][0], \n row['king_pair'][1]),\n axis=1)\narchenemy_df.sort_values('battle_count',\n inplace=True,\n ascending=False)",
"_____no_output_____"
],
[
"archenemy_df[['versus_text',\n 'battle_count']].set_index('versus_text').iplot(\n kind='bar')",
"_____no_output_____"
]
],
[
[
"---\nNote: A lot more exploration is possible with the remaining attributes and their different combinations. This is just tip of the iceberg",
"_____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"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb49ef18a6845e4f3933150ccadfbaaed2f2c1e9 | 26,892 | ipynb | Jupyter Notebook | c2_improving_deep_neural_networks/week_5/gradient_checking/Gradient Checking v1.ipynb | jorgelmadrid/deep_learning_specialization | 08e41326a03580b3cd906fa8e20f26bc1f63b494 | [
"MIT"
] | null | null | null | c2_improving_deep_neural_networks/week_5/gradient_checking/Gradient Checking v1.ipynb | jorgelmadrid/deep_learning_specialization | 08e41326a03580b3cd906fa8e20f26bc1f63b494 | [
"MIT"
] | null | null | null | c2_improving_deep_neural_networks/week_5/gradient_checking/Gradient Checking v1.ipynb | jorgelmadrid/deep_learning_specialization | 08e41326a03580b3cd906fa8e20f26bc1f63b494 | [
"MIT"
] | null | null | null | 41.757764 | 399 | 0.550238 | [
[
[
"# Gradient Checking\n\nWelcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. \n\nYou are part of a team working to make mobile payments available globally, and are asked to build a deep learning model to detect fraud--whenever someone makes a payment, you want to see if the payment might be fraudulent, such as if the user's account has been taken over by a hacker. \n\nBut backpropagation is quite challenging to implement, and sometimes has bugs. Because this is a mission-critical application, your company's CEO wants to be really certain that your implementation of backpropagation is correct. Your CEO says, \"Give me a proof that your backpropagation is actually working!\" To give this reassurance, you are going to use \"gradient checking\".\n\nLet's do it!",
"_____no_output_____"
]
],
[
[
"# Packages\nimport numpy as np\nfrom testCases import *\nfrom gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector",
"_____no_output_____"
]
],
[
[
"## 1) How does gradient checking work?\n\nBackpropagation computes the gradients $\\frac{\\partial J}{\\partial \\theta}$, where $\\theta$ denotes the parameters of the model. $J$ is computed using forward propagation and your loss function.\n\nBecause forward propagation is relatively easy to implement, you're confident you got that right, and so you're almost 100% sure that you're computing the cost $J$ correctly. Thus, you can use your code for computing $J$ to verify the code for computing $\\frac{\\partial J}{\\partial \\theta}$. \n\nLet's look back at the definition of a derivative (or gradient):\n$$ \\frac{\\partial J}{\\partial \\theta} = \\lim_{\\varepsilon \\to 0} \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon} \\tag{1}$$\n\nIf you're not familiar with the \"$\\displaystyle \\lim_{\\varepsilon \\to 0}$\" notation, it's just a way of saying \"when $\\varepsilon$ is really really small.\"\n\nWe know the following:\n\n- $\\frac{\\partial J}{\\partial \\theta}$ is what you want to make sure you're computing correctly. \n- You can compute $J(\\theta + \\varepsilon)$ and $J(\\theta - \\varepsilon)$ (in the case that $\\theta$ is a real number), since you're confident your implementation for $J$ is correct. \n\nLets use equation (1) and a small value for $\\varepsilon$ to convince your CEO that your code for computing $\\frac{\\partial J}{\\partial \\theta}$ is correct!",
"_____no_output_____"
],
[
"## 2) 1-dimensional gradient checking\n\nConsider a 1D linear function $J(\\theta) = \\theta x$. The model contains only a single real-valued parameter $\\theta$, and takes $x$ as input.\n\nYou will implement code to compute $J(.)$ and its derivative $\\frac{\\partial J}{\\partial \\theta}$. You will then use gradient checking to make sure your derivative computation for $J$ is correct. \n\n<img src=\"images/1Dgrad_kiank.png\" style=\"width:600px;height:250px;\">\n<caption><center> <u> **Figure 1** </u>: **1D linear model**<br> </center></caption>\n\nThe diagram above shows the key computation steps: First start with $x$, then evaluate the function $J(x)$ (\"forward propagation\"). Then compute the derivative $\\frac{\\partial J}{\\partial \\theta}$ (\"backward propagation\"). \n\n**Exercise**: implement \"forward propagation\" and \"backward propagation\" for this simple function. I.e., compute both $J(.)$ (\"forward propagation\") and its derivative with respect to $\\theta$ (\"backward propagation\"), in two separate functions. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: forward_propagation\n\ndef forward_propagation(x, theta):\n \"\"\"\n Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)\n \n Arguments:\n x -- a real-valued input\n theta -- our parameter, a real number as well\n \n Returns:\n J -- the value of function J, computed using the formula J(theta) = theta * x\n \"\"\"\n \n ### START CODE HERE ### (approx. 1 line)\n J = theta * x \n ### END CODE HERE ###\n \n return J",
"_____no_output_____"
],
[
"x, theta = 2, 4\nJ = forward_propagation(x, theta)\nprint (\"J = \" + str(J))",
"J = 8\n"
]
],
[
[
"**Expected Output**:\n\n<table style=>\n <tr>\n <td> ** J ** </td>\n <td> 8</td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"**Exercise**: Now, implement the backward propagation step (derivative computation) of Figure 1. That is, compute the derivative of $J(\\theta) = \\theta x$ with respect to $\\theta$. To save you from doing the calculus, you should get $dtheta = \\frac { \\partial J }{ \\partial \\theta} = x$.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: backward_propagation\n\ndef backward_propagation(x, theta):\n \"\"\"\n Computes the derivative of J with respect to theta (see Figure 1).\n \n Arguments:\n x -- a real-valued input\n theta -- our parameter, a real number as well\n \n Returns:\n dtheta -- the gradient of the cost with respect to theta\n \"\"\"\n \n ### START CODE HERE ### (approx. 1 line)\n dtheta = x\n ### END CODE HERE ###\n \n return dtheta",
"_____no_output_____"
],
[
"x, theta = 2, 4\ndtheta = backward_propagation(x, theta)\nprint (\"dtheta = \" + str(dtheta))",
"dtheta = 2\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td> ** dtheta ** </td>\n <td> 2 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"**Exercise**: To show that the `backward_propagation()` function is correctly computing the gradient $\\frac{\\partial J}{\\partial \\theta}$, let's implement gradient checking.\n\n**Instructions**:\n- First compute \"gradapprox\" using the formula above (1) and a small value of $\\varepsilon$. Here are the Steps to follow:\n 1. $\\theta^{+} = \\theta + \\varepsilon$\n 2. $\\theta^{-} = \\theta - \\varepsilon$\n 3. $J^{+} = J(\\theta^{+})$\n 4. $J^{-} = J(\\theta^{-})$\n 5. $gradapprox = \\frac{J^{+} - J^{-}}{2 \\varepsilon}$\n- Then compute the gradient using backward propagation, and store the result in a variable \"grad\"\n- Finally, compute the relative difference between \"gradapprox\" and the \"grad\" using the following formula:\n$$ difference = \\frac {\\mid\\mid grad - gradapprox \\mid\\mid_2}{\\mid\\mid grad \\mid\\mid_2 + \\mid\\mid gradapprox \\mid\\mid_2} \\tag{2}$$\nYou will need 3 Steps to compute this formula:\n - 1'. compute the numerator using np.linalg.norm(...)\n - 2'. compute the denominator. You will need to call np.linalg.norm(...) twice.\n - 3'. divide them.\n- If this difference is small (say less than $10^{-7}$), you can be quite confident that you have computed your gradient correctly. Otherwise, there may be a mistake in the gradient computation. \n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: gradient_check\n\ndef gradient_check(x, theta, epsilon = 1e-7):\n \"\"\"\n Implement the backward propagation presented in Figure 1.\n \n Arguments:\n x -- a real-valued input\n theta -- our parameter, a real number as well\n epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n \n Returns:\n difference -- difference (2) between the approximated gradient and the backward propagation gradient\n \"\"\"\n \n # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.\n ### START CODE HERE ### (approx. 5 lines)\n thetaplus = theta + epsilon # Step 1\n thetaminus = theta - epsilon # Step 2\n J_plus = forward_propagation(x, thetaplus) # Step 3\n J_minus = forward_propagation(x, thetaminus) # Step 4\n gradapprox = (J_plus - J_minus) / (2*epsilon) # Step 5\n ### END CODE HERE ###\n \n # Check if gradapprox is close enough to the output of backward_propagation()\n ### START CODE HERE ### (approx. 1 line)\n grad = backward_propagation(x, theta)\n ### END CODE HERE ###\n \n ### START CODE HERE ### (approx. 1 line)\n numerator = np.linalg.norm(grad - gradapprox) # Step 1'\n denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'\n difference = numerator / denominator # Step 3'\n ### END CODE HERE ###\n \n if difference < 1e-7:\n print (\"The gradient is correct!\")\n else:\n print (\"The gradient is wrong!\")\n \n return difference",
"_____no_output_____"
],
[
"x, theta = 2, 4\ndifference = gradient_check(x, theta)\nprint(\"difference = \" + str(difference))",
"The gradient is correct!\ndifference = 2.919335883291695e-10\n"
]
],
[
[
"**Expected Output**:\nThe gradient is correct!\n<table>\n <tr>\n <td> ** difference ** </td>\n <td> 2.9193358103083e-10 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"Congrats, the difference is smaller than the $10^{-7}$ threshold. So you can have high confidence that you've correctly computed the gradient in `backward_propagation()`. \n\nNow, in the more general case, your cost function $J$ has more than a single 1D input. When you are training a neural network, $\\theta$ actually consists of multiple matrices $W^{[l]}$ and biases $b^{[l]}$! It is important to know how to do a gradient check with higher-dimensional inputs. Let's do it!",
"_____no_output_____"
],
[
"## 3) N-dimensional gradient checking",
"_____no_output_____"
],
[
"The following figure describes the forward and backward propagation of your fraud detection model.\n\n<img src=\"images/NDgrad_kiank.png\" style=\"width:600px;height:400px;\">\n<caption><center> <u> **Figure 2** </u>: **deep neural network**<br>*LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*</center></caption>\n\nLet's look at your implementations for forward propagation and backward propagation. ",
"_____no_output_____"
]
],
[
[
"def forward_propagation_n(X, Y, parameters):\n \"\"\"\n Implements the forward propagation (and computes the cost) presented in Figure 3.\n \n Arguments:\n X -- training set for m examples\n Y -- labels for m examples \n parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n W1 -- weight matrix of shape (5, 4)\n b1 -- bias vector of shape (5, 1)\n W2 -- weight matrix of shape (3, 5)\n b2 -- bias vector of shape (3, 1)\n W3 -- weight matrix of shape (1, 3)\n b3 -- bias vector of shape (1, 1)\n \n Returns:\n cost -- the cost function (logistic cost for one example)\n \"\"\"\n \n # retrieve parameters\n m = X.shape[1]\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n W3 = parameters[\"W3\"]\n b3 = parameters[\"b3\"]\n\n # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID\n Z1 = np.dot(W1, X) + b1\n A1 = relu(Z1)\n Z2 = np.dot(W2, A1) + b2\n A2 = relu(Z2)\n Z3 = np.dot(W3, A2) + b3\n A3 = sigmoid(Z3)\n\n # Cost\n logprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)\n cost = 1./m * np.sum(logprobs)\n \n cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)\n \n return cost, cache",
"_____no_output_____"
]
],
[
[
"Now, run backward propagation.",
"_____no_output_____"
]
],
[
[
"def backward_propagation_n(X, Y, cache):\n \"\"\"\n Implement the backward propagation presented in figure 2.\n \n Arguments:\n X -- input datapoint, of shape (input size, 1)\n Y -- true \"label\"\n cache -- cache output from forward_propagation_n()\n \n Returns:\n gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables.\n \"\"\"\n \n m = X.shape[1]\n (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache\n \n dZ3 = A3 - Y\n dW3 = 1./m * np.dot(dZ3, A2.T)\n db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)\n \n dA2 = np.dot(W3.T, dZ3)\n dZ2 = np.multiply(dA2, np.int64(A2 > 0))\n dW2 = 1./m * np.dot(dZ2, A1.T)\n db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)\n \n dA1 = np.dot(W2.T, dZ2)\n dZ1 = np.multiply(dA1, np.int64(A1 > 0))\n dW1 = 1./m * np.dot(dZ1, X.T)\n db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)\n \n gradients = {\"dZ3\": dZ3, \"dW3\": dW3, \"db3\": db3,\n \"dA2\": dA2, \"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2,\n \"dA1\": dA1, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1}\n \n return gradients",
"_____no_output_____"
]
],
[
[
"You obtained some results on the fraud detection test set but you are not 100% sure of your model. Nobody's perfect! Let's implement gradient checking to verify if your gradients are correct.",
"_____no_output_____"
],
[
"**How does gradient checking work?**.\n\nAs in 1) and 2), you want to compare \"gradapprox\" to the gradient computed by backpropagation. The formula is still:\n\n$$ \\frac{\\partial J}{\\partial \\theta} = \\lim_{\\varepsilon \\to 0} \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon} \\tag{1}$$\n\nHowever, $\\theta$ is not a scalar anymore. It is a dictionary called \"parameters\". We implemented a function \"`dictionary_to_vector()`\" for you. It converts the \"parameters\" dictionary into a vector called \"values\", obtained by reshaping all parameters (W1, b1, W2, b2, W3, b3) into vectors and concatenating them.\n\nThe inverse function is \"`vector_to_dictionary`\" which outputs back the \"parameters\" dictionary.\n\n<img src=\"images/dictionary_to_vector.png\" style=\"width:600px;height:400px;\">\n<caption><center> <u> **Figure 2** </u>: **dictionary_to_vector() and vector_to_dictionary()**<br> You will need these functions in gradient_check_n()</center></caption>\n\nWe have also converted the \"gradients\" dictionary into a vector \"grad\" using gradients_to_vector(). You don't need to worry about that.\n\n**Exercise**: Implement gradient_check_n().\n\n**Instructions**: Here is pseudo-code that will help you implement the gradient check.\n\nFor each i in num_parameters:\n- To compute `J_plus[i]`:\n 1. Set $\\theta^{+}$ to `np.copy(parameters_values)`\n 2. Set $\\theta^{+}_i$ to $\\theta^{+}_i + \\varepsilon$\n 3. Calculate $J^{+}_i$ using to `forward_propagation_n(x, y, vector_to_dictionary(`$\\theta^{+}$ `))`. \n- To compute `J_minus[i]`: do the same thing with $\\theta^{-}$\n- Compute $gradapprox[i] = \\frac{J^{+}_i - J^{-}_i}{2 \\varepsilon}$\n\nThus, you get a vector gradapprox, where gradapprox[i] is an approximation of the gradient with respect to `parameter_values[i]`. You can now compare this gradapprox vector to the gradients vector from backpropagation. Just like for the 1D case (Steps 1', 2', 3'), compute: \n$$ difference = \\frac {\\| grad - gradapprox \\|_2}{\\| grad \\|_2 + \\| gradapprox \\|_2 } \\tag{3}$$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: gradient_check_n\n\ndef gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):\n \"\"\"\n Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n\n \n Arguments:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. \n x -- input datapoint, of shape (input size, 1)\n y -- true \"label\"\n epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n \n Returns:\n difference -- difference (2) between the approximated gradient and the backward propagation gradient\n \"\"\"\n \n # Set-up variables\n parameters_values, _ = dictionary_to_vector(parameters)\n grad = gradients_to_vector(gradients)\n num_parameters = parameters_values.shape[0]\n J_plus = np.zeros((num_parameters, 1))\n J_minus = np.zeros((num_parameters, 1))\n gradapprox = np.zeros((num_parameters, 1))\n \n # Compute gradapprox\n for i in range(num_parameters):\n \n # Compute J_plus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_plus[i]\".\n # \"_\" is used because the function you have to outputs two parameters but we only care about the first one\n ### START CODE HERE ### (approx. 3 lines)\n thetaplus = np.copy(parameters_values) # Step 1\n thetaplus[i][0] += epsilon # Step 2\n J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Step 3\n ### END CODE HERE ###\n \n # Compute J_minus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_minus[i]\".\n ### START CODE HERE ### (approx. 3 lines)\n thetaminus = np.copy(parameters_values) # Step 1\n thetaminus[i][0] -= epsilon # Step 2 \n J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Step 3\n ### END CODE HERE ###\n \n # Compute gradapprox[i]\n ### START CODE HERE ### (approx. 1 line)\n gradapprox[i] = (J_plus[i] - J_minus[i]) / (2*epsilon)\n ### END CODE HERE ###\n \n # Compare gradapprox to backward propagation gradients by computing difference.\n ### START CODE HERE ### (approx. 1 line)\n numerator = np.linalg.norm(grad - gradapprox) # Step 1'\n denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'\n difference = numerator / denominator # Step 3'\n ### END CODE HERE ###\n\n if difference > 2e-7:\n print (\"\\033[93m\" + \"There is a mistake in the backward propagation! difference = \" + str(difference) + \"\\033[0m\")\n else:\n print (\"\\033[92m\" + \"Your backward propagation works perfectly fine! difference = \" + str(difference) + \"\\033[0m\")\n \n return difference",
"_____no_output_____"
],
[
"X, Y, parameters = gradient_check_n_test_case()\n\ncost, cache = forward_propagation_n(X, Y, parameters)\ngradients = backward_propagation_n(X, Y, cache)\ndifference = gradient_check_n(parameters, gradients, X, Y)",
"\u001b[92mYour backward propagation works perfectly fine! difference = 1.1885552035482147e-07\u001b[0m\n"
]
],
[
[
"**Expected output**:\n\n<table>\n <tr>\n <td> ** There is a mistake in the backward propagation!** </td>\n <td> difference = 0.285093156781 </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"It seems that there were errors in the `backward_propagation_n` code we gave you! Good that you've implemented the gradient check. Go back to `backward_propagation` and try to find/correct the errors *(Hint: check dW2 and db1)*. Rerun the gradient check when you think you've fixed it. Remember you'll need to re-execute the cell defining `backward_propagation_n()` if you modify the code. \n\nCan you get gradient check to declare your derivative computation correct? Even though this part of the assignment isn't graded, we strongly urge you to try to find the bug and re-run gradient check until you're convinced backprop is now correctly implemented. \n\n**Note** \n- Gradient Checking is slow! Approximating the gradient with $\\frac{\\partial J}{\\partial \\theta} \\approx \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon}$ is computationally costly. For this reason, we don't run gradient checking at every iteration during training. Just a few times to check if the gradient is correct. \n- Gradient Checking, at least as we've presented it, doesn't work with dropout. You would usually run the gradient check algorithm without dropout to make sure your backprop is correct, then add dropout. \n\nCongrats, you can be confident that your deep learning model for fraud detection is working correctly! You can even use this to convince your CEO. :) \n\n<font color='blue'>\n**What you should remember from this notebook**:\n- Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation).\n- Gradient checking is slow, so we don't run it in every iteration of training. You would usually run it only to make sure your code is correct, then turn it off and use backprop for the actual learning process. ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cb4a39b34a752c75e7386b970dabac20537cad28 | 22,039 | ipynb | Jupyter Notebook | ADABOOSTClassifier.ipynb | mkmritunjay/machineLearning | 80f6963cba5d2a3471ba5d22054fd26bcdd02e03 | [
"MIT"
] | null | null | null | ADABOOSTClassifier.ipynb | mkmritunjay/machineLearning | 80f6963cba5d2a3471ba5d22054fd26bcdd02e03 | [
"MIT"
] | null | null | null | ADABOOSTClassifier.ipynb | mkmritunjay/machineLearning | 80f6963cba5d2a3471ba5d22054fd26bcdd02e03 | [
"MIT"
] | null | null | null | 30.356749 | 244 | 0.379237 | [
[
[
"<a href=\"https://colab.research.google.com/github/mkmritunjay/machineLearning/blob/master/ADABOOSTClassifier.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# ADABOOST (Adaptive Boosting)",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport statsmodels.formula.api as sm\nimport scipy.stats as stats\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = 10, 7.5\nplt.rcParams['axes.grid'] = True\nplt.gray()\n\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.linear_model import LogisticRegression\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom patsy import dmatrices\n\nimport sklearn.tree as dt\nimport sklearn.ensemble as en\n\nfrom sklearn import metrics\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz, export\nfrom sklearn.model_selection import GridSearchCV, cross_val_score\nfrom sklearn.ensemble import AdaBoostClassifier\n\nimport pydotplus as pdot\nfrom IPython.display import Image\n\nurl = 'https://raw.githubusercontent.com/mkmritunjay/machineLearning/master/HR_comma_sep.csv'",
"_____no_output_____"
],
[
"hr_df = pd.read_csv(url)",
"_____no_output_____"
],
[
"# now we need to create dummy variables for categorical variables(dtype=object)\nnumerical_features = ['satisfaction_level', 'last_evaluation', 'number_project',\n 'average_montly_hours', 'time_spend_company']\n\ncategorical_features = ['Work_accident','promotion_last_5years', 'department', 'salary']",
"_____no_output_____"
],
[
"categorical_features",
"_____no_output_____"
],
[
"numerical_features",
"_____no_output_____"
],
[
"# A utility function to create dummy variable\ndef create_dummies( df, colname ):\n col_dummies = pd.get_dummies(df[colname], prefix=colname)\n col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)\n df = pd.concat([df, col_dummies], axis=1)\n df.drop( colname, axis = 1, inplace = True )\n return df",
"_____no_output_____"
],
[
"for c_feature in categorical_features:\n hr_df = create_dummies( hr_df, c_feature )\n\nhr_df.head()",
"_____no_output_____"
],
[
"#Splitting the data\n\nfeature_columns = hr_df.columns.difference( ['left'] )\nfeature_columns",
"_____no_output_____"
]
],
[
[
"### Train Test split",
"_____no_output_____"
]
],
[
[
"train_X, test_X, train_y, test_y = train_test_split( hr_df[feature_columns],\n hr_df['left'],\n test_size = 0.3,\n random_state = 42 )",
"_____no_output_____"
]
],
[
[
"### Building the model",
"_____no_output_____"
]
],
[
[
"# provide estimators and learning rate\npargrid_ada = {'n_estimators': [100, 200, 400, 600, 800],\n 'learning_rate': [10 ** x for x in range(-3, 3)]}",
"_____no_output_____"
],
[
"gscv_ada = GridSearchCV(estimator=AdaBoostClassifier(),\n param_grid=pargrid_ada,\n cv=5,\n verbose=True, n_jobs=-1)",
"_____no_output_____"
],
[
"gscv_ada.fit(train_X, train_y)",
"Fitting 5 folds for each of 30 candidates, totalling 150 fits\n"
],
[
"gscv_ada.best_params_",
"_____no_output_____"
],
[
"gscv_ada.best_score_",
"_____no_output_____"
]
],
[
[
"### Building final model",
"_____no_output_____"
]
],
[
[
"ad = AdaBoostClassifier(learning_rate=0.1, n_estimators=800)\nad.fit(train_X, train_y)",
"_____no_output_____"
],
[
"clf_ada = gscv_ada.best_estimator_",
"_____no_output_____"
],
[
"print (pd.Series(cross_val_score(clf_ada, \n train_X, train_y, cv=10)).describe()[['min', 'mean', 'max']])",
"min 0.954286\nmean 0.961901\nmax 0.971429\ndtype: float64\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb4a478db76f143f6184f2b1d025b39cfd5c4a41 | 4,949 | ipynb | Jupyter Notebook | FEA/youtube-tutorials/digvijay-patankar/.ipynb_checkpoints/harmonic-analysis-graph-checkpoint.ipynb | adriaan90/66daysofcae | d30dcc6e03c61e2a9854db7cb3c8505215b78e44 | [
"MIT"
] | 1 | 2021-09-29T10:38:16.000Z | 2021-09-29T10:38:16.000Z | FEA/youtube-tutorials/digvijay-patankar/.ipynb_checkpoints/harmonic-analysis-graph-checkpoint.ipynb | adriaan90/66daysofcae | d30dcc6e03c61e2a9854db7cb3c8505215b78e44 | [
"MIT"
] | null | null | null | FEA/youtube-tutorials/digvijay-patankar/.ipynb_checkpoints/harmonic-analysis-graph-checkpoint.ipynb | adriaan90/66daysofcae | d30dcc6e03c61e2a9854db7cb3c8505215b78e44 | [
"MIT"
] | null | null | null | 47.586538 | 1,155 | 0.615882 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_table(\"FRF2.dat\", delimiter=' ')",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2003 entries, 0 to 2002\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 freq 2003 non-null object\n 1 amplitude 2002 non-null object\ndtypes: object(2)\nmemory usage: 31.4+ KB\n"
],
[
"df.plot(df.freq, df.amplitude)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
cb4a494869b6bf04408c43def1112a205cf07d17 | 323,900 | ipynb | Jupyter Notebook | hypersolver/image_classification/hypereuler_mnist.ipynb | DiffEqML/diffeqml_research | 7f4379f1fc703a5b19b9e248bbbeaf188511bdb9 | [
"Apache-2.0"
] | 49 | 2020-08-06T12:27:05.000Z | 2022-03-16T12:32:06.000Z | hypersolver/image_classification/hypereuler_mnist.ipynb | DiffEqML/diffeqml_research | 7f4379f1fc703a5b19b9e248bbbeaf188511bdb9 | [
"Apache-2.0"
] | null | null | null | hypersolver/image_classification/hypereuler_mnist.ipynb | DiffEqML/diffeqml_research | 7f4379f1fc703a5b19b9e248bbbeaf188511bdb9 | [
"Apache-2.0"
] | 6 | 2020-12-07T06:10:40.000Z | 2022-03-08T09:23:22.000Z | 475.624082 | 146,160 | 0.932245 | [
[
[
"# HyperEuler on MNIST-trained Neural ODEs",
"_____no_output_____"
]
],
[
[
"import sys ; sys.path.append('..')\nfrom torchdyn.models import *; from torchdyn import *\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.metrics.functional import accuracy\nfrom tqdm import tqdm_notebook as tqdm\nfrom src.custom_fixed_explicit import ButcherTableau, GenericExplicitButcher\nfrom src.hypersolver import *",
"_____no_output_____"
],
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")",
"_____no_output_____"
],
[
"# smaller batch_size; only needed for visualization. The classification model\n# will not be retrained\nbatch_size=16\nsize=28\npath_to_data='../../data/mnist_data'\n\nall_transforms = transforms.Compose([\n transforms.RandomRotation(20),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)),\n\n])\n\ntest_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)),\n])\n\ntrain_data = datasets.MNIST(path_to_data, train=True, download=True,\n transform=all_transforms)\ntest_data = datasets.MNIST(path_to_data, train=False,\n transform=test_transforms)\n\ntrainloader = DataLoader(train_data, batch_size=batch_size, shuffle=True)\ntestloader = DataLoader(test_data, batch_size=batch_size, shuffle=True)",
"_____no_output_____"
]
],
[
[
"## Loading the pretrained Neural ODE ",
"_____no_output_____"
]
],
[
[
"func = nn.Sequential(nn.Conv2d(32, 46, 3, padding=1),\n nn.Softplus(), \n nn.Conv2d(46, 46, 3, padding=1),\n nn.Softplus(), \n nn.Conv2d(46, 32, 3, padding=1)\n ).to(device)\nndes = []\nfor i in range(1):\n ndes.append(NeuralDE(func, \n solver='dopri5',\n sensitivity='adjoint',\n atol=1e-4,\n rtol=1e-4,\n s_span=torch.linspace(0, 1, 2)).to(device))\n #ndes.append(nn.Conv2d(32, 32, 3, padding=1)))\n\nmodel = nn.Sequential(nn.BatchNorm2d(1),\n Augmenter(augment_func=nn.Conv2d(1, 31, 3, padding=1)),\n *ndes,\n nn.AvgPool2d(28),\n #nn.Conv2d(32, 1, 3, padding=1),\n nn.Flatten(), \n nn.Linear(32, 10)).to(device)\n",
"_____no_output_____"
],
[
"state_dict = torch.load('../pretrained_models/nde_mnist')\n\n# remove state_dict keys for `torchdyn`'s Adjoint nn.Module (not used here)\ncopy_dict = state_dict.copy()\nfor key in copy_dict.keys(): \n if 'adjoint' in key: state_dict.pop(key)\n \nmodel.load_state_dict(state_dict)",
"_____no_output_____"
]
],
[
[
"### Visualizing pretrained flows",
"_____no_output_____"
]
],
[
[
"x, y = next(iter(trainloader)); x = x.to(device)\nfor layer in model[:2]: x = layer(x)\nmodel[2].nfe = 0\ntraj = model[2].trajectory(x, torch.linspace(0, 1, 50)).detach().cpu()\nmodel[2].nfe ",
"/home/jyp/michael_dev/testenv/lib/python3.7/site-packages/torchdiffeq/_impl/misc.py:237: UserWarning: t is not on the same device as y0. Coercing to y0.device.\n warnings.warn(\"t is not on the same device as y0. Coercing to y0.device.\")\n"
]
],
[
[
"Pixel-flows of the Neural ODE, solved with `dopri5`",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(nrows=5, ncols=10, figsize=(22, 10))\nK = 4\nfor i in range(5):\n for j in range(10):\n im = axes[i][j].imshow(traj[i*5+j, K, 0], cmap='inferno')\nfig.tight_layout(w_pad=0)",
"_____no_output_____"
]
],
[
[
"### Defining the HyperSolver class (-- HyperEuler version --)",
"_____no_output_____"
]
],
[
[
"tableau = ButcherTableau([[0]], [1], [0], [])\neuler_solver = GenericExplicitButcher(tableau)\n\nhypersolv_net = nn.Sequential( \n nn.Conv2d(32+32+1, 32, 3, stride=1, padding=1),\n nn.PReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n nn.PReLU(),\n nn.Conv2d(32, 32, 3, padding=1)).to(device)\n#for p in hypersolv_net.parameters(): torch.nn.init.zeros_(p)\n\nhs = HyperEuler(f=model[2].defunc, g=hypersolv_net)\n\nx0 = torch.zeros(12, 32, 6, 6).to(device)\nspan = torch.linspace(0, 2, 10).to(device)\n\ntraj = model[2].trajectory(x0, span)\nres_traj = hs.base_residuals(traj, span)\nhyp_res_traj = hs.hypersolver_residuals(traj, span)\nhyp_traj = hs.odeint(x0, span)",
"_____no_output_____"
],
[
"hyp_traj = hs.odeint(x0, span, use_residual=False).detach().cpu()\netraj = odeint(model[2].defunc, x0, span, method='euler').detach().cpu()",
"_____no_output_____"
],
[
"(hyp_traj - etraj).max()",
"_____no_output_____"
]
],
[
[
"### Training the Hypersolver",
"_____no_output_____"
]
],
[
[
"PHASE1_ITERS = 10 # num iters without swapping of the ODE initial condition (new sample)\nITERS = 15000\ns_span = torch.linspace(0, 1, 10).to(device)\n\nrun_loss = 0.\n\n# using test data for hypersolver training does not cause issues\n# or task information leakage; the labels are not utilized in any way\nit = iter(trainloader) \nX0, Y = next(it)\nY = Y.to(device)\nX0 = model[:2](X0.to(device))\n\nmodel[2].solver = 'dopri5'\ntraj = model[2].trajectory(X0, s_span)\netraj = odeint(model[2].defunc, X0, s_span, method='euler')\n\nopt = torch.optim.AdamW(hypersolv_net.parameters(), 1e-3, weight_decay=1e-8)\nsched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=ITERS, eta_min=5e-4)\nfor i in tqdm(range(ITERS)): \n \n ds = s_span[1] - s_span[0]\n base_traj = model[2].trajectory(X0, s_span)\n residuals = hs.base_residuals(base_traj, s_span).detach()\n # Let the model generalize to other ICs after PHASE1_ITERS\n if i > PHASE1_ITERS:\n if i % 10 == 0: # swapping IC \n try:\n X0, _ = next(it)\n except:\n it = iter(trainloader)\n X0, _ = next(it)\n X0 = model[:2](X0.to(device)) \n model[2].solver = 'dopri5'\n base_traj = model[2].trajectory(X0, s_span)\n residuals = hs.base_residuals(base_traj.detach(), s_span).detach()\n \n \n corrections = hs.hypersolver_residuals(base_traj.detach(), s_span)\n loss = torch.norm(corrections - residuals.detach(), p='fro', dim=(3, 4)).mean() * ds**2 \n \n loss.backward()\n torch.nn.utils.clip_grad_norm_(hypersolv_net.parameters(), 1)\n if i % 10 == 0: print(f'\\rLoss: {loss}', end='')\n opt.step() \n sched.step()\n opt.zero_grad()",
"/home/jyp/michael_dev/testenv/lib/python3.7/site-packages/ipykernel_launcher.py:20: TqdmDeprecationWarning: This function will be removed in tqdm==5.0.0\nPlease use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`\n"
],
[
"it = iter(testloader)\nX0, _ = next(it)\nX0 = model[:2](X0.to(device))\nsteps = 10\ns_span = torch.linspace(0, 1, steps)\n# dopri traj\nmodel[2].solver = 'dopri5'\ntraj = model[2].trajectory(X0, s_span).detach().cpu()\n# euler traj\nmodel[2].solver = 'euler'\netraj = model[2].trajectory(X0, s_span).detach().cpu()\n#etraj = hs.odeint(X0, s_span, use_residual=False).detach().cpu()\n\nstraj = hs.odeint(X0, s_span, use_residual=True).detach().cpu()",
"/home/jyp/michael_dev/testenv/lib/python3.7/site-packages/torchdiffeq/_impl/misc.py:237: UserWarning: t is not on the same device as y0. Coercing to y0.device.\n warnings.warn(\"t is not on the same device as y0. Coercing to y0.device.\")\n"
]
],
[
[
"Evolution of absolute error: [Above] HyperEuler, [Below] Euler",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(nrows=2, ncols=steps-1, figsize=(10, 4))\nK = 1\nvmin = min(torch.abs(straj[steps-1,:]-traj[steps-1,:]).mean(1)[K].min(), \n torch.abs(etraj[steps-1,:]-traj[steps-1,:]).mean(1)[K].min())\nvmax = max(torch.abs(straj[steps-1,:]-traj[steps-1,:]).mean(1)[K].max(), \n torch.abs(etraj[steps-1,:]-traj[steps-1,:]).mean(1)[K].max())\n\nfor i in range(steps-1):\n im = axes[0][i].imshow(torch.abs(straj[i+1,:]-traj[i+1,:]).mean(1)[K], cmap='inferno', vmin=vmin, vmax=vmax)\nfor i in range(steps-1):\n im = axes[1][i].imshow(torch.abs(etraj[i+1,:]-traj[i+1,:]).mean(1)[K], cmap='inferno', vmin=vmin, vmax=vmax) \nfig.colorbar(im, ax=axes.ravel().tolist(), orientation='horizontal')\n#tikz.save('MNIST_interpolation_AE_plot.tex')",
"_____no_output_____"
]
],
[
[
"Evolution of absolute error: HyperEuler (alone). Greater detail",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(nrows=1, ncols=steps-1, figsize=(10, 4))\nfor i in range(steps-1):\n im = axes[i].imshow(torch.abs(straj[i+1,:]-traj[i+1,:]).mean(1)[K], cmap='inferno')\nfig.colorbar(im, ax=axes.ravel().tolist(), orientation='horizontal')",
"_____no_output_____"
]
],
[
[
"### Evaluating ODE solution error",
"_____no_output_____"
]
],
[
[
"x = []\n# NOTE: high GPU mem usage for generating data below for plot (on GPU)\n# consider using less batches (and iterating) or performing everything on CPU\nfor i in range(5):\n x_b, _ = next(it)\n x += [model[:2](x_b.to(device))]\nx = torch.cat(x); x.shape",
"_____no_output_____"
],
[
"STEPS = range(8, 50)\n\neuler_avg_error, euler_std_error = [], []\nhyper_avg_error, hyper_std_error = [], []\nmidpoint_avg_error, midpoint_std_error = [], []\nrk4_avg_error, rk4_std_error = [], []\n\nfor step in tqdm(STEPS):\n s_span = torch.linspace(0, 1, step)\n # dopri traj\n model[2].solver = 'dopri5'\n traj = model[2].trajectory(x, s_span).detach().cpu()\n # euler traj\n model[2].solver = 'euler'\n etraj = model[2].trajectory(x, s_span).detach().cpu()\n # hypersolver\n s_span = torch.linspace(0, 1, step)\n straj = hs.odeint(x, s_span, use_residual=True).detach().cpu()\n #midpoint\n model[2].solver = 'midpoint'\n s_span = torch.linspace(0, 1, step//2)\n mtraj = model[2].trajectory(x, s_span).detach().cpu()\n \n #midpoint\n model[2].solver = 'rk4'\n s_span = torch.linspace(0, 1, step//4)\n rtraj = model[2].trajectory(x, s_span).detach().cpu()\n \n # errors\n euler_error = torch.abs((etraj[-1].detach().cpu() - traj[-1].detach().cpu()) / traj[-1].detach().cpu()).sum(1)\n hyper_error = torch.abs((straj[-1].detach().cpu() - traj[-1].detach().cpu()) / traj[-1].detach().cpu()).sum(1)\n midpoint_error = torch.abs((mtraj[-1].detach().cpu() - traj[-1].detach().cpu()) / traj[-1].detach().cpu()).sum(1)\n rk4_error = torch.abs((rtraj[-1].detach().cpu() - traj[-1].detach().cpu()) / traj[-1].detach().cpu()).sum(1)\n \n # mean, stdev\n euler_avg_error += [euler_error.mean().item()] ; euler_std_error += [euler_error.mean(dim=1).mean(dim=1).std(0).item()]\n hyper_avg_error += [hyper_error.mean().item()] ; hyper_std_error += [hyper_error.mean(dim=1).mean(dim=1).std(0).item()]\n midpoint_avg_error += [midpoint_error.mean().item()] ; midpoint_std_error += [midpoint_error.mean(dim=1).mean(dim=1).std(0).item()]\n rk4_avg_error += [rk4_error.mean().item()] ; rk4_std_error += [rk4_error.mean(dim=1).mean(dim=1).std(0).item()]",
"_____no_output_____"
],
[
"euler_avg_error, euler_std_error = np.array(euler_avg_error), np.array(euler_std_error)\nhyper_avg_error, hyper_std_error = np.array(hyper_avg_error), np.array(hyper_std_error)\nmidpoint_avg_error, midpoint_std_error = np.array(midpoint_avg_error), np.array(midpoint_std_error)\nrk4_avg_error, rk4_std_error = np.array(rk4_avg_error), np.array(rk4_std_error)\n\nrange_steps = range(8, 50, 1)\nfig, ax = plt.subplots(1, 1); fig.set_size_inches(8, 3)\nax.plot(range_steps, euler_avg_error, color='red', linewidth=3, alpha=0.5)\nax.fill_between(range_steps, euler_avg_error-euler_std_error, euler_avg_error+euler_std_error, alpha=0.05, color='red')\n\nax.plot(range_steps, hyper_avg_error, c='black', linewidth=3, alpha=0.5)\nax.fill_between(range_steps, hyper_avg_error+hyper_std_error, hyper_avg_error-hyper_std_error, alpha=0.05, color='black')\n\n# start from 10 steps, balance the steps \nmid_range_steps = range(8, 50, 2)\nax.plot(mid_range_steps, midpoint_avg_error[::2], color='green', linewidth=3, alpha=0.5)\nax.fill_between(mid_range_steps, midpoint_avg_error[::2]-midpoint_std_error[::2], midpoint_avg_error[::2]+midpoint_std_error[::2], alpha=0.1, color='green')\n\n# start from 10 steps, balance the steps \nmid_range_steps = range(8, 50, 4)\nax.plot(mid_range_steps, rk4_avg_error[::4], color='gray', linewidth=3, alpha=0.5)\nax.fill_between(mid_range_steps, rk4_avg_error[::4]-rk4_std_error[::4], rk4_avg_error[::4]+rk4_std_error[::4], alpha=0.05, color='gray')\n\n\nax.set_ylim(0, 200)\nax.set_xlim(8, 40)\nax.legend(['Euler', 'HyperEuler', 'Midpoint', 'RK4'])\nax.set_xlabel('NFEs')\nax.set_ylabel('Terminal error (MAPE)')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb4a53a04cab85dbcb3d8a6e9cc9a5c993623643 | 84,444 | ipynb | Jupyter Notebook | Chapter 7/Chap7_Linear_Regression.ipynb | chikoungoun/OpenIntro | 12ce09cc169fdf0458e504b97b8db472ad84df4b | [
"MIT"
] | null | null | null | Chapter 7/Chap7_Linear_Regression.ipynb | chikoungoun/OpenIntro | 12ce09cc169fdf0458e504b97b8db472ad84df4b | [
"MIT"
] | null | null | null | Chapter 7/Chap7_Linear_Regression.ipynb | chikoungoun/OpenIntro | 12ce09cc169fdf0458e504b97b8db472ad84df4b | [
"MIT"
] | null | null | null | 109.241915 | 30,008 | 0.851499 | [
[
[
"# Introduction to Linear Regression",
"_____no_output_____"
],
[
"Linear Regression assumes that the relationship between 2 variables, x and y can be modeled by a straight line",
"_____no_output_____"
],
[
"$y = \\beta_0 + \\beta_1x$",
"_____no_output_____"
],
[
"We can also see the equation written as : ** y = mx +b**",
"_____no_output_____"
],
[
"with $\\beta_0$ and $\\beta_1$ represents 2 model parameters ",
"_____no_output_____"
],
[
"$x$ is usually called the **predictor** and $y$ the **response**",
"_____no_output_____"
],
[
"Some examples of linear relationships : \n* size of vocabulary of a child and the amount of education of the parents\n* length of hospital stay and severity of an operation",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"import seaborn as sns",
"_____no_output_____"
],
[
"df = pd.read_csv('../Dataset/Iris.csv',index_col=0)\ndf.head()",
"_____no_output_____"
]
],
[
[
"Using the famous Iris dataset to showcase an example of a linear regression plot. This plot shows the relationship between flower petal length and their petal width. (Where the hell am I going to find \"Common Brushtail Possum\" data)",
"_____no_output_____"
],
[
"Linear regression with seaborn : **regplot()** or **lmplot()**\n<br/><br/>\n**regplot() : ** simple model fit\n<br/><br/>\n**lmplot() : ** model fit + FacetGrid",
"_____no_output_____"
]
],
[
[
"sns.regplot(x=\"PetalLengthCm\",y=\"PetalWidthCm\",data=df)",
"_____no_output_____"
]
],
[
[
"We can witness that the data align following a straight line ",
"_____no_output_____"
],
[
"## 7.1 Line fitting, residuals and correlation",
"_____no_output_____"
],
[
"**Linear relationship** is being able to represent the relationship between 2 set of variables with a line",
"_____no_output_____"
],
[
"### 7.1.1 Beginning with straight lines",
"_____no_output_____"
]
],
[
[
"petal = df.sample(1,random_state=123)\npetal",
"_____no_output_____"
]
],
[
[
"Straight line should only be used when the dta appear to have a linear relationship",
"_____no_output_____"
],
[
"### 7.1.2 Fitting a line by eye",
"_____no_output_____"
],
[
"Linear regression function",
"_____no_output_____"
]
],
[
[
"def linear_regression(x,y):\n #Small control to test the nature of the parameters (Should be dataFrame columns)\n if type(x) and type(y) is pd.Series:\n print('Series')\n\n df = pd.DataFrame()\n df['X'] = x\n df['Y'] = y\n df['XY'] = df['X']*df['Y']\n df['X_squared'] = df['X']*df['X']\n df['Y_squared'] = df['Y']*df['Y']\n #Let's make this more readable by putting each of the Numerator and Denominator\n A = (df['Y'].sum() * df['X_squared'].sum()) - (df['X'].sum() * df['XY'].sum())\n B = df.shape[0]*df['X_squared'].sum() -(df['X'].sum())**2\n #We calculate the Y-intercept\n y_intercept = A/B\n\n #We know calculate the slope\n C = df.shape[0]*df['XY'].sum() - df['X'].sum()*df['Y'].sum()\n D = df.shape[0]*df['X_squared'].sum() - (df['X'].sum())**2\n\n #separating the Numerator and Denominator makes it more readable\n slope = C/D\n\n #Gives the whole table\n #print(df)\n\n return (slope,y_intercept)\n\n\n else:\n print('Type should should be Series (a dataframe column)')",
"_____no_output_____"
],
[
"d = pd.DataFrame({'A':[1,2,3,4,5,6],'B':[6,5,4,3,2,1]})",
"_____no_output_____"
],
[
"linear_regression(d['A'],d['B'])",
"Series\n"
]
],
[
[
"* We compute the **slope** and **Y-intercept** ",
"_____no_output_____"
]
],
[
[
"sl,yi = linear_regression(df[\"PetalLengthCm\"],df[\"PetalWidthCm\"])",
"Series\n"
],
[
"sl",
"_____no_output_____"
],
[
"yi",
"_____no_output_____"
]
],
[
[
"So we can conclude that the equation for the line of the petal length and width relationship is approximatively (the \"hat\" signifies that we are talking about an estimate) : ",
"_____no_output_____"
],
[
"<h3>$\\hat{y} = 0.415x - 0.366$ </h3>",
"_____no_output_____"
],
[
"### 7.1.2 Residuals",
"_____no_output_____"
],
[
"The data don't usually all fit exactly accross the line, they are mostly scattered around. We call **residual** the vertical distance between a data point and the regression line.\n<br/>\nThey are positive if they fall above the regression line, and negative if they fall below.\n<br/>\nIf they fit the line, the residual is zero.",
"_____no_output_____"
],
[
"We can write them as : \n<br/><br/>\n\n    $Residual = Data - Fit$\n",
"_____no_output_____"
],
[
"Or mathematically :\n<br/><br/>\n    $e = y - \\hat{y}$",
"_____no_output_____"
],
[
"A right linear model would be for these residuals to be as small as possible",
"_____no_output_____"
],
[
"* **<u>Residual plot</u>**",
"_____no_output_____"
]
],
[
[
"sns.residplot(x=\"PetalLengthCm\",y=\"PetalWidthCm\",data=df)",
"_____no_output_____"
]
],
[
[
"Here we plot the residuals, as the middle straight line represents the regression line; the data on the line fit perfectly the model, the one above it are the positive residuals and vice versa. We call this a **residual plot**, and is very useful to evaluate how well a linear model fits a dataset.",
"_____no_output_____"
],
[
"### 7.1.3 Describing linear relationships with correlation",
"_____no_output_____"
],
[
"**Correlation** describes the strength of the linear relationship between 2 variable. It measures how things are related.\n<br/>\nThe correlation **R** is always comprised between -1 and 1 ",
"_____no_output_____"
],
[
"* **0** : No apparent linear relationship\n* **1** : perfectly linear and positive relationship (going upward)\n* **-1** : Perfectly linear and negative relationship (going downward)",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(filename=\"../img/correlation.png\")",
"_____no_output_____"
]
],
[
[
"* We find the correlation of the \"iris\" database",
"_____no_output_____"
]
],
[
[
"\"\"\" Correlation Function \"\"\"\n#Zscore function\ndef zscore(x,mu,sigma):\n return (x-mu)/sigma\n\ndef correlation(dx,dy):\n if type(dx) and type(dy) is pd.Series:\n #Compute the means\n mx = dx.mean()\n my = dy.mean()\n\n #Compute the standard deviations\n sx = dx.std()\n sy = dy.std()\n\n #Compute the second part of the equation\n Q=0\n for i,j in zip(dx,dy):\n Q = Q + (zscore(i,mx,sx)*zscore(j,my,sy))\n\n #multiply with the first part and return the result\n return (1/(dx.shape[0]-1))*Q\n\n else:\n print('Type should should be Series (a dataframe column)')",
"_____no_output_____"
]
],
[
[
"Petal Length in relationship to Petal Width",
"_____no_output_____"
]
],
[
[
"correlation(df[\"PetalLengthCm\"],df[\"PetalWidthCm\"])",
"_____no_output_____"
]
],
[
[
"We find that the Correlation shows a pretty strong upward and positive fit",
"_____no_output_____"
],
[
"## 7.2 Least square regression line",
"_____no_output_____"
],
[
"When we find a linear fit for our data, we call this line the **regression line**. And it's equation is $\\hat{y}= mx + b$.",
"_____no_output_____"
],
[
"The **Least squares regression line** is a more rigorous approach in which we try to minimize the vertical distance from the data points to the regression line, or in other words minimize the some of the **residuals**.",
"_____no_output_____"
],
[
"we can add some other definitions, as the slope equation :\n<br/>\n<h2>$m = \\frac{S_y}{S_x}R$</h2>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb4a60d7fbd67ea65d986dbd1be59f62d3c3bdbe | 35,229 | ipynb | Jupyter Notebook | 2022/Python-for-finance/Section 13/regression_analysis.ipynb | millennialseb/EDU_python | 806bb21f873170c29d45d5279af5bd83c8b27dc9 | [
"MIT"
] | 1 | 2021-09-10T23:39:55.000Z | 2021-09-10T23:39:55.000Z | 2022/Python-for-finance/Section 13/regression_analysis.ipynb | millennialseb/EDU_python | 806bb21f873170c29d45d5279af5bd83c8b27dc9 | [
"MIT"
] | null | null | null | 2022/Python-for-finance/Section 13/regression_analysis.ipynb | millennialseb/EDU_python | 806bb21f873170c29d45d5279af5bd83c8b27dc9 | [
"MIT"
] | null | null | null | 62.132275 | 9,506 | 0.639871 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\n\ndata = pd.read_excel(\"Housing.xlsx\")\n",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"X = data['House Size (sq.ft.)']\nY = data['House Price']\n",
"_____no_output_____"
],
[
"X",
"_____no_output_____"
],
[
"Y",
"_____no_output_____"
],
[
"#understanding house market \nplt.scatter(X,Y)\nplt.show()\n",
"_____no_output_____"
],
[
"#understanding relationship betwwen price and dimension of houses\nplt.scatter(X,Y)\nplt.axis([0,2500,0,1500000])\nplt.ylabel('House Price')\nplt.xlabel('House Size (sq.ft)')",
"_____no_output_____"
],
[
"#creating reggression\n\nX1 = sm.add_constant(X)\nreg = sm.OLS(Y, X1).fit()\n",
"_____no_output_____"
],
[
"reg.summary()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb4a651eeff21558811c6071003877aadf4ac9bc | 16,324 | ipynb | Jupyter Notebook | training/cnn_predict_singlesided_var.ipynb | stanfordnmbl/video-gait-analysis | 4167ee6213ac81fb9168f4e20c6538d42a41a5a6 | [
"Apache-2.0"
] | 60 | 2020-04-15T11:41:41.000Z | 2022-03-24T04:46:41.000Z | training/cnn_predict_singlesided_var.ipynb | stanfordnmbl/video-gait-analysis | 4167ee6213ac81fb9168f4e20c6538d42a41a5a6 | [
"Apache-2.0"
] | 3 | 2021-02-02T22:50:45.000Z | 2022-03-17T20:07:10.000Z | training/cnn_predict_singlesided_var.ipynb | stanfordnmbl/video-gait-analysis | 4167ee6213ac81fb9168f4e20c6538d42a41a5a6 | [
"Apache-2.0"
] | 25 | 2020-05-29T21:43:47.000Z | 2022-03-14T11:46:18.000Z | 33.519507 | 177 | 0.612595 | [
[
[
"import numpy as np\nimport tensorflow as tf\nimport random as rn\nimport os\nimport matplotlib.pyplot as plt\n%matplotlib inline\nos.environ['PYTHONHASHSEED'] = '0'\nnp.random.seed(1)\nrn.seed(1)\nfrom keras import backend as K\ntf.compat.v1.set_random_seed(1)\n#sess = tf.Session(graph=tf.get_default_graph())\n#K.set_session(sess)\nimport sys \nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, Activation, Dropout, Flatten\nfrom keras.layers import Conv1D,MaxPooling1D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD\nfrom keras.optimizers import RMSprop\nimport keras.regularizers\nimport scipy\nimport math\nimport sys\nimport pandas as pd\nfrom scipy.ndimage.filters import gaussian_filter1d\nfrom sklearn.metrics import mean_squared_error\nfrom scipy.stats import linregress\nfrom scipy import interpolate\nfrom scipy import signal\nimport pickle\nfrom video_process_utils import *\nimport collections",
"_____no_output_____"
],
[
"target_col = \"SEMLS_dev_residual\"",
"_____no_output_____"
],
[
"#assign train/validation/test ids\nalldata_processed =\\\n pd.read_csv(\"./data/processed/alldata_processed_with_dev_residual.csv\" )\nalldata_processed['videoid'] = alldata_processed['videoid'].apply(lambda x: int(x))\nalldata_processed = alldata_processed[alldata_processed[target_col].notnull()]\nalldata_processed = alldata_processed.groupby(['videoid','side']).head(1)\nids_nonmissing_target = set(alldata_processed['videoid'].unique())",
"_____no_output_____"
],
[
"datasplit_df = pd.read_csv('./data/processed/train_test_valid_id_split.csv')\ndatasplit_df['videoid'] = datasplit_df['videoid'].apply(lambda x: int(x))\nall_ids = set(datasplit_df['videoid']).intersection(ids_nonmissing_target)\ntrain_ids = set(datasplit_df[datasplit_df['dataset'] == 'train']['videoid']).intersection(ids_nonmissing_target)\nvalidation_ids = set(datasplit_df[datasplit_df['dataset'] == 'validation']['videoid']).intersection(ids_nonmissing_target)\ntest_ids = set(datasplit_df[datasplit_df['dataset'] == 'test']['videoid']).intersection(ids_nonmissing_target)",
"_____no_output_____"
],
[
"with open('./data/processed/all_processed_video_segments.pickle', 'rb') as handle:\n processed_video_segments = pickle.load(handle)",
"_____no_output_____"
],
[
"x_columns = [2*LANK,2*LANK+1,2*LKNE,2*LKNE+1,\n 2*LHIP,2*LHIP+1,2*LBTO,2*LBTO+1,\n 2*RANK,2*RANK+1,2*RKNE,2*RKNE+1,\n 2*RHIP,2*RHIP+1,2*RBTO,2*RBTO+1,50,51,52,53,54,55,56]\n\ntarget_dict = {}\nfor i in range(len(alldata_processed)):\n row = alldata_processed.iloc[i]\n target_dict[row['videoid']] = row[target_col]",
"_____no_output_____"
],
[
"if target_col == \"gmfcs\":\n processed_video_segments = list(filter(lambda x: target_dict[x[0]] in range(1,6), processed_video_segments))",
"_____no_output_____"
],
[
"X = [t[2] for t in processed_video_segments if t[0] in all_ids]\nX = np.stack(X)[:,:,x_columns]",
"_____no_output_____"
],
[
"y = np.array([target_dict[t[0]] for t in processed_video_segments if t[0] in all_ids])",
"_____no_output_____"
],
[
"X_train = [t[2] for t in processed_video_segments if t[0] in train_ids]\nX_train = np.stack(X_train)[:,:,x_columns]",
"_____no_output_____"
],
[
"X_validation = [t[2] for t in processed_video_segments if t[0] in validation_ids]\nX_validation = np.stack(X_validation)[:,:,x_columns]",
"_____no_output_____"
],
[
"y_train = np.array([target_dict[t[0]] for t in processed_video_segments if t[0] in train_ids])",
"_____no_output_____"
],
[
"y_validation = np.array([target_dict[t[0]] for t in processed_video_segments if t[0] in validation_ids])",
"_____no_output_____"
],
[
"videoid_count_dict = collections.Counter(np.array([t[0] for t in processed_video_segments]))",
"_____no_output_____"
],
[
"train_videoid_weights = [1./videoid_count_dict[t[0]] for t in processed_video_segments if t[0] in train_ids]\ntrain_videoid_weights = np.array(train_videoid_weights).reshape(-1,1)\nvalidation_videoid_weights = [1./videoid_count_dict[t[0]] for t in processed_video_segments if t[0] in validation_ids]\nvalidation_videoid_weights = np.array(validation_videoid_weights).reshape(-1,1)",
"_____no_output_____"
],
[
"target_min = np.min(y_train,axis=0)\ntarget_range = np.max(y_train,axis=0) - np.min(y_train,axis=0)\nprint(target_min, target_range)",
"_____no_output_____"
],
[
"y_train_scaled = ((y_train-target_min)/target_range).reshape(-1,1)\ny_validation_scaled = ((y_validation-target_min)/target_range).reshape(-1,1)\n\ny_validation_scaled = np.hstack([y_validation_scaled,validation_videoid_weights])\ny_train_scaled = np.hstack([y_train_scaled,train_videoid_weights])\nc_i_factor = np.mean(np.vstack([train_videoid_weights,validation_videoid_weights]))",
"_____no_output_____"
],
[
"vid_length = 124",
"_____no_output_____"
],
[
"def step_decay(initial_lrate,epochs_drop,drop_factor):\n def step_decay_fcn(epoch):\n return initial_lrate * math.pow(drop_factor, math.floor((1+epoch)/epochs_drop))\n return step_decay_fcn\n\nepochs_drop,drop_factor = (10,0.8)\ninitial_lrate = 0.001\ndropout_amount = 0.5\nlast_layer_dim = 10\nfilter_length = 8\nconv_dim = 32\nl2_lambda = 10**(-3.5)\n\ndef w_mse(weights):\n def loss(y_true, y_pred):\n #multiply by len(weights) to make the magnitude invariant to number of components in target\n return K.mean(K.sum(K.square(y_true-y_pred)*weights,axis=1)*tf.reshape(y_true[:,-1],(-1,1)))/c_i_factor\n return loss\n\n#we don't want to optimize for the column counting video occurences of course, but\n#they are included in the target so we can use that column for the loss function\nweights = [1.0,0]\nnormal_weights = [1.0,0]\n\n\n#normalize weights to sum to 1 to prevent affecting loss function\nweights = weights/np.sum(weights)\nnormal_weights = normal_weights/np.sum(normal_weights)\n\n#fixed epoch budget of 100 that empirically seems to be sufficient \nn_epochs = 100\n\nmse_opt = w_mse(weights)\n\n#monitor our actual objective\nmse_metric = w_mse(target_range**2*normal_weights)\n\nhyper_str = \"params_\"\nfor param in [initial_lrate,epochs_drop,drop_factor,dropout_amount,conv_dim,last_layer_dim,filter_length,l2_lambda]:\n hyper_str = hyper_str + str(param) + \"_\"\n\nK.clear_session()\n#K.set_session(sess)\n\nmodel = Sequential()\nmodel.add(Conv1D(conv_dim,filter_length, input_dim=X_train.shape[2],input_length=vid_length,padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv1D(conv_dim,filter_length,padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(Dropout(dropout_amount))\nmodel.add(Conv1D(conv_dim,filter_length,padding='same',kernel_regularizer=keras.regularizers.l2(l2_lambda)))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv1D(conv_dim,filter_length,padding='same',kernel_regularizer=keras.regularizers.l2(l2_lambda)))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling1D(pool_size=2))\nmodel.add(Dropout(dropout_amount))\nmodel.add(Conv1D(conv_dim,filter_length,padding='same',kernel_regularizer=keras.regularizers.l2(l2_lambda)))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv1D(conv_dim,filter_length,padding='same',kernel_regularizer=keras.regularizers.l2(l2_lambda)))\nmodel.add(Activation('relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling1D(pool_size=3))\nmodel.add(Dropout(dropout_amount))\nmodel.add(Flatten())\nmodel.add(Dense(last_layer_dim,activation='relu'))\nmodel.add(Dense(2, activation='linear'))",
"_____no_output_____"
],
[
"checkpoint_folder = \"./data/checkpoints/cnn_checkpoints_%s\" % (target_col)",
"_____no_output_____"
],
[
"from keras.callbacks import LearningRateScheduler\n\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.callbacks import TerminateOnNaN\n\ntrain_model = True\n\nif not os.path.exists(checkpoint_folder):\n os.makedirs(checkpoint_folder)\n\nfilepath=checkpoint_folder+\"/weights-{epoch:02d}-{val_loss_1:.4f}.hdf5\"\nif train_model:\n\n opt = RMSprop(lr=0.0,rho=0.9, epsilon=1e-08, decay=0.0)\n model.compile(loss=mse_opt,metrics=[mse_metric],\n optimizer=opt)\n\n checkpoint = \\\n ModelCheckpoint(filepath, monitor='val_loss_2', verbose=1, save_best_only=False, save_weights_only=False, mode='auto', period=1)\n\n lr = LearningRateScheduler(step_decay(initial_lrate,epochs_drop,drop_factor))\n\n history = model.fit(X_train, y_train_scaled,callbacks=[checkpoint,lr,TerminateOnNaN()],\n validation_data=(X_validation,y_validation_scaled),\n batch_size=32, epochs=n_epochs,shuffle=True)",
"_____no_output_____"
],
[
"import statsmodels.api as sm",
"_____no_output_____"
],
[
"def undo_scaling(y,target_range,target_min):\n return y*target_range+target_min",
"_____no_output_____"
],
[
"weight_files = os.listdir(checkpoint_folder)\nweight_files_df = pd.DataFrame(weight_files,columns=['filename'])\nweight_files_df['num'] = weight_files_df['filename'].apply(lambda x: int(x.split('-')[1]))\nweight_files_df.sort_values(by='num',ascending=True,inplace=True)",
"_____no_output_____"
],
[
"def predict_and_aggregate_singlevar(y,X,ids,model,target_col):\n df = pd.DataFrame(y,columns=[target_col])\n target_col_pred = target_col + \"_pred\"\n videoids = [t[0] for t in processed_video_segments if t[0] in ids]\n df[\"videoid\"] = np.array(videoids)\n preds = model.predict(X)\n df[target_col_pred] = undo_scaling(preds[:,0],target_range,target_min)\n df[\"count\"] = 1\n df = df.groupby(['videoid'],as_index=False).agg({target_col_pred:np.mean,'count':np.sum,target_col:np.mean})\n df['ones'] = 1\n return df",
"_____no_output_____"
],
[
"video_ids = [t[0] for t in processed_video_segments if t[0] in all_ids]\npredictions_df = pd.DataFrame(video_ids,columns=['videoid'])\npredictions_df[target_col] = y\npredictions_df = predictions_df.merge(right=datasplit_df[['videoid','dataset']],on=['videoid'],how='left')",
"_____no_output_____"
],
[
"for i in range(0,len(weight_files_df)):\n weight_file = weight_files_df['filename'].iloc[i]\n print(weight_file)\n model.load_weights(checkpoint_folder + \"/%s\" % (weight_file))\n preds = model.predict(X)\n predictions_df[\"%s_pred_%s\" % (target_col,i)] = undo_scaling(preds[:,0],target_range,target_min)",
"_____no_output_____"
],
[
"predictions_df.groupby(['videoid','dataset'],as_index=False).mean().to_csv(\"./data/predictions/cnn_%s_singlesided_predictions_all_epochs.csv\" % (target_col),index=False)",
"_____no_output_____"
],
[
"# Save best models\n# This must be run after finding the best model with select_optimal_epoch \nmaps = {\n \"gmfcs\": \"./data/checkpoints/cnn_checkpoints_gmfcs/weights-08-0.5025.hdf5\", #\n \"speed\": \"./data/checkpoints/cnn_checkpoints_speed/weights-77-0.0336.hdf5\", #\n \"cadence\": \"./data/checkpoints/cnn_checkpoints_cadence/weights-36-0.0211.hdf5\", #\n \"SEMLS_dev_residual\": \"./data/checkpoints/cnn_checkpoints_SEMLS_dev_residual/weights-32-0.8929.hdf5\", #\n# \"GDI\": \"./data/checkpoints/cnn_checkpoints_GDI/weights-88-72.0330.hdf5\" #\n \"GDI\": \"./data/checkpoints/cnn_checkpoints_GDI/weights-92-90.8354.hdf5\" #\n}\nfor col in maps.keys():\n model_folder_path = \"./data/models/%s_best.pb\" % (col)\n model.load_weights(maps[col])\n model.save(model_folder_path)",
"_____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"
]
] |
cb4a6e7c6c8291537e0a519c5d47693eea21c483 | 38,408 | ipynb | Jupyter Notebook | notebooks/neo4j_modeling.ipynb | diegoquintanav/pinochet-analyze | 51d5ab8a3c3a73ee99eb5c54c57434ed62510d98 | [
"MIT"
] | 5 | 2019-09-24T08:53:40.000Z | 2021-08-04T16:32:05.000Z | notebooks/neo4j_modeling.ipynb | diegoquintanav/pinochet-analyze | 51d5ab8a3c3a73ee99eb5c54c57434ed62510d98 | [
"MIT"
] | 3 | 2019-09-21T11:55:33.000Z | 2021-03-31T20:22:06.000Z | notebooks/neo4j_modeling.ipynb | diegoquintanav/pinochet-analyze | 51d5ab8a3c3a73ee99eb5c54c57434ed62510d98 | [
"MIT"
] | null | null | null | 33.544105 | 2,730 | 0.418168 | [
[
[
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Modeling\" data-toc-modified-id=\"Modeling-1\"><span class=\"toc-item-num\">1 </span>Modeling</a></span><ul class=\"toc-item\"><li><span><a href=\"#Victims\" data-toc-modified-id=\"Victims-1.1\"><span class=\"toc-item-num\">1.1 </span>Victims</a></span></li><li><span><a href=\"#Perpetrators\" data-toc-modified-id=\"Perpetrators-1.2\"><span class=\"toc-item-num\">1.2 </span>Perpetrators</a></span></li><li><span><a href=\"#ViolenceEvent\" data-toc-modified-id=\"ViolenceEvent-1.3\"><span class=\"toc-item-num\">1.3 </span>ViolenceEvent</a></span></li></ul></li></ul></div>",
"_____no_output_____"
]
],
[
[
"import sys\nsys.version",
"_____no_output_____"
],
[
"from pathlib import Path\nimport pprint",
"_____no_output_____"
],
[
"%load_ext cypher\n# https://ipython-cypher.readthedocs.io/en/latest/\n# used for cell magic",
"_____no_output_____"
],
[
"from py2neo import Graph\nNEO4J_URI=\"bolt://localhost:7687\"\ngraph = Graph(NEO4J_URI)\ngraph",
"_____no_output_____"
],
[
"def clear_graph():\n print(graph.run(\"MATCH (n) DETACH DELETE n\").stats())",
"_____no_output_____"
],
[
"clear_graph()",
"constraints_added: 0\nconstraints_removed: 0\ncontained_updates: True\nindexes_added: 0\nindexes_removed: 0\nlabels_added: 0\nlabels_removed: 0\nnodes_created: 0\nnodes_deleted: 2398\nproperties_set: 0\nrelationships_created: 0\nrelationships_deleted: 0\n"
],
[
"graph.run(\"RETURN apoc.version();\").data()",
"_____no_output_____"
],
[
"graph.run(\"call dbms.components() yield name, versions, edition unwind versions as version return name, version, edition;\").data()",
"_____no_output_____"
]
],
[
[
"# Modeling",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"We are modeling data from the pinochet dataset, available in https://github.com/danilofreire/pinochet\n\n> Freire, D., Meadowcroft, J., Skarbek, D., & Guerrero, E.. (2019). Deaths and Disappearances in the Pinochet Regime: A New Dataset. https://doi.org/10.31235/osf.io/vqnwu.\n\nThe dataset has 59 variables with information about the victims, the perpetrators, and geographical\ncoordinates of each incident. ",
"_____no_output_____"
]
],
[
[
"PINOCHET_DATA = \"../pinochet/data/pinochet.csv\"\npin = pd.read_csv(PINOCHET_DATA)\npin.head()",
"_____no_output_____"
],
[
"pin.age.isna().sum()",
"_____no_output_____"
]
],
[
[
"The dataset contains informations about perpetrators, victims, violence events and event locations. We will develop models around these concepts, and we will stablish relationships between them later. ",
"_____no_output_____"
],
[
"\n## Victims\n\n- victim_id*: this is not the same as in the dataset.\n- individual_id\n- group_id\n- first_name\n- last_name\n- age\n- minor\n- male\n- number_previous_arrests\n- occupation\n- occupation_detail\n- victim_affiliation\n- victim_affiliation_detail\n- targeted",
"_____no_output_____"
]
],
[
[
"victim_attributes = [\n \"individual_id\",\n \"group_id\",\n \"first_name\",\n \"last_name\",\n \"age\",\n \"minor\",\n \"male\",\n \"number_previous_arrests\",\n \"occupation\",\n \"occupation_detail\",\n \"victim_affiliation\",\n \"victim_affiliation_detail\",\n \"targeted\",\n]\n\npin_victims = pin[victim_attributes]\npin_victims.head()",
"_____no_output_____"
],
[
"# https://neo4j.com/docs/labs/apoc/current/import/load-csv/\nPINOCHET_CSV_GITHUB = \"https://raw.githubusercontent.com/danilofreire/pinochet/master/data/pinochet.csv\"\n\nquery = \"\"\"\nWITH $url AS url \nCALL apoc.load.csv(url) \nYIELD lineNo, map, list\nRETURN *\nLIMIT 1\"\"\"\n\ngraph.run(query, url = PINOCHET_CSV_GITHUB).data()",
"_____no_output_____"
],
[
"%%cypher\nCALL apoc.load.csv('pinochet.csv') \nYIELD lineNo, map, list\nRETURN *\nLIMIT 1",
"1 rows affected.\n"
]
],
[
[
"## Perpetrators\n\n- perpetrator_affiliation\n- perpetrator_affiliation_detail\n- war_tribunal",
"_____no_output_____"
]
],
[
[
"perpetrators_attributes = [\n \"perpetrator_affiliation\",\n \"perpetrator_affiliation_detail\",\n \"war_tribunal\",\n]\n\npin_perps = pin[perpetrators_attributes]\npin_perps.head()",
"_____no_output_____"
]
],
[
[
"## ViolenceEvent",
"_____no_output_____"
]
],
[
[
"clear_graph()",
"constraints_added: 0\nconstraints_removed: 0\ncontained_updates: True\nindexes_added: 0\nindexes_removed: 0\nlabels_added: 0\nlabels_removed: 0\nnodes_created: 0\nnodes_deleted: 7849\nproperties_set: 0\nrelationships_created: 0\nrelationships_deleted: 0\n"
],
[
"query = Path(\"../services/graph-api/project/queries/load_csv.cql\").read_text()\n# pprint.pprint(query)\ngraph.run(query, url = PINOCHET_CSV_GITHUB).stats()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb4a6fc3fac0e3ce6405d9106bac7c767239eaab | 35,635 | ipynb | Jupyter Notebook | NB.ipynb | trangtran72/CS585_FinalProject | 8d91a05d1720f6dffe5e90cb82eabc377a9f3aff | [
"MIT"
] | null | null | null | NB.ipynb | trangtran72/CS585_FinalProject | 8d91a05d1720f6dffe5e90cb82eabc377a9f3aff | [
"MIT"
] | null | null | null | NB.ipynb | trangtran72/CS585_FinalProject | 8d91a05d1720f6dffe5e90cb82eabc377a9f3aff | [
"MIT"
] | null | null | null | 39.594444 | 6,464 | 0.553978 | [
[
[
"import pandas as pd\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.ensemble import RandomForestClassifier\nimport pickle\n%matplotlib inline",
"_____no_output_____"
],
[
"iron_man = pd.read_csv('iron_man.csv',index_col=0)",
"_____no_output_____"
],
[
"iron_man.head()",
"_____no_output_____"
],
[
"iron_man.shape",
"_____no_output_____"
],
[
"iron_man['is_duplicate'] = iron_man.review.duplicated(keep='first')",
"_____no_output_____"
],
[
"iron_man.head()",
"_____no_output_____"
],
[
"iron_man.is_duplicate.value_counts()",
"_____no_output_____"
],
[
"iron_man = iron_man[iron_man.is_duplicate == False]",
"_____no_output_____"
],
[
"iron_man.shape",
"_____no_output_____"
],
[
"iron_man.groupby('score').review.count().plot.bar(ylim=0)\nplt.show()\n",
"_____no_output_____"
],
[
"import nltk\nnltk.download('stopwords')\nstemmer = PorterStemmer()\nwords = stopwords.words(\"english\")\niron_man['cleaned'] = iron_man['review'].apply(lambda x: \" \".join([stemmer.stem(i) for i in re.sub(\"[^a-zA-Z]\", \" \", x).split() if i not in words]).lower())",
"[nltk_data] Downloading package stopwords to\n[nltk_data] /Users/mm40743/nltk_data...\n[nltk_data] Unzipping corpora/stopwords.zip.\n"
],
[
"iron_man.head()",
"_____no_output_____"
],
[
"iron_man[0:2]",
"_____no_output_____"
],
[
"vectorizer = TfidfVectorizer(min_df= 3, stop_words=\"english\", sublinear_tf=True, norm='l2', ngram_range=(1, 2))\nfinal_features = vectorizer.fit_transform(iron_man['cleaned']).toarray()\nfinal_features.shape",
"_____no_output_____"
],
[
"#first we split our dataset into testing and training set:\n# this block is to split the dataset into training and testing set \nX = iron_man['cleaned']\nY = iron_man['score']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25)",
"_____no_output_____"
],
[
"X_train.head()",
"_____no_output_____"
],
[
"X_test.head()",
"_____no_output_____"
],
[
"y_train.head()",
"_____no_output_____"
],
[
"y_test.head()",
"_____no_output_____"
],
[
"# instead of doing these steps one at a time, we can use a pipeline to complete them all at once\npipeline = Pipeline([('vect', vectorizer),\n ('chi', SelectKBest(chi2, k=1200)),\n ('clf', RandomForestClassifier())])",
"_____no_output_____"
],
[
"# fitting our model and save it in a pickle for later use\nmodel = pipeline.fit(X_train, y_train)\nwith open('RandomForest.pickle', 'wb') as f:\n pickle.dump(model, f)\nytest = np.array(y_test)",
"/anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.\n \"10 in version 0.20 to 100 in 0.22.\", FutureWarning)\n"
],
[
"ytest[:50]",
"_____no_output_____"
],
[
"# confusion matrix and classification report(precision, recall, F1-score)\nprint(classification_report(ytest, model.predict(X_test)))",
" precision recall f1-score support\n\n 1.0 1.00 0.22 0.36 9\n 2.0 0.00 0.00 0.00 6\n 3.0 0.00 0.00 0.00 12\n 4.0 0.33 0.14 0.20 56\n 5.0 0.66 0.91 0.76 148\n\n micro avg 0.63 0.63 0.63 231\n macro avg 0.40 0.26 0.27 231\nweighted avg 0.54 0.63 0.55 231\n\n"
],
[
"print(confusion_matrix(ytest, model.predict(X_test)))",
"[[ 2 0 0 0 7]\n [ 0 0 0 1 5]\n [ 0 0 0 2 10]\n [ 0 0 0 8 48]\n [ 0 0 0 13 135]]\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb4a7197ccb3dec267616c0afed5aec42e5a2d63 | 132,356 | ipynb | Jupyter Notebook | debug/remote_collector.ipynb | sergeivolodin/causality-disentanglement-rl | 5a41b4a2e3d85fa7e9c8450215fdc6cf954df867 | [
"CC0-1.0"
] | 2 | 2020-12-11T05:26:24.000Z | 2021-04-21T06:12:58.000Z | debug/remote_collector.ipynb | sergeivolodin/causality-disentanglement-rl | 5a41b4a2e3d85fa7e9c8450215fdc6cf954df867 | [
"CC0-1.0"
] | 9 | 2020-04-30T16:29:50.000Z | 2021-03-26T07:32:18.000Z | debug/remote_collector.ipynb | sergeivolodin/causality-disentanglement-rl | 5a41b4a2e3d85fa7e9c8450215fdc6cf954df867 | [
"CC0-1.0"
] | null | null | null | 326 | 62,820 | 0.923079 | [
[
[
"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nimport ray\nimport gin\nfrom sparse_causal_model_learner_rl.sacred_gin_tune.sacred_wrapper import load_config_files\nfrom sparse_causal_model_learner_rl.learners.rl_learner import CausalModelLearnerRL\nfrom sparse_causal_model_learner_rl.config import Config\nfrom time import sleep",
"_____no_output_____"
],
[
"load_config_files(['../sparse_causal_model_learner_rl/configs/test.gin', '../vectorincrement/config/ve5_nonlinear.gin'])",
"_____no_output_____"
],
[
"ray.init()",
"2021-02-05 01:21:34,798\tINFO services.py:1092 -- View the Ray dashboard at \u001b[1m\u001b[32mhttp://127.0.0.1:8265\u001b[39m\u001b[22m\n"
],
[
"gin.bind_parameter('Config.opt_iterations', {'opt1': 50})",
"_____no_output_____"
],
[
"gin.bind_parameter('Config.train_steps', 100)\ngin.bind_parameter('Config.env_steps', 100)\ngin.bind_parameter('Config.collect_every', 1)\ngin.bind_parameter('Config.collect_remotely', False)",
"_____no_output_____"
],
[
"learner = CausalModelLearnerRL(Config())\nlearner.create_trainables()\n_ = learner.collect_and_get_context()\nsleep(10)",
"Make environment VectorIncrement-v0 [<class 'encoder.observation_encoder.KerasEncoderWrapper'>] {}\nLoading model /home/sergei/git/science/causality-disentanglement/encoder/encoders/encoder-config-ve5_nonlinear-892637fe-fde9-11ea-84c5-00155d22e64a.pb\nWARNING:tensorflow:From /home/sergei/miniconda3/envs/causal/lib/python3.7/site-packages/tensorflow_core/python/ops/init_ops.py:97: calling GlorotUniform.__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\n"
],
[
"learner.train(do_tqdm=True)",
"_____no_output_____"
],
[
"# gin.bind_parameter('Config.train_steps', 100)\n# gin.bind_parameter('Config.env_steps', 100)\ngin.bind_parameter('Config.collect_remotely', True)",
"_____no_output_____"
],
[
"learner = CausalModelLearnerRL(Config())\nlearner.create_trainables()\n_ = learner.collect_and_get_context()\nsleep(10)",
"Make environment VectorIncrement-v0 [<class 'encoder.observation_encoder.KerasEncoderWrapper'>] {}\nLoading model /home/sergei/git/science/causality-disentanglement/encoder/encoders/encoder-config-ve5_nonlinear-892637fe-fde9-11ea-84c5-00155d22e64a.pb\nWARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually.\n"
],
[
"learner.train(do_tqdm=True)",
"_____no_output_____"
]
],
[
[
"Without parallel:\n",
"_____no_output_____"
],
[
"With parallel:\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cb4a92190cbea66c13a0d95e52f66a179f8a7bd9 | 30,509 | ipynb | Jupyter Notebook | Data Cleansing Master/Selecting Features using RFE.ipynb | behzad1195/Data-Prepration-in-Python | 81833d408bd886ab7a574ffdf880ca64a4b12f11 | [
"MIT"
] | 1 | 2021-08-18T14:47:10.000Z | 2021-08-18T14:47:10.000Z | Data Cleansing Master/Selecting Features using RFE.ipynb | behzad1195/Data-Prepration-in-Python | 81833d408bd886ab7a574ffdf880ca64a4b12f11 | [
"MIT"
] | null | null | null | Data Cleansing Master/Selecting Features using RFE.ipynb | behzad1195/Data-Prepration-in-Python | 81833d408bd886ab7a574ffdf880ca64a4b12f11 | [
"MIT"
] | null | null | null | 67.348786 | 8,428 | 0.775706 | [
[
[
"# evaluate RFE for classification\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score, RepeatedStratifiedKFold, RepeatedKFold\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.pipeline import Pipeline\n# define dataset\nX, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n#create pipeline\nrfe = RFE(estimator=DecisionTreeClassifier(), n_features_to_select=5)\nmodel= DecisionTreeClassifier() # the model shouldn't necessary the same with rfe's model\npipeline = Pipeline(steps=[('s', rfe),('m', model)]) # 's' and 'm' is just a chosen letters you can use any letter\n# evaluate model\ncv=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\nn_scores=cross_val_score(pipeline, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n# report performance\nprint('Accuracy: %.3f (%.3f)'% (np.mean(n_scores), np.std(n_scores)))\n",
"Accuracy: 0.888 (0.031)\n"
],
[
"# make a prediction with an RFE pipeline\n# define dataset\nX, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n#create pipeline\nrfe = RFE(estimator=DecisionTreeClassifier(), n_features_to_select=5)\nmodel= DecisionTreeClassifier() # the model shouldn't necessary the same with rfe's model\npipeline = Pipeline(steps=[('s', rfe),('m', model)]) # 's' and 'm' is just a chosen letters you can use any letter\n# fit the model on all available data\npipeline.fit(X,y)\n# make a prediction for one example\ndata = [[2.56999479, 0.13019997, 3.16075093, -435936352, -1.61271951, -1.39352057, -2.48924933, -1.93094078, 3.26130366, 1.05692145]]\nyhat = pipeline.predict(data)\nprint('Predicted Class: %d' % (yhat))",
"Predicted Class: 1\n"
],
[
"# test regression dataset\nfrom sklearn.datasets import make_regression\n# define dataset\nX, y= make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)\n# summarize the dataset\nprint(X.shape, y.shape)",
"(1000, 10) (1000,)\n"
],
[
"# evaluate RFE for regression\nimport numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score, RepeatedKFold\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.pipeline import Pipeline\n# define dataset\nX, y= make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)\n# create pipeline\nrfe = RFE(estimator=DecisionTreeRegressor(), n_features_to_select=5)\nmodel= DecisionTreeRegressor() # the model shouldn't necessary the same with rfe's model\npipeline = Pipeline(steps=[('s', rfe),('m', model)])\n# evaluate model\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\nn_scores = cross_val_score(pipeline, X, y, scoring= 'neg_mean_absolute_error', cv=cv, n_jobs=-1, error_score='raise')\n# reporting MAE of the model across all the folds, the sklearn library make the MAE negative so it maximize\n# instead of minimizing. This means the negative MAE values closer to zero are better and the perefect MAE is zero. \n# report performance\nprint('MAE: %.3f (%.3f)'% (np.mean(n_scores), np.std(n_scores)))",
"MAE: -27.075 (2.769)\n"
],
[
"# make a regression prediction with an RFE pipeline\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_regression\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.pipeline import Pipeline\n#define dataset\nX, y= make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)\n# create pipeline\nrfe = RFE(estimator=DecisionTreeRegressor(), n_features_to_select=5)\nmodel= DecisionTreeRegressor() # the model shouldn't necessary the same with rfe's model\npipeline = Pipeline(steps=[('s', rfe),('m', model)])\n# fit the model on all available data\npipeline.fit(X,y)\n# make a prediction for one example\ndata = [[-2.022220122, 0.31563495, 0.8279464, -0.30620401, 0.116003707, -1.44411381, 0.87616892, -0.50446586, 0.23009474, 0.76201118]]\nyhat=pipeline.predict(data)\nprint('Predicted: %.3f' % (yhat))",
"Predicted: -84.288\n"
],
[
"# explore the number of selected features for RFE\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score, RepeatedStratifiedKFold\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.pipeline import Pipeline\nfrom matplotlib import pyplot\n# get the dataset\ndef get_dataset():\n X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n return X,y\n\n# get a list of models to evaluate\ndef get_models():\n models=dict()\n for i in range(2, 10):\n rfe = RFE(estimator=DecisionTreeClassifier(), n_features_to_select=i)\n model = DecisionTreeClassifier()\n models[str(i)] = Pipeline(steps=[('s', rfe), ('m', model)])\n return models\n\n# evaluate a give model using cross-validation\ndef evaluate_model(model, X, y):\n cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n return scores\n\n# define datasets\nX, y = get_dataset()\n\n# get the model to evaluate\nmodels = get_models()\n\n# evaluate the models and store results\nresults, names = list(), list()\nfor name, model in models.items():\n scores = evaluate_model(model, X, y)\n results.append(scores)\n names.append(name)\n print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\n\n# plot model performance for comparison\npyplot.boxplot(results, labels=names, showmeans=True)\npyplot.show()",
">2 0.712 (0.041)\n>3 0.823 (0.036)\n>4 0.873 (0.032)\n>5 0.888 (0.036)\n>6 0.892 (0.025)\n>7 0.886 (0.030)\n>8 0.885 (0.027)\n>9 0.886 (0.026)\n"
],
[
"# automatically select the number of features for RFE\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import cross_val_score, RepeatedStratifiedKFold\nfrom sklearn.feature_selection import RFECV #-> for automation we should use 'REFCV' instead of 'REF'\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.pipeline import Pipeline\n# define dataset\ndef get_dataset():\n X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n return X,y\nX, y = get_dataset()\n# create pipeline\nrfe = RFECV(estimator=DecisionTreeClassifier())\nmodel = DecisionTreeClassifier()\npipeline = Pipeline(steps = [('s', rfe), ('m', model)])\n# evaluate model\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\nn_scores = cross_val_score(pipeline, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n# report performance\nprint('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))",
"Accuracy: 0.884 (0.029)\n"
],
[
"# by using RFE we might be interested to know which feature get selected and which not\nfrom sklearn.datasets import make_classification\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeClassifier\n# define dataset\nX, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n# define RFE\nrfe = RFE(estimator=DecisionTreeClassifier(), n_features_to_select=5)\n# fit RFE\nrfe.fit(X, y)\n#Summarize all features\nfor i in range(X.shape[1]):\n print('Column: %d, Selected %s, Rank: %.3f' % (i, rfe.support_[i], rfe.ranking_[i])) \n # .support_ reports True or False\n # .ranking_ reports the importance of each feature",
"Column: 0, Selected False, Rank: 5.000\nColumn: 1, Selected False, Rank: 4.000\nColumn: 2, Selected True, Rank: 1.000\nColumn: 3, Selected True, Rank: 1.000\nColumn: 4, Selected True, Rank: 1.000\nColumn: 5, Selected False, Rank: 6.000\nColumn: 6, Selected True, Rank: 1.000\nColumn: 7, Selected False, Rank: 3.000\nColumn: 8, Selected True, Rank: 1.000\nColumn: 9, Selected False, Rank: 2.000\n"
],
[
"# explore the algorithm wrapped by RFE -> This will tell us which algorithm is better to be used in RFE\nfrom numpy import mean\nfrom numpy import std\nfrom sklearn.datasets import make_classification\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression, Perceptron\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom matplotlib import pyplot\n\n# get the dataset\ndef get_dataset():\n X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)\n return X,y\n\n# get a list of models to evaluate\ndef get_models():\n models=dict()\n #lr\n rfe=RFE(estimator=LogisticRegression(), n_features_to_select=5)\n model = DecisionTreeClassifier()\n models['lr']= Pipeline(steps=[('s', rfe), ('m', model)])\n #perceptron\n rfe=RFE(estimator=Perceptron(), n_features_to_select=5)\n model = DecisionTreeClassifier()\n models['per']= Pipeline(steps=[('s', rfe), ('m', model)])\n # cart\n rfe=RFE(estimator=DecisionTreeClassifier(), n_features_to_select=5)\n model = DecisionTreeClassifier()\n models['cart']= Pipeline(steps=[('s', rfe), ('m', model)])\n # rf\n rfe=RFE(estimator=RandomForestClassifier(), n_features_to_select=5)\n model = DecisionTreeClassifier()\n models['rf']= Pipeline(steps=[('s', rfe), ('m', model)])\n # gbm\n rfe=RFE(estimator=GradientBoostingClassifier(), n_features_to_select=5)\n model = DecisionTreeClassifier()\n models['gbm']= Pipeline(steps=[('s', rfe), ('m', model)])\n return models\n\n# evaluate a give model using cross-validation\ndef evaluate_model(model, X, y):\n cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise')\n return scores\n\n# define datasets\nX, y = get_dataset()\n\n# get the model to evaluate\nmodels = get_models()\n\n# evaluate the models and store results\nresults, names = list(), list()\nfor name, model in models.items():\n scores = evaluate_model(model, X, y)\n results.append(scores)\n names.append(name)\n print('>%s %.3f (%.3f)' % (name, mean(scores), std(scores)))\n\n# plot model performance for comparison\npyplot.boxplot(results, labels=names, showmeans=True)\npyplot.show()\n",
">lr 0.890 (0.030)\n>per 0.847 (0.038)\n>cart 0.885 (0.035)\n>rf 0.858 (0.031)\n>gbm 0.889 (0.026)\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb4aa9d828315cd98816f83e38b8daa55ad9e8ce | 13,329 | ipynb | Jupyter Notebook | HackerRank/30 Days of Code/30 Days of Code.ipynb | Dhaneshgupta1027/Python | 12193d689cc49d3198ea6fee3f7f7d37b8e59175 | [
"MIT"
] | 37 | 2019-04-03T07:19:57.000Z | 2022-01-09T06:18:41.000Z | HackerRank/30 Days of Code/30 Days of Code.ipynb | Dhaneshgupta1027/Python | 12193d689cc49d3198ea6fee3f7f7d37b8e59175 | [
"MIT"
] | 16 | 2020-08-11T08:09:42.000Z | 2021-10-30T17:40:48.000Z | HackerRank/30 Days of Code/30 Days of Code.ipynb | Dhaneshgupta1027/Python | 12193d689cc49d3198ea6fee3f7f7d37b8e59175 | [
"MIT"
] | 130 | 2019-10-02T14:40:20.000Z | 2022-01-26T17:38:26.000Z | 22.289298 | 382 | 0.439718 | [
[
[
"# [Day 8](https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem)",
"_____no_output_____"
]
],
[
[
"{'1':'a'}.update({'2':'c'})",
"_____no_output_____"
],
[
"d = {}\nfor i in range(int(input())):\n x = input().split()\n d[x[0]] = x[1]\nwhile True:\n try:\n name = input()\n if name in d:\n print(name, \"=\", d[name], sep=\"\")\n else:\n print(\"Not found\") \n except:\n break",
" 2\n kes 34\n pl 56\n"
],
[
"n = int(input().strip())\nprint(max(len(length) for length in bin(n)[2:].split('0')))",
" 6\n"
]
],
[
[
"# Day 13",
"_____no_output_____"
]
],
[
[
"class Shape:\n def area(): pass\n def perimeter(): pass\n\nclass square(Shape):\n def __init_(self,side):\n self.side=side\ns=Shape()\ns",
"_____no_output_____"
],
[
"from abc import ABC,abstractclassmethod\nclass Shape(ABC):\n @abstractclassmethod\n def area(): pass\n @abstractclassmethod\n def perimeter(): pass\n\nclass square(Shape):\n def __init__(self,side):\n self.__side=side\n def area(self):\n return self.__side**2\n def perimeter(self):\n return self.__side*4",
"_____no_output_____"
],
[
"s=Shape() #if class is abstrat then we cant refrence this as",
"_____no_output_____"
],
[
"r=square(34)\nprint(r.area())\nprint(r.perimeter())",
"1156\n136\n"
],
[
"from abc import ABCMeta, abstractmethod\nclass Book(object, metaclass=ABCMeta):\n def __init__(self,title,author):\n self.title=title\n self.author=author \n @abstractmethod\n def display(): pass\n\n#Write MyBook class\nclass MyBook(Book):\n price=0\n def __init__(self,t,a,p):\n super(Book,self).__init__()\n self.price=p\n def display(self):\n print('Title: {}'.format(title))\n print('Author: {}'.format(author))\n print('Price: {}'.format(price))\n\ntitle=input()\nauthor=input()\nprice=int(input())\nnew_novel=MyBook(title,author,price)\nnew_novel.display()",
" The Alchemist\n Paulo Coelho\n 248\n"
]
],
[
[
"# Day 17",
"_____no_output_____"
]
],
[
[
"#Write your code here\nclass Calculator:\n def power(self,a,c):\n if a>0 and c>0:\n return a**c\n else:\n raise Exception('n and p should be non-negative')\nmyCalculator=Calculator()\nT=int(input())\nfor i in range(T):\n n,p = map(int, input().split())\n try:\n ans=myCalculator.power(n,p)\n print(ans)\n except Exception as e:\n print(e) ",
" 1\n -1 2\n"
]
],
[
[
"# Day 18",
"_____no_output_____"
]
],
[
[
"s=list(input())\nl=len(s)\nif l%2!=0:\n s.pop(l//2)\nfor i in range(l//2):\n if s.pop(0)!=s.pop(-1):\n print('oo')\n break\nelse:\n print('aagram')",
" racecar\n"
],
[
"[]+[1]",
"_____no_output_____"
],
[
"import sys\n\nclass Solution:\n # Write your code here\n def __init__(self):\n self.s=[]\n self.q=[]\n def pushCharacter(self,i):\n self.s+=[i]\n def enqueueCharacter(self,j):\n self.q=[j]+self.q\n def popCharacter(self):\n return self.s.pop()\n def dequeueCharacter(self):\n return self.q.pop()\n# read the string s\ns=input()\n#Create the Solution class object\nobj=Solution() \n\nl=len(s)\n# push/enqueue all the characters of string s to stack\nfor i in range(l):\n obj.pushCharacter(s[i])\n obj.enqueueCharacter(s[i])\n \nisPalindrome=True\n'''\npop the top character from stack\ndequeue the first character from queue\ncompare both the characters\n''' \nfor i in range(l // 2):\n if obj.popCharacter()!=obj.dequeueCharacter():\n isPalindrome=False\n break\n#finally print whether string s is palindrome or not.\nif isPalindrome:\n print(\"The word, \"+s+\", is a palindrome.\")\nelse:\n print(\"The word, \"+s+\", is not a palindrome.\") ",
"_____no_output_____"
]
],
[
[
"# Day 20",
"_____no_output_____"
]
],
[
[
"class Swaps:\n def __init__(self,n,a):\n self.n=n\n self.a=a\n self.numberOfSwaps=0\n def calculate(self):\n for i in range(self.n):\n #Track number of elements swapped during a single array traversal\n for j in range(self.n-1):\n # Swap adjacent elements if they are in decreasing order\n if self.a[j] > self.a[j + 1]:\n self.numberOfSwaps+=1\n temp=self.a[j]\n self.a[j]=self.a[j + 1]\n self.a[j+1]=temp\n #If no elements were swapped during a traversal, array is sorted\n if self.numberOfSwaps == 0:\n break;\n def display(self):\n self.calculate()\n print('Array is sorted in {0} swaps.\\nFirst Element: {1}\\nLast Element: {2}'.format(self.numberOfSwaps,a[0],a[-1]))\nn = int(input().strip())\na = list(map(int, input().strip().split(' ')))\n\ns=Swaps(n,a)\ns.display()",
" 3\n 3 2 1\n"
],
[
"s.display()",
"Array is sorted in 3 swaps.\nFirst Element: 1\nLast Element: 3\n"
],
[
"def isPrime(n) : \n \n if (n <= 1) : \n return False\n if (n <= 3) : \n return True\n \n if (n % 2 == 0 or n % 3 == 0) : \n return False\n \n i = 5\n while(i * i <= n) : \n if (n % i == 0 or n % (i + 2) == 0) : \n return False\n i = i + 6\n \n return True\nfor _ in range(int(input())):\n if isPrime(int(input())):\n print('Prime')\n else:\n print('Not prime')",
" 3\n 12\n"
],
[
"rd, rm, ry = [int(x) for x in input().split(' ')]\ned, em, ey = [int(x) for x in input().split(' ')]\n\nif (ry, rm, rd) <= (ey, em, ed):\n print(0)\nelif (ry, rm) == (ey, em):\n print(15 * (rd - ed))\nelif ry == ey:\n print(500 * (rm - em))\nelse:\n print(10000)",
" 9 6 2015\n 6 6 2015\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb4aaaabec519d2c69ba5189d12036b505387e70 | 6,920 | ipynb | Jupyter Notebook | StatisticsAndProbability/Lab2.ipynb | rostard/University | 02ff6efcfdb1f087d2a5adadcf38ace1fe7c34f8 | [
"MIT"
] | null | null | null | StatisticsAndProbability/Lab2.ipynb | rostard/University | 02ff6efcfdb1f087d2a5adadcf38ace1fe7c34f8 | [
"MIT"
] | null | null | null | StatisticsAndProbability/Lab2.ipynb | rostard/University | 02ff6efcfdb1f087d2a5adadcf38ace1fe7c34f8 | [
"MIT"
] | null | null | null | 6,920 | 6,920 | 0.663006 | [
[
[
"## *Лабораторна робота №2* - Перевірка статистичних гіпотез\n### Завдання\n##### *Розробити зошит*\nНа основі змодельованих даних реалізувати алгоритми перевірки критеріїв Колмогорова та Вілкоксона. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"#Критерій Колмогорова\nБудемо моделювати рівномірний розподіл на проміжку [low, high]",
"_____no_output_____"
]
],
[
[
"n = 100\n\nlow = 140\nhigh = 150\n\ndiff = high - low\n\n#функція розподілу для рівномірного розподілу\ndef eq_dist(x, low, high):\n if x < low:\n return 0\n if x > high:\n return 1\n return (x - low) / (high - low)",
"_____no_output_____"
],
[
"data1 = [(low + high) / 2 + np.random.randint(-diff//2, diff//2) for _ in range(n)] #генеруємо данні",
"_____no_output_____"
],
[
"guess_dist = [eq_dist(low + x*(high - low) / n, low, high) for x in range(n)]",
"_____no_output_____"
],
[
"sample_dist = [eq_dist(x, low, high) for x in sorted(data1)]",
"_____no_output_____"
],
[
"D = max(abs(guess_dist[i] - sample_dist[i]) for i in range(n))\nz = D * np.sqrt(n)",
"_____no_output_____"
]
],
[
[
"For** a=0.05** we find from table **z<sub>1–α</sub>=1,36**",
"_____no_output_____"
]
],
[
[
"if z < 1.36:\n print(\"Гіпотезу не відхиляємо\")\nelse:\n print(\"Гіпотезу відхиляємо\")",
"Гіпотезу відхиляємо\n"
]
],
[
[
"#Критерій Вілкоксона",
"_____no_output_____"
]
],
[
[
"n = 90\nm = 100\n# Генеруємо данні\ndata1 = [150 + np.random.randint(-10, 10) for _ in range(n)]\ndata2 = [160 + np.random.randint(-10, 10) for _ in range(m)]\n",
"_____no_output_____"
],
[
"last = 0\nranks = dict()\n\n#розраховуємо об'єднанні ранги\nfor x in sorted((set(data2) | set(data1))):\n c = (data1+data2).count(x)\n print(x, c, end=' ')\n print(last + (c+1)/2)\n last += c\n ranks[x] = last + (c+1)/2\n ",
"140 7 4.0\n141 5 10.0\n142 4 14.5\n143 5 19.0\n144 5 24.0\n145 7 30.0\n146 4 35.5\n147 3 39.0\n148 3 42.0\n149 4 45.5\n150 5 50.0\n151 10 57.5\n152 13 69.0\n153 9 80.0\n154 12 90.5\n155 8 100.5\n156 9 109.0\n157 7 117.0\n158 12 126.5\n159 9 137.0\n160 4 143.5\n161 5 148.0\n162 5 153.0\n163 6 158.5\n164 8 165.5\n165 3 171.0\n166 5 175.0\n167 7 181.0\n168 4 186.5\n169 2 189.5\n"
],
[
"W=0\nfor x in data1:\n W+=ranks[x]\nprint(W)",
"5912.5\n"
],
[
"#Розраховуэмо критичні значення W\nlow_W = 0.5*n*(n+m+1) - 2 * np.sqrt(1/12 * n * m * (n + m + 1))\nhigh_W = n * (n+m+1) - low_W",
"_____no_output_____"
],
[
"print(low_W, high_W)",
"7838.032365288977 9351.967634711022\n"
],
[
"if low_W < W < high_W:\n print(\"Гіпотезу не відхиляємо\")\nelse:\n print(\"Гіпотезу відхиляємо\")",
"Гіпотезу відхиляємо\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb4aad83786878aaa4cd12409717aa4f302cf46f | 3,091 | ipynb | Jupyter Notebook | Array/1027/835. Image Overlap.ipynb | YuHe0108/Leetcode | 90d904dde125dd35ee256a7f383961786f1ada5d | [
"Apache-2.0"
] | 1 | 2020-08-05T11:47:47.000Z | 2020-08-05T11:47:47.000Z | Array/1027/835. Image Overlap.ipynb | YuHe0108/LeetCode | b9e5de69b4e4d794aff89497624f558343e362ad | [
"Apache-2.0"
] | null | null | null | Array/1027/835. Image Overlap.ipynb | YuHe0108/LeetCode | b9e5de69b4e4d794aff89497624f558343e362ad | [
"Apache-2.0"
] | null | null | null | 24.531746 | 83 | 0.407312 | [
[
[
"说明:\n 给出两个图像 A 和 B ,A 和 B 为大小相同的二维正方形矩阵。\n (并且为二进制矩阵,只包含0和1)。\n 我们转换其中一个图像,向左,右,上,或下滑动任何数量的单位,并把它放在另一个图像的上面。\n 之后,该转换的重叠是指两个图像都具有 1 的位置的数目。\n (请注意,转换不包括向任何方向旋转。)\n 最大可能的重叠是什么?\n示例 1:\n 输入:A = [[1,1,0],\n [0,1,0],\n [0,1,0]]\n B = [[0,0,0],\n [0,1,1],\n [0,0,1]]\n 输出:3\n 解释: 将 A 向右移动一个单位,然后向下移动一个单位。\n\n注意: \n 1、1 <= A.length = A[0].length = B.length = B[0].length <= 30\n 2、0 <= A[i][j], B[i][j] <= 1",
"_____no_output_____"
]
],
[
[
"class Solution:\n def largestOverlap(self, img1, img2):\n N = len(img1)\n t_img1 = self.get_sum(img1)\n t_img2 = self.get_sum(img2)\n \n \n def get_sum(self, img):\n N, count = len(img), 0\n for i in range(N):\n for j in range(N):\n if img[i][j] == 1:\n count += 1\n return count",
"_____no_output_____"
],
[
"from collections import defaultdict\n\nclass Solution:\n def largestOverlap(self, img1, img2):\n N = len(img1)\n move_dict = defaultdict(int)\n for i in range(N):\n for j in range(N):\n if img1[i][j] == 1:\n for x in range(N):\n for y in range(N):\n if img2[x][y] == 1:\n p = (i - x, j - y)\n move_dict[p] += 1\n vals = move_dict.values()\n return max(vals) if vals else 0",
"_____no_output_____"
],
[
"solution = Solution()\nsolution.largestOverlap([[1,1,0],[0,1,0],[0,1,0]], [[0,0,0],[0,1,1],[0,0,1]])",
"_____no_output_____"
]
]
] | [
"raw",
"code"
] | [
[
"raw"
],
[
"code",
"code",
"code"
]
] |
cb4ab3bb28933e9fda2a43e4488f5f36d24637a6 | 22,461 | ipynb | Jupyter Notebook | Illustra.ipynb | lacostya86/aphantasia | c287ffd30d19ff1b51111143be7c1d3d98bac962 | [
"MIT"
] | null | null | null | Illustra.ipynb | lacostya86/aphantasia | c287ffd30d19ff1b51111143be7c1d3d98bac962 | [
"MIT"
] | null | null | null | Illustra.ipynb | lacostya86/aphantasia | c287ffd30d19ff1b51111143be7c1d3d98bac962 | [
"MIT"
] | null | null | null | 44.922 | 347 | 0.526379 | [
[
[
"# Illustra: Multi-text to Image\n\nThe part of [Aphantasia](https://github.com/eps696/aphantasia) series. \nBased on [CLIP](https://github.com/openai/CLIP) + FFT from [Lucent](https://github.com/greentfrapp/lucent) // made by Vadim Epstein [[eps696](https://github.com/eps696)] \nthanks to [Ryan Murdock](https://twitter.com/advadnoun), [Jonathan Fly](https://twitter.com/jonathanfly), [@eduwatch2](https://twitter.com/eduwatch2) for ideas.\n\n## Features \n* **continuously processes phrase lists** (e.g. illustrating lyrics)\n* generates massive detailed high res imagery, a la deepdream\n* directly parameterized with [FFT](https://github.com/greentfrapp/lucent/blob/master/lucent/optvis/param/spatial.py) (no pretrained GANs)\n* various CLIP models (including multi-language from [SBERT](https://sbert.net))\n* saving/loading FFT snapshots to resume processing\n* separate text prompt for image style\n",
"_____no_output_____"
],
[
"**Run the cell below after each session restart**\n\nMark `resume` and upload `.pt` file, if you're resuming from the saved params.",
"_____no_output_____"
]
],
[
[
"#@title General setup\n\n!pip install ftfy==5.8 transformers==4.6.0\n!pip install gputil ffpb \n\ntry: \n !pip3 install googletrans==3.1.0a0\n from googletrans import Translator, constants\n translator = Translator()\nexcept: pass\n\n!apt-get -qq install ffmpeg\nfrom google.colab import drive\ndrive.mount('/G', force_remount=True)\n# gdir = !ls /G/\n# gdir = '/G/%s/' % str(gdir[0])\ngdir = '/G/MyDrive/'\n%cd $gdir\nwork_dir = 'illustra'\nimport os\nwork_dir = os.path.join(gdir, work_dir)\nos.makedirs(work_dir, exist_ok=True)\n%cd $work_dir\n\nimport os\nimport io\nimport time\nimport math\nimport random\nimport imageio\nimport numpy as np\nimport PIL\nfrom base64 import b64encode\nimport shutil\n# import moviepy, moviepy.editor\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torch.autograd import Variable\n\nfrom IPython.display import HTML, Image, display, clear_output\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = \"all\"\nimport ipywidgets as ipy\nfrom google.colab import output, files\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n!pip install git+https://github.com/openai/CLIP.git --no-deps\nimport clip\n!pip install sentence_transformers\nfrom sentence_transformers import SentenceTransformer\n!pip install kornia\nimport kornia\n!pip install lpips\nimport lpips\n!pip install PyWavelets==1.1.1\n!pip install git+https://github.com/fbcotter/pytorch_wavelets\n\n%cd /content\n!rm -rf aphantasia\n!git clone https://github.com/eps696/aphantasia\n%cd aphantasia/\nfrom clip_fft import to_valid_rgb, fft_image\nfrom utils import slice_imgs, derivat, pad_up_to, basename, file_list, img_list, img_read, txt_clean, plot_text, checkout \nimport transforms\nfrom progress_bar import ProgressIPy as ProgressBar\n\nclear_output()\n\nresume = False #@param {type:\"boolean\"}\nif resume:\n resumed = files.upload()\n params_pt = list(resumed.values())[0]\n params_pt = torch.load(io.BytesIO(params_pt))\n if isinstance(params_pt, list): params_pt = params_pt[0]\n\ndef read_pt(file):\n return torch.load(file).cuda()\n\ndef ema(base, next, step):\n scale_ma = 1. / (step + 1)\n return next * scale_ma + base * (1.- scale_ma)\n\ndef save_img(img, fname=None):\n img = np.array(img)[:,:,:]\n img = np.transpose(img, (1,2,0)) \n img = np.clip(img*255, 0, 255).astype(np.uint8)\n if fname is not None:\n imageio.imsave(fname, np.array(img))\n imageio.imsave('result.jpg', np.array(img))\n\ndef makevid(seq_dir, size=None):\n out_sequence = seq_dir + '/%05d.jpg'\n out_video = seq_dir + '.mp4'\n !ffpb -y -i $out_sequence -codec nvenc $out_video\n # moviepy.editor.ImageSequenceClip(img_list(seq_dir), fps=25).write_videofile(out_video, verbose=False)\n data_url = \"data:video/mp4;base64,\" + b64encode(open(out_video,'rb').read()).decode()\n wh = '' if size is None else 'width=%d height=%d' % (size, size)\n return \"\"\"<video %s controls><source src=\"%s\" type=\"video/mp4\"></video>\"\"\" % (wh, data_url)\n\n# Hardware check\n!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi\nimport GPUtil as GPU\ngpu = GPU.getGPUs()[0] # XXX: only one GPU on Colab and isn’t guaranteed\n!nvidia-smi -L\nprint(\"GPU RAM {0:.0f}MB | Free {1:.0f}MB)\".format(gpu.memoryTotal, gpu.memoryFree))\nprint('\\nDone!')",
"_____no_output_____"
],
[
"#@title Upload text file\n\n#@markdown For non-English languages mark one of:\n\nmultilang = False #@param {type:\"boolean\"}\ntranslate = False #@param {type:\"boolean\"}\nuploaded = files.upload()\n\n#@markdown (`multilang` = multi-language CLIP model, trained with ViT, \n#@markdown `translate` = Google translation, compatible with any visual model)\n",
"_____no_output_____"
]
],
[
[
"### Settings\nSet the desired video resolution and `duration` (in sec). \nDescribe `style`, which you'd like to apply to the imagery. \nSelect CLIP visual `model` (results do vary!). I prefer ViT for consistency (and it's the only native multi-language option). \n\n`align` option is about composition. `uniform` looks most adequate, `overscan` can make semi-seamless tileable texture. \n`aug_transform` applies some augmentations, inhibiting image fragmentation & \"graffiti\" printing (slower, yet recommended). \nDecrease `samples` if you face OOM (it's the main RAM eater). \nIncreasing `steps` will elaborate details and make tones smoother, but may start throwing texts like graffiti (and will obviously take more time). \n`show_freq` controls preview frequency (doesn't affect the results; one can set it higher to speed up the process). \nTune `decay` (compositional softness) and `sharpness`, `colors` (saturation) and `contrast` as needed. \n\nExperimental tricks: \n`aug_noise` augmentation, `macro` (from 0 to 1) and `progressive_grow` (read more [here](https://github.com/eps696/aphantasia/issues/2)) may boost bigger forms, making composition less disperse. \n`no_text` tries to remove \"graffiti\" by subtracting plotted text prompt. good start is \\~0.1. \n`enhance` boosts training consistency (of simultaneous samples) and steps progress. good start is 0.1~0.2. \n\nNB: `keep` parameter controls how well the next line/image generation follows the previous. By default X = 0, and every frame is produced independently (i.e. randomly initiated). \nSetting it higher starts each generation closer to the average of previous runs, effectively keeping macro compositions more similar and the transitions smoother. Safe values are < 0.5 (higher numbers may cause the imagery getting stuck). This behaviour depends on the input, so test with your prompts and see what's better in your case.",
"_____no_output_____"
]
],
[
[
"#@title Generate\n\n# from google.colab import drive\n# drive.mount('/content/GDrive')\n# clipsDir = '/content/GDrive/MyDrive/T2I ' + dtNow.strftime(\"%Y-%m-%d %H%M\")\n\nstyle = \"\" #@param {type:\"string\"}\nsideX = 1280 #@param {type:\"integer\"}\nsideY = 720 #@param {type:\"integer\"}\nduration = 60#@param {type:\"integer\"}\n#@markdown > Config\nmodel = 'ViT-B/16' #@param ['ViT-B/16', 'ViT-B/32', 'RN101', 'RN50x16', 'RN50x4', 'RN50']\nalign = 'uniform' #@param ['central', 'uniform', 'overscan']\naug_transform = True #@param {type:\"boolean\"}\nkeep = 0. #@param {type:\"number\"}\n#@markdown > Look\ndecay = 1.5 #@param {type:\"number\"}\ncolors = 1.5 #@param {type:\"number\"}\ncontrast = 0.9#@param {type:\"number\"}\nsharpness = 0.3 #@param {type:\"number\"}\n#@markdown > Training\nsteps = 200 #@param {type:\"integer\"}\nsamples = 200 #@param {type:\"integer\"}\nlearning_rate = .05 #@param {type:\"number\"}\nshow_freq = 10 #@param {type:\"integer\"}\n#@markdown > Tricks\naug_noise = 0.2 #@param {type:\"number\"}\nno_text = 0. #@param {type:\"number\"}\nenhance = 0. #@param {type:\"number\"}\nmacro = 0.4 #@param {type:\"number\"}\nprogressive_grow = False #@param {type:\"boolean\"}\ndiverse = -enhance\nexpand = abs(enhance)\nfps = 25\nif multilang: model = 'ViT-B/32' # sbert model is trained with ViT\n\nuse_jit = True if float(torch.__version__[:3]) < 1.8 else False\nmodel_clip, _ = clip.load(model, jit=use_jit)\nmodsize = model_clip.visual.input_resolution\nxmem = {'ViT-B/16':0.25, 'RN50':0.5, 'RN50x4':0.16, 'RN50x16':0.06, 'RN101':0.33}\nif model in xmem.keys():\n samples = int(samples * xmem[model])\n\ndef enc_text(txt):\n if multilang:\n model_lang = SentenceTransformer('clip-ViT-B-32-multilingual-v1').cuda()\n emb = model_lang.encode([txt], convert_to_tensor=True, show_progress_bar=False).detach().clone()\n del model_lang\n else:\n emb = model_clip.encode_text(clip.tokenize(txt).cuda())\n return emb.detach().clone()\n\nif diverse != 0:\n samples = int(samples * 0.5)\n \nif aug_transform is True:\n trform_f = transforms.transforms_elastic\n samples = int(samples * 0.95)\nelse:\n trform_f = transforms.normalize()\n\ntext_file = list(uploaded)[0]\ntexts = list(uploaded.values())[0].decode().split('\\n')\ntexts = [tt.strip() for tt in texts if len(tt.strip())>0 and tt[0] != '#']\nprint(' text file:', text_file)\nprint(' total lines:', len(texts))\n\nif len(style) > 0:\n print(' style:', style)\n if translate:\n translator = Translator()\n style = translator.translate(style, dest='en').text\n print(' translated to:', style) \n txt_enc2 = enc_text(style)\n\nworkdir = os.path.join(work_dir, basename(text_file))\nworkdir += '-%s' % model if 'RN' in model.upper() else ''\n!rm -rf $workdir\nos.makedirs(workdir, exist_ok=True)\n\noutpic = ipy.Output()\noutpic\n \n# make init\nglobal params_start, params_ema\nparams_shape = [1, 3, sideY, sideX//2+1, 2]\nparams_start = torch.randn(*params_shape).cuda() # random init\nparams_ema = 0.\n\nif resume is True:\n # print(' resuming from', resumed)\n # params, _, _ = fft_image([1, 3, sideY, sideX], resume = params_pt, sd=1.)\n params_start = params_pt.cuda()\n if keep > 0:\n params_ema = params[0].detach()\n torch.save(params_pt, os.path.join(workdir, '000-start.pt'))\nelse:\n torch.save(params_start, os.path.join(workdir, '000-start.pt'))\n\ntorch.save(params_start, 'init.pt') # final init\n\nprev_enc = 0\ndef process(txt, num):\n\n global params_start\n sd = 0.01\n if keep > 0: sd = keep + (1-keep) * sd\n params, image_f, _ = fft_image([1, 3, sideY, sideX], resume='init.pt', sd=sd, decay_power=decay)\n image_f = to_valid_rgb(image_f, colors = colors)\n \n if progressive_grow is True:\n lr1 = learning_rate * 2\n lr0 = lr1 * 0.01\n else:\n lr0 = learning_rate\n optimizer = torch.optim.AdamW(params, lr0, weight_decay=0.01, amsgrad=True)\n \n print(' topic: ', txt)\n if translate:\n translator = Translator()\n txt = translator.translate(txt, dest='en').text\n print(' translated to:', txt)\n txt_enc = enc_text(txt)\n if no_text > 0:\n txt_plot = torch.from_numpy(plot_text(txt, modsize)/255.).unsqueeze(0).permute(0,3,1,2).cuda()\n txt_plot_enc = model_clip.encode_image(txt_plot).detach().clone()\n else: txt_plot_enc = None\n\n out_name = '%03d-%s' % (num+1, txt_clean(txt))\n tempdir = os.path.join(workdir, out_name)\n !rm -rf $tempdir\n os.makedirs(tempdir, exist_ok=True)\n\n pbar = ProgressBar(steps) # // save_freq\n for i in range(steps):\n loss = 0\n noise = aug_noise * torch.randn(1, 1, *params[0].shape[2:4], 1).cuda() if aug_noise > 0 else 0.\n img_out = image_f(noise)\n imgs_sliced = slice_imgs([img_out], samples, modsize, trform_f, align, macro=macro)\n out_enc = model_clip.encode_image(imgs_sliced[-1])\n\n loss -= torch.cosine_similarity(txt_enc, out_enc, dim=-1).mean()\n if len(style) > 0:\n loss -= 0.5 * torch.cosine_similarity(txt_enc2, out_enc, dim=-1).mean()\n if no_text > 0:\n loss += no_text * torch.cosine_similarity(txt_plot_enc, out_enc, dim=-1).mean()\n if sharpness != 0: # mode = scharr|sobel|default\n loss -= sharpness * derivat(img_out, mode='sobel')\n # loss -= sharpness * derivat(img_sliced, mode='scharr')\n if diverse != 0:\n imgs_sliced = slice_imgs([image_f(noise)], samples, modsize, trform_f, align, macro=macro)\n out_enc2 = model_clip.encode_image(imgs_sliced[-1])\n loss += diverse * torch.cosine_similarity(out_enc, out_enc2, dim=-1).mean()\n del out_enc2; torch.cuda.empty_cache()\n if expand > 0:\n global prev_enc\n if i > 0:\n loss += expand * torch.cosine_similarity(out_enc, prev_enc, dim=-1).mean()\n prev_enc = out_enc.detach()\n del img_out, imgs_sliced, out_enc; torch.cuda.empty_cache()\n\n if progressive_grow is True:\n lr_cur = lr0 + (i / steps) * (lr1 - lr0)\n for g in optimizer.param_groups: \n g['lr'] = lr_cur\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if i % show_freq == 0:\n with torch.no_grad():\n img = image_f(contrast=contrast).cpu().numpy()[0]\n if sharpness != 0:\n img = img ** (1 + sharpness/2.) # empirical tone mapping\n save_img(img, os.path.join(tempdir, '%05d.jpg' % (i // show_freq)))\n outpic.clear_output()\n with outpic:\n display(Image('result.jpg'))\n del img\n\n pbar.upd()\n\n if keep > 0:\n global params_start, params_ema\n params_ema = ema(params_ema, params[0].detach(), num+1)\n torch.save((1-keep) * params_start + keep * params_ema, 'init.pt')\n\n torch.save(params[0], '%s.pt' % os.path.join(workdir, out_name))\n # shutil.copy(img_list(tempdir)[-1], os.path.join(workdir, '%s-%d.jpg' % (out_name, steps)))\n # os.system('ffmpeg -v warning -y -i %s\\%%05d.jpg -codec nvenc \"%s.mp4\"' % (tempdir, os.path.join(workdir, out_name)))\n # HTML(makevid(tempdir))\n\nfor i, txt in enumerate(texts):\n process(txt, i)\n\nvsteps = int(duration * fps / len(texts))\ntempdir = os.path.join(workdir, '_final')\n!rm -rf $tempdir\nos.makedirs(tempdir, exist_ok=True)\n\nprint(' rendering complete piece')\nptfiles = file_list(workdir, 'pt')\npbar = ProgressBar(vsteps * len(ptfiles))\nfor px in range(len(ptfiles)):\n params1 = read_pt(ptfiles[px])\n params2 = read_pt(ptfiles[(px+1) % len(ptfiles)])\n\n params, image_f, _ = fft_image([1, 3, sideY, sideX], resume=params1, sd=1., decay_power=decay)\n image_f = to_valid_rgb(image_f, colors = colors)\n\n for i in range(vsteps):\n with torch.no_grad():\n img = image_f((params2 - params1) * math.sin(1.5708 * i/vsteps)**2)[0].permute(1,2,0)\n img = torch.clip(img*255, 0, 255).cpu().numpy().astype(np.uint8)\n imageio.imsave(os.path.join(tempdir, '%05d.jpg' % (px * vsteps + i)), img)\n _ = pbar.upd()\n\nHTML(makevid(tempdir))\n",
"_____no_output_____"
],
[
"#@markdown Run this, if you need to make the same video of another length (model must be the same)\n\nduration = 12#@param {type:\"integer\"}\nmodel = 'ViT-B/32' #@param ['ViT-B/32', 'RN101', 'RN50x4', 'RN50']\ncolors = 1.3 #@param {type:\"number\"}\nfps = 25\n\ntext_file = list(uploaded)[0]\nworkdir = os.path.join(work_dir, basename(text_file))\nworkdir += '-%s' % model if 'RN' in model.upper() else ''\ntempdir = os.path.join(workdir, '_final')\n!rm -rf $tempdir\nos.makedirs(tempdir, exist_ok=True)\n\nprint(' re-rendering final piece')\nptfiles = file_list(workdir, 'pt')\nvsteps = int(duration * fps / (len(ptfiles)-1))\n\nptest = torch.load(ptfiles[0])\nif isinstance(ptest, list): ptest = ptest[0]\nshape = [*ptest.shape[:3], (ptest.shape[3]-1)*2]\n\npbar = ProgressBar(vsteps * len(ptfiles))\nfor px in range(len(ptfiles)):\n params1 = read_pt(ptfiles[px])\n params2 = read_pt(ptfiles[(px+1) % len(ptfiles)])\n\n params, image_f, _ = fft_image(shape, resume=params1)\n image_f = to_valid_rgb(image_f, colors = colors)\n\n for i in range(vsteps):\n with torch.no_grad():\n img = image_f((params2 - params1) * math.sin(1.5708 * i/vsteps)**2)[0].permute(1,2,0)\n img = torch.clip(img*255, 0, 255).cpu().numpy().astype(np.uint8)\n imageio.imsave(os.path.join(tempdir, '%05d.jpg' % (px * vsteps + i)), img)\n _ = pbar.upd()\n\nHTML(makevid(tempdir))\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb4ab4c2484ac332b0b6fe6a3f87f5a7e021123d | 10,597 | ipynb | Jupyter Notebook | examples/notebooks/python/mortgage-gpu.ipynb | GaryShen2008/spark-xgboost-examples | 880f8b8a6fde21f2f8308450883c3a980f6d434e | [
"Apache-2.0"
] | 48 | 2020-06-11T07:49:47.000Z | 2022-03-27T13:57:41.000Z | examples/notebooks/python/mortgage-gpu.ipynb | GaryShen2008/spark-xgboost-examples | 880f8b8a6fde21f2f8308450883c3a980f6d434e | [
"Apache-2.0"
] | 23 | 2020-06-11T07:51:42.000Z | 2021-12-10T19:04:48.000Z | examples/notebooks/python/mortgage-gpu.ipynb | GaryShen2008/spark-xgboost-examples | 880f8b8a6fde21f2f8308450883c3a980f6d434e | [
"Apache-2.0"
] | 26 | 2020-06-11T06:55:15.000Z | 2021-09-06T08:28:01.000Z | 31.167647 | 433 | 0.562235 | [
[
[
"# Introduction to XGBoost Spark with GPU\n\nThe goal of this notebook is to show how to train a XGBoost Model with Spark RAPIDS XGBoost library on GPUs. The dataset used with this notebook is derived from Fannie Mae’s Single-Family Loan Performance Data with all rights reserved by Fannie Mae. This processed dataset is redistributed with permission and consent from Fannie Mae. This notebook uses XGBoost to train 12-month mortgage loan delinquency prediction model .\n\nA few libraries required for this notebook:\n 1. NumPy\n 2. cudf jar\n 3. xgboost4j jar\n 4. xgboost4j-spark jar\n 5. rapids-4-spark.jar\n\nThis notebook also illustrates the ease of porting a sample CPU based Spark xgboost4j code into GPU. There is only one change required for running Spark XGBoost on GPU. That is replacing the API `setFeaturesCol(feature)` on CPU with the new API `setFeaturesCols(features)`. This also eliminates the need for vectorization (assembling multiple feature columns in to one column) since we can read multiple columns.",
"_____no_output_____"
],
[
"#### Import All Libraries",
"_____no_output_____"
]
],
[
[
"from ml.dmlc.xgboost4j.scala.spark import XGBoostClassificationModel, XGBoostClassifier\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import FloatType, IntegerType, StructField, StructType\nfrom time import time",
"_____no_output_____"
]
],
[
[
"Besides CPU version requires two extra libraries.\n```Python\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.sql.functions import col\n```",
"_____no_output_____"
],
[
"#### Create Spark Session and Data Reader",
"_____no_output_____"
]
],
[
[
"spark = SparkSession.builder.getOrCreate()\nreader = spark.read",
"_____no_output_____"
]
],
[
[
"#### Specify the Data Schema and Load the Data",
"_____no_output_____"
]
],
[
[
"label = 'delinquency_12'\nschema = StructType([\n StructField('orig_channel', FloatType()),\n StructField('first_home_buyer', FloatType()),\n StructField('loan_purpose', FloatType()),\n StructField('property_type', FloatType()),\n StructField('occupancy_status', FloatType()),\n StructField('property_state', FloatType()),\n StructField('product_type', FloatType()),\n StructField('relocation_mortgage_indicator', FloatType()),\n StructField('seller_name', FloatType()),\n StructField('mod_flag', FloatType()),\n StructField('orig_interest_rate', FloatType()),\n StructField('orig_upb', IntegerType()),\n StructField('orig_loan_term', IntegerType()),\n StructField('orig_ltv', FloatType()),\n StructField('orig_cltv', FloatType()),\n StructField('num_borrowers', FloatType()),\n StructField('dti', FloatType()),\n StructField('borrower_credit_score', FloatType()),\n StructField('num_units', IntegerType()),\n StructField('zip', IntegerType()),\n StructField('mortgage_insurance_percent', FloatType()),\n StructField('current_loan_delinquency_status', IntegerType()),\n StructField('current_actual_upb', FloatType()),\n StructField('interest_rate', FloatType()),\n StructField('loan_age', FloatType()),\n StructField('msa', FloatType()),\n StructField('non_interest_bearing_upb', FloatType()),\n StructField(label, IntegerType()),\n])\nfeatures = [ x.name for x in schema if x.name != label ]\n\ntrain_data = reader.schema(schema).option('header', True).csv('/data/mortgage/csv/train')\ntrans_data = reader.schema(schema).option('header', True).csv('/data/mortgage/csv/test')",
"_____no_output_____"
]
],
[
[
"Note on CPU version, vectorization is required before fitting data to classifier, which means you need to assemble all feature columns into one column.\n\n```Python\ndef vectorize(data_frame):\n to_floats = [ col(x.name).cast(FloatType()) for x in data_frame.schema ]\n return (VectorAssembler()\n .setInputCols(features)\n .setOutputCol('features')\n .transform(data_frame.select(to_floats))\n .select(col('features'), col(label)))\n\ntrain_data = vectorize(train_data)\ntrans_data = vectorize(trans_data)\n```",
"_____no_output_____"
],
[
"#### Create a XGBoostClassifier",
"_____no_output_____"
]
],
[
[
"params = { \n 'eta': 0.1,\n 'gamma': 0.1,\n 'missing': 0.0,\n 'treeMethod': 'gpu_hist',\n 'maxDepth': 10, \n 'maxLeaves': 256,\n 'objective':'binary:logistic',\n 'growPolicy': 'depthwise',\n 'minChildWeight': 30.0,\n 'lambda_': 1.0,\n 'scalePosWeight': 2.0,\n 'subsample': 1.0,\n 'nthread': 1,\n 'numRound': 100,\n 'numWorkers': 1,\n}\nclassifier = XGBoostClassifier(**params).setLabelCol(label).setFeaturesCols(features)",
"_____no_output_____"
]
],
[
[
"The CPU version classifier provides the API `setFeaturesCol` which only accepts a single column name, so vectorization for multiple feature columns is required.\n```Python\nclassifier = XGBoostClassifier(**params).setLabelCol(label).setFeaturesCol('features')\n```\n\nThe parameter `num_workers` should be set to the number of GPUs in Spark cluster for GPU version, while for CPU version it is usually equal to the number of the CPU cores.\n\nConcerning the tree method, GPU version only supports `gpu_hist` currently, while `hist` is designed and used here for CPU training.",
"_____no_output_____"
],
[
"#### Train the Data with Benchmark",
"_____no_output_____"
]
],
[
[
"def with_benchmark(phrase, action):\n start = time()\n result = action()\n end = time()\n print('{} takes {} seconds'.format(phrase, round(end - start, 2)))\n return result\nmodel = with_benchmark('Training', lambda: classifier.fit(train_data))",
"Training takes 25.67 seconds\n"
]
],
[
[
"#### Save and Reload the Model",
"_____no_output_____"
]
],
[
[
"model.write().overwrite().save('/data/new-model-path')\nloaded_model = XGBoostClassificationModel().load('/data/new-model-path')",
"_____no_output_____"
]
],
[
[
"#### Transformation and Show Result Sample",
"_____no_output_____"
]
],
[
[
"def transform():\n result = loaded_model.transform(trans_data).cache()\n result.foreachPartition(lambda _: None)\n return result\nresult = with_benchmark('Transformation', transform)\nresult.select(label, 'rawPrediction', 'probability', 'prediction').show(5)",
"Transformation takes 11.39 seconds\n+--------------+--------------------+--------------------+----------+\n|delinquency_12| rawPrediction| probability|prediction|\n+--------------+--------------------+--------------------+----------+\n| 0|[7.76566505432128...|[0.99957613222068...| 0.0|\n| 0|[4.50240230560302...|[0.98903913144022...| 0.0|\n| 0|[4.50240230560302...|[0.98903913144022...| 0.0|\n| 0|[4.50240230560302...|[0.98903913144022...| 0.0|\n| 0|[4.50240230560302...|[0.98903913144022...| 0.0|\n+--------------+--------------------+--------------------+----------+\nonly showing top 5 rows\n\n"
]
],
[
[
"#### Evaluation",
"_____no_output_____"
]
],
[
[
"accuracy = with_benchmark(\n 'Evaluation',\n lambda: MulticlassClassificationEvaluator().setLabelCol(label).evaluate(result))\nprint('Accuracy is ' + str(accuracy))",
"Evaluation takes 1.03 seconds\nAccuracy is 0.9876786703104035\n"
],
[
"spark.stop()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb4abbf06a6ec559d17a31f00674417b86c20bf9 | 6,429 | ipynb | Jupyter Notebook | ExamPrep/SciCompComplete/Assessment1/Assessment1Q1.ipynb | FHomewood/ScientificComputing | bc3477b4607b25a700f2d89ca4f01cb3ea0998c4 | [
"IJG"
] | null | null | null | ExamPrep/SciCompComplete/Assessment1/Assessment1Q1.ipynb | FHomewood/ScientificComputing | bc3477b4607b25a700f2d89ca4f01cb3ea0998c4 | [
"IJG"
] | null | null | null | ExamPrep/SciCompComplete/Assessment1/Assessment1Q1.ipynb | FHomewood/ScientificComputing | bc3477b4607b25a700f2d89ca4f01cb3ea0998c4 | [
"IJG"
] | null | null | null | 39.685185 | 231 | 0.545186 | [
[
[
"# Constructing the Set of Equations For the Blocks:\n\n### Newtons second law is applied and each block is considered seperately to form the four equations of motion.\n### Newton's Second Law: \n$\\Sigma F=ma$\n#### Note:\nIn this circumstance, as each mass (except for 4) is on the same angled slope, I have made the decision to omit the explicit steps in each equation where I mention that: \n\n$F_N = m_n gcos \\theta$\n\n*Where $F_N$ is the Normal force, $m_n$ is the mass of the block and $g$ is acceleration due to gravity.*\n\nand the Friction on each block is:\n\n$F_r=\\mu F_N = \\mu_n m_n gcos \\theta $\n\n*Where $\\mu_n$ is the coefficients of friction for each block.*\n\nI have just expressly written them into the equations.\n\n\n### Block 1\n$\\Sigma F=m_1 g sin\\theta - \\mu_1 m_1 g cos\\theta - T_1 = m_1 a\n\\implies m_1 g (sin\\theta - \\mu_1 cos\\theta)=m_1 a + T_1 $\n### Block 2\n$\\Sigma F=m_2 g sin\\theta - \\mu_2 m_2 g cos\\theta + T_1 - T_2 = m_2 a\n\\implies m_2 g (sin\\theta - \\mu_2 cos\\theta)=m_2 a + T_2 - T_1$\n### Block 3\n$\\Sigma F=m_3 g sin\\theta - \\mu_3 m_3 g cos\\theta + T_2 - T_3 = m_3 a\n\\implies m_3 g sin\\theta - \\mu_3 cos\\theta)=m_3 a + T_3 - T_2$\n### Block 4\n$\\Sigma F=m_4 g - T_3 = m_2 a \\implies -T_3 + m_4 a=-m_4 g$\n\n### Setting up the problem; the matrix \"A\" and vector \"b\" .\nThe matrix \"A\" is constructed from the coefficients of the tensions, $T_n$ and the acceleration, $a$.\n\n\nThe Vector \"b\" is constructed for the masses (multiplied by gravity); $sin\\theta$ and $\\mu_n cos\\theta$.\n\n\nAs theta, $\\theta$ ; the masses, *m* and the coefficients of fricton, $\\mu$ are given the each element of \"b\" is a number.\n$$\\begin{bmatrix}\n 1 & 0 & 0 & m_1\\\\\n -1 & 1 & 0 & m_2\\\\\n 0 & -1 & 1 & m_3\\\\\n 0 & 0 & 1 & m_4\\\\\n\\end{bmatrix}\n\\begin{bmatrix}\n T_1\\\\\n T_2\\\\\n T_3\\\\\n a\\\\\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n m_1 g (sin\\theta - \\mu_1 cos\\theta)\\\\\n m_2 g (sin\\theta - \\mu_2 cos\\theta)\\\\\n m_3 g (sin\\theta - \\mu_3 cos\\theta)\\\\\n -m_4 g\\\\\n\\end{bmatrix}$$\n\n#### Note:\nAbove I have placed \"A\" and \"b\" in the standard Ax=b layout, hence I have included another vector containing $T_1$ through to $a$.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport gaussElimin as gE\n\n#Problem Sheet 1 Question 2b\n\n#Defining the values and constructing arrays for mass and coefficients of friction.\ng=9.82\nS=np.sin(np.pi/4)\nC=np.cos(np.pi/4)\nM=np.array([10,4,5,6])\nmu=np.array([0.25,0.3,0.2])\n\n#constructing the array of coeffiecients and the vector b \na=np.c_[(np.array([[1,0,0],[-1,1,0],[0,-1,1],[0,0,-1]])),M]#I am concatenating the array \"M\" to an array of the coefficients of the tensions. The values in \"M\" are the coefficients of the unknown acceleration, a value.\nb=g*M*np.array([(S-C*mu[0]),(S-C*mu[1]), (S-C*mu[2]), -1])\n\ngE.gaussElimin(a,b)\nprint ('T1=',b[0], ' T2=', b[1], ' T3=', b[2],' a=',b[3])\n\n#Problem Sheet 1 Question 2c\n\n#Want a to equal -9.82 then m4 will be in freefall.\n\n#All the tensions found in part 2b can be used.\n\n#Let a be set to -g and use Equations 3 and 4 to solve for sin(Theta) and cos(Theta).\n\n#Rearrange the equations so sin and cos are in a matrix and use Gauss elim.\n\n#Create another a and b; a is just the right hand side and b the left. Use -g as acceleration.\na1=g*np.array([[(M[1]),(M[1]*mu[1])], [(M[2]),(M[2]*mu[2])]]).astype(np.float)\n# I am using specific values for the 2nd & 3rd equations of mass & coefficients of friction from the \"M\" & \"mu\" arrays defined in part 1b.\n\nb=np.array([(-b[0]+b[1]+M[1]*-g),(-b[1]+b[2]+M[2]*-g)]).astype(np.float)\n#I am calling back to the values of T for Eqn 2 & Eqn 3, T2=b[1] & T3=b[2]\n\ngE.gaussElimin(a1,b)\n\nprint ('sin(Theta)=',b[0], ' cos(Theta)=',b[1])\nif abs(b[0])>1 or abs(b[1])>1: #1st logical argument. If either sin theta or cos theta are over 1 or under -1 then its obvious there is not solution.\n print ('Neither sin(Theta) or cos(Theta) can take values above or below 1 or -1. Hence there is not solution where Mass 4 is in freefall. ')\n\nif abs(b[0])<=1 and abs(b[1])<=1: #2nd logical argument. Since sin theta & cos theta do not exceed their limits and as they are dependant on the same theta so taking the inverse of both should yeild the same result.\n if round(np.arcsin(b[0]),20)==round(np.arccos(b[1]),20):\n print ('When Mass 4 is in freefall; Theta=',np.arcsin(b[0])*180/np.pi, ' degrees.')\n else:\n print('There is not solution where Mass 4 is in freefall.')\n",
"T1= 35.9279436924 T2= 48.9103634511 T3= 68.6102824452 a= 1.6150470742\nsin(Theta)= -0.457358297652 cos(Theta)= -0.707106781187\nThere is not solution where Mass 4 is in freefall.\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
cb4ac568a9bd0772a1a70f97498278db6ebc1211 | 272,837 | ipynb | Jupyter Notebook | additional_reference_notebooks/building_permits.ipynb | hud-capstone/Data-and-Urban-Development | c27a900c7594f87aa8f3abd0d911484d1b331bb4 | [
"Unlicense"
] | null | null | null | additional_reference_notebooks/building_permits.ipynb | hud-capstone/Data-and-Urban-Development | c27a900c7594f87aa8f3abd0d911484d1b331bb4 | [
"Unlicense"
] | null | null | null | additional_reference_notebooks/building_permits.ipynb | hud-capstone/Data-and-Urban-Development | c27a900c7594f87aa8f3abd0d911484d1b331bb4 | [
"Unlicense"
] | null | null | null | 40.582627 | 136 | 0.268516 | [
[
[
"# Building Permit Data\n\n## Documentation\n\n[United States Census Bureau Building Permits Survey](https://www.census.gov/construction/bps/)\n\n[ASCII files by State, Metropolitan Statistical Area (MSA), County or Place](https://www2.census.gov/econ/bps/)\n\n[MSA Folder](https://www2.census.gov/econ/bps/Metro/)\n\n[ASCII MSA Documentation](https://www2.census.gov/econ/bps/Documentation/msaasc.pdf)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nimport re\n\nimport os.path\nfrom os import path\n\nfrom datetime import datetime\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy import stats\n\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, PowerTransformer\nfrom sklearn.cluster import KMeans\n\nimport wrangle as wr\nimport preprocessing as pr\nimport explore as ex\nimport model as mo\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"\nBad key \"text.kerning_factor\" on line 4 in\n/usr/local/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/_classic_test_patch.mplstyle.\nYou probably need to get an updated matplotlibrc file from\nhttps://github.com/matplotlib/matplotlib/blob/v3.1.3/matplotlibrc.template\nor from the matplotlib source distribution\n"
],
[
"pd.set_option(\"display.max_columns\", None)",
"_____no_output_____"
],
[
"def rename_columns(df):\n \"\"\"\n Docstring\n \"\"\"\n \n # rename columns inplace\n df.rename(\n columns={\n \"Date\": \"survey_date\",\n \"Code\": \"csa_code\",\n \"Code.1\": \"cbsa_code\",\n \"Unnamed: 3\": \"moncov\",\n \"Name\": \"cbsa_name\",\n \"Bldgs\": \"one_unit_bldgs_est\",\n \"Units\": \"one_unit_units_est\",\n \"Value\": \"one_unit_value_est\",\n \"Bldgs.1\": \"two_units_bldgs_est\",\n \"Units.1\": \"two_units_units_est\",\n \"Value.1\": \"two_units_value_est\",\n \"Bldgs.2\": \"three_to_four_units_bldgs_est\",\n \"Units.2\": \"three_to_four_units_units_est\",\n \"Value.2\": \"three_to_four_units_value_est\",\n \"Bldgs.3\": \"five_or_more_units_bldgs_est\",\n \"Units.3\": \"five_or_more_units_units_est\",\n \"Value.3\": \"five_or_more_units_value_est\",\n \"Bldgs.4\": \"one_unit_bldgs_rep\",\n \"Units.4\": \"one_unit_units_rep\",\n \"Value.4\": \"one_unit_value_rep\",\n \"Bldgs.5\": \"two_units_bldgs_rep\",\n \"Units.5\": \"two_units_units_rep\",\n \"Value.5\": \"two_units_value_rep\",\n \" Bldgs\": \"three_to_four_units_bldgs_rep\",\n \"Units.6\": \"three_to_four_units_units_rep\",\n \"Value.6\": \"three_to_four_units_value_rep\",\n \"Bldgs.6\": \"five_or_more_units_bldgs_rep\",\n \"Units.7\": \"five_or_more_units_units_rep\",\n \"Value.7\": \"five_or_more_units_value_rep\",\n },\n inplace=True,\n )\n \n return df\n",
"_____no_output_____"
],
[
"# def sort_values_and_reset_index(df):\n# \"\"\"\n# Docstring\n# \"\"\"\n \n# # sort values by survey_date\n# df.sort_values(by=[\"survey_date\"], ascending=False, inplace=True)\n\n# # reset index inplace\n# df.reset_index(inplace=True)\n\n# # drop former index inplace\n# df.drop(columns=[\"index\"], inplace=True)\n \n# return df",
"_____no_output_____"
],
[
"def acquire_building_permits():\n \"\"\"\n Docstring\n \"\"\"\n \n # conditional\n if path.exists(\"building_permits.csv\"):\n \n # read csv\n df = pd.read_csv(\"building_permits.csv\", index_col=0)\n \n else:\n \n # create original df with 2019 data\n df = pd.read_csv(\"https://www2.census.gov/econ/bps/Metro/ma2019a.txt\", sep=\",\", header=1)\n\n # rename columns\n rename_columns(df)\n\n for i in range(1980, 2019):\n\n # read the txt file at url where i is the year in range\n year_df = pd.read_csv(\n f\"https://www2.census.gov/econ/bps/Metro/ma{i}a.txt\",\n sep=\",\",\n header=1,\n names=df.columns.tolist(),\n )\n \n # append data to global df variable\n df = df.append(year_df, ignore_index=True)\n\n # make moncov into bool so that the null observations of this feature are not considered in the dropna below\n df[\"moncov\"] = np.where(df.moncov == \"C\", 1, 0)\n\n # dropna inplace\n df.dropna(inplace=True)\n \n # chop off the succeding two digits after the year for survey_date\n df[\"survey_date\"] = df.survey_date.astype(str).apply(lambda x: re.sub(r\"\\d\\d$\", \"\", x))\n \n # add a preceding \"19\" to any years where the length of the observation is 2 (e.i., \"80\"-\"97\")\n df[\"survey_date\"] = df.survey_date.apply(lambda x: \"19\" + x if len(x) == 2 else x)\n \n # turn survey_date back into an int\n df[\"survey_date\"] = df.survey_date.astype(int)\n \n # turn moncov back into a bool\n df[\"moncov\"] = df.moncov.astype(bool)\n \n # sort values by survey_date\n df.sort_values(by=[\"survey_date\"], ascending=False, inplace=True)\n\n # reset index inplace\n df.reset_index(inplace=True)\n\n # drop former index inplace\n df.drop(columns=[\"index\"], inplace=True)\n \n # write df to disk as csv\n df.to_csv(\"building_permits.csv\")\n \n return df",
"_____no_output_____"
],
[
"df = pd.read_csv(\"ma2019a.txt\", sep=\",\", header=1)\ndf",
"_____no_output_____"
],
[
"df.rename(columns={\n \"Date\": \"survey_date\",\n \"Code\": \"csa_code\",\n \"Code.1\": \"cbsa_code\",\n \"Unnamed: 3\": \"moncov\",\n \"Name\": \"cbsa_name\",\n \"Bldgs\": \"one_unit_bldgs_est\",\n \"Units\": \"one_unit_units_est\",\n \"Value\": \"one_unit_value_est\",\n \"Bldgs.1\": \"two_units_bldgs_est\",\n \"Units.1\": \"two_units_units_est\",\n \"Value.1\": \"two_units_value_est\",\n \"Bldgs.2\": \"three_to_four_units_bldgs_est\",\n \"Units.2\": \"three_to_four_units_units_est\",\n \"Value.2\": \"three_to_four_units_value_est\",\n \"Bldgs.3\": \"five_or_more_units_bldgs_est\",\n \"Units.3\": \"five_or_more_units_units_est\",\n \"Value.3\": \"five_or_more_units_value_est\",\n \"Bldgs.4\": \"one_unit_bldgs_rep\",\n \"Units.4\": \"one_unit_units_rep\",\n \"Value.4\": \"one_unit_value_rep\",\n \"Bldgs.5\": \"two_units_bldgs_rep\",\n \"Units.5\": \"two_units_units_rep\",\n \"Value.5\": \"two_units_value_rep\",\n \" Bldgs\": \"three_to_four_units_bldgs_rep\",\n \"Units.6\": \"three_to_four_units_units_rep\",\n \"Value.6\": \"three_to_four_units_value_rep\",\n \"Bldgs.6\": \"five_or_more_units_bldgs_rep\",\n \"Units.7\": \"five_or_more_units_units_rep\",\n \"Value.7\": \"five_or_more_units_value_rep\",\n}, inplace=True)\n\ndf",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 384 entries, 0 to 383\nData columns (total 29 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 survey_date 384 non-null int64 \n 1 csa_code 384 non-null int64 \n 2 cbsa_code 384 non-null int64 \n 3 moncov 384 non-null object\n 4 cbsa_name 384 non-null object\n 5 one_unit_bldgs_est 384 non-null int64 \n 6 one_unit_units_est 384 non-null int64 \n 7 one_unit_value_est 384 non-null int64 \n 8 two_units_bldgs_est 384 non-null int64 \n 9 two_units_units_est 384 non-null int64 \n 10 two_units_value_est 384 non-null int64 \n 11 three_to_four_units_bldgs_est 384 non-null int64 \n 12 three_to_four_units_units_est 384 non-null int64 \n 13 three_to_four_units_value_est 384 non-null int64 \n 14 five_or_more_units_bldgs_est 384 non-null int64 \n 15 five_or_more_units_units_est 384 non-null int64 \n 16 five_or_more_units_value_est 384 non-null int64 \n 17 one_unit_bldgs_rep 384 non-null int64 \n 18 one_unit_units_rep 384 non-null int64 \n 19 one_unit_value_rep 384 non-null int64 \n 20 two_units_bldgs_rep 384 non-null int64 \n 21 two_units_units_rep 384 non-null int64 \n 22 two_units_value_rep 384 non-null int64 \n 23 three_to_four_units_bldgs_rep 384 non-null int64 \n 24 three_to_four_units_units_rep 384 non-null int64 \n 25 three_to_four_units_value_rep 384 non-null int64 \n 26 five_or_more_units_bldgs_rep 384 non-null int64 \n 27 five_or_more_units_units_rep 384 non-null int64 \n 28 five_or_more_units_value_rep 384 non-null int64 \ndtypes: int64(27), object(2)\nmemory usage: 87.1+ KB\n"
],
[
"len(df.cbsa_name.unique())",
"_____no_output_____"
],
[
"df.columns.tolist()",
"_____no_output_____"
],
[
"# df_2018 = pd.read_csv(\"ma2018a.txt\", sep=\",\", header=1, names=df.columns.tolist())\n# df_2018",
"_____no_output_____"
],
[
"# df = df.append(df_2018, ignore_index=True)\n# df.shape",
"_____no_output_____"
],
[
"# df_2017 = pd.read_csv(\"https://www2.census.gov/econ/bps/Metro/ma2017a.txt\", sep=\",\", header=1, names=df.columns.tolist())\n# df_2017",
"_____no_output_____"
],
[
"# df = df.append(df_2017, ignore_index=True)\n# df.shape",
"_____no_output_____"
],
[
"for i in range(2017, 2019):\n temp_df = pd.read_csv(\n f\"https://www2.census.gov/econ/bps/Metro/ma{i}a.txt\",\n sep=\",\",\n header=1,\n names=df.columns.tolist(),\n )\n df = df.append(temp_df, ignore_index=True)\n\ndf",
"_____no_output_____"
],
[
"for i in range(2010, 2017):\n # read the txt file at url where i is the year in range\n temp_df = pd.read_csv(\n f\"https://www2.census.gov/econ/bps/Metro/ma{i}a.txt\",\n sep=\",\",\n header=1,\n names=df.columns.tolist(),\n )\n \n # append data to global df variable\n df = df.append(temp_df, ignore_index=True)\n\ndf",
"_____no_output_____"
],
[
"for i in range(2006, 2010):\n # read the txt file at url where i is the year in range\n temp_df = pd.read_csv(\n f\"https://www2.census.gov/econ/bps/Metro/ma{i}a.txt\",\n sep=\",\",\n header=1,\n names=df.columns.tolist(),\n )\n # append data to global df variable\n df = df.append(temp_df, ignore_index=True)\n\ndf",
"_____no_output_____"
],
[
"for i in range(1980, 2006):\n # read the txt file at url where i is the year in range\n temp_df = pd.read_csv(\n f\"https://www2.census.gov/econ/bps/Metro/ma{i}a.txt\",\n sep=\",\",\n header=1,\n names=df.columns.tolist(),\n )\n # append data to global df variable\n df = df.append(temp_df, ignore_index=True)\n\ndf",
"_____no_output_____"
],
[
"df.isna().sum()",
"_____no_output_____"
],
[
"df[df.csa_code.isna()]",
"_____no_output_____"
],
[
"df.moncov.unique().tolist()",
"_____no_output_____"
],
[
"df[\"moncov\"] = np.where(df.moncov == \"C\", 1, 0)",
"_____no_output_____"
],
[
"df.isna().sum()",
"_____no_output_____"
],
[
"df.dropna(inplace=True)",
"_____no_output_____"
],
[
"df.isna().sum()",
"_____no_output_____"
],
[
"print(df.shape)\ndf.head(20)",
"(14149, 29)\n"
],
[
"# df.to_csv(\"building_permits.csv\")",
"_____no_output_____"
],
[
"# df = pd.read_csv(\"building_permits.csv\", index_col=0)\n# print(f\"\"\"Our DataFrame contains {df.shape[0]:,} observations and {df.shape[1]} features.\"\"\")\n# df.head()",
"_____no_output_____"
],
[
"# df[\"survey_date\"] = df.survey_date.astype(str).apply(lambda x: re.sub(r\"\\d\\d$\", \"\", x))\n# df",
"_____no_output_____"
],
[
"# df.survey_date.unique()",
"_____no_output_____"
],
[
"# len(df.survey_date)",
"_____no_output_____"
],
[
"# df[\"survey_date\"] = df.survey_date.astype(str).apply(lambda x: \"19\" + x if len(x) == 2 else x)\n# df",
"_____no_output_____"
],
[
"# df.survey_date.unique().tolist()",
"_____no_output_____"
],
[
"# df.info()",
"_____no_output_____"
],
[
"# df = pd.read_csv(\"building_permits.csv\", index_col=0)\n# df",
"_____no_output_____"
],
[
"# df[\"survey_date\"] = df.survey_date.astype(str).apply(lambda x: re.sub(r\"\\d\\d$\", \"\", x))\n# df.survey_date.unique().tolist()",
"_____no_output_____"
],
[
"# df.info()",
"_____no_output_____"
],
[
"# df[\"survey_date\"] = df.survey_date.apply(lambda x: \"19\" + x if len(x) == 2 else x)",
"_____no_output_____"
],
[
"# df.survey_date.unique().tolist()",
"_____no_output_____"
],
[
"# df[\"survey_date\"] = df.survey_date.astype(int)\n# df.info()",
"_____no_output_____"
],
[
"# df = acquire_building_permits()\n# df",
"_____no_output_____"
],
[
"# df.reset_index(inplace=True)",
"_____no_output_____"
],
[
"# df.drop(columns=[\"index\"], inplace=True)\n# df",
"_____no_output_____"
],
[
"df = acquire_building_permits()\nprint(f\"\"\"Our DataFrame contains {df.shape[0]:,} observations and {df.shape[1]} features.\"\"\")\ndf",
"Our DataFrame contains 14,149 observations and 29 features.\n"
],
[
"# df.sort_values(by=[\"survey_date\"], ascending=False, inplace=True)",
"_____no_output_____"
],
[
"# df",
"_____no_output_____"
],
[
"# df.info()",
"_____no_output_____"
],
[
"# df.moncov.unique().tolist()",
"_____no_output_____"
],
[
"# df[\"moncov\"] = df.moncov.astype(bool)\ndf.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 14149 entries, 0 to 14148\nData columns (total 29 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 survey_date 14149 non-null int64 \n 1 csa_code 14149 non-null float64\n 2 cbsa_code 14149 non-null float64\n 3 moncov 14149 non-null bool \n 4 cbsa_name 14149 non-null object \n 5 one_unit_bldgs_est 14149 non-null float64\n 6 one_unit_units_est 14149 non-null float64\n 7 one_unit_value_est 14149 non-null float64\n 8 two_units_bldgs_est 14149 non-null float64\n 9 two_units_units_est 14149 non-null float64\n 10 two_units_value_est 14149 non-null float64\n 11 three_to_four_units_bldgs_est 14149 non-null float64\n 12 three_to_four_units_units_est 14149 non-null float64\n 13 three_to_four_units_value_est 14149 non-null float64\n 14 five_or_more_units_bldgs_est 14149 non-null float64\n 15 five_or_more_units_units_est 14149 non-null float64\n 16 five_or_more_units_value_est 14149 non-null float64\n 17 one_unit_bldgs_rep 14149 non-null float64\n 18 one_unit_units_rep 14149 non-null float64\n 19 one_unit_value_rep 14149 non-null float64\n 20 two_units_bldgs_rep 14149 non-null float64\n 21 two_units_units_rep 14149 non-null float64\n 22 two_units_value_rep 14149 non-null float64\n 23 three_to_four_units_bldgs_rep 14149 non-null float64\n 24 three_to_four_units_units_rep 14149 non-null float64\n 25 three_to_four_units_value_rep 14149 non-null float64\n 26 five_or_more_units_bldgs_rep 14149 non-null float64\n 27 five_or_more_units_units_rep 14149 non-null float64\n 28 five_or_more_units_value_rep 14149 non-null float64\ndtypes: bool(1), float64(26), int64(1), object(1)\nmemory usage: 3.1+ MB\n"
],
[
"# df",
"_____no_output_____"
],
[
"# df = sort_values_and_reset_index(df)\n# df",
"_____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"
]
] |
cb4acf80138bd6ca843eecb5e4f5a72656cfe595 | 5,051 | ipynb | Jupyter Notebook | docs/notebooks/404.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | docs/notebooks/404.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | docs/notebooks/404.ipynb | TheV1rtuoso/debuggingbook | dd4a1605cff793f614e67fbaef74de7d20e0519c | [
"MIT"
] | null | null | null | 24.400966 | 344 | 0.557909 | [
[
[
"# Oh no! We are not ready yet!\n\nWe're sorry - this page does not exist (yet). ",
"_____no_output_____"
],
[
"## Finding Content\n\nMost likely, you have been looking for material that is not yet written or not yet published. Go to the [home page](__SITE_HTML__) or choose from this list of chapters:\n\n<ol start=\"0\">\n <__STRUCTURED_ALL_CHAPTERS_MENU__>\n</ol>",
"_____no_output_____"
],
[
"If you think this is an error, please [report an issue](__GITHUB_HTML__/issues/).",
"_____no_output_____"
],
[
"## Getting Informed About New Content\n\nNew chapters are coming out every week. To get notified when a new chapter (or this one) comes out, <a href=\"https://twitter.com/Debugging_Book?ref_src=twsrc%5Etfw\" data-show-count=\"false\">follow us on Twitter</a>.\n\n<a class=\"twitter-timeline\" data-width=\"500\" data-chrome=\"noheader nofooter noborders transparent\" data-link-color=\"#A93226\" data-align=\"center\" href=\"https://twitter.com/Debugging_Book?ref_src=twsrc%5Etfw\">News from @Debugging_Book</a> <script async src=\"https://platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>",
"_____no_output_____"
],
[
"## Error Details",
"_____no_output_____"
]
],
[
[
"import bookutils",
"_____no_output_____"
],
[
"class NotFoundError(Exception):\n def __init__(self, value: str = \"404\") -> None:\n self.value = value\n\n def __str__(self) -> str:\n return repr(self.value)",
"_____no_output_____"
],
[
"from ExpectError import ExpectError\n\nwith ExpectError():\n raise NotFoundError",
"Traceback (most recent call last):\n File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_36519/1830731544.py\", line 4, in <module>\n raise NotFoundError\nNotFoundError: '404' (expected)\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb4ad344590a60b6590633d6456948dd6df09bb5 | 193,279 | ipynb | Jupyter Notebook | notebooks/exp41_analysis.ipynb | CoAxLab/infomercial | fa5d1c1e5c1351735dda2961a2a94f71cd17e270 | [
"MIT"
] | 4 | 2019-11-14T03:13:25.000Z | 2021-01-04T17:30:23.000Z | notebooks/exp41_analysis.ipynb | CoAxLab/infomercial | fa5d1c1e5c1351735dda2961a2a94f71cd17e270 | [
"MIT"
] | null | null | null | notebooks/exp41_analysis.ipynb | CoAxLab/infomercial | fa5d1c1e5c1351735dda2961a2a94f71cd17e270 | [
"MIT"
] | null | null | null | 485.625628 | 84,948 | 0.94509 | [
[
[
"# Exp 41 analysis\n\nSee `./informercial/Makefile` for experimental\ndetails.",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\n\nfrom IPython.display import Image\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport seaborn as sns\nsns.set_style('ticks')\n\nmatplotlib.rcParams.update({'font.size': 16})\nmatplotlib.rc('axes', titlesize=16)\n\nfrom infomercial.exp import meta_bandit\nfrom infomercial.local_gym import bandit\nfrom infomercial.exp.meta_bandit import load_checkpoint\n\nimport gym",
"_____no_output_____"
],
[
"# ls ../data/exp2*",
"_____no_output_____"
]
],
[
[
"# Load and process data",
"_____no_output_____"
]
],
[
[
"data_path =\"/Users/qualia/Code/infomercial/data/\"\nexp_name = \"exp41\"\nbest_params = load_checkpoint(os.path.join(data_path, f\"{exp_name}_best.pkl\"))\nsorted_params = load_checkpoint(os.path.join(data_path, f\"{exp_name}_sorted.pkl\"))",
"_____no_output_____"
],
[
"best_params",
"_____no_output_____"
]
],
[
[
"# Performance\n\nof best parameters",
"_____no_output_____"
]
],
[
[
"env_name = 'BanditHardAndSparse2-v0'\nnum_episodes = 20*10\n\n# Run w/ best params\nresult = meta_bandit(\n env_name=env_name,\n num_episodes=num_episodes, \n lr=best_params[\"lr\"], \n tie_threshold=best_params[\"tie_threshold\"],\n seed_value=19,\n save=\"exp41_best_model.pkl\"\n)",
"_____no_output_____"
],
[
"# Plot run\nepisodes = result[\"episodes\"]\nactions =result[\"actions\"]\nscores_R = result[\"scores_R\"]\nvalues_R = result[\"values_R\"]\nscores_E = result[\"scores_E\"]\nvalues_E = result[\"values_E\"]\n\n# Get some data from the gym...\nenv = gym.make(env_name)\nbest = env.best\nprint(f\"Best arm: {best}, last arm: {actions[-1]}\")\n\n# Init plot\nfig = plt.figure(figsize=(6, 14))\ngrid = plt.GridSpec(5, 1, wspace=0.3, hspace=0.8)\n\n# Do plots:\n# Arm\nplt.subplot(grid[0, 0])\nplt.scatter(episodes, actions, color=\"black\", alpha=.5, s=2, label=\"Bandit\")\nplt.plot(episodes, np.repeat(best, np.max(episodes)+1), \n color=\"red\", alpha=0.8, ls='--', linewidth=2)\nplt.ylim(-.1, np.max(actions)+1.1)\nplt.ylabel(\"Arm choice\")\nplt.xlabel(\"Episode\")\n\n# score\nplt.subplot(grid[1, 0])\nplt.scatter(episodes, scores_R, color=\"grey\", alpha=0.4, s=2, label=\"R\")\nplt.scatter(episodes, scores_E, color=\"purple\", alpha=0.9, s=2, label=\"E\")\nplt.ylabel(\"log score\")\nplt.xlabel(\"Episode\")\nplt.semilogy()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n_ = sns.despine()\n\n# Q\nplt.subplot(grid[2, 0])\nplt.scatter(episodes, values_R, color=\"grey\", alpha=0.4, s=2, label=\"R\")\nplt.scatter(episodes, values_E, color=\"purple\", alpha=0.4, s=2, label=\"E\")\nplt.ylabel(\"log Q(s,a)\")\nplt.xlabel(\"Episode\")\nplt.semilogy()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n_ = sns.despine()\n\n# -\nplt.savefig(\"figures/epsilon_bandit.pdf\", bbox_inches='tight')\nplt.savefig(\"figures/epsilon_bandit.eps\", bbox_inches='tight')",
"Best arm: 0, last arm: 0\n"
]
],
[
[
"# Sensitivity\n\nto parameter choices",
"_____no_output_____"
]
],
[
[
"total_Rs = [] \nties = []\nlrs = []\ntrials = list(sorted_params.keys())\nfor t in trials:\n total_Rs.append(sorted_params[t]['total_R'])\n ties.append(sorted_params[t]['tie_threshold'])\n lrs.append(sorted_params[t]['lr'])\n \n# Init plot\nfig = plt.figure(figsize=(10, 18))\ngrid = plt.GridSpec(4, 1, wspace=0.3, hspace=0.8)\n\n# Do plots:\n# Arm\nplt.subplot(grid[0, 0])\nplt.scatter(trials, total_Rs, color=\"black\", alpha=.5, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"total R\")\n_ = sns.despine()\n\nplt.subplot(grid[1, 0])\nplt.scatter(trials, ties, color=\"black\", alpha=.3, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"Tie threshold\")\n_ = sns.despine()\n\nplt.subplot(grid[2, 0])\nplt.scatter(trials, lrs, color=\"black\", alpha=.5, s=6, label=\"total R\")\nplt.xlabel(\"Sorted params\")\nplt.ylabel(\"lr\")\n_ = sns.despine()",
"_____no_output_____"
]
],
[
[
"# Distributions\n\nof parameters",
"_____no_output_____"
]
],
[
[
"# Init plot\nfig = plt.figure(figsize=(5, 6))\ngrid = plt.GridSpec(2, 1, wspace=0.3, hspace=0.8)\n\nplt.subplot(grid[0, 0])\nplt.hist(ties, color=\"black\")\nplt.xlabel(\"tie threshold\")\nplt.ylabel(\"Count\")\n_ = sns.despine()\n\nplt.subplot(grid[1, 0])\nplt.hist(lrs, color=\"black\")\nplt.xlabel(\"lr\")\nplt.ylabel(\"Count\")\n_ = sns.despine()",
"_____no_output_____"
]
],
[
[
"of total reward",
"_____no_output_____"
]
],
[
[
"# Init plot\nfig = plt.figure(figsize=(5, 2))\ngrid = plt.GridSpec(1, 1, wspace=0.3, hspace=0.8)\n\nplt.subplot(grid[0, 0])\nplt.hist(total_Rs, color=\"black\", bins=50)\nplt.xlabel(\"Total reward\")\nplt.ylabel(\"Count\")\nplt.xlim(0, 10)\n_ = sns.despine()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb4ada16cb12af11192e88ee1ca9b10d00f3f33e | 177,275 | ipynb | Jupyter Notebook | l6 CNN/mnist_mlp_exercise.ipynb | kuThang/udacity-deep-learning | 4bc32a34a1dd478363c24dee2d0cd162f20acca1 | [
"Apache-2.0"
] | null | null | null | l6 CNN/mnist_mlp_exercise.ipynb | kuThang/udacity-deep-learning | 4bc32a34a1dd478363c24dee2d0cd162f20acca1 | [
"Apache-2.0"
] | null | null | null | l6 CNN/mnist_mlp_exercise.ipynb | kuThang/udacity-deep-learning | 4bc32a34a1dd478363c24dee2d0cd162f20acca1 | [
"Apache-2.0"
] | null | null | null | 257.667151 | 100,042 | 0.885709 | [
[
[
"!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi\n!pip install gputil\n!pip install psutil\n!pip install humanize\nimport psutil\nimport humanize\nimport os\nimport GPUtil as GPU\nGPUs = GPU.getGPUs()\n# XXX: only one GPU on Colab and isn’t guaranteed\ngpu = GPUs[0]\ndef printm():\n process = psutil.Process(os.getpid())\n print(\"Gen RAM Free: \" + humanize.naturalsize( psutil.virtual_memory().available ), \" | Proc size: \" + humanize.naturalsize( process.memory_info().rss))\n print(\"GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB\".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))\nprintm() \n",
"Collecting gputil\n Downloading https://files.pythonhosted.org/packages/ed/0e/5c61eedde9f6c87713e89d794f01e378cfd9565847d4576fa627d758c554/GPUtil-1.4.0.tar.gz\nBuilding wheels for collected packages: gputil\n Building wheel for gputil (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for gputil: filename=GPUtil-1.4.0-cp36-none-any.whl size=7410 sha256=a63e03a8233326b1b94bcafa5f90a558d6646479854b873bdcef0f9bae9e8fee\n Stored in directory: /root/.cache/pip/wheels/3d/77/07/80562de4bb0786e5ea186911a2c831fdd0018bda69beab71fd\nSuccessfully built gputil\nInstalling collected packages: gputil\nSuccessfully installed gputil-1.4.0\nRequirement already satisfied: psutil in /usr/local/lib/python3.6/dist-packages (5.4.8)\nRequirement already satisfied: humanize in /usr/local/lib/python3.6/dist-packages (0.5.1)\nGen RAM Free: 12.8 GB | Proc size: 155.5 MB\nGPU RAM Free: 16280MB | Used: 0MB | Util 0% | Total 16280MB\n"
]
],
[
[
"# Multi-Layer Perceptron, MNIST\n---\nIn this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.\n\nThe process will be broken down into the following steps:\n>1. Load and visualize the data\n2. Define a neural network\n3. Train the model\n4. Evaluate the performance of our trained model on a test dataset!\n\nBefore we begin, we have to import the necessary libraries for working with data and PyTorch.",
"_____no_output_____"
]
],
[
[
"# import libraries\nimport torch\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"---\n## Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)\n\nDownloading may take a few moments, and you should see your progress as the data is loading. You may also choose to change the `batch_size` if you want to load more data at a time.\n\nThis cell will create DataLoaders for each of our datasets.",
"_____no_output_____"
]
],
[
[
"from torchvision import datasets\nimport torchvision.transforms as transforms\n\nnum_workers = 0\nbatch_size = 20\n\ntransform = transforms.ToTensor()\n\ntrain_data = datasets.MNIST(root='data', train=True, download=True, transform=transform)\ntest_data = datasets.MNIST(root='data', train=False, download=True, transform=transform)\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)",
"_____no_output_____"
],
[
"# from torchvision import datasets\n# import torchvision.transforms as transforms\n\n# # number of subprocesses to use for data loading\n# num_workers = 0\n# # how many samples per batch to load\n# batch_size = 20\n\n# # convert data to torch.FloatTensor\n# transform = transforms.ToTensor()\n\n# # choose the training and test datasets\n# train_data = datasets.MNIST(root='data', train=True,\n# download=True, transform=transform)\n# test_data = datasets.MNIST(root='data', train=False,\n# download=True, transform=transform)\n\n# # prepare data loaders\n# train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n# num_workers=num_workers)\n# test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, \n# num_workers=num_workers)",
"_____no_output_____"
]
],
[
[
"### Visualize a Batch of Training Data\n\nThe first step in a classification task is to take a look at the data, make sure it is loaded in correctly, then make any initial observations about patterns in that data.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n \n# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy()\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n ax.imshow(np.squeeze(images[idx]), cmap='gray')\n # print out the correct label for each image\n # .item() gets the value contained in a Tensor\n ax.set_title(str(labels[idx].item()))",
"_____no_output_____"
]
],
[
[
"### View an Image in More Detail",
"_____no_output_____"
]
],
[
[
"img = np.squeeze(images[1])\n\nfig = plt.figure(figsize = (12,12)) \nax = fig.add_subplot(111)\nax.imshow(img, cmap='gray')\nwidth, height = img.shape\nthresh = img.max()/2.5\nfor x in range(width):\n for y in range(height):\n val = round(img[x][y],2) if img[x][y] !=0 else 0\n ax.annotate(str(val), xy=(y,x),\n horizontalalignment='center',\n verticalalignment='center',\n color='white' if img[x][y]<thresh else 'black')",
"_____no_output_____"
]
],
[
[
"---\n## Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)\n\nThe architecture will be responsible for seeing as input a 784-dim Tensor of pixel values for each image, and producing a Tensor of length 10 (our number of classes) that indicates the class scores for an input image. This particular example uses two hidden layers and dropout to avoid overfitting.",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\n## TODO: Define the NN architecture\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # linear layer (784 -> 1 hidden node)\n h1_node = 512\n h2_node = 512\n self.fc1 = nn.Linear(28 * 28, h1_node)\n self.fc2 = nn.Linear(h1_node, h2_node)\n self.fc3 = nn.Linear(h2_node, 10)\n self.dropout = nn.Dropout(0.2)\n\n def forward(self, x):\n # flatten image input\n x = x.view(-1, 28 * 28)\n # add hidden layer, with relu activation function\n x = F.relu(self.fc1(x))\n x = self.dropout(x)\n x = F.relu(self.fc2(x))\n x = self.dropout(x)\n x = self.fc3(x)\n\n return x\n\n# initialize the NN\nmodel = Net()\nprint(model)\nmodel.to('cuda');",
"Net(\n (fc1): Linear(in_features=784, out_features=512, bias=True)\n (fc2): Linear(in_features=512, out_features=512, bias=True)\n (fc3): Linear(in_features=512, out_features=10, bias=True)\n (dropout): Dropout(p=0.2, inplace=False)\n)\n"
]
],
[
[
"### Specify [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)\n\nIt's recommended that you use cross-entropy loss for classification. If you look at the documentation (linked above), you can see that PyTorch's cross entropy function applies a softmax funtion to the output layer *and* then calculates the log loss.",
"_____no_output_____"
]
],
[
[
"## TODO: Specify loss and optimization functions\nfrom torch import nn \nfrom torch import optim\n# specify loss function\ncriterion = nn.CrossEntropyLoss()\n\n# specify optimizer\noptimizer = optim.SGD(model.parameters(), lr=0.01)",
"_____no_output_____"
]
],
[
[
"---\n## Train the Network\n\nThe steps for training/learning from a batch of data are described in the comments below:\n1. Clear the gradients of all optimized variables\n2. Forward pass: compute predicted outputs by passing inputs to the model\n3. Calculate the loss\n4. Backward pass: compute gradient of the loss with respect to model parameters\n5. Perform a single optimization step (parameter update)\n6. Update average training loss\n\nThe following loop trains for 30 epochs; feel free to change this number. For now, we suggest somewhere between 20-50 epochs. As you train, take a look at how the values for the training loss decrease over time. We want it to decrease while also avoiding overfitting the training data. ",
"_____no_output_____"
]
],
[
[
"# number of epochs to train the model\nn_epochs = 30 # suggest training between 20-50 epochs\nmodel.to('cuda')\nmodel.train() # prep model for training\n\nfor epoch in range(n_epochs):\n # monitor training loss\n train_loss = 0.0\n \n ###################\n # train the model #\n ###################\n for data, target in train_loader:\n data, target = data.to('cuda'), target.to('cuda')\n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the loss\n loss = criterion(output, target)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # update running training loss\n train_loss += loss.item()*data.size(0)\n \n # print training statistics \n # calculate average loss over an epoch\n train_loss = train_loss/len(train_loader.sampler)\n\n print('Epoch: {} \\tTraining Loss: {:.6f}'.format(\n epoch+1, \n train_loss\n ))",
"Epoch: 1 \tTraining Loss: 0.816076\nEpoch: 2 \tTraining Loss: 0.326933\nEpoch: 3 \tTraining Loss: 0.256327\nEpoch: 4 \tTraining Loss: 0.205694\nEpoch: 5 \tTraining Loss: 0.173361\nEpoch: 6 \tTraining Loss: 0.151329\nEpoch: 7 \tTraining Loss: 0.130792\nEpoch: 8 \tTraining Loss: 0.117683\nEpoch: 9 \tTraining Loss: 0.105585\nEpoch: 10 \tTraining Loss: 0.095513\nEpoch: 11 \tTraining Loss: 0.085649\nEpoch: 12 \tTraining Loss: 0.080714\nEpoch: 13 \tTraining Loss: 0.074476\nEpoch: 14 \tTraining Loss: 0.068259\nEpoch: 15 \tTraining Loss: 0.062834\nEpoch: 16 \tTraining Loss: 0.059720\nEpoch: 17 \tTraining Loss: 0.055033\nEpoch: 18 \tTraining Loss: 0.051956\nEpoch: 19 \tTraining Loss: 0.048639\nEpoch: 20 \tTraining Loss: 0.046284\nEpoch: 21 \tTraining Loss: 0.042549\nEpoch: 22 \tTraining Loss: 0.041212\nEpoch: 23 \tTraining Loss: 0.037976\nEpoch: 24 \tTraining Loss: 0.036173\nEpoch: 25 \tTraining Loss: 0.034536\nEpoch: 26 \tTraining Loss: 0.031946\nEpoch: 27 \tTraining Loss: 0.029860\nEpoch: 28 \tTraining Loss: 0.028814\nEpoch: 29 \tTraining Loss: 0.027555\nEpoch: 30 \tTraining Loss: 0.026601\n"
]
],
[
[
"---\n## Test the Trained Network\n\nFinally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as well as looking at its overall loss and accuracy.\n\n#### `model.eval()`\n\n`model.eval(`) will set all the layers in your model to evaluation mode. This affects layers like dropout layers that turn \"off\" nodes during training with some probability, but should allow every node to be \"on\" for evaluation!",
"_____no_output_____"
]
],
[
[
"# initialize lists to monitor test loss and accuracy\ntest_loss = 0.0\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\n\nmodel.eval() # prep model for *evaluation*\n\nfor data, target in test_loader:\n data, target = data.to('cuda'), target.to('cuda')\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the loss\n loss = criterion(output, target)\n # update test loss \n test_loss += loss.item()*data.size(0)\n # convert output probabilities to predicted class\n _, pred = torch.max(output, 1)\n # compare predictions to true label\n correct = np.squeeze(pred.eq(target.data.view_as(pred)))\n # calculate test accuracy for each object class\n for i in range(len(target)):\n label = target.data[i]\n class_correct[label] += correct[i].item()\n class_total[label] += 1\n\n# calculate and print avg test loss\ntest_loss = test_loss/len(test_loader.sampler)\nprint('Test Loss: {:.6f}\\n'.format(test_loss))\n\nfor i in range(10):\n if class_total[i] > 0:\n print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (\n str(i), 100 * class_correct[i] / class_total[i],\n np.sum(class_correct[i]), np.sum(class_total[i])))\n else:\n print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))\n\nprint('\\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (\n 100. * np.sum(class_correct) / np.sum(class_total),\n np.sum(class_correct), np.sum(class_total)))",
"Test Loss: 0.059057\n\nTest Accuracy of 0: 99% (972/980)\nTest Accuracy of 1: 99% (1126/1135)\nTest Accuracy of 2: 98% (1014/1032)\nTest Accuracy of 3: 98% (995/1010)\nTest Accuracy of 4: 98% (966/982)\nTest Accuracy of 5: 98% (879/892)\nTest Accuracy of 6: 98% (939/958)\nTest Accuracy of 7: 97% (1001/1028)\nTest Accuracy of 8: 96% (941/974)\nTest Accuracy of 9: 97% (986/1009)\n\nTest Accuracy (Overall): 98% (9819/10000)\n"
]
],
[
[
"### Visualize Sample Test Results\n\nThis cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n\n# obtain one batch of test images\ndataiter = iter(test_loader)\nimages, labels = dataiter.next()\nimages_cuda = images.to('cuda')\nlabels = labels.to('cuda')\n\n# get sample outputs\noutput = model(images_cuda)\n# convert output probabilities to predicted class\n_, preds = torch.max(output, 1)\n# prep images for display\nimages = images.numpy()\n\n# plot the images in the batch, along with predicted and true labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n ax.imshow(np.squeeze(images[idx]), cmap='gray')\n ax.set_title(\"{} ({})\".format(str(preds[idx].item()), str(labels[idx].item())),\n color=(\"green\" if preds[idx]==labels[idx] else \"red\"))",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb4aec8cbcc0a249b043991874d589eab9da6215 | 108,487 | ipynb | Jupyter Notebook | notebooks/Testing ZTF Run GP Code.ipynb | dirac-institute/CometGPs | 7395bfabd84df294bba74ff21d8d8020b2155814 | [
"MIT"
] | 6 | 2017-11-17T22:35:05.000Z | 2020-05-09T11:12:31.000Z | notebooks/Testing ZTF Run GP Code.ipynb | dirac-institute/CometGPs | 7395bfabd84df294bba74ff21d8d8020b2155814 | [
"MIT"
] | 4 | 2017-11-27T18:52:54.000Z | 2019-08-20T18:47:28.000Z | notebooks/Testing ZTF Run GP Code.ipynb | dirac-institute/CometGPs | 7395bfabd84df294bba74ff21d8d8020b2155814 | [
"MIT"
] | 2 | 2017-11-17T22:53:24.000Z | 2018-03-16T18:25:06.000Z | 41.328381 | 99 | 0.424632 | [
[
[
"import pandas as pd\nimport numpy as np\n",
"_____no_output_____"
],
[
"filename = \"../data/paper_plots/ztf_lightcurves/christina/11351_obs.csv\"",
"_____no_output_____"
],
[
"data = pd.read_csv(filename, header=None, delim_whitespace=False)\n",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"new_header = data.iloc[0] \nnew_header\n",
"_____no_output_____"
],
[
"\n\ndata = data[1:] #take the data less the header row\ndata.columns = new_header #set the header row as the df header\n\n",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"tsample = pd.to_numeric(data['mjd'])",
"_____no_output_____"
],
[
"tsample.head()",
"_____no_output_____"
],
[
"fsample = pd.to_numeric(data['magcorrOO'])\nfsample.head()",
"_____no_output_____"
],
[
"flux_err = pd.to_numeric(data['sigmapsf'] )\nlen(flux_err)",
"_____no_output_____"
],
[
"\n\n\n#tsample = data['mjd']\n\n#using the uncertainty from the psf, check with Lynne and Daniela that this is appropriate\n\n\nprint(tsample, fsample, flux_err)\n",
"1 58360.358101859696\n2 58365.20752315922\n3 58368.24967595982\n4 58368.273541659124\n5 58371.2495486592\n6 58371.29446755909\n7 58374.16688655923\n8 58374.26899305918\n9 58377.274050959386\n10 58377.254282359514\n11 58378.18901615917\n12 58380.16752315919\n13 58380.245196759235\n14 58383.188240759075\n15 58386.24789355929\n16 58389.231655058924\n17 58389.191365758896\n18 58430.07636575914\n19 58430.143495359465\n20 58433.08650465916\n21 58469.074398159064\n22 58469.079305559404\n23 58469.084212959286\n24 58469.08912035918\n25 58471.089849559125\n26 58472.08409725923\n27 58472.08895835932\n28 58473.07474535937\n29 58473.07961805911\n30 58473.08447915923\n ... \n52 58697.41193285911\n53 58661.427696759354\n54 58661.476562459495\n55 58678.4390624594\n56 58681.43291665894\n57 58682.446678259425\n58 58682.456261559404\n59 58682.476990758914\n60 58684.400162059355\n61 58686.444432859316\n62 58691.34034725932\n63 58691.40515045963\n64 58694.38296295937\n65 58694.426041658975\n66 58694.43384255889\n67 58705.41962965905\n68 58700.47668985929\n69 58706.39666665905\n70 58706.43629625906\n71 58709.42020835914\n72 58709.45230325918\n73 58712.37576385961\n74 58712.47643515933\n75 58713.435868059285\n76 58716.39030096028\n77 58716.392106459476\n78 58716.38837965905\n79 58719.3811689592\n80 58719.38296295937\n81 58721.3137847595\nName: mjd, Length: 81, dtype: object 1 -0.04845148093378526\n2 0.33548214374216556\n3 -0.22953131323912146\n4 -0.18631528302590894\n5 -0.021038798458285157\n6 -0.02924831953094298\n7 0.38676010648847736\n8 0.33058307596545333\n9 -0.28561587827307733\n10 -0.24129039610341607\n11 -0.29534479042581196\n12 -0.04399188621135508\n13 -0.16050859078491442\n14 0.20152904980108843\n15 -0.18408901023998325\n16 -0.10616041507832819\n17 -0.18715492620126284\n18 0.46144969946533365\n19 0.384102436128515\n20 -0.2649222592491576\n21 -0.08150240359672267\n22 0.2786962107966424\n23 -0.06530517172747707\n24 0.01639344936844367\n25 -0.5621499744025087\n26 -0.24025431888890836\n27 -0.2981535642618276\n28 -0.09381479465393738\n29 -0.17001332929922697\n30 -0.13071186318281036\n ... \n52 -0.08036578225934932\n53 -0.009266104175917889\n54 0.0862691788745451\n55 -0.13135165119178183\n56 0.35580263817008984\n57 0.27350547185314156\n58 0.3120048640325557\n59 0.4236072694758555\n60 -0.10021217978988162\n61 -0.3500601948833122\n62 0.41364242433324705\n63 0.4347267976364755\n64 -0.1711421060206817\n65 -0.13454207689775544\n66 -0.14825477820771127\n67 -0.32613816297986276\n68 0.3454994333149344\n69 -0.1964697302323799\n70 -0.12168116094545312\n71 0.23167171211458282\n72 0.3850451612057775\n73 -0.04845030916233384\n74 -0.016910528933614444\n75 -0.3642030196259931\n76 -0.062040647360316115\n77 -0.028318626029225413\n78 -0.11956408357116644\n79 0.4858114934841673\n80 0.4414330872399006\n81 0.053801195818039105\nName: magcorrOO, Length: 81, dtype: object 1 0.123724\n2 0.10781500000000001\n3 0.0791686\n4 0.062199300000000006\n5 0.07661439999999999\n6 0.06045349999999999\n7 0.0746485\n8 0.11036199999999999\n9 0.0659617\n10 0.07273550000000001\n11 0.0627726\n12 0.11151300000000001\n13 0.0747313\n14 0.182662\n15 0.0758391\n16 0.0720869\n17 0.09278380000000001\n18 0.125117\n19 0.111454\n20 0.0869564\n21 0.0915559\n22 0.190172\n23 0.127843\n24 0.0963135\n25 0.195475\n26 0.110463\n27 0.09778680000000001\n28 0.11857100000000001\n29 0.0985406\n30 0.11804200000000001\n ... \n52 0.0495102\n53 0.0553207\n54 0.12300499999999999\n55 0.0751903\n56 0.079326\n57 0.06811489999999999\n58 0.06742469999999999\n59 0.158721\n60 0.14689000000000002\n61 0.05174580000000001\n62 0.0470254\n63 0.057592599999999994\n64 0.0399251\n65 0.0508344\n66 0.0576303\n67 0.0399851\n68 0.07674650000000001\n69 0.0549177\n70 0.07733200000000001\n71 0.0626048\n72 0.102038\n73 0.0590879\n74 0.0978248\n75 0.0537873\n76 0.0471382\n77 0.0657652\n78 0.046842199999999994\n79 0.070258\n80 0.0640761\n81 0.0976433\nName: sigmapsf, Length: 81, dtype: object\n"
],
[
"np.mean(fsample)",
"_____no_output_____"
],
[
"filename[:-4]",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb4b01f56fbd3f2a04fbab9dd2426ba84eefddab | 405,195 | ipynb | Jupyter Notebook | Desarrollo_Jupyter/ecuacion_conveccion.ipynb | LeonardoLopez2218061/Proyecto_Final_EDP-NS | 849e54becbe0c013dcd41a382728122ba17b1e51 | [
"CC-BY-3.0"
] | null | null | null | Desarrollo_Jupyter/ecuacion_conveccion.ipynb | LeonardoLopez2218061/Proyecto_Final_EDP-NS | 849e54becbe0c013dcd41a382728122ba17b1e51 | [
"CC-BY-3.0"
] | null | null | null | Desarrollo_Jupyter/ecuacion_conveccion.ipynb | LeonardoLopez2218061/Proyecto_Final_EDP-NS | 849e54becbe0c013dcd41a382728122ba17b1e51 | [
"CC-BY-3.0"
] | null | null | null | 578.024251 | 77,652 | 0.944688 | [
[
[
"# Hola mundo... \nAgradecemos de manera especial a la PhD Lorena A. Barba [@LorenaABarba](https://twitter.com/LorenaABarba), quien desarrolló el material [CFDPython](https://github.com/barbagroup/CFDPython), sobre el cual está desarrollado el siguiente proyecto pedagógico.\n\n¡Hola! Bienvenido a **Una introducción a la ecuación de Navier-Stokes en una y dos dimensiones, buscando soluciones numúricas vía Python**. Este es un material práctico que se utiliza al comienzo de un curso interactivo de dinámica de fluidos computacional (CFD), y está basado en la propuesta del curso **12 steps to Navier–Stokes**, el cual es impartido por el [Prof. Lorena Barba](http://lorenabarba.com) desde la primavera de 2009 en la Universidad de Boston.\n\nEl curso asume solo conocimientos básicos de programación y, por supuesto, algunos fundamentos en ecuaciones diferenciales parciales y mecánica de fluidosy se imparte en su totalidad utilizando Python.",
"_____no_output_____"
],
[
"# Ecuación de convección lineal",
"_____no_output_____"
],
[
"Para poder estudiar algunas ideas en la discretización de las ecuaciones de Navier-Stokes en una dimensión (1-D) y dos dimensiones (2-D) es importarte comenzar estudiando la ecuación de [convección lineal](http://www.unet.edu.ve/~fenomeno/F_DE_T-165.htm)\n\n$$\\frac{\\partial u}{\\partial t} + c \\frac{\\partial u}{\\partial x} = 0.$$\ncon condiciones iniciales $u(x,0)=u_0(x)$, dato conocido como onda inicial. La ecuación representa la propagación de la onda inicial con velicidad $c$. La solución analítica usando variables separables es dada por $u(x,t)=u_0(x-ct)$.\n\nPara poder implementar el método numérico, nosotros discretizamos esta ecuación tanto en el tiempo como en el espacio, usando el esquema de diferencias finitas hacia adelante para la derivada en el tiempo y el esquema de diferencias finitas hacia atrás para la derivada en el espacio.\n\nLa coordenada espacial $x$ se discretiza en $N$ pasos regulares $\\Delta x$ desde $i=0$ hasta $i=N$. Para la variable temporal $t$ se discretiza tomando intervalos de tamaño $\\Delta t$.\nPor la definición de derivada, removiendo el límite, es posible aproximar\n\n$$\\frac{\\partial u}{\\partial x}\\approx \\frac{u(x+\\Delta x)-u(x)}{\\Delta x}.$$\n\nAsí, por nuestra discretización, se sigue que:\n$$\\frac{u_i^{n+1}-u_i^n}{\\Delta t} + c \\frac{u_i^n - u_{i-1}^n}{\\Delta x} = 0, $$\ndonde $n$ y $n+1$ son dos pasos en el tiempo, mientras que $i-1$ y $i$ son dos puntos vecinos de la coodenada $x$ discretizada. Si se tienen en cuenta la condiciones iniciales, la única variable desconocida es $u_i^{n+1}$. Resolviendo la ecuación para $u_i^{n+1}$, podemos obtener una ecuación que nos permita avanzar en el tiempo de la siguiente manera: \n$$u_i^{n+1} = u_i^n - c \\frac{\\Delta t}{\\Delta x}(u_i^n-u_{i-1}^n).$$\n",
"_____no_output_____"
]
],
[
[
"import numpy as np \nimport matplotlib.pyplot as plt \nimport time, sys \n%matplotlib inline\n#esto hace que los gráficos de matplotlib aparezcan en el cuaderno (en lugar de una ventana separada)",
"_____no_output_____"
]
],
[
[
"## Ahora definamos algunas variables: \n\nqueremos definir una cuadrícula de puntos uniformemente espaciados dentro de un dominio espacial que tiene $2$ unidades de longitud de ancho, es decir, $x_i\\in(0,2)$. Definiremos una variable `nx`, que será el número de puntos de cuadrícula que queremos y `dx` será la distancia entre cualquier par de puntos de cuadrícula adyacentes.",
"_____no_output_____"
]
],
[
[
"nx = 41 \ndx = 2 / (nx-1)\nnt = 20 #nt es el número de pasos de tiempo que queremos calcular\ndt = .025 #dt es la cantidad de tiempo que cubre cada paso de tiempo (delta t)\nc = 1 # suponga una velocidad de onda de c = 1",
"_____no_output_____"
]
],
[
[
"También necesitamos configurar nuestras condiciones iniciales.\n\nPara ello, disponemos de dos funciones, definidas sobre el intervalo $(0,2)$. \n# Ejemplo 1: f1\nLa velocidad inicial $ u_0 $ se da como\n$ u = 2 $ en el intervalo $ 0.5 \\leq x \\leq 1 $ y $ u = 1 $ en cualquier otro lugar de $ (0,2) $ (es decir, una función de sombrero). \n\n# Ejemplo 2: f2\nFijando el tiempo, y tomando valores fijos para las constastes, podemos crear un variado número de funciones para la velocidad inicial. \n$$u_n(x,t)=C_n\\sin\\left(\\frac{n\\pi c}{L}t+\\phi_n\\right) \\sin\\left(\\frac{n\\pi }{L}x\\right)$$",
"_____no_output_____"
]
],
[
[
"def f1(nx):\n #dx = 2 / (nx-1)\n u = np.ones(nx) #numpy función ones()\n u[int(.5 / dx):int(1 / dx + 1)] = 2 #configurar u = 2 entre 0.5 y 1 y u = 1 para todo lo demás según nuestra CI\n #print(u)\n return u",
"_____no_output_____"
],
[
"def f1_var(x):\n u=np.piecewise(x,[x<0.5,np.abs(x-0.75)<=0.25,x>1],[lambda x:1,lambda x: 2,lambda x:1])\n return u",
"_____no_output_____"
],
[
"def f2(nx):\n #dx = 2 / (nx-1)\n L=2\n n=4\n Fi=0.2#ángulo de fase temporal\n c=10 #velocidad de la onda\n A=0.5#amplitud máxima, relacionada con la intensidad del sonido\n t=0.18 #instantánea en el tiempo t segundos\n x=np.arange(0.0,L+dx,dx)\n u=A*np.sin(n*np.pi*c*0.005*t/L+Fi)*np.sin(n*np.pi*x/L)#aquí definimos la función\n return u",
"_____no_output_____"
],
[
"def mostrar_imagen(u):\n plt.plot(np.linspace(0, 2, nx), u);",
"_____no_output_____"
]
],
[
[
"## Ahora es el momento de implementar la discretización de la ecuación de convección utilizando un esquema de diferencias finitas.\n\nPara cada elemento de nuestra matriz `u`, necesitamos realizar la operación $$u_i^{n+1} = u_i^n - c \\frac{\\Delta t}{\\Delta x}(u_i^n-u_{i-1}^n)$$\n\nAlmacenaremos el resultado en una nueva matriz (temporal) `un`, que será la solución $ u $ para el próximo paso de tiempo. Repetiremos esta operación durante tantos pasos de tiempo como especifiquemos y luego podremos ver qué tan lejos se ha convectado la onda.\n\nPrimero inicializamos nuestra matriz de marcador de posición `un` para contener los valores que calculamos para el paso de tiempo $ n + 1 $, usando una vez más la función NumPy`ones() `.\n\nEntonces, podemos pensar que tenemos dos operaciones iterativas: una en el espacio y otra en el tiempo (aprenderemos de manera diferente más adelante), por lo que comenzaremos anidando un bucle dentro del otro. Tenga en cuenta el uso de la ingeniosa función `range()`. Cuando escribimos: `for i in range(1, nx)` iteraremos a través de la matriz `u`, pero omitiremos el primer elemento (el elemento cero). *¿Por qué?*",
"_____no_output_____"
]
],
[
[
"def ECL(u):\n for n in range(nt): # bucle para valores de n de 0 a nt, por lo que se ejecutará nt veces\n un = u.copy() ##copiar los valores existentes de u en un\n for i in range(1, nx): \n #for i in range(nx): \n u[i] = un[i] - c * (dt / dx) * (un[i] - un[i-1])\n #pyplot.plot(np.linspace(0, 2, nx), u);\n return u",
"_____no_output_____"
],
[
"def ECLspeed(u):\n for n in range(nt): ## recorrer el número de pasos de tiempo\n un = u.copy()\n u[1:] = un[1:]- c * (dt / dx) * (un[1:] - un[:-1])\n return u",
"_____no_output_____"
]
],
[
[
"Usemos el método para la ECL con la función usada en el ejemplo 1, denominada `f1`.",
"_____no_output_____"
]
],
[
[
"u=f1(nx)\nmostrar_imagen(u)",
"_____no_output_____"
]
],
[
[
"Cuyo resultado final, después de $t = 0.5$ segundos es:",
"_____no_output_____"
]
],
[
[
"u=ECL(f2(nx))\nmostrar_imagen(u)",
"_____no_output_____"
],
[
"x=np.arange(0.0,2.0+dx,dx)\nu=ECL(f1_var(x))\nmostrar_imagen(u)",
"_____no_output_____"
],
[
"u=ECL(f2(nx))\nmostrar_imagen(u)",
"_____no_output_____"
]
],
[
[
"# Ecuación de convección no lineal",
"_____no_output_____"
],
[
"Consideremos la ecuación de convección no lineal (ECnL) dada por \n\n$$\\frac{\\partial u}{\\partial t} + u \\frac{\\partial u}{\\partial x} = 0$$\n\nUsaremos la misma discretización que en el caso lineal: diferencia hacia adelante en el tiempo y diferencia hacia atrás en el espacio. Aquí está la ecuación discretizada.\n\n$$\\frac{u_i^{n+1}-u_i^n}{\\Delta t} + u_i^n \\frac{u_i^n-u_{i-1}^n}{\\Delta x} = 0.$$\n\nResolviendo en términos de $u_i^{n+1}$, obtenemos:\n\n$$u_i^{n+1} = u_i^n - u_i^n \\frac{\\Delta t}{\\Delta x} (u_i^n - u_{i-1}^n)$$",
"_____no_output_____"
],
[
"Para obtener una explicación más detallada del método de diferencias finitas, es necesario tocar temas como el error de truncamiento, el orden de convergencia y otros detalles, que por efectos de tiempo no vamos a tratar en este proyecto.\nAún así, el lector que quiera profundizar en esto, por favor vea las lecciones en video 2 y 3 de la profesora Barba en YouTube.",
"_____no_output_____"
]
],
[
[
"def ECnL(u):\n for n in range(nt): # bucle para valores de n de 0 a nt, por lo que se ejecutará nt veces\n un = u.copy() ##copiar los valores existentes de u en un\n #for i in range(1, nx): \n for i in range(nx): \n u[i] = un[i] - un[i] * (dt / dx) * (un[i] - un[i-1])\n #print(u)\n #pyplot.plot(np.linspace(0, 2, nx), u);\n return u",
"_____no_output_____"
]
],
[
[
"## Juguemos un poco...\n\n... con los valores de `nx` en la **ecuación lineal**",
"_____no_output_____"
]
],
[
[
"nx = 41 # intente cambiar este número de 41 a 81 y Ejecutar todo ... ¿qué sucede? \ndx = 2 / (nx-1)\nnt = 20 #nt es el número de pasos de tiempo que queremos calcular\ndt = .025 #dt es la cantidad de tiempo que cubre cada paso de tiempo (delta t)\nc = 1 # suponga una velocidad de onda de c = 1\nx=np.arange(0.0,2.0+dx,dx)\n\nplt.figure(figsize=(18,12))\n#como colocar un título general a un paquete \n\nplt.subplot(2, 2, 1) \nplt.plot(x,f1(nx),label=f' Velocidad inicial para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 2) \nplt.plot(x,ECL(f1(nx)),label=f'Vel en t=0.5 para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 3) \nplt.plot(x,f2(nx),label=f' Velocidad inicial para f2')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 4) \nplt.plot(x,ECL(f2(nx)),label=f'Vel en t=0.5 para f2')\nplt.legend(frameon=False)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Y ahora,\n\nen la **ecuación no lineal**...\n\n# ¿Qué sucede?",
"_____no_output_____"
]
],
[
[
"nx = 41 # intente cambiar este número de 41 a 81 y Ejecutar todo ... ¿qué sucede? \ndx = 2 / (nx-1)\nnt = 20 #nt es el número de pasos de tiempo que queremos calcular\ndt = .025 #dt es la cantidad de tiempo que cubre cada paso de tiempo (delta t)\nc = 1 # suponga una velocidad de onda de c = 1\nx=np.arange(0.0,2.0+dx,dx)\n\nplt.figure(figsize=(18,12))\n#como colocar un título general a un paquete \n\nplt.subplot(2, 2, 1) \nplt.plot(x,f1(nx),label=f' Velocidad inicial para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 2) \nplt.plot(x,ECnL(f1(nx)),label=f'Velocidad en t=0.5 para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 3) \nplt.plot(x,f2(nx),label=f' Velocidad inicial para f2')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 4) \nplt.plot(x,ECnL(f2(nx)),label=f'Velocidad en t=0.5 para f2')\nplt.legend(frameon=False)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Para responder a esa pregunta, tenemos que pensar un poco sobre lo que realmente estamos implementando en el código.\n\nEn cada iteración de nuestro ciclo de tiempo, usamos los datos existentes sobre nuestra onda para estimar la velocidad de la onda en el siguiente paso de tiempo. Inicialmente, el aumento en el número de puntos de la cuadrícula arrojó respuestas más precisas. Hubo menos difusión numérica y la onda cuadrada se parecía mucho más a una onda cuadrada que en nuestro primer ejemplo.\n\nCada iteración de nuestro ciclo de tiempo cubre un intervalo de tiempo de longitud $\\Delta t $, que hemos estado definiendo como 0.025\n\nDurante esta iteración, evaluamos la velocidad de la onda en cada uno de los puntos $ x $ que hemos creado. En la última trama, claramente algo salió mal.\n\nLo que ha sucedido es que durante el período de tiempo $ \\Delta t $, la onda viaja una distancia que es mayor que `dx`. La longitud `dx` de cada cuadro de cuadrícula está relacionada con el número de puntos totales` nx`, por lo que la estabilidad se puede aplicar si el tamaño del paso $ \\Delta t $ se calcula con respecto al tamaño de `dx`.\n\n$$\\sigma = \\frac{u \\Delta t}{\\Delta x} \\leq \\sigma_{\\max}$$\n",
"_____no_output_____"
],
[
"donde $ u $ es la velocidad de la onda; $ \\sigma $ se llama [**número de Courant**](https://n9.cl/86phk) (CFL) y el valor de $\\sigma_{\\max} $ que garantizará la estabilidad depende de la discretización utilizada.\n\n\nEn una nueva versión de nuestro código, usaremos el número CFL para calcular el paso de tiempo apropiado `dt` dependiendo del tamaño de `dx`.",
"_____no_output_____"
]
],
[
[
"nx = 1001 # intente cambiar este número de 41 a 81 y Ejecutar todo ... ¿qué sucede? \ndx = 2 / (nx-1)\nnt = 20 #nt es el número de pasos de tiempo que queremos calcular\nsigma =0.5\ndt = sigma * dx #dt es la cantidad de tiempo que cubre cada paso de tiempo (delta t)\nc = 1 # suponga una velocidad de onda de c = 1\nx=np.arange(0.0,2.0+dx,dx)\n\nplt.figure(figsize=(18,12))\n#como colocar un título general a un paquete \n\nplt.subplot(2, 2, 1) \nplt.plot(x,f1(nx),label=f' Velocidad inicial para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 2) \nplt.plot(x,ECL(f1(nx)),label=f'Vel en t=0.5 para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 3) \nplt.plot(x,f2(nx),label=f' Velocidad inicial para f2')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 4) \nplt.plot(x,ECL(f2(nx)),label=f'Vel en t=0.5 para f2')\nplt.legend(frameon=False)\nplt.show()",
"_____no_output_____"
],
[
"nx = 41 # intente cambiar este número de 41 a 81 y Ejecutar todo ... ¿qué sucede? \ndx = 2 / (nx-1)\nnt = 20 #nt es el número de pasos de tiempo que queremos calcular\ndt = .025 #dt es la cantidad de tiempo que cubre cada paso de tiempo (delta t)\nc = 1 # suponga una velocidad de onda de c = 1\nx=np.arange(0.0,2.0+dx,dx)\n\nplt.figure(figsize=(18,12))\n#como colocar un título general a un paquete \n\nplt.subplot(2, 2, 1) \nplt.plot(x,f1(nx),label=f' Velocidad inicial para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 2) \nplt.plot(x,ECnL(f1(nx)),label=f'Velocidad en t=0.5 para f1')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 3) \nplt.plot(x,f2(nx),label=f' Velocidad inicial para f2')\nplt.legend(frameon=False)\nplt.subplot(2, 2, 4) \nplt.plot(x,ECnL(f2(nx)),label=f'Velocidad en t=0.5 para f2')\nplt.legend(frameon=False)\nplt.show()",
"_____no_output_____"
],
[
"from IPython.display import YouTubeVideo\nYouTubeVideo('iz22_37mMkk')",
"_____no_output_____"
],
[
"YouTubeVideo('xq9YTcv-fQg')",
"_____no_output_____"
]
],
[
[
"# Extra!!!\nPara una descripción detallada de la discretización de la ecuación de convección lineal con diferencias finitas (y también los siguientes problemas estudiados aquí), vea la Lección en video 4 del Prof. Barba en YouTube.",
"_____no_output_____"
]
],
[
[
"YouTubeVideo('y2WaK7_iMRI')",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.